/***********************************
* Main, l'application se trouve ICI
***********************************/

function addHover(elm, iframeTag) {
	elm.style.behavior = " "; //reecriture du style behavior
	elm.hoverClassName = "hover";
	if (iframeTag) {
		elm.iframeElm = getNode(elm, iframeTag);
		alert(elm.iframeElm)
	}
	elm.onmouseenter = function() {
	   this.className+= ' ' + this.hoverClassName;
	   if (this.iframeElm) {
		   ifrlayer.make(this.iframeElm);
	   }
	};
	elm.onmouseleave = function() {
	   this.className = this.className.replace(new RegExp("\\b" + this.hoverClassName + "\\b", "g"), "");
	   if (this.iframeElm) {
		   ifrlayer.hide(this.iframeElm);
	   }
	};
}

////////// FIX PNG UNDER IE6 //////////

function pngFix(elm, noOverflow) {
	elm.style.filter = ' ';
	if (!(document.all && window.print && /MSIE [56]/.test(navigator.userAgent))) return;
	var exec = (function(elm, noOverflow, scale) {
		return function() {


			var options = { noOverflow:noOverflow};
			var repeat = elm.currentStyle.backgroundRepeat.toLowerCase()=='repeat';
			elm.style.filter = ' ';
				// si l'Ã©lÃ©ment est un tag img, on va en faire creer une balise qui encadrera cette image et ensuite traiter la balise comme si c'etait un Ã©lÃ©ment qui avait une image de fond
				if (elm.nodeName.match(/^(IMG|INPUT)$/)) {
					if (!elm.src.match(/.*\.png$/)) return;

					elm.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='image', src='"+ elm.src + "')";

					elm.width = elm.offsetWidth;
					elm.height = elm.offsetHeight;

					/* recuperation de l'url du pixel transparent */
					var url = elm.currentStyle.backgroundImage.match(/^url\(["'](.*\.gif)["']\)$/); //seulement les .png
					elm.src = url[1];
					elm.className = elm.className.replace(/pngFix/g,'');

				}
				else {
					if (elm.currentStyle.backgroundImage == "" || elm.currentStyle.backgroundImage == "url()") return;
					var url = elm.currentStyle.backgroundImage.match(/^url\(["'](.*\.png)["']\)$/); //seulement les .png
					if (!url || url.length<2) return;
					var pngLayer = document.createElement('i'); // on genere un <i> en position:absolute (layer), qui viendra se placer sous le contenu du div  qui avait besoin du style.
					with(pngLayer.style) {
						if (options.noOverflow) {
							width = elm.offsetWidth + 'px';
							height = elm.offsetHeight + 'px';
						} else {
							width = '32000px';
							height = '32000px';
						}
						position = 'absolute';
						zIndex = -1;
						fontSize = '1%';
						filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='" + (options.noOverflow ? 'crop' : 'image') + "', src='"+url[1]+"')";
						background = 'none'; //forcing car parfois il peut arriver qu'on ai une CSS qui vienne rajouter des images / couleurs de fond
						/* positionnement de l'image en fonction du background-position sur l'element */
						if (!repeat) {
							switch((elm.currentStyle.backgroundPositionX+'').toLowerCase()) {
								case 'left' : left=0; break;
								case 'right' : right = 0; break;
								case 'center' :
									left='50%';
									setTimeout(function(pngLayer) {
										return function() {
											pngLayer.style.marginLeft = -(pngLayer.offsetWidth/2)+'px';
										}
									}(pngLayer), 50);
									break;
								default :
									left = elm.currentStyle.backgroundPositionX;
							}

							switch((elm.currentStyle.backgroundPositionY+'').toLowerCase()) {
								case 'top' : top = 0; break;
								case 'bottom' : bottom = 0; break;
								case 'center' :
									top='50%';
									setTimeout(function(pngLayer) {
										return function() {
											pngLayer.style.marginTop=-(pngLayer.offsetHeight/2)+'px';
										}
									}(pngLayer), 100);
									break;
								default :
									top = elm.currentStyle.backgroundPositionY || 0;
							}
						} else {
							left = 0; //elm.currentStyle.backgroundPositionX +'';
							top = 0; //elm.currentStyle.backgroundPositionY +'';
						}
					}

						/* gestion automatique du sizingMethod='scale' ou sizingMethod='image', ne pouvant pas tester le backgroundRepeat correctement, on passe par une methode un peu plus tricky */
						setTimeout(function(elmN, pngLayerN, repeatN) {
							return function() {
								if (!elmN || elmN.parentNode || !pngLayerN || !pngLayerN.parentNode) return;
								if (pngLayerN.filters['DXImageTransform.Microsoft.AlphaImageLoader'].sizingMethod=='image') {
									if (pngLayerN.offsetWidth<elmN.offsetWidth && repeatN) {
										pngLayerN.filters['DXImageTransform.Microsoft.AlphaImageLoader'].sizingMethod='scale';
									} else if (pngLayerN.offsetWidth>elmN.offsetWidth && elm.currentStyle.backgroundPositionX.match(/^(left|0%|0px|0)$/) || elm.currentStyle.backgroundPositionY.match(/^(top|0%|0px|0)$/)){
										pngLayerN.filters['DXImageTransform.Microsoft.AlphaImageLoader'].sizingMethod='crop';
									}
								} else {
									pngLayerN.sizingMethod = 'image';
								}
								if (elm.currentStyle.width.match(/^(0|[12](%|px)?)$/)) {
									pngLayerN.filters['DXImageTransform.Microsoft.AlphaImageLoader'].sizingMethod='image';
								}
								if (pngLayerN.style.right != 'auto' && pngLayerN.style.right !='')
									setTimeout(function() {
										pngLayerN.style.right = parseInt(pngLayerN.style.right) - (elm.offsetWidth%2 ? 1 : 0) + 'px';
									}, 50)
							}
						}(elm, pngLayer, repeat), 200);

					with (elm.style) {
						position = elm.currentStyle.position=="static" || elm.currentStyle.position=="" ? 'relative' : position;
						if (elm.currentStyle.overflow!='auto' && elm.currentStyle.overflow!='hidden') overflow = options.noOverflow ? 'visible' : (elm.currentStyle.width.match(/^(0|[12](%|px)?)$/) ? 'visible' : 'hidden');
						backgroundImage = 'none';
					}
					elm.appendChild(pngLayer);

			}
		}
	})(elm, noOverflow);
	try{
		pngFixLoader.useOnload ? pngFixLoader.addFunc(exec) : exec();
	} catch(e) {};
}



/* pngFixLoader
	@function 		:	objet pour permet le lancement des modifications des png via pngFix en dÃ©calÃ© sur le onload de la page.
							cela permet de contourner un bug d'internet explorer qui affiche un message d'erreur si le DOM est modifiÃ© pendant le chargement de la page.
*/
var pngFixLoader = {
	useOnload : true, // true : active l'execution du fixPng sur le load, et false, execute le fixPng dÃ¨s qu'il est appelÃ© par la CSS
	functions : [], // toutes les fonctions Ã  Ã©xÃ©cuter sur le onload de la page
	addFunc : function(func) {
		pngFixLoader.functions.push(func);
	},
	launch : function() {
			pngFixLoader.useOnload = false; //une fois la page chargÃ©e, il faut laisser s'executer automatiquement la fonction pour d'autres actions (ex : ouverture layer)
			var counter = 1;
			while(pngFixLoader.functions.length>0) {
				//setTimeout(pngFixLoader.functions.pop(), 20*counter);
				pngFixLoader.functions.pop()();
				counter++;
			}
	},
	init : function() {
		if (pngFixLoader.useOnload && window.attachEvent && document.all) {
			window.attachEvent('onload', function() {
				setTimeout(pngFixLoader.launch, 100);
			});
		}
	}
}
pngFixLoader.init();

/* ********************************************************************************** */
var $layer = {
	options : {
		id : 'insidePopup',
		templateHTML : [
			'<div class="top">&nbsp;<div>',
				'<div class="insidePopupContent">',
					'<a href="#" class="close popupCloseButton">__CLOSINGWORDING__</a>',
					'<div>',
						'__CONTENT__',
					'</div>',
				'</div>',
			'<div class="bottom">&nbsp;<div>'
		].join(''),
		styles : {
			width: '500px'
		},
		position: 'center', // pour l'instant il ne prend que center et sera developpe plus tard pour prendre les valeurs left/right/center et top/bottom/center avec les combo 'left top', 'right top' etc, etc
		mask : true, //mask sous le  layer
		maskPosition : null, // element HTML sur lequel le mask s'appliquera, si null, le parent le plus haut sera pris (<body>)
		maskClickClose : true, // click sur le mask ferme le layer
		content : '', //code HTML pour remplir le layer,
		contentFrom : null, //element contenant du code HTML pour l'afficher dedans
		elmToShow: null, // add by tibo, permet d'afficher une div presente dans la page
		parent : null, //le parent du layer, par defaut c'est document.body
		fixLayerOnParent : false, // si on veut placer le layer au dessus d'un element, on peut specifier si on met le position:relative ou pas
		className : "", //une classe CSS posee sur la popup afin de customiser la popup si necessaire
		timerInterval : 100,
		offsetTop : 10,
		offsetLeft : 10,
		closingWording : '',
		url : null, //URL externe, permet d'ouvrir une page et l'afficher dans un iframe
		iframeHeight : 100,
		iframeResizeAuto : true
	},
	currentOptions : {},
	resetOptions : function() {this.currentOptions = {}; $extend(this.currentOptions, this.options);},
	lastPositions : {},
	open : function(options) {
		var _self = this;
		var frag;
		this.close();
		this.resetOptions();
		if (options.styles && options.styles.opacity!=null) options.styles.filter = 'alpha(opacity='+options.styles.opacity*100+')'; // compatible IE
		if (options.contentFrom!=null) {
			options.contentFrom = FW(options.contentFrom).el;
			options.content = options.contentFrom.innerHTML;
		}
		// add by tibo
		if (options.elmToShow!=null) {
			options.content = "";
			this.currentElmId = options.elmToShow;
		}
		//
		if (this.currentOptions.over) this.currentOptions.over = FW(this.currentOptions.over).el;
		for (var i in options) {
			if (i!='styles') this.currentOptions[i] = options[i];
		}
		if (options.styles)
			for (var i in options.styles) {
				this.currentOptions.styles[i] = options.styles[i];
			}
		this.options.lastScrollTop = this.options.offsetTop;
		this.options.lastScrollLeft = this.options.offsetLeft;

		if (!FW(this.currentOptions.id).el)  this.createLayer();
		if (this.currentOptions.mask)  this.createMask();
		// add by tibo
		if (this.currentOptions.url) {
			this.layer.innerHTML = this.layer.innerHTML.replace(/__CONTENT__/,
					['<iframe style="width:100%" height="', this.options.iframeHeight,'" style="border:none;" onload="$layer.iframeResize(this)"',
						'frameborder="no" border="no" ',
						'src="', this.currentOptions.url, '"',
						'></iframe>'
					].join('')
				);
		}
		else {
			this.layer.innerHTML = this.layer.innerHTML.replace(/__CONTENT__/g, this.currentOptions.content).replace(/__CLOSINGWORDING__/, this.currentOptions.closingWording);
		}
		if(this.currentOptions.elmToShow) {
			//FW(this.currentOptions.elmToShow).addClass('layered');
			FW(this.currentOptions.elmToShow).el.style.display = "block";
		}
		//
		//this.layer.innerHTML = this.layer.innerHTML.replace(/__CONTENT__/g, this.currentOptions.content).replace(/__CLOSINGWORDING__/, this.currentOptions.closingWording);
		this.correctIE(this.layer);
		this.initActionsButtonsOnLayer();

		this.layer.style.width = this.layer.clientWidth - FW(this.layer).getHStyle() + 'px';
		this.setSize();
		this.setPosition();
		this.timerRefresh = setInterval(function() {
			_self.refreshSizeAndPosition()
		},this.options.timerInterval)
		this.lastPositions = {
			scrollLeft : document.documentElement.scrollLeft,
			scrollTop : document.documentElement.scrollTop
		}
		this.refreshSizeAndPosition();
		this.layer.style.visibility = 'visible';


	},
	close : function() {
		if (this.timerRefresh) clearInterval(this.timerRefresh);
		var elmW = FW(this.currentOptions.id);
		if (elmW.el) {
			elmW.el.parentNode.removeChild(elmW.el);
		}
		if (this.currentOptions.parent)
			this.currentOptions.parent.style.height  = '';
		if (this.mask){
			if (this.mask.$layerIframe)
				this.mask.$layerIframe.parentNode.removeChild(this.mask.$layerIframe);
			this.mask.parentNode.removeChild(this.mask);
		}
		try {
			delete this.layer;
			delete this.content;
			delete this.mask;
		} catch(e) {}
		if (typeof window.CollectGarbage == 'function') {
		  CollectGarbage();
		}
		if(this.currentElmId){
			FW(this.currentElmId).el.style.display = "none";
			FW(this.currentElmId).removeClass('layered');
			this.currentElmId = null;
		}
	},
	createLayer : function() {
		var layer = document.createElement('div');
		layer.className += ' '+this.currentOptions.className || "";
		layer.id = this.currentOptions.id;
		$extend(layer.style, this.currentOptions.styles);
		$extend(layer.style, {left:0, top:0, display:'block', visibility:'hidden'});
		layer.innerHTML = this.currentOptions.templateHTML;
		if (this.currentOptions.over) {
			(this.currentOptions.parent || document.body).appendChild(layer);
			if (this.currentOptions.fixLayerOnParent) {
				this.currentOptions.parent.style.position = 'relative';
			} else
				this.currentOptions.position = 'byElement';
		} else
			document.body.appendChild(layer);
		this.layer = layer;
		//FW(this.layer).addEvent('click', function(e) {FW.event.stop(e);});
		this.layerContent = FW(layer).getElement({nodeName:'div', className:'insidePopupContent'}).el;
		return this.layer;
	},
	createMask : function() {
		var mask  = document.createElement('div');
		this.mask = mask;
		mask.id = 'insidePopupMask';
		this.correctIE(mask);
		document.body.appendChild(mask);
		if (this.currentOptions.maskClickClose) {
			FW(mask).addEvent('click', function(e) {
				FW.event.stop(e);
				$layer.close();
			})
		}
	},
	iframeResize : function(iframe) {
		var doc = iframe.contentDocument || iframe.contentWindow.document;
		if(doc && doc.documentElement)
			iframe.height = doc.documentElement.scrollHeight;

	},
	setPosition : function() {
		var styles = {};
		var currStyles = this.currentOptions.styles;
		switch(this.currentOptions.position) {
			case 'center' :
				var parentToUse = window.opera ? document.body : document.documentElement;
				var top = (parentToUse.clientHeight-this.layer.offsetHeight)/2+document.documentElement.scrollTop;
				var left = (parentToUse.clientWidth-this.layer.offsetWidth)/2+document.documentElement.scrollLeft;
				//opera.postError(top+','+left);
				if (this.layer.offsetHeight>parentToUse.clientHeight)
					top = (this.lastPositions.scrollTop || 0) + this.options.offsetTop;
				else
					this.lastPositions.scrollTop = document.documentElement.scrollTop;
				if (this.layer.offsetWidth>parentToUse.clientWidth)
					left = (this.lastPositions.scrollLeft || 0) + this.options.offsetLeft;
				else
					this.lastPositions.scrollLeft = document.documentElement.scrollLeft
				styles = {
					left : left+'px',
					top : top+'px'
				};
				break;
			case 'user' :
				styles = {
					left : currStyles.left,
					top : currStyles.top
				}
				break;
			case 'byElement' :
				var pos = FW(this.currentOptions.over).getPosition();
				styles = {
					left : pos.x + 'px',
					top : pos.y + 'px'
				};
				break;
			default :
				break;
		}
		$extend(this.layer.style, styles);
	},
	setSize : function() {
		if (!isNaN(parseInt(this.currentOptions.styles.height))) {
			this.layer.style.height = 'auto';
			var inside = FW(this.layer).getElement({nodeName:'div', className:'insidePopupCloseButtonContent'}).el;
			if (this.currentOptions.parent && inside && FW(inside).getStyle('position')!='absolute' && inside.offsetHeight > this.currentOptions.parent.offsetHeight) {
				this.currentOptions.parent.style.height = this.layer.offsetHeight+'px';
			}
			if (this.layer.offsetHeight<parseInt(this.currentOptions.styles.height))
				this.layer.style.height = parseInt(this.currentOptions.styles.height)-FW(this.layer).getVStyle(this.layer)+'px';
		}
	},
	refreshSizeAndPosition : function() {
		var parentToUse = window.opera ? document.body : document.documentElement;
		if (
			(this.mask && this.mask.offsetHeight<this.layer.offsetHeight) ||
			this.lastPositions.layerHeight != this.layer.offsetHeight ||
			this.lastPositions.width != parentToUse.clientWidth ||
			this.lastPositions.height != parentToUse.clientHeight ||
			this.lastPositions.scrollLeft != document.documentElement.scrollLeft ||
			this.lastPositions.scrollTop != document.documentElement.scrollTop
		) {
			this.setPosition();
			if (this.mask && (this.lastPositions.width != document.documentElement.clientWidth || this.lastPositions.height != document.documentElement.clientHeight)) {
				var height =(document.body.clientHeight < document.documentElement.clientHeight ?
								document.documentElement.clientHeight :
									(document.body.scrollHeight>document.documentElement.scrollHeight ?
										document.body.scrollHeight : document.documentElement.scrollHeight
									)
							)
				if(!height) height = document.documentElement.scrollHeight;
				$extend(this.mask.style, {
					height : height+'px',
					width : document.documentElement.scrollWidth > document.documentElement.clientWidth ? document.documentElement.scrollWidth+'px' : "100%"
				});
			}
			this.lastPositions.layerHeight = this.layer.offsetHeight;
			this.lastPositions.width = parentToUse.clientWidth;
			this.lastPositions.height = parentToUse.clientHeight;

			this.correctIE(this.layer);
			this.correctIE(this.mask);

		}
	},
	initActionsButtonsOnLayer : function() {
		var closeButtons = FW(this.layer).getElements({className:'(close|insidePopupCloseButton)'});
		if(this.currentElmId) {
			closeButtons = FW(this.currentElmId).getElements({className:'(close|insidePopupCloseButton)'});
		}
		closeButtons.each(function(btn) {
			btn.onclick = function() {
				$layer.close();
				return false;
			}
		})
	},
	correctIE : function(element) {
		if(!element) return;
		if (!element.$layerIframe && FW.browser.ie6) {
			var ifr = document.createElement('<iframe style="filter:alpha(opacity=0);width:100%;height:100%;position:absolute;top:0;left:0;z-index:-1;">');
			element.$layerIframe = (this.options.maskClickClose && element==this.mask ? document.body : element).appendChild(ifr);
			if (element==this.mask)
				element.$layerIframe.style.zIndex = 1;
		}
		if (element.$layerIframe)
			element.$layerIframe.style.height = element.offsetHeight+'px';


	}
}


function 	aAaInit(){
	if (!FW.$('tool').el) return;
	var aAaBody = document.body;
	var array = FW.$('tool', 'a').el;
	for (var i=0; i<= 2; i++){
		FW.$(array[i]).addEvent('click', function(e){
			FW.event.stop(e);
			aAaBody.className = 'bodyFontSize'+FW.event.getSrc(e).className;
		})
	}
	/*
	FW.$(FW.$('tool', 'a').el[0]).addEvent('click',function(e){
		console.info('pute');

		$c.remove(aAaBody, 'aAaNormal');
		$c.remove(aAaBody, 'aAaBig');
		$c.add( aAaBody, 'aAaSmall');
	});/*
	aAaNormal.addEvent('click',function(e){
		$e.stop(e);
		$c.remove(aAaBody, 'aAaSmall');
		$c.remove(aAaBody, 'aAaBig');
		$c.add(   aAaBody, 'aAaNormal');
	});
	aAaBig.addEvent('click',function(e){
		$e.stop(e);
		$c.remove(aAaBody, 'aAaSmall');
		$c.remove(aAaBody, 'aAaNormal');
		$c.add(   aAaBody, 'aAaBig');
	});*/
}

/* ********************************************************************************** */
// <a href="#" onclick="popup(this.href, {width:300, scrollbars:'no'})
function popup(link, params, title) {
	var defaultParams = {
		width:400,
		height:300,
		location:'no',
		menubar:'no',
		resizable:'no',
		scrollbars:'yes',
		status:'no',
		toolbar:'no'
	};
	var popParams=[];
	for (var i in params) {
		defaultParams[i] = params[i];
	}
	for (var i in defaultParams)
		popParams.push(i+'='+defaultParams[i]);

	window.open(link, title || '_blank', popParams.join(','));
}

/* XITI */

function openLink(mySelect, openInSameWindow){
	
	openInSameWindow = (openInSameWindow != null) ? openInSameWindow : false ;

	if(mySelect.selectedIndex == 0) {

		return;

	}

	var link = mySelect.value;

	if(link.match(";")) {
		var linkContent = link.split(";");
		var optionInNewWindow = linkContent[1];
		link = linkContent[0];
	}
	
	if(link.match(/javascript/)){
		var link_splitted = link.split(',');
		var link_url = link_splitted[4].substring(1, link_splitted[4].indexOf(')') - 1);
		var link_no_url =  link.substring(link.indexOf('xt_med'), link.lastIndexOf(',')) + ')'
		var link_without_params = link.substring(link.indexOf('xt_med'));
		var popup_parameters = link.substring(11, link.indexOf('xt_med') - 1).split('#');
		if (popup_parameters[0] == '1'){
			if (popup_parameters[1] != '0' && popup_parameters[2] != '0'){
				eval(link_no_url);
				window.open(link_url, '', 'directories=no,menubar=no,status=no,location=no,scrollbars=no,resizable=no,height=' + popup_parameters[1] + ',width=' + popup_parameters[2] +',fullscreen=no');
			}else{
				var link_without_params_blank = link.substring(link.indexOf('xt_med'), link.lastIndexOf(')')) + ',\'1\')';
				eval(link_without_params_blank);
			}
		} else {
			eval(link_without_params);
		}



	}else if (link.match(/http/)){
		if(openInSameWindow == false || optionInNewWindow == 'true') {
			window.open(link);
		}
		else {
			document.location = link;
		}
	}

	else {

		document.location = link;

	}

}

/* ********************************************************************************** */

/**
*  Calculate height to 3 cols display
*/
function init3ColsHeight() {
	var cols = FW(document.body).getElements({nodeName:'div', className:'borderRPart'});

	for(var i = 0; i < cols.length; i++) {
		var currentElem = cols[i];
		var currentParent = FW(currentElem).getParent().el;
		var currentParentHeight = parseInt(currentParent.offsetHeight);

		currentElem.style.height = currentParentHeight + 'px';
	}
}

/* ********************************************************************************** */

function initNavIntHightlight() {
	var navIntBlocs = FW(document.body).getElements({nodeName:'div', className:'infoBloc'}); 	
	var targetUrl = document.location.href;
	
	for(var i = 0; i < navIntBlocs.length; i++) {
		var navLinks = FW(navIntBlocs[i]).getElements({nodeName:'a'});
		
		for(var j = 0; j < navLinks.length; j++) {
			if(navLinks[j] == targetUrl) {	
				FW(navLinks[j]).getParent().addClass("hover");	
			}
		}
	}
}

/* ********************************************************************************** */

function initRightColumnHeight() {
	var rightColumn = FW(document.getElementById("rightColumn"));
	var rightColumnParent = rightColumn.getParent();
	
	rightColumn.el.style.height = parseInt(rightColumnParent.el.offsetHeight) + "px";
}

/* ********************************************************************************** */

FW.$(window).addEvent('load', function() {
	aAaInit();

	var cols = FW(document.body).getElements({nodeName:'div', className:'borderRPart'});
	if(cols.length > 0 ) init3ColsHeight();
	
	var navIntBlocs = FW(document.body).getElements({nodeName:'div', className:'infoBloc'}); 
	if(navIntBlocs.length > 0 ) initNavIntHightlight();
	
	if(document.getElementById("rightColumn")) initRightColumnHeight();
});

/*console.log(navigator.userAgent);*/
if(navigator.userAgent.match(/Firefox\/2/)) document.documentElement.className += " isFF2";
if(navigator.userAgent.match(/AppleWebKit/)) document.documentElement.className += " isWK";

