//Contains an array, with for each menu a boolean indicating true if the menu is
// shown, otherwise false
var menuSettings = new Array();

// The css class that a menu is that should be collaseable
var menuClass = ".collapse_menu_header";

$(document).ready(function(){

	// Load the existing menu settings	
    loadMenuSettings();
   
    // When a linkheader is clicked, save the settings and toggle the show/hide status
    $(menuClass).click(function(){
		// The menu is the next div after the header
    	$(this).next().slideToggle("slow");
        var menuItem = $(menuClass).index(this);
    	//Update menu settings array, and save it
        menuSettings[menuItem] = !menuSettings[menuItem];
		saveMenuSettings();
    });
});

// Save the menu settings to a cookie as comma separated booleans
function saveMenuSettings()
{
	$.cookie('menusettings', menuSettings.join(","));
}

// Load the settings, if no settings exists, or the number of menus is different from the 
// amount in the cookie, we reset the settings and save them
function loadMenuSettings()
{
	// The values are stored as strings, later we convert them to boolean to allow easier handling
	var menuSettingsString = ($.cookie('menusettings') || "").split(",");
	var numberOfMenus = $(menuClass).size();
	
	if (menuSettingsString.length != numberOfMenus)
	{
		// No valid cookie, so open all menus
		//alert("Different size: " + menuSettingsStirng.length);
		menuSettings = fillArray(numberOfMenus, true);
	}
	else
	{
		// We found a valid cookie, so load it 
		// Convert the array of strings to bool and
		// go over the array and hide the menus

		menuSettings = new Array(numberOfMenus);
		
		for ( var i in menuSettingsString )
		{
			// Convert to boolean, invalid values are treated as true (= show menu)
			menuSettings[i] = (menuSettingsString[i] == "false") ?  false : true;
		    if (!menuSettings[i])
		    {
				// Hide the menu, this is always the next div after the header
				$(menuClass).eq(i).next().hide();
			}
		} 
	}
}

//returns an array with the given size and each field at the default value
function fillArray(size, defaultvalue)
{
	var array = new Array(size);
	for (var i = 0; i < size; ++i)
	{
		array[i] = defaultvalue;
	}
	return array;
}