﻿$(function() {
    InitializeControls();

    // Turn on loading message when AJAX request begins.
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(Loading);

    // Turn off loading message when AJAX request ends.
    prm.add_endRequest(function() {
        $.loading(false);
        InitializeControls();
    });
});

function InitializeControls() {
    var disableLoading = false;
    $(".disable-loading").click(function() { disableLoading = true; });
    
    // Show loading message when form is submitted if validation passed.
    $("form").submit(function() {
        if (disableLoading) { disableLoading = false; return; }
        if (typeof (Page_IsValid) != "undefined" && typeof (Page_BlockSubmit) != "undefined" && (Page_IsValid == false || Page_BlockSubmit == true)) return;
        Loading();
    });

    $("input[title], select[title], table[title], textarea[title]").after(AddHelp);
    $("th[title], span[title], h4[title], label[title], legend[title]").append(AddHelp);
    $("input[type='text'].date").datepicker({ changeMonth: true, changeYear: true, yearRange: '1920:2100', showOn: 'button', buttonImageOnly: true, buttonImage: '/images/calendar.gif' });

    // Enable buttons associated with GridView when at least one checkbox is checked.
    $(".gvDependent").each(function() {
        // Check if the associated gridview has any checkboxes checked at page initialization.
        var classes = $(this).attr('class').split(' ');
        for (var i = 0; i < classes.length; ++i) {
            if (classes[i].indexOf("MainContentPlaceHolder") == 0) {
                ToggleGridViewButtons(classes[i]);
                break;
            }
        }
    });
    $(".gvselect input:checkbox").click(function() {
        ToggleGridViewButtons($(this).parents("table.clsTable").attr("id"));
    });

    $(".disable-onbeforeunload").click(TemporarilyDisablePromptAboutUnsavedChanges);

    // Preload images.
    $.preLoadImages("/images/spinner.gif");
}

function encode(input) { return $('<div/>').text(input).html(); }
function decode(input) { return $('<div/>').html(input).text(); }

var promptAboutUnsavedChangesMessage;
var promptAboutUnsavedChangesEnabled = false;
function PromptAboutUnsavedChanges() {
    promptAboutUnsavedChangesEnabled = true;

    return promptAboutUnsavedChangesMessage;
}

function TemporarilyDisablePromptAboutUnsavedChanges() {
    window.onbeforeunload = null;

    if (promptAboutUnsavedChangesEnabled)
        setTimeout('window.onbeforeunload = PromptAboutUnsavedChanges', 1000);
}

function SubmitToNewWindow(elem) {
    elem.form.target = '_blank';
    setTimeout("$('#" + elem.id + "')[0].form.target = '_self'", 1000);
}

function DayMonthPickerChanged(month, day, days, required) {
    var m = month.val();
    var i = days.size() - 1;
    var size = 30;

    if (m == 4 || m == 6 || m == 9 || m == 11) size = 29;
    else if (m == 2) size = 27;

    if (i < size) {
        i = i + (required == true ? 2 : 1);
        for (i; i <= size + 1; ++i) { day.append('<option value="' + i + '">' + i + '</option>'); }
    }
    else if (i > size) {
        if (required == false) {
            ++i;
            ++size;
        }

        for (i; i > size; --i) { days.eq(i).remove(); }
    }
}

function CourseOverview(courseID, sessionID) { return IFramePopup('/lib/Overview.aspx?CourseID=' + courseID + '&SessionID=' + sessionID, 'Course Overview'); }
function CurriculumOverview(curriculumID) { return IFramePopup('/Learning/CurriculumOverview.aspx?CurriculumID=' + curriculumID, 'Curriculum Overview'); }
function TrainingCategoryOverview(trainingCategoryID) { return IFramePopup('/Learning/TrainingCategoryOverview.aspx?TrainingCategoryID=' + trainingCategoryID, 'Training Category Overview'); }
function CareerPathOverview(careerPathID) { return IFramePopup('/Learning/CareerPathOverview.aspx?CareerPathID=' + careerPathID, 'Career Path Overview'); }
function CourseUses(courseID) { return IFramePopup('/Learning/CourseUses.aspx?CourseID=' + courseID, 'Course In Use'); }
function CurriculumUses(curriculumID) { return IFramePopup('/Learning/CurriculumUses.aspx?CurriculumID=' + curriculumID, 'Curriculum In Use'); }
function AssessmentTemplateUses(templateID) { return IFramePopup('/Learning/AssessmentTemplateUses.aspx?AssessmentTemplateID=' + templateID, 'Template In Use'); }

function IFramePopup(url, title) {
    TemporarilyDisablePromptAboutUnsavedChanges();
    $('<iframe width="100%" height="100%" frameborder="0" src="' + url + '"/>').dialog({ title: title, width: 600, height: 400, zIndex: 9999999, modal: true, buttons: { Ok: function() { $(this).dialog('close'); } } }).width(600).height(400);
    return false;
}

function AddHelp() {
    if (typeof(this.tagName) == "undefined") return; // Prevents the document title from being replaced.
    if ($.trim($(this).attr("title")) == "") return; // Don't show empty tooltips.
    if ($(this).parents(".reportviewer, .mceEditor").length > 0) return; // Don't add tooltips to report viewer.
    if ($(this).is(".no-tooltip")) return; // Don't add tooltip to items that restrict it.

    var tip = $(this).attr("title");
    var cssClass = "help";
    if (this.tagName.toLowerCase() == "table" || this.tagName.toLowerCase() == "select" || (this.tagName.toLowerCase() == "input" && $(this).attr("type") == "file")) cssClass = cssClass + ' table';
    $(this).attr("title", "");

    return $('<img src="/images/help.png" class="' + cssClass + '" />').qtip({
        content: tip,
        position: { corner: { target: 'rightMiddle', tooltip: 'leftMiddle' }, adjust: { x: 5, screen: true }},
        show: { when: 'click', effect: { length: 0} },
        hide: { when: 'unfocus', effect: { length: 0} },
        style: { border: { width: 5 }, tip: false, name: 'cream', padding: 14, color: '#000' }
    });
}

function Loading() { $.loading(true, { align: 'center', mask: true, css: { zIndex: 100005 }, maskCss: { zIndex: 100004 }, working: { time: 5000 }, error: { time: 600000} }); }

function CheckAll(id, checked) {
    $("#" + id).find(".gvselect input:checkbox").attr("checked", checked);
    ToggleGridViewButtons(id);
}

function ToggleGridViewButtons(id) {
    var gridview = $("#" + id);
    var checked = gridview.find(".gvselect input:checkbox:checked").length > 0;

    $("input:submit." + id).attr("disabled", !checked);
}

(function($) {
    var cache = [];
    // Arguments are image paths relative to the current page.
    $.preLoadImages = function() {
        var args_len = arguments.length;
        for (var i = args_len; i--; ) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery)
