/* Set to true to turn on obnoxious debug alerts */
var storesDebugMode = false;

/* Define geocoder here to assist caching, and use a decent cache. */
var geocoder = null;

var locatorLinkSubmitResponseFunction = 
	function(response) {
		if (!response || !response.Placemark || ! response.Placemark[0]) {
			alert(errorMissingField);
			return;
		} else {
			document.getElementById("searchForm:latStr").value = response.Placemark[0].Point.coordinates[1];
			document.getElementById("searchForm:lngStr").value = response.Placemark[0].Point.coordinates[0];
			document.getElementById("searchForm:searchString").value = '';
			fireClickEvent("searchForm:locatorLink");
		}
	};

var locatorLinkClick = 
	function(searchString){
		document.getElementById("searchForm:searchString").value = searchString;
		return Locator.locate(searchString, locatorLinkSubmitResponseFunction);
	};
	


/*
 * Locator - Defines the "LocatorClass" JS class used for supporting client-side
 * store location operations.
 */
var LocatorClass = Class.create( {

	/*
	 * Display alert box if debugging.
	 */
	log : function(args) {
		if (storesDebugMode) {
			alert("LOG: " + args);
		}
	},

	/*
	 * Validate the input arguments
	 */
	isValid : function(storeLocationString) {
		if (storeLocationString == null
				|| storeLocationString.length == 0
				|| storeLocationString == this.defaultStoreLocationString) {
			alert(errorMissingField);
			return false;
		}
		return true;
	},

	/*
	 * Use Google Maps to convert user-submitted search criteria to a
	 * lat/lon point. Add a response function to the geocoder parameters
	 * that will then update the elements specified by latElementId and lngElementId 
	 * with the returned placemark values and then fire a click event on the 
	 * element specified by clickElementId.
	 * 
	 * This function will ALWAYS return false in order to prevent inadvertent
	 * submission of any form click that may have triggered this function. It
	 * is intended that the response function click event will submit a form
	 * button or a link.
	 */
	locate : function(searchString, responseFunction) {
		
		if (!GBrowserIsCompatible()) {
			alert("Browser is not compatible with google map api");
		}

		if (!geocoder) {
			geocoder = new GClientGeocoder();
			geocoder.setCache(new GFactualGeocodeCache());
		}

		if (!this.isValid(searchString)) {
			return false;
		}


		geocoder.setBaseCountryCode("us");
		geocoder.getLocations(searchString + " US", responseFunction);

		/* Disallow form submission by returning false. */
		return false;
	}


/* End this class */
});

var Locator = new LocatorClass;

