  //Declare global variables  
  var color = null;
  var descriptionLanguage = null;
  var calculationMode = null;
  var routePoints = new Array();
  var type = null;
  var geocoder = null;
  var geocoder_sel = null;
  var router = null;
  var routePointsCount = null;
  var geocodedPointsCount = null;
  var routeID = null;
  var startPointAlternatives = new Array();
  var destinationPointAlternatives = new Array();
  var viaLocs = new Array();
  var startLoc = null;
  var destLoc = null;
  
  function goMap24() {
    Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );
  }
  
  function map24ApiLoaded(){
    Map24.MapApplication.init( { NodeName: "maparea" } ); 
    
    //Hide HTML elements that should not be shown initially
    hideLayer("geocodingResults");
  }
 
  function startRouting(){
  	//Initialize the array for storing route points
    routePoints = {};
    //Initialize the counter for geocoded addresses
    geocodedPointsCount = 0;
       
    //Disable the button for starting a route calculation.
    document.getElementById("button_calculate_route").disabled = true;
            
    //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 fields for setting the start and destination points are empty
    if( start == "" ) { showLayer("errmsg");showerr("Va rugam introduceti adresa de plecare!"); return; }
    if( destination == "" ) { showLayer("errmsg");showerr("Va rugam introduceti adresa destinatiei!"); return; }
    
		//hide error message layer
    hideLayer("errmsg");
  	 
    //Create a geocoder_sel stub
    if( geocoder_sel == null ) geocoder_sel = new Map24.GeocoderServiceStub();
    
     //Geocode the start address of the route
    geocoder_sel.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_sel.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 = "";
    
    if (params.position=="start")
    	result="<select id=\"geocodingresultsStart\">"
    else
    	result="<select id=\"geocodingresultsDestination\">"
			
    //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 = "Oras: "+city;
      zip == null? zip = "": zip = ", Cod postal: "+zip;
      street == null? street = "": street = ", Strada: "+street;
      houseNo == null? houseNo = "": houseNo = " "+houseNo;
      county == null? county = "": county = ", Regiunea: "+county;
      state == null? state = "": state = ", Judet / District: "+state;
       
			var opt_value=city+state+zip+street+houseNo+county
			 
      //Add the geocoded address to the result list
      result +="<option value=\""+ opt_value +"\">"+opt_value+"</option>"; 
    }
	 
	 	result +="</select>"
	 	
	 	//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
       document.getElementById("div_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
      document.getElementById("div_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";
      
			showLayer("geocodingResults");
			document.getElementById("button_calculate_route").disabled = false;
     
    }
    
  }

 //function called onClick btn after select
  function linkRoute() {  
  	if( geocoder == null ) geocoder = new Map24.GeocoderServiceStub();

		//Store the geocoded start or destination point
    //Get the index of the selected start and destination
    var start = document.getElementById("geocodingresultsStart").selectedIndex;
    var dest = document.getElementById("geocodingresultsDestination").selectedIndex;

		var ss=document.getElementById("geocodingresultsStart")[start].value
		var dd=document.getElementById("geocodingresultsDestination")[dest].value
		
		//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: ss,
      CallbackFunction: setRoutePoint,
      CallbackParameters: {position: "start"}
    });
    
    //Geocode the destination address of the route.
    geocoder.geocode({
      SearchText: dd,
      CallbackFunction: setRoutePoint,
      CallbackParameters: {position: "destination"}
    });
    
    
    //Retrieve via points from the input fields. 
    //Ignore empty fields and fields that are filled with whitespaces only.
    var 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;

		//Geocode the via points.
    for( var i=0; i < vias.length; i++ ) {
      geocoder.geocode({
        SearchText: vias[i],
        CallbackFunction: setRoutePoint,
        CallbackParameters: { position: "via", index: i }
      });
    }
    
  }
  
 
  //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
    //Get the index of the selected start and destination
    var start = document.getElementById("geocodingresultsStart").selectedIndex;
    var dest = document.getElementById("geocodingresultsDestination").selectedIndex;
 	 	
 	 	//Store the selected route points in the routePoints array
    routePoints["start"] = startPointAlternatives[start];
    routePoints["destination"] = destinationPointAlternatives[dest];
	
		}
 
      //Increment the counter for geocoded addresses
      geocodedPointsCount++;

    //If all addresses are geocoded successfully, this function calls the calculateRoute() function.
    if( geocodedPointsCount == routePointsCount ) {
      calculateRoute(); 
	  }  
  }
  
  //Calculate the route.
  function calculateRoute() {
  	//Access the calculation mode from the radio buttons
    if ( $v('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;
    }
    
    
    //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: "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();    
      	
    //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),
        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)
    
		var v_ore = Math.floor((route.TotalTime)/(60*60) ) 
    var v_min = Math.floor((totalTime - v_ore)*59)
        
		//Create table with description of the route
    var div_content = "<table class='tbl_pret' cellspacing='0' width='710'><tr><td class='td_cap' align='left' colspan='2'>Timp Total: </td>"
		div_content += "<td class='td_bg1' align='left' width='420'> "
		if (v_ore > 0)
			div_content += v_ore + " ore,  " 
		div_content +=v_min + " minute</td>"
		
		div_content +="<td class='td_cap' width='50' rowspan='2' valign='bottom' align='center'>Distanta</td>"
		div_content +="<td class='td_cap' width='50' rowspan='2' valign='bottom' align='center'>Timp</td>"
		
		div_content +="<td class='td_cap' colspan='2' align='center'>TOTAL</td></tr>"
		
		div_content += "<tr><td class='td_cap' align='left' colspan='2'>Lungime drum: </td>"
		div_content += "<td class='td_bg1' align='left'> "
		div_content += totalLength.toFixed(2) +" km</td>"
		
		div_content +="<td class='td_cap' width='60' align='center'>Distanta</td>"
		div_content +="<td class='td_cap' width='60' align='center'>Timp</td></tr>";
    
    //contor for current step
    var v_step=0
    
		var tot_lung=0			//lungimea traseului parcurs pana la segmentul curent, inclusiv seg crt
    
		var seg_timp=0			//timpul de parcurgere a segmentului curent
		var tot_timp=0			//timpul traseului parcurs pana in prezent, inclusiv seg crt
    var aux_timp=0
    
    var aux_h		//auxiliara pt nr. de ore
    var aux_m		//auxiliara pt nr. de minute
    
    var v_city=""
    var v_nextcity=""
    var v_country=""
    var v_nextcountry=""
    var aux_i=0
    
    //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:
      	
				v_step=v_step + 1
      	div_content += "<tr><td class='td_cap' align='left' width='30'>"+ v_step +". </td>"

				v_city = route.Segments[i].City
				v_country = route.Segments[i].Country		
				
				if (i<(route.Segments.length-1))
					aux_i = i+1
				else
					aux_i = i
				
				v_nextcity = route.Segments[aux_i].City
				v_nextcountry = route.Segments[aux_i].Country		
					
				/*
				var x = document.getElementById("msgrows");				
				x.value += "\n" + v_step + ". country=" + v_country  + ", nextcountry=" + v_nextcountry 
				x.value += ". city=" + v_city  + ", nextcity=" + v_nextcity 
				*/
				
				//picture
				div_content += "<td class='td_bg1' align='left' width='40'><img alt=\"\" src=\"http://www.gazonline.ro/img/rp_"

				if (i==0 && j==0)		//start point
					div_content += "start.gif\" width=\"17\" height=\"18\" "
				else {
					if (i==(route.Segments.length-1) && j==(route.Segments[i].Descriptions.length-1))		//end point
						div_content += "end.gif\" width=\"25\" height=\"25\" "
					else {
						if ((v_country != v_nextcountry) && (j==(route.Segments[i].Descriptions.length-1)))
							div_content += "vama.gif\" width=\"30\" height=\"28\" "
						else {
							if ((v_city==undefined) && (v_nextcity != undefined) && (j==(route.Segments[i].Descriptions.length-1)))
								div_content += "scity.gif\" width=\"25\" height=\"15\" "
							else {
								if ((v_city!=undefined) && (v_nextcity == undefined) && (j==(route.Segments[i].Descriptions.length-1)))
									div_content += "ecity.gif\" width=\"25\" height=\"15\" "
								else {
									if (route.Segments[i].ExitNumber>0 && route.Segments[i].ExitNumber<17) {
										if (route.Segments[i].SegmentLength==0 && route.Segments[i].Time==0)		//punct intermediar (via)
											div_content += "via.gif\" width=\"17\" height=\"18\" "
										else		//sens giratoriu
											div_content += "gir.gif\" width=\"24\" height=\"24\" "
									}
									else {
										if (route.Segments[i].StreetClass=='Freeway' && route.Segments[i].Direction.Value==0)		//autostrada
											div_content += "Freeway.gif\" width=\"19\" height=\"17\" "
										else 
											div_content += "dir" + route.Segments[i].Direction.Value + ".gif\" width=\"13\" height=\"18\" "	
									}
								}
							}
						}
					}
				}
									
				div_content += " /></td>"
				      	
      	//end picture
				
				
      	div_content += "<td class='td_bg1' align='left'>"
        div_content +=  route.Segments[i].Descriptions[j].Text.replace(/(\[|\[\/)[0-9A-Z_]+\]/g, '' ) 
        + "<a href=\"#harta\"><img src=\"http://www.gazonline.ro/img/rp_start.gif\" width=\"17\" height=\"18\" alt=\"Localizare\" border=\"0\" onmouseover=\"showtip(this,event,'<?=$vg_tips['route_planner']['loc']?>');\" onmouseout=\"hidetip();\" onclick=\"centerOnSegment("+centerLon+", "+centerLat+");\" /></a></td>"
				
				//calcul distanta si timp pe segment, si subtotaluri
				//se afiseaza doar pe prima linie (cand j=0), cu rowspan pe cate descriptions am la segmentul crt
				
				if (j==0) {
					//distanta seg crt
					div_content += "<td class='td_bg1' rowspan='"+ route.Segments[i].Descriptions.length +"' align='right' valign='middle'>"
					if (route.Segments[i].SegmentLength>0)
						div_content += (route.Segments[i].SegmentLength/1000).toFixed(2) + "	km</td>"
					tot_lung += route.Segments[i].SegmentLength/1000
					
					//timp seg crt
					seg_timp = ((route.Segments[i].Time)/(60*60) ).toPrecision(3) 
    			aux_h = Math.floor((route.Segments[i].Time)/(60*60) ) 
    			aux_m = Math.floor((seg_timp - aux_h)*59)
    
					div_content += "<td class='td_bg1' rowspan='"+ route.Segments[i].Descriptions.length +"' align='right' valign='middle'>"
					if (aux_h>0)
						div_content += aux_h + " h, "
					if (aux_m>0)
						div_content += aux_m + " m </td>"
					tot_timp += route.Segments[i].Time
									
					//distanta totala
					div_content += "<td class='td_bg2' rowspan='"+ route.Segments[i].Descriptions.length +"' align='right' valign='middle'>"
					div_content += tot_lung.toFixed(2) + "	km</td>"
			
					//timp total
					aux_timp = ((tot_timp)/(60*60) ).toPrecision(3) 
    			aux_h = Math.floor((tot_timp)/(60*60) ) 
    			aux_m = Math.floor((aux_timp - aux_h)*59)
    
					div_content += "<td class='td_bg2' rowspan='"+ route.Segments[i].Descriptions.length +"' align='right' valign='middle'>"
					if (aux_h>0)
						div_content += aux_h + " h, "
					div_content += aux_m + " m </td>"
					
				}
				
				div_content +=  "</tr>"

      }		//end for j
      
    }		//end for i
    
		div_content += "</table>"    
    
    //Show the route description
    document.getElementById('routeDescription').innerHTML = div_content;
    //Enable the buttons for hiding or removing the route, and for printing the route description
    document.getElementById("button_hide_route").disabled = false;
    document.getElementById("button_remove_route").disabled = false;
    document.getElementById("print").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();
    } 
    document.getElementById("button_show_route").disabled = true;
    document.getElementById("button_hide_route").disabled = false;
    document.getElementById("button_remove_route").disabled = false;
  }
  
  //Hide the route and route points.
  function hideRoute(routeID) {
    router.hideRoute( {RouteId: routeID} );
    startLoc.hide();
    destLoc.hide();
    for(var i = 0; i < (routePointsCount-2); i++){
      viaLocs[i].hide();
    }  
    document.getElementById("button_remove_route").disabled = true;
    document.getElementById("button_show_route").disabled = false;
    document.getElementById("button_hide_route").disabled = true;
  }
  
  //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("button_show_route").disabled = true;
    document.getElementById("button_hide_route").disabled = true;
    document.getElementById("button_remove_route").disabled = true;
    document.getElementById("routeDescription").innerHTML = "";
    document.getElementById("button_calculate_route").disabled = false;
    document.getElementById("print").disabled = true;   
    
		//Hide HTML elements that should not be shown initially
    //document.getElementById("geocodingResults").style.visibility = "hidden"; 
    //document.getElementById("button_calculate_route").style.visibility = "hidden";
		hideLayer("geocodingResults");
  }
 
  
  //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 = "<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"styles/style.css\" /></head>"		
		printContent += (document.getElementById("routeDescription")).innerHTML;
		printContent += "</html>"
		
    var windowPrint = window.open('','','left=0,top=0,width=0,height=0,toolbar=0,scrollbars=0,status=0');
    windowPrint.document.write(printContent);
    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 : ""; 
  }
 