var RoutePlanner = function()
{
	var preauLocation;
	var mapOptions;
	var map;
	var marker;
	var form;
	var directionsDisplay;
	var directionsService;
	var trips;
	
	var initialize = function()
	{
		preauLocation = new google.maps.LatLng(47.088734, 3.858449);
		
		mapOptions = {
			zoom: 6,
			center: preauLocation,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
	
		map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
		
		marker = new google.maps.Marker({
			position: preauLocation, 
			map: map, 
			title:"l'Huy Préau"
		});
		
		directionsDisplay = new google.maps.DirectionsRenderer();
		directionsService = new google.maps.DirectionsService(); 

		directionsDisplay.setMap(map);		
		
		form = document.getElementById("routeplanner");
		
		form.onsubmit = function()
		{
			try
			{
				var origin = form["startLocation"].value + ", Nederland";
				sendRequest(origin);
			}
			catch(err)
			{
				alert(err);
			}
			
			return false;
		};
		
		form["startLocation"].focus();
	};

	var sendRequest = function(origin)
	{
		var request = {
			origin : origin,
			destination : preauLocation,
			travelMode : google.maps.DirectionsTravelMode.DRIVING,
			unitSystem : google.maps.DirectionsUnitSystem.METRIC,
			provideRouteAlternatives : true,
			region : "nl"
		};

		directionsService.route(request, showResponse);
	};
	
	var showResponse = function(result, status)
	{
		if (status == google.maps.DirectionsStatus.OK)
		{
			trips = result.trips;
			
			marker.setVisible(false);
			directionsDisplay.setDirections(result);
			
			showTripTable();
		}
		else if(status == google.maps.DirectionsStatus.NOT_FOUND)
		{
			var container = document.getElementById("Trips");
			container.innerHTML = "<span class=\"error\">De opgegeven plaats is niet bekend bij de routeplanner.</span>";
		}
		else
		{
			var container = document.getElementById("Trips");
			container.innerHTML = "Fout: " + status;
		}
	};
	
	var showTripTable = function()
	{
		var container = document.getElementById("Trips");
		container.innerHTML = "";
		
		var table = document.createElement("table");
		container.appendChild(table);
		
		for(var i=0; i<trips.length; i++)
		{
			var trip = trips[i];
			
			var distance = 0;
			var duration = 0;
			
			for(var j=0; j<trip.routes.length; j++)
			{
				for(var k=0; k<trip.routes[j].steps.length; k++)
				{
					distance += trip.routes[j].steps[k].distance.value;
					duration += trip.routes[j].steps[k].duration.value;
				}
			}
			
			var row = table.insertRow(-1);
			var descriptionCell = row.insertCell(-1);
			var distanceCell = row.insertCell(-1);
			var durationCell = row.insertCell(-1);
			
			descriptionCell.className = "first";
			descriptionCell.appendChild(document.createTextNode("Route " + (i + 1)));
			distanceCell.appendChild(document.createTextNode(toDistanceString(distance)));
			durationCell.appendChild(document.createTextNode(toDurationString(duration)));
			
			(function(i, row) {
				row.onclick = function() 
				{ 
					for(var r=0; r<table.rows.length; r++)
						table.rows[r].className = "";
					
					row.className = "selected";
					showTrip(i); 
					
					document.getElementById("mapHeader").innerHTML = "Routebeschrijving - afstand: " + toDistanceString(distance) + " - tijdsduur: " + toDurationString(duration);
				};
			})(i, row);
			
			if(i==0)
				row.onclick();
		}
	};
	
	var showTrip = function(index)
	{
		directionsDisplay.setTripIndex(index);
		
		var trip = trips[index];
		var container = document.getElementById("Directions");

		container.innerHTML = "<h2>Routebeschrijving:</h2>";
		
		var table = document.createElement("table");
		container.appendChild(table);
		
		var position = 1;
		
		for(var i=0; i<trip.routes.length; i++)
		{
			var route = trip.routes[i];

			for(var j=0; j<route.steps.length; j++)
			{
				var step = route.steps[j];

				var row = table.insertRow(-1);
				
				var positionCell = row.insertCell(-1);
				var instructionsCell = row.insertCell(-1);
				var distanceCell = row.insertCell(-1);
				var durationCell = row.insertCell(-1);
				
				positionCell.appendChild(document.createTextNode(position + "."));
				instructionsCell.innerHTML = step.instructions;
				distanceCell.appendChild(document.createTextNode(toDistanceString(step.distance.value)));
				durationCell.appendChild(document.createTextNode(toDurationString(step.duration.value)));
				
				positionCell.style.textAlign = "right";
				distanceCell.style.width = "80px";
				durationCell.style.width = "80px";
				
				position++;
			}
		}
	};	
	
	var toDistanceString = function(meters)
	{
		var km = Math.round(meters / 100) / 10;
		return (km + " km").replace(".", ",");
	};
	
	var toDurationString = function(seconds)
	{
		if(seconds < 60)
			return seconds + " sec";

		var minutes = Math.round(seconds / 60);

		if(minutes < 60)
			return minutes + " min";
		
		var hours = Math.floor(minutes / 60);
		minutes = minutes % 60; // calculate the remainer of the minutes

		if(minutes == 0)
			return hours + " uur";
			
		if(minutes < 10)
			minutes = "0" + minutes.toString();
		
		return hours + ":" + minutes + " uur";
	};
	
	var pub = {
		initialize: initialize
	};
	
	return pub;
}();

window.onload = RoutePlanner.initialize;
