/**
 * HORIZONTAL PULLDOWN MENU

 */
// ENCAPSULATION DU SCRIPT
(function() {
// INSTANCE DE GESTION DE CLASSES CSS
/*var css = {
	remove: function(oEl, sClass) {
		var rep = oEl.className.match(' ' + sClass) ? ' ' + sClass : sClass;
		oEl.className = oEl.className.replace(rep, '');
	},
	add: function(oEl, sClass) {
		if(!css.has(oEl, sClass)) oEl.className += oEl.className ? ' ' + sClass : sClass;
	},
	has: function(oEl, sClass) {
		return new RegExp('\\b' + sClass + '\\b').test(oEl.className);
	}
};
*/
// CLASSE MENU
var Menu = function() {};
// PROTOTYPE DE LA CLASSE MENU
var Mp = Menu.prototype = {
	menus: [],
	openEls: [],
	currentUl:null,
	show: 'show',
	active: 'active',
	// IDENTIFIE TOUS LES MENUS AYANT LA CLASSE MP.LABEL ET LES AJOUTE AU TABLEAU MP.MENUS
	identify: function(oMenu) {
		Mp.menus.push(oMenu);
		return Mp;
	},
	// VERIFIE SI UN ELEMENT EST CONTENU DANS UN AUTRE
	contains: function(container, containee) {
		if(!container || !containee) return;
		for(var n = containee; n && n != container; n = n.parentNode);
		return n;
	},
	// INITIALISE UN MENU
	init: function(oMenu) {
		var aLis = $(oMenu).getElements('li'), iLi = aLis.length;
		while(iLi-- > 0) {
			$(aLis[iLi]).removeClass(Mp.show);
			// F6 DEBUG css.remove(aLis[iLi], Mp.show);
		}
		Mp.initThumbs(oMenu);
		
		if ( window.ie ) Mp.ieSize(oMenu);
	},
	// RESIZE LES MENUS POUR IE
	ieSize : function(parent){
		var ancParent = null;
		var width = 0;
		var marges = 42;
		
		parent.getElements("ul").each( function(ul, i){
			if (!ul.hasClass("sub_img")) {
				ul.addClass("invisible");
				width = ul.getCoordinates().width
				ul.setStyle("width", width);

				ul.getChildren().each(function(li,j){
					a = li.getElement('a');
					a.setStyle("width", (width - marges));
				});
				
				(function(){ ul.removeClass("invisible"); }).delay(500);
			}
		});
		
		if( window.ie6 ) {
			parent.getElements("ul").each( function(ul){
				ul.addClass("notVisible");
			});
		}
		
	},
	// AJOUTE DES GESTIONNAIRES D'EVENEMENT SUR CHAQUE MENU
	addBehaviour: function() {
		var iMenu = Mp.menus.length;
		while(iMenu-- > 0) {
			//si pas de menu, je sors -- ajout Flo
			if (!Mp.menus[iMenu]) return;
			
			Mp.init(Mp.menus[iMenu]);
			var aLis = Mp.menus[iMenu].getElements('li'), iLi = aLis.length;
			while(iLi-- > 0) {
				var oLi = aLis[iLi];
				var oA = oLi.getElement('a');
				var oUl = oLi.getElement('ul');
				
				//is SafariMobile
				if (navigator.userAgent.match(/iPad/i) != null || navigator.userAgent.match(/iPhone/i) != null){
					if ( oUl && oLi.hasClass('sub') ) {
						var oSpan = new Element('span', {'class' : 'ipad'});
						oSpan.oLi = oLi;
						oSpan.addEvent('click', function(e){
							new Event(e).stop();
						})
						oLi.adopt(oSpan)
					}
				}
				
				/*
				if(window.attachEvent && oLi.parentNode != Mp.menus[iMenu] && oA.lastChild.nodeValue.length > 23) // Fix IE (grmpf)
					oLi.getElement('img').style.height = '3.4em';
				*/
				
				oLi.addEvents({
					"mouseenter" : function(){
						var oUl = this.getElement("ul");
						
						
						
						if(Mp.currentUl) {
							clearTimeout(Mp.currentUl.timeOut);
							var li = Mp.currentUl.getParent();
							// corrige un effet de cliping lorsqu on sort puis rentre dans le menu
							if(li.getParent() == this.getParent()){
								li.removeClass(Mp.show);
								// css.remove(li.getElement('a'), Mp.active);
								if(window.ie && li.hasClass("sub")) li.removeClass("fixMenu");
							}
							Mp.currentUl = null;
						}
						
						if ( oUl ) {
							if(window.ie6 && oUl.hasClass("notVisible")) oUl.removeClass("notVisible");
							if(oUl.timeOut) clearTimeout(oUl.timeOut);
							if(!this.hasClass(Mp.show)) 
							{
								var parentUl = $(this).getParent();
								var ul = $(this).getElement("ul");
								var lis = ul.getChildren();
								if (lis) {
									/* gestion afficahge des images */
									if (!this.childrenImagesRegistered){
										var _liParentId = this.id;
										if (!!_liParentId){
											//generation images :
											if (ConfigMenu){
												lis.each(function(oLi){
													new Asset.image(ConfigMenu[_liParentId][oLi.id], {
														onload : function(){
															this.injectTop(oLi.getElement('a'));
															oLi.setStyle('background', 'none');
														}
													});
												});
											}
											
										}
										this.childrenImagesRegistered = true;
									}
									
									
													
									lis.setOpacity(0);
									var index = 0;
									var timerSet = null;
								
									if (timerSet)
										$clear(timerSet);
									// Replace le menu en escalier
									if(!Mp.menus.contains(parentUl) && !ul.hasClass("sub_img") ){
										var thisTop = parentUl.getChildren().indexOf(this) * 30;
										oUl.setStyle("top", thisTop - 1);
									}
									timerSet = (function(){
										if(!Mp.openEls.contains(lis[index])) Mp.openEls.push(lis[index]);
                                        if(lis[index]){
                                            lis[index].effect('opacity', {duration: 100}).start(1);
                                        }
										if (index >= lis.length -1) {
											$clear(timerSet);
										
											if(!Mp.menus.contains(parentUl)){
												// si la liste a ouvrir est plus petite que la liste ouverte
												var thisHeight = oUl.getCoordinates().height;
												var parentHeight = parentUl.getCoordinates().height;
												if(parentHeight > thisHeight && thisHeight > 0 && !oUl.getProperty("resized")){
													if(ul.hasClass("sub_img")){
														oUl.setStyle("height", parentHeight);
													}
												}
											}
										}
										index++;
									}).periodical(15, this);
								}
							}
						};
						this.addClass(Mp.show);
						// css.add(this.getElement('a'), Mp.active);
						if(window.ie && this.hasClass("sub")) this.addClass("fixMenu");
					},
					"mouseleave" : function(){
						var currentLi = this;
						var oUl = currentLi.getElement("ul");
						
						var removeClass = function(){
							if(oUl) {
								if(window.ie6 && !oUl.hasClass("notVisible")) oUl.addClass("notVisible");
								$(oUl).getChildren().each(function(li, i){
									if(li) li.setOpacity(0);
									currentLi.removeClass(Mp.show);
									// css.remove(currentLi.getElement('a'), Mp.active);
									if(window.ie && currentLi.hasClass("sub")) currentLi.removeClass("fixMenu");
								});
							} else {
								currentLi.removeClass(Mp.show);
								// css.remove(currentLi.getElement('a'), Mp.active);
								if(window.ie && currentLi.hasClass("sub")) currentLi.addClass("fixMenu");
							}
						}
						
						if(oUl){
							if(oUl.timeOut) clearTimeout(oUl.timeOut);
							oUl.timeOut = setTimeout(removeClass, 400);
							Mp.currentUl = oUl;
						}
						else {
							removeClass();
						}
					}
				});
			}
		}
		return Mp;
	},
	
	initThumbs : function(oMenu){
		var aUls = oMenu.getElements("ul.sub_img"), maxLis = 4;
		aUls.each( function(ul){
			var itemPerCol = [];
			var aLis = ul.getElements("li"), iLi = aLis.length;
			if(iLi > maxLis){
				var nbCols = Math.ceil(iLi / maxLis);
				for(var i = 0; i < nbCols - 1; i++){
					itemPerCol.push(maxLis);
					iLi -= maxLis;
				}
				itemPerCol.push(iLi);
				Mp.cutThumbs(aLis, itemPerCol, ul);
			} else {
				if (aLis && aLis.length > 0)
					aLis[aLis.length - 1].addClass("last");
			}
		});
	},
	
	cutThumbs : function(aLis, itemPerCol, ul){
		var height = 86, width = 170, decal = 4;
		ul.setStyle("width", itemPerCol.length * width);
		itemPerCol.each( function(col, i){
			if (i > 0){
				for(var j = (i*decal); j < (i*decal)+col; j++) {
					var x = i;
					var y = j - (i*decal);
					aLis[j].addClass("cut");
					aLis[j].setStyles({ "left" : width * x, "top"  : height * y});
				}
				var indexLast = 0;
				for (var k = i; k >= 0; k--)
					indexLast += itemPerCol[i-k];
				aLis[(indexLast-1)].addClass("last");
			}
			else aLis[itemPerCol[i]-1].addClass("last");
		});
	}
};

var setMenu = function(){
	// VERIFICATION DE LA PRESENCE DE CSS
	var oNewDiv = document.createElement('div');
	document.body.appendChild(oNewDiv);
	oNewDiv.style.visibility = 'hidden';
	oNewDiv.style.width = '20px';
	oNewDiv.style.padding = '10px';
	if(oNewDiv.offsetWidth != 40) {
		document.body.removeChild(oNewDiv);
		return $(document.documentElement).removeClass('hasJS');
	}
	document.body.removeChild(oNewDiv);
	// CHARGEMENT DU MENU
	var oMenu = document.getElementById('menu');
	return new Menu().identify(oMenu).addBehaviour();
}


function cancelClick(e) {
	if(e && e.stopPropagation && e.preventDefault) {
		e.stopPropagation();
		e.preventDefault();
	}
	else if(e && window.event) {
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	return false;
}
window.addEvent('load', function () {
	setMenu()
})


})();



