
var gdir;
var map;
var reasons=[];
var homePoint;
var homeMarker;
var gmarkers = [];
var htmls = [];
var overlays = [];
// arrays to hold variants of the info window html with get direction forms open
var from_htmls = [];
var i=0;
var routeLoaded = false;
var routeShowing = false;


// A function to create the marker and set up the event window
function createMarker(point,name,html) {
   var marker = new GMarker(point);


   // The info window version with the "to here" form open
   html = html + '<br>Directions from: <\/b>' +
   '<form action="javascript:getFormDirections(\'saddr\',\'daddr\',\'walk\')">' +
   '<input type="hidden" id="saddr" value="Edinburgh Airport@55.95,-3.37"/>'+
   '<INPUT value="Edinburgh Airport" TYPE="SUBMIT"><br>' +
   '<input type="hidden" name="walk" id="walk" value="false" />'  +
   '<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
   '"/>'+
   '</form>'+
   '<form action="javascript:getFormDirections(\'saddr2\',\'daddr2\',\'walk2\')">' +
   '<input type="hidden" id="saddr2" value="Waverley Train Station@55.95201117179783, -3.1899619102478027"/>'+
   '<INPUT value="Waverley Train Station" TYPE="SUBMIT"><br>' +
   '<input type="hidden" name="walk2" id="walk2" value="true" />'  +
   '<input type="hidden" id="daddr2" value="'+name+"@"+ point.lat() + ',' + point.lng() +
   '"/>'+
   '</form>' +
   '<form action="javascript:getFormDirections(\'saddr3\',\'daddr3\',\'walk3\')">' +
   '<input type="hidden" id="saddr3" value="Edinburgh Bus Station@55.955315,-3.191099"/>'+
   '<INPUT value="Edinburgh Bus Station" TYPE="SUBMIT"><br>' +
   '<input type="hidden" name="walk3" id="walk3" value="true" />'  +
   '<input type="hidden" id="daddr3" value="'+name+"@"+ point.lat() + ',' + point.lng() +
   '"/>'+
   '</form><br/>';


   // save the info we need to use later for the side_bar
   gmarkers[i] = marker;
   htmls[i] = html;
   GEvent.addListener(marker, "click", function()
   {
      marker.openInfoWindowHtml(html);
   });


   i++;
   return marker;
}

function fromA1()
{
   var dst = "Number 21@"+homePoint.lat()+"," + homePoint.lng();
   var src = "A1 North from Haddington@55.965519,-2.757756";
   var walking = "false";
   getDirections(src, dst, walking);
}

function fromM74()
{
   var dst = "Number 21@"+homePoint.lat()+"," + homePoint.lng();
   var src = "M74 North from Uddingston@55.829458, -4.095023";
   var walking = "false";
   getDirections(src, dst, walking);
}

function fromBridge()
{
   var dst = "Number 21@"+homePoint.lat()+"," + homePoint.lng();
   var src = "From Forth Road Bridge@56.01114629406849, -3.403615951538086";
   var walking = "false";
   getDirections(src, dst, walking);
}


function printRoute()
{
   var prtContent = document.getElementById("directions");
   var printWindow =window.open('','','left=0,top=0,width=250,height=250,t oolbar=0,scrollbars=0,status=0');
   printWindow.document.write(prtContent.innerHTML);
   printWindow.document.close();
   printWindow.focus();
   printWindow.print();
   printWindow.close();
}

// ===== request the directions =====
function getDirections(saddr, daddr, walk)
{
   // ==== Set up the walk and avoid highways options ====
   var opts = {};
   if (walk == "true")
   {
      opts.travelMode = G_TRAVEL_MODE_WALKING;
   }
   opts.getPolyline =true;
   // ==== set the start and end locations ====
   gdir.load("from: "+saddr+" to: "+daddr, opts);
   routeLoaded = true;
   routeShowing = true;
   homeMarker.closeInfoWindow();
   document.getElementById("directions").style.visibility="visible";
   document.getElementById("routeDisplay").innerHTML = "<input type=\"submit\" class=\"btn\" name=\"print\" onclick=\"javascript:printRoute()\" value=\"Print Route\"/>";
   document.getElementById("routeMessage").innerHTML = "";
}


function getFormDirections(src, dst, walk)
{
   var saddr = document.getElementById(src).value
   var daddr = document.getElementById(dst).value
   var walking = document.getElementById(walk).value;
   getDirections(saddr, daddr, walking);
}

function getPostCodeDirs(postcode)
{
   var localSearch = new GlocalSearch();
   localSearch.setSearchCompleteCallback(null,
   function()
   {
      if (localSearch.results[0])
      {
         var resultLat = localSearch.results[0].lat;
         var resultLng = localSearch.results[0].lng;
         var point2 = new GLatLng(resultLat,resultLng);
         getDirections("Your Address@" + point2.lat() + "," + point2.lng(), "Number 21@" + homePoint.lat() + "," + homePoint.lng(), "false");
      }
      else
         {
            alert("Postcode not found!");
         }
      });
      var postcodeValue = document.getElementById(postcode).value
      localSearch.execute(postcodeValue + ", UK");
 }


function showRoute()
{
   if (routeShowing)
   {
      clearOverlays();
      routeShowing = false;
   }
   else
   {
         if (routeLoaded)
         {
            document.getElementById("routeMessage").innerHTML = "";
            homeMarker.closeInfoWindow();
            map.setCenter(new GLatLng(0,0),0);
            var bounds = new GLatLngBounds();
            bounds.extend(gdir.getMarker(1).getLatLng() );
            for(var i=0; i < overlays.length; i++)
            {
               map.removeOverlay(overlays[i]);
            }
            map.addOverlay(gdir.getMarker(0));
            bounds.extend(gdir.getMarker(0).getLatLng() );
            overlays[overlays.length] = gdir.getMarker(0);
            map.addOverlay(gdir.getPolyline());
            overlays[overlays.length] = gdir.getPolyline();
            map.setZoom(map.getBoundsZoomLevel(bounds));
            map.setCenter(bounds.getCenter());
            routeShowing = true;
         }
    }
}

// This function picks up the click and opens the corresponding info window
function clickInfoWindow(i)
{
   gmarkers[i].openInfoWindowHtml(htmls[i]);

}


function clearOverlays()
{
   document.getElementById("directions").style.visibility="hidden";
   map.clearOverlays();
   map.addControl(new GLargeMapControl());
   map.addControl(new GMapTypeControl());
   map.setCenter(new GLatLng(55.955713, -3.20575), 15);

   // Set up three markers with info windows
   map.addOverlay(homeMarker);
   clickInfoWindow(0);
   document.getElementById("routeDisplay").innerHTML = "";
   document.getElementById("routeMessage").innerHTML ="";
   document.getElementById("directions").innerHTML = "";
}



function loadMap()
{

   reasons=[];
   gmarkers = [];
   htmls = [];
   overlays = [];
   // arrays to hold variants of the info window html with get direction forms open
   from_htmls = [];
   i=0;
   routeLoaded = false;
   routeShowing = false;
   if (GBrowserIsCompatible())
   {
      // === Array for decoding the failure codes ===       
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
      reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
      reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

      map = new GMap2(document.getElementById("map"));
      gdir=new GDirections(map, document.getElementById("directions"));
      homePoint = new GLatLng(55.955713, -3.20575);
      user = "zmacp"
      site = "btinternet.com"
      homeMarker = createMarker(homePoint,'Number 21','<img src="../images/logo.jpg"/> <br/>21 India Street<br/>Edinburgh<br/>EH3 6HE<br/>Tel: (+44)131 2254353<br/>Email: <a href="mailto:' + user + '@' + site + '">' + user + '@' + site + '</a>');
      // === catch Directions errors ===
      GEvent.addListener(gdir, "error", function()
      {
         var code = gdir.getStatus().code;
         var reason="Code "+code;
         if (reasons[code])
         {
            reason = reasons[code]
         }

         alert("Failed to obtain directions, "+reason);
      });
      clearOverlays();
   }
   else
   {
      alert("Sorry, the Google Maps API is not compatible with this browser");
   }
}
      
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(loadMap);
addUnLoadEvent(GUnload);



         // This Javascript is based on code provided by the
         // Blackpool Community Church Javascript Team
         // http://www.commchurch.freeserve.co.uk/
         // http://econym.googlepages.com/index.htm
