//<![CDATA[

// delay between geocode requests - at the time of writing, 100 miliseconds seems to work well
var delay = 100;

// variabile per gestione errore
var counterror = 0;

// ========= Variabili partenza arrivo per invio Ajax  ==================
var paese;
var indirizzocompleto;
var longitudine;
var latitudine;

if (GBrowserIsCompatible()) {

  // ====== Create a Client Geocoder ======
  var geo = new GClientGeocoder();

  // ====== Array for decoding the failure codes ======
  var reasons=[];
  reasons[G_GEO_SUCCESS]            = "Ok";
  reasons[G_GEO_MISSING_ADDRESS]    = "Indirizzo non valorizzato";
  reasons[G_GEO_UNKNOWN_ADDRESS]    = "Indirizzo sconosciuto" ;
  reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Indirizzo non disponibile";
  reasons[G_GEO_BAD_KEY]            = "Chiave API non valida";
  reasons[G_GEO_TOO_MANY_QUERIES]   = "Numero di richieste superato";
  reasons[G_GEO_SERVER_ERROR]       = "La richiesta non pu&ograve; essere inoltrata";
  reasons[403]                      = "Errore 403";

  // ====== Geocoding ======
  function getAddress(search, next) {

      geo.getLocations(search, function (result)
        {
          // If that was successful
          if (result.Status.code == G_GEO_SUCCESS ) {

            var opzioni = '';

            // se ho pił indirizzi possibili
            if (result.Placemark.length>1) {
              
              for (var pi=0; pi<result.Placemark.length; pi++) {

                var citta = "-";
                var indirizzo = result.Placemark[pi].address;

/*
                var accuracy = result.Placemark[pi].AddressDetails.Accuracy;
  
                if (accuracy==9)
                {
                  var citta = "-";
                  var indirizzo = result.Placemark[pi].address;
                }
                else
                {
                  if (result.Placemark[pi].AddressDetails.Country.AddressLine) {
                    var citta = "-";
                    var indirizzo = result.Placemark[pi].AddressDetails.Country.AddressLine;
                  } 
                  else if (result.Placemark[pi].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality!=null ) {
                    var citta = result.Placemark[pi].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                    var indirizzo = result.Placemark[pi].address.split(",")[0]
                  }
                }
*/

                opzioni += citta + '>' + indirizzo + '#';
              };
              next("op|" + opzioni);
              return;
            }
            // se ho un solo indirizzo possibile
            else {        

              var p = result.Placemark[0].Point.coordinates;
              var lat=p[1];
              var lng=p[0];

              var accuracy = result.Placemark[0].AddressDetails.Accuracy;
              
              if (accuracy==9)
              {
                var indirizzo = result.Placemark[0].address;
              }
              else
              {
                if (result.Placemark[0].AddressDetails.Country.AddressLine) {
                  var citta = "-";
                  var indirizzo = result.Placemark[0].AddressDetails.Country.AddressLine;
                } 
                else if (result.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality!=null ) {
                  var citta = result.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                  var indirizzo = result.Placemark[0].address.split(",")[0]
                  if (!isNaN(result.Placemark[0].address.split(",")[1]))
                    indirizzo += ", " + result.Placemark[0].address.split(",")[1]
                }
                
                var paese = result.Placemark[0].AddressDetails.Country.CountryNameCode;
                
              }

              var indirizzo = result.Placemark[0].address;
                
              next("ok|" + indirizzo + "|" + citta + "|" + paese + "|" + lat + "|" + lng);          

            }

          }
          // ====== Decode the error status ======
          else {

            // === if we were sending the requests to fast, try this one again and increase the delay
            if (result.Status.code == G_GEO_TOO_MANY_QUERIES) {
              delay++;
            } else {

              counterror +=1;
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              }     
         
              //indirizzo non corretto ma esistente in formato diverso
              if (reason=="" && result.Placemark[0].AddressDetails.Country.AdministrativeArea==null)
                reason = reasons[G_GEO_UNKNOWN_ADDRESS]
                
              next("ko|" + reason);

            }


          }
        }
      );
      
  }

  function GeoReferenzia(indirizzo, fn_risposta) {
    ResetVariabiliGlobali();        
    if(indirizzo!="") { getAddress(indirizzo,fn_risposta); }
  }


}
// display a warning if the browser was not compatible
else {
  alert("Attenzione, le Google Maps API non sono compatibili con questo browser");
}

    
function ResetVariabiliGlobali()
{ 
    counterror  = 0;        
    paese             ="";
    indirizzocompleto ="";
    longitudine       ="";
    latitudine        ="";
}

//]]>

