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

//Declare global variables
var map = null;
var pageName = null;
var bubbles = null;
var centerCoordinate = new google.maps.LatLng(23.805450, 78.486328);
var Address = new Array();
var infoBubbleMessage = new Array();
var content = null;
var latlngStart = null;
var latlngEnd = null;
var MarkerPoints = new Array();
var infoBubble = new google.maps.InfoWindow({ content: content }), infoMarkers = {};
var TimeDistance = new Array();

function goMap24() {
    LoadMap();
}

//Load Navteq maps.
function LoadMap() {

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

    map = new google.maps.Map(document.getElementById("maparea"),
            {
                center: centerCoordinate,
                zoom: 2,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                mapTypeControlOptions: {
                    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
                },
                style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                panControl: true,
                zoomControl: true,
                zoomControlOptions: {

                    style: google.maps.ZoomControlStyle.LARGE
                },
                mapTypeControl: true,
                scaleControl: false,
                streetViewControl: false,
                overviewMapControl: false
            });

    //centerCoordinate = map.center;
    //}

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

function loadMapAlone() {
    map = new google.maps.Map(document.getElementById("maparea"),
            {
                center: centerCoordinate,
                zoom: 2,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                mapTypeControlOptions: {
                    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
                },
                style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                panControl: true,
                zoomControl: true,
                zoomControlOptions: {

                    style: google.maps.ZoomControlStyle.LARGE
                },
                mapTypeControl: true,
                scaleControl: false,
                streetViewControl: false,
                overviewMapControl: false
            });
}

//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();

    for (var i = 0; i < points.length; i++) {
        var latlng = points[i].split(',');
        if (i == 0) {
            latlngStart = new google.maps.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1]));
        }
        else if (i == points.length - 1) {
            latlngEnd = new google.maps.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1]));
        }
        else {
            var coords = new google.maps.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1]));
            waypoints.push({
                location: coords,
                stopover: true
            });
        }
    }
    callroute(latlngStart, waypoints, latlngEnd);
    return;
}

//-------------------------------------------------------------------------------------------------------------
//////////////////////////////////////Routing with GoogleV3 Maps//////////////////////////////////////////

function callroute(start, waypoints, End) {
    try {
        var directionsService = new google.maps.DirectionsService();
        var directionsDisplay = new google.maps.DirectionsRenderer();
        //var dd = new google.maps.DirectionsResult();

        var routeRequest = {
            origin: start,
            destination: End,
            //unitSystem: METRIC,
            waypoints: waypoints,
            optimizeWaypoints: false,
            travelMode: google.maps.TravelMode.DRIVING
        };

        directionsService.route(routeRequest, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                if (directionsDisplay)
                    loadMapAlone();
                directionsDisplay.setMap(map);
                directionsDisplay.setDirections(response);
                //showSteps(response);

                if (pageName == "AE")
                    DrivingDirection(response);
                else {
                    //DrivingDirection(response);
                    //document.getElementById("directions").InnerHTML = "Directions for V3";
                    directionsDisplay.setPanel(document.getElementById("directions"));
                }
                HidePopUp();
            }
            else {
                HidePopUp();
                alert("Routing request failed");
            }
        });
    }
    catch (er) {
        HidePopUp();
        alert("Routing request failed.")
    }
};


function showSteps(directionResult) {
    // For each step, place a marker, and add the text to the marker's
    // info window. Also attach the marker to an array so we
    // can keep track of it and remove it when calculating new
    // routes.
    var myRoute = directionResult.routes[0].legs[0];
    Array.clear(MarkerPoints);
    if (directionResult.eg.waypoints.length > 0) {
        for (var i = 0; i < directionResult.eg.waypoints.length; i++) {//myRoute.steps.length
            //var latlng = response.eg.origin;
            var marker = new google.maps.Marker({
                position: directionResult.eg.waypoints[i].location //MarkerPoints[i],   //myRoute.steps[i].start_point,     
            });
            marker.setMap(map);
            attachInstructionText(marker, Address[i]);  //myRoute.steps[i].instructions);            
        }
    }
}
//Info Bubble Events.
function attachInstructionText(marker, text) {
    google.maps.event.addListener(marker, 'mouseover', function() {
        if (infoBubble) infoBubble.close();
        infoBubble.setContent("<B>LandMark</B>" + "   " + text);
        infoBubble.open(map, marker);
    });

    google.maps.event.addListener(marker, 'mouseout', function() {
        infoBubble.close();
    });
}

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

        directionsDisplay.setPanel(document.getElementById("directions"));

        //        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() {
    loadMapAlone();
    //    try {
    //        map.objects.clear();
    //        if (mapRoute) map.objects.remove(mapRoute);
    //        map.setZoomLevel(1, '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 = null; //(parseFloat() / (60 * 60));
    var Distance = null;
    for (var i = 0; i < routes.routes[0].legs.length; i++) {
        Time += parseFloat(routes.routes[0].legs[i].duration.value);
        Distance += parseFloat(routes.routes[0].legs[i].distance.value);
    }
    var tim = Time / (60 * 60);
    var mins = '';
    mins = tim.toFixed(3).split('.');
    mins = Math.round((parseFloat("0." + mins[1]) * 60)) + " mins";
    var Hrs = '';
    Hrs = tim >= 1 ? Math.round(tim) + " Hr(s) " : '';
    Array.clear(TimeDistance);
    TimeDistance.push(Hrs + mins); //(parseFloat("0." + mins[1]) * 60).toFixed(2) + " mins"
    TimeDistance.push((Distance / 1000) + "Km(s)");
    //return (Hrs + mins)
}
function calculateDistance(routes) {

}

////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 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) {
    //Address = Addr.split('$');
    Address = LandMark.split('$');
    Address.splice(0, 1);
    Address.splice(Address.length - 1, 1);
}
