﻿var FAA_UTILITY = {
    openHelp: function(page) {
        window.open(page, null, 'height=620, width=960,status=no,resizable=yes,scrollbars=yes,toolbar=no,location=no,menubar=no');
    },

    toggleCheckboxes: function(parentElement, checked) {
        parentElement.select('input').each(function(e) {
            if (e.type == 'checkbox') e.checked = checked;
        });
    },

    // this function determines whether the event is the equivalent of the microsoft
    // mouseleave or mouseenter events.
    isMouseLeaveOrEnter: function(e, handler) {
        var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
        while (reltg && reltg != handler) reltg = reltg.parentNode;
        return (reltg != handler);
    },

    callWebService: function(url, parameters, successMethod) {
        new Ajax.Request(url,
                         {
                             'method': 'post',
                             'postBody': Object.toJSON(parameters),
                             'contentType': 'application/json; charset=utf-8',
                             'onSuccess': function(transport) {
                                 var response = eval("(" + transport.responseText + ")");
                                 successMethod(response.d);
                             }
                         }
        );
    }
};



var FAA_USER_WIDGET = {
    DISABLED: false,
    INITIALIZED: false,

    init: function () {
        Event.observe('usrw', 'click', FAA_USER_WIDGET.toggle);
        if ($('logoutLink')) {
            // Don't toggle the widget if the user is logging out.
            Event.observe('logoutLink', 'click', function () { FAA_USER_WIDGET.DISABLED = true; });
        }
        if ($('alertIcon')) {
            new Effect.Move('alertIcon', { x: 66, y: 0, mode: 'relative' });
        }
    },

    toggle: function () {

        // To avoid double-clicks causing issues with the Effects, disable toggling
        // for one second after the first click.  That will be enough time for the 
        // effect to finish.
        if (!FAA_USER_WIDGET.DISABLED) {
            FAA_USER_WIDGET.DISABLED = true;

            if (!FAA_USER_WIDGET.INITIALIZED) {
                if ($('myAreasOfResponsibility')) {
                    FAA_UTILITY.callWebService('/webServices/UserWidget.aspx/GetMyAreasOfResponsibility', {}, FAA_USER_WIDGET.loadMyAreasOfResponsibilities);
                }
                if ($('myEvents')) {
                    FAA_UTILITY.callWebService('/webServices/UserWidget.aspx/GetMyEvents', {}, FAA_USER_WIDGET.loadMyEvents);
                }
                if ($('myCourses')) {
                    FAA_UTILITY.callWebService('/webServices/UserWidget.aspx/GetMyCourses', {}, FAA_USER_WIDGET.loadMyCourses);
                }

                FAA_USER_WIDGET.INITIALIZED = true;
            }

            setTimeout(function () { FAA_USER_WIDGET.DISABLED = false; }, 500);

            if ($('usrwopen').visible()) {
                $('usrwarrow').src = '/include/lookandfeel/images/usrw/ar_down.gif';
                $('oc').innerHTML = 'open';
                Effect.SlideUp('usrwopen', { duration: 0.5 });
            } else {
                $('usrwarrow').src = '/include/lookandfeel/images/usrw/ar_up.gif';
                $('oc').innerHTML = 'close';
                Effect.SlideDown('usrwopen', { duration: 0.5 });
            }
        }
    },

    loadMyEvents: function (eventList) {
        var eventDiv = $('myEvents');
        while (eventDiv.hasChildNodes()) {
            eventDiv.removeChild(eventDiv.firstChild);
        }

        if (eventList.length == 0) {
            var textDiv = new Element('div');
            textDiv.addClassName('widgetText');
            textDiv.appendChild(document.createTextNode('You are not registered for any seminars at this time.  '));
            eventDiv.appendChild(textDiv);
        } else {
            for (var i = 0; i < eventList.length; i++) {
                var ev = eventList[i];

                var dateDiv = new Element('div');
                dateDiv.addClassName('row');

                // We need this function because of how closures work.  Without this "function(ev)"
                // wrapper function, all of the overlib boxes will show only the last event's info.
                // This is because ev will only be bound after the loop finishes and will therefore
                // always reference the last item of eventList.
                var funcWithDiffScopeToSolveClosureIssue = function (ev) {
                    return function () {
                        return overlib(
                            '<div class="eventTooltipTitle">' + ev.title + '</div>' +
                            '<div class="eventTooltipBody">' + ev.date + '</div>' +
                            '<div class="eventTooltipBody">' + ev.location + '</div>'
                        );
                    }
                }

                var dateLink = new Element('a');
                dateLink.addClassName('tooltip');
                dateLink.addClassName('eventDate');
                Event.observe(dateLink, 'click', function () { return false; });
                Event.observe(dateLink, 'mouseout', function () { return nd(); });
                Event.observe(dateLink, 'mouseover', funcWithDiffScopeToSolveClosureIssue(ev));
                var dateText = document.createTextNode(ev.date);
                dateLink.appendChild(dateText);
                dateDiv.appendChild(dateLink);
                eventDiv.appendChild(dateDiv);


                var linkDiv = new Element('div');
                linkDiv.addClassName('eventRow');
                var link = new Element('a', { 'href': ev.link });
                var text = document.createTextNode(ev.text);

                link.appendChild(text);
                linkDiv.appendChild(link);
                eventDiv.appendChild(linkDiv);
            }
        }
    },

    loadMyCourses: function (courseList) {
        var courseDiv = $('myCourses');
        while (courseDiv.hasChildNodes()) {
            courseDiv.removeChild(courseDiv.firstChild);
        }

        if (courseList.length == 0) {
            var textDiv = new Element('div');
            textDiv.addClassName('widgetText');
            textDiv.appendChild(document.createTextNode('You are not enrolled in any courses at this time.  '));

            var link = new Element('a', { 'href': '/gslac/ALC/course_catalog.aspx' });
            link.appendChild(document.createTextNode('Find Courses'));
            textDiv.appendChild(link);
            courseDiv.appendChild(textDiv);
        } else {
            for (var i = 0; i < courseList.length; i++) {
                var div = new Element('div');
                div.addClassName('row clearfix');

                var iconDiv = new Element('div');
                iconDiv.addClassName('iconDiv');
                var img = new Element('img', { 'src': '/images/navigation/bullet.gif', 'alt': '' });
                iconDiv.appendChild(img);
                div.appendChild(iconDiv);

                var linkDiv = new Element('div');
                linkDiv.addClassName('linkDiv');
                var link = new Element('a', { 'href': courseList[i].link });
                var text = document.createTextNode(courseList[i].text);
                link.appendChild(text);
                linkDiv.appendChild(link);
                div.appendChild(linkDiv);

                courseDiv.appendChild(div);
            }
        }
    },

    loadMyAreasOfResponsibilities: function (aorList) {
        var aorDiv = $('myAreasOfResponsibility');
        while (aorDiv.hasChildNodes()) {
            aorDiv.removeChild(aorDiv.firstChild);
        }

        if (aorList.length == 0) {
            var textDiv = new Element('div');
            textDiv.addClassName('widgetText');
            textDiv.appendChild(document.createTextNode('You are not assigned multiple districts.  '));

            var link = new Element('a', { 'href': '/login/LoginSelectAreaOfResponsibility.aspx' });
            //link.appendChild(document.createTextNode('Find Courses'));
            textDiv.appendChild(link);
            aorDiv.appendChild(textDiv);
        } else {
            for (var i = 0; i < aorList.length; i++) {
                var div = new Element('div');
                div.addClassName('row clearfix');

                var iconDiv = new Element('div');
                iconDiv.addClassName('iconDiv');
                var img = new Element('img', { 'src': '/images/navigation/bullet.gif', 'alt': '' });
                iconDiv.appendChild(img);
                div.appendChild(iconDiv);

                var linkDiv = new Element('div');
                linkDiv.addClassName('linkDiv');
                var link = new Element('a', { 'href': aorList[i].link });
                var text = document.createTextNode(aorList[i].text);
                link.appendChild(text);
                linkDiv.appendChild(link);
                div.appendChild(linkDiv);

                aorDiv.appendChild(div);
            }
        }
    },

    expandAndFocusEmail: function () {
        if (!$('usrwopen').visible()) {
            FAA_USER_WIDGET.toggle();
            setTimeout(function () { $('userWidgetEmail').activate(); }, 500);
        } else {
            $('userWidgetEmail').activate();
        }
    },

    setLoginDestination: function (newDest) {
        if ($('userWidgetLoginDestination')) {
            $('userWidgetLoginDestination').value = newDest;
        }
    },

    setEmailPassword: function (email, password) {
        $('userWidgetEmail').value = email;
        $('userWidgetPassword').value = password;
    }
};



var HOT_TOPIC = {
    IMAGES: [],     // Initialized by code-behind
    DELAY_SECONDS: 5,
    CURRENT_INDEX: -1,

    init: function () {
        HOT_TOPIC.CURRENT_INDEX = Math.floor(Math.random() * HOT_TOPIC.IMAGES.length);
        $('hotTopicProgress').hide();
        HOT_TOPIC.next();
    },

    previous: function (userClicked) {
        clearTimeout(HOT_TOPIC.TIMEOUT);

        HOT_TOPIC.CURRENT_INDEX--;
        if (HOT_TOPIC.CURRENT_INDEX < 0) {
            HOT_TOPIC.CURRENT_INDEX = HOT_TOPIC.IMAGES.length - 1;
        }

        HOT_TOPIC.updateTopic();

        if (!userClicked) {
            HOT_TOPIC.addTimeout();
        }
    },

    next: function (userClicked) {
        clearTimeout(HOT_TOPIC.TIMEOUT);

        HOT_TOPIC.CURRENT_INDEX++;
        if (HOT_TOPIC.CURRENT_INDEX == HOT_TOPIC.IMAGES.length) {
            HOT_TOPIC.CURRENT_INDEX = 0;
        }

        HOT_TOPIC.updateTopic();

        if (!userClicked) {
            HOT_TOPIC.addTimeout();
        }
    },

    addTimeout: function () {
        HOT_TOPIC.TIMEOUT = setTimeout("HOT_TOPIC.next();", HOT_TOPIC.DELAY_SECONDS * 1000);
    },

    updateTopic: function () {
        var topic = HOT_TOPIC.IMAGES[HOT_TOPIC.CURRENT_INDEX];
        var div = $('hotTopicDiv');

        while (div.hasChildNodes()) {
            div.removeChild(div.firstChild);
        }

        var topLink = new Element('a', { 'href': topic.linkTop, 'target': topic.urlTarget });
        var topImg = new Element('img', { 'src': topic.imageTop, 'alt': topic.imageTopAlt, 'width': 218, 'height': 110 });
        topLink.appendChild(topImg);
        div.appendChild(topLink);

        var bottomLink = new Element('a', { 'href': topic.linkBottom, 'target': topic.urlTarget });
        var bottomImg = new Element('img', { 'src': topic.imageBottom, 'alt': topic.imageBottomAlt, 'width': 218, 'height': 20 });
        bottomLink.appendChild(bottomImg);
        div.appendChild(bottomLink);

        var actionLink = new Element('a', { 'href': topic.linkBottom, 'target': topic.urlTarget });
        var actionText = document.createTextNode(topic.imageBottomAlt);
        actionLink.appendChild(actionText);
        div.appendChild(actionLink);
        div.style.textAlign = 'center';
    }
};



var FAA_TIMEOUT = {
    initTimeout: function(urlPrefix, sessionTimeoutKey, warningAt, milliSecondsTilTimeOut) {
        // Initialize values
        FAA_TIMEOUT.urlPrefix = urlPrefix;
        FAA_TIMEOUT.sessionTimeoutKey = sessionTimeoutKey;
        FAA_TIMEOUT.warningAt = warningAt;
        FAA_TIMEOUT.milliSecondsTilTimeOut = milliSecondsTilTimeOut;
        
        // Set warning and actual timeouts
        FAA_TIMEOUT.setTimeouts();
    },

    setTimeouts: function() {
        FAA_TIMEOUT.timeoutWarningIntervalID = window.setInterval('FAA_TIMEOUT.sessionTimeoutWarning()', FAA_TIMEOUT.warningAt);
        FAA_TIMEOUT.timeoutIntervalID = window.setInterval('FAA_TIMEOUT.sessionTimeout()', FAA_TIMEOUT.milliSecondsTilTimeOut);
    },

    sessionTimeoutWarning: function() {
        FAA_TIMEOUT.timeoutWarningWindow = window.open(
            FAA_TIMEOUT.urlPrefix + 'PreSessionTimeoutWarning.aspx?SessionTimeoutKey=' + FAA_TIMEOUT.sessionTimeoutKey,
            '_blank',
            'height=200, width=600,status=no,resizable=no,scrollbars=yes,toolbar=no,location=no,menubar=no'
        );
    },

    sessionTimeout: function() {
        FAA_TIMEOUT.timeoutWarningWindow.close();
        window.location = FAA_TIMEOUT.urlPrefix + 'SessionTimeout.aspx';
    },

    extendSessionTimeout: function() {
        FAA_TIMEOUT.timeoutWarningWindow.close();
        clearInterval(FAA_TIMEOUT.timeoutWarningIntervalID);
        clearInterval(FAA_TIMEOUT.timeoutIntervalID);
        FAA_TIMEOUT.setTimeouts();
    }
};



var NAVIGATION = {
    LEVEL_ONE: {},          // Populated by the code-behind
    LEVEL_TWO_MORE: [],     // Populated by the code-behind

    EFFECT_OPTIONS: { duration: 0.1, queue: 'end' },

    initLevelOne: function() {
        for (var levelOne in NAVIGATION.LEVEL_ONE) {
            var ul = $(levelOne + '_submenu');
            var levelTwos = NAVIGATION.LEVEL_ONE[levelOne];
            for (var i = 0; i < levelTwos.length; i++) {
                var levelTwo = levelTwos[i];
                var li = new Element('li');
                if (i == 0) {
                    li.addClassName('first');
                }
                var link = new Element('a', { 'href': levelTwo.link, 'target': levelTwo.target });
                link.appendChild(document.createTextNode(levelTwo.title));
                li.appendChild(link);
                ul.appendChild(li);
            }
        }
    },

    init: function() {
        NAVIGATION.initLevelOne();
        $('navigation').style.visibility = 'visible';
    },

    showLevelTwo: function(event, el, levelOne) {
        if (FAA_UTILITY.isMouseLeaveOrEnter(event, el)) {
            $(levelOne + '_submenuContainer').show();
        }
        $(levelOne + '_Container').addClassName('hover');
    },

    hideLevelTwo: function(event, el, levelOne) {
        if (FAA_UTILITY.isMouseLeaveOrEnter(event, el)) {
            $(levelOne + '_submenuContainer').hide();
        }
        $(levelOne + '_Container').removeClassName('hover');
    }
};

var EXPANDABLE_TEXT = {
    toggle: function(textId, linkId) {
        if ($(textId) && $(linkId)) {

            if ($(textId).visible()) {
                $(textId).hide();
                $(linkId).innerHTML = ' More...';
            } else {
                $(textId).show();
                $(linkId).innerHTML = ' Less...';
            }
        }
    }
};


// DEPRECATED?
// The functions below are not too readable or maintainable, but they are used all over the place

function MM_swapImgRestore() { //v3.0
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}

function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

// Only used on www\users\pub\Preferences.aspx
function MM_blockLayers() {
    var i, p, v, obj, args = MM_blockLayers.arguments;
    for (i = 0; i < (args.length - 1); i += 2) if ((obj = MM_findObj(args[i])) != null) {
        v = args[i + 1];
        if (obj.style) { v = (v == 'show') ? 'inline' : (v == 'hide') ? 'none' : v; obj.style.display = v; } 
    }
}

function MM_swapImage() { //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}

function MM_openBrWindow(theURL, winName, features) { //v2.0
    window.open(theURL, winName, features);
}
