var timerInterval;
var map = null;
var polyline = null;
var contextmenu;
var history_latlng = null;
var centerCoordinate = new jsapi.geo.Coordinate(23.805450, 78.486328);  //ew GLatLng(23.805450, 78.486328);
var isViewLatLong = 0;
var mapItMarkers;

// 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";
jsapi.util.ApplicationContext.set("authenticationToken", "4b25c0fb0d9f746bbe44a74f549b49208f1833336bb01f04");
jsapi.util.ApplicationContext.set("appId", "<AppId>");
var infoBubble = new jsapi.map.component.InfoBubbles(), infoMarkers = {};
infoBubble.Bubble.prototype.defaultWidth = 300;

// Set the alert messages from the Resource File
function SetIconLegendText(AllLandmarkAlert, CurrLocationAlert, IgnitionOnAlert, IgnitionOffAlert, MovingAlert, IdlingAlert, AlarmsAlert, VDetailsTab, VOtherinfoTab, VDateTimeAlert, VMessageAlert, VAddressAlert, VLegendAlignAlert, VLandmarkAlert, VDirectionMessage, VSleepMessage, VOtherMessage, VLegendHdrMessage, VLegendToolTipMessage) {

    VAllLandmark = AllLandmarkAlert;
    VCurrLocation = CurrLocationAlert;
    VIgnitionOn = IgnitionOnAlert;
    VIgnitionOff = IgnitionOffAlert;
    VMoving = MovingAlert;
    VIdling = IdlingAlert;
    VAlarms = AlarmsAlert;
    VDetails = VOtherinfoTab;
    VOtherinfo = VDetailsTab;
    VDateTime = VDateTimeAlert;
    VMessage = VMessageAlert;
    VAddress = VAddressAlert;
    VLegendAlign = VLegendAlignAlert;
    VLandmark = VLandmarkAlert;
    VDirection = VDirectionMessage;
    VSleep = VSleepMessage;
    VOthers = VOtherMessage;
    VLegendHeader = VLegendHdrMessage;
    VLegendToolTip = VLegendToolTipMessage;
}
var VLandmarkLocationDetails = "Landmark Location Details";
var VOrgCoordinates = "Original Coordinates";
function SetLandMarkText(VLandmarkLocationDetailsMessage, VOrgCoordinatesMessage, VAddressMessage, VDirectionMessage) {
    VLandmarkLocationDetails = VLandmarkLocationDetailsMessage;
    VOrgCoordinates = VOrgCoordinatesMessage;
    VAddress = VAddressMessage;
    VDirection = VDirectionMessage;
}
function load() {
    //document.getElementById("map-legend").innerHTML = iconLegendText();
    try {
        if (map != null) {
            map.removeComponent(map.getComponentById("ZoomBar"));
            map.removeComponent(map.getComponentById("TypeSelector"));
            map.removeComponent(map.getComponentById("Overview"));
            map.removeComponent(map.getComponentById("zoom.DoubleClick"));
            map.removeComponent(map.getComponentById("Behavior"));
            map.removeComponent(map.getComponentById("InfoBubbles"));
            map.destroy();
        }
        //GUnload();
    }
    catch (Error) {
    }
    try {
        var gridViewControl = document.getElementById('gvData');
        if (gridViewControl == null) {
            gridViewControl = document.getElementById('gvHistory');
        }
        if (gridViewControl != null) {
            document.getElementById('map-dsply').style.width = gridViewControl.width; //document.body.clientWidth ;//document.documentElement.clientWidth-35//screen.width - 35;
        }

        document.getElementById('map-dsply').style.height = (document.body.clientHeight / 2) + 'px';

        //if (document.getElementById('map-dsply').innerHTML == "") {
        map = new jsapi.map.Display(document.getElementById("map-dsply"), {
            center: centerCoordinate,
            zoomLevel: 4
        });
        map.addComponent(infoBubble);
        map.addComponent(new jsapi.map.component.ZoomBar());
        map.addComponent(new jsapi.map.component.TypeSelector());
        map.addComponent(new jsapi.map.component.Overview());
        map.addComponent(new jsapi.map.component.zoom.DoubleClick());
        map.addComponent(new jsapi.map.component.Behavior());
        //var myNode = document.createElement("div");
        //myNode.innerHTML = iconLegendText();

        // ---- START of the custom component implementation
        //            var myCustomComponent = new jsapi.map.component.Component({

        //                getId: function() { return "MyCustomComponent"; },

        //                //method called when component is attached to display
        //                attach: function(map) {
        //                    var superClass = jsapi.map.component.Component.prototype;
        //                    superClass.attach.apply(this, arguments);
        //                    map.getUIContainer().appendChild(myNode);
        //                    if (!this.button) {
        //                        this.button = jsapi.dom.EventTarget(document.getElementById("myCustomComponentButton"));
        //                    }
        //                    var that = this; //Save the context to make it possible to access it in the listener
        //                    this.button.addListener("click", this.onButtonClick = function(evt) {
        //                        var level = parseInt(Math.random() * 10);
        //                        that.mapDisplay.setZoomLevel(level, "linear");
        //                    });
        //                },

        //                //method called when component is removed from display
        //                detach: function(map) {
        //                    var superClass = jsapi.map.component.Component.prototype;
        //                    map.getUIContainer().removeChild(myNode);
        //                    //this.button.removeListener("click", this.onButtonClick);
        //                    superClass.detach.apply(this, arguments);
        //                },

        //                //method called after clicking on button
        //                onButtonClick: null
        //            });
        // END of the custom component implementation ----
        //          map.components.add(myCustomComponent);
        //To enable the Mouse wheel Scroll
        var mapTypeHolder = document.getElementById("hdnMapType");
        if (mapTypeHolder != null) {
            switch (mapTypeHolder.value) {
                case 'N': map.set("baseMapType", map.NORMAL); break;
                case 'S': map.set("baseMapType", map.SATELLITE); break;
                case 'H': map.set("baseMapType", map.HYBRID); break;
            }
        }
        //}

        return true;

    }
    catch (Error) {
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }
}

function iconLegendText() {
    var height = '';
    //if (navigator.appName == 'IE') {
    //    if (document.getElementById('gvHistory') != null) { height = "height='190px'"; } else { height = "height='162px'"; }
    //}
    //else {
    //}
    var landmarkIconText = "<tr>" +
                          "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkLandmark' style='height:15px;width:15px;' name='chkLandmark' onclick='ShowPopUp();document.getElementById(\"chkShowLandmarks\").checked = this.checked;drawCircleForLandmark(document.getElementById(\"hdnLandmarkEntries\").value,this.checked);HidePopUp();'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
                          "  <td style='font:11px arial;color:#333333;vertical-align:middle' align='" + VLegendAlign + "'>" + VAllLandmark + "</span></td>" +
    "</tr>";
    var landmarkIconTextForFullscreen = "<tr>" +
                          "  <td style='padding-left:2px;' align='right'><input type='checkbox' id='chkLandmark' style='height:15px;width:15px;' name='chkLandmark' onclick='ShowPopUp();drawCircleForLandmark(document.getElementById(\"hdnLandmarkEntries\").value,this.checked);HidePopUp();'><span style='vertical-align:top;background-color:white;color:Blue'></td>" +
                          "  <td style='font:11px arial;color:#333333;vertical-align:middle' align='" + VLegendAlign + "'>" + VAllLandmark + "</span></td>" +
    "</tr>";
    var downIconText = (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>" + landmarkIconTextForFullscreen : (document.getElementById('gvData') != null) ? landmarkIconText : (document.getElementById('hdnLandmarkEntries') != null && document.getElementById('hdnLandmarkEntries').value.length != 0) ? landmarkIconTextForFullscreen : "";

    var legendText = "<br><table id='tblLegend' align='right' width='120px' " + height + " style='direction:" + VDirection + ";padding:2px 0px 2px 2px;background-color:#E8ECF8;border-left:1px solid #979797;border-top:1px solid #979797;border-bottom:1px solid #979797'>" +
                "<tr><td align='right' style='padding: 6px 0px 6px 6px;'>" +
                 "<table cellpadding='2' cellspacing='2' align='right' width='112px' height='114px' style='background-color:#F4F3F0;border-left:1px solid #979797;border-top:1px solid #979797;border-bottom:1px solid #979797'>" +
                 "<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>" + downIconText +
                 "</table>"
    "</td></tr></table>";
    return legendText;
}
//TO load Map in Full screen mode
function loadFullscreen() {
    //document.getElementById("map-legend").innerHTML = iconLegendText();
    try {
        if (map != null) {
            map.removeComponent(map.getComponentById("ZoomBar"));
            map.removeComponent(map.getComponentById("TypeSelector"));
            map.removeComponent(map.getComponentById("Overview"));
            map.removeComponent(map.getComponentById("zoom.DoubleClick"));
            map.removeComponent(map.getComponentById("Behavior"));
            map.removeComponent(map.getComponentById("InfoBubbles"));
            map.destroy();
        }
        //GUnload();
    }
    catch (Error) {
    }
    try {
        var gridViewControl = document.getElementById('gvData');
        if (gridViewControl == null) {
            gridViewControl = document.getElementById('gvHistory');
        }
        if (gridViewControl != null) {
            document.getElementById('map-dsply').style.width = document.body.clientWidth; //document.documentElement.clientWidth-35//screen.width - 35;
        }
        document.getElementById('map-dsply').style.height = document.body.clientHeight + 'px';

        //if (document.getElementById('map-dsply').innerHTML == "") {
        map = new jsapi.map.Display(document.getElementById("map-dsply"), {
            center: new jsapi.geo.Coordinate(23.805450, 78.486328),
            zoomLevel: 4
        });
        map.addComponent(infoBubble);
        map.addComponent(new jsapi.map.component.ZoomBar());
        map.addComponent(new jsapi.map.component.TypeSelector());
        map.addComponent(new jsapi.map.component.Overview());
        map.addComponent(new jsapi.map.component.zoom.DoubleClick());
        map.addComponent(new jsapi.map.component.Behavior());
        //Set map Type
        var mapTypeHolder = document.getElementById("hdnMapType");
        if (mapTypeHolder != null) {
            switch (mapTypeHolder.value) {
                case 'N': map.set("baseMapType", map.NORMAL); break;
                case 'S': map.set("baseMapType", map.SATELLITE); break;
                case 'H': map.set("baseMapType", map.HYBRID); break;
            }
            //  }
        }


        //        map = new GMap2(document.getElementById("map-dsply"));
        //        map.addControl(new GLargeMapControl());
        //        map.addControl(new GMapTypeControl());
        //        map.addControl(new GOverviewMapControl());

        //var myControl = new HtmlControl(iconLegendText());        
        //        map.addControl(myControl, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 30)));

        //        // define minimum and maximum zoom levels
        //        G_NORMAL_MAP.getMinimumResolution = function() { return 0; }
        //        G_NORMAL_MAP.getMaximumResolution = function() { return 19; }

        //        //To enable the Mouse wheel Scroll
        //        map.enableScrollWheelZoom();
        //        map.enableContinuousZoom();
        //        map.setCenter(new GLatLng(23.805450, 78.486328), 4);
        //        GEvent.addListener(map, "maptypechanged", mapTypeChanged);
        //        var mapTypeHolder = document.getElementById("hdnMapType");
        //        if (mapTypeHolder != null) {
        //            switch (mapTypeHolder.value) {
        //                case 'N': map.set("baseMapType", map.NORMAL); break;
        //                case 'S': map.set("baseMapType", map.SATELLITE); break;
        //                case 'H': map.set("baseMapType", map.HYBRID); break;
        //            }
        //        }
        return true;
    }
    catch (Error) {
        return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }
}

function mapTypeChanged() {
    //    var mapTypeHolder = document.getElementById("hdnMapType");
    //    if (mapTypeHolder != null) {
    //        switch (map.getCurrentMapType()) {
    //            case G_NORMAL_MAP: mapTypeHolder.value = 'N'; break;
    //            case G_SATELLITE_MAP: mapTypeHolder.value = 'S'; break;
    //            case G_HYBRID_MAP: mapTypeHolder.value = 'H'; break;
    //        }
    //    }
}

var flag = false;
//To toggle from Fullscreen Mode - Not used now, but kept for future reference
function changeSize() {
    //map = new GMap2(document.getElementById("map-dsply"));

    if (flag == false) {
        document.getElementById('top-content').style.display = 'none';
        document.getElementById('updGrid').style.display = 'none';
        document.getElementById('map-dsply').style.width = document.body.clientWidth - 10;
        document.getElementById('map-dsply').style.height = document.body.clientHeight - 10;
    }
    else {
        document.getElementById('top-content').style.display = 'block';
        document.getElementById('updGrid').style.display = 'block';
        var gridViewControl = document.getElementById('gvData');
        if (gridViewControl == null) {
            gridViewControl = document.getElementById('gvHistory');
        }
        if (gridViewControl != null) {
            document.getElementById('map-dsply').style.width = gridViewControl.width; //document.body.clientWidth ;//document.documentElement.clientWidth-35//screen.width - 35;
        }
        document.getElementById('map-dsply').style.height = (document.body.clientHeight / 2) + 'px';
    }
    // Always change value of flag
    // from true to false or vice versa
    flag = !flag;
    // Always call checkResize()
    map.checkResize();
    map.setCenter();
}

var marker = null;
function loadForLandMark() {
    try {
        //map = null;
        //        $find('ModalPopupExtender1').hide();
        document.getElementById("pnlInfoWindow").style.display = "none";
        //GUnload();
    }
    catch (Error) {
    }
    try {
        var isIE = CheckBrowser();
        var hdnCanAddLandmarksControl = document.getElementById('hdnCanAddLandmarks');
        var gridViewControl = document.getElementById('gvData');
        if (hdnCanAddLandmarksControl.value == 'false') {
            document.getElementById('search-area').setAttribute(isIE ? 'className' : 'class', 'ControlHide');
            if (gridViewControl != null) {
                document.getElementById('map-dsply').style.width = gridViewControl.clientWidth + 'px';
            }
        }
        else {
            document.getElementById('search-area').setAttribute(isIE ? 'className' : 'class', "ControlShow");
            document.getElementById('map-dsply').style.width = (gridViewControl.clientWidth - 5 -
             (document.getElementById('search-box').clientWidth)) + 'px';
        }

        // Setting the height of the map
        //document.getElementById('map-dsply').style.height = (screen.height / 2) - 44;
        if (document.body.clientHeight < 875) {
            document.getElementById('map-dsply').style.height = ((875 / 2) - 18) + 'px';
            document.getElementById('search-box').style.height = document.getElementById('map-dsply').style.height;
        }
        else {
            document.getElementById('map-dsply').style.height = ((document.body.clientHeight / 2) - 18) + 'px';
            document.getElementById('search-box').style.height = document.getElementById('map-dsply').style.height;
        }

        if (map) {
            map.objects.clear();
            map.set("zoomLevel", 4);
            map.set("Center", centerCoordinate);
            //map.setCenter = centerCoordinate;
        }

        if (document.getElementById('map-dsply').innerHTML == '') {
            map = new jsapi.map.Display(document.getElementById("map-dsply"), {
                center: new jsapi.geo.Coordinate(23.805450, 78.486328),
                zoomLevel: 4,
                components: [infoBubble,
                new jsapi.map.component.ZoomBar(),
                new jsapi.map.component.TypeSelector(),
                new jsapi.map.component.Overview(),
                new jsapi.map.component.zoom.DoubleClick(),
                new jsapi.map.component.Behavior()]
            });

            map.addListener("click", function(evt) {

                var cord = map.pixelToGeo(evt.displayX, evt.displayY);
                showControls(1);
                if (cord != null) {
                    document.getElementById('txtlat').value = Math.round(cord.latitude * 1000000) / 1000000;
                    document.getElementById('txtlong').value = Math.round(cord.longitude * 1000000) / 1000000;
                    if (document.getElementById('hdnLatLong') != null) {
                        document.getElementById('hdnLatLong').value = cord.latitude + ',' + cord.longitude;
                    }
                    chkValue = 0;
                    document.getElementById('hdnIsLocateMe').value = 'N';
                }
            });
        }
        //        map = new GMap2(document.getElementById("map-dsply"));
        //        map.addControl(new GLargeMapControl());
        //        map.addControl(new GMapTypeControl());
        //        map.addControl(new GOverviewMapControl());
        //        //To enable the Mouse wheel Scroll
        //        map.enableScrollWheelZoom();
        //        map.enableContinuousZoom();

        if (document.getElementById('hdnMapZoomLevelLatLong').value != "") {
            var zoomLevelLatLong = document.getElementById('hdnMapZoomLevelLatLong').value.split(',');
            //centerCoordinate = new jsapi.geo.Coordinate(parseFloat(zoomLevelLatLong[0]), parseFloat(zoomLevelLatLong[1]));
        }
        //map.setCenter = centerCoordinate;
        //        GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
        //            document.getElementById('hdnMapZoomLevel').value = newLevel;
        //            centerCoordinate = map.getCenter();
        //            try {
        //                document.getElementById('hdnMapZoomLevelLatLong').value = centerCoordinate.y + ',' + centerCoordinate.x;
        //            }
        //            catch (Error) { }
        //        });

        // === create the context menu div ===
        contextmenu = document.createElement("div");
        contextmenu.style.visibility = "hidden";
        contextmenu.style.background = "#ffffff";
        contextmenu.style.border = "1px solid #8888FF";

        contextmenu.innerHTML = '<a href="javascript:zoomIn()"><div class="context">&nbsp;&nbsp;Zoom in&nbsp;&nbsp;</div></a>'
                            + '<a href="javascript:zoomOut()"><div class="context">&nbsp;&nbsp;Zoom out&nbsp;&nbsp;</div></a>';

        //map.getContainer().appendChild(contextmenu);

        // === listen for singlerightclick ===
        //        GEvent.addListener(map, "singlerightclick", function(point, src, overlay) {

        //            showControls(1);
        //            marker = new GMarker(map.fromDivPixelToLatLng(point), { draggable: true, bouncy: false, dragCrossMove: true });
        //            var lndLatlng = marker.getLatLng().toUrlValue();
        //            lndLatlng = lndLatlng.split(',');
        //            document.getElementById('txtlat').value = lndLatlng[0];
        //            document.getElementById('txtlong').value = lndLatlng[1];
        //                               var x = point.x;
        //                               var y = point.y;
        //                               if (x > map.getSize().width - 120) { x = map.getSize().width - 120 }
        //                               if (y > map.getSize().height - 100) { y = map.getSize().height - 100 }
        //                               var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x, y));
        //            pos.apply(contextmenu);
        //            contextmenu.style.visibility = "visible";
        //        });

        //== Click on Map to get the co-ordinates

        //        GEvent.addListener(map, 'click', function(overlay, latlng) {
        //            showControls(1);
        //            //        var lndLatlng = latlng.split(',');

        //            if (latlng != null) {
        //                document.getElementById('txtlat').value = Math.round(latlng.y * 1000000) / 1000000;
        //                document.getElementById('txtlong').value = Math.round(latlng.x * 1000000) / 1000000;

        //                if (document.getElementById('hdnLatLong') != null) {
        //                    document.getElementById('hdnLatLong').value = latlng.y + ',' + latlng.x;
        //                }
        //                chkValue = 0;

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

        //            //marker = new GMarker(latlng, { draggable: false, bouncy: false, dragCrossMove: true });
        //        });

        //== End of function

        //               GEvent.addListener(marker, "drag", function() { });
        //               GEvent.addListener(marker, "mouseover", function() { });

        //               GEvent.addListener(marker, "mouseout", function() {                   
        //                   var geoFinder = new GClientGeocoder();
        //                   geoFinder.getLocations(marker.getLatLng().toUrlValue(), showAddress_Latlng);
        //               });

        //map.addOverlay(marker);
    }
    catch (Error) {
        TrinetraCustomAlerts('Please check your Internet Connection. Map cannot be loaded');
    }

    if (document.getElementById('hdnMapZoomLevel').value != "") {
        // map.setZoom(eval(document.getElementById('hdnMapZoomLevel').value));
    }
}
//------End------Added by Ramya on 03 Oct 09 (To change the width of the map displaying div----------//
var lt;
var count = '';
//To get the array of LatLong values
var collectdata = null;

var lntlngs = new Array();
var geocoder;
var address = new Array();
var disArray = new Array();
var googleResults;
var lastvalue = null;
var positioncurrent = null;
var landmarkInfo = null;
var canClearCircle = true;
var historyLandmarks = ''
//var startDateTime;
// 'Message Details',true,'Message',true,'Address',true,'Landmark',true,'Speed'
function DisplayLocation(latlng, pageName, mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible, datetimeCaption,
    isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption, isSpeedVisible, speedCaption,
    addLandmarkCaption, isVehicleVisbile, vehicleCaption, isPolylineVisible, isCurrentPositionVisible) {
    try {
        //        ShowPopUp();
        //        load();
        var mapItValueList = document.getElementById("hdnAlarmIDs").value.split(',');
        var mapTypeHolder = document.getElementById("hdnMapType");
        if (mapTypeHolder != null) {
            switch (mapTypeHolder.value) {
                case 'N': map.set("baseMapType", map.NORMAL); break;
                case 'S': map.set("baseMapType", map.SATELLITE); break;
                case 'H': map.set("baseMapType", map.HYBRID); break;
            }
        }
        lt = new Array();
        history_latlng = latlng;
        //        var clusterer = new Clusterer(map);
        //var icon1 = G_START_ICON;
        //        clusterer.SetIcon(icon1);
        googleResults = new Array();
        lntlngs = new Array();
        collectdata = null;  //new GLatLngBounds();
        //if (GBrowserIsCompatible()) {

        if (latlng.indexOf('~&~*') > 0) {
            var currentpos = latlng.split('~&~*');
            lt = currentpos[0].split('~&~');
            positioncurrent = currentpos[1];
        }
        else {
            lt = latlng.split('~&~*');
            positioncurrent = lt[1];

            if (positioncurrent != null) {
                var curpos = positioncurrent.split("~#~");
                //collectdata.extend(new jsapi.geo.Coordinate(parseFloat(curpos[0]), parseFloat(curpos[1])));
                var point = new jsapi.geo.Coordinate(parseFloat(curpos[0]), parseFloat(curpos[1])); //new GLatLng(curpos[0], curpos[1]);
                map.objects.add(createMarker(point, curpos[5], curpos[3], curpos[4], 'current', i, curpos[2],
                     curpos[6], curpos[7], curpos[8], curpos[9], mainCaption, isMessageVisbile, msgCaption,
                     isDateTimeVisible, datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible,
                     landmarkCaption, isSpeedVisible, speedCaption, addLandmarkCaption));
                canClearCircle = false;
                //map.setCenter(collectdata.getCenter(), map.getBoundsZoomLevel(collectdata) - 1);
                return;
            }
        }

        for (var i = 0; i < lt.length; i++) {
            var lng = new Array();
            lng = lt[i].split("~#~");
            if (i == lt.length - 1) {
                lastvalue = new jsapi.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1]));
            }
            lntlngs.push(new jsapi.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1])));
            //lntlngs.push(new GLatLng(lng[0], lng[1]));
            //collectdata.extend(new GLatLng(lng[0], lng[1]));
        }

        //create our new class
        var work = new threadedLoop(lntlngs);
        var mapMarker;
        work.action = function(item, index, total) {
            var lng = new Array();
            if (index <= total) {
                lng = lt[index - 1].split("~#~");
                mapMarker =
                    createMarker(lntlngs[index - 1], lng[5], lng[3], lng[4],
                    Array.contains(mapItValueList, "'" + lng[10].toString().toUpperCase() + "'") ?
                     'MapIt' : i.toString(), i, lng[2], lng[6], lng[7], lng[8], lng[9],
                     mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible, datetimeCaption,
                     isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption,
                     isSpeedVisible, speedCaption, addLandmarkCaption);
                map.objects.add(mapMarker);
                map.zoomTo(mapMarker.getBoundingBox(), false);
                if (map.zoomLevel > 10) map.set("zoomLevel", 10); //zoom out if too close
                //                    clusterer.AddMarker(mapMarker, lng[4] + ' - ' + lng[9]);
            }
        };
        work.finish = function(thread) {
            if (positioncurrent != null && isCurrentPositionVisible == 'true') {
                var curpos = positioncurrent.split("~#~");
                var point = new jsapi.geo.Coordinate(parseFloat(curpos[0]), parseFloat(curpos[1]));  //new GLatLng(curpos[0], curpos[1]);
                map.objects.add(createMarker(point, curpos[5], curpos[3], curpos[4], 'current', i, curpos[2],
                 curpos[6], curpos[7], curpos[8], curpos[9], mainCaption, isMessageVisbile, msgCaption,
                 isDateTimeVisible, datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible,
                 landmarkCaption, isSpeedVisible, speedCaption, addLandmarkCaption));
                canClearCircle = false;
                //map.zoomTo(lntlngs.getBoundingBox(), false);
                //map.setCenter(collectdata.getCenter(), map.getBoundsZoomLevel(collectdata) - 1);
            }
            work = null;
            HidePopUp();
        };
        work.start();
        if (isPolylineVisible) {

            polyline = new jsapi.map.Polyline(
                        lntlngs,
                        {
                            pen: { strokeColor: "#980900", lineWidth: 2 },
                            brush: { color: "#980900" }
                        }
                    );
            //polyline = new BDCCPolyline(lntlngs, "#980900", 2, 0.8, "Polyline", 'dash');
            map.objects.add(polyline);
        }
        //map.zoomTo(lntlngs[lntlngs.length-1].getBoundingBox(), false);
        //map.setCenter(lntlngs, lntlngs.getBoundingBox());
        //map.setCenter(collectdata.getCenter(), map.getBoundsZoomLevel(collectdata) - 1);
    }
    //}
    catch (Error) {
    }
}

function continueOperations(isPolylineVisible, polyline, collectdata) {
    if (isPolylineVisible) {
        polyline = new BDCCPolyline(lntlngs, "#980900", 2, 0.8, "Polyline", 'dash');
        map.addOverlay(polyline);
    }
    map.setCenter(collectdata.getCenter(), map.getBoundsZoomLevel(collectdata) - 1);
}

// Creates a marker at the given point with the given number label
function Draw(polystyle) {
    try {
        var ctrl = document.getElementById(polystyle);

        if (ctrl.id == 'dot') {
            var solid = document.getElementById('solid');
            var dash = document.getElementById('dash');
            ctrl.src = '../images/btn-' + polystyle + '-over.jpg';
            solid.src = '../images/btn-solid.jpg';
            dash.src = '../images/btn-dash.jpg';
        }
        //Dash
        else if (ctrl.id == 'dash') {
            var solid = document.getElementById('solid');
            var dot = document.getElementById('dot');
            ctrl.src = '../images/btn-' + polystyle + '-over.jpg';
            solid.src = '../images/btn-solid.jpg';
            dot.src = '../images/btn-dot.jpg';
        }
        //Solid
        else if (ctrl.id == 'solid') {
            var dash = document.getElementById('dash');
            var dot = document.getElementById('dot');
            ctrl.src = '../images/btn-' + polystyle + '-over.jpg';
            dot.src = '../images/btn-dot.jpg';
            dash.src = '../images/btn-dash.jpg';
        }

        if (lntlngs.length > 0) {

            map.objects.remove(polyline);

            polyline = new jsapi.map.Polyline(
                        lntlngs, polystyle,
                        {
                            pen: { strokeColor: "#980900", lineWidth: 2 },
                            brush: { color: "#980900" }
                        }
                    );

            //polyline = new BDCCPolyline(lntlngs, "#980900", 2, 0.8, "Polyline", polystyle);
            map.objects.add(polyline);
        }
    }
    catch (Error) {
        //    return confirm('Please check your Internet Connection. Map cannot be loaded. Click Ok to proceed.');
    }
}
var timeoutMarker;
function createMarker(point, heading, speed, time, id, i_No, addr, dist, ignstatus, landmark, msgdetails,
    mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible, datetimeCaption, isAddressVisible,
    addressCaption, isLandmarkVisible, landmarkCaption, isSpeedVisible, speedCaption, addLandmarkCaption) {
    var mapIcon = null; //new GIcon();
    //mapIcon.iconSize = new GSize(20, 20);
    var marker = null;  //= new GMarker(point, { draggable: false, icon: icon });
    try {
        if (heading == -1 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-1_.png';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-1_.png';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-1_.png';
            }
            else if (ignstatus == '3' || ignstatus == '8' || ignstatus == '9') /*Idling start & end 06-Dec-2011 - Sakthi*/{
                mapIcon = '../images/pink-1_.png';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-1_.png';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-1_.png';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/1_.png';
            }
            else if (ignstatus == '10') {
                mapIcon = '../images/mapit-9_.png'; /*Sleep mode - 20-Dec-2011 Sakthi*/
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-1_.png';
            }
        }
        else if (heading >= 0 && heading <= 30 && id != 'current') {
            if (id == 'MapIt') {
                if (heading == '0' && ignstatus == '7')
                    mapIcon = '../images/mapit-1_.png';
                else
                    mapIcon = '../images/mapit-3_20.png';
            }
            else if (heading == '0' && ignstatus == '7') {
                mapIcon = '../images/fuellow-1_.png';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-3_20.png';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-3_20.png';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-3_20.png';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-3_20.png';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/3_20.png';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-3_20.png';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-3_20.png';
            }
        }
        else if (heading > 30 && heading <= 70 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-7_20.png';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-7_20.png';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-7_20.png';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-7_20.png';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-7_20.png';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/7_20.png';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-7_20.png';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-7_20.png';
            }
        }
        else if (heading > 70 && heading <= 100 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-1_20.png';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-1_20.png';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-1_20.png';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-1_20.png';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-1_20.png';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/1_20.png';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-1_20.png';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-1_20.png';
            }
        }
        else if (heading > 100 && heading <= 150 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-5_20.png';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-5_20.png';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-5_20.png';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-5_20.png';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-5_20.png';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/5_20.png';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-5_20.png';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-5_20.png';
            }
        }
        else if (heading > 150 && heading <= 200 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-4_20.png';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-4_20.png';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-4_20.png';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-4_20.png';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-4_20.png';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/4_20.png';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-4_20.png';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-4_20.png';
            }
        }
        else if (heading > 200 && heading <= 240 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-8_20.png';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-8_20.png';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-8_20.png';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-8_20.png';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-8_20.png';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/8_20.png';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-8_20.png';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-8_20.png';
            }
        }
        else if (heading > 240 && heading <= 280 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-2_20.png';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-2_20.png';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-2_20.png';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-2_20.png';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-2_20.png';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/2_20.png';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-2_20.png';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-2_20.png';
            }
        }
        else if (heading > 280 && heading <= 330 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-6_20.png';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-6_20.png';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-6_20.png';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-6_20.png';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-6_20.png';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/6_20.png';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-6_20.png';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-6_20.png';
            }
        }
        else if (heading > 330 && heading <= 360 && id != 'current') {
            if (id == 'MapIt') {
                mapIcon = '../images/mapit-3_20.png';
            }
            else if (ignstatus == '6' || ignstatus == '7') {
                mapIcon = '../images/fuellow-3_20.png';
            }
            else if (ignstatus == '3') {
                mapIcon = '../images/pink-3_20.png';
            }
            else if (ignstatus == '4') {
                mapIcon = '../images/fuelnormal-3_20.png';
            }
            else if (ignstatus == '5') {
                mapIcon = '../images/fuelhigh-3_20.png';
            }
            else if (ignstatus == '2') {
                mapIcon = '../images/3_20.png';
            }
            else if (ignstatus == '0') {
                mapIcon = '../images/orange-3_20.png';
            }
            else if (ignstatus == '1') {
                mapIcon = '../images/purple-3_20.png';
            }
        }
        else if (heading > 370 && id != 'current') {
            mapIcon = '../images/greendot_16.gif';
        }
        //        else {
        //            mapIcon = '../images/1.png';
        //        }
        //        mapIcon.shadowSize = new GSize(1, 1);
        //        mapIcon.iconAnchor = new GPoint(12, 12);
        //        mapIcon.infoWindowAnchor = new GPoint(12, 5);

        if (id == 'current') {
            //            mapIcon.iconSize = new GSize(32, 32);
            mapIcon = '../images/down.png';
            //            mapIcon.shadowSize = new GSize(1, 1);
            //            mapIcon.iconAnchor = new GPoint(12, 12);
            //            mapIcon.infoWindowAnchor = new GPoint(25, 5);
        }

        //        if (mapIcon == null || mapIcon == '') {
        //            mapIcon = '../images/1.png';
        //        }

        if (id == 'MapIt' || id == 'current') {
            // TO set Z-index for Marker

            if (mapIcon != null || mapIcon != '') {
                marker = new jsapi.map.Marker(
                point, {
                    draggable: false,
                    icon: mapIcon

                });
            }
            //offset the top left icon corner so that it's centered above the coordinate
            //            marker = new google.maps.Marker(point, { draggable: false, icon: mapIcon,
            //                zIndexProcess: function(m) {
            //                    return 28800001;
            //                }
            //            });
        }
        else {
            //            marker = new GMarker(point, { draggable: false, icon: icon, zIndexProcess: 1 });
            if (mapIcon != null || mapIcon != '') {
                marker = new jsapi.map.Marker(
                point, {
                    draggable: false,
                    icon: mapIcon,
                    zIndexProcess: function(m) {
                        return 28800001;
                    }
                });
            }
        }

        var temp1 = "'" + point + "'";
        var temp = temp1.substring(2, temp1.length - 2);
        temp = "'" + point.latitude + "," + point.longitude + "'";
        var infoBubbleMessage = (!isSpeedVisible ? FrameMessage(mainCaption, isMessageVisbile, msgCaption, msgdetails,
        isDateTimeVisible, datetimeCaption, time, isAddressVisible, addressCaption, addr, isLandmarkVisible,
        landmarkCaption, landmark, isSpeedVisible, speedCaption, speed, addLandmarkCaption,
        (document.getElementById('hdnAddLandmark').value == "No" || landmark != "-") ? false : true, temp) : '');

        var tabs = (isSpeedVisible ? CreateTabs(mainCaption, isMessageVisbile, msgCaption, msgdetails,
        isDateTimeVisible, datetimeCaption, time, isAddressVisible, addressCaption, addr, isLandmarkVisible,
        landmarkCaption, landmark, isSpeedVisible, speedCaption, speed, addLandmarkCaption,
        (document.getElementById('hdnAddLandmark').value == "No" || landmark != "-") ? false : true, temp) : null);
        // Add tabs to the InfowWindow
        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, "mouseover", function() { if (isSpeedVisible) { marker.openInfoWindowTabsHtml(tabs); } else { marker.openInfoWindowHtml(infoBubbleMessage); } });      //  (BreakTime(marker)));
        //        if (id == 'current') {
        //            var contentString = '<div id="tabs">' + '<ul>' + '<li><a href="#fragment-1"><span>One</span></a></li>' +
        //            '<li><a href="#fragment-2"><span>Two</span></a></li>' + '<li><a href="#fragment-3"><span>Three</span></a></li>' +
        //            '</ul>' + '<div id="fragment-1">' + '<p>Tab 1</p>' + '</div>' + '<div id="fragment-2">' + '<p>Tab 2</p>' +
        //            '</div>' + '<div id="fragment-3">' + '<p>Tab 3</p>' + '</div>' + '</div>';
        //            GEvent.addListener(marker, "mouseover", function() { marker.openInfoWindowHtml(contentString); });
        //        }

        //Info Bubble
        //        var OpenBubble = function(evt) {
        //            //var element = 
        //            infoBubble.addBubble(bubbleMessage, point);
        //            //map.objects.add(infoMarkers[element.id] = marker);
        //        }
        //        var CloseBubble = function(evt) {
        //            //var element = 
        //            infoBubble.addBubble(bubbleMessage, point);
        //            //map.objects.add(infoMarkers[element.id] = marker);
        //        }
        //        var myListener = {
        //            "click": [OpenBubble, true, null],
        //            "mouseover": [OpenBubble, true, null],
        //            "mouseout": [CloseBubble, true, null]
        //        };
        //        var marker = new jsapi.map.Marker(
        //            point, {
        //                title: "marker",
        //                visibility: true,
        //                icon: icon,
        //                eventListener: myListener
        //                //offset the top left icon corner so that it's centered above the coordinate
        //                ///anchor: new jsapi.util.Point(35, 17)
        //            });
    }
    catch (Error) {
    }
    return marker;
}
function CreateTabs(mainCaption, isMessageVisbile, msgCaption, msgdetails, isDateTimeVisible, datetimeCaption,
time, isAddressVisible, addressCaption, address, isLandmarkVisible, landmarkCaption, landmarkName, isSpeedVisible,
 speedCaption, speed, addLandmarkCaption, canAddLandmark, temp) {
    var tabs = [];
    var tabMessage = '<table style="direction:' + VDirection + '" cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'>'; //<tr><td colspan="2"><u><b>' + mainCaption
    //+ '</b></u></td></tr>';
    if (isMessageVisbile) {
        tabMessage += '<tr><td width="45px">' + '<b>' + msgCaption + '</b></td><td>' + msgdetails
            + '</td></tr>';
    }
    if (isDateTimeVisible) {
        tabMessage += '<tr><td width="60px" ><b>' + datetimeCaption + '</b></td><td>' + time + '</td></tr>';
    }
    if (isAddressVisible) {
        tabMessage += '<tr><td><b>' + addressCaption + '</b></td><td>' + address + '</td></tr>';
    }
    tabMessage += '</table>';

    tabs.push(new GInfoWindowTab(VDetails, tabMessage));

    tabMessage = '<table style="direction:' + VDirection + '" cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'>';
    if (isSpeedVisible) {
        tabMessage += '<tr><td><b>' + speedCaption + '</b></td><td>' + speed + '</td></tr>';
    }
    if (isLandmarkVisible) {
        tabMessage += '<tr><td width="40px"><b>' + landmarkCaption + '</b></td><td>' + landmarkName + '</td></tr>';
    }
    if (canAddLandmark) {
        tabMessage += '<tr><td colspan="2"><a href="javascript:getlngs(' + temp + ',\'' + address + '\');' +
        'document.getElementById(\'txtLocationName\').focus();">' + addLandmarkCaption + '<\/a></td></tr>';
    }
    tabs.push(new GInfoWindowTab(VOtherinfo, tabMessage));
    return tabs;
}
function BreakTime(marker) {
    //alert();
    marker.openInfoWindowHtml('infoBubbleMessage');
}

function FrameMessage(mainCaption, isMessageVisbile, msgCaption, msgdetails, isDateTimeVisible, datetimeCaption,
time, isAddressVisible, addressCaption, address, isLandmarkVisible, landmarkCaption, landmarkName, isSpeedVisible,
 speedCaption, speed, addLandmarkCaption, canAddLandmark, temp) {
    var bubbleMessage = '<table style="direction:' + VDirection + '" cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'><tr><td colspan="2"><u><b>' + mainCaption
        + '</b></u></td></tr>';
    if (isMessageVisbile) {
        bubbleMessage += '<tr><td width="25px">' + '<b>' + msgCaption + '</b></td><td>' + msgdetails
    + '</td></tr>';
    }
    if (isDateTimeVisible) {
        bubbleMessage += '<tr><td><b>' + datetimeCaption + '</b></td><td>' + time + '</td></tr>';
    }
    if (isAddressVisible) {
        bubbleMessage += '<tr><td><b>' + addressCaption + '</b></td><td>' + address + '</td></tr>';
    }
    if (isLandmarkVisible) {
        bubbleMessage += '<tr><td width="40px"><b>' + landmarkCaption + '</b></td><td>' + landmarkName + '</td></tr>';
    }
    if (isSpeedVisible) {
        bubbleMessage += '<tr><td><b>' + speedCaption + '</b></td><td>' + speed + '</td></tr>';
    }
    if (canAddLandmark) {
        bubbleMessage += '<tr><td colspan="2"><a href="javascript:getlngs(' + temp + ',\'' + address + '\');' +
        'document.getElementById(\'txtLocationName\').focus();">' + addLandmarkCaption + '<\/a></td></tr>';
    }
    bubbleMessage += '</table>';
    return bubbleMessage
}

function MapIT_Marker(point, heading, speed, VehName, id, i_No, addr, dist, msgDetails, mainHeading, isVehicleVisbile, vehCaption, isMessageVisbile, msgCaption, isAddressVisbile, addrCaption, isSpeedVisbile, speedCaption,
                        isLandmarkVisible, landmarkCaption, landmarkName, canAddLandmark, isDriverNameVisible, driverNameCaption, 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;
    //        }
    //    });

    var bubbleMessage = '<table style="direction:' + VDirection + '" cellspacing=5 class=\'InfoBubble\'>';
    //<tr><td colspan="2"><u><b>' + ((mainHeading == null || mainHeading == '') ? 'Vehicle Statistics' : mainHeading) + '</b></u></td></tr>';

    var monitorTabs = [];

    if (isVehicleVisbile) {
        bubbleMessage += '<tr><td><b>' + ((vehCaption == null || vehCaption == '') ? 'Vehicle' : vehCaption) + '</b></td><td>' + VehName + '</td>';
        if (isDriverNameVisible) {
            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>';
    }
    if (isDriverNameVisible) {
        bubbleMessage += '<tr><td><b>' + ((driverNameCaption == null || driverNameCaption == '') ? 'Driver' : driverNameCaption) + '</b></td><td>' + ((driverName == null || driverName == '') ? '-' : driverName) + '</td></tr>';
        bubbleMessage += '<tr><td><b>' + ((PhnoCaption == null || PhnoCaption == '') ? 'Phno' : PhnoCaption) + '</b></td><td>' + driverPhno + '</td></tr>';
    }
    if (hd != null && hd[0] != undefined && hd[0] == 'A' && isVehicleVisbile == true) {
        bubbleMessage += '<tr><td><b>' + VDateTime + '</b></td><td>' + hd[1] + '</td></tr>';
    }
    if (isMessageVisbile) {
        bubbleMessage += '<tr><td><b>' + ((msgCaption == null || msgCaption == '') ? VMessage : msgCaption) + '</b></td><td>' + msgDetails + '</td></tr>';
    }
    if (isAddressVisbile) {
        bubbleMessage += '<tr><td><b>' + ((addrCaption == null || addrCaption == '') ? VAddress : addrCaption) + '</b></td><td>' + addr + '</td></tr>';
    }

    bubbleMessage += '</table>';

    //monitorTabs.push(new GInfoWindowTab(VDetails, bubbleMessage));
    //    var isSpeedVisbile = true;
    //    var isLandmarkVisible = true;
    //    var canAddLandmark = true;
    //    
    //    var tabMessage = '<table cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'>';
    //    if (isSpeedVisbile) {
    //        tabMessage += '<tr><td><b>' + speedCaption + '</b></td><td>' + speed + '</td></tr>';
    //        }
    var tabMessage = '<table style="direction:' + VDirection + '" cellpadding=\'5\' class=\'InfoBubble\' cellspacing=\'5\'>';
    if (isSpeedVisbile) {
        tabMessage += '<tr><td><b>' + ((speedCaption == null || speedCaption == '') ? 'Speed' : speedCaption) + '</b></td><td>' + speed + '</td></tr>';
    }
    if (landmarkName != '-') {
        tabMessage += '<tr><td width="40px"><b>' + landmarkCaption + '</b></td><td>' + landmarkName + '</td></tr>';
    }
    else {
        tabMessage += '<tr><td colspan="2"><a href="javascript:getlngs(' + temp + ',\'' + addr + '\');' +
        'document.getElementById(\'txtLocationName\').focus();">' + canAddLandmark + '<\/a></td></tr>';
    }
    //monitorTabs.push(new GInfoWindowTab(VOtherinfo, tabMessage));
    var clicks = function(evt) {
        infoBubble.addBubble(bubbleMessage + tabMessage, point);
    }
    var myListener = {
        "click": [clicks, true, null]
    };
    var marker = new jsapi.map.Marker(
            point, {
                title: "marker",
                visibility: true,
                icon: icon,
                eventListener: myListener
                //offset the top left icon corner so that it's centered above the coordinate
                ///anchor: new jsapi.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;
}

var ltMapIT = new Array();
var mapPoints = null;  //new GLatLngBounds();
//To plot the Map for MapIT
function DisplayMapIt(latlng, pageName, mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible,
    datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption, isSpeedVisible,
    speedCaption, addLandmarkCaption, isVehicleVisbile, vehicleCaption, isPolylineVisible, driverNameCaption, isDriverNameVisible) {
    try {
        if (mapItMarkers == null) {
            mapItMarkers = new Array();
        }
        else {
            for (var j = 0; j < mapItMarkers.length; j++) {
                //map.removeOverlay(mapItMarkers[j]);
                map.objects.remove(mapItMarkers[j]);
            }
            mapItMarkers = new Array();
        }
        var mapTypeHolder = document.getElementById("hdnMapType");
        if (mapTypeHolder != null) {
            switch (mapTypeHolder.value) {
                case 'N': map.set("baseMapType", map.NORMAL); break;
                case 'S': map.set("baseMapType", map.SATELLITE); break;
                case 'H': map.set("baseMapType", map.HYBRID); break;
            }
        }
        if (pageName == 'H') {
            //            DisplayLocation(history_latlng, 'H');
            PerformScrollSetting();
            CheckMapItBoxes();
            SetDivPosition()
        }

        var bounds = new Array(); // new GLatLngBounds();

        //if (GBrowserIsCompatible()) {
        //            collectdata = new GLatLngBounds();
        ltMapIT = latlng.split('~&~');
        if (pageName == 'M') {
            //map.clearOverlays();
        }
        for (var i = 0; i <= ltMapIT.length - 1; i++) {
            if (ltMapIT[i] == "") {
                break;
            }
            var lng = new Array();
            lng = ltMapIT[i].split("~#~");
            //var marker = new GMarker(new GLatLng(lng[0], lng[1]));
            var point = new jsapi.geo.Coordinate(parseFloat(lng[0]), parseFloat(lng[1]));
            lntlngs.push(point);
            if (pageName == 'M') {
                var mapMarker = MapIT_Marker(point, lng[4], lng[3], lng[5], lng[6], i, lng[2], lng[2],
                                  lng[7], mainCaption, isVehicleVisbile, vehicleCaption, isMessageVisbile, msgCaption, isAddressVisible, addressCaption, isSpeedVisible, speedCaption,
                                  isLandmarkVisible, landmarkCaption, lng[8], addLandmarkCaption, isDriverNameVisible, driverNameCaption, lng[9], lng[10], lng[11], lng[12]);
                bounds.push(mapMarker);
                //map.addOverlay(mapMarker);
                //clusterMarkers.push(mapMarker);
                //clusterer.AddMarker(mapMarker, '');
                //mapPoints.extend(new GLatLng(point));

            }
            else if (pageName == 'H') {
                var mapMarker = createMarker(point, lng[5], lng[3], lng[4], 'MapIt', i, lng[2], lng[6],
                    lng[7], lng[8], lng[9], mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible,
                    datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption,
                     isSpeedVisible, speedCaption, addLandmarkCaption);
                Array.add(mapItMarkers, mapMarker);
                //map.addOverlay(mapMarker);
                map.objects.add(mapMarker);
            }
            else if (pageName == 'HF') {
                var mapMarker = createMarker(point, lng[5], lng[3], lng[4], '1', i, lng[2], lng[6],
                    lng[7], lng[8], lng[9], mainCaption, isMessageVisbile, msgCaption, isDateTimeVisible,
                    datetimeCaption, isAddressVisible, addressCaption, isLandmarkVisible, landmarkCaption,
                     isSpeedVisible, speedCaption, addLandmarkCaption);
                Array.add(mapItMarkers, mapMarker);
                map.addOverlay(mapMarker);
            }

            //bounds.extend(point);
        }
        //var markerCluster = new MarkerClusterer(map, clusterMarkers);
        map.zoomTo(mapMarker.getBoundingBox(), false);
        if (map.zoomLevel > 11) map.set("zoomLevel", 11); //zoom out if too close
        //map.setCenter(bounds.center, map.getBoundsZoomLevel(bounds));
        //map.setZoom(map.getBoundsZoomLevel(mapPoints));
        //map.setCenter(bounds.getCenter());

        HidePopUp();
        //}
    }
    catch (Error) {
    }
}

//To plot the Map for MapIT
function DisplayUpdPosition(latlng) {
    try {
        if (GBrowserIsCompatible()) {
            collectdata = new GLatLngBounds();
            lt = latlng.split('&');

            for (var i = 0; i < lt.length; i++) {
                var lng = new Array();
                lng = lt[i].split("~#~");
                var marker = new GMarker(new GLatLng(lng[0], lng[1]));
                var point = new GLatLng(lng[0], lng[1]);
                map.setCenter(new GLatLng(lng[0], lng[1]), 12);

                map.addOverlay(MapIT_Marker(point, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''));
                collectdata.extend(new GLatLng(lng[0], lng[1]));
            }
            map.setCenter(collectdata.getCenter(), map.getBoundsZoomLevel(collectdata) - 1);
        }
    }
    catch (Error) {
    }
}

function getlngs(query, lndaddress) {
    try {
        var isIE = CheckBrowser();
        //document.getElementById('hdnInput').value = query;
        var lnd_Latlong = query.split(',');
        document.getElementById('txtlat').value = lnd_Latlong[0];
        document.getElementById('txtlong').value = lnd_Latlong[1];
        document.getElementById('txtstreet').value = lndaddress;
        document.getElementById('txtstreet').disabled = true;
        document.getElementById('pnlLandmark').style.display = "block";
    } catch (Error) {
    }
}

/* Functions related to Landmark Page */
var geo;
var reasons = [];
var getAddress = null;
var geocoder; var address;
var bubble = null;
var bubbleTemplate;

var isIE = CheckBrowser();

function CheckBrowser() {
    var isIE = false;
    if (navigator.appName == "Microsoft Internet Explorer") {
        isIE = true;
    }
    else {
        isIE = false;
    }
    return isIE;
}
// ====== Plot a marker after positive reponse to "did you mean" ======
function place(lat, lng) {
    try {

        var icon = LandMarkImage; //new GIcon(G_DEFAULT_ICON);
        //        icon = new GIcon(icon, LandMarkImage);
        //        icon.iconSize = new GSize(32, 32);
        var point = new jsapi.geo.Coordinate(parseFloat(lat), parseFloat(lng));
        map.setCenter = point;

        //Add info bubble Template.
        bubbleTemplate = '<br /><table style="direction:' + VDirection + '" class=\'InfoBubble\'cellpadding=\'5\' cellspacing=\'5\'><tr><td><b>Address</b></td><td>:</td><td>' + search + '</td></tr></table>';

        //Event to open bubble template
        var OpenBubble = function(evt) {
            var coordinate = map.pixelToGeo(evt.displayX, evt.displayY);
            bubble = infoBubble.addBubble(bubbleTemplate, coordinate);
        }
        //Event to close bubble template
        var CloseBubble = function(evt) {
            infoBubble.removeBubble(bubble);
        }
        //Event Listener
        var myListener = {
            "mouseover": [OpenBubble, true, null],
            "mouseout": [CloseBubble, true, null]
        };

        //Set marker to a variable.
        var marker = new jsapi.map.Marker(point, {
            draggable: false,  //the marker is marked to be draggable
            icon: icon,
            eventListener: myListener
            //anchor: new jsapi.util.Point(35,17)
        });
        //Add marker to the map.
        map.objects.add(marker);
        //Zoom to the result.
        map.zoomTo(marker.getBoundingBox());
        //Zoom out if to close.
        if (map.zoomLevel > 15) map.set("zoomLevel", 15);

        //        GEvent.addListener(marker, "mouseover", function() {
        //            marker.openInfoWindowHtml('<br /><table style="direction:' + VDirection + '" class=\'InfoBubble\'cellpadding=\'5\' cellspacing=\'5\'><tr><td><b>Address</b></td><td>:</td><td>' + search + '</td></tr></table>');
        //        });

        var LocDesc = (document.getElementById('txtLocationDesc').value == "Description") ? "" : document.getElementById('txtLocationDesc').value;
        var Radius = (document.getElementById('txtRadius').value == "Radius") ? 500 : document.getElementById('txtRadius').value;
        getAddress = document.getElementById('txtLocationName').value + '#' + lat + '#' + lng + '#' + LocDesc + '#' + search + '#' + Radius + '#' /*+ document.getElementById('txtEmail').value + '#' + document.getElementById('txtSMS').value + '#'*/ + (document.getElementById('chkNotify').checked ? 1 : 0) + '#0';  /* + document.getElementById('ddlTimezone').value; */
        //        map.enableScrollWheelZoom();
        //        map.enableContinuousZoom();
        document.getElementById('txtlat').value = lat;
        document.getElementById('txtlong').value = lng;
        centerPoint = new jsapi.geo.Coordinate(parseFloat(lat), parseFloat(lng));
        document.getElementById("message").innerHTML = "";
        document.getElementById("pnlInfoWindow").style.display = "none";
        //        $find('ModalPopupExtender1').hide();
        drawCircle();
    } catch (Error) {
    }
}


function Findplace(lat, lng, lndMark, addr, radius, isView, image) {
    try {
        getAddress = null;
        if (image == null) {
            image = '../images/poi_viewer_house.gif';
        }
        if (LandMarkImage == null || LandMarkImage == '')
            LandMarkImage = image;
        var icon = LandMarkImage; //new GIcon(G_DEFAULT_ICON);
        //map = new GMap(document.getElementById("map-dsply"));
        map.objects.clear();
        //icon = new GIcon(icon, LandMarkImage);
        //icon.iconSize = new GSize(32, 32);
        var point = new jsapi.geo.Coordinate(parseFloat(lat), parseFloat(lng));
        map.setCenter = point;


        //Event to open bubble template
        var OpenBubble = function(evt) {
            var coordinate = map.pixelToGeo(evt.displayX, evt.displayY);
            bubble = infoBubble.addBubble(bubbleTemplate, coordinate);
        }

        //Event to close bubble template
        var CloseBubble = function(evt) {
            infoBubble.removeBubble(bubble);
        }

        //Event Listener
        var myListener = {
            "mouseover": [OpenBubble, true, null],
            "mouseout": [CloseBubble, true, null]
        };

        //Set marker to a variable.
        var marker = new jsapi.map.Marker(point, {
            draggable: false,  //the marker is marked to be draggable
            icon: icon,
            eventListener: myListener
            //anchor: new jsapi.util.Point(35,17)
        });
        //var marker = new GMarker(point, { draggable: false, icon: icon });
        map.objects.add(marker);
        map.zoomTo(marker.getBoundingBox());
        if (map.zoomLevel > 13) map.set("zoomLevel", 13); //Zoom Out if too close.

        if (lndMark == '') {
            var LocDesc = (document.getElementById('txtLocationDesc').value == "Description") ? "" : document.getElementById('txtLocationDesc').value;
            var Radius = (document.getElementById('txtRadius').value == "Radius") ? 500 : document.getElementById('txtRadius').value;

            getAddress = document.getElementById('txtLocationName').value + '#' + lat + '#' + lng + '#' + LocDesc + '#' + search + '#' + Radius + '#' + /*document.getElementById('txtEmail').value + '#' + document.getElementById('txtSMS').value + '#'*/+(document.getElementById('chkNotify').checked ? 1 : 0) + '#0';  /*+ document.getElementById('ddlTimezone').value; */
            document.getElementById('txtlat').value = lat;
            document.getElementById('txtlong').value = lng;

            //info Bubble Template frame.
            bubbleTemplate = '<br /><table cellpadding=\'5\' class=\'InfoBubble\'cellspacing=\'5\'><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + search + '</td></tr></table>';

            //            GEvent.addListener(marker, "mouseover", function() {
            //                marker.openInfoWindowHtml('<br /><table cellpadding=\'5\' class=\'InfoBubble\'cellspacing=\'5\'><tr><td><b>' + VAddress + '</b></td><td>:</td><td>' + search + '</td></tr></table>');
            //            });

            //            GEvent.addListener(marker, "mouseout", function() { marker.closeInfoWindow(marker); });
        }
        else {
            //document.getElementById('txtlat').value = '';
            //document.getElementById('txtlong').value = '';

            bubbleTemplate = '<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>';

            //            GEvent.addListener(marker, "mouseover", function() {
            //                //marker.openInfoWindowHtml();
            //            });

            //GEvent.addListener(marker, "mouseout", function() { marker.closeInfoWindow(marker); });
        }

        centerPoint = new jsapi.geo.Coordinate(parseFloat(lat), parseFloat(lng));
        document.getElementById("message").innerHTML = "";
        //$find('ModalPopupExtender1').hide();

        //        if (isView == 1) {
        //            document.getElementById('txtRadius').value = radius;
        //        }
        drawCircle();
        //        if (isView == 1)
        //        { document.getElementById('txtRadius').value = ''; }
    }
    catch (Error) {
    }
    //    map.enableScrollWheelZoom();
    //    map.enableContinuousZoom();
}


var search = '';
var chkValue = 0;
var LandMarkImage = '';

var searchManager = new jsapi.advsearch.Manager();
var revGeocodeTerm;
var searchTerm;
// ====== Geocoding ======
function showAddress(IsNew, image) {
    try {
        if (image == null || image == '') {
            if (document.getElementById('hdnLandmarkImage') != null) {

                image = String(document.getElementById('hdnLandmarkImage').value);

            }
            else {
                image = '../images/poi_viewer_house.gif';
            }
        }
        LandMarkImage = image;
        getAddress = null;
        chkValue = 1;
        document.getElementById('hdnIsLocateMe').value = 'Y';
        //if (GBrowserIsCompatible()) {
        map.objects.clear();  //clearOverlays();
        if (document.getElementById('ddlType').value == 'addr') {
            search = FrameAddress();
            //geo = new GClientGeocoder();

            //Set the Advance Search manager to the variable
            geo = new jsapi.advsearch.Manager();


            //======= GeCode Callback function ======
            geo.addObserver("state", function(observedManager, key, value) {
                if (value == "finished") {
                    if (observedManager.locations.length > 0) {
                        // ===== If there was more than one result, "ask did you mean" on them all =====
                        if (observedManager.matchQuality == 3) {

                        }
                        if (observedManager.locations.length > 1) {
                            document.getElementById("message").innerHTML = "Did you mean:";
                            // Loop through the results
                            for (var i = 0; i < observedManager.locations.length; i++) {
                                var p = observedManager.getLocations()[i].displayPosition;

                                document.getElementById("message").innerHTML += "<br>" + (i + 1) + ": <a href='#' onclick='place(" + p.latitude + "," + p.longitude + "); return false;'>" + FormAddressList(observedManager.getLocations()[i]) + "<\/a>";

                            }
                            document.getElementById("pnlInfoWindow").style.display = "block";
                        }
                        else {

                            document.getElementById("message").innerHTML = "";
                            var p = observedManager.getLocations()[0].displayPosition;

                            if (document.getElementById('hdnLatLong') != null) {
                                document.getElementById('hdnLatLong').value = p.latitude + ',' + p.longitude;
                            }
                            //                            if (result.Placemark[0].AddressDetails.Accuracy < 6) {
                            //                                alert('Unable to find the address. Please verify the location');
                            //                            }
                            //else if(isNew == '1') {
                            Findplace(p.latitude, p.longitude, '', document.getElementById('txtRadius').value, 0);

                            //                            var rs = (new jsapi.search.component
                            //                                              .SearchResultSet(observedManager.locations)).container;
                            //                            map.objects.add(rs); //push marker(s) to map
                            //                            map.zoomTo(rs.getBoundingBox());
                            //                            map.set("zoomLevel", 15); //zoom to result(s)
                            //                            if (map.zoomLevel > 16) map.set("zoomLevel", 16); //zoom out if too close
                        }
                    }
                }
                else if (value == "failed") {
                    var reason = "Code " + result.Status.code;
                    //if (reasons[result.Status.code]) { reason = reasons[result.Status.code] }
                    //alert('Could not find "' + search + '" ' + reason);
                    TrinetraCustomAlerts('Could not find "' + search + '" ');
                    loadForLandMark();
                    //alert("Unable to find the address. Please verify the location");
                }
            });

            // ====== Perform the Geocoding ======
            searchTerm = {//geocode
                searchText: search,
                spatialFilter: {
                    radius: 8000
                },
                representationOptions: {
                    language: ["en-US"],
                    maxResults: 20,
                    pageInformation: 1,
                    //possible SearchResponseAttribute switches: 
                    //"perfomedSearch(ps)", "label(la)", "didYouMeanSuggestion(dm)", "matchQuality(mq)", "matchType(mt)"
                    //request label, didYouMeanSuggestion, matchType and skip matchQuality
                    searchResponseAttributes: ["la", "dm", "mq", "mt"],
                    //possible LocationAttribute switches:
                    //"address(ar)", "mapReference(mr)", "mapView(mv)", "additionalData(ad)", "alternativeLabels(al)"
                    //request address, mapReference, mapView, additionalData and alternativeLabels
                    locationAttributes: ["ar", "mr", "mv", "ad", "al"],
                    //possible AddressAttribute switches:
                    //"country(ctr)", "state(sta)", "county(cty)", "city(cit)", "district(dis)", "street(str)", 
                    //"houseNumber(hnr)", "postalCode(pst)", "suite(sui)", "floor(flr)", "additionalAttributes(add)", "alternativeAttributes(alt)"
                    //request state, city, street, houseNumber, postalCode, suite, floor, and skip county and district
                    addressAttributes: ["sta", "-cty", "cit", "dis", "str", "hnr", "pst", "sui", "flr", "add"]
                },
                metaInfo: {
                    requestId: "qwertzuiop",
                    //Level of verbose information which will be included in the response structure. 
                    //Can be a value between 0 and 5.
                    verboseMode: 2
                }
            };
            geo.clear();
            geo.geocode(search);


            //            geo.getLocations(search, function(result) {
            //                //map.clearOverlays();
            //                map = new GMap(document.getElementById("map-dsply"));
            //                if (result.Status.code == G_GEO_SUCCESS) {
            //                    // ===== If there was more than one result, "ask did you mean" on them all =====
            //                    if (result.Placemark.length > 1) {
            //                        document.getElementById("message").innerHTML = "Did you mean:";
            //                        // Loop through the results
            //                        for (var i = 0; i < result.Placemark.length; i++) {
            //                            var p = result.Placemark[i].Point.coordinates;

            //                            document.getElementById("message").innerHTML += "<br>" + (i + 1) + ": <a href='#' onclick='place(" + p[1] + "," + p[0] + "); return false;'>" + result.Placemark[i].address + "<\/a>";

            //                        }
            //                        //                            $find('ModalPopupExtender1').show();
            //                        document.getElementById("pnlInfoWindow").style.display = "block";
            //                    }
            //                    // ===== If there was a single marker =====
            //                    else {
            //                        document.getElementById("message").innerHTML = "";
            //                        var p = result.Placemark[0].Point.coordinates;

            //                        if (document.getElementById('hdnLatLong') != null) {
            //                            document.getElementById('hdnLatLong').value = p[1] + ',' + p[0];
            //                        }
            //                        if (result.Placemark[0].AddressDetails.Accuracy < 6) {
            //                            alert('Unable to find the address. Please verify the location');
            //                        }
            //                        //else if(isNew == '1') {
            //                        Findplace(p[1], p[0], '', document.getElementById('txtRadius').value, 0);
            //                        //}
            //                    }
            //                }
            //                // ====== Decode the error status ======
            //                else {
            //                    var reason = "Code " + result.Status.code;
            //                    if (reasons[result.Status.code]) { reason = reasons[result.Status.code] }
            //                    //alert('Could not find "' + search + '" ' + reason);
            //                    alert('Could not find "' + search + '" ');
            //                    loadForLandMark();
            //                }
            //            }
            //        );
        }
        //}
        else {

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

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

            centerPoint = new jsapi.geo.Coordinate(parseFloat(document.getElementById('txtlat').value), parseFloat(document.getElementById('txtlong').value));
            //map.setCenter(centerPoint, 16);
            map.setCenter = centerPoint;

            //Search Process for Reverse geoCode.
            var bubble = null;
            var bubbleTemplate;
            var OpenBubble = function(evt) {
                var coordinate = map.pixelToGeo(evt.displayX, evt.displayY);
                bubble = infoBubble.addBubble(bubbleTemplate, coordinate);
            }
            var CloseBubble = function(evt) {
                infoBubble.removeBubble(bubble);
            }

            var DragEnd = function(evt) {
                var coord = map.pixelToGeo(evt.displayX, evt.displayY);
                document.getElementById('txtlat').value = coord.latitude;
                document.getElementById('txtlong').value = coord.longitude;
                point = coord;
            }

            var myListener = {
                "mouseover": [OpenBubble, true, null],
                "mouseout": [CloseBubble, true, null],
                "dragend": [DragEnd, true, null],
                "dragstart": [CloseBubble, true, null]
            };

            //Search Callback function.
            searchManager.addObserver("state", function(observedManager, key, value) {
                if (value == "finished") {
                    if (observedManager.locations.length > 0) {
                        var strAddress = observedManager.getLocations()[0].address.street + ',' + observedManager.getLocations()[0].address.city + ',' + observedManager.getLocations()[0].address.state + ',' + observedManager.getLocations()[0].address.additionalData.CountryName;


                        bubbleTemplate = '<table style="direction:' + VDirection + '" class=\'InfoBubble\' cellpadding=\'5\' cellspacing=\'2\'><tr><td colspan=3><b><u>Landmark Location Details</u></b></td><tr><td><b>Original Coordinates</b></td><td>:</td><td>'
                                    + observedManager.getLocations()[0].displayPosition.latitude + " , " + observedManager.getLocations()[0].displayPosition.longitude
            + '</td></tr><tr><td><b>Address</b></td><td>:</td><td>' + strAddress + '</td></tr></table>';

                        var te = map.geoToPixel(coord);
                        //var offset = map.getDisplayOffset(coord, te.x, te.y)
                        if (marker) map.objects.remove(marker);
                        marker = new jsapi.map.Marker(coord, {
                            draggable: true,  //the marker is marked to be draggable
                            icon: image,
                            eventListener: myListener
                            //anchor: new jsapi.util.Point(35,17)
                        });
                        map.objects.add(marker);
                        var LocDesc = (document.getElementById('txtLocationDesc').value == "Description") ? "" : document.getElementById('txtLocationDesc').value;
                        var Radius = (document.getElementById('txtRadius').value == "Radius") ? 500 : document.getElementById('txtRadius').value;

                        getAddress = document.getElementById('txtLocationName').value + '#' + centerPoint.longitude + '#' + centerPoint.latitude + '#' + LocDesc + '#' + strAddress + '#' + Radius + '#' + /*document.getElementById('txtEmail').value + '#' + document.getElementById('txtSMS').value + '#' + document.getElementById('ddlSeverity').value */(document.getElementById('chkNotify').checked ? 1 : 0) + '#0';  /* + document.getElementById('ddlTimezone').value; */
                        document.getElementById('txtstreet').value = strAddress;

                        //Set the center point value.
                        centerPoint = new jsapi.geo.Coordinate(parseFloat(document.getElementById('txtlat').value), parseFloat(document.getElementById('txtlong').value))

                        //Draw circle around the Landmark.
                        drawCircle();
                        map.zoomTo(marker.getBoundingBox(), false);

                        //zoom out if too close
                        if (map.zoomLevel > 15) map.set("zoomLevel", 15);
                    }
                } else if (value == "failed") {
                    TrinetraCustomAlerts("Address Cannot be found. Please check the LatLong Values ");
                }
            });

            landmarkLatitude = document.getElementById('txtlat').value;
            landmarkLongitude = document.getElementById('txtlong').value;
            var coord = new jsapi.geo.Coordinate(parseFloat(document.getElementById('txtlat').value), parseFloat(document.getElementById('txtlong').value))

            //Set attributes for the search term.
            revGeocodeTerm = {//reverse geocode
                spatialFilter: {
                    center: coord,
                    radius: 8000
                },
                representationOptions: {
                    language: ["en-US"],
                    maxResults: 5,
                    pageInformation: 2,
                    searchResponseAttributes: ["la", "dm", "mq", "mt"],
                    locationAttributes: ["ar", "mr", "mv", "ad", "al"],
                    addressAttributes: ["ctr", "sta", "cty", "cit", "dis", "str", "hnr", "pst", "sui", "flr", "add", "alt"]
                },
                reverseGeocodeSettings: {
                    mode: "retrieveAddresses"
                },
                metaInfo: {
                    requestId: "qwertzuiop",
                    verboseMode: 2
                }
            };
            searchManager.clear();
            //make a rev geocode request
            searchManager.reverseGeocode(revGeocodeTerm);
            //var geoFinder = new GClientGeocoder();                
            //geoFinder.getLocations(latlong, showAddress_Latlng);
            showControls(1);
        }
        //}
        // display a warning if the browser was not compatible
        //else {
        //    alert("Sorry, the Google Maps API is not compatible with this browser"); 
        //}
    }
    catch (Error) {
    }
}

// Frame the List of Address to show to the user for their suggession.
function FormAddressList(observedManager) {
    var temp = '';
    temp += observedManager.address.street + ',' + observedManager.address.district + ',' + observedManager.address.city + ',' + observedManager.address.state + ',' + observedManager.address.country;
    return temp; //.substring(0, temp.lastIndexOf(","));
}


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

        if (document.getElementById('txtstreet').value != '') {
            if (address1 != '') {
                address1 = address1 + ' ' + document.getElementById('txtstreet').value;
            }
            else {
                address1 = document.getElementById('txtstreet').value;
            }
        }
        if (document.getElementById('txtcity').value != '' && document.getElementById('txtcity').value != "City") {
            if (address1 != '') {
                address1 = address1 + ',' + document.getElementById('txtcity').value;
            }
            else {
                address1 = document.getElementById('txtcity').value;
            }
        }
        if (document.getElementById('txtstate').value != '' && document.getElementById('txtstate').value != "State") {
            if (address1 != '') {
                address1 = address1 + ',' + document.getElementById('txtstate').value;
            }
            else {
                address1 = document.getElementById('txtstate').value;
            }
        }

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

function AddToDB() {
    try {
        var isError = false;
        var alertMessage = '';
        var txtLocationName = document.getElementById('txtLocationName');
        var controlToBeFocussed;
        var txtRadius = document.getElementById('txtRadius');
        var hdnLandmark = document.getElementById('hdnLand');
        if (txtLocationName.value == "Name" || RemoveSpaces(txtLocationName).length == 0) {
            alertMessage = locationNameAlert;
            isError = true;
            controlToBeFocussed = txtLocationName;
            txtLocationName.style.backgroundColor = 'lightyellow';
        }
        else {
            txtLocationName.style.backgroundColor = 'white';
        }
        if (txtRadius.value == "Radius" || RemoveSpaces(txtRadius).length == 0 || isNaN(txtRadius.value)) {
            alertMessage += (isError ? '\n' : '') + radiusAlert;
            txtRadius.style.backgroundColor = 'lightyellow';
            controlToBeFocussed = isError ? controlToBeFocussed : txtRadius;
            isError = true;
        }
        else {
            if (eval(txtRadius.value) == 0) {
                alertMessage += (isError ? '\n' : '') + radiusAlert;
                txtRadius.style.backgroundColor = 'lightyellow';
                controlToBeFocussed = isError ? controlToBeFocussed : txtRadius;
                isError = true;
            }
            else {
                txtRadius.style.backgroundColor = 'white';
            }
        }
        if (!isError) {
            if (chkValue == 0) {
                alertMessage += (isError ? '\n' : '') + locateMeError;
                controlToBeFocussed = isError ? controlToBeFocussed : document.getElementById('btnAddress');
                isError = true;
            }
        }
        if (!isError) {
            if (getAddress != null) {
                document.getElementById('hdnLand').value = getAddress;
            }
            else {
                alertMessage += (isError ? '\n' : '') + locationAlert;
                isError = true;
            }
        }
    }
    catch (Error) {
        isError = true;
    }
    if (isError) { TrinetraCustomAlerts(alertMessage); if (controlToBeFocussed != null) { controlToBeFocussed.focus(); } }
    return !isError;
}

function ReceiveServerData(arg, context) {
}

//Get Address by Map Co-ordinates
//function getAddress(overlay, latlng) {
//    if (latlng != null) {
//        address = latlng;

//        geocoder.getLocations(latlng, showAddress_Latlng);
//    }
//}

/* Function for zoom-in ,zoom-out in Context Menu */

function hideContext() {
    contextmenu.style.visibility = "hidden";
}
// === functions that perform the context menu options ===
function zoomIn() {
    // perform the requested operation
    map.zoomIn();
    // hide the context menu now that it has been used
    contextmenu.style.visibility = "hidden";
}
function zoomOut() {
    // perform the requested operation
    map.zoomOut();
    // hide the context menu now that it has been used
    contextmenu.style.visibility = "hidden";
}



/* End of Function Context Menu */
function showControls(typeid) {
    try {
        if (typeid == '0') {
            document.getElementById('spLatlng').style.display = 'none';
            document.getElementById('spAddr').style.display = (CheckBrowser() ? "block" : "table-row");
            document.getElementById('txtlat').value = '';
            document.getElementById('txtlong').value = '';
        }
        else {
            document.getElementById('ddlType').value = 'ltlng';
            document.getElementById('spLatlng').style.display = (CheckBrowser() ? "block" : "table-row");
            document.getElementById('spAddr').style.display = 'none';
        }
    }
    catch (Error) {
    }
}
function showAddress_Latlng(response) {
    if (document.getElementById('ddlType') != null) {
        showControls(document.getElementById('ddlType').selectedIndex);
    }

    var icon = new GIcon(G_DEFAULT_ICON);
    //To enable the Mouse wheel Scroll
    map.enableScrollWheelZoom();
    map.enableContinuousZoom();
    icon = new GIcon(icon, LandMarkImage);
    icon.iconSize = new GSize(32, 32);

    if (!response || response.Status.code != 200) {
        TrinetraCustomAlerts("Address Cannot be found. Please check the LatLong Values ");
    } else {
        if (response != null) {
            place = response.Placemark[0];
            marker = new GMarker(centerPoint, { draggable: true, icon: icon });

            GEvent.addListener(marker, "dragstart", function() {
                map.closeInfoWindow();
            });

            GEvent.addListener(marker, "dragend", function() {
                document.getElementById('txtlat').value = marker.getPoint().lat();
                document.getElementById('txtlong').value = marker.getPoint().lng();
                point = new GLatLng(document.getElementById('txtlat').value, document.getElementById('txtlong').value);
            });
            //marker = new GMarker(point, { draggable: true, icon: icon });
            map.addOverlay(marker);

            GEvent.addListener(marker, "mouseover", function() {
                marker.openInfoWindowHtml(
            '<table style="direction:' + VDirection + '" class=\'InfoBubble\' cellpadding=\'5\' cellspacing=\'2\'><tr><td colspan=3><b><u>Landmark Location Details</u></b></td><tr><td><b>Original Coordinates</b></td><td>:</td><td>'
            + response.name.split(",")[0] + " , " + response.name.split(",")[1]
            + '</td></tr><tr><td><b>Address</b></td><td>:</td><td>' + place.address + '</td></tr></table>');
            });

            GEvent.addListener(marker, "mouseout", function() { marker.closeInfoWindow(marker); });
        }
        var LocDesc = (document.getElementById('txtLocationDesc').value == "Description") ? "" : document.getElementById('txtLocationDesc').value;
        var Radius = (document.getElementById('txtRadius').value == "Radius") ? 500 : document.getElementById('txtRadius').value;


        getAddress = document.getElementById('txtLocationName').value + '#' + centerPoint.y + '#' + centerPoint.x + '#' + LocDesc + '#' + place.address + '#' + Radius + '#' + /*document.getElementById('txtEmail').value + '#' + document.getElementById('txtSMS').value + '#' + document.getElementById('ddlSeverity').value */(document.getElementById('chkNotify').checked ? 1 : 0) + '#0';  /* + document.getElementById('ddlTimezone').value; */

        //document.getElementById('txtlat').value = place.Point.coordinates[1];
        //document.getElementById('txtlong').value = place.Point.coordinates[0];
        document.getElementById('txtstreet').value = place.address;

        centerPoint = new GLatLng(document.getElementById('txtlat').value, document.getElementById('txtlong').value);
        drawCircle();

        //        if (isViewLatLong == 1) {
        //            document.getElementById('txtlat').value = '';
        //            document.getElementById('txtlong').value = '';
        //        }
    }
}

var landmarkLatitude = '';
var landmarkLongitude = '';
var landmarkMarkers = new Array();
var landMarkCircles = new Array();
function drawCircleForLandmark(landmarkEntries, isLandmarkEnable) {
    var lanmarkInformation = landmarkEntries.toString().split("~&~");
    canClearCircle = (isLandmarkEnable) ? false : true;
    if (!isLandmarkEnable) {
        for (var n = 0; n < landmarkMarkers.length; n++) {
            map.objects.remove(landmarkMarkers[n]);
        }
        landmarkMarkers.splice(n, 1);
        for (var c = 0; c < landMarkCircles.length; c++) {
            map.objects.remove(landMarkCircles[c]);
            //map.removeOverlay(landMarkCircles[c]);
        }
        landMarkCircles.splice(c, 1);
        //landmarkMarkers = null;
    }
    for (var iterator = 0; iterator < lanmarkInformation.length; iterator++) {
        if (lanmarkInformation[iterator] == "") {
            break;
        }
        else {
            var landmarkinfo = lanmarkInformation[iterator].split("~#~");
            centerPoint = new jsapi.geo.Coordinate(parseFloat(landmarkinfo[0]), parseFloat(landmarkinfo[1]));
            //centerPoint = new GLatLng(landmarkinfo[0], landmarkinfo[1]);
            landmarkLatitude = landmarkinfo[0];
            landmarkLongitude = landmarkinfo[1];
            var marker = new jsapi.map.Marker(centerPoint);
            //DrawCircle = marker;
            //var marker = new GMarker(new GLatLng(landmarkinfo[0], landmarkinfo[1]));
            if (isLandmarkEnable) {
                var lndMarks = flagMarker(centerPoint, landmarkinfo[3], landmarkinfo[4], landmarkinfo[0], 'green', 1)
                landmarkMarkers.push(lndMarks);
                map.objects.add(lndMarks);
            }
            circleRadius = landmarkinfo[2];
            if (isLandmarkEnable) { doDrawCircle(); }
        }
    }
    //    lat, lng, radius, lndName, lndAddr

}
function flagMarker(point, lndName, lndAddr, time, id, i_No) {

    var icon = null; //new GIcon();

    //    if (id == 'green') {
    //icon = new GIcon(icon, '../images/flag_1.png');
    icon = '../images/flag_1.png';
    //    }
    //icon.shadowSize = new GSize(1, 1);
    //icon.iconAnchor = new GPoint(12, 12);
    //icon.infoWindowAnchor = new GPoint(0, 0);
    var bubble = null;
    var OpenBubble = function(evt) {
        bubbleMessage = '<br><table style="direction:' + VDirection + '" class=\'InfoBubble\' cellspacing=\'2\'><tr><td><b>' + VLandmark + '</b></td><td><b>:</b></td></td><td>' + lndName + '</td></tr><td>'
             + '<b>' + VAddress + '</b></td><td><b>:</b></td><td>' + lndAddr + '</td></tr></table>';
        var coordinate = map.pixelToGeo(evt.displayX, evt.displayY);
        bubble = infoBubble.addBubble(bubbleMessage, coordinate);
    }
    var CloseBubble = function(evt) {
        infoBubble.removeBubble(bubble);
    }
    var myListener = {
        "click": [OpenBubble, true, null],
        "mouseover": [OpenBubble, true, null],
        "mouseout": [CloseBubble, true, null]
    };


    //    var marker = new jsapi.map.Marker(
    //            point, {
    //                title: "marker",
    //                visibility: true,
    //                icon: icon,
    //                eventListener: myListener
    //                //offset the top left icon corner so that it's centered above the coordinate
    //                ///anchor: new jsapi.util.Point(35, 17)
    //            });
    //Standard
    var marker = new jsapi.map.Marker(
    point, {
        draggable: false,
        eventListener: myListener,
        icon: icon
    });

    //var marker = new GMarker(point, { draggable: false, icon: icon });
    //    if (document.getElementById('chkMsg').checked == true) {

    //    GEvent.addListener(marker, "mouseover", function() {
    //        marker.openInfoWindowHtml(
    //        '<br><table style="direction:' + VDirection + '" class=\'InfoBubble\' cellspacing=\'2\'><tr><td><b>' + VLandmark + '</b></td><td><b>:</b></td></td><td>' + lndName + '</td></tr><td>'
    //        + '<b>' + VAddress + '</b></td><td><b>:</b></td><td>' + lndAddr + '</td></tr></table>');
    //    });
    //    GEvent.addListener(marker, "mouseout", function() { marker.closeInfoWindow(marker); });
    //    }
    return marker;
}

var circle;
var centerMarker;
var circleUnits;
var circleRadius;
//var zoom = 2;
var centerPoint; // = new GLatLng(40,-100);
//var oRadius;

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

        if (oRadius.value.match(/[^\d.]/)) {
            TrinetraCustomAlerts("Enter a number for radius");
            return;
        }
        if (oRadius.value > 9999) {
        }

        circleRadius = oRadius.value;

        doDrawCircle();
        //map.addControl(new GLargeMapControl());
        //map.addControl(new GMapTypeControl());
        //map.addControl(new GOverviewMapControl());
    }
    catch (Error) {
    }
}

function doDrawCircle() {
    try {
        if (circle && canClearCircle) {
            map.objects.remove(circle);
        }

        var center = map.center;

        //var bounds = new GLatLngBounds();


        var circlePoints = Array();

        with (Math) {
            //if (circleUnits == 'KM') {
            var d = circleRadius / 6378.8; // radians
            d = d / 1000;
            //}
            //		else { //miles
            //			var d = circleRadius/3963.189;	// radians
            //		}
            //var d = circleRadius/6378.8;	
            //            var lat1 = (PI / 180) * (!canClearCircle ? landmarkLatitude : center.lat()); // radians
            //            var lng1 = (PI / 180) * (!canClearCircle ? landmarkLongitude : center.lng()); // radians

            var lat1 = (PI / 180) * (!canClearCircle ? landmarkLatitude : center.latitude); // radians
            var lng1 = (PI / 180) * (!canClearCircle ? landmarkLongitude : center.longitude); // 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 jsapi.geo.Coordinate(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI)));
                //var point = new GLatLng(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI)));
                circlePoints.push(point);
                //bounds.extend(point);
            }

            if (d < 1.5678565720686044) {


                circle = new jsapi.map.Circle(
                            centerPoint,
                            circleRadius,
                            {
                                pen: { strokeColor: "#5270B2", lineWidth: 2 },
                                brush: { color: "#A4A7" }
                            }
                        );

                //circle = new GPolygon(circlePoints, '#5270B2'/*#000000'*/, 2, 1, '#D8E2FA', 0.25);
            }
            else {
                circle = new jsapi.map.Circle(
                            centerPoint,
                //circleRadius,
                            circleRadius,
                            {
                                pen: { strokeColor: "#5270B2", lineWidth: 2 },
                                brush: { color: canClearCircle ? '#000000' : '#A4A7' }
                            }
                        );

                //circle = new GPolygon(circlePoints, canClearCircle ? '#000000' : '#D8E2FA', 2, 1);
            }

            landMarkCircles.push(circle);
            map.objects.add(circle);
            // Included code to append Landmark & MapIT for best zoom level
            if (mapPoints != null) {
                //bounds.extend(mapPoints);
            }
            else {
                //map.setZoom(map.getBoundsZoomLevel(bounds));
            }
        }

    }
    catch (Error) {
    }
}

function plotLandMark(latlong) {
    try {
        //To Get the Address for the LatLng Values given by user
        var latlong = latlong;
        var ltlng = latlong.split(',');

        //Set attributes for the search term.
        revGeocodeTerm = {//reverse geocode
            spatialFilter: {
                center: coord,
                radius: 8000
            },
            representationOptions: {
                language: ["en-US"],
                maxResults: 5,
                pageInformation: 2,
                searchResponseAttributes: ["la", "dm", "mq", "mt"],
                locationAttributes: ["ar", "mr", "mv", "ad", "al"],
                addressAttributes: ["ctr", "sta", "cty", "cit", "dis", "str", "hnr", "pst", "sui", "flr", "add", "alt"]
            },
            reverseGeocodeSettings: {
                mode: "retrieveAddresses"
            },
            metaInfo: {
                requestId: "qwertzuiop",
                verboseMode: 2
            }
        };
        searchManager.clear();
        //make a rev geocode request
        searchManager.reverseGeocode(revGeocodeTerm);

        //        centerPoint = new GLatLng(ltlng[0], ltlng[1]);
        //        //map.setCenter(centerPoint,14);
        //        var geoFinder = new GClientGeocoder();
        //        geoFinder.getLocations(latlong, showAddress_Latlng);
    }
    catch (Error) {
    }
}

/* End of Landmark page */

//Window Functions
//window.onload = load;
//window.onunload = GUnload;

//        function silentErrorHandler() { return true; }
//        window.onerror = silentErrorHandler;

function DoCancel() {
    try {
        $find("mpAddEditLandmarkCategory").hide();
    }
    catch (Error) {
    }
}

/*********** Functions for Map It************************/
function SetMapItValue(mapItValue, isChecked, checkBoxName) {
    var mapValue = document.getElementById('hdnMapItValue').value;
    var mapItValueList = mapValue.split('~&~');
    if (isChecked) {
        if (!Array.contains(mapItValueList, mapItValue.toString().replace('~&~', ''))) {
            mapValue += mapItValue;
        }
    } else {
        if (Array.contains(mapItValueList, mapItValue.toString().replace('~&~', ''))) {
            Array.remove(mapItValueList, mapItValue.toString().replace('~&~', ''));
            mapValue = mapItValueList.join('~&~');
        }
    }
    document.getElementById('hdnMapItValue').value = mapValue;
    //    alert(document.getElementById('hdnMapItValue').value);
}
function MapIt(errorMessage, pageName) {
    if (document.getElementById('hdnMapItValue').value.length > 0) {
        ShowPopUp();
        eval("DisplayMapIt('" + document.getElementById('hdnMapItValue').value + "\',\'" + pageName + "\'," +
                document.getElementById('hdnInfoBubbleProcessing').value + ')');
    }
    else {
        TrinetraCustomAlerts(errorMessage);
    }
    return false;
}

function SelectGridRow(keyValue, isChecked) {
    gvData.SelectRowsByKey(keyValue, isChecked);
}
