/********************************************************************
The functions listed below are related to Routing Feature.
Functions and terms used are specific to NavTeq Maps. Thsi is been 
used in Route management Module. 
********************************************************************/

//Declare global variables
//nokia.maps.util.ApplicationContext.set("authenticationToken", "PzCfyYAsV98qvfU8gusqRg");
//nokia.maps.util.ApplicationContext.set("appId", "UdwAigBKPRhu01vbIGkI");
nokia.Settings.set("authenticationToken", "PzCfyYAsV98qvfU8gusqRg");
nokia.Settings.set("appId", "UdwAigBKPRhu01vbIGkI");
nokia.Settings.set("secureConnection", "force");

//nokia.maps.Config.setDefaultsNS("map.tileprovider", {
//    "normal.baseUrl": "maps.nlp.nokia.com/maptile/2.1/maptile/newest/normal.day",
//    "hybrid.baseUrl": "maps.nlp.nokia.com/maptile/2.1/maptile/newest/hybrid.day",
//    "satellite.baseUrl": "maps.nlp.nokia.com/maptile/2.1/maptile/newest/satellite.day",
//    "terrain.baseUrl": "maps.nlp.nokia.com/maptile/2.1/maptile/newest/terrain.day",
//    "publictransport.baseUrl": "maps.nlp.nokia.com/maptile/2.1/maptile/newest/normal.day.transit",
//    "grey.baseUrl": "maps.nlp.nokia.com/maptiler/2.1/maptile/newest/normal.day.grey",
//    "traffic.baseUrl": "maps.nlp.nokia.com/traffic/6.0/tiles",
//    "trafficincidents.baseUrl": "traffic.nlp.nokia.com/traffic/6.0/incidents.json?"
//});

var maptype = "normal.day";
var LoadTime = null;
var map = null;
var pageName = null;
var bubbles = null;
//var centerCoordinate = null;
var centerCoordinate = new nokia.maps.geo.Coordinate(20.00, 78.00);
var Address = new Array();
var infoBubbleMessage = new Array();
var infoBubble = new nokia.maps.map.component.InfoBubbles(), infoMarkers = {};
var CountLandmark = null;
var RouteTypeCond = null;
//infoBubble.Bubble.prototype.defaultWidth = 300;
//infoBubble.Bubble.prototype.defaultXAlignment = 'auto';
//infoBubble.Bubble.prototype.defaultYAlignment = 'auto';

//navteq Maps License Key registration.
//nokia.maps.util.ApplicationContext.set("authenticationToken", "4b25c0fb0d9f746bbe44a74f549b49208f1833336bb01f04");
//nokia.maps.util.ApplicationContext.set("appId", "4b25c0fb0d9f746bbe44a74f549b49208f1833336bb01f04");


//Map type change event.
var MapTypeObserver = function(obj, key, newValue, oldValue) {
    var TypeofMap = null;
    switch (newValue.uri) {
        case 'normal': TypeofMap = 'N'; maptype = 'normal.day'; break;
        case 'hybrid': TypeofMap = 'H'; maptype = 'hybrid.day'; break;
        case 'terrain': TypeofMap = 'T'; maptype = 'terrain.day'; break;
    }

    if (document.getElementById("hdnlang") != null) {
        if (document.getElementById("hdnlang").value == "LanguageArNew") {
            changeTileProvider(maptype);
        }
    }
};

function goMap24() {
    LoadMap();
}

//Load Navteq maps.
function LoadMap() {

    //Load NLP nokia.maps NavTeq maps.
    if (document.getElementById('maparea').innerHTML == "" || document.getElementById('maparea').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {
        map = new nokia.maps.map.Display(document.getElementById("maparea"), {
            center: centerCoordinate,
            zoomLevel: 4,
            components: [infoBubble, new nokia.maps.map.component.ZoomBar(),
            //new nokia.maps.map.component.TypeSelector(),
             new nokia.maps.map.component.zoom.DoubleClick(),
            new nokia.maps.map.component.Behavior(),
            new nokia.maps.map.component.ViewControl()]
        });
        centerCoordinate = map.center;

        if (document.getElementById("hdnlang") != null) {
            if (document.getElementById("hdnlang").value == "LanguageArNew") {
                changeTileProvider(maptype);
                LoadTime = null;
                map.addObserver("baseMapType", MapTypeObserver);
            }
        }
    }

    //Disable print description button
    if (document.getElementById('btnGetDirections') != null) {
        document.getElementById('btnGetDirections').click();
    }
}

//Split the lat long values and pass to the routing process.
function startRouting(LatLongs, Page, type) {//LatLongs
    pageName = Page;
    RouteTypeCond = type;
    var points = LatLongs.split('$');
    var waypoints = new Array();
    var prevLatLng = new Array();
    for (var i = 0; i < points.length; i++) {
        var latlng = points[i].split(',');
        var coords = new nokia.maps.geo.Coordinate(parseFloat(latlng[0]), parseFloat(latlng[1]));
        if (prevLatLng[0] != coords) {
            //prevLatLng.push(coords);
            waypoints.push({ position: coords });
            prevLatLng.push(coords);

        }
    }
    CountLandmark = points.length - 1;
    callroute(waypoints);
//alert(type + "Hello");

    return;
}

//-------------------------------------------------------------------------------------------------------------
//////////////////////////////////////Routing with LBSP nokia.maps NavTeq//////////////////////////////////////////

//Event to open info bubble.
var OpenBubble = function(evt) {
    try {
        if (bubbles) infoBubble.closeAll();
        if (Address.length > 0 && infoBubbleMessage.length > 0) {
            var coordinate = evt.currentTarget.coordinate;
            var msg = "<table cellpadding='5' class='InfoBubble'>";
            msg += evt.currentTarget.text == "A" ? "<tr><td width='113px'><B>Landmark Name</B></td><td>" + Address[0] + "</td></tr>" + "<tr><td width='113px'><B>Address</B></td><td>" + infoBubbleMessage[0] + "</br></td></tr>" : evt.currentTarget.text == "B" ? "<tr><td width='113px'><B>Landmark Name</B></td><td>" + Address[infoBubbleMessage.length - 1] + "</td></tr>" + "<tr><td width='113px'><B>Address</B></td>" + "<td>" + infoBubbleMessage[infoBubbleMessage.length - 1] + "</td></tr>" : "<tr><td width='113px'><B>Landmark Name</B></td><td>" + Address[parseInt(evt.currentTarget.text)] + "</td></tr>" + "<tr><td width='113px'><B>Address</B></td><td>" + infoBubbleMessage[parseInt(evt.currentTarget.text)] + "</td></tr>";
            msg += "</table>";
            bubbles = infoBubble.openBubble(msg, coordinate);
        }
        else if (Address.length > 0) {
            //infoBubble.Bubble.prototype.defaultWidth = 200;
            var coordinate = evt.currentTarget.coordinate;
            var msg = "<table cellpadding='5' class='InfoBubble'>";
            msg += evt.currentTarget.text == "A" ? "<tr><td width='80px'><B>Landmark</B></td><td>" + Address[0] + "</td></tr>" : evt.currentTarget.text == "B" ? "<tr><td width='80px'><B>Landmark</B></td><td>" + Address[Address.length - 1] + "</td></tr>" : "<tr><td width='80px'><B>Landmark</B></td><td>" + Address[parseInt(evt.currentTarget.text)] + "</td></tr>";
            msg += "</table>";
            bubbles = infoBubble.openBubble(msg, coordinate);
        }
    }
    catch (er) { }
}

//Event to close info bubble.
var CloseBubble = function(evt) {
    if (bubbles)
        infoBubble.closeAll();
}

//Event Listener which are added to the bubble.
var myListener = {
    "mouseover": [OpenBubble, true, null],
    "mouseout": [CloseBubble, true, null]
};

//Variable Declaration.
var objectContainer = new nokia.maps.map.Container();
var routingRequest, routes, mapRoute, routeId, routeColor, routeTrafficMode;
//Route Call
routingCallback = function(observedRouter, key, value) {
    try {
        if (value == "finished") {
            routes = observedRouter.getRoutes();
            routeTrafficMode = routes[0].mode.trafficMode;
            if (routes) {
                DrivingDirection(routes);
            }
            else {
                alert("Routing Request Failed.")
                HidePopUp();
                return;
            }
            if (mapRoute) {
                map.objects.remove(mapRoute);
                map.objects.clear();
            }

            routeColor = routeTrafficMode == "enabled" ? "#a000a080" : "#0000f080";
            //create the default map representation of a route
            mapRoute = new nokia.maps.routing.component.RouteResultSet(routes[0]).container;
            //            mapRoute.set("visibility",
            //			(routeTrafficMode == "enabled"));
            map.objects.add(mapRoute);

            for (var i in routes[0].waypoints) {
                // var coord = routes[0].waypoints[i].mappedPosition;
                var marker = new nokia.maps.map.StandardMarker(routes[0].waypoints[i].mappedPosition,
                                {
                                    text: i == 0 ? "A" : i == routes[0].waypoints.length - 1 ? "B" : i,
                                    name: i,
                                    eventListener: myListener,
                                    brush: {
                                        //fillcolor of brush
                                        color: i == 0 ? "#008000" : i == routes[0].waypoints.length - 1 ? "#FF0000" : "#0055AA"
                                    }
                                });
                map.objects.add(marker);
                //infoBubbleMessage
            }

            //Zoom to the bounding box of the route
            map.zoomTo(mapRoute.getBoundingBox(), false, "default");
            // callservermethod();
            HidePopUp();

            if (RouteTypeCond == "1") {
             //   alert("In");
                __doPostBack('btnRoute', 'OnClick');
                //document.getElementById('btnRoute').click();
            }
           
            //__doPostBack('btnRoute', 'OnClick');
            //document.getElementById('btnRoute').click();             
            //  HidePopUp();
            //  alert('completed');


        }
        else if (value == "failed") {
            HidePopUp();
            alert("The routing request failed.");
        }
    }
    catch (er) {
        HidePopUp();
        alert("Kindly check your Internet Connection.");
    } 
};

var routingManager = new nokia.maps.advrouting.Manager();
routingManager.addObserver("state", routingCallback);

function callroute(waypoints) {
    try {
        var modes = [
    {
        type: "fastest",
        transportModes: ["car"],
        trafficMode: "default"
}];

        var routeRequest = new nokia.maps.advrouting.CalculateRouteRequest();
        routeRequest.set("modes", modes.slice(0));
        routeRequest.set("representationOptions", {
            language: "en-US",
            representationMode: "overview",
            routeAttributes: ["wp", "sc", "sm", "sh", "bb", "lg", "no"],
            legAttributes: ["wp", "mn", "li", "le", "tt"],
            maneuverAttributes: ["po", "sh", "tt", "le", "ti", "li", "pt", "pl", "eq", "la", "rn", "nr"],
            linkAttributes: ["sh", "le", "sl", "ds", "ic", "tr", "er"],
            corridorDepth: 2,
            instructionFormat: "html"
        });
        routeRequest.set("departure", "2010-04-01T17:00:00Z");
        routeRequest.set("alternatives", 2);
        routeRequest.set("metaInfo", { requestId: "sampleRequest" });
        routeRequest.set("waypoints", waypoints);

        //add map objects if they are not added
        // if (!objectContainer.isAdded(map))
        map.objects.add(objectContainer);
        //make a calculateRoute request
        routingManager.calculateRoute(routeRequest);
    }
    catch (er) {
        HidePopUp();
        alert("Routing request failed.")
    }
};

//Calculate Driving Direction
function DrivingDirection(routes) {
   
    if (pageName == "AE") {         
        document.getElementById("txtDuration").value = calculateTime(routes); //(((parseFloat(routes[0].summary.baseTime)) / (60)).toFixed(3)) + " mins";
        document.getElementById("txtDistance").value = parseFloat(routes[0].summary.distance) / 1000 + " Kms";
        document.getElementById("hdnIndDistance").value = (routes[0].legs[CountLandmark - 1].length) / 1000;

        var IndTime = (parseFloat((routes[0].legs[CountLandmark - 1].travelTime)) / 3600) % 24;
        var Indmins = '';
        Indmins = Math.ceil(parseInt(routes[0].legs[CountLandmark - 1].travelTime) / 60) % 60 + " min(s)";
        var IndHrs = '';
        IndHrs = IndTime >= 1 ? Math.round(IndTime) + " Hr(s) " : '';
        document.getElementById("hdnDuration").value = IndHrs + Indmins;
        document.getElementById("hdnDurationSec").value = parseInt(routes[0].legs[CountLandmark - 1].travelTime);
        document.getElementById("hdnTrafficDuration").value = calculateTrafficTime(routes);
        document.getElementById("txtTrafficDuration").value = calculateTrafficTime(routes);
        //hdnIndDistanceroutes[0].legs[0].travelTime
        //alert((routes[0].legs[CountLandmark - 1].length) / 1000);
        //routes[0].legs[0].length
    }
    else {
        var temp = '';
        if (Address != null && Address.length > 0) {
            //            for (var i = 0; i < Address.length; i++) {
            //                temp += i == 0 ? "<B>Start :" + Address[i] + " (A)</B></br>" : i == Address.length - 1 ? "<B>Destination :" + Address[i] + " (B)</B></br></br>" : "Via " + i + ":" + Address[i] + "</br>";
            //            }
            temp = FrameAddress(Address);
        }
        temp += "<table cellpadding='5' class='InfoBubble'><tr><td><B>Time Taken to Travel</B> : </td><td>" + calculateTime(routes) + "</td></tr>";  //(((parseFloat(routes[0].summary.baseTime)) / (60)).toFixed(3)) + " mins</br></br>";
        //Access the total lenght of the route in kilometers
        temp += "<tr><td><B>Total Distance</B> : </td><td>" + parseFloat(routes[0].summary.distance) / 1000 + " Kms</td></tr></table></br></br>";
        document.getElementById("directions").innerHTML = '';
        temp += "<table cellpadding='5' class='InfoBubble'>";
        for (var i = 0; i < routes[0].getManeuvers().length; i++) {
            var j = parseInt(i) + 1;
            temp += "<tr><td>" + j + ") </td><td>" + routes[0].getManeuvers()[i].instruction + "</td></tr>";
        }
        temp += "</table>";
        document.getElementById("directions").innerHTML = temp;
        temp = '';
    }
}

//Clear Overlays in the maps
function ClearOverlay() {
    try {
        map.objects.clear();
        if (mapRoute) map.objects.remove(mapRoute);
        map.setZoomLevel(4, 'default');
        if (centerCoordinate)
            map.setCenter(centerCoordinate, 'default');
    }
    catch (er) {
        alert("Please check your Internet Connection. Map cannot be loaded.");
    }
}

//Function for Rounding a decimal number 
function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

//Time Calculation for Routing.
function calculateTime(routes) {
    //var Time = (parseFloat(routes[0].summary.baseTime) / (60 * 60));
    //var mins = '';
    //mins = Math.ceil(parseFloat(routes[0].summary.baseTime) / 60) + " min(s)";
    //var Hrs = '';
    //Hrs = Time >= 1 ? Math.round(Time) + " Hr(s) " : '';
    //return (Hrs + mins)
    var seconds = parseFloat(routes[0].summary.baseTime);
    var hours = parseInt(seconds / 3600) % 24;
    var minutes = parseInt(seconds / 60) % 60;
    var result = (hours < 10 ? "0" + hours : hours) + " Hr(s) " + (minutes < 10 ? "0" + minutes : minutes) + " min(s)";
    return result;
}
function calculateTrafficTime(routes) {
    //var traTime = (parseFloat(routes[0].summary.trafficTime) / (60 * 60));
    //var tramins = '';
    //tramins = Math.ceil(parseFloat(routes[0].summary.trafficTime) / 60) + " min(s)";
    //var traHrs = '';
    //traHrs = traTime >= 1 ? Math.round(traTime) + " Hr(s) " : '';
    //return (traHrs + tramins)
    var seconds = parseFloat(routes[0].summary.trafficTime);
    var hours = parseInt(seconds / 3600) % 24;
    var minutes = parseInt(seconds / 60) % 60;
    //  var seconds = seconds % 60;
    var result = (hours < 10 ? "0" + hours : hours) + " Hr(s) " + (minutes < 10 ? "0" + minutes : minutes) + " min(s)";
    //+ "-" + (seconds < 10 ? "0" + seconds : seconds);
    return result;
}
//Assign the Address and Landmark Name
function AssignAddress(Addr, info) {
    Array.clear(Address);
    Array.clear(infoBubbleMessage);
    Address = Addr.split('$');
    infoBubbleMessage = info.split('$');
}


function ClearArray() {
    //    Array.clear(Address);
    //    Array.clear(infoBubbleMessage);
}

function FrameAddress(Address) {
    var Temp = '';
    Temp += "<table cellpadding='5' class='InfoBubble'>";
    for (var i = 0; i < Address.length; i++) {
        Temp += i == 0 ? "<tr><td width='50px'><B>Start</B></td><td><B>" + Address[i] + " (A)</B></td></tr>" : i == Address.length - 1 ? "<tr><td width='50px'><B>End</B></td><td><B>" + Address[i] + " (B)</B></td></tr>" : "<tr><td width='50px'>Via " + i + "</td><td>" + Address[i] + "</td></tr>";
    }
    Temp += "</table></br></br>";
    return Temp;
}

//LandMark
function AddressForRoute(LandMark) {
    Array.clear(Address);
    //Address = Addr.split('$');
    Address = LandMark.split('$');
}

/***********************************Maps in Arabic******************************************/
function changeTileProvider(MapType) {
    if (LoadTime == null) {
        var server_rr = 0;
        var token = "rUx1XDKfl8JPUTnWuM2tcg";
        var appId = "dPiRUN4pTa6p9mp63F-8";

        var baseMapProvider = new nokia.maps.map.provider.ImgTileProvider({
            label: "normal.day",
            descr: "Nokia Base Map tile provider",
            width: 256,
            height: 256,
            min: 0,
            max: 23,
            getUrl: function(level, row, col) {
                server_rr++;
                if (server_rr > 4)
                    server_rr = 1;

                return ["https://", server_rr, ".maps.nlp.nokia.com/maptile/", "2.1", "/", "maptile", "/", "newest", "/", MapType, "/", level, "/", col, "/", row, "/", "256", "/", "png", "?lg=", "ARA",
					"&token=",
					token,
					"&app_id=",
					appId
					].join("");
            }
        });
        // very evil to overwrite the base provider for minimap provider
        // nokia.maps.map.js.nokiaTileProviders.base[0] = baseMapProvider;
        LoadTime = 1;
        map.set("baseMapType", baseMapProvider);
    }
    else {
        LoadTime = null;
    }
}
/***********************************End of Maps in Arabic******************************************/