//Declare global variables  
  var geocoder = null;
  var router = null;
  var routePoints = [];
  var routeID = null;
  var destinationLocationID = null;
  
  var baseUrl = 'http://'+window.location.host+'/thiqaApp/en/script/routingservicestub.js';
  
  var mapObjectIDs = new Array();
  var locConn = null;


  var App = {
		$chain:[],
		// call App.onComplete when the last nessesary Javascript has been loaded
		onComplete: function(){
			for(var i=0;i<App.$chain.length;i++)
			{
				// execute each script
				App.$chain[i]();
			}
			// overload onReady function
			App.onReady = function(fn){
				try {
					fn();
				}
				catch(e){
					console.log(e);
				}
			};
			// delete $chain (to save memory, its useless until now)
			delete(App.$chain);
		},
		// use App.onReady(fn) to execute a function after all Javascript files have been loaded
		onReady: function(fn){
			App.$chain.push(fn);
		}
	};
  
  function goMap24() {

  //  Map24.loadApi( ["core_api", "wrapper_api"] , map24ApiLoaded );

  //loads the Map24 api - fix to load the routing service stub js
    Map24.loadApi( ["core_api", "wrapper_api", baseUrl], map24ApiLoaded );
	Map24.onLoad();
    
	//setting layout size for tool tip
    Map24.MapObject._LayoutBalloon.Size[0] = [170, 150 , 165, 145];
  
	/* gets all the provider coordinates from the server side attribute 
	   which populates the data into an array finally calls the function 
	   plotLocations() */

	setGeocodes();
  }


  //setting the coordinates to the Map24 object for intial view of a map.
  function setCoordinatesForStartUpView(leftLongitude,leftLatitude, rightLongitude, rightLatitude) {
    // this will set the view of the map position to specific part (UAE)
	if( leftLongitude != null ) {
         Map24.MapApplication.setStartMapView({ 
	      UpperLeftLongitude:leftLongitude,
	      UpperLeftLatitude:leftLatitude,
	      LowerRightLongitude:rightLongitude,
	      LowerRightLatitude:rightLatitude
	    });
	} else {
	      Map24.MapApplication.setStartMapView( { 
	      UpperLeftLongitude:  3056.711,
	      UpperLeftLatitude:   1587.986,
	      LowerRightLongitude: 3433.245,
	      LowerRightLatitude:  1341.509
	    } );
    }
  }

  function map24ApiLoaded(){
    // sets the coordinates for setting the intial view of a map
	setValuesForStartUpView();
	// While loading the map this will call the static map first once the applet is loaded,
	//it will automatically changed to interactive one
	 Map24.MapApplication.init( { 
    	NodeName: "maparea",
    	MapType:  "Auto"
    } );
 
  // add java detection event
   Map24.MapApplication.Map.addListener( "Map24.Event.JavaDetectionTimeout", onJavaDetectionTimeout ); 

    locConn = Map24.MapApplication.Map.Local.openConnection();
    locConn.onError = function(){ alert("An Error Occured!") };
    locConn.onTimeout = function(){ alert("A Timeout Occured!") };
    
	// execute all App.onReady callbacks
	App.onComplete();
  }

  // on mouse out hiding the tooltip and showing the object in map
  function hide(ht) {
    ht["cb1"].hide();
    ht["cb1"].show();
  }

  //Change the layout of the tooltip.
  function changeLayout(param) {
    id.setTooltipLayout( param );
    id.commit();
  }
  
  //Change the size of the tooltip.
  function changeSize(param) {
    id.setTooltipSize( param );
    id.commit();
  }
 
 // plotting the location in map 
 function plotLocations(objectArray ) {

   var array = null;;
   	for(i=0;i<objectArray.length;i++) {
		array = objectArray[i];
		id= array[0];
		longitude = array[1];
		lattitude = array[2];
		htmlContent = array[3];
		var htmlArray = htmlContent.split("&lt;&gt;");
		htmlContent = "<b>"+htmlArray[0]+"</b>";
		var newLinkCheck = htmlArray[1].split("&lt;br/&gt;");
		
		for(j=0;j<newLinkCheck.length;j++) {
		  htmlContent = htmlContent + "<br/>" + newLinkCheck[j];
		}
		logo = array[4];
   	  
   	  id = new Map24.Location({
	      Longitude: longitude,
	      Latitude: lattitude,
	      LogoURL: logo,
	      TooltipContent: htmlContent,
	      TooltipLayout: Map24.MapObject.LAYOUT_BALLOON,
	      TooltipSize: Map24.MapObject.SIZE_S
	    });
    
	    // to call the event on mouse out (hide function)
	    id.addListener( "OnMouseOut", hide, {cb1:id}  );
	    
	    //Call commit() on the location. The location is shown on the map.
	   	id.commit();
   	}
   }
   
  
// Directions

function startRouting(){
    //Retrieve start and destination of the route from the input fields
  document.getElementById('areaerror').innerHTML = "";
  document.getElementById('destinationerror').innerHTML = "";
  document.getElementById('regionerror').innerHTML = "";
  var street =Map24.trim( $v('start') ); 
  var region = Map24.trim( $v('region') );
  var start = street+','+region;
  
  var destination =  Map24.trim( $v('destination') );
    //Check if the start and the destination form fields are empty
    if( destination == "" ) {
	    var error = "<span style='color:#FF0000'>" +"حدد عنوان مكان الوصول -- انقر على '\u0627\u0644\u062D\u0635\u0648\u0644 \u0639\u0644\u0649 \u0627\u0644\u0645\u0646\u0637\u0642\u0629'"+"</span>";
     	document.getElementById('destinationerror').innerHTML = error;
	    return;
	 } else {
     	document.getElementById('destinationerror').innerHTML = "";
    }
    
    
    if(street == "" || region == "") {
	    if(street == ""  ) {
		     var error =  "<span style='color:#FF0000'>" +"الرجاء إدخال جميع الحقول في عنوان البداية" +"</span>";
		     document.getElementById('areaerror').innerHTML = error;
		     return;
	     } else {
	      	document.getElementById('areaerror').innerHTML = "";
	     }
	    if(region == "") {
		   	var error = "<span style='color:#FF0000'>" + "الرجاء إدخال جميع الحقول في عنوان البداية"+"</span>";
		    document.getElementById('regionerror').innerHTML = error;
		    return; 
	    } else {
	    	document.getElementById('regionerror').innerHTML = "";
	    }
    }
    
    hideRoute(routeID);
    if(document.getElementById('routeDescription') != null) {
    	document.getElementById('routeDescription').innerHTML ="";
		document.getElementById('routeDescription').style.display= 'none';
	}
	// disabling the get direction button in search screen
    if(document.getElementById("enableDirection") != null) {
   		document.getElementById("enableDirection").style.display= 'none';
		document.getElementById("disableDirection").style.display= 'block';
	}
	  
    //Create a geocoder stub
    var geocoder = new Map24.GeocoderServiceStub();
	routePoints["destination"]=destinationLocationID;

   //Geocode the start point of the route
    geocoder.geocode({ 
      SearchText: start, 
      //Define the name of the callback function that is called when the result is available on the client.
      CallbackFunction: setRouteEndPoint, 
      //Set a parameter that is passed to the callback function. The parameter defines that this is the start point.
      CallbackParameters: {position: "start"}
    });
    
  }
  
  //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 setRouteEndPoint(locations, params){

    //Access the geocoded address and add it to the routePoints array.
    //The geocoded address is stored at the first position in the locations array.
	
	routePoints[ params.position ] = locations[0]; 
	calculateRoute(); 
     
   }
  
 // calculate the routing process
 function calculateRoute() {
	router = new Map24.RoutingServiceStub();
    router.calculateRoute({
      Start: routePoints["start"],
      DestinationLocationID: routePoints["destination"],
      CallbackFunction: displayRoute,
      ShowRoute: false
    });
    routePoints = [];
  }

  //Callback function used to access the calculated route of type Map24.WebServices.Route.
  //This function is called after the client has received the result from the routing service.
  function displayRoute( route ){
    //Remember the routeId. It is used e.g. to hide the route.
    routeID = route.RouteID;
    router.showRoute( {
      RouteId: routeID,
      Color: ['#00F', 150]
  });
    
    //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 = "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>";
      }
    }
   
    // enabling the get direction button in search screen 
    document.getElementById("enableDirection").style.display= 'block';
	document.getElementById("disableDirection").style.display= 'none';
	document.getElementById('routeDescription').innerHTML = div_content;
	document.getElementById('routeDescription').style.display='block';
	document.getElementById('viewGetDirection').focus();
  }
  
  //Show route
  function showRoute(routeID) {
    router.showRoute({RouteId: routeID});
  }
  
  //hide route
  function hideRoute(routeID) {
	if(routeID != null) {
    	router.hideRoute({RouteId: routeID});
    }
  }
  
   
  //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 != "null") && document.getElementById( id ).value != "undefined") ? document.getElementById( id ).value : ""; 
  }
   
   //CR changes for Provider search and map
  var mapInstantiated = false;
  function showHideMap(xpoint, ypoint, locationId, maps){
      document.getElementById("resultandmap").style.display = "block";
      if (! mapInstantiated) {
            try {
                  goMap24();
            } catch (e) {
            }
            mapInstantiated = true;
      }
        document.getElementById("srch").style.display = "none";
        if(maps == "map") {
              document.getElementById("maparea").className="map_area1";
              document.getElementById("more_details").style.display = "none";
        }
        else {
              document.getElementById("maparea").className="map_area";
              document.getElementById("more_details").style.display = "block";
        }

  	 App.onReady(function(){
			// execute centerOnCoordinate after Map24 API is loaded!
			centerOnCoordinate(xpoint, ypoint, locationId);
		});
  }
 //Changes done for Provider Search and map CR end
 //function to highlight the location
  function centerOnCoordinate(xpoint, ypoint, locationId) {
    destinationLocationID = locationId;
    Map24.MapApplication.center( {Longitude:xpoint, Latitude:ypoint, MinimumWidth: 1000} );
  }

// Java Detection Timeout
// shows the Tooptip for a Location
function onJavaDetectionTimeout(){
   var html=['<div text="#000000" link="#80D9ED" alink="#80D9ED" vlink="#80D9ED" hlink="#80D9ED" style="width:280px;height:160px;background-color: #ffffff; border: 1px solid #CCCCCC; padding:0px 0px 0px 0px; overflow: none; nose-background-color: #ffffff; nose-color: #CCCCCC; nose-width: 1px; nose-offset: 1px; font-family:verdana; font-size:12px;">',
			'<div style="position:relative;width:270px; padding:5px 5px 5px 5px;  font-family:verdana;">',
						'<img style="position:absolute;right:3px;top:5px;z-index:9;" src="http://img.customer3.map24.com/swr/close.gif" border="0" onclick="control:disable" />',
						'<div link="#80D9ED" alink="#80D9ED" vlink="#80D9ED" hlink="#80D9ED"  style="width:245px; font-weight:bold;font-family:verdana;">',
						'Important hint</div>',
			'</div>',
			'<div style="overflow:auto;width:270px;height:100px;margin-top:3px;border-top:1px solid #CCCCCC; padding:5px 5px 5px 5px;  font-family:verdana;">',
				'<div style="margin-right:5px;">',
							'<img src="http://img.customer3.map24.com/swr/java.gif" style="float:left; padding-right:5px;" />',
							'The interactive Map requires Java VM Version 1.4.x or better.<br/><br/><a href="http://www.java.com/en/download/" target="_blank">Click here to download Java VM for free.</a></div>',
				'</div>',
			'</div>'].join("");

            var cmds = [];
            cmds.push(
				new Map24.WebServices.XMLCommandWrapper({
					DeclareMap24HTMLObject: new Map24.WebServices.DeclareMap24HTMLObject({
						MapObjectID: 'javahint',
						HTML: html,
						CanvasReferencePoint: new Map24.WebServices.CanvasReferencePoint({
							HPercentage: 50,
							VPercentage: 50
						}),
						Orientation: new Map24.WebServices.MapObjectOrientation({
							Horizontal: "CENTER",
							Vertical: "CENTER"
						})
					})
				})
            );
            cmds.push(
				new Map24.WebServices.XMLCommandWrapper({
					ControlMapObject: new Map24.WebServices.ControlMapObject({
						MapObjectIDs: ['javahint'],
						Control: "ENABLE"
					})
				})
            );
            // execute the commands
            locConn.mapletRemoteControl(
				new Map24.WebServices.Message.mapletRemoteControlRequest({
					MapletRemoteControlRequest: new Map24.WebServices.MapletRemoteControlRequest({
						Map24MRC: new Map24.WebServices.Map24MRC({
						  Commands: cmds
						})
					})
				})
            );          
}

