var map;
var gdir;
var html;
var geocoder = null;
var addressMarker;

var polyline = new GPolyline([
	new GLatLng(50.638901, 6.387434),
	new GLatLng(50.638799, 6.387573),
	new GLatLng(50.638187, 6.388067),
	new GLatLng(50.638071, 6.388196),
	new GLatLng(50.63735, 6.389591),
	new GLatLng(50.637078, 6.390191),
	new GLatLng(50.63671, 6.390953),
	new GLatLng(50.636629, 6.39106),
	new GLatLng(50.636431, 6.391243),
	new GLatLng(50.63588, 6.391693),
	new GLatLng(50.634649, 6.392326),
	new GLatLng(50.634499, 6.392455),
	new GLatLng(50.634438, 6.392627),
	new GLatLng(50.634431, 6.392809),
	new GLatLng(50.634451, 6.392959),
	new GLatLng(50.634832, 6.394558),
	new GLatLng(50.634846, 6.39473),
	new GLatLng(50.634785, 6.395427),
	new GLatLng(50.634785, 6.395856),
	new GLatLng(50.634853, 6.397176),
	new GLatLng(50.634825, 6.397766),
	new GLatLng(50.634778, 6.398045),
	new GLatLng(50.634587, 6.398689),
	new GLatLng(50.63439, 6.399128),
	new GLatLng(50.634254, 6.399268),
	new GLatLng(50.634104, 6.399364),
	new GLatLng(50.633948, 6.399611),
	new GLatLng(50.633818, 6.399869),
	new GLatLng(50.633675, 6.40003),
	new GLatLng(50.633478, 6.400298),
	new GLatLng(50.633369, 6.400502),
	new GLatLng(50.633294, 6.400577),
	new GLatLng(50.633015, 6.400727),
	new GLatLng(50.632893, 6.400824),
	new GLatLng(50.632784, 6.400985),
	new GLatLng(50.632723, 6.401135),
	new GLatLng(50.632682, 6.401242),
	new GLatLng(50.632478, 6.401446),
	new GLatLng(50.632382, 6.401585),
	new GLatLng(50.632308, 6.401778),
	new GLatLng(50.632294, 6.401961),
	new GLatLng(50.632308, 6.402143),
	new GLatLng(50.632335, 6.402304),
	new GLatLng(50.632573, 6.403495),
	new GLatLng(50.632716, 6.404246),
	new GLatLng(50.632723, 6.404439)
]);

function runde(x, n) {
	if (n < 1 || n > 14) return false;
	var e = Math.pow(10, n);
	var k = (Math.round(x * e) / e).toString();
	if (k.indexOf('.') == -1) k += '.';
	k += e.toString().substring(1);
	//return k.substring(0, k.indexOf('.') + n+1);
	
	var tmp = k.substring(0, k.indexOf('.') + n+1);
	var tmp_array = tmp.split(".");
	return tmp_array[0] + "," + tmp_array[1];
}


// ============ custom direction panel ===============
function customPanel(map, mapname, gdir, div) {
	html = "";
	
	var lastNumMarkers = gdir.getNumGeocodes()-1;
	var lastMarker = gdir.getMarker(lastNumMarkers);

	// ===== local functions =====

	// === waypoint banner ===
	function waypoint(point, imgURL, address) {
		var target = '"' + mapname + ".showMapBlowup(new GLatLng(" + point.toUrlValue(6) + "))" + '"';
		html += '<table style="border: 1px solid silver; margin: 10px 0px; background-color: rgb(238, 238, 238); border-collapse: collapse; color: rgb(0, 0, 0);">';
		html += '  <tr style="cursor: pointer;" onclick='+target+'>';
		html += '    <td style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;">';
		html += '      <img src="' +imgURL+ '">'
		html += '    </td>';
		html += '    <td style="vertical-align: middle; width: 100%;">';
		html +=        address;
		html += '    </td>';
		html += '  </tr>';
		html += '</table>';
	}

	// === route distance ===
	function routeDistance(dist) {
		html += '<div style="text-align: right; padding-bottom: 0.3em;">' + dist + '</div>';
	}      

	// === step detail ===
	function detail(point, num, description, dist) {
		var target = '"' + mapname + ".showMapBlowup(new GLatLng(" + point.toUrlValue(6) + "))" + '"';
		html += '<table style="margin: 0px; padding: 0px; border-collapse: collapse;">';
		html += '  <tr style="cursor: pointer;" onclick='+target+'>';
		html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; text-align: right;">';
		html += '      <a href="javascript:void(0)"> '+num+'. </a>';
		html += '    </td>';
		html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; width: 100%;">';
		html +=        description;
		html += '    </td>';
		html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;">';
		html +=        dist;
		html += '    </td>';
		html += '  </tr>';
		html += '</table>';
	}

	// === Copyright tag ===
	function copyright(text) {
		html += '<div style="font-size: 0.86em;">' + text + "</div>";
	}


	// === read through the GRoutes and GSteps ===
	for (var i=0; i<gdir.getNumRoutes(); i++) {
		var route = gdir.getRoute(i);
		var geocode = route.getStartGeocode();
		var point = route.getStep(0).getLatLng();
		
		// === Waypoint at the start of each GRoute
		var marker = gdir.getMarker(i);
		
		waypoint(point, marker.getIcon().image, geocode.address);
		
		//routeDistance(route.getDistance().html+" (ca. "+route.getDuration().html+")");
		routeDistance(runde(((route.getDistance().meters + polyline.getLength())/1000), 1)+" km (ca. "+route.getDuration().html+")");
		
		for (var j=0; j<route.getNumSteps(); j++) {
			var step = route.getStep(j);
			// === detail lines for each step ===
			detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
		}
		
		var tmp_num = j+1;
		var tmp_target = '"' + mapname + ".showMapBlowup(new GLatLng(50.638901,6.387434))" +'"';
		
		html += '<table style="margin: 0px; padding: 0px; border-collapse: collapse;">';
		html += '  <tr style="cursor: pointer;" onclick='+tmp_target+'>';
		html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; text-align: right;">';
		html += '      <a href="javascript:void(0)"> '+tmp_num+'. </a>';
		html += '    </td>';
		html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px; vertical-align: top; width: 100%;">';
		html += '      Schilsbachstra&szlig;e (Uferstra&szlig;e) bis zum Ende <b>folgen</b>. Die Einfahrt zum <b>Segelclub J&uuml;lich e.V.</b> Clubgel&auml;nde befindet sich am Ende der Stra&szlig;e (Teerstra&szlig;e wird zu Schotterweg).';
		html += '    </td>';
		html += '    <td style="border-top: 1px solid rgb(205, 205, 205); margin: 0px; padding: 0.3em 3px 0.3em 0.5em; vertical-align: top; text-align: right;" nowrap="nowrap">';
		html += '      '+runde((polyline.getLength()/1000), 1)+' km';
		html += '    </td>';
		html += '  </tr>';
		html += '</table>';
	}
	
	// === the final destination waypoint ===   
	//var geocode = route.getEndGeocode();
	//var point = route.getEndLatLng();
	//waypoint(point, lastMarker.getIcon().image, "Clubgel&auml;nde des Segelclub J&uuml;lich e.V.");
	
	var tmp_target = '"' + mapname + ".showMapBlowup(new GLatLng(50.632723,6.404439))" +'"';
	html += '<table style="border: 1px solid silver; margin: 10px 0px; background-color: rgb(238, 238, 238); border-collapse: collapse; color: rgb(0, 0, 0);">';
	html += '  <tr style="cursor: pointer;" onclick='+tmp_target+'>';
	html += '    <td style="padding: 4px 15px 0px 5px; vertical-align: middle; width: 20px;">';
	html += '      <img src="'+lastMarker.getIcon().image+'">'
	html += '    </td>';
	html += '    <td style="vertical-align: middle; width: 100%;">';
	html += '      Clubgel&auml;nde des Segelclub J&uuml;lich e.V.';
	html += '    </td>';
	html += '  </tr>';
	html += '</table>';
			 
	// === the copyright text ===
	copyright(gdir.getCopyrightsHtml());

	// === drop the whole thing into the target div
	div.innerHTML = html;
	
    var numMarkers = gdir.getNumGeocodes()-1;
	var marker = gdir.getMarker(i);
	if (marker != null)
		marker.hide();
	
	var point = new GLatLng(50.63270910176157, 6.404460668563843);
	
	// Erstellt ein Basissymbol für alle Markierungen, das den Schatten, die Symbolabmessungen usw. angibt
	var baseIcon = new GIcon();
	
	var baseIcon = new GIcon();
	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);
	
	// Erstellt ein Symbol mit einem Buchstaben für diesen Punkt mithilfe der Symbolklasse
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = lastMarker.getIcon().image;
	
	// Richtet das GMarkerOptions-Objekt ein
	var markerOptions = {icon:letteredIcon};

	map.addOverlay(new GMarker(point, markerOptions));

} // ============ end of customPanel function ===========

function initialize() {
	if (GBrowserIsCompatible()) {
    	map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
    	gdir = new GDirections(map);

    	GEvent.addListener(gdir, "error", function() {
    		alert("Directions Failed: " + gdir.getStatus().code);
    	});

    	setDirections("Juelich", "");
		
		// ========== launch the custom Panel creator a millisecond after the GDirections finishes loading ==========
		// == The delay is required in case we rely on GDirections to perform the initial setCenter ==
		GEvent.addListener(gdir, "load", function() {
			setTimeout('customPanel(map, "map", gdir, document.getElementById("path"))', 1);
		});
		
		map.addOverlay(polyline);
  	}
}
    
function setDirections(fromAddress, overAdresse) {
	if (overAdresse != "") 
		gdir.load("from: " + fromAddress + " to: " + overAdresse + " to: 50.638901, 6.387434", {getSteps:true});
	else
		gdir.load("from: " + fromAddress + " to: 50.638901, 6.387434", {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.");
   
}
