/*
	fncSetState - Set the State for a given LI
*/
function fncSetState()
{
	// References
	var sLIid = jQuery(this).attr('class').split(' ')[1];
	
	// Get the cookie for a given element (LI)
	var sCookie = jQuery.cookie(sLIid);

    // If the LI has children menus...
    if(jQuery('.' + sLIid + ' > ul').length)
    {    
	    // Open only the neccesary submenus (Default state: all closed)
	    if(sCookie == 'open')
	    {
		    jQuery('.' + sLIid + ' > ul').show();
		    jQuery(this).children('.panel').removeClass("collapsed").addClass("expanded");
            
	    }else if (sCookie == 'close'){
		    jQuery(this).children('.panel').removeClass("expanded").addClass("collapsed");
	    }
    // If the LI has NO children, leave the DIV (panel) without the state class (=> without icon)
    }else{
        jQuery(this).children('.panel').removeClass("expanded").removeClass("collapsed");
    }
}


/*
	fncDivClick - Manages the click events on every DIV bar
*/
function fncDivClick()
{
    if(onTransition)
    {
        return false;
    }else{
        // Start Transition
        onTransition = true;
        
	    // References
	    var tagULsubmenu = jQuery(this).next();
	    var tagULparent = jQuery(this).parent().parent();
	    var sLIparentID = jQuery(this).parent().attr('class').split(' ')[1];
        //alert("tagULsubmenu = " + tagULsubmenu.attr('class'));

	    // If the MENU has a SubMenu
	    if(tagULsubmenu.attr('class'))
	    {
		    // Set the cookie for the submenu; update the State Icon
		    if(tagULsubmenu.is(':visible'))
		    {
			    jQuery.cookie(sLIparentID, 'closed', {path: '/'});
			    jQuery(this).removeClass("expanded").addClass("collapsed");
		    }else{
			    jQuery.cookie(sLIparentID, 'open', {path: '/'});
			    jQuery(this).removeClass("collapsed").addClass("expanded");
		    }
		    
		    // Toggle the submenu
		    tagULsubmenu.slideToggle('fast', function(){onTransition = false;});
		    return false;
	    }
    }
}


/* 
	fncSetupMenus - Turns a group of UL - LI (a) levels into an Accordion Widget
*/
function fncSetupMenus()
{
	// SET INITIAL STATE: Hide every UL-child list for every MENU in the page; updates the State Icon
	jQuery('ul.menu > li > ul').hide().prev().removeClass("expanded").addClass("collapsed");

	// SET FINAL STATE: Set the state for every MENU in the page
	jQuery.each(jQuery('ul.menu > li'), fncSetState);

	// Handle the events
	jQuery('ul.menu > li > div').click(fncDivClick);
}

// Flag to know if Menu it's on transition
var onTransition = false;

// Once the DOM is loaded Setup the Menus
jQuery(document).ready(fncSetupMenus);

