/* This Javascript is based on code provided by the Blackpool Community Church Javascript Team
	http://www.commchurch.freeserve.co.uk/   
	http://www.econym.demon.co.uk/googlemaps/ 
*/

var simpleMap;
var trafficMap;
var geocoder = null;

/* Arrays to hold copies of the markers and html used by the side_bar */
var gmarkers = [];
var htmls = [];
var i = 0;
/* Arrays to hold variants of the info window html with get direction forms open */
var to_htmls = [];
var from_htmls = [];

var zoom;
var infoSeparator = "|";
var fullInfoCount = 5; /* count of info parts that include lat/lng (pattern of line - lat|lng|address|html) */
var partInfoCount = 2; /* count of info parts that don't include lat/lng (pattern of line - address|html) */

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var baseIcon = new GIcon(G_DEFAULT_ICON);
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);

function displayStaticMap(mapId, startPointLat, startPointLng, airport, zm)
{
  if (GBrowserIsCompatible())
  {
    // create the map
    map = new GMap2(document.getElementById(mapId));

    geocoder = new GClientGeocoder();
    if ((startPointLat != 0) && (startPointLng != 0))
    {
      var point = new GLatLng(startPointLat, startPointLng);
      map.setCenter(point, zm);
      loadMarker(0, false, true);
    } else if (geocoder)
    {
      geocoder.getLatLng(airport, function(point)
      {
        if (!point)
        {
          alert(airport + " not found.");
        }
        else
        {
          map.setCenter(point, zm);
        }
        setTimeout(function(){loadMarker(0, false, true)}, 1725);
      });
    }
  }
  else
  {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  }
}

function loadMap(mapId, startPointLat, startPointLng, airport, zm, useLetters, displayTraffic, useDirections)
{
  if (displayTraffic) map = trafficMap; else map = simpleMap;
  if (map) return;
  zoom = zm;
  if (GBrowserIsCompatible())
  {
    // create the map
    map = new GMap2(document.getElementById(mapId));
    if (displayTraffic) trafficMap = map; else simpleMap = map;
    map.addControl(new GSmallMapControl());
    //map.enableScrollWheelZoom();
    map.addControl(new GMapTypeControl());
    //map.addControl(new ExtMapTypeControl({showTraffic: true, showTrafficKey: true}));
    if (displayTraffic) map.addOverlay(new GTrafficOverlay());
    geocoder = new GClientGeocoder();
    if ((startPointLat != 0) && (startPointLng != 0))
    {
      var point = new GLatLng(startPointLat, startPointLng);
      map.setCenter(point, zoom);
      loadMarker(0, useLetters, useDirections);
    } else if (geocoder)
    {
      geocoder.getLatLng(airport, function(point)
      {
        if (!point)
        {
          alert(airport + " not found.");
        }
        else
        {
          map.setCenter(point, zoom);
        }
        setTimeout(function(){loadMarker(0, useLetters, useDirections)}, 1725);
      });
    }
  }
  else
  {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  }
}

function loadMarker(markerIndex, useLetters, useDirections)
{
  if (markerIndex < markersData.length)
  {
    parts = markersData[markerIndex].split(infoSeparator);
    markerIndex++;
    /* Lat/lng were given in a data string */
    if (parts.length == fullInfoCount)
    {
      var lat = parseFloat(parts[0]);
      var lng = parseFloat(parts[1]);
      var addr = parts[2];
      var html = parts[3];
      var brand = parts[4];
      if ((!isNaN(lat) && (lat != 0)) && (!isNaN(lng) && (lng != 0)))
      {
        var point = new GLatLng(lat, lng);
        addMarker(point, brand, html, markerIndex - 1, useLetters, useDirections);
        loadMarker(markerIndex, useLetters, useDirections);
      } else if (geocoder)
      {
        geocoder.getLatLng(addr, function(point)
        {
          if (!point)
          {
            alert(addr + " not found.");
          }
          else
          {
            markersData[markerIndex - 1] = point.lat() + '|' + point.lng() + '|' + addr + '|' + html + '|' + brand;
            addMarker(point, brand, html, markerIndex - 1, useLetters, useDirections);
          }
          setTimeout(function(){loadMarker(markerIndex, useLetters, useDirections)}, 1725);
      });
      }
    }
  }
}

function addMarker(point, brand, html, markerIndex, useLetters, useDirections)
{
  var htmlToMarker = '';
  if (brand != '')
  {
    htmlToMarker += "<img style='float:right; margin:0 10px 10px 0;' src='/images/" + brand + "Logo_sml.jpg'></img>";
  }
  htmlToMarker += html;
  htmlToMarker += "<br/>";
  var marker = createMarker(point, htmlToMarker, markerIndex, html, useLetters, useDirections);
  map.addOverlay(marker);
}

/* A function to create the marker and set up the event window */
function createMarker(point, html, markerIndex, descHtml, useLetters, useDirections)
{
  if(useLetters)
  {
    var letter = String.fromCharCode("A".charCodeAt(0) + markerIndex);
    var letteredIcon = new GIcon(baseIcon);
    letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
    //document.getElementById('description').innerHTML += "<img src='" + letteredIcon.image + "' /> - " + descHtml + "<br/>";
    // Set up our GMarkerOptions object
    markerOptions = { icon:letteredIcon };
    var marker = new GMarker(point, markerOptions);
  }
  else
  {
    var marker = new GMarker(point);
  }
  // The info window version with the "to here" form open

  if (useDirections)
  {
    to_htmls[i] = html + '<br>Get directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
    '<br>Start address:<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() + 
    // "(" + name + ")" + 
    '"/>';
    // The info window version with the "to here" form open
    from_htmls[i] = html + '<br>Get directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
    '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
    '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
    '<INPUT value="Get Directions" TYPE="SUBMIT">' +
    '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
    // "(" + name + ")" + 
    '"/>';
    // The inactive version of the direction info
    html += '<br/>Get directions: <a href="javascript:tohere(' + i + ')">To here</a> - <a href="javascript:fromhere(' + i + ')">From here</a>';
  }
  GEvent.addListener(marker, "click", function()
  {
    marker.openInfoWindowHtml('<div style="font-size:11px;width:200px;">' + html + '</div>');
  });
  gmarkers[i] = marker;
  htmls[i] = html;
  i++;
  return marker;
}
      
/* This function picks up the click and opens the corresponding info window */
function myclick(i)
{
  gmarkers[i].openInfoWindowHtml('<div style="font-size:11px;width:200px;">' + htmls[i] + '</div>');
}

/*  Functions that open the directions forms */
function tohere(i) {
  gmarkers[i].openInfoWindowHtml('<div style="font-size:11px;">' + to_htmls[i] + '</div>');
}

function fromhere(i) {
  gmarkers[i].openInfoWindowHtml('<div style="font-size:11px;">' + from_htmls[i] + '</div>');
}

/* Address examples:
	350 Perimeter Center North, Atlanta, GA 30346
	1600 Amphitheatre Pky, Mountain View, CA
*/
function changePosition(addrId)
{
  var addrValue = document.getElementById(addrId).value;
  if (geocoder)
  {
    geocoder.getLatLng(addrValue, function(point)
    {
      if (!point)
      {
        alert(addrValue + " not found.");
      }
      else
      {
        //map.setCenter(point, zoom);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(addrValue);
      }
    });
  }
}