
//= depends: zapi

/**
 * Provides an abstraction around Javascript-based geocoders. All geocoders
 * will return a plain ol' Javascript Object with the following structure:
 *
 * {
 *     latitude: Float,
 *     longitude: Float,
 *     address: {
 *         city: String,
 *         county: String,
 *         countryCode: String,
 *         region: String
 *     }
 * }
 *
 * Calling ZAPI.Geo.ClientLocation.auto() is likely your best bet, as it will
 * go through each geolocator in order and try to build a location for you.
 * When using ZAPI.Geo.ClientLocation.auto(), an additional 'geolocator' value
 * will be added to the POJSO response.
 *
 * To use the Google loader, you'll have to include the Google AJAX loader
 * as detailed at http://code.google.com/apis/ajax/documentation/.
 *
 * At the moment, the Google library loader is the only geolocator available,
 * but more may be added later. This module is more or less a stub to provide
 * an abstraction and keep things consistent in the future.
 *
 * @namespace A module for grabbing a client's geolocation.
 */
ZAPI.namespace('Geo').ClientLocation = (function() {
	var _order = [ 'googleLoader' ];
	return {
		googleLoader: function() {
			var loc;
			try {
				if ((loc = google.loader.ClientLocation)) {
					return {
						'latitude': loc.latitude,
						'longitude': loc.longitude,
						'address': {
							'city': loc.address.city,
							'country': loc.address.country,
							'countryCode': loc.address.country_code,
							'region': loc.address.region
						}
					};
				}
				else {
					return null;
				}
			}
			catch (e) {
				ZAPI.debug("Google's ClientLocation isn't loaded");
				return null;
			}
		},

		auto: function(order) {
			if (this._auto) {
				return this._auto;
			}
			else {
				(order || _order).each(function(f) {
					if ((this._auto = this[f]())) {
						this._auto.geolocator = f;
						return;
					}
				}.bind(this));

				return this._auto;
			}
		}
	};
}());
