/***********************************************************************************
The functions listed below are related to Vehicle tracking Feature in Google V3 Maps.
***********************************************************************************/

var timerInterval;
var map = null;
var polyline = null;
var contextmenu;
var history_latlng = null;
var centerCoordinate = null;//new google.maps.LatLng(23.805450, 78.486328); //new GLatLng(23.805450, 78.486328);
var isViewLatLong = 0;
var mapItMarkers;
var content;
var MapView = new Array();
var MapViewFullScreen = Array();
var infowindow = null; //new google.maps.InfoWindow({ content: content });
var isEditable = false;
var isDraggable = false;
var MarkerImage = null;
var orgCenter = null;
var orgZoomLevel = null;
var resultContainer;
var markerCluster = null;
var isShowLandmarkPlotter = 0;
var isShowGeozonePlotter = false;
var circle;
var Rec_bounds;
var polyPoints = new Array();
var polyShape;


var PlayBack = {};
var playBackArray = new Array();
var busMarker;
var PlayBackZoom = new Array();
var playAlarm = new Array();
var PlaybackMarker = new Array();


// 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";

//Playback Legends
var VStart = "Start";
var VDestination = "Destination";
var VVehicle = "Vehicle";
var VAlarm = "Alarms";
var VInfopanel = "Show Info Panel";
var VMarkers = "Show Markers";
var Caption_Play = "Play";
var Caption_Pause = "Pause";
var Caption_Reset = "Reset";
var Caption_Stop = "Stop";
var Caption_Fast = "Fast";
var Caption_Medium = "Medium";
var Caption_Slow = "Slow";
var marker = null;
function loadMapControl() {
    try {
        debugger;
        if (document.body.clientHeight < 640)
            document.getElementById('map-dsply').style.height = '400px';
        if (document.body.clientHeight < 800)
            document.getElementById('map-dsply').style.height = (document.body.clientHeight / 4) + 'px';
        else
            document.getElementById('map-dsply').style.height = (document.body.clientHeight / 4) + 'px';
        if (circle) {
            circle.setMap(null);
        }
        if (marker != null) {
            marker.setMap(null);
        }
        //if (LandMarkImage != null || LandMarkImage != '')
        //{
        //    LandMarkImage = null;
        //}
        //if (map) {
            map = new google.maps.Map(document.getElementById("map-dsply"),
                {//centerCoordinate,
                    center: (new google.maps.LatLng(11.004556, 76.961632)),
                    zoom: parseInt(4),
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    panControl: true,
                    zoomControl: true,
                    zoomControlOptions: {
                        style: google.maps.ZoomControlStyle.SMALL,
                        position: google.maps.ControlPosition.RIGHT_CENTER
                    },
                    streetViewControl: false,
                    fullscreenControl: false,
                    //streetViewControlOptions: {
                    //    position: google.maps.ControlPosition.LEFT_BOTTOM
                    //},
                    mapTypeControl: true,
                    scaleControl: false,

                    //                streetViewControl: true,
                    overviewMapControl: true
                });
        //}
        //== Click on Map to get the co-ordinates
        google.maps.event.addListener(map, 'click', function (evt) {
            showControls(1);
            if (evt != null) {
                //alert(Math.round(evt.latLng.lat() * 1000000));
                document.getElementById('ctl00_BodyContentPH_txtlat').value = Math.round(evt.latLng.lat() * 1000000) / 1000000;
                document.getElementById('ctl00_BodyContentPH_txtlong').value = Math.round(evt.latLng.lng() * 1000000) / 1000000;

                //if (document.getElementById('hdnLatLong') != null) {
                //    document.getElementById('hdnLatLong').value = evt.latLng.lat() + ',' + evt.latLng.lng();
                //}
                //chkValue = 0;

                //document.getElementById('hdnIsLocateMe').value = 'N';
            }
        });

        infowindow = new google.maps.InfoWindow({ content: content });
        infowindow.setHeight = 500;
        orgCenter = null;
        orgZoomLevel = null;
        return true;
    }
    catch (Error) {
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }
}
/* Functions related to Landmark Page */
var geo;
var reasons = [];
var getAddress = null;
var geocoder; var address;

function showAddress(IsNew, image) {
    try {
        if (marker) marker.setMap(null);

        getAddress = null;
        //chkValue = 1;
        //document.getElementById('hdnIsLocateMe').value = 'Y';

        if (document.getElementById('ctl00_BodyContentPH_ddlType').value == 'addr') {
            search = FrameAddress();
            geo = new google.maps.Geocoder();
            // ====== Perform the Geocoding ======
            geo.geocode({ 'address': search }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results.length > 1) {
                        //document.getElementById("message").innerHTML = "Did you mean:";
                        //// Loop through the results
                        //for (var i = 0; i < results.length; i++) {
                        //    var p = results[i].geometry.location;
                        //    document.getElementById("message").innerHTML += "<br>" + (i + 1) + ": <a href='#' onclick='place(" + p.lat() + "," + p.lng() + "); return false;'>" + results[i].formatted_address + "</a>";
                        //}
                        //document.getElementById("pnlInfoWindow").style.display = "block";
                        map.setCenter(new google.maps.LatLng(-13.880745, 79.101562));
                        map.setZoom(6);
                    }
                        // ===== If there was a single marker =====
                    else if (results.length == 1) {
                        document.getElementById("message").innerHTML = "";
                        var p = results[0].geometry.location;

                        //if (document.getElementById('hdnLatLong') != null) {
                        //    document.getElementById('hdnLatLong').value = p.lat() + ',' + p.lng();
                        //}

                        Findplace(p.lat(), p.lng(), '', document.getElementById('ctl00_BodyContentPH_txtRadius').value, 0);
                        LandMarkImage = '';
                    }
                    else {
                        alert('Unable to find the address. Please verify the location');
                    }
                } else {
                    alert('Unable to find the address. Please verify the location');
                }
            });
        }
        else {

            //To Get the Address for the LatLng Values given by user            
            var latlong = new google.maps.LatLng(document.getElementById('ctl00_BodyContentPH_txtlat').value, document.getElementById('txtlong').value);

            if (document.getElementById('hdnLatLong') != null) {
                document.getElementById('hdnLatLong').value = latlong.toUrlValue();
            }

            centerPoint = new google.maps.LatLng(document.getElementById('ctl00_BodyContentPH_txtlat').value, document.getElementById('txtlong').value);
            map.setCenter(centerPoint, 16);

            //var geoFinder = new GClientGeocoder();
            var geoFinder = new google.maps.Geocoder();
            isDraggable = (IsNew == "0" || IsNew == '') ? false : true;
            geoFinder.geocode({ 'latLng': latlong }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0]) {
                        place = results[0];
                        var icon = new google.maps.MarkerImage(LandMarkImage,
                                   new google.maps.Size(22, 22),
                                   new google.maps.Point(0, 0),
                                   new google.maps.Point(0, 22));

                        marker = new google.maps.Marker({
                            position: centerPoint,
                            map: map,
                            icon: icon,
                            draggable: isDraggable
                        });
                        //isDraggable = true;
                        google.maps.event.addListener(marker, "dragstart", function () {
                            if (infowindow) infowindow.close();
                        });

                        google.maps.event.addListener(marker, 'dragend', function () {
                            document.getElementById('ctl00_BodyContentPH_txtlat').value = marker.position.lat();
                            document.getElementById('txtlong').value = marker.position.lng();
                            point = new google.maps.LatLng(document.getElementById('ctl00_BodyContentPH_txtlat').value, document.getElementById('txtlong').value);
                        });

                        google.maps.event.addListener(marker, "mouseover", function () {
                            infowindow.setContent('<table style="direction:' + VDirection + '" class=\'InfoBubble\' cellpadding=\'5\' cellspacing=\'2\'><tr><td colspan=3 width = "550px"><b><u>'
                                                    + VLandmarkLocationDetails + '</u></b></td><tr><td><b>' + VOrgCoordinates + '</b></td><td>:</td><td>'
                                                    + latlong.lat() + " , " + latlong.lng()
                                                    + '</td></tr><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + place.formatted_address + '</td></tr></table>');
                            infowindow.open(map, marker);
                        });

                        google.maps.event.addListener(marker, "mouseout", function () {
                            if (infowindow) infowindow.close();
                        });
                        var LocDesc = (document.getElementById('txtLocationDesc').value == "Description") ? "" : document.getElementById('txtLocationDesc').value;
                        var Radius = (document.getElementById('ctl00_BodyContentPH_txtRadius').value == "Radius") ? 500 : document.getElementById('ctl00_BodyContentPH_txtRadius').value;


                        getAddress = document.getElementById('ctl00_BodyContentPH_txtLocationName').value + '#' + centerPoint.lat() + '#' + centerPoint.lng() + '#' + LocDesc + '#' + place.formatted_address + '#' + Radius + '#' + (document.getElementById('chkNotify').checked ? 1 : 0) + '#0';
                        document.getElementById('ctl00_BodyContentPH_txtstreet').value = place.formatted_address;

                        centerPoint = new google.maps.LatLng(document.getElementById('ctl00_BodyContentPH_txtlat').value, document.getElementById('txtlong').value);
                        isEditable = (IsNew == "0" || IsNew == '') ? false : true;
                        drawCircle();
                        map.fitBounds(circle.getBounds());
                        LandMarkImage = '';
                    }
                } else {
                    alert("Address Cannot be found. Please check the LatLong Values ");
                }
            });

            // showControls(1);
        }
    } catch (Error) {
    }
}


var address1 = null;
function FrameAddress() {
    try {
        address1 = ''

        if (document.getElementById('ctl00_BodyContentPH_txtstreet').value != '') {
            if (address1 != '') {
                address1 = address1 + ' ' + document.getElementById('ctl00_BodyContentPH_txtstreet').value;
            }
            else {
                address1 = document.getElementById('ctl00_BodyContentPH_txtstreet').value;
            }
        }
        if (document.getElementById('ctl00_BodyContentPH_txtcity').value != '' && document.getElementById('ctl00_BodyContentPH_txtcity').value != "City") {
            if (address1 != '') {
                address1 = address1 + ',' + document.getElementById('ctl00_BodyContentPH_txtcity').value;
            }
            else {
                address1 = document.getElementById('ctl00_BodyContentPH_txtcity').value;
            }
        }
        if (document.getElementById('ctl00_BodyContentPH_txtstate').value != '' && document.getElementById('ctl00_BodyContentPH_txtstate').value != "State") {
            if (address1 != '') {
                address1 = address1 + ',' + document.getElementById('ctl00_BodyContentPH_txtstate').value;
            }
            else {
                address1 = document.getElementById('ctl00_BodyContentPH_txtstate').value;
            }
        }

        if (document.getElementById('ctl00_BodyContentPH_txtCountry').value != '' && document.getElementById('ctl00_BodyContentPH_txtCountry').value != "Country") {
            if (address1 != '') {
                address1 = address1 + ',' + document.getElementById('ctl00_BodyContentPH_txtCountry').value;
            }
            else {
                address1 = document.getElementById('ctl00_BodyContentPH_txtCountry').value;
            }
        }
        return address1;
    } catch (Error) {
    }
}



function Findplace(lat, lng, lndMark, addr, radius, isView) {
    debugger;
    try {
        getAddress = null;
        if (marker != null) {
            marker.setMap(null);
        }
        // if (LandMarkImage == null || LandMarkImage == '')
        LandMarkImage = '../dist/img/city.png';
        var icon = new google.maps.MarkerImage(LandMarkImage,
                   new google.maps.Size(32, 32),
                   new google.maps.Point(0, 0),
                   new google.maps.Point(0, 22));

        var point = new google.maps.LatLng(lat, lng);

        map.setCenter(point, 16);
        marker = new google.maps.Marker({
            position: point,
            icon: icon,
            draggable: false
        });

        marker.setMap(map);

        if (lndMark == '') {
            var LocDesc = (document.getElementById('ctl00_BodyContentPH_txtLocationDesc').value == "") ? "" : document.getElementById('ctl00_BodyContentPH_txtLocationDesc').value;
            var Radius = (document.getElementById('ctl00_BodyContentPH_txtRadius').value == "") ? 500 : document.getElementById('ctl00_BodyContentPH_txtRadius').value;

            getAddress = document.getElementById('ctl00_BodyContentPH_txtLocationName').value + '#' + lat + '#' + lng + '#' + Radius;
            document.getElementById('ctl00_BodyContentPH_txtlat').value = lat;
            document.getElementById('ctl00_BodyContentPH_txtlong').value = lng;

            //google.maps.event.addListener(marker, "mouseover", function () {
            //    infowindow.setContent('<br /><table cellpadding=\'5\' class=\'InfoBubble\'cellspacing=\'5\'><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + search + '</td></tr></table>');
            //    infowindow.open(map, marker);
            //});

            //google.maps.event.addListener(marker, "mouseout", function () {
            //    if (infowindow) infowindow.close();
            //});
        }
        else {

            google.maps.event.addListener(marker, "mouseover", function () {
                infowindow.setContent('<br/><table style="direction:' + VDirection + '" cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'><tr style="direction:' + VDirection + '"><td><b>' + VLandmark + '</b></td><td>:</td><td>'
                 + lndMark + '</td></tr><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + addr + '</td></tr></table>');
                infowindow.open(map, marker);
            });

            google.maps.event.addListener(marker, "mouseout", function () { if (infowindow) infowindow.close(); });
        }

        centerPoint = new google.maps.LatLng(lat, lng);
        // document.getElementById("message").innerHTML = "";

        isEditable = isView == "true" ? false : true;
        isDraggable = false;
        drawCircle();
        map.fitBounds(circle.getBounds());
        LandMarkImage = '';

    }
    catch (Error) {
    }
}

var centerMarker;
var circleUnits;
var circleRadius;
var centerPoint;

function drawCircle() {
    try {
        var oRadius = document.getElementById('ctl00_BodyContentPH_txtRadius');
        oRadius.value = (oRadius.value != '' && oRadius.value != "Radius") ? oRadius.value : 500;

        if (oRadius.value.match(/[^\d.]/)) {
            alert("Enter a number for radius");
            return;
        }
        if (oRadius.value > 9999) {
        }
        circleRadius = oRadius.value;
        doDrawCircle();
    }
    catch (Error) {
    }
}


function doDrawCircle() {
    try {
        if (circle) {
            circle.setMap(null);
        }
        var center = map.getCenter();
        var bounds = new google.maps.LatLngBounds();
        //isEditable = isEdit;

        var radius = parseInt(circleRadius);
        var populationOptions = {
            strokeColor: "#5270B2",
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: "#D8E2FA",
            fillOpacity: 0.25,
            center: centerPoint,
            radius: radius,
            editable: isEditable
        };

        circle = new google.maps.Circle(populationOptions);
        circle.setMap(map);

        if (!isEditable) {

            //Radius Change Event
            google.maps.event.addListener(circle, 'radius_changed', function () {
                circleRadius = Math.round(circle.getRadius());
                var center = circle.getCenter();
                document.getElementById('ctl00_BodyContentPH_txtRadius').value = circleRadius;
                var LocDesc = (document.getElementById('ctl00_BodyContentPH_txtLocationDesc').value == "") ? "" : document.getElementById('ctl00_BodyContentPH_txtLocationDesc').value;
                var Radius = (document.getElementById('ctl00_BodyContentPH_txtRadius').value == "") ? 500 : document.getElementById('ctl00_BodyContentPH_txtRadius').value;
                getAddress = document.getElementById('ctl00_BodyContentPH_txtLocationName').value + '#' + centerPoint.lat() + '#' + centerPoint.lng() + '#' + LocDesc + '#' + place.formatted_address + '#' + Radius + '#' + (document.getElementById('chkNotify').checked ? 1 : 0) + '#0';
            });

            //Center Change Event
            google.maps.event.addListener(circle, 'center_changed', function () {
                circleRadius = Math.round(circle.getRadius());
                var center = circle.getCenter();
                document.getElementById('ctl00_BodyContentPH_txtRadius').value = circleRadius;
                var LocDesc = (document.getElementById('ctl00_BodyContentPH_txtLocationDesc').value == "") ? "" : document.getElementById('ctl00_BodyContentPH_txtLocationDesc').value;
                var Radius = (document.getElementById('ctl00_BodyContentPH_txtRadius').value == "") ? 500 : document.getElementById('ctl00_BodyContentPH_txtRadius').value;
                getAddress = document.getElementById('ctl00_BodyContentPH_txtLocationName').value + '#' + centerPoint.lat() + '#' + centerPoint.lng() + '#' + LocDesc + '#' + place.formatted_address + '#' + Radius + '#' + (document.getElementById('chkNotify').checked ? 1 : 0) + '#0';

                document.getElementById('ctl00_BodyContentPH_txtlat').value = Math.round(center.lat() * 1000000) / 1000000;
                document.getElementById('ctl00_BodyContentPH_txtlong').value = Math.round(center.lng() * 1000000) / 1000000;
                document.getElementById('ctl00_BodyContentPH_txtstreet').value = place.formatted_address;


                var geoFinder = new google.maps.Geocoder();

                geoFinder.geocode({ 'latLng': center }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[0]) {
                            place = results[0];
                            var icon = new google.maps.MarkerImage(MarkerImage, //'../images/flag_2.svg'
                                       new google.maps.Size(32, 32),
                                       new google.maps.Point(0, 0),
                                       new google.maps.Point(0, 22));

                            if (marker) marker.setMap(null);
                            marker = new google.maps.Marker({
                                position: center,
                                map: map,
                                icon: icon,
                                draggable: isDraggable
                            });

                            google.maps.event.addListener(marker, "dragstart", function () {
                                if (infowindow) infowindow.close();
                            });

                            google.maps.event.addListener(marker, 'dragend', function () {
                                document.getElementById('ctl00_BodyContentPH_txtlat').value = marker.position.lat();
                                document.getElementById('ctl00_BodyContentPH_txtlong').value = marker.position.lng();
                                point = new google.maps.LatLng(document.getElementById('ctl00_BodyContentPH_txtlat').value, document.getElementById('ctl00_BodyContentPH_txtlong').value);
                            });

                            google.maps.event.addListener(marker, "mouseover", function () {
                                var latlong = new google.maps.LatLng(document.getElementById('ctl00_BodyContentPH_txtlat').value, document.getElementById('ctl00_BodyContentPH_txtlong').value);
                                infowindow.setContent('<table style="direction:' + VDirection + '" class=\'InfoBubble\' cellpadding=\'5\' cellspacing=\'2\'><tr><td colspan=3><b><u>'
                                                    + VLandmarkLocationDetails + '</u></b></td><tr><td><b>' + VOrgCoordinates + '</b></td><td>:</td><td>'
                                                    + latlong.lat() + " , " + latlong.lng()
                                                    + '</td></tr><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + place.formatted_address + '</td></tr></table>');
                                infowindow.open(map, marker);
                            });

                            google.maps.event.addListener(marker, "mouseout", function () {
                                if (infowindow) infowindow.close();
                            });

                            //                            getAddress = document.getElementById('ctl00_BodyContentPH_txtLocationName').value + '#' + centerPoint.lat() + '#' + centerPoint.lng() + '#' + LocDesc + '#' + place.formatted_address + '#' + Radius + '#' + (document.getElementById('chkNotify').checked ? 1 : 0) + '#0';
                            //                            document.getElementById('ctl00_BodyContentPH_txtstreet').value = place.formatted_address;
                        }
                    }
                });
            });
        }

        //isEdit = true;
        landMarkCircles.push(circle);
    }
    catch (Error) {
    }
}
function SetCenter() {
    alert("Manikandan");
    if (!map) {
        map.setCenter(new google.maps.LatLng(11.004556, 76.961632));
        zoom: 4;
    }
}