  var geocoder = null;
  var router = null;
  var routePoints = [];
  var routeID = null;
  var startPointAlternatives = new Array();
  var destinationPointAlternatives = new Array();
  var startLoc = null;
  var destLoc = null;
  
  function goMap24() {
    Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );
  }
  
  function map24ApiLoaded(){
	Map24.MapApplication.setStartMapView( { 
		UpperLeftLongitude: 510.1348148148172,
		UpperLeftLatitude: 3191.6679661016906,
		LowerRightLongitude: 544.1718518518542,
		LowerRightLatitude: 3177.9991525423684
	});    
    Map24.MapApplication.init( { NodeName: "maparea" } ); 
    //Hide HTML elements that should not be shown initially
    document.getElementById("geocodingResults").style.visibility = "hidden"; 
    document.getElementById("geocodingResults").style.display = "none"; 
    document.getElementById("routen_pruefung").style.display = "none";
    document.getElementById("routen_pruefung").style.visibility = "hidden";
    document.getElementById("fahrpreis").style.visibility = "hidden";
    document.getElementById("fahrpreis_box").style.visibility = "hidden"; 
    document.getElementById("fahrpreis_box").style.display = "none"; 
  }
 
  //Geocode given start and destination points.
  //This function is called when the user clicks on the button "Choose the start and destination points".
  function startRouting(){
  	
  	//Initialize the array for storing route points
    routePoints = {};
    //Create a geocoder stub
    if( geocoder == null ) geocoder = new Map24.GeocoderServiceStub();
            
    var start_adresse = Map24.trim( $v('start_strasse'));
    var ziel_adresse = Map24.trim( $v('ziel_strasse'));

    if( start_adresse == "" ) { alert("Bitte geben Sie eine Startadresse ein!"); return; }
    if( ziel_adresse == "" ) { alert("Bitte geben Sie eine Zieladresse ein"); return; }


    var start_ort = Map24.trim( $v('start_ort'));
    var ziel_ort = Map24.trim( $v('ziel_ort'));

    //Retrieve start and destination of the route from the input fields
    var start = Map24.trim( $v('start_strasse') + ' ' + $v('start_plz') + ' ' + $v('start_ort') );
    var destination = Map24.trim( $v('ziel_strasse') + ' ' + $v('ziel_plz') + ' ' + $v('ziel_ort') );
  
    //Check if the start and the destination form fields are empty.
    if( start == "" ) { alert("Bitte geben Sie eine Startadresse ein!"); return; }
    if( destination == "" ) { alert("Bitte geben Sie eine Zieladresse ein"); return; }
  
    //Geocode the start address of the route
		if (start_ort.toLowerCase() == "bremen") {
	    geocoder.geocode({ 
  	    SearchText: start, 
    	  //Define a maximum number of geocoding results to limit
      	//the number of entries that will be shown in the result lists
      	MaxNoOfAlternatives: 20,
      	CallbackFunction: printGeocodingResult,
				Language: "de",
				State: "Bremen",
	      CallbackParameters: {position: "start"}
  	  });
		}
		else {
	    geocoder.geocode({ 
 	    SearchText: start, 
   	  //Define a maximum number of geocoding results to limit
     	//the number of entries that will be shown in the result lists
     	MaxNoOfAlternatives: 20,
     	CallbackFunction: printGeocodingResult,
			Language: "de",
			State: "Bremen",
      CallbackParameters: {position: "start"}
	 	  });
		}
    
    //Geocode the destination address of the route.
		if (ziel_ort.toLowerCase() == "bremen") {
	    geocoder.geocode({
  	    SearchText: destination, 
    	  MaxNoOfAlternatives: 20, 
				Language: "de",
				State: "Bremen",
      CallbackFunction: printGeocodingResult,
      CallbackParameters: {position: "destination"}
    	});
    }
    else {
	    geocoder.geocode({
  	    SearchText: destination, 
    	  MaxNoOfAlternatives: 20, 
				Language: "de",
      CallbackFunction: printGeocodingResult,
      CallbackParameters: {position: "destination"}
		})
  }
  }
  //Callback function that is called when the geocoding result for the start or destination point is available.
  //This function prints all alternative geocoded addresses for the start and destination points in two lists
  //and allows to select one address from each list as start or destination point for the route calculation.
  //The locs array contains the geocoded addresses.
  function printGeocodingResult( locs, params ){
  	
  	//Declare local variables
    var county = null;
    var city = null;
    var zip = null;
    var street = null;
    var houseNo = null;
    var state = null;
    var result = "";
    
    //Iterate through the array of geocoded addresses
    for( var i=0; i<locs.length; i++ ){
      //Access the fields of the geocoded address	
      county = locs[i].getCounty();
      city = locs[i].getCity();
      zip = locs[i].getZip();
      street = locs[i].getStreet();
      houseNo = locs[i].getHouseNo();
      state = locs[i].getState();
      
      //If an address field is null, it is not shown in the result list.
      //Otherwise, the field's value is shown together with the category, 
      //e.g. "City: Frankfurt".
      city == null? city = "": city = city + ",";
      zip == null? zip = "": zip = zip + "";
      street == null? street = "": street = street + ",";
      houseNo == null? houseNo = ", ": houseNo = houseNo + ", ";
      county == null? county = "": county = ", Kreis: "+county;
      state == null? state = "": state = ", Land: "+state;
        
      //Add the geocoded address to the result list
      result += "<option";
			result += ">"+street+city+zip+"</option>"; 
   }
	 
   //Print alternative geocoded addresses for the start point in a list
   if (params.position=="start"){
      //Store alternatives for start point in an array
      for( var i=0; i<locs.length; i++ ){
        startPointAlternatives[i] = locs[i];  
      }
       
      //Show geocoded alternatives for the start point in a list
      if( Map24.Browser.IE )
        //For Internet Explorer:
        document.getElementById("geocodingresultsStart").outerHTML ='<select name="printGeocodingResult" class="ortswahl_select"  id="geocodingresultsStart">'+result+'</select>';
      else
        document.getElementById("geocodingresultsStart").innerHTML = result;
      
    }
    
    //Print alternative geocoded addresses for the destination point in a list
    else {     
      //Store alternatives for destination point in an array
      for( var i=0; i<locs.length; i++ ){
        destinationPointAlternatives[i] = locs[i]; 
      } 
      //Show geocoded alternatives for the destination point in a list
      if( Map24.Browser.IE )
        //For Internet Explorer:
        document.getElementById("geocodingresultsDestination").outerHTML ='<select name="printGeocodingResult" class="ortswahl_select" id="geocodingresultsDestination">'+result+'</select>';
      else
        document.getElementById("geocodingresultsDestination").innerHTML = result;
      
      //Enable and disable buttons
      document.getElementById("geocodingresultsStart").style.visibility = "visible";
      document.getElementById("geocodingresultsDestination").style.visibility = "visible";
	    document.getElementById("geocodingResults").style.display = "block"; 
      document.getElementById("geocodingResults").style.visibility = "visible";
	    document.getElementById("routen_pruefung").style.display = "block";
	    document.getElementById("routen_pruefung").style.visibility = "visible";
      document.getElementById("button_calculate_route").style.visibility = "visible";
      document.getElementById("button_calculate_route").disabled = false;
    	document.getElementById("button_remove_route").style.visibility = "visible";
      document.getElementById("button_remove_route").disabled = false;
     
    }
    
  }
  
  //This function is called after the user has pressed the "Show Route" button.
  //It accesses the selected start and destination from the list boxes and 
  //initiates the route calculation.
  function setRoutePoints(){
    //Get the index of the selected start and destination
    var start = document.forms["start"]["geocodingresultsStart"].selectedIndex;
    var dest = document.forms["dest"]["geocodingresultsDestination"].selectedIndex;
 	 	
    //Store the selected route points in the routePoints array
    routePoints["start"] = startPointAlternatives[start];
    routePoints["destination"] = destinationPointAlternatives[dest];
    
    //Start route calculation
    calculateRoute();
 
//    document.getElementById("button_show_list").disabled = true;
  }
 
  //Calculate the route.
  function calculateRoute() {
  	
    //Create a routing service stub
    if( router == null ) router = new Map24.RoutingServiceStub();
    
	  //Calculate the route. 
    router.calculateRoute({
      Start: routePoints["start"],
      Destination: routePoints["destination"],
      CallbackFunction: displayRoute,
      //The ShowRoute parameter is set to false, the route is not shown automatically.
      //This is necessary if you want to change the default color used for showing the route.
      //To show the route call the Map24.RoutingServiceStub.showRoute() function in the callback function.
      ShowRoute: false
    });
     
     document.getElementById("button_remove_route").disabled = false;   
     document.getElementById("button_show_list").disabled = true;   
     document.getElementById("button_calculate_route").disabled = true;   
     document.getElementById("fahrpreis").style.visibility = "visible";   
	    document.getElementById("fahrpreis_box").style.display = "block"; 
    document.getElementById("fahrpreis_box").style.visibility = "visible"; 
  }
  
  //Callback function used to access the calculated route of type Map24.WebServices.Route.
  //This function shows the route on the map, adds locations at the position of the start and 
  //destination points to the map, prints a detailed route description, and provides 
  //a button next to each entry in the route description that allows to center on a route segment.
  function displayRoute( route ){
  	
    //Remember the routeId. It is used e.g. to hide the route.
    routeID = route.RouteID;
	  
    //Show the route with blue color and transparency.
    //The transparency can be set to a value between 0 (completely transparent) and 255 (opaque).
    router.showRoute( {
      RouteId: routeID,
      Color: ['#00F', 150]
    });
		
    //Add a location at the position of the route's start point.
    startLoc = new Map24.Location({
      Longitude: routePoints["start"].getLongitude(),
      Latitude: routePoints["start"].getLatitude(),
      Description: "Start Point",
      SymbolId: 20950
    });
    startLoc.commit();
    
    //Add a location at the position of the route's destination point.
    destLoc = new Map24.Location({
      Longitude: routePoints["destination"].getLongitude(),
      Latitude: routePoints["destination"].getLatitude(),
      Description: "Destination Point",
	    SymbolId: 20958
    });
    destLoc.commit();    
      	
    //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
//	alert("Hallo");
	var div_laenge = (route.TotalLength/1000);
	var div_zeit = (totalTime*60 ).toFixed(1);     
	var div_laenge = totalLength;
	div_laenge = div_laenge.toFixed(1);
	var div_laenge2 = div_laenge; 
	if ((div_laenge-3) > 0)
	{
		var div_preis = 2.5 + 3*1.7;
//		alert(div_preis);
		div_laenge -= 3;       
		if ((div_laenge-7) > 0)
		{
			div_preis += 1.5*7;
//			alert(div_preis);
			div_laenge -= 7;
//			alert(div_laenge);
			div_preis += 1.3*div_laenge;
//			alert(div_preis);
		}
		else
		{
			div_preis += 1.5*div_laenge;
		}     
	}
	else
	{
		var div_preis = 2.5 + 1.7*div_laenge;       
	}
	if (div_preis < 2.5)
	{
		div_preis = 2.5;
	}
	if (div_laenge2 < 15)
	{
		div_preis *= 1.15;
	}
    var div_zeit1 = div_zeit + " Minuten";     
    var div_laenge1 = div_laenge2 + " km";
//	var div_preis1 = div_preis.toFixed(2) + " EUR";
    var div_preis1 = div_preis.toFixed(1) + "0 EUR";
//    var div_preis1 = div_preis1.toFixed(2) + " EUR";
//	 alert(div_preis1);     
    document.getElementById('div_zeit').innerHTML = div_zeit1;
    document.getElementById('div_laenge').innerHTML = div_laenge1;
    document.getElementById('div_preis').innerHTML = div_preis1;
   
  }
  
  //This function is called after the user has selected a route segment to center on.
  function centerOnSegment (centerLon, centerLat){
  	//Center on the given variable
  	Map24.MapApplication.center( { Coordinate:new Map24.Coordinate(centerLon, centerLat), MinimumWidth: 3034 } );
  }
  
  function showRoute() {
    //Show the route. 
    router.showRoute( {RouteId: routeID} );
    startLoc.show();
    destLoc.show();
    
    document.getElementById("button_show_route").disabled = true;
    document.getElementById("button_hide_route").disabled = false;
    document.getElementById("button_calculate_route").disabled = true;  
    document.getElementById("button_remove_route").disabled = false;  
    document.getElementById("button_show_list").disabled = true;
  }
  
  function hideRoute() {
    //Hide the route.
    router.hideRoute( {RouteId: routeID} );
    startLoc.hide();
    destLoc.hide();
    
    document.getElementById("button_show_route").disabled = false;
//    document.getElementById("button_hide_route").disabled = true;
    document.getElementById("button_remove_route").disabled = false; 
  }
  
  //Removes a route. After the route is removed, a new route can be calculated.
  function removeRoute(routeID) {
    //Remove route
  	router.removeRoute({RouteId: routeID});
  	//Remove locations that show start and destination of the route
    startLoc.remove();
    destLoc.remove();
 
    //Delete route description  
//    document.getElementById("routeDescription").innerHTML = "";
    
    //Reset buttons
//    document.getElementById("button_show_route").disabled = true;
//    document.getElementById("button_hide_route").disabled = true;
    document.getElementById("routen_pruefung").style.visibility = "hidden";
    document.getElementById("routen_pruefung").style.display = "none";
    document.getElementById("button_remove_route").style.visibility = "hidden"; 
    document.getElementById("button_remove_route").disabled = true; 
    document.getElementById("button_calculate_route").style.visibility = "hidden";
    document.getElementById("button_calculate_route").disabled = true;
    document.getElementById("button_show_list").style.visibility = "visible";
    document.getElementById("button_show_list").disabled = false;
//    document.getElementById("print").disabled = true; 
    document.getElementById("geocodingResults").style.display = "none"; 
    document.getElementById("geocodingResults").style.visibility = "hidden";
    document.getElementById("geocodingresultsStart").style.visibility = "hidden";
    document.getElementById("geocodingresultsDestination").style.visibility = "hidden";
    document.getElementById("fahrpreis").style.visibility = "hidden";
    document.getElementById("fahrpreis_box").style.display = "none"; 
    document.getElementById("fahrpreis_box").style.visibility = "hidden"; 

  }
  
  //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 : ""; 
  }
