var map = null;
var lastPoint = null;

/**
* Reusable marker icons
*/

var defaultIcon = 'assets/js/truck2.png';
var homeIcon = 'assets/js/truck1.png';

var baseIcon = new GIcon();
baseIcon.iconSize = new GSize(32, 32);
baseIcon.iconAnchor = new GPoint(16, 32);

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

/**
* Functions which interact with the Google Maps API
*/

function load()
{
  if (GBrowserIsCompatible())
  {
    map = new GMap2(document.getElementById("map"));

    // Add map control
    //map.addControl(new GSmallZoomControl());
    //map.addControl(new GLargeMapControl());
    map.addControl(new GSmallMapControl());

    // Add type control
    //map.addControl(new GMapTypeControl(0));
    //map.addControl(new GMapTypeControl(1));

    // Setup overview map
    //ovcontrol = new GOverviewMapControl();
    //map.addControl(ovcontrol, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10, 10)));
    //ovcontrol.hide();

    map.setCenter(new GLatLng(42.25, -71.55), 11);
  }
}

// Add a point via manual coordinate entry
function addCoords(lat, lng, link)
{
  var lat = parseFloat(lat);
  var lng = parseFloat(lng);

  if (!(isNaN(lat) || isNaN(lng) || lat > 90 || lat < -90 || lng > 180 || lng < -180))
  {
    var point = new GLatLng(lat, lng);
    createMarker(point, link);
    lastPoint = point;
  }
}

function createMarker(point, link)
{
  var icon = new GIcon(baseIcon);
  var marker = null;
  if (link == '')
  {
	 icon.image = homeIcon;
         marker = new GMarker(point, {icon: icon, clickable: false, zIndexProcess: highImportance});
  }
  else
  {
	 icon.image = defaultIcon;
         marker = new GMarker(point, {icon: icon});
  }

  GEvent.addListener(marker, "click", function()
    {
	document.location.href = link;
    }
  );

  map.addOverlay(marker);
}

function highImportance(marker)
{
  return GOverlay.getZIndex(marker.getPoint().lat()) + 100000;
} 

if (window.addEventListener)
{
  window.addEventListener("load", function() {
    load();
    if (window.importMap)
    {
      importMap();
      map.setCenter(lastPoint, map.getZoom());
    }
  }, false);

  window.addEventListener("unload", function() {
    GUnload();
  }, false);
}
else if (window.attachEvent)
{
  window.attachEvent("onload", function() {
    load();
    if (window.importMap)
    {
      importMap();
      map.setCenter(lastPoint, map.getZoom());
    }
  });

  window.attachEvent("onunload", function() {
    GUnload();
  });
}
