var OpenMenu = new Array();
var OpenMenuTimer = new Array();
var CloseMenuTimer = new Array();
function HookMenu(id) 
{
	var menuID = "#" + id;
	var ct = 0;
	OpenMenu[menuID] = null;
	OpenMenuTimer[menuID] = null;
	CloseMenuTimer[menuID] = null;
	
	jQuery(menuID).children("li").each(function(){ jQuery(this).attr("id", menuID + ct++); });

	// ========================================================
	// == Menu Opening ========================================
	// ========================================================
	jQuery(menuID).children("li").mouseover(function(ev){
		var delay = 200;
		var submenu = jQuery(this).find("ul");
		
		// Cancel the opening of other menus
		clearTimeout(OpenMenuTimer[menuID]);
		clearTimeout(CloseMenuTimer[menuID]);
		
		// Schedule the opening of this menu
		OpenMenuTimer[menuID] = setTimeout(function() { 
			submenu.prev().addClass("selected");
			HideOtherMenus(submenu);
			ShowMenu(submenu); 
		}, delay);
	});
	
	// ========================================================
	// == Menu Closing ========================================
	// ========================================================
	jQuery(menuID).children("li").mouseout(function(){
		clearTimeout(OpenMenuTimer[menuID]);
		// The menu will close after a half second delay
		var submenu = jQuery(this).find("ul");
		CloseMenuTimer[menuID] = setTimeout(function() { 
			HideOtherMenus(submenu);
			submenu.prev().removeClass("selected");
			submenu.hide();
			OpenMenu[menuID] = null;
		}, 200);
	});
	
	function ShowMenu(menu)
	{
		OpenMenu[menuID] = menu.attr("id");
		if(menu.css("display") == "none")
			menu.slideDown(150, function() { HideOtherMenus(menu); });
	}
	function HideOtherMenus(menuToNotHide)
	{	
		jQuery(menuID + " ul").not(menuToNotHide).hide().prev().removeClass("selected");
		if(menuToNotHide.length > 0)
			OpenMenu[menuID] = menuToNotHide.attr("id");
	}
	
	// ========================================================
	// == Menu Navigation =====================================
	// ========================================================
	jQuery(menuID + " li").click(function(){
		// the entire box should be clickable if there is a link within.
		var link = jQuery(this).children("a");
		if(link.length > 0)
		{
			var url		= link.attr("href");
			var target	= link.attr("target");
			
			if(target == "")
				location.href = url;
			else window.open(url, target);
		}
		
		return false;
	});
}
