var map;
var localSearch = new GlocalSearch();
var geocoder;
var p1;
var p2;
var gdir;

var icon = new GIcon();
icon.image =  "http://www.capiouk.immersive360.com/googlemap/images/orangelink.png";
icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.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 createMarker(point,showInfoWindow) {	
  var marker = new GMarker(point);
  if(showInfoWindow)
  {
	  GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml("<table width='300' cellpadding='1' cellspacing='1' border='0' ><tr><td align='center'><font color='blue' size='3px' style='font-weight:bold'>Clifton Park NHS Treatment Centre</font></td><tr><tr><td align='center'><img src='images/thumbnail.JPG' /></td><tr><tr><td align='center'><font color='blue' size='2px' >T: +44 (0)1904 464550</font></td><tr><tr><td align='center' ><font color='blue' size='3px' ><A  href='mailto:clifton.enquiries@ramsayhealth.co.uk' style='text-decoration:none'>Email here</A></font></td><tr></table>");
	  });
  }
  return marker;
}

function placeMarkerAtPoint(point,showInfoWindow)
{
	var marker = new GMarker(point,icon);

    map.addOverlay(createMarker(point,showInfoWindow));
}

function setCenterToPoint(point)
{
	map.setCenter(point, 17);
}

// Utility function for converting degrees to radians
Math.deg2rad = function ( x ) {
        return x * (Math.PI / 180.0); 
}

// Distance in metres
var EARTH_RADIUS = 6367000;

// Calculates the distance (in metres) between 2 points. 
function getDistance(p1,p2) 
{
        var a = Math.deg2rad( 90 - p1.y);
        var b = Math.deg2rad( 90 - p2.y);
        var theta = Math.deg2rad( p2.x - p1.x);
        var c = Math.acos( Math.cos(a) * Math.cos(b) + Math.sin(a) * Math.sin(b) * Math.cos(theta));

        return c * EARTH_RADIUS; 
}

//plus to move down.less to move left.
function showPointLatLng(point)
{
	var point = new GLatLng(53.97691,-1.11297);
	
	placeMarkerAtPoint(point,true);
}

//Get coordinates from this function
function gmap_geocode_postcode(){
    var s = document.createElement('script');
	var postcode = document.getElementById("txtPostalCode").value;

    s.src = 'http://geo.localsearchmaps.com/?cb=gmap_map_postcode&use=google2&country=uk&zip=' + postcode;
    s.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(s);
}

//Call back function specified by cb in the previous method.
function gmap_map_postcode(lon, lat){
	var point = new GLatLng(lon,lat);
	placeMarkerAtPoint(point,true);
}

function mapLoad() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(53.97691,-1.11297), 14, G_NORMAL_MAP);
		
		geocoder = new GClientGeocoder();
		gdir = new GDirections(map, document.getElementById("directions"));
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
		
		var p3 = new GLatLng(53.97691,-1.11297);
		placeMarkerAtPoint(p3,true);
	}
}

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 setDirections(fromAddress, toAddress, locale) {
  gdir.load("from: " + fromAddress + " to: " + toAddress,
			{ "locale": locale });
}

function onGDirectionsLoad(){ 
  // Use this function to access information about the latest load()
  // results.
	//var p3 = new GLatLng(51.806946,0.130174);
	///placeMarkerAtPoint(p3,true);
  // e.g.
  // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
  // and yada yada yada...
}

function handleErrors()
{
   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	 alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	 alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
   
   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	 alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	 
   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	 alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	 alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	
   else alert("An unknown error occurred.");
   
}

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) 
{
  map.clearOverlays();
  if (!response || response.Status.code != 200) {
	alert("Sorry, we were unable to geocode that address");
  } else {
	place = response.Placemark[0];
	point = new GLatLng(place.Point.coordinates[1],
						place.Point.coordinates[0]);
	
	var endIndex = place.address.lastIndexOf(",");
	var placeAddress = place.address.substr(0,endIndex);
	placeAddress = placeAddress + ",UK";
	
	setDirections(placeAddress,"Bluebeck Drive,Shipton Road,York YO30 5RA,UK","en_US");
  }
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation() {
  var address = document.getElementById("txtYourPostCode").value;
  geocoder.getLocations(address, addAddressToMap);
}

// findLocation() is used to enter the sample addresses into the form.
function findLocation(address) {
  document.getElementById("txtPostalCode").value = address;
  showLocation();
}

addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);
