var promoPage = {
	currentCarID : "",
	currentCarURL : "",
	currentMenuPos: 0,
	nextMenuPos: 0,
	posxCar:"274px",
	previousCarURL : "",
	nextCarURL : "",
	carURL : "",
	carElements : ['#fond .aside ul', '#fond .voirPub', '#fond .voirMentions', '#fond .modelePresente', '#fond .demandeEssai', '#fond .financement', '#fond .bonusEco', '#fond .casseOuReprise', '#fond .autreAvantageClient', '#fond .avantages .avantageClient', '#fond .offrePrix + small', '#fond .offrePrix', '#fond .menuGamme', '#fond .equipements li']
};
var	isNavigating = false,
	menuActiveItemIsChanged =  false,
	arrayCarElements = [],
	previousOrNext = '',
	slideGoValue = '',
	slideComeValue = '',
	isTransitionRuning = false,
	liPrev,
	liNext,
	liFirst,
	liLast;

function initPlaceholders() {
	if(!$("#placeHolder").length) {
		var $placeHolder = $('<div id="placeHolder"></div>');
		$('body').append($placeHolder);
		$placeHolder.hide();
		//$("#placeHolder").detach();
	}
}

function initPageContext(firstTime) {
	if(firstTime) {
		if($("body").attr("id") != undefined) promoPage.currentCarID = $("body").attr("id");
	} else {
		if(menuActiveItemIsChanged) {
			promoPage.currentCarID = $("#mainNav .active").attr("rel");
		} else if(currentPage == 'homeParticuliers' || currentPage == 'homeEntreprise') {
			promoPage.currentCarID = '';
		}
		$('body').attr('id',promoPage.currentCarID);
	}
	
	if(currentPage == 'page') {
		var isSliderClass = (sliderNav!=undefined)? '.pager':'';
		
		var activeNavButton = $('#mainNav '+isSliderClass+' .active');
		liPrev = activeNavButton.parent('li'+isSliderClass).prev(isSliderClass);
		liNext = activeNavButton.parent('li'+isSliderClass).next(isSliderClass);
		liFirst = activeNavButton.parents('ul').find('li'+isSliderClass+':first');
		liLast = activeNavButton.parents('ul').find('li'+isSliderClass+':last');
		promoPage.previousCarURL = (liPrev.length)? liPrev.find("a").attr("href") : liLast.find("a").attr("href");
		promoPage.nextCarURL = (liNext.length)? liNext.find("a").attr("href") : liFirst.find("a").attr("href");
	}
}

function prepareAnimation(href) {
	if(!isMobile){
		cacherEquipements();
		arrayCarElements = $(promoPage.carElements.join(',')).get();
		if($('#fond .presentationVehicule h3 img').length) promoPage.posxCar = $('#fond .presentationVehicule h3 img').css('left');
		switch(previousOrNext) {
			case 'previous' :
				slideGoValue = (parseInt(promoPage.posxCar)+550)+'px';
				slideComeValue = (parseInt(promoPage.posxCar)-550)+'px';
				break;
			case 'next' :
				slideGoValue = (parseInt(promoPage.posxCar)-550)+'px';
				slideComeValue = (parseInt(promoPage.posxCar)+550)+'px';
				break;
			default :
				if(menuActiveItemIsChanged) {
					if(promoPage.nextMenuPos - promoPage.currentMenuPos > 0) {
						slideGoValue = (parseInt(promoPage.posxCar)-550)+'px';
						slideComeValue = (parseInt(promoPage.posxCar)+550)+'px';
					} else {
						slideGoValue = (parseInt(promoPage.posxCar)+550)+'px';
						slideComeValue = (parseInt(promoPage.posxCar)-550)+'px';
					}
				} else {
					slideGoValue = promoPage.posxCar;
					slideComeValue = promoPage.posxCar;
				}
				break;
		}
		
		makeThemGo(href);
	}
	
	else loadPlaceholder(href);
	
}

function loadPlaceholder(href) {
	$('#loadingImg').fadeIn('fast',function(){
		$("#placeHolder").load(href+" title, meta[name='keywords'], meta[name='description'], #fond", function(){
			$('#loadingImg').fadeOut('slow',function(){
				switchContents(href);
			});
		});
	});
}

function makeThemGo(href) {
	if(arrayCarElements.length!=0) {
		if(jQuery.browser.msie && jQuery.browser.version < 9) {
			$(arrayCarElements[arrayCarElements.length-1]).fadeOut(50,function(){
				arrayCarElements.pop();
				makeThemGo(href);
			});
		}else{
			$(arrayCarElements[arrayCarElements.length-1]).slideUp(50,function(){
				arrayCarElements.pop();
				makeThemGo(href);
			});
		}
	} else {
		if(jQuery.browser.msie && jQuery.browser.version < 9) {
			if($('#fond .presentationVehicule h3 img').length) $('#fond .presentationVehicule h3 img').css({left:'10000px'});
			loadPlaceholder(href);
		}else {
			if($('#fond .presentationVehicule h3 img').length) {
				$('#fond .presentationVehicule h3 img').animate({
					left:slideGoValue,
					opacity:0
				},{
					duration:300,
					easing:'easeInQuart',
					complete:function(){
						
						loadPlaceholder(href);
						
					}
				});
			} else {
				$('#fond .content').animate({
					opacity:0
				},{
					duration:300,
					easing:'easeInQuart',
					complete:function(){
						
						loadPlaceholder(href);
						
					}
				});
			}
		}
	}
}

function switchContents(href) {
	
	$("head title").replaceWith($("#placeHolder title"));
	$("head meta[name='keywords']").replaceWith($("#placeHolder meta[name='keywords']"));
	$("head meta[name='description']").replaceWith($("#placeHolder meta[name='description']"));
	$('#masque').first().replaceWith($('#placeHolder #masque'));

	if($('.ctaOffre').length) {
		if($('.ctaOffre[rel^="entreprise"]').length) {
			currentPage = 'homeEntreprise';
			$('body').removeClass().addClass('entreprise');
		} else {
			currentPage = 'homeParticuliers';
			$('body').removeClass().addClass('home');
		}
	} else {
		currentPage = 'page';
		$('body').removeClass().addClass('page');
	}
	
	buidNav();
		
	$("#mainNav li").each(function(i){
		if($(this).has('.active').length) promoPage.currentMenuPos = i;
	});
	
	if(currentPage == 'page') {
		if($('#pagination:hidden').length) $('#pagination').fadeIn();
	} else {
		$('#pagination').fadeOut();
		$('#fond .content').css({opacity:0});
	}
	
	if(isMobile){
		$('.menuGamme h2 img').attr('src', '/static/images/fleche-menu-mobile.png');
		$('ul.equipements').prepend("<p class='yellow'>ÉQUIPEMENTS</p>");
		$('ul.equipements li p').each(function(){
			var val = $(this).text();
			if(val.indexOf('-')!=-1)$(this).text(val.substring(1,val.length));
		});
	}
		
	if(currentPage == 'page') {
		
		hideAndPositioning();
		initPageContext();
		
		if(isNavigating && !isMobile) History.pushState({carId:promoPage.currentCarID}, null, href);
		
		arrayCarElements = $(promoPage.carElements.join(',')).hide().get();
		$('#fond .presentationVehicule h3 img').css({left:slideComeValue,opacity:0});
		if(jQuery.browser.msie && jQuery.browser.version < 9) {
			$('#fond .presentationVehicule h3 img').css({left:promoPage.posxCar,opacity:1});
			makeThemCome();
		} else {
			$('#fond .presentationVehicule h3 img').animate({
				opacity:1,
				left:promoPage.posxCar
			},{
				duration:300,
				easing:'easeOutQuart',
				complete:function(){
					
					makeThemCome();
					
				}
			});
		}
	} else {
		
		hideAndPositioning();
		initPageContext();
		
		if(isNavigating && !isMobile) {
			History.pushState({carId:promoPage.currentCarID}, null, href);
		}
		
		if(jQuery.browser.msie && jQuery.browser.version < 9) {
			isTransitionRuning = false;
			$('#fond .content').css({opacity:1});
		} else {
			$('#fond .content').animate({
				opacity:1
			},{
				duration:300,
				easing:'easeInQuart',
				complete:function(){
						
					isTransitionRuning = false;
						
				}
			});
		}
		
	}
}
	
function makeThemCome() {
	if(arrayCarElements.length) {
		if(jQuery.browser.msie && jQuery.browser.version < 9) {
			$(arrayCarElements[arrayCarElements.length-1]).fadeIn(50,function(){
				arrayCarElements.pop();
				makeThemCome();
			});
		} else {
			$(arrayCarElements[arrayCarElements.length-1]).slideDown(50,function(){
				arrayCarElements.pop();
				makeThemCome();
			});
		}
	} else {
		isTransitionRuning = false;
	}
}

function backToHome(url) {
			isNavigating = true;
			menuActiveItemIsChanged = false;
			if(jQuery.browser.msie && jQuery.browser.version < 9) {
				$('#pagination').hide();
				$('#fond .content').css({opacity:0});
				loadPlaceholder(url);
			} else {
				$('#pagination').fadeOut(function(){
				});
				$('#fond .content').animate({
					opacity:0
				},{
					duration:300,
					easing:'easeInQuart',
					complete:function(){
						loadPlaceholder(url);
						
					}
				});
			}
}


(function(window,undefined){
	if(!isMobile) {
		// Prepare
		var History = window.History; // Note: We are using a capital H instead of a lower h
		if ( !History.enabled ) {
			 // History.js is disabled for this browser.
			 // This is because we can optionally choose to support HTML4 browsers or not.
			return false;
		}
	
		// Bind to StateChange Event
		History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
			var State = History.getState(); // Note: We are using History.getState() instead of event.state
			if(!isNavigating) {
				promoPage.carURL = State.url;
				promoPage.currentCarID = State.data.carId;
				if(!isMobile) isTransitionRuning = true;
				previousOrNext='';
				menuActiveItemIsChanged = false;
				var urlArray = promoPage.carURL.split('/');
				
				if(promoPage.carURL != rootPath) { // si on est pas revenu à la home
					prepareAnimation(promoPage.carURL);
				} else {
					backToHome(promoPage.carURL);
				}
			}
			isNavigating = false;
		});
	}
})(window);



$(document).ready(function($) {
	
	$("#mainNav li").each(function(i){
		if($(this).has('.active').length) promoPage.currentMenuPos = i;
	});
	
	if(sliderNav!=undefined) {
		if(promoPage.currentMenuPos>9) sliderNav.goToSlide(promoPage.currentMenuPos-9);
	}
	
	initPlaceholders();
	initPageContext(true);
		
	$("#pagination a").live('click',function(e){
		if(!isTransitionRuning) {
			if(!isMobile) isTransitionRuning = true;
			menuActiveItemIsChanged = true;
			isNavigating = true;
			previousOrNext = $(this).attr("id");
			prepareAnimation(promoPage[previousOrNext+'CarURL']);
		}
		e.preventDefault();
	});
	
	$(".vehiculeHP .ctaOffre").live('click',function(e){
		if(!isTransitionRuning) {
			if(!isMobile) isTransitionRuning = true;
			menuActiveItemIsChanged = true;
			isNavigating = true;
			previousOrNext='';
			promoPage.carURL = $(this).attr('href');
			
			var $eqInNav = $("#mainNav li a:[rel='"+$(this).attr('rel')+"']");
			promoPage.nextMenuPos = $eqInNav.parent('li').index();
			
			if(!isMobile){
				if(promoPage.carURL.length>4) prepareAnimation(promoPage.carURL);
			}
		}
		if(!isMobile) e.preventDefault();
	});
	
	$("#mainNav h2 a").live('click',function(e){
		if(!isTransitionRuning) {
			if(!isMobile) isTransitionRuning = true;
			menuActiveItemIsChanged = true;
			isNavigating = true;
			previousOrNext='';
			promoPage.carURL = $(this).attr('href');
			
			var $eqInNav = $("#mainNav li a:[rel='"+$(this).attr('rel')+"']");
			promoPage.nextMenuPos = $eqInNav.parent('li').index();
			
			if(!isMobile){
				if(promoPage.carURL.length>4) prepareAnimation(promoPage.carURL);
				else backToHome(promoPage.carURL);
			}
		}
		if(!isMobile) e.preventDefault();
	});
	
	$("#mainNav li a").live('click',function(e){
		if(!isTransitionRuning) {
			if(!isMobile) isTransitionRuning = true;
			menuActiveItemIsChanged = true;
			isNavigating = true;
			previousOrNext='';
			promoPage.carURL = $(this).attr('href');
			
			promoPage.nextMenuPos = $(this).parent('li').index();
			
			if(!isMobile){
				if(promoPage.carURL.length>4) prepareAnimation(promoPage.carURL);
			}
		}
		if(!isMobile) e.preventDefault();
	});
	
	$("#fond .menuGamme ul a").live('click',function(e){
		if(!isTransitionRuning) {
			if(!isMobile) isTransitionRuning = true;
			
			menuActiveItemIsChanged = false;
			promoPage.currentCarID = $(this).attr('rel');
			
			isNavigating = true;
			previousOrNext='';
			promoPage.carURL = $(this).attr('href');
			
			if(!isMobile){
				if(promoPage.carURL.length>4) prepareAnimation(promoPage.carURL);
			}
		}
		if(!isMobile) e.preventDefault();
	});
	
	$('header a, #retourAccueil a').live('click',function(e){
		if(!isMobile) {
			//if(currentPage == 'page' || currentPage == 'homeEntreprise') {
				backToHome($(this).attr('href'));
			//}
			 e.preventDefault();
		}
	});
	
	if(isMobile){
		$('ul.equipements li p').each(function(){
			var val = $(this).text();
			if(val.indexOf('-')==-1 || val.indexOf('-')!=0)$(this).prepend('- ');
			
		});
		
		$('ul.equipements').prepend("<p class='yellow'>ÉQUIPEMENTS</p>");
		
	}
	
	if(navigator.platform.indexOf("iPad")){
		$("").touchwipe({
				 wipeLeft: function() {
					if(!isTransitionRuning) {
						if(!isMobile) isTransitionRuning = true;
						menuActiveItemIsChanged = true;
						isNavigating = true;
						previousOrNext = "next";
						prepareAnimation(promoPage[previousOrNext+'CarURL']);
					//	e.preventDefault();
					}
			
				},
				 wipeRight: function() {
					if(!isTransitionRuning) {
						if(!isMobile) isTransitionRuning = true;
						menuActiveItemIsChanged = true;
						isNavigating = true;
						previousOrNext = "previous";
						prepareAnimation(promoPage[previousOrNext+'CarURL']);
					//	e.preventDefault();
					}
				
				 },
				wipeDown:function(){
					// $('html, body').animate({scrollTop:$(document).height()}, 'slow');
				},
				 
				min_move_x: 20,
			    min_move_y: 20,
				preventDefaultEvents: true
				
		});
	}
});
/**
 * jQuery Plugin to obtain touch gestures from iPhone, iPod Touch and iPad, should also work with Android mobile phones (not tested yet!)
 * Common usage: wipe images (left and right to show the previous or next image)
 * 
 * @author Andreas Waltl, netCU Internetagentur (http://www.netcu.de)
 * @version 1.1.1 (9th December 2010) - fix bug (older IE's had problems)
 * @version 1.1 (1st September 2010) - support wipe up and wipe down
 * @version 1.0 (15th July 2010)
 */
 
(function($) { 
   $.fn.touchwipe = function(settings) {
     var config = {
    		min_move_x: 20,
    		min_move_y: 20,
 			wipeLeft: function() { },
 			wipeRight: function() { },
 			wipeUp: function() { },
 			wipeDown: function() { },
			preventDefaultEvents: true
	 };
    
     if (settings) $.extend(config, settings);
 
     this.each(function() {
    	 var startX;
    	 var startY;
		 var isMoving = false;
			
    	 function cancelTouch() {
    		 this.removeEventListener('touchmove', onTouchMove);
    		 startX = null;
    		 isMoving = false;
    	 }	
    	 
    	 function onTouchMove(e) {
    		 if(config.preventDefaultEvents) {
    			 e.preventDefault();
    		 }
    		 if(isMoving) {
	    		 var x = e.touches[0].pageX;
	    		 var y = e.touches[0].pageY;
	    		 var dx = startX - x;
	    		 var dy = startY - y;
	    		 if(Math.abs(dx) >= config.min_move_x) {
	    			cancelTouch();
	    			if(dx > 0) {
	    				config.wipeLeft();
	    			}
	    			else {
	    				config.wipeRight();
	    			}
	    		 }
	    		 else if(Math.abs(dy) >= config.min_move_y) {
		    			cancelTouch();
		    			if(dy > 0) {
		    				config.wipeDown();
		    			}
		    			else {
		    				config.wipeUp();
		    			}
		    		 }
    		 }
    	 }
    	 
    	 function onTouchStart(e)
    	 {
    		 if (e.touches.length == 1) {
    			 startX = e.touches[0].pageX;
    			 startY = e.touches[0].pageY;
    			 isMoving = true;
    			 this.addEventListener('touchmove', onTouchMove, false);
			
    		 }
    	 }    	 
    	 if ('ontouchstart' in document.documentElement) {
    		 this.addEventListener('touchstart', onTouchStart, false);
    	 }
     });
 
     return this;
   };
 
 })(jQuery);

