  var htmlObj = null;
  var geocoder = null;
  var router = null;
  var routePoints = [];
  var routeID = null;
  
  function goMap24() {
    Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );

  }

  function map24ApiLoaded(){
   //This function sets the map view that after start-up.
   Map24.MapApplication.setStartMapView( { 
      UpperLeftLongitude: 2766.696585185183,
      UpperLeftLatitude: 1808.019701694914,
      LowerRightLongitude: 2923.5899185185162,
      LowerRightLatitude: 1709.591735593219
    } );
        
    //Initialize mapping client
    Map24.MapApplication.init( { NodeName: "maparea" } );
	add();
	Map24.MapApplication.Map.addListener( "Map24.Event.MapClick", mapClicked );
  }
 
 function mapClicked( e ){
    document.getElementById("lon").value = e.Coordinate.Longitude;
	document.getElementById("lat").value = e.Coordinate.Latitude;
    e.stop();    
  }
  
  
  //Create content of HTML object.
  var htmlContent = "<b>Dasman Center for Research and Treatment of Diabetes</b>"+
    "<br/>"+
    "P.O.Box 1180"+
    "<br/>"+
    "Dasman, 15462 Kuwait "+
    "<br/>"+
    "Tel:(00965) 2242999"+
    "<br/>"+
	" Fax:(00965) 2492436 "+
    "<br/>"+
    " Email:pr@dcrtd.org.kw"+
	"<p>";
      
  function add() {
    //Create a location with a tooltip. Tooltips are HTML objects that are shown when a mouse event 
    //occurs on the location. The content of the tooltip is set in TooltipContent. 
    myLoc = new Map24.Location({
      Longitude: 2879.595103703701,
      Latitude: 1763.428515254236,
      LogoURL: "http://www.design-master.com/map/logo_dcrtd.gif",
	  Description: "Dasman Center for Research and Treatment of Diabetes\n(click to view address)",
      TooltipLayout: Map24.MapObject.LAYOUT_PLAIN,
      TooltipSize: Map24.MapObject.SIZE_M
    });
    //Call commit() on the location. The location is shown on the map.
	myLoc.addListener( "OnClick", Popup  );
    myLoc.commit();
  }
  //Remove the location.
  
  function centerOn() {
    myLoc.center( { MinimumWidth: 3034 } );
  }
  function Popup() {
    myLoc.commit();
  }

  //Change the layout of the tooltip.
  function changeLayout(param) {
    myLoc.setTooltipLayout( param );
    myLoc.commit();
  }
  
  //Change the size of the tooltip.
  function changeSize(param) {
    htmlObj.setTooltipSize( param );
    htmlObj.commit();
  }
  function mapClicked( e ){
  	document.getElementById("lon").value = e.Coordinate.Longitude;
	document.getElementById("lat").value = e.Coordinate.Latitude;
    e.stop();    
  }
  
  function startRouting(){
    //Retrieve start and destination of the route from the input fields
    var startString = Map24.trim( $v('start') );
    var destinationString = Map24.trim( $v('destination') );
    
    //Check if the start and the destination form fields are empty.
    if( startString == "" ) { alert("Please enter start address!"); return; }
    if( destinationString == "" ) { alert("Please enter destination address!"); return; }
	
	document.getElementById("button_calculate_route").disabled = true;
    
    //Create a geocoder stub
    var geocoder = new Map24.GeocoderServiceStub();
    //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: startString, 
      MaxNoOfAlternatives: 1, 
      CallbackFunction: setRouteEndPoint, 
      CallbackParameters: {position: "start"}
    });
    
    //Geocode the destination 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: destinationString, 
      MaxNoOfAlternatives: 1, 
      CallbackFunction: setRouteEndPoint,
      CallbackParameters: {position: "destination"}
    });
  }
  
  //Callback function that is called when the geocoding result is available.
  //After both the start and the destination address is geocoded, this function calls the calculateRoute() function.
  //The geocoded address is stored at the first position in the locations array.
  function setRouteEndPoint(locations, params){
    //Access the geocoded address and add it to the routePoints array.
    routePoints[ params.position ] = locations[0];
    
    if( typeof routePoints["start"] != "undefined" && typeof routePoints["destination"] != "undefined")
      calculateRoute(); 
  }
  
  //Calculate the route.
  function calculateRoute() {
    router = new Map24.RoutingServiceStub();
    router.calculateRoute({
      Start: routePoints["start"],
      Destination: routePoints["destination"],
      CallbackFunction: displayRoute
    });
    routePoints = [];
  }
  
  //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 to hide a route.
	routeID = route.RouteID;
	
    //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>Route Direction:</b><br/>" ;
	div_content += "Total Time: " + totalTime + " h<br/>";     
    div_content += "Total Length: "+ 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++){
      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, '' ) + "<br>";
      }
    }
    document.getElementById('route_description').innerHTML = div_content;
	document.getElementById( 'button_remove_route' ).disabled = false;
  }
   //Remove route
  function removeRoute(routeID) {
  	router.removeRoute({RouteId: routeID});
	document.getElementById("lon").value = "";
	document.getElementById("lat").value = "";
	document.getElementById("start").value = "";
	document.getElementById('route_description').innerHTML = "";
	document.getElementById('button_calculate_route').disabled = false;
  }
//Helper function.
  function $v( id ) { 
    return   (document.getElementById( id ).value != "undefined") ?  
        document.getElementById( id ).value : ""; 
  }
  
  //This function sends a request to reverse geocode the given coordinate to the Web services.
  //It is necessary to define the name of a callback function to be able to access the result.
	function reverseGeocode( lon, lat ){
		var geocoder = new Map24.GeocoderServiceStub();
		  geocoder.reverseGeocode({ Longitude: lon, Latitude: lat, CallbackFunction: printResult });
	  }
  //Callback function that is called when the client has received a response from the Web services.
  //The parameter contains the reverse geocoded address. The function reads the address data 
  //and shows it in a list.
  function printResult( location ){
  	var result = "" + location.getStreet() + ", "+ location.getCity();
    document.getElementById("start").value = result;       
  }