/* Implement this function for handling the result
function gotGeocodedAddress(lat, lng, city) {
	
}
function gotNoGeo() {
	
}
 */

function addAddressToMap(response) {
	if (!response || response.Status.code != 200) {
		$.log("Unable to geocode address");
	} else {
		place = response.Placemark[0];
		var city = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
		$.log("Found: " + place.address);
		gotGeocodedAddress(null, null, city);
	}
}

function html5geo() {
	$.log("Determining current position using browser geolocation");
	navigator.geolocation.getCurrentPosition(function(position) {
		// Did we get the position correctly?
			$.log("Got latitude: " + position.coords.latitude);

			try {
				// Start up a new reverse geocoder for addresses?
				geocoder = new GClientGeocoder();
				geocoder.getLocations(position.coords.latitude + ','
						+ position.coords.longitude, addAddressToMap);
			} catch (e) {
				$.log("GClientGeocoder probably not available");
			}
		}, function(error) {
			// Error callback
			$.log("User didn't gave us access to position: " + error);
			/*
			 * switch (error.code) { case error.TIMEOUT: alert('Timeout');
			 * break; case error.POSITION_UNAVAILABLE: alert('Position
			 * unavailable'); break; case error.PERMISSION_DENIED:
			 * alert('Permission denied'); break; case error.UNKNOWN_ERROR:
			 * alert('Unknown error'); break; }
			 */
			fallbackgeo();
		}, {
			maximumAge : Infinity,
			timeout : 0
		});
}

function google_api() {
   	$.log("Using Google AJAX APIs to determine location");
   	
   	if (google.loader.ClientLocation)
   	{
   		var city = google.loader.ClientLocation.address.city;
   	   	$.log("Got: " + city);
   	   	var lat = google.loader.ClientLocation.latitude;
   	   	var lng = google.loader.ClientLocation.longitude;
   	  	$.log("Got lat/lng: " + lat + " / " + lng);
   		gotGeocodedAddress(lat, lng, city);
   		return true;
   	}
   	else{
   		$.log("No clientlocation for us.. ");
   	}
   	return false;
}
    
    
function google_gears() {
	$.log("Falling back to google gears");

	// Requires:
// <!-- Google gears geolocating -->
// <script type="text/javascript"
// src="http://code.google.com/intl/nl-NL/apis/gears/gears_init.js"></script>

    if (!google.gears.factory.hasPermission) {
         var siteName = 'My Site';
         var icon = 'images/myIcon.png';
         var msg = 'This site would like to use Google Gears to enable fast, '
                   + 'as-you-type searching of its documents.';
         
         var allowed = google.gears.factory.getPermission(siteName, icon, msg);
       }
     
	 
	var geo = google.gears.factory.create('beta.geolocation');
	geo.getCurrentPosition(function(postition) {
		$.log("Got latitude: " + position.latitude);
		// updatePosition callback
			geocoder = new GClientGeocoder();
			geocoder.getLocations(position.latitude + ',' + position.longitude,
					addAddressToMap);
		}, function(positionError) {
			$.log("Gears geolocation failed: " + positionError.message);
		});
}


function fallbackgeo() {
	  $.log("Falling back to less quality database");
	  var url =  "http://www.ipinfodb.com/ip_query.php?output=json&callback=?";
	   $.getJSON(url, function(data) {
		   try {
			   var city = data['City'];
			   $.log("Got city: [" + city + "]");
			   gotGeocodedAddress(null, null, city);
		   } catch (e) {
			   // Couldn't find anything. Ok, fine.
		   }
		});
}

function getUserCityBasedOnIP() {
	try
		{
		// First try the Google AJAX APIs
		if (google_api()) {return;}
		// First try: http://merged.ca/iphone/html5-geolocation
		if (navigator.geolocation) {
			html5geo();
		} else {
			// Client is not compliant with the spec, fallback
			fallbackgeo();
		}
		}
	catch(e)
	{
		// No geo found, let just say we're in amsterdam.
		city = "the Netherlands";
		lat = 52.35;
		lng = 4.916;				
		gotGeocodedAddress(lat, lng, city);
	}
}

