﻿var AccordionMenu = new Object();

AccordionMenu.persistedElements = new Object();

AccordionMenu.init = function(menuId, shouldPersistState, durationDays) {
    var durationDays = (typeof(persistDays) == 'undefined') ? 0 : parseInt(persistDays);

    if(typeof(AccordionMenu.persistedElements[menuId]) == 'undefined') {
		if(shouldPersistState == true) {
			// Load menu state from persistent medium.
			AccordionMenu.persistedElements[menuId] = AccordionMenu.loadState(menuId);
		}
	}

    var index = 0;

    // Initialize all UL's before we continue.
    $('ul.' + menuId + ' ul').each(function() {
        // TODO: Denna metod skall sätta RÄTT state baserat på cookie-settings.
        var e = $(this);

        var forceOpen = false;
        if(shouldPersistState == true) {
            if(AccordionMenu.searchArray(AccordionMenu.persistedElements[menuId], index) == true) {
                forceOpen = true;
            }
        }
        
        index += 1;

        if(forceOpen == true || e.attr("rel") == "open") {
            e.show();
            e.prev().addClass("OpenMenuItem");
            e.parent().addClass("OpenSubMenu");
            e.attr("rel", "open");
        } else {
            e.hide();
            e.prev().addClass("ClosedMenuItem");
            e.parent().addClass("ClosedSubMenu");
            e.attr("rel", "closed");
        }
    });
	
	// TODO: Här (efter ovanstående anrop, ja - ute i init-metod) skall man spara staten om det är Opera.
	
	// React to clicks on any LI A-tag in the menu.
	$('ul.' + menuId + ' li a').click(
		function() {
		    // Get the element directly after the A-tag that was clicked.
		    // If a submenu exists this will be an UL.
		    var aElement = $(this); // The current A-tag.
			var ulElement = aElement.next(); // The UL element following the current A-tag.
			//var parentId = this.parentNode.parentNode.id; // The parenting UL-tag id (above the LI-tag).
			//var parentULElement = $('#' + parentId); // The UL-tag (above the LI-tag).

            // TODO: Denna meny klarar bara av en 1 djup meny eftersom man ref. till parent-elementet.
            // Bättre hade varit att ha en root-UL som man hämtade istället för att hämta parent.
		    var liElement = aElement.parent();

		    if(ulElement.attr("rel") == "closed") {
                aElement.removeClass("ClosedMenuItem");
                liElement.removeClass("ClosedSubMenu");
                aElement.addClass("OpenMenuItem");
                liElement.addClass("OpenSubMenu");
		    }

			ulElement.slideToggle('normal', function() {
			    var ulElement = $(this);
			    var aElement = ulElement.prev();
			    var liElement = ulElement.parent();
			    
			    if(ulElement.attr("rel") == "closed") {
			        ulElement.attr("rel", "open");
			    } else {
                    aElement.removeClass("OpenMenuItem");
                    liElement.removeClass("OpenSubMenu");
                    aElement.addClass("ClosedMenuItem");
                    liElement.addClass("ClosedSubMenu");				    
			        ulElement.attr("rel", "closed");
			    }
			});
			
			if(shouldPersistState == true) {
    		    if(window.opera) {
	    	        AccordionMenu.saveState(menuId, durationDays);
		        }
		    }
			
			//return false;

/*
			if(ulElement.is('ul') && ulElement.is(':visible')) {
				if(parentULElement.hasClass('collapsible')) {
				    $('#' + parentId + ' ul:visible').slideUp('normal');
				}
				return false;
			}
			
			if(ulElement.is('ul') && !ulElement.is(':visible')) {
				$('#' + parentId + ' ul:visible').slideUp('normal');
				ulElement.slideDown('normal');
				return false;
			}
*/			
		}
	);
	
	if(shouldPersistState == true) {
        if(!window.opera) {
			// Save opened element indexes on window.onunload.
			Events.attachEventListener(window, 'unload', function() {
				AccordionMenu.saveState(menuId, durationDays);
			});
		}
	}
};

AccordionMenu.searchArray = function(a, value) { // Searches an array for the entered value. If found, delete value from array.
	for(var i=0; i<a.length; i++) {
		if(a[i] == value) {
			if(a.shift) a.shift(); // Delete this element from array for efficiency sake if supported.
			return true;
		}
	}
	
	return false;
};

AccordionMenu.clearState = function(menuId) {
    Cookie.deleteCookie(menuId);
};

AccordionMenu.loadState = function(menuId) {
	var cookieContent = Cookie.getCookie(menuId);
	if(cookieContent == '') return '';
	return cookieContent.split(',');
};

AccordionMenu.saveState = function(menuId, durationDays) { // Store index of opened ULs relative to other ULs in Tree into cookie.
	var openElementsList = '';
	var i = 0;
	$('ul.' + menuId + ' ul').each(function() {
	    if($(this).attr("rel") == "open") {
			// Save the index of the opened UL.
			if(openElementsList != '') openElementsList += ',';
			openElementsList += i;
	    }
	    i += 1;
	});
		
	// Are there any opened ULs to save/persist.
	// Set array value to string to simply indicate all ULs should persist with state being closed.
	if(openElementsList != '') {
		// Populate cookie with the name menuId with value 1,2,3 etc (where 1,2... are the indexes of the opened ULs).
		if(durationDays > 0) {
	        Cookie.setCookie(menuId, openElementsList, durationDays);
	    } else {
	        Cookie.setSessionCookie(menuId, openElementsList);
	    }
    } else {
        Cookie.deleteCookie(menuId);
	}
};

//$(document).ready(function() { AccordionMenu.init("CatalogMenu", true); });
