/**
* Use this to get lat/lng points based on location strings.
*
* Usage for autocomplete plugin:
*		var ig = new IasGeocoder();
*		$("#my-element").autocomplete(function(term, cb) {
*			// do the geocoding here, then call cb(results)
*		});
*
* Dependancies:
* http://maps.google.com/maps/api/js?sensor=false
*
* @package Ias
*/

/**
* Constructor
*
*/
function IasGeocoder() {
	
}

/**
* Find some results for a given query.
*
* @param string Query string
* @param function Callback function to which results are sent
* @return void
*/
IasGeocoder.prototype.find = function(q, callback) {

	// Geocode
	var GC = this;
	GC.findLatLng(q, function(gcResults) {

		// Only find location names if Google returned no results
		if(gcResults && gcResults.length>0) {
			callback(gcResults);
		}
		else {
			GC.findLocation(q, function(locResults) {
	
				// Merge results
				var allResults = gcResults.concat(locResults);
				callback(allResults);
			});
		}
	});
	
}

IasGeocoder.prototype.findLatLng = function(q, callback) {

	// Submit query to geocoder
	var geocoder = window.geocoder = new google.maps.Geocoder();
	q = q.replace(/UK/, '') + ", UK";
	geocoder.geocode({address: q}, function(r, status) {

		// Gather results, ensuring they're in the UK
		var results = [];
		if(status==google.maps.GeocoderStatus.OK) {
			if(r.length>0) {
				for(var ri=0; ri<r.length; ri++) {
					if(r[ri].formatted_address) {
						var isuk = false;
						for(var c=0; c<r[ri].address_components.length; c++) {
							if($.inArray("country", r[ri].address_components[c].types)>-1 && r[ri].address_components[c].short_name=='GB') {
								isuk = true;
							}
						}
						if(!isuk) continue;
						r[ri].formatted_address = r[ri].formatted_address.replace(/North\s+Humberside/ig, 'East Yorkshire');
						results[results.length] = {
							latlng: r[ri].geometry.location.toString(),
							value: r[ri].formatted_address,
							label: r[ri].formatted_address
						};
					}
				}
			}
		}

		// Send results to callback
		callback(results);
	});
}

IasGeocoder.prototype.findLocation = function(q, callback) {
	$.get('/ajax/property-location', {q:q}, function(response) {
		response = response.split("\n");
		var results = [];
		for(var i=0; i<response.length; i++) {
			results[results.length] = {
				label: response[i],
				value: response[i]
			};
		}
		callback(results);
	});
}
