/********************************************************************
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;
var varRouteDestinationDuration = null;

// Legend Icons
var VAllLandmark = "All Landmark";
var VCurrLocation = "Curr. Location";
var VIgnitionOn = "Ignition On";
var VIgnitionOff = "Ignition Off";
var VMoving = "Others";
var VIdling = "Idling";
var VAlarms = "Alarms";
var VDetails = "Details";
var VOtherinfo = "Other Info";
var VDateTime = "Date & Time";
var VMessage = "Message";
var VAddress = "Address";
var VLegendAlign = "left";
var VLandmark = "Landmark";
var VSleep = "Sleep Mode";
var VOthers = "Moving";
var VLegendHeader = "Legends";
var VLegendToolTip = "click to show / hide legends";
var VDirection = "ltr";
var VShowRoute = 'Show Route';
var VAllGeozone = "Show Geozone";
//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,}/, ' ') == "") {

        var gridViewControl = document.getElementById('gvData');

        if (gridViewControl != null) {
            document.getElementById('maparea').style.width = gridViewControl.width; //document.body.clientWidth ;//document.documentElement.clientWidth-35//screen.width - 35;          
        }

        document.getElementById("map-legend").innerHTML = iconLegendText();
        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();
    }
}
//Load Navteq maps.
function LoadMapFullScreen() {

    //Load NLP nokia.maps NavTeq maps.
    if (document.getElementById('maparea').innerHTML == "" || document.getElementById('maparea').innerHTML.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ') == "") {

        var gridViewControl = document.getElementById('gvData');

        document.getElementById('maparea').style.width = document.body.clientWidth; //document.documentElement.clientWidth-35//screen.width - 35;
        document.getElementById('maparea').style.height = document.body.clientHeight + 'px';

        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();
    }
}
function iconLegendText() {
    var height = '';  


    var CurrentPosistion = (document.getElementById('gvHistory') != null) ? "<tr>" +
                       "  <td style='padding-left:2px'><img src='../images/down.png' alt='current location' style='height:15px;width:15px'/></td>" +
                       "  <td align=" + VLegendAlign + "><span class='txt' id='spLocation' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VCurrLocation + "</span></td>" +
                       "</tr>" : '';
    var legendText = "<div class='panel' align='center' id='lnkLegend'> <h2><b>" + VLegendHeader + "</b></h2><div class='panelcontent'><table id='tblLegend' align='right'" + height + " style='direction:" + VDirection + ";'>" +
                "<tr><td align='right' style='padding: 6px 0px 6px 6px;'>" +
                 "<table cellpadding='2' cellspacing='2' align='right' width='112px' " +
                 ((location.pathname.indexOf("FullscreenMap.aspx") != -1 && location.search.indexOf("?q=A") != -1) ?
                 "height='20px'>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/fuellow-1_.png' alt='Alarms' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spAlarms' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VAlarms + "</span></td>" +
                 "</tr>"
                 :
                 "height='114px'>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/purple-1_.png' alt='Ignition On' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOn' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIgnitionOn + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/orange-1_.png' alt='Ignition Off' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spIgnitionOff' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIgnitionOff + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/1_.png' alt='Ignition On' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spMoving' runat='server' style='font:11px arial; color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VMoving + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/pink-1_.png' alt='Idling' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt'  id='spIdling' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VIdling + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/3.png' alt='moving' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spMoving' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VOthers + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/mapit-9_.png' alt='sleep' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spSleep' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VSleep + "</span></td>" +
                 "</tr>" +
                 "<tr>" +
                 "  <td style='padding-left:2px'><img src='../images/fuellow-1_.png' alt='Alarms' style='height:15px;width:15px' /></td>" +
                 "  <td align='" + VLegendAlign + "'><span class='txt' id='spAlarms' runat='server' style='font:11px arial;color:#333333'>&nbsp;&nbsp;-&nbsp;&nbsp;" + VAlarms + "</span></td>" +
                 "</tr>" + CurrentPosistion + "</table></td></tr></table>") +
                 "</div></div>";
    return legendText;
}
var bubble = null;
var IsMSIE9 = null;
//Set the info Bubble Style
function infoBubbleStyle() {
    if (!CheckBrowserForBubble()) {
        infoBubble.node.firstElementChild.style.borderRadius = "10px 10px 10px 10px";
        infoBubble.node.firstElementChild.style.boxshadow = "rgba(0,0,0,0.4)10px 10px";
        //infoBubble.node.firstChild.style.cssText = "borderRadius:10px 10px 10px 10px";
        //infoBubble.node.firstElementChild.firstElementChild.nextElementSibling.style.right = "5px";
        //infoBubble.node.firstElementChild.firstElementChild.nextElementSibling.style.top = "4px";
        if (!IsMSIE9)
            infoBubble.node.firstElementChild.firstElementChild.nextElementSibling.style.cssText = "top: 4px; right: 5px;background-position: -31px -193px;width: 16px;height: 16px;"; //background-image:url(../images/icn-action-off.gif)
        else
            infoBubble.node.firstElementChild.firstElementChild.nextElementSibling.style.cssText = "top: 4px; right: 5px;background-position: -33px -198px;width: 16px;height: 16px"; //;background-image:url(../images/icn-action-off.gif)
    }
    else {
        infoBubble.node.firstChild.style.cssText = "border-radius: 10px; -moz-border-radius: 10px;-webkit-border-radius: 10px;"; //behavior: url(../border-radius-ie8.htc);"; //rgba(0,0,0,0.4)30px 30px"
        //infoBubble.node.firstChild.style.borderColor = "#959CC8";
        //border-style: solid;border-color: #959CC8;border-width:1px;box-shadow:10px 10px 20px #000;
        infoBubble.node.firstChild.firstChild.nextSibling.style.cssText = "top: 4px; right: 5px;background-position: -31px -193px;width: 16px;height: 16px;"; //;background-image:url(../images/icn-action-off.gif)
    }
}
function CheckBrowserForBubble() {
    var isIE = false;
    if (navigator.appName == "Microsoft Internet Explorer") {
        var version = null;
        version = navigator.appVersion.substring(0, 3);
        isIE = parseFloat(version) < 5.0 ? true : false;
        IsMSIE9 = navigator.appVersion.substring(25, 19) == "IE 9.0" ? true : false;
    }
    else {
        isIE = false;
    }
    return isIE;
}
//Split the lat long values and pass to the routing process.
function startRouting(LatLongs, Page, type) {//LatLongs    
    try
    {
    map.objects.remove(mapRoute);
    map.objects.clear();
    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);            
            //doDrawCircle_gz(coords, parseFloat(latlng[0]), parseFloat(latlng[1]), 500)
        }
    }
    CountLandmark = points.length - 1;
    callroute(waypoints);
    return;
}
    catch(e)
    { alert(e);}
//alert(type + "Hello");

   
}
function doDrawCircle_gz(centerPoint, lat, long, circleRadius) {
    try {

        var center = map.center;
        var circlePoints = Array();

        with (Math) {
            var d = circleRadius / 6378.8; // radians
            d = d / 1000;
            var lat1 = (PI / 180) * (lat); // radians
            var lng1 = (PI / 180) * (long); // radians

            for (var a = 0; a < 361; a++) {
                var tc = (PI / 180) * a;
                var y = asin(sin(lat1) * cos(d) + cos(lat1) * sin(d) * cos(tc));
                var dlng = atan2(sin(tc) * sin(d) * cos(lat1), cos(d) - sin(lat1) * sin(y));
                var x = ((lng1 - dlng + PI) % (2 * PI)) - PI; // MOD function

                var point = new nokia.maps.geo.Coordinate(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI)));
                circlePoints.push(point);
            }

            var cFilClr = "#2387";  //"#2387"; - Normal Geozone  #F145 - Restricted Geozone  #2E45 - UnRestricted Geozone
            var cLneClr = "#3355ff"; //#3355ff - Normal Geozone #FF0000 - Restricted Geozone #2E8B57 - UnRestricted Geozone         

            if (d < 1.5678565720686044) {


                circle = new nokia.maps.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                pen: { strokeColor: cLneClr, lineWidth: 2 },
                                brush: { color: cFilClr }
                            }
                        );
            }
            else {
                circle = new nokia.maps.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                pen: { strokeColor: cLneClr, lineWidth: 2 },
                                brush: { color: cFilClr }
                            }
                        );
            }

            polyShapeArray.push(circle);
            map.objects.add(circle);
        }
    }
    catch (Error) {
    }
}
function startRoutingGetData(LatLongs, Page, type) {//LatLongs    
    pageName = Page;
    RouteTypeCond = type;    
    var pointRoute = LatLongs.split('~!~');
   
    for (var j = 0; j < pointRoute.length; j++) {
        var points = pointRoute[j].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;
        callrouteGetData(waypoints);
        //document.getElementById("hdnResultValue").value = "";
    }
    //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='60px'><B>Stop</B></td><td>" + Address[0] + "</td></tr>" : evt.currentTarget.text == "B" ? "<tr><td width='60px'><B>Stop</B></td><td>" + Address[Address.length - 1] + "</td></tr>" : "<tr><td width='60px'><B>Stop</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);              
            }

            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(er);
        alert("Kindly check your Internet Connection.");
    } 
};
//Route Call
routingCallbackGetData = function (observedRouter, key, value) {
    try {
        if (value == "finished") {
            routes = observedRouter.getRoutes();
            routeTrafficMode = routes[0].mode.trafficMode;
            if (routes) {             
                DrivingDirectionGetData(routes);
                //__doPostBack('btnRouteUpdatetest', 'OnClick');
            }
            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('btnRouteUpdatetest', 'OnClick');
            
            //__doPostBack(' btnRouteUpdate', 'OnClick');
            //__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);
var routingManagerGetData = new nokia.maps.advrouting.Manager();
routingManagerGetData.addObserver("state", routingCallbackGetData);

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.")
    }
};
function callrouteGetData(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
        routingManagerGetData.calculateRoute(routeRequest);
    }
    catch (er) {
        HidePopUp();
        alert("Routing request failed.")
    }
};

//Calculate Driving Direction
function DrivingDirection(routes) {
   
   
}
function DrivingDirectionGetData(routes) {
   
    document.getElementById("lblDestinationDuration").value = "";
    document.getElementById("lblDestinationDistance").value = "";
    document.getElementById("hdnResultValue").value = "";
    if (pageName == "AE") {
        document.getElementById("hdnIndDistance").value = (routes[0].legs[CountLandmark - 1].length) / 1000;
        document.getElementById("lblDestinationDuration").value = calculateTime(routes);        
        document.getElementById("lblDestinationDistance").value = parseFloat(routes[0].summary.distance) / 1000 + " Kms";
        document.getElementById("hdnResultValue").value = parseFloat(routes[0].summary.distance) / 1000 + " Kms";
        alert(document.getElementById("hdnResultValue").value);
    }
    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 = '';
        document.getElementById("lblDestinationDuration").value = calculateTime(routes);
        document.getElementById("lblDestinationDistance").value = parseFloat(routes[0].summary.distance) / 1000 + " Kms";
    }
}

//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******************************************/
function Mapit(ltMapIT) {
  
    var lng = new Array();
    lng = ltMapIT.split("~#~");
    var point = new nokia.maps.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1]));

    MapIT_Marker(point, lng[4], lng[3], lng[5], lng[6], lng[2], lng[2],lng[7], lng[8], lng[9], lng[10], lng[11], lng[12]);
}

function MapIT_Marker(point, heading, speed, VehName, id, addr, dist, msgDetails,landmarkName, driverName, driverPhoto, driverPhno, PhnoCaption) {

    var temp1 = "'" + point + "'";
    var temp = temp1.substring(2, temp1.length - 2);
    temp = "'" + point.latitude + "," + point.longitude + "'";

    var icon = null;

    if (heading == -1) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-1_.png';
        }
        else if (id == '0') {
            icon = '../images/orange-1_.png';
        }
        else if (id == '1') {
            icon = '../images/purple-1_.png';
        }
        else if (id == '3' || id == '8' || id == '9') /*Idling start & end 06-Dec-2011 - Sakthi*/ {
            icon = '../images/pink-1_.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-1_.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-1_.png';
        }
        else if (id == '10') {
            icon = '../images/mapit-9_.png'; /*Sleep mode - 20-Dec-2011 Sakthi*/
        }
        else {
            icon = '../images/1_.png';
        }
    }
    else if (heading >= 0 && heading <= 30) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-3_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-3_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-3_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-3_20.png';
        }
        else {
            icon = '../images/3_20.png';
        }
    }
    else if (heading > 30 && heading <= 70) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-7_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-7_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-7_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-7_20.png';
        }
        else {
            icon = '../images/7_20.png';
        }
    }
    else if (heading > 70 && heading <= 100) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-1_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-1_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-1_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-1_20.png';
        }
        else {
            icon = '../images/1_20.png';
        }
    }
    else if (heading > 100 && heading <= 150) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-5_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-5_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-5_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-5_20.png';
        }
        else {
            icon = '../images/5_20.png';
        }
    }
    else if (heading > 150 && heading <= 200) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-4_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-4_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-4_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-4_20.png';
        }
        else {
            icon = '../images/4_20.png';
        }
    }
    else if (heading > 200 && heading <= 240) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-8_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-8_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-8_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-8_20.png';
        }
        else {
            icon = '../images/8_20.png';
        }
    }
    else if (heading > 240 && heading <= 280) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-2_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-2_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-2_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-2_20.png';
        }
        else {
            icon = '../images/2_20.png';
        }
    }
    else if (heading > 280 && heading <= 330) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-6_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-6_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-6_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-6_20.png';
        }
        else {
            icon = '../images/6_20.png';
        }
    }
    else if (heading > 330 && heading <= 360) {
        if (id == '6' || id == '7') {
            icon = '../images/fuellow-3_20.png';
        }
        else if (id == '3') {
            icon = '../images/pink-3_20.png';
        }
        else if (id == '4') {
            icon = '../images/fuelnormal-3_20.png';
        }
        else if (id == '5') {
            icon = '../images/fuelhigh-3_20.png';
        }
        else {
            icon = '../images/3_20.png';
        }
    }
    else {
        var hd = heading.split('-');
        if (hd != null) {
            if (hd[0] == 'A') {
                icon = '../images/fuellow-1_.png';   //+ hd[1] + '-alert.gif';
            }
        }
    }
    //    icon.shadowSize = new GSize(1, 1);
    //    icon.iconAnchor = new GPoint(12, 12);
    //    icon.infoWindowAnchor = new GPoint(12, 5);

    //var marker = new GMarker(point, { draggable: false, icon: icon });
    // TO set Z-index for Marker
    //    var marker = new google.maps.Marker(point, { draggable: false, icon: icon,
    //        zIndexProcess: function(m) {
    //            return 28800001;
    //        }
    //    });
   
    //<div style="text-align:' + tableAlign + ';">
    var bubbleMessage = '<div style="text-align:' + 'left' + ';"><table style="direction:' + 'left' + '" cellspacing=5 class=\'InfoBubble\'>';
    //<tr><td colspan="2"><u><b>' + ((mainHeading == null || mainHeading == '') ? 'Vehicle Statistics' : mainHeading) + '</b></u></td></tr>';
    //var validlocationImage = addr == 'N/A' ? '<img src="../Images/icn-address-notvalid.gif" />' : '<img src="../Images/icn-address-valid.gif" />';
    var monitorTabs = [];

   
        bubbleMessage += '<tr><td><b>' + 'Vehicle'  + '</b></td><td>' + VehName + '</td>';
       
    //bubbleMessage += '<td rowspan="3" align="left"><br><img src=" ' + ((driverPhoto == null || driverPhoto == '') ? '../images/default-user.png' : driverPhoto) + '" width="60px" height="60px" alt="Driver" /></td>';        
        
        
            bubbleMessage += '<tr><td><b>Address</b></td><td>' + addr + '</td></tr>';
        
            bubbleMessage += '<tr><td><b>Speed</b></td><td>' + speed + '</td></tr>';
        
        bubbleMessage += '</tr>'; 
  
    
      
    bubbleMessage += '</table><div>';
    //</div>  

    //Event to open bubble template
    var coordinate;
    if (bubble) infoBubble.closeAll();

    var OpenBubble = function (evt) {
        if (bubble) infoBubble.closeAll();
        //Set Info Bubble styles(Rounded like Cornors etc.) 
        infoBubbleStyle();
        coordinate = evt.currentTarget.coordinate;
        bubble = infoBubble.openBubble(bubbleMessage, coordinate);
    }
    //Event to close bubble template
    var CloseBubble = function (evt) {
        infoBubble.closeAll();
    }

    //Remove the info bubble on map click.
    map.addListener("click", function (evt) {
        if (bubble) infoBubble.closeAll();
    });

    var myListener = {
        "mouseover": [OpenBubble, true, null],
        //"mouseout": [CloseBubble, true, null],
        "click": [OpenBubble, true, null]
    };
    var marker = new nokia.maps.map.Marker(
            point, {
                visibility: true,
                icon: icon,
                eventListener: myListener,
                anchor: new nokia.maps.util.Point(9, 12)
                //offset the top left icon corner so that it's centered above the coordinate
                ///anchor: new nokia.maps.util.Point(35, 17)
            });

    map.objects.add(marker);

    //map.addListener("click", clicks, true);

    //Handle closing of the bubble(s)
    //    infoBubble.openBubbleHandles.addObserver(function(list, method, element, idx) {
    //        map.objects.remove(infoMarkers[element.id]);
    //    });

    // tabs.push(new GInfoWindowTab('Other Info', tabMessage));

    //    GEvent.addListener(marker, "mouseover", function() {
    //        timerInterval = setTimeout(function() { marker.openInfoWindowTabsHtml(monitorTabs); }, 1000)
    //    });
    //    GEvent.addListener(marker, "mouseout", function() { clearInterval(timerInterval) });
    //    if (isSpeedVisible) {
    //        GEvent.addListener(marker, "mouseover", function() { timerInterval = setTimeout(function() { marker.openInfoWindowTabsHtml(tabs); }, 1000) });
    //        GEvent.addListener(marker, "mouseout", function() { clearInterval(timerInterval) });
    //    }
    //    else {
    //        GEvent.addListener(marker, "mouseover", function() { timerInterval = setTimeout(function() { marker.openInfoWindowHtml(infoBubbleMessage); }, 1000) });
    //        GEvent.addListener(marker, "mouseout", function() { clearInterval(timerInterval) });
    //    }
    //GEvent.addListener(marker, "mouseout", function() {marker.closeInfoWindow(marker);});

    //return marker;
}