﻿
/*
* GLOBAL VARIABLES
*/
var debugPanel;
var debugMode = false;


/*
 * SITE INIT - add all function that need to be run on page load into this function
 * site pages and templates
 */
$(document).ready(function () {
    debugPanel = $("<div id='debug'></div>").insertAfter("div.global-family");
    if (!debugMode) { debugPanel.hide(); }
    setLinkClasses();
    initDropMenus();
    initHeaderFormElements();
    initSideNavMenus();
    initDeferredLoading();
});

/*
 * SET LINK CLASSES - applies link styles on page load to make styles compatible with all
 * browsers regardless of CSS3 selector capabilities
 */
function setLinkClasses() {
    $('.main a[href^="mailto:"]').addClass("link-email");
    $('.main a[href$=".pdf"]').addClass("link-pdf");
    $('.main a[href$=".doc"]').addClass("link-word");
    $('.main a[href$=".xls"]').addClass("link-excel");
    $('.main a[href$=".rss"], a[href$=".rdf"]').addClass("link-feed");
    $('.main a[href^="aim:"]').addClass("link-messenger");
    // only add external-link to items that don't have a link class already
    $('.main a[target$="blank"]').not('[class*="link-"]').addClass("link-external");
    $('.main a[class*="link-"] > img:first-child').parent().removeClass("link-external link-pdf link-word, link-excel link-feed link-email"); // remove from linked images
    //$('.main a[class~="button"]').removeClass("link-external link-pdf link-word, link-excel link-feed link-email"); // remove from buttons
}



/*
 * DROP MENU CODE - Creates and controls drop-menus on all
 * site pages and templates
 */
function initDropMenus() {

    var dropMenuTimeout; // will hold id for setTimeout
    var dropMenuTriggers; //JQObj with top-level menu triggers
    var dropMenus; //JQObj with drop menus

    // detach drop-menus and move them outside the <nav> tag (this gets around z-index issues in IE)
    $('<ul class="drop-menus"></ul>').insertAfter("header");
    $("nav li.drop-menu").detach().appendTo("ul.drop-menus");

    dropMenuTriggers = $("nav li.top-level");
    dropMenus = $("ul.drop-menus > li");
    //debugPanel.append("dropMenuTriggers: " + dropMenuTriggers.length + ", dropMenus: " + dropMenus.length);

    dropMenuTriggers.hover(triggerDropMenu, startDropMenuTimeout);
    dropMenus.hover(stopDropMenuTimeout, startDropMenuTimeout);
    dropMenuTriggers.children("a").bind("touchstart", touchEventTrigger);

    //SET INITIAL MENU POSITIONS AND ONRESIZE
    setMenuPositions();
    $(window).resize(setMenuPositions);

    function setMenuPositions() {
        // SET POSITION FOR MENUS TO DISPLAY
        var dropMenuArray = dropMenus.toArray();
        var triggerNode;
        for (x in dropMenuArray) {
            triggerNode = dropMenuTriggers.filter("#" + dropMenuArray[x].id + "Trigger");
            triggerNode.data("menuNodeID", dropMenuArray[x].id);
            //debugPanel.append(x+":"+triggerNode[0].id + " is " + triggerNode.position().left + "; ");
            switch (x) {
                case "0":
                    $(dropMenuArray[x]).css("left", triggerNode.offset().left);
                    break;
                case "1":
                    $(dropMenuArray[x]).css("left", triggerNode.offset().left - 40);
                    break;
                case "2":
                    $(dropMenuArray[x]).css("left", (triggerNode.offset().left + triggerNode.outerWidth()) - $(dropMenuArray[x]).outerWidth() + 80);
                    break;
                case "3":
                    $(dropMenuArray[x]).css("left", (triggerNode.offset().left + triggerNode.outerWidth()) - $(dropMenuArray[x]).outerWidth());
                    break;
            }
            $(dropMenuArray[x]).css("top", triggerNode.offset().top + triggerNode.outerHeight());
        }
    }

    // for touch devices, first click will trigger a menu, second will trigger the actual link
    // touch-triggered menus have a separate timeout (5 seconds)
    function touchEventTrigger(evtObj) {
        var menuName = $(evtObj.currentTarget).parent().data("menuNodeID");
        if (dropMenus.filter("#" + menuName).is(":hidden")) {
            $(evtObj.currentTarget).parent().trigger("mouseenter");
            dropMenuTimeout = setTimeout(hideDropMenus, 5000);
            return false;
        }
    }

    function triggerDropMenu(evtObj) {
        // hide all menus
        hideDropMenus();

        // visually highlight top-level trigger
        $(evtObj.currentTarget).addClass("selected");

        // remove get ID of menu to show
        var menuName = $(evtObj.currentTarget).data("menuNodeID");
        //debugPanel.html("showing menu " + menuName);
        dropMenus.filter("#" + menuName).show();
        stopDropMenuTimeout();
    }
    function stopDropMenuTimeout() {
        clearTimeout(dropMenuTimeout);
    }
    function startDropMenuTimeout() {
        dropMenuTimeout = setTimeout(hideDropMenus, 500);
    }
    function hideDropMenus() {
        dropMenus.hide();
        dropMenuTriggers.removeClass("selected");
    }
    this.hideDropMenus = hideDropMenus; // MAKE INTO A PUBLIC METHODS
}





/*
* HEADER FORM INIT - Sets up default values and blur/focus events for
* site search and login/password forms
*/
function initHeaderFormElements() {
    // register header boxes for blur/focus behaviour
    var siteSearchBox = $('header input.site-search-box')[0];
    registerBlurFocusInput(siteSearchBox, "Search Site");

    var loginUserBox = $('header input.login-username')[0];
    registerBlurFocusInput(loginUserBox, "User Name");

    var loginPasswordBox = $('header input.login-password')[0];
    registerBlurFocusInput(loginPasswordBox, "Password");

    // attempt to catch "enter" on site-search box
    $(siteSearchBox).keypress(function (e) {
        var characterCode = e.charCode || e.keyCode;

        if (characterCode == 13) {

            // hack: id like to find a better way to post back here - gjv
            __doPostBack($('header input.search-site-button').attr("id").replace("_", "$"), "");

            if (e.preventDefault) {
                e.preventDefault();
                e.stopPropagation();
            }
            else {
                e.returnValue = false;
                e.cancelBubble = true;
            }

            return false;
        }
        else {
            return true;
        }
    });

}


// USE THIS TO REGISTER ANY TEXT OR PASSWORD INPUT THAT NEEDS TO DIM AND HAVE
// A SUGGESTIVE VALUE, BUT CLEAR OUT AND BRIGHTEN FOR TYPING
function registerBlurFocusInput(inputElement, initialValue) {
    if (inputElement == undefined)
        return;

    var inputElement = $(inputElement).filter(":text,:password");
    if (inputElement.length < 1) // if not a text or pasword input, quit
        return;

    var isPassword = (inputElement.filter(":password").length > 0); // determine if box is password

    inputElement.data("initialValue", initialValue || inputElement.val());
    inputElement.data("isPassword", isPassword);
    inputElement.focus(onTextInputFocus).blur(onTextInputBlur);
    
    function onTextInputFocus(evtObj) {
        var formInput = $(evtObj.currentTarget);
        formInput.removeClass("quiet");
        if (formInput.val() == formInput.data("initialValue")) {
            formInput.val("");

            if (formInput.data("isPassword")) {
                try { // this is a try because IE doesn't support setting this property
                    evtObj.currentTarget.setAttribute('type', 'password');
                    formInput.focus();
                } catch(err) {}
            }

        }
    }

    function onTextInputBlur(evtObj) {
        var formInput = $(evtObj.currentTarget);
        if (formInput.val() == "" || formInput.val() == formInput.data("initialValue")) {
            if (formInput.data("isPassword")) { // this is a try because IE doesn't support setting this property
                try {
                    evtObj.currentTarget.setAttribute('type', 'text');
                } catch (err) {}
            }
            formInput.val(formInput.data("initialValue"));
            formInput.addClass("quiet");
        } else {
            if (formInput.data("isPassword")) { // this is a try because IE doesn't support setting this property
                try {evtObj.currentTarget.setAttribute('type', 'password');} catch(err) {}
            }
            formInput.removeClass("quiet");
        }
    }

    inputElement.blur();

}



/*  SIDE NAV ENGINE
=========================================
Any page that has a side menu with sections will need this code to make the 
side nav work properly
    
LOGIC: after page loads, will check page to see how it matches the current URL an
will highlight the appropriate list item as ".current" If current item is a section heading,
it will be set to expanded (from expandable) and will not make the shadowed selection box.
If it is a member of a subnav list, the list will be left expanded (and parent set to expanded).
Otherwise, current items get shadowed selection box, and expandable lists collapse.
*/

function initSideNavMenus() {
    // HIGHLIGHT "CURRENT" ITEM
    $('ul.sidenav-menu li a[href="' + window.location.pathname + '"]').addClass("current").parent().addClass("current");
    
    // ONLY APPLY FULL MENU TREATMENT IF A SIDENAV MENU EXISTS AND WE'RE NOT ON IE6
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        if ($('ul.sidenav-menu li.expandable').length == 0) {
            return;
        } else {
            $('ul.sidenav-menu li.expandable > a').addClass("expandable");
            return;
        }
    }

    // COLLAPSE ALL SIDE SUBNAV MENUS, AND IF BLANK HREF, ASSIGN A CLICK ACTION TO EXPAND/COLLAPSE
    $('ul.sidenav-menu li.expandable > a').click(onSubsectionClick);
    $("ul.sidenav-menu li.expandable ul.sidenav-submenu").not(":has('li.current')").each(function () { contractSubMenu($(this)); });
    $("ul.sidenav-menu li.expandable ul.sidenav-submenu").has("li.current").each(function () { expandSubMenu($(this)); });

    function onSubsectionClick(evtObj) {
        var trigger = $(evtObj.currentTarget);
        var childMenu = trigger.parent().children("ul.sidenav-submenu");
        if (childMenu.is(":visible")) {
            contractSubMenu(childMenu);
        } else {
            expandSubMenu(childMenu);
        }

        return false; // STOPS EVENT FROM BUBBLING TO A TAG
    }

    function contractSubMenu(childMenuJQO) {
        childMenuJQO.hide().parent().removeClass("expanded").addClass("expandable");
    }
    function expandSubMenu(childMenuJQO) {
        childMenuJQO.show().parent().removeClass("expandable").addClass("expanded");
    }
}

/*
*/
function initDeferredLoading() {
    $('div[load]').load($(this).attr('load'));
}
