﻿    
    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: -1024.0711111111095,
            UpperLeftLatitude: 3720.62389830508,
            LowerRightLongitude: 2234.765925925929,
            LowerRightLatitude: 2281.8045762711826
        } );
        Map24.MapApplication.init( { NodeName: maparea } ); 
        if (startVal != '' && destVal != '')
        {
	        setTimeout('startRouting("' + startVal + '", "' + destVal + '");',2000);
        }
    }


    function startRouting(start, destination){
        //Retrieve start and destination of the route from the input fields
        //Check if the start and the destination form fields are empty
        if( start == "" ) { alert(noStartErrorMessage); return; }
        if( destination == "" ) { alert(noEndErrorMessage); return; }
          
        //Disable the button for starting a route calculation.
        onRoutingStart();

        //Create a geocoder stub
        var geocoder = new Map24.GeocoderServiceStub();


        //Geocode the start point of the route
        var startMatch = start.match(/([^,]+),([A-Z][A-Z])/);
        if (startMatch != null)
        {
            geocoder.geocode({ 
                SearchText: start, 
                City: startMatch[1], 
                Country: startMatch[2], 
                CallbackFunction: setRouteEndPoint, 
                CallbackParameters: {position: "start"}
            });
        }
        else
        {
            geocoder.geocode({ 
                SearchText: start, 
                CallbackFunction: setRouteEndPoint, 
                CallbackParameters: {position: "start"}
            });
        }
        
        //Geocode the destination point of the route
        var destinationMatch = destination.match(/([^,]+),([A-Z][A-Z])/);
        if (destinationMatch != null)
        {
            geocoder.geocode({ 
                SearchText: destination, 
                City: destinationMatch[1], 
                Country: destinationMatch[2], 
                CallbackFunction: setRouteEndPoint, 
                CallbackParameters: {position: "destination"}
            });
        }
        else
        {
            geocoder.geocode({ 
                SearchText: destination, 
                CallbackFunction: setRouteEndPoint, 
                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 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];

        //After both the start and the destination addresses are geocoded, this function calls the calculateRoute() function.
        if( typeof routePoints["start"] != "undefined" && typeof routePoints["destination"] != "undefined")
            calculateRoute(); 
    }

    //Calculate the route.
    function calculateRoute() {
        if (routeID != null)
        {
            removeRoute(routeID);
        }
        router = new Map24.RoutingServiceStub();
        router.setDefaultDescriptionLanguage(routingLanguage);
        router.calculateRoute({
            Start: routePoints["start"],
            Destination: routePoints["destination"],
            CallbackFunction: displayRoute,
            ShowRoute: false
        });
        currentStart = routePoints["start"]._City + "," + routePoints["start"]._Country;
        currentDest = routePoints["destination"]._City + "," + routePoints["destination"]._Country;
        onCalculateRoute();
        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]
        });

        //Enable helicopter flight on the route. The route flight control
        //will be shown on the map. To start the route flight click on the
        //start button of the route flight control.
        Map24.MapApplication.displayHelicopterFlight({ RouteId: 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 = routingTotalTimeStr + " " + totalTime + " " + "h";     
        div_content += "<br>";
        div_content += routingTotalLengthStr + " " + totalLength + " " + "km";
        div_content += "<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") {

                //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)];
            }
            var segmentDescription ="";
            //For each route segment add the route description and the button for centering on the 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:
                segmentDescription = segmentTemplate.replace("[ROUTE_DESCRIPTION]", route.Segments[i].Descriptions[j].Text.replace(/(\[|\[\/)[0-9A-Z_]+\]/g, ''));
                segmentDescription = segmentDescription.replace("[SEGMENT_IMAGE]", route.Segments[i].Direction.Hint + ".gif");
                segmentDescription = segmentDescription.replace("[CLICK_EVENT]", "centerOnSegment(" + centerLon + ", " + centerLat + ");");
                div_content += segmentDescription;
            }
        }
  
        onDisplayRoute(div_content);
    }


    //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 });
        
    }

    //Remove route
    function removeRoute(rtID) {
        routeID = null;
        router.removeRoute({RouteId: rtID});
        currentDest = null;
        currentStart = null;
        //Delete route description  
        onRemoveRoute();
    }

    //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=800,height=800,toolbar=0,scrollbars=0,status=0');
        windowPrint.document.write(printContent.innerHTML);
        windowPrint.document.close();
        windowPrint.focus();
        windowPrint.print();
        windowPrint.close();
    }

