﻿var IdPrefix = 'ctl00_cphBody_MyMapControl_'; //name of usercontrol, needed because asp.net adds it to the id of each control in the usercontrol

var map = null;
var startGeocoded = null;
var destinationGeocoded = null;

function goMap24(){
    try {    
        map = Map24.Webservices.getMap24Application({
        AppKey: "FJXd530db5cae8d96286986231f112c9X13",
        MapArea: document.getElementById( "maparea" ),
        MapWidth: document.getElementById( IdPrefix+"width" ).value,
        MapHeight: document.getElementById( IdPrefix+"height" ).value
        });        
        addLocation();        
    }
    catch (err) {
        //alert(document.getElementById( IdPrefix+"notavailable_message" ).value);
        document.getElementById( IdPrefix+"lblNotAvailable" ).innerHTML = document.getElementById( IdPrefix+"notavailable_message" ).value; 
        document.getElementById( IdPrefix+"divMapType" ).style.display = 'none';
        document.getElementById( IdPrefix+"fldStartAddress" ).style.display = 'none';
        document.getElementById( IdPrefix+"fldRoute" ).style.display = 'none';
    }  
}

function addLocation(){
    var mrcContainer = new Map24.Webservices.Request.MapletRemoteControl( map );
    
    var mydescription = document.getElementById( IdPrefix+"description" ).value;
    var mylogourl = document.getElementById( IdPrefix+"logourl" ).value;
    var mysymbolid = document.getElementById( IdPrefix+"symbolid" ).value;
    
    var popupsize = document.getElementById( IdPrefix+"popupsize" ).value;
    var popupwidth, popupheight, popupdivwidth, popupdivheight, popupbackground;
    
    switch (popupsize) {
    case "S":
        popupwidth = 208;
        popupheight = 183;
        popupdivwidth = 140;
        popupdivheight = 116;
        popupbackground = "tooltip_bubble_shade2_S.gif"; //208*183
        break;
    case "M":
        popupwidth = 305;
        popupheight = 216;
        popupdivwidth = 236;
        popupdivheight = 151;
        popupbackground = "tooltip_bubble_shade2_M.gif"; //305*216
        break;
    case "L":
        popupwidth = 366;
        popupheight = 237;
        popupdivwidth = 296;
        popupdivheight = 170;
        popupbackground = "tooltip_bubble_shade2_L.gif"; //366*237
        break;
    default:
        popupwidth = 366;
        popupheight = 237;
        popupdivwidth = 296;
        popupdivheight = 170;
        popupbackground = "tooltip_bubble_shade2_L.gif"; //366*237
        break;
    statements-(N+1)
    }
    
    map.Webservices.sendRequest(        
        new Map24.Webservices.Request.MapSearchFree(map, {
            SearchText: document.getElementById( IdPrefix+"dest_address" ).value,
            MaxNoOfAlternatives: 50
        })
    );
    
    map.onMapSearchFree = function( event ){
        var mrcContainer = new Map24.Webservices.Request.MapletRemoteControl( map );
        var tempGeocoded = event.Alternatives[0];
        
        mrcContainer.push(
            new Map24.Webservices.MRC.DeclareMap24Location({
                MapObjectID: "myLocation",
                Description: "none",
                Coordinate: new Map24.Coordinate( tempGeocoded.Coordinate.Longitude, tempGeocoded.Coordinate.Latitude ),
                LogoURL: mylogourl, //"http://img.map24.com/map24/3DSignet/signet3d22x20.gif"
                SymbolID: mysymbolid,                
                Events: new Array(
                    new Map24.Webservices.MapObjectEvent({
                        ID: "OnMouseOver",
                        Commands: new Map24.Webservices.CommandsArray(
                            new Map24.Webservices.MRC.DeclareMap24HTMLObject({
                                MapObjectID: "myTooltip",
                                Coordinate: new Map24.Coordinate( tempGeocoded.Coordinate.Longitude, tempGeocoded.Coordinate.Latitude ),
                                HTML: "<div style=\"width:" + popupwidth + "px;height:" + popupheight + "px;overflow:hidden;font-family:arial;"+
                                    "font-size:11;padding:0px;margin:0px;border:0px;"+
                                    "background:url(http://devnet.map24.com/files/tooltip/" + popupbackground + ")\">"+
                                    "<div style=\"width:" + popupdivwidth + "px;height:" + popupdivheight + "px;"+
                                    "overflow:scroll;padding-left:10px;padding-top:10px;\">"+
                                    mydescription+
                                    "</div>"+
                                    "</div>",
                                Orientation: new Map24.Webservices.MapObjectOrientation({
                                    'Vertical':'TOP',
                                    'Horizontal':'RIGHT',
                                    'HOffset':0,
                                    'VOffset':0
                                })
                            }),
                            new Map24.Webservices.MRC.ControlMapObject({
                                Control: 'ENABLE',
                                MapObjectIDs: 'myTooltip'
                            })
                        )
                    }),
                    new Map24.Webservices.MapObjectEvent({
                        ID: "OnMouseOut",
                        Commands: new Map24.Webservices.CommandsArray(
                            new Map24.Webservices.MRC.ControlMapObject({
                                Control: 'DISABLE',
                                MapObjectIDs: 'myTooltip'
                            })
                        )
                    })
                )
            })
        );
        
        mrcContainer.push(
            new Map24.Webservices.MRC.ControlMapObject({
                Control: "ENABLE",
                MapObjectIDs: "myLocation"
            })
        );
        
        mrcContainer.push(
            new Map24.Webservices.MRC.SetMapView({
                Coordinates: new Map24.Coordinate( tempGeocoded.Coordinate.Longitude, tempGeocoded.Coordinate.Latitude ),
                ClippingWidth: new Map24.Webservices.ClippingWidth(
                    { MinimumWidth: 5000 }            
                )
            })
        );
        
        map.Webservices.sendRequest( mrcContainer );
    }
}

function addStartLocation(lon, lat){
    var mrcContainer = new Map24.Webservices.Request.MapletRemoteControl( map );
    mrcContainer.push(
        new Map24.Webservices.MRC.DeclareMap24Location({
            MapObjectID: "myStart",
            Coordinate: new Map24.Coordinate( lon, lat ),
            SymbolID: 20953
        })
    );
    mrcContainer.push(
        new Map24.Webservices.MRC.ControlMapObject({
            Control: "ENABLE",
            MapObjectIDs: "myStart"
        })
    );
    map.Webservices.sendRequest( mrcContainer );
}

//function showProgressbar(isVisible) {
//    var siteurl = document.getElementById( IdPrefix+"siteurl" ).value;
//    
//    var imagecontainer = document.getElementById( "LoadingImage" )
//    if(isVisible) {        
//        var image = imagecontainer.appendChild( document.createElement("img") );
//        image.setAttribute("id", ("ImageSrc"));
//        image.setAttribute("src", (siteurl+"images/progressbar.gif"));
//        image.setAttribute("alt", "Loading...");                
//    }
//    else {
//        imagecontainer.removeChild( document.getElementById("ImageSrc") );
//    }
//}

function showProgressbar(isVisible) {
    var siteurl = document.getElementById( IdPrefix+"siteurl" ).value;
    
    var loadingimage_path = document.getElementById( IdPrefix+"loadingimage_path" ).value;
    var loadingimage_width = document.getElementById( IdPrefix+"loadingimage_width" ).value;
    var loadingimage_height = document.getElementById( IdPrefix+"loadingimage_height" ).value;
    
    var imagecontainer = document.getElementById( "LoadingImage" )

    if(isVisible) {
        imagecontainer.setAttribute("src", (siteurl+"images/progressbar.gif"));
        imagecontainer.setAttribute("alt", "Loading...");
        imagecontainer.setAttribute("width", loadingimage_width);
        imagecontainer.setAttribute("height", loadingimage_height);
    }
    else {
        imagecontainer.setAttribute("src", (siteurl+"images/progressbar.gif"));
        imagecontainer.setAttribute("alt", "");
        imagecontainer.setAttribute("width", 0);
        imagecontainer.setAttribute("height", 0);
    }
}

/*The route is calculated between the passed start and destination*/
function calculateRouteAddr(){
    showProgressbar(true); 

    var start_address = document.getElementById( IdPrefix+"start_street" ).value + " " + document.getElementById( IdPrefix+"start_postalcode" ).value + " " + document.getElementById( IdPrefix+"start_city" ).value + " " + document.getElementById( IdPrefix+"start_country" ).value;
    var destination_address = document.getElementById( IdPrefix+"dest_address" ).value;

    if( Map24.isNull( start_address ) ) return;
    if( Map24.isNull( destination_address ) ) return;

    geocodePoints( start_address, destination_address );    
    return;
}

/*Geocode the start and destination address*/
function geocodePoints( start, destination ){
    //1. Geocode the start address
    geocode( start, onGeocodeStart )
    //2. When start address has been geocoded, then geocode destination address      
    function onGeocodeStart( geoRes ){
        startGeocoded = geoRes.firstResult;
        geocode( destination, onGeocodeDest )
    }
    //3. When both start and dest address have been geocoded, then start route calculation
    function onGeocodeDest( geoRes ){
        destinationGeocoded = geoRes.firstResult;        
        calculateRouteCoord( startGeocoded, destinationGeocoded );
    }    
}

//Calculate a route between two addresses
function calculateRouteCoord( startGeocoded, destinationGeocoded ){
    if( Map24.isNull( startGeocoded ) ) return;
    if( Map24.isNull( destinationGeocoded ) ) return;

    /*Construct the Route Request*/      
    var routeRequest = new Map24.Webservices.Request.CalculateRoute();

    routeRequest.Start = new Map24.Webservices.Point();
    routeRequest.Start.Coordinate = new Map24.Coordinate( startGeocoded.Coordinate.Longitude,
                                                    startGeocoded.Coordinate.Latitude );
    routeRequest.Destination = new Map24.Webservices.Point();
    routeRequest.Destination.Coordinate = new Map24.Coordinate( destinationGeocoded.Coordinate.Longitude,
                                                          destinationGeocoded.Coordinate.Latitude );
                                                          
    addStartLocation( startGeocoded.Coordinate.Longitude, startGeocoded.Coordinate.Latitude ); //own code

    routeRequest.DescriptionLanguage = document.getElementById( IdPrefix+"description_language" ).value;
    routeRequest.CalculationMode = document.getElementById( IdPrefix+"calculation_mode" ).value;
    routeRequest.VehicleType = document.getElementById( IdPrefix+"vehicle_type" ).value;

    routeRequest.SpeedClassification = new Map24.Webservices.SpeedClassification ({
        CityRoad: document.getElementById( IdPrefix+'city_road' ).value,
        CountryRoad: document.getElementById( IdPrefix+'country_road' ).value,
        Ferry: document.getElementById( IdPrefix+'ferry' ).value,
        Motorway: document.getElementById( IdPrefix+'motorway' ).value
    });

    //Send the route request to the Map24 Web services
    map.Webservices.sendRequest( routeRequest );

    //This listener is called when the route calculation has finished
    map.onCalculateRoute = function( routeResult ){
        var mrcContainer = new Map24.Webservices.Request.MapletRemoteControl();

        /* Push the route onto the map (visualize the route). The route is now a map object that has the ID = currentRoute*/
        mrcContainer.push( 
            new Map24.Webservices.MRC.DeclareMap24RouteObject({
                MapObjectID: "currentRoute",
                Map24RouteID: routeResult.Route.RouteID,
                Color: new Map24.Color( 255, 100, 100, 0 )
            }) 
        );
        
        //Create table with textual description of the route
        var intMinutes;
        var intHours;
        var intTotalLength = 0;
        var intTotalTime = 0;  
        var strRoute = "";     
        var siteurl = document.getElementById(IdPrefix+"siteurl").value;
        
        strRoute += "<div id=\"total_distance\">";
        strRoute += "<strong>" + document.getElementById(IdPrefix+"translation_totallength").value + "</strong>: " + (routeResult.Route.TotalLength/1000).toFixed(2) + " km";
        
        //Output the total time of the route
        //strRoute += "<div id=\"total_time\">";
        intMinutes = Math.floor(routeResult.Route.TotalTime/60);
        intHours = Math.floor(intMinutes/60);
        intMinutes = intMinutes % 60;

        strRoute += "<br/><strong>" + document.getElementById( IdPrefix+"translation_totaltime" ).value + ": </strong>" + intHours + "h" + ((intMinutes>9)?"":"0")+intMinutes;
        strRoute += "</div>";
        
        strRoute += "<ul>";
        for(var i = 0; i < routeResult.Route.Segments.length; i++){
            var segment = routeResult.Route.Segments[i];
            
            //add segment id
            strRoute += "<li class=\"route_row\">";
            strRoute += "<div class=\"route_cell_id\">" + (i+1) + "</div>";
                       
            //add segment direction
            strRoute += "<div class=\"route_cell_direction\">";
                if( (i+1) == 1 ) {
                    strRoute += "<img src=\"" + siteurl+"images/arrows/start.gif\" alt=\"Start\" />";
                }
                else {
                    if( (i+1) == routeResult.Route.Segments.length ) {
                        strRoute += "<img src=\"" + siteurl+"images/arrows/stop.gif\" alt=\"Stop\" />";
                    }
                    else {
                        if( segment.ExitNumber != null ) { //junction or roundabout?
                            strExit = ">>> " + segment.ExitNumber;
                            if(segment.FreewayExit.length > 0) { //junction
                                strRoute += "<img src=\"" + siteurl+"images/arrows/FreewayExit.gif\" alt=\"FreewayExit\" />";
                            } 
                            else { //roundabout
                                strRoute += "<img src=\"" + siteurl+"images/arrows/Roundabout.gif\" alt=\"Roundabout\" />";
                            }
                            strRoute += "<br/>" + strExit;
                        }
                        else { //normal direction
                            strRoute += "<img src=\"" + siteurl+"images/arrows/" + segment.Direction.Hint + ".gif\" alt=\"" + segment.Direction.Hint + "\" />";                            
                        }
                    }
                }
            strRoute += "</div>"
                 
            //add segment description
            strRoute += "<div class=\"route_cell_description\">";
            var tempdescription = "";
            
            for(var j = 0; j < segment.Descriptions.length; j++){
                segment.Descriptions[j].Text = segment.Descriptions[j].Text.replace(/(\[|\[\/)[0-9A-Z_]+\]/g, '' );
                tempdescription = tempdescription + segment.Descriptions[j].Text;
            }    
             
            strRoute += tempdescription;       
            strRoute += "</div>";
                        
            //add segment total time
            strRoute += "<div class=\"route_cell_currenttime\">";
            
            intMinutes = Math.floor(intTotalTime/60);
            intHours = Math.floor(intMinutes/60);
            intMinutes = intMinutes % 60;
            
            strRoute += intHours + "h" + ((intMinutes>9)?"":"0")+intMinutes;
            intTotalTime = intTotalTime + segment.Time //first show time, then add time that has passed in segment  
            strRoute += "</div>";
                        
            //add segment total length
            strRoute += "<div class=\"route_cell_currentlength\">";
            strRoute += (Math.round(intTotalLength*100)/100).toFixed(2) + "km";
            intTotalLength = intTotalLength + segment.SegmentLength/1000;
            strRoute += "</div>";
            
            //clear floats
            strRoute += "<div class=\"clearBoth\">";
            strRoute += "</li>";
        }
        
        strRoute = strRoute + "</ul>";
        document.getElementById("route_table").innerHTML = strRoute;

        /*Center the map view on the visualization of the route. View Percentage determines the
        forced amount of percent that is left between the border of the map view and the route
        object. You can also specify the MinimumWidth that specifies the width of the map view 
        in real-world meters.*/
        mrcContainer.push( genSetMapViewMapObj( { ViewPercentage: 100, MapObjectIDs: "currentRoute" } ) );

        //Enable the visibility of the route 
        mrcContainer.push( genControlMapObject( { Control: "ENABLE", MapObjectIDs: "currentRoute" } ) );

        map.Webservices.sendRequest( mrcContainer );  
        
        showProgressbar(false); 
    }
}

//Geocoding. The onGeoFunc function is called, as soon as the geocoding is finished.
function geocode( address, onGeoFunc, _params ){
    map.Webservices.sendRequest(
        new Map24.Webservices.Request.MapSearchFree(map, {
            SearchText: address,
            MaxNoOfAlternatives: 100
        })
    );

    map.onMapSearchFree = function( geocodingResult ){
        var geoRes = new Object();
        geoRes.Alternatives = geocodingResult.Alternatives;
        geoRes.firstResult = geoRes.Alternatives[0];

        if( typeof _params == "undefined" ) {
            onGeoFunc( geoRes );				
        }
        else{
            onGeoFunc( geoRes, _params );
        }
    }
}    

//Factory functions
function genSetMapViewMapObj( _params ){

if( Map24.isNull( _params.MinimumWidth ) )  
_params.MinimumWidth = 0;

if( Map24.isNull( _params.ViewPercentage ) )  
_params.ViewPercentage = 0;

_params.ClippingWidth = new Map24.Webservices.ClippingWidth( _params);

var SetMapViewMapObj = new Map24.Webservices.MRC.SetMapView( _params );

return SetMapViewMapObj;
}

function genControlMapObject( _params ){
    var ControlObject = new Map24.Webservices.MRC.ControlMapObject({
        Control: _params.Control,
        MapObjectIDs: _params.MapObjectIDs
    });
    return ControlObject;
}     

//static/interactive switching
function setMGI(){
    map.setMaptype( "MGI" );
}

function setJava(){
    map.setMaptype( "JAVA" );
} 

//special function to load map at pageload (instead of "body onload")
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } 
    else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

addLoadEvent(function() {
    goMap24();
});
