var directionsPanel;
var directions;
var map;
var polyline;

function load() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("anfahrtskizze"));
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(49.142822,9.229932), 12);
    
    var popups = [
		  "<b>Cycle Sport Michael Ebner</b><br />Oststrasse 96<br />74072 Heilbronn",
		  "Startpunkt MTB-Touren"
		  ];
    
    // Creates a marker at the given point with the given number label	
    function createMarker(point, number) {
      var marker = new GMarker(point);
      GEvent.addListener(marker, "click", function() {
			   marker.openInfoWindowHtml(popups[number]);
			 });
      return marker;
    }
    
    var standort = new GLatLng(49.142770,9.230050);
    var mkr = createMarker(standort, 0);
    map.addOverlay(mkr);
    mkr.openInfoWindowHtml(popups[0]);
    directions = new GDirections(map, directionsPanel);
    GEvent.addListener(directions, "error", ondirload);
    GEvent.addListener(directions, "load", ondirload);
    wirelinks();
  }
}

function wirelinks () {
  var rl = document.getElementById("routelist");
  var links = document.getElementsByTagName("a");
  for (var i=0; i<links.length; i++) {
    if (links[i].getAttribute("id") == "a6-mannheim") {
      links[i].onclick = createA6Mh;
    }
    if (links[i].getAttribute("id") == "a6-nuernberg") {
      links[i].onclick = createA6Nb;
    }
    if (links[i].getAttribute("id") == "a81-stuttgart") {
      links[i].onclick = createA81S;
    }
    if (links[i].getAttribute("id") == "ax-wegdamit") {
      links[i].onclick = delRoute;
    }
  }
}

function createA6Mh () {
  delRoute ();
  directions.load("from: 49.187461,9.191812 to: 49.142770,9.230050", { "locale": "de_DE", "getSteps": false });
  // directions.load("from: 49.049486,9.267601 to: 49.142770,9.230050", { "locale": "de_DE", "getSteps": false });
  return false;
}

function createA6Nb () {
  delRoute ();
  directions.load("from: 49.175482,9.241315 to: 49.142770,9.230050", { "locale": "de_DE", "getSteps": false });
  return false;
}

function createA81S () {
  delRoute ();
  directions.load("from: 49.079481,9.287878 to: 49.142770,9.230050", { "locale": "de_DE", "getSteps": false });
  // directions.load("from: 49.187461,9.191812 to: 49.142770,9.230050", { "locale": "de_DE", "getSteps": false });
  return false;
}

function delRoute () {
  if (polyline) {
    map.removeOverlay(polyline);
    // polyline = null;
  }
  return false;
}

function ondirload () {
if (directions.getStatus().code == "200") {
  polyline = directions.getPolyline();
  map.addOverlay(polyline);
  map.setCenter(new GLatLng(49.142822,9.229932), 12);
 } else {
  alert(directions.getStatus().code);
 }
}
