var urlListeMarques = '';
var urlListeModele = '';
var urlListeCategories = '';

var toutesCategories = [];

var urlListerDynamiquement = '';

var marqueDefaut = '';
var modeleDefaut = '';
var rubriqueDefaut = '';
var typeDefaut = '';
var energieDefaut = '';
var homologationDefaut = '';
var cylindreeDefaut = '';

var criteresAutorises = [];
var listModelPreloaded = [];


// Affiche ou non le libell? "Plus de crit?res", selon s'il y a ou non des crit?res ? saisir
function majAffichagePlusDeCriteres()
{
    if ($('blocPlusCriteres'))
    {

        if ($H(criteresAutorises).keys().without('pays', 'prix', 'elargissement', 'localisation', 'AUCUN').findAll(
                    function (elt)
                    {
                        return $('allArround_' + elt) ? $('allArround_' + elt).visible() : false;
                    }).any())
        {
            $('blocPlusCriteres').show();
        }
        else
        {
            $('blocPlusCriteres').hide();
        }
    }
} // majAffichagePlusDeCriteres






// Formulaire recherche voiture : MAJ de la liste des mod?les quand choix d'une marque
function choixMarque()
{
    if (!$('arroundModele')) return;
    var rubrique = (document.forms.recherche===undefined ? $F('r') : document.forms.recherche.elements['r'].value);
    var marque = (document.forms.recherche===undefined ? $F('r2') : document.forms.recherche.elements['r2'].value);
   
    if (!marque)
    { // S?lection de "toutes les marques"
        var select = $$('#arroundModele select').first();
        if (select)
        {
            viderRemplirSelect(select);
            select.selectedIndex = 0;
            select.disabled = true;
        }
        
        gestionRemplissageListeCategories(toutesCategories);
        
        return;
    }
    //Pour Citroen / Peugeot / Renault
    if (marque == 'VVOCI000' || marque == 'VVOPE000' || marque == 'VVORE000') {
    	var select = $$('#arroundModele select').first();
    	viderRemplirSelect(select,listModelPreloaded[marque]);
    	select.disabled = (select.options.length === 1);
    	return ;
    }
    
    var myAjax = new Ajax.Request(
      urlListeModele,
      {
        method: 'get',
        asynchronous: true,
        parameters: {'r': rubrique, 'm': marque, 'nh': 1},
        onSuccess: function (xhr, liste)
        	{
				liste = liste || xhr.responseText.evalJSON();
                
                var select = $$('#arroundModele select').first();
                if (select)
                {
                    viderRemplirSelect(select, liste);
                    select.disabled = (select.options.length === 1);
                }
                
                gestionRemplissageListeCategories(toutesCategories);
                
                majAffichagePlusDeCriteres();
        	}
      });
      
} // choixMarque



// Formulaire recherche voiture : MAJ de la liste des cat?gories quand choix d'un mod?le
function choixModele()
{
    var rubrique = (document.forms.recherche===undefined ? $F('r') : document.forms.recherche.elements['r'].value);
    var marque = (document.forms.recherche===undefined ? $F('r2') : document.forms.recherche.elements['r2'].value);
    var modele = (document.forms.recherche===undefined ? $F('md') : document.forms.recherche.elements['md'].value);
    
    if (!modele)
    { // S?lection de "tous les mod?les"
        gestionRemplissageListeCategories(toutesCategories);
        return;
    }
    
    var myAjax = new Ajax.Request(
      urlListeCategories,
      {
        method: 'get',
        asynchronous: true,
        parameters: {'r': rubrique, 'm': marque, 'md': modele, 'nh': 1},
        onSuccess: function (xhr, liste)
            {
                liste = liste || xhr.responseText.evalJSON();
                
                gestionRemplissageListeCategories(liste);
                majAffichagePlusDeCriteres();
            }
      });
   
} // choixModele



// Formulaire recherche Voiture : choix d'une cat?gorie => affichage ou non de certaines crit?res
function choixCategorie()
{
    gestionAffichageNPO();
} // choixCategorie



function gestionAffichageNPO()
{
    var codeCategorie = (document.forms.recherche===undefined ? $F('r1') : document.forms.recherche.elements['r1'].value)
    var rubrique = (document.forms.recherche===undefined ? $F('r') : document.forms.recherche.elements['r'].value);
    if (rubrique.substring(0, 3)==='VVO' && $('allArround_nombrePortes'))
    {
        if (codeCategorie === 'TO')
        {
            $('allArround_nombrePortes').show();
        }
        else
        {
            $('allArround_nombrePortes').hide();
        }
    }
}


function gestionRemplissageListeCategories(liste)
{
    var select = $$('#arroundCategorie select').first();
    if (select)
    {
        viderRemplirSelect(select, liste);
        
        var longueur = liste.length;
        /*if (longueur === 1)
        {
            select.selectedIndex = 1;
            $('allArround_categorie').show();
        }
        else*/
        {
            select.selectedIndex = 0;
            if (longueur === 0) {$('allArround_categorie').hide();}
            else {$('allArround_categorie').show();}
        }
    }
    
    gestionAffichageNPO();
} // gestionRemplissageListeCategories




function viderRemplirSelect(select, liste) 
{
    select.immediateDescendants().reject(function (elt) {return elt.value==='';}).each(function (elt) {elt.remove();});
    if (liste)
    {
        liste.each(function (elt) {
                var longueur = select.options.length;
                select.options.length++;
                select.options[longueur].value = elt.c;
                select.options[longueur].text = elt.l;
            });
    }
} // viderRemplirSelect









function verificationMoteurRechercheAlerte(demandeValidationFormulaire)
{
	// Si demande de validation formulaire on submit le formulaire
	// Sinon on renvoie true pour informer que tout est OK
	if(demandeValidationFormulaire){		
		document.getElementById('moteur').submit();
	}else{
		return verificationMoteurRecherche();
	}	
}


function verificationMoteurRecherche()
{


	Validation.add('validate-our-annee', 'Ann?e incorrecte', function (v) {
			return Validation.get('IsEmpty').test(v) ||  /^[0-9]{4}$/.test(v);
		});
	
	Validation.add('validate-our-number-positive', 'Nombre n?gatif', function (v) {
			return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v) && !(v<0));
		});
	
	Validation.add('validate-our-integer-positive', 'Nombre non entier ou n?gatif', function (v) {
			return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v) && !/[^\d]/.test(v) && !(v<0));
		});
	
	Validation.add('validate-our-float-positive', 'Nombre non d?cimal ou n?gatif', function (v) {
			return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v) && /\d+(\.\d+)?/.test(v) && !(v<0));
		});
	
	
	$$('.messageErreurRecherche').invoke('hide');
	
	var isOK = true;
	var anneeMinOK, anneeMaxOK, surfaceMinOK, surfaceMaxOK;
	var localisations, nbrLocalisationsIncorrectes, localisationsIncorrectes;
	var nbrLocalisationsVilleOuCP;
	var elargissementCoche;
	
	if ($('px1') && $F('px1')!='PRIX MAX' && (!Validation.get('validate-our-integer-positive').test($F('px1')) || !Validation.get('validate-our-integer-positive').test($F('px1'))) )
	{
		$('erreur_prixIncorrect').show();
		isOK = false;
	}
	if (criteresAutorises.annee && $('a0') && $('a1'))
	{
		anneeMinOK = Validation.get('validate-our-annee').test($F('a0'));
		anneeMaxOK = Validation.get('validate-our-annee').test($F('a1'));
		if (!anneeMinOK)
		{
			$('erreur_anneeMinIncorrecte').show();
			isOK = false;
		}
		if (!anneeMaxOK)
		{
			$('erreur_anneeMaxIncorrecte').show();
			isOK = false;
		}
		if (anneeMaxOK && !$F('a1').empty())
		{
			if (parseInt($F('a1'), 10) > new Date().getFullYear())
			{
				$('erreur_anneeMaxPlusGrandeAnneeCourante').show();
				isOK = false;
			}
		}
		if (anneeMinOK && anneeMaxOK && !$F('a0').empty() && !$F('a1').empty())
		{
			if (parseInt($F('a1'), 10) < parseInt($F('a0'), 10))
			{
				$('erreur_anneeMaxPlusPetiteAnneeMin').show();
				isOK = false;
			}
		}
	}
	
	if (criteresAutorises.kilometrage && $('km1'))
	{
		if (!Validation.get('validate-our-integer-positive').test($F('km1')))
		{
			$('erreur_kilometrageIncorrect').show();
			isOK = false;
		}
	}
	
	if (criteresAutorises.nombreCouchages && $('nc'))
	{
		if (!Validation.get('validate-our-integer-positive').test($F('nc')))
		{
			$('erreur_nombreCouchagesIncorrect').show();
			isOK = false;
		}
	}
	
	if (criteresAutorises.longueur && $('lg'))
	{
		if (!Validation.get('validate-our-float-positive').test($F('lg')))
		{
			$('erreur_longueurIncorrect').show();
			isOK = false;
		}
	}
	
	if (criteresAutorises.surface && $('sur0') && $('sur1'))
	{
		surfaceMinOK = Validation.get('validate-our-integer-positive').test($F('sur0'));
		surfaceMaxOK = Validation.get('validate-our-integer-positive').test($F('sur1'));
		if (!surfaceMinOK)
		{
			$('erreur_surfaceMinIncorrecte').show();
			isOK = false;
		}
		if (!surfaceMaxOK)
		{
			$('erreur_surfaceMaxIncorrecte').show();
			isOK = false;
		}
		if (surfaceMinOK && surfaceMaxOK && !$F('sur0').empty() && !$F('sur1').empty())
		{
			if (parseInt($F('sur1'), 10) < parseInt($F('sur0'), 10))
			{
				$('erreur_surfaceMaxPlusPetiteSurfaceMin').show();
				isOK = false;
			}
		}
	}
	
	
		
	if (criteresAutorises.localisation && $('lo'))
	{
		localisations = $F('lo').split(',');

		if (localisations.length > 8)
		{
			$('erreur_pasPlus8Localisations').show();
			$('erreur_localisationsSepareesVirgules').show();
			isOK = false;
		}
		
		nbrLocalisationsIncorrectes = 0;
		nbrLocalisationsVilleOuCP = 0;
		localisationsIncorrectes = [];
		localisations.each(function (localisation)
			{
				localisation = localisation.strip();
				if (/\d/.test(localisation))
				{
					if (! /^(_?\d{5})$/.test(localisation) &&
						! /^(\d{2})$/.test(localisation))
					{
						nbrLocalisationsIncorrectes++;
						localisationsIncorrectes.push(localisation);
					}
				}
				else
				{
					nbrLocalisationsVilleOuCP++;
				}
			});
		
		if (nbrLocalisationsIncorrectes)
		{
			if (nbrLocalisationsIncorrectes == 1)
			{
				$('erreur_localisationIncorrecte').show();
				$('strLocalisationIncorrecte').innerHTML = localisationsIncorrectes.join(', ');
			}
			else
			{
				$('erreur_localisationsIncorrectes').show();
				$('strLocalisationsIncorrectes').innerHTML = localisationsIncorrectes.join(', ');
			}
			$('erreur_localisationsSepareesVirgules').show();
			isOK = false;
		}
		
		if (localisations.length > 1 )
		{
			elargissementCoche = $F('distance1') || $F('distance2') || $F('distance3');
			if (elargissementCoche)
			{
				$('erreur_elargissementSeulementPourUneLocalisation').show();
				isOK = false;
			}
		}
		
		//pas de recherche ?largie si aucune localisation renseign?e ou si c'est un d?partement qui est renseign?
		elargissementCoche = $F('distance1') || $F('distance2') || $F('distance3');
		if(($F('lo') == null || $F('lo') == '' || /^(\d{2})$/.test($F('lo').strip())) && elargissementCoche != null){
			$('erreur_elargissementSeulementSiLocalisation').show();
			isOK = false;
		}

	}
	
	return isOK;
	//return false;
}





function choixDynamique(selectOrig, arroundSelectDest, nomCritere, nameSelectDest, defaultText, options)
{
	var myAjax;
	options = options || {};
	
    majAffichagePlusDeCriteres();
    
	if (options.cascadeBefore)
	{
		options.cascadeBefore.apply(this, arguments);
	}
	
	if (criteresAutorises[nomCritere] &&
		(criteresAutorises[nomCritere].indexOf($F(selectOrig)) != -1 ||
		criteresAutorises[nomCritere].indexOf($F(selectOrig).substring(0, 5) + '000') != -1 ||
		criteresAutorises[nomCritere].indexOf($F(selectOrig).substring(0, 3) + '00000') != -1 ||
		criteresAutorises[nomCritere].indexOf($F(selectOrig).substring(0, 1) + '0000000') != -1))
	{
		
		myAjax = new Ajax.Request(
	      urlListerDynamiquement,
	      {
	        method: 'post',
	        asynchronous: !/async=0/.test(window.location.search),
	        parameters: {'r': $F(selectOrig),
	        			 'c': nomCritere},
	        onSuccess: function (xhr, liste)
	        	{
                    if (!liste && xhr.responseText)
                    {
                        liste = xhr.responseText.evalJSON();
                    }
                    
					var str = '';
					if (defaultText)
					{
						str += '<option value="">' + defaultText + '</option>';
					}
                    else
                    {
                        str += '<option value="">&nbsp;</option>';
                    }
					
					var disabled = '';
					if (liste.length > 0)
					{
						liste.each(function (elt) {
		        				str += '<option value="' + elt.c + '">' + elt.l + '</option>';
		       				});
					}
					else
					{
						disabled = 'disabled="disabled"';
					}
					
                    //var className = $(nameSelectDest).className;
                    var className = $$('select[id=' + nameSelectDest + ']').first().className;
                    
                    $(arroundSelectDest).innerHTML = '<select ' + disabled + ' name="' + nameSelectDest + '" id="' + nameSelectDest + '" class="' + className + '">' + str + '</select>';
					
					
					if (disabled !== '' ||
                        !($H(criteresAutorises)[nomCritere].indexOf($F(selectOrig)) >= 0))
					{
						$('allArround_' + nomCritere).hide();
					}
					else
					{
						$('allArround_' + nomCritere).show();
					}
					
                    
	        		if (options.cascadeAfter)
					{
						options.cascadeAfter(selectOrig, arroundSelectDest, nomCritere, nameSelectDest, defaultText);
					}
                    
	        	}
	      });
	}
}





function MAJApparitionMasquageElementsFormulaire(selectOrig, arroundSelectDest, nomCritere, nameSelectDest, defaultText)
{
	Object.keys(criteresAutorises).each(function (nomCritere) {
			if ($('allArround_' + nomCritere))
			{
				if ($H(criteresAutorises)[nomCritere].indexOf($F(selectOrig)) >= 0)
				{
					$('allArround_' + nomCritere).show();
				}
				else
				{
					if ($(nameSelectDest))
                    {
                        $(nameSelectDest).selectedIndex = 0;
                    }
                    
                    
                    $('allArround_' + nomCritere).hide();
                    
                    
				}
			}
		});
} // MAJApparitionMasquageElementsFormulaire









// Appel? quand l'utilisateur s?lectionne un pays dans le menu d?roulant
function selectionPays(ddlPays)
{
	if ($F(ddlPays) == 'FR')
	{
		$('localisationFR').show();
	}
	else
	{
		$('localisationFR').hide();
	}
}


/******************************************************************************
*******************************************************************************
PAGES ALERTE AUTO
*******************************************************************************
******************************************************************************/

/*
* @param demandeValidationFormulaire
* vaut true si on desire valider le form, false sinon
*/
function verif_moteur_auto(demandeValidationFormulaire){
	
	var verif = true;
	if ( $('rdbAidePro1').checked)
	{
		if ( $F('r') == 'VVO00000')
		{
			if ($F('r2').empty())
			{
				$('erreur_vehiculeOccasionAideProSansMarque').show();
				return false;
			}
			
			if ($F('md').empty())
			{
				$('erreur_vehiculeOccasionAideProSansModele').show();
				return false;
			}
		}
	}
	
	verif = verificationMoteurRecherche();
	
	// Si demande de validation formulaire on submit le formulaire
	// Sinon on renvoie true pour informer que tout est OK
	if(demandeValidationFormulaire){
		document.getElementById('moteur').submit();
	}else{
		return verif;
	}	
}



/******************************************************************************
*******************************************************************************
PAGE IMMO NEUF
*******************************************************************************
******************************************************************************/

/*
* @param demandeValidationFormulaire
* vaut true si on desire valider le form, false sinon
*/
function verif_moteur_immoneuf(demandeValidationFormulaire){
	

	//verfication que localisation ne soit pas vide
	if(document.getElementById('prov').value=='deta'){
		if(document.getElementById('pa').selectedIndex == "0"){
			if (document.getElementById('lo').value == "")
			{
				document.getElementById('msg_err_bloc_cnt').style.display = "block";
				document.getElementById("msg_err_bloc").innerHTML = "<span class='puceErr'>" + msgErreur_preciserLocalisation + "</span>";
				document.location.href="#";
				return false;
			}
			else
			{
				document.getElementById('msg_err_bloc_cnt').style.display = "none";
			} 
		}
	}		
		//verification que prix max soit un numerique
		if (IsNumeric(document.getElementById('px1').value)== false){
			document.getElementById('msg_err_bloc_cnt').style.display = "block";
			document.getElementById("msg_err_bloc").innerHTML = "<span class='puceErr'>" + msgErreur_prixMaxQueChiffres + "</span>";
			document.getElementById('px1').value = "";
			document.getElementById('P5M_LGN').value = "";
			document.getElementById('P5M_INV').value = "";
			if(document.getElementById('prov').value=='deta')
				document.getElementById('P5M_LGN').focus();
			else
				document.getElementById('P5M_INV').focus();
			document.location.href="#";
			return false;
		}
		else
		{
			document.getElementById('msg_err_bloc_cnt').style.display = "none";
		}

	
	//vérification des valeurs entrees dans localisation, comptage de virgule
	if (document.getElementById('lo').value != "")
	{
		var chn = document.getElementById('lo').value;
		var longu = chn.length;
		var nbrvirg =0;
		for(i=0; i< longu; i++){
			var elmt = chn.charAt(longu-i);
			if(elmt == ','){
				nbrvirg = nbrvirg + 1;
			}
		}
			
		//alert(nbrvirg);
		if(nbrvirg  > 7){
			document.getElementById('msg_err_bloc_cnt').style.display = "block";
			document.getElementById("msg_err_bloc").innerHTML = "<span class='puceErr'>" + msgErreur_pasPlus8Localisations + "</span>";
			document.location.href="#";
			return false;
		}
		else
		{
				document.getElementById('msg_err_bloc_cnt').style.display = "none";
		}
	}

	// Si demande de validation formulaire on submit le formulaire
	// Sinon on renvoie true pour informer que tout est OK
	if(demandeValidationFormulaire){
		document.getElementById('moteur').submit();
	}else{
		return true;
	}	
}



