Geolocation = function() {};
Geolocation.prototype = {

	get_location_async:function(chain) {
		
		if (typeof chain == 'undefined') {
			this.get_cookie_location(true);
			return;
		}
		
		this.get_cookie_location(chain);
		
	},
	get_cookie_location:function(chain) {

		geolocation = $.cookie('golfthis.geolocation');
		geolocation = JSON.parse(geolocation, function (key, value) {
               var a;
               if (typeof value === 'string') {
                   a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                   if (a) {
                       return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                           +a[5], +a[6]));
                   }
               }
               return value;
           });
		
		if (geolocation) {
			$(window).trigger('geolocation.loaded', geolocation);
		}
		else {
			if (chain) this.get_browser_location();
		}
	},
	get_browser_location:function() {
		var self = this;
		// try browser geolocation services
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				self.geocode_reverse({latitude:position.coords.latitude, longitude:position.coords.longitude});
			},  function() {self.get_ip_location()});
		}
		// try google gears geolocation 
		else if (google.gears) {
		    var geo = google.gears.factory.create('beta.geolocation');
		    geo.getCurrentPosition(function(position) {
		      	self.geocode_reverse({latitude:position.coords.latitude, longitude:position.coords.longitude});
		    },  function() {self.get_ip_location()});
		}
	},
	get_ip_location:function() {
		$.ajax({
			context:this,
			url:'http://api.ipinfodb.com/v2/ip_query.php?key=a767d9279824ea42c8b1f893bf41b4c34afc8da7b43e048d64bff3d2874a9db2&output=json&timezone=false',
			dataType:'jsonp',
			success:function(data) {
				this.geocode_reverse({latitude:data.Latitude, longitude:data.Longitude});
			},
			error:self.throw_geolocalization_error
		});
	},
	throw_geolocalization_error:function() {
		$(window).trigger('geolocation.error');
	},
	geocode:function(address) {
		var self = this;
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode( { 'address': address}, function(results, status){self.parse_geocode_results(results, status);});
	},
	geocode_reverse:function(coords) {
		var self = this;
		var geocoder = new google.maps.Geocoder();
		var latlng = new google.maps.LatLng(parseFloat(coords.latitude), parseFloat(coords.longitude));
		geocoder.geocode({'latLng': latlng}, function(results, status){self.parse_geocode_results(results, status);});
	},
	parse_geocode_results:function(results, status) {
		var geolocation = null;
		if (status == google.maps.GeocoderStatus.OK) {

			geolocation = {latitude:results[0].geometry.location.lat(), longitude:results[0].geometry.location.lng()}

			for(var i=results[0].address_components.length;i--;) {

				if (results[0].address_components[i].types[0] == "administrative_area_level_1") {
					geolocation.state = results[0].address_components[i].long_name;
					geolocation.state_code = results[0].address_components[i].short_name;
				}

				if (results[0].address_components[i].types[0] == "locality") {
					geolocation.locality = results[0].address_components[i].long_name;
				}
			}

			$.cookie('golfthis.geolocation', JSON.stringify(geolocation), {path: '/'});
			
			$(window).trigger('geolocation.loaded', geolocation);

	      } else {
	        this.throw_geolocalization_error();
	      }
	}
}
