var monGeocodeur;
var adr_cache=null;
var mode_recherche='';
var rare_auto = false;
var latitude = 0;
var longitude = 0;
var templa=0;
var templn=0;

Number.prototype.toRad = function() { return this * Math.PI / 180; }  // convert degrees to radians

Number.prototype.toDeg = function() { return this * 180 / Math.PI; }  // convert radians to degrees (signed)

mot_a_exclure = new Array("saint","paul","jean","victor","france","pierre");

var myGeocode = 
[
	
	{
		types:
		 	{
				0:"locality"
			}
		,
		formatted_address:"Le diamant, 97223, Martinique",
		address_components:
		[
		 	{
						short_name:"MQ"
			}
		],
		geometry:
			{
				location:
					{
						lat:function () { return 14.4837975; },
						lng:function () { return -61.0325805; }
					},
				bounds:
					{
						getCenter:function () { return '(14.475945649999998, -61.034288399999994)'; },
						getSouthWest:function () { return '(14.4615268, -61.0494804)'; }
					}
			}
	},
	{
		types:
		 	{
				0:"locality"
			}
		,
		formatted_address:"Fort de France, 97200, Martinique",
		address_components:
		[
		 	{
						short_name:"MQ"
			}
		],
		geometry:
			{
				location:
					{
						lat:function () { return 14.59971; },
						lng:function () { return -61.07597; }
					},
				bounds:
					{
						getCenter:function () { return '(14.615186299999998, -61.0631704)'; },
						getSouthWest:function () { return '(14.5915576, -61.0945415)'; }
					}
			}
	},
	{
		types:
		 	{
				0:"locality"
			}
		,
		formatted_address:"Les arcs sur argens, 83460, France",
		address_components:
		[
		 	{
						short_name:"FR"
			}
		],
		geometry:
			{
				location:
					{
						lat:function () { return 43.463367; },
						lng:function () { return 6.478766; }
					},
				bounds:
					{
						getCenter:function () { return '(43.453350300000004, 6.4862623)'; },
						getSouthWest:function () { return '(43.4046955, 6.4338432)'; }
					}
			}
	},
	{
		types:
		 	{
				0:"locality"
			}
		,
		formatted_address:"Orange, 84100, France",
		address_components:
		[
		 	{
						short_name:"FR"
			}
		],
		geometry:
			{
				location:
					{
						lat:function () { return 44.1366433; },
						lng:function () { return 4.8050066; }
					},
				bounds:
					{
						getCenter:function () { return '(44.126378100000004, 4.8018222)'; },
						getSouthWest:function () { return '(44.0652392, 4.7246343)'; }
					}
			}
	},
	{
		types:
		 	{
				0:"locality"
			}
		,
		formatted_address:"Saint-Denis, 97400, Réunion",
		address_components:
		[
		 	{
						short_name:"RE"
			}
		],
		geometry:
			{
				location:
					{
						lat:function () { return -20.9114662; },
						lng:function () { return 55.4526995; }
					},
				bounds:
					{
						getCenter:function () { return '(-20.90470045, 55.45017605)'; },
						getSouthWest:function () { return '(-20.9379573, 55.4273129)'; }
					}
			}
	},
	{
		types:
		 	{
				0:"country"
			}
		,
		formatted_address:"La Réunion, 974, Réunion",
		address_components:
		[
		 	{
						short_name:"RE"
			}
		],
		geometry:
			{
				location:
					{
						lat:function () { return -21.114531; },
						lng:function () { return 55.532059; }
					},
				bounds:
					{
						getCenter:function () { return '(-21.1353425, 55.527305649999995)'; },
						getSouthWest:function () { return '(-21.4035321, 55.2097321)'; }
					}
			}
	},
	{
		types:
		 	{
				0:"country"
			}
		,
		formatted_address:"La Martinique, 972, Martinique",
		address_components:
		[
		 	{
						short_name:"MQ"
			}
		],
		geometry:
			{
				location:
					{
						lat:function () { return 14.6340895; },
						lng:function () { return -61.01377485; }
					},
				bounds:
					{
						getCenter:function () { return '(14.634089549999999, -61.013774850000004)'; },
						getSouthWest:function () { return '(14.370833999999999, -61.2419128)'; }
					}
			}
	},
	{
		types:
		 	{
				0:"country"
			}
		,
		formatted_address:"La Guadeloupe, 971, Guadeloupe",
		address_components:
		[
		 	{
						short_name:"GP"
			}
		],
		geometry:
			{
				location:
					{
						lat:function () { return 16.995971; },
						lng:function () { return -62.067641; }
					},
				bounds:
					{
						getCenter:function () { return '(16.369001500000003, -61.50749145000001)'; },
						getSouthWest:function () { return '(15.742032, -62.067641)'; }
					}
			}
	},
	{
		types:
		 	{
				0:"country"
			}
		,
		formatted_address:"Saint-Barthelemy, 97133, Guadeloupe",
		address_components:
		[
		 	{
						short_name:"GP"
			}
		],
		geometry:
			{
				location:
					{
						lat:function () { return 17.9005134; },
						lng:function () { return -62.8205871; }
					},
				bounds:
					{
						getCenter:function () { return '(17.9005134, -62.8205871)'; },
						getSouthWest:function () { return '(17.99833, -63.14529)'; }
					}
			}
	},
	{
		types:
		 	{
				0:"country"
			}
		,
		formatted_address:"Saint Barthelemy, 97133, Guadeloupe",
		address_components:
		[
		 	{
						short_name:"GP"
			}
		],
		geometry:
			{
				location:
					{
						lat:function () { return 17.9005134; },
						lng:function () { return -62.8205871; }
					},
				bounds:
					{
						getCenter:function () { return '(17.9005134, -62.8205871)'; },
						getSouthWest:function () { return '(17.99833, -63.14529)'; }
					}
			}
	},
	{
		types:
		 	{
				0:"country"
			}
		,
		formatted_address:"St Barth, 97133, Guadeloupe",
		address_components:
		[
		 	{
						short_name:"GP"
			}
		],
		geometry:
			{
				location:
					{
						lat:function () { return 17.9005134; },
						lng:function () { return -62.8205871; }
					},
				bounds:
					{
						getCenter:function () { return '(17.9005134, -62.8205871)'; },
						getSouthWest:function () { return '(17.99833, -63.14529)'; }
					}
			}
	}
];
function noaccent(chaine) 
{
  temp = chaine.replace(/[àâä]/gi,"a");
  temp = temp.replace(/[éèêë]/gi,"e");
  temp = temp.replace(/[îï]/gi,"i");
  temp = temp.replace(/[ôö]/gi,"o");
  temp = temp.replace(/[ùûü]/gi,"u");
  return temp;
}
function initialize()
{
	monGeocodeur = new google.maps.Geocoder();
	//monGeocodeur.setCache(new myCache());
}
//monGeocodeur.setBaseCountryCode("fr");



var adr_non_trouve	= "<p class=\"erreur_geocodeur\">Nous n'avons pu trouver cette adresse. Veuillez reformuler votre demande, merci.</p>";
var compilInfo;
var searchNumeric	= false;
var precision 		= ["Adresse inconnue", "Pays", "Région", "Département", "Ville", "Code postal", "Rue", "Intersection", "Adresse", "Maximum"];
var postFormulaire	= false;

//monGeocodeur.setBaseCountryCode='FR';
//monGeocodeur.setViewport(new GLatLngBounds(new GLatLng(40.8272,-5.98222), new GLatLng(51.13666,10.565)));


function IsNumeric(input){
   return (input - 0) == input && input.length > 0;
}


function click_liste_adr(adresse,lat,lng,distance){
	adresse = unescape(adresse);
	document.forms["formBasic"].centreVille.value=adresse;
	document.forms["formBasic"].lat.value=lat;
	document.forms["formBasic"].lng.value=lng;
	document.forms["formBasic"].rayonRecherchea.value=distance;
	document.forms["formBasic"].submit();
}

function ordre_tri(a,b){
	if(a.AddressDetails.Accuracy==b.AddressDetails.Accuracy)
		return 0;
	return ( a.AddressDetails.Accuracy < b.AddressDetails.Accuracy ) ? -1 : 1;
}
function chercheDist(une_adr)
{
	var chaine2 = new String(une_adr['geometry']['bounds'].getCenter());
	chaine2 = chaine2.substring(1,chaine2.length-2);
	virgule = chaine2.indexOf(',');
	lat = chaine2.substring(0,virgule-1);
	lng = chaine2.substring(virgule+1,chaine2.length-1);
	lat1 = parseFloat(lat);
	lng1 = parseFloat(lng);
	var chaine = new String(une_adr['geometry']['bounds'].getSouthWest());
	chaine = chaine.substring(1,chaine.length-2);
	virgule = chaine.indexOf(',');
	lat = chaine.substring(0,virgule-1);
	lng = chaine.substring(virgule+1,chaine.length-1); 
	lat2 = parseFloat(lat);
	lng2 = parseFloat(lng);
	return Math.ceil(Math.acos(Math.sin(lat1.toRad())*Math.sin(lat2.toRad()) + 
			  Math.cos(lat1.toRad())*Math.cos(lat2.toRad()) * Math.cos(lng2.toRad()-lng1.toRad())) * 6371);
}

// fonction retour ajax du geocoding
function AfficheAdresse(reponse,status){
	
	postFormulaire = false;
	var type = {'gg' : ['airport','route','locality','sublocality','bus_station','transit_station','point_of_interest','administrative_area_level_2','administrative_area_level_1','country','postal_code','street_address'], 'dist_defaut' : [1,1,4,1,1,1,2,20,100,500,50,2], 'fr' : ['aéroport','route / place','ville / village','lieu-dit / bourg','station de bus / quartier','station de bus / quartier','point d\'intérêt','département','région','pays / ile','code postal','rue']};
	code_pays_accepte = new Array('FR','MQ','GP','PM','Guyane','PF','YT','RE','GF','TF','WF');
	//	SI ON TROUVE QUELQUE CHOSE
	if (status == google.maps.GeocoderStatus.OK){
		if(adr_cache!=null)
		{
			adr_cache = adr_cache.concat(reponse);
			reponse = adr_cache;
		}
		i=0;
		var listeAdr		= '<p>Veuillez pr&eacute;ciser votre recherche :</p><ul>';
		nb_resultat = 0;
		while((une_adr = reponse[i])!=null)
		{
			j=0;
			// pour les types 'transit station' et 'bus_station' qui ne renvoit pas de code pays
			if(une_adr['types'][0]== 'bus_station' || une_adr['types'][0]== 'transit_station' || une_adr['types'][0]== 'route')
			{
				if(une_adr['formatted_address'].indexOf('France') != -1)
				{
					prec = 'station de bus / quartier';
					nb_resultat++;
					adr_trouve = une_adr['formatted_address'];
					lat_trouve = une_adr['geometry']['location'].lat();
					lng_trouve = une_adr['geometry']['location'].lng();
					dist_trouve = chercheDist(une_adr);
					listeAdr += "<li><span>"+prec+" :</span> <a class=\"link_js_onclik\" onclick=\"click_liste_adr('" + escape(adr_trouve) + "', '" + lat_trouve + "', '" + lng_trouve + "', '" + (dist_trouve*1.5) + "');\">" + adr_trouve + "</a></li>";
				}
			}
			// on verifie que l'adresse trouvée n'est pas etrangere
			while((une_adr_comp = une_adr['address_components'][j])!=null)
			{
				k=0;
				while((un_code_pays = code_pays_accepte[k])!=null)
				{
					if(une_adr_comp['short_name'] == un_code_pays)
					{
						nb_resultat++;
						m=0;
						prec = 'inconnu';
						dist_trouve = 50;
						while((precision = type['gg'][m])!=null)
						{
							if(precision == une_adr['types'][0])
							{
								prec = type['fr'][m];
								if(document.forms["formBasic"].rayonRecherche.options.selectedIndex==0) // auto
								{
									// on cherche la distance entre le centre et un des coins du bounds
									if(une_adr['geometry']['bounds']!=null)
									{
										dist_trouve = chercheDist(une_adr);
									}
									else
									{
										dist_trouve = type['dist_defaut'][m];
									}
								}
								break;
							}
							m++;
						}
						adr_trouve = une_adr['formatted_address'];
						lat_trouve = une_adr['geometry']['location'].lat();
						lng_trouve = une_adr['geometry']['location'].lng();
						listeAdr += "<li><span>"+prec+" :</span> <a class=\"link_js_onclik\" onclick=\"click_liste_adr('" + escape(adr_trouve) + "', '" + lat_trouve + "', '" + lng_trouve + "', '" + (dist_trouve*1.5) + "');\">" + adr_trouve + "</a></li>";
						break;
					}
					k++;
				}
				j++;
			}
			i++;
		}

		if(nb_resultat > 0){
			listeAdr += '</ul><div></div>';

			if(nb_resultat==1){
				document.forms["formBasic"].centreVille.value=adr_trouve;
				if(document.forms["formBasic"].rayonRecherche.options.selectedIndex==0)
					document.forms["formBasic"].rayonRecherchea.value = dist_trouve*1.5;
				document.forms["formBasic"].lat.value = lat_trouve;
				document.forms["formBasic"].lng.value = lng_trouve;
				postFormulaire = true;											// un seul resultat -> on autorise a poster le formulaire
				document.forms["formBasic"].submit();							// parce que Google est asynchrone, on poste le formulaire en JS
			}
			if(nb_resultat>1){
				document.getElementById("geoloc_info").innerHTML = listeAdr;// + compilInfo;
																				// plusieurs resultats -> on affiche la liste
			}
		}
		
		if(nb_resultat == 0){
			document.getElementById("geoloc_info").innerHTML = adr_non_trouve;	// aucun resultat -> message d'erreur
		}
	}
	else 	//SI ON TROUVE RIEN
	{
		document.getElementById("geoloc_info").innerHTML = adr_non_trouve;
	}


}


function bascule_alentour(memCeFi)
{
	if(document.forms["formBasic"].cefi.checked)
	{
		document.forms["formBasic"].rayonRecherche.value="10";
		document.forms["formBasic"].refBien.value="";
		document.forms["formBasic"].refBien.disabled="disabled";
		document.forms["formBasic"].centreVille.value="adresse, ville ou code postal";
		document.forms["formBasic"].centreVille.disabled="disabled";
		document.forms["formBasic"].centreFixe.value=memCeFi;
		document.forms["formBasic"].geoloc_faux.disabled="disabled";
		document.forms["formBasic"].geoloc_vrai.disabled="disabled";
		document.forms["formBasic"].geoloc_vrai.checked="checked";
	}
	else
	{
		document.forms["formBasic"].refBien.disabled="";
		document.forms["formBasic"].geoloc_faux.disabled="";
		document.forms["formBasic"].geoloc_vrai.disabled="";
		document.forms["formBasic"].centreVille.disabled="";
		document.forms["formBasic"].centreFixe.value="";
	}
}
function flipFlopCarte()
{
	if(document.getElementById("map").style.display == 'none')
	{
		document.getElementById("map").style.display = 'block';
		document.getElementById("flipFlopCarte").innerHtml ='Replier la Carte';
	}
	else
	{
		document.getElementById("map").style.display ='none';
		document.getElementById("flipFlopCarte").innerHtml ='D&eacute;plier la Carte';
	}
}
function basculeFormExpert(){
	
	//	IMAGE --> On passe par des regex pour eviter d'avoir en entrer en dur le rep du template actuel
	var imgOpen		= 'fleche-open-form-expert.gif';
	var imgClose	= 'fleche-close-form-expert.gif';
	var imgEnCours	= document.getElementById('img_formExpert').src;
	
	var reg1 		= new RegExp("(fleche-open-form-expert.gif)","g");
	var reg2 		= new RegExp("(fleche-close-form-expert.gif)","g");
	var newImg		= '';
	
	if (imgEnCours.match(reg1)) {
		newImg = imgEnCours.replace(reg1,imgClose);
	} else {
		newImg = imgEnCours.replace(reg2,imgOpen);
	}
	document.getElementById('img_formExpert').src = newImg;


	// TEXTE
	if(document.getElementById("formExpert").style.display == 'none'){
		document.getElementById("formExpert").style.display = 'block';
	} else{
		document.getElementById("formExpert").style.display ='none';
	}

}
function f_nbParPage(url,comp,rewrite){
	if(rewrite){
		if(comp == 10){ 
			url2 = './';
		} else { 
			url2 = 'biens-0-n'+comp+'-tridistasc.html';
		}
		window.location.href=url2;
	} else {
		url2="&nbpa="+comp;
		window.location.href=url+url2;
	}
}

function f_nbParPageRewrite(url,comp){
	if(comp == 10) url2 = './';
	else url2 = 'biens-0-n'+comp+'-trisurfasc.html';
	window.location.href=url2;
}

function js_viager(ref)
{
	if(ref)
	{
		document.forms["formBasic"].vente.checked="";
		document.forms["formBasic"].location.checked="";
	}
	else	document.forms["formBasic"].viager.checked="";

}
	

function js_form_geoloc(val)
{
	if(val)
	{
		document.forms["formBasic"].centreVille.disabled="";
		document.forms["formBasic"].rayonRecherche.disabled="";
	}
	else
	{
		document.forms["formBasic"].centreVille.disabled="disabled";
		document.forms["formBasic"].rayonRecherche.disabled="disabled";
	}
}
function js_form_check_ref()
{
	if((document.forms["formBasic"].rbien.value).length > 8)
	{
		document.forms["formBasic"].rbien.value="";
		alert("La référence ne doit pas dépasser les 8 caractères.\n");
	}
}



function js_check_form(obj)
{
	document.forms["formBasic"].js.value = 1; // debug des adresses succintes dans base gps
	
	//	si rien de renseigne dans la recherche -> "tous les biens" est coche
	if((document.forms["formBasic"].centreVille.value=="adresse, ville ou code postal" || document.forms["formBasic"].centreVille.value=="") && document.forms["formBasic"].geoloc[0].checked){
		document.forms["formBasic"].geoloc[1].checked="checked";
		document.forms["formBasic"].rayonRecherche.disabled="disabled";
	}
	
	//	si la recherche a sa valeur par defaut -> on vide le champ et on coche "tous les biens"
	if(document.forms["formBasic"].centreVille.value == "adresse, ville ou code postal"){
		document.forms["formBasic"].centreVille.value="";
	}
	
	//	si "tous les biens" est cochee -> on vide le champ
	if(document.forms["formBasic"].geoloc[1].checked){
		document.forms["formBasic"].centreVille.value = '';
	}

	if(document.forms["formBasic"].rayonRecherche.options.selectedIndex==0)
		rare_auto=true;
		
	address = document.forms["formBasic"].cevi.value;
	
	//	si c'est une recherche numerique
	if(IsNumeric(address)) {
		searchNumeric = true;
		if(address.substr(0,2)=='97'){
			if(address.length == 2)	address='reunion'; 
		}
		else address=address + ' fr';
	}
	
	//	soit on recherche sur tous les biens
	if(address == ''){
		document.forms["formBasic"].geoloc[1].checked="checked";
		document.forms["formBasic"].rayonRecherche.disabled="disabled";
		return true;
	}
	else
	{
	//	soit on recherche via geolocalisation
	// on cherche en premier dans le cache
	m=0;
	adr_cache=Array();
	for(m=0;m<myGeocode.length;m++)
	{
		adr=myGeocode[m]['formatted_address'];
		adr=noaccent(adr.toLowerCase());
		var reg=new RegExp("[ ,;-]+", "g");
		adr = adr.replace(reg,' ');
		address = address.replace(reg,' ');

		//alert('adr '+adr+' adresse '+noaccent(address.toLowerCase()));
		if(adr.indexOf(noaccent(address.toLowerCase()))!=-1) // adresse trouvee dans le cache
		{
			adr_cache=adr_cache.concat(myGeocode[m]);
			break;
		}
	}
	if (monGeocodeur)  	monGeocodeur.geocode( { 'address': address, 'language': 'fr', 'country': 'FR'}, AfficheAdresse);

		//return postFormulaire;
		return false;
	}

}
function verifAlerteMail(form)
{
	if(form.elements['mdp_alerte'].value!='' || form.elements['tel_alerte'].value!='') // si un de ces champs est rempli alors c'est un robot spam
	{
		return false;
	}

	var re=RegExp("^([a-zA-Z0-9_-])+([.]?[a-zA-Z0-9_-]{1,})*@([a-zA-Z0-9-_]{2,}[.])+[a-zA-Z]{2,3}$");
	var agence = form.elements['mail_alerte'].value;
	var tab = new Array();
	tab = agence.split('---',2);
	if(tab[1]!=null) mail = tab[1];
	else mail = agence;
	if(!re.test(mail)){
		alert('Merci de renseigner une adresse email valide dans le champ "Votre email"');
		return false;
	}

	return true;
}
