var contextmenu, clickedPixel;
var startWaypoint, endWaypoint;

// Aktivieren der Routing Funktion
function enableRouting() {
	if(typeof(map) == 'object' && map != null) {
		map.AttachEvent("onclick", function(mapevent) {
			// Öffnen des Contextmenü bei rechtsklick
			if(mapevent.rightMouseButton == true) {
				// Contextmenü einblenden
				showRoutingMenu(new VEPixel(mapevent.mapX,mapevent.mapY));
			} else {
				hideRoutingMenu();
			}
		});
	}
}



// Contextmenü erzeugen, falls noch nicht vorhanden
function generateRoutingMenu(menu) {
	if(contextmenu == null) {
		contextmenu = document.createElement("div");
		contextmenu.className = 'contextMenu';
		contextmenu.style.position = 'absolute';
		contextmenu.style.zIndex = 300;
		contextmenu.style.width = '238px';
		contextmenu.style.visibility="hidden";
		contextmenu.innerHTML = '<a href="javascript:setStartWaypoint();">Route von...</a>'
													+ '<a href="javascript:setEndWaypoint();">Route bis...</a>'
													+ '<a href="javascript:showDirections();" id="linkShowDirections" class="disabled">Fahrtanweisungen anzeigen</a>'
													+ '<a href="javascript:delRoute();" id="linkDelRoute" class="disabled">'+unescape("Route l%F6schen")+'</a>'
													+ '<div class="hline"></div>'
													+ '<a href="javascript:setZoom(\'+\');">'+unescape("Vergr%F6%DFern")+'</a>'
													+ '<a href="javascript:setZoom(\'-\');">Verkleinern</a>'
													+ '<a href="javascript:setCenter();">Karte hier zentrieren</a>';
		var objBody = document.getElementsByTagName("body").item(0);
		objBody.insertBefore(contextmenu, objBody.firstChild);
	}
}



// Contextmenü üffnen
function showRoutingMenu(pixel,marker_id) {
	// Speichern des geklickten Pixels
	clickedPixel = pixel;
	
	// Routing Menü erzeugen, falls noch nicht vorhanden
	generateRoutingMenu();
	
	// Position des ContextMenüs bestimmen
	var x=pixel.x;
	var y=pixel.y;
	var map_width = document.getElementById('map').offsetWidth;
	var map_height = document.getElementById('map').offsetHeight;
	if(x > map_width - 240) { x = map_width - 240 }
	if(y > map_height - 130) { y = map_height - 130 }
	contextmenu.style.left = map.GetLeft()+x+"px";
	contextmenu.style.top = map.GetTop()+y+"px";
	
	// Contextmenü einblenden
	contextmenu.style.visibility = "visible";
}



// Contextmenü ausblenden
function hideRoutingMenu() {
	if(contextmenu != null) {
		contextmenu.style.visibility = "hidden";
	}
}



// Startwegpunkt setzen
function setStartWaypoint() {
	// Contextmenü auslbenden
	hideRoutingMenu();
	
	// Alten Marker löschen
	if(startWaypoint != null) {
		map.DeleteShape(startWaypoint);
	}
	// Marker setzen
	startWaypoint = new VEShape(VEShapeType.Pushpin, map.PixelToLatLong(clickedPixel));
	// MarkerIcon setzen
	if(typeof(route_starticon) != "undefined") {
		startWaypoint.SetCustomIcon(route_starticon);
	}
	// Marker einzeichnen
	map.AddShape(startWaypoint);
	
	// Route anzeigen
	showRoute();
}



// Endwegpunkt setzen
function setEndWaypoint() {
	// Contextmenü auslbenden
	hideRoutingMenu();
	
	// Alten Marker löschen
	if(endWaypoint != null) {
		map.DeleteShape(endWaypoint);
	}
	// Marker setzen
	endWaypoint = new VEShape(VEShapeType.Pushpin, map.PixelToLatLong(clickedPixel));
	// MarkerIcon setzen
	if(typeof(route_endicon) != "undefined") {
		endWaypoint.SetCustomIcon(route_endicon);
	}
	// Marker einzeichnen
	map.AddShape(endWaypoint);
	
	// Route anzeigen
	showRoute();
}



// Route anzeigen
var groute;
function showRoute() {
	if(startWaypoint != null && endWaypoint != null) {
		// Routenoptionen
		var routeOptions = new VERouteOptions();
		routeOptions.DistanceUnit = VERouteDistanceUnit.Kilometer;
		routeOptions.RouteZIndex = 200;
		
		if(typeof(route_color) != "undefined") {
			//routeOptions.RouteColor = new VEColor(0,41,103,0.7);
			routeOptions.RouteColor = new VEColor(parseInt(route_color.substr(1,2),16),parseInt(route_color.substr(3,2),16),parseInt(route_color.substr(5,2),16),0.7);
		}
		
		routeOptions.RouteCallback = function(route) {
			groute = route;
			var legs     = route.RouteLegs;
			var turns = '<div style="float:left;padding-bottom:8px;"><strong>' + route.Distance.toFixed(1) + " km</strong></div>";
			turns += '<div style="float:right;padding-bottom:8px;"><strong>' + GetTime(route.Time) + "</strong></div>";
			var leg      = null;
			
			// Get intermediate legs
			for(var i = 0; i < legs.length; i++) {
				leg = legs[i];
				var turn = null; 
					
				turns += '<table cellspacing="0" cellpadding="0">';
				for(var j = 0; j < leg.Itinerary.Items.length; j++) {
					turn = leg.Itinerary.Items[j];
					turns += '<tr><td class="nr">'+(j+1)+'.</td><td class="text">' + turn.Text + '</td><td class="distance">' + turn.Distance.toFixed(1) + " km</td></tr>";
				}
				turns += '</table>';
			
				// Icon des Ersten Punktes austauschen
				if(i == 0 && typeof(route_starticon) != "undefined") {
					leg.Itinerary.Items[0].Shape.SetCustomIcon(route_starticon);
				}
				// Icon des letzten Punktes austauschen
				if(i == legs.length-1 && typeof(route_endicon) != "undefined") {
					var lastitem = leg.Itinerary.Items.length - 1;
					leg.Itinerary.Items[lastitem].Shape.SetCustomIcon(route_endicon);
				}
			}
			
			// Directions DIV erzeugen, falls noch nicht vorhanden
			if(document.getElementById('directions') == null) {
				var directions_div = document.createElement("div");
				directions_div.id = 'directions';
				document.getElementById('map').parentNode.appendChild(directions_div);
			}
			
			// Fahrtanweisungen ausgeben
			document.getElementById('directions').innerHTML = turns;
			
			// Marker löschen
			map.DeleteShape(startWaypoint);
			startWaypoint = null;
			map.DeleteShape(endWaypoint);
			endWaypoint = null;
			
			// Links einblenden
			if(turns != null) {
				document.getElementById('linkShowDirections').className = '';
				document.getElementById('linkDelRoute').className = '';
			}
		};
		
		// Route anzeigen
		map.GetDirections([startWaypoint.GetPoints()[0],endWaypoint.GetPoints()[0]],routeOptions);
	}
}


function GetTime(time){
	if(time == null){
		 return("");
	}

 var seconds = time % 60;
 var minutes = time - seconds;
 minutes     = minutes / 60;

 if(minutes > 60) {
		var minLeft = minutes % 60;
		var hours   = minutes - minLeft;
		hours       = hours / 60;

		return(hours + " h, " + minLeft + " min.");
 } else {
		return(minutes + " min.");
 }
}
        

// Fahrtanweisungen anzeigen
function showDirections() {
	if(document.getElementById('directions') != null && document.getElementById('directions').innerHTML != '') {
		// Contextmenü auslbenden
		hideRoutingMenu();
		// Zu den Fahrtanweisungen springen
		window.location.hash = 'directions';
	}
}



// Route ausblenden
function delRoute() {
	if(document.getElementById('directions') != null && document.getElementById('directions').innerHTML != '') {
		// Contextmenü auslbenden
		hideRoutingMenu();
		
		// Fahrtanweisungen ausblenden
		document.getElementById('directions').innerHTML = '';
		// Route ausblenden
		map.DeleteRoute();
		
		// Links ausblenden
		document.getElementById('linkShowDirections').className = 'disabled';
		document.getElementById('linkDelRoute').className = 'disabled';
	}
}



// Vergrößern / Verkleinern
function setZoom(value) {
	// Gewünschen Zoomlevel herausfinden
	if(value == "+") {
		var zoom = map.GetZoomLevel() + 1;
	} else {
		var zoom = map.GetZoomLevel() - 1;
	}
	// Zoomen
	map.SetCenterAndZoom(map.PixelToLatLong(clickedPixel), zoom);
	// Contextmenü ausblenden
	hideRoutingMenu();
}



// Karte zentrieren
function setCenter() {
	map.PanToLatLong(map.PixelToLatLong(clickedPixel));
	// Contextmenü ausblenden
	hideRoutingMenu();
}



// Routing starten
if(typeof(addLoadEvent) == 'function') {
	addLoadEvent(enableRouting);
}
