//Declarare variabile 
  var color = null;
  var descriptionLanguage = null;
  var calculationMode = null;
  var routePoints = new Array();
  var type = null;
  var geocoder = null;
  var router = null;
  var routePointsCount = null;
  var geocodedPointsCount = null;
  var routeID = null;
  var viaLocs = new Array();
  var vias = new Array();
  var startLoc = null;
  var destLoc = null;
  var startPointAlternatives = new Array();
  var destinationPointAlternatives = new Array();
  var alternativeCheck = null;

  
  function goMap24() {
  	Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );
  }
  
  function map24ApiLoaded(){
  	// functia de initializare a aplicatiei
  	
  	// varianta (modul) default: initial statica - iar la incarcarea appletului - harta interactiva
  	Map24.MapApplication.init( { NodeName: "maparea" } );
  	
  	// varianta default statica
    // Map24.MapApplication.init( { NodeName: "maparea", MapType: "Static" } );
    
    // afisare controale avansate
    Map24.MapApplication.controlComponent( { Control: "SHOW" , Component: "SHOWTBAR" } ) // controalele pentru masurare distante, highlighting objects, printare harta, afisare harta in fereastra separata
    Map24.MapApplication.controlComponent( { Control: "SHOW" , Component: "SHOWM3DROUTE" } ); // afisare control 3D-VIEW
    Map24.MapApplication.controlComponent( { Control: "SHOW" , Component: "SHOWM3D" } ); // parcurgere drum pe modul fly cu optiune de 3D
    Map24.MapApplication.controlComponent( { Control: "SHOW" , Component: "SHOWOV" } ); // parcurgere drum pe modul fly
    
  }
  
  // Afisare harta statica.
  function staticMap(){
    Map24.MapApplication.setMapType( "Static" );
  }
  
  // Afisare harta interactiva.
  function interactiveMap(){
    Map24.MapApplication.setMapType( "Applet" );
  }
  
  
  function startRouting(){
  	
	// Daca a fost calculata in prealabil o ruta, intai o sterg:
	if ( routeID ){
		removeRoute(routeID);
	}
	
	// Daca am afisat in prealabil rezultatele unei cautari le sterg:
	removeGeocode();
	
    //Initialize the array for storing route points
    routePoints = {};
    //Initialize the counter for geocoded addresses
    geocodedPointsCount = 0;
    
    //Access the calculation mode from the radio buttons
    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;
    }
    
    //Retrieve start and destination of the route from the input fields
 	if (!alternativeCheck){
   
    	var start = Map24.trim( $v('start') );
    	var destination = Map24.trim( $v('destination') );
    	
    	//Check if the fields for setting the start and destination points are empty
    	if( start == "" ) { alert("Va rugam sa introduceti adresa de start!"); return; }
    	if( destination == "" ) { alert("Va rugam sa introduceti destinatia!"); return; }
    }
    
    //Retrieve via points from the input fields. 
    //Ignore empty fields and fields that are filled with whitespaces only.
    
    vias = [];
    for( var i=0; i < 4; i++ ){
      if( Map24.trim( $v( "via_"+i ) ) != "" )
        vias.push( $v("via_"+i) );
    }
    
    //Create a counter that contains the number of route points
    routePointsCount = 2 + vias.length;
   
    //Create a geocoder stub
    if( geocoder == null ) geocoder = new Map24.GeocoderServiceStub();
    
     //Geocode the via points.
    for( var i=0; i < vias.length; i++ ) {
      geocoder.geocode({
        SearchText: vias[i],
        CallbackFunction: setRoutePoint,
        CallbackParameters: { position: "via", index: i }
      });
    }
    
    if (alternativeCheck){
    	setAlternativeRoutePoint();
    }
    
  //scot geocodingurile doar daca nu sunt trimise pe alternative:
    if (!alternativeCheck){
    
       //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.
    // se executa acest bloc doar cand nu exista alternative!
    
    geocoder.geocode({
      SearchText: start,
      CallbackFunction: setRoutePoint,
      CallbackParameters: {position: "start"}
    });
    
    //Geocode the destination address of the route.
    geocoder.geocode({
      SearchText: destination,
      CallbackFunction: setRoutePoint,
      CallbackParameters: {position: "destination"}
    });
    
    	
       //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: 15,
      CallbackFunction: printGeocodingAlternatives, 
      CallbackParameters: {position: "start"}
    });
    
    //Geocode the destination address of the route.
    geocoder.geocode({
      SearchText: destination, 
      MaxNoOfAlternatives: 15, 
      CallbackFunction: printGeocodingAlternatives,
      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 setAlternativeRoutePoint(){
   
      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];
    	
		calculateRoute(); 

    }
   
  
  
  
  //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 setRoutePoint(locations, params){
  	
    //Check if the geocoded address is a via point.
    if( params.position == "via") {
      //Check if via points were provided in the request at all.
      if( typeof routePoints[ "via" ] == "undefined") 
        routePoints[ "via" ] = [];
      //Store the via point
      routePoints[ params.position ][ params.index ] = locations[0];
    }
    else {
      //Store the geocoded start or destination point
      if ( alternativeCheck )
      {
      	if ( params.position == "start" )
      	{
      		routePoints["start"] = startPointAlternatives[starting];
      	}
      	else
      	{
      		routePoints["destination"] = destinationPointAlternatives[dest];
      	}
      }
      else{
      routePoints[ params.position ] = locations[0];
      }
    }
      //Increment the counter for geocoded addresses
      geocodedPointsCount++;
    
    //If all addresses are geocoded successfully, this function calls the calculateRoute() function.
    if( geocodedPointsCount == routePointsCount && !alternativeCheck) {
      calculateRoute(); 
	}  
  }
  
  //Calculate the route.
  function calculateRoute() {
    //Set the transit radius for all via points.
    //Create new Map24.Location objects first
    //with the coordinates of the via points.
    for (var i=0; i<(routePointsCount-2); i++){
      var via = new Map24.Location({
        Longitude: routePoints["via"][i].getLongitude(),
        Latitude: routePoints["via"][i].getLatitude()
      })
      //Set the transit radius
      via.setTransitRadius( parseInt(Map24.trim(document.getElementById('radius'+i).value * 1000)) );
      //Store the new locations in the routePoints array
      //The old locations are overwritten
      routePoints["via"][i] = via;  
    }
    document.getElementById("print").disabled = true; 
    
    //Create a routing service stub
    if( router == null ) router = new Map24.RoutingServiceStub();
 
    //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  
    });
  }
  
  
  //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 e.g. to hide the route.
    routeID = route.RouteID;
    
    //Access the selected color from list box
    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]
    });
    
     //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: "Punctul de plecare:\n"+routePoints["start"].getCity(),
      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: "Destinatie:\n"+routePoints["destination"].getCity(),
      SymbolId: 20958
    });
    destLoc.commit();   
      	
    //Add locations at the position of the route's via points.	
    for(var i = 0; i < (routePointsCount-2); i++){
      var loc = new Map24.Location({
        Longitude: routePoints["via"][i].getLongitude(),
        Latitude: routePoints["via"][i].getLatitude(),
        Description: "Via Point "+(i+1)+"\n"+vias[i],
        SymbolId: 20951
      });
      loc.commit();   
      viaLocs[i] = loc;   		
    }
        
    //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>Ruta: " + $v('start') + " - " + $v('destination') + "</b><br />";
    div_content += "<br />";
    div_content += "Timpul total: " + totalTime + " h<br />" ;     
    div_content += "Lungimea traseului: "+ 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" ) {
        coordinates = route.Segments[i].Coordinates;
       
        //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 a route 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=\"http://devnet.map24.com/demo/ajax/2.0_beta/img/centerabove_std.gif\" alt=\"Center\" onclick=\"centerOnSegment("+centerLon+", "+centerLat+");window.location='#top_map';\"/><br>";
      }
    }
    //Show the route description
    document.getElementById('routeDescription').innerHTML = div_content;
    //Enable the buttons for printing the route description
    document.getElementById("print").disabled = false;
    document.getElementById("button_remove").disabled = false;
  }
  
  
  //Show the route and route points.
  function showRoute (routeID) {
    router.showRoute( {RouteId: routeID, Color: [color, 150]} );
    startLoc.show();
    destLoc.show();
    for(var i = 0; i < (routePointsCount-2); i++){
      viaLocs[i].show();
    } 
  }
  
  
  //Removes a route. After the route is removed, a new route can be calculated.
  function removeRoute(routeID) {
    router.removeRoute( {RouteId: routeID} );   
    startLoc.remove();
    destLoc.remove();
    for(var i = 0; i < (routePointsCount-2); i++){
      viaLocs[i].remove();
    } 
    
    document.getElementById("routeDescription").innerHTML = "";
    document.getElementById("print").disabled = true;   
  }
  
  //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 } );
  }
  
  //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();
	}

	function setLayerStatus( obj, layerId ){
    	if( obj.checked == true )
      		controlLayer( "ENABLE", layerId );
    	else 
      		controlLayer( "DISABLE", layerId );
    	return;  
	}
      
  function controlLayer( cmd, layerId ){
    // Enable or disable the layer
    Map24.MapApplication.controlLayer( { Control: cmd, LayerIds: layerId } );
  }
  
  //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 : ""; 
  }
  
  
  //Geocode an address.
  //The address is provided in the searchText parameter as free text.
  function geocode( searchText ){
  	
  	// Daca a fost calculata in prealabil o ruta, intai o sterg:
	if ( routeID ){
		removeRoute(routeID);
	}
  	
     if(Map24.trim( searchText ) == "") { alert("Va rugam sa introduceti o adresa."); 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: 15, 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 = "<b>Rezultatele cautarii:</b><hr />";
    
    //Iterate through the array of locations.
    for( var i=0; i<locs.length; i++ ){
      
      //Output all relevant properties of all locations.
      result += "<b>Rezultatul Nr."+(i+1)+"</b><br />";
      if (locs[i].getCity()){
      	result += "Localitate: "+locs[i].getCity()+"<br />";
      }
      if (locs[i].getStreet()){
      	result += "Strada: "+locs[i].getStreet()+"<br />";
      }
      if (locs[i].getZip()){
      	result += "Cod Zip: "+locs[i].getZip()+"<br />";
      }
      if (locs[i].getCounty()){
      	result += "Regiune: "+locs[i].getCounty()+"<br />";
      }
      if (locs[i].getState()){
      	result += "Zona administrativa: "+locs[i].getState()+"<br />";
      }
      if (locs[i].getCountry()){
      result += "Tara: "+locs[i].getCountry()+"<br />";
      }
      result += "Longitudine : "+locs[i].getLongitude()+"<br />";
      result += "Latitudine : "+locs[i].getLatitude()+"<br />";
      if (locs[i].getDescription()){
      result += "Descriere: "+locs[i].getDescription()+"<br />";
      }
      result += "<input type=\"button\" value=\"Arata-mi pe harta\" style=\"width: 110px; height: 20px; vertical-align: middle; text-align: center;\" onclick=\"Map24.MapApplication.center( {Longitude: "+locs[i].getLongitude()+", Latitude: "+locs[i].getLatitude()+"}); window.location='#top_map';\" />";
      result += "<hr/>";
    }
    document.getElementById("geocodingresults").innerHTML = result;
    document.getElementById("button_remove").disabled = false;
  }
  
  // functie necesara a fi apelata in cazul in care dorim sa afisam altceva decat rezultatul unei cautari:
  function removeGeocode(){
  	document.getElementById("geocodingresults").innerHTML = "";
  }
  
  function removeAll()
  {
  	if ( routeID )
  	{
  		removeRoute( routeID );
  	}
  	
  	removeGeocode();
  	document.getElementById("button_remove").disabled = true;
  	document.getElementById("geocodingAlternatives").style.display = "none";
  	alternativeCheck = null;
  	vias = [];
  }
  
   
  //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 printGeocodingAlternatives( locs, params ){
  	
  	//Declare local variables
    var county = null;
    var country = 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
      country = locs[i].getCountry();
      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 = "Loc: "+city;
      zip == null? zip = "": zip = ", Zip: "+zip;
      street == null? street = "": street = ", Str: "+street;
      houseNo == null? houseNo = "": houseNo = " "+houseNo;
      county == null? county = "": county = ", Reg: "+county;
      country == null? country = "": country = ", Tara: "+country;
      state == null? state = "": state = ", Zona: "+state;
        
      //Add the geocoded address to the result list
      result +="<option title=\""+city+country+state+zip+street+houseNo+county+"\" style=\"overflow:visible;\">"+city+country+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];  
      }
      
      if( Map24.Browser.IE )
        //For Internet Explorer:
        document.getElementById("geocodingresultsStart").outerHTML ='<select name="printGeocodingAlternatives" id="geocodingresultsStart" style="width:300px; overflow: visible;">'+result+'</select>';
      else
      //Show geocoded alternatives for the start point in a list
      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];
      }
      
      if( Map24.Browser.IE )
        //For Internet Explorer:
        document.getElementById("geocodingresultsDestination").outerHTML ='<select name="printGeocodingAlternatives" id="geocodingresultsDestination" style="width:300px; overflow: visible;">'+result+'</select>';
      else
      //Show geocoded alternatives for the start point in a list
        document.getElementById("geocodingresultsDestination").innerHTML = result;
    }
    
  }

  function pressButtonSubmit() {
  	alternativeCheck = 1;
  	startRouting();
  }