$(document).ready(function(){
	init();
	$('.firstChild').click(function (){
		$(this).toggleClass('aperto');
		$('.secondLevel').filter('#'+$(this).attr('id')+'').slideToggle('slow');
		$('.secondLevel').filter('#'+$(this).attr('id')+'').toggleClass('aperto');
		$(this).removeAttr('style');
	});
	$('.secondChild').click(function (){
		$('.thirdLevel').filter('#'+$(this).attr('id')+'').slideToggle('slow');
		$('.thirdLevel').filter('#'+$(this).attr('id')+'').toggleClass('aperto');
	});

});

// inizializza il menu
function init() {
	$('.secondLevel').css('display', 'none');
	$('.thirdLevel').css('display', 'none');
	var string = document.location.href;
	traccia = gup('aperti');
	
	livelli = traccia.split('_');
	
	
	if (traccia != '') {
		if(livelli[0] !='') {
			var arrauSec = livelli[0].split(',');
			for( var i=0; i<arrauSec.length; i++) {
				$('.secondLevel').filter('#'+arrauSec[i]+'').css('display','block');
				$('.secondLevel').filter('#'+arrauSec[i]+'').toggleClass('aperto');
				$('.firstChild').filter('#'+arrauSec[i]+'').toggleClass('aperto');
			}
		}
		if (livelli[1] !='') {
			var arrauTrd = livelli[1].split(',');
			for( var i=0; i<arrauTrd.length; i++) {
				$('.thirdLevel').filter('#'+arrauTrd[i]+'').css('display','block');
				$('.thirdLevel').filter('#'+arrauTrd[i]+'').toggleClass('aperto');
			}
		}
	}
}

// colleziona voci di menu aperte e link con parametro
function collect(targ) {
	var apSec = new Array()
	$('.secondLevel').filter('.aperto').each(function(){
		apSec.push($(this).filter('.aperto').attr('id'))
	});
	var apTrd = new Array()
	$('.thirdLevel').filter('.aperto').each(function(){
		apTrd.push($(this).filter('.aperto').attr('id'))
	});
	//window.location.href = ''+targ+'&aperti='+apSec+'_'+apTrd+'';
	window.location.href = ''+targ+'';
}

// ottieni voci di menu aperte dall'url
function gup( name ) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
}

// gestione eventi over & out
$(document).ready(function() {
	var era_aperto;
$('.firstLevel > li, .secondLevel > li').hover(function() {
	$(this).toggleClass('hover_item');
	if($(this).hasClass('aperto')) {
		$(this).toggleClass('aperto');
		era_aperto = 1;
		$(this).css('font-weight','bold');
	}else{
		era_aperto = 0;
	}
},
function() {
	$(this).toggleClass('hover_item');
	if(era_aperto == 1) {
		$(this).toggleClass('aperto');
		era_aperto = 0;
	}
});
});

