var map;
var localSearch = new GlocalSearch();
var icon = new GIcon();

var minLat = 90.0;
var maxLat = -90.0;
var minLng = 180.0;
var maxLng = -180;

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);
			}else{
				alert("Postcode not found!");
			}
		});	
		
	localSearch.execute(postcode + ", UK");
}

function placeMarkerAtPoint(point)
{
	var marker = new GMarker(point,icon);
	map.addOverlay(marker);
}

function placeMarkerAtPointAndSetLatLng(point)
{
	var marker = new GMarker(point,icon);
	map.addOverlay(marker);
	if (document.getElementById('latitude')) document.getElementById('latitude').value = point.lat();
	if (document.getElementById('longitude')) document.getElementById('longitude').value = point.lng();
	map.setCenter(point, 12);
	if (document.getElementById('zoomlevel')) document.getElementById('zoomlevel').value = map.getZoom();
}


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

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

function setZoomLevel()
{
	if (document.getElementById('zoomlevel')) document.getElementById('zoomlevel').value = map.getZoom();
}

function mapLoad() {
	if (GBrowserIsCompatible()) {
		var markercount = 0;
		
		map = new GMap2(document.getElementById("map"));
		
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		//map.setCenter(new GLatLng(54.622978,-2.592773), 5, G_NORMAL_MAP);

		map.setCenter(new GLatLng(55.410307,-2.785034), 10, G_NORMAL_MAP);

		if (document.getElementById('multiplemarkers')) {
			markercount = document.getElementById('multiplemarkers').value;
			//alert("multiple marker entry found" + markercount.toString());
			for (var x = 1; x <= markercount; x++) {
				//alert("Latitude: " + document.getElementById('lat' + x.toString()).value + "\nLongitude: " + document.getElementById('lon' + x.toString()).value);
				addPlace(map, document.getElementById('lat' + x.toString()).value, document.getElementById('lon' + x.toString()).value, document.getElementById('markerlabel' + x.toString()).value, document.getElementById('markerlink' + x.toString()).value);				
			}
		} else if (document.getElementById('latitude')) {
			if (document.getElementById('latitude').value && document.getElementById('longitude').value) {
				if (document.getElementById('zoomlevel').value)
				{
					map.setCenter(new GLatLng(document.getElementById('latitude').value,document.getElementById('longitude').value), parseInt(document.getElementById('zoomlevel').value, 10), G_NORMAL_MAP);
				} 
				else
				{
					map.setCenter(new GLatLng(document.getElementById('latitude').value,document.getElementById('longitude').value), 13, G_NORMAL_MAP);
				}
				var marker = new GMarker(new GLatLng(document.getElementById('latitude').value,document.getElementById('longitude').value),icon);
				map.addOverlay(marker);
			} else {
				if (document.getElementById('postcode')) {
					if (document.getElementById('postcode').value) {
						usePointFromPostcode(document.getElementById('postcode').value, placeMarkerAtPointAndSetLatLng);
					}
				}
			}
		} else if (document.getElementById('postcode')) {
			if (document.getElementById('postcode').value) {
				usePointFromPostcode(document.getElementById('postcode').value, placeMarkerAtPointAndSetLatLng);
			}
		}
		//http://maps.google.co.uk/maps?hl=en&ie=UTF8&ll=55.410307,-2.785034&spn=0.877835,1.870422&z=9
		map.enableScrollWheelZoom();
	}
}

function addPlace(map, lat, lng, label, link) {

    // Create a marker for a particular lattitude and longitude.
    var point = new GLatLng (lat, lng);
    var marker = new GMarker (point, icon);

    // Show an info window whenever the user moves the mouse cursor
    // over a location marker, and close the info window when they
    // move off the map entirely.
    GEvent.addListener (marker, "click", function () {
 /*       map.openInfoWindowHtml (point, (label + "<br />"
                                        + "Lat " + lat
                                        + "     Lng " + lng));
*/
		map.openInfoWindowHtml (point, (label + "<br />"
		 								+ "<a href=\"" + link + "\">" + "View Property Details" + "</a>"));

    });
    GEvent.addListener (map, "mouseout", function () {
        map.closeInfoWindow ();
    });
/*	GEvent.addListener(marker, "click", function() {
	  location.href=link;
	});
*/
    // Add the new marker to the map.
    map.addOverlay (marker);

    // Remember the range of coordinates that have been marked
    // so that we can make the map encompass all of them.
    minLat = Math.min (minLat, lat);
    maxLat = Math.max (maxLat, lat);
    minLng = Math.min (minLng, lng);
    maxLng = Math.max (maxLng, lng);

    // Recenter the map to the middle of all locations that
    // we have marked so far.
    map.setCenter (new GLatLng ((minLat + maxLat) / 2,
                                (minLng + maxLng) / 2));

    // Find the maximum zoom level at which all of the requested addresses
    // will fit into the map (with a bit of margin), and zoom the map to
    // that level.  Note that it doesn't seem to work to specify the
    // corners of the bounding box when creating the GLatLngBounds
    // object, so we need to use the alternate approach of calling the
    // extend method instead.
    var bounds = new GLatLngBounds;
    bounds.extend (new GLatLng (minLat - ((maxLat - minLat) / 12),
                                minLng - ((maxLng - minLng) / 12)));
    bounds.extend (new GLatLng (maxLat + ((maxLat - minLat) / 12),
                                maxLng + ((maxLng - minLng) / 12)));
    map.setZoom (map.getBoundsZoomLevel (bounds));
};


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