var geocoder = null;
var router = null;
var routePoints = [];
var routeID = null;

function goMap24() 
{
	Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );
}

function map24ApiLoaded()
{
	Map24.MapApplication.init( { NodeName: "maparea", MapType: "Static" } ); 
	//Create a new location. 
	myLoc = new Map24.Location({
		Longitude: 615.15478515625,
		Latitude: 2917.39501953125,
		Description: "Ziegler",
		LogoURL: "http://10.2.1.93/ziegler/fileadmin/images/map24/pin2.gif"
	});
	
	myLoc.setStreet('Memminger Straße');
	myLoc.setHouseNo('28');
	myLoc.setCity('Giengen');
	myLoc.setZip('89537');
	
	
	//Commit the location. Only after calling commit() it is possible 
	//to execute further operations on the location such as hide and show.
	
	if ( document.URL.indexOf("L=2") != -1 )
	{
		document.getElementById("label_address").innerHTML = "Enter address:";
		document.getElementById("b_route").value = "calculate route";
	}
	else
	{
		document.getElementById("label_address").innerHTML = "Adresseingabe:";
		document.getElementById("b_route").value = "Route berechnen";
	}
	
	myLoc.commit();
}

//Show the static map.
function staticMap(){
	Map24.MapApplication.setMapType( "Static" );
}

//Show the interactive map.
function interactiveMap(){
	Map24.MapApplication.setMapType( "Applet" );
}

function startRouting()
{
	//Retrieve start and destination of the route from the input fields
	var start = Map24.trim( $v('field_address') );
	var destination = "Memminger+Stra%C3%9Fe+28+89537+Giengen+an+der+Brenz";

	//Check if the start and the destination form fields are empty
	if( start == "" ) { alert("Please enter start address!"); return; }
	if( destination == "" ) { alert("Please enter destination address!"); return; }

	//Disable the button for starting a route calculation.
	document.getElementById("b_route").disabled = true;
	
	
	//Create a geocoder stub
	var geocoder = new Map24.GeocoderServiceStub();

	//Geocode the start point of the route
	geocoder.geocode({ 
		SearchText: start, 
		//Define the name of the callback function that is called when the result is available on the client.
		CallbackFunction: setRouteEndPoint, 
		//Set a parameter that is passed to the callback function. The parameter defines that this is the start point.
		CallbackParameters: {position: "start"}
	});

	//Geocode the destination point of the route
	geocoder.geocode({
		SearchText: destination,  
		CallbackFunction: setRouteEndPoint,
		CallbackParameters: {position: "destination"}
	});
}

//Callback function that is called when the geocoding result is available.
//The locations parameter contains an array with multiple alternative geocoding results.
//The params parameter passes the value of CallbackParameters that specifies which route 
//end point is returned (start or destination point).
function setRouteEndPoint(locations, params)
{
	//Access the geocoded address and add it to the routePoints array.
	//The geocoded address is stored at the first position in the locations array.
	routePoints[ params.position ] = locations[0];

	//After both the start and the destination addresses are geocoded, this function calls the calculateRoute() function.
	if( typeof routePoints["start"] != "undefined" && typeof routePoints["destination"] != "undefined")
		calculateRoute(); 
}

//Calculate the route.
function calculateRoute() 
{
	router = new Map24.RoutingServiceStub();
	
	if ( document.URL.indexOf("L=2") != -1 )
	{
		router.calculateRoute({
			Start: routePoints["start"],
			Destination: routePoints["destination"],
			CallbackFunction: displayRoute,
			DescriptionLanguage: 'en',
			ShowRoute: false
		});
	}
	else
	{
		router.calculateRoute({
			Start: routePoints["start"],
			Destination: routePoints["destination"],
			CallbackFunction: displayRoute,
			DescriptionLanguage: 'de',
			ShowRoute: false
		});
	}
	
	
	//document.getElementById("print").disabled = true;
	routePoints = [];
}

//Callback function used to access the calculated route of type Map24.WebServices.Route.
//This function is called after the client has received the result from the routing service.
function displayRoute( route )
{
	//Remember the routeId. It is used e.g. to hide the route.
	routeID = route.RouteID;
	router.showRoute( {
		RouteId: routeID,
		Color: ['#00F', 150]
	});
	
	//Access the assumed time needed for traversing the route in hours
	var totalTime = ((route.TotalTime)/(60*60) ).toPrecision(3) 
	//Access the total lenght of the route in kilometers
	var totalLength = (route.TotalLength/1000) 
	//Create table with description of the route
	var div_content = "Gesamtzeit: " + totalTime + " Stunden<br/>" ;     
	div_content += "Gesamtlänge: "+ totalLength +" km<br/>";
	div_content += "<br/>";
	div_content += "<ol>";

	//Iterate through the route segments and output the step-by-step textual description of the route
	for(var i = 0; i < route.Segments.length; i++)
	{
		for(var j = 0; j < route.Segments[i].Descriptions.length; j++)
		{
			//The route description contains tags for further evaluation. For example, the [M24_STREET] tag is used 
			//to denote a street in the description. Add the following line of code to replace these tags by a blank:
			div_content += "<li>" + route.Segments[i].Descriptions[j].Text.replace(/(\[|\[\/)[0-9A-Z_]+\]/g, '' ) + "</li>";
		}
	}
	
	div_content += "</ol>";
	
	
	document.getElementById('routeDescription').innerHTML = div_content;
	
	document.getElementById("b_route").disabled = false;
}
/*
//Show route
function showRoute(routeID) 
{
	router.showRoute({RouteId: routeID});
	document.getElementById("button_show_route").disabled = true;
	document.getElementById("button_hide_route").disabled = false;
	document.getElementById("button_remove_route").disabled = false; 
}

//Hide route
function hideRoute(routeID) 
{
	router.hideRoute({RouteId: routeID});
	document.getElementById("button_show_route").disabled = false;
	document.getElementById("button_hide_route").disabled = true;
	document.getElementById("button_remove_route").disabled = true;
}

//Remove route
function removeRoute(routeID) 
{
	router.removeRoute({RouteId: routeID});
	//Delete route description  
	document.getElementById("routeDescription").innerHTML = "";
	document.getElementById("b_route").disabled = false;
	document.getElementById("button_show_route").disabled = true;
	document.getElementById("button_hide_route").disabled = true;
	document.getElementById("button_remove_route").disabled = true;
	document.getElementById("print").disabled = true; 
}

//Print Description function. 
//The function opens a print preview window of the route description and one can choose the printer. 
function printRouteDescription()
{
	var printContent = document.getElementById("routeDescription");
	var windowPrint = window.open('','','left=0,top=0,width=0,height=0,toolbar=0,scrollbars=0,status=0');
	windowPrint.document.write(printContent.innerHTML);
	windowPrint.document.close();
	windowPrint.focus();
	windowPrint.print();
	windowPrint.close();
}
*/  
//Helper function for accessing the div specified in the id parameter.
//The function checks first if the div contains content.
function $v( id ) 
{ 
	return   (document.getElementById( id ).value != "undefined") ?  document.getElementById( id ).value : ""; 
}