var geocoder, location1, location2;

function initialize() {
   geocoder = new GClientGeocoder();
}

function getAddressFromIP() {
   if (google.loader.ClientLocation) {   
      visitor_city = google.loader.ClientLocation.address.city;
      visitor_region = google.loader.ClientLocation.address.region;
      visitor_country = google.loader.ClientLocation.address.country;
      //visitor_countrycode = google.loader.ClientLocation.address.country_code;
      //visitor_lat = google.loader.ClientLocation.latitude;
      //visitor_lon = google.loader.ClientLocation.longitude;
      swfobject.getObjectById("website").sendAddressToFlash(visitor_city + ", " + visitor_region + ", " + visitor_country);
   } else {
      swfobject.getObjectById("website").sendAddressToFlash("USA");
   }
}

function showLocation(address1, address2) {
   geocoder.getLocations(address1, function (response) {
      if (!response || response.Status.code != 200)
      {
         swfobject.getObjectById("website").sendErrorTextToFlash("error1", address1);
      }
      else
      {
         location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
         geocoder.getLocations(address2, function (response) {
            if (!response || response.Status.code != 200)
            {
               alert("Sorry, we were unable to geocode the destination address. Google must be down.");
            }
            else
            {
               location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
               calculateDistance();
            }
         });
      }
   });
}

function calculateDistance()
{
   try
   {
      var glatlng1 = new GLatLng(location1.lat, location1.lon);
      var glatlng2 = new GLatLng(location2.lat, location2.lon);
      var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
      var kmdistance = (miledistance * 1.609344).toFixed(1);
      swfobject.getObjectById("website").sendTextToFlash(location1.address, location1.lat, location1.lon, location2.address, location2.lat, location2.lon, miledistance, kmdistance);
   }
   catch (error)
   {
      swfobject.getObjectById("website").sendErrorTextToFlash("error2", location1.address);
   }
}
