var map;
var localSearch = new GlocalSearch();

var icon = new GIcon();
icon.image = "http://www.google.com/mapfiles/marker.png";
icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
icon.iconSize = new GSize(20, 34);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(10, 34);

function usePointFromPostcode(postcode, callbackFunction) {
	
	localSearch.setSearchCompleteCallback(null, 
		function() {
			
			if (localSearch.results[0])
			{		
				var resultLat = localSearch.results[0].lat;
				var resultLng = localSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				callbackFunction(point);
				placeMarkerAtPoint(point);
			}else{
				alert("Postcode not found!");
			}
		});	
		
	localSearch.execute(postcode + ", UK");
}

function placeMarkerAtPoint(point)
{
// Our info window content
	var infoTabs = [
  new GInfoWindowTab("Venue", venuename),
  new GInfoWindowTab("Directions", '<strong>Start address / postcode:</strong><form action="http://maps.google.com/maps" method="get" target="_blank">' +
	'<input type="text" size=40 maxlength=40 name="saddr" id="saddr" value="" /><br>' +
	'<input value="Get Directions" type="submit">' +
	'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
	'"/>')
];

// Place a marker in the center of the map and open the info window
// automatically
	var marker = new GMarker(map.getCenter());
	GEvent.addListener(marker, "click", function() {
  marker.openInfoWindowTabsHtml(infoTabs);
});
	map.addOverlay(marker);
	marker.openInfoWindowTabsHtml(infoTabs);
}

function setCenterToPoint(point)
{
	map.setCenter(point, 14);
}

function showPointLatLng(point)
{
	var latitude = point.lat();
	var longitude = point.lng();
	alert("Latitude: " + latitude + " - Longitude: " + longitude);
}

function showPointLat(point)
{
	var latitude = point.lat();
	alert("Latitude: " + latitude );
}

function showPointLng(point)
{
	var longitude = point.lng();
	alert("Longitude: " + longitude);
}

function mapLoad() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
//		map.addControl(new GSmallMapControl());//
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(40.486688,-3.70427), 16);
		placeMarkerAtPoint(new GLatLng(40.486688,-3.70427));
//	usePointFromPostcode(postcode, setCenterToPoint);//
	}
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function addUnLoadEvent(func) {
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') {
	  window.onunload = func;
	} else {
	  window.onunload = function() {
	    oldonunload();
	    func();
	  }
	}
}

addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);
