$(function(){
	var isIe  = $.browser.msie ;
	if ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent)) var ltie7 = true;
	else var ltie7 = false;
	$.ifixpng('/_media/img/pixel.gif');
	$('img[@src$=.png]').each(function() {
		if (ltie7)  {
			w = $(this).width();
			h = $(this).height();
			$(this).ifixpng();
			$('#menu > li > a > img').iunfixpng();
			nw = $(this).width();
			nh = $(this).height();

			$(this).width(w + (w-nw));
			$(this).height(h  + (h-nh));

		}
		return true;
	});
	$('input[@src$=.png]').ifixpng();
	$('.spip_out').attr('target', '_tab');	


	// Sous menus.
	$('#menu ul').css({position: 'absolute', top: '42px'}).each(function(){
		$(this).show().find('a').css({whiteSpace: "nowrap"}).adjustSize({periode: '100', mode: 'width'});
		if ($(this).find('a').width() < ($(this).parent().width()-10)) $(this).find('a').width(($(this).parent().width()-10));
		$(this).hide();
	});
	if (ltie7) $('#menu ul').css({top: '38px'});
	// Switch Image
	$('#menu > li').not(".on").each(function(){$(this).switchImage("","> a > img");}).end().filter(".on").each(function(){$(this).switchImage("","> a > img",{stringDefault: '_selected'});});
	// Depliement
	$('#menu > li').mouseover(function(){menuOver($(this))}).mouseout(function(){menuOut($(this))}).blur(function(){menuOut($(this))}).focus(function(){menuOver($(this))});

	// Hauteur des paires de blocs dans la page rubrique
	//$("#listeContenu > li").find('> a').adjustSize().end().filter(":even").css('margin-right','70px').end().filter(":odd").css('margin-right','0');
	$("#listeContenu > li").adjustSize().filter(":even").css('margin-right','70px').end().filter(":odd").css('margin-right','0').each(function(){
		var elmt = $(this);
		// Le -30 correspond aux valeurs de padding et margin top et bottom.
		var aHeight = (elmt.height()-30);
		elmt.find('>a').height(aHeight+'px');
	});
	$(".sous_rub li").adjustSize();
	$(".contact fieldset").adjustSize();
	$('.cadreBas li, .sous_rub li').each(function() {if (!$(this).hasClass('noLink')) setClickable($(this)); });

	// Ajustement images illustrations
	$('.illustrations img').filter(':first').css('padding-left', 0).end().filter(':last').css('paddingRight', 0);
	

	// Info produits
	$("#infosProduit > *:last").css('marginBottom','0');

	// Tableaux
	$('table').each(function(){
		$('tr:even',$(this)).addClass('even');
	});

	// Menu secondaire
	$('#menuSecondaire .menuSecondaire_haut >ul >li').adjustSize();
	if (isIe) {
		$('.ombre_basse').css({'bottom':''});
		$('.ombre_basse').css({'bottom':0});
	}
	// HOME
	if ($('body#home').size() > 0) {
		$('.cadreBas').adjustSize();
		aLaUneHeight = $('#aLaUne').css('height');
		recrutementHeight = $('#recrutement').css('height');
		maxHeight = parseInt(aLaUneHeight) >= parseInt(recrutementHeight) ? parseInt(aLaUneHeight) : parseInt(recrutementHeight);
		// On compense la différence de padding des deux blocks
		// Cette compensation pourrait être à l'origine de recouvrements disgracieux, mais les méthodes pour l'éviter ne fonctionnent pas sous safari 1.2 (getComputedStyle et autres).
		if (maxHeight + 152 > parseInt($('#carteFrance').height()))
			$('#carteFrance').height((maxHeight + 152) + 'px');
		var heightALaUneCadreHaut = (parseInt($('#aLaUne .cadreBas').height())-148)+'px';
		if (isIe) 
		{
			$('#aLaUne .cadreHaut').height(heightALaUneCadreHaut);
		}
		else 
		{
			$('#aLaUne .cadreHaut').css('minHeight',heightALaUneCadreHaut);
			$('.cadreBas').each(function(){
				$(this).css({minHeight: maxHeight + 15, height: 'auto'});
			});
		}
	}
	if (ltie7)
			$('#footer li:first').find('a').css('border','none');
	// GLOSSAIRE
	if ($('body#glossaire').size() > 0) {
		var texteElmt = $('#texte');
		$('#glossaireListeLettres', texteElmt).append('<li><a href="#" id="glossaireToutVoir">Tout Voir</a></li>');
		$('#texte>ul.glossaireListe, #texte h2').hide();
		$('#glossaireListeLettres a', texteElmt).click(function(){
			if ($(this).is('#glossaireToutVoir')) {
				$('#texte>ul.glossaireListe').filter(':hidden').slideDown(function(){
					if (isIe) {
						$('.ombre_basse').css({'bottom':0});
						$('.ombre_basse').css({'bottom':'0px'});
						ajusteBG();
					}
				});
				return false;
			} else {
				var ulCible = $($(this).attr('href')).next('ul');
				$('#texte>ul.glossaireListe').not(ulCible).filter(':visible').slideUp(function(){
					if (isIe) {
						$('.ombre_basse').css({'bottom':0});
						$('.ombre_basse').css({'bottom':'0px'});
						ajusteBG();
					}
				});
				ulCible.slideDown(function(){
					if (isIe) {
						$('.ombre_basse').css({'bottom':0});
						$('.ombre_basse').css({'bottom':'1px'});
						ajusteBG();
					}
				});
				return false;
			}
		});
		var pointer=$(window.location.hash,texteElmt);
		if(pointer.size()){
			pointer.parents('ul').show();
		}
		if (isIe) {
			ajusteBG();
			}

	}
	// PLAN
	if ($('body').is('#plan')) {
		$("#texte > ul > li > ul li").each(function(){
			var elmt = $(this);
			if (elmt.find('>ul').size()) {
				if (!elmt.find('>ul >li').size()) {
					elmt.find('>ul').remove();
				} else {
					elmt.addClass("planContientListe").find('>ul').hide().end().find('> a').before("<a href=\"#\" title=\"Déplier le sous-menu\" class=\"planSwitchList\"><img src=\"_media/img/puce_screg_plan_off.gif\" width=\"28\" height=\"18\" alt=\"Déplier\"/></a>");
					$('.planSwitchList',elmt).switchImage("","img").toggle(function(){
						elmt.find('>ul').show();
						$(this).unSwitchImage("","img");
						if (isIe) {
							$('.ombre_basse').css({'bottom':0});
							$('.ombre_basse').css({'bottom':'0px'});
							ajusteBG();
						}
						return false;
					}, function(){
						elmt.find('>ul').hide();
						$(this).switchImage("","img");
						if (isIe) {
							$('.ombre_basse').css({'bottom':0});
							$('.ombre_basse').css({'bottom':'0px'});
							ajusteBG();
						}
						return false;
					});
				}
			}
		});
		if (isIe) {
			$('.ombre_basse').css({'bottom':0});
			$('.ombre_basse').css({'bottom':'0px'});
			ajusteBG();
		}
	}
	// RECRUTEMENT
	$('#postulerMessage').find('input[@type=file]').click(function(){$(this).val('');});
	$('#submitBid').click(function(){
		$('#form_coordonnees').submit();
		return false;
	});
	
	// IMPRIMER & RETOUR
	if ($('.action').size() > 0) {
		var classAction  = ($('.background').size() > 0 )?'class="large"':'';
		$('#contenu').append('<p id="actions"'+classAction+'><a href="#" title="Revenir à la page précédente" id="retour"><img src="_media/img/fleche_retour3.gif" width="15" height="14" alt="Retour"/></a>&nbsp;&mdash;&nbsp;<a href="#" title="Imprimer cette page" id="print"><img src="_media/img/picto_print.gif" width="13" height="14" alt="Imprimer" title="Imprimer cette page"/></a></p>');
		$('#retour').click(function(){
			window.history.back();
			return false;
		});
		$('#print').click(function(){
			window.print();
			return false;
		});
		$('.ombre_basse').css({'bottom':0});
		$('.ombre_basse').css({'bottom':'0px'});
		ajusteBG();
	}

	// Corrections pour les versions d'IE inférieures à 7
	if (ltie7) {
		$('#ligneVerticale').height(($('#contenu').css('zoom',1).height()));
		$('#ligneInfosProduit').height(($('#infosProduit').height()));

		$("#listeContenu li .savoirPlus").css('position','relative').css('position','absolute');
		$("#listeContenu li a").each(function(){
			var url = $(this).attr('href');
			if ($(this).attr('target') == '_blank') var newWindow = true;
			else  var newWindow = false;
			$('*',$(this)).css('cursor','pointer').click(function(){
				if (newWindow) window.open(url, 'siteScreg');
				else window.location = url;
				return false;
			})
		});
	}
	ajusteBG();
	function ajusteBG() {
		
		if (isIe) { 	
//			if (ltie7) 	{
				var hauteur = $('#contenu').height();
				hauteur += ($('.ombre_basse').size() >0)?$('.ombre_basse').height(): 0;
				hauteur += 6;
				
				$('.background').css('height',hauteur);
//			}
//			else
//				$('.background').css('bottom',0);
		}
}
	if ($('body').is('#home'))
		ticker.init();
	popUpPS.init();
});

function menuOver(e) { e.find("> ul").show(); }
function menuOut(e) { e.find("> ul").hide(); }
var setClickable = function(elt) { elt.css({'cursor':'pointer'}).click(function () { lienLi(elt);} ).mouseover(function () { $(this).css({'background':'#EDE5DA'});}).mouseout(function () { $(this).css({'background':''});}); }

var lienLi = function(elt) {
	var lien = elt.find('a:first');
	var url  = lien.attr('href');
	var newWindow = (lien.attr('target') == '_blank')?true:false;
	if (newWindow)
		window.open(url, 'siteScreg');
	else
		window.location = url;
	return false;
}

//Plugins
$.fn.adjustSize=function(options) {
	var settings = {
		periode: 2,
		mode: 'height',
		minHeight: 0,
		minWidth: 0
	};
	if (options) {
		jQuery.extend(settings, options);
	}
	var totalSize = $(this).size();
	var nbPeriodes = Math.ceil(totalSize/settings.periode);
	var index = 0;
	if (settings.mode == 'height' || settings.mode == 'both') {
		var maxTotalHeightArray = new Array();
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			if (!maxTotalHeightArray[blockId]) maxTotalHeightArray[blockId]=0;
			var blockTotalHeight = $(this).height();
			if (blockTotalHeight > maxTotalHeightArray[blockId]) {
				if (settings.minHeight && settings.minHeight > blockTotalHeight) blockTotalHeight = settings.minHeight;
				maxTotalHeightArray[blockId] = blockTotalHeight;
			}
			index++;
		});
		var index = 0;
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			var blockComputedHeight = maxTotalHeightArray[blockId];
			$(this).height(blockComputedHeight+'px');
			index++;
		});
	}
	if (settings.mode == 'width' || settings.mode == 'both') {
		var maxTotalWidthArray = new Array();
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			if (!maxTotalWidthArray[blockId]) maxTotalWidthArray[blockId]=0;
			var blockTotalWidth = $(this).width() ? $(this).width() : $(this).attr('offsetWidth') ;
			if (blockTotalWidth > maxTotalWidthArray[blockId]) {
				if (settings.minWidth && settings.minWidth > blockTotalWidth) blockTotalWidth = settings.minWidth;
				maxTotalWidthArray[blockId] = blockTotalWidth;
			}
			index++;
		});
		var index = 0;
		$(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			var blockComputedWidth = maxTotalWidthArray[blockId];
			$(this).width(blockComputedWidth+'px');
			index++;
		});
	}
	return this;
}

$.fn.switchImage=function(eventTargetSelector, changeTargetSelector, options) {
	var eventTargetSelector, changeTargetSelector, eventTarget, changeTarget;
	if (!eventTargetSelector) eventTargetSelector = '?myself';
	if (!changeTargetSelector) changeTargetSelector = '?myself';
	var settings = {
		stringDefault: '_off',
		stringHover: '_on'
	};
	if (options) {
		jQuery.extend(settings, options);
	}
	if (eventTargetSelector == '?myself') eventTarget=$(this);
	else eventTarget = $(this).find(eventTargetSelector);
	if (changeTargetSelector == '?myself') changeTarget=$(this);
	else changeTarget = $(this).find(changeTargetSelector);

	eventTarget.filter(function(index){
		return (changeTarget.is("input[@type=image][@src]") || changeTarget.is("img[@src]"));
	}).mouseover(function(){switchToHover(changeTarget)}).focus(function(){switchToHover(changeTarget)}).mouseout(function(){switchToDefault(changeTarget)}).blur(function(){switchToDefault(changeTarget)});
	function switchToHover(e) {
		var ltie7  = $.browser.msie && $.browser.version < 7;
		var ispng=false;
		if (ltie7 && e.css('filter')!='') {
			e.iunfixpng(); 
			ispng=true;
		}
		var src = e.attr('src');
		var srcPathSplit = src.split('/');
		var fileName=srcPathSplit.pop();
		var filePath=srcPathSplit.join('/');
		if (fileName.indexOf(settings.stringDefault) != -1) {
			e.attr('src', filePath+'/'+fileName.replace(settings.stringDefault, settings.stringHover));
		}
		if (ltie7 && ispng) {
			w = e.width();
			h = e.height();
			e.ifixpng();
			nw = e.width();
			nh = e.height();
			e.width(w + (w-nw));
			e.height(h  + (h-nh));
		}
	}
	function switchToDefault(e) {
		var ltie7  = $.browser.msie && $.browser.version < 7;
		var ispng=false;
		if (ltie7 && e.css('filter')!='') {
			e.iunfixpng();
			ispng=true;
		}
		var src = e.attr('src');
		var srcPathSplit = src.split('/');
		var fileName=srcPathSplit.pop();
		var filePath=srcPathSplit.join('/');
		if (fileName.indexOf(settings.stringHover) != -1) {
			e.attr('src', filePath+'/'+fileName.replace(settings.stringHover, settings.stringDefault));
		}
		if (ltie7 && ispng) {
			w = e.width();
			h = e.height();
			e.ifixpng();
			nw = e.width();
			nh = e.height();
			e.width(w + (w-nw));
			e.height(h  + (h-nh));
		}
	}
	return this;
}
 
$.fn.unSwitchImage=function(eventTargetSelector, changeTargetSelector) {
	var eventTargetSelector, changeTargetSelector, eventTarget, changeTarget;
	if (!eventTargetSelector) eventTargetSelector = '?myself';
	if (!changeTargetSelector) changeTargetSelector = '?myself';
	if (eventTargetSelector == '?myself') eventTarget=$(this);
	else eventTarget = $(this).find(eventTargetSelector);
	if (changeTargetSelector == '?myself') changeTarget=$(this);
	else changeTarget = $(this).find(changeTargetSelector);
	eventTarget.unbind("mouseover").unbind("focus").unbind("mouseout").unbind("blur");
	return this;
}

var ticker = function() {
	if ($.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent)) var ltie7 = true;
	else var ltie7 = false;
	var newsTicker, recallMove, movingObject;
	var widthGetter, widthGetterElmts;
	var aLineElmts = [];
	var aLineElmtsLength = [];
	var aLineElmtsTotalLength=0;
	var moveDelay=30;
	if(ltie7) var moveDelay=60;
	var moveLength=1;
	var listContainer='li';
	var listContainerSeparationWidth=18;
	var newsTicker= $('#tickerImg');
	var listContainerExclude=$('#tickerExclude');
	var counter=0;
	function init() {
		newsTickerElmts = $('>'+listContainer,newsTicker).not(listContainerExclude);
		getTotalWidth();
		newsTicker.width(aLineElmtsTotalLength+'px');
		aLineElmts = $(listContainer,newsTicker);
		lineMove(newsTicker);
	}

	function lineMove() {
		newsTicker.bind('mouseover.ticker',function(){lineStop();}).bind('mouseout.ticker',function(){lineAnimate(newsTicker)}).find('>'+listContainer+':visible >a').bind('focus.ticker',function(){newsTicker.css({left: '2px'});listContainerExclude.css({left: '120px'});lineStop();}).bind('blur.ticker',function(){lineAnimate(newsTicker);});
		lineAnimate(newsTicker);
	}
	
	function lineAnimate(){
		recallMove = window.setTimeout(lineAnimate,moveDelay);
		newsTicker.css({left: (parseInt(newsTicker.css('left'))-moveLength)+'px'});
		listContainerExclude.css({left: (parseInt(listContainerExclude.css('left'))+moveLength)+'px'});
		if (parseInt(newsTicker.css('left')) < -aLineElmtsLength[0]) {
			lineSwap();
		}
	}

	function lineSwap() {
		movingObject = newsTicker.find(listContainer+':first');
		movingObject.insertBefore(listContainerExclude);
		newsTicker.css({left: (parseInt(newsTicker.css('left'))+aLineElmtsLength[0])+'px'});
		listContainerExclude.css({left: (parseInt(listContainerExclude.css('left'))-aLineElmtsLength[0])+'px'});
		aLineElmtsLength.push(aLineElmtsLength.shift());
	}
	
	function getTotalWidth() {
//		widthGetter=$('<div id="widthGetter"></div>');
//		widthGetter.css({position: 'absolute', top: '-999px', left: '-999px', width: '1000em'});
//		$('body').append(widthGetter);
//		widthGetter.append(newsTickerElmts.clone());
//		widthGetterElmts=widthGetter.find(listContainer).css({display: 'block', position: 'absolute', whiteSpace: 'nowrap'});
		newsTickerElmts.each(function(){
			aLineElmtsLength[newsTickerElmts.index(this)]=(parseInt($(this).width())+listContainerSeparationWidth);
		});
//		widthGetter.remove();
		var aLineElmtsLengthSize=aLineElmtsLength.length;
		if (!aLineElmtsLengthSize) return;
		for (var i=0; i < aLineElmtsLengthSize; i++) {
			aLineElmtsTotalLength += aLineElmtsLength[i];
		}
	}
	function lineStop() {window.clearTimeout(recallMove);}

	return{init:init,stop:lineStop,start:lineAnimate};
}();

var popUpPS = function(){
	var block = $('div.popUpPS');
	var newW;
	function init() {
		$('a.popUpPS').click(
		function(){
			newW = window.open('_squelettes/modeles/popup.html', '', 'height='+ block.height()*1.1 +',width=500,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=no');
			newW.focus();
			window.setTimeout('popUpPS.setContent()', 400);
			return false;
		});
	}
	
	function setContent()
	{
		var newWBody = newW.document.getElementsByTagName('body')[0];
		newWBody.innerHTML = '<div class="msgPopUp">'+block.html() +'</div>';
		newW.document.title = $('a.popUpPS').html();
	}
	
	return{init:init, setContent:setContent};
}();