// use browser function to get latlon
if ( navigator.geolocation && !readCookie('Latitude') ) 
{
	navigator.geolocation.getCurrentPosition( geoCodeIt, errorCallback, {maximumAge:600000} );
}

function geoCodeIt( position )
{
  // init obj
  var geocoder = new GClientGeocoder();

  // get LocalityName, AdministrativeAreaName, CountryNameCode from latlon
  latlng = new GLatLng( position.coords.latitude, position.coords.longitude );
  geocoder.getLocations(latlng, makeCookies);
  
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return false;
}

function errorCallback( error )
{
  // do something with error.message
}

function makeCookies( response )
{
  // set to 30 days from now
  var date = new Date();
  date.setTime(date.getTime()+(30*24*60*60*1000));
  var expires = "; expires="+date.toGMTString();  

  // store for my usage later
  place = response.Placemark[0];
  document.cookie = 'Latitude='+place.Point.coordinates[1]+''+expires+'; path=/';
  document.cookie = 'Longitude='+place.Point.coordinates[0]+''+expires+'; path=/';
  document.cookie = 'CountryNameCode='+place.AddressDetails.Country.CountryNameCode+expires+'; path=/';
  document.cookie = 'AdministrativeAreaName='+place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName+expires+'; path=/';

  var locality;
  if ( place.AddressDetails.Country.AdministrativeArea.Locality ) 
  {
	  // uses the short codes
	  locality = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
  } else {
	  // uses the long codes
	  locality = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
  }

  document.cookie = 'LocalityName='+locality+expires+'; path=/';

  // refresh cuz sometime
  location.href = location.search;
}

