﻿/*
DatePicker: add class="date" to any input control to add the datepicker

confirm-prompt="<msg>" to display a confirmation prompt containing the <msg>
data-url="<url>" to override default click event and redirect to specified url
    
Dialogs:
class="dialog" on a div to intialize the dialog (id="<id>" to reference it)
dialog-title="<title>" to set the title of the dialog
dialog-width="<#>" to set the width of the dialog in pixels (default = auto)
dialog-height="<#>" to set the height of the dialog in pixels (default = auto)
dialog-auto="true" to automatically open the dialog at page load

dialog-open="<id>" to open the dialog with matching id
dialog-close="<id>" to close the dialog with matching id
dialog-ajax="<url>" to perform an ajax request to <url> and display the result as a dialog

value-complete="<url>" to add auto-complete functionality
value-target="<id>" element to fill with the selected value from auto-complete
*/

autoCompleteCache = []; // Cache storage for auto-complete lookups

function showErrorDialog(title, message) {
    var d = $('<div id="errorDialog"></div>');
    if (message instanceof Array) {
        var m = "";
        var i = 0;
        for (i = 0; i < message.length; i++) {
            m += "<li>" + message[i] + "</li>";
        }
        d.html("<ul>" + m + "</ul>");
    } else {
        d.html(message);
    }
    d.dialog({
        autoOpen: true,
        modal: true,
        width: 550,
        title: title,
        buttons: { "Close": function () { $(this).dialog('destroy'); } }
    });
}

$(function () {

    // Displays the no photo image when the original photo cannot be loaded
    $("img.storephoto").each(function (index) {
        $(this).error(function () {
            $(this).attr('src', '/cts/images/nophoto.png');
        });
        $(this).attr("src", $(this).attr("src"));
    });

    // Displays a date picker when the textbox has focus
    $('input.date').each(function () {
        var yearRange = $(this).attr('data-year-range') || '-5:+5';
        $(this).datepicker({
            changeMonth: true,
            changeYear: true,
            yearRange: yearRange
        });
    });

    //Checks all check boxes in a containter
    $('input[data-checkall]').click(function (event) {
        var container = $(this).attr('data-checkall');
        $(this).parents('#' + container).find(':checkbox').attr('checked', this.checked);
    });

    // Displays a confirmation prompt
    // ex: confirm-prompt="Are you sure you wish to delete this?"
    $('*[confirm-prompt]').click(function (event) {
        var promptText = $(this).attr('confirm-prompt');
        if (!confirm(promptText)) {
            event.preventDefault();
        }
    });

    $('.click-disable').click(function () {
        $(this).attr('disabled', 'disabled');
    });

    // Shows/Hides element when the checkbox/radio button is checked
    $('*[data-show]').each(function () {
        var src = $(this)
        if (src.attr('type') != 'radio') { src = src.find('input[type=radio]'); }
        if (src) {
            var target = $('#' + $(this).attr('data-show'));
            target.toggle(src.is(':checked'));

            src.change(function () {
                target.toggle($(this).is(':checked'));
            });
        }
    });
    $('*[data-hide]').each(function () {
        var src = $(this)
        if (src.attr('type') != 'radio') { src = src.find('input[type=radio]'); }
        if (src) {
            var target = $('#' + $(this).attr('data-hide'));
            target.toggle(!src.is(':checked'));

            src.change(function () {
                target.toggle(!$(this).is(':checked'));
            });
        }
    });

    // Overrides the click event to redirect the user to the url contained in the data-url value
    $('*[data-url]').click(function (event) {
        event.preventDefault();
        window.location.href = $(this).attr('data-url');
    });

    // Initializes a dialog
    $('.dialog').each(function () {
        var w = $(this).attr('dialog-width');
        var h = $(this).attr('dialog-height');
        var auto = $(this).attr('dialog-auto');
        // TODO: Implement external uri dialogs
        $(this).dialog({
            autoOpen: auto && auto !== 'false' ? true : false,
            modal: true,
            title: $(this).attr('dialog-title'),
            height: h > 0 ? h : 'auto',
            width: w > 0 ? w : 'auto',
            open: function (type, data) { $(this).parent().appendTo(jQuery("form:first")); }
        });

    });

    // Opens the dialog with the id matching the value of dialog-open
    $('*[dialog-open]').click(function (event) {
        var dialog = $(this).attr('dialog-open');
        $('#' + dialog).dialog('open');
        event.preventDefault();
    });

    // Closes the dialog with the id matching the value of dialog-close
    $('*[dialog-close]').click(function (event) {
        var dialog = $(this).attr('dialog-close');
        $('#' + dialog).dialog('close');
        event.preventDefault();
    });

    // Executes an ajax call to the url in the href or dialog-ajax value and displays the result in a dialog
    $('a[dialog-ajax],input[dialog-ajax]').click(function (event) {
        event.preventDefault();
        var url = $(this).attr('href').length ? $(this).attr('href') : $(this).attr('dialog-ajax');
        $('#loadingDialog').dialog('open');
        $.ajax({
            type: 'GET',
            url: url,
            success: function (data, textStatus, jqXHR) {
                try {
                    // Check for json result
                    if (data.status !== undefined && data.status.match(/success/i) === null) {
                        if (data.status.match(/redirect/i) !== null) {
                            document.location.href = data.data;
                        } else {
                            showErrorDialog(data.errorTitle, data.errorMessages);
                        }
                    } else {
                        var w = $(data).attr('dialog-width');
                        var h = $(data).attr('dialog-height');
                        $(data).dialog({
                            autoOpen: true,
                            modal: true,
                            title: $(data).attr('dialog-title'),
                            height: h > 0 ? h : 'auto',
                            width: w > 0 ? w : 'auto',
                            open: function (type, data) {
                                $('*[dialog-ajax-close]').click(function (event) {
                                    var dialog = $(this).attr('dialog-ajax-close');
                                    $('#' + dialog).dialog('destroy').remove();
                                    event.preventDefault();
                                });
                                //$(this).parent().appendTo(jQuery("form:first"));
                            },
                            close: function (event, ui) {
                                $(this).dialog('destroy').remove();
                            }
                        });
                    }
                } catch (err) {
                    document.location.href = url;
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                showErrorDialog(textStatus, errorThrown);
            },
            complete: function () {
                $('#loadingDialog').dialog('close');
            }
        });
    });

    // Posts the form using ajax and displays the result in a dialog
    $('form[dialog-ajax]').submit(function (event) {
        event.preventDefault();
        var url = $(this).attr('action'); if (!url || !url.length) { alert("You must provide an action for this form!"); }
        var fm = '#' + $(this).attr('id'); if (fm === '#') { alert('You must provide an id for this form!'); }
        $('#loadingDialog').dialog('open');
        $.ajax({
            type: 'POST',
            url: url,
            processData: false,
            data: $(this).serialize(),
            success: function (data, textStatus, jqXHR) {
                try {
                    // Check for json result
                    if (data.status !== undefined && data.status.match(/success/i) === null) {
                        if (data.status.match(/redirect/i) !== null) {
                            document.location.href = data.data;
                        } else {
                            showErrorDialog(data.errorTitle, data.errorMessages);
                        }
                    } else {
                        var w = $(data).attr('dialog-width');
                        var h = $(data).attr('dialog-height');
                        $(data).dialog({
                            autoOpen: true,
                            modal: true,
                            title: $(data).attr('dialog-title'),
                            height: h > 0 ? h : 'auto',
                            width: w > 0 ? w : 'auto',
                            open: function (type, data) {
                                $('*[dialog-ajax-close]').click(function (event) {
                                    var dialog = $(this).attr('dialog-ajax-close');
                                    $('#' + dialog).dialog('destroy').remove();
                                    event.preventDefault();
                                });
                                //$(this).parent().appendTo(jQuery("form:first"));
                            },
                            close: function (event, ui) {
                                $(this).dialog('destroy').remove();
                            }
                        });
                    }
                } catch (err) {
                    document.location.href = document.location.href;
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                showErrorDialog(textStatus, errorThrown);
            },
            complete: function () {
                $('#loadingDialog').dialog('close');
            }
        });
        return false;
    });

    $('input[value-complete]').each(function () {
        var elem = this;
        var url = $(elem).attr('value-complete');
        var vt = $(elem).attr('value-target');
        if (autoCompleteCache.indexOf(url) == -1) {
            autoCompleteCache[url] = [];
        }
        $(elem).autocomplete({
            minLength: 2,
            source: function (req, res) {
                var term = req.term;
                if (vt) { $('#' + vt).val(''); } // Clear the value target on a new search
                // check local cache for the search term for previous results
                if (autoCompleteCache[url].indexOf(term) != -1) {
                    res(autoCompleteCache[url][term]);
                    return;
                }
                lastXhr = $.getJSON(url, req, function (data, status, xhr) {
                    autoCompleteCache[url][term] = data;
                    if (xhr == lastXhr) {
                        res(data);
                    }
                });
            },
            select: function (event, ui) {
                // if a value target is specified, insert the selected value
                // into that target element and the selected label into this
                if (vt) {
                    $('#' + vt).val(ui.item.value);
                    $(elem).val(ui.item.label);
                    return false;
                }
                // otherwise, allow the default functionality
            }
        });
    });

    // Allows for placeholder text in form textboxes
    // ex: placeholder="search text"
    $('[placeholder]').focus(function () {
        var input = $(this);
        if (input.val() === input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
        }
    }).blur(function () {
        var input = $(this);
        if (input.val() === '' || input.val() === input.attr('placeholder')) {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
        }
    }).blur().parents('form').submit(function () {
        $(this).find('[placeholder]').each(function () {
            var input = $(this);
            if (input.val() === input.attr('placeholder')) {
                input.val('');
            }
        });
    });

    //Fills in the options for select control with the number of days for the given month
    $('select[data-monthOfDate]').change(function () {
        //Get the days select control.  This is passed in as the attribute value
        var element = $("*[id$='" + $(this).attr('data-monthOfDate') + "']");

        //Get the currently selected day
        var selectedDay = element.val();

        //Clear all existing options from the days select control
        element.children().remove().end();

        //Add an empty row back in
        element.append($("<option> </option>"));

        //Get the max number of days given the selected month
        var maxDays = 31;
        switch ($(this).val()) {
            case "1": case "3": case "5": case "7": case "8": case "10": case "12":
                maxDays = 31;
                break;
            case "2":
                maxDays = 29;
                break;
            case "4": case "6": case "9": case "11":
                maxDays = 30;
                break;
        }

        //Add the options back into the days select control
        for (i = 1; i <= maxDays; i++) {
            if (i == selectedDay) {
                element.append($("<option selected=\"selected\" value= \"" + i.toString() + "\">" + i.toString() + "</option>"));
            } else {
                element.append($("<option value= \"" + i.toString() + "\">" + i.toString() + "</option>"));
            };
        }
    });

    //Disable a button after clicking
    $('.click-disable').click(function () {
        $(this).attr('disabled', 'disabled');
    });

    // Only process this when in the /Itineraries pages
    if ((/\/itineraries.*/i).test(document.location.pathname)) {
        // Use ajax to load itinerary balance for faster page loading
        // Looks for a span with id=itineraryBalance-<itineraryId>
        $('span[id|="itineraryBalance"]').each(function () {
            var src = this;
            $.ajax({
                type: 'GET',
                url: '/api/itineraries/balance/?id=' + src.id.match(/itineraryBalance-(.*)/)[1],
                success: function (data, textStatus, jqXHR) {
                    $(src).fadeOut('slow', function () {
                        src.innerHTML = data;
                        $(src).fadeIn('slow');
                    });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    src.innerHTML = textStatus;
                }
            });
        });
    }

});

// Only CMS scripts below
var UpdateContentField = {
    ajax: function (d) {
        $.ajax({
            type: 'POST',
            url: "/Content/UpdateField/",
            processData: false,
            data: JSON.stringify(d),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data, textStatus, jqXHR) {
                if (data.status === null) {
                    showErrorDialog("Error", "A serious error has occurred.  If you continue to receive this error, please contact CircuiTree Support.");
                } else if (data.status.match(/success/i) !== null) {
                    window.location.href = window.location.href;
                } else {
                    showErrorDialog(data.errorTitle, data.errorMessages);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                showErrorDialog(textStatus, errorThrown);
            },
            complete: function () {
                $(this).dialog('close');
            }
        });
    },
    preview: function (contentCategoryName, contentFieldName, value) {
        UpdateContentField.ajax({
            Action: 'Preview',
            ContentCategoryName: contentCategoryName,
            ContentFieldName: contentFieldName,
            TempValue: value
        });
    },
    commit: function (contentCategoryName, contentFieldName, value) {
        UpdateContentField.ajax({
            Action: 'Commit',
            ContentCategoryName: contentCategoryName,
            ContentFieldName: contentFieldName,
            Value: value
        });
    },
    revert: function (contentCategoryName, contentFieldName) {
        UpdateContentField.ajax({
            Action: 'Revert',
            ContentCategoryName: contentCategoryName,
            ContentFieldName: contentFieldName
        });
    },
    undo: function (contentCategoryName, contentFieldName) {
        UpdateContentField.ajax({
            Action: 'Undo',
            ContentCategoryName: contentCategoryName,
            ContentFieldName: contentFieldName
        });
    }
};
$(function () {
    // Wire up TinyMCE for CMS
    tinyMCE.init({
        // General options
        mode: "specific_textareas",
        editor_selector: "mce",
        theme: "advanced",
        convert_urls: 0,
        remove_script_host: 0,
        plugins: "advimage,advlink,paste,preview,safari,table,iespell,inlinepopups,media",
        theme_advanced_buttons1: "cut,copy,paste,pastetext,pasteword,|,undo,redo,|,outdent,indent,|,justifyleft,justifycenter,justifyright,bullist,numlist,|,iespell,removeformat,cleanup,code,preview,help",
        theme_advanced_buttons2: "bold,italic,underline,strikethrough,sub,sup,|,backcolor,forecolor,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons3: "link,unlink,charmap,hr,blockquote,image,media,|,tablecontrols",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: true,
        content_css: "/CTS/css/site.css"
    });

    $('.contentdialog').dialog({
        autoOpen: false,
        modal: true,
        width: 720,
        height: 440,
        title: $(this).attr('dialog-title') || "Edit Content Field",
        buttons: {
            "Preview": function () {
                var id = $(this).attr('id').match(/contentdialog_(.+)/i)[1];
                UpdateContentField.preview($('#categoryname_' + id).val(),
                                           $('#fieldname_' + id).val(),
                                           tinyMCE.editors['fieldvalue_' + id].getContent());
            },
            "Commit": function () {
                var id = $(this).attr('id').match(/contentdialog_(.+)/i)[1];
                UpdateContentField.commit($('#categoryname_' + id).val(),
                                          $('#fieldname_' + id).val(),
                                          tinyMCE.editors['fieldvalue_' + id].getContent());
            },
            "Cancel": function () {
                $(this).dialog('close');
            },
            "Revert To Default": function () {
                var id = $(this).attr('id').match(/contentdialog_(.+)/i)[1];
                UpdateContentField.revert($('#categoryname_' + id).val(),
                                          $('#fieldname_' + id).val());
            }
        },
        open: function () {
            var mce = $(this).find('iframe')[0];
            if (mce) {
                mce.style.width = '690px';
                mce.style.height = '200px';
            }
        }
    });

    $('a[edit-content]').click(function (event) {
        var id = $(this).attr('edit-content');
        $('#contentdialog_' + id).dialog('open');
        event.preventDefault();
    });

});

function winopen(url, title, vars) {
    newWindow = window.open(url, title, vars);
    newWindow.focus();
}
