﻿var geocoder = null;
  var router = null;
  var routePoints = [];
  var routeID = null;
  
  function startRouting(){
    //Retrieve start and destination of the route from the input fields
    var startString = Map24.trim( $v('start') );
    var destinationString = Map24.trim( $v('destination') );
    
    //Check if the start and the destination form fields are empty.
    if( startString == "" ) { alert("Please enter start address!"); return; }
    if( destinationString == "" ) { alert("Please enter destination address!"); return; }
	
	document.getElementById("button_calculate_route").disabled = true;
    
    //Create a geocoder stub
    var geocoder = new Map24.GeocoderServiceStub();
    //Geocode the start address of the route
    //Define the name of the callback function that is called when the result is available on the client.
    geocoder.geocode({ 
      SearchText: startString, 
      MaxNoOfAlternatives: 1, 
      CallbackFunction: setRouteEndPoint, 
      CallbackParameters: {position: "start"}
    });
    
    //Geocode the destination address of the route.
    //Define the name of the callback function that is called when the result is available on the client.
    geocoder.geocode({
      SearchText: destinationString, 
      MaxNoOfAlternatives: 1, 
      CallbackFunction: setRouteEndPoint,
      CallbackParameters: {position: "destination"}
    });
  }
  
  //Callback function that is called when the geocoding result is available.
  //After both the start and the destination address is geocoded, this function calls the calculateRoute() function.
  //The geocoded address is stored at the first position in the locations array.
  function setRouteEndPoint(locations, params){
    //Access the geocoded address and add it to the routePoints array.
    routePoints[ params.position ] = locations[0];
    
    if( typeof routePoints["start"] != "undefined" && typeof routePoints["destination"] != "undefined")
      calculateRoute(); 
  }
  
  //Calculate the route.
  function calculateRoute() {
    router = new Map24.RoutingServiceStub();
    router.calculateRoute({
      Start: routePoints["start"],
      Destination: routePoints["destination"],
     
      CallbackFunction: displayRoute
    });
  
    routePoints = [];
  }

  //Callback function used to access the result of the route calculation.
  //This function is called after the client has received the result from the Routing Service.
  //The route parameter is of type Map24.WebServices.Route.
  function displayRoute( route ){
    
	//Remember the routeId. It is used to hide a route.
	routeID = route.RouteID;

    //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 = "Total Time: " + totalTime + " h<br>" ;     
    div_content += "Total Length: "+ totalLength +" km<br>";
    div_content += "<br>";
    
    //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 += (i+1) + ". " + route.Segments[i].Descriptions[j].Text.replace(/(\[|\[\/)[0-9A-Z_]+\]/g, '' ) + "<br>";
      }
    }
    document.getElementById('route_description').innerHTML = div_content;
	
	document.getElementById("button_hide_route").disabled = false;
	document.getElementById("button_remove_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;
  }
  
  //Hide route
  function hideRoute(routeID) {
  	router.hideRoute({RouteId: routeID});
	document.getElementById("button_show_route").disabled = false;
	document.getElementById("button_hide_route").disabled = true;
  }
  
  //Remove route
  function removeRoute(routeID) {
  	router.removeRoute({RouteId: routeID});
	
	document.getElementById("button_calculate_route").disabled = false;
	document.getElementById("button_show_route").disabled = true;
	document.getElementById("button_hide_route").disabled = true;
	document.getElementById("button_remove_route").disabled = true;
  }
  
  //Helper function.
  function $v( id ) { 
    return   (document.getElementById( id ).value != "undefined") ?  
        document.getElementById( id ).value : ""; 
  }
 function geocode( searchText ){
    if(Map24.trim( searchText ) == "") { alert("Please enter an address."); return; }
  
    var geocoder = new Map24.GeocoderServiceStub();
    //Geocodes the address. The address is passed in the Search field. The Alternatives field defines the number
    //of geocoded addresses that are returned in the response. You must pass the name of the callback function
    //that is called as soon as the client has received the response.
    geocoder.geocode( { SearchText: Map24.trim( searchText ), MaxNoOfAlternatives: 10, CallbackFunction: printResult } );
  }
    
  //Callback function that is called after the client has received the response.
  //This function accesses the array of geocoded addresses and shows them in a list.
  //The elements of this array are objects of the type Map24.Location.
  function printResult( locs ){
    //Center the map view on the first element in the array of geocoded addresses. A Map24.Location object has several
    //methods and properties which you can find in the API documentation for the corresponding class.
    Map24.MapApplication.center( { Longitude: locs[0].getLongitude(), Latitude: locs[0].getLatitude(), MinimumWidth: 2500 } );
    
    //Create a list that shows the results.
    var result = "<br /><center><b>Gefunden:</b></center><hr />";
    
    //Iterate through the array of locations.
    for( var i=0; i<locs.length; i++ ){
      
      //Output all relevant properties of all locations.
      result += "<b>Suchergebniss Nr."+(i+1)+"</b><br />";  
      
      
 
      result += "Ort: "+locs[i].getCity()+"<br />";
      result += "PLZ: "+locs[i].getZip()+"<br />";
      result += "Kreis: "+locs[i].getCounty()+"<br />";
      result += "Land: "+locs[i].getState()+"<br />";
      result += "Country: "+locs[i].getCountry()+"<br />";
      
      result += "<input type=\"button\" value=\"Zeigen\" onclick=\"Map24.MapApplication.center( {Longitude: "+locs[i].getLongitude()+", Latitude: "+locs[i].getLatitude()+"});\" />";            
      result += "<hr/>";
    }
    document.getElementById("geocodingresults").innerHTML = result;
     }