var map = null;
var geocoder = null;
var startZoom = 9;
var cityLocation = null;

function init() {
	if (GBrowserIsCompatible()) {
		if(document.getElementById("map")){
			cityLocation = document.getElementById("map").firstChild.nodeValue;
			map = new GMap2(document.getElementById("map"));
			geocoder = new GClientGeocoder();
			geocoder.getLatLng(cityLocation, 
				function(point) 
				{
					map.setCenter(point, startZoom);
				});
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
		} else {
			return;
		}
	} else {
		return;
	}
}

function addSearchForm() {
	var mapElement = document.getElementById("map");
	var theForm = document.createElement("form"); 
	theForm.setAttribute("action",window.location);
	theForm.setAttribute("id","searchAddressForm");
	var formContent = '<input type="text" size="50" id="address" name="address" value="'+lang.addressSuggestion+'" /><input type="submit" value="'+lang.searchAddress+'" id="searchAddressBtn" />';
	theForm.innerHTML = formContent;
	mapElement.parentNode.insertBefore(theForm,mapElement);
}

function showAddress(address) {
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function(point) {
				if (!point) {
					alert(address + " not found")
				} else {
					map.setCenter(point, 15);
					var marker = new GMarker(point);
					map.addOverlay(marker);
					marker.openInfoWindowHtml(address);
				}
			}
		);
	}
}

function doSearch(){
	if(document.getElementById("map")){
		addSearchForm();
		var addressForm = document.forms['searchAddressForm'];
		var searchAddressField = addressForm["address"];
		searchAddressField.onblur = function () {
    		if(this.value == '') {
    	    	this.value = lang.addressSuggestion;
    		}
		};
    	searchAddressField.onfocus = function () {
    		if(this.value == lang.addressSuggestion) {
    	    	this.value = '';
    		}
		};
		addressForm.onsubmit  = function(){
			if (addressForm.address.value != lang.addressSuggestion) {
				showAddress(addressForm.address.value);
			}
			return false;
		}
	} else {
		return;
	}
}

addEventSimple(window,"load",init);
addEventSimple(window,"load",doSearch);
window.onunload = GUnload;