/*
 * Copyright (c) 2009 Discovery Health Systems.
 * The information contained in this file is the intellectual property of Discovery Health Systems (the owner).
 * No part of this file may be changed, copied or removed by persons other than the owner or persons
 * authorised to do so by the owner.
 */
var enableAjaxLoading = false;
var debugAjaxLoading = false;
var hoverTimeout = 700;
var context = '';
var defaultHoverNodeMarginTop = '-15px';
//var linkPrefix = '';
/* There might be a need for this in the future... (function($) {*//*Default values*//*var defaults = {};})(jQuery);*/
/*Convenience function to remove the selected class on an element.*/
var removeSelected = function(element) {
    element.removeClass('selected');
};
/*Convenience function to add the selected class on an element.*/
var setSelected = function(element) {
    element.addClass('selected');
};
/*Get the current menu context from the element that contains it.*/
var getMenuContext = function() {
    return $('#menuContext').val();
};
/*Get the actual expand node for the specified Menu Node Entry...*/
var getExpandNode = function(menuNodeEntry) {
    var expandNodeId = '#expand_node_' + $.getId(menuNodeEntry);
    return $(expandNodeId);
};
/*Selects a menu node, and writes the selected cookie.*/
var selectMenuNode = function(menuNode) {
    $('.expand_node').each(function() {
        if (JQueryUtils.getId($(this)) != 'expand_node_' + JQueryUtils.getId(menuNode)) {
            removeSelected($(this).parent().find('.menu_node > a.expand'));
            $(this).hide();
        }
    });
    $('.nonexpand').each(function() {
        removeSelected($(this));
    });

    setSelected(menuNode);
    setCookie(getMenuContext() + '_selectedMenuNodeId', JQueryUtils.getId(menuNode), 1);
};
/*Selects a expand menu node and it's parent, and writes the selected cookie.*/
var selectAllFromExpandNodeEntry = function(expandNodeEntry) {

    setSelected(expandNodeEntry);
    setCookie(getMenuContext() + '_selectedExpandNodeId', JQueryUtils.getId(expandNodeEntry), 1);
    var menuNode = expandNodeEntry.parent().parent().parent().find('.menu_node > a.expand');

    getExpandNode(menuNode).show();
    selectMenuNode(menuNode);
};
/*Selects a hover node and it's parent, and writes the selected cookie.*/
var selectAllFromHoverNodeEntry = function(hoverNodeEntry) {
    setSelected(hoverNodeEntry);
    setCookie(getMenuContext() + '_selectedHoverMenuNodeId', JQueryUtils.getId(hoverNodeEntry), 1);
    var expandNodeEntry = hoverNodeEntry.parent().parent().parent().parent().find('a.expand_node_entry');
    selectAllFromExpandNodeEntry(expandNodeEntry);
};
/*Select the currently selected hidden child node entry's parent.*/
var  selectHiddenChildNodeEntryParent = function(hiddenChildNodeEntry) {
    var parentNode = hiddenChildNodeEntry.parent().find('a.menu_item');
    if (parentNode) {
        selectAllFromExpandNodeEntry(parentNode);
    }
};
/*Handles the fly-out menus display process...*/
var hoverNodeShow = function(menuNode) {
    var menuNodeId = JQueryUtils.getId(menuNode);
    $('.hover_node').hide();
    $.jqo('hover_node_bridge_' + menuNodeId).hover(function() {
        menuNode.data('hovering', true);
    }, function() {
        hoverNodeHide(menuNode);
    });
    $.jqo('hover_node_shadow_' + menuNodeId).hover(function() {
        menuNode.data('hovering', true);
    }, function() {
        hoverNodeHide(menuNode);
    });
    $.jqo('hover_node_bridge_' + menuNodeId).show();
    $.jqo('hover_node_shadow_' + menuNodeId).show().each(function() {
      // check for IE6
      if ($.browser.msie && $.browser.version.substr(0,1)<8) {
        // check if iframe already exists if not add. (div containing iframe with absolute position)
        if ($(this).find('#hover_node_iframe_' + menuNodeId).length <= 0) {
          $(this).prepend('<div id="hover_node_iframe_' + menuNodeId + '" class="navLeftThirdiFrame"><iframe width="' + $(this).outerWidth() + 'px" height="' + $(this).outerHeight() + 'px" src="/portal/Ping.html" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no">IFrame not supported by your browser version...</iframe></div>');
        }
      }
      // makes sure hover object is not cut off by window.
      var windowheight = $(window).height();
      var scrollHeight = $(window).scrollTop();
      var hoverNodeWindowOffset = $(this).offset().top - scrollHeight;
      var hoverNodeBottom = hoverNodeWindowOffset + $(this).innerHeight();
      var hoverNodeOverflow = hoverNodeBottom - windowheight;
      if (hoverNodeOverflow >= 0) {
        // reposition hover node
        $(this).css('margin-top', (0 - hoverNodeOverflow + parseInt(($(this).css('margin-top')).substring(0, $(this).css('margin-top').indexOf('px')))) + 'px');
        hoverNodeWindowOffset = $(this).offset().top - scrollHeight;
        hoverNodeBottom = hoverNodeWindowOffset + $(this).innerHeight() - 10; // and subtract a couple of pixels for pixel error
        var bridgeWindowOffset = $(this).prev('.navLeftThirdContainerBridge').offset().top - scrollHeight;
        var bridgeBottom = bridgeWindowOffset + $(this).prev('.navLeftThirdContainerBridge').innerHeight();
        if (bridgeBottom  > hoverNodeBottom) {
          $(this).css('margin-top', (parseInt(($(this).css('margin-top')).substring(0, $(this).css('margin-top').indexOf('px'))) + (bridgeBottom - hoverNodeBottom)) + 'px');
        }
      } else {
        //set it back to default margin value
        $(this).css('margin-top', defaultHoverNodeMarginTop);
      }
    });
    menuNode.data('hovering', true);
};
/*Handles the fly-out menus hiding process...*/
var hoverNodeHide = function(menuNode) {
    var menuNodeId = JQueryUtils.getId(menuNode);
    menuNode.data('hovering', false);
    setTimeout(function() {
        if (!$.jqo(menuNodeId).data('hovering')) {
            $.jqo('hover_node_bridge_' + menuNodeId).hide();
            $.jqo('hover_node_shadow_' + menuNodeId).hide();
        }
    }, hoverTimeout);
};
/*Checks if the context needs to be scrubbed from the url...*/
var scrubUrlOfContext = function(url) {
    if (context) {
        var ctx = StringUtils.substringAfter(context, '/') + "/";
        url = StringUtils.substringAfter(url, ctx);
        if (debugAjaxLoading) alert('Scrubbed URL of Context: ' + url);
    }
    return url;
};
/*Check the states of the menu items...*/
var checkMenuStates = function(lastSelectedNode) {
    var selectedNode;

    if (lastSelectedNode) {
        selectedNode = lastSelectedNode;
    } else {
        var selectedLocation = location.pathname;
        if (location.href.search('#') >= 0) selectedLocation = location.href.split('#')[1];
        selectedLocation = scrubUrlOfContext(selectedLocation);
        var pathElements = selectedLocation.split('/');
        selectedNode = pathElements[pathElements.length - 1];
    }
    removeSelected($('.selected'));
    if ($.jqo(selectedNode)) {
        if ($.jqo(selectedNode).hasClass('menu_node_entry')) selectMenuNode($.jqo(selectedNode));
        if ($.jqo(selectedNode).hasClass('expand_node_entry')) selectAllFromExpandNodeEntry($.jqo(selectedNode));
        if ($.jqo(selectedNode).hasClass('hover_node_entry')) selectAllFromHoverNodeEntry($.jqo(selectedNode));
        if ($.jqo(selectedNode).hasClass('hidden_child_node_entry')) selectHiddenChildNodeEntryParent($.jqo(selectedNode));
    }
};
/*The history load callback function. This loads all the required framework elements like styles, breadcrumbs and the content itself via the AJAX APIs for each framework element.*/
var pageload = function(hash) {
    /*Make sure we have a hash to load...*/
    if (hash) {
        if (debugAjaxLoading) alert('Loading Hash: ' + hash);
        /*Recalculate the hash by stripping away context path...*/
        hash = scrubUrlOfContext(hash);
        /*Determine the style for the requested url...*/
        var ajaxOptions = {url: context + '/style.do?url=' + hash,success: function(data, textStatus) {
            try {
                if (textStatus != 'error') {
                    if (debugAjaxLoading) alert('AJAX Load of style returned: ' + data);
                    if ($.browser.msie) {
                        $($(document).attr('styleSheets')[1]).attr('href', data);
                    } else {
                        $('#overrideStyle').attr('href', data);
                    }
                }
            } catch(e) {/*Make sure the rest of the script is not broken if this fails...!*/
            }
        },dataType: 'text'};
        $.ajax(ajaxOptions);
        /*Update the breadcrumb accordingly for the requested url...*/
        if (debugAjaxLoading) alert('Trying AJAX Load of breadcrumb with URL: ' + context + '/breadcrumb.do?url=' + hash);
        $('#contentTop').load(context + '/breadcrumb.do?url=' + hash);
        /*Load the requested page/content/iframe/view for the requested url...*/
        if (debugAjaxLoading) alert('Trying AJAX Load of content with URL: ' + context + '/content.do?url=' + hash);
        $('#content').load(context + '/content.do?url=' + hash);
    }
};
/*Convenience function to check if an anchor element's target contains the specified value.*/
var targetContains = function(anchor, value) {
    return anchor && $(anchor).attr('target') && $(anchor).attr('target') == value;
};
/*The AJAX loading control function, this function will use the history plugin to load, using the specified callback method.*/
var ajaxLoad = function(anchor) {
    if (targetContains(anchor, '_blank') ||
        targetContains(anchor, '_top') ||
        targetContains(anchor, '_parent') ||
        targetContains(anchor, '_self')) {
        return true;
    }
    var url = anchor.pathname;
    $.historyLoad(url);
    checkMenuStates();
    return false;
};
/*Add the events that are required to control the menu.*/
var addMenuEvents = function() {
    /*Initialize the history plugin and register the callback function for it...*/
    if (enableAjaxLoading) {
        $.historyInit(pageload);
    }
    /* detect level 2 nav items spanning 2 lines that are expandable and change arrowUp class on span to wrapArrow class */
    $('.navLeftSecond').children('a').each(function() {
        if ($(this).innerHeight() > 25) {
            $(this).find('.arrowUp').removeClass('arrowUp').addClass('wrapArrow');
        }
    });
    /* set defaultHoverNodeMarginTop */
    defaultHoverNodeMarginTop = $('.navLeftThirdShadow:first').css('margin-top');
    /*Add click events for expandable items...*/
    $('.expand').click(function() {
        var expandNode = getExpandNode($(this));
        $('.expand_node').each(function() {
            if (JQueryUtils.getId($(this)) != JQueryUtils.getId(expandNode)) {
                $(this).hide();
            }
        });

        // Stop the top level menu's from expanding when clicked on. The content should load, and then only should they expand.
        if ($(this).attr('target') != '_self'){
            expandNode.toggle();
        }

        if(expandNode.css('display') == 'block'){
            return false;
        }
    });
    $('.hover').hover(function() {
        hoverNodeShow($(this));
    }, function() {
        hoverNodeHide($(this));
    });
    /*Click consume event if so specified by the element...*/
    $('.noclick').click(function () {
        return false;
    });
    /*Click event for menu items to use ajax loading...*/
    if (enableAjaxLoading) {
        $('a.menu_item:not(.noclick)').click(function() {
            return ajaxLoad(this);
        });
    }
};
/*Globally jqurery extended function to initialize left navigation scripts/events.*/
jQuery.extend({
    leftNavInit:function(ctx) {
        if (ctx && ctx != '/') context = ctx;
        checkMenuStates();
        addMenuEvents();
//        $(function() {addMenuEvents();});
},
    checkMenuState:function(selectedNode) {
        checkMenuStates(selectedNode);
    }
});
