var currentUL = new Array();
var currentLI = null;
var currentAncestors = new Array();

function dirty(evt) {
	var elt = Event.findElement(evt,"LI");
 	clearTimeout(timeoutID);
	if (elt == document) return;
	var ancestorsArray = elt.ancestors();
	clearHere();
	// unhighlight the current li
	if ((currentLI != null) && (currentLI != elt)) {
		clearPath(currentLI);
		currentLI.removeClassName('here');
		currentLI = elt;
	}
	// highlight this one
	markPath(elt);
	elt.addClassName('here');
	var childLists = elt.getElementsByTagName("UL");
	var newUL = (childLists.length > 0) ? $(childLists[0]) : null;
	if (newUL != null) ancestorsArray.push(newUL);

	var cleared = false;
	while ((currentUL.length >0) && (! cleared)) {
		if (ancestorsArray.indexOf(currentUL.last()) < 0)  { // this UL should not be visible
			currentUL.pop().hide();
		} else {
			cleared = true;
		}
	}
	if (newUL != null)  {
		newUL.show();
		currentUL.push(newUL);
	}
	currentLI = elt;

}

function markPath(currentChild) {
	var pathToHere = currentChild.ancestors();
	pathToHere.push(currentChild); // comment this
	pathToHere.each(function(n) {
		n = $(n);
		if (n.tagName == "LI") n.addClassName('path');
	});
}
function clearPath(currentChild) {
	var pathToHere = currentChild.ancestors();
	pathToHere.push(currentChild); // comment this if needed
	pathToHere.each(function(n) {
		n = $(n);
		if (n.tagName == "LI") n.removeClassName('path');
	});
}


function hideSubLists(ul) {
	if (ul == null) return;
	var items = $A(ul.getElementsByTagName("LI"));
	items.each(function(li) {
		li = $(li);
		var childLists = $A(li.getElementsByTagName("UL"));
		childLists.each(function(ulc) {
			ulc = $(ulc);
			ulc.hide();
			hideSubLists(ulc);
		});
	});
	if (currentLI != null) { 
		currentLI.removeClassName('here');
		clearPath(currentLI);
		currentLI = null;
	}
	
}

var timeoutID = null;

function delayHideMenus() {
	clearTimeout(timeoutID);
	timeoutID = setTimeout( "hideSubLists(navUL);showHere();", 500); // milliseconds
	
}


function showHere() {
	// assume that all ULs have been hidden
	currentUL = new Array();
	pathHere.each(function(n) {
		n = $(n);
		if (n.tagName == "LI") n.addClassName('here');
		if (n.tagName == "UL") {
			currentUL.push(n); // capture any lists we make visible
			n.show();
		}
	});
	currentUL.shift() // remove the first element (it's the UL#nav)
}
function clearHere() {
	pathHere.each(function(n) {
		n = $(n);
		if (n.tagName == "LI") n.removeClassName('here');
	});
}

var pathHere = new Array();
// only need do this once per page
function findHere() {
	var here = $('here');
	pathHere = here.ancestors();
	pathHere.push(here); // make sure 'here' is also here.
	pathHere = $A(pathHere);
	pathHere = pathHere.reverse();
}

var navUL;
function navSetup() {
	navUL = $("nav"); // change the id of nav_panel if necessary.
	hideSubLists(navUL);
	Event.observe(navUL,'mouseover',dirty);
	navUL.style.visibility = "visible";
	findHere(); showHere();
}
