
// correctif bug ID - sur preventDefaut qd js click
function preventDefaultIEfix(e){
    if(e.preventDefault){ e.preventDefault()}
    else{ e.returnValue = false; }//IE
    //else{ e.stop() };
	e.returnValue = false;    
    e.stopPropagation();    
}

function openBlocFromUrl(url){
	if(WPpreview == ""){ // sauf si mode preview WP
		if(url == undefined)
		     url =  window.location +"" ;
		var match = new RegExp(WPhomeURL+"/", "ig"); // suprime l'url racine du site
		url =  url.replace(match, "");
		match= new RegExp("[/]+", "g"); // explose l'url restante 
		var tableau=url.split(match);
		var tablength = tableau.length;
		//	for (var i=0; i<tablength; i++){	alert( tablength+"elements , el"+i+" = "+tableau[i]); }		
		el0 = tableau[0]
		el1 = tableau[1]
		openPage(el0, el1);//, "actu-1-tst")
	}else{
		//alert("preview type : "+WPpreviewType)
		openPage(WPpreviewType, "");
	}
	/*
		// si lien est une ancre on scrole juste la page
		var linkPageName = $(this).attr('href');	
		var anchor = this.hash.slice(1);	
		//		alert( linkPageName + " / anchor : "+anchor);

		if( anchor.length &&  linkPageName == "#"+anchor ){ 
           	scrollToElement( $("#"+anchor) , 800 , function(){ window.location.hash = anchor  }); // // ajoute l'ancre dans l'url apres le scroll
		}else if (linkPageName.length){
			loadPageContent( linkPageName ) // pas d'ancre - le lien charge la page
      	}		 	
	*/
	// si 1er niveau : openPage avec id correspondante
}

function updateUrl(wantedUrl , wantedTitle, wnatedAnchor){
	if(WPpreview != ""){
		wantedTitle = "***PREVIEW***";
	}else{
		if( window.location != wantedUrl ){ // empeche de resoquer l'url ds l'historique
			// if(WPpreview != "") wantedUrl = wantedUrl + WPpreview;
			if(wantedTitle != "") wantedTitle = WPtitle + " - " + wantedTitle;	
			else wantedTitle = WPtitle;
			
//			window.history.pushState({"html":wantedUrl,"pageTitle":wantedTitle},"", wantedUrl); // HTML 5

			document.title = wantedTitle;
			// Todo : gestion des ancres
			// window.location.hash = catUrl ;
			// update traking analytics
			var match = new RegExp(WPhomeURL+"/", "ig"); // enleve le http://racine.com de l'url     
			url = "/"+ wantedUrl.replace(match, "");
			if (typeof _gaq !== "undefined" && _gaq !== null) _gaq.push(['_trackPageview', wantedUrl ]);
		}
	}
}
function initHistoryPopstate (){
/*
	// mise a jour de la page qd navig par historique browser (fleches)
	window.onpopstate = function(event) {  
		// recup la var html passé ds l'histo
		if(WPpreview == "")	 openBlocFromUrl( event.state.html);  
	};  
*/
}


// DESACTIVE - mise a jour tracking ds updateUrl suffisant
/*
function initAnlyticsAjaxTraking(){
  // Log all jQuery AJAX requests to Google Analytics
	$(document).ajaxSend(function(event, xhr, settings){ 
    if (typeof _gaq !== "undefined" && _gaq !== null) _gaq.push(['_trackPageview', settings.url]);
    else if (typeof pageTracker !== "undefined" && pageTracker !== null) pageTracker._trackPageview(settings.url); // ancien code anlytic
  });
}
*/  


// ------------

function initMenu(){
	$("#nav ul li a").click(function(e){
		preventDefaultIEfix(e);
		closeCurrentThenOpenPage($(this).attr("rel"));
		return false;
	});
	
	$("#logo a").click(function(e){
		preventDefaultIEfix(e);
		openPage("accueil");
		return false;
	});
	
	$("#footerContact, .goToGmap").click(function(e){ preventDefaultIEfix(e); closeCurrentThenOpenPage("contacts"); return false;});
	
	$("#mentionsBtn").click(function(e){
		preventDefaultIEfix(e);
		targetOffset = $("body").offset().top; $('html,body').animate({scrollTop: targetOffset}, 800, "easeOutCubic");
		openPage("mentions");
		return false;});	
	
	/*
	$("#blocInfoStatique #savoir-plus").click(function(){
		if($(this).attr('rel')=="interne"){
			openBlocFromUrl($(this).attr("href"));
			return false;
		}
	})
	*/
	
	// liens avec rel=interne ouvrent leur lien sur le site
	$("a[rel=interne]").click(function(e){
			preventDefaultIEfix(e);
			hrf = $(this).attr("href");
			if(hrf != undefined && hrf!="" && hrf!="#"){
			     targetOffset = 0; $('html,body').animate({scrollTop: targetOffset}, 800, "easeOutCubic");
				 openBlocFromUrl(hrf);			     
			}
			return false;	
	})
}

function initCloseBlocsBtn()
{
	$(".close a").click(function(e){
		preventDefaultIEfix(e);
		closeAll();
		$("#menu-accueil").addClass("current");
		return false;
	});
}

function closeCurrentThenOpenPage(pageID){
	if(pageID != $("#nav ul li a.current").attr("rel") ){ closeCurrent(pageID); } // si page demandee n'est pas la current
}

function closeCurrent(onpenBlocAfter){
	//	targetOffset = $("body").offset().top; $('html,body').animate({scrollTop: targetOffset}, 800, "easeOutCubic");
	currentBlocID = $("#nav ul li a.current").attr("rel");
	$("#nav ul li a.current").removeClass("current");		

	closeActusColumn();
	 $('#mentions').stop().slideUp(300); 	
		
	if(onpenBlocAfter == "references"){ // si ref: animes simultanees sauf si metier actuel
		if(currentBlocID == "metiers")
			closeBlocMetiers(onpenBlocAfter);
		else
		{
			$('#'+currentBlocID).slideUp(500);
			openPage(onpenBlocAfter); 
		}
	}
	else if(currentBlocID == "metiers"){
		closeBlocMetiers(onpenBlocAfter);
	}
	else if(currentBlocID == "accueil"){
		openPage(onpenBlocAfter);		
	}
	else if( currentBlocID != "references" && currentBlocID != undefined )
	{
		$('#'+currentBlocID).slideUp(500, function(){ openPage(onpenBlocAfter) } );
	}
	else // pas de bloc ouvert
	{
		// marche pas
		// if(currentPageId=="types_metier" || currentPageId=="fiche_metier") closeAll(onpenBlocAfter); // blocs sans menu
		
		openPage(onpenBlocAfter);
	}
}


// TODO WP+  toujour utiliser les meme id que le slug des pages wP pour plus de rétrocompatibilité
var currentPageId = "";
function openPage(pageID, subPageId, subSubPageId){
	
	if( pageID =="fiches_actu" ){ pageID ="fiche_actu"; }
	if( pageID =="fiches_metiers" ){ pageID ="fiche_metier"; }	
	

	
	closeActusColumn();	
	
	if(pageID != undefined){
		$("#nav ul li a.current").removeClass("current");		
		switch(pageID){
			// case undefined  :
			case "fiche_actu": 
					// si une id de fiche passée
					if(subPageId != undefined){
						//updateUrl( WPhomeURL+"/fiche_actu/"+subPageId+"/", "Actualite");
						$("#siteBackground").cycle(0); $("#content").slideDown(500);
						
						if( $("#actuSlide").children().length > 1 )
							$("#actuSlide").cycle(0); 
						
						openActuPage(subPageId);
					}// sinon passe sur accueil (au cas ou url manuelle)
					else{
						 openPage("accueil")
					}
					break
			case "accueil"     : updateUrl( WPhomeURL+"/", "Accueil"); $("#siteBackground").cycle(0); closeAll(); break;
			case "agence"      :
					updateUrl( WPhomeURL+"/agence/", "Agence"); $("#siteBackground").cycle(1);
					$("#content").slideDown(500);
					$("#agence #image-mini #slider ul").cycle(0);
					$('#agence').slideDown(500); break;			
			
			case "types_metier": 
				$("#siteBackground").cycle(2);
				if(subPageId != undefined){
					 updateUrl(  WPhomeURL+"/types_metier/"+subPageId+"/" , "Metiers" , null );
					 
					 //if(currentPageId == "types_metier") 
					 openBlocSelectionMetiers(subPageId, null, true);					 
					 //openMetiers(subPageId);
				}else{
					updateUrl(  WPhomeURL+"/metiers/", "Metiers" , null );
					openMetiers();
				}	
				break;
				
			case "fiche_metier": 
				$("#siteBackground").cycle(2);
				if(subPageId != undefined){
					updateUrl(  WPhomeURL+"/fiche_metier/"+subPageId+"/", "fiche metier" , null );
					// openMetiers("null", subPageId); // TODO - peut pas charger le menu on a pas encore la cat
					callFicheProjet(subPageId, true);
				}else{
					updateUrl(  WPhomeURL+"/metiers/", "Fiche metier" , null );
					openMetiers();
				}
				break;
					
			case "metiers"     : 
				
				updateUrl(  WPhomeURL+"/metiers/", "Metiers" , null );
				$("#siteBackground").cycle(2);
				openMetiers(subPageId, subSubPageId);
				break;
					
			case "references"  : updateUrl( WPhomeURL+"/references/", "References"); $("#siteBackground").cycle(3); $("#content").slideUp(500); break; // ferme juste bloc content (remonte recompenses)
			case "recompenses" : updateUrl( WPhomeURL+"/recompenses/", "Recompenses"); $("#siteBackground").cycle(4); $("#content").slideDown(500); $("#recompenses #image-mini #slider ul").cycle ; $('#recompenses').slideDown(500); break;
			case "contacts"    : updateUrl( WPhomeURL+"/contacts/", "Contacts"); $("#siteBackground").cycle(5); $("#content").slideDown(500); $('#contacts').slideDown(500); break;
			
			case "mentions" : updateUrl( WPhomeURL+"/mentions-legales/", "Mentions Légales"); $("#siteBackground").cycle(0); closeAll(); $("#content").stop().slideDown(500); $('#mentions').slideDown(500); break;
			
			default : 
				// $("#content").slideDown(500,"easeOutCubic"); $('#'+pageID).slideDown(500,"easeOutCubic"); 
				$("#content").slideDown(500); $('#'+pageID).slideDown(500); break;
		}
		currentPageId = pageID;
		
		if(pageID == "types_metier" || pageID=="fiche_metier" ) pageID = "metiers";// sous menu soulignent le menu
		else if(pageID == "fiche_actu") pageID = "accueil";
		$("#menu-"+pageID).addClass("current");
	}
}


function closeAll(onpenBlocAfter){
	//	targetOffset = $("body").offset().top; $('html,body').animate({scrollTop: targetOffset}, 800, "easeOutCubic");
	closeActusColumn();
	closeBlocMetiers();
	$("#nav ul li a.current").removeClass("current");	
	$('.pageBloc').not("#menu-metiers").slideUp(300);
	$('#mentions').stop().slideUp(300); 

	$("#content").slideDown(500);

	if( $("#actuSlide").children().length > 1 )
		$("#actuSlide").cycle(0);

	if(onpenBlocAfter == undefined || onpenBlocAfter == "" ) onpenBlocAfter = "accueil";
	else openPage(onpenBlocAfter);
}



function initActus()
{
    $("#actuCount").hide();
   
	if( $("#actuSlide").children().length > 1 ){
	    $("#actuSlide").cycle({
			timeout: 0 ,
			speed: 800,
			fx: "scrollUp",
			after:  function(curr,next,opts ){ var caption =  (opts.currSlide+1)+'/' +opts.slideCount; $('#actuCount').html(caption);},
	    });         
	    
		$(".fleche img").click(function(e){
			preventDefaultIEfix(e);
			//	if($("#actuSlide").height()<300)   // descativé -taille fixe
			//		openActusColumn(); // 1er lic ouvre
			//	else							 
			 $("#actuSlide").cycle("next");	// autres -> scroll
			return false;	
		});
	}
	$("#content #colonneActu #closeActuColum a").click(function(e){ preventDefaultIEfix(e); closeActusColumn(); return false;	});
	
	$(".actuSuite").click(function(e){ preventDefaultIEfix(e); openActuPage($(this).attr("rel")); return false; });
}

function openActusColumn(){
	////	targetOffset = $("#colonneActu").offset().top; $('html,body').animate({scrollTop: targetOffset}, 600, "easeOutCubic");
	$("#actuSlide").animate({height : "375px"},600); 
	$("#content #colonneActu #closeActuColum a").delay(200).animate({left:"45px", opacity:"1"}, 400, "easeOutBounce");
    $("#actuCount").fadeIn();
	if( $("#actuSlide").children().length > 1 )
	    $("#actuSlide").cycle(0);  
    $("#blocInfoStatique ").slideUp();
}

function closeActusColumn(){
	closeActuPage();
	//	targetOffset = $("body").offset().top; $('html,body').animate({scrollTop: targetOffset}, 500, "easeOutCubic");
	
/*	désactivé - la colonne est fixe etn'affiche plus que 2 actu a la fois
	$("#content #colonneActu #closeActuColum a").animate({left:"-100px", opacity:"0"}, 500 , "easeOutBounce");
	$("#actuSlide").animate({height : "180px"},600); // 1er lic ouvre
	$("#actuCount").fadeOut();
    $("#actuSlide").cycle(0);
    $("#blocInfoStatique ").slideDown();
*/    
}

function openActuPage(wantedActuSlug)
{
	if(WPpreview == "")
		updateUrl( WPhomeURL+"/fiche_actu/"+wantedActuSlug+"/", "Actualite");
	else
		updateUrl( WPhomeURL+"/fiche_actu"+wantedActuSlug+"/", "Actualite");

	$('#actualite').slideUp(500, "easeOutCubic", function(){ // ferme avant d'ouvrir
		$("#description #actuAjaxcontent").hide();
//		$("#content #actualite #description").fadeOut(400,function()
//		{
			$('#actualite  #description #actuAjaxcontent').empty();
			$('#actualite').slideDown(500);		
			
			if(WPpreviewType == "fiches_actu")
				actuUrl = WPpreview + "&ajaxcall=1";
			else
				actuUrl = WPhomeURL+"/fiche_actu/"+wantedActuSlug  + "/?ajaxcall=1";
			
			//actuUrl = WPhomeURL;
			//alert(actuUrl)
			
			$("#content #actualite #description #actuAjaxcontent").load( actuUrl , function(){
				// virer img loader
				$("#description #actuAjaxcontent").fadeIn();
				$("#content #actualite #description").fadeIn(300);
			});
//		})
	}); 
}

function closeActuPage(){
	$('#actualite').slideUp(400, function(){
//		$('#actualite').hide();

		$('#actualite #actuAjaxcontent').empty();
	});
//	updateUrl( WPhomeURL+"/", "");
}


function initSliders()
{	
	/* Slider images accueil #content */
	fistEvent = true;
	$("#sliderAccueil ul").cycle({
    	prev: ".prevAccueil",
    	next: ".nextAccueil",
		timeout: 0 ,
		speed: "slow",
		fx: "scrollHorz",
		easing: 'easeOutCubic',
		pager: ".thumbsSlideAccueil",
		before:  function(){ if(fistEvent) fistEvent = false; else  closeAll();  },
		pagerAnchorBuilder: function(idx, slide) { 
       		 // return selector string for existing anchor 
        	return '.thumbsSlideAccueil .bloc:eq(' + idx + ') .slideAccueilBtn'; 
    	}//,pagerEvent: null    	
    }); 
    
    $('.thumbsSlideAccueil .moreLnk').click(function(e){
		    preventDefaultIEfix(e);
			openBlocFromUrl( $(this).attr('rel') )
    	return false ;
    }); 
   
   /*
   if(isMobile)
   {

		document.addEventListener("orientationChanged", function(e){
			switch (e.orientation)
			{   
			    case -90:
			    case 90:
			   		$('#siteBackground').css({width:"1024px !important"});
			   		$('.siteBackgroundimg').css({width:"1024px !important"})
			        break;
			    default:
			   	//	$('#siteBackground').css({height:"1024px !important"});
			   	//	$('.siteBackgroundimg').css({height:"1024px !important"})
			        break;
			}
		});
		
   }
   else{
   		$('#siteBackground').css({width:"100% !important"});
   		$('.siteBackgroundimg').css({width:"100% !important"})   		
	}   
*/


	$("#siteBackground").cycle({
		timeout: 0 ,
		speed: 1000,
		fx: "fade",
		containerResize: false,
		slideResize: false				
    });




    if($("#sliderFooter ul").children().length > 1 ){
	    $("#sliderFooter").jCarouselLite({
	    	btnNext: "#footer #logos .next",
	    	btnPrev: "#footer #logos .prev",
	    	easing: "easeOutCubic",
	    	speed: "slow",
	    	visible: 1 
	    });
	}else{
		$( "#footer #logos .next").hide();
		$( "#footer #logos .prev").hide();		
	}
	
	    
    if($("#recompenses #image-mini #slider ul").children().length > 1 ){
		$("#recompenses #image-mini #slider ul").cycle({
	    	prev: "#content #recompenses #image-mini .prev",
	    	next: "#content #recompenses #image-mini .next",
			timeout: 0 ,
			speed: "slow",
			fx: "scrollHorz",
			easing: 'easeOutCubic',
	    });    
	}else{
	   $("#content #recompenses #image-mini .prev").hide();
	   $("#content #recompenses #image-mini .next").hide();
	}
	
    if($("#agence #image-mini #slider ul").children().length > 1 ){	
		$("#agence #image-mini #slider ul").cycle({
	    	prev: "#content #agence #image-mini .prev",
	    	next: "#content #agence #image-mini .next",
			timeout: 0 ,
			speed: "slow",
			fx: "scrollHorz",
			easing: 'easeOutCubic',
	    });     
	}else{
	   $("#content #agence #image-mini .prev").hide();
	   $("#content #agence #image-mini .next").hide();
	}
	    
}


/*------------------ Slider images de #agence ------------------*/        
//	btnNext: "#content #agence #image-mini .next",  btnPrev: "",

/*---------------- Slider images de #recompenses ---------------*/        
//	btnNext: "#content #recompenses #image-mini2 .next",	btnPrev: "#content #recompenses #image-mini2 .prev",



function initMenuMetiers()
{
	// pos initiales des elements "fermés"
	$("#accueil-metiers").css({top:"-336px"});
	$("#tiroirMenuProjets #menuProjets").css({right:"-250px"});	

	$("#content #metiers #metierDrawer #tiroirMenuProjets #menuProjets .closeX a #closeImg").animate({opacity:0});
	$("#tiroirMenuProjets #menuProjets #listeProjets").css({height: "0"})

	$("#bloc-selection-metiers .left #metiersSlideHolder").css({opacity:"0"});

	$("#bloc-selection-metiers .left #metiersSlideHolder .prev").css({left:"-50px"});
	$("#bloc-selection-metiers .left #metiersSlideHolder .next").css({left:"400px"});

	$("#nav-metiers ul li a").click(function(e){
		preventDefaultIEfix(e);
		// TODO : Psser le select current ds la fction qui ouvre le bloc plutot (si appel exterieur par url)
		$("#nav-metiers ul li a.current").removeClass("current"); $(this).addClass("current");
		metierID = $(this).attr("rel")
		openBlocSelectionMetiers( metierID  );
		return false;
	})
	
	$("#accueil-metiers .box .nos-real").click(function(e){
		preventDefaultIEfix(e);
		relMenuref = $("#nav-metiers ul li #"+ $(this).attr("rel") )
		openBlocSelectionMetiers( metierID = relMenuref.attr("rel") );
		return false;
	})
	
	$("#bloc-selection-metiers .closeX a").click(function(e){
		preventDefaultIEfix(e);
		closeBlocSelectionMetiers();
		return false;
	});
	
}

function openMetiers( metierID ){
	$("#content").slideDown(500);//reouvre apres reference
	$("#metiers").show();
	
	$("#bloc-accueil-metiers").show().slideDown();
	$("#bloc-selection-metiers").slideUp();	
	
	$("#nav-metiers").slideDown(600, "easeOutCubic");
	$("#accueil-metiers ").animate({top:"0"},600);
	
	if( metierID != undefined && metierID != "")
		openBlocSelectionMetiers(metierID);
}

function closeBlocMetiers(openAfter)
{
	//	$("#nav-metiers ul li a.current").removeClass("current"); // déjà dans closeBlocSelectionMetiers
	$("#nav-metiers").slideUp(400, "easeOutCubic", function(){openPage(openAfter);} )
	$("#accueil-metiers ").delay(200).animate({top:"-336px"}, 500, function(){$("#metiers").hide();})
	closeBlocSelectionMetiers();		
}

function openBlocSelectionMetiers(metierID, openedFromFiche, fromUrl){

	if(openedFromFiche || fromUrl){
		$("#content").slideDown(0);//reouvre apres reference
		// referme métiers accueil	
		$("#metiers").fadeIn(200);	
		$("#bloc-accueil-metiers").hide()//.slideUp(0);
		
		$("#bloc-selection-metiers").slideDown(200);//.show();
		$("#nav-metiers").show()//.slideDown(0);		
		$("#accueil-metiers ").css({top:"0"});		
	}
	
	//  surligner btn du menu correspondant en fonction de son rel
	$("#nav-metiers ul li a.current").removeClass("current");
	relMenuref = $("#nav-metiers ul li a[rel="+ metierID+"]" )	
	relMenuref.addClass("current");
	
	// adresse de la liste des cat a chager
	catUrl = WPhomeURL+"/types_metier/"+metierID ;	

	$("#content").animate({marginBottom : "40px"}, 300);
	
	if(openedFromFiche == undefined || fromUrl){
		// referme métiers accueil	
		$("#bloc-accueil-metiers").slideUp(300);
		// met à jour l'url en js (avec vraie adresse) si pas deja fait
		updateUrl( catUrl, metierID , null )
	};

	$("#bloc-selection-metiers").slideDown(300, function()
	{
		if(openedFromFiche != undefined )speed=0;else speed =400;	// PAtch - se bloque sinon qd ouverture from fiche meme si deja a 0
		$("#bloc-selection-metiers .left #metiersSlideHolder").animate({opacity:"0"}, speed, function()
		{
			clearCatBlocThumbs();//vire les vignetes si affichees

			// ferme tiroir (vers drte si ouvert)
			$("#tiroirMenuProjets #menuProjets").animate({right:"0"},500, "easeOutCubic", function()
			{
				// ferme tiroir (vers haut)
				$("#tiroirMenuProjets #menuProjets #listeProjets").slideUp(400, "easeOutCubic", function()
				{
					$("#listeProjets .blocListe a.actif").removeClass("actif");			

					// afficher loader a la place de la croix
					$("#content #metiers #metierDrawer #tiroirMenuProjets #menuProjets .closeX a #closeImg").animate({opacity:0});
					$("#content #metiers #metierDrawer #tiroirMenuProjets #menuProjets .closeX a #loadImg").animate({opacity:1});

					// detruit slide précédent
				   	$("#listeProjets").cycle("destroy");
					// supprime ancien contenu
					$("#tiroirMenuProjets #menuProjets #listeProjetsAjaxHolder").empty(); // charge conenu avant et utiliser replace() plutot ? gagne quelques ms.//
	
					// load  du slide de la cat demandée
					
//				if(WPpreviewType == "fiches_metiers") catUrl = catUrl+"/"+WPpreview + "&ajaxcall=1";
//				else								  catUrl = catUrl  + "/?ajaxcall=1";
					catUrl = catUrl  + "/?ajaxcall=1";
					
					$("#tiroirMenuProjets #menuProjets #listeProjetsAjaxHolder").load( catUrl, function()
					{
						// regénerre le slide			
					    $("#listeProjets").cycle({
							timeout: 0 ,
							speed: 1000,
							fx: "scrollUp",
							easing: 'easeOutCubic',
							after:  function(curr,next,opts ){ var caption =  (opts.currSlide+1)+'/' +opts.slideCount; $('#blocListePCount').html(caption);},
					    });         
				
						// TODO ? : si nbre de div blocListe <2 masque le btn suivant
						$("#tiroirMenuProjets #menuProjets #scrollListeProjets img").click(function(e){
							preventDefaultIEfix(e);
							$("#listeProjets").cycle("next");	// autres -> scroll
							return false;	
						});				
						// remet la hauteur du tiroir chargé à 0
						$("#tiroirMenuProjets #menuProjets #listeProjets").hide();
					
						// la liste est chargée - réouvre tirroir
						$("#tiroirMenuProjets #menuProjets #listeProjets").slideDown(400, "easeOutCubic");
					
						// affiche croix fermeture
						$("#content #metiers #metierDrawer #tiroirMenuProjets #menuProjets .closeX a #closeImg").animate({opacity:1});
						$("#content #metiers #metierDrawer #tiroirMenuProjets #menuProjets .closeX a #loadImg").animate({opacity:0});
					
						// init btns de la liste
						$("#listeProjets .blocListe a").click(function(e){
							preventDefaultIEfix(e);
							if(	$("#listeProjets .blocListe a.actif") != $(this)) callFicheProjet($(this).attr("rel"));				
							return false;
						})
						
						// charger le 1er slide projet de la cat que l'on viens d'ouvrir
						//callFicheProjet( $("#tiroirMenuProjets #menuProjets #listeProjets .blocListe:first a:first").attr('rel') )
						// callFicheBlocThumbs( $("#tiroirMenuProjets #menuProjets #listeProjets .blocListe:first a:first").attr('rel') )
						
						if(openedFromFiche == undefined)
							showCatBlocThumbs(); // ne pas le faire si on charge directement une fiche depuis l'url
						else
							selectListIdBtn(openedFromFiche);
					});
				});
			});
		});
	})
}

function selectListIdBtn(ficheId){
	$("#listeProjets .blocListe a.actif").removeClass("actif");
	$("#listeProjets .blocListe a[rel="+ficheId+"]").addClass("actif");
}



// charge les 8 thumbs a louverture de la page affichant les fiches
function showCatBlocThumbs(){
	// copie les vignettes recuperrées avec le menu et les replace dans le bon ajaxHoler
	$('#content #metiers #metierDrawer .real .left  #vignetteAjaxHolder').animate({opacity:0}, function(){
		$('#content #metiers #metierDrawer .real .left  #vignetteAjaxHolder #vignette').replaceWith($('#tempvignettes #vignette'));
		$('#content #metiers #metierDrawer .real .left  #vignetteAjaxHolder').show().animate({opacity:1});
		$('#content #metiers #metierDrawer .real .left  #vignetteAjaxHolder #vignette .bloc').click(function(e){
			preventDefaultIEfix(e);
			$(this).siblings().animate({opacity:"0"}, 200 );
			$(this).delay(200).animate({opacity:"0"}, 500 , function(){
				callFicheProjet( $(this).attr("rel") ); 				
			});
			return false;
		});
	});	
}
function clearCatBlocThumbs(){
	// copie les vignettes recuperrées avec le menu et les replace dans le bon ajaxHoler
	$('#content #metiers #metierDrawer .real .left  #vignetteAjaxHolder').animate({opacity:0}, 150, function(){
		$('#content #metiers #metierDrawer .real .left  #vignetteAjaxHolder').hide();
		$('#content #metiers #metierDrawer .real .left  #vignetteAjaxHolder #vignette').empty();	
	});
}

function callFicheProjet(ficheId, isOpenedBeforeListe){

	if( isOpenedBeforeListe ){
		$("#content").slideDown(0);//reouvre apres reference
		// referme métiers accueil	
		$("#metiers").fadeIn(200);	
		$("#bloc-accueil-metiers").hide()//.slideUp(0);
		
		$("#bloc-selection-metiers").slideDown(200);//.show();
		$("#nav-metiers").show()//.slideDown(0);		
		$("#accueil-metiers ").css({top:"0"});		
	}

	// emplacement fiche pour url et chargment
	ficheUrl = WPhomeURL+"/fiche_metier/"+ficheId ;

	// met url a jour
	updateUrl( ficheUrl, "fiche metier") // todo mettre a jour le titre apres le chargement

	// TODO METRE UN LOADR DANS LA PARTIE GAUCHE PUTOT QUE R2UTILISER CELI DE LA LISTE
	$("#content #metiers #metierDrawer #tiroirMenuProjets #menuProjets .closeX a #closeImg").animate({opacity:1});
	$("#content #metiers #metierDrawer #tiroirMenuProjets #menuProjets .closeX a #loadImg").animate({opacity:0});

	// surligne le btn orrespondant dans la liste ayant cet id en rel

	selectListIdBtn(ficheId)

	$('#content #metiers #metierDrawer .real .left  #vignetteAjaxHolder').animate({opacity:0},100, "easeOutCubic",function(){
		$('#content #metiers #metierDrawer .real .left  #vignetteAjaxHolder').hide();
		$('#content #metiers #metierDrawer .real .left  #vignetteAjaxHolder #vignette').empty();
		
		
		//sortie des fleches si ouvertes
		showSlideArrows = false;
		$("#bloc-selection-metiers .left #metiersSlideHolder .prev").stop().animate({left:"-50px"}, 400, "easeOutCubic");
		$("#bloc-selection-metiers .left #metiersSlideHolder .next").stop().animate({left:"400px"}, 400, "easeOutCubic");
		
		$("#bloc-selection-metiers .left #metiersSlideHolder .prev a").css({opacity:"1"}).animate({opacity:"0"}, 400, function(){$(this).hide();});
		$("#bloc-selection-metiers .left #metiersSlideHolder .next a").css({opacity:"1"}).animate({opacity:"0"}, 400, function(){ 
			$(this).hide()
			// masque slide précédent
			$("#bloc-selection-metiers .left #metiersSlideHolder").animate({opacity:"0"}, 200, function(){
				// detruit slide précdédent

				$("#bloc-selection-metiers .left #metiersSlideHolder #contenuSlideFicheMetier .ytFrame").empty();
			 
			  	$("#bloc-selection-metiers .left #metiersSlideHolder #contenuSlideFicheMetier").cycle("destroy");
				// vide la div
				$("#bloc-selection-metiers .left #metiersSlideHolder #conteneurSlideFicheMetierAjax").empty();
				// affiche le loader
				$("#content #metiers #metierDrawer .real .left .loader").fadeIn();				
				// recuperrer le contenu du slide
				if(WPpreviewType == "fiches_metiers") ficheUrl = WPpreview + "&ajaxcall=1";
				else								 ficheUrl = ficheUrl  + "/?ajaxcall=1";
				
				$("#bloc-selection-metiers .left #metiersSlideHolder #conteneurSlideFicheMetierAjax").load( ficheUrl , function()
				{
				   	if(isOpenedBeforeListe)// && WPpreview=="")
				   	{
					   	// charge la colonne de la liste des termes si pas déja fait (cas ouverture directe de fiche)
					   	// terme stoke dans la liste de la fiche loadée
					   	term = $("#bloc-selection-metiers .left #metiersSlideHolder #contenuSlideFicheMetier").attr('rel');
					   	openBlocSelectionMetiers(term, ficheId);
					}	   	
				   
				   	// contenu chagé on init le js si + d'un contenu
					if( $("#bloc-selection-metiers .left #metiersSlideHolder #contenuSlideFicheMetier").children().length > 1 ){
					
					    $("#bloc-selection-metiers .left #metiersSlideHolder #contenuSlideFicheMetier").cycle({
							startingSlide: 0,
							timeout: 0 ,
							speed: 1000,
							fx: "scrollHorz",
							//containerResize: true,
							//slideResize: true,
							//fit:0,
							height: '485px',
							width:  '750px',							
					    	prev: "#bloc-selection-metiers .left #metiersSlideHolder .prev a",
	    					next: "#bloc-selection-metiers .left #metiersSlideHolder .next a",
							easing: 'easeOutCubic',
							after:  function(curr,next,opts ){
								$('#content #metiers #metierDrawer .real .left  #metiersSlideHolder  #imgTextHolder #imgTextBloc').animate({bottom:"-50px"}, 200, function(){
									wantedText = $("#tempTextesImgTxt .txt"+opts.currSlide).text() ;
									if( wantedText != undefined && wantedText !="")
									{
										//$('#content #metiers #metierDrawer .real .left  #metiersSlideHolder  #imgTextHolder #imgTextBloc p').replaceWith( $("#tempTextesImgTxt .txt"+opts.currSlide));
										$('#content #metiers #metierDrawer .real .left  #metiersSlideHolder  #imgTextHolder #imgTextBloc p').html( wantedText );
										$('#content #metiers #metierDrawer .real .left  #metiersSlideHolder  #imgTextHolder #imgTextBloc').animate({bottom:"0"},200);
									}else{
										$('#content #metiers #metierDrawer .real .left  #metiersSlideHolder  #imgTextHolder #imgTextBloc p').text("");
									}
								});
								//var caption =  (opts.currSlide+1)+'/' +opts.slideCount; $('#blocListePCount').html(caption);
							},
					    });         
					  //  !!! bug si recharge slide  
					  //  $("#bloc-selection-metiers .left #metiersSlideHolder .prev a").click(function(){ $("#bloc-selection-metiers .left #metiersSlideHolder ul").cycle("prev")  ;return false;})
					  //  $("#bloc-selection-metiers .left #metiersSlideHolder .next a").click(function(){ $("#bloc-selection-metiers .left #metiersSlideHolder ul").cycle("next")  ;return false;})
						showSlideArrows = true;
					}
					
					// enleve loader
					$("#content #metiers #metierDrawer .real .left .loader").fadeOut(200);
					// réaffiche le slide
					$("#bloc-selection-metiers .left #metiersSlideHolder").animate({opacity:"1"}, 200, function(){
					
						// entree des fleches
						$("#bloc-selection-metiers .left #metiersSlideHolder .prev a").show().css({opacity:"1"});
						$("#bloc-selection-metiers .left #metiersSlideHolder .next a").show().css({opacity:"1"});
						
						if(showSlideArrows){
							$("#bloc-selection-metiers .left #metiersSlideHolder .prev").stop().animate({left:"0"},200, "easeOutCubic")
							$("#bloc-selection-metiers .left #metiersSlideHolder .next").stop().animate({left:"350px"},200, "easeOutCubic")	
						}
					}) ;			
				});
			});		
		});
	});
}

function closeBlocSelectionMetiers(){
	//	targetOffset = $("body").offset().top; $('html,body').animate({scrollTop: targetOffset}, 800, "easeOutCubic");

	$("#bloc-selection-metiers .left #metiersSlideHolder .prev").stop().animate({left:"-50px"}, 200, "easeOutCubic")
	$("#bloc-selection-metiers .left #metiersSlideHolder .next").stop().animate({left:"400px"}, 200, "easeOutCubic")

	$("#bloc-selection-metiers .left #metiersSlideHolder .prev a").show().stop().animate({opacity:"0"}, 200, function(){ $(this).hide(); });
	$("#bloc-selection-metiers .left #metiersSlideHolder .next a").show().stop().animate({opacity:"0"}, 200, function(){

		$(this).hide();

		// detruitre slide fiche précédent	
		$("#bloc-selection-metiers .left #metiersSlideHolder").animate({opacity:"0"}, 200, function(){
		  	$("#bloc-selection-metiers .left #metiersSlideHolder #contenuSlideFicheMetier").cycle("destroy");
			$("#bloc-selection-metiers .left #metiersSlideHolder #conteneurSlideFicheMetierAjax").empty();
		});

		clearCatBlocThumbs();

		$("#tiroirMenuProjets #menuProjets #listeProjets").slideUp(400, function(){
			// detruitre slide liste précédent
		   	$("#listeProjets").cycle("destroy");
			$("#tiroirMenuProjets #menuProjets #listeProjets").empty(); // charge conenu avant et utiliser replace() plutot ? gagne quelques ms.//
		
		});
	});

	$("#content").animate({marginBottom:"0"}, 400); // recale footer
	$("#tiroirMenuProjets #menuProjets").delay(200).animate({right:"-250px"},400, "easeOutCubic")	
	
	$("#listeProjets").cycle(0);
	$("#listeProjets .blocListe a.active").removeClass("active");
	// virer le slide projet
	// + le détruire	
		
	$("#bloc-accueil-metiers").delay(400).slideDown();
	$("#bloc-selection-metiers").delay(400).slideUp();
	$("#nav-metiers ul li a.current").removeClass("current");	
	
	if(currentPageId == "types_metier" || currentPageId =="fiche_metier" ) 
	{	currentPageId = "metiers";// sous menu soulignent le menu
		updateUrl(  WPhomeURL+"/metiers/", "Metiers" , null );
	}
}


/* DOC READY */
var isMobile = false;
$(document).ready(function() {

	switch(navigator.platform)
	{
		case 'iPad': isMobile= true   ;break;
		case 'iPhone': isMobile= true ;break;
		case 'iPod': isMobile= true ;break;					
		default : isMobile= false ;		
	}		
	
	if(isMobile){
		initMobileBehaviours();
		img = $('#siteBackground img[rel=1]').attr("src");
		$("body").css("background-image", "url(http://okgo.fr/WIP/LaSolution/WIP/wp-content/themes/lasolution/img/src/bg/bg1.jpg)");
		$('#siteBackground').hide();
	}else{
		$('#siteBackground').css({display:"block", opacity:"0"}).animate({opacity:"1"},1000);   
   		$('#siteBackground').css({width:"100% !important"});
   		$('.siteBackgroundimg').css({width:"100% !important"})   		
	} 

	initMenu();
	initActus();
	initMenuMetiers();	
	initCloseBlocsBtn();
	initSliders();
	// initAnlyticsAjaxTraking(); // dans update url suffisant
	openBlocFromUrl();
	
	initHistoryPopstate();
	
});




function initMobileBehaviours(){
	updateOrientation();
	window.addEventListener("orientationchange", updateOrientation, false);
}


function hideUrlBar(){
	setTimeout(function() {
		window.scrollTo(0, 1);
	}, 500);
}


function updateOrientation(){
	
	hideUrlBar();
	window.scrollTo(0, 1);

	var orientation = window.orientation;
	switch (orientation) {
			case 90:
			case -90:
			 //  	$('#siteBackground').css({width:"1024px !important", height:"768px !important"});
			  // 	$('.siteBackgroundimg').css({width:"100% !important", height:"auto !important" })   					   		
			   	//	$('#siteBackground').css({width:"100% !important", height:"auto", overflow:"hidden"});
			   	//	$('.siteBackgroundimg').css({width:"1024px !important",  })
			   	//	$('#siteBackground').css({height:"1024px !important"});
			   	//	$('.siteBackgroundimg').css({height:"1024px !important"})
//			   		$('meta[name=viewport]').attr("content")="width=100,  user-scalable=yes"; // height=device-height, 
				break;	
			case 0 :
			default:
		//	   	$('#siteBackground').css({height:"1024px !important", width:"768px !important"});			
		//	   	$('.siteBackgroundimg').css({height:"100% !important", width:"auto !important" })   		
			   	
//		   		$('#siteBackground').show().css({height:"1024px !important", width:"auto", display:"block", overflow:"hidden" });
//	  			$('.siteBackgroundimg').css({height:"1024px !important", width:"auto  !important" })   	
//				$('meta[name=viewport]').attr("content")="width=50,  user-scalable=yes"; // height=device-height, 	
			break;
		}
		
//alert(  $('meta[name=viewport]').attr("content")  )


// $('meta[name=viewport]').attr("content") = "width=device-width, minimum-scale=0.25, maximum-scale=1.6, user-scalable=yes"
/*
var e = window
, a = 'inner';
if ( !( 'innerWidth' in window ) )
{
a = 'client';
e = document.documentElement || document.body;
}
alert( e[ a+'Width' ] +" / "+  e[ a+'Height' ] )
*/


}

  	hideUrlBar();
	window.scrollTo(0, 1);


