 //Declare global variables  
  var color = null;
  var descriptionLanguage = "pl";
  var calculationMode = null;
  var routePoints = new Array();
  var type = null;
  var geocoder = null;
  var router = null;
  var routePointsCount = null;
  var geocodedPointsCount = null;
   var startPointAlternatives = new Array();
  var destinationPointAlternatives = new Array();
  var routeID = null;
  var viaLocs = new Array();
  var startLoc = null;
  var destLoc = null;

  
  function goMap24() {
    Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );
  }
  
  function map24ApiLoaded(){
	   Map24.MapApplication.setStartMapView( { 
      UpperLeftLongitude: 548.7633629629665,
      UpperLeftLatitude: 3392.5818,
      LowerRightLongitude: 1766.0907703703745,
      LowerRightLatitude: 2861.50146101695
    } );
    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";
  }
  function staticMap(){
    Map24.MapApplication.setMapType( "Static" );
  }
 
  //Show the interactive map.
  function interactiveMap(){
    Map24.MapApplication.setMapType( "Applet" );
  }
  //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(){
	  
	  if ( document.getElementById('fast').checked )
      calculationMode = "Fastest";                                      
    else
      calculationMode = "Shortest";
    
    //Access the type of route to be calculated (either for car or pedestrian)
    type = Map24.trim( $v('type') );
      
    //Access the description language setting
    descriptionLanguage = Map24.trim( $v('descriptionLanguage') );
  
    //Access the chosen measuring unit (only if the description language is english).
    //Internally, the measuring unit is passed in the descriptionLanguage value:
    //"en" for kilometers and "us" for miles.
    if(descriptionLanguage == "en"){
    	descriptionLanguage = document.getElementById("measuringUnit").value;
		
    }
    
  	
  	//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;
      zip == null? zip = "": zip = " "+zip;
      street == null? street = "": street = ", "+street;
      houseNo == null? houseNo = "": houseNo = " "+houseNo;
      county == null? county = "": county = ", "+county;
      state == null? state = "": state = ", "+state;
        
      //Add the geocoded address to the result list
      result +="<option>"+zip+city+street+houseNo+"</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:270px;">'+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:270px;">'+result+'</select>';
      else
        document.getElementById("geocodingresultsDestination").innerHTML = result;
      
      //Enable and disable buttons
      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. 
     //Calculate the route. 
    router.calculateRoute({
      Start: routePoints["start"],
      Destination: routePoints["destination"],
      //Specify further routing options
      CalculationMode: calculationMode,
      VehicleType: type,
      ViaPoints: routePoints["via"],
      DescriptionLanguage: descriptionLanguage,
      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.
   color = document.getElementById("colorBox").value;
     
    //Show the route with the selected color and default transparency value.
    //The transparency can be set to a value between 0 (completely transparent) and 255 (opaque). 
    router.showRoute({
      RouteId: routeID,
      Color: [color, 150]
    });
		
		//Enable helicopter flight on the route. The route flight control
    //will be shown on the map. To start the route flight click on the
    //start button of the route flight control.
    Map24.MapApplication.displayHelicopterFlight({ RouteId: routeID });
    //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 = "Szacowany czas podróży:<b> " + totalTime + " h</b><br>" ;     
    div_content += "Długość wytyczonej trasy: <b>"+ totalLength +" km<br></b>";
    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, '' ) 
        + "&nbsp;&nbsp;&nbsp;<img src=\"/images/strzalka.gif\" width='32' alt=\"Pokaż na mapie\" onclick=\"centerOnSegment("+centerLon+", "+centerLat+");\"/><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;
    
  }
  
  //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 : ""; 
  }
 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: 4500 } );
    //Create a list that shows the results.
    var result = "<div align='center'><table border=0 cellpadding=1 cellspacing=1 width=285><tr><td class=tlo1><b><center>Rezultaty wyszukiwania</center></b></td></tr></table>";
    
    //Iterate through the array of locations.
    for( var i=0; i<locs.length; i++ ){
      
      //Output all relevant properties of all locations.
      result += "<table border=0 cellpadding=1 cellspacing=1 width=285><tr><td class='tlo'><b><center>Wynik wyszukiwania nr"+(i+1)+"</center></b></td></tr></table>";  
      
      result += "<div align='left' style='padding-left:15px;'><b>Wysokość geograficzna</b> :<br /> "+[i+1]+": "+locs[i].getLongitude()+"<br />";
      result += "<b>Szerokość geograficzna</b> :<br /> "+[i+1]+": "+locs[i].getLatitude()+"<br />";
 
      result += "<b>Miasto: </b>"+locs[i].getCity()+"<br />";
      result += "<b>Kod Pocztowy: </b>"+locs[i].getZip()+"<br />";
      result += "<b>Powiat: </b>"+locs[i].getCounty()+"<br />";
      result += "<b>Województwo:</b> "+locs[i].getState()+"<br />";
      result += "<b>Państwo: </b>"+locs[i].getCountry()+"<br />";
      result += "<center><input type=\"button\" value=\"Pokaż na Mapie\" class='button' onclick=\"Map24.MapApplication.center( {Longitude: "+locs[i].getLongitude()+", Latitude: "+locs[i].getLatitude()+"});\" /></center></div>";            
    }
    document.getElementById("menu").innerHTML = result;      
  }