var map;
var exml;

function initialize() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    // There is no way to stop the page from also scrolling, unless map takes up entire page.
    // map.enableScrollWheelZoom();
    map.setCenter(new GLatLng(41.875696,-100.624207), 3); 
    map.addControl(new GMapTypeControl());
    map.addControl(new GLargeMapControl());
    map.addControl(new TextualZoomControl());
    exml = new EGeoXml("exml", map, "/our-branches/branches.kml", {directions:true, titlestyle:'class = "marker_title"'});
    exml.parse()

    GEvent.addListener(exml, "parsed", function() {
      map.savePosition(); //Call this the 'home' position
      for (var i = 0; i < exml.gmarkers.length; i++) {
        add_events(exml.gmarkers[i]);
        //For changing the behavior of the Driving Directions, it requires a change to EGeoXML
        var marker = exml.gmarkers[i];
        if (marker.desc.substring(7,0) == 'Contact') {
          marker.window_html = marker.html;
        }
      }
    });
  }
} 

var previousmarker = null;

function add_events(marker) {
  GEvent.addListener(marker, "click", function() {
    if (marker == previousmarker && map.getZoom() < 12) {
      map.setCenter(marker.getLatLng(), 12);
      previousmarker = null;
    }
    previousmarker = marker;
  });
}

function TextualZoomControl() {
}
TextualZoomControl.prototype = new GControl();

TextualZoomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  container.style.border = "1px solid black";

  var homeDiv = document.createElement("div");

  homeDiv.style.backgroundColor = "white";
  homeDiv.style.font = "12px Arial";
  homeDiv.style.border = "1px solid #B0B0B0";
  homeDiv.style.borderLeftColor = "white";
  homeDiv.style.borderTopColor = "white";
  homeDiv.style.textAlign = "center";
  homeDiv.style.width = "5em";
  homeDiv.style.cursor = "pointer";

  container.appendChild(homeDiv);
  homeDiv.appendChild(document.createTextNode("Home"));
  GEvent.addDomListener(homeDiv, "click", function() {
    previousmarker = null;
    map.getInfoWindow().hide();
    map.returnToSavedPosition();
  });

  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
TextualZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(75, 7));
}
