//<![CDATA[
    
    if (GBrowserIsCompatible()) { 

    var map;
    var geo;
    var reasons=[];
	var country;
	var localiserAfter=false;
	var Zoom;
	var lastResult;
	var lastMarker;
	var Alert_type;
	var MustExact;
	var nbVilleLastresult;
	var lastGPS;
	var localiserClicked=false;
	var search_value;//adresse recherché avant geo_loc
	var not_use_signet;
	
	function slctCountry(c){
	   country=c;
	   search_value = c+" ";
	   //on change de pays=> les adresses sont suprimé
       clearAll(); 	
	   showAddress(5,"all",false);
	}
	
	function clearAll(){
	   document.getElementById("PostalCodeNumber").value="";
	   document.getElementById("LocalityName").value="";
	   document.getElementById("adresse").value="";
	}
	// si ville sous la forme 13090 Aix-en-Provence, France on extrait nom ville sinon return false
	function getGvilleName(marker){
	//return dump(marker);
	 if(itemFinder(marker,"DependentLocalityName"))return itemFinder(marker,"DependentLocalityName");
	 if(itemFinder(marker,"LocalityName"))return itemFinder(marker,"LocalityName");
	 return false;
	 /*cp_pos=adresse.indexOf(document.getElementById("cp").value, 0);
	 pays_pos=adresse.lastIndexOf(',', ville.lenght);
	 if(cp_pos<0 || pays_pos<0) return false;
	 result =  adresse.substring(cp_pos+document.getElementById("cp").value.length,pays_pos);
	 return result;*/
	}
	
	function setVille(){
	   if(getGvilleName(lastMarker)&& itemFinder(lastMarker,"PostalCodeNumber")==document.getElementById("PostalCodeNumber").value){
	    //document.forms[1].LocalityName.disabled=true;
		document.getElementById("LocalityName").value=getGvilleName(lastMarker);
		document.getElementById("adresse").focus();
		}else{ //nom ville unmatch on  reset ville et focus sur le input
		document.getElementById("LocalityName").value="";
		}
	}
	
	//13300=> Salon-de-provence
    function cpToVille(cp){
		document.getElementById("find-cp").innerHTML ="";
		if(isEmpty(cp)|| ! isInteger(cp)) return;
	   ville="";
	   localiserCliked=false;
	   document.getElementById("localiserAfterCheckbox").innerHTML="";
	   document.getElementById("map-notice").innerHTML ="";
	   document.getElementById("LocalityName").value="";
       pays = document.getElementById("id_pays").options[document.getElementById("id_pays").selectedIndex].text;
          search_value = cp+" ,"+pays;
          showAddress(12,"cp",false);
		  setTimeout("setVille()", 400);
		  
  }

     var nbCpVilleLastresult;//variable qui permet de retenir le nombre de résultats pour la requete cp-ville avant de faire la requete ville (pour zommer)
	 
	 function cpVilleChecker(ville){
	 document.getElementById("find-locality").innerHTML = "";
	 if(not_use_signet==false){
	 window.location.href="#map_signet";
	 }
	 var cp=document.getElementById("PostalCodeNumber").value;
	 if(isEmpty(cp)||isEmpty(ville)  || ! isInteger(cp)) return; //pas de recherche si champs vide ou CP pas un nombre
	 localiserClicked=false;
	    document.getElementById("localiserAfterCheckbox").innerHTML="";
          document.getElementById("map-notice").innerHTML ="";
	    var cp=document.getElementById("PostalCodeNumber").value;
		pays = document.getElementById("id_pays").options[document.getElementById("id_pays").selectedIndex].text;
		 // search_value = pays+", "+ville+" ,"+cp ;
		  search_value = ville+" "+cp+", "+pays ;
          showAddress(12,"ville",false);  //le Cp avec cette ville existe?
		setTimeout(function(){
                nbCpVilleLastresult=nbVilleLastresult; //savoir le nb de resultat avec cp ville pays pour la fct localiser
		     if (nbVilleLastresult>0){//il y a eu un résultat avec ce CP
				 document.getElementById("SubAdministrativeAreaName").value=itemFinder (lastMarker,"SubAdministrativeAreaName");
				 document.getElementById("AdministrativeAreaName").value=itemFinder (lastMarker,"AdministrativeAreaName");
				 search_value = ville+" ,"+pays;
				 showAddress(13,"ville",true);//on zoom sur la ville si c'est possble (mustexact=true, 1 seul resultat)
			}

			 }, 400);
	 }
	 
	 function LocaliserAfter(){
	   if (localiserClicked==true)localiserClicked=false;
	   if(localiserClicked==false)localiserClicked=true; //switch
	 
	 }
	  function localiser_not_use_signet(){
	  	not_use_signet = true;
	  	localiser();
	  }
	 
	 function localiser(){
	 	 var cp=document.getElementById("PostalCodeNumber").value;
	 	 var ville=document.getElementById("LocalityName").value;
	 	 var adresse=document.getElementById("adresse").value;
	 	 if(isEmpty(cp)||isEmpty(ville)  || ! isInteger(cp)||isEmpty(adresse) ){
	 	   alert (MessageCantLocalise);
	 	   return;
	 	 }
	     localiserCliked=true;
	     document.getElementById("map-notice").innerHTML ="";
	     cpVilleChecker(ville); //on check si ville-cp sont ok avant de localiser ladresse-cp-ville
		  document.getElementById("localiser-button").disabled=true;//1 seul localisation a la fois
		 var pays = document.getElementById("id_pays").options[document.getElementById("id_pays").selectedIndex].text;
		 setTimeout(function(){
		     //alert (nbCpVilleLastresult);
		     setTimeout(function(){document.getElementById("localiser-button").disabled=false;},400);
			 //alert (nbCpVilleLastresult);
		     if (nbCpVilleLastresult>0){//localisation cp-ville OK
				//search_value = adresse+" ,"+cp+" "+ville+" ,"+pays;
				search_value = adresse+" ,"+pays+" "+ville+" ,"+cp;
				
				// search_value = pays+" , "+adresse+", "+ville+" ,"+cp;
				 showAddress(16,"adress",false);//localisation CP ville avec message action si le résultat ne trouve pas des info pour ThoroughfareName
				 setTimeout(function(){
				 //alert(nbVilleLastresult);
				 //alert (dump(lastMarker));
				    if(nbVilleLastresult==1 && lastMarker.AddressDetails.Accuracy>5){//adresse mis donc doit etre sup au niveau CP
					   document.getElementById("map-notice").innerHTML = "<font color=red>"+MessageisLocalised+".</font>";
					   document.getElementById("localiserAfterCheckbox").innerHTML=localiserAfterCheckbox_part1+labelCheckboxLocalised+localiserAfterCheckbox_part2
					}else{
					   cpVilleChecker(ville);//proposition d'adresse pas implementé si on localise pas adress+cp+ville+pays on revien au niveau ville+cp+pays
					  document.getElementById( "map-notice").innerHTML = "<font color=red>"+MessageisNotLocalised+".</font>"; 
					  document.getElementById("localiserAfterCheckbox").innerHTML=localiserAfterCheckbox_part1+labelCheckboxNotLocalised+localiserAfterCheckbox_part2;
					}
					localiserClicked=true;
				 },400);
			 }	  
		}, 400);
	 }
	 
	 function submiter(){
	    if(localiserAfter==false && localiserClicked ==true){
		    document.getElementById("gps").value=lastGPS;
		}else {
		  document.getElementById("gps").value="";
		}
	    //alert (document.getElementById("gps").value);
		if(localiserClicked==false){//on a cliqué sur locliser
	       if(!confirm(submitAndNotLocalised))return false;//on ne pas continuer sans avoir localiser
		}
		document.getElementById("LocalityName").disabled=false;//si disabled la var n'est pas posté 
		return true;
	 }

    function load() {
      map = new GMap(document.getElementById("map"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());

      
      // ====== Create a Client Geocoder ======
      geo = new GClientGeocoder(); 


	  

	  
      // ====== Array for decoding the failure codes ======
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      
      // ====== START WITH FRANCE ======
      search_value= "FRANCE";
	  lastResult="";
	  showAddress(5,"all",false);
    }



      
      // ====== Geocoding ======
      function showAddress(zoom,alert_type,mustExact) {
	   // Alert_type=alert_type;
		MustExact=mustExact;//mettre en gloabal les parametre pour accce dans le callback
		lastResult="";
        nbVilleLastresult=0;
        // ====== Perform the Geocoding ====== 
        Zoom = zoom;
		//alert (search_value);
        geo.getLocations(search_value,resulter);
		
      }
	  
	  
	  
	  function resulter (result)
          { //alert (dump(result));
		   zoom = Zoom; //zoom local = Zoom général	
            if (result.Status.code == G_GEO_SUCCESS && (result.Placemark.length == 1 ||MustExact==true)) { //on ne gère pas la liste de proposition pour linstant
              // ===== If there was more than one result, "ask did you mean" on them all =====
			 // alert(result.Placemark.length);
              nbVilleLastresult=result.Placemark.length;
              if (result.Placemark.length > 1) {
			      if(MustExact==true)return;//one result max=>break
                document.getElementById("message").innerHTML = proposition+":";
                // Loop through the results
                for (var i=0; i<result.Placemark.length; i++) {
                  var p = result.Placemark[i].Point.coordinates;
                   document.getElementById("message").innerHTML +="<br>"+(i+1)+": <a href='javascript:place(" +p[1]+","+p[0]+",14)'>"+ result.Placemark[i].address+"</a>";
                }
              }
              // ===== If there was a single marker, is the returned address significantly different =====
              else {
          // alert ("Alert_type"+Alert_type);
			//alert ("itemFinder"+itemFinder(result.Placemark[0],"PostalCodeNumber));
			//document.getElementById("map-notice").innerHTML = dump(result.Placemark[0]);
				map.clearOverlays(); 
			    lastResult = result.Placemark[0].address;
				lastMarker = result.Placemark[0];
				if (Alert_type== "cp") {
				    var cp = itemFinder(result.Placemark[0],"PostalCodeNumber");
				    if (cp==false || cp!=document.getElementById("PostalCodeNumber").value){
						document.getElementById("find-cp").innerHTML = error_cp;
						clearAll();
						return;
					}
				 }
				 //on ne peut pas vérifier la ville Aix en provence 13100=> donne 13100, france
				 if (Alert_type== "adresse") {
				   var ThoroughfareName=itemFinder(result.Placemark[0],"ThoroughfareName");
				   if (ThoroughfareName==false){//il n'y a pas de nom de rue pour cette adressse
				       return;
				   }
				 }
				if (Alert_type== "ville"){ //une seule ville trouvé avec ville, pays=> correction ortho et mise en forme auto si on cherche la ville (Alert_type=ville) + alert si la ville semble incorect
					var LocalityName = itemFinder(lastMarker,"LocalityName");
					/*var cp =  itemFinder(lastMarker,"PostalCodeNumber"); //on ne peut pas vérifier le CP: aix en provence, france=> ne renvoi pas le CP de aix en provence
					//la ville ne semble pas correspondre avec le CP rentré
					//alert (dump(lastMarker));
					if(cp==false || LocalityName ==false || different (cp,document.getElementById("PostalCodeNumber").value)){
						alert(error_ville);
					    document.getElementById("adresse").value="";
					    document.forms[1].PostalCodeNumber.focus();
					} */
					if(document.getElementById("LocalityName").value.length==0){//on vérifie  que ville rentré ne soit pas vide
						document.getElementById("find-locality").innerHTML = error_ville;
						return;
					}
					if(LocalityName!=false){
					document.getElementById("LocalityName").value=getGvilleName(result.Placemark[0]);
					}
                  }
                  var p = result.Placemark[0].Point.coordinates;
                  place(p[1],p[0],zoom);
                  document.getElementById("message").innerHTML = "<font color=green>Localisation: "+lastResult+"</font>";

				 // alert ("prime abord:"+lastResult);
               // }
              }
            }
            // ====== Decode the error status ======
            else {
             
             if (Alert_type == "all"){
             	var reason="Code "+result.Status.code;
             	 if (reasons[result.Status.code]) {
              	  reason = reasons[result.Status.code]
              	} 
              	alert('Could not find  ' + reason);
              }
              if (Alert_type== "ville"){
              	document.getElementById("find-locality").innerHTML = error_ville;
              	document.getElementById("adresse").value="";
              }
			  if (Alert_type== "cp") {
				document.getElementById("find-cp").innerHTML = error_cp;
				clearAll();
			  }
            }
          }
	  
	  
    }
    
    // display a warning if the browser was not compatible
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
	
	
	function itemFinder(arr,toFind){
	    var resultat=false;
	    if(typeof(arr) == 'object') { //Array/Hashes/Objects
			for(var item in arr) {
				var value = arr[item];
				if(typeof(value) == 'object') { //If it is an array,
					Tresultat=itemFinder(value,toFind);
					if(Tresultat!=false)resultat=Tresultat;
				} else 
				{   //alert (item);
					if(item==toFind) {
					   resultat=value;
					}
				}
			}
		}
		//alert(resultat);
	return resultat;
	}
	
	
	
//#########################################################################		
	
      // Blackpool Community Church Javascript Team
    // http://www.commchurch.freeserve.co.uk/   
    // http://econym.googlepages.com/index.htm
    // ===== list of words to be standardized =====
    var standards = [   ["road","rd"],   
                        ["street","st"], 
                        ["avenue","ave"], 
                        ["av","ave"], 
                        ["drive","dr"],
                        ["saint","st"], 
                        ["north","n"],   
                        ["south","s"],    
                        ["east","e"], 
                        ["west","w"],
                        ["expressway","expy"],
                        ["parkway","pkwy"],
                        ["terrace","ter"],
                        ["turnpike","tpke"],
                        ["highway","hwy"],
                        ["lane","ln"]
                     ];

    // ===== convert words to standard versions =====
    function standardize(a) {
      for (var i=0; i<standards.length; i++) {
        if (a == standards[i][0])  {a = standards[i][1];}
      }
      return a;
    }
	
	
    // ===== check if two addresses are sufficiently different =====
    function different(a,b) {
      // only interested in the bit before the first comma in the reply
      var c = b.split(",");
      b = c[0];
      // convert to lower case
      a = a.toLowerCase();
      b = b.toLowerCase();
      // remove apostrophies
      a = a.replace(/'/g ,"");
      b = b.replace(/'/g ,"");
      // replace all other punctuation with spaces
      a = a.replace(/\W/g," ");
      b = b.replace(/\W/g," ");
      // replace all multiple spaces with a single space
      a = a.replace(/\s+/g," ");
      b = b.replace(/\s+/g," ");
      // split into words
      awords = a.split(" ");
      bwords = b.split(" ");
      // perform the comparison
      var reply = false;
      for (var i=0; i<bwords.length; i++) {
        //GLog.write (standardize(awords[i])+"  "+standardize(bwords[i]))
        if (standardize(awords[i]) != standardize(bwords[i])) {reply = true}
      }
      //GLog.write(reply);
      return (reply);
    }
	
	
		  // == use different GDirections for adding and dragging, it is just simpler that way ==
      var dirn1 = new GDirections();
      var dirn2 = new GDirections();
	
	  // == when the "drag marker" load event completes, move the marker ==
      GEvent.addListener(dirn2,"load", function() {
        var p=dirn2.getPolyline().getVertex(0);
        lastmarker.setPoint(p);
		//alert(lastmarker.getPoint());
      });
      
	function createMarker(p) {
        var marker = new GMarker(p,{draggable:true});
        GEvent.addListener(marker, "dragend", function() {
          lastmarker = marker;
          var point = marker.getPoint();
          dirn2.loadFromWaypoints([point.toUrlValue(6),point.toUrlValue(6)],{getPolyline:true});
        });
		//alert(marker.getPoint());
        return marker;
      }

      // ====== Plot a marker after positive reponse to "did you mean" ======
      function place(lat,lng,zoom) {
        var point = new GLatLng(lat,lng);
		lastGPS=lat+";"+lng;
        map.setCenter(point,zoom); 
        map.addOverlay(createMarker(point));
        document.getElementById("message").innerHTML = "";
      }

$(document).ready( load );
$(document).unload( GUnload );

    //]]>
	
	
	
	
	
	
	
	
	/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];
 
  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}

