function CookieHandler () {};

// leave out nDays if session cookie required.
CookieHandler.setCookie = function ( sName, sValue, nDays ) {
	var expires = "";
	if ( nDays ) {
		var d = new Date();
		d.setTime( d.getTime() + nDays * 24 * 60 * 60 * 1000 );
		expires = "; expires=" + d.toGMTString();
	}
	document.cookie = sName + "=" + sValue + expires + "; path=/";
};

CookieHandler.getCookie = function (sName) {
	var re = new RegExp( "(\;|^)[^;]*(" + sName + ")\=([^;]*)(;|$)" );
	var res = re.exec( document.cookie );
	return res != null ? res[3] : null;
};

CookieHandler.removeCookie = function ( name ) {
	CookieHandler.setCookie( name, "", -1 );
};

function HierListNav () {};

/**
 * Returns the first child "ul" element in parent passed as parameter "p".
 * Returns null if no "ul" element is found with child "li" elements.
 */
HierListNav.findFirstULWithLI = function(p) {
	var el = p.childNodes;		//getElementsByTagName("ul");
	for (var i = 0; i < el.length; i++) {
		if (el[i].nodeName == "UL" && el[i].getElementsByTagName("li").length > 0)
			return el[i];	// if there is a li at any level below a "UL" then can safely assume the UL concerned is a submenu
	}
	return null;
};
/**
 * Check if there is a link element in the menu item,
 * return the link element if present.
 */
HierListNav.findOnclickTarget = function(e) {
	var el = e.childNodes;		//getElementsByTagName("a");
	for (var i = 0; i < el.length; i++) {
		if (el[i].nodeName == "A") return el[i];	// just in case there is a text node preceding the "A"
	}
	return e;
};

function LHSMenuNav(menuname) {

    var theRef = document.referrer.split("?")[0];
    var theUrl = document.URL.split("?")[0];
    var isSamePage = (theRef == theUrl);
    //alert("Referrer: " + theRef + ", URL: " + theUrl + ", Is the same: " + isSamePage);

    //Reset the menu cookie if returning to this page
    if (!isSamePage) {
        //Clear menu expansion cookie
        CookieHandler.removeCookie("menuVis" + menuname);
    }
	
	if (LHSMenuNav.resetOnMenuChange) {
		var prevMenuName = CookieHandler.getCookie("menuVis_CurrentMenuName");
		if (prevMenuName != menuname) {
			CookieHandler.removeCookie("menuVis" + prevMenuName);
			CookieHandler.setCookie("menuVis_CurrentMenuName", menuname);
		}
	}

	this.name = menuname;
	this.cname = "menuVis" + this.name;
	this.mCount = 0;
	var cvalue = CookieHandler.getCookie(this.cname);
	this.visList = (cvalue == null) ? new Array() : cvalue.split(",");
	
	this.allMenus = new Array();
	
	this.findAll();
	this.hideAll();
	this.setInitialMenus();
	
};

LHSMenuNav.maxMenus = 20;
LHSMenuNav.pageMenu = null;
LHSMenuNav.resetOnMenuChange = true;
LHSMenuNav.topLevelIsClickable = false;

LHSMenuNav.setupMenus = function() {
	var menuName = null;
	// This is now redundant, there is no longer any selector
	try {
		menuName = document.getElementById("RegionSelect").value;
	} catch (e) {
		//alert ("Unable to determine region, using default");
	}
	try {
		menuName = (menuName == null || menuName == "") ? "default" : menuName;
		LHSMenuNav.pageMenu = new LHSMenuNav(menuName);
	} catch (e) {
		alert ("Unable to initialise menus: " + e);
	}
};
LHSMenuNav.cancelBubble = function(evt) {
	if (!evt) evt = window.event;
	evt.cancelBubble = true;
	if (evt.stopPropagation) evt.stopPropagation();
};
LHSMenuNav.prototype = {

	menuShowHide:	function (evt, eId, level) {
		LHSMenuNav.cancelBubble(evt);
		var elem = document.getElementById(eId);
	    if (elem.style.display == "none") {
	        // Open level, make sure all other menus at same level or lower are closed
	        this.visList.length = level;
	        this.visList[level - 1] = eId;
	    } else {
	        // Close level, make sure all other menus at same level or lower are closed
	        this.visList.length = level -1;
	    }
	    // update the page, then update cookie so page re-load works correctly
	    this.hideAll();
	    this.setInitialMenus();
	    CookieHandler.setCookie(this.cname, this.visList.join(","));
	},
	
	findAll:	function () {
	
		for (var i = 1; i <= LHSMenuNav.maxMenus; i++) {
			var elem = document.getElementById("Menu" + i);
			if (elem == null)
				break;			//<<--- Comment this line out if don't have sequentially numbered menus
			else {
				var ulElem = HierListNav.findFirstULWithLI(elem);
				this.findAllSubs(ulElem, LHSMenuNav.topLevelIsClickable, 0);
			}
		}
	},
	
	findAllSubs: function(e, isClickable, level) {
		if (e == null) return;
		var liList = e.childNodes;		//getElementsByTagName("li");	// only want "LI" elements of immediate parent
		for (var i = 0; i < liList.length; i++) {
			if (liList[i].nodeName != "LI") continue;	//only consider "LI" elements
			var liElem = liList[i];
			//Check if LI has sub menu (UL element with one or more LI elements)
			var ulElem = HierListNav.findFirstULWithLI(liElem);
			if (ulElem == null) {
				//Attach an event handler to a UL element
				var clickElem = HierListNav.findOnclickTarget(liElem);
				clickElem.onclick = function(evt) { LHSMenuNav.cancelBubble(evt); };
			} else {
				if (isClickable)
					this.setupNavHandler(liElem, ulElem, level);
					
				this.findAllSubs(ulElem, true, (level + 1));
			}
		}
	},
	
	setupNavHandler: function(liElem, ulElem, level) {
		ulElem.id = this.cname + "_" + (this.mCount++);	//Create a unique id for each menu item with a sub-menu
		this.allMenus[this.allMenus.length] = ulElem;
		var m = this;
		var clickElem = HierListNav.findOnclickTarget(liElem);
		clickElem.onclick = function(evt) { m.menuShowHide(evt, ulElem.id, level); };
	},
	
	setInitialMenus:	function () {
		for (var i = 0; i < this.visList.length; i++) {
			var elem = document.getElementById(this.visList[i]);
			if (elem != null) {
				elem.style.display = "block";
			} else {
				this.visList.splice(i, 1);
				// update the cookie
				CookieHandler.setCookie(this.cname, this.visList.join(","));
			}
		}
	},

	hideAll:	function () {
		for(var i = 0; i < this.allMenus.length; i++)
			this.allMenus[i].style.display = "none";
	}
}
