//<![CDATA[

var geocoder = new google.maps.Geocoder();

// ====== Array for decoding the failure codes ======
var GeocoderStatusDescription = {
  "OK": "",
  "UNKNOWN_ERROR": MSG_UNKNOWN_ERROR,
  "OVER_QUERY_LIMIT": MSG_OVER_QUERY_LIMIT,
  "REQUEST_DENIED": MSG_REQUEST_DENIED,
  "INVALID_REQUEST": MSG_INVALID_REQUEST,
  "ZERO_RESULTS": MSG_ZERO_RESULTS,
  "ERROR": MSG_ERROR
};

// ====== Geocoding ======
function getAddress(search, next) {

  geocoder.geocode({'address': search }, function (results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

      var opzioni = '';

      if (results.length>1) {
        for (var pi=0; pi<results.length; pi++) {

          var indirizzo = results[pi].formatted_address;

          opzioni += indirizzo;
          if (pi<results.length-1) opzioni = opzioni + '#';
        }
        next("op|" + opzioni);
        return;
      }
      else {

        var lat=results[0].geometry.location.lat();
        var lng=results[0].geometry.location.lng();
        var addresstype = results[0].types[0];
        
        var indirizzo = '';

        //se ricerca per paese
        if(addresstype=="country") {
          var paese = results[0].address_components[0].short_name;
        }
        else {
          var indirizzo = results[0].formatted_address;
          for (i=0;i<results[0].address_components.length;i++) {
            if(results[0].address_components[i].types[0]=="country") {
               var paese   =  results[0].address_components[i].short_name;
            }            
          }
        }
        
        var accuracy = FromAddressTypeToAccuracy(addresstype);
        next("ok|" + indirizzo + "|" + paese + "|" + lat + "|" + lng + "|" + accuracy);

      }

    }
    else
    {
      var reason="Code " + status;
      if (GeocoderStatusDescription[status]) {
        reason = GeocoderStatusDescription[status];
      }
      next("ko|" + reason);
    }

  });

}

function GeoReferenzia(indirizzo, fn_risposta) {
  if(indirizzo!="") { getAddress(indirizzo,fn_risposta); }
}


//*** conversione in accuracy ***
function FromAddressTypeToAccuracy(adtype)
{
  var ac = 0;
  if(adtype.indexOf("country")!=-1)
    ac = 1;
  if(adtype.indexOf("administrative_area_level_1")!=-1 || adtype.indexOf("administrative_area_level_2")!=-1)
    ac = 2;
  if(adtype.indexOf("locality")!=-1)
    ac = 4;    
  if(adtype=="street_address" || adtype=="route")
    ac = 5;
  if( adtype.indexOf("bus_station")!=-1 || adtype.indexOf("airport")!=-1 || adtype.indexOf("transit_station")!=-1 
    || adtype.indexOf("point_of_interest")!=-1 || adtype.indexOf("park")!=-1 || adtype.indexOf("natural_feature")!=-1 )
    ac = 8;

  return ac;
}

//]]>


