//Declare global variables  
  var geocoder = null;
  var calculationMode = null; //PLUS
  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 );
	
	
	//-------------------
	  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  //window.alert( 'Width = ' + myWidth );
  //window.alert( 'Height = ' + myHeight );
  

htext = 536;
  
var nodeObj1 = document.getElementById('leftnav')
nodeObj1.style.height = (myHeight-htext)+"px" ;

width_table = 320;
height_fix = 96;

var nodeObj2 = document.getElementById('maparea')
nodeObj2.style.height = (myHeight-height_fix)+"px" ;	
nodeObj2.style.width = (myWidth-width_table)+"px";	
	//-------------------
	
  }
  
  function map24ApiLoaded(){
    Map24.MapApplication.init( { NodeName: "maparea" } ); 
    
    //Hide HTML elements that should not be shown initially
    document.getElementById("geocodingResults").style.visibility = "hidden"; 
    document.getElementById("button_calculate_route").style.visibility = "hidden";
  }

  //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(){
  	
	//Access the calculation mode from the radio buttons
    if ( document.getElementById('fast').checked )calculationMode = "Fastest";                                      
    else calculationMode = "Shortest";
	
  	//Initialize the array for storing route points
    routePoints = {};
    //Create a geocoder stub
    if( geocoder == null ) geocoder = new Map24.GeocoderServiceStub();
            
    //Retrieve start and destination of the route from the input fields
    var start = Map24.trim( $v('start') );
    var destination = Map24.trim( $v('destination') );
  
    //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; }
  
    //Geocode the start address of the route
    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: 5,
      CallbackFunction: printGeocodingResult, 
      CallbackParameters: {position: "start"}
    });
    
    //Geocode the destination address of the route.
    geocoder.geocode({
      SearchText: destination, 
      MaxNoOfAlternatives: 5, 
      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: "+city;
      zip == null? zip = "": zip = ", Zip: "+zip;
      street == null? street = "": street = ", Street: "+street;
      houseNo == null? houseNo = "": houseNo = " "+houseNo;
      county == null? county = "": county = ", County: "+county;
      state == null? state = "": state = ", State: "+state;
        
      //Add the geocoded address to the result list
      result +="<option>"+city+state+zip+street+houseNo+county+"</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" id="geocodingresultsStart" style="width:350px;">'+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" id="geocodingresultsDestination" style="width:350px;">'+result+'</select>';
      else
        document.getElementById("geocodingresultsDestination").innerHTML = result;
      
      //Enable and disable buttons
	  //document.getElementById("print").style.visibility = "hidden"; //PLUS
	  
      //document.getElementById("print").disabled = true;
      document.getElementById("geocodingresultsStart").style.visibility = "visible";
      document.getElementById("geocodingresultsDestination").style.visibility = "visible";
      document.getElementById("geocodingResults").style.visibility = "visible";
      document.getElementById("button_calculate_route").style.visibility = "visible";
      document.getElementById("button_calculate_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"],
	  CalculationMode: calculationMode, //PLUS
      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("print").disabled = true;
     document.getElementById("button_calculate_route").disabled = true; 
  	 
  }
  
  //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
    var div_content = "<b>Total Time:</b> " + totalTime + " h<br>" ;     
    div_content += "<b>Total Length:</b> "+ 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++){
      if( typeof route.Segments[i].Coordinates != "undefined" ) {
       
        //Access the longitudes and latitudes of the route segment's coordinates array
        var longitudes = route.Segments[i].Coordinates.Longitudes.toString().split("|");
        var latitudes = route.Segments[i].Coordinates.Latitudes.toString().split("|");
         
        //Get the longitude and latitude in the center of the route segment.
        //These values are needed for centering on a route segment. 
        var centerLon = longitudes[parseInt(longitudes.length / 2)];
        var centerLat = latitudes[parseInt(latitudes.length / 2)];
      }
      
      //For each route segment add the route description and the button for centering on the segment
      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, '' ) 
       // + "<img src=\"/images/ms/centerabove_std.gif\" alt=\"Center\" onclick=\"centerOnSegment("+centerLon+", "+centerLat+");\"/><br>"
      + "<br><br>"
	  }
    }
    document.getElementById('routeDescription').innerHTML = div_content;
    document.getElementById("button_hide_route").disabled = false;
    document.getElementById("button_remove_route").disabled = false;
    document.getElementById("print").disabled = false;
      document.getElementById("print").style.visibility = "hidden"; //PLUS
  }
  
  //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_remove_route").disabled = false;  
  }
  
  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 = true; 
  }
  
  //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("button_remove_route").disabled = true; 
    document.getElementById("button_calculate_route").style.visibility = "visible";
    document.getElementById("button_calculate_route").disabled = false;
    document.getElementById("button_show_list").style.visibility = "visible";
    document.getElementById("button_show_list").disabled = false;
    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 : ""; 
  }
