var prevMenuId = ""; // used to remember what the current open menu is so it can be reopened to the same position when we navigate to another page

function setInitialMenuPosition(){
	urlParams = window.location.search;

	if (urlParams.substring(1,4) == 'mid'){ // check to see if the mid parameter was passed indicating that you should open the menu to it's previous state
		menuID = urlParams.substring(5); // get the value of the mid variable, i.e. 'menu1'
		toggleClamShellMenu(menuID); // reopen the menu
	}
}

function isSubMenu(objectid){
	var isSubmenu = false;
	var dashPos = objectid.indexOf('-');
	if(dashPos != -1){
		isSubmenu = true; // a submenu was clicked on
	}
	return isSubmenu;
}

function getParentId(objectid){
	var dashPos = objectid.indexOf('-');
	var parentid = objectid.substring(0,dashPos); // the parent menu
	return parentid;
}

function toggleClamShellMenu(objectID) {
	var object = document.getElementById(objectID); // the menu to be opened
	var parentid = objectID; //initialize parent id to current id - will override if it has a true parent
	var prevparentid = prevMenuId;
	
	if(isSubMenu(objectID)){
		var parentid = getParentId(objectID); // the parent menu
	}
	
	//check whether to close the previous menu	
	if(prevMenuId != '' && prevMenuId != parentid && prevMenuId != objectID){
		var prevObject = document.getElementById(prevMenuId); // the menu to be opened
		prevObject.style.display='none'; // close selected menu
		
		//also check whether to close the previous parent menu
		if(isSubMenu(prevMenuId)){
			var prevParentId = getParentId(prevMenuId); // the parent menu
			if(prevParentId != '' && prevParentId != parentid){
				var prevParentObject = document.getElementById(prevParentId); // the menu to be opened
				prevParentObject.style.display='none'; // close selected menu
			}
		}
	}
	
	if (object.style.display =='block'){// close selected menu
		object.style.display='none'; 
		prevMenuId = "";
	}else {//open selected menu
		object.style.display='block';
	
		// if the menu is being dynamically opened rather than by the users clicking, then we need to also be sure to open the parent menu
		if(isSubMenu(objectID)){
			var parentid = getParentId(objectID); // the parent menu
			parentObject = document.getElementById(parentid);
			parentObject.style.display='block';
		}
		
		prevMenuId = objectID; // set the current menu item to the one just opened
	}
	return;
}
	
function go(url){ // redirect to the requested page and tack on the current menuid so we can reopen the menu to it's previous position
	document.location.href = url + "?mid=" + prevMenuId;
	return false;
}

DOMhelp.addEvent(window, 'load', setInitialMenuPosition);
