/****************************************************************************************
 Description:   1st - The Exchange Prospects Site - Sitemap JS 
 Created:       23/02/2009
 Author:        Mike Hearfield/Nick Elliott - Presentation Team, Cheltenham 
 Copyright:     Independent Specialist Technology (UK) Ltd. 2009, All Rights Reserved.
****************************************************************************************/


/******************** TABLE OF CONTENTS ********************/

// 1.  GLOBAL VARIABLES
// 2.  DOCUMENT READY (ON LOAD)
// 3.  AJAX CALLBACK FUNCTIONS
// 4.  MAKE MENU STRING FROM XML
// 5.  MAKE MENU FROM STRING
// 6.  MAKE FOOTER MENU STRING FROM XML
// 7.  MAKE FOOTER MENU FROM STRING
// 8.  LOGIN INTERACTIONS 

/************************************************************/

/*
	File spec:
	load sitemap.
		Add entries to main menu
		Add entries to footer menu if within global limit
		If there's a contextId in the querystring, look for it in the entries and cookie the id and text
		
	Inc.js:
		Setup page context text using defaults or context as appropriate
*/

/******************** GLOBAL VARIABLES **********************/
var CONSTANT_timeout = 500;
var closetimer = null;
var ddMenuItem = null;
var strMainMenuClassName = "ulMenuMain";
var strSitemapMenuClassName = "ulFooterMenu";
var strCookieFooterMenuState = "cooFooterMenuState";
var strFooterMenuOpen = "true";
var strMenuStringSeparator = "~~~";

// setup an array to contain menuItem data
var arrMenuItem = new Array();

//var intFooterMenuRowCount = 5;
/************************************************************/


/******************** DOCUMENT READY (ON LOAD) ********************/
$(function() {
  // Should the footer menu be open?
  strFooterMenuOpen = ($.cookie(strCookieFooterMenuState) && $.cookie(strCookieFooterMenuState).length > 0) ? $.cookie(strCookieFooterMenuState) : strFooterMenuOpen;
  // load page text from XML
  loadPageTextFromXML();
  initLoginInteractions();

  //sort height on column floats
  $(".mainColumn").equalHeights();
  $("#divMainColumns").height($("#divMainColumn1").height());

  strContextHeading = $("#divImageContentInnerContainer h2").text();
  strContextId = $("body").attr("class");
})
/************************************************************/


/******************** AJAX CALLBACK FUNCTIONS ********************/
function ajaxMenuCallback(menuString) {
	makeMenuFromString(menuString);	
}

function ajaxSitemapCallback(menuString){
	makeFooterMenuFromString(menuString);
}
/************************************************************/


/******************** LOAD PAGE TEXT FROM XML ********************/
function loadPageTextFromXML() {
	// paints menu & sitemap XML-sourced page text

	var defaults = {
		xmlPath: "/xml/sitemap.xml"
	};

	$.get(defaults.xmlPath, {}, function(xml) {

	    // start mainMenuString off, when the intFooterMenuRowCount is reached, clone a copy as footerMenuString.
	    var mainMenuString = "<ul class='" + strMainMenuClassName + "'>";
	    var footerMenuString = "<h2 id='h2MenuExpandContract'><a href='#' name='sitemaplink' class='lnkMenuExpandContract' title='Expand or contract the menu'>Sitemap</a></h2><ul class='" + strSitemapMenuClassName + "'>";

	    // sitemap expand/collapse click event
	    $(".lnkMenuExpandContract").live("click", function(e) {
	        $("." + strSitemapMenuClassName + " li.liMenuEntry").toggle();
	        $(this).toggleClass("sitemapHidden");
	        strFooterMenuOpen = (strFooterMenuOpen == "true") ? "false" : "true";
	        $.cookie(strCookieFooterMenuState, strFooterMenuOpen, { expires: 7, path: '/' });
	        if (strFooterMenuOpen) { // focus on last field of sitemap briefly so that sitemap fully opens
	            $(".liMenuEntry:last a:last").focus();
	            $(this).focus();
	        }
	        e.preventDefault();
	    });

	    /* for each menu entry:
	    1) Add to main menu
	    2) If within page's intFooterMenuRowCount, add to footerMenu
	    3) If page has a contextId in its querystring, look it up and cookie the "id" and "text" attributes
	    4) stuff it in an array for retrieval later
	    */
	    $("menuEntry", xml).each(function(i) {
	        // check to see if this should be displayed in the main menu
	        var displayInMainMenu = ($(this).attr("mainMenu") == "1");
	        if (displayInMainMenu) {
	            var strOnClick = ($(this).attr("href") == "#") ? "onclick='return false;'" : "";
	            mainMenuString += "<li class='liMenuHeading'><a href='" + $(this).attr("href") + "' " + strOnClick + " title='" + $(this).attr("title") + "' class='aMenuHeading'>" + $(this).attr("text") + "</a>";
	            footerMenuString += "<li class='liMenuHeading'><a href='" + $(this).attr("href") + "' " + strOnClick + " title='" + $(this).attr("title") + "'>" + $(this).attr("text") + "</a>";
	        }

	        // check to see if there is a submenu to render
	        if ($(this).find("menuItem").size() > 0) {
	            if (displayInMainMenu) {
	                mainMenuString += "<ul>";
	                footerMenuString += "<ul>";
	            }
	            $(this).find("menuItem").each(function(j) {

	                // if there is a context in the page's querystring, check it agains the element's ctxt attribute
	                if (($.query.get('ctxt') != undefined) && ($(this).attr("id").toLowerCase() == $.query.get('ctxt').toLowerCase())) {
	                    $.cookie(strCookieContextText, $(this).attr("text"), { expires: 7, path: '/' });
	                    $.cookie(strCookieContextId, $(this).attr("id"), { expires: 7, path: '/' });
	                    pageContext = strCookieContextText;
	                }

	                // if there is a context, add it to the href for later retrieval
	                var strCtxt = ($(this).attr("ctxt") != undefined) ? "?ctxt=" + $(this).attr("ctxt") : "";
	                // if the href is a "#" then add some onclick to cancel navigation
	                var strSubOnClick = ($(this).attr("href") == "#") ? "onclick='return false;'" : "";
	                //check to see if menu item has subtitle
	                var strSubTitle = ($(this).attr("subtitle") != undefined) ? "<div>" + $(this).attr("subtitle") + "</div>" : "";

	                if (displayInMainMenu) {
	                    mainMenuString += "<li><div class='liMenuSub'><a href='" + $(this).attr("href") + strCtxt + "' " + strSubOnClick + " title='" + $(this).attr("title") + "'>" + $(this).attr("text") + strSubTitle + "</a></div></li>";

	                    // check to see if we should save a copy for the footer
	                    footerMenuString += /*(j < intFooterMenuRowCount) ?*/ "<li class='liMenuEntry'><a href='" + $(this).attr("href") + strCtxt + "' " + strSubOnClick + " title='" + $(this).attr("title") + "'>" + $(this).attr("text") + "</a></li>" /*: ""*/;
	                }

	                var menuItemObj = new Object();
	                menuItemObj.text = $(this).attr('text');
	                menuItemObj.id = $(this).attr('id');
	                menuItemObj.href = $(this).attr('href');
	                menuItemObj.title = $(this).attr('title');
	                // check to see if there's an array of entries, if there's nothing set the array length to 0, if there's 1, make an array of 1.
	                menuItemObj.services = ($(this).attr('svc') && $(this).attr('svc').indexOf(",") != -1) ? $(this).attr('svc').split(",") : ($(this).attr('svc') == undefined) ? "" : Array($(this).attr('svc'));
	                menuItemObj.support = ($(this).attr('spt') && $(this).attr('spt').indexOf(",") != -1) ? $(this).attr('spt').split(",") : ($(this).attr('spt') == undefined) ? "" : Array($(this).attr('spt'));
	                menuItemObj.products = ($(this).attr('prd') && $(this).attr('prd').indexOf(",") != -1) ? $(this).attr('prd').split(",") : ($(this).attr('prd') == undefined) ? "" : Array($(this).attr('prd'));
	                menuItemObj.offers = ($(this).attr('off') && $(this).attr('off').indexOf(",") != -1) ? $(this).attr('off').split(",") : ($(this).attr('off') == undefined) ? "" : Array($(this).attr('off'));
	                menuItemObj.caseStudies = ($(this).attr('cst') && $(this).attr('cst').indexOf(",") != -1) ? $(this).attr('cst').split(",") : ($(this).attr('cst') == undefined) ? "" : Array($(this).attr('cst'));
	                menuItemObj.testimonials = ($(this).attr('tes') && $(this).attr('tes').indexOf(",") != -1) ? $(this).attr('tes').split(",") : ($(this).attr('tes') == undefined) ? "" : Array($(this).attr('tes'));

	                var arrSubMenuItem = new Array();

	                $(this).find("submenuItem").each(function(k) {
	                    var subMenuItemObj = new Object();
	                    subMenuItemObj.text = $(this).attr('text');
	                    subMenuItemObj.id = $(this).attr('id');
	                    subMenuItemObj.href = $(this).attr('href');
	                    subMenuItemObj.title = $(this).attr('title');
	                    arrSubMenuItem[k] = subMenuItemObj;

	                });
	                menuItemObj.subMenuItems = arrSubMenuItem;

	                arrMenuItem[$(this).attr('id')] = menuItemObj;
	                //log("arrMenuItem: " + $(this).attr('id'));

	                //set Parent text
	                if (menuItemObj.text == strContextHeading) {
	                    var thisMenuEntry = $(this).parents("menuEntry");
	                    if ($("#parent").length == 0) $("#divSidebarLeftTop h2").text(thisMenuEntry.attr("text"));
	                    $("li#liBreadParent").html("<a href='" + thisMenuEntry.attr("href") + "'>" + thisMenuEntry.attr("text") + "</a>>");
	                }
	            });

	            if (displayInMainMenu) {
	                mainMenuString += "</ul></li>";
	                footerMenuString += "</ul></li>";
	            }
	        }
	    });

	    mainMenuString += "</ul>";
	    footerMenuString += "</ul>";

	    // PAINT MAIN MENU
	    $("#divMenu").html(mainMenuString);
	    //main menu rollover functionality
	    //NE Comment: I've had to use the hover method rather than the mouseOver/mouseOut method to stop the event firing again on all child elements
	    $("." + strMainMenuClassName + " li.liMenuHeading").hover(function() { // mouseOver
	        if (closetimer) {
	            clearTimeout(closetimer);
	            closetimer = null;
	            $("." + strMainMenuClassName + " li.liMenuHeading ul").css({ "visibility": "hidden" });
	        }
	        if (jQuery.support.boxModel == false) $("ul li", $(this)).width("20.9em");  //fix hover list item width in IE6
	        // make hover list items equal height - to get this working on all browsers you need to do this on both the list item and the link contained within it
	        // as the hover list pairs list items, we only equal height on each pair.
	        $("ul li:even", $(this)).each(function(i) {
	            $(this).add($(this).next("li")).equalHeights(); // the list item pair
	            $("a", $(this)).add($(this).next("li").children("div").children("a")).equalHeights(); // the link pair
	        });
	        $("ul", $(this)).css({ "visibility": "visible" }).bgiframe();
	        return false;
	    },
    function() { // mouseOut
        closetimer = setTimeout(function() {
            $("ul", $("." + strMainMenuClassName + " > li.liMenuHeading")).css({ "visibility": "hidden" });
        }, CONSTANT_timeout);
        return false;
    });

	    mainMenuString = null;

	    // PAINT fOOTER MENU, hide links if necessary
	    $("#divSiteMap").html(footerMenuString);
	    footerMenuString = null;
	    initSiteMapFunctionality();

	    // PAINT SIDEBAR MENU, if applicable
	    if (window.pageMenuContents != undefined && window.pageId != undefined) {
	        // check which sections the page wants populated, defined in the page-hosted array "pageMenuContents" (e.g. ["support","services"])
	        // find the contents of arrMenuItem[pageId].services and paint them.
	        var strSidebar = "<ul class='sideMenu'>";
	        $.each(pageMenuContents, function(a) {
	            // the arrayMenuItem entry's length will be 0 if there were no associated things (e.g. no products related to the menu item)
	            if ((arrMenuItem[pageId][pageMenuContents[a]] != undefined) && (arrMenuItem[pageId][pageMenuContents[a]].length > 0)) {
	                strSidebar += "<li><a href='#' class='sideMenuCategory'>" + pageMenuContents[a].substr(0, 1).toUpperCase() + pageMenuContents[a].substr(1).toLowerCase() + "</a><ul class='sideMenuCat'>";
	                $.each(arrMenuItem[pageId][pageMenuContents[a]], function(b) {
	                    if (arrMenuItem[arrMenuItem[pageId][pageMenuContents[a]][b]] != undefined) {
	                        var menuItem = arrMenuItem[arrMenuItem[pageId][pageMenuContents[a]][b]];
	                        // if this menu items text equals the page's header, mark it as active
	                        var strActiveClass = (menuItem.subMenuItems.length > 0 && strContextId == menuItem.id) ? "sideMenuItemActive" : "";
	                        strSidebar += "<li class='sideMenuItem " + strActiveClass + "'><a href='" + menuItem.href + "' title='" + menuItem.title + "'>" + menuItem.text + "</a>";

	                        if (menuItem.subMenuItems.length > 0 && strContextId == menuItem.id) {
	                            strSidebar += "<ul>";
	                            $.each(menuItem.subMenuItems, function(c) {
	                                strSidebar += "<li><a href='" + menuItem.subMenuItems[c].href + "' title='" + menuItem.subMenuItems[c].title + "'>" + menuItem.subMenuItems[c].text + "</a></li>";
	                            });
	                            strSidebar += "</ul>";
	                        }

	                        strSidebar += "</li>";
	                    }
	                });
	                strSidebar += "</ul></li>";
	            }
	        });
	        $("#divSidebarLeftTop").append(strSidebar);
	        initSideMenuInteractions();
	    }

	    //PAINT PARENT CATEGORY MENU, if applicable
	    var parentList = "";
	    if ($("#parent").length > 0) {
	        $("menuEntry", xml).each(function(i) {
	            if ($(this).attr("text") == strContextHeading) {
	                $(this).find("menuItem").each(function(i) {
	                    parentList += "<li><a href='" + $(this).attr("href") + "'>" + $(this).attr("text") + "</a></li>";
	                });
	            }
	        });
	    }
	    $("#ulCategories").html(parentList).css({ zIndex: 0 });
/*	    $("#ulCategories li:even").each(function(i) {
	        $(this).add($(this).next("li")).equalHeights(); // the list item pair
	    });*/
	});
};
/************************************************************/

/******************** LOGIN INTERACTIONS ********************/
function initLoginInteractions() {

  $("#lnkExwebLogin, #lnkExtranetLogin").click(function() {

    // if another login box is already open slide it closed
    if ($(".divLoginBox:visible").length > 0) $(".divLoginBox").slideUp();

    // if this login box is not already open, open it, otherwise close it
    var thisBoxID = "#" + $(this).attr("id").replace("lnk", "div");
    if ($(thisBoxID + ":visible").length > 0) {
      $(thisBoxID).slideUp();
    } else {
      $(thisBoxID).slideDown("normal", function() {
        $(thisBoxID + " input:first").focus();
      });
    }
  });

  $(".btnCancel").click(function() {
    $(".divLoginBox").slideUp();
  });
}
/************************************************************/

/******************** SIDE MENU INTERACTIONS ********************/
function initSideMenuInteractions() {

  if ($("li.sideMenuItemActive").length > 0) { // if one of the menu options equals the current context
    $("li.sideMenuItemActive").parents("li").addClass("activeSection"); //add class to active section
    $("ul.sideMenu > li").not(".activeSection").addClass("nonActiveSection").children("ul").hide(); // hide non active sections
  } 

  $("ul.sideMenuCat li:last").css({ borderBottom: "none" }); // bodge to get rid of double border on bottom of each section

  $(".sideMenuCategory").click(function(e) { //side menu category click function i.e. products, services or support
    $(this).siblings("ul").slideToggle().parent("li").toggleClass("nonActiveSection");
    e.preventDefault();
  });
}
/************************************************************/

/******************** SITE MAP *******************/
function initSiteMapFunctionality() {


  if (strFooterMenuOpen == "false") {
    $("." + strSitemapMenuClassName + " li.liMenuEntry").hide();
    $("#h2MenuExpandContract a").addClass("sitemapHidden"); // sitemap is hidden - show arrow up icon
  }
  $("." + strSitemapMenuClassName + " li.liMenuHeading:last").width("15%");
  $(".liMenuEntry:last a:last").height("30px"); // used when expanding the sitemap
}

/************************************************************/