/*
	$.fn.accordianMenu
	@param	menu		string			élément constituant un menu
	@param	button		string			élément constituant un bouton
	@param	hideOn		string/array	évènement(s) invoquant la fermeture d'un menu
	@param	showOn		string/array	évènement(s) invoquant l'ouverture d'un sous menu
	@param	activeClass	string			class ajouté aux boutons ayant un sous menu
	@param	openedClass	string			class ajouté aux boutons ayant un sous menu ouvert
*/
(function($) {
	$.fn.accordianMenu = function(options) {
		//	Récupération des paramètres
		var opt 		=	$.extend({}, $.fn.accordianMenu.defaults, options);
		var	menu		=	this;
		var	opened		=	0;
		
		//	Traitement des paramètres
		if(!$.isArray(opt.showOn)){
			opt.showOn	=	new Array(opt.showOn);
		}
		if(!$.isArray(opt.hideOn)){
			opt.hideOn	=	new Array(opt.hideOn);
		}
		
		//	Application du plugin
		var output	=	this.each(function(){
			bindShow($(opt.button, this));
			if(opt.activeClass){
				$(opt.menu, this).parent('li').addClass(opt.activeClass);
			}
		});
		
		if(opt.autoShow){
			$(this).children(opt.button+opt.autoShow).click();
		}
		
		return output;
		
		//	Plugin Methods
		function openSubLevel() {
			var brothers	=	$(this).parent(opt.menu).children(opt.button).not(this);
			var	current		=	$(this);
			
			showSubLevel(this);
			$(brothers).each(function(){
				hideSubLevel(this);
			});
			/*$(brothers).each(function(){
				if($(this).get(0) != $(current).get(0)){
					hideSubLevel(this);
				}else{
					showSubLevel(this);
				}
			});*/
			return false;
		}		
		function closeSubLevel() {
			hideSubLevel(this);
			return false;
		}
		
		function showSubLevel(o)
		{
			if($(o).children(opt.menu + ':hidden').length){
				//	Add openedClass to the button
				if(opt.openedClass){
					$(o).addClass(opt.openedClass);
				}
				//	Show direct children
				$(o).children(opt.menu + ':hidden').slideDown();
				bindHide(o);
				opened++;
			}
		}		
		function hideSubLevel(o)
		{
			//alert(opened);
			if(opened > opt.keepOpened && $(opt.menu + ':visible', o).length){
				//	Remove openedClass to the button
				if(opt.openedClass && $(o).hasClass(opt.openedClass)){
					$(o).removeClass(opt.openedClass);
				}
				//	Hide direct and indirect children
				$(opt.menu + ':visible', o).slideUp();
				bindShow(o);
				bindShow($(opt.button, o));
				opened--;
			}
		}
		
		function bindShow(o)
		{
			for(var i = 0; i < opt.showOn.length; i++){
				$(o).unbind(opt.showOn[i], closeSubLevel)
					.bind(opt.showOn[i], openSubLevel);
			}
		}		
		function bindHide(o)
		{
			for(var i = 0; i < opt.hideOn.length; i++){
				$(o).unbind(opt.hideOn[i], openSubLevel)
					.bind(opt.hideOn[i], closeSubLevel);
			}
		}
	};
	$.fn.accordianMenu.defaults = {
		menu:			'ul',
		button:			'li',
		hideOn:			['mouseleave'],
		showOn:			['mouseenter'],
		activeClass:	'hasChild',
		openedClass:	'opened',
		keepOpened:		0,
		autoShow:		false
	};
})(jQuery);