/**
 * Binds hover actions on the main menu to
 * display links from the category
 */
function bindMenu()
{
    // Categories ans submenus
    var categories = $('#navigation .category');
    if (categories.length == 0)
        categories = $('#navigation li');
    var subMenus = $('#subnavigation ul');
	// Timeout to hide the current menu if any
	var hideTimeout = null;
    // Function to set the visible menu
    function setVisible(activeIndex)
    {
        var index = 0;
        subMenus.each(function()
        {
	        if (index == activeIndex)
            	$(this).slideDown("slow");
            else
				$(this).slideUp("slow");
            index++;
        });
    }
	// Function to get ready to hide the menu
	function setHide()
	{
		if (hideTimeout == null) {
			hideTimeout = setTimeout(function() {
				setVisible(-1);
			}, 500);
		}
	}
	// Function to cancel hiding the menu
	function cancelHide()
	{
		if (hideTimeout != null) {
			clearTimeout(hideTimeout);
			hideTimeout = null;
		}
	}
    // Prepares the categories
    var index = 0;
    categories.each(function()
    {
        var thisIndex = index;
		var item = $(this);
		// Position the submenu
		var subMenu = $(subMenus[index]);
		subMenu.css("left", item.position().left + "px");
		// Menu display event
        item.mouseenter(function()
        {
			cancelHide();
            setVisible(thisIndex);
        });
		// Menu hiding management
        subMenu.mouseenter(function()
        {
			cancelHide();
        });
	    subMenu.mouseleave(function()
	    {
			setHide();
	    });
	    index++;
    });
	// Menu hiding management
    $("#navigation").mouseleave(function()
    {
        setHide();
    });
	$("#navigation").mouseenter(function()
	{
	    cancelHide();
	});
}

$(bindMenu);

