function visible(nr) {
	if (document.layers)
	{
		current = (document.layers[nr].left == '0') ? '-600' : '0';
		document.layers[nr].left = current;
		current2 = (document.layers[nr].top == '10') ? '-410' : '10';
		document.layers[nr].top = current2;
	}
	else if (document.all)
	{
		current = (document.all[nr].style.left == '0') ? '-600' : '0';
		document.all[nr].style.left = current;
		current2 = (document.all[nr].style.top == '10') ? '-410' : '10';
		document.all[nr].style.top = current2;
	}
	else if (document.getElementById)
	{
		vista = (document.getElementById(nr).style.left == '0') ? '-600' : '0';
		document.getElementById(nr).style.left = vista;
		vista2 = (document.getElementById(nr).style.top == '10') ? '-410' : '10';
		document.getElementById(nr).style.top = vista2;
	}
}

function blocking(nr) {
	if (document.layers)
	{
		current = (document.layers[nr].display == 'none') ? 'block' : 'none';
		document.layers[nr].display = current;
	}
	else if (document.all)
	{
		current = (document.all[nr].style.display == 'none') ? 'block' : 'none';
		document.all[nr].style.display = current;
	}
	else if (document.getElementById)
	{
		vista1 = (document.getElementById(nr).style.display == 'none') ? 'block' : 'none';
		document.getElementById(nr).style.display = vista1;
	}
}

function centerMap(){
  var mrcContainer = new Map24.Webservices.Request.MapletRemoteControl();
  mrcContainer.push(
    new Map24.Webservices.MRC.SetMapView({
      Coordinates: new Map24.Coordinate( 801, 2853 ),
      ClippingWidth: new Map24.Webservices.ClippingWidth(
        { MinimumWidth: 80000 }              
      )
    })
  );
  map.Webservices.sendRequest( mrcContainer );
}

function goMap24() {
    Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );
  }
  
  function map24ApiLoaded(){
    Map24.MapApplication.init( { NodeName: "maparea" } ); 
    centerMap();
  }
  
  var RouteID = null;
  var routePoints = null;
  var routePointsCount = null;
  var geocodedPointsCount = null;
  var geocoder = null;
  var router = null;
  
  
 
  function startRouting(){
    //Retrieve start of the route from the input fields
    var startString = Map24.trim( $v('start') );
    if( startString == "" ) { alert(enter_start); return; }
    
    //Retrieve destination of the route from the input fields
    var destinationString = Map24.trim( $v('destination') );
    if( destinationString == "" ) { alert(enter_destination); return; }
    
    if (destinationString != "" && startString != "" && block == true) {
      visible('maparea');
      blocking('formulararea');
    }
    routePoints = {};
  	geocodedPointsCount = 0;
  	
    //Create a geocoder stub
    if( geocoder == null ) geocoder = new Map24.GeocoderServiceStub();
    //Create a routing service stub
    if( router == null ) router = new Map24.RoutingServiceStub();
  	
   //Retrieve via points from the input fields. 
    //Ignore empty fields and fields that are filled with whitespaces only.
    var viaPointsStrings = [];
    for( var i=1; i < 3; i++ ){
      if( Map24.trim( $v( "via_"+i ) ) != "" )
        viaPointsStrings.push( $v("via_"+i) );
    }
    
    //Create a counter that contains the number of route points
    routePointsCount = 2 + viaPointsStrings.length;
    //Geocode the start address
    geocoder.geocode({ 
      SearchText: startString, 
      MaxNoOfAlternatives: 1, 
      CallbackFunction: setRoutePoint, 
      CallbackParameters: {position: "start"}
    });
    
    //Geocode the destination address
    geocoder.geocode({
      SearchText: destinationString, 
      MaxNoOfAlternatives: 1, 
      CallbackFunction: setRoutePoint,
      CallbackParameters: {position: "destination"}
    });
    
    //Geocode the via points. As for the start and destination address, you have to 
    //define the name of the callback function that is called when the result is available 
    //on the client. In the CallbackParameters you have to specify the position of the via 
    //point in the array (index field).
    for( var i=0; i < viaPointsStrings.length; i++ ) {
      geocoder.geocode({
        SearchText: viaPointsStrings[i],
        MaxNoOfAlternatives: 1,
        CallbackFunction:  setRoutePoint,
        CallbackParameters: { position: "via", index: i }
      });
    }
  }
  
  //Callback function that is called when a geocoding result is available.
  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
      routePoints[ params.position ] = locations[0];
    
    geocodedPointsCount++;
    //If all addresses are geocoded successfully, this function calls the calculateRoute() function.
    if( geocodedPointsCount == routePointsCount ) {
      calculateRoute(); 
	 }

  }
  
  //Calculate the route
  function calculateRoute() {
    router.calculateRoute({
      Start: routePoints["start"],
      Destination: routePoints["destination"],
      DescriptionLanguage: lang,
      CalculationMode: getCalculationMode(),
      ViaPoints: routePoints["via"],
      CallbackFunction: displayRoute
    });
  }
  
  //Get the calculation mode. either fastest or shortest
  function getCalculationMode() {
    if (document.calc.elements[0].checked == true) {
      return document.calc.elements[0].value;
    }
    else {
      return document.calc.elements[1].value;
    }
  }
  
  function show() {
    //Show the route. 
    router.showRoute( {RouteId: RouteID} );
  }
  
  function hide() {
    //Hide the route.
    router.hideRoute( {RouteId: RouteID} );
  }
  
  function remove(routeID) {
    //Remove route
  	router.removeRoute({RouteId: routeID});
  }
  
  //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.
  function displayRoute( route ){
    
    RouteID = route.RouteID;
    
    //Access route information
    var totalTime = ((route.TotalTime)/(60*60) ).toPrecision(3) //h
    var totalLength = (route.TotalLength/1000) //km
    //Create table with description of the route
    var div_content = dur + totalTime + dur_unit + "<br>" ;     
    div_content += dist + totalLength + dist_unit + "<br>";
    div_content += "<br>";
    div_content += "<ol>";
    
    //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++){
      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 += "<li>" + route.Segments[i].Descriptions[j].Text.replace(/(\[|\[\/)[0-9A-Z_]+\]/g, '' ) + "</li>";
      }
    }
    div_content += "</ol>";
    $('route_description').innerHTML = div_content;  
  }
  
  //Show route
  function showRoute(routeID) {
  	router.showRoute({RouteId: routeID});
  }
  
  //Hide route
  function hideRoute(routeID) {
  	router.hideRoute({RouteId: routeID});
  }
    //Remove route
  function removeRoute(routeID) {
  	router.removeRoute({RouteId: routeID});
  }
  
  //Helper functions.
  function $( id ) { return document.getElementById( id ); }
  function $v( id ) { 
    return   (document.getElementById( id ).value != "undefined") ?  
        document.getElementById( id ).value : ""; 
  }
