var map;
var geocoder;


var baseIcon = new GIcon();
baseIcon.image = "http://www.google.com/mapfiles/marker.png";
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);


var geocoder = new GClientGeocoder();


function usePointFromPostcode(postcode, callbackFunction, htmlContent, iconType) {
	geocoder.getLatLng(
	postcode,
	function(point) {
	  if (!point) {
//		alert(postcode + " not found");
	  } else {
		var icon = new GIcon(baseIcon);
//		icon.image = "http://maps.landsendcornwall.co.uk/images/marker_" + iconType + ".png";

		var marker = new GMarker(point, icon);
		map.addOverlay(marker);
		setCenterToPoint(point);

		if(htmlContent) {
			
			GEvent.addListener(marker, "mouseover", function() {
			  marker.openInfoWindowHtml(htmlContent);
			});
		}
	  }
	}
	);
}

function placeMarkerAtPoint(lat, long, htmlContent, iconType)
{
	var point = new GLatLng(lat,long);

	var icon = new GIcon(baseIcon);
//	icon.image = "http://maps.landsendcornwall.co.uk/images/marker_" + iconType + ".png";

	var marker = new GMarker(point, icon);
	setCenterToPoint(point);
	if(htmlContent) {
		GEvent.addListener(marker, "mouseover", function() {
		  marker.openInfoWindowHtml(htmlContent);
		});
	}
	map.addOverlay(marker);
}

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

function showPointLatLng(point)
{
	alert("Latitude: " + point.lat() + "\nLongitude: " + point.lng());
}

function mapLoad() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		
		
		map.addControl(new GLargeMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 10)));
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());
		 
		//map.setCenter(new GLatLng(54.622978,-2.592773), 5, G_HYBRID_MAP);
		map.setCenter(new GLatLng(latitude, longitude), 13, G_HYBRID_MAP);
	}
}

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();
	  }
	}
}

function createRequest() {
	var ajaxRequest;
	try
	{
		ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
	}		
		catch (e1)
		{
			try
			{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
				catch (e2)
				{
					ajaxRequest = new XMLHttpRequest();
				}
		}
	
	return ajaxRequest;
}

addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);
