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

//Declare global variables
//nokia.maps.util.ApplicationContext.set("authenticationToken", "lEHyh2Yk1vwUf57LkaIgGA");
//nokia.maps.util.ApplicationContext.set("appId", "lJFheTIST9H7WAQeLleh");

//nokia.maps.util.ApplicationContext.set("authenticationToken", "rUx1XDKfl8JPUTnWuM2tcg");
//nokia.maps.util.ApplicationContext.set("appId", "dPiRUN4pTa6p9mp63F-8");
nokia.Settings.set("authenticationToken", "PzCfyYAsV98qvfU8gusqRg");
nokia.Settings.set("appId", "UdwAigBKPRhu01vbIGkI");
(document.location.protocol == "https:") && nokia.Settings.set("secureConnection", "force");


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

//nokia.maps.Config.setDefaultsNS("map.tileprovider", {
//    "normal.baseUrl": "maps.nlp.nokia.com/maptiler/2.1/maptile/newest/normal.day",
//    "hybrid.baseUrl": "maps.nlp.nokia.com/maptiler/2.1/maptile/newest/hybrid.day",
//    "satellite.baseUrl": "maps.nlp.nokia.com/maptiler/2.1/maptile/newest/satellite.day",
//    "terrain.baseUrl": "maps.nlp.nokia.com/maptiler/2.1/maptile/newest/terrain.day",
//    "publictransport.baseUrl": "maps.nlp.nokia.com/maptiler/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?"
//});

//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/maptile/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 map = null;
var pageName = null;
var bubbles = null;
//var centerCoordinate = null;
var centerCoordinate = new nokia.maps.geo.Coordinate(23.89, 54.32);
var Address = new Array();
var infoBubbleMessage = new Array();
var infoBubble = new nokia.maps.map.component.InfoBubbles(), infoMarkers = {};
var MarkerArray = new Array();

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(),
            new nokia.maps.map.component.Traffic(),
            new nokia.maps.map.component.ZoomRectangle(),
            new nokia.maps.map.component.PublicTransport()]
          
        });
        centerCoordinate = map.center;
    }

    //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) {//LatLongs
    pageName = Page;
    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) {
            waypoints.push({ position: coords });
            prevLatLng.push(coords);
        }

    }
    callroute(waypoints);
    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,
//Route Call
    routingCallback = function(observedRouter, key, value) {
        try {
            if (value == "finished") {
                routes = observedRouter.getRoutes();
                if (routes) {
                    DrivingDirection(routes);
                }
                else {
                    TrinetraCustomAlerts("Routing Request Failed.")
                    HidePopUp();
                    return;
                }
                if (mapRoute) {
                    map.objects.remove(mapRoute);
                    for (var i = 0; i < MarkerArray.length; i++) {
                        map.objects.remove(MarkerArray[i]);
                    }
                }
                //create the default map representation of a route
                mapRoute = new nokia.maps.routing.component.RouteResultSet(routes[0]).container;
                map.objects.add(mapRoute);
                Array.clear(MarkerArray);

                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);
                    MarkerArray.push(marker);
                    //infoBubbleMessage
                }

                //Zoom to the bounding box of the route
                map.zoomTo(mapRoute.getBoundingBox(), false, "default");
                HidePopUp();
            } else if (value == "failed") {
                HidePopUp();
                TrinetraCustomAlerts("The routing request failed.");
            }
        }
        catch (er) {
            HidePopUp();
            TrinetraCustomAlerts("Kindly check your Internet Connection.");
        }
    };


var routingManager = new nokia.maps.advrouting.Manager();

//var routingManager = new nokia.maps.routing.Manager();

routingManager.addObserver("state", routingCallback);

function callroute(waypoints) {
    try {
        var modes = [
    {
        type: "shortest",
        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();
        TrinetraCustomAlerts("Routing request failed.")
    }
};

//Calculate Driving Direction
function DrivingDirection(routes) {
    try {
        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";
        }
        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 = FrameAddresss(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 = '';
        }
    }
    catch (er) {
    }
}

//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) {
        TrinetraCustomAlerts("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 = (parseFloat(routes[0].summary.baseTime) % 60) + " mins";
    var Hrs = '';
    Hrs = Time >= 1 ? Math.round(Time) + " Hr(s) " : '';
    return (Hrs + mins)
}

//Assign the Address and Landmark Name
function AssignAddress(Addr, info) {
    Address = Addr.split('$');
    infoBubbleMessage = info.split('$');
}


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

function FrameAddresss(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;
}

var Alert_Route = 'No route found for this vehicle.';
function setAlertForRoute(AlertRoute) {
    Alert_Route = (AlertRoute == null || AlertRoute == '') ? Alert_Route : AlertRoute;
}

//LandMark
function AddressForRoute(LandMark) {
    if (LandMark == '') {
        document.getElementById("chkRoute").checked = false;
        HidePopUp();
        TrinetraCustomAlerts(Alert_Route)
        return;
    }
    var LandRoute = LandMark.split('~#~');
    Address = LandRoute[1].split('$');
    startRouting(LandRoute[0], "AE");
    HidePopUp();
}


function clearRoute() {
    try {
        if (mapRoute) map.objects.remove(mapRoute);
        if (MarkerArray) {
            for (var i = 0; i < MarkerArray.length; i++) {
                map.objects.remove(MarkerArray[i]);
            }
        }
    }
    catch (er) {
    }
    HidePopUp();
}