var bacheca = new Array();
var global_id_concession = 0;
var popup_vide_top = '';
var popup_vide_bottom = '';
var popup_top = '';
var popup_bottom = '';
var popup_top2 = '';
var popup_bottom2 = '';
var popup_loader = '';
var result_loader = '';
var elt_js_result = '';
var panier = new Array();
var result_fois = 0;
var bouton_popup = '';

var TRAD_SEARCH_NO_RESULT = '';

var panier_from = 'center_offres';

var tab_civ = new Array();
tab_civ['M.'] = 'Monsieur';
tab_civ['Mme'] = 'Madame';
tab_civ['Mle'] = 'Mademoiselle';

var tab_val_profil_default = new Array();

//updateBacheca();

function updateBacheca() {
	$.ajax({
		url: '_ajax.php',
		type: 'POST',
		dataType: "json",
		data: {
			action: 'getBacheca'
		},
		success: function(data){
			bacheca = data;
		}
	});
}

function open_popup_distrib_plan( id) {
	global_id_concession = id;
	$.nmData( popup_top.replace('{ID}', 'distrib_plan') +'<div id="popup_distrib_plan_google_map"></div>'+popup_bottom,{ callbacks: {
		afterShowCont: function() {
			idc = global_id_concession;
			var latlng = new google.maps.LatLng( bacheca[idc]['infos-latitude'], bacheca[idc]['infos-longitude']);
			var options = {
				center: latlng,
				zoom: 8,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			var map = new google.maps.Map(document.getElementById("popup_distrib_plan_google_map"), options);
			
			var image = new google.maps.MarkerImage('themes/fiat/images/marker_fiat.png',
			// This marker is 20 pixels wide by 32 pixels tall.
			new google.maps.Size(60, 58),
			// The origin for this image is 0,0.
			new google.maps.Point(0,0),
			// The anchor for this image is the base of the flagpole at 0,32.
			new google.maps.Point(29,57));
			
			var shadow = new google.maps.MarkerImage('themes/fiat/images/marker_fiat_shadow.png',
			// The shadow image is larger in the horizontal dimension
			// while the position and offset are the same as for the main image.
			new google.maps.Size(60, 69),
			new google.maps.Point(0,0),
			new google.maps.Point(29,57));
			
			var marker = new google.maps.Marker({
				position: latlng,
				map: map,
				shadow: shadow,
				icon: image,
				title: bacheca[idc]['raison_sociale']
			});
		}
	}});
	
	
}

function left_search_onglet_show( type) {
	$('#onglet_liste a').removeClass( 'on');
	$('#onglet_zone_geo_content').hide();
	$('#onglet_affinez_content').hide();
	
	if( type == 'zone_geo' || type == 'affinez' ) {
		$('#onglet_'+type).addClass( 'on');
		$('#onglet_'+type+'_content').show();
	}
	return false;
}

function getValFromCheckboxName( name) {
	var data = new Array();
	$('input[name="'+name+'"]:checked').each( function() {
		data[data.length] = $(this).val();
	});
	return data;
}

function getValFromRadioName( name) {
	var data = new Array();
	$('input[name="'+name+'"]:checked').each( function() {
		data[data.length] = $(this).val();
	});
	if( data.length > 0 ) return data[0];
	return '';
}

/*function getSelectedModel() {
	return new Array('169');
}*/

function validLeftSearch( data) {
	var erreur = false;
	
	//if( empty( data.localite) || data.localite == 'CATEGORIES' || data.localite == 'NO_RESLUT' ) return true;
	if( empty( data.departement) || data.departement <= 0 ) { erreur = true; }
	if( !data.modele.length) { erreur = true; }
	return erreur;
}

function click_left_search() {
	var data = getValRechercher();
	//console.log( data);
	var erreur = validLeftSearch( data);
	if( erreur == false ) {
		sendLeftSearch( data);
	}
	else {
		// popup Erreur
		var top = popup_top2.replace('{BOUTONS}', '');
		top = top.replace('{POPUP_CLASS}', 'popup2_merci');
		$.nmData( top.replace('{ID}', 'merci') + '<div class="popup_titre">Erreur</div><p class="popup2_merci_contenu">Merci de sélectionner jusqu’à 3 modèles et un distributeur.</p>' + popup_bottom2,{ callbacks: {} });
	}
	return false;
}

function sendLeftSearch( data) {
	//openPopupLoader();
	$('#center_results_ajax').html(result_loader);
	$('#center_offres').hide();
	$('#center_results').show();
	data.action = 'sendLeftSearch';
	$.ajax({
		url: '_ajax.php',
		type: 'POST',
		dataType: "json",
		data: data,
		//complete: function() { closePopupLoader(); }, 
		//error: function() { closePopupLoader(); }, 
		success: function(data){
			//Actions à effectuer suite à la soumission Ajax de la Recherche
			html='';
			for(v in data) {
				html_elt = elt_js_result;
				html_elt = html_elt.replace('{ID}',data[v]['id']);
				html_elt = html_elt.replace('{DISTR}',data[v]['distr']);
				html_elt = html_elt.replace('{PRIX}',data[v]['prix']);
				html_elt = html_elt.replace('{PRIX_HTML}',data[v]['prix_html']);
				html_elt = html_elt.replace('{MODELE}',data[v]['mod']);
				html_elt = html_elt.replace('{VERSION}',data[v]['vers']);
				html_elt = html_elt.replace('{MOTOR}',data[v]['motor']);
				html_elt = html_elt.replace('{COULEUR}',data[v]['coul']);
				html += html_elt;
			}
			if( empty( html) ) {
				html = '<tr><td colspan="7">'+TRAD_SEARCH_NO_RESULT+'</td></tr>';
			}
			$('#center_results_ajax').html(html);
			ga_track_page( GA_PAGENAME_RESULTATS);
			$("#tab_offres .ligne #lien_panier_sel").click( function() {
			  var id = getEndNumber( $(this).parent().attr('id'));
				togglePanier(id, "popup"); return false;
			});
			$('#center_results_contenu').netscroller({repeat_delay: 50, pas: 20, puceHeight: 45});
			if ( result_fois == 0 ) { $("#tab_offres").tablesorter({widgets: ['zebra']}); result_fois++; }
			else { $("#tab_offres").trigger("update"); }
			$("#tab_offres .ligne .bt_popup_vehicule").click( function() {
			  var id = $(this).parent().attr('id');
			  ga_track_page( GA_PAGENAME_POPUP);
				$.ajax({
					url: '_ajax.php',
					type: 'POST',
					dataType: "html",
					data: { action: 'detailVehicule', vehicule_id: id },
					success: function(data){
						var retour = data.split('|@@|');
					  var top = popup_top2.replace('{BOUTONS}', retour[0]);
				    $.nmData( top.replace('{ID}', 'offres_'+id) + retour[1] + popup_bottom2,{ callbacks: {
							afterShowCont: function() {
							  eval(retour[2]);
							}
						}}	);

					}
				});
			});
			//closePopupLoader();
		}
	});
}

function getValRechercher() {
	idc = $('#id_distrib_id_concession').val();
	code_ce = '';
	if( idc > 0 ) code_ce = bacheca[idc]['code_ce'];
	//getSelectedModel()
	var data = {
		modele: getValFromCheckboxName( 'modele[]'), 
		id_concession: idc, 
		code_ce: code_ce, 
		/*localite: $('#id_distrib_cp').val(), */
		departement: $('#id_num_dept').val(), 
		budget_min: $('#id_budget_min').val(), 
		budget_max: $('#id_budget_max').val(), 
		energie: getValFromCheckboxName( 'energie[]'), 
		motorisation: $('#id_motorisation').val(), 
		nb_portes: $('#id_nb_portes').val(), 
		type_vehic: getValFromCheckboxName( 'type_vehic[]')
	};
	return data;
}

function refreshAdvancedSelectors(modeles_list) {
	$.ajax({
		url: '_ajax.php',
		type: 'POST',
		dataType: "json",
		data: { action: 'selectAdvanced', modeles_list: modeles_list },
		success: function(data){
			selected_motorisation = $('#id_motorisation').val();
			selected_nb_portes = $('#id_nb_portes').val();
			//Sélecteur Motorisation
			selMotorisation = elt_js_sel_motorisation;
			for(i in data.motorisation) {
				selMotorisation += '<option value="'+i+'"'+(i==selected_motorisation?' selected="selected"':'')+'>'+data.motorisation[i]+'</option>'+"\n";
			}
			$('#id_motorisation').html(selMotorisation);
			//Sélecteur Nb portes
			selNbPortes = elt_js_sel_nb_portes;
			for(i in data.nb_portes) {
				selNbPortes += '<option value="'+i+'"'+(i==selected_nb_portes?' selected="selected"':'')+'>'+data.nb_portes[i]+'</option>'+"\n";
			}
			$('#id_nb_portes').html(selNbPortes);
		}
	});
}

function addPanier(id_v) {
	$.ajax({
		url: '_ajax.php',
		type: 'POST',
		dataType: "html",
		data: {action: 'addPanier', vehicule_id: id_v},
		success: function(data){
			var res=data.split('|');
			//Mise à jour du tableau JS Panier
			if(indexPanier(id_v) == -1) panier[panier.length] = id_v;
			//console.log(panier);
			//Mise à jour du bloc "Votre sélection"
			refreshPanier(res[1]);
			//Mise à jour des affichages
			if(!$('#bloc_offres_'+res[0]).hasClass('bloc_offres_on')) $('#bloc_offres_'+res[0]).addClass('bloc_offres_on');
			if($('#bloc_offres_'+res[0]).hasClass('bloc_offres')) $('#bloc_offres_'+res[0]).removeClass('bloc_offres');
			$('#bloc_offres_'+res[0]+' .bt_panier_txt').css('display','none');
			$('#bloc_offres_'+res[0]+' .bt_panier_txt_on').css('display','');
			if ($('#popup_bt_selection_on').length ) {
				$('#popup_bt_selection_on').hide();
				$('#popup_bt_selection_off').show();
				$('img.popup_bt_close').click();
			}
			// popup Lors du premier ajout
			//if ( panier.length == 1) {
				var top = popup_top2.replace('{BOUTONS}', '');
				top = top.replace('{POPUP_CLASS}', 'popup2_merci');
				$.nmData( top.replace('{ID}', 'merci') + '<div class="popup_titre">Ma Sélection</div><p class="popup2_merci_contenu" style="margin-top: 30px;">Ce modèle a été ajouté à votre sélection. Souhaitez-vous :</p>' + bouton_popup + popup_bottom2,{ callbacks: {} });
			//}
		}
	});
}

function removePanier(id_v) {
	$.ajax({
		url: '_ajax.php',
		type: 'POST',
		dataType: "html",
		data: {action: 'removePanier', vehicule_id: id_v},
		success: function(data){
			var res=data.split('|');
			//Mise à jour du tableau JS Panier
			ind = indexPanier(id_v)
			if(ind != -1) panier[ind] = undefined;
			//console.log(panier);
			//Mise à jour du bloc "Votre sélection"
			refreshPanier(res[1]);
			//Mise à jour des affichages
			if($('#bloc_offres_'+res[0]).hasClass('bloc_offres_on')) $('#bloc_offres_'+res[0]).removeClass('bloc_offres_on');
			if(!$('#bloc_offres_'+res[0]).hasClass('bloc_offres')) $('#bloc_offres_'+res[0]).addClass('bloc_offres');
			$('#bloc_offres_'+res[0]+' .bt_panier_txt_on').css('display','none');
			$('#bloc_offres_'+res[0]+' .bt_panier_txt').css('display','');
			if ($('#popup_bt_selection_on').length ) {
				$('#popup_bt_selection_off').hide();
				$('#popup_bt_selection_on').show();
				$('img.popup_bt_close').click();
			}
			if ( $('#bloc_panier_'+id_v)) {
				$('#bloc_panier_'+id_v).remove(); // Page panier
				$('#center_panier_contenu').trigger('display_change');
			}
		}
	});
}

function togglePanier(id_v) {
	if(indexPanier(id_v) != -1) {//Le véhicule est dans le panier, il faut l'en enlever
		removePanier(id_v);
	} else {//Le véhicule n'est pas dans le panier, il faut l'ajouter
		addPanier(id_v);
	}
}

function removeOffre(id_v) {
	$.ajax({
		url: '_ajax.php',
		type: 'POST',
		dataType: "html",
		data: {action: 'addDisabled', vehicule_id: id_v},
		success: function(data){
			var res=data.split('|');
			$('#bloc_offres_'+res[0]).css('display','none');
		}
	});
	removePanier( id_v);
}

function refreshPanier(nb_v) {
	if(nb_v>0) {
		$('#panier_nb_vehic').html(nb_v);
		$('#contener_panier').css('display', 'block');
	} else {
		$('#contener_panier').css('display', 'none');
	}
}

function indexPanier(id_v) {
	for(i in panier) {
		if(panier[i]==id_v) return i;
	}
	return -1;
}

function retourAccueil() {
	ga_track_page( GA_PAGENAME);
	$('#left_profil').hide();
	$('#center_results').hide();
	$('#center_panier').hide();
	$('#left_search').show();
	$('#center_offres').show();
	return false;
}

function showSelection() {
	ga_track_page( GA_PAGENAME_PANIER);
	if( $('#center_results').css( 'display') == 'block' ) panier_from = 'center_results';
	else if( $('#center_offres').css( 'display') == 'block' ) panier_from = 'center_offres';
	
	$('#left_search').hide();
	$('#center_offres').hide();
	$('#center_results').hide();
	$('#left_profil').show();
	$('#center_panier').show();
	
	//data.action = 'sendPanier';
	$.ajax({
		url: '_ajax.php',
		type: 'POST',
		dataType: "json",
		data: { action: "sendPanier" },
		success: function(data){
			//Actions à effectuer suite à la soumission Ajax de la Recherche
			html='';
			for(v in data) {
				html_elt = elt_js_panier;
				html_elt = html_elt.replace(/{ID}/g,data[v]['id']);
				html_elt = html_elt.replace('{VISUEL}',data[v]['visuel']);
				html_elt = html_elt.replace('{TYPE}',data[v]['type']);
				html_elt = html_elt.replace('{MODELE}',data[v]['modele']);
				html_elt = html_elt.replace('{VERSION}',data[v]['version']);
				html_elt = html_elt.replace('{MOTOR}',data[v]['motor']);
				html_elt = html_elt.replace('{BOITE}',data[v]['boite']);
				html_elt = html_elt.replace('{COULEUR}',data[v]['coul']);
				html_elt = html_elt.replace('{REVET}',data[v]['revet']);
				html_elt = html_elt.replace('{CHASSIS}',data[v]['chassis']);
				html_elt = html_elt.replace('{PRIX_REMISE}',data[v]['prix_remise']);
				html_elt = html_elt.replace('{PRIX_CATALOGUE}',data[v]['prix_catalogue']);
				html_elt = html_elt.replace('{POURC_REMISE}',data[v]['pourc_remise']);
				html_elt = html_elt.replace('{REMISE_DETAILS}',data[v]['remise_details']);
				html_elt = html_elt.replace('{DEALER_ID}',data[v]['dealer_id']);
				html_elt = html_elt.replace('{RAISON_SOCIALE}',data[v]['raison_sociale']);
				html_elt = html_elt.replace('{ADRESSE}',data[v]['adresse']);
				html_elt = html_elt.replace('{CP}',data[v]['cp']);
				html_elt = html_elt.replace('{VILLE}',data[v]['ville']);
				html += html_elt;
			}
			$('#center_panier_contenu').html(html);
			$('#center_panier_contenu').show();
			
			$('#center_panier_contenu').netscroller({repeat_delay: 50, pas: 20, puceHeight: 45});
			$(".bloc_panier_content .bloc_panier_bt_close").click( function() {
				var id = getEndNumber($(this).attr('id'));
				removePanier(id);
				return false;
			});

			$(".bloc_panier_content .bloc_panier_dealer_carte").click( function(e) {
			  e.preventDefault();
				var id = getEndNumber($(this).attr('id'));
				open_popup_distrib_plan(id);
				return false;
			});
			
			$(".bloc_panier_content .bloc_panier_dealer_amis").click( function() {
				var id = getEndNumber($(this).attr('id'));
				$.ajax({
					url: '_ajax.php',
					type: 'POST',
					dataType: "html",
					data: { action: "sendAmis" },
					success: function(data){
						var retour = data.split('|@@|');
						var top = popup_top2.replace('{BOUTONS}', retour[0]);
						top = top.replace('{POPUP_CLASS}', 'popup2_amis');
						var html = retour[1].replace('{ID_VEHICULE}', id);
						$.nmData( top.replace('{ID}', 'amis_'+id) + html + popup_bottom2,{ callbacks: {
							afterShowCont: function() {
								eval(retour[2]);
							}
						}}	);
					}
				});
				return false;
			});

			$('#bt_retour').click(selectionRetour);
	
		}
	});
	return false;
}

function selectionRetour() {
	if( panier_from == 'center_results' ) {
		ga_track_page( GA_PAGENAME_RESULTATS);
		$('#center_offres').hide();
		$('#center_panier').hide();
		$('#left_profil').hide();
		$('#left_search').show();
		$('#center_results').show();
	} else {
		retourAccueil();
	}
	return false;
}

function validFormAmis( data) {

	erreur = false;

	if( empty( data.civilite) || empty( tab_civ[data.civilite]) ) { erreur = true; setErreur( 'id_amis_'+'civilite_mle'); setErreur( 'id_amis_'+'civilite_mme'); setErreur( 'id_amis_'+'civilite_m'); }
	else { unsetErreur( 'id_amis_'+'civilite_mle'); unsetErreur( 'id_amis_'+'civilite_mme'); unsetErreur( 'id_amis_'+'civilite_m'); }

	if( empty( data.nom) || data.nom == tab_val_profil_default['nom'] || !verif_champ( data.nom, 'name') ) { erreur = true; setErreur( 'id_amis_'+'nom'); }
	else { unsetErreur( 'id_amis_'+'nom'); }

	if( empty( data.prenom) || data.prenom == tab_val_profil_default['prenom'] || !verif_champ( data.prenom, 'name') ) { erreur = true; setErreur( 'id_amis_'+'prenom'); }
	else { unsetErreur( 'id_amis_'+'prenom'); }

	if( empty( data.destinataire) || data.destinataire == tab_val_profil_default['destinataire'] || !verif_champ( data.destinataire, 'email') ) { erreur = true; setErreur( 'id_amis_'+'destinataire'); }
	else { unsetErreur( 'id_amis_'+'destinataire'); }

	if( empty( data.email) || data.email == tab_val_profil_default['email'] || !verif_champ( data.email, 'email') ) { erreur = true; setErreur( 'id_amis_'+'email'); }
	else { unsetErreur( 'id_amis_'+'email'); }
	
	return erreur;
	
}

function valid_form_envoyer_amis() {
	var data = getValAmis();
	var erreur = validFormAmis( data);
	if( erreur == false ) {
		sendFormAmis( data);
	}
	return false;
}

function sendFormAmis( data) {
	data.action = 'sendFormAmis';
	$.ajax({
		url: '_ajax.php',
		type: 'POST',
		dataType: "json",
		data: data,
		success: function(data){
			//Actions à effectuer suite à la soumission Ajax du form profil
			if( data['result'] == 'OK' ) {
				$('.popup_amis').hide();
				$('#popup_amis_reponse_ok').show();
			} else {
				$('.popup_amis').hide();
				$('#popup_amis_reponse_erreur').show();
			}
		}
	});
}

function getValAmis() {
	var data = {
		id_vehicule: $('#id_amis_vehicule').val(),
		civilite: getValFromRadioName( 'civilite'),
		nom: $('#id_amis_nom').val(),
		prenom: $('#id_amis_prenom').val(),
		adresse: $('#id_amis_adresse').val(),
		destinataire: $('#id_amis_destinataire').val(),
		email: $('#id_amis_email').val()
	};
	return data;
}

function ga_track_page( pagename) {
	if( CONFIG == 'PROD') {
		if( !empty( pagename) ) _gaq.push(['_trackPageview', pagename]);
		else _gaq.push(['_trackPageview']);
		
		if( GA_TAB_ACCOUNT_LETTERS.length > 0 ) {
			for( var i = 0 ; i < GA_TAB_ACCOUNT_LETTERS.length ; i++ ) {
				if( !empty( pagename) ) _gaq.push([GA_TAB_ACCOUNT_LETTERS[i]+'._trackPageview', pagename]);
				else _gaq.push([GA_TAB_ACCOUNT_LETTERS[i]+'._trackPageview']);
			}
		}
	}
}

function preloader( images) {
	imageObjArray = new Array();
	for( var i = 0 ; i <= images.length ; i++ ) {
		imageObjArray[i] = new Image();
		imageObjArray[i].src = images[i];
	}
}

function openPopupLoader() {
	$.nmData( popup_loader,{ modal: true, callbacks: {} });
}

function closePopupLoader() {
	$('img#popup_chargement_img_close').click();
}

