// http://code.google.com/apis/maps/documentation/localsearch/reference.html
// http://code.google.com/apis/maps/documentation/geocoding/

google.load("search", "1");

function notEmptyString(str) {
	if (str == null || jQuery.trim(str) == "") {
		return false;
	}
	return true;
}

function currentSearchQueryOnThePage() {
	return $("#businessQuery").val();
}

function getCurrentLocation() {
	var centerPoint = '';
	if (google.loader.ClientLocation) {
		city = google.loader.ClientLocation.address.city;
		region = google.loader.ClientLocation.address.region;
		countrycode = google.loader.ClientLocation.address.country_code;
		centerPoint = city + ", " + region + ", " + countrycode;
	} else if ($("#preferredLocation").length) {
		centerPoint = $("#preferredLocation").val()
	} else {
		centerPoint = "New York, NY, USA";
	}
	return centerPoint;
}

/**
 * Creates a new local-searcher centered at:
 * (1) User's current location
 * (2) If (1) is not known, then user's preferred location (if he is signed in)
 * (3) Otherwise, NY.
 */
function newLocalSearch() {
	var localSearch = new google.search.LocalSearch();
	if (localSearch) {
		localSearch.setCenterPoint(getCurrentLocation());
		localSearch.setResultSetSize(8);
		localSearch.setNoHtmlGeneration();
		//localSearch.setRestriction(google.search.Search.RESTRICT_TYPE, google.search.LocalSearch.TYPE_LOCALONLY_RESULTS);
	}
	return localSearch;
}

// Assumes that:
// - There is an element with id "searchBox": contains text to be searched
// - There is a div with id "searchResults": a placeholder into which we put search results
// - There is an element with id "businessQuery": the query that the user has done from before (server will tell this to us via this field if it knows the last search query)
// - There is an element with id "redscoophelp": contains html for a helper text
function searchComplete(localSearch, searchQuery) {
	if (searchQuery != currentSearchQueryOnThePage()) {
		// There was a more recent search, so skip this
		return;
	}
	
	$('#searchResults').html('');
	// If there are results:
	// alert('local search: '+ localSearch.constructor);
	// alert('local search results: '+ localSearch.results);
	if (localSearch.results && localSearch.results.length > 0) {
		resultTable = "";
		
		var totalResultsSoFar = 0;
		for ( var i = 0; i < localSearch.results.length && totalResultsSoFar < 5; i++) {
			splitted = localSearch.results[i].url.split('cid=');
			businessId = splitted[1];
			if (businessId != undefined) {
				var addressElements = new Array();

				if (notEmptyString(localSearch.results[i].city)) {
					addressElements.push(localSearch.results[i].city);
				}
				if (notEmptyString(localSearch.results[i].region)) {
					addressElements.push(localSearch.results[i].region);
				}
				if (notEmptyString(localSearch.results[i].postalCode)) {
					addressElements.push(localSearch.results[i].postalCode);
				}
				if (notEmptyString(localSearch.results[i].country)
						&& localSearch.results[i].country != "US"
						&& localSearch.results[i].country != "United States") {
					addressElements.push(localSearch.results[i].country);
				}

				// We have a valid address
				if (addressElements.length > 0) {
					totalResultsSoFar++;
					
					innerHTML = "<div class=\"topboxes\">";
					innerHTML += "<div class=\"title\">";
					innerHTML += "<a href=\"/reviews/for-business/"
							+ businessId
							+ "/?query="
							+ document.getElementById('searchBox').value
							+ "\">"
							+ localSearch.results[i].title
							+ "</a>";
					innerHTML += "</div>";
				
					innerHTML += "<div class=\"text\">";
					innerHTML += localSearch.results[i].streetAddress;
					innerHTML += "<br />" + addressElements.join(", ")
							+ "<br />";

					if (localSearch.results[i].phoneNumbers != null
							&& localSearch.results[i].phoneNumbers.length > 0
							&& localSearch.results[i].phoneNumbers[0].number != null) {
						innerHTML += localSearch.results[i].phoneNumbers[0].number;
					}

					innerHTML += "</div>";
					innerHTML += "</div>";

					resultTable = resultTable + innerHTML;
				}
			}
			;
		}
		;

		$('#searchResults').html(resultTable);
	}
}

function performTextSearch(searchQuery) {
	// Always keep track of what the user searched for in the hidden variable
	$('#businessQuery').val(searchQuery);
	if (searchQuery.length >= 5 && searchQuery != $("#searchBoxDefaultMessage").val()) {
		// begin: _This part is still prototype
		var tempLocalSearch = newLocalSearch();
		var searchCompleteClosure = function(searcher, queryParam){ return function() {
				searchComplete(searcher, queryParam);
			};};
		tempLocalSearch.setSearchCompleteCallback(this, searchCompleteClosure(tempLocalSearch, searchQuery));
		// end: _This part is still prototype
		
		tempLocalSearch.execute(searchQuery);
	} else {
		// nothing to search yet, hence no search results. So display help text.
		$('#searchResults').html($('#redscoophelp').html());
	}
}

// Called only once upon loading the page
function onLoad() {
	// If there is a query from before, put it into the search box
	if (notEmptyString($("#businessQuery").val())) {
		$('#searchBox').val($("#businessQuery").val());
	}
	$("#searchBox").focus();
	// In case there is something from before, do a search immediately
	performTextSearch($("#searchBox").val());
}

// Set a callback to call your code when the page loads
google.setOnLoadCallback(onLoad);

