/*global jQuery */
(function ($) {
    $.sailtime_dialogs = {
        defaults: {
            autoOpen: false,
            modal: true,
            position: ['center', 140],
            width: 590
        },
        cancel_button: {
            'Cancel': function () {
                $(this).dialog("close");
            }
        },
        close_button: {
            'Close': function () {
                $(this).dialog("close");
            }
        },
        video_buttons: {
            'Close': function () {
                if ($.sailtime_video.player) {
                    $.sailtime_video.player.stopVideo();
                }
                $(this).dialog("close");
            }
        }
    };

    $.sailtime_dialogs.alertDialog = function (title, text) {
        $('#alert-dialog').notify("create", {
            title: title,
            text: text
        });
    };

    $.sailtime_dialogs.reservationDialog = function () {
        var d, el, ts, sel, start, sd = $('#CalendarShowDialog');

        if (typeof sd === "object") {
            start = sd.val();
        }

        if (typeof start === "string" && start !== "") {
            ts = '.slot-timestamp:contains(' + start + ')';
            sel = $(ts);
        }

        if (typeof sel === "object") {
            el = sel.parent('.slot');
            d = el.data('sailtime');
        }

        if (typeof d === "object") {
            d.showReservationDialog(0);
            return true;
        }

        return false;
    };

    $.sailtime_dialogs.initReservationDialog = function () {
        var rd = $('#reservation-dialog'), cd = $('#confirm-dialog');

        // Reservation Info Dialog
        rd.dialog($.extend({}, $.sailtime_dialogs.defaults, {
            width: 700,
            buttons: $.sailtime_dialogs.close_button,
            open: function () {
                $('.element-updated').removeClass('element-updated');
            },
            close: function () {
                $(this).data('sailtime', {});
                $('.element-updated').effect('highlight', {}, 1000, function () {
                    $(this).removeClass('element-updated');
                });
            }
        }));

        $('#cancelReservation').live('click', function () {
            cd.html('<p>Are you sure you wish to delete this SailTime? Please be advised that payments for cancelled SailTimes are non-refundable.</p>').dialog({
                buttons: {
                    'Yes, Delete it!': function () {
                        $('.rd-main-indicator').show();
                        rd.data('sailtime').disableButton(this).cancel(0);
                        $(this).dialog("close");
                    },
                    'No': function () {
                        $(this).dialog("close");
                    }
                }
            }).dialog('open');
        });

        $('#cancelReservationBlock').live('click', function () {
            cd.html('<p>Are you sure you wish to delete this block of SailTimes? Please be advised that payments for cancelled SailTimes are non-refundable.</p>').dialog({
                buttons: {
                    'Yes, Delete them!': function () {
                        $('.rd-main-indicator').show();
                        rd.data('sailtime').disableButton(this).cancel(1);
                        $(this).dialog("close");
                    },
                    'No': function () {
                        $(this).dialog("close");
                    }
                }
            }).dialog('open');
        });

        $('#confirmReservation').live('click', function () {
            $('.rd-main-indicator').show();
            rd.data('sailtime').disableButton(this).confirm(0);
        });

        $('#confirmReservationBlock').live('click', function () {
            $('.rd-main-indicator').show();
            rd.data('sailtime').disableButton(this).confirm(1);
        });

        $('#addWait').live('click', function () {
            $('.rd-main-indicator').show();
            rd.data('sailtime').disableButton(this).addWait();
        });

        $('.reservationDialogSaveNote').live('click', function () {
            var r, d = rd.data('sailtime'), s = d.getSlotSettings(),
            notes = $('#ReservationNotes').val(), indicator = $('.rd-notes-indicator');

            if (typeof notes === "string") {
                notes = $.trim(notes.replace(/(<([^>]+)>)/gi, ""));
            } else {
                notes = '';
            }

            $('#ReservationNotes').val(notes);

            r = $.extend(true, {}, s, {
                Reservation: {
                    notes: notes
                }
            });

            indicator.show();

            d.disableButton(this).save(r);
        });

        $('.reservationDialogClearNote').live('click', function () {
            $('#ReservationNotes').val('');
            $('.reservationDialogSaveNote').trigger('click');
        });

        $('.reservationDialogSave').live('change', function () {
            var r, d = rd.data('sailtime'), s = d.getSlotSettings(),
            indicator = $('.rd-options-indicator'),
            key = $(this).data('key'), obj = {
                Reservation: {}
            };

            obj.Reservation[key] = $(this).is(':checked') ? '1' : '0';

            r = $.extend(true, {}, s, obj);

            indicator.show();

            d.save(r);
        });

        $('.reservationDialogInviteCrew').live('click', function () {
            var d = rd.data('sailtime'), c=$('.crewUserId:checked'),
            invitees = c.map(function(i,n) {
                return $(n).val();
            }).get(),
            count = invitees.length;

            var crew_invite_message = $('#ReservationCrewInviteMessage').val();
            
            d.inviteCrew(count,invitees,crew_invite_message);
        });
        
        $('.reservationDialogSelectAllCrew').live('change', function () {            
            $(".crewUserId").attr('checked', $('.reservationDialogSelectAllCrew').is(':checked'));           
        });



        $('.sailtime-dialog-launch').live('click', function (e) {

            var href = $(this).find('a').attr('href').split('#') || null;

            e.preventDefault();

            if(typeof href === "object" && href.length === 2) {

                $('#CalendarShowDialog').val(href[1]);

                if (!$.sailtime_dialogs.reservationDialog()) {
                    $('#CalendarSchedulerForm').updateCalendarDateAndSubmit(href[0]);
                }
            }
            return false;
        });

        $.sailtime_dialogs.reservationDialog();

    };

    $.sailtime_dialogs.initMemberSummary = function () {
        var ms = $('#member-summary');

        ms.dialog($.extend({}, $.sailtime_dialogs.defaults, {
            width: 750,
            buttons: $.sailtime_dialogs.close_button
        }));

        $('.my-summary-launch').click(function () {
            var url = '/calendars/memberSummary #member-summary-content', postData = {
                data: {
                    timezone: $('#CalendarTimezone').val(),
                    user: $('#CalendarUser').val(),
                    boat: $('#CalendarBoat').val(),
                    month: $('#CalendarMonth').val(),
                    year: $('#CalendarYear').val(),
                    base: $('#CalendarBase').val()
                }
            };
            ms.load(url, postData, function (responseText, textStatus, XMLHttpRequest) {
                if (responseText && XMLHttpRequest && textStatus === "success") {
                    ms.dialog('open');
                } else {
                    $.sailtime_dialogs.alertDialog(
                        $.js_vars.strings.errorLabel,
                        $.js_vars.strings.memberSummaryLoadError);
                }
            });

            return false;
        });
    };

    $.sailtime_dialogs.initEmbarkAudio = function () {
        var ead = $('#embark-audio-dialog');

        ead.dialog($.extend({}, $.sailtime_dialogs.defaults, {
            width: 350,
            buttons: $.sailtime_dialogs.close_button
        }));

        $('.ead-audio-link').click(function () {
            var url, href = $(this).attr('href');

            url = href  + ' #embark-audio-content';

            ead.load(url, null, function (responseText, textStatus, XMLHttpRequest) {
                if (responseText && XMLHttpRequest && textStatus === "success") {
                    ead.dialog('open');
                }
            });
            return false;

        });
    };

    $.sailtime_dialogs.initEditDialog = function (ed, link, dialogExtensionsObj) {
        var deo = dialogExtensionsObj || {};
        if(!ed) {
                ed = $('.edit-dialog');
        }
        if(!link) {
            link = $('.edit-dialog-link');
        }

        ed.dialog($.extend({}, $.sailtime_dialogs.defaults, {
            buttons: $.sailtime_dialogs.cancel_button
        }, deo));

        link.live("click", function () {
            var url, href = $(this).attr('href');

            url = href  + ' #edit-dialog-content';

            ed.load(url, null, function (responseText, textStatus, XMLHttpRequest) {
                if (responseText && XMLHttpRequest && textStatus === "success") {
                    ed.dialog('open');
                }
            });
            return false;
        });
    };

    $.sailtime_dialogs.init = function () {

        $('#alert-dialog').notify();

        // Progress Loader Dialog
        $('#progress-dialog').dialog($.extend({}, $.sailtime_dialogs.defaults, {
            width: 300
        })).bind('ajaxSend', function () {
            $(this).dialog('open');
        }).bind('ajaxComplete', function () {
            $(this).dialog('close');
            // fix an error in JQuery UI tabs where ajax loaded tab stays highlighted
            $('.ui-tabs-selected').removeClass('ui-state-focus');
        });

        $('#confirm-dialog').dialog($.extend({}, $.sailtime_dialogs.defaults, {
            width: 400
        }));

        $('#help-dialog').dialog($.extend({}, $.sailtime_dialogs.defaults, {
            dialogClass: 'help-dialog-alpha',
            width: 640,
            buttons: $.sailtime_dialogs.close_button
        }));

        $('#info-dialog').dialog($.extend({}, $.sailtime_dialogs.defaults, {
            dialogClass: 'help-dialog-alpha',
            position: ['center', 20],
            width: 640,
            buttons: $.sailtime_dialogs.close_button
        }));

        $('#yt-video-player').dialog($.extend({}, $.sailtime_dialogs.defaults, {
            modal: false,
            buttons: $.sailtime_dialogs.video_buttons
        }));

        $('#yt-intro-player').dialog($.extend({}, $.sailtime_dialogs.defaults, {
            buttons: $.sailtime_dialogs.video_buttons
        }));
    };
}(jQuery));
