var scrollTopIE6 = 0;

function setScrollTopIE(num){
	scrollTopIE6 = num;
}
function getScrollTopIE(){
	return scrollTopIE6;
}

jQuery.parseJSON =  function( data ) {
	if ( typeof data !== "string" || !data ) {
		return null;
	}

	// Make sure leading/trailing whitespace is removed (IE can't handle it)
	data = jQuery.trim( data );
	
	// Make sure the incoming data is actual JSON
	// Logic borrowed from http://json.org/json2.js
	if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
		.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
		.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {

		// Try to use the native JSON parser first
		return window.JSON && window.JSON.parse ?
			window.JSON.parse( data ) :
			(new Function("return " + data))();

	} else {
		jQuery.error( "Invalid JSON: " + data );
	}
}

var D_GMAP =  null;

var GmapManagerID = GmapManagerID?GmapManagerID:"";

document.documentElement.className += " hasJS";

nbrResultatsVisible = 6;

var racine = racine?racine:"/";

var pageCheckEnvoiAmi = racine+"inc/checkEnvoiAmi.php";

var popinVideoPage = racine+"popin.video.php";

var arrayFiltres = new Array();

arrayFiltres["XX"] = [racine+"img/filtreGmap/ico_none.png",""];
arrayFiltres[225] = [racine+"img/filtreGmap/ico_hotel.png",f6_dfomain_gmap_categories_hotel];
arrayFiltres[226] = [racine+"img/filtreGmap/ico_reunion.png",f6_dfomain_gmap_categories_congres];
arrayFiltres[227] = [racine+"img/filtreGmap/ico_restaurant.png",f6_dfomain_gmap_categories_restaurant];
arrayFiltres[228] = [racine+"img/filtreGmap/ico_loisir.png",f6_dfomain_gmap_categories_loisirs];

var jsonPopinGmap = {}
var jsonGeneralGmap = {}

function setjsonpopinGmap(json){
	jsonPopinGmap = json;
}
function getjsonpopinGmap(){
	return jsonPopinGmap;
}
function setjsonGeneralGmap(json){
	jsonGeneralGmap = json;
}
function getjsonGeneralGmap(){
	return jsonGeneralGmap;
}

var player = null;	

/** 
	array pour declaration des classes contenant des img à "arrondir"
	roundImg est la classe a ajouter dans le html si pas de selecteur pertinant
*/

var ImgRoundedSelector = [".roundImg",".miniNews ", ".quoteExt1 .lastUnit"];


function relaunchPopin(){
	//File Browse
	/*if($(".mypopin").find(".FileBrowse").length > 0) {
		new FileBrowseUIGroup("FileBrowse", {
			browseButtonPos: "right", 						//left/right: default = right + 
															//top/bottom: default = bottom
															//top/bottom: relative to the textbox
			browseButtonClassName: "BrowseBtnStyle",		//use for Styling,
															//default = "DefaultBrowseBtn"
			browseTextBoxClassName: "BrowseTextBoxStyle",	//use for Styling,
															//default = "DefaultBrowseBtn"
			browseButtonText: "> Parcourir",						//use for Styling,
															//default = "Browse"
			browseTextBoxValue: ""
		});
		$(".mypopin").find(".BrowseTextBoxStyle").attr("readonly", true);
	}*/
	
	//console.log($(".mypopin").find(".SelectUI"));
	$(".mypopin").find(".SelectUI").addSelectUI({
		scrollbarWidth: 12,
		after_action: function(){
			if($selectDroplist_Manager.activeName != null){
				$("select[name='"+$selectDroplist_Manager.activeName+"']").trigger("change");
				$("select[name='"+$selectDroplist_Manager.activeName+"']").trigger("focusout");
			}else{
				$("select[name='"+$selectDroplist_Manager.oldActiveName+"']").trigger("change");
				$("select[name='"+$selectDroplist_Manager.oldActiveName+"']").trigger("focusout");
			}
		}
	});
	
	if($(".mypopin").find(".CheckBoxUI").length > 0) {
		$(".mypopin").find(".CheckBoxUI").addCheckBoxUI();
	}
	
	if($(".mypopin").find(".CheckBoxExtraUI").length > 0) {
		$(".mypopin").find(".CheckBoxExtraUI").addCheckBoxExtraUI();
	}
	
	if($(".mypopin").find(".RadioUI").length > 0) {
		$(".mypopin").find(".RadioUI").addRadioUI();
	}
	
	if($(".mypopin").find('.gmapLocator').length != 0){
		// gestion des donnees JSON
		myJsonURL = racine+"json/"+jsonFile+".json";
		// lancement de la fabrication de la map
		var getJsonGenerated = getjsonpopinGmap();
		var jsonPopinGmap = getJsonGenerated ? getJsonGenerated : {googlemaps:{langue:'fr',offre:[]}};
		if(jsonPopinGmap.googlemaps.offre.length != 0){
			$(".mypopin").find('.gmapLocator').each(function(i, el){
				
				var myArgumentsMap = getCssParam(el);
				if(myArgumentsMap.typeMap == "noResults"){
					D_GMAP = new GmapManager(el,"",jsonPopinGmap, "");
				}else if(myArgumentsMap.typeMap == "popinGMap"){
					D_GMAP = new GmapManager(el,"",jsonPopinGmap, "popinGMap");
				}else{
					D_GMAP = new GmapManager(el,"",jsonPopinGmap, "withResults");
				}
			});
		}else{
			$.getJSON(myJsonURL, function(data) {
                setjsonGeneralGmap(data);
				$(".mypopin").find('.gmapLocator').each(function(i, el){					
					var myArgumentsMap = getCssParam(el);
					if(myArgumentsMap.typeMap == "noResults"){
						D_GMAP = new GmapManager(el,"",data, "");
					}else if(myArgumentsMap.typeMap == "popinGMap"){
						D_GMAP = new GmapManager(el,"",data, "popinGMap");
					}else{
						D_GMAP = new GmapManager(el,"",data, "withResults");
					}
				});
				
			});
		}
	}

	if($(".mypopin").find(".diapoCarousel").length > 0) {
		$(".mypopin").find(".diapoCarousel").each(function(i, el){
			var myArgumentsPopin = getCssParam(el);
			var myId = "#"+el.id;
			
			var myScrollCarousel = myArgumentsPopin.scrollCarousel?myArgumentsPopin.scrollCarousel:1;
			var myStartCarousel = myArgumentsPopin.startCarousel?myArgumentsPopin.startCarousel:1;
			var myTimeCarousel = myArgumentsPopin.timeCarousel?myArgumentsPopin.timeCarousel:0;
			var myTimeReact = myArgumentsPopin.timeReact?myArgumentsPopin.timeReact:0;
			
			new DisneyCarousel(myId, {scroll:parseInt(myScrollCarousel),start:parseInt(myStartCarousel)}, parseInt(myTimeCarousel),parseInt(myTimeReact));
		});
	}
	
	$(".mypopin").find(".autoclean").each(function (i, el){
		$(el).bind("focus", function (){
			if($(this).val() == $(this).attr("defaultValue")){
				$(this).val("");
			}
		})
		$(el).bind("blur", function (){
			if($(this).val() == ""){
				$(this).val($(this).attr("defaultValue"));
			}
		})
	})
	
	$(".mypopin").find(".popin-content").each(function (i, el){
		var a = $(el).find("select").attr("id");
		
		$(el).bind("scroll", (function (a){
			return function (){
				if($selectDroplist_Manager.els && $selectDroplist_Manager.els[a]) $selectDroplist_Manager.els[a].reset();
			}
		})(a));
	})
	
	
	
	// gestion de Gmap
	/* Gestion formulaires */
	if($(".mypopin").find(".formValidation").length != 0){
		//console.log("test")
		//$.metadata.setType("attr", "validate");
		$(".mypopin").find(".formValidation").each(function(i, el){
			var myElem = $(el);
			//console.log(myElem)
			
			var errorMainDiv = myElem.find(".errorMain");
			
			myElem.validate({
				showErrors: function() {
					this.defaultShowErrors();
					if(this.numberOfInvalids() != 0){
						errorMainDiv.removeClass("hidden");
						//alert("attend ya encore du pas bon")
					}
					
				}
			});
		});
	}

	
	
	$(".ajaxUpload").each(function (i, el){
		var queueId = $(this).attr('id')+'_Queue';
		$(el).uploadify({
		'uploader'       : racine + 'scripts/uploadify.swf',
		'script'         : 'uploadify',
		'cancelImg'      : racine + 'img/cancel.png',
		'folder'         : '/sites/default/files/' + 'uploads',
			'queueID'   	 : queueId ,
			'auto'           : true,
			'multi'          : true,
			'hideButton' : true,
			'buttonImg': null,
			'wmode': 'transparent',
			'width': 85,
			'height': 18,
			
			'onComplete':function (e, id, fileObj, response, data){
					var oData = jQuery.parseJSON(response);
					var q = $("#" + $(e.target).attr("id") + "_Queue");
					q.append("<input type='hidden' id='inp_"+id+"' name='joinFile[]' value='"+oData['file']+"' /> ");
					q.append("<p class='uploadifyQueueItem'>"+"<img src='"+racine+"img/cancel.png' alt='Supprimer' onclick='deleteHidden(this, \""+ "inp_"+id +"\")'/>" +oData['nameSRC'] + "</p>");
				},
			'onProgress': function (){
				//console.log("progress=",arguments);
			},
			
			'onSelect': function (e, id, fileObj){
				//console.log("select=", arguments);
			}
			
			
		});	
	})


	
	
	
	
	
}

function relaunchVideoPopin(fileFLV, width, height){
		var flashWidth = width-20;
		var flashHeight = height-35;
		//console.log(flashWidth,flashHeight);
		var spopinVideo = new SWFObject(''+racine+'scripts/diaporama/player.swf','playerPopinVideoF',flashWidth,flashHeight,'9');
		spopinVideo.addParam('allowfullscreen','false');
		spopinVideo.addParam('allowscriptaccess','always');
		spopinVideo.addParam('wmode','transparent');
		// pour pouvoir lancer nos fonctions sur le flash quand il se lance, arrive en fin et est mis en pause
		spopinVideo.addVariable('enablejs', 'true');
		// spopinVideo.addVariable('autostart', 'true'); pour le flash qui demarre tout seul
		spopinVideo.addVariable('volume', '50');
		spopinVideo.addVariable('file', ''+fileFLV);
		// skin disney
		spopinVideo.addVariable('skin', ''+racine+'xml/skins/disney/disney.xml');
		// suppression des clip share en fin de video et en pause
		spopinVideo.addVariable('viral.onpause', 'false');
		spopinVideo.addVariable('viral.oncomplete', 'false');
		// on etire la video pour qu'elle tienne dans le player a sa taille ("fill" pour agrandir jusqu a ce que les lateraux touchent sinon "none" pour laisser la taille de la video sur la hauteur)
		spopinVideo.addVariable('stretching', 'uniform');
		spopinVideo.write('playerPopinVideo');
		
		var idFlash = $(".myVideoPopin").find(".playerflash").children()[0].id;
		var myPlayer = document.getElementById(idFlash);
		$(".myVideoPopin").find(".muteSound").bind("click",function(event){
			event.preventDefault();
			event.stopPropagation();
			if($(this).hasClass("muted")){
				// lancer la fonction qui demute le flash
				$(this).removeClass("muted");
				myPlayer.sendEvent("mute", "false");
			}else{
				// lancer la fonction qui mute le flash
				$(this).addClass("muted");
				myPlayer.sendEvent("mute", "true");
			}
		});

}
function relaunchVideoMovPopin(file, title, width, height){
		width -=20;
		height-=150;
		var html='<div class="em18 bold txtC txtBlue">'+title+'</div>';
		html+='<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="'+height+'" width="'+width+'">';
		html+='<param name="src" value="'+file+'">';
		html+='<param name="autoplay" value="false">';
		html+='<param name="type" value="video/quicktime" height="'+height+'" width="'+width+'">';
		
		html+='<embed src="'+file+'" height="'+height+'" width="'+width+'" autoplay="false" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/">';
		html+='</object>';
		
		$('#playerPopinVideo').html(html);
}



$(document).ready(function(){

	$(".hasJS").find(".jsinactive").removeClass("jsinactive");
	//console.log($("div.ThemeComboBoxExtra8"))
	// configurateur nbPers
	Cufon.replace(".fontFranklinMed", { fontFamily: 'franklingoth' });
	if($(".RadioUI").length > 0) {
		$(".RadioUI").addRadioUI();
	}
	
	// sync
	
	if($(".diapoCarousel").length != 0  && $('.printStyle').length == 0){
		
		/*	Preparation des elements de diaporama Carousel des pages
		*
		*	structure 		: <ul id="myID" class="diapoCarousel scrollCarousel:'1' startCarousel:'1' timeCarousel:'7' timeReact:'20' ">
		*
		*	scrollCarousel	: nombre d'elements a scroller a chaque deplacement
		*	startCarousel	: position de depart du carousel
		*	timeCarousel	: temps entre les changements automatiques
		*	timeReact		: temps d'attente apres un clic sur un element avant de reprendre la rotation automatique
		*/
		
		$(".diapoCarousel").each(function(i, el){
			var myArguments = getCssParam(el);
			var myId = "#"+el.id;
			
			var myScrollCarousel = myArguments.scrollCarousel?myArguments.scrollCarousel:1;
			var myStartCarousel = myArguments.startCarousel?myArguments.startCarousel:1;
			var myTimeCarousel = myArguments.timeCarousel?myArguments.timeCarousel:7;
			var myTimeReact = myArguments.timeReact?myArguments.timeReact:20;
			
			new DisneyCarousel(myId, {scroll:parseInt(myScrollCarousel),start:parseInt(myStartCarousel)}, parseInt(myTimeCarousel),parseInt(myTimeReact));
		});
		
		
		
	}
	//if($('.printStyle').length != 0){
	$(".carouselConfigurator").each(function(i, el){
		var myArguments = getCssParam(el);
		var myId = "#"+el.id;
		var myScrollCarousel = myArguments.scrollCarousel?myArguments.scrollCarousel:1;
		var myStartCarousel = myArguments.startCarousel?myArguments.startCarousel:1;
		var myTimeCarousel = myArguments.timeCarousel?myArguments.timeCarousel:7;
		var myTimeReact = myArguments.timeReact?myArguments.timeReact:20;
		
		
		$(myId).jcarousel({
			scroll:parseInt(myScrollCarousel),
			start:parseInt(myStartCarousel)
		});
		//new DisneyCarousel(myId, {scroll:parseInt(myScrollCarousel),start:parseInt(myStartCarousel)}, parseInt(myTimeCarousel),parseInt(myTimeReact));
	});
	
	if($(".blockHome").length != 0){
		/*	Preparation des elements du block Home (sorte de block tabs automatique avec des fade)
		*
		*	structure 		: <div class="mod blockHome timerTabs:'7'">
		*	timerTabs		: temps entre les changements automatiques
		*/
		$(".blockHome").each(function(i, el){
			var myArguments = getCssParam(el);
			
			var myTimerTabs = myArguments.timerTabs?myArguments.timerTabs:7;
			
			new HomeTabs(el,myTimerTabs);
		});
	}
	
	$(".autoclean").each(function (i, el){
		$(el).bind("focus", function (){
			if($(this).val() == $(this).attr("defaultValue")){
				$(this).val("");
			}
		})
		$(el).bind("blur", function (){
			if($(this).val() == ""){
				$(this).val($(this).attr("defaultValue"));
			}
		})
	})
	
	// fonction d'ouverture de popin VIDEO
	if($(".videoPopin").length != 0){
		$(".videoPopin").each(function(i, el){
				
			$(el).bind("click",function(eventObject){
			
				var myArgumentsPopin = getCssParam(el);
				var thispopinwidth = myArgumentsPopin.width?parseInt(myArgumentsPopin.width):800;
				var thispopinheight = myArgumentsPopin.height?parseInt(myArgumentsPopin.height):500;
				// Dimensions player en dur (pb ss FFx de dimensionnement de la popin).
				//var thispopinwidth = 800;
				//var thispopinheight = 500;
				//console.log(thispopinwidth,thispopinheight);
				
				eventObject.preventDefault();
				eventObject.stopPropagation();
				
				var lienVideoPopin = $(this).attr("href");
				var mytitleVideoPopin = $(this).attr("title");
				
				
				//omniture tracking
				var maReg = new RegExp( '((%20)|[_ -])+', "gi") ;
				var videoStr=lienVideoPopin.split('/').pop().replace( maReg,' ').split('.');
				var videoExt=videoStr.pop();
				var videoName=videoStr.join('.');
				videoClick(videoName);

				
				$(document.body).append('<a id="popinLinkTemp" href="'+popinVideoPage+'">'+f6_dfomain_videoPopin_tempLink+'</a>');
				
				$("#popinLinkTemp").popin({
					width:thispopinwidth,
					height:thispopinheight,
					className: "mypopin",
					loaderImg : racine+'scripts/popin/ajax-loader.gif',
					onComplete: function() {
						// Pb hauteur player sur FFx
						var vpopin = $(".myVideoPopin");
						vpopin.css("height", thispopinheight);
						centerPopin();
						if($(".myVideoPopin").length != 0){
							
							if (videoExt=='mov')
								relaunchVideoMovPopin(lienVideoPopin, mytitleVideoPopin, thispopinwidth, thispopinheight);
							else
								relaunchVideoPopin(lienVideoPopin, thispopinwidth, thispopinheight);
						}
					},
					onExit : function(){
						$("#popinLinkTemp").remove();
					},
					onStart: function (){
						ie6 = ($.browser.msie && ($.browser.version == "6.0")) ? true : false;
						//alert(document.documentElement.scrollTop+" --- "+document.body.scrollTop);
						if(ie6 == true){
							setScrollTopIE(document.documentElement.scrollTop);
						}
					}
				});
				$("#popinLinkTemp").click();
				
			});
			//relaunchVideoPopin
		});
	}
	
	// fonction d'ouverture de popins si pas ds tpl print
	if($('.openPopin').length != 0 && $('.printStyle').length == 0){
		$('.openPopin').each(function(i, el){
			var myArgumentsPopin = getCssParam(el);
			
			var thispopinwidth = myArgumentsPopin.width?parseInt(myArgumentsPopin.width):980;
			var thispopinheight = myArgumentsPopin.height?parseInt(myArgumentsPopin.height):500;
			var oTmpImg = null;
			if(el.rel != "" && el.rel != "nofollow"){ // el.rel == "" || el.rel == "nofollow"
				oTmpImg = $('#' + el.rel);
			}
			$(el).popin({
				width:thispopinwidth,
				height:thispopinheight,
				className: "mypopin",
				loaderImg : racine+'scripts/popin/ajax-loader.gif',
				oImg:oTmpImg,
				onComplete: function() {
					// fonction a envoyer dans la popin une fois celle ci ouverte


					centerPopin();
					//alert("test exists mypopin")
					if($(".mypopin").length != 0){
						//alert("dans mypopin")
						// on relance les cufon des textes speciaux
						Cufon.replace(".fontExtra", { fontFamily: 'CenturyGothic' });
						Cufon.replace(".fontExtraBold", { fontFamily: 'CenturyGothicBold' });
						relaunchPopin();
					}
					//alert("fin test exists mypopin")
				},
				onExit : function(){
					if($selectDroplist_Manager.activeName != null){
						$selectDroplist_Manager.els[$selectDroplist_Manager.activeName].hideList();
					}
				},
				onStart: function (){
					ie6 = ($.browser.msie && ($.browser.version == "6.0")) ? true : false;
					//alert(document.documentElement.scrollTop+" --- "+document.body.scrollTop);
					if(ie6 == true){
						setScrollTopIE(document.documentElement.scrollTop);
					}
				}
			});
		});
	}
	
	
	
	// gestion des googlemaps
	if($('.gmapLocator').length != 0){
		// gestion des donnees JSON
		var myJsonURL = racine+"json/"+jsonFile+".json";
		// lancement de la fabrication de la map
		
		$.getJSON(myJsonURL, function(data) {
            setjsonGeneralGmap(data)
			$('.gmapLocator').each(function(i, el){
				
				var myArgumentsMap = getCssParam(el);
				if(myArgumentsMap.typeMap == "noResults"){
					new GmapManager(el,"",data, "");
				}else{
					new GmapManager(el,"",data, "withResults");
				}
			});
			
		});
	}
	
	// gestion des blocks OFFRES
	if($('.blockOffreSlider').length != 0){
		$('.blockOffreSlider').each(function(i, el){
			new HomeOffers(el);
		});
	}
	
	
	/* Gestion formulaires */
	if($(".formValidation").length != 0){
		//console.log("test")
		//$.metadata.setType("attr", "validate");
		$(".formValidation").each(function(i, el){
			var myElem = $(el);
			//console.log(myElem)
			
			var errorMainDiv = myElem.find(".errorMain");
			
			myElem.validate({
				showErrors: function() {
					this.defaultShowErrors();
					if(this.numberOfInvalids() != 0) {
						//$('html, body').animate({scrollTop:0}, 'slow');
						errorMainDiv.removeClass("hidden");
					}
				}
			});
		});
	}

	if($(".blockLinked").length != 0){
		var myBlocksLinked = $(".blockLinked");
		
		myBlocksLinked.each(function(index, elem){
			var myelem = $(elem);
			var mySource = myelem.find(".linkedSource");
			var mytargets = myelem.find(".linkedTarget");
			
			if(myelem.hasClass("blockLinkedInputs")){
				//console.log("inputs");
				mytargets.bind("blur",function() {
					var oneFilled = false;
					for(var i =0; i<myelem.find(".linkedTarget").length; i++){
						if(myelem.find(".linkedTarget")[i].value != ""){
							oneFilled = true;
							break;
						}
					}
					if(oneFilled){
						mySource.parent(".formCheckBox").find(".CheckBoxStyle").addClass("CheckBoxUIActive");
						mySource.attr('checked',true);
					}else{
						mySource.parent(".formCheckBox").find(".CheckBoxStyle").removeClass("CheckBoxUIActive");
						mySource.attr('checked',false);
					}
				});
			}else if(myelem.hasClass("blockLinkedChecks")){
				
				//mySource
				mytargets.bind("click",function() {
					var nbrTargetChecked = myelem.find(".linkedTarget:checked").length;
					//console.log(nbrTargetChecked);
					if(nbrTargetChecked>=1){
						mySource.parent(".formCheckBox").find(".CheckBoxStyle").addClass("CheckBoxUIActive");
						mySource.attr('checked',true);
					}else{
						mySource.parent(".formCheckBox").find(".CheckBoxStyle").removeClass("CheckBoxUIActive");
						mySource.attr('checked',false);
					}
				});
			}
		});
	}

	$('.blockLiens .inner div:last ').removeClass("Bmargin8");
	//var racienbis = "/test";
	$(".ajaxUpload").each(function (i, el){
		var queueId = $(this).attr('id')+'_Queue';
		$(el).uploadify({
			'uploader'       : racine + 'scripts/uploadify.swf',
			'script'         : 'uploadify',
			'cancelImg'      : racine + 'img/cancel.png',
			'folder'         : '/sites/default/files/' + 'uploads',
			'queueID'    : queueId ,
			'auto'           : true,
			'multi'          : true,
			'hideButton' : true,
			'buttonImg': null,
			'wmode': 'transparent',
			'width': 85,
			'height': 18,
			
			'onComplete':function (e, id, fileObj, response, data){
				var oData = jQuery.parseJSON(response);
				var q = $("#" + $(e.target).attr("id") + "_Queue");
				q.append("<input type='hidden' id='inp_"+id+"' name='joinFile[]' value='"+oData['file']+"' /> ");
				q.append("<p class='uploadifyQueueItem'>"+"<img src='"+racine+"img/cancel.png' alt='Supprimer' onclick='deleteHidden(this, \""+ "inp_"+id +"\")'/>" +oData['nameSRC'] + "</p>");
			},
			'onProgress': function (){
				//console.log("progress=",racine + 'uploadify');
			},
			
			'onSelect': function (e, id, fileObj){
				//console.log("select=", arguments);
			},
			
			'onInit' : function (){}
			
			
		});	
	})
	
	
	// Gestion des temoignages de la HP (à cause du cache PHP) : on masque tous, on affiche 1 aléatoire
	if($('.testimonies').length != 0){
		max = $('.testimonies').length - 1;
		rand = Math.floor(Math.random()*max);
		$(".testimony"+rand).show();
	}
	
	// Gestion des Blocs footer de la HP (à cause du cache PHP) : on masque tous, on affiche 1 aléatoire
	if($('.simpleEcoResponsibility').length != 0){
		max = $('.simpleEcoResponsibility').length - 1;
		rand = Math.floor(Math.random()*max);
		$(".showEco"+rand).show();
	}
	
	
	if($('.roundedImg').length != 0){
		$('.roundedImg').each(function(i, el){
			//alert($(el).css("width"))
			var myImg = $(el).find("img")[0];
			if(!myImg) return;
			var valueWidthRounded = $(el).width();
			if($(myImg).width() > valueWidthRounded) valueWidthRounded = $(myImg).width();
			if($(myImg).innerWidth() > valueWidthRounded) valueWidthRounded = $(myImg).innerWidth();
			if($(myImg).outerWidth() > valueWidthRounded) valueWidthRounded = $(myImg).outerWidth();
			$(el).css("width",valueWidthRounded)
		//	console.log("--------------")
			var valueHeightRounded = $(el).height();
		//	console.log(valueHeightRounded)
			if($(myImg).height() > valueHeightRounded) valueHeightRounded = $(myImg).height();
		//	console.log(valueHeightRounded)
			if($(myImg).innerHeight() > valueHeightRounded) valueHeightRounded = $(myImg).innerHeight();
		//	console.log(valueHeightRounded)
			if($(myImg).outerHeight() > valueHeightRounded) valueHeightRounded = $(myImg).outerHeight();
		//	console.log(valueHeightRounded)
			$(el).css("height",valueHeightRounded)
		
		});
	}
	
	$(".sizingAlphaFoot").each(function(i,elem){
		var thisfoottext = $(elem).find(".txtFoot")[0];
		var thisalphafoot = $(elem).find(".alphaFoot")[0];
		
		var linkTxtFoot = $(thisfoottext).find("a")[0];
		
		var heightBlock = $(thisfoottext).innerHeight();
		
		var marginLink = heightBlock-10-$(linkTxtFoot).innerHeight();
		
		$(linkTxtFoot).css("margin-top",marginLink);
		$(thisfoottext).css("height",heightBlock);
		$(thisalphafoot).css("height",heightBlock);
		
	});
});

function centerPopin(){
	ie6 = ($.browser.msie && ($.browser.version == "6.0")) ? true : false;
	var popin = $(".popin");
	var content = $(".popin-content");
	var innerH = window.innerHeight || document.documentElement.offsetHeight;
		
	if(ie6){
		//alert("test3 IE");
		$("#PPNCSS").remove();				

		content.css("height", "auto");		
		//alert(getScrollTopIE());		
		content.css("height", popin.height()-35);

		popin.css("height", "auto");
		popin.css("height",	popin.height());
		//popin.css("margin-top", -popin.height() + "px");
		popin.css("top", 20+getScrollTopIE());
		
		if(popin.height() > innerH){
			content.css("height", "auto");
			content.css("height",innerH - 120);
			popin.css("height", "auto");
			popin.css("height",	innerH - 85);
			popin.css("margin-top", "0px");
			popin.css("top", 20+getScrollTopIE());
		}		
	}
	else {
		//alert("test3 : "+content.height());
		content.css("height", "auto");
		content.css("height", content.height());
		popin.css("height", "auto");
		popin.css("height",	popin.height());
		popin.css("margin-top", -popin.height()/2 + "px");
		popin.css("top", "50%")
		//alert(popin.height() +', '+ content.height());
		
		if(popin.height() > innerH){
			//alert("fsdfsd");
			popin.css("height",	innerH - 55);
			content.css("height",innerH - 90);
			popin.css("margin-top", "0px")
			popin.css("top", "10px");		
		}	
	}
	//alert("fin test center")
	//$("#PPNCSS").attr("disabled", "disabled");	
}



function getCssParam(elm, param){
	var o = {}
	var sp = elm.className.split(" ");
	for(var i=0,l=sp.length;i<l;i++){
		if(/:/.test(sp[i])) {
			var sp2 = sp[i].split(":");
			o[sp2[0]] = sp2[1].replace(/^'|'$/g, "");
		}
	}
	return param ? o[param] : o;
}

/*	Classe pour la gestion du diaporama Disney */ 
var DisneyCarousel = function (){
	this.initialize.apply(this, arguments);
};

DisneyCarousel.prototype = {
	initialize: function (el, args, autoScroll,timereact){
		var self = this;
		this.index= 0;
		this.ulCarousel = $(el);
		
		this.intervalFlash = [];
		this.activeFlashVideo = "";
		
		this.initVisuals();
		
	
		this.auto = autoScroll*1000;
		if(this.auto == 0){
			this.startAutoActivated = false;
		}else{
			this.startAutoActivated = true;
		}
		this.timereaction = timereact*1000;
		// crado mais dis moi comment faire mieux
		args.itemLoadCallback = function (carousel, state){
			self.carousel = carousel;
		}
		this.ulCarousel.jcarousel(args);
		if(this.startAutoActivated){
			$(el).parent().parent().bind("click", function (){self.stopAuto()});
			this.startAuto();
		}
		/* Gestion des elements carousel */
		this.gestionBtnPrevNext();
		this.gestionCarElem();
		this.soundCheckFlash();
		
		
		
	},
	
	startAuto: function (){
		var self = this; 
		
		this.interval = setInterval(function (){
			
			var myCarouselElm = self.ulCarousel.find(".active");
			if(myCarouselElm.next(".carouselElem").length != 0){
				self.carousel.next();
				self.index += 1;
				
				myCarouselElm.removeClass("active");
				myCarouselElm.next(".carouselElem").addClass("active");
				self.updateVisuals(self.index);
			}
			else {
				if(self.startAutoActivated){
					self.stopAutoForLoop();
				}
				self.index = 0;
				self.carousel.scroll(0, true);
				myCarouselElm.removeClass("active");
				$(self.ulCarousel.find(".carouselElem")[0]).addClass("active");
				self.updateVisuals(self.index);
				if(self.startAutoActivated){
					self.startAuto();
				}
			}
			// detection fin carousel
			
		},this.auto)
	},
	nextAuto: function (){
		var self = this; 
		var myCarouselElm = self.ulCarousel.find(".active");
		if(myCarouselElm.next(".carouselElem").length != 0){
			self.carousel.next();
			self.index += 1;
			
			myCarouselElm.removeClass("active");
			myCarouselElm.next(".carouselElem").addClass("active");
			self.updateVisuals(self.index);
			if(self.startAutoActivated){
				self.startAuto();
			}
		}
		else {
			self.index = 0;
			self.carousel.scroll(0, true);
			myCarouselElm.removeClass("active");
			$(self.ulCarousel.find(".carouselElem")[0]).addClass("active");
			self.updateVisuals(self.index);
			if(self.startAutoActivated){
				self.startAuto();
			}
		}
		// detection fin carousel
	},
	stopAuto: function (){
		var self = this;
		if(this.interval) clearInterval(this.interval);
		if(this.timeout) clearTimeout(this.timeout);
		if(this.startAutoActivated){
			this.timeout = setTimeout(function (){self.startAuto()}, self.timereaction);
		}
	},
	stopAutoForLoop: function (){
		if(this.interval){clearInterval(this.interval);}
		if(this.timeout){clearTimeout(this.timeout);}
	},
	stopForVideo: function (element){
		
		var self = this;
		if(this.interval){clearInterval(this.interval);}
		if(this.timeout){clearTimeout(this.timeout);}
		
		var myChild = element.find(".playerflash").children();
		if(myChild.length != 0){
			var childId = myChild[0].id;
			var myPlayer = document.getElementById(childId);
			this.activePlayer = myPlayer;
			this.intervalVideo = setInterval(function (){
				if($(self.activePlayer).hasClass("endVideo")){
					clearInterval(self.intervalVideo);
					$(self.activePlayer).removeClass("endVideo");
					$(self.activePlayer).addClass("bufferVideo");
					this.activePlayer = null;
					if(self.startAutoActivated){
						self.nextAuto();
					}
				}
			},2000);
		}
	},
	gestionBtnPrevNext : function(){
		var self = this;
		var zonePrev = this.ulCarousel.parent().parent().find(".jcarousel-prev");
		var zoneNext = this.ulCarousel.parent().parent().find(".jcarousel-next")
		
		zoneNext.bind("click", function (){self.goToNext()});
		zonePrev.bind("click", function (){self.goToPrev()});
		
	},
	goToNext: function(){
		// function vide, juste pour contrer la non existance des clics des boutons
		var nextButton = f6_dfomain_carousel_nextBtn;
		var prevButton = empty_str;
	},
	goToPrev: function(){
		// function vide, juste pour contrer la non existance des clics des boutons
		var prevButton = f6_dfomain_carousel_prevBtn;
		var nextButton = empty_str;
	},
	gestionCarElem: function(){
		var self = this;
		//console.log("-----------------------")
		var divVisuels = this.ulCarousel.parents('.diaporamazone').find(".visuelElem");
		this.ulCarousel.find('.carouselElem').each(function(index){
			var myCarouselElm = $(this);
			
			var visuelLinked = divVisuels[index];
			if($(visuelLinked).hasClass("flash")){
				myCarouselElm.find("a").append('<span class="vignetteFlash"><img src="/img/diaporamas/flashVignette.png" alt="" /></span>');
			}
			//myCarouselElm.find("a").append('<span class="hoverCadre"></span>');
			myCarouselElm.find("a").click(function(eventObject){
				if(myCarouselElm.hasClass("active")){
					eventObject.preventDefault();
				}else{
					eventObject.preventDefault();
					myCarouselElm.parent(".diapoCarousel").find(".active").removeClass("active");
					myCarouselElm.addClass("active");
					self.index = index;
					self.updateVisuals(index);
				}
			})
		});
		
	},
	initVisuals : function(){
		var divVisuels = this.ulCarousel.parents('.diaporamazone').find(".visuel");
		var toInitialiseVisuel = divVisuels.find(".visuelElem");
		
		if(divVisuels.hasClass("alignVerticalDiapo")){
			toInitialiseVisuel.each(function(index, elm){
				var myelm = $(elm)
				var activeElm = myelm.hasClass("active")?true:false;
				
				if(activeElm){
					var imgVisuel = myelm.find('.visuelElemImg');
					if(imgVisuel.length != 0){
						var margeTop = (imgVisuel.height() - divVisuels.height())/2;
						if(margeTop>0){
							imgVisuel.css("margin-top","-"+margeTop+"px")
						}
					}
				}else{
					myelm.addClass("active");
					var imgVisuel = myelm.find('.visuelElemImg');
					if(imgVisuel.length != 0){
						var margeTop = (imgVisuel.height() - divVisuels.height())/2;
						if(margeTop>0){
							imgVisuel.css("margin-top","-"+margeTop+"px")
						}
					}
					myelm.removeClass("active");
				}
			});
		}
	},
	updateVisuals : function (index){
		var divVisuels = this.ulCarousel.parents('.diaporamazone').find(".visuel");
		var divoverAll = this.ulCarousel.parents('.diaporamazone').find(".overAllElem");
		var activeVisuel = divVisuels.find(".active");
		var toActiveVisuel = divVisuels.find(".visuelElem")[index];
		
		$(toActiveVisuel).addClass("toActive")
		activeVisuel.fadeOut("slow",function(){
			activeVisuel.removeClass("active");
		});
		$(toActiveVisuel).fadeIn("slow", function(){
			$(toActiveVisuel).removeClass("toActive");
			$(toActiveVisuel).addClass("active");
		});
		// on reset les active
		if($(toActiveVisuel).hasClass("flash")){
			if(divoverAll.hasClass('overAllHidden')){
			}else{
				divoverAll.fadeOut("slow", function(){
					divoverAll.addClass("overAllHidden");
				});
			}
		}else{
			if(divoverAll.hasClass('overAllHidden')){
				divoverAll.fadeIn("slow", function(){
					divoverAll.removeClass("overAllHidden");
				});
			}
		}
		
	},
	soundCheckFlash : function(){
		var self = this;
		var divVisuels = this.ulCarousel.parents('.diaporamazone').find(".visuelElem");
		divVisuels.each(function(index,elm){
			var myElement = $(elm);
			var myMuter = myElement.find(".muteSound");
			if(myElement.hasClass("flash")){
				if(self.startAutoActivated){
					myElement.bind("click", function (){self.stopForVideo(myElement)});
				}
				var myChild = myElement.find(".playerflash").children();
				if(myChild.length != 0){
					var childId = myChild[0].id;
					var myPlayer = document.getElementById(childId);
					if(self.startAutoActivated){
						$(myPlayer).bind("focus", function (){self.stopForVideo(myElement)});	
					}
					if(myElement.hasClass("flashautostart")){
						self.intervalFlash[childId] = setInterval(function (){
							self.checkVideoPlaying(myElement,childId);
						},3000);
					}
					myMuter.click(function(event){
						event.stopPropagation();
						if(self.startAutoActivated){self.stopForVideo(myElement);}
						if($(this).hasClass("muted")){
							// lancer la fonction qui demute le flash
							$(this).removeClass("muted");
							myPlayer.sendEvent("mute", "false");
						}else{
							// lancer la fonction qui mute le flash
							$(this).addClass("muted");
							myPlayer.sendEvent("mute", "true");
						}
					});
				}else{
					myMuter.addClass("hidden");
				}
			}
		});
	},
	checkVideoPlaying: function(myElement,childId){
		var myplayer = document.getElementById(childId);
		
		if($(myplayer).hasClass("playVideo") && this.activeFlashVideo == ""){
			this.activeFlashVideo = childId;
			this.stopForVideo(myElement);
		}else if($(myplayer).hasClass("endVideo") && this.activeFlashVideo == childId){
			this.activeFlashVideo = "";
		}else{
			//console.log(childId, $(myplayer), $(myplayer).hasClass("playVideo"));
		}
		
		
	}

}

/* Classe pour la gestion des block Home Tabs */
var HomeTabs = function (){
	this.initialize.apply(this, arguments);
};
HomeTabs.prototype = {
	initialize: function (el, timer){
		var self = this;
		this.timer = parseInt(timer)*1000;
		this.index= 0;
		this.tabler = $(el);
		this.visuels = this.tabler.find(".visuels")[0];
		this.blockNav = this.tabler.find(".navBlock")[0];
		
		this.countElements = $(this.visuels).find(".visuelElem").length;
		
		this.startAuto();
		
		
		
		
		//console.log(this.visuels);
		//console.log(this.blockNav);
		this.gestionTabs();
		
		$('.visuels .visuelElem').each(function (i, el){
			if($(el).find("a").length > 0){
				$(el).find(".contents").css("cursor", "pointer");
			}
			if($(el).find(".muteSound").length >0){
				var idFlash = $(el).find(".playerflash").children()[0].id;
				var myPlayer = document.getElementById(idFlash);
				$(el).find(".muteSound").bind("click",function(event){
					event.stopPropagation();
					if($(this).hasClass("muted")){
						// lancer la fonction qui demute le flash
						$(this).removeClass("muted");
						myPlayer.sendEvent("mute", "false");
					}else{
						// lancer la fonction qui mute le flash
						$(this).addClass("muted");
						myPlayer.sendEvent("mute", "true");
					}
				});
			}
		});
		$('.visuels .visuelElem .contents').bind("click", function (){
			if($(this).parent().find("a").length > 0){
				document.location.href =  $(this).parent().find("a").attr("href");
			}
		})
	},
	startAuto:function(){
		var self = this;		
		this.interval = setInterval(function (){
			
			self.index += 1;
			if(self.index == self.countElements){
				self.index = 0;
			}
			var index = self.index;
			var el = $(this.blockNav).find(".elemNav a")[index];
			self.updateTabler(index,el);
			
		},this.timer)
		
	},
	gestionTabs: function(){
		var self = this;
		$(this.blockNav).find(".elemNav a").each(function(i,el){
			$(el).bind("click", function (eventObject){
				eventObject.preventDefault();
				if(self.interval){clearInterval(self.interval);}
				if($(el).parent().parent(".elemNav").hasClass("active")){
				
				}else{
					self.index += 1;
					if(self.index == self.countElements){
						self.index = 0;
					}
					self.updateTabler(i,el);
				}
			});
		});
	},
	updateTabler: function(index,elem){
		var actualActive = $(this.blockNav).find(".active");
		var setToActive = $(elem).parent().parent(".elemNav");
		
		actualActive.removeClass("active");
		setToActive.addClass("active");
		Cufon.refresh();
		this.updateVisuals(index);
	},
	updateVisuals: function(index){
		var actualVisualActive = $(this.visuels).find(".active");
		var setToVisualActive = $(this.visuels).find(".visuelElem")[index];
		
		
		actualVisualActive.fadeOut("slow");
		$(setToVisualActive).fadeIn("slow");
		actualVisualActive.removeClass("active");
		$(setToVisualActive).addClass("active");
		
		
	}
};

/* Classe pour la gestion des block GoogleMap Dealer Locator */
var GmapManager = function (){
	this.initialize.apply(this, arguments);
};
GmapManager.prototype = {
	initialize: function (el, template, json, typeCard){
		var self = this;
		this.typeCard = typeCard;
		this.datas = json;
		this.activeFilters = [0];
		if(GmapManagerID){
			this.activeOffres = (GmapManagerID != null && GmapManagerID != "") ? [GmapManagerID] : [];
		}else{
			this.activeOffres = [];
		}
		this.gmapMapper = $(el);
		// Lancement de la Carte google maps		
		
		if(this.typeCard == "withResults"){
			this.map = initializeNormal(json,el);
			// gestion des controlers active
			this.activeJSON = json;
			this.generationListeResultats(this.activeJSON, 0, nbrResultatsVisible, true);
			//this.generationListeResultats(json);
			this.gestionActiveControlsMap();
			this.generationFiltres(json);
			this.actionOnSituer(json);
		}else if(this.typeCard == "popinGMap"){
			this.map = initializeNormal(json,el);
			this.gestionActiveControlsMap();
		}else{
			this.map = initializeLittleMap(json,el);
			this.gestionActiveControlsMap();
		}
		
		if(this.activeOffres.length != 0){
			this.autoChangeMapOnLoadWithParam(json);
		}
		
	},
	generationListeResultats : function(json,start,nbrvisible,generePagin){
		var self = this;
		if($("#resultatRecherche")){
			// on a une partie de recherche sur le Json
			var divResults = $("#resultatRecherche").find(".listeResAjax")[0];
			$(divResults).empty();
			var iVisible = 0;
			
			var newJsonAff = {
				googlemaps:{
					langue:'fr',
					offre:[]
				}
			};
			
			if(json.googlemaps){
				var nbrOffresAff = json.googlemaps.offre?json.googlemaps.offre.length:0;
				if(nbrOffresAff != 0){
					var mesOffresAFF = json.googlemaps.offre;
					for(var i=0;i<nbrOffresAff;i++){
						//console.log(mesOffresAFF[i].type, "---", this.activeFilters);
						if(mesOffresAFF[i].type != "XX"){
							//console.log("A checker")
							newJsonAff.googlemaps.offre.push(mesOffresAFF[i]);
						}
					}
				}
			}
			
			if(newJsonAff.googlemaps){
				var nbrOffres = newJsonAff.googlemaps.offre?newJsonAff.googlemaps.offre.length:0;
				if(nbrOffres != 0){
					// on stoque les offres
					var mesOffres = newJsonAff.googlemaps.offre;
					// si la div d'affichage du nombre de resultats est definie
					if($("#nbrResultats")){
						// on compte le nombre d'offres actives (sans les XX)
						var compteurActive = 0;
						for(var counter=0;counter<nbrOffres;counter++){
							var monType = mesOffres[counter].type;
							if(monType != "XX"){
								compteurActive++;
							}
						}
						// on met a jour le nombre de resultats.
						var divShowNbrResults = $("#nbrResultats").find(".showNbr")[0];
						divShowNbrResults.innerHTML = ""+compteurActive;
					}
					// on commence l'affichage des elements.
					var myHTMLResultats = "";
					
					for(var i=start;i<nbrOffres;i++){
						
						if(iVisible == nbrvisible){break;}
						
						var monType = mesOffres[i].type;
						if(monType != "XX"){
							var myResultat = "";
							if(iVisible < nbrvisible){
								myResultat += '<div class="resultat odd borderDotGreyB visible">';
									myResultat += '<div class="line Tpadding15 Bpadding15">';
										myResultat += '<div class="unit size1of16 txtBlueL em14 bold">';
											myResultat += '<div class="formCheckBox Tpadding23 Lpadding">';
												var myId = ""+mesOffres[i].id;
												var checkedOffre = "";
												if(jQuery.inArray(myId,self.activeOffres)>-1){
													
													checkedOffre = ' checked="checked"';
												}
												myResultat += '<input name="checkbox" id="checkbox'+mesOffres[i].id+'"'+checkedOffre+' type="checkbox" value="" class="CheckBoxExtraUI floatR" />';
												myResultat += '<label for="checkbox'+mesOffres[i].id+'" class="CheckBoxExtraStyle  Rpadding28 floatL">'+mesOffres[i].identifier+'</label>';
											myResultat += '</div>';
										myResultat += '</div>';
										myResultat += '<div class="unit size14of16 Tmargin-3">';
											myResultat += '<div class="mea">';
												myResultat += '<a href="#" title="" class="media">';
												myResultat += '<div class="roundedImg" style="width: 68px; height: 68px;">';
												myResultat += '<b class="top"><b class="tl">&nbsp;</b><b class="tr">&nbsp;</b></b>';
												myResultat += '<img src="' + mesOffres[i].img + '" alt="" width="68" height="68" />';
												myResultat += '<b class="bottom"><b class="bl">&nbsp;</b><b class="br">&nbsp;</b></b>';
												myResultat += '</div></a>';
												myResultat += '<div class="text">';
													myResultat += '<p class="txtBlueD em12 BmarginSm Tmargin-1"><strong class="bold">'+mesOffres[i].nom1+'</strong> '+mesOffres[i].presta+'</p>';
													myResultat += '<p class="txtBlueD em12 Bmargin">'+mesOffres[i].accroche+'</p>';
													if(mesOffres[i].urlmore != ""){
													myResultat += '<div class="functionLink">';
														myResultat += '<a href="'+mesOffres[i].urlmore+'" title="'+f6_dfomain_gmap_en_savoir_plus+'"><span>&gt; '+f6_dfomain_gmap_en_savoir_plus+'</span></a>';
													myResultat += '</div>';
													}
												myResultat += '</div>';
											myResultat += '</div>';
										myResultat += '</div>';
                                        //console.log(monType)
										myResultat += '<div class="unit size1of16 lastUnit Tpadding"><img src="'+arrayFiltres[monType][0]+'" alt="'+arrayFiltres[monType][1]+'" width="35" height="30" /></div>';
									myResultat += '</div>';
								myResultat += '</div>';
								// on envoie le resultat dans le HTML a envoyer
								myHTMLResultats += myResultat;
								iVisible++;
							}
						}
					}
					if(iVisible == 0){
						var myHTMLResultats = "";
						myHTMLResultats += '<div class="noresults">'+f6_dfomain_gmap_pas_de_resultat+'</div>';
					}
					divResults.innerHTML = myHTMLResultats;
					if($(divResults).find(".CheckBoxUI").length > 0) {
						$(divResults).find(".CheckBoxUI").addCheckBoxUI();
					}
					if($(divResults).find(".CheckBoxExtraUI").length > 0) {
						$(divResults).find(".CheckBoxExtraUI").addCheckBoxExtraUI();
					}
					if($(divResults).find(".RadioUI").length > 0) {
						$(divResults).find(".RadioUI").addRadioUI();
					}
					
					// Gestion de la pagination
					this.gestionCheckListeResultat();
					if(generePagin){
						this.gestionPagination();
					}
				}else{
					var myHTMLResultats = "";
					myHTMLResultats += '<div class="noresults">'+f6_dfomain_gmap_pas_de_resultat+'</div>';
					divResults.innerHTML = myHTMLResultats;
					var divShowNbrResults = $("#nbrResultats").find(".showNbr")[0];
					divShowNbrResults.innerHTML = "0";
					if(generePagin){
						this.gestionPagination();
					}
				}
			}else{
				var myHTMLResultats = "";
				myHTMLResultats += '<div class="noresults">'+f6_dfomain_gmap_pas_de_resultat+'</div>';
				divResults.innerHTML = myHTMLResultats;
				var divShowNbrResults = $("#nbrResultats").find(".showNbr")[0];
				divShowNbrResults.innerHTML = "0";
				if(generePagin){
					this.gestionPagination();
				}
			}
		}
	},
	gestionCheckListeResultat : function(){
		var self = this;
		this.gmapMapper.find("input.CheckBoxExtraUI").bind("click",function(eventObject){
			var myId = this.id;
			myId = myId.replace("checkbox", "")
			if(jQuery.inArray(myId,self.activeOffres)>-1){
				var test = jQuery.grep(self.activeOffres, function(value){
					return value != myId;
				});
				self.activeOffres = test;
			}else{
				self.activeOffres.push(myId);
			}
		});
	},
	generationFiltres : function(json){
		var self = this;
		if($("#resultatRecherche")){
			var filtresLI = $("#resultatRecherche").find(".filtreresultats ul li");
			var firstFiltreLI = $(filtresLI[0]);
			var filtres = $("#resultatRecherche").find(".filtreresultats ul li a");
			// gestion des clics sur les filtres
			if(filtres.length != 0){
				filtres.each(function(i, el){
					var myArguments = getCssParam(el);
					$(el).bind("click", function (eventObject){
						eventObject.preventDefault();
						// si on clique sur le type 0 on desactive tout le monde
						var typePOI = parseInt(myArguments.type);
						
						filtresLI.removeClass("active");
						filtresLI.removeClass("firstactive");
						filtresLI.removeClass("lastactive");
						var myParentLiFiltre = $(this).parent();
						// ajout de l'active sur le bouton avec gestion speciale si first ou last
						if(myParentLiFiltre.hasClass("first")){
							myParentLiFiltre.addClass("active");
							myParentLiFiltre.addClass("firstactive");
						}else if(myParentLiFiltre.hasClass("last")){
							myParentLiFiltre.addClass("active");
							myParentLiFiltre.addClass("lastactive");
						}else{
							myParentLiFiltre.addClass("active");
						}
						// mise a jour du tableau des filtres actifs
						if(typePOI == 0){
							// si on a choisi le filtre "all" on redefinit le tableau
							self.activeFilters = [0];
						}else{
							// si on a choisi un filtre en particulier
							// on verifie de le filtre en question est inactif
							if(jQuery.inArray(typePOI,self.activeFilters)>-1){
								// s'il est actif on le desactive et on reaffiche tout
								var test = jQuery.grep(self.activeFilters, function(value){
									return value != typePOI;
								});
								if(test.length!=1){
									self.activeFilters = test;
								}else{
									self.activeFilters = [0];
									firstFiltreLI.addClass("active");
									firstFiltreLI.addClass("firstactive");
								}
								myParentLiFiltre.removeClass("active");
								myParentLiFiltre.removeClass("firstactive");
								myParentLiFiltre.removeClass("lastactive");
								
							}else{
								self.activeFilters = [];
								self.activeFilters[0] = "XX";
								self.activeFilters.push(typePOI);
							}
						}
						// Action JSON sur les contenus
						// generation du nouveau JSON contenant les elements a afficher.
						self.actionOnFiltre(json);
					});
				});
			}
		}
	},
	actionOnFiltre:function(json){
		var self = this;
		if(this.activeFilters[0] == 0){
			
			this.activeJSON = json;
			this.generationListeResultats(this.activeJSON, 0, nbrResultatsVisible, true);
			//this.generationListeResultats(json);
			this.map.clearOverlays();
			// et on affiche les nouveaux markers selectionnes
			addPointsByJson(json,this.map);
		}else{
			var newJson = {
				googlemaps:{
					langue:'fr',
					offre:[]
				}
			};
			var newJsonpoints = {
				googlemaps:{
					langue:'fr',
					offre:[]
				}
			};
			if(json.googlemaps){
				var nbrOffres = json.googlemaps.offre?json.googlemaps.offre.length:0;
				if(nbrOffres != 0){
					var mesOffres = json.googlemaps.offre;
					for(var i=0;i<nbrOffres;i++){
						
						if(jQuery.inArray(mesOffres[i].type, this.activeFilters) != -1 && mesOffres[i].type != "XX"){
							
							newJson.googlemaps.offre.push(mesOffres[i]);
						}
						if(jQuery.inArray(mesOffres[i].type, this.activeFilters) != -1){
							
							newJsonpoints.googlemaps.offre.push(mesOffres[i]);
						}
					}
				}
			}
			this.activeJSON = newJson;
			this.generationListeResultats(this.activeJSON, 0, nbrResultatsVisible,true);
			// on efface les markers de la page
			this.map.clearOverlays();
			// et on a ffiche les nouveaux markers selectionnes
			addPointsByJson(newJsonpoints,this.map);
		}
	},
	gestionActiveControlsMap:function(){
		var self = this;
		var myControlers = this.gmapMapper.find(".btnControler");
		var myControlersZoom = this.gmapMapper.find(".btnControlerZoom");
		if(myControlers.length != 0){
			myControlers.each(function(i, el){
				$(el).bind("click", function (eventObject){
					eventObject.preventDefault();
					myControlers.removeClass("active");
					$(this).addClass("active");
				});
			});
		}
		if(myControlersZoom.length != 0){
			myControlersZoom.each(function(i, el){
				$(el).bind("click", function (eventObject){
					eventObject.preventDefault();
				});
			});
		}
	},
	actionOnSituer:function(json){
		var self = this;
		this.gmapMapper.find(".situerMap").bind("click", function (eventObject){
			eventObject.preventDefault();
			if(self.activeOffres.length != 0){
				// on efface les markers de la page
				self.map.clearOverlays();
				// et on a ffiche les nouveaux markers selectionnes				
				var newJson = {
					googlemaps:{
						langue:'fr',
						offre:[]
					}
				};
				if(json.googlemaps){
					var nbrOffres = json.googlemaps.offre?json.googlemaps.offre.length:0;
					if(nbrOffres != 0){
						var mesOffres = json.googlemaps.offre;
						for(var i=0;i<nbrOffres;i++){
							var myId = ''+mesOffres[i].id;
							if(jQuery.inArray(myId, self.activeOffres) != -1 || mesOffres[i].type == "XX"){
								newJson.googlemaps.offre.push(mesOffres[i]);
							}
						}
					}
				}
				addPointsByJson(newJson,self.map);
			}
			document.location.hash  = "#gmap";
		});
	},
	gestionPagination:function(){
		var self = this;
		var divpagination = $("#resultatRecherche").find(".paginationResultat");
		var resultats = this.activeJSON.googlemaps.offre;
		// calcul du nombre de pages affichables
		var nbrPages = Math.ceil(resultats.length/nbrResultatsVisible);
		// creation des paginations
		divpagination.each(function(index,elm){
			var myListPagin = $(elm);
			myListPagin.empty();
			if(nbrPages>1){
				for(var i=0; i<nbrPages; i++){
					var myLiPagin = '<li class="paginationElem paginElem'+i+(i==0?" active":"")+'"><a href="#" class="page:'+i+'">'+(i+1)+'</a></li>';
					myListPagin.append(myLiPagin);
				}
			}
		});
		this.setActionOnPagination();
	},
	setActionOnPagination:function(){
		var self = this;
		var divpaginationElm = $("#resultatRecherche").find(".paginationResultat .paginationElem");
		var divpagination = $("#resultatRecherche").find(".paginationResultat .paginationElem a");
		var resultats = $("#resultatRecherche").find(".resultat");
		divpagination.each(function(index,elm){
			//console.log(elm);
			var paginElemTarget = getCssParam(elm).page;
			$(elm).bind("click", function (eventObject){
				eventObject.preventDefault();
				var mesTargets = self.gmapMapper.find(".paginElem"+paginElemTarget);
				divpaginationElm.removeClass("active");
				mesTargets.addClass("active");
				
				var myNewStart = parseInt(paginElemTarget)*nbrResultatsVisible;
				
				self.generationListeResultats(self.activeJSON, myNewStart, nbrResultatsVisible, false);
				
			});
		});
	},
	
	autoChangeMapOnLoadWithParam: function (json){
		var self = this;
		if(self.activeOffres.length != 0){
			// on efface les markers de la page
			self.map.clearOverlays();
			// et on a ffiche les nouveaux markers selectionnes				
			var newJson = {
				googlemaps:{
					langue:'fr',
					offre:[]
				}
			};
			if(json.googlemaps){
				var nbrOffres = json.googlemaps.offre?json.googlemaps.offre.length:0;
				if(nbrOffres != 0){
					var mesOffres = json.googlemaps.offre;
					for(var i=0;i<nbrOffres;i++){
						var myId = ''+mesOffres[i].id;
						if(jQuery.inArray(myId, self.activeOffres) != -1 || mesOffres[i].type == "XX"){
							newJson.googlemaps.offre.push(mesOffres[i]);
						}
					}
				}
			}
			
			if(self.typeCard == "withResults"){
				addPointsByJson(newJson,self.map);
			}else if(self.typeCard == "popinGMap"){
				addPointsByJson(newJson,self.map);
			}else{
				addLittlePointsByJson(newJson,self.map);
			}
	    if(self.activeOffres.length == 1)
			{
				self.map.panTo(new GLatLng(newJson.googlemaps.offre[0].longitude,newJson.googlemaps.offre[0].latitude));
			}
		}
	},
	
	aProx: function (){
		
		$.getJSON(myJsonURL, function(data) {
				//console.log(data)
				$(data.googlemaps.offre).each(function (i, el){
					//console.log(jsonGenerated.googlemaps.offre[1].id)
					//console.log(el)
				})
				
				
			});
		}
		
	};


/* Classe pour la gestion des block Home Tabs */
var HomeOffers = function (){
	this.initialize.apply(this, arguments);
};
HomeOffers.prototype = {
	initialize: function (elem){
		var self = this;
		// mise en place des elements generaux
		this.tabler = $(elem);
		this.visuals = this.tabler.find(".elemOfferBlock");
		
		this.listElemSwitchActive = this.tabler.find(".listOfferBlock .active")[0];
		this.prevBtn = this.tabler.find(".listOfferBlock .prevBtn")[0];
		this.nextBtn = this.tabler.find(".listOfferBlock .nextBtn")[0];
		this.listElemSwitch = this.tabler.find(".listOfferBlock .elemListOfferBlock");
		
		var listeElem = this.tabler.find(".listOfferBlock")[0];
		var paramsLoop = getCssParam(listeElem);
		var loop = (paramsLoop.autoloop ? parseInt(paramsLoop.autoloop) : 0);
		
		loop = loop*1000;
		this.timer = loop;
		
		this.nbrListSwitch = this.listElemSwitch.length;
		this.indiceActive = parseInt(getCssParam(this.listElemSwitchActive).indice);
		
		this.listElemSwitch.each(function(index, el){
			var indiceElm = parseInt(getCssParam(el).indice);
			//console.log(indiceElm);
			var linkElm = $(el).find("a")[0];
			$(linkElm).bind("click",function(eventObject){
				eventObject.preventDefault();
				self.setVisibleElm(indiceElm);
			});
		});
		
		$(this.prevBtn).bind("click",function(eventObject){
			eventObject.preventDefault();
			self.prevElm();
		});
		
		$(this.nextBtn).bind("click",function(eventObject){
			eventObject.preventDefault();
			self.nextElm();
		});
		
		if(this.timer != 0){
			this.startAuto();
		}
		
	},
	setVisibleElm: function(index){
		var self = this;
		if(index != this.indiceActive){
			// si le loop est en attente on l arrete
			if(this.interval){ clearInterval(this.interval);}
			if(self.timer != 0){
				self.startAuto();
			}
			
			var listToSetActive = self.listElemSwitch[index];
			var elemToSetActive = self.visuals[index];
			
			
			self.listElemSwitch.removeClass("active");
			$(listToSetActive).addClass("active");
			
			var previousActive = this.visuals[this.indiceActive];
			self.indiceActive = index;
			
			$(previousActive).fadeOut("slow",function(){				
				$(previousActive).attr("style", "");
				$(previousActive).addClass("hidden");
				$(previousActive).removeClass("active");
				
				// si on doit loop, on relance
				
			});
			
			$(elemToSetActive).fadeIn("slow",function(){
				$(elemToSetActive).attr("style", "");
				$(elemToSetActive).removeClass("hidden");
				$(elemToSetActive).addClass("active");
			});
		}
	},
	prevElm:function(){
		var newIndice = parseInt(this.indiceActive-1);
		if(newIndice == -1){
			newIndice = this.nbrListSwitch-1;
		}
		this.setVisibleElm(newIndice);
	},
	nextElm:function(){
		
		var newIndice = parseInt(this.indiceActive+1);
		if(newIndice >= this.nbrListSwitch){
			newIndice = 0;
		}
		this.setVisibleElm(newIndice);
	},
	startAuto:function(){
		var self = this;		
		this.interval = setInterval(function (){
			
			self.nextElm();
			
		},this.timer)
		
	}
};


// fonctions qui gere les evenements sur le player flash
function playerReady(obj){
	player = document.getElementById(obj.id);
	player.addModelListener('STATE', 'stateMonitor');
}

function stateMonitor(obj){
	// ajouter au player une classe en fonction de l'etat de lecture : buffer, playing, paused, complete
	if(obj.newstate == "BUFFERING"){
		player = document.getElementById(obj.id);
		player.className = "bufferVideo";
	}
	if(obj.newstate == "PLAYING"){
		player = document.getElementById(obj.id);
		player.className = "playVideo";
	}
	if(obj.newstate == "COMPLETED"){
		player = document.getElementById(obj.id);
		player.className = "endVideo";
	}
	
}

// var a = new DisneyCarousel();

var getLabel = function (input){ 
	if(input.push) input = $(input).get(0);
	if(!input.form) return;
	var labs = input.form.getElementsByTagName('label');
	for(var i = 0 ; i < labs.length; i++){
		var theFor = labs[i].getAttribute('for') || labs[i].getAttribute('htmlFor');
		if(theFor == input.id) {
			return labs[i];
		}
	}
}

var getInputFromLabel = function (label){
		label = $(label);
		
		return $("#"+ $(label).attr('for'));

}
/*
Module.LineResizer = function (line, bubbleResize){
		var lines = $$('div.line').filter(function(a, b){return !a.hasClass("noresize")});
		
		for(var i = lines.length-1; i>=0; i--){
			var line = $(lines[i]);
			var height = line.offsetHeight;
			var units = line.getElements(".unit, .lastUnit").filter(function(a, b){
				var noresize = a.hasClass("noresize");
				var pLine = a.getParent(".line");
				return pLine == line && !pLine.hasClass("noresize") && pLine.offsetHeight != 0 && !noresize;
			});
			
			for(var j=0,l=units.length;j<l;j++){
				var el = units[j];
				//var body = el.getElements(".body, .bd").filter(function(a, b){return a.getParent(".unit") == el && !a.hasClass("noresize") && !a.getParent(".block .noresize")});
				var body = el.getElements(".bd").filter(
					function(a, b){
						return (a.getParent(".unit") == el || a.getParent(".lastUnit") == el) && !a.hasClass("noresize") && !a.getParent(".mod .noresize")
					}
				);
				
				// si pas de .body, le .unit est resize
				if(!body) body = [el];
				
				var h2apply = (line.clientHeight - el.clientHeight) / body.length;
				body.each(function (bdy, i){
					var oriH = bdy.getStyle("height").toInt();
					doResize(bdy, oriH + h2apply);
				})
			}
		}
		
		if(bubbleResize){
			var parentLine = line.getParent('.line');
			if(parentLine) Module.LineResizer(parentLine, true);
			else Module.AfterResize();
		}
		else Module.AfterResize();
	}*/
	
function deleteHidden(img, inp){
	$(img).parent().remove();
	$('#' + inp).remove();
}
function checkFormEnvoiAmi(form){
	setTimeout(function (){
		if($(form).find(".errorLabel").length != 0) return;
		/*$('.popin-voile').click();
		$(form).trigger("submit");*/
		var reg=new  RegExp("[?]+", "g");		
		var urlPage = document.location.href.split(reg)[0];
		$(form).find(".urlPage").val(urlPage);
		
		var toSerializeForm = $(form).serialize();
		$.post(pageCheckEnvoiAmi, toSerializeForm, function(data) {
			$(".popin-content").animate({"scrollTop":0},{duration: 200})
			if(data == "error"){
				// si le script nous renvoi error, on affiche le message d erreur
				$(form).find(".errorMain").show();
				$(form).find(".errorServeur").hide();
			}else if(data == "ok"){
				// si le script nous renvoi ok, on va a la page definie dans le action du form
				//document.location.href = $(form).attr("action");
        $(form).submit();
				//$('.popin-voile').click();
			}else{
				// si le script nous renvoi toute autre erreur, on appelle une erreur serveur
				$(form).find(".errorServeur").show();
				$(form).find(".errorMain").hide();
			}
		});

	}, 500)
}

var virtualVisit = {
	tmp:{
		currentHostel:null,
		currentHostelLink:null
	},
	changeHostel:function(oItem, iItem){
		var oTmpCurrent = $('#virtualVisit').find('.JSvirtualVisitDiapo' + iItem);
		if(virtualVisit.tmp.currentHostel == null){
			$('#virtualVisit').find('.virtualVisitDiapo').hide();
			$('#virtualVisit').find('.VVVostelItemActiv').removeClass('VVVostelItemActiv');
			virtualVisit.tmp.currentHostel = $('#virtualVisit').find('.virtualVisitDiapo:first');
			virtualVisit.tmp.currentHostelLink = $(this);
		}
		else{
			virtualVisit.tmp.currentHostel.hide();
			virtualVisit.tmp.currentHostelLink.removeClass('VVVostelItemActiv');
		}
		oTmpCurrent.show();
		$(oItem).addClass('VVVostelItemActiv');
		virtualVisit.tmp.currentHostel.find('.VVvideo').html('');
		virtualVisit.tmp.currentHostel = oTmpCurrent;
		virtualVisit.tmp.currentHostelLink = $(oItem);
	},
	changeImg:function(oItem, sSrc, bIsVideo){
		if(virtualVisit.tmp.currentHostel == null){
			virtualVisit.tmp.currentHostel = $('#virtualVisit').find('.virtualVisitDiapo:first');
			virtualVisit.tmp.currentHostelLink = $('#virtualVisit').find('.VVVostelItem:first');
		}

		if(bIsVideo){
			var sTplVideo = '<object style="position:absolute;" width="344" height="240" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab"><param name="src" value="'+ sSrc +'" /><param name="controller" value="true" /><param name="autoplay" value="true" /><embed src="'+ sSrc +'" width="344" height="240" controller="true" autoplay="true" scale="tofit" cache="true" pluginspage="http://www.apple.com/quicktime/download/"/></object>';
			virtualVisit.tmp.currentHostel.find('.VVvideo').html(sTplVideo);
		}
		else{
			virtualVisit.tmp.currentHostel.find('.VVvideo').html('');
			virtualVisit.tmp.currentHostel.find('img.bigImg').attr('src', sSrc);
		}
		virtualVisit.changeThumb(oItem);
	},
	changeThumb:function(oLink){
		virtualVisit.tmp.currentHostel.find('.thumbItemActiv').removeClass('thumbItemActiv');
		$(oLink).parent().addClass('thumbItemActiv')
	}
};


$(document).ready(function (){
	var klass = " ";
	switch(true){
		case $.browser.msie == true:
			klass += "isIE";
			klass += " isIE" + parseInt($.browser.version);
			break;
		case $.browser.mozilla == true:
			klass += "isFF";
			break;
		case $.browser.opera == true:
			klass += "isO";
			break;
		case $.browser.safari == true:
			klass += "isWK";
			break;
	}
	//
	document.documentElement.className += klass;
})

$(document).ready(function (){	
	// open onglet with QS
	if(QS()["tab"]){
		$("a[href=#"+QS()["tab"]+"]").click()
	}
})


var QS = function (){
	var qs = document.location.search.substr(1);
	var sp = qs.split("&");
	var o = {};
	for(var i = 0, l = sp.length;i<l;i++){
		var kv = sp[i].split("=");
		o[kv[0]] = kv[1];
	}
	return o;
}

