var map;
var marker;
var markerText;
var directions;
var targetAddress;

function load() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		directions = new GDirections(map, document.getElementById("route"));
		GEvent.addListener(directions, "error", handleErrors); 
		
		// Add navigation and zoom control
		map.addControl(new GLargeMapControl());
		map.enableScrollWheelZoom();
		
		// Add map type control
		map.addControl(new GMapTypeControl());
		
		// Geocoding of the start address
		var address = document.getElementById("target_address").innerHTML;
		var zipLocation = document.getElementById("target_zip_location").innerHTML;
		targetAddress = address +", "+ zipLocation;
		var geocoder = new GClientGeocoder();				
		geocoder.getLatLng(targetAddress,
			function(point) {
				if (!point) {
					alert(targetAddress + " konnte auf der Landkarte nicht gefunden werden.");
					return;
				}
				
				map.setCenter(point, 12);
				
				marker = new GMarker(point);
				markerText = "<p><strong>"+ targetAddress +"</strong></p>";
				GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(markerText); });
				map.addOverlay(marker);
				marker.openInfoWindowHtml(markerText);
			}
		);
	}
}

function handleErrors() {
	alert("Fehler: Ihre Startadresse konnte leider nicht gefunden werden.");
}

function setDirections(startAddress) {
	marker.closeInfoWindow();
	var language = document.getElementById("google_maps_language").value;
	directions.load("from: "+ startAddress +" to: "+ targetAddress, { "locale": language });
	
	changeStyles();
}

function changeStyles() {
	var status = directions.getStatus();
	
	if (status["code"] != 200) {
	    window.setTimeout("changeStyles()", 100);
	    return;
	}
	
	status["code"] = 500;
	
	document.getElementById("route_text").style.display = "none";
	document.getElementById("route_form").style.display = "none";

	var routeElement = document.getElementById("route");
	routeElement.getElementsByTagName("table")[0].className = "marker_top";
	routeElement.getElementsByTagName("table")[1].className = "route";
	routeElement.getElementsByTagName("table")[2].className = "marker";
	routeElement.style.display = "block";
}