var delay = 300;
var menu = null;

// Menu Item Data structure
MenuItem = function(ul_id,li_id) {
	// Hold on to LI ID
	this.liID = li_id;
	this.childMenuItems = null;
	
  // If we have a UL (we do) then look through its children
	if ($(ul_id)) {
		this.ulID = ul_id;
		this.childMenuItems = [];
		var childNodes = $(ul_id).childNodes;
		for (index in childNodes) {
			var child = childNodes[index];
			if (child.nodeName == 'LI') {
				// Does this LI have a UL? (-menu)
				if ($(child.id+'-menu')) {
					// Then create and save it as a child item
					var childMenuItem = new MenuItem(child.id+'-menu',child.id);
					this.childMenuItems.push(childMenuItem);          
				}
			}
		}
	}
	
	// Bind our mouse behavior
	if (this.liID) {
		Event.observe(this.liID, 'mouseover', this.Show.bindAsEventListener(this));
		Event.observe(this.liID, 'mouseout', this.StartTimer.bind(this,this.Hide.bind(this)));
	}
};
MenuItem.prototype.timerID = null;
MenuItem.prototype.isOpen = false;
MenuItem.prototype.StartTimer = function(event) { this.timerID = setTimeout(event, delay); };
MenuItem.prototype.StopTimer = function() { clearTimeout(this.timerID); this.timerID = null; };
MenuItem.prototype.Show = function() {
	// Stop the timer, if it's going
	if (this.timerID) { this.StopTimer(); }
	// Are we currently open?
	if (this.isOpen) {
		return; // Then we're done
	}
	// Hide all other menus
	menu.HideAllButThisTree(this);
	// Show ourselves
	$(this.ulID).removeClassName('hide');
	$(this.ulID).addClassName('show');
	$A($(this.ulID).childNodes).each(function(child) { if (child.nodeName == 'A') { Element.addClassName(child, 'hover'); } });
	this.isOpen = true;
}
MenuItem.prototype.Hide = function() {
	if (!this.isOpen) { return; }
	// Hide ourselves
	$(this.ulID).removeClassName('show');
	$(this.ulID).addClassName('hide');
	$A($(this.ulID).childNodes).each(function(child) { if (child.nodeName == 'A') { Element.removeClassName(child, 'hover'); } });
	this.isOpen = false;
}
MenuItem.prototype.HideAllButThisTree = function(protectedMenuItem) {
	for (var index in this.childMenuItems) {
		var child = this.childMenuItems[index];
		if (child.liID == window.undefined || child.liID == protectedMenuItem.liID) { continue; }
		child.HideAllButThisTree(protectedMenuItem);
	}
	this.Hide();
}

// Global functions
function InitMenus(ul_id) {
	menu = new MenuItem(ul_id);
}
