$(document).ready(function() {
	$("#search_by_name").click(function() {
		$("#search_mode").attr("value", "name");
		$("#search_category").hide();
		$("#search_name").show();
	});
	$("#search_by_category").click(function() {
		$("#search_mode").attr("value", "category");
		$("#search_category").show();
		$("#search_name").hide();
	});
});

function clearAllChildren(node) {
	while (node.hasChildNodes())
		node.removeChild(node.firstChild);
}

function render_result(result) {
	var resultNode = $("#google_result_template").clone();
	$(resultNode).removeAttr("id");
	$(resultNode).show();
	$(resultNode).find(".name").text(result.titleNoFormatting);
	$(resultNode).find(".address").text(result.addressLines.join(", "));
	if (result.phoneNumbers != undefined)
		$(resultNode).find(".phone").text(result.phoneNumbers[0].number);
	else
		$(resultNode).find(".phone").text("Ph: unknown");
	$(resultNode).find("a.website").attr("href", result.url);
	return resultNode;
}

var search_callback = {
	'results_received' : function(searcher) {
		$("#google_results").livequery(function() {
			clearAllChildren(this);
			var resultsSummary = document.createElement("div");
			if (searcher.results.length > 0) {
				$(resultsSummary).append("<h2>" + searcher.results.length + " supplier results</h2>");
				$(resultsSummary).append(google.search.Search.getBranding());
			}
			$(resultsSummary).addClass('results-summary');
			$(this).append(resultsSummary);
			for (var i = 0; i < searcher.results.length; i++) {
				$(this).append(render_result(searcher.results[i]));
			}
			var attribution = searcher.getAttribution();
			if (attribution) {
				$(this).append(attribution);
			}
		});
	}
}

function do_google_search(query, location) {
	var searcher = new google.search.LocalSearch();
	searcher.setCenterPoint(location);
	
	searcher.setAddressLookupMode(google.search.LocalSearch.ADDRESS_LOOKUP_DISABLED);
	searcher.setSearchCompleteCallback(this, search_callback.results_received, [searcher]);
	searcher.execute(query);
}