/*
* Author: Pradeep Kumar S, Vipashyin Web
* Project: Navigation Menu Slider, for Invivia
* Version: v1.44
* Notes:
* To use this script, simply place the following code in your document:
* <div id="menu_layers"></div>
* Do not use the following IDs in your page: menu_layers, menu_top, menu_bottom, menu_submenus.
* Do not use a node named "text" in the XML document, as the xml2json plugin uses this keyword to denote values in a node.
* If the styles ever break in Chrome, modify the padding values in this document for it to look right.
*/
var currentLevel = 10; // Equal to z-index of menu item in menu_top
var arrowWidth = 17;
var shadowWidth = 5; // For submenu
// Set this value to the padding-left value in menuslider.css
var padding = 8; // For Google Chrome
var offset = 0; // For Google Chrome
var correction = 0; // Padding correction: Left Padding on menu items with arrows seemed too much
var arrowFlag = 0; // For switching from Arrow to End only if necessary
var initOffset = 35; // Explained during time of usage (offset problem on initial loading -- if the home icon's size changes, change this value)
var MenuTopZIndex = 20;
var htmlMenuTop = "";
var htmlMenuBot = "";
var FromStateID, ToStateID;
var disableAnimation = true;
$(document).ready(function() {
    var sPath = window.location.pathname;
    var sLoc = sPath.substring(0, sPath.lastIndexOf('/') + 1)

    $("#menu_layers").html("Loading...");
    imgstopreload = new Array(
		'../../images/header/arrow.png',
		'../../images/header/arrow-gray.png',
		'../../images/header/end.png',
		'../../images/header/end-submenu.png',
		'../../images/header/end-submenu-gray.png',
		'../../images/header/nav_home.png',
		'../../images/header/nav_home_over.png',
		'../../images/header/shadow-submenu.png'
	);
    for (x in imgstopreload) { (new Image).src = imgstopreload[x]; }
    var menuLoc = sLoc + "xml/menuslider.xml";
    // Check to see if menuslider has a localized version, if not use global version
    $.ajax({
        url: menuLoc,
        type: 'GET',
        success: function() {
            buildmenu();
        },
        error: function() {
            menuLoc = '../../en/us/xml/menuslider.xml';
            buildmenu();
        }
    })


    function buildmenu() {
        $.get(menuLoc, function(xml) {

            // Creating Menu - XML -> JSON -> HTML

            $("#menu_layers").html('<div id="menu_top"></div><div id="menu_bottom"></div><div id="menu_submenus"><span></span><span class="shadow"></span></div><div style="clear:both" />');

            var menu = $.xml2json(xml, true);
            createJSONMenu(menu.item, true, MenuTopZIndex);

            $("#menu_top").append(htmlMenuTop);
            $("#menu_bottom").append(htmlMenuBot);

            // End - Creating Menu

            resetState('init');
            if (ToStateID == null)
                ToStateID = 'h';
            if (FromStateID == null)
                FromStateID = 'h';
            if (disableAnimation)
                FromStateID = ToStateID;
            loadState(FromStateID, ToStateID);

            // Adjust padding for arrows
            $("#menu_bottom > *").each(function() {
                offset = parseInt($(this).children().children(":first").css("padding-left"), 10) + arrowWidth;
                $(this).children().children(":first").css("padding-left", offset);
            });

            // Top Menu Action
            $("#menu_top > *").find("a").bind("mousemove", function() {
                showSubmenu($(this));
            });
            $("#menu_bottom").bind("mouseenter mouseout", function() {
                hideSubmenu();
            });
            $("#menu_layers").bind("mouseleave", function() {
                hideSubmenu();
            });
        });
    }
});

function resetState(init) {
    // Show only home icon, move in others	
    $("#menu_top > *:not(:first)").each(function() {
        $(this).css({
            "display": "none",
            "margin-left": "0px"
        });
        if (init != null) {
            offset = parseInt($(this).children(":first").children().css("padding-left"), 10) + arrowWidth - correction;
            if (IsChrome()) { // For Google Chrome
                offset += padding;
            }
            $(this).children(":first").children().css("padding-left", offset);
        }
    });
    // Move bottom menus in (for animation)
    $("#menu_bottom > *").each(function() {
        $(this).css({
            "display": "none",
            "margin-left": -$(this).attr("offsetWidth")
        });
    });
}

var MenuTop_Items = new Array();
var MenuTop2_Items = new Array();
var m = 0; // matching
var flag = 0; // if same menu is requested
function animateR(MenuTop_Items, i, timeGap) { // Recursive Animation
    var menuTopWidth = 0;
    if (i <= MenuTop_Items.length - 1) {
        $TopMenu = $("#mt_" + MenuTop_Items[i]).parent().parent();
        $TopMenu.hide();
        $("#menu_top > *:visible").each(function() {
            menuTopWidth += $(this).attr("offsetWidth");
        });
        $TopMenu.show();
        $TopMenu.animate({ marginLeft: menuTopWidth }, timeGap, "linear", function() {
            animateR(MenuTop_Items, ++i, timeGap);
        });
    }
    if (i == (MenuTop_Items.length - 1) || MenuTop_Items.length == 1) {
        if (MenuTop_Items.length == 1)
            i = 0;
        var newMenuTopWidth = menuTopWidth + $("#menu_top > *:visible:last").attr("offsetWidth");
        if ($("#" + MenuTop_Items[i]).length != 0) { // submenu exists
            $("#" + MenuTop_Items[i]).show();
            $("#" + MenuTop_Items[i]).animate({ marginLeft: newMenuTopWidth }, timeGap * 2.5);
        }
        if (MenuTop_Items.length == 1)
            i = 1;
    }
    if (i == MenuTop_Items.length && timeGap == 1) {
        if (!disableAnimation)
            animateInR(MenuTop2_Items.length - 1);
    }
}

function animateInR(i) {
    if (flag == 0) {
        $BotMenu = $("#menu_bottom > *:visible");
        if ($BotMenu.length != 0) {
            $BotMenu.animate({ marginLeft: -$BotMenu.attr("offsetWidth") }, 500, "linear", function() {
                $BotMenu.hide();
                animateInR(i);
            });
        } else if (i > m) {
            $TopMenu = $("#mt_" + MenuTop2_Items[i]).parent().parent();
            $TopMenu.animate({ marginLeft: "0px" }, 200, "linear", function() {
                $TopMenu.hide();
                animateInR(--i);
            });
        } else {
            colorMenu(MenuTop_Items);
            animateR(MenuTop_Items, 1, 200); // Starts from 1, because Home shouldn't be animated. Time Gap = 1 implies no animation.	
        }
    }
}

function gotoState(FromMenuID, ToMenuID) { // need to reset flag, this function doesn't work as of now
    resetState();
    loadState(FromMenuID, ToMenuID);
}

function loadState(FromMenuID, ToMenuID) {
    if (FromMenuID == 'h') {
        // Move home menu past menu_top
        // The first time the menu loads onto the browser, there's an unexplainable gap introduced
        // which disappears on refreshing the page
        // Old: offset = parseInt($("#mt_home").attr("offsetWidth"), 10);
        // New: 
        offset = initOffset;
        $("#menu_bottom > *:first").css({
            "display": "",
            "margin-left": offset
        });
    }
    var TempID = ToMenuID;
    do {
        MenuTop_Items.push(TempID);
        $Test = $("#mb_" + TempID).parent().parent();
        TempID = $Test.attr("id");
    } while ($Test.length != 0);
    MenuTop_Items.reverse();

    TempID = FromMenuID;
    do {
        MenuTop2_Items.push(TempID);
        $Test = $("#mb_" + TempID).parent().parent();
        TempID = $Test.attr("id");
    } while ($Test.length != 0);
    MenuTop2_Items.reverse();

    for (var i = 1; i < MenuTop_Items.length; i++) {
        for (var j = 1; j < MenuTop2_Items.length; j++) {
            if (MenuTop_Items[i] == MenuTop2_Items[j]) {
                m++;
            }
            else
                break;
        }
    }
    if (m == MenuTop_Items.length - 1 && MenuTop_Items.length == MenuTop2_Items.length) {
        flag = 1;
    }
    colorMenu(MenuTop2_Items);
    animateR(MenuTop2_Items, 1, 1);
}

function colorMenu(MenuTop_Items) {
    for (var i = 0; i < MenuTop_Items.length; i++) {
        $TopMenu = $("#mt_" + MenuTop_Items[i]).parent().parent();
        if (i == MenuTop_Items.length - 1) {
            $TopMenu.children()
					.children("a").removeClass("gray")
					.end()
					.filter(".arrow-gray").removeClass("arrow-gray").addClass("arrow")
					.end();
        } else {
            $TopMenu.children()
					.children("a").addClass("gray")
					.end()
					.filter(".arrow").removeClass("arrow").addClass("arrow-gray")
					.end();
        }
    }
}

function hideSubmenu() {
    $("#menu_submenus > span").empty();
    $("#menu_submenus").css("display", "none");
}

function showSubmenu($Item) {
    if ($Item != $("#menu_submenus > span > *")) {
        hideSubmenu();
    }
    // Get ID of requested menu
    var MenuID = $Item.attr("id").substring(3);
    $SubMenu = $("#mb_" + MenuID).parent().parent();
    $SubMenu.clone().addClass($Item.hasClass("gray") ? "submenu-gray" : "submenu").css({
        "display": "",
        "margin-left": parseInt($Item.parent().parent().css("margin-left"), 10)
    }).appendTo("#menu_submenus > span:first")
	.children(":first").children().each(function() {
	    $(this).css("padding-left", parseInt($(this).css("padding-left"), 10) - arrowWidth - 10);
	}).end().end().children().each(function() {
	    $(this).children(":first").css("padding-left", parseInt($(this).children(":first").css("padding-left"), 10) + arrowWidth - correction + ((IsChrome()) ? padding : 0));
	    $(this).children(":first").css("padding-right", parseInt($(this).children(":first").css("padding-right"), 10) + arrowWidth - shadowWidth);
	});

    if ($("#menu_submenus > span:first > *").length > 0) {
        $("#menu_submenus").css({
            "display": "",
            "z-index": parseInt($Item.parent().parent().css("z-index"), 10) + 1
        });
    }

    // Shift current menu item to the top
    $("#menu_submenus > span:first > *").children(":contains(" + $Item.text() + ")").remove().prependTo("#menu_submenus > span:first > *");
    $("#menu_submenus > span:last").css({
        "width": shadowWidth,
        "height": $("#menu_submenus > span:first").attr("offsetHeight")
    });

    // Bind actions after shift
    $("#menu_submenus > span:first").find("a").click(function() {
        //hideMenu($(this));
        hideSubmenu();
    });
}

// Creates a unique ID for your menu item
function createID(text) {
    var myID = text.toLowerCase().replace('&', 'n', 'g').replace('-', '_', 'g').replace(/ /g, '_').replace(',', '');
    var i = 0;
    while (htmlMenuTop.indexOf('"mt_' + myID + '"') != -1) myID += i++;
    return myID;
}
// Converts from a JSON tree to HTML
function createJSONMenu(jsonObj, root, depth) {
    $.each(jsonObj, function(i, obj) {
        var myText = "";
        if (!root)
            myText = obj.name[0].text;
        else
            myText = obj.name;

        if (typeof (obj.link) != "undefined")
            myLink = obj.link[0].text;
        else
            myLink = "javascript:void(0)";

        var hasSubmenu = false;

        //Hidden variables
        var isHidden = false;
        var isSelectedPage = false;
        var currentPath = (window.location.pathname);
        var lastIndex = currentPath.lastIndexOf('/');
        var currentPage = currentPath.substring(lastIndex + 1, currentPath.length);

        if (obj.submenu) {
            hasSubmenu = true;

            if (typeof (obj.hideSubmenu) != "undefined")
                if (obj.hideSubmenu == "true") {
                isHidden = true;
            }

        }


        var myID = "";
        myID = createID(myText);

        var rg = new RegExp(myLink + '$');
        if (window.location.pathname.match(rg) != null) {
            ToStateID = myID;
        }
        if (FromPath != null && FromPath.match(rg) != null) {
            FromStateID = myID;
        }
        //Set class for home button/rollover

        /*BEGIN OLD
        htmlMenuTop += '<div style="z-index: ' + depth + '"><span><a href="' + myLink + '" id="mt_' + myID + '">';

        if (obj.name.imageurl)
        htmlMenuTop += '<img src="' + obj.name.imageurl + '" alt="' + myText + '" hspace="0" vspace="0" border="0" />';
        else
        htmlMenuTop += myText;
        htmlMenuTop += '</a></span><span class="' + ((hasSubmenu) ? 'arrow' : 'end') + '"></span></div>\r\n';
        END OLD*/

        //BEGIN NEW, SETS ROLLOVER CLASSES FOR HOME BUTTON
        if (myID == 'h') {
            htmlMenuTop += '<div style="z-index: ' + depth + '"><span id="menu_home" onmouseover="btnHomeOver()" onmouseout="btnHomeOut()"><a href="' + myLink + '" id="mt_' + myID + '">';
        } else {
            htmlMenuTop += '<div style="z-index: ' + depth + '"><span><a href="' + myLink + '" id="mt_' + myID + '">';
        }
        if (obj.name.imageurl) {
            htmlMenuTop += '<img id="menu_img" src="' + obj.name.imageurl + '" alt="' + myText + '" hspace="0" vspace="0" border="0" />';
            htmlMenuTop += '</a></span><span class="' + ((hasSubmenu) ? 'arrow' : 'end') + '"></span></div>\r\n';
        } else {
            htmlMenuTop += myText;
            htmlMenuTop += '</a></span><span class="' + ((hasSubmenu) ? 'arrow' : 'end') + '"></span></div>\r\n';
        }
        //END NEW

        if (hasSubmenu) {

            if (!isHidden) {

                htmlMenuBot += '<ul id="' + myID + '">';
                $.each(obj.submenu[0].item, function(i, obj) {
                    myText = obj.name[0].text;
                    myID = createID(myText);
                    if (typeof (obj.link) != "undefined")
                        myLink = obj.link[0].text;
                    else
                        myLink = "javascript:void(0)";

                    htmlMenuBot += '<li><a href="' + myLink + '" id="mb_' + myID + '">' + myText + '</a></li>';
                });

                htmlMenuBot += '</ul>';
                createJSONMenu(obj.submenu[0].item, false, depth - 2);

            }
            else {

                var isCurrentPageInSubMenu = IsInSubMenu(currentPage, obj.submenu[0].item);

                if (isCurrentPageInSubMenu) {

                    // Again create the menu

                    htmlMenuBot += '<ul id="' + myID + '">';
                    $.each(obj.submenu[0].item, function(i, obj) {
                        myText = obj.name[0].text;
                        myID = createID(myText);
                        if (typeof (obj.link) != "undefined")
                            myLink = obj.link[0].text;
                        else
                            myLink = "javascript:void(0)";

                        htmlMenuBot += '<li><a href="' + myLink + '" id="mb_' + myID + '">' + myText + '</a></li>';
                    });

                    htmlMenuBot += '</ul>';
                    createJSONMenu(obj.submenu[0].item, false, depth - 2);

                    // end of creation
                }

            }
        }


        //}
    });





}


function btnHomeOver() {
    $('#menu_img').css("visibility", "hidden");
}




function btnHomeOut() {
    $('#menu_img').css("visibility", "visible");
}


function IsInSubMenu(currentPage, jsonObj) {

    var isFound = false;

    $.each(jsonObj, function(i, obj) {
        if (currentPage == obj.link[0].text)
            isFound = true;

    });

    if (currentPage == 'home.aspx')
        isFound = true;

    return isFound;


}
function IsChrome() {
    return navigator.userAgent.toLowerCase().indexOf("chrome") + 1;
}