/** Requires Mochikit 1.4 or later **/
// create the dropdown namespace
var dropdown = {};

dropdown.TIMEOUT = 0.500;
dropdown.FADE_SPEED = 0.400;
dropdown.current_menu = null;
dropdown.current_timer = null;


/**
 * Event handler for opening a menu.
 */
dropdown.menu_open = function(e){
	
	// cancel the current deferred
	dropdown.cancel_timer(null);
	
	var parent = getFirstParentByTagAndClassName(e.target(), "li", null);
	var target = getFirstElementByTagAndClassName("div", null, parent);
	// hide the current open menu
	if(dropdown.current_menu && dropdown.current_menu != target){
		hideElement(dropdown.current_menu);
	}
	
	if(target != null){
		dropdown.current_menu = target;
		if(dropdown.current_menu) appear(dropdown.current_menu, {duration:dropdown.FADE_SPEED, queue:"parallel"});
	}
}

/**
 * Event handler for hiding a menu.
 */
dropdown.menu_hide = function(e){
	if(dropdown.current_menu != null) fade(dropdown.current_menu, {duration:dropdown.FADE_SPEED, queue:"parallel"});
	dropdown.current_menu = null;
}

/**
 * Event handler for starting the timer before hiding the menu.
 */
dropdown.start_timer = function(e){
	dropdown.current_timer = callLater(dropdown.TIMEOUT, dropdown.menu_hide);
}

/**
 * Event handler for cancelling the timer.
 */
dropdown.cancel_timer = function(e){
	if(dropdown.current_timer){
		dropdown.current_timer.cancel()
		dropdown.current_timer = null;
	}	
}

addLoadEvent(function(){
	// This is the magic... any unordered list with class dropdown_menu.
	var menus = getElementsByTagAndClassName("ul", "dropdown_menu");
	map(function(menu){
		var listitems = getElementsByTagAndClassName("li", null, menu);
		map(function(listitem){
			// connect the signals and handlers
			var anchor = getFirstElementByTagAndClassName("a", null, listitem);
			if(anchor){
				connect(anchor, "onmouseover", dropdown.menu_open);
				connect(anchor, "onmouseout", dropdown.start_timer);
			}
			var div = getFirstElementByTagAndClassName("div", null, listitem);
			if(div){
				connect(div, "onmouseover", dropdown.cancel_timer);
				connect(div, "onmouseout", dropdown.start_timer);
			}
		}, listitems);
	}, menus);
	
	connect(currentDocument(), 'onclick', function(e){ hideElement(dropdown.current_menu); dropdown.current_menu =null;});
});
