// No conflict with jquery
var $j = jQuery.noConflict();
// JavaScript Document
/**************** init onload */
$j(function(){
	$j('#menu').menu();
});

/*
[ MENU GAUCHE]
*/
(function($j) { 
	$j.fn.menu = function(options){
		var defaults = {
		animate_toggle: 'yes',
		highlight_selected_link: 'yes'
	};

	var opts = $j.extend(defaults, options);
		
	if ( defaults.highlight_selected_link == 'yes' ) {
		if(typeof(force_menu_ouvert) != "undefined"){ 
			var patternUrl = /(\S*)/;
			var urlArray = force_menu_ouvert.match(patternUrl);
			var pathAndPage = urlArray[0];
		}else{
			var pageNameString = location.toString();
			var patternUrl = /(\w+):\/\/([\w.]*)(\S*)/;
			var urlArray = pageNameString.match(patternUrl);
			var pathAndPage = pageNameString;//urlArray[urlArray.length-1];
			//alert(pathAndPage);
		}
		if (pathAndPage) {
			$j("#menu a[href$='"+pathAndPage+"']:first").parent("li").addClass('menu-selected');
		}
	}
	// Change la classe du parent de cette page
	$j(".menu-selected").parent("ul").parent("li").addClass('mg-ouvert');
	
	if(typeof(section_ouverte) != "undefined")
		forceOuvertureSection(section_ouverte).addClass('mg-ouvert');
	
	/* Fait : Enlève l'utilisation de la classe section */
	/* Todo: Remplacer les toogle par des conditions parce que certain menu peuvent être forcé */
	$j("#menu").children("li").children("a").each(function(){
		var $this = $j(this);
		if($this.attr("href") == "#") {
			$this.parent().addClass("section");
			if($this.parent().hasClass('mg-ouvert')) {
				$this.toggle(function(){
					$this.next("ul").slideUp("fast");
					$this.parent().removeClass('mg-ouvert');
				}, function(){
					$this.next("ul").slideDown("fast");
					$this.parent().addClass('mg-ouvert');
				});
			} else {
				$this.toggle(function(){
					$this.next("ul").slideDown("fast");
					$this.parent().addClass('mg-ouvert');
				}, function(){
					$this.next("ul").slideUp("fast");
					$this.parent().removeClass('mg-ouvert');
				});
			}
		}
									   
		$this.next("ul").hide();
	});
	// Ouvre la section  laquel appartient la page courante
	$j(".menu-selected").parent("ul").show();
	
	// Si une ouverture forcée de section est déclaré dans la page
	// Ouvre le menu avec show()
	if(typeof(section_ouverte) != "undefined")
		forceOuvertureSection(section_ouverte).find('ul:first').show();
}
//end of closure
})(jQuery);

function forceOuvertureSection(id) {
	if(/^\d+/.test(id)) {
		id=id-1; // index par a 0 sur les li
		//alert(id);
		return $j('#menu').children('li:eq('+id+')');
	} else if(/s_\w+/.test(id)) {//Si id est un string = id de la section (id="")
		id='#'+id;
		//alert(id);
		return $j('#menu '+id);
	}
}

