var map;
var gdir;
var geocoder;
var fromMarker;
var toMarker;
var fromAddress;
var toAddress;
var defaultCenter;
function initialize() {
	if (GBrowserIsCompatible()) { 
		map = new GMap2(document.getElementById("mapCanvas"));
		defaultCenter = new GLatLng(50.8, 4);
		map.setCenter(defaultCenter, 8);
		map.addControl(new GSmallMapControl());
   		map.addControl(new GMapTypeControl());
		fromMarker = new GMarker(defaultCenter, {draggable: true});
		GEvent.addListener(fromMarker, "dragstart", function() {
			fromMarker.closeInfoWindow();
		});
		GEvent.bind(this.fromMarker, "dragend", this, this.fromMarkerDrop);
		
		toMarker = new GMarker(defaultCenter,{draggable: true});
		GEvent.addListener(toMarker, "dragstart",function(){
			toMarker.closeInfoWindow();
		});
		GEvent.bind(this.toMarker, "dragend", this, this.toMarkerDrop);
		
		geocoder = new GClientGeocoder();
		
		
		gdir = new GDirections(map, document.getElementById("directions"));
		//GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
		GEvent.addListener(gdir, "addoverlay", onGDirectionsAddOverlay); // Triggers marker swap, Esa

		//setDirections("Antwerpen", "Brussel", "nl_NL");
	}
}

function checkFromLocation(street, city, country){
	if (street != "" && (city!="" || country!="")) street=street+", ";
	if (city!="" && country!="") city=city+", ";
	fromAddress=street+city+country;
	geocoder.getLocations(fromAddress, addFromAddressToMap);
}

function addFromAddressToMap(response) {
	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to geocode that address");
	} else {
		place = response.Placemark[0];
		point = new GLatLng(place.Point.coordinates[1],
                       place.Point.coordinates[0]);
		fromMarker.setLatLng(point);
		map.addOverlay(fromMarker);
		fromMarker.openInfoWindowHtml(place.address + '<br>' +
			'<b>Coordinates:</b> ' + point) ;
		//update textfields
		if (place.address != fromAddress){
			fromAddress = place.address;
			fillFromTextFields(fromAddress);		
		}
	
 }
}

function fillFromTextFields(address){
	if (address){
	var arr = address.split(",");
		switch (arr.length){
			case 1:
				document.getElementById("fromCountry").value = arr[0];
				break;
			case 2:
				document.getElementById("fromCity").value = arr[0];
				document.getElementById("fromCountry").value = arr[1];
				break;
			case 3:
				document.getElementById("fromStreet").value = arr[0];
				document.getElementById("fromCity").value = arr[1];
				document.getElementById("fromCountry").value = arr[2];
				break;
			default:
				break;
		}
	}
}

function fromMarkerDrop(){
	var dropPoint = fromMarker.getLatLng();
	geocoder.getLocations(dropPoint,addFromAddressToMap);
}

function checkToLocation(street, city, country){
	if (street != "" && (city!="" || country!="")) street=street+", ";
	if (city!="" && country!="") city=city+", ";
	toAddress=street+city+country;
	geocoder.getLocations(toAddress, addToAddressToMap);
}

function addToAddressToMap(response) {
 if (!response || response.Status.code != 200) {
   alert("Sorry, we were unable to geocode that address");
 } else {
   place = response.Placemark[0];
   point = new GLatLng(place.Point.coordinates[1],
                       place.Point.coordinates[0]);
   toMarker.setLatLng(point);
   map.addOverlay(toMarker);
   toMarker.openInfoWindowHtml(place.address + '<br>' +
     '<b>Coordinates:</b> ' + point) ;
 //update textfields
		if (place.address != toAddress){
			toAddress = place.address;
			fillToTextFields(toAddress);		
		}
	
 }
}

function fillToTextFields(address){
	if (address){
	var arr = address.split(",");
		switch (arr.length){
			case 1:
				document.getElementById("toCountry").value = arr[0];
				break;
			case 2:
				document.getElementById("toCity").value = arr[0];
				document.getElementById("toCountry").value = arr[1];
				break;
			case 3:
				document.getElementById("toStreet").value = arr[0];
				document.getElementById("toCity").value = arr[1];
				document.getElementById("toCountry").value = arr[2];
				break;
			default:
				break;
		}
	}
}
function toMarkerDrop(){
	var dropPoint = toMarker.getLatLng();
	geocoder.getLocations(dropPoint,addToAddressToMap);
}






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

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_UNAVAILABLE_ADDRESS) <--- Doc bug... this is either not defined, or Doc is wrong
	// alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\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.");
}

function onGDirectionsLoad(){
	// Use this function to access information about the latest load()
	// results.
	// e.g.
	// document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	// and yada yada yada...
}

//**
//* The add-on code for draggable markers
//* @author Esa 2008
//*/

var custIcon = new GIcon(G_DEFAULT_ICON);
custIcon.iconSize = new GSize(25, 25);
//custIcon.shadowSize = new GSize(0, 0);
//custIcon.iconAnchor = new GPoint(0, 0);

var newMarkers = [];
var latLngs = [];

var icons = [];
icons[0] = new GIcon(custIcon);
icons[0].image = './afbeeldingen/nineball-marker/markers/image.png';
icons[1] = new GIcon(custIcon);
icons[1].image ='./afbeeldingen/nineball-marker/markers/image.png';

 
// Note the 'addoverlay' GEvent listener inside initialize() function of the original code (above).
// 'load' event cannot be used
 
function onGDirectionsAddOverlay(){ 

  for (var i=0; i<newMarkers.length; i++){
    map.removeOverlay(newMarkers[i]);
  }
 
  // Loop through the markers and create draggable copies

  for (var i=0; i<=gdir.getNumRoutes(); i++){
    var originalMarker = gdir.getMarker(i);
    latLngs[i] = originalMarker.getLatLng();
    //icons[i] = originalMarker.getIcon();

map.removeOverlay(originalMarker);
    newMarkers[i] = new GMarker(latLngs[i],{icon:icons[i]});
    map.addOverlay(newMarkers[i]);
  }
}

