// Checks to see whether the page URL matches the URL for any of the lefthand menu items
function checkMenu(pageUrl) {
	// Get all link elements in the lefthand menu
	var menulinks = document.getElementById("primaryMenu");
	menulinks = menulinks.getElementsByTagName("ul")[0];
	menulinks = menulinks.getElementsByTagName("a");
	
	showSubs(menulinks);
	
	// Go through all the menu links and check to see if they match the page name
	for (var i = 0; i < menulinks.length; i++) {
		if (menulinks[i].href == pageUrl) {			// The page matches a page in the menu
			var thismenu = menulinks[i].parentNode;
			var submenu = null;
			
			// Get submenu, if applicable
			if (menulinks[i].parentNode.lastChild.tagName == "UL") {
				submenu = menulinks[i].parentNode.lastChild;
			}
			
			// Call menu expansion function, pass thismenu and submenu variables
			expandMenu(thismenu, submenu);
		}
	}
}

function expandMenu(thismenu, submenu) {
	// First, show the submenu (if there is any)
	if (submenu) {
		submenu.style.display = "block";
	}
	
	// Second, if there are levels of menus above the current item that are not expanded, expand them now
	if (thismenu.parentNode.tagName == "UL") {
		thismenu.parentNode.style.display = "block";
	}
	if (thismenu.parentNode.parentNode.parentNode.tagName == "UL") {
		thismenu.parentNode.parentNode.parentNode.style.display = "block";
	}
	if (thismenu.parentNode.parentNode.parentNode.parentNode.parentNode.tagName == "UL") {
		thismenu.parentNode.parentNode.parentNode.parentNode.parentNode.style.display = "block";
	}
	
	highlightCurrent(thismenu);	
}

// Adds a class to the menu items that have submenus associated with them
function showSubs(menu) {	
	for (var i = 0; i < menu.length; i++) {
		var inMenu = menu[i].parentNode.innerHTML.indexOf("<ul>");
		if (inMenu != "-1") {
			menu[i].parentNode.className = "subMenu";
		}
	}
}

// Adds the class "current" to the currently selected page
function highlightCurrent(thismenu) {
	thismenu.firstChild.className = "current";
}

window.onload = function () {
	var pageUrl = this.location;		// Gets page URL
	checkMenu(pageUrl);			// Calls menu checker function
}

