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

function initializeGMaps() {
	if (GBrowserIsCompatible()) {      
		map = new GMap2(document.getElementById("map_canvas"));
		gdir = new GDirections(map);
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		
		geocoder = new GClientGeocoder();

		//setDirections(document.directionsForm.route_to.value, document.directionsForm.route_to.value, "nl_NL");
		showAddress(document.getElementById('route_to').value);
	}
}

function setDirections(fromAddress, toAddress, locale) {
	gdir.load("from: " + fromAddress + " to: " + toAddress,
	{ "locale": locale, getSteps: true });
}

function onGDirectionsLoad(){ 

	var route = gdir.getRoute(0);
	
	/* Get the addresses to display at the start and end of the directions */
	var startAddress = route.getStartGeocode().address;
	var   endAddress = route.getEndGeocode().address;
	
	/* Write the start address title, marker, and summary */
	var html =  getLiHtml("&nbsp", "Naar " + endAddress + " - " + route.getSummaryHtml(), "");
	
	/* Build up the textual directions step by step */
	for (var n = 0; n < route.getNumSteps(); n++) {
	html += getLiHtml((n + 1) + ".", route.getStep(n).getDescriptionHtml(), route.getStep(n).getDistance().html);
	}
	
	/* Fill in the div on the page with the generated HTML */
	document.getElementById("map_directions").innerHTML = html;

}

function getLiHtml(step, description, distance) {
	var li = "<li>";
	li += '<div class="number">' + step + '</div>';
	li += '<div class="description">' + description + '</div>';
	li += '<div class="distance">' + distance + '</div>';
	li += '<div class="clearboth"></div>';
	return li;
}

function showAddress(address) {
	if (geocoder) {
		geocoder.getLatLng(
		address,
		function(point) {
			if (!point) {
				//alert(address + " not found");
			} else {
				map.setCenter(point, 7);
				var marker = new GMarker(point);
				map.addOverlay(marker);
			}
		}
		);
	}
}
