/**
 * Takes the URL and an unordered list menu and will highlight the current page
 * 
 * The function menuHighlight will take an element containing a list of links
 * and the pathname of the current page. The pathname is split along the forward
 * slash and placed into an array. Depending on the level indicated (0 being a
 * root level menu, 1 being a submenu, 2 being a submenu of the submenu, etc. ),
 * the function will attempt to match up certain parts of the pathname with the 
 * href attribute of a link in the list. Upon a successful match, the anchor 
 * element adds the class "current" to allow for styling. NOT FOR USE WITH A
 * NESTED SUBMENU DESIGN (e.g. http://www.jewishculture.uiuc.edu)
 * 
 * @author          Applied Technology for Learning in the Arts and Sciences (ATLAS)
 * @param   menu    Id of the 'div' element containing the linked list.
 * @param   level   Level of traversal for the menu
 * @return          void
 */  

function menuHighlight(menu,level){
	if (!document.getElementsByTagName) return;	
	var mainMenu = document.getElementById(menu);
	var navTwo = document.getElementById("nav2");
	var headerOne = document.getElementsByTagName("h1");
	// if the element exists, extract the list items for the list
  
  if(document.getElementById(menu)){
		var menuItems = mainMenu.getElementsByTagName("li");
		
	//obtain the pathname (e.g. "/contact/things/index.html") and the domain 
    //(e.g  http://example.com) from the page
		
    var pathName = window.location.pathname.toString().split("/");
	var hostName = window.location.hostname.toString();
		
	//remove any filename that may end up at the end of the pathName
	
	var pathNameLength = pathName.length;
	if((pathName[pathNameLength -1].indexOf("."))!= -1) {
		pathName[pathNameLength -1] = "";	
	}
	
	// loop through all the menu items to find the corresponding one

    for (var i=0; i<menuItems.length; i++) {
			var menuItem = menuItems[i];
			var anchors = menuItem.getElementsByTagName("a");
			var anchoref = anchors[0].href.toString().split("/");
			if (anchoref[2] == hostName) {
				var success = true;
				
				for (var j = 0; j<(level +1); j++) {
					if (anchoref[j + 3] == pathName[j +1]){
						if(level == 0) {
							var section = "section-" + anchoref[j+3];
							navTwo.className = navTwo.className + " " + section;
						}
					}
					else {success = false;}
					
					if (anchoref[j + 3] == pathName[j +1] && anchoref[j + 2] == pathName[j + 0]){
						if(level == 1) {
							headerOne[0].className = headerOne[0].className + " " + "subsection-" + (i % 6);
						}
					}
					else {success = false;}
				}
				
				//Adds the class to the proper page anchor
				
				if(success == true) {
					anchors[0].className = "current";
				}
			}
		}
	}
}

//Executes the function when the document is loaded
$(document).ready(function(){
	menuHighlight('nav',0);
	menuHighlight('subnav',1);
});
