// eLabs Google Map functions --- START ---   **********************************************************************

var map;
var gdir;
var mgr;
var icons = {};
var allmarkers = [];

var iconData = {
  "logo": { width: 49, height: 104 },
  "shadow": { width: 62, height:85 }
};

var officeLayer = [
  {
    "zoom": [0, 17],
    "places": [
      {
        "name": "eLabs, Inc. Office",
        "icon": ["logo", "shadow"],
        "posn": [43.605377, -79.775541]
      },
    ]
  }
];

function initialize() {
      if (GBrowserIsCompatible()) {
        // define the crosshair tile layer and its required functions
        var crossLayer = new GTileLayer(new GCopyrightCollection(""), 0, 15);
        crossLayer.getTileUrl =  function(tile, zoom) {
          return "/images/crosshair.png";
        }
        crossLayer.isPng = function() {return true;}

        // Create a new map type incorporating the tile layer
        var layerTerCross = [ G_PHYSICAL_MAP.getTileLayers()[0],
                              crossLayer ];
        var mtTerCross = new GMapType(layerTerCross,
                                      G_PHYSICAL_MAP.getProjection(), "Ter+");

        var map = new GMap2(document.getElementById("map_canvas"),
            { size: new GSize(660,400) } );
        map.addMapType(G_PHYSICAL_MAP);
        map.addMapType(mtTerCross);
        map.setCenter(new GLatLng(43.605377, -79.775541), 10); // eLabs geo code
        map.addControl(new GLargeMapControl())

        var mapControl = new GHierarchicalMapTypeControl();
        
        // Set up map type menu relationships
        mapControl.clearRelationships();
        mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);
        mapControl.addRelationship(G_PHYSICAL_MAP, mtTerCross, "Crosshairs");
  
        // Add control after you've specified the relationships
        map.addControl(mapControl);
        map.addControl(new GOverviewMapControl());
        map.enableDoubleClickZoom();
        
        
        mgr = new MarkerManager(map, {trackMarkers:true});
        window.setTimeout(setupOfficeMarkers, 0);
  }
}

    function setupOfficeMarkers() {
      allmarkers.length = 0;
      for (var i in officeLayer) {
        var layer = officeLayer[i];
        var markers = [];
        for (var j in layer["places"]) {
          var place = layer["places"][j];
          var icon = getIcon(place["icon"]);
          var title = place["name"];
          var posn = new GLatLng(place["posn"][0], place["posn"][1]);
          var marker = createMarker(posn,title,icon); 
          markers.push(marker);
          allmarkers.push(marker);
        }
        mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);
      }
      mgr.refresh();
    }
    
    function getIcon(images) {
      var icon = null;
      if (images) {
        if (icons[images[0]]) {
          icon = icons[images[0]];
        } else {
          icon = new GIcon();
          icon.image = "images/elabs.png" 
          var size = iconData[images[0]];
          icon.iconSize = new GSize(size.width, size.height);
          icon.iconAnchor = new GPoint(size.width >> 1, size.height >> 1);
          icon.shadow = "images/shadow.png" 
          size = iconData[images[1]];
          icon.shadowSize = new GSize(size.width, size.height);
          icons[images[0]] = icon;
        }
      }
      return icon;
    }    
  
    function createMarker(posn, title, icon) {
      var marker = new GMarker(posn, {title: title, icon: icon, draggable:false });
      GEvent.addListener(marker, 'dblclick', function() { mgr.removeMarker(marker) } ); 
      return marker;
    }

    function deleteMarker() {
      var markerNum = parseInt(document.getElementById("markerNum").value);
      mgr.removeMarker(allmarkers[markerNum]);
    }
   
    function clearMarkers() {
      mgr.clearMarkers();
    }
   
    function reloadMarkers() {
      setupOfficeMarkers();
    }

function setDirections(fromAddress, toAddress, locale) {
  gdir.load("from: " + fromAddress + " to: " + toAddress,
  { "locale": locale , "getSteps":true});
}

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_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.");
}

///////////////////////////////////////////////////////////////////////

/**
* The add-on code for draggable markers
* @author Esa 2008
*/
var newMarkers = [];
var latLngs = [];
var icons = [];

// Note the 'addoverlay' GEvent listener inside initialize() function of the original code (above).
// 'load' event cannot be used

function onGDirectionsAddOverlay(){
  // Remove the draggable markers from previous function call.
  for (var i=0; i<newMarkers.length; i++){
    map.removeOverlay(newMarkers[i]);
  }

  // Loop through the markers and create draggable copies
  for (var i=0; i<=gdir.getNumRoutes(); i++){
    var originalMarker = gdir.getMarker(i);
    latLngs[i] = originalMarker.getLatLng();
    icons[i] = originalMarker.getIcon();
    newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i], draggable:true, title:'Draggable'});
    map.addOverlay(newMarkers[i]);

    // Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
    GEvent.addListener(newMarkers[i], "dragend", function(){
      var points = [];
      for (var i=0; i<newMarkers.length; i++){
        points[i]= newMarkers[i].getLatLng();
      }
      gdir.loadFromWaypoints(points);
    });

    //Bind 'click' event to original markers 'click' event
    copyClick(newMarkers[i],originalMarker);

    // Now we can remove the original marker safely
    map.removeOverlay(originalMarker);
  }

  function copyClick(newMarker,oldMarker){
    GEvent.addListener(newMarker, 'click', function(){
      GEvent.trigger(oldMarker,'click');
    });
  }
}

// eLabs Google Map functions --- END ---  **********************************************************************
