/** PRODUCT COMPARISON, OPENED IN A NEW WINDOW **/
function productCompare()
{	
	$('form#sort').submit(
		function(event)
		{
			var products_id = new Array();
			var attributes = new String();
			
			event.preventDefault();
			
			if($('li.comparaison input:checked').length > 6)
				alert('Vous pouvez comparer jusqu\'à 6 produits');
			else
			{
				$('li.comparaison input:checked').each(
					function()
					{
						products_id.push($(this).val());
					}
				);
				
				$.each(products_id,
					function(iterator)
					{
						attributes = attributes + products_id[iterator] + '=' + products_id[iterator] + '&';  
					}
				);
				
				var regex = new RegExp('([0-9A-Za-z/]+)?');
				action = regex.exec($(this).attr('action'));
				
				$(this).attr('action', action[0] + '?' + attributes);
				window.open($(this).attr('action'));
			}
		}
	);
}

function loadWorksheet()
{
	/*$('img[alt="Fiche produit"]').parent().click(
		function(event)
		{	
			var parent, href; 
			event.preventDefault();
			parent = $(this).parent();
			href = $(this).attr('href');
			$(this).parent().empty(); 
			$(parent).append('<img src="/images/worksheet/ajax-loader.gif" />');
			$(parent).css({marginTop: '5px', textAlign: 'center'});
			
			setTimeout(function() { location.href = href; }, 1500);
		}
	);*/
}

/** WINDOW OPEN **/
function displayWindow()
{
	$('a[rel="open"]').click(
		function(event)
		{
			event.preventDefault();
			
			window.open($(this).attr('href'));
		}
	);
}

/** Display Subcategories Catalog **/
function toggleCatalog()
{
	$("dl#left_catalog>dd>dl.categories>dt").css({'cursor': 'pointer'});
	$("dl#left_catalog>dd>dl.categories>dt").click(
		function()
		{	
			$("dl#left_catalog>dd>dl.categories>dd>dl.subcategories").slideUp('slow');
			if (navigator.userAgent.indexOf('Chrome') != -1)
				$(this).parent().children('dd').children().css("display","block");
			else	
				$(this).parent().children('dd').children('dl.subcategories').slideToggle("slow");
			
		}
	);
}

function quotationSlide()
{
//	if($('dl#quotation')) $.scrollTo('dl#quotation',800{top:'210px'}, 3000);
}

/*
 * WORKSHEET
 */
function displayFormRelay()
{
	$('a#wk_pointrelais').click(
		function(event)
		{
			event.preventDefault();
			
			jQuery.facebox({ajax: '/worksheet/formRelay'});
		}
	);
}

function displayShippingInfos()
{
	$('dd.wk_basket').next().children('a').hover(
		function(event)
		{
			$('dd#infosLivraison').show();
		}
	);
	
	$('dd.wk_basket').next().children('a').mouseleave(
		function(event)
		{
			$('dd#infosLivraison').hide();
		}
	);
	
	$('dd.wk_basket').next().children('a').click(
		function(event)
		{
			event.preventDefault();
		}
	);
	
	$('img#shipping_img').hover(
			function(event)
			{
				$('div#infosLivraison').show();
			}
	);
	
	$('img#shipping_img').mouseleave(
			function(event)
			{
				$('div#infosLivraison').hide();
			}
	);
	
	$('img#tel_img').hover(
			function(event)
			{
				$('div#infosTel').show();
			}
	);
	
	$('img#tel_img').mouseleave(
			function(event)
			{
				$('div#infosTel').hide();
			}
	);
}

/** Enlarge Images **/
function enlargeMiniPictures() 
{	
	$('ul#pictures li img').each(
		function (element)
		{
			$(this).click(
				function(event) 
				{	
					var regex = new RegExp('(.+)/thumb(.+)');
					newsrc = regex.exec($(this).attr('src'));
					newsrc = newsrc[1]+newsrc[2];
						
					$('img.worksheet_picture').attr('src',$(this).attr('src'));
					$('img.worksheet_picture').parent().attr('href',newsrc);
				}
			);
		}
	);
}

/** Affichage modèles de véhicule **/
function worksheetModelViewer() {
	var opencars = $('a.car_model');
	
	opencars.each(function (element){
		$(this).click(
			function(event) 
			{	
				event.preventDefault();
						
				if ($(this).parent().next().css("display") == "none")
				{
					$(this).parent().next().show();
					$(this).children().attr("src","/images/worksheet/down.gif");
				}
				else
				{
					$(this).parent().next().hide();
					$(this).children().attr("src","/images/worksheet/up.gif");
							}
					}
				);
		});
}

/*** PB Searchengine ***/
function resetSE()
{
	$("input[name='reference']").click(
		function(event)
		{
			$(this).attr('value', '');
		}
	);
	
	$("input[name='tnt_zipcode']").click(
			function(event)
			{
				$(this).attr('value', '');
			}
	);
	
	$("input[name='mail_address']").click(
			function(event)
			{
				$(this).attr('value', '');
			}
	);	
}

/** Consultation Garages **/
function garagesConsult()
{	
	$("form[name='garage_consultation']").submit(
		function(event)
		{
			event.preventDefault();
			
			jQuery.facebox({ajax: '/common/showGarage/province_code/' + $("form[name='garage_consultation']").find('input[name="garages_zipcode"]').val()});
		}
	);
}

function takeARdv()
{
	$("a.rendez_vous").click(
			function(event)
			{
				event.preventDefault();
				
				jQuery.facebox({ajax: '/common/rendezVous/garage_id/' + $(this).attr('title')});
			}
		);
}

/** Consultation des garages par facebox */
function GarageDetail() 
{
	$('a.garageconsult').each(function (element)
	{
		
		$(this).click(
			function(event) 
			{	 
				event.preventDefault();
					 
				var html = $.ajax(
				{
					url: '/common/infoGarage',
					type: 'get',
					async: false,
					data: (
					{
						garage_id: $(this).attr('id')
					})
				}).responseText;
				
				div_content = $('div.content')[0]; 
				$(div_content).empty();
				$(div_content).html(html);			
			}
		);
	});
}

/****** VehicleChange ******/
function changeVehicle()
{
	$('#change_vehicle').click(
		function(event)
		{
			event.preventDefault();
			$('div#content').show();
		}
	);
}

/******** Moteur de recherche par véhicule ********/
function fillSelector(requete, i)
{	
	var option, optiongroup, element;
	
	element = $('select.searchengine_car').get(i);
	option = $(element).children('option')[0];
	myvalue = option.value;
	option = $('<option></option>').text($(option).text()).attr('value', '');
	$(element).empty();
	$(element).append(option);

	$(element).removeAttr('disabled');
	
	$.each(requete,
		function(iterator)
		{
			var options = new Array(); 
		
			$.each(this,
				function(iter)
				{
					optiongroup = this[0];
					options.push($('<option></option>').text(this.description + ' [' + this.year_from + ' - ' + this.year_to + ']').attr('value', this.id));
				}
			);
			
			optiongroup = $('<optgroup></optgroup>').attr('label', optiongroup);
			
			$.each(options, 
				function(iter)
				{
					$(this).css({paddingLeft: '15px'});
					$(optiongroup).append(this);
				}
			);
			
			$(element).append(optiongroup);
		}
	);
	
	if (myvalue!="")
	{
		element.value = myvalue;
		getNextValue(element.getAttribute("name"), myvalue);
	}
}

function getNextValue(type, value) 
{
	var type_sub;
	
	type_sub = (type.substring(0, type.indexOf("_")));	
	
	switch(type) 
	{
		case 'brand_car':
			i = 1;
		break;
		
		case 'model_car':
			i = 2;
		break;
	}
	
	$.ajax(
		{
			url: '/homepage/carSearchEngine',
			type: 'post',
			dataType: 'json',
			data: (
				{
					value: value,
					type: type_sub
				}
			),
			success: function(json) {
				fillSelector(json, i);
			}
		}
	);
};

function loadSearchEngineValues()
{	
	$('select.searchengine_car').each( 
		function(index_select) {
			/** quand la valeur change, on la recupere **/
			if(index_select != 2) 
			{
				$(this).change(
					function() 
					{
						getNextValue(this.getAttribute("name"), this.value);
					}
				);				
			}
			if (index_select == 1 && this.value!="")
			{
				//getNextValue(this.getAttribute("name"), this.value);
			}
			if(index_select == 0)
			{
				$(this).change(
					function() 
					{
						$('select.searchengine_car').each( 
							function(index) {
								if(index != 0) 	
								{
									$(this).attr('disabled', 'disabled');
									element = $('select.searchengine_car').get(index);
									option = $(element).children('option')[0];
									option = $('<option></option>').text($(option).text()).attr('value', '');
									$(element).empty();
									$(element).append(option);
								}
							}
						);
					}
				);
				
				if (this.value!="")
				{
					getNextValue(this.getAttribute("name"), this.value);
				}
			}
		} 
	);
}

/*** RECHERCHE PAR TYPEMINES ****/
function showCarValue(requete)
{	
	$('#form_typemines select').removeAttr('disabled');
	
	if(requete != null)
	{
		$('#form_typemines select').show();
		$('p[title="no_result"]').hide();
		
		option = $('#form_typemines select').children('option')[0];
		option = $('<option></option>').text($(option).text()).attr('value', '');
		
		$('#form_typemines select').empty();
		$('#form_typemines select').append(option);
	}
	else
	{
		$('#form_typemines select').hide();
		$('p[title="no_result"]').show();
	}
	
	if(requete != null)
	{
		$.each(requete,
			function(iterator)
			{
				option = $('<option></option>').attr('value', this.cars_id);
				$(option).text(this.brand_description + ' ' + this.model_description + ' [' + this.year_from + ' - ' + this.year_to + ']');
				$('#form_typemines select').append(option);
			}
		);
	}
}

function getCar()
{
	$.ajax(
		{
			url: '/homepage/typeMinesSearchEngine',
			type: 'post',
			dataType: 'json',
			data: (
				{
					value: $("#form_typemines input[type='text']").val()
				}
			),
			success: function(json) {
				showCarValue(json);
			}
		}
	);
}

function loadSearchEngineTypeMines()
{
	$('#form_typemines input').keypress( 
		function(event) 
		{ 
			if(event.keyCode == 13) {
				getCar();
				event.preventDefault();
			}
		}
	);
	
	$('input#b2').click(
		function(event) 
		{
			event.preventDefault();
			getCar();
		}
	);
}

/*** PRODUITS COMPLEMENTAIRES ***/
function displayFurtherOn()
{
	$('ul.further_product').each(
		function(index)
		{
			$(this).fadeIn("slow");
		}
	);
}

function displayFurtherOff()
{
	$('ul.further_product').each(
		function(index)
		{
			$(this).fadeOut("slow");
		}
	);
}

function loadFurtherProducts()
{	
	$('a#display_further').click(
		function(event)
		{
			event.preventDefault();
			displayFurtherOn();
		}
	);
	
	$('a#display_further_off').click(
		function(event)
		{
			event.preventDefault();
			displayFurtherOff();
		}
	);
}

/******** genere Url pour le catalogue *******/
function generateUrl()
{
	$("select[name='select_typemines']").change(
		function(event)
		{
			if($(this).val() != '')
			{
				carid = $(this).val();
				
				nameform = '#form_typemines';
				
				url = $(nameform).attr('action');
				
				url_language = location.pathname.substring(1);
				
				test="";
				if (url_language.indexOf('/')!= -1)
				{
					url_language=url_language.substring(0,url_language.indexOf('/'));
					
					if (url_language == 'frontend_dev.php')
					{
						test="frontend_dev.php";
						if (location.pathname.substring(1).substr(location.pathname.substring(1).indexOf('/',2)+1,2) == "")
							url_language='fr';
						else
							url_language=location.pathname.substring(1).substr(location.pathname.substring(1).indexOf('/',2)+1,2);
					}
				}
			
				 var html = $.ajax({
					  url: "/common/seekCar",
					  async: false,
					  data: "carid="+carid+"&language="+url_language
					 }).responseText;
				 
				// alert(html);
				 if ((html.indexOf('frontend_dev.php') == -1) && (test != ""))
					 html=" "+html;
				// alert(html);
				 $(nameform).attr('action',html);
				 
//				 alert($(nameform).attr('action'));

				 $(nameform).submit();
			}
		}
	);
	
	$('input#b1').click(
		function(event)
		{
			// b1 -> recherche normale
			if (this.getAttribute("id") == "b1")
			{
				nameform='#vehicle_searchEngine';
				carid=$("select[name='motor_car']");
			}
			else
			{
				carid=$("select[name='select_typemines']");
				nameform='#form_typemines';
			}
			
			url=$(nameform).attr('action');
			
			url_language=location.pathname.substring(1);
			
			test="";
			if (url_language.indexOf('/')!= -1)
			{
				url_language=url_language.substring(0,url_language.indexOf('/'));
				
				if (url_language == 'frontend_dev.php')
				{
					test="frontend_dev.php";
					if (location.pathname.substring(1).substr(location.pathname.substring(1).indexOf('/',2)+1,2) == "")
						url_language='fr';
					else
						url_language=location.pathname.substring(1).substr(location.pathname.substring(1).indexOf('/',2)+1,2);
				}
			}
		
			 var html = $.ajax({
				  url: "/common/seekCar",
				  async: false,
				  data: "carid="+carid.attr('value')+"&language=fr"
				 }).responseText;
			 
			// alert(html);
			 if ((html.indexOf('frontend_dev.php') == -1) && (test != ""))
				 html=" "+html;
			// alert(html);
			 $(nameform).attr('action',html);
		}
	);
}

/*
 * Account
 */
/** Affichage ou pas du formulaire d'adresse **/
function displayAddress()
{
	$('h3.title_form a').toggle(
		function()
		{
			$('table#shipping').show();
		},
		function()
		{
			$('table#shipping').hide();
		}
	);
}

/****** Recuperation liste departements *****/
function fillProvinces(requete, adressType)
{
	var element, option;
	
	element = $('select[name="' + adressType + '[provinces_id]"]');
	
	$(element).empty();
	
	$.each(requete,
		function(iter)
		{
			option = $('<option></option>').attr('value', this.province_id);
			$(option).text(this.libelle);
			$(element).append(option);
		}
	);
}

function getProvinces()
{
	$('select[name="billing[countries_id]"]').change(
		function()
		{
			$.ajax({
				url: '/customers/getProvinces',
				type: 'post',
				dataType: 'json',
				data: (
					{
						country_id: $(this).val()
					}
				),
				success: function(json) {
					fillProvinces(json, 'billing');
				}
			});
		}
	);
	
	$('select[name="shipping[countries_id]"]').change(
			function()
			{
				$.ajax({
					url: '/customers/getProvinces',
					type: 'post',
					dataType: 'json',
				
					data: (
						{
							country_id: $(this).val()
						}
					),
					success: function(json) {
					fillProvinces(json, 'shipping');
				}
				});
			}
	);	
}

function gestionGarageInscription() {
	
	var selecteurs=$('select.fork');

	selecteurs.each(
		function (element)
		{	
			$(this).change(
				function(event) 
				{	
					if ($(this).next().next().css("visibility") == "visible")
						$(this).next().next().css("visibility","hidden");
					else
						$(this).next().next().css("visibility","visible");	
				}
			);
		}
	);
}

/** Permet la gestion des votes sur les centre de montage */
function garageStar() {
	
	var stars = $('li.garageStar');
	
	stars.each(function (element){
		if (!$(this).hasClass("unc")) {
			$(this).mouseenter(
					function(event) 
					{	
						//var classes = $(this).attr('class');
						
						//var regex = new RegExp('([a-z]+)\s([a-z]+)');
						//params = regex.exec(classes);
						
						//$(this).prevAll().andSelf().attr('title', 'stars' + params[2]);
						//$(this).prevAll().andSelf().removeClass('stars' + params[2]);
						
						$(this).prevAll().andSelf().addClass('starson');
					}
				);
			
			$(this).mouseleave(function(event) {	
					//var old_class = $(this).attr('title');
					//$(this).removeAttr('title');
					
					$('.garageStar').removeClass('starson');
					//$('.garageStar').addClass(old_class);
				}
			);
			
			$(this).click(
				function(event) 
				{	
					
					var regex = new RegExp('([0-9]+)_([0-9]+)');
					params = regex.exec($(this).attr('id'));
				 	$.ajax(
						{
							url: '/garages/notation',
							type: 'post',
							dataType: 'json',
							data: (
								{
									garage_id: params[1],
									notation: params[2]
								}
							),
							success: function(json) {
								GarageMAJ(json,params[1]);
							}
						}
					);
				}
			);
		}
		else
			$(this).css("cursor","default");
		});
}

function GarageMAJ(json,garage_id) 
{
	$('#'+garage_id+'moyenne').text(json.moyenne);
	$('#'+garage_id+'moyenne').next().text(json.nbv);
	$('#'+garage_id+'moyenne').parent().next().next().next().next().text(json.txt);
	
	for (i=1; i<6; i++){
		$('#'+garage_id+'_'+i).empty();
		$('#'+garage_id+'_'+i).unbind();
		$('#'+garage_id+'_'+i).css("cursor","default");
	}
}

function garageSubmit()
{
	$("select[name='zipcode']").change(
		function(event)
		{
			$('form[name="departments"]').submit();
		}
	);
}
/********************************/

/** Valide les conditions de retour **/
function validateConds() 
{
	$("#submitReturn").click(
		function()
		{
			if($('#condsReturn').attr('checked')==true)
			{
				$('#formReturn').submit();
			}
			else
			{
				window.alert('Vous devez accepter les conditions de retour.');
			}
		}
	);
	
	$('form#checkout').submit(
		function(event)
		{
			if($('input[name="condition"]').attr('checked')==false)
			{
				event.preventDefault();
				
				alert('Vous devez accepter les conditions générales de vente.');
			}
		}
	);
}

/** Affichage infos TNT **/
function TNTConsult()
{
	$("form[name='tnt_consultation']").submit(
		function(event)
		{
			event.preventDefault();
			jQuery.facebox({ajax: '/homepage/tntrelay/zipcode_value/' + $('input[name="tnt_zipcode"]').val()});
		}
	);
}

function LoadTntInfo() 
{
	var loupes_tnt = $('img.tntInfo');

	loupes_tnt.each(
		function(element)
		{
			$(this).click(
				function(event) 
				{
					debut = parseInt($(this).attr('id'));
					fin = parseInt(debut + 1);
				
					$(this).parent().parent().parent().parent().nextAll().css('display','none');
					$(this).parent().parent().parent().parent().nextAll().slice(debut,fin).css('display','block');
				}
			);
		}
	);
	
	$('img.tntInfo').css('cursor', 'pointer');
	
	/** Activer le bouton enregister final */
	elementsTNT=$("input[name='groupe']");
	elementsTNT.each(
		function (element)
		{
			$(this).hide();
		}
	);
}

function LoadCommuneInfo() 
{
	var liens = $('a.teille');
	liens.each(
		function (element)
		{
			$(this).click(
				function(event) 
				{
					event.preventDefault();
			
					var html = $.ajax(
					{
						url: '/homepage/tntrelay',
						type: 'get',
						async: false,
						data: (
							{
								zipcode_value: $(this).prev().html(),
								commune: $(this).html()
							}
						)
					}
					).responseText;
			
					div_content =$('div.content')[0]; 
					$(div_content).empty();
					$(div_content).html(html);
				
				}
			);
		}
	);
}

function SendNewsletter() {
	
	$("form[id='newsletter_right_homepage']").submit(
	
			function(event)
			{
				event.preventDefault();
				elements=$(this).find("input");
								
				jQuery.facebox({ajax: '/customers/signUpNewsletter/email/' + elements.val()});
			}
		);
	 
}
 
/******** INITIALISATION ********/
$(document).ready(
	function() 
	{   
		loadSearchEngineValues();
		loadFurtherProducts();
		loadSearchEngineTypeMines();
		changeVehicle();
		generateUrl();
		getProvinces();
		
		jQuery(document).ready(function($) {
		       $('a[rel*=facebox]').facebox({
		         loading_image : 'loading.gif',
		         close_image   : 'closelabel.gif'
		       }) 
		     });
		
		garagesConsult();
		resetSE();
		toggleCatalog();
		takeARdv();
		gestionGarageInscription();
		garageStar();
		worksheetModelViewer();
		enlargeMiniPictures();
		validateConds();
		garageSubmit();
		TNTConsult();
		productCompare();
		displayShippingInfos();
		displayFormRelay();
		displayAddress();
		displayWindow();
		SendNewsletter();
		quotationSlide();
		loadWorksheet();
		
		$('select#dimensions').css('width', '98px');
		
		$('span#login_suivi').click(
			function(event)
			{
				jQuery.facebox({ajax: '/customers/loginSuivi'});
			}
		);
		
		$('span#login_retour').click(
			function(event)
			{
				jQuery.facebox({ajax: '/customers/loginRetour'});
			}
		);
		
		$('span#login_contact').click(
				function(event)
				{
					jQuery.facebox({ajax: '/company/contacts'});
				}
			);
		
		$('span#login_suivi').hover(
			function(event)
			{
				$(this).css({textDecoration: 'underline', cursor: 'pointer'});
			}
		);
		
		$('span#login_retour').hover(
			function(event)
			{
				$(this).css({textDecoration: 'underline', cursor: 'pointer'});
			}
		);
		
		$('span#login_retour').mouseleave(
			function(event)
			{
				$(this).css({textDecoration: 'none'});
			}
		);

		$('span#login_suivi').mouseleave(
				function(event)
				{
					$(this).css({textDecoration: 'none'});
				}
		);

		$('a#ok_ref_search').click( function(event)
		{
			event.preventDefault();
			if ($('input#reference').val()!='' && $('input#reference').val()!='recherche par référence')
				$('form#ref_search').submit();
		});
    }
);
/********************************/
