var geocoder;
var locationSearch;

function initializeGMaps() {
   if (GBrowserIsCompatible()) {
        // Create a cache to use and set it up with well known locations.
        var cache = new GFactualGeocodeCache();
        
        // Set up the geocoder.
        geocoder = new GClientGeocoder(cache);
        geocoder.setBaseCountryCode(".au");
    }
}

jQuery(function($) {
	//Make sure google API's been initialised because location search
    try{
    	if(!GBrowserIsCompatible())
    		return;
    }
    catch(err){
    	return;
    }
    	
    // Setup the Google Maps API
	initializeGMaps();
    $(window).unload(GUnload);

    // Setup the location field.
    $("#location").locationSearch(geocoder).change(function() {
        // Extract the selected result and further extract the bounds related to the selection. 
		// We pass the bounds as a JSON formatted string so that it can be transmitted over HTTP.
        var i = this.locationSearch.placemarkSelected;
        var bounds;
        var coord;
        var accuracy;
        if (i != null) {
            var result = this.locationSearch.response.Placemark[i];
            bounds = $.toJSON(result.ExtendedData.LatLonBox);
            coord = $.toJSON(result.Point.coordinates);
            accuracy = $.toJSON(result.AddressDetails.Accuracy);
        } else {
            bounds = "";
            coord = "";
            accuracy ="";
        }
        $("#locationResultBounds").val(bounds);
        $("#locationResultPoint").val(coord);
        $("#locationResultAccuracy").val(accuracy);
    });
});

