var common = 
{
	
	isFullFlash:false,
	
	init:function(root) 
	{
		common.ready = true;
				
		// comportement des liens
		common.showCounter = 0;
		
		common.initSub(root);
		
		var panel = $("PANEL");
		if (panel) {
			panel.addEvent("mouseover", common.checkSub.bindWithEvent(this,1));
			panel.addEvent("mouseout", common.checkSub.bindWithEvent(this,-1));
		}

		// capture clics pour popups DHML
		var wMask = $("WHITEMASK");
		if(wMask) wMask.addEvent('click', common.clearFrame);
		
		// valeur par défaut dans les formulaires
		$$("input").each(function(item) 
		{
			if (item.getProperty("alt")) {
				if (item.value == "") item.value = item.getProperty("alt");
				item.addEvent("focus", common.fieldFocus);
				item.addEvent("blur", common.fieldBlur);
			}
		});
		$$("textarea").each(function(item) 
		{
			if (item.getProperty("alt")) {
				if (item.value == "") item.value = item.getProperty("alt");
				item.addEvent("focus", common.fieldFocus);
				item.addEvent("blur", common.fieldBlur);
			}
		});

		// ouverture d'un popup au démarrage
		if (common.autoLaunch) common.launchFrame.apply(common, common.autoLaunch);	
		
		//Selection de la couleur du background selon si la page est en fullflash
		
		var allcss = $$("link");
		allcss.each(function(item)
		{
			
			if(item.href.indexOf("fullflash") != -1 ) common.isFullFlash = true;
			
		});
	},
	
	
	/*** MENU NAVIGATION ***/
	initSub:function(root)
	{
	    if (root == undefined) root = document;
		root.getElements("a[rel]").each(function(item)
		{
			if (item.rel.split("|")[0] == "nav") {
				item.addEvent("mouseover", common.tempoSub);
				item.addEvent("mouseout", common.cancelSub);
			}
			else item.addEvent("click", common.handleLink);
		});
	},
	
	tempoSub:function(event)
	{
	    common.menuDisplayed = true;
	    
		event = new Event(event);
		while (event.target && event.target.nodeName != "A") event.target = $(event.target.parentNode);
		common.urlToLoad = event.target.rel.split("|")[1];		
		if (common.currentItem) 
		{
			if (common.hideTimer) clearTimeout(common.hideTimer);
			if (common.showTimer) clearTimeout(common.showTimer);
			common.hideSub();
		}
		common.showCounter = 1;
		common.keepSub(event.target);
	},
	
	cancelSub:function()
	{
	    common.menuDisplayed = false;
		if (common.showTimer) 
		{
			clearTimeout(common.showTimer);
			common.showTimer = 0;
		}
		if (common.currentItem && !common.currentItem.hasClass("over")) common.currentItem = null;
		
		common.showCounter = 0;
		common.showCounter -= 1;
		common.keepSub();
	},
	
	showSub:function()
	{
	    common.showTimer = 0;
		common.currentItem.addClass("over");
		
		var left = common.currentItem.parentNode.offsetLeft;
		if (left == 0) left = 2;
		var offset = $("PERMA").offsetLeft;
		var panel = $("PANEL");
		panel.setStyles({
			display:"block",
			left:offset + Math.min(left, 678-276),
			opacity:0
		});
		if(common.heightEffect) common.heightEffect.stop();
		common.loadNavContent();
		$("PANEL").getElement(".inner").innerHTML = "loading...";
		$("PANEL").getElement(".inner").setStyle("height",25);
		if (common.showEffect) common.showEffect.stop();
		common.showEffect = new Fx.Style(panel, "opacity", {duration:200});
		common.showEffect.start(0, 1);
		
		common.showWhiteMask();
	},
	
	hideSub:function()
	{
	    common.hideTimer = 0;
		if (common.currentItem) 
		{
			common.currentItem.removeClass("over");
			common.currentItem = null;
		}
		if (common.showEffect) common.showEffect.stop();
		$("PANEL").setStyle("display", "none");
		
		if (!common.menuDisplayed && !common.frameDisplayed) common.hideWhiteMask();
	    		
		common.keepSub();
	},
	
	// compteurs pour savoir si le menu deroulant doit être en position ouverte ou fermée
	keepSub:function(target) 
	{
		if (common.hideTimer) clearTimeout(common.hideTimer);
		if (common.showTimer) clearTimeout(common.showTimer);
		
		if (common.showCounter > 0) {
			if (target) {
				common.currentItem = target;
				common.showTimer = setTimeout("common.showSub()", 100);
			}
		}
		else if (common.showCounter <= 0) {
			common.hideTimer = setTimeout("common.hideSub()", 500);
    		common.showCounter = 0;
		}
	},	
	checkSub:function(e,b) 
	{
		common.showCounter += b;
		common.keepSub();
	},
	
	
	/* Chargement des contenus de la NAV */
	
	loadNavContent:function()
	{
	    var navCt = new Ajax(common.urlToLoad, {onComplete : common.navContentLoaded , method: 'get'}).request();
	},
	
	navContentLoaded:function(request)
	{
		var inner = $("PANEL").getElement("div[class=inner]");
		inner.innerHTML = common.extractSourceBody(request);

		var navLoaded = $("NAV");
		if(common.inputs) {
			for(var i = 0; i < common.inputs.length; i++) {
				common.inputs[i].removeEvents();
			}
		}
		// Gestions du focus des champs de textes dans les differents menus
		
		common.inputs = $("NAV").getElements("input");
		if(!common.inputs.length) common.inputs = [common.inputs];
		for(var i = 0; i < common.inputs.length; i++) {
			common.inputs[i].addEvent("focus", common.checkSub.bindWithEvent(this,1));
			common.inputs[i].addEvent("blur", common.checkSub.bindWithEvent(this,-1));
		}
		
		navLoaded.setStyle("visibility","hidden");
		
		common.heightEffect = new Fx.Style(inner, "height", {duration:200,onComplete:common.viewNavContent}).start(inner.getCoordinates().height,navLoaded.getCoordinates().height);
	},
	
	viewNavContent:function() 
	{
		if($("NAV"))$("NAV").setStyle("visibility","visible");
	},
	
	/**
	* Comportement liens :
	* - blank : <a rel="external">
	* - popup : <a rel="popup|width|height|sizeable|scrollable">
	* - popup : <a rel="popup|name|width|height|sizeable|scrollable">
	*/
	handleLink:function(event)
	{
		event = new Event(event);
		if(event) {
			event = new Event(event);
			event.preventDefault();
			while (event.target && event.target.nodeName != "A") event.target = $(event.target.parentNode);
			var href = event.target.href;
			var rel = event.target.rel.split("|");
		}
		
		// fenetre _blank
		if (rel[0] == "external") 
		{
			var win = window.open(href);
			if (win != null) event.preventDefault();
		}
		// fenetre popup
		else if (rel[0] == "popup")
		{
		    var name = "_blank";
			if (isNaN(rel[1])) name = rel.splice(1,1).toString();
			
			var resizable  = (isNaN(rel[3])) ? "1" : rel[3];
			var scrollbars = (isNaN(rel[4])) ? "1" : rel[4];
			var left = (screen.width-parseInt(rel[1])) / 2;
			var top  = (screen.height-parseInt(rel[2])) / 2;
			
			var params = "width="+rel[1]+",height="+rel[2]+",scrollbars="+scrollbars+",resizable="+resizable;
			if (window.gecko) params +",screenx="+left+",screeny="+top;
			params += ",left="+left+",top="+top;
			
			var win = window.open(href, name, params);
			if (win != null) event.preventDefault();
		}
		// layer/iframe
		else if (common.IS_POPUP_ACTION[rel[0]])
		{
		    if (window.top.common) window.top.common.layoutPopup(event.target, rel);
			else common.layoutPopup(event.target, rel);
			event.preventDefault();
		}
		// autre gestionnaire
		else if (common.onRelLink)
		{
			if (common.onRelLink(event.target, rel)) event.preventDefault();
		}
	},
	switchToLink:function(l,t) 
	{
		while (l && l.nodeName != t) l = $(l.parentNode);
		return l;
	},
	
	
	/*** GESTION POPUPS DHTML ***/
	
	IS_POPUP_ACTION: { divpopup:true, framepopup:true, closepopup:true },
	
	layoutPopup:function(item, rel/*Array*/)
	{
		if (rel[0] == "framepopup") 
		{
			common.launchFrame(rel[1],rel[2], item.href);
			return true;
		}
		else if (rel[0] == "divpopup") 
		{
			common.launchFrame(rel[1],rel[2], item.href, true);
			return true;
		}
		else if (rel[0] == "closepopup")
		{
			common.clearFrame();
			return true;	
		}
	},
	
	showWhiteMask:function()
	{
		if(!common.isFullFlash) {
			var content = $("CONTENT");
			var wMask = $("WHITEMASK");
			var footer = $("FOOTER");
			
			wMask.setStyle("display","block");
			var contentCoords = content.getCoordinates();
			contentCoords.left = 0;
			
			// On récupère le top du footer
			// pour déterminer la hauteur que le masque doit avoir
			// pour récouvrir toute la page jusqu'au footer
			var bottom = footer.getCoordinates().bottom;
			contentCoords.top = 0;
			contentCoords.height = bottom;
		
			
		
			wMask.setStyles(contentCoords);
		
			// Opacité du masque
			
			//console.info("document.body "+document.body);
		
			
			document.body.style.background = "#CCCCCC";
			wMask.setOpacity(0.20); // BLACK
			if (window.ie6) $$("select").setStyle("visibility","hidden");
			}
	},
	
	hideWhiteMask:function()
	{
	    var wMask = $("WHITEMASK");
		if(!common.isFullFlash) document.body.style.background = "#ffffff";
		wMask.setStyle("display","none");
		if(window.ie6) $$("select").setStyle("visibility","visible");
	},
	
	launchFrame:function(width, height, link, doAjaxLoad) 
	{
		if (!common.ready)	{
			// mise en attente
			common.autoLaunch = [width, height, link, doAjaxLoad];
			return;
		}
		
		common.frameDisplayed = true;
		
		// parametre indicatif
		link += (link.indexOf('?') > 0) ? "&popup=1" : "?popup=1";
		
		// positionnement popup
		var content = $("CONTENT");
		var contentCoords = content.getCoordinates();
		common.showWhiteMask();
		
		var popup = $("DIVPOPUP");
		// contenu initial
		
		if (doAjaxLoad) popup.innerHTML = "<strong>loading...</strong>";
		else popup.innerHTML = "<iframe src='"+link+"' width='"+width+"' height='"+height+"' "
			+"name='pop"+Math.round(Math.random()*65536)+"' scrolling='no' frameborder='no' "
			+"style='border:none; overflow:hidden' scrollbars></iframe>";
		
		var popupCoords = popup.getCoordinates();
		popup.setStyles({
			width:width+"px",
			height:"35px",
			left:contentCoords.width/2 - width/2,
			display:"block"
		});
		var top = Math.max(Window.getScrollTop()+(Window.getHeight() - height) / 2, 90);
		popup.setStyle("top", top);
		
		if (common.frameEffect) common.frameEffect.stop();
		common.frameHeight = height;
		
		// chargement Ajax ?
		if (doAjaxLoad) var myAjax = new Ajax(link, {onComplete : common.fillPopup , method: 'get'}).request();
		else common.startFrameEffect();
	},
	
	fillPopup:function(request) 
	{
	    var popup = $("DIVPOPUP");
		popup.innerHTML = common.extractSourceBody(request);
		common.init(popup);
		common.startFrameEffect();
	},
	
	startFrameEffect:function()
	{
		common.frameEffect = new Fx.Style("DIVPOPUP", "height", {duration:500});
		common.frameEffect.start(35, common.frameHeight);
	},
	
	clearFrame:function(e)
	{
	    common.frameDisplayed = false;
	    
		if (e) {
			var evt = new Event(e);
			evt.preventDefault();
		}
		
		common.hideWhiteMask();
		
		// cacher le bouton close
		var closep = $$("#DIVPOPUP div.close a")[0];
		if (closep) closep.remove();
		
		// supprimer tous les evenements
		$$("#DIVPOPUP a").each(function(item) {
			item.removeEvents();
		});
		
		if (common.frameEffect) common.frameEffect.stop();
		common.frameEffect = new Fx.Style("DIVPOPUP", "height", {duration:500, onComplete:function() {
			$("DIVPOPUP").setStyle("display","none");
			$("DIVPOPUP").innerHTML = "";
		}});
		common.frameEffect.start(0);
	},
	
	
	/*** VALIDATION DES FORMULAIRES ***/
	
	fieldFocus:function(e)
	{
		var item = $(new Event(e).target);
		if (item.value == item.getProperty("alt")) item.value = "";
	},
	fieldBlur:function(e)
	{
		var item = $(new Event(e).target);
		if (item.value == "") item.value = item.getProperty("alt");
	},
	
	checkForm:function(forms)
	{
		if(!forms.length) forms = [forms];
		// Recuperation de tout les elements
		forms.each(function(formItem) 
		{	
			textInput = formItem.getElements("input[type=text]");
			passInput = formItem.getElements("input[type=password]");
			//checkInput = formItem.getElements("input[type=checkbox]");
			//radioInput = formItem.getElements("input[type=radio]");
			//textArea = formItem.getElements("textarea");
			//selects = formItem.getElements("select");
			
			textInput.each(function(item)
			{
				if(item.hasClass("mandatory")) {
					item.addEvent("focus", common.resetField);
					item.addEvent("blur", common.checkField);
				}
			});
			
			passInput.each(function(item)
			{
				if(item.hasClass("mandatory")) {
					item.addEvent("focus", common.resetField);
					item.addEvent("blur", common.checkField);
				}
			});
		});
		
	},
	
	resetField:function(e)
	{
		var evt = new Event(e);
		var item = evt.target;
		item.removeClass("error");
	},
	checkField:function(e) 
	{
		var evt = new Event(e);
		var item = evt.target;
		item.removeClass("error");
		if (!item.value.length || item.value == item.getProperty("alt")) item.addClass("error");
		else 
		{
			if (item.id == "mail" || item.id == "confirmmail") 
			{
				if (item.id == "mail") common.mail = item;
				var checkMail = /^[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}$/;
				if (checkMail.test(item.value)) 
				{
					if (item.id == "confirmmail") {
						if (!common.mail) item.addClass("error");
						else if (item.value != common.mail.value) item.addClass("error");
					}
				}
				else item.addClass("error");
			} 
			else if(item.id.indexOf("birth") != -1 ) 
			{
				if (!isNaN(parseInt(item.value))) {
					if (item.id.indexOf("day") != -1) {
						if (parseInt(item.id.indexOf("day")) > 31 || parseInt(item.id.indexOf("day")) < 1 ) 
							item.addClass("error");
					}
					
					if (item.id.indexOf("month") != -1) {
						if(parseInt(item.id.indexOf("month")) > 12 || parseInt(item.id.indexOf("month")) < 1 ) 
							item.addClass("error");
					}
					
					if (item.id.indexOf("year") != -1) {
						if(parseInt(item.id.indexOf("year")) > 2000 || parseInt(item.id.indexOf("year")) < 1900 ) 
							item.addClass("error");
					}
				} 
				else item.addClass("error");
			}
		}
		
	},
	
	
	/*** TOOLS ***/
	
	//... Function used for client-side tagging
	tagPage:function(urlPage)
	{
	    if (window.urchinTracker)
	    {
	        urchinTracker(urlPage);
	    }
	    
	    var imgSageMetrics = document.getElementById("imgSageMetrics");
	    if (imgSageMetrics)
	    {
	        var imgSrc = imgSageMetrics.src.split("pg=")[0] + "pg=" + urlPage + "&ai=";
	        imgSageMetrics.src = imgSrc;
	    }
	},
	
	/**
	* Extraire le contenu du <body> d'un source HTML
	*/
	extractSourceBody:function(src)
	{
		var reBody = /<body[^>]*>/i;
		var match = reBody.exec(src);
		if (match == null) return src;
		
		if (src.indexOf("<div id=\"POPUP\">") > 0)
        {
            var start = src.indexOf("<div id=\"POPUP\">");
            var end = src.lastIndexOf("</div>") + 6;
        }
        else if (src.indexOf("<div id=\"NAV\">") > 0)
        {
            var start = src.indexOf("<div id=\"NAV\">");
            var end = src.lastIndexOf("</div>") + 6;
        }
		else
		{
            var start = Math.max(0, src.indexOf(match[0])) + match[0].length;
		    var end = src.toLowerCase().indexOf("</body>");
        }
		
		if (end < start) end = src.length;
		
		return src.substr(start, end-start);
	},
	
	arrWindow:Array(),
	
	openWindow:function(src, name, width, height)
	{
	    var wnd = common.arrWindow[name];
	    
	    //... Close the window if already opened
	    var isClosed = (wnd == null);
	    if ( !isClosed ) isClosed = (wnd.closed);
	    if ( !isClosed ) wnd.close();
	    
	    //... Open a centered window
	    var scrHeight = (screen.availheight ? screen.availheight : screen.height - 20);
	    var scrWidth = (screen.availwidth ? screen.availwidth : screen.width - 10);
	    
	    var top  = (scrHeight - height)/2;
	    var left = (scrWidth - width)/2;
	    
	    common.arrWindow[name] = window.open(src, name, "width="+width+",height="+height+",top="+top+",left="+left+",scrollbars=yes,location=yes,directories=no,status=yes,toolbar=no,resizable=yes");
	    common.arrWindow[name].focus();
	}
}

window.addEvent("domready", common.init);
window.setTimeout("common.init()", 1000);

// appelé par Flash après une opération client/serveur
function cmpnConfirm(cmpnId, siteId, operation, details, uid)
{
	//if (window.console) console.info("Track: cmpn="+cmpnId+", site="+siteId+", op="+operation+", details="+details+", uid="+uid);
}
