/****************
################# WHEN DOM LOADS ################# 
****************/

$(document).ready(function(){
	//if search module exists init module search functionality
	if($('.blockSearchModule').length){
		initModuleSearch();
	}	
	//init custom accordion on search list
	if($(".coll03").length){
		initCustomAcc();
	}
	//init sort links on results from search
	if($(".selectorOption").length){
		initSortLinks();
	}
	//custom generic accordion
	if($('.customAcc2').length){
		genericCustomAcc();
	}
	
	//FORM PAGE 500
	if($('.blockFormAuto500').length){
		init500CheckForm();
	}
	//CUSTOM OVERLAY
	if($('a.overlayIn').length){
		$("a.overlayIn").overlayIn();
	}
	$("a.overlayOut").live('click',function(){
		overlayOut();
		return false;
	});
	
	//CUSTOM CAROUSEL FOR FICHE AUTO
	if($('#mycarousel').length){
		initFicheAutoCarrousel();
	}
	
	//REMOVE BORDER BOTTOM FROM LAST DIV PAGE LISTING
	if($('.blockRowPageListing').length){
		initRowPageListing();
	}
	
	//SHOW HIDE FORM LAYER ON DEALER PAGE
	if($('#formIn').length){
		initShowHideFormNousContacter();
	}
	//SHOW HIDE MAP LAYER ON DEALER PAGE
	if($('#mapIn').length){
		initShowHideMap();
	}
	// HIDE FORM THANK YOU ON FICHE AUTO
	if($('#overlayFormThankYou').length){
		initShowHideFormThankYou();
	}
	
	//POPUP
	if($('.blockPopUpContainer').length){
		initShowPOPUP();
	}
	//POPUP
	if($('#popUpClose').length){
		initClosePOPUP();
	}
	
	
	
	
	
	
	
	
	

	
});
/****************
################# INIT POPUP ################# 
****************/

function initShowPOPUP(){
	$('#popUpOpen').click(function() {
  		$('.blockPopUpContainer').fadeIn();
	return false;
	});
	
	}
	
function initClosePOPUP(){
	$('#popUpClose').click(function() {
  		$('.blockPopUpContainer').fadeOut();
	return false;
	});
	}
/****************
################# INIT SEARCH MODULE ################# 
****************/

function initModuleSearch(){
	
	//init module search tabs event handlers
	initModuleBrand();
	//init sliders for module search
	initModuleSliders();
	//init accordion functionality to more options menu
	initModuleMoreOptions();
	//init color options populate input type hidden
	initModuleColor();
	//init dynamic selects, brand and model
	initSelectBrand();
	
}

/****************
################# INIT MODULE BRAND ################# 
****************/

function initModuleBrand(){
	$('#listBrand a').click(function(){
		$(this).parents('ul').find('li').removeClass('selected');
		$(this).parent().addClass('selected');
		
		var linkId = $(this).attr('rel');
		
		//show module other vehicles when link others is selected
		if(linkId == 'others'){
			$('#blockOthers').slideDown('fast');
			changeSelectBrand();
		}else{
			$('#blockOthers').slideUp('fast');
			changeSelectBrand(linkId);
		}
		return false;
	});
	
	//show module others when others link is selected on page load
	if($('#listBrand li.selected').length){
		var idSelected = $('#listBrand li.selected a').attr('id');
		if(idSelected == 'others'){
			$('#blockOthers').show();
		}
	}
}

/****************
################# INIT SELECT BRAND ################# 
this function creates select brand, option selected, and select brand onchange event
****************/

function initSelectBrand(brandParam){

	if(typeof brandParam == 'undefined'){
		brandParam = config.defaultBrand;	
	}

	var selectBrand = $('#sltBrand');
	var optionBrand = [];
	optionBrand.push('<option value="0">----- Tous -----</option>');
  
	for(x in brands){
		if(x == brandParam){
			optionBrand.push('<option selected value="' + x + '">' + brands[x] + '</option>');
		}else{
			optionBrand.push('<option value="' + x + '">' + brands[x] + '</option>');
		}
	}
	
	selectBrand.html(optionBrand.join(''));
	
	selectBrand.change(function(){
		var valueSelected = $(this).find('option:selected').val();
		changeSelectBrand(valueSelected)
		initSelectModel(valueSelected);						
	});
	
	initSelectModel();
	
}

/****************
################# INIT SELECT MODEL ################# 
this function creates select model based on param sent
****************/

function initSelectModel(brandParam){
	
	if(typeof brandParam == 'undefined'){
		brandParam = config.defaultBrand;	
	}
	
	var selectModel = $('#sltModel');
	var optionModel = [];
	
	// Add a default option to search on all models
	optionModel.push('<option value="0">----- Tous -----</option>');
	
	for(x in models){
		if(x == brandParam){
			for(y in models[x]){
				var model_id = y;
				var model = models[x][y];//.toLowerCase();
				optionModel.push('<option value="' + model_id + '" ' + ((config.defaultModel != '') ? ((config.defaultModel == model_id) ? 'selected' : '' ) : '') + '>' + model + '</option>');        
			}
		}
	}
	
	selectModel.html(optionModel.join(''));
	
	selectModel.change(function(){
		var valueSelected = $(this).find('option:selected').val();
		$('#txtModel').val(valueSelected);					
	});
	
	//initially populate input type hidden with default values
	$('#txtBrand').val(brandParam);
	$('#txtModel').val(selectModel.find('option:first').val());
	
}

/****************
################# INIT CHANGE SELECT BRAND SELECTED ################# 
this function changes the select selected, and inits the creation of select model
****************/

function changeSelectBrand(brandParam){
	
	if(typeof brandParam == 'undefined'){
		brandParam = config.defaultBrand;	
	}
	
	$('#sltBrand option[value='+ brandParam +']').attr('selected', 'selected');
	
	initSelectModel(brandParam);
	
	//alert($('#sltBrand option:selected').val());
	
}

/****************
################# INIT SLIDERS KM PRICE YEAR ################# 
****************/

function initModuleSliders(){
	
	//INIT SLIDER KM
	
	/* SLIDER KM 
	input type hidden are dynamically filled with range values
	if 
	range is greater than 1000000 km id txtKmGreater has value 1 
	and id txtKmGreater and id txtKmMax have value 0
	if
	range is less than 100000 km id txtKmGreater has value 0
	and id txtKmMin and id txtKmMax have value of slider range
	*/
	
	$("#sliderKm").slider({
		range: true,
		min: config.minKm,
		max: config.maxKm,
		step: config.stepKm,
		values: [config.rangeMinKm, config.rangeMaxKm],
		slide: function(event, ui) {
			
//			var kmCount = Number(ui.values[1]);
//			var kmMaxCount = config.maxKm - config.stepKm;
//		
//			if(kmCount > kmMaxCount){
//				$("#sliderKmCount").html(config.msgGreaterKm);
//				
//				//place value inside input type hidden to know km range
//				$('#txtKmMin').val('0');
//				$('#txtKmMax').val('0');
//				$('#txtKmGreater').val('1');
//				
//				
//			}else if(kmCount <= kmMaxCount){
				$("#sliderKmCount").html(formatage_nombre_fr(ui.values[0]) + ' à ' + formatage_km(ui.values[1]) );
				
				//place value inside input type hidden to know km range
				$('#txtKmMin').val(ui.values[0]);
				$('#txtKmMax').val(ui.values[1]);
//				$('#txtKmGreater').val('0');	
//			}
		}
	});
	//DEFAULT VALUES FOR SLIDER KM  ON DOM LOAD
	
	$("#sliderKmCount").html(formatage_nombre_fr($("#sliderKm").slider("values", 0)) + ' à ' + formatage_km($("#sliderKm").slider("values", 1)));
	
	//place value inside input type hidden to know km range
	$('#txtKmMin').val($("#sliderKm").slider("values", 0));
	$('#txtKmMax').val($("#sliderKm").slider("values", 1));
//	$('#txtKmGreater').val('0');
	
	//END SLIDER KM
	//INIT SLIDER PRICE
	
	/* SLIDER PRICE
	input type hidden are dynamically filled with range values
	if 
	range is greater than 30000 EUR id txtPriceGreater has value 1 
	and id txtPriceMin and id txtPriceMax have value 0
	if
	range is less than 100000 km id txtPriceGreater has value 0
	and id txtPriceMin and id txtPriceMax have value of slider range
	*/
	
	$("#sliderPrice").slider({
		range: true,
		min: config.minPrice,
		max: config.maxPrice,
		step: config.stepPrice,
		values: [config.rangeMinPrice, config.rangeMaxPrice],
		slide: function(event, ui) {
			
//			var priceCount = Number(ui.values[1]);
//			var priceMaxCount = config.maxPrice - config.stepPrice;
//			
//			if(priceCount > priceMaxCount){
//				$("#sliderPriceCount").html(config.msgGreaterPrice);
//				
//				//place value inside input type hidden to know price range
//				$('#txtPriceMin').val('0');
//				$('#txtPriceMax').val('0');
//				$('#txtPriceGreater').val('1');
//				
//			}else if(priceCount <= priceMaxCount){
				$("#sliderPriceCount").html(ui.values[0] + ' à ' + formatage_euro(ui.values[1]));
				
				//place value inside input type hidden to know price range
				$('#txtPriceMin').val(ui.values[0]);
				$('#txtPriceMax').val(ui.values[1]);
//				$('#txtPriceGreater').val('0');
//			}
		}
	});
	
	//DEFAULT VALUES FOR SLIDER PRICE ON DOM LOAD
	
	$("#sliderPriceCount").html($("#sliderPrice").slider("values", 0) + ' à ' + formatage_euro($("#sliderPrice").slider("values", 1)));
	
	//place value inside input type hidden to know price range
	$('#txtPriceMin').val($("#sliderPrice").slider("values", 0));
	$('#txtPriceMax').val($("#sliderPrice").slider("values", 1));
//	$('#txtPriceGreater').val(0);
	
	//END SLIDER PRICE
	//INIT SLIDER YEAR
	
	$("#sliderYear").slider({
		range: true,
		min: config.minYear,
		max: config.maxYear,
		step: config.stepYear,
		values: [config.rangeMinYear, config.rangeMaxYear],
		slide: function(event, ui) {
			$("#sliderYearCount").html(ui.values[0] + ' à ' + ui.values[1]);
			
			//place value inside input type hidden to know year range
			$('#txtYearMin').val(ui.values[0]);
			$('#txtYearMax').val(ui.values[1]);
		}
	});
	
	//DEFAULT VALUES FOR SLIDER YEAR ON DOM LOAD
	
	$("#sliderYearCount").html($("#sliderYear").slider("values", 0) + ' à ' + $("#sliderYear").slider("values", 1));
	
	//place value inside input type hidden to know year range
	$('#txtYearMin').val($("#sliderYear").slider("values", 0));
	$('#txtYearMax').val($("#sliderYear").slider("values", 1));
	
	//END SLIDER YEAR
    
    
    
    //INIT SLIDER Rayon	- GEOLOC
	/* SLIDER Rayon 
	input type hidden are dynamically filled with range values
	if 
	range is greater than 1000000 km id txtRayonGreater has value 1 
	and id txtKmGreater and id txtRayonMax have value 0
	if
	range is less than 100000 km id txtRayonGreater has value 0
	and id txtRayonMin and id txtRayonMax have value of slider range
	*/
	/*
    //console.log(' Debug slider : '+config.minRayon+' '+config.maxRayon+' '+config.stepRayon);
	$("#sliderRayon").slider({
		range: true,
		min: config.minRayon,
		max: config.maxRayon,
		step: config.stepRayon,
		values: [config.rangeMinRayon, config.rangeMaxRayon],
		slide: function(event, ui) {
            //console.log('test slider rayon');
            $("#sliderRayonCount").html(formatage_nombre_fr(ui.values[0]) + ' à ' + formatage_km(ui.values[1]) );				
            //place value inside input type hidden to know Rayon range
            $('#txtRayonMin').val(ui.values[0]);
            $('#txtRayonMax').val(ui.values[1]);
		}
	});
	//DEFAULT VALUES FOR SLIDER Rayon  ON DOM LOAD	
	$("#sliderRayonCount").html(formatage_nombre_fr($("#sliderRayon").slider("values", 0)) + ' à ' + formatage_km($("#sliderRayon").slider("values", 1)));	
	//place value inside input type hidden to know Rayon range
	$('#txtRayonMin').val($("#sliderRayon").slider("values", 0));
	$('#txtRayonMax').val($("#sliderRayon").slider("values", 1));
//	$('#txtRayonGreater').val('0');
	*/
    
    
    
    
    
	//PLACE CORRECT IMG ON SLIDER HANDLE RIGHT LINK IMG	
	$('.blockSliderContainer .ui-slider').each(function(){
		$(this).find('.ui-slider-handle:eq(1)').addClass('rightArrow');										   
	});
}

/****************
################# INIT MODULE MORE OPTIONS ################# 
****************/

function initModuleMoreOptions(){
	$(".blockAccordionContainer").each(function(){
		$(this).find('h3').toggle(function(){
			$(this).toggleClass('open');
			$(this).next('.blockAccordionContent').slideDown('fast');
		},function(){
			$(this).toggleClass('open');
			$(this).next('.blockAccordionContent').slideUp('fast');
		});
	});
}

/****************
################# INIT MODULE COLOR ################# 
****************/

function initModuleColor(){
	$('.blockColorItems a').click(function(){
        var _self = $(this);
		//$(this).parents('ul').children('li').removeClass('selected').find('a span').hide(); // Masque + deselectionne tous les autres
		if( $(this).parent().hasClass('selected') ) { // Switch selected et check
            $(this).parent().removeClass('selected');
            $(this).find('span').hide();
        } else {
            $(this).parent().addClass('selected');
            $(this).find('span').show();
        }
		
		
		//place value inside input type hidden to know model color
        // EVO : contains only the last color
		$('#txtColor').val($(this).attr('id'));
        
        // EVO : manage multicolors select
        // Todo get liste items selected
        /*
        var listeColors = $(this).parents('ul').find('li.selected');
        var strListeColors = '';
        for(thisColor in listeColors) {
            strListeColors = thisColor.attr('id')+',';
        }
        
        
        $.each(listeColors, addColor(i,val) );
        // TODO : virer le , final
        //console.log('Liste colors = '+listeColors);
        $('#txtColors').val('liste colors = '+listeColors);
        */
        
        // EVO : contains munlticolors : 1,2,3
        var tabIds = '';
        _self.parents('ul').find('li.selected a').each(function(index, valeur){
            //tabIds += ((tabIds == '') ? '' : ','); // Gestion de la virgule
            if(tabIds != '') tabIds += ','; // Gestion de la virgule
            tabIds += $(this).attr('id'); // Add color ID
        });
        $('#txtColors').val(tabIds);
        
		return false;
	});
}

function addColor(i,val) {
    var newColor = i.attr('id')+',';
    $('#txtColors').val('liste colors = '+newColor);
}

/****************
################# HOME ACCORDION SEARCH  ################# 
****************/

var carrouselInterval;

function initCustomAcc(){
	
	$('.coll03 h3').click(function() {
		if($(this).parents('.rowBlock').next().is('.open')){
			
			autoscrolling = false;
			
			window.clearInterval(carrouselInterval);
			
			$(this).parents('.rowBlock').next().find('.carCarousel .arrow').hide();
			
			$(this).parents('.rowBlock').next().slideUp('slow',function(){
			
			}).removeClass('open');
			
			$('.coll03 h3').removeClass('active');
			
		}else{
			
			autoscrolling = false;
			
			window.clearInterval(carrouselInterval);

			$(this).parents('.customAcc').find('.open .carCarousel .arrow').hide();
			
			$(this).parents('.customAcc').find('.open').slideUp('slow');
			
			$('.coll03 h3').removeClass('active').parents('.rowBlock').next().slideUp('slow').removeClass('open');
			
			$(this).addClass('active');
			
			$(this).parents('.rowBlock').next().slideDown('slow',function(){
				
				var objCarrousel = $(this).find('.carCarousel');
				
				var liCarrousel = objCarrousel.find('.wrapper ul li');
				
				//IF CARROUSEL ITEMS GREATER THAN 1
				if(liCarrousel.length > 1){
					
					if(objCarrousel.length && !objCarrousel.data('slider')){
						
						autoscrolling = true;
						
						initCarrousel(objCarrousel);
						
						objCarrousel.data('slider','true');
						
					}else{
						
						autoscrolling = true;
						
						//window.clearInterval(carrouselInterval);
						
						carrouselInterval = window.setInterval(function () {
							if(autoscrolling){
							   objCarrousel.trigger('next');
							}
						}, 5000);
						
						objCarrousel.find('.arrow').show();
						
					}
					
				}else if(liCarrousel.length == 1){ //IF CARROUSEL ITEMS = 1
				
					carrouselFixLoadImages(objCarrousel);
					
				}

			}).addClass('open');
		}
		return false;
	}).parents('.rowBlock').next().hide();

}

/****************
################# CARROUSEL INSIDE ACCORDION  ################# 
****************/

function initCarrousel(objCarrousel){

	carrouselFixLoadImages(objCarrousel);

	var $objCarrousel = objCarrousel;
    
    $objCarrousel.infiniteCarousel().mouseover(function () {
        autoscrolling = false;
    }).mouseout(function () {
        autoscrolling = true;
    });
	
	//FIX ON IE6 AND IE7
	$objCarrousel.find('.wrapper').scrollLeft(300);
    
    carrouselInterval = window.setInterval(function () {
        if(autoscrolling){
           $objCarrousel.trigger('next');
        }
    }, 5000);

}

/****************
################# REPLACE CARROUSEL LOAD IMAGES  ################# 
****************/

function carrouselFixLoadImages(objCarrousel) {
	var $objCarrousel = objCarrousel;
	$objCarrousel.find('img').each(function() {
		var imgTitle = $(this).attr('title').toLowerCase();
		if(this.title && imgTitle.match(/.(jpg|jpeg|png|gif)$/)) {
			this.src = this.title;
			this.title = '';
			$(this).removeClass('loading');
		}
	});
}

/****************
################# CHANGE FUNCTION FOR SLIDER DEALER PAGE ################# 
****************/

function handleSliderChange(e, ui){
	var $target = $(e.target);
  	var contentScroll = $target.parent().find('.content-scroll');
	contentScroll.attr({scrollLeft: ui.value});
}

function handleSliderSlide(e, ui){
	var $target = $(e.target);
  	var contentScroll = $target.parent().find('.content-scroll');
	contentScroll.attr({scrollLeft: ui.value });
}

/****************
################# INIT MODEL LIST SEARCH SORT LINKS  ################# 
****************/

function initSortLinks(){
	$('.selectorOption ul').find('li:not(:first)').each(function(index){
		$(this).hover(function(){
			$(this).parent().find('li:first').addClass('selectedDesc');				   
		},function(){
			$(this).parent().find('li:first').removeClass('selectedDesc');							   
		});
		
		$(this).click(function(){
			$(this).parents('.selectorOption').find('li').removeClass('selected').removeClass('selectedDescClick');	
			$(this).addClass('selected').parent().find('li:first').addClass('selectedDescClick');
			//return false;
		});
	});
}

/****************
################# GENERIC CUSTOM ACC  ################# 
****************/

function genericCustomAcc(){
	$('.customAcc2 h3').click(function() {
		if($(this).next().is('.open')){
			$('.customAcc2 h3').next().slideUp('fast',function(){
											 
			 }).removeClass('open');
			$('.customAcc2 h3').removeClass('active');
		}else{
			$(this).parent().find('.open').slideUp('fast');
			$('.customAcc2 h3').removeClass('active').next().slideUp('fast').removeClass('open');
			$(this).addClass('active');
			$(this).next().slideDown('fast',function(){

				var hasForm = $(this).find('form');
				if(hasForm.length){
					hasForm.check_form();
				}
			
			 }).addClass('open');
		}
		return false;
	}).next().hide();
}


/****************
################# FUNCTION CUSTOM OVERLAY WITH PNG IE6 FIX ################# 
****************/

$.fn.overlayIn = function() {
	$(this).click(function(){
		var html = '';
		html += '<div id="overlayContainer">';
		html += '<div id="overlay">&nbsp;</div>';
		html += '<div id="overlayContent">&nbsp;</div>';
		html += '</div>';
		$('body').append(html);
		var overlayUrl = $(this).attr('href');
		//CUSTOM OVERLAY
		if($(this).hasClass('overlayIn')){
			var thisLink = $(this);
			$('#overlayContent').load(overlayUrl,function(){
				$('#overlayContent').show();
				$('#formNousContacter').check_form();
			});
		}
		return false;
	});
};

/****************
################# CLOSE OVERLAY ################# 
****************/

var overlayOut = function() {
	$('#overlayContent').fadeOut('slow');
	$('#overlayContainer').fadeOut('slow',function(){ 
		$(this).remove();										   
	});						   	
};

/****************
################# CARROUSEL FOR FICHE AUTO ################# 
****************/

function initFicheAutoCarrousel(){
	$('#mycarousel').jcarousel({
        scroll: 1
    });
	
	//REPLACE LOADING GIF BY CARROUSEL IMAGE
	carrouselFixLoadImages($('#mycarousel'));
	
	$('#mycarousel .jcarousel-item a').live('click',function(e){
		var img = $(this).attr('href');
		loadCarrouselImage(img);
		e.preventDefault();
	});
	
	$('.picture-fade').hide();
	
	$('.jcarousel-skin-ie7').each(function(){
		var firstImg = $(this).find('li:first a').attr('href');	
		$('.picture img').attr('src',firstImg);
	});	
}

//FUNCTION THAT LOADS BIG CARROUSEL IMAGE FROM CAROUSEL THUMBS

function loadCarrouselImage(img){
	$('.picture-fade').fadeIn('slow', function(){
		$('.picture img').attr('src',img);
	});
	$('.picture-fade').fadeOut('fast');	
};

/****************
################# //REMOVE BORDER BOTTOM FROM LAST DIV PAGE LISTING ################# 
****************/

function initRowPageListing(){
	$('.blockRowPageListing:last').addClass('noBorder')
}

/****************
################# FUNCTIONS TO SHOW HIDE FORM AND MAP LAYER ON DEALER PAGE ################# 
****************/

function initShowHideFormNousContacter(){
	$('#formIn').click(function(){
		$('#overlayFormContainer').show();
		$('#overlayFormContainer').bgiframe();
		$('#formNousContacter').check_form();
		return false;
	});
}
function initShowHideFormThankYou() {
	$('.formOut').click(function(){
		$('#overlayFormContainer').hide();	
		$('#overlayFormThankYou').hide();	
		return false;
	});
}

function initShowHideMap(){
	$('#mapIn').click(function(){
		$('#overlayMapContainer').show();						
		return false;
	});
	$('.mapOut').click(function(){
		$('#overlayMapContainer').hide();						
		return false;
	});
}
/**/
function init500CheckForm(){
		$('#autoexpert500').check_form();
}

function formatPrice (price){
	alert("dfsdf")
	return "aaaaaaa" + price;
}

function formatage_nombre_fr(valeur) { // Todo gestion d'un float facultatif : formatage_nombre_fr(valeur,float=false)
	var isNotANumber = isNaN(valeur)
	if(isNotANumber) { 
		return val_format = 0; // Si ce n'est pas un nombre, on renvoie 0 !
	}
	var decimal = 0;
	var separateur = ' ';
// formate un chiffre avec 'decimal' chiffres apr?s la virgule et un separateur
	var deci=Math.round( Math.pow(10,decimal)*(Math.abs(valeur)-Math.floor(Math.abs(valeur)))) ; 
	var val=Math.floor(Math.abs(valeur));
	if ((decimal==0)||(deci==Math.pow(10,decimal))) {val=Math.floor(Math.abs(valeur)); deci=0;}
	var val_format=val+"";
	var nb=val_format.length;
	for (var i=1;i<4;i++) {
		if (val>=Math.pow(10,(3*i))) {
			val_format=val_format.substring(0,nb-(3*i))+separateur+val_format.substring(nb-(3*i));
		}
	}
	if (decimal>0) {
		var decim="";
		for (var j=0;j<(decimal-deci.toString().length);j++) {decim+="0";}
		deci=decim+deci.toString();
		val_format=val_format+"."+deci;
	}
	if (parseFloat(valeur)<0) {val_format="-"+val_format;}
	return val_format;
}

function formatage_euro(valeur) {
	var euro = formatage_nombre_fr(valeur);
	return euro+' €';
}

function formatage_km(valeur) {
	var euro = formatage_nombre_fr(valeur);
	return euro+' Km';
}
