//Définition des constantes
var _NOTMODIFIED = 0;
var _DATAMODIFIED = 1;
var _NEW = 2;
var _NEWMODIFIED = 3;

var rech_rapide =
{
	status : _NEW,	
	chps : new Array("rechrapide_surface_min","rechrapide_surface_max", "rechrapide_zone_ggl", "rechrapide_perimetre", "rechrapide_id_type_bien_principal"),
	location_vente : '', 	//FR L pour location, V pour vente
							//EN L for rent, V for sell
	id_recherche : 0,	 //0 si nouvelle recherche EN 0 if new search
	
	msg_choix_location_vente : '',
	msg_type_bien_principal : '',
	txt_ori_rechrapide_zone_ggl : '',	//FR : contient le texte d'origine, est initialisé dans le constructeur et est utilisé dans clic_nom_ville
										//EN : contain the original data, is initialised in the constructor and used in clic_nom_ville
	
	trait_en_cours : 0,	   				//FR =1 quand la req ajax sur les zone_dvc est lancé. Sert pour éviter que la sauvegarde soit effectué avant que le traitement soit terminé
						   				//EN =1 if ajax query about zone_dvc is launched. Is used to avoid that saving is done before treatment is finished
	fct_fin_trait_en_cours : '',		//FR contient le code à exècuter quand le traitement encore en cours (au sujet de zone_dvc) est fini.
								 		//EN contains the source code to execute when current treatment (about zone_dvc) is done.
	txt_sel_zone_ggl : '',				//FR contient le texte de l'élément sélectionné par l'autocomplétion
										//EN contain the text selected with autocompletion
	txt_geoloc_ggl : '',				//FR contient le texte utilisé pour la req de géolocalisation google 
										//EN text used for google geolocalization query
										
	constructor : function()
	{	
		Debug.Log('rech_rapide.constructor()');
		
		//FR rech_rapide.constructor() est appellé sur toutes les pages du site
		//FR on en profite pour faire l'initialisation du défilement de partenaire, qui doit également être fait partout
		if ($('partenaires'))
		{	partenaires.constructor();}
		
		$('grise_tout').className='display_none';
		switch(id_langue)
		{
			case '1':
				rech_rapide.msg_choix_location_vente='Il faut choisir entre la location ou la vente.';
				rech_rapide.msg_type_bien_principal="Le type de bien principal n'a pas été sélectionné.";
			break;
		}
		//FR il y a un timeout pour que le onchange du dernier élément soit pris en compte et que si nécessaire
		//EN there is a timeout so that the onchange event is launched
		$('rechrapide_img_rechercher').onclick = function () { setTimeout('rech_rapide.rechercher();', 12); }
		rech_rapide.chps.each( function(id){ $(id).onchange=function(){ rech_rapide.chps_onchange(this); } });
		
		//pour rechrapide_zone_ggl, il faut avec les keypress détecter les changement pour mettre à jour le type et id et aussi afficher ou cacher l'élargissement
		
		//FR initialisation de l'autocomplétion de ville
		//EN town autofill initalisation
		var options_autocompletion = {
				//type : ville_cp
				script:dossier_appli+"/adresse/request_lieu.php?limit=23&type=dvc&",
				varname:"input",
				json:true,
				shownoresults:false,
				timeout:3000, 
				delay:150,
				cache: false,
				callback: function (obj, id) { 
					$('rechrapide_zone_ggl').setAttribute('provient_liste', 1);
					if (obj.nom_ss_doublon!='')
					{
						rech_rapide.txt_geoloc_ggl=obj.nom_ss_doublon;
						$('rechrapide_zone_ggl').value=obj.nom_ss_doublon;
					}
					else
					{	
						rech_rapide.txt_geoloc_ggl=obj.value+' '+obj.info; //FR (ville cp) EN (town postal code)
						$('rechrapide_zone_ggl').value=obj.value;
					}
					
					if (obj.type!='ville')
					{
						$('rechrapide_id_zone_dvc_1').value=obj.id;
						$('rechrapide_type_zone_dvc_1').value=obj.type;
						rech_rapide.txt_sel_zone_ggl=obj.value;
					}
					
					if (obj.type=='dep' || obj.type=='reg')
					{	$('rechrapide_perimetre').style.display='none';}
					else
					{	$('rechrapide_perimetre').style.display='inline';}
					
					rech_rapide.chps_onchange($('rechrapide_zone_ggl'));
				}
			};
		var as_json1 = new bsn.AutoSuggest('rechrapide_zone_ggl', options_autocompletion);		
		
		rech_rapide.txt_ori_rechrapide_zone_ggl=$('rechrapide_zone_ggl').value;
		$('rechrapide_zone_ggl').onclick = function () { rech_rapide.clic_zone_ggl(); }
		$('rechrapide_zone_ggl').onblur = function () { rech_rapide.blur_zone_ggl(); } //on vérifie que le nom/cp correspond à qqch
		
	},	//fin constructor

	clic_zone_ggl : function()
	{
		//FR : retire le msg 'ville, cp' pour permettre à l'utilisateur de saisir la localité sans avoir à effacer au préalable
		//EN : remove the 'town, postal code' to allow the user to type witout deleting the text
		Debug.Log('rech_rapide.clic_zone_ggl()');
		if (rech_rapide.txt_ori_rechrapide_zone_ggl==$('rechrapide_zone_ggl').value)
		{
			$('rechrapide_zone_ggl').value='';
		}
	},

	blur_zone_ggl : function()
	{
		Debug.Log('rech_rapide.blur_zone_ggl()');
		if ($('rechrapide_zone_ggl').value=='')
		{
			//FR : on remet le txt d'origine
			//EN : put again the original text
			$('rechrapide_zone_ggl').value=rech_rapide.txt_ori_rechrapide_zone_ggl;
			rech_rapide.txt_sel_zone_ggl='';
		}
		else
		{
			//FR la vérification des données saisie est faite dans le prep_save
			//EN data are checked in prep_save
			if (rech_rapide.txt_sel_zone_ggl!=$('rechrapide_zone_ggl').value)
			{	//pas de vérification
				rech_rapide.txt_sel_zone_ggl='';
			}
		}
	},
	
	chps_onchange : function(el)
	{	//FR evnmt onchange sur un champ du formulaire
		//EN onchange event on a field of the form
		if (activ_debug==1)
		{	Debug.Log('rech_rapide.chps_onchange('+el.id+')');}
		
		switch(el.id)
		{
			case 'rechrapide_zone_ggl':
				//FR on vérifie que la donnée correspond à quelque chose de correct
				//EN we verify that the data corresponds to something decent
				Debug.Log('rech_rapide.trait_en_cours=1;');
				rech_rapide.trait_en_cours=1;
				rech_rapide.verifie_dvp(el);
			break;	
			//FR élément numérique :
			//EN must be numerical
			case 'rechrapide_surface_min':
			case 'rechrapide_surface_max':
				if (isNaN(parseFloat(el.value)) && el.value!='')
				{	//err : valeur non numérique
					//MsgBox.error(1, 'khgkgh');
					$('exp_m_'+el.id).innerHTML='(REEL)';
					el.value='';
				}
				else
				{	$('exp_m_'+el.id).innerHTML='';}
				break;
		}
		
		if (rech_rapide.status==_NEW)
		{	rech_rapide.status=_NEWMODIFIED;}
		else if (rech_rapide.status==_NOTMODIFIED)
		{	rech_rapide.status=_DATAMODIFIED;}
	},
	
	verifie_dvp : function(el)
	{
		if (activ_debug==1)
		{	Debug.Log('rech_rapide.verifie_dvp('+el.id+') (val : '+el.value+')');}
		if (el.value!='' && el.value!=rech_rapide.txt_sel_zone_ggl)
		{	//FR petit temps de pause, nécessaire pour éviter que le code soit executer avant le code du clic dans la liste de proposition des villes
			//EN little break time, to avoid that the code is execute before the clic code in the list of the towns
			setTimeout("rech_rapide.verifie_dvp_suite('"+el.id+"')",128);
		}
		else
		{	rech_rapide.trait_en_cours=0;}
	},	

	verifie_dvp_suite : function(el_id)
	{
		if (activ_debug==1)
		{	Debug.Log('rech_rapide.verifie_dvp_suite('+el_id+') (val : '+$(el_id).value+')');}
		if (parseInt($('rechrapide_zone_ggl').getAttribute('provient_liste'))==1)
		{
			//FR provient de la liste, rech_rapide.txt_geoloc_ggl est utilisé
			//EN comes from the list, rech_rapide.txt_geoloc_ggl is used
		}
		else
		{	
			rech_rapide.txt_geoloc_ggl=$(el_id).value;
			if (rech_rapide.isNumeric(rech_rapide.txt_geoloc_ggl))
			{	//FR c'est un nombre, on suppose que c'est un code postal ; on ajoute France (pour éviter de se trouver ailleurs dans le monde)
				//EN it is a number, we suppose it is a postal code ; we add France (to avoid to be in an other part of the world)
				rech_rapide.txt_geoloc_ggl+=' France';
			}
		}
		//FR on cherche les coord gps avec géolocalisation google
		//EN the corresponding location is searched with google
		$('iframe_geo').contentWindow.cherche_lieu(rech_rapide.txt_geoloc_ggl, el_id); //appelle verifie_dvp_suite2 une fois la géolocalisation effectuée
	},	
	
	isNumeric : function(value) 
	{
		  if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
		  return true;
	},
	
	verifie_dvp_suite2 : function(lat_lng, el_id)
	{	//FR est appellé par l'iframe de géolocalisation
		//EN is called by the geolocalisation iframe
		Debug.Log('rech_rapide.verifie_dvp_suite2()');
		rech_rapide.trait_en_cours=0;		
		if (lat_lng.constructor.toString().indexOf("Array") > -1)
		{
			$('rechrapide_rech_latitude').value=lat_lng['lat'];
			$('rechrapide_rech_longitude').value=lat_lng['lng'];
			$('rechrapide_perimetre').style.display='inline';
		}
		else
		{
			MsgBox.error(1, lat_lng);
			$(el_id).value=rech_rapide.txt_ori_rechrapide_zone_ggl;
		}
	},
	
	get_defaut_nom_recherche : function ()
	{	//FR nom par défaut d'une recherche d'un membre
		//EN name by default of a search of a member
		Debug.Log('rech_rapide.get_defaut_nom_recherche()');
		var nom='';
		if ($('rechrapide_location_vente_l').checked)
		{	nom+='Location';}
		else
		{	nom+='Vente';}
		
		nom+=' '+$('rechrapide_id_type_bien_principal').options[$('rechrapide_id_type_bien_principal').selectedIndex].text+' ';
		if ($('rechrapide_zone_ggl').value!='' && $('rechrapide_zone_ggl').value!=rech_rapide.txt_ori_rechrapide_zone_ggl)
		{
			nom+=$('rechrapide_zone_ggl').value;
			if ($('rechrapide_perimetre').value>0 && $('rechrapide_type_zone_dvc_1').value!='dep' && $('rechrapide_type_zone_dvc_1').value!='reg')
			{
				nom+=' '+$('rechrapide_perimetre').value+' km ';
			}
		}
		if ($('rechrapide_surface_max').value!='')
		{
		nom+=$('rechrapide_surface_min').value+'-'+$('rechrapide_surface_max').value+'m² ';
		}
		return nom;
	},
	
	clic_save : function()
	{	//FR clic sur btn sauvegarde dans favoris
		//EN clic on save button on favorites
		Debug.Log('rech_rapide.clic_save()');
		rech_rapide.btn_enr='save';
		rech_rapide.save();
	},	
	
	prep_save : function()
	{	
		//FR effectue quelques vérifications avant sauvegarde
		//FR vérifie que location ou vente est coché
		//EN some tests before saving
		//EN rent or sell checked
		Debug.Log('rech_rapide.prep_save()');
		if (!$('rechrapide_location_vente_l').checked && !$('rechrapide_location_vente_v').checked)
		{
			MsgBox.degrise_close=true;
			MsgBox.error(1, rech_rapide.msg_choix_location_vente);
			return false;
		}
		//FR on vérifie que le type de bien principale a été indiqué
		//EN verification : primary asset type filled
		if ($('rechrapide_id_type_bien_principal').selectedIndex==0)
		{
			MsgBox.error(1, rech_rapide.msg_type_bien_principal);
			return false;			
		}

		return true;
	},

	save : function()
	{	//FR si le formulaire est bon, affiche le formulaire de nom/description de recherche
		//EN if the form is good, display the form of name/description of research 
		Debug.Log('rech_rapide.save()');
		if (!rech_rapide.enr_en_cours && rech_rapide.prep_save())
		{			
			rech_rapide.enr_en_cours=true;
					
			if ($('rechrapide_nom_recherche').value=='')
			{	$('rechrapide_nom_recherche').value=rech_rapide.get_defaut_nom_recherche();}
					
			//FR on lance l'enregistrement de la recherche
			//EN we run the save of the research
			if ($('rechrapide_zone_ggl').value==rech_rapide.txt_ori_rechrapide_zone_ggl) //FR le txt d'origine n'est pas à prendre en compte, équivaut à chaîne vide
			{	$('rechrapide_zone_ggl').value='';}									  //EN original text = empry string
			var liste_chps=$('form_rechrapide').toQueryString();
			if ($('rechrapide_zone_ggl').value=='')									  //FR remet txt ori
			{	$('rechrapide_zone_ggl').value=rech_rapide.txt_ori_rechrapide_zone_ggl;} //EN put again original text
			
			Debug.Log('liste_chps '+liste_chps, 2);
				
			if (typeof(id_partenaire)=="undefined")
			{	id_partenaire=0;}
			
			Aj = new Request
			({
				url: dossier_appli+'/recherche/request_recherche.php',
				method: 'post',
				async: false,	//FR l'enregistrement se fait de façon synchrone, l'utilisateur ne doit rien faire tant que non enregistré
								//EN the save is synchronous, the user must do nothing until the save is not finished
				data: {'mode': 'insert', 'liste_chps': liste_chps, 'recherche_rapide': 1, 'id_partenaire': id_partenaire},	
				        
				onRequest: function() 
				{
					Debug.Log('mode: insert ; '+rech_rapide.status+' ; id_recherche: '+rech_rapide.id_recherche, 2);
					ajaxloader.show();
				},  
				        
			    onComplete: function(response) 
			    {
					ajaxloader.hide();
					Debug.Log('Response: ' + response, 2);
					var tab=JSON.decode(response);	
					if (tab['code_retour']<=0)
					{	MsgBox.error(tab['code_retour'], tab['msg_retour']); }
					else
					{	
						rech_rapide.id_recherche=tab['code_retour'];
						rech_rapide.redirige_liste(tab['fic_html']);	
					}	
				},  
				        
			    onFailure: function() 
			    {	alert('erreur ajax');}
						
			}).send();
		}
	},
	
	rechercher : function()
	{
		Debug.Log('rech_rapide.rechercher()');
		if (rech_rapide.trait_en_cours==1)
		{	//FR le traitement sur rechrapide_zone_ggl n'est pas fini, la recherche sera relancé quand ce traitement sera fini
			//EN a rechrapide_zone_ggl treatment is not finished, rechercher function will be launched again when this job is finished
			Debug.Log("rech_rapide.fct_fin_trait_en_cours='rech_rapide.rechercher();");
			rech_rapide.fct_fin_trait_en_cours='rech_rapide.rechercher();';
		}
		else if (rech_rapide.prep_save())	//FR une recherche doit satisfaire les conditions de prep_save()
										//EN a search must satisfied the prep_save() conditions
		{
			rech_rapide.status=_NEWMODIFIED;	//FR il n'y a pas de modification quand on clic sur une recherche, une nouvelle recherche est enregistrée à chaque fois
												//EN there is no modification when we clic on a search, a new search is saved each time
			rech_rapide.save();
		}
	},
	
	redirige_liste : function(url)
	{
		Debug.Log('rech_rapide.redirige_liste()');
		if (id_partenaire>0)
		{	window.location=url;}
		else
		{	window.parent.location=url;}
	}
};
