
;(function($) {
	
	/* Google Maps */
	$.googleMap = {
		maps: {},
		marker: function(m) {
			if (!m) {
				return null;
			} else if (m.lat == null && m.lng == null) {
				return $.googleMap.marker($.googleMap.readFromGeo(m));
			} else {
				var marker = new GMarker(new GLatLng(m.lat, m.lng));
				if (m.txt) {
					GEvent.addListener(marker, "click", function() {
						marker.openInfoWindowHtml(m.txt);
					});
				}
				return marker;
			}
		},
		readFromGeo: function(elem) {
			var latElem = $(".latitude", elem)[0];
			var lngElem = $(".longitude", elem)[0];
			if (latElem && lngElem) {
				return { lat:parseFloat($(latElem).attr("title")), lng:parseFloat($(lngElem).attr("title")), txt:$(elem).attr("title") }
			} else {
				return null;
			}
		},
		mapNum: 1
	};

	$.fn.googleMap = function(lat, lng, zoom, options) {

		// If we aren't supported, we're done
		if (!window.GBrowserIsCompatible || !GBrowserIsCompatible()) return this;

		// Default values make for easy debugging
		if (lat == null) lat = 37.4419;
		if (lng == null) lng = -122.1419;
		if (!zoom) zoom = 13;

		// Sanitize options
		if (!options || typeof options != 'object')	options = {};
		options.mapOptions = options.mapOptions || {};
		options.markers = options.markers || [];
		options.controls = options.controls || {};

		// Map all our elements
		return this.each(function() {
			// Make sure we have a valid id
			if (!this.id) this.id = "gMap" + $.googleMap.mapNum++;
			// Create a map and a shortcut to it at the same time
			var map = $.googleMap.maps[this.id] = new GMap2(this, options.mapOptions);
			// Center and zoom the map
			map.setCenter(new GLatLng(lat, lng), zoom);
			// Add controls to our map
			for (var i = 0; i < options.controls.length; i++) {
				var c = options.controls[i];
				eval("map.addControl(new " + c + "());");
			}
			// If we have markers, put them on the map
			var marker = null;
			for (var i = 0; i < options.markers.length; i++) {
				if (marker = $.googleMap.marker(options.markers[i])) map.addOverlay(marker);
			}
		});
	};
	
	/* Location autocompleter */
	$.fn.extend({
		locationAutocomplete: function(options) {
			options = $.extend({}, $.LocationAutocomplete.defaults, options);
			return this.each(function() {
				new $.LocationAutocomplete(this, options);
			});
		}
	});

	$.LocationAutocomplete = function(input, options) {
		var $input = $(input)
		$input.autocomplete(
			options.locationLookupUrl, 
			{
				minChars: 2,
				max: 10,
				cacheLength: 20,
				autoFill: true,
				mustMatch: true,
				matchContains: false,
				scrollHeight: 220,
				dataType: 'json',
				parse: function(response){
					var data = $.evalJSON(response.d);
					for (var i = 0; i < data.length; i++){
						var lat = data[i].Lat;
						var lng = data[i].Lng;
						var cityId = data[i].CityId;
						var val = data[i].City + ', ';
						if (data[i].Region && data[i].Region != '')
							val += data[i].Region + ', ';
						val += data[i].Country;
						
						data[i] = new Object();
						data[i].result = val; 	// Formatted value to be putted into input box
						data[i].value = val;  	// Value to be compared to input
						data[i].data = new Object();
						data[i].data.CityId = cityId;
						data[i].data.Lat = lat;
						data[i].data.Lng = lng;
					}
					
					return data;
				},
				formatItem: function(data, i, max, value, term) {
					return value;
				},
				selectItem: function(data){
					// Init tooltip
					if (!$input.tipControl){
						$input.tipControl = $input.qtip({
							content: { 
								prerender: true,
								text: "<div id='" + options.mapContainerId + "' style='width:260px; height:250px;'></div>"
							},
							style: { name: "validator", width: { max: 277 }, padding: '5px 5px'},
							position: { corner: {tooltip: "leftTop", target: "rightMiddle"} },
							show: { effect: {type: "fade", length: 0}, when: false, ready: true, delay: 0 },
							hide: false
						});
					}
					else{
						if (data.CityId)
							$input.qtip("show");
						else
							$input.qtip("hide");
					}

					// Init map in tooltip
					var zoom = 7;
					if (!$input.mapControl){
						$('#' + options.mapContainerId).googleMap(data.Lat, data.Lng, zoom, {
							controls: ["GSmallMapControl"]
						});
						$input.mapControl = $.googleMap.maps[options.mapContainerId];
					}

					if (data.CityId){
						var point = new GLatLng(data.Lat, data.Lng);

						$input.mapControl.setCenter(point, zoom);
						$input.mapControl.clearOverlays() ;
						$input.mapControl.addOverlay(new GMarker(point));
					}
				},
				finishSelectItem: function(data){
					if ($input.tipControl)
						$input.qtip("hide");
						
					if (data == null)
						$input.CityId = null;
					else
						$input.CityId = data.CityId;
				}				
		});	
	}

	$.LocationAutocomplete.defaults = {};

})(jQuery);