﻿/// <reference path="script\maps\global.js" />
/// <reference path="script\maps\weather.js" />
/*
script.js 
Copyright (c) 2006, 2007, 2008, 2009, 2010 by US Fleet Tracking, Inc.
All rights reserved.
No part of this script may be used, altered in any way, or distributed
without the express written consent of US Fleet Tracking Corp. and its Board of Directors.
*/

//////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                      beginning of functions.
// 

function datetime() {
    var currentDate = new Date();
    var day = currentDate.getDate();
    var month = currentDate.getMonth() + 1;
    var year = currentDate.getFullYear();
    var hours = currentDate.getHours();
    var minutes = currentDate.getMinutes();
    var seconds = currentDate.getSeconds();
    var suffix = "AM";
    if (hours < 12) { suffix = "AM"; } else { suffix = "PM"; }
    if (hours == 0) { hours = 12; }
    if (hours > 12) { hours = hours - 12; }
    if (minutes < 10) { minutes = "0" + minutes; }
    if (seconds < 10) { seconds = "0" + seconds; }
    if (month < 10) { month = "0" + month; }
    if (day < 10) { day = "0" + day; }
    var returnstring = month + "." + day + "." + year + " " + hours + ":" + minutes + ":" + seconds + " " + suffix;
    return returnstring;
}

function datetimeNoYear() {
    var currentDate = new Date();
    var day = currentDate.getDate();
    var month = currentDate.getMonth() + 1;
    var hours = currentDate.getHours();
    var minutes = currentDate.getMinutes();
    var seconds = currentDate.getSeconds();
    if (hours == 0) { hours = 12; }
    if (hours < 10) { hours = "0" + hours; }
    if (minutes < 10) { minutes = "0" + minutes; }
    if (seconds < 10) { seconds = "0" + seconds; }
    if (month < 10) { month = "0" + month; }
    if (day < 10) { day = "0" + day; }
    var returnstring = month + "/" + day + " " + hours + ":" + minutes + ":" + seconds;
    return returnstring;
}

function stopError() {
    return true;
}

function startdivdrag(object) {
    return false;
    // record the object's initial location
    element = document.getElementById(object);
    dragStartX = element.style.left;
    dragStartY = element.style.top;
    dragClickStartX = event.x;
    dragClickStartY = event.y;
    dragObject = element;
    dragging = true;
    dragging = true;
    if (m_loadTimeout != null) {
        clearTimeout(m_loadTimeout);
        clearInterval(m_loadInterval);
        wereloadingmarkers = true;
    }

}

function continuedivdrag(object) {
    if (dragging == true) {
        var oldLeft = element.style.left;
        oldLeft = oldLeft.substring(0, oldLeft.length - 2);
        var changeX = event.x - dragClickStartX;
        var newX = (oldLeft * 1) + changeX;
        element.style.left = newX + "px";
        dragClickStartX = event.clientX;

        var oldTop = element.style.top;
        oldTop = oldTop.substring(0, oldTop.length - 2);
        var changeY = event.y - dragClickStartY;
        var newY = (oldTop * 1) + changeY;
        element.style.top = newY + "px";
        dragClickStartY = event.clientY;
    }
}

function stopdivdrag(object) {
    dragObject = null;
    dragging = false;
    if (wereloadingmarkers == true) {
        m_loadTimeout = setTimeout("loadMarkers('" + sessionID + "');", 4000);
        wereloadingmarkers = true;
    }
}

function enterHandler(event) {
    var keycode;
    if (window.event) {
        keycode = event.keyCode;
    }
    else if (event.which) {
        keycode = event.which;
    }
    if (keycode == 13) {
        switch (event.srcElement.id) {
            case "txtUserID":
            case "txtPassword":
                {
                    element = document.getElementById("loginCell");
                    if (whichBrs() == "safari") { event.keyCode = null; }
                    dummyUser = "";
                    dummyPwd = "";
                    logInUser();
                    if (whichBrs() == "safari") { return false; } else { return true; }
                    break;
                }
            case "TextSearch":
                {
                    element = document.getElementById("SearchCell");
                    if (element != null) {
                        MapSearch();
                        if (whichBrs() == "safari") { return false; } else { return true; }
                    }
                    break;
                }
            case "textChatOutput":
                {
                    OnlineChatSend();
                    return false;
                    break;
                }
            case "txtMessageToDriver":
                {
                    sendMessageToDriver();
                    return false;
                    break;
                }
            case "DTDtxtAddressFind":
                {
                    if (addressFind.value.indexOf(';') > -1) {
                        var tmpArray = new Array();
                        tmpArray = addressFind.value.split(';');
                        rLat = tmpArray[0];
                        rLon = tmpArray[1];
                        Feed.MpPntRvGeo(rLat, rLon, DTDlookupLatLonCallback);
                    }
                    else {
                        DTDlookupAddress();
                    }
                    return false;
                    break;
                }
            case "tbAddressSearch":
                {
                    AddressSearch();
                    return false;
                    break;
                }
            default:
                {
                    if (event.srcElement.id == "rStartLoc" || event.srcElement.id == "rEndLoc" || event.srcElement.id.substring(0, 5) == "rStop") {
                        if (whichBrs() == "safari") { event.keyCode = null; }
                        MapRouting();
                        if (whichBrs() == "safari") { return false; } else { return true; }
                        break;
                    }
                }
        }
    }
    return true;
}

function setViewType(value) {

    if (value == true) {
        element = document.getElementById("ddlGroups");
        if (element.selectedIndex == 0) {
            value = false; ;
        }
        else {
            if (element != null) {
                if (element.options.length == 0) {
                    value = false;
                }
            }
        }
    }
    else {
        element = document.getElementById("ddlVehicles");
        if (element.selectedIndex == 0) {
            value = false;
            // turn off following the device, since all devices has been selected.
            followThisVehicleOFF();
        }
        else {
            // following the device, since only one is selected.
            //vehicleToFollow = element[element.selectedIndex].value;

            setVehicleToFollow(element[element.selectedIndex].value);
        }
    }
    m_groupView = value;
    
    trigger_address_update = true;
}

function vgAddVehicleToList() {
    vehicleAddList = document.getElementById("vgVehicles");
    if (vehicleAddList != null) {
        if (vehicleAddList.selectedIndex > 0) {
            if (vehicleAddList.options[vehicleAddList.selectedIndex].value != -1) {
                vehicleGroupList = document.getElementById("vgUGroups");
                if (vehicleGroupList != null) {
                    for (i = 0; i < vehicleGroupList.length; i++) {
                        if (vehicleGroupList.options[i].value == vehicleAddList.options[vehicleAddList.selectedIndex].value) {
                            return;
                        }
                    }
                    vehicleGroupList.options[vehicleGroupList.length] = new Option(vehicleAddList.options[vehicleAddList.selectedIndex].text, vehicleAddList.options[vehicleAddList.selectedIndex].value);
                }
            }
        }
        else {
            vehicleGroupList = document.getElementById("vgUGroups");
            vehicleGroupList.options.length = 0;
            for (i = 1; i < vehicleAddList.options.length; i++) {
                vehicleGroupList.options[vehicleGroupList.options.length] = new Option(vehicleAddList.options[i].text, vehicleAddList.options[i].value);
            }
        }
    }
}

function vdAddVehicleToList() {
    vehicleAddList = document.getElementById("vdVehicles");
    if (vehicleAddList != null) {
        if (vehicleAddList.selectedIndex > 0) {
            if (vehicleAddList.options[vehicleAddList.selectedIndex].value != -1) {
                vehicleGroupList = document.getElementById("vdAssignedVehicles");
                if (vehicleGroupList != null) {
                    for (i = 0; i < vehicleGroupList.length; i++) {
                        if (vehicleGroupList.options[i].value == vehicleAddList.options[vehicleAddList.selectedIndex].value) {
                            return;
                        }
                    }
                    vehicleGroupList.options[vehicleGroupList.length] = new Option(vehicleAddList.options[vehicleAddList.selectedIndex].text, vehicleAddList.options[vehicleAddList.selectedIndex].value);
                }
            }
        }
        else {
            vehicleGroupList = document.getElementById("vdAssignedVehicles");
            vehicleGroupList.options.length = 0;
            for (i = 1; i < vehicleAddList.options.length; i++) {
                vehicleGroupList.options[vehicleGroupList.options.length] = new Option(vehicleAddList.options[i].text, vehicleAddList.options[i].value);
            }
        }
    }
}

function vgRemoveVehicleFromGroupList(allFlag) {
    vehicleGroupList = document.getElementById("vgUGroups");
    if (vehicleGroupList != null) {
        if (allFlag) {
            vehicleGroupList.options.length = 0;
            return;
        }

        if (vehicleGroupList.selectedIndex != -1) {
            vehicleGroupList.remove(vehicleGroupList.selectedIndex);
        }
    }
}

function vdRemoveVehicleFromDriverList(allFlag) {
    vehicleGroupList = document.getElementById("vdAssignedVehicles");
    if (vehicleGroupList != null) {
        if (allFlag) {
            vehicleGroupList.options.length = 0;
            return;
        }

        if (vehicleGroupList.selectedIndex != -1) {
            vehicleGroupList.remove(vehicleGroupList.selectedIndex);
        }
    }
}

function vgRefreshGroupList() {
    Feed.SVehGrp(m_CurrentUser, vgRefreshGroupListCallback);
}

function vdRefreshDriverList() {
    Feed.SVehDrv(m_CurrentUser, vdRefreshDriverListCallback);
}

function vgRefreshGroupListCallback(results) {
    if (results == null || results.value == null) {
        AlertMessage("Failed to retrieve group entries.<br/><br/>Please logout and try again.");
    }
    else {
        vgVehicles = results.value;
        vgGroupList = document.getElementById("vgGroups");
        vgGroupList.options.length = 0;
        m_vehicleGroups = vgVehicles;
        for (i = 0; i < vgVehicles.Rows.length; i++) {
            vgGroupList.options[vgGroupList.options.length] = new Option(vgVehicles.Rows[i].name, vgVehicles.Rows[i].id);
        }
        refreshGroupFilter();
    }
}

function vdRefreshDriverListCallback(results) {
    if (results == null || results.value == null) {
        AlertMessage("Failed to retrieve driver entries.<br/><br/>Please logout and try again.");
    }
    else {
        vdDrivers = results.value;
        vdDriverList = document.getElementById("vdDrivers");
        vdDriverList.options.length = 0;
        m_vehicleDrivers = vdDrivers;
        for (i = 0; i < vdDrivers.Rows.length; i++) {
            vdDriverList.options[vdDriverList.options.length] = new Option(vdDrivers.Rows[i].Name, vdDrivers.Rows[i].id);
        }
    }
}

function refreshGroupFilter() {
    groupFilter = document.getElementById("ddlGroups");
    groupFilter.options.length = 0;
    groupFilter.options[groupFilter.options.length] = new Option("View All Vehicles");
    for (i = 0; i < m_vehicleGroups.Rows.length; i++) {
        groupFilter.options[groupFilter.options.length] = new Option(m_vehicleGroups.Rows[i].name, m_vehicleGroups.Rows[i].id);
    }
}

function vgSaveVehicleGroupList() {
    //validate the name
    vgGroupName = document.getElementById("vgtxtName");
    if (vgGroupName.value == "") {
        AlertMessage("You must enter a name for this group.");
        return;
    }
    //validate the listing
    vgGroupList = document.getElementById("vgUGroups");
    if (vgGroupList.options.length == 0) {
        AlertMessage("Please add vehicles to your group list.");
        return;
    }
    vgSerialList = "";
    for (i = 0; i < vgGroupList.options.length; i++)
        vgSerialList = vgSerialList + vgGroupList.options[i].value + ",";

    Feed.UVehGrp(m_CurrentUser, vgGroupName.value, vgSerialList, vgRefreshGroupListCallback);
}

function vdSaveDriver() {
    //validate the name
    vgGroupName = document.getElementById("txtDriverName");
    if (vgGroupName.value == "") {
        AlertMessage("You must enter a name for this driver.");
        return;
    }
    //validate the listing
    vgGroupList = document.getElementById("vdAssignedVehicles");
    if (vgGroupList.options.length == 0) {
        AlertMessage("Please add vehicles to this driver.");
        return;
    }
    //validate the phone numbers
    vdPhone1 = document.getElementById("txtDriverPhone1").value;
    vdPhone2 = document.getElementById("txtDriverPhone2").value;
    if (!isNumeric(vdPhone1)) {
        AlertMessage("Invalid character in phone entry 1");
        return;
    }

    if (!isNumeric(vdPhone2)) {
        AlertMessage("Invalid character in phone entry 2");
        return;
    }

    vdCarrier1 = document.getElementById("DriverPROVIDER1").value;
    vdCarrier2 = document.getElementById("DriverPROVIDER2").value;
    if (trim(vdPhone1, " ") == "") {
        vdCarrier1 = "";
        document.getElementById("DriverPROVIDER1").value = "";
    }
    if (trim(vdPhone2, " ") == "") {
        vdCarrier2 = "";
        document.getElementById("DriverPROVIDER2").value = "";
    }

    vgSerialList = "";
    for (i = 0; i < vgGroupList.options.length; i++)
        vgSerialList = vgSerialList + vgGroupList.options[i].value + ",";
    Feed.UVehDrv(m_CurrentUser, vgGroupName.value, vdPhone1, vdPhone2, vdCarrier1, vdCarrier2, vgSerialList, vdRefreshDriverListCallback);
}

function vgAddVehicleGroup() {
    // displaying the add/edit group Div
    var vgAddGroup = document.getElementById("divAddGroup");
    vgAddGroup.style.display = "inline";
    vgAddGroup.style.visibility = "visible";
    // hide remove group div
    var vgRemoveGroup = document.getElementById("divRemoveGroup");
    vgRemoveGroup.style.display = "none";
    vgRemoveGroup.style.visibility = "hidden";

    vgGroupName = document.getElementById("vgtxtName");
    vgGroupName.value = ""
    vgGroupList = document.getElementById("vgUGroups");
    vgGroupList.options.length = 0;
    vgGroupName.focus();
}

function vgRemoveVehicleGroup(action) {
    switch (action) {
        case "displayMessage":
            // hide the add/edit group Div
            var vgAddGroup = document.getElementById("divAddGroup");
            vgAddGroup.style.display = "none";
            vgAddGroup.style.visibility = "hidden";
            // display remove group div
            var vgRemoveGroup = document.getElementById("divRemoveGroup");
            vgRemoveGroup.style.display = "inline";
            vgRemoveGroup.style.visibility = "visible";

            vgGroupList = document.getElementById("vgGroups");
            if (vgGroupList.selectedIndex != -1) {
                var table = document.getElementById("groupSelected");
                table.style.display = "inline";
                table.style.visibility = "visible";

                table = document.getElementById("noGroupSelected");
                table.style.display = "none";
                table.style.visibility = "hidden";
            }
            else {
                var table = document.getElementById("noGroupSelected");
                table.style.display = "inline";
                table.style.visibility = "visible";

                table = document.getElementById("groupSelected");
                table.style.display = "none";
                table.style.visibility = "hidden";
            }
            break;
        case "editGroup":
            // user Selected No, showing edit Group information
            vgEditVehicleGroup();
            break;
        case "removeGroup":
            // user selected Yes, removig the Group from the database
            vgGroupList = document.getElementById("vgGroups");
            if (vgGroupList.selectedIndex != -1) {
                Feed.DVehGrp(m_CurrentUser, vgGroupList.options[vgGroupList.selectedIndex].value, vgRefreshGroupListCallback);
            }
            break;
    }
}

function vdAddVehicleDriver() {
    // displaying the add/edit driver Div
    var vgAddDriver = document.getElementById("divAddDriver");
    vgAddDriver.style.display = "inline";
    vgAddDriver.style.visibility = "visible";
    // hide remove driver div
    var vgRemoveDriver = document.getElementById("divRemoveDriver");
    vgRemoveDriver.style.display = "none";
    vgRemoveDriver.style.visibility = "hidden";

    vgGroupName = document.getElementById("txtDriverName");
    vgGroupName.value = "";
    vgGroupList = document.getElementById("vdAssignedVehicles");
    vgGroupList.options.length = 0;
    vdPhone1 = document.getElementById("txtDriverPhone1");
    vdPhone2 = document.getElementById("txtDriverPhone2");
    vdPhone1.value = "";
    vdPhone2.value = "";
    vdCarrier1 = document.getElementById("DriverPROVIDER1");
    vdCarrier2 = document.getElementById("DriverPROVIDER2");
    vdCarrier1.value = "";
    vdCarrier2.value = "";
    vgGroupName.focus();
}

function vdRemoveVehicleDriver(action) {

    switch (action) {
        case "displayMessage":
            // Display confirmation message in divRemoveDriver
            // hidding the add/edit Driver Div
            var vgAddDriver = document.getElementById("divAddDriver");
            vgAddDriver.style.display = "none";
            vgAddDriver.style.visibility = "hidden";
            // displaying the RemoveDriver Div
            var vgRemoveDriver = document.getElementById("divRemoveDriver");
            vgRemoveDriver.style.display = "inline";
            vgRemoveDriver.style.visibility = "visible";

            vgGroupList = document.getElementById("vdDrivers");
            if (vgGroupList.selectedIndex != -1) {
                var table = document.getElementById("driverSelected");
                table.style.display = "inline";
                table.style.visibility = "visible";

                table = document.getElementById("noDriverSelected");
                table.style.display = "none";
                table.style.visibility = "hidden";
            }
            else {
                var table = document.getElementById("noDriverSelected");
                table.style.display = "inline";
                table.style.visibility = "visible";

                table = document.getElementById("driverSelected");
                table.style.display = "none";
                table.style.visibility = "hidden";
            }
            break;

        case "editDriver":
            // user Selected No, showing edit Driver information
            vdEditVehicleDriver();
            break;

        case "removeDriver":
            // user selected Yes, removig the Driver from the database
            vgGroupList = document.getElementById("vdDrivers");
            if (vgGroupList.selectedIndex != -1) {
                Feed.DVehDrv(m_CurrentUser, vgGroupList.options[vgGroupList.selectedIndex].value, vdRefreshDriverListCallback);
            }
            break;
    }
}

function vgEditVehicleGroup() {
    // displaying the add/edit group Div
    var vgAddGroup = document.getElementById("divAddGroup");
    vgAddGroup.style.display = "inline";
    vgAddGroup.style.visibility = "visible";
    // hide remove group div
    var vgRemoveGroup = document.getElementById("divRemoveGroup");
    vgRemoveGroup.style.display = "none";
    vgRemoveGroup.style.visibility = "hidden";

    vgGroupsList = document.getElementById("vgGroups");
    if (vgGroupsList.selectedIndex != -1) {
        //set the name
        groupName = document.getElementById("vgtxtName");
        groupName.value = m_vehicleGroups.Rows[vgGroupsList.selectedIndex].name;
        //setup the vehicles (map the serial numbers to names)
        vgListing = document.getElementById("vgUGroups");
        vgListing.options.length = 0;
        vehicleAddList = document.getElementById("vgVehicles");
        serialString = m_vehicleGroups.Rows[vgGroupsList.selectedIndex].serials;
        for (i = 0; i < vehicleAddList.options.length; i++) {
            if (serialString.match(vehicleAddList.options[i].value) != null) {
                vgListing.options[vgListing.options.length] = new Option(vehicleAddList.options[i].text, vehicleAddList.options[i].value);
            }
        }
    }
}

function vdEditVehicleDriver() {
    vgGroupsList = document.getElementById("vdDrivers");

    if (vgGroupsList.selectedIndex != -1) {
        // displaying the add/edit driver Div
        var vgAddDriver = document.getElementById("divAddDriver");
        vgAddDriver.style.display = "inline";
        vgAddDriver.style.visibility = "visible";
        // hide remove driver div
        var vgRemoveDriver = document.getElementById("divRemoveDriver");
        vgRemoveDriver.style.display = "none";
        vgRemoveDriver.style.visibility = "hidden";

        //set the name
        groupName = document.getElementById("txtDriverName");
        groupName.value = m_vehicleDrivers.Rows[vgGroupsList.selectedIndex].Name;
        //setup the vehicles (map the serial numbers to names)
        vgListing = document.getElementById("vdAssignedVehicles");
        vgListing.options.length = 0;
        vehicleAddList = document.getElementById("vdVehicles");
        serialString = m_vehicleDrivers.Rows[vgGroupsList.selectedIndex].VehicleList;
        for (i = 0; i < vehicleAddList.options.length; i++) {
            if (serialString.match(vehicleAddList.options[i].value) != null) {
                vgListing.options[vgListing.options.length] = new Option(vehicleAddList.options[i].text, vehicleAddList.options[i].value);
            }
        }
        //set the phone numbers
        phone1 = document.getElementById("txtDriverPhone1");
        phone2 = document.getElementById("txtDriverPhone2");
        carrier1 = document.getElementById("DriverPROVIDER1");
        carrier2 = document.getElementById("DriverPROVIDER2");
        phone1.value = m_vehicleDrivers.Rows[vgGroupsList.selectedIndex].Phone1;
        phone2.value = m_vehicleDrivers.Rows[vgGroupsList.selectedIndex].Phone2;

        carrier1.value = "";
        if (m_vehicleDrivers.Rows[vgGroupsList.selectedIndex].SMSCarrier1 != null) {
            
            // Adding a loop to get the proper index to select.
            for (var index = 0; index < carrier1.length; index++) {
                if (carrier1[index].value == m_vehicleDrivers.Rows[vgGroupsList.selectedIndex].SMSCarrier1) {
                    // carrier1.value = m_vehicleDrivers.Rows[vgGroupsList.selectedIndex].SMSCarrier1;
                    carrier1.selectedIndex = index;
                    break;
                }
            } 
        }
//        else {
//            carrier1.value = "";
//        }
        carrier2.value = "";
        if (m_vehicleDrivers.Rows[vgGroupsList.selectedIndex].SMSCarrier2 != null) {
            
            for (var index = 0; index < carrier1.length; index++) {
                if (carrier2[index].value == m_vehicleDrivers.Rows[vgGroupsList.selectedIndex].SMSCarrier2) {
                    // carrier2.value = m_vehicleDrivers.Rows[vgGroupsList.selectedIndex].SMSCarrier2;
                    carrier2.selectedIndex = index;
                    break;
                }
            }
            
        }
//        else {
//            carrier2.value = "";
//        }
    }
}

function qs() {
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i = 0; i < parms.length; i++) {
        var pos = parms[i].indexOf('=');
        if (pos > 0) {
            var key = parms[i].substring(0, pos);
            var val = parms[i].substring(pos + 1);
            queryStringParams[key] = val;
        }
    }
}

function autologin() {
    qs();

    if (queryStringParams["h"] != null) {
        requestedHeight = queryStringParams["h"] * 1;
    }
    if (queryStringParams["w"] != null) {
        requestedWidth = queryStringParams["w"] * 1;
    }
    if (queryStringParams["weather"] != null) {
        if (queryStringParams["weather"] == "radar") {
            RadarCB_onclick(null);
        } else if (queryStringParams["weather"] == "clouds") {
            CloudCB_onclick(null);
        }
    }
    if (queryStringParams["loopweather"] != null) {
        if (queryStringParams["loopweather"] == "true") {
            LoopWeatherCB_onclick(null);
        }
    }

    // checking to see if login and pass are stored in cookie.
    dummyUser = getCookie("USFTLoginID");
    dummyPwd = getCookie("USFTPassword");
    removeCookie("USFTLoginID", "");
    removeCookie("USFTPassword", "");
    if (dummyUser != "" && dummyUser != null) {
        if (dummyPwd != "" && dummyPwd != null) {
            dummyPwd = decrypt_pwd(dummyPwd);
            loginUserTimer = setTimeout("logInUser('" + document.getElementById("loginCell") + "')", 1000);
        }
    } else if (queryStringParams["login"] != null) {  // checking to see if parameters contain login and pass
        if (queryStringParams["pwd"] != null) {
            dummyUser = queryStringParams["login"];
            dummyPwd = decrypt_pwd(queryStringParams["pwd"]);
            loginUserTimer = setTimeout("logInUser('" + document.getElementById("loginCell") + "')", 1000);
        }
    }
    else {
        if (queryStringParams["demo"] != null) {
            logInDemoUser();
        }
        else {
            if (queryStringParams["DemoChat"] != null) {
                logInDemoChat();
            }
        }
    }
}

function positionMapOnQStr() {


    if (queryStringParams["lat"] != null && queryStringParams["lon"] != null) {
        var center = new VELatLong(queryStringParams["lat"] * 1, queryStringParams["lon"] * 1);
        map.SetCenter(center);
    }
    if (queryStringParams["zoom"] != null) {
        setZoomValue(queryStringParams["zoom"], "set");
    }
}

function decrypt_pwd(pwd) {
    var decptd = "";
    var dateis = new Date;
    var xor_key = (dateis.getDate() % 3) + 1;
    for (i = 0; i < pwd.length; i++) {
        decptd += String.fromCharCode(xor_key ^ pwd.charCodeAt(i));
    }
    return decptd;
}

function reenableLiveTracking() {

    for (var i = 0; i < carPins.length; i++) {
        carPins[i].Hide();
        nameTags[i].Hide();
        infoBoxes[i].Hide();
    }

    if (isAdvRouteVisible) {
        AdvRouteClearLayer();
    }

    resetHistoricalPlayback();
    // Clearmap is done in resetHistorical Playback if histcarpin
    clearMap();

    clearTimeout(m_loadTimeout);
    clearTimeout(historicalPlaybackTimer);
    clearInterval(m_loadInterval);
    m_loadTimeout = null;
    m_loadInterval = null;
    historicalPlaybackTimer = null;
    
    // resetting center map and optimize, so screen will refocus properly
    m_firstRetrieve = true;
    m_bcentermap = true;
    m_bOptimizeZoom = true;

    if (m_demoUser && m_CurrentUser.match("livedemo") == null)
        logInDemoUser();
    else
        logInUser();
}

function ssrReportTypeClicked() {
    rpt_IgnitionMovement = document.getElementById("rptIgnition");
    var divMinStopTime1 = document.getElementById("divMinStopTime1");
    var divMinStopTime2 = document.getElementById("divMinStopTime2");
    if (rpt_IgnitionMovement.checked) {
        divMinStopTime1.style.visibility = "hidden";
        divMinStopTime2.style.visibility = "hidden";
    }
    else {
        divMinStopTime1.style.visibility = "visible";
        divMinStopTime2.style.visibility = "visible";
    }
}

function ssOrReportTypeClicked() {
    ddldivOLRIdle = document.getElementById("divOLRIdle");
    var rpt_Ignition = document.getElementById("rptIgnition");
    if (rpt_Ignition.checked) {
        ddldivOLRIdle.style.visibility = "hidden";
    }
    else {
        ddldivOLRIdle.style.visibility = "visible";
    }
}

function showToolTip2() {
    var point = m_gMap.getCurrentMapType().getProjection().fromLatLngToPixel(m_gMap.fromDivPixelToLatLng(new GPoint(0, 0), true), m_gMap.getZoom());
    var offset = m_gMap.getCurrentMapType().getProjection().fromLatLngToPixel(this.getPoint(), m_gMap.getZoom());
    var anchor = this.getIcon().iconAnchor;
    var width = this.getIcon().iconSize.width;
    var height = 100;
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width + TOOLTIP_OFFSET_X2, offset.y - point.y - anchor.y + TOOLTIP_OFFSET_Y2));
    pos.apply(this.tooltip);
    this.tooltip.style.display = "block";
}

function hideToolTip2() {
    this.tooltip.style.display = "none";
}

function lookupLatLon() {
    addressLAT = document.getElementById("addressLAT");
    addressLON = document.getElementById("addressLON");
    Feed.MpPntRvGeo(addressLAT.value, addressLON.value, lookupLatLonCallback);
}

function lookupLatLonCallback(response) {
    if (response != null) {
        addressText = document.getElementById("txtAddressFind");
        addressText.value = response.value;
    }
}

function lookupAddress() {
    addressFind = document.getElementById("txtAddressFind");
    map.Find(null, addressFind.value, null, null, null, null, true, true, null, true, lookupAddressCallback);
}

function lookupAddressCallback(layer, resultsArray, places, hasMore, veErrorMessage) {
    if (places[0] == null) {
        AlertMessage("Address not found.");
    }
    else {
        place = places[0].LatLong;
        addressLAT = document.getElementById("addressLAT");
        addressLON = document.getElementById("addressLON");
        addressLAT.value = place.Latitude;
        addressLON.value = place.Longitude;
    }
}

function lookupReportAddress() {
    addressFind = document.getElementById("txtAddressFind");
    window.parent.map.Find(null, addressFind.value, null, null, null, null, true, true, null, true, lookupAddressCallback);
}

//  This code is called when a user clicks on an address url on a report.
function showAddress(strControl, dLat, dLon, sType) {
    m_AddressControl = strControl;
    m_AddressType = sType;
    document.body.style.cursor = 'wait';
    Feed.MpPntRvGeo(dLat, dLon, showAddressCallback);
}

function showAddressCallback(response) {
    var strResponse = "";
    if (response != null) {
        switch (m_AddressType) {
            case "1":
                strResponse = " Heading change at:<br>";
                break;
            case "2":
                strResponse = " Stopped at:<br>";
                break;
            case "3":
                strResponse = " Stayed at:<br>";
                break;
            case "4":
                strResponse = " Continued to:<br>";
                break;
            default:
                strResponse = "";
                break;
        }
        aaddrcontrol = document.getElementById("address_" + m_AddressControl);
        if (aaddrcontrol != null) {
            aaddrcontrol.innerHTML = strResponse + response.value;
        }
    }
    m_AddressControl = "";
    m_AddressTyep = "";
    document.body.style.cursor = 'auto';
}

function showTitleBar(type) {
    if (type == 0) {
        titleBar = document.getElementById("titleBar");
        titleBar.style.visibility = "visible";
    }
}

function hideTitleBar() {
    titleBar = document.getElementById("titleBar");
    titleBar.style.visibility = "hidden";
}

function mapZoomStart() {
    close_address_info();

    clearWeatherLoopInterval();

    if (null != address_marker_layer)
        address_marker_layer.Hide();

    if (null != map)
        vehicles_set_visible(false);
}

function vehicles_set_visible(visible) {
    if (true == visible) {
        for (var i = 0; i < carPins.length; i++) {
            carPins[i].Show();
            nameTags[i].Hide();
            infoBoxes[i].Hide();
        }
    }
    else {
        for (var i = 0; i < carPins.length; i++) {
            carPins[i].Hide();
            nameTags[i].Hide();
            infoBoxes[i].Hide();
        }
    }
}

function mapZoomEnd() {

    if (null != address_marker_layer)
        address_marker_layer.Show();

    if (null != map)
        vehicles_set_visible(true);

    setZoomValue(map.GetZoomLevel(), 'set');
    if (m_drawingFence == true) {
        drawFence();
    }
    if (MarkerNames != null) {
        //updateAddressMarkers();
        
    }
    if (carInPanic == true) {
        showCarsInPanic();
    }
    if (isAdvRouteVisible) {
        AdvRouteSetWidth(null, "tbRadius");
    }
    if (AlertEditorOpen) {
        AlertRadiusChanged();
    }
    if (allRouteLayer != null) {
        ResizeAllRoutes();
    }
    initWeatherLoopInterval();
}
function mapPanStart() {close_address_info(); clearWeatherLoopInterval(); }
function mapPanEnd() {

    if (carInPanic == true) {
        showCarsInPanic();
    }
    initWeatherLoopInterval();
    
}

function stripID(value) {
    allowed_chars = "1234567890";
    new_id = "";
    for (i = 0; i < value.length; i++) {
        if (value.charAt(i) != ")" && value.charAt(i) != "(") {
            if (allowed_chars.match(value.charAt(i)) != null) {
                new_id = new_id + value.charAt(i);
            }
        }
    }
    return new_id;
}

function clearFence() {
    map.DeleteAllPolygons();
    if (fenceUL != null) {
        map.DeleteShape(fenceUL);
        fenceUL = null;
    }
    if (fenceLR != null) {
        map.DeleteShape(fenceLR);
        fenceLR = null;
    }
}


function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
}

function openReportOverlay(report, help) {
    fadeout("divReportSelector");
    // Moved to when the generate button is selected (function getreport)
    //  this stops the vehicle refresh while we are doing the report!!
    //stopLoadMarkers();
    //clearTimeout(m_loadTimeout);
    //clearInterval(m_loadInterval);
    var sessionQueryKey = document.getElementById("SESSIONKEY");
    var imgRPHelp = document.getElementById("RPHelp");
    if (help != false) {

        imgRPHelp.setAttribute("onclick", "showvideo('" + help + "', true);");
        imgRPHelp.style.visibility = "visible";
    }
    else {
        imgRPHelp.setAttribute("onclick", "showvideo('', false);");
        imgRPHelp.style.visibility = "hidden";
    }
    
    m_divTitlebar = document.getElementById("divReportPlate");
    m_divROverlay = document.getElementById("divROverlay");
    m_divTitlebar.style.width = "744px";
    m_divROverlay.style.width = '708px';
    getOverlaySize();
    //m_divROverlay.style.height = parseInt(windowHeight - 150) + 'px';
    m_divTitlebar.style.height = '763px';
    m_divROverlay.innerHTML = "<iframe src='" + report + ".aspx?SESSIONID=" + sessionQueryKey.getAttribute("value") + "' style='background-color: Transparent; width:100%; height:100%;' frameBorder=0 allowtransparency='true' />";
    m_divROverlay.style.visibility = "visible";
    m_divTitlebar.style.visibility = "visible";
    fadein("divReportPlate");
}

function hideReportOverlay() {
    m_rptType = 0;
    fadeout("divReportPlate");
    // the following two lines of code restart the vehicle refresh after the report is closed...
    // This is implemented since the user can close the report before it has finished running.
    //var sessionID = document.getElementById("SESSIONKEY").getAttribute("value");
    //m_loadTimeout = setTimeout("loadMarkers('" + sessionID + "');", 4000);
    clearTimeout(m_loadTimeout);
    clearInterval(m_loadInterval);
    restartLoadMarkers();
}

function openVehicleActionPane(i) {
    if (m_bLoggedIn) {
        m_vgodiv = document.getElementById("divVehicleAction");
        m_vgodiv.style.display = "block";
        getPageSize();
        var originalPoint = map.LatLongToPixel(new VELatLong(cars.Rows[i].lt * 1, cars.Rows[i].ln * 1));
        if (originalPoint.x + m_vgodiv.clientWidth > windowWidth) {
            m_vgodiv.style.left = (windowWidth - m_vgodiv.clientWidth) + 8 + "px";
        }
        else {
            m_vgodiv.style.left = originalPoint.x + 8 + "px";
        }

        if (originalPoint.y + m_vgodiv.clientHeight > windowHeight) {
            m_vgodiv.style.top = windowHeight - m_vgodiv.clientHeight - 50 + "px";
        }
        else {
            m_vgodiv.style.top = originalPoint.y + "px";
        }
        fadein("divVehicleAction");
        vapId = document.getElementById("vapId");
        vapId.value = cars.Rows[i].s;
        vapName = document.getElementById("vapName");
        vapName.value = cars.Rows[i].n;
        vapFlagColor = document.getElementById("vapFlagColor");
        vapFlagColor.value = cars.Rows[i].cl;
        vapTextColor = document.getElementById("vapTextColor");
        vapTextColor.value = cars.Rows[i].tc;
        element = document.getElementById("vehicle_address");
        element.innerText = "";
        var imageloc = "images/";
        //if (cars.Rows[i].Image == null) {
        if (cars.Rows[i].iconFolder == null || cars.Rows[i].iconFolder == "") {
            imageloc += "default/";
        }
        else {
            imageloc += cars.Rows[i].Image + "/";
        }
        imageloc += "Master1.gif";
        var VehIcon = document.getElementById("VehIcon");
        VehIcon.src = imageloc;
        IconFolderToUse = null;
        var followme = document.getElementById("followme");
        if (vehicleToFollow == cars.Rows[i].s) {
            followme.innerHTML = "<img alt='' onclick=\"followThisVehicle();\" src='images/vapSTOPfollowvehicle0.gif' onmouseover=\"this.src='images/vapSTOPfollowvehicle1.gif'\" onmouseout=\"this.src='images/vapSTOPfollowvehicle0.gif'\" onmousedown=\"this.src='images/vapSTOPfollowvehicle0.gif'\" />";
        }
        else {
            followme.innerHTML = "<img alt='' onclick=\"followThisVehicle();\" src='images/vapfollowvehicle0.gif' onmouseover=\"this.src='images/vapfollowvehicle1.gif'\" onmouseout=\"this.src='images/vapfollowvehicle0.gif'\" onmousedown=\"this.src='images/vapfollowvehicle0.gif'\" />";
        }
    }
    else {
        AlertMessage("You must be logged in to use this feature.");
    }
}

function selectVehicleIcon() {
    if (!m_bLoggedIn) {
        AlertMessage("You must be logged in to use this feature.");
    }
    else {
        Feed.SIcnFld(getIconFoldersCallback);
    }
}

function getIconFoldersCallback(result) {
    if (result != null) {
        IconFolders = result.value;
        var divInfo = "<table style='vertical-align:top;'><tr valign='top' align='center' style='vertical-align:top;'>";
        for (var i = 0; i < IconFolders.Rows.length; i++) {
            divInfo += "<td valign='top' style='vertical-align:bottom; cursor:pointer;'><img alt='' valign='top' onclick='useIcon(" + i + ");' src='images/" + IconFolders.Rows[i].iconFolder + "/Master.gif' /></td>";
            var j = (i + 1) % 8;
            if (j == 0) {
                divInfo += "</tr><tr valign='top' align='center' style='vertical-align:top;'>";
            }
        }
        divInfo += "</tr></table>";
        var divIconSelector = document.getElementById("divIconSelector");
        divIconSelector.innerHTML = divInfo;
        m_divIOverlay = null;
        m_divIOverlay = document.getElementById("divIconSelectorOverlay");
        fadein("divIconSelectorOverlay");
    }
    Feed.SAdrMrk(getAddressMarkersCallback);
}

function hideVehicleIcon() {
    fadeout("divIconSelectorOverlay");
}

function useIcon(id) {
    if (ControlPanelLockout == true || m_demoUser || demo2_user) {
        AlertMessage("Sorry, this feature has been disabled in demonstration mode.");
        return;
    }

    IconFolderToUse = id;
    var VehIcon = document.getElementById("VehIcon");
    VehIcon.src = "images/" + IconFolders.Rows[id].iconFolder + "/Master1.gif"
    hideVehicleIcon();
}

function updateVehicleName() {
    if (ControlPanelLockout == true || m_demoUser || demo2_user) {
        AlertMessage("Sorry, this feature has been disabled in demonstration mode.");
        return;
    }
    if (vapName.value != "") {
        for (i = 0; cars.Rows.length; i++) {
            if (clickedOnSerial == cars.Rows[i].s) {
                var iconFolder = null;
                if (IconFolderToUse != null) {
                    iconFolder = IconFolders.Rows[IconFolderToUse].iconFolder;
                }
                cars.Rows[i].cl = vapFlagColor;
                cars.Rows[i].tc = vapTextColor;
                hideVehicleActionPane();
                Feed.UVeh(cars.Rows[i].s.toString(), vapName.value, cars.Rows[i].cl.value, cars.Rows[i].tc.value, iconFolder);
                break;
            }
        }
    }
    else {
        AlertMessage("You must supply the Flag Text.");
    }
}

// This function will select the serial number and device name for all vehicles assigned to the session account
// or it's viewable accounts.  It will then populate the list in the passed in list. It can pull a specific type
// Types MSG will only pull vehciles allowed for messaging
function getAccountVehicles(type) {
    var sessionID = document.getElementById("SESSIONKEY").getAttribute("value");
    var result = Feed.SActVeh(sessionID, type);
    if (result != null && result.value != null) {
        return result.value;
    }
    
}


function hideVehicleActionPane() {
    fadeout("divColorPopOverLay");
    fadeout("divVehicleAction");
}

function openGroupEditor() {
    if (m_bLoggedIn) {
        m_alertdiv = null;
        m_alertdiv = document.getElementById("divVehicleGroupOverlay");
        m_alertdiv.style.display = "block";
        m_alertdiv.style.position = "absolute";
        m_alertdiv.style.visibility = "visible";
        fadein("divVehicleGroupOverlay")
        vgRefreshGroupList();
    }
    else {
        AlertMessage("You must be logged in to use this feature.");
    }
}

function hideGroupEditor() {
    fadeout("divVehicleGroupOverlay")
    var vgAddGroup = document.getElementById("divAddGroup");
    vgAddGroup.style.display = "inline";
    vgAddGroup.style.visibility = "hidden";
    var vgRemoveGroup = document.getElementById("divRemoveGroup");
    vgRemoveGroup.style.display = "none";
    vgRemoveGroup.style.visibility = "hidden";
}

function openDriverEditor() {
    if (m_bLoggedIn) {
        m_alertdiv = null;
        m_alertdiv = document.getElementById("divVehicleDriverOverlay");
        m_alertdiv.style.display = "block";
        m_alertdiv.style.position = "absolute";
        m_alertdiv.style.top = "5px";
        m_alertdiv.style.left = "-220px";
        m_alertdiv.style.visibility = "visible";
        fadein("divVehicleDriverOverlay");
        vdRefreshDriverList();
    }
    else {
        AlertMessage("You must be logged in to use this feature.");
    }
}

function hideDriverEditor() {
    fadeout("divVehicleDriverOverlay");
    var vgAddDriver = document.getElementById("divAddDriver");
    vgAddDriver.style.display = "inline";
    vgAddDriver.style.visibility = "hidden";
    var vgRemoveDriver = document.getElementById("divRemoveDriver");
    vgRemoveDriver.style.display = "none";
    vgRemoveDriver.style.visibility = "hidden";
}

function openAddresses() {
    if (m_bLoggedIn) {
        fadein("divAddressesOverlay");
        document.getElementById('addressAdd').style.display = "inline";
    }
    else {
        AlertMessage("You must be logged in to use this feature.");
    }
}

function hideAddresses() {
    if (NewAddressMarkerPresent) {
        NewAddressPin.Hide();
        map.DeleteShape(NewAddressPin);
        NewAddressMarkerPresent = false;
    }
    fadeout("divAddressesOverlay");
    document.getElementById('addressAdd').style.visibility = "hidden";
    document.getElementById('addressRemove').style.visibility = "hidden";
    m_SelectPoint = false;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                      Address Search
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var AddressLayer = null;
var AddressMarker = null;
var AddressMarkerOffsetX = 45;
var AddressMarkerOffsetY = -5;
function ShowAddressDescription(value, title, description, latLon) {
    if (value) {
        var icon = GetAddressDiv(title, description);

        var originalPoint = map.LatLongToPixel(latLon[0]);
        var newLatLon = map.PixelToLatLong(new VEPixel(originalPoint.x + AddressMarkerOffsetX, originalPoint.y + AddressMarkerOffsetY));

        if (AddressMarker == null) {
            if (AddressLayer == null) {
                AddressLayer = AddLayer("Address Search Layer", "Contains the results of an address search");
            }
            AddressMarker = AddPushpinToLayer(AddressLayer, newLatLon, icon, false, null, null);
        } else {
            MovePushpin(AddressMarker, newLatLon);
            SetPushpinCustomIcon(AddressMarker, icon);
        }
        ShowPushpin(AddressMarker, true);
    } else { ShowPushpin(AddressMarker, false); }
}
function GetAddressDiv(title, description) {
    var string = "";
    if (!(title == null || title.length < 1)) {
        string += "<tr><td style='vertical-align:top;' class='whiteType12'>" + title + "</td></tr>";
    }
    string += "<tr><td style='vertical-align:top;' class='whiteType10'>" + description + "</td></tr>";
    return "<div style='background:URL(images/AddressMarkerPopUp.png) no-repeat top right Transparent; width:319px; height:109px;z-index:1000;'>" +
                "<div style='position:absolute;top:22px;left:15px; width:280px; height:60px; overflow:hidden;'>" +
                    "<table cellpadding='0' cellspacing='0'>" +
                        string +
                    "</table>" +
                "</div>" +
            "</div>";
}
function ShowAddressSearch(show) {
    if (show) {
        fadein("divAddressSearch");
    } else {
        fadeout("divAddressSearch");
    }
}
function AddressSearch() {
    var address = document.getElementById("tbAddressSearch").value;
    if (address == null || address.length < 1) { AlertMessage("You must enter an address to search for."); return; }
    if (AddressLayer == null) {
        AddressLayer = AddLayer("Address Search Layer", "Contains the results of an address search");
    }
    map.Find(null, address, VEFindType.Businesses, AddressLayer, 0, 1, false, false, false, true, AddressSearchCallback);
    //map.Find(what, where, findType, shapeLayer, startIndex, numberOfResults, showResults, createResults, useDefaultDisambiguation, setBestMapView, callback);
}
function AddressSearchCallback(layer, resultsArray, places, hasMore, veErrorMessage) {
    if (places == null || places[0] == null) { AlertMessage("We could not find a match for the location. Please check your spelling, enter the complete address using commas, and try again."); return; }
    if (veErrorMessage != null) { AlertMessage(veErrorMessage); return; }
    var pin = AddPushpinToLayer(layer, places[0].LatLong, "images/redpushpin.gif", true, "", places[0].Name);
    pin.isAddressMarker = true;
}
function clearAddresses() {
    RemoveLayer(AddressLayer);
    AddressLayer = null;
}

//
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                              On-Line Chat

function openLiveChat() {
    if (ChatIsOpen != true) {
        var crlf = String.fromCharCode(13) + String.fromCharCode(10);
        if (m_bLoggedIn) {
            m_divOLROverlay = null;
            m_divOLROverlay = document.getElementById("divOnlineChatOverlay");
            m_divOLROverlay.style.marginTop = parseInt(0);
            fadein("divOnlineChatOverlay");
            ChatLines = new Array();

            ChatLines.push("Live Chat Support hours are 7am to 7pm Central Time Monday through Friday," + crlf + "and 9am to 4pm Central Time on Saturdays." + crlf + crlf);
            ChatLines.push(dtime + " - " + m_CurrentUser + ": " + "*** Live Support Session Opened ***" + crlf);
            loadChatMessages();
            ChatIsOpen = true;
            ChatWaitTime = 5000;
            SetCheckOnLineMessagesTimeout();
            m_divOLROverlay = null;
            document.getElementById("textChatOutput").focus();
        }
        else {
            AlertMessage("You must be logged in to use this feature.");
        }
    }
}

function hideOnLineChat() {
    clearTimeout(m_checkMesagesTimeout);
    fadeout("divOnlineChatOverlay");
    var sessionID = document.getElementById("SESSIONKEY").getAttribute("value");
    ChatWaitTime = 10000;
    SetCheckOnLineMessagesTimeout();
    ChatIsOpen = false;
}

function OnlineChatSend() {
    var ChatIP = document.getElementById("textChatOutput");
    if (ChatIP.value != "") {
        var crlf = String.fromCharCode(13) + String.fromCharCode(10)
        var currentTime = new Date();
        ChatLines.push(currentTime + " - " + m_CurrentUser + ": " + ChatIP.value + crlf);
        loadChatMessages();
        Feed.IOnlCht(m_CurrentUser, ChatIP.value);
        ChatIP.value = "";
    }
}

function SetCheckOnLineMessagesTimeout() {
    clearTimeout(m_checkMesagesTimeout);
    var sessionID = document.getElementById("SESSIONKEY").getAttribute("value");
    m_checkMesagesTimeout = setTimeout("CheckOnLineMessages('" + sessionID + "');", ChatWaitTime);
}

function CheckOnLineMessages() {
    Feed.ChkOnlMsg(m_CurrentUser, ChatMsgNo * 1, CheckOnLineMessagesResponse)
}

function CheckOnLineMessagesResponse(Response) {
    var crlf = String.fromCharCode(13) + String.fromCharCode(10)
    if (Response != null && Response.value != null) {
        if (ChatIsOpen != true) {
            openLiveChat();
        }
        var ChatMsg = Response.value;
        if (ChatMsg.Rows.length > 0) {
            for (var i = 0; i < ChatMsg.Rows.length; i++) {
                ChatLines.push(ChatMsg.Rows[i].PostTime + " - " + ChatMsg.Rows[i].SenderUserID + ": " + ChatMsg.Rows[i].MsgPayload);
                ChatMsgNo = ChatMsg.Rows[i].MsgNumber;
            }
            loadChatMessages();
        }
    }
    var WaitTime = 5000;
    if (ChatIsOpen == true) {
        WaitTime = 5000;
    }
    SetCheckOnLineMessagesTimeout();
}

function loadChatMessages() {
    var crlf = String.fromCharCode(13) + String.fromCharCode(10)
    var opLine = "";
    for (var i = 0; i < ChatLines.length; i++) {
        opLine += ChatLines[i];
    }

    var chatOp = document.getElementById("ChatIP");
    chatOp.value = opLine;
    chatOp.scrollTop = chatOp.scrollHeight;
}

function GetOnLineMessageMaxResponse(Response) {
    ChatMsgNo = Response.value;
    SetCheckOnLineMessagesTimeout();
}

//                                                  End of On-Line Chat

//  ╔════════════════════════════════════════════════════════════════════════════════════════════════╗
//  ║                             CNAV Instant Message Center Functions                              ║
//  ╚════════════════════════════════════════════════════════════════════════════════════════════════╝

function openCNAVMessage() {
    hideVehicleActionPane();
    // populate the vehicle list
    buildMsgVehicleList();

    fadein("divNAVMessageCenter");
}

// building the vehicle drop down list for the CNAV messaging
function buildMsgVehicleList() {

    var cnavunitlistText = "<label class='whiteType' style='padding-right:3px;display:block;'><input name='cbvlist' value='1' type='checkbox' id='cb1' onclick='SelectAll(\"cbvlist\",\"MessageTo\");' />ALL Devices</label>";
    var cnavdisplist = "<label class='whiteType' style='padding-right:3px;display:block;'><input name='cbdlist' value='1' type='checkbox' id='cd1' onclick='SelectAll(\"cbdlist\",\"DispatchTo\");' />ALL Devices</label>";
    var cnavunitcount = 1;
    var tmpVehicles = getAccountVehicles('MSG');
    if (tmpVehicles != null) {
        for (var i = 0; i < tmpVehicles.Rows.length; i++) {
           // if (tmpVehicles.Rows[i].s.toString().substring(0, 1) == "8" || tmpVehicles.Rows[i].MsgE.toString() == true) {
                cnavunitcount = cnavunitcount + 1;
                cnavunitlistText += "<label class='whiteType' style='padding-right:3px;display:block;'><input name='cbvlist' value='" + cnavunitcount.toString() + "' type='checkbox' id='cb" + cnavunitcount.toString() + "' onclick='SelectItems(\"cbvlist\",\"MessageTo\");' />" + tmpVehicles.Rows[i].n + "</label>";
                cnavdisplist += "<label class='whiteType' style='padding-right:3px;display:block;'><input name='cbdlist' value='" + cnavunitcount.toString() + "' type='checkbox' id='cd" + cnavunitcount.toString() + "' onclick='SelectItems(\"cbdlist\",\"DispatchTo\");' />" + tmpVehicles.Rows[i].n + "</label>";
            //}
        }
    }
    
    var divCNAVdispatchdroplist = document.getElementById("CNAVDispatchDroplist");
    divCNAVdispatchdroplist.innerHTML = cnavdisplist;

    var divCNAVUnitlist = document.getElementById("CNAVUnitList");
    divCNAVUnitlist.innerHTML = cnavunitlistText;
}

function hideCNAVMessage() {
    hidedroplist();
    hideCannery();
    fadeout("divNAVMessageCenter");
}

// Select Items
// cbElement - input field name attribute
// targetfield - input field to display the string of values with ; between them
function SelectItems(cbElement, targetfield) {
    var strContent = "";
    var cblist = document.getElementsByName(cbElement);
    for (var i = 1; i < cblist.length; i++) {
        if (cblist[i].checked == true) {
            //strContent = strContent + cblist[i].content + ";";
            strContent = strContent + cblist[i].parentNode.innerText + ";";
        }
        else {
            cblist[0].checked = false;   // if at least one item has been unchecked -- uncheck All Devices
        }
    }

    if (targetfield != null && targetfield != "") {
        var target = document.getElementById(targetfield);
        target.value = strContent;
    }
}

// Select All
// cbElement - input field name attribute
// targetfield - input field to display the string of values with ; between them
function SelectAll(cbElement, targetfield) {
    var strContent = "";
    var cblist = document.getElementsByName(cbElement);

    if (cblist[0].checked == true) {
        // checking all of the options in the list
        for (var i = 1; i < cblist.length; i++) {
            cblist[i].checked = true;
            //strContent = strContent + cblist[i].content + ";";
            strContent = strContent + cblist[i].parentNode.innerText + ";";
        }

        if (targetfield != null && targetfield != "") {
            var target = document.getElementById(targetfield);
            target.value = strContent;
        }
    }
    else {
        // unchecking all of the options in the list
        for (var i = 1; i < cblist.length; i++) {
            cblist[i].checked = false;
        }

        if (targetfield != null && targetfield != "") {
            var target = document.getElementById(targetfield);
            target.value = "";
        }
    }
}

function showdroplist() {
    var divCNAVUnitlist = document.getElementById("CNAVUnitList");
    if (divCNAVUnitlist.style.visibility != "visible") {
        divCNAVUnitlist.style.visibility = "visible";
        divCNAVUnitlist.style.display = "block";
        divCNAVUnitlist.focus;
    }
}

function hidedroplist() {

    // Need to make sure that it is actually moveing out of the div and not just over an element in the div.
    if (event.toElement != null && (event.toElement.id == "divNAVMessageCenter" || event.toElement.id == "MessageTo" || event.toElement.id == "cleft")) {
        var divCNAVUnitlist = document.getElementById("CNAVUnitList");
        divCNAVUnitlist.style.visibility = "hidden";
        divCNAVUnitlist.style.display = "none";
    }

}

function showdispatchdroplist() {
    var divCNAVDispatchDroplist = document.getElementById("CNAVDispatchDroplist");
    if (divCNAVDispatchDroplist.style.visibility != "visible") {
        divCNAVDispatchDroplist.style.visibility = "visible";
        divCNAVDispatchDroplist.style.display = "block";
        divCNAVDispatchDroplist.focus;
    }
}

function hidedispatchdroplist() {
    // Need to make sure that it is actually moveing out of the div and not just over an element in the div.
    if (event.toElement != null && (event.toElement.id == "divSendDirections" || event.toElement.id == "dText" || event.toElement.id == "DispatchTo")) {
        var divCNAVDispatchDroplist = document.getElementById("CNAVDispatchDroplist");
        divCNAVDispatchDroplist.style.visibility = "hidden";
        divCNAVDispatchDroplist.style.display = "none";
    }
}

function LimitText(AId, BId) {   // limit the message body field to a max of 230 characters
    var e1 = document.getElementById(AId);
    var e2 = document.getElementById(BId);
    var l1 = e1.value.length;
    (l1 > 230) ? e1.value = e1.value.substring(0, 230) : e2.innerHTML = (230 - l1).toString() + " Characters remaining.";
}

function showDispatchCannery() {
    fadein("divCannery");
    populateCanneryList();
    countCannery();
    CanneryPost = "DispatchReturnOptions";
}

function showMessageCannery() {
    fadein("divCannery");
    populateCanneryList();
    countCannery();
    CanneryPost = "MessageReturnOptions";
}

function countCannery() {
    var counter = document.getElementById("Label2");
    var strList = "";
    var count = 0;
    var n = 0;
    var cblist = document.getElementsByName('cmbox');
    for (var i = 0; i < cblist.length; i++) {
        if (cblist[i].checked == true) {
            n++;
        }
    }
    var string = "(" + n.toString() + " are currently selected)";
    counter.innerHTML = string;
}

function populateCanneryList() {
    Feed.SCanRsp(m_CurrentUser, populateCanneryListCallback);
}

function populateCanneryListCallback(data) {
    if (data.value != null) {
        m_CanneryList = data.value;
        var string = "";
        var checkedstate = "";
        for (var i = 0; i < m_CanneryList.Rows.length; i++) {
            if (m_CanneryList.Rows[i].Activated) { checkedstate = 'checked' } else { checkedstate = '' };
            //string += "<label class='whiteType' style='padding-right:3px; display:block;'><input type='checkbox' id='cmbox' name='cmbox' value = '" + i.toString() + "' " + checkedstate + " content='" + m_CanneryList.Rows[i].CannedMsg + "' onclick='countCannery();'/>" + m_CanneryList.Rows[i].CannedMsg + "</label>";
            string += "<label class='whiteType' style='padding-right:3px; display:block;'><input type='checkbox' id='cmbox' name='cmbox' value = '" + i.toString() + "' " + checkedstate + " onclick='countCannery();'/>" + m_CanneryList.Rows[i].CannedMsg.replace("''","'") + "</label>";
        }
        document.getElementById("CanneryList").innerHTML = string;
    }
    showCannerySelect();
    countCannery();
}

function importCannery() {      //place selected items into Canned Responses field defined in the global variable "CanneryPost"
    var strList = "";
    var count = 0;
    var cblist = document.getElementsByName('cmbox');
    for (var i = 0; i < cblist.length; i++) {
        if (cblist[i].checked == true) {
            if (count > 0) {
                strList += ";";
            }
            strList += cblist[i].parentNode.innerText;
            count += 1;
        }
    }
    if (CanneryPost == "MessageReturnOptions") {
        var canResponse = document.getElementById("MessageReturnOptions");
        canResponse.value = strList;
    }
    else {
        var canResponse = document.getElementById("DispatchReturnOptions");
        canResponse.value = strList;
    }
    fadeout("divCannery");
}

function hideCannery() {
    fadeout("divCannery");
    var divCanneryEdit = document.getElementById("CannerySelect");
    divCanneryEdit.style.visibility = "visible";
    divCanneryEdit.style.display = "block";
    divCanneryEdit = document.getElementById("CanneryAdd");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryTask");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryRemove");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryRUSure");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
}

function editCannery() {
    var divCanneryEdit = document.getElementById("CannerySelect");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryTask");
    divCanneryEdit.style.visibility = "visible";
    divCanneryEdit.style.display = "block";
    divCanneryEdit = document.getElementById("CanneryAdd");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryRemove");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryRUSure");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
}

function showCanneryadd() {
    var divCanneryEdit = document.getElementById("CannerySelect");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryTask");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryAdd");
    divCanneryEdit.style.visibility = "visible";
    divCanneryEdit.style.display = "block";
    divCanneryEdit = document.getElementById("CanneryRemove");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryRUSure");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";

    //clearing fields in CanneryAdd
    divCanneryEdit = document.getElementById("CannedMsgtxt");
    divCanneryEdit.value = "";
    divCanneryEdit = document.getElementById("CanAutoSelcted");
    divCanneryEdit.checked = false;

}

function showCanneryremove() {
    // unchecking all responses in the list
    var cblist = document.getElementsByName('cmbox');
    for (var i = 0; i < cblist.length; i++) {
        cblist[i].checked = false;
    }
    // displaying the Cannery Remove screen
    var divCanneryEdit = document.getElementById("CannerySelect");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryTask");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryAdd");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryRemove");
    divCanneryEdit.style.visibility = "visible";
    divCanneryEdit.style.display = "block";
    divCanneryEdit = document.getElementById("CanneryRUSure");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
}

function showCanneryRUSure() {
    var divCanneryEdit = document.getElementById("CannerySelect");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryTask");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryAdd");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryRemove");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryRUSure");
    divCanneryEdit.style.visibility = "visible";
    divCanneryEdit.style.display = "block";
}

function showCannerySelect() {
    var divCanneryEdit = document.getElementById("CanneryRUSure");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryTask");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryAdd");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryRemove");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CannerySelect");
    divCanneryEdit.style.visibility = "visible";
    divCanneryEdit.style.display = "block";
}

function CanneryCancel() {
    var divCanneryEdit = document.getElementById("CanneryRUSure");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryTask");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryAdd");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CanneryRemove");
    divCanneryEdit.style.visibility = "hidden";
    divCanneryEdit.style.display = "none";
    divCanneryEdit = document.getElementById("CannerySelect");
    divCanneryEdit.style.visibility = "visible";
    divCanneryEdit.style.display = "block";
}

function addCanneryResponse() {
    // insert code here to call feed for addition of cannery items
    oSESSIONKEY = document.getElementById("SESSIONKEY");
    sessionQueryKey = oSESSIONKEY.getAttribute("value");
    var inputCannedMsgtxt = document.getElementById("CannedMsgtxt");
    var inputCanAutoSelected = document.getElementById("CanAutoSelcted");
    Feed.ICanRsp(m_CurrentUser, sessionQueryKey, inputCannedMsgtxt.value, inputCanAutoSelected.checked, populateCanneryList);
}

function removeCanneryResponse() {
    // insert call to feed here for removal of cannery items
    oSESSIONKEY = document.getElementById("SESSIONKEY");
    sessionQueryKey = oSESSIONKEY.getAttribute("value");

    var cblist = document.getElementsByName('cmbox');
    for (var i = 0; i < cblist.length; i++) {
        if (cblist[i].checked == true) {
            //Feed.DCanRsp(m_CurrentUser, sessionQueryKey, cblist[i].content, populateCanneryList);
            Feed.DCanRsp(m_CurrentUser, sessionQueryKey, cblist[i].parentNode.innerText, populateCanneryList);
        }
    }
}

function sendCNAVMessage() {
    var TargetRecipients = document.getElementById("MessageTo");
    var TargetDevices = new Array();
    var MessageContent = document.getElementById("mText");
    var ReturnOptions = document.getElementById("MessageReturnOptions");
    var itext = document.getElementById("iText")
    var crlf = String.fromCharCode(13) + String.fromCharCode(10);
    var MsgType = "3";
    var msgOpts = new Array();
    var stringMsg = "";
    var i = 0;
    var e = 0;
    var n = 0;
    var recipients = new Array();                                               // first, parse Recipients and convert to array of serials
    recipients = TargetRecipients.value.split(';');
    var tmpVehicles = getAccountVehicles('MSG');                               // array the elements for valid MSG vehicles
    if (tmpVehicles != null) {
        for (e = 0; e < recipients.length - 1; e++) {                               // run the circuit of all recipients
        //for (e = 0; e < tmpVehicles.length -1; e++) {
            //for (i = 0; i < cars.Rows.length; i++) {                                // loop to find the friendly name
            for (i = 0; i < tmpVehicles.Rows.length; i++) {
                //if (UCase(trim(cars.Rows[i].n)) == UCase(trim(recipients[e]))) {    // found it!
                if (UCase(trim(tmpVehicles.Rows[i].n)) == UCase(trim(recipients[e]))) {
                    //TargetDevices[n] = cars.Rows[i].s;                              // add the serial to the array
                    TargetDevices[n] = tmpVehicles.Rows[i].s;
                    n = n + 1;                                                      // increment the array index
                    break;                                                          // and get the heck OUT!
                }
            }
        }
    }
    if (ReturnOptions.value != '') {                                            // next, we see if there are return options
        MsgType = "2";                                                          // YES, so MsgType=2 multiple choice response
        var j = 0;
        for (i = 1; i < 10; i++) {
            msgOpts.push("");                                                   // clear any priors
        }
        msgOpts = ReturnOptions.value.split(';');
        for (i = 0; i < msgOpts.length; i++) {
            msgOpts[i] = msgOpts[i];
        }
    }
    oSESSIONKEY = document.getElementById("SESSIONKEY");
    sessionQueryKey = oSESSIONKEY.getAttribute("value");
    for (i = 0; i < TargetDevices.length; i++) {                                // finally, we loop our recipients and ship 'em off
        var targetdevice = TargetDevices[i];
        Feed.IMsgCpl(m_CurrentUser, sessionQueryKey, targetdevice.toString(), MsgType, MessageContent.value, msgOpts);
        stringMsg = dtime + " - " + m_CurrentUser + " to " + recipients[i] + ": " + MessageContent.value;
        if (ReturnOptions.value != '') { stringMsg += " (Return Options:" + ReturnOptions.value + ")" }
        itext.value += stringMsg + crlf;
    }
    //setting the scroll to the bottom line
    itext.scrollTop = itext.scrollHeight;
    //clearing the screen Fields
    MessageContent.value = "";
    ReturnOptions.value = "";
}

function sendCNAVDispatch() {
    var TargetRecipients = document.getElementById("DispatchTo");
    var TargetDevices = new Array();
    var MessageContent = document.getElementById("dText");
    var DispatchReturnOptions = document.getElementById("DispatchReturnOptions");
    var itext = document.getElementById("iText");
    var crlf = String.fromCharCode(13) + String.fromCharCode(10);
    var MsgType = "3";
    var msgOpts = new Array();
    var stringMsg = "";
    var i = 0;
    var e = 0;
    var n = 0;
    var recipients = new Array();                                               // first, parse Recipients and convert to array of serials
    recipients = TargetRecipients.value.split(';');                             // array the elements
    for (e = 0; e < recipients.length - 1; e++) {                               // run the circuit of all recipients
        for (i = 0; i < cars.Rows.length; i++) {                                // loop to find the friendly name
            if (UCase(trim(cars.Rows[i].n)) == UCase(trim(recipients[e]))) {    // found it!
                TargetDevices[n] = cars.Rows[i].s;                              // add the serial to the array
                n = n + 1;                                                      // increment the array index
                break;                                                          // and get the heck OUT!
            }
        }
    }
    if (DispatchReturnOptions.value != '') {                                    // next, we see if there are return options
        MsgType = "2";                                                          // YES, so MsgType=2 multiple choice response
        var j = 0;
        for (i = 1; i < 10; i++) {
            msgOpts.push("");                                                   // clear any priors
        }
        msgOpts = DispatchReturnOptions.value.split(';');
        for (i = 0; i < msgOpts.length; i++) {
            msgOpts[i] = msgOpts[i];
        }
    }
    oSESSIONKEY = document.getElementById("SESSIONKEY");
    sessionQueryKey = oSESSIONKEY.getAttribute("value");
    for (i = 0; i < TargetDevices.length; i++) {                                // finally, we loop our recipients and ship 'em off

        // Checking the dispatch for valid address and lat / lon
        addressFind = document.getElementById("DTDtxtAddressFind");
        if (addressFind.value == "1234 North Any Street, City, State" || trim(addressFind.value, "") == "") {
            AlertMessage("A destination has not been defined.");
            return false;
        }

        // if a ; character is present in the address field then the user entered a latitude;longitude
        //  this will return the address based on lat/lon
        if (addressFind.value.indexOf(';') > -1) {
            var tmpArray = new Array();
            tmpArray = addressFind.value.split(';');
            rLat = tmpArray[0];
            rLon = tmpArray[1];
            Feed.MpPntRvGeo(rLat, rLon, DTDlookupLatLonCallback);
            UserMessage("Please verify the address is correct and press Send.");
            return false;
        }
        else {
            if (rLat == null || rLon == null) {
                DTDlookupAddress();
                UserMessage("Please verify the address is correct and press Send.");
                return false;
            }

            // only process the message if the address is going to be sent
            var targetdevice = TargetDevices[i];
            
            
            if (MessageContent.value != '') {                                       // don't waste our time if no message content
                // only send message for X5 Copilot OR if Response Options are entered
                if (targetdevice.toString().substring(0,1) == "8" || ( msgOpts.length > 0)) {
                Feed.IMsgCpl(m_CurrentUser, sessionQueryKey, targetdevice.toString(), MsgType, MessageContent.value, msgOpts);
                stringMsg = dtime + " - " + m_CurrentUser + " to " + recipients[i] + ": " + MessageContent.value;
                if (DispatchReturnOptions.value != '') { stringMsg += " (Return Options:" + DispatchReturnOptions.value + ")" }
                itext.value += stringMsg + crlf;
            }
            }

            // Sending Dispatch
            var addrs = addressFind.value.split(',');
            Feed.IDrvDir(m_CurrentUser, targetdevice.toString(), trim(addrs[0]), trim(addrs[1]), trim(addrs[2]), rLat + "", rLon + "", MessageContent.value, hideCNAVDispatch)
            stringMsg = dtime + " - " + recipients[i] + " Dispatched to " + addressFind.value + ".";
            itext.value += stringMsg + crlf;
             
        }
    }
    //setting the scroll to the bottom line
    itext.scrollTop = itext.scrollHeight;
    //clearing the Fields on the screen
    MessageContent.value = "";
    addressFind.value = "1234 North Any Street, City, State";
    DispatchReturnOptions.value = "";
    
    // Mission complete.
    openCNAVMessage();
}

function openDirectionsToDriver() {

    if (m_bLoggedIn) {
        hideVehicleActionPane();
        // Build vehicle list for drop down list
        buildMsgVehicleList();
        
        fadein("divSendDirections");
        var center = map.GetCenter();
        var addressLAT = center.Latitude
        var addressLON = center.Longitude
        var pixel = map.LatLongToPixel(center);
        pixel.x = pixel.x - 0;
        pixel.y = pixel.y - 0;
        var LL = map.PixelToLatLong(pixel);
        var imgloc = "images/CrossHairs.gif";
        DestinationPin = new VEShape(VEShapeType.Pushpin, LL);
        DestinationPin.SetTitle(DestinationMarker);
        DestinationPin.SetCustomIcon(imgloc);
        map.AddShape(DestinationPin);
        DestinationPinPresent = true;
        rLat = null;
        rLon = null;
        addressFind = document.getElementById("DTDtxtAddressFind");
        addressFind.value = "1234 North Any Street, City, State";
        addressFind.focus();
    }
    else {
        AlertMessage("You must be logged in to use this feature.");
    }
}

function hideCNAVDispatch() {
    if (DestinationPinPresent) {
        DestinationPin.Hide();
        map.DeleteShape(DestinationPin);
        DestinationPinPresent = false;
    }
    fadeout("divSendDirections");
}

function DTDlookupLatLonCallback(response) {
    if (response != null) {
        addressText = document.getElementById("DTDtxtAddressFind");
        addressText.value = response.value;
    }
}

function DTDlookupAddress() {
    addressFind = document.getElementById("DTDtxtAddressFind");
    map.Find(null, addressFind.value, null, null, null, null, true, true, null, true, DTDlookupAddressCallback);
}

function DTDlookupAddressCallback(layer, resultsArray, places, hasMore, veErrorMessage) {
    if (places[0] == null) {
        AlertMessage("Address not found.");
        return;
    }
    else {
        place = places[0].LatLong;
        var addressLAT = place.Latitude;
        var addressLON = place.Longitude;
        var addressFind = document.getElementById("DTDtxtAddressFind");
        addressFind.value = places[0].Name;
        var pixel = map.LatLongToPixel(new VELatLong(addressLAT, addressLON));
        pixel.x = pixel.x - 25;
        pixel.y = pixel.y - 25;
        var LL = map.PixelToLatLong(pixel);
        DestinationPin.SetPoints(LL);
        rLat = LL.Latitude;
        rLon = LL.Longitude;
        //DTDSendDestToDriver();
    }
}

function UCase(strInput) {
    return strInput.toUpperCase();
}

function trimstring(str) { // hyper-fast trim function benchmarked faster than 0.5ms...
    str = str.replace(/^\s\s*/, ''),
	ws = /\s/,
	i = str.length;
    while (ws.test(str.charAt(--i)));
    return str.slice(0, i + 1);
}

function getDriverMessageMaxResponse(response) {
    DriverMessageNumber = response.value; //hit when logging in
    MessageFromDriverTimer = setInterval("checkMessageFromDriver();", 15000);
}

function getDriverGMessageMaxResponse(response) {
    DriverGMesageNumber = response.value; //hit when logging in
    MessageFromDriverTimer = setInterval("checkGMessageFromDriver();", 15000);
}

function openMessageToDriver(id) {   // this is now strictly for SMS messages...
    if (m_bLoggedIn) {
        hideVehicleActionPane();
        m_divOLROverlay = null;
        m_divOLROverlay = document.getElementById("divSendMessageToDriver");
        var txtMessageToDriver = document.getElementById("txtMessageToDriver");
        txtMessageToDriver.value = "";
        mtdPhoneNo = document.getElementById("mtdPhoneNo");
        mtdPhoneNo.value = "";
        mtdCarrier = document.getElementById("mtdCarrier");
        mtdCarrier.value = "";
        m_divOLROverlay.style.marginTop = parseInt(0);
        m_divOLROverlay.style.position = "absolute";
        m_divOLROverlay.style.top = "4px";
        m_divOLROverlay.style.left = "22px";
        m_divOLROverlay.style.height = "400px";
        fadein("divSendMessageToDriver");
        txtMessageToDriver.focus();
    }
    else {
        AlertMessage("You must be logged in to use this feature.");
    }
}

function hideMessageToDriver() {
    fadeout("divSendMessageToDriver");
}

function sendMessageToDriver() {        // SMS ONLY
    var txtMessageToDriver = document.getElementById("txtMessageToDriver");
    if (trim(txtMessageToDriver.value, " ") == "") {
        AlertMessage("You must enter a message to send.");
        return;
    }
    clickedOnSerial += "";
    mtdPhoneNo = document.getElementById("mtdPhoneNo");
    mtdCarrier = document.getElementById("mtdCarrier");
    if (mtdPhoneNo.value == "") {
        AlertMessage("You must enter a phone number.");
        return;
    }
    if (mtdCarrier.value == "") {
        AlertMessage("You must select a carrier.");
        return;
    }
    DAL.EmailRequest_Insert(document.getElementById("SESSIONKEY").getAttribute("value"), mtdPhoneNo.value + "@" + mtdCarrier.value, txtMessageToDriver.value, "", sendMessageToDriverCallback); 
}

function sendMessageToDriverCallback(results) {
    ActionCompleted("Text message sent to driver");
    hideMessageToDriver();
    oSESSIONKEY = document.getElementById("SESSIONKEY");
    sessionQueryKey = oSESSIONKEY.getAttribute("value");
}

//hit when logging in almost complete, and periodicaly after
function checkMessageFromDriver() {
    oSESSIONKEY = document.getElementById("SESSIONKEY");
    var sessionQueryKey = oSESSIONKEY.getAttribute("value");
    Feed.SDrvMsg(m_CurrentUser, sessionQueryKey, DriverMessageNumber * 1, checkMessageFromDriverCallback);
}

//hit when login almost complete, periodicaly after
function checkMessageFromDriverCallback(results) {
    driverResponse = results.value;
    var carName = "";
    var crlf = String.fromCharCode(13) + String.fromCharCode(10);
    if (driverResponse != null && typeof (driverResponse) == "object" && driverResponse.Rows.length > 0) {
        for (var i = 0; i < cars.Rows.length; i++) {
            if (cars.Rows[i].s == driverResponse.Rows[0].Sender || cars.Rows[i].s == driverResponse.Rows[0].VehicleId) {
                carName = cars.Rows[i].n;
            }
        }
        var stringMsg = ""
        if (driverResponse.Rows[0].Type == 3 && driverResponse.Rows[0].DeviceInitiated == 1) {
            NAVMsghandle = document.getElementById("divNAVMessageCenter");
            if (NAVMsghandle.style.visibility != "visible") { openCNAVMessage(); }
            stringMsg = "";
            var currentTime = new Date();
            stringMsg = dtime + " - " + carName + ": " + driverResponse.Rows[0].Question;
            var itext = document.getElementById("iText");
            itext.value += stringMsg + "" + crlf;
        }
        else {
            if (driverResponse.Rows[0].Type == 4) {
                if (driverResponse.Rows[0].Response == 0) {
                    stringMsg += "Yes";
                }
                else {
                    stringMsg += "No";
                }
            }
            else if (driverResponse.Rows[0].Type == 3) {
                stringMsg += driverResponse.Rows[0].Response;
            }
            else if (isNumeric(driverResponse.Rows[0].Response)) {
                switch (driverResponse.Rows[0].Response) {
                    case "0":
                        stringMsg += driverResponse.Rows[0].Option1;
                        break;
                    case "1":
                        stringMsg += driverResponse.Rows[0].Option2;
                        break;
                    case "2":
                        stringMsg += driverResponse.Rows[0].Option3;
                        break;
                    case "3":
                        stringMsg += driverResponse.Rows[0].Option4;
                        break;
                    case "4":
                        stringMsg += driverResponse.Rows[0].Option5;
                        break;
                    case "5":
                        stringMsg += driverResponse.Rows[0].Option6;
                        break;
                    case "6":
                        stringMsg += driverResponse.Rows[0].Option7;
                        break;
                    case "7":
                        stringMsg += driverResponse.Rows[0].Option8;
                        break;
                    case "8":
                        stringMsg += driverResponse.Rows[0].Option9;
                        break;
                }
            }
            else {
                stringMsg += driverResponse.Rows[0].Response;
            }
            NAVMsghandle = document.getElementById("divNAVMessageCenter");
            if (NAVMsghandle.style.visibility != "visible") { openCNAVMessage(); }
            var currentTime = new Date();
            stringMsg = dtime + " - " + carName + ": Response:" + stringMsg + " (Original Message:" + driverResponse.Rows[0].Question + ")";
            var itext = document.getElementById("iText");
            itext.value += stringMsg + crlf;

        }

        //setting scroll to the bottom line
        itext.scrollTop = itext.scrollHeight;
    }
    else {//hit when login almost complete and periodicaly after
        // MessageFromDriverTimer = setTimeout("checkMessageFromDriver();", 10000); 
    }
}

// GARMIN MESSAGING
//hit when logging in almost complete, and periodicaly after
function checkGMessageFromDriver() {
    oSESSIONKEY = document.getElementById("SESSIONKEY");
    var sessionQueryKey = oSESSIONKEY.getAttribute("value");
    Feed.SDrvGMsg(m_CurrentUser, sessionQueryKey, DriverGMessageNumber * 1, checkGMessageFromDriverCallback);
}

//hit when login almost complete, periodicaly after
function checkGMessageFromDriverCallback(results) {
    driverResponse = results.value;
    var carName = "";
    var stringMsg = "";
    var crlf = String.fromCharCode(13) + String.fromCharCode(10);
    if (driverResponse != null && typeof (driverResponse) == "object" && driverResponse.Rows.length > 0) {

        for (var x = 0; x < driverResponse.Rows.length; x++) {
            // Getting the device name
            for (var i = 0; i < cars.Rows.length; i++) {
                if (cars.Rows[i].s == driverResponse.Rows[x].sender || cars.Rows[i].s == driverResponse.Rows[x].VehicleName) {
                    carName = cars.Rows[i].n;
                }
            }

            stringMsg = "";
            
            NAVMsghandle = document.getElementById("divNAVMessageCenter");
            if (NAVMsghandle.style.visibility != "visible") { openCNAVMessage(); }

            var currentTime = new Date();
            stringMsg = dtime + " - " + carName + ": " + driverResponse.Rows[x].body;
            var itext = document.getElementById("iText");
            itext.value += stringMsg + "" + crlf;
            
            // stringMsg = dtime + " - " + carName + ": Response:" + stringMsg + " (Original Message:" + driverResponse.Rows[0].Question + ")";

            //setting scroll to the bottom line
            itext.scrollTop = itext.scrollHeight;
        }
    }
    else {//hit when login almost complete and periodicaly after
        // MessageFromDriverTimer = setTimeout("checkMessageFromDriver();", 10000); 
    }
}


function mtd_NoInputHandler(event) {
    var keycode;
    if (window.event) {
        keycode = event.keyCode;
    }
    else if (e.which) {
        keycode = e.which;
    }
    else {
        mtd_KeypadPressed(-1);
    }
}

function mtd_KeypadPressed(key) {
    mtdPhoneNo = document.getElementById("mtdPhoneNo");
    switch (key) {
        case -1: // keyboard input
            break;
        case 10: // asterisk
            mtdPhoneNo.value += "*";
            break;
        case 11: // pound
            mtdPhoneNo.value += "#";
            break;
        default: // numbers
            mtdPhoneNo.value += key;
    }
}

//                                                  End of SMS to Driver
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function openLoadNotification() {
    m_divROverlay = document.getElementById("divLoadNotification")
    m_divROverlay.style.visibility = "visible";
    vloader_src = document.getElementById("vloader");
    if (vloader_src != null)
        vloader_src.src = cached_loader.src;
}

function hideopenLoadNotification() {
    m_divROverlay = document.getElementById("divLoadNotification");
    m_divROverlay.style.visibility = "hidden";
}

function openSearchResultsWindow() {
    fadein("divSearchResults");
}

function hideSearchResultsWindow() {
    clearsearchmarkers();
    m_divROverlay = document.getElementById("divSearchResults");
    fadeout("divSearchResults");
}

function clearsearchmarkers() {
    if (FindResultArray.length > 0) {
        for (var i = 0; i < FindResultArray.length; i++) {
            FindResultArray[i].Shape.Hide();
            ResultInfo[i].Hide();
        }
    }
}


function openDemoNotification(message) {
    m_divROverlay = document.getElementById("divDemoNotification");
    m_divROverlay.style.marginTop = parseInt(0);
    m_divROverlay.style.display = "block";
    m_divROverlay.style.visibility = "visible";
    m_divROverlay.style.position = "absolute";
    m_divROverlay.style.width = "488px";
    m_divROverlay.style.height = "308px";
    m_divROverlay.style.top = "162px";
    m_divROverlay.style.left = "262px";
    m_divROverlay = null;
    //fadein("divDemoNotification");
    vloader_src = document.getElementById("vloader");
    if (vloader_src != null)
        vloader_src.src = cached_loader.src;
}

function hideDemoNotification() {
    m_divROverlay = document.getElementById("divDemoNotification");
    m_divROverlay.style.visibility = "hidden";
    m_divROverlay = null;
}

function openGeneralNotification(message) {
    m_divROverlay = document.getElementById("divGeneralNotification");
    getPageSize();
    m_divROverlay.style.top = parseInt(windowHeight / 2);
    m_divROverlay.style.left = parseInt(windowWidth / 2 - 130);
    m_divROverlay.style.visibility = "visible";
    textMessage = document.getElementById("GENERALTEXTMSG");
    textMessage.innerHTML = message;

    vloader_src = document.getElementById("vloader");
    if (vloader_src != null)
        vloader_src.src = cached_loader.src;
}
function hideGeneralNotification() {
    m_divROverlay = document.getElementById("divGeneralNotification");
    m_divROverlay.style.visibility = "hidden";
}
function AlertMessage(message) {
    textMessage = document.getElementById("divXMessage");
    textMessage.innerHTML = message;
    fadein("divMessageWithX");
}
function hideAlertMessage() {
    fadeout("divMessageWithX");
}
// This is a blank window that you can display messages in.
function UserMessage(message) {
    textMessage = document.getElementById("divBlankMsg");
    textMessage.innerHTML = message;
    fadein("divBlankMsgWithX");
}
function hideUserMessage() {
    fadeout("divBlankMsgWithX");
}
function ActionCompleted(message) {
    textMessage = document.getElementById("divOutput");
    textMessage.innerHTML = message;
    fadein("divActionCompleted");
}
function hideActionCompleted() {
    fadeout("divActionCompleted");
}
//function opennoVehicleSelectedNotify() {
//    m_divROverlay = document.getElementById("noVehicleSelectedNotify");
//    fadein("noVehicleSelectedNotify");
//    vloader_src = document.getElementById("vloader");
//    if (vloader_src != null)
//        vloader_src.src = cached_loader.src;
//}

//function hidenoVehicleSelectedNotify() {
//    fadeout("noVehicleSelectedNotify");
//}

function getOverlaySize() {
    windowWidth = parseInt(window.screen.width - 20);
    windowHeight = parseInt(window.screen.height - 190);
}

function getPageSize() {
    if (self.innerHeight) {	// all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }
    if (requestedHeight != 0 && requestedWidth != 0) {
        windowHeight = requestedHeight;
        windowWidth = requestedWidth;
    }
}

function body_onLoad() {
    getPageSize();
    m_divMap = document.getElementById("divMap");
    m_divMap.style.visibility = "hidden";
    elementMainTable = document.getElementById("tblMain");
    currentTime = new Date();
    m_strDateTime = currentTime;
    rpt_Report = new StringBuilder("");
    preloadMarkers();
    TheBrowser = whichBrs();

    //Initialize Variables
    m_ddlVehicles = document.getElementById("ddlVehicles");
    m_ddlAlerts = document.getElementById("ddlAlertList");
    m_ddlCannery = document.getElementById("ddlCannery");
    m_AlertVehicleList = document.getElementById("ddlVehicleSpeedAlert");
    m_ZoneVehicleList = document.getElementById("ddlVehicleZoneAlert");
    m_OLRVehiclesList = document.getElementById("ddlOLRVehicles");
    m_VTVehiclesList = document.getElementById("ddlVTVehicles");
    m_IGNVehicleList = document.getElementById("ddlVehicleIgnAlert");
    m_ddlVehicleGroupEditor = document.getElementById("vgVehicles");
    m_ddlVehicleDriversEditor = document.getElementById("vdVehicles");
    showHistCalendar();
    loadMap();
    loadMarkers(-1);
    tooltip = document.createElement("div");
    autologin();
    resizeMap();

    m_divMap.style.visibility = "visible";
    ActivityTray = false;
    
    Feed.SIcnFld(loadIconSizes);
    Feed.SMblCar(getMobilProviders_CallBack);

    hookEvent(window, "resize", body_onResize);
    hookEvent(window, "error", stopError);
    hookEvent("RadarCB", "click", RadarCB_onclick);
    hookEvent("CloudCB", "click", CloudCB_onclick);
    hookEvent("LoopWeatherCB", "click", LoopWeatherCB_onclick);

    setTimeout("hideSplash();", 2000);
}

function hideSplash() {
    fadeout("splash");
}

function body_onResize() {
    var strParams = location.pathname.split("/");
    var strPage = strParams[strParams.length - 1];
    switch (strPage) {
        case "map.aspx":
            resizeMap();
            break;
        default:
            break;
    }
}

function body_onUnload() {
    var strParams = location.pathname.split("/");
    var strPage = strParams[strParams.length - 1];
    switch (strPage) {
        case "map.aspx":
            break;
    }
}

//MAP TOKEN EVENTS ////////////////////////
function HandleTokenExpire() {
    // insert code here to handle token expiration
    AlertMessage("Your Microsoft Virtual Earth token has expired<br/>because your session exceeded their time limit.<br/>(This is their rule, not ours.)<br/> Please log in again");
    logout();
}

function HandleTokenError() {
    // insert code here to handle token errors
    //alert("There was an error processing your request: [Token errors]: " + map.Error.toString());
}

//////////////////////////

function loadMap() {


    //create map obj
    map = new VEMap('divMap');
    var mapOptions = new VEMapOptions();
    mapOptions.UseEnhancedRoadStyle = true;
    map.LoadMap(
               new VELatLong(37.160317, -99.667969),  // center
               4, // zoom level
               VEMapStyle.Hybrid, // map style
               false, // fixed map
               VEMapMode.Mode2D, // map mode
               true,  // show map mode switch
               0, // tile buffer
               mapOptions// options
            );

    map.HideDashboard();

    //map.LoadMap(new VELatLong(37.160317, -99.667969), 4, VEMapStyle.Hybrid, false, VEMapMode.Mode2D, false, 0);
    map.SetMouseWheelZoomToCenter(false);
    map.HideDashboard();

    //create map shape layer
    address_marker_layer = new VEShapeLayer();
    address_marker_layer.SetClusteringConfiguration(VEClusteringType.Grid);

    full_address_marker_layer = new VEShapeLayer();
    map.AddShapeLayer(full_address_marker_layer);
    full_address_marker_layer.Hide();

    //Events
    map.AttachEvent('onclick', mapMouseClick);
    map.AttachEvent('onmousemove', mapMouseMove);
    map.AttachEvent("onmouseover", mapMouseOver);
    map.AttachEvent("onmouseout", mapMouseOut);
    map.AttachEvent("onmousedown", mapMouseDown);
    map.AttachEvent("onmouseup", mapMouseUp);
    map.AttachEvent("onstartzoom", mapZoomStart);
    map.AttachEvent("onendzoom", mapZoomEnd);
    map.AttachEvent("onstartpan", mapPanStart);
    map.AttachEvent("onendpan", mapPanEnd);

}

function getMobilProviders_CallBack(response) {
    SMSPROVIDERGFOBJ = document.getElementById("SMSPROVIDERGF");
    SMSPROVIDERAROBJ = document.getElementById("SMSPROVIDERAR");
    SMSPROVIDERSZOBJ = document.getElementById("SMSPROVIDERSZ");
    SMSPROVIDERSPOBJ = document.getElementById("SMSPROVIDERSP");
    SMSPROVIDERIGNOBJ = document.getElementById("SMSPROVIDERIGN");
    DriverPROVIDER1 = document.getElementById("DriverPROVIDER1");
    DriverPROVIDER2 = document.getElementById("DriverPROVIDER2");
    selFMProviderOBJ = document.getElementById("selFMProvider");
    
    mtdCarrier = document.getElementById("mtdCarrier");
    if ((SMSPROVIDERGFOBJ != null) && (SMSPROVIDERSZOBJ != null) && (SMSPROVIDERSPOBJ != null)) {
        // clear out the selection boxes
        for (var i = (SMSPROVIDERGFOBJ.options.length - 1); i >= 0; i--) {
            SMSPROVIDERGFOBJ.options[i] = null;
        }
        for (var i = (SMSPROVIDERSZOBJ.options.length - 1); i >= 0; i--) {
            SMSPROVIDERSZOBJ.options[i] = null;
        }
        for (var i = (SMSPROVIDERSPOBJ.options.length - 1); i >= 0; i--) {
            SMSPROVIDERSPOBJ.options[i] = null;
        }
        for (var i = (SMSPROVIDERIGNOBJ.options.length - 1); i >= 0; i--) {
            SMSPROVIDERIGNOBJ.options[i] = null;
        }
        for (var i = (selFMProviderOBJ.options.length - 1); i >= 0; i--) {
            selFMProviderOBJ.options[i] = null;
        }
        for (var i = (mtdCarrier.options.length - 1); i >= 0; i--) {
            mtdCarrier.options[i] = null;
        }
        for (var i = (DriverPROVIDER1.options.length - 1); i >= 0; i--) {
            DriverPROVIDER1.options[i] = null;
        }
        for (var i = (DriverPROVIDER2.options.length - 1); i >= 0; i--) {
            DriverPROVIDER2.options[i] = null;
        }

        SMSPROVIDERAROBJ.options.length = 0;
        providers = response.value;
        if (providers != null && typeof (providers) == "object" && providers.Rows.length > 0) {
//            DriverPROVIDER1.options[i] = new Option("", "");
//            DriverPROVIDER2.options[i] = new Option("", "");
            for (var i = 0; i < providers.Rows.length; i++) {
                SMSPROVIDERGFOBJ.options[i] = new Option(providers.Rows[i].name, providers.Rows[i].URL);
                SMSPROVIDERAROBJ.options[i] = new Option(providers.Rows[i].name, providers.Rows[i].URL);
                SMSPROVIDERSZOBJ.options[i] = new Option(providers.Rows[i].name, providers.Rows[i].URL);
                SMSPROVIDERSPOBJ.options[i] = new Option(providers.Rows[i].name, providers.Rows[i].URL);
                SMSPROVIDERIGNOBJ.options[i] = new Option(providers.Rows[i].name, providers.Rows[i].URL);
                DriverPROVIDER1.options[i + 1] = new Option(providers.Rows[i].name, providers.Rows[i].URL);
                DriverPROVIDER2.options[i + 1] = new Option(providers.Rows[i].name, providers.Rows[i].URL);
                selFMProviderOBJ.options[i] = new Option(providers.Rows[i].name, providers.Rows[i].URL);
                mtdCarrier.options[i + 1] = new Option(providers.Rows[i].name, providers.Rows[i].URL);
            }
        }
        SMSPROVIDERAROBJ.value = "txt.att.net";
    }
}

function StandardizeTimeFormat(inboundatum, outboundatum) {
    var indat = inboundatum.toString();
    var outboundatum = "";
    var datetimeset = indat.split(" ");
    var newdatetime = "";
    if (TheBrowser == "internet explorer") {
        newdatetime = datetimeset[0] + " ";
        newdatetime += datetimeset[1] + " ";
        newdatetime += datetimeset[2] + " ";
        newdatetime += datetimeset[5] + " ";
        newdatetime += datetimeset[3];
    }
    else {
        newdatetime = datetimeset[0] + " ";
        newdatetime += datetimeset[1] + " ";
        newdatetime += datetimeset[2] + " ";
        newdatetime += datetimeset[3] + " ";
        newdatetime += datetimeset[4];
    }
    return newdatetime;
}

function loadMarkers(sessionID) {
    if (m_bViewHistory) {
        clearInterval(m_loadInterval);
        return;
    }
    // setting load markers running to true
    m_loadMarkerRunning = true;

    //group filter
    groupFilter = document.getElementById("ddlGroups");

    if (sessionID != null && sessionID != '' && sessionID != -1) { //&& m_ddlVehicles != null
        if (m_groupView && groupFilter.selectedIndex > 0) {
            if (m_vehicleGroups.Rows[groupFilter.selectedIndex - 1].serials != null) {
                //  passing vehicle ids of a group
                var filterString = m_vehicleGroups.Rows[groupFilter.selectedIndex - 1].serials;
                while (filterString.charAt(filterString.length - 1) == " " || filterString.charAt(filterString.length - 1) == ",") {
                    filterString = filterString.substring(0, filterString.length - 1);
                }
                Feed.SLvData(sessionID, filterString, loadMarkers_CallBack);
            }
            else {
                //  asking for all vehicles
                Feed.SLvData(sessionID, "0", loadMarkers_CallBack);
            }
        }
        else if (m_ddlVehicles.value != "" && m_ddlVehicles.value != null && m_ddlVehicles.value != -1) {
            if (!m_bViewHistory) {
                // asking for one vehicle id
                Feed.SLvData(sessionID, m_ddlVehicles.value, loadMarkers_CallBack);
            }
        }
        else {
            //  asking for all vehicles
            Feed.SLvData(sessionID, "0", loadMarkers_CallBack);
        }
    }
}

/////////////////////////////////////////////////// LOADMARKERS! /////////////////////////////////////////////////////////
function loadMarkers_CallBack(response) {
    dtime = datetime();
    var dtimeNoYear = datetimeNoYear();
    clearInterval(m_loadInterval);
    if (m_bViewHistory) {
        return;
    }
    //hide if we haven't already
    m_divROverlay = document.getElementById("divLoadNotification");
    if (m_divROverlay != null) {
        if (m_divROverlay.style.visibility != "hidden") {
            hideopenLoadNotification();
        }
    }

    cars = response.value;
    if (cars != null && typeof (cars) == "object" && cars.Rows.length > 0) {
        if (carPins.length != cars.Rows.length) {
            m_firstRetrieve = true;
        }

        if (m_firstRetrieve == true) {
            lastCars = cars;
        }

        for (var i = 0; i < carPins.length; i++) {
            carPins[i].Hide();
            nameTags[i].Hide();
            infoBoxes[i].Hide();
        }

        //  panic code
        eraseCarsInPanic();
        //  end of panic code

        var carWeAreFollowing = 0;
        //  data is present
        if (m_firstRetrieve == true) {
            // lastCars holds the cars data from last time
            carPins = new Array();
            nameTags = new Array();
            infoBoxes = new Array();
            clearMap();
        }
        var minLat = 50000000;
        var minLon = 50000000;
        var maxLat = -50000000;
        var maxLon = -50000000;

        // Set up to force load of the vehicle dropdown
        var NeedToLoadDropDown = 0;
//        var cnavunitlistText = "";
//        //cnavunitlistText = "";
//        var cnavdisplist = "";
//        var cnavunitcount = 1;
        // Set up to force load of the vehicle dropdown
        if (m_ddlVehicles.options.length == 0) {
            bPopulateOptions = true;
//            cnavunitlistText = "<label class='whiteType' style='padding-right:3px;display:block;'><input name='cbvlist' value='1' type='checkbox' id='cb1' onclick='SelectAll(\"cbvlist\",\"MessageTo\");' />ALL Devices</label>";
//            cnavdisplist = "<label class='whiteType' style='padding-right:3px;display:block;'><input name='cbdlist' value='1' type='checkbox' id='cd1' onclick='SelectAll(\"cbdlist\",\"DispatchTo\");' />ALL Devices</label>";
            m_ddlVehicles.options[0] = new Option("View All Vehicles", "-1");
            m_ddlVehicleGroupEditor[0] = new Option("Add All Vehicles", "-1");
            m_ddlVehicleDriversEditor[0] = new Option("Add All Vehicles", "-1");
            m_AlertVehicleList.options[0] = new Option("All Vehicles", "-1");
            m_ZoneVehicleList.options[0] = new Option("All Vehicles", "-1");
            m_OLRVehiclesList.options[0] = new Option("All Vehicles", "-1");
            m_IGNVehicleList.options[0] = new Option("All Vehicles", "-1");
            NeedToLoadDropDown = 1;
        }
        PinIds = new Array();
        var points = new Array;

        //  set up the header for the scrolling activity window
        ActivityOut = ActivityHeader;
        ActivityCount = 0;

        // Main loop for walking thru the cars    
        for (var i = 0; i < cars.Rows.length; i++) {
            var eightcheck = cars.Rows[i].s + "";
            if (eightcheck.substring(0, 1) == "8" || cars.Rows[i].MsgE.toString() == "true") {
                EightThousandPresent = true;
            }
            // Follow vehicle if control panel lockout and only one vehicle exists on the account.
            // Follow vehicle if device is selected in the control panel Devices Dropdown menu
            if (ControlPanelLockout == true && cars.Rows.length == 1) {
            //if (cars.Rows.length == 1 && (ControlPanelLockout == true || (m_ddlVehicles.value != "" && m_ddlVehicles.value != null && m_ddlVehicles.value != -1))) {
                //vehicleToFollow = cars.Rows[i].s
                setVehicleToFollow(cars.Rows[i].s);
                carWeAreFollowing = i;
            }

            if (vehicleToFollow != null) {
                if (cars.Rows[i].s == vehicleToFollow) {
                    carWeAreFollowing = i;
                }
            }
            //  fix so the car doesn't point north each time it stops 
            if (cars.Rows[i].o == 0 && cars.Rows[i].v == 0) {
                if (cars.Rows[i].s == lastCars.Rows[i].s) {
                    cars.Rows[i].o = lastCars.Rows[i].o;
                }
            }
            // load the drop downs if needed
            if (NeedToLoadDropDown == 1) {
                m_ddlVehicles.options[m_ddlVehicles.options.length] = new Option(cars.Rows[i].n, cars.Rows[i].s);
//                if (cars.Rows[i].s.toString().substring(0, 1) == "8" || cars.Rows[i].s.toString().substring(0, 3) == "380") {
//                    //if (cars.Rows[i].s >= 8000000) {
//                    cnavunitcount = cnavunitcount + 1;
//                    cnavunitlistText += "<label class='whiteType' style='padding-right:3px;display:block;'><input name='cbvlist' value='" + cnavunitcount.toString() + "' type='checkbox' id='cb" + cnavunitcount.toString() + "' onclick='SelectItems(\"cbvlist\",\"MessageTo\");' />" + cars.Rows[i].n + "</label>";
//                    cnavdisplist += "<label class='whiteType' style='padding-right:3px;display:block;'><input name='cbdlist' value='" + cnavunitcount.toString() + "' type='checkbox' id='cd" + cnavunitcount.toString() + "' onclick='SelectItems(\"cbdlist\",\"DispatchTo\");' />" + cars.Rows[i].n + "</label>";
//                }
                m_ddlVehicleGroupEditor.options[m_ddlVehicleGroupEditor.options.length] = new Option(cars.Rows[i].n, cars.Rows[i].s);
                m_ddlVehicleDriversEditor.options[m_ddlVehicleDriversEditor.options.length] = new Option(cars.Rows[i].n, cars.Rows[i].s);
                m_AlertVehicleList.options[m_AlertVehicleList.options.length] = new Option(cars.Rows[i].n, cars.Rows[i].s);
                m_ZoneVehicleList.options[m_ZoneVehicleList.options.length] = new Option(cars.Rows[i].n, cars.Rows[i].s);
                m_OLRVehiclesList.options[m_OLRVehiclesList.options.length] = new Option(cars.Rows[i].n, cars.Rows[i].s);
                m_VTVehiclesList.options[m_VTVehiclesList.options.length] = new Option(cars.Rows[i].n, cars.Rows[i].s);
                m_IGNVehicleList.options[m_IGNVehicleList.options.length] = new Option(cars.Rows[i].n, cars.Rows[i].s);
            }
            //  Look for min and max lat and lon to center and optimize zoom
            points[i] = new VELatLong(cars.Rows[i].lt * 1, cars.Rows[i].ln * 1);
            if ((cars.Rows[i].lt * 1) < minLat) { minLat = cars.Rows[i].lt * 1 };
            if ((cars.Rows[i].lt * 1) > maxLat) { maxLat = cars.Rows[i].lt * 1 };
            if ((cars.Rows[i].ln * 1) < minLon) { minLon = cars.Rows[i].ln * 1 };
            if ((cars.Rows[i].ln * 1) > maxLon) { maxLon = cars.Rows[i].ln * 1 };

            var direction = cars.Rows[i].o;
            direction = (Math.floor(((direction * 1) + 5) / 10) * 10);
            if (direction >= 360 || direction < 0) { direction = 0 };

            //  Do a correction if we are in birds eye view and we are not looking north.
            var mapstyle = map.GetMapStyle();

            if (mapstyle == "b") {
                var be = map.GetBirdseyeScene();
                var maporentation = be.GetOrientation();
                if (maporentation == "East") { direction = direction + 270 };
                if (maporentation == "South") { direction = direction + 180 };
                if (maporentation == "West") { direction = direction + 90 };
                if (direction > 360) { direction = direction - 360 };
            }

            //  find the center of the icon so we can center it on the lat/lon 
            var tmpXCenter = 0;
            var tmpYCenter = 0;
            if (cars.Rows[i].XCenter != null) { tmpXCenter = 13 - cars.Rows[i].XCenter; }
            if (cars.Rows[i].YCenter != null) { tmpYCenter = 13 - cars.Rows[i].YCenter; }

            //  build all the info we will show in the carPin, infoBox, and nameTag
            // Adjusting margins based on the vehicles_icon table XCenter and YCenter values to center graphic on lat/lon
            var imageloc = "<img style='margin: " + tmpYCenter + "px 0px 0px " + tmpXCenter + "px' src='images/"; //   /v" + direction + ".gif'/>" ;

            var imageFolder = "default";
            if (cars.Rows[i].iconFolder != null && cars.Rows[i].iconFolder != "") {
                imageFolder = cars.Rows[i].iconFolder;  //+ "/";
            }
            imageloc += imageFolder + "/v" + direction + ".gif'/>";

            var tempTime = cars.Rows[i].timeStamp;
            var revisedTime = "";
            var topPos = 30;
            revisedTime = StandardizeTimeFormat(tempTime);
            var kph = Math.round(cars.Rows[i].v * 1.60934);
            // VEHICLE ID 
            var string = "<br/><br/>" +
                "<label style='position: absolute; top: 30px; left: 12px;'><b>VehicleID:</b></label><label style='position: absolute; top: 30px; left: 75px;'>" + cars.Rows[i].s + "</label><br />";
            // LATITUDE
            string += "<label style='position: absolute; top: 45px; left: 12px;'><b>Latitude:</b></label><label style='position: absolute; top: 45px; left: 75px;'>" + NumberAlterPrecision(cars.Rows[i].lt, 6, false) +
                      "</label><label style='position: absolute; top: 45px; left: 165px;'>" + convertToDegree(cars.Rows[i].lt) + "</label><br />";
            // LONGITUDE
            string += "<label style='position: absolute; top: 60px; left: 12px;'><b>Longitude:</b></label><label style='position: absolute; top: 60px; left: 75px;'>" + NumberAlterPrecision(cars.Rows[i].ln, 6, false) +
                      "</label><label style='position: absolute; top: 60px; left: 165px;'>" + convertToDegree(cars.Rows[i].ln) + "</label><br />";

            if (cars.Rows[i].address == null || cars.Rows[i].address == "") {
//                commented out until we are closer to getting all vehicles reversed geocoded.  -- Rebekah            
//                string += "&nbsp;&nbsp;&nbsp;&nbsp;<b>Address: </b>&nbsp;&nbsp;Coming Soon<br />" +
                //                          "&nbsp;&nbsp;&nbsp;&nbsp;" + "<br />";
                topPos = 75;
                string += "&nbsp;&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;<br />";
            }
            else {
                // ADDRESS
                var tmpstr = new Array;
                tmpstr = cars.Rows[i].address.split("^", 2)
                string += "<label style='position: absolute; top: 75px; left: 12px;'><b>Address: </b></label><label style='position: absolute; top: 75px; left: 75px;'>" + tmpstr[0] + "</label><br />" +
                          //"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                          "<label style='position: absolute; top: 90px; left: 75px;'>" + tmpstr[1] + "</label><br />";
                topPos = 105;
            }
            //HEADING
            string += "<label style='position: absolute; top: " + topPos + "px; left: 12px;'><b>Heading:</label></b>" +
                      "<label style='position: absolute; top: " + topPos + "px; left: 75px;'>" + cars.Rows[i].o + "&#176 / " + define_direction(cars.Rows[i].o, cars.Rows[i].v) + "</label><br />";
            topPos += 15;
            // VELOCITY
            string += "<label style='position: absolute; top: " + topPos + "px; left: 12px;'><b>Velocity:</label></b>" +
                      "<label style='position: absolute; top: " + topPos + "px; left: 75px;'>" + cars.Rows[i].v + " mph / " + kph + " kph</label><br />";
            topPos += 15;
                    
            var idCheck = cars.Rows[i].s * 1;
            idCheck = idCheck + "";
            if ((idCheck.substring(0, 1) == "7" && idCheck.length > 4) || (idCheck.substring(0, 1) == "8" && idCheck.length > 4) || (idCheck.substring(0, 2) == "14" && idCheck.length == 7)) {
                // POWER
                string += "<label style='position: absolute; top: " + topPos + "px; left: 12px;'><b>Power:</label></b>" +
                          "<label style='position: absolute; top: " + topPos + "px; left: 75px;'>" + cars.Rows[i].Power + "%</label><br />" + ""
                topPos += 15;
            }
            else {
                // IGNITION
                if (cars.Rows[i].ignition == 1) {
                    string += "<label style='position: absolute; top: " + topPos + "px; left: 12px;'><b>Ignition:</label></b><label style='position: absolute; top: " + topPos + "px; left: 75px;'>On</label><br />" + "";
                    topPos += 15;
                }
                else if (cars.Rows[i].ignition == -1) {
                    string += "<label style='position: absolute; top: " + topPos + "px; left: 12px;'><b>Ignition:</label></b><label style='position: absolute; top: " + topPos + "px; left: 75px;'>Off</label><br />" + "";
                    topPos += 15;
                }
            }
            // GPS SATELLITES
            if (cars.Rows[i].sats) {
                string += "<label style='position: absolute; top: " + topPos + "px; left: 12px;'><b>GPS Satellites:</label></b>" +
                          "<label style='position: absolute; top: " + topPos + "px; left: 98px;'>" + cars.Rows[i].sats + "</label><br />" + "";
                topPos += 15;
            }
            else {
                string += "<label style='position: absolute; top: " + topPos + "px; left: 12px;'><b>GPS Satellites:</label></b>" +
                          "<label style='position: absolute; top: " + topPos + "px; left: 98px;'>Not Available</label><br />" + "";
                topPos += 15;
            }

            if (idCheck.substring(0, 2) == "53") {
                // MPG
                string += "<label style='position: absolute; top: " + topPos + "px; left: 12px;'><b>MPG:</label></b>" +
                      "<label style='position: absolute; top: " + topPos + "px; left: 45px;'>" + cars.Rows[i].MPG + "</label><br />" + "";
                topPos += 15;

                // Fuel Level
                string += "<label style='position: absolute; top: " + topPos + "px; left: 12px;'><b>Fuel Level:</label></b>" +
                      "<label style='position: absolute; top: " + topPos + "px; left: 78px;'>" + cars.Rows[i].FuelLevel + "</label><br />" + "";
                topPos += 15;
            }

            // LAST MOVED
            string += "<label style='position: absolute; top: " + topPos + "px; left: 12px;'><b>Last Moved:</label></b>";
            if (cars.Rows[i].LastMoved != null && cars.Rows[i].LastMoved != "") {
                var lmovtime = cars.Rows[i].LastMoved;
                var rmovtime = "";
                rmovtime = StandardizeTimeFormat(lmovtime);
                string += "<label style='position: absolute; top: " + topPos + "px; left: 85px;'>" + rmovtime + "</label>";
            }
            topPos += 15;
            // LAST UPDATED
            string += "<br /><label style='position: absolute; top: " + topPos + "px; left: 12px;'><b>Last Update:</label></b>" +
                      "<label style='position: absolute; top: " + topPos + "px; left: 85px;'>" + revisedTime + "</label><br />";
            topPos += 15;  
            // CLICK VEHICLE FOR FURTHER OPTIONS
            string = string + "<label style='position: absolute; top: 210px; left: 60px;'>Click Vehicle for further options</label>"
            var divInfoVar = "<div style='background:URL(images/CurrentDeviceData.png) no-repeat top right Transparent; color:white; font-family:arial; font-size:12px; width:297px; height:253px;'>" + string + "</div>";

            //  change newLatLon to reflect centered icon
            var originalPoint = map.LatLongToPixel(new VELatLong(cars.Rows[i].lt * 1, cars.Rows[i].ln * 1));
            var newx = originalPoint.x;   //- wide;
            var newy = originalPoint.y;   //- hi;
            pixel = new VEPixel(newx, newy);
            newLatLon = map.PixelToLatLong(pixel)

            // if more rows in cars than carPins then add another carPin, nameTag, and infoBox        
            if (i + 1 > carPins.length) {
                carPins[i] = new VEShape(VEShapeType.Pushpin, newLatLon);
                map.AddShape(carPins[i]);
                //carPins[i].SetTitle(cars.Rows[i].s.toString());
                nameTags[i] = new VEShape(VEShapeType.Pushpin, newLatLon);
                map.AddShape(nameTags[i]);
                infoBoxes[i] = new VEShape(VEShapeType.Pushpin, newLatLon);
                map.AddShape(infoBoxes[i]);
                infoBoxes[i].Hide();
            }

            // update the data in the pins, etc
            carPins[i].SetPoints(newLatLon);
            carPins[i].SetCustomIcon(imageloc);
            carPins[i].ShowIcon();
            carPins[i].SetPoints(newLatLon);
            carPins[i].Show();

            //  panic code
            //  sw2 is present in switches 2,3,6,7,10,11,14,15 (all switches are in 1 byte)
            var sw = cars.Rows[i].switches;
            if (sw == 2 || sw == 3 || sw == 6 || sw == 7 || sw == 10 || sw == 11 || sw == 14 || sw == 15 || cars.Rows[i].InRoute == false) {
                carInPanic = true;
            }
            //  end of panic code

            if (true == carInPanic)
                showPTOToggle(true);
            else
                showPTOToggle(false);

            //  if this vehicle has moved then build the data for the scrolling activity window
            if (lastCars.Rows.length > 0) {
                if (cars.Rows[i].lt != lastCars.Rows[i].lt || cars.Rows[i].ln != lastCars.Rows[i].ln) {
                    for (k = 0; k < 29; k++) {
                        if (ActivityContent[k + 1] != null) {
                            ActivityContent[k] = ActivityContent[k + 1];
                        }
                    }
                    var dActivity = document.getElementById("Activity");
                    if (dActivity.up) {
                        if (rowtoggle == true) {
                            rowtoggle = false;
                            accenture = " alt";
                        }
                        else {
                            rowtoggle = true;
                            accenture = " bg";
                        }
                        var ignition = "?"
                        if (cars.Rows[i].ignition == 1) { ignition = "On" };
                        if (cars.Rows[i].ignition == -1) { ignition = "Off" };
                        var sats = "?";
                        if (cars.Rows[i].sats != 0) { sats = cars.Rows[i].sats };
                        var panic = "Off";
                        if (cars.Rows[i].panic == 1) { ignition = "On" };

                        var switches = cars.Rows[i].switches;

                        var aux1 = "Off";
                        if (switches == 4 || switches == 5 || switches == 6 || switches == 7 || switches == 12 || switches == 13 || switches == 14 || switches == 15) {
                            aux1 = "On";
                        }

                        var aux2 = "Off";
                        if (switches > 7) {
                            aux2 = "On";
                        }
                        ActivityContent[29] = "<tr class='data" + accenture + "'><td class='l'>" + dtimeNoYear + "&nbsp;</td><td class='c'>" + cars.Rows[i].n + "&nbsp;&nbsp;</td><td>" + cars.Rows[i].lt + "&nbsp;&nbsp;</td><td>" + cars.Rows[i].ln + "&nbsp;</td><td>" + cars.Rows[i].v + "mph/" + kph + "kph&nbsp;&nbsp;</td><td>" + cars.Rows[i].o + "&nbsp;&nbsp;</td><td>" + sats + "&nbsp;&nbsp;</td><td>" + ignition + "</td><td>" + panic + "</td><td>" + aux1 + "</td><td class='r'>" + aux2 + "</td></tr>";
                        ActivityCount = ActivityCount + 1;
                    }
                }
            }

            var tagwidth = cars.Rows[i].n.length * 10;
            if (TheBrowser == "safari") { tagwidth = tagwidth * 1.2 };
            
            var fontSize = "14";

            if (0 != servicecall_viewmode) {
                fontSize = "8";
            }

            var divVar = "<div style='font-family:arial;font-size:" + fontSize + "px;color: #" + cars.Rows[i].tc + ";font-weight:bold;border:solid 1px Black;background-color: #" + cars.Rows[i].cl + ";width:auto;padding-left:1px; padding-right:1px; white-space:nowrap; '>" + cars.Rows[i].n + "</div>";

            nameTags[i].SetCustomIcon(divVar);
            nameTags[i].ShowIcon();
            nameTags[i].Show();

            infoBoxes[i].SetCustomIcon(divInfoVar);
            infoBoxes[i].Hide();
            PinIds[i] = carPins[i].GetId();

            // End of the cars loop
        }

//        var divCNAVdispatchdroplist = document.getElementById("CNAVDispatchDroplist");
//        divCNAVdispatchdroplist.innerHTML += cnavdisplist;

//        var divCNAVUnitlist = document.getElementById("CNAVUnitList");
//        divCNAVUnitlist.innerHTML += cnavunitlistText;

        if (carInPanic == true) {
            showCarsInPanic();
        }

        var dActivity = document.getElementById("Activity");
        if (dActivity.up) {
            for (k = 0; k < 29; k++) {
                if (ActivityContent[k] == null) { ActivityContent[k] = "<tr class='data bg'><td class='l'>&nbsp;&nbsp;</td><td class='c'>&nbsp;&nbsp;</td><td>&nbsp;&nbsp;</td><td>&nbsp;&nbsp;</td><td>&nbsp;&nbsp;</td><td>&nbsp;&nbsp;</td><td>&nbsp;&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td class='r'>&nbsp;</td></tr>"; };
                if (ActivityContent[k] != null) {
                    ActivityOut = ActivityOut + ActivityContent[k];
                }
            }
            ActivityOut = ActivityOut + "</table>";
            var m_divROverlay = document.getElementById("ActScroller");

            m_divROverlay.innerHTML = ActivityOut;
            if (TheBrowser == "safari") {
                animate("ActScroller", 0, -100, 640, 600, 1500, null);
            }
            else {
                animate("ActScroller", 0, -237, 640, 600, 1500, null);
            }
        }
        else {
            if (TheBrowser == "safari") {
                animate("ActScroller", 0, -100, 640, 600, 0, null);
            }
            else {
                animate("ActScroller", 0, -237, 640, 600, 0, null);
            }
        }

        if (m_bCenterMap || vehicleToFollow != null) {
            if (vehicleToFollow != null) {
                var latCenter = cars.Rows[carWeAreFollowing].lt * 1;
                var lonCenter = cars.Rows[carWeAreFollowing].ln * 1;
                var heading = cars.Rows[carWeAreFollowing].o;
                //slCtlSetMapView(latCenter, lonCenter, heading, true);
            }
            else {
                var latCenter = (maxLat + minLat) / 2;
                var lonCenter = (maxLon + minLon) / 2;
                var heading = 0;
            }
            var center = new VELatLong(latCenter, lonCenter);
            map.SetCenter(center);
        }
        if (m_bOptimizeZoom) {
            // If following a vehicle then optimize map on that vehicle alone.
            if (vehicleToFollow != null) {
                var tmpLatLon = new Array; 
                tmpLatLon[0] = new VELatLong(cars.Rows[carWeAreFollowing].lt * 1, cars.Rows[carWeAreFollowing].ln * 1);
                
                map.SetMapView(tmpLatLon);
            }
            // If not following a vehicle optimize on all vehicle points.
            else {
                map.SetMapView(points);
            }
            
            var gzv = map.GetZoomLevel();
            if (gzv > 17) {
                gzv = gzv - 2;
            }
            setZoomValue(gzv, "set");
        }

        //  reposition the name flag to be just above and to the right of the vehicle flag            
        //  this must be done after centering and zooming or the flags could fall off the map!
        for (var i = 0; i < carPins.length; i++) {
            //var originalPoint = map.LatLongToPixel(new VELatLong(cars.Rows[i].lt * 1, cars.Rows[i].ln * 1));
            var originalPoint = map.LatLongToPixel(new VELatLong(carPins[i].Latitude, carPins[i].Longitude));
            //var newx = originalPoint.x + 30;
            //var newy = originalPoint.y - 5;
            // minus tagOffset to pull it back into the air in the graphic
            var newx = originalPoint.x + cars.Rows[i].width - cars.Rows[i].tagOffset;
            var newy = originalPoint.y - 15;   // minus to account for the height of the NameTag window height
            pixel = new VEPixel(newx, newy);
            var newNameLatLon = map.PixelToLatLong(pixel)
            nameTags[i].SetPoints(newNameLatLon);

            //newx = originalPoint.x + 32;
            //newy = originalPoint.y + 13;
            newx = originalPoint.x + cars.Rows[i].width - cars.Rows[i].infoOffset;
            newy = originalPoint.y + 5;
            pixel = new VEPixel(newx, newy);
            var newInfoLatLon = map.PixelToLatLong(pixel)
            infoBoxes[i].SetPoints(newInfoLatLon);
        }

        if (m_showTraffic) {
            map.LoadTraffic(true);
        }
        else {
            map.ClearTraffic();
        }

        //  Reposition address marker info box 
        for (var i = 0; i < addrInfoBox.length; i++) {
            if (MapAddresspins[i] != null) {
                var originalPoint = map.LatLongToPixel(new VELatLong(MapAddresspins[i].Latitude, MapAddresspins[i].Longitude));
                var newx = originalPoint.x + 50;
                var newy = originalPoint.y - 5;
                pixel = new VEPixel(newx, newy);
                var newInfoLatLon = map.PixelToLatLong(pixel);
                addrInfoBox[i].SetPoints(newInfoLatLon);
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        if (m_CurrentUser == "proparkyale") {
            //Feed.SAddr(m_CurrentUser, updateAddressMarkersCallback);
            if (address_layer_update_signal == false) {
                queue_address_dt = null;
                loadAddressData();
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        if (novdatapresent == true) { hidenoVehicleDataPresent(); };

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // code to start Santa moving accross the screen on 12/24 and 12/25
        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth() + 1;
        if (santaTimer == null && m == 12 && (d == 24 || d == 25)) {
            santaTimer = setTimeout("showSanta()", 4000);
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        if (EightThousandPresent && MessageFromDriverTimer == null) {
            Feed.SDrvMsgMx(getDriverMessageMaxResponse);
            Feed.SDrvGMsgMx(getDriverGMessageMaxResponse);
        }
        lastCars = cars;
    }
    else {
        //No vehicles in the list
        noVehicleDataPresent();
        novdatapresent = true;
        m_bOptimizeZoomSet = false;
    }

    oSessionKey = document.getElementById("SESSIONKEY");
    if (oSessionKey != null) {
        var sessionID = oSessionKey.getAttribute("value");
        m_loadTimeout = setTimeout("loadMarkers('" + sessionID + "');", 4000);
    }

    if (m_firstRetrieve) {
        m_firstRetrieve = false;
        m_bCenterMap = false;
        m_bOptimizeZoom = false;
        positionMapOnQStr();
    }
    if (!MapFencesVisible) {
        updateMapFences();
    }

    if (address_layer_update_signal == false && trigger_address_update) {
        updateAddressMarkersCallback(queue_address_dt);
        trigger_address_update = false;
    }
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                Functions to show red circle around vehicles in panic mode
//

function eraseCarsInPanic() {
    if (maxCarsInPanic > 0) {
        for (var i = 0; i < maxCarsInPanic; i++) {
            var panicNumber = "panicDiv" + i;
            var panicDiv = document.getElementById(panicNumber);

            panicDiv.parentNode.removeChild(panicDiv);
        }
    } 
    carInPanic = false;
    maxCarsInPanic = 0;
}

function showPTOToggle(flag) {
    var targetElement = document.getElementById("emergencyAlertToggle");

    if(true == flag)
        targetElement.style.display = 'block';
        else
        targetElement.style.display = 'none';
}

function togglePTOAlerts() {
    disable_pto_alerts = !disable_pto_alerts;

    var targetElement = document.getElementById("emergencyAlertToggle");

    var targetText = "Emergency Alerts: ";

    if (null != targetElement) {
        if (disable_pto_alerts == true)
            targetText = targetText + "Off";
        else
            targetText = targetText + "On";

        targetElement.innerHTML = targetText;
    }


    showCarsInPanic();
}

function showCarsInPanic() {
    eraseCarsInPanic();

    if (false == disable_pto_alerts) {
        for (var i = 0; i < cars.Rows.length; i++) {
            var sw = cars.Rows[i].switches;
            if (sw == 2 || sw == 3 || sw == 6 || sw == 7 || sw == 10 || sw == 11 || sw == 14 || sw == 15 || cars.Rows[i].InRoute == false) {
                carInPanic = true;
                var originalPoint = map.LatLongToPixel(new VELatLong(cars.Rows[i].lt, cars.Rows[i].ln));
                newx = originalPoint.x - 37;
                newy = originalPoint.y - 37;
                var panicNumber = "panicDiv" + maxCarsInPanic;
                var panicDiv = document.createElement('DIV');
                panicDiv.setAttribute('id', panicNumber);
                panicDiv.style.width = 120;
                panicDiv.style.height = 120;
                panicDiv.style.position = "absolute";
                panicDiv.style.left = newx + "px";
                panicDiv.style.top = newy + "px";
                // moved before .innerHTML was assigned to prevent about:blank pages.
                document.body.appendChild(panicDiv);
                panicDiv.innerHTML = "<img id='Img" + 1000 + maxCarsInPanic + "' alt='' onclick='clickedOnPanic(" + i + ");' onmouseover='mouseOverPanic(" + i + ");' src='images/AlertGIF.gif'  />";
                panicDiv.style.opacity = "0.65";
                panicDiv.style.filter = "alpha(opacity=65)";
                panicDiv.style.display = "block";
                var parentDiv = document.getElementById('divMap');
                // document.body.appendChild(panicDiv);
                maxCarsInPanic++;
            }
        }
    }
}

function mouseOverPanic(i) {
    for (var n = 0; n < PinIds.length; n++) {
        if (n == i) {
            infoBoxes[n].Show();
        }
        else {
            infoBoxes[n].Hide();
        }
    }
}

function clickedOnPanic(i) {
    alert(window.event);
    clickedOnSerial = cars.Rows[i].s;
    infoBoxes[i].Hide();
    lastClickedBox = i;
    openVehicleActionPane(i);
    
}
//
//                                                         End of Panic functions
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function noVehicleDataPresent() {
    m_divROverlay = document.getElementById("noVehicleDataPresent");
    m_divROverlay.style.marginTop = parseInt(0);
    m_divROverlay.style.position = "absolute";
    m_divROverlay.style.top = "200px";
    m_divROverlay.style.left = "300px";
    fadein("noVehicleDataPresent");
    novdatapresent = true;
}

function hidenoVehicleDataPresent() {
    fadeout("noVehicleDataPresent");
    novdatapresent = false;
}

function animate(elementID, newLeft, newTop, newWidth,
      newHeight, time, callback) {
    var el = document.getElementById(elementID);
    if (el == null)
        return;

    var cLeft = parseInt(el.style.left);
    var cTop = parseInt(el.style.top);
    var cWidth = parseInt(el.style.width);
    var cHeight = parseInt(el.style.height);

    var totalFrames = 1;
    if (time > 0)
        totalFrames = time / 40;

    var fLeft = newLeft - cLeft;
    if (fLeft != 0)
        fLeft /= totalFrames;

    var fTop = newTop - cTop;
    if (fTop != 0)
        fTop /= totalFrames;

    var fWidth = newWidth - cWidth;
    if (fWidth != 0)
        fWidth /= totalFrames;

    var fHeight = newHeight - cHeight;
    if (fHeight != 0)
        fHeight /= totalFrames;

    doFrame(elementID, cLeft, newLeft, fLeft,
          cTop, newTop, fTop, cWidth, newWidth, fWidth,
          cHeight, newHeight, fHeight, callback);

}

function doFrame(eID, cLeft, nLeft, fLeft,
      cTop, nTop, fTop, cWidth, nWidth, fWidth,
      cHeight, nHeight, fHeight, callback) {
    var el = document.getElementById(eID);
    if (el == null)
        return;

    cLeft = moveSingleVal(cLeft, nLeft, fLeft);
    cTop = moveSingleVal(cTop, nTop, fTop);
    cWidth = moveSingleVal(cWidth, nWidth, fWidth);
    cHeight = moveSingleVal(cHeight, nHeight, fHeight);

    el.style.left = Math.round(cLeft) + 'px';
    el.style.top = Math.round(cTop) + 'px';
    el.style.width = Math.round(cWidth) + 'px';
    el.style.height = Math.round(cHeight) + 'px';

    if (cLeft == nLeft && cTop == nTop && cHeight == nHeight && cWidth == nWidth) {
        if (callback != null)
            callback();
        return;
    }

    setTimeout('doFrame("' + eID + '",' + cLeft + ',' + nLeft + ',' + fLeft + ','
        + cTop + ',' + nTop + ',' + fTop + ',' + cWidth + ',' + nWidth + ',' + fWidth + ','
        + cHeight + ',' + nHeight + ',' + fHeight + ',' + callback + ')', 40);
}

function moveSingleVal(currentVal, finalVal, frameAmt) {
    if (frameAmt == 0 || currentVal == finalVal)
        return finalVal;

    currentVal += frameAmt;
    if ((frameAmt > 0 && currentVal >= finalVal) || (frameAmt < 0 && currentVal <= finalVal)) {
        return finalVal;
    }
    return currentVal;
}


function slideActivityTray(elementId, headerElement) {

    var element = document.getElementById(elementId);
    var outerElement = document.getElementById("MasterMask");

    if (element.up == null || element.down) {
        new Effect.Parallel([
            //new Effect.Move("MasterMask", { x: 0, y: -286, mode: 'relative' }),
            new Effect.Scale("MasterMask", 100, { scaleMode: { originalHeight: 308, originalWidth: 635 }, scaleContent: false, scaleX: false, scaleFrom: 7 })
            ], { duration: 0.37 }
        );


        element.up = true;
        element.down = false;
        ActivityTray = true;
        document.getElementById("Activity").innerHTML = ActWindowHeader;     //exposed
    }
    else {
        new Effect.Parallel([
            //new Effect.Move("MasterMask", { x: 0, y: 286, mode: 'relative' }),
            new Effect.Scale("MasterMask", 7, { scaleMode: { originalHeight: 308, originalWidth: 635 }, scaleContent: false, scaleX: false, scaleFrom: 100 })
            ], { duration: 0.37 }
        );


        element.down = true;
        element.up = false;
        ActivityTray = false;
        for (k = 0; k < 29; k++) {
            ActivityContent[k] = '';
        }

        //ActivityOut = ActivityHeader + "</table>";
        var tmpObj = document.getElementById("Activity");
        tmpObj.innerHTML = ActWindowHeader; // + ActivityOut;     //hidden

        //if (TheBrowser == 'safari') { tmpObj.style.top = "150px"; }   
    }
}

function MoveActivityTray() {

    slideActivityTray("Activity", "MoveActivityPanel");

}

var firstLoad = true;
function resizeMap() {
    if (m_bResizing)
        return;

    tempWidth = windowWidth;
    tempHeight = windowHeight;
    getPageSize();
    if (tempWidth == windowWidth && tempHeight == windowHeight) {
        if (firstLoad) {
            firstLoad = false;
        } else {
            return;
        }
    }

    if (map != null) {
        map.Resize(windowWidth, windowHeight);
    }
}

/********************************************************************
*   Event handlers for Accordion items
********************************************************************/

// Zoom in & Zoom Out
function setZoomValue(value, vType) {
    zoomvalue = map.GetZoomLevel();
    if (zoomvalue == value) {
        return;
    }
    switch (vType) {
        case 'in':
            if (zoomvalue < 19) {
                zoomvalue = zoomvalue + 1;
                A_SLIDERS[0].f_setValue(20 - zoomvalue);
            }
            break;
        case 'out':
            if (zoomvalue > 2) {
                zoomvalue = zoomvalue - 1;
                A_SLIDERS[0].f_setValue(20 - zoomvalue);
            }
            break;
        case 'change':
            zoomvalue = 20 - value;
            break;
        case 'set':
            zoomvalue = value;
            A_SLIDERS[0].f_setValue(20 - zoomvalue);
            break;
        default:
            m_setValue = false;
            return false;
            break;
    }

    if (zoomvalue < 14)
        m_maxHistoricalCenterCount = 7;
    else if (zoomvalue >= 14 && zoomvalue < 16)
        m_maxHistoricalCenterCount = 4;
    else if (zoomvalue >= 16 && zoomvalue < 18)
        m_maxHistoricalCenterCount = 2
    else if (zoomvalue >= 18 && zoomvalue < 20)
        m_maxHistoricalCenterCount = 0;
    else
        m_maxHistoricalCenterCount = 0;
    map.SetZoomLevel(zoomvalue);

    return false;
}

function logout() {
    m_demoUser = false;

    removeAddressMarkers();
    oSessionKey = document.getElementById("SESSIONKEY");
    if (oSessionKey != null) {
        ActionCompleted("Ending session");
        var existing_session = oSessionKey.getAttribute("value");
        oLoginCell = document.getElementById("loginCell");
        oLoginCell.innerHTML = "Login";
        oLoginCell.setAttribute("onclick", logInUser);
        Feed.LOUsr(existing_session, logoutCallback);
        history.go(-1) // return to previous page (whatever that previous page was)
    }
    m_bOptimizeZoomSet = false;
    return true;

}

function logoutCallback(rvalue) {
    // RAS - Enable text boxes on log out
    Disable('txtUserID', false);
    Disable('txtPassword', false);
    // Show the demo button on log out
    var btnDemoButton = document.getElementById("DemoButton");
    btnDemoButton.style.visibility = "visible";
    btnDemoButton.display = "block"
    var lblInfo = document.getElementById("lblInfo");
    lblInfo.innerHTML = "";
    lblInfo.style.visibility = "hidden";
    
    oTextUserId = document.getElementById("txtUserID");
    oTextUserId.value = '';
    oTextPassword = document.getElementById("txtPassword");
    oTextPassword.value = '';
    oSessionContainer = document.getElementById("sessionContainer");
    oSessionKey = document.getElementById("SESSIONKEY");
    oSessionContainer.removeChild(oSessionKey);
    cleanMap();
    removeCookie("USFTLoginID", "");
    removeCookie("USFTPassword", "");
    oTextUserId.focus
    oTextUserId = null;
    oTextPassword = null;
    m_groupView = false;
    m_bOptimizeZoomSet = false;
    m_loadTimeout = null;
    m_loadInterval = null;
    location.reload();
}

function logInUser() {
    if (dummyUser != null && dummyUser != "") {
        if (dummyPwd != null && dummyPwd != "") {
            clearTimeout(loginUserTimer);
            if (document.getElementById("txtUserID") == null) {
                loginUserTimer = setTimeout("logInUser('" + document.getElementById("loginCell") + "')", 1000);
                return null;
            }
            // setting pass field for user
            document.getElementById("txtPassword").value = dummyPwd;
        }
        // setting login field for user
        document.getElementById("txtUserID").value = dummyUser;
    }
    var txtUserID = document.getElementById("txtUserID");
    var txtPassword = document.getElementById("txtPassword");
    m_CurrentUser = txtUserID.value;
    m_bViewHistory = false;
    var sessionKey = document.getElementById("SESSIONKEY");

    Feed.LIUsr(null, txtUserID.value, txtPassword.value, logInUser_CallBack);
    m_TriggerMapControl = true;
}

function logInDemoUser(field) {
    oTxtUserId = document.getElementById("txtUserID");
    oTxtUserId.value = "jdemo";
    oTxtPassword = document.getElementById("txtPassword");
    oTxtPassword.value = "jdemo";
    m_demoUser = true;
    m_CurrentUser = "jdemo";
    logInUser();
    m_TriggerMapControl = true;
    openDemoNotification();
}

function logInDemoChat(field) {
    oTxtUserId = document.getElementById("txtUserID");
    oTxtUserId.value = "ChatDemo";
    oTxtPassword = document.getElementById("txtPassword");
    oTxtPassword.value = "ChatDemo";
    m_demoUser = true;
    m_CurrentUser = "ChatDemo";
    ChatDemo = true;
    logInUser();
    m_TriggerMapControl = true;
}

function logInUser_CallBack(response) {
    if (response != null) {
        var sessionField = 0;
        var limitationsField = 1;
        var addressMarkersField = 2;
        var messageField = 3;
        var allowLogonField = 4;
        var startupViewField = 5;
        var DemoUserField = 6;
        var Dealer_Id = 7;
        var rvalue = response.value;
        var word = rvalue.split("|")

        if (m_CurrentUser.toLowerCase() == "livedemo") {
            m_demoUser = true;
        }
        if (word[messageField] != null && word[messageField] != "") {
            if (word[allowLogonField] != '1') {
                if (word[messageField] == 'ATTI6' && word[Dealer_Id] == "6") {
                    fadein("divSpcNotice");
                }
                else {
                    AlertMessage(word[messageField] + "\nAccess to your account is currently restricted.");
                }
                logout();
                return;
            }
            else {
                if (word[messageField] == 'ATTI6' && word[Dealer_Id] == "6") {
                    fadein("divSpcNotice");
                }
                else {
                    AlertMessage(word[messageField]);
                }
            }
        }

        if (word[limitationsField] == "99") {
            ControlPanelLockout = true;
        }
        else {
            ControlPanelLockout = false;
        }

        if (word[DemoUserField] == "1") {
            demo2_user = true;
        }
        else {
            demo2_user = false;
        }

        if (word[startupViewField] != null & word[startupViewField] != "") {
            m_StartupView = word[startupViewField];
        }
        else {
            m_StartupView = "";
        }
        cbAddressVisible = document.getElementById("cbAddressVisible");
        if (word[addressMarkersField] == "01") {
            AddressMarkersVisible = true;
            cbAddressVisible.setAttribute("checked", "true");
        }
        else {
            cbAddressVisible.setAttribute("checked", "false");
        }

        response.value = word[sessionField];
        if (response.value != "false" && response.value != "False" && response.value != "") {
            // RAS - Disable text boxes when user logs in
            Disable('txtUserID', true);
            Disable('txtPassword', true);
            // Hide the demo button, since user is already logged in
            var btnDemoButton = document.getElementById("DemoButton");
            btnDemoButton.style.visibility = "hidden";
            btnDemoButton.display = "none";
            var lblInfo = document.getElementById("lblInfo");
            var userMessage = Feed.sUsrInfo().value;
            if (userMessage != null && userMessage.Rows.length > 0) {
                lblInfo.innerHTML = userMessage.Rows[0].message;
                lblInfo.style.visibility = "visible";
            }
            
            cleanMap();
            m_bLoggedIn = true;
            m_bRepeat = true;

            ActivityContent = new Array;
            openLoadNotification();
            var object = document.getElementById("loginCell");
            object.innerHTML = "<img alt='' src='images/blogoutlight.gif' id='loginImage' onmouseover=\"this.src='images/blogoutdark.gif'\" onmouseout=\"this.src='images/blogoutlight.gif'\" onclick='logout();' />"
            if (document.getElementById("SESSIONKEY") == null) {
                var currentElement = document.createElement("input");
                currentElement.setAttribute("type", "hidden");
                currentElement.setAttribute("name", "SESSIONKEY");
                currentElement.setAttribute("id", "SESSIONKEY");
                currentElement.value = response.value;
                document.getElementById("sessionContainer").appendChild(currentElement);
            }

            if (ControlPanelLockout == true) {
                ControlPanelLockout = false;
                ShowLockedPlate();
                ControlPanelLockout = true;
            }
            loadIconSizes();

            if (m_StartupView != null && m_StartupView != "") {
                if (m_StartupView == "Map") {
                    map.SetMapStyle(VEMapStyle.Road);
                }
                else if (m_StartupView == "Hybrid") {
                    map.SetMapStyle(VEMapStyle.Hybrid);
                }
                else if (m_StartupView == "Satallite") {
                    map.SetMapStyle(VEMapStyle.Aerial);
                }
            }
            m_firstRetrieve = true;

            //Move Map Control slider into position
            if (m_TriggerMapControl == true) {
                m_TriggerMapControl = false;
                var myControl = document.getElementById("MapControl");

                if (myControl != null) {
                    myControl.onclick();
                    spanClicked(2);
                }
            }

            vgRefreshGroupList();
            loadMarkers(response.value);
            flashPanic();

            if (AddressMarkersVisible == true) {
                Feed.SAdrMrk(getAddressMarkersCallback)
            }
            else {
                showUserRoute()
            }

            Feed.SOnlMsgMx(m_CurrentUser, GetOnLineMessageMaxResponse);
            if (ChatDemo) {
                openLiveChat();
            }
            __doPostBack(UPRList, m_CurrentUser);
        }
        else {
            cleanMap();
            AlertMessage("Invalid Login Credentials.<br/><br/>Please re-enter your login name and password.");
            m_bRepeat = false;
            m_bLoggedIn = false;
        }
    }
    else if (response.value == null) {
        cleanMap();
        AlertMessage("Invalid Login Credentials.<br/><br/>Please re-enter your login name and password.");
        m_bRepeat = false;
        m_bLoggedIn = false;
    }
    else {
        cleanMap();
        AlertMessage("Invalid Login Credentials.<br/><br/>Please re-enter your login name and password.");
        m_bRepeat = false;
        m_bLoggedIn = false;
    }
}


function addressEnabled() {
    result = cbAddressVisible.getAttribute("checked");
    if (result == true) {
        updateAddressMarkers();
    }
    else {
        removeAddressMarkers();
    }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                                            HISTORICAL PLAYBACK
//
function createHistoricalMarker() {
    if (historicalIndex > -1 && historicalIndex < m_historicalData.Rows.length) {
        var tempTime = m_historicalData.Rows[historicalIndex].timestamp;
        historicalPlaybackMessage(m_historicalData.Rows[historicalIndex].timestamp);
        var direction = m_historicalData.Rows[historicalIndex].ori;

        //  fix so the car doesn't point north each time it stops        
        if (m_historicalData.Rows[historicalIndex].vel == 0 && direction == 0 && historyLastDirection != 0) {
            direction = historyLastDirection;
        } else {
            direction = (Math.floor(((direction * 1) + 5) / 10) * 10);
            if (direction >= 360) {
                direction = 0;
            }
        }
        historyLastDirection = direction;

        //  we need to do a correction if we are in birds eye view and we are not looking north.
        var mapstyle = map.GetMapStyle();
        if (mapstyle == VEMapStyle.Birdseye) {
            var be = map.GetBirdseyeScene();
            var maporentation = be.GetOrientation();
            if (maporentation == "East") {
                direction = direction + 270;
            }
            if (maporentation == "South") {
                direction = direction + 180;
            }
            if (maporentation == "West") {
                direction = direction + 90;
            }
            if (direction > 360) {
                direction = direction - 360;
            }
        }

        //  find the center of the icon so we can center it on the lat/lon 
        var tmpXCenter = 0;
        var tmpYCenter = 0;
        if (historyXCenter != null) { tmpXCenter = 13 - historyXCenter; }
        if (historyYCenter != null) { tmpYCenter = 13 - historyYCenter; }

        var imageloc = "<img style='margin: " + tmpYCenter + "px 0px 0px " + tmpXCenter + "px' src='images/" + historyIconFolder + "/" + "v" + direction + ".gif'/>";

        var kph = Math.round(m_historicalData.Rows[historicalIndex].vel * 1.60934);
        var string = "" +
            "&nbsp;Latitude: <b>" + m_historicalData.Rows[historicalIndex].lat + "</b><br />" +
            "&nbsp;Longitude: <b>" + m_historicalData.Rows[historicalIndex].lon + "</b><br />" +
        // Rebekah - need to uncomment when all history tables are up to date with new address field.
        //"&nbsp;Address: <b>" + m_historicalData.Rows[historicalIndex].address + "</b><br />" +
            "&nbsp;Heading: <b>" + m_historicalData.Rows[historicalIndex].ori + "&#176 / " + define_direction(m_historicalData.Rows[historicalIndex].ori, m_historicalData.Rows[historicalIndex].vel) + "</b><br />" +
            "&nbsp;Velocity: <b>" + m_historicalData.Rows[historicalIndex].vel + " mph / " + kph + " kph</b><br />" +
            "&nbsp;Last Moved: <b>" + tempTime + "</b><br />" +
            "&nbsp;Last Update: <b>" + tempTime + "</b><br />";
        if (m_historicalData.Rows[historicalIndex].sats) {
            string = string + "&nbsp;GPS Satellites: <b>" + m_historicalData.Rows[historicalIndex].sats + "</b><br />" + "";
        }
        else {
            string = string + "&nbsp;GPS Satellites: <b>Not Available</b><br />" + "";
        }
        var ckwidth = "&nbspLast Moved: " + tempTime;
        var wdth = ckwidth.length
        ckwidth = "&nbspLast Update: " + tempTime;
        if (ckwidth.length > wdth) {
            wdth = ckwidth.length
        }
        var divInfoVar = "<div style='filter: alpha(opacity=80); -moz-opacity: 0.70; opacity: 0.70; color:black; font-family:arial; font-size:12px;border:solid 1px Red;background-color:White;width:" + wdth * 6 + "px;'>" + string + "</div>";

        var lat = m_historicalData.Rows[historicalIndex].lat;
        var lon = m_historicalData.Rows[historicalIndex].lon;
        var newLatLon = new VELatLong(lat * 1, lon * 1);

        if (m_ddlVehicles.value.substring(0, 1) != "7") {
            if (m_historicalData.Rows[historicalIndex].vel * 1 == 0) {
                var stopsign = new VEShape(VEShapeType.Pushpin, newLatLon);
                stopsign.SetCustomIcon("<img src='images/stop.png'/>");
                map.AddShape(stopsign);
                stopsign.ShowIcon();
            }
        }


        var originalPoint = map.LatLongToPixel(new VELatLong(m_historicalData.Rows[historicalIndex].lat * 1, m_historicalData.Rows[historicalIndex].lon * 1));

        var newx = originalPoint.x;   //+ wide;
        var newy = originalPoint.y;   //- hi;
        pixel = new VEPixel(newx, newy);
        var newLatLon = map.PixelToLatLong(pixel)

        // setting the tag name position
        //var newx = originalPoint.x + 30;
        //var newy = originalPoint.y - 22;
        var newx = originalPoint.x + historyWidth - historyTagOffset;
        var newy = originalPoint.y - 10;   // minus 10 to account for the height of the NameTag window height
        pixel = new VEPixel(newx, newy);
        var newNameLatLon = map.PixelToLatLong(pixel)

        // setting the information box position
        //newx = originalPoint.x + 50;
        //newy = originalPoint.y - 5;
        newx = originalPoint.x + historyWidth;
        newy = originalPoint.y + 10;  // to seperate from the tag name box above
        pixel = new VEPixel(newx, newy);
        var newInfoLatLon = map.PixelToLatLong(pixel);

        if (historyCarPin != null) {
            historyCarPin.SetCustomIcon(imageloc);
            historyCarPin.SetPoints(newLatLon);
            historyCarPin.Show();

            historyNameTag.SetPoints(newNameLatLon);
            historyNameTag.Show();

            historyInfoBox.SetCustomIcon(divInfoVar);
            historyInfoBox.SetPoints(newInfoLatLon);
        }
        else {
            var pin = new VEShape(VEShapeType.Pushpin, newLatLon);
            pin.SetCustomIcon(imageloc);
            historyCarPin = pin;
            map.AddShape(historyCarPin);
            historyCarPin.ShowIcon();

            var tagwidth = m_historicalData.Rows[historicalIndex].n.length * 10;
            if (TheBrowser == "safari") { tagwidth = tagwidth * 1.2 };

            var shape = new VEShape(VEShapeType.Pushpin, newNameLatLon);
            var divVar = "<div style='filter:alpha(opacity=80);font-family:arial;font-size:14px;font-weight:bold;border:solid 1px Black;background-color:White;width:" + tagwidth + "px;'>" + m_historicalData.Rows[historicalIndex].n + "</div>"; shape.SetCustomIcon(divVar);
            historyNameTag = shape;
            map.AddShape(historyNameTag);
            historyNameTag.ShowIcon();

            var shape = new VEShape(VEShapeType.Pushpin, newLatLon);
            shape.SetCustomIcon(divInfoVar);
            historyInfoBox = shape;
            map.AddShape(historyInfoBox);
            historyInfoBox.Hide();
        }

        if (historicalPlaybackDirection == 1) {
            var points = new Array(
                new VELatLong(m_historicalData.Rows[historicalIndex - 1].lat, m_historicalData.Rows[historicalIndex - 1].lon),
                new VELatLong(m_historicalData.Rows[historicalIndex].lat, m_historicalData.Rows[historicalIndex].lon)
                );
            var vaptrail = new VEShape(VEShapeType.Polyline, points);
            vaptrail.SetLineColor(new VEColor(255, 0, 100, 0.6));
            vaptrail.SetLineWidth(4);
            vaptrail.HideIcon();
            layer01.AddShape(vaptrail);
        }
        //slCtlSetMapView(lat, lon, direction, false);
        var center = new VELatLong(lat * 1, lon * 1);
        map.SetCenter(center);
    }
}


function initHistoricalPlayback() {
    
    if (m_ddlVehicles.options.length == 2) {
        m_ddlVehicles.value = m_ddlVehicles.options[1].value;
    }

    if (m_ddlVehicles.value == "" || m_ddlVehicles.value == null || m_ddlVehicles.value == -1) {
        AlertMessage("No Device or Vehicle has been selected for playback.<br/>Please select a device from the DEVICES tab<br/>in order to replay that device's history.");
        return;
    }

    followThisVehicleOFF();
    
    var response = null;
    //clean off the map
    clearMap();
    clearWeather();
    //Turn on loading bar and make it flash
    openGeneralNotification("<br/>Loading data for historical playback...<br/>Please Stand By...<br/>");

    layer01 = new VEShapeLayer();
    map.AddShapeLayer(layer01);
    response = Feed.SVehIcn(m_ddlVehicles.value);
    tmpVehData = response.value;

    if (tmpVehData != null && tmpVehData != "") {
        historyIconFolder = tmpVehData.Rows[0].Image;
        historyXCenter = tmpVehData.Rows[0].XCenter;
        historyYCenter = tmpVehData.Rows[0].YCenter;
        historyWidth = tmpVehData.Rows[0].width;
        historyHeight = tmpVehData.Rows[0].height;
        if (tmpVehData.Rows[0].tagOffset != null || tmpVehData.Rows[0].tagOffset != "") { historyTagOffset = tmpVehData.Rows[0].tagOffset; }
        else { historyTagOffset = 0; }
    }
    else {
        historyIconFolder = "Default";
        historyXCenter = 20;
        historyYCenter = 20;
        historyTagOffset = 9;
        historyWidth = 40;
        historyHeight = 40;
    }
    //retrieve the data for the specified date/time/vehicle combo
    response = Feed.SHstPlay(m_ddlVehicles.value,
                                m_strDateTime.getFullYear() + "/" + (m_strDateTime.getMonth() + 1) + "/" + m_strDateTime.getDate(),
                                "00:00:00",
                                m_strDateTime.getFullYear() + "/" + (m_strDateTime.getMonth() + 1) + "/" + m_strDateTime.getDate(),
                                "23:59:59");

    //Turn off loading bar
    hideGeneralNotification();

    //create our marker if the response is not null
    if (response != null) {
        if (response.value != null) {
            //Historical data save
            m_historicalData = response.value;

            if (m_historicalData.Rows.length == 0) {
                AlertMessage("No history present for this date.");
                return;
            }
            historyCarPin = null;
            historyNameTag = null;
            historyInfoBox = null;
            setZoomValue(14, "set");
            historicalIndex = 0;
            A_SLIDERS[1].n_maxValue = m_historicalData.Rows.length;
            A_SLIDERS[1].n_minValue = 0;
            setHistorySlider(1, 'set');
        }
        else {
            resetHistoricalPlayback();
            AlertMessage("No data found.<br/>Please rerun your query,<br/>or email support@usfleettracking.com");
        }
    }
    else {
        resetHistoricalPlayback();
        AlertMessage("Data returned is null.<br/>Please rerun your query,<br/>or email support@usfleettracking.com");
    }
}

function play(restart) {
    //clearMap();

    for (var i = 0; i < carPins.length; i++) {
        carPins[i].Hide();
        nameTags[i].Hide();
        infoBoxes[i].Hide();
    }

    //first time to play anything back for this date, load the data
    //hitting play from a pause/fastforward/rewind/stop state
    if (restart == true) {
        historicalDateChange = true;
    }
    historicalPlaybackDirection = 1; //forwards
    historicalTimeout = DEFAULT_HISTORICAL_TIMEOUT;

    if (m_historicalData == null || historicalDateChanged == true) {
        m_bViewHistory = true;
        initHistoricalPlayback();
        historicalDateChanged = false;
    }
    if (m_historicalData && m_historicalData.Rows.length > 1 && m_historicalData.Rows.length > historicalIndex) {
        with (m_historicalData.Rows[historicalIndex]) {
            clearTimeout(historicalPlaybackTimer);
//            if (slCtlIsLoaded()) {
//                slCtlSetMapView(lat, lon, ori, false);
                  historicalPlaybackTimer = setTimeout("historicalPlaybackTick()", 2000);
//            } else {
//                StreetsideShow(true, lat, lon, ori);
//                historicalPlaybackTimer = setTimeout("historicalPlaybackTick()", 5000);
//            }
        }
    }

    historicalPlaybackMessage("Playing History");
}

function fastforward() {
//    if (slCtlIsLoaded()) {
//        AlertMessage("Fast-forward is not available while Streetside view is open. Close the Streetside view to enable fast-forwarding.");
//        return;
//    }
    if (historicalPlaybackDirection != 1) {
        historicalTimeout = DEFAULT_HISTORICAL_TIMEOUT;
        historicalPlaybackDirection = 1;
    }
    else {
        historicalTimeout -= 500;
        if (historicalTimeout <= 0)
            historicalTimeout = 100;
    }

    ffspeed = ">";
    if (historicalTimeout < 2500)
        ffspeed = ">";
    if (historicalTimeout < 2200)
        ffspeed = ">>";
    if (historicalTimeout < 1500)
        ffspeed = ">>>";
    if (historicalTimeout < 1000)
        ffspeed = ">>>>";
    if (historicalTimeout < 500)
        ffspeed = ">>>>>";

    historicalPlaybackMessage("Fast Forward " + ffspeed);
    if (!historicalPlaybackTimer) {
        historicalPlaybackTimer = setTimeout("historicalPlaybackTick()", historicalTimeout);
    }
}

function rewind() {
    if (m_historicalData == null || m_historicalData.Rows.length < 2) {
        return;
    }
    if (historicalPlaybackDirection != -1) {
        if (historicalIndex > m_historicalData.Rows.length - 2) {
            historicalIndex = m_historicalData.Rows.length - 2;
        }
        historicalPlaybackDirection = -1;
    }
    else {
        historicalTimeout -= 100;
        if (historicalTimeout <= 0)
            historicalTimeout = 100;
    }

    rwspeed = "<";
    if (historicalTimeout == 500)
        rwspeed = "<";
    if (historicalTimeout == 400)
        rwspeed = "<<";
    if (historicalTimeout == 300)
        rwspeed = "<<<";
    if (historicalTimeout == 200)
        rwspeed = "<<<<";
    if (historicalTimeout == 100)
        rwspeed = "<<<<<";

    historicalPlaybackMessage(rwspeed + " Rewind");
    if (!historicalPlaybackTimer) {
        historicalPlaybackTimer = setTimeout("historicalPlaybackTick()", 2000);
    }
}

function stop() {
    skiptobeginning();
    pause();
    historicalPlaybackMessage("Stopped");
}

function pause() {
    historicalPlaybackDirection = 0;
    historicalPlaybackMessage("Paused");
    clearTimeout(historicalPlaybackTimer);
    historicalPlaybackTimer = null;
}

function skiptobeginning() {
    current_hindex = 0;
    historicalIndex = 0;
    pause();
    setHistorySlider(historicalIndex, "set")
    createHistoricalMarker();
    historicalPlaybackMessage("Skipping to start");
}

function skiptoend() {
    if (m_historicalData != null) {
        historicalIndex = m_historicalData.Rows.length - 2;
        current_hindex = m_historicalData.Rows.length - 1;
    }
    setHistorySlider(historicalIndex, "set")
    createHistoricalMarker();
    pause();
    historicalPlaybackMessage("Skipping to end");
}

function historicalPlaybackTick() {
    clearTimeout(historicalPlaybackTimer);
    historicalPlaybackTimer = null;
    if (m_historicalData != null && historicalPlaybackDirection != 0) {
        if (historicalIndex > -1 && historicalIndex < m_historicalData.Rows.length - 1) {
//            if (slCtlIsLoaded()) {
//                historicalPlaybackTimer = setTimeout("historicalPlaybackTick()", 2000);
//            } else {
                historicalPlaybackTimer = setTimeout("historicalPlaybackTick()", historicalTimeout);
//            }
            historicalIndex = historicalIndex + historicalPlaybackDirection;
            setHistorySlider(historicalIndex, "set")
            createHistoricalMarker();
        }
    }
}

function historicalPlaybackMessage(message) {
    hMessage = document.getElementById("HISTORICALINFO");
    hMessage.innerHTML = "<center style=\"color:White; font-size:8pt; font-family:Arial;\">" + message + "</center>";
}

function setHistorySlider(value, vType) {
    if (!m_setHistoryValue) {

        switch (vType) {
            case 'change':
                historicalIndex = value;
                current_hindex = value;
                historicalCenterCount = -99;
                break;
            case 'set':
                m_setHistoryValue = true;
                A_SLIDERS[1].f_setValue(value);
                break;
            default:
                return true;
                break;
        }
    }

    m_setHistoryValue = false;
    return true;
}

function resetHistoricalPlayback() {
    if (historyCarPin) { clearMap(); }
    historicalDateChanged = true;
    //StreetsideShow(false);
    historyCarPin = null;
    historyNameTag = null;
    historyInfoBox = null;
    historicalPlaybackDirection = 0; //paused
    historicalTimeout = DEFAULT_HISTORICAL_TIMEOUT;
    m_historicalData = null;
    m_historicalMarker = null;
    m_bViewHistory = false;
    current_hindex = 0;
    historicalIndex = 0;
    historicalPlaybackDirection = 0;
    historicalPlaybackMessage("Stopped");
    clearTimeout(historicalPlaybackTimer);
    historicalPlaybackTimer = null;
    setHistorySlider(0, "set");
}
function historicalPlaybackActive() {
    return (historicalPlaybackTimer != null);
}
//
//                                                         End of Historical Playback
//                         
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*********************************************************************************
*   Misc Methods
*********************************************************************************/
function preloadMarkers() {
    cached_loader = new Image();
    cached_loader.src = "images/rotator.gif";

}

function Pad(str, ch, num) {
    var resultStr = '';

    resultStr = PadLeft(str, ch, num);
    resultStr = PadRight(resultStr, ch, num);

    return resultStr;
}

function PadLeft(str, ch, num) {
    // Return immediately if an invalid value was passed in
    if (str + '' == 'undefined' || str == null)
        return null;
    if (ch + '' == 'undefined' || ch == null)
        return null;
    if (typeof (num) != typeof (0)) // check to see if num is numeric
        return null;

    // Make sure the string arguments are strings
    str += '';
    ch += '';

    var resultStr = str;

    // Make sure the argument is a string
    str += '';

    if (str.length < num) {
        for (var i = 0; i < num - str.length; i++)
            resultStr = ch + resultStr;
    }

    return resultStr;
} // end PadLeft

function PadRight(str, ch, num) {
    // Return immediately if an invalid value was passed in
    if (str + '' == 'undefined' || str == null)
        return null;
    if (ch + '' == 'undefined' || ch == null)
        return null;
    if (typeof (num) != typeof (0)) // check to see if num is numeric
        return null;

    // Make sure the string arguments are strings
    str += '';
    ch += '';

    var resultStr = str;

    if (str.length < num) {
        for (var i = 0; i < num; i++)
            resultStr += ch;
    }

    return resultStr;
}

//-----------------------------------------------------------------------------
// shows pop-up tooltip marker
function showToolTip1() {
    var point = m_gMap.getCurrentMapType().getProjection().fromLatLngToPixel(m_gMap.fromDivPixelToLatLng(new GPoint(0, 0), true), m_gMap.getZoom());
    var offset = m_gMap.getCurrentMapType().getProjection().fromLatLngToPixel(this.getPoint(), m_gMap.getZoom());
    var anchor = this.getIcon().iconAnchor;
    var width = this.getIcon().iconSize.width;
    var height = 100;
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width + TOOLTIP_OFFSET_X, offset.y - point.y - anchor.y + TOOLTIP_OFFSET_Y));
    pos.apply(this.tooltip);
    this.tooltip.style.display = "block";
}

//-----------------------------------------------------------------------------
// hides currently visible tooltip marker
function hideToolTip1() {
    this.tooltip.style.display = "none";
}

//-----------------------------------------------------------------------------
// shows pop-up infoPane marker
function showInfoPane1() {
    var point = m_gMap.getCurrentMapType().getProjection().fromLatLngToPixel(m_gMap.fromDivPixelToLatLng(new GPoint(0, 0), true), m_gMap.getZoom());
    var offset = m_gMap.getCurrentMapType().getProjection().fromLatLngToPixel(this.getPoint(), m_gMap.getZoom());
    var anchor = this.getIcon().iconAnchor;
    var width = this.getIcon().iconSize.width;
    var height = 100;
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width + INFOPANE_OFFSET_X, offset.y - point.y - anchor.y + INFOPANE_OFFSET_Y));
    pos.apply(this.infoPane);
    this.infoPane.style.display = "block";
}

//-----------------------------------------------------------------------------
// hides currently visible infoPane marker
function hideInfoPane1() {
    this.infoPane.style.display = "none";
}

function cleanMap(ClearDropDown) {
    
    if (ClearDropDown == null) {
        ClearDropDown = true;
    }

    // Hiding API results window before API addresspins are deleted.
    hideAPIResultsWindow();

    
    for (var i = 0; i < m_gMarkers.length; i++) {
        m_gMap.getPane(G_MAP_MARKER_PANE).removeChild(m_gMarkers[i].mkr.tooltip);
        m_gMap.getPane(G_MAP_FLOAT_PANE).removeChild(m_gMarkers[i].mkr.infoPane);
    }
    

    if (ClearDropDown) {
        m_ddlVehicles.options.length = 0;
        m_ddlVehicleGroupEditor.options.length = 0;
        m_ddlVehicleDriversEditor.options.length = 0;
        m_AlertVehicleList.options.length = 0;
        m_ZoneVehicleList.options.length = 0;
        m_OLRVehiclesList.options.length = 0;
        m_VTVehiclesList.options.length = 0;
        m_IGNVehicleList.options.lenght = 0;
    }

    //Gonse: Need to clear the shape layer as well
    MapAddresspins = new Array();

    if (m_bViewHistory) {
        play(true);
    }
    
}

function clearMap() {
    // Hiding API results window before addresspins are deleted.
    hideAPIResultsWindow();
    CheckUncheckAllRoutes(false);
    eraseCarsInPanic();

    carPins = new Array();
    nameTags = new Array();
    infoBoxes = new Array();
    
    //Gonse: Need to clear the shape layer as well
    MapAddresspins = new Array();

    map.DeleteAllShapeLayers();
    map.DeleteAllShapes();    
    map.DeleteRoute();
    map.Clear();
}

function AutoCenterMap(value) {
    if (value!=null) { m_bCenterMap = value; }
    else { m_bCenterMap = !m_bCenterMap; }
    document.getElementById('CenterMap').src = (m_bCenterMap) ? 'Images/CenterMap1.png' : 'Images/CenterMap0.png';

    if (vehicleToFollow != null && m_bCenterMap == false) { followThisVehicleOFF(); }
}

function AutoZoomMap(value) {
    // if optimize is checked
    if (value) { m_bOptimizeZoom = value; }
    // if optimize is unchecked
    else { m_bOptimizeZoom = !m_bOptimizeZoom; }
    document.getElementById('OptZoom').src = (m_bOptimizeZoom) ? 'Images/OptimizeZoom1.png' : 'Images/OptimizeZoom0.png';
	// auto center the map if optimize is checked
    if (m_bOptimizeZoom) { AutoCenterMap(true); }
}

/*********************************************************************************
*   Calendar Methods
*********************************************************************************/
var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

function showVTCalendar(x, y, callTo) {
    var parent = document.getElementById("divVTCal");
    parent.style.visibility = "visible";
    parent.style.display = "block";
    parent.style.top = y;
    parent.style.left = x;
    var cal = new Calendar(0, null, callTo);
    cal.weekNumbers = false;
    cal.setDateFormat("%m/%d/%Y");

    var len = parent.childNodes.length;
    if (len > 0) {
        for (var i = 0; i < len; i++) {
            parent.removeChild(parent.childNodes[i]);
        }
    }
    cal.create(parent);
    cal.show();
    divVTCal.style.zIndex = 999;
    CalendarActive = 1;
}

function showCalendar(x, y, callTo) {
    var parent = document.getElementById("divCal");
    parent.style.visibility = "visible";
    parent.style.display = "block";
    //parent.style.padding = y + "px 0px 0px " + x + "px";
    parent.style.top = y + "px";
    parent.style.left = x + "px";
    var cal = new Calendar(0, null, callTo);
    cal.weekNumbers = false;
    cal.setDateFormat("%m/%d/%Y");
    var len = parent.childNodes.length;
    if (len > 0) {
        for (var i = 0; i < len; i++) {
            parent.removeChild(parent.childNodes[i]);
        }
    }
    cal.create(parent);
    //cal.showAt(x, y);
    cal.show();
    divCal.style.zIndex = 999;
    CalendarActive = 1;
}

function showHistCalendar() {
    var parent = document.getElementById("divCalContainer");
    var cal = new Calendar(0, null, histCalSelected);
    cal.weekNumbers = false;
    cal.setDateFormat("%m/%d/%Y");
    cal.create(parent);
    cal.show();
}

function toTxtDate(cal, date) {
    if (cal.dateClicked) {
        m_strDate = date;
        document.getElementById("txtDate").value = date;
        cal.hide();
    }
}

function fSSelected(cal, date) {
    if (cal.dateClicked) {
        m_strDate = date;
        document.getElementById("txtStartDate").value = date;
        cal.hide();
        var parent = document.getElementById("divCal");
        parent.style.visibility = "hidden";
        parent.style.display = "none";
    }
}
function fESelected(cal, date) {
    if (cal.dateClicked) {
        m_strDate = date;
        document.getElementById("txtEndDate").value = date;
        cal.hide();
        var parent = document.getElementById("divCal");
        parent.style.visibility = "hidden";
        parent.style.display = "none";
    }
}

function VTSSelected(cal, date) {
    if (cal.dateClicked) {
        m_strDate = date;
        document.getElementById("txtVTStartDate").value = date;
        cal.hide();

        // hiding the calendar background div
        var parent = document.getElementById("divVTCal");
        parent.style.visibility = "hidden";
        parent.style.display = "none";
    }
}
function VTESelected(cal, date) {
    if (cal.dateClicked) {
        m_strDate = date;
        document.getElementById("txtVTEndDate").value = date;
        cal.hide();

        // hiding the calendar background div
        var parent = document.getElementById("divVTCal");
        parent.style.visibility = "hidden";
        parent.style.display = "none";
    }
}

function OPSStartSelected(cal, date) {
    if (cal.dateClicked) {
        m_strDate = date;
        document.getElementById("txtOPSStartDate").value = date;
        cal.hide();
    }
}

function OPSEndSelected(cal, date) {
    if (cal.dateClicked) {
        m_strDate = date;
        document.getElementById("txtOPSEndDate").value = date;
        cal.hide();
    }
}

function dateChanged(calendar) {
    if (calendar.dateClicked)
        AlertMessage(calendar.date.getdate())
}

function histCalSelected(cal, date) {
    if (m_bLoggedIn) {
        m_strDateTime = new Date(date);
        resetHistoricalPlayback();
        historicalDateChanged = true;
    }
    else
        AlertMessage("<br/><br/>Please log in");
}


function onSelect(calendar, date) {
}

function onClose(calendar) {
}
// 
//                                                       End of Calendar functions
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function findAddressForVehicle() {
    element = document.getElementById("vehicle_address");
    element.innerText = "Looking up address...";
    Feed.MpPntRvGeo(cars.Rows[lastClickedBox].lt, cars.Rows[lastClickedBox].ln, fillVehicleAddress);
}

function fillVehicleAddress(result) {
    element = document.getElementById("vehicle_address");
    if (result == null) {
        element.innerText = "Unable to reverse geocode this point.";
    }
    else {
        element.innerText = "  " + result.value;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                                        Process Button Requests
//

function processButtonRequest(id) {
    // 1 - Lock Doors
    // 2 - Unlock Doors
    // 3 - Honk Horn
    // 4 - Disable Starter
    // 5 - Enable Starter
    // 6 - Remote Start
    // 7 - Message to NAV unit
    // 8 - Directions to NAV unit
    // 9 - Text message to driver

    if (ControlPanelLockout == true) {
        AlertMessage("Sorry, this function has been locked at the<br/>request of the account owner.");
        return;
    }
    if (m_demoUser || demo2_user) {
        AlertMessage("Sorry, this feature has been disabled in demonstration mode.");
        return;
    }

    var strSerial = cars.Rows[lastClickedBox].s + "";
    var idCheck = strSerial + "";
    switch (id) {
        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
        case 4:
            break;
        case 5:
            break;
        case 6:
            break;
        case 7:
            if (idCheck.substring(0, 1) == "8" || cars.Rows[lastClickedBox].MsgE == 1) { 
            openCNAVMessage();
            } else {
                AlertMessage("Sorry, this feature is not supported for this device.");
            }

            return;
            break;
        case 8:
            if (idCheck.substring(0, 1) == "8" || cars.Rows[lastClickedBox].MsgE == 1) { 
            openDirectionsToDriver();
            } else {
                AlertMessage("Sorry, this feature is not supported for this device.");
            }

            return;
            break;
        case 9:
            openMessageToDriver(id);
            return;
            break;

    }

    if (idCheck.substring(0, 1) == "7" || idCheck.substring(0, 2) == "14") {
        AlertMessage("Sorry, this feature is not supported for this device.");
        return;
    }

    var strId = id + "";
    DAL.DeviceCommandRequest_Insert(document.getElementById("SESSIONKEY").getAttribute("value"), strSerial, strId, processButtonRequestCallback);
}

function processButtonRequestCallback(id) {
    if (m_demoUser || demo2_user) {
        AlertMessage("Sorry, this feature has been disabled in demonstration mode.");
        return;
    }
    var msg = "Your request failed to process";
    if (id != null) {
        if (id.value != null) {
            msg = "Your "
            switch (id.value) {
                case "1":
                    msg += "'lock door' ";
                    break;
                case "2":
                    msg += "'unlock door' ";
                    break;
                case "3":
                    msg += "'honk horn' ";
                    break;
                case "4":
                    msg += "'disable starter' ";
                    break;
                case "5":
                    msg += "'enable starter' ";
                    break;
                case "6":
                    msg += "'remote start' ";
                    break;
            }
            msg += "request has been processed";
        }
    }
    ActionCompleted(msg);
}

function toggleFlagColor(serial, color) {
    element = document.getElementById("tbmrkr" + serial);

    if (element != null) {
        element.style.backgroundColor = color;
    }
}

function flashFlagColor(serial) {
    element = document.getElementById("tbmrkr" + serial);

    if (element != null) {
        if (element.style.backgroundColor.match("red") != null) {
            element.style.backgroundColor = "white";
        }
        else {
            element.style.backgroundColor = "red";
        }
    }
}

function flashPanic() {
    if (currentpanicentries != null) {
        for (i = 0; i < currentpanicentries.Rows.length; i++) {
            if (currentpanicentries.Rows[i].enabled && parseInt(currentpanicentries.Rows[i].code) == 8) {
                flashFlagColor(currentpanicentries.Rows[i].serial);
            }
        }
    }

    if (m_bLoggedIn)
        setTimeout("flashPanic()", 250);
}

function getSystemMessages() {
    Feed.SSysMsg(getSystemMessagesCallback);
}

function getSystemMessagesCallback(result) {
    override = false;
    if (result != null) {
        if (result.value != null) {
            sysMsgs = result.value;
            for (i = 0; i < sysMsgs.Rows.length; i++) {
                if ((sysMsgs.Rows[i].username == m_CurrentUser) && (sysMsgs.Rows[i].enabled == true)) {
                    openGeneralNotification(sysMsgs.Rows[i].message);
                }

                if ((sysMsgs.Rows[i].username == "allcall") && (sysMsgs.Rows[i].enabled == true)) {
                    openGeneralNotification(sysMsgs.Rows[i].message);
                }
            }
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                                              Reports
//
function getReport(vType) {
    var rptDate = new Date();
    var endDate = new Date();

    //calc GMTOffSet ///////////////////
    var dt = new Date();
    var sGMTOffSet = dt.getTimezoneOffset().toString();

    //  this stops the vehicle refresh while we are doing the report!!
    window.parent.clearTimeout(m_loadTimeout);
    window.parent.clearInterval(m_loadInterval);

    // setting the AJAXPRO utility timeout to 120,000 to allow more time for longer reports to finish
    AjaxPro.timeoutPeriod = 120 * 1000;

    // hiding the print report button
    document.getElementById("printRpt").style.visibility = "hidden";

    //hide current query
    document.getElementById("divResults").innerHTML = '';

    var sessionQueryKey = '';
    var dtFromDate = new Date();
    var dtToDate = new Date();
    var tmpReturn = "";

    if (vType == 8 || vType == 10 || vType == 11) {
        var startDate = document.getElementById("txtStartDate").value;
        if (startDate == null || startDate == '') {
            window.parent.AlertMessage("Please select begin date.");
            return false;
        }

        // Validate Start Date
        tmpReturn = validateDate(startDate);
        if (tmpReturn.length > 0) {
            window.parent.AlertMessage(tmpReturn);
            return false;
        }

        dtFromDate = new Date(startDate + ' 00:00:00 AM');
        var endDate = document.getElementById("txtEndDate").value;
        if (endDate == null || endDate == '') {
            window.parent.AlertMessage("Please select end date.");
            return false;
        }
        dtToDate = new Date(endDate + ' 11:59:59 PM');

        // validate End Date
        tmpReturn = validateDate(endDate);
        if (tmpReturn.length > 0) {
            window.parent.AlertMessage(tmpReturn);
            return false;
        }
    }
    else {
        rptDate = document.getElementById("txtDate").value;
        if (rptDate == null || rptDate == '') {
            window.parent.AlertMessage("Please select report date.");
            return false;
        }
        dtFromDate = new Date(rptDate + ' 00:00:00 AM');
        dtToDate = new Date(rptDate + ' 11:59:59 PM');

        // validate Report Date
        tmpReturn = validateDate(rptDate);
        if (tmpReturn.length > 0) {
            window.parent.AlertMessage(tmpReturn);
            return false;
        }
    }

    var startTime = '';
    var endTime = '';
    var precision = '';
    var type = 0;

    var fromDate = dtFromDate.getFullYear() + "/"
                 + (dtFromDate.getMonth() + 1) + '/'
                 + dtFromDate.getDate() + ' '
                 + dtFromDate.getHours() + ':'
                 + dtFromDate.getMinutes() + ':'
                 + dtFromDate.getSeconds();
    var toDate = dtToDate.getFullYear() + "/"
                 + (dtToDate.getMonth() + 1) + '/'
                 + dtToDate.getDate() + " "
                 + dtToDate.getHours() + ':'
                 + dtToDate.getMinutes() + ':'
                 + dtToDate.getSeconds();

    oSESSIONKEY = document.getElementById("SESSIONKEY");
    sessionQueryKey = oSESSIONKEY.getAttribute("value");

    switch (vType) {
        case 1: // Standard Report
            var oddlVehicleID = document.getElementById("ddlVehicleID");
            rpt_VehicleId = oddlVehicleID.value;
            rpt_fromDate = fromDate.toString();
            rpt_toDate = toDate.toString();
            rpt_reportName = "Vehicle Summary Report";
            showProgressBar();
            Feed.SGenRpt(sessionQueryKey, rpt_VehicleId, fromDate.toString(), toDate.toString(), "0", sGMTOffSet, standardReport_CallBack);
            break;

        case 2: // Enhanced Vehicle Report
            var oddlVehicleID = document.getElementById("ddlVehicleID");
            rpt_VehicleId = oddlVehicleID.value;
            fromDate = dtFromDate.getFullYear() + "/"
                     + (dtFromDate.getMonth() + 1) + '/'
                     + dtFromDate.getDate() + ' '
                     + document.getElementById("startHours").value + ':'
                     + document.getElementById("startMins").value + ':'
                     + document.getElementById("startSecs").value;
            toDate = dtFromDate.getFullYear() + "/"
                   + (dtFromDate.getMonth() + 1) + '/'
                   + dtFromDate.getDate() + ' '
                   + document.getElementById("endHours").value + ':'
                   + document.getElementById("endMins").value + ':'
                   + document.getElementById("endSecs").value;
            rpt_fromDate = fromDate.toString();
            rpt_toDate = toDate.toString();
            type = document.getElementById("ddlPrecisionType").selectedIndex;
            precision = document.getElementById("precisionValue").value;
            if (type == 0) {
                rpt_precision = precision;
            }
            else {
                if (type == 1) {
                    rpt_precision = precision * 60;
                }
                else {
                    rpt_precision = precision * 3600;
                }
            }
            showProgressBar();
            Feed.SGenRpt(sessionQueryKey, rpt_VehicleId, fromDate.toString(), toDate.toString(), "0", sGMTOffSet, enhancedReport_CallBack);
            break;
        case 3: // Stop/Start Report
            var oddlVehicleID = document.getElementById("ddlVehicleID");
            rpt_VehicleId = oddlVehicleID.value;
            fromDate = dtFromDate.getFullYear() + "/"
                     + (dtFromDate.getMonth() + 1) + '/'
                     + dtFromDate.getDate() + ' '
                     + document.getElementById("startHours").value + ':'
                     + document.getElementById("startMins").value + ':'
                     + document.getElementById("startSecs").value;
            toDate = dtFromDate.getFullYear() + "/"
                     + (dtFromDate.getMonth() + 1) + '/'
                     + dtFromDate.getDate() + ' '
                     + document.getElementById("endHours").value + ':'
                     + document.getElementById("endMins").value + ':'
                     + document.getElementById("endSecs").value;
            rpt_fromDate = fromDate.toString();
            rpt_toDate = toDate.toString();
            type = document.getElementById("ddlPrecisionType").selectedIndex;
            precision = document.getElementById("precisionValue").value;
            if (type == 0) {
                rpt_precision = precision;
            }
            else {
                if (type == 1) {
                    rpt_precision = precision * 60;
                }
                else {
                    rpt_precision = precision * 3600;
                }
            }
            showProgressBar();
            Feed.SGenRpt(sessionQueryKey, rpt_VehicleId, fromDate.toString(), toDate.toString(), "0", sGMTOffSet, stopStartReport_CallBack);
            break;
        case 4: // Agressive Driving Report
            var oSpeedChange = document.getElementById("ddSpeedChange");
            rpt_precision = oSpeedChange.value;
            rpt_fromDate = fromDate.toString();
            rpt_toDate = toDate.toString();
            showProgressBar();
            //Feed.SGenRpt(sessionQueryKey, "0", fromDate.toString(), toDate.toString(), "0", sGMTOffSet, agressiveDrivingReport_CallBack);
            Feed.SAgrRpt(sessionQueryKey, "0", fromDate.toString(), toDate.toString(), rpt_precision, sGMTOffSet, agressiveDrivingReport_CallBack);
            break;
        case 5: // Excessive Idling Report
            rpt_precisionType = document.getElementById("ddlPrecisionType").selectedIndex;
            precision = document.getElementById("precisionValue").value;
            if (rpt_precisionType == 0) {
                rpt_precision = precision;
            }
            else {
                if (rpt_precisionType == 1) {
                    rpt_precision = precision * 60;
                }
                else {
                    rpt_precision = precision * 3600;
                }
            }
            rpt_fromDate = fromDate.toString();
            rpt_toDate = toDate.toString();
            showProgressBar();
            Feed.SGenRpt(sessionQueryKey, "0", fromDate.toString(), toDate.toString(), "0", sGMTOffSet, excessiveIdlingReport_CallBack);
            break;
        case 6: // Milage Report
            var oddlVehicleID = document.getElementById("ddlVehicleID");
            rpt_VehicleId = oddlVehicleID.value;
            rpt_fromDate = fromDate.toString();
            rpt_toDate = toDate.toString();
            rpt_reportName = "Vehicle Mileage Report";
            showProgressBar();
            Feed.SGenRpt(sessionQueryKey, rpt_VehicleId, fromDate.toString(), toDate.toString(), "0", sGMTOffSet, standardReport_CallBack);
            break;
        case 7: // PTO Report
            var oddlVehicleID = document.getElementById("ddlVehicleID");
            rpt_VehicleId = oddlVehicleID.value;
            rpt_fromDate = fromDate.toString();
            rpt_toDate = toDate.toString();
            rpt_reportName = "Switches Report";
            showProgressBar();
            Feed.SGenRpt(sessionQueryKey, rpt_VehicleId, fromDate.toString(), toDate.toString(), "0", sGMTOffSet, switchesReport_CallBack);
            break;
        case 8:  // Speeding Report
            precision = document.getElementById("precisionValue").value;
            rpt_precision = precision;
            rpt_fromDate = fromDate.toString();
            rpt_toDate = toDate.toString();
            rpt_reportName = "Speeding Report";
            showProgressBar();
            Feed.SGenRpt(sessionQueryKey, "0", fromDate.toString(), toDate.toString(), rpt_precision, sGMTOffSet, speedingReport_CallBack);
            break;
        case 9: // Sent Message History
            var sentTo = document.getElementById("ddlVehicleID").value;
            var sentFrom = document.getElementById("sentFrom").value;
            showProgressBar();
            Feed.SSntMsg(sessionQueryKey, sentTo, sentFrom, dtFromDate.toString(), toDate.toString(), sGMTOffSet, sentMsgReport_CallBack);
            break;
        case 10: // Units within radius (Proximity Report)
            var rpt_feet = document.getElementById("txtFeet").value;
            var rpt_lat = document.getElementById("addressLAT").value;
            var rpt_lon = document.getElementById("addressLON").value;
            // building start and end date/time based on user input
            fromDate = dtFromDate.getFullYear() + "/"
                     + (dtFromDate.getMonth() + 1) + '/'
                     + dtFromDate.getDate() + ' '
                     + document.getElementById("startHours").value + ':'
                     + document.getElementById("startMins").value + ':'
                     + document.getElementById("startSecs").value;
            toDate = dtFromDate.getFullYear() + "/"
                     + (dtFromDate.getMonth() + 1) + '/'
                     + dtFromDate.getDate() + ' '
                     + document.getElementById("endHours").value + ':'
                     + document.getElementById("endMins").value + ':'
                     + document.getElementById("endSecs").value;
            rpt_fromDate = fromDate.toString();
            rpt_toDate = toDate.toString();
            rpt_reportName = "Proximity Report";
            showProgressBar();
            Feed.SUntNRad(sessionQueryKey, fromDate.toString(), toDate.toString(), rpt_feet, rpt_lat, rpt_lon, sGMTOffSet, proximityReport_CallBack);
            break;

        case 11: // Units within GeoFence (Zone Activity Report)
            var strList = "";
            var geoArray = new Array();
            var vArray = new Array();
            var count = 0;

            // Validating Start Hours, Mins and Secs entered by user
            var tmpHours = 0;
            var tmpMins = 0;
            var tmpSecs = 0;
            tmpHours = document.getElementById("startHours").value;
            tmpMins = document.getElementById("startMins").value;
            tmpSecs = document.getElementById("startSecs").value;

            if ((!isNumeric(tmpHours) || tmpHours < 0 || tmpHours > 23) || (!isNumeric(tmpMins) || tmpMins < 0 || tmpMins > 59) || (!isNumeric(tmpSecs) || tmpSecs < 0 || tmpSecs > 59)) {
                window.parent.AlertMessage("Please enter a valid Start Time.");
                return false;
            }

            // building start date/time based on user input
            fromDate = dtFromDate.getFullYear() + "/"
                     + (dtFromDate.getMonth() + 1) + '/'
                     + dtFromDate.getDate() + ' '
                     + tmpHours + ':'
                     + tmpMins + ':'
                     + tmpSecs;


            // Validating End Hours, Mins and Secs entered by user
            var tmpHours = 0;
            var tmpMins = 0;
            var tmpSecs = 0;
            tmpHours = document.getElementById("endHours").value;
            tmpMins = document.getElementById("endMins").value;
            tmpSecs = document.getElementById("endSecs").value;

            if ((!isNumeric(tmpHours) || tmpHours < 0 || tmpHours > 23) || (!isNumeric(tmpMins) || tmpMins < 0 || tmpMins > 59) || (!isNumeric(tmpSecs) || tmpSecs < 0 || tmpSecs > 59)) {
                window.parent.AlertMessage("Please enter a valid End Time.");
                return false;
            }

            // building end date/time based on user input                     
            toDate = dtToDate.getFullYear() + "/"
                     + (dtToDate.getMonth() + 1) + '/'
                     + dtToDate.getDate() + ' '
                     + document.getElementById("endHours").value + ':'
                     + document.getElementById("endMins").value + ':'
                     + document.getElementById("endSecs").value;


            // Restricting Date Range to one week ( 7 day period )
            var tmpFromDate = new Date(fromDate);
            var tmpToDate = new Date(toDate);
            var tmpMilSecs = tmpToDate - tmpFromDate;
            tmpDays = Math.round(tmpMilSecs / (1000 * 60 * 60 * 24));
            if (tmpDays > 7) {
                window.parent.AlertMessage("Please reduce your date range to 7 days or less.");
                return false;
            }

            // getting the unit List options that are selected
            var cblist = document.getElementsByName('unitBox');
            for (var i = 1; i < cblist.length; i++) {
                if (cblist[i].checked == true) {
                    vArray[count] = cblist[i].value;
                    count += 1;
                }
            }

            // if no vehicles where selected give error message
            if (count < 1) {
                window.parent.AlertMessage("Please select at least one Vehicle from the List.");
                return false;
            }

            var rpt_vehicles = strList;

            // getting the geo fence List options that are selected
            strList = "";
            count = 0;
            var cblist = document.getElementsByName('geoBox');
            for (var i = 1; i < cblist.length; i++) {
                if (cblist[i].checked == true) {
                    // each array element will contain the geoID
                    geoArray[count] = cblist[i].value;
                    count += 1;
                }
            }

            // if no GeoFences where selected give error message
            if (count < 1) {
                window.parent.AlertMessage("Please select at least one Zone from the List.");
                return false;
            }

            rpt_fromDate = fromDate.toString();
            rpt_toDate = toDate.toString();
            rpt_reportName = "Zone Activity Report";
            showProgressBar();

            DAL.GeofenceReport(sessionQueryKey, vArray, geoArray, fromDate.toString(), toDate.toString(), sGMTOffSet, GetSelectedValue("GeoReportSort"), geoReport_CallBack);
            break;

        default:
            return false;
            break;
    }
}

function showProgressBar() {
    // displaying Progress Bar
    var tmpDiv = document.getElementById("progressBar");
    tmpDiv.style.visibility = "visible";
    tmpDiv.style.display = "block";
}


function restartLoadMarkers() {
    // this is to start the vehicle refresh after the report is displayed  
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //if (location.hostname != "localhost") {
    //  we don't restart vehicle refresh on localhost because it blows up!
    var sessionID = document.getElementById("SESSIONKEY").getAttribute("value");
    m_loadTimeout = setTimeout("loadMarkers('" + sessionID + "');", 4000);
    //}
}
function stopLoadMarkers() {
    clearTimeout(m_loadTimeout);
    clearInterval(m_loadInterval);
}

function validateDate(pDate) {
    // To check Date format as mm/dd/yyyy
    var regExpDateFormat = /^\d{2}\/\d{2}\/\d{4}$/

    if (!regExpDateFormat.test(pDate)) {
        //        window.parent.AlertMessage("Invalid Date Format. Please correct to mm/dd/yyyy.");
        //        return false;
        return "Invalid Date Format. Please correct to mm/dd/yyyy.";
    }
    else {
        //Checking for valid date by using the date object
        var monthValue = pDate.split("/")[0];
        var dayValue = pDate.split("/")[1];
        var yearValue = pDate.split("/")[2];

        var tmpDate = new Date(yearValue, monthValue - 1, dayValue);
        if ((tmpDate.getMonth() + 1 != monthValue) || (tmpDate.getDate() != dayValue) || (tmpDate.getFullYear() != yearValue)) {
            //window.parent.AlertMessage("Invalid Month, Day, or Year.");
            //return false;
            return "Invalid Month, Day, or Year.";
        }
        else {
            //return true;
            return "";
        }
    }
}

///////////////////////////                    Standard Report
function standardReport_CallBack(response) {
    rpt_history = response.value;
    rpt_historySub = 0;
    rpt_linesPrinted = 0;
    rpt_lastLat = null;
    rpt_lastLon = null;
    rpt_lastOri = null;

    rpt_GraphArray1 = new Array();
    rpt_GraphArray2 = new Array();
    rpt_FirstArray = null;
    rpt_chartTitle = null;

    // Hiding progress bar, since data is about to be displayed.
    var tmpDiv = document.getElementById("progressBar");
    tmpDiv.style.visibility = "hidden";
    tmpDiv.style.display = "none";

    rpt_Report = new StringBuilder();
    rpt_Report.append(
        "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"reportTable\" style=\"background-color: Transparent;\">" +
          "<tr>" +
            "<td colspan=\"4\" class=\"reportHeader\">" +
              "Device ID: " + rpt_VehicleId + "<br>" +
              "Begin: " + rpt_fromDate + "<br>" +
              "End: " + rpt_toDate +
            "</td>" +
          "</tr>" +
          "<tr><td colspan='4'>&nbsp;</td></tr>" +
          "<tr>" +
            "<td colspan=\"4\" align='center' class=\"reportTitle\">" + rpt_reportName + "</td>" +
          "</tr>" +
          "<tr><td colspan='4'>&nbsp;</td></tr>" +
          "<tr>");
    if (rpt_reportName == "Vehicle Mileage Report") {
        //var WebChartHeading = document.getElementById("WebChartHeadingMIL");
        //WebChartHeading.style.visibility = "hidden";
        rpt_Report.append(
            "<td class=\"reportColTitle\" width=\"75\">Time</td>" +
            "<td class=\"reportColTitle\" width=\"300\">Address</td>" +
            "<td class=\"reportColTitle\" width=\"130\">Speed</td>" +
            "<td class=\"reportColTitle\" width=\"170\">Distance</td>" +
           "</tr>");
        chartDiv = document.getElementById("WebChartMIL");
        chartDiv.innerHTML = "";
        chartDiv.innerHTML = "<center><p>Loading Report Chart</p></center>";
        chartDiv.innerHTML += "<center><img alt=\"Report Loading\" id=\"Chartloader\" src=\"images/redline2.gif\" width=\"150\" height=\"8\"/></center>";
    }
    else {
        //var WebChartHeading = document.getElementById("WebChartHeadingSTD");
        //WebChartHeading.innerText = "";
        rpt_chartTitle = null;
        rpt_Report.append(
            "<td class=\"reportColTitle\" width=\"150\">Time</td>" +
            "<td class=\"reportColTitle\" width=\"325\">Address</td>" +
            "<td class=\"reportColTitle\" width=\"100\">Speed</td>" +
            "<td class=\"reportColTitle\" width=\"100\">Heading</td>" +
          "</tr>");
        chartDiv = document.getElementById("WebChartSTD");
        chartDiv.innerHTML = "";
        chartDiv.innerHTML = "<center><p>Loading Report Chart</p></center>";
        chartDiv.innerHTML += "<center><img alt=\"Report Loading\" id=\"Chartloader\" src=\"images/redline2.gif\" width=\"150\" height=\"8\"/></center>";
    }

    if (rpt_history == null || rpt_history.Rows.length == 0) {
        var divResults = document.getElementById("divResults");
        divResults.style.top = "304px";
        divResults.innerHTML = "<table style='background-color: Transparent;'><tr><td><br>&nbsp;&nbsp;No historical information was found for specified interval</td></tr>";
        chartDiv.innerHTML = "";
        window.parent.restartLoadMarkers();
        return null;
    }

    // Hide selection criteria
    document.getElementById("divRpt").style.visibility = "hidden";
    var divResults = document.getElementById("divResults");
    divResults.style.top = "304px";

    var lat = rpt_history.Rows[rpt_historySub].lat;
    var lon = rpt_history.Rows[rpt_historySub].lon;
    Feed.MpPntRvGeo(lat, lon, standardReportLoop);
}

function standardReportLoop(response) {
    oSessionKey = document.getElementById("SESSIONKEY");
    var sessionID = oSessionKey.getAttribute("value");
    var divResults = document.getElementById("divResults");

    var lat = rpt_history.Rows[rpt_historySub].lat;
    var lon = rpt_history.Rows[rpt_historySub].lon;
    var vel = parseInt(rpt_history.Rows[rpt_historySub].vel);
    var ori = rpt_history.Rows[rpt_historySub].ori;
    var time = rpt_history.Rows[rpt_historySub].time;
    var dKPH = Math.round(vel * 1.60934);
    var locDesc = "";

    if (rpt_historySub == 0) {
        locDesc = "Initial vehicle position at <br>";
        rpt_lastLat = lat;
        rpt_lastLon = lon;
        rpt_lastOri = ori;
        rpt_miles = 0;
    }

    var miles = calcDistance(rpt_lastLat, rpt_lastLon, lat, lon);
    rpt_miles += miles;
    miles = Math.round(rpt_miles * 10) / 10;
    var KMs = Math.round(rpt_miles * 1.60934 * 10) / 10;

    if (vel != 0 && rpt_lastVel == 0) {
        hours = rpt_lastTime.getHours() + "";
        minutes = rpt_lastTime.getMinutes() + "";
        seconds = rpt_lastTime.getSeconds() + "";
        while (hours.length < 2) {
            hours = "&nbsp;&nbsp;" + hours;
        }
        while (minutes.length < 2) {
            minutes = "0" + minutes;
        }
        while (seconds.length < 2) {
            seconds = "0" + seconds;
        }
        // checking to see if the address field has a valid address (reverse geocoded on DL)
        if (rpt_history.Rows[rpt_historySub].address != null && rpt_history.Rows[rpt_historySub].address != "" && rpt_history.Rows[rpt_historySub].address.substring(0, 15) != "Unknown Address") {

            rpt_Report.append("<tr><td>" + hours + ":" + minutes + ":" + seconds + "</td><td>"
                + "Stayed at <br>"
                + rpt_history.Rows[rpt_historySub].address.replace("^", " ") + "</td>"
                + "<td>0mph 0kph</td>");
        }
        else {

            rpt_Report.append("<tr><td>" + hours + ":" + minutes + ":" + seconds + "</td><td>"
                + "Stayed at <br>"
                + "<span id=\"address_" + (rpt_historySub - 1) + "\"><a href=\"javascript:void(0);\" onclick=\"javascript:showAddress('" + (rpt_historySub - 1) + "','" + rpt_lastLat + "','" + rpt_lastLon + "', '0');\" title=\"Click Here to view Address\" >Lat:" + rpt_lastLat + "  Lon:" + rpt_lastLon + "</a></span></td>"
                + "<td>0mph 0kph</td>");
        }
        if (rpt_reportName == "Vehicle Mileage Report") {
            rpt_Report.append("<td></td></tr>");
            rpt_GraphArray1.push(rpt_miles);
            rpt_GraphArray2.push(0);
        }
        else {
            rpt_Report.append("<td>" + rpt_lastOri + "</td></tr>");
            rpt_GraphArray1.push(rpt_lastVel);
            rpt_GraphArray2.push(rpt_GraphArray1.length);
        }
        divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        locDesc = "";
        rpt_lastVel = vel;
    }

    if (Math.abs(rpt_lastOri - ori) > 30) {
        locDesc = "Heading change at <br>"
    }
    if (locDesc == "") {
        locDesc = "Continued to <br>";
    }
    if ( rpt_historySub == 0 && response != null) {
        locDesc += response.value + "</td>";
    }
    // checking to see if the address field has a valid address (reverse geocoded on DL)
    else if (rpt_history.Rows[rpt_historySub].address != null && rpt_history.Rows[rpt_historySub].address != "" && rpt_history.Rows[rpt_historySub].address.substring(0, 15) != "Unknown Address") {
        locDesc += rpt_history.Rows[rpt_historySub].address.replace("^", " ") + "</td>";
    }
    else {
        locDesc += "<span id=\"address_" + rpt_historySub + "\"><a href=\"javascript:void(0);\" onclick=\"javascript:showAddress('" + rpt_historySub + "','" + lat + "','" + lon + "', '0');\" title=\"Click Here to view Address\" >Lat:" + lat + "  Lon:" + lon + "</a></span></td>";
    }

    if ((vel != 0 && rpt_lastVel != 0) || rpt_historySub == 0 || rpt_historySub == rpt_history.Rows.length - 1) {

        hours = time.getHours() + "";
        minutes = time.getMinutes() + "";
        seconds = time.getSeconds() + "";
        while (hours.length < 2) {
            hours = "&nbsp;&nbsp;" + hours;
        }
        while (minutes.length < 2) {
            minutes = "0" + minutes;
        }
        while (seconds.length < 2) {
            seconds = "0" + seconds;
        }

        rpt_Report.append("<tr><td>" + hours + ":" + minutes + ":" + seconds + "</td><td>"
                    + locDesc
                    + "<td>" + vel + "mph " + dKPH + "kph</td>");
        if (rpt_reportName == "Vehicle Mileage Report") {
            rpt_Report.append("<td>" + miles + "mi " + KMs + "km</td></tr>");
            rpt_GraphArray1.push(rpt_miles);
            rpt_GraphArray2.push(vel);
        }
        else {
            rpt_Report.append("<td>" + rpt_history.Rows[rpt_historySub].ori + "</td></tr>");
            rpt_GraphArray1.push(vel);
            rpt_GraphArray2.push(rpt_GraphArray1.length);
        }
        rpt_linesPrinted++;
        var waitCt = parseInt(rpt_linesPrinted / 100) + 1;
        if (rpt_linesPrinted % waitCt == 0) {
            divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        }
    }

    if (divResults.scrollHeight > 400) {
        divResults.style.top = 295 - (divResults.scrollHeight - 400) + "px";
    }
    rpt_historySub++;
    if (rpt_historySub < rpt_history.Rows.length) {
        rpt_lastLat = lat;
        rpt_lastLon = lon;
        rpt_lastOri = ori;
        rpt_lastVel = vel;
        rpt_lastTime = time;
        rpt_Timeout = setTimeout("standardReportLoop();", 0);
    }
    else {
        divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        divResults.style.top = "304px";
        if (rpt_GraphArray1.length == 0) {
            rpt_GraphArray1.push(null);
        }
        if (rpt_GraphArray2.length == 0) {
            rpt_GraphArray2.push(null);
        }
        if (rpt_reportName == "Vehicle Mileage Report") {
            rpt_chartTitle = "Speed";
            Feed.DrwMilGrph(rpt_GraphArray1, rpt_GraphArray2, rpt_chartTitle);
            divResults.style.top = "304px";
            var chartDiv = document.getElementById("WebChartMIL");
            chartDiv.innerHTML = "";
            chartDiv.innerHTML = "<iframe id=\"thechart\" src=\"ChartingMIL.aspx\" frameborder=\"0\" scrolling=\"no\" style=\"height: 295px; width:360px;\" allowtransparency='true'></iframe>";
            //var WebChartHeading = document.getElementById("WebChartHeadingMIL");
            //WebChartHeading.innerText = "Speed";
        }
        else {
            rpt_chartTitle = "Speed";
            Feed.DrwMilGrph(rpt_GraphArray1, rpt_GraphArray2, rpt_chartTitle);
            setTimeout('setIFrameSource()',500);
            //var WebChartHeading = document.getElementById("WebChartHeadingSTD");
            //WebChartHeading.innerText = "Speed";
        }

        // redisplay selection criteria
        document.getElementById("divRpt").style.visibility = "visible";
        document.getElementById("printRpt").style.visibility = "visible";

        // restart the main loop
        window.parent.restartLoadMarkers();
    }
}

function setIFrameSource() {
	var chartDiv = document.getElementById("WebChartSTD");
	chartDiv.innerHTML = "";
	chartDiv.innerHTML = "<iframe id=\"thechart\" src=\"ChartingSTD.aspx\" frameborder=\"0\" scrolling=\"no\" style=\"height: 295px; width:360px;\" allowtransparency='true'></iframe>";
}
/////////////////////////////                    Enhanced Report
function enhancedReport_CallBack(response) {
    rpt_history = response.value;
    rpt_historySub = 0;
    rpt_linesPrinted = 0;

    rpt_GraphArray1 = new Array();
    rpt_GraphArray2 = new Array();
    rpt_FirstArray = null;
    rpt_chartTitle = null;
    //var WebChartHeading = document.getElementById("WebChartHeadingSTD");
    //WebChartHeading.innerText = "";

    // Hiding progress bar, since data is about to be displayed.
    var tmpDiv = document.getElementById("progressBar");
    tmpDiv.style.visibility = "hidden";
    tmpDiv.style.display = "none";

    rpt_Report = new StringBuilder();
    rpt_Report.append(
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"reportTable\" style=\"background-color: Transparent;\">" +
            "<tr>" +
              "<td colspan=\"4\" class=\"reportHeader\">" +
                "Device ID: " + rpt_VehicleId + "<br>" +
                "Begin: " + rpt_fromDate + "<br>" +
                "End: " + rpt_toDate +
              "</td>" +
            "</tr>" +
            "<tr>" +
              "<td colspan=\"4\" align='center' class=\"reportTitle\">Enhanced Report</td>" +
            "</tr>" +
            "<tr><td colspan='4'>&nbsp;</td></tr>" +
            "<tr>" +
              "<td class=\"reportColTitle\" width=\"200\">Date/Time</td>" +
              "<td class=\"reportColTitle\" width=\"290\">Address</td>" +
              "<td class=\"reportColTitle\" width=\"105\">Speed</td>" +
              "<td class=\"reportColTitle\" width=\"60\">Heading</td>" +
            "</tr>");

    if (rpt_history == null || rpt_history.Rows.length == 0) {
        var divResults = document.getElementById("divResults");
        divResults.style.top = "304px";
        divResults.innerHTML = "<table><tr><td><br>&nbsp;&nbsp;No historical information was found for specified interval</td></tr>";
        window.parent.restartLoadMarkers();
        return null;
    }

    // Hide selection criteria
    document.getElementById("divRpt").style.visibility = "hidden";
    chartDiv = document.getElementById("WebChartSTD");
    chartDiv.innerHTML = "";
    chartDiv.innerHTML = "<center><p>Loading Report Chart</p></center>";
    chartDiv.innerHTML += "<center><img alt=\"Report Loading\" id=\"Chartloader\" src=\"images/redline2.gif\" width=\"150\" height=\"8\"/></center>";

    var lat = rpt_history.Rows[rpt_historySub].lat;
    var lon = rpt_history.Rows[rpt_historySub].lon;
    Feed.MpPntRvGeo(lat, lon, enhancedReportLoop);
}

function enhancedReportLoop(response) {
    oSessionKey = document.getElementById("SESSIONKEY");
    var sessionID = oSessionKey.getAttribute("value");
    var divResults = document.getElementById("divResults");
    divResults.style.visibility = "visible";
    var lat, lon, vel, ori, time, dKPH, locDesc, secs;

   // for (rpt_historySub = 0; rpt_historySub < rpt_history.Rows.length; rpt_historySub++) {

        lat = rpt_history.Rows[rpt_historySub].lat;
        lon = rpt_history.Rows[rpt_historySub].lon;
        vel = parseInt(rpt_history.Rows[rpt_historySub].vel);
        ori = rpt_history.Rows[rpt_historySub].ori;
        time = rpt_history.Rows[rpt_historySub].time;
        dKPH = Math.round(vel * 1.60934);
        locDesc = "";
        secs = 0;

        if (rpt_historySub != 0) {
            secs = parseInt((time.getTime() - rpt_lastTime.getTime()) / 1000);
        }
        if (secs >= rpt_precision || rpt_historySub == 0 || rpt_historySub == rpt_history.Rows.length - 1) {
            // first record is reverse geo coded by microsoft 
            if (rpt_historySub == 0 && response != null) {
                locDesc += response.value + "</td>";
            }
            // checking to see if the address field has a valid address (reverse geocoded on DL)
            else if (rpt_history.Rows[rpt_historySub].address != null && rpt_history.Rows[rpt_historySub].address != "" && rpt_history.Rows[rpt_historySub].address.substring(0,15) != "Unknown Address") {
                locDesc += rpt_history.Rows[rpt_historySub].address.replace("^", " ") + "</td>";
            }
            // adding a link that will reverse geocode by 
            else {
                locDesc += "<span id=\"address_" + rpt_historySub + "\"><a href=\"javascript:void(0);\" onclick=\"javascript:showAddress('" + rpt_historySub + "','" + lat + "','" + lon + "', '0');\" title=\"Click Here to view Address\" >Lat:" + lat + "  Lon:" + lon + "</a></span></td>";
            }

            rpt_Report.append("<tr><td>" + time + "</td><td>"
                        + locDesc
                        + "<td>" + vel + "mph " + dKPH + "kph</td>"
                        + "<td>" + rpt_history.Rows[rpt_historySub].ori + "</td></tr>");
            rpt_GraphArray1.push(vel);
            rpt_GraphArray2.push(rpt_GraphArray1.length);
            rpt_linesPrinted++;
            var waitCt = parseInt(rpt_linesPrinted / 100) + 1;
            if (rpt_linesPrinted % waitCt == 0) {
                divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
            }
            rpt_lastTime = time;
        }
        if (divResults.scrollHeight > 400) {
            divResults.style.top = 295 - (divResults.scrollHeight - 400) + "px";
        }
        else {
            divResults.style.top = "304px";
        }
        rpt_historySub++;
    //}   // end for
    if (rpt_historySub < rpt_history.Rows.length) {
        rpt_Timeout = setTimeout("enhancedReportLoop();", 0);
    }
    else {
        if (rpt_GraphArray1.length == 0) {
            rpt_GraphArray1.push(null);
        }
        if (rpt_GraphArray2.length == 0) {
            rpt_GraphArray2.push(null);
        }
        divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        divResults.style.top = "304px";
        rpt_chartTitle = "Speed";
        Feed.DrwMilGrph(rpt_GraphArray1, rpt_GraphArray2, rpt_chartTitle);
        var chartDiv = document.getElementById("WebChartSTD");
        chartDiv.innerHTML = "";
        chartDiv.innerHTML = "<iframe id=\"thechart\" src=\"ChartingSTD.aspx\" frameborder=\"0\" scrolling=\"no\" style=\"height: 295px; width:360px; vertical-align:top;\" allowtransparency='true'></iframe>";
        //var WebChartHeading = document.getElementById("WebChartHeadingSTD");
        //WebChartHeading.innerText = "Speed";
        // redisplay selection criteria
        document.getElementById("divRpt").style.visibility = "visible";
        document.getElementById("printRpt").style.visibility = "visible";
        window.parent.restartLoadMarkers();
    }
}

/////////////////////////////                    Agressive Driving Report
function agressiveDrivingReport_CallBack(response) {
    rpt_history = response.value;

    oSESSIONKEY = document.getElementById("SESSIONKEY");
    sessionQueryKey = oSESSIONKEY.getAttribute("value");
    Feed.SVehNm(sessionQueryKey, agressiveDriving_run);

}

function agressiveDriving_run(response) {
    // rpt_vehNames = response.value
    rpt_historySub = 0;
    rpt_linesPrinted = 0;

    // Assigning the vehnames to an array for quick lookup
    for (var i = 0; i < response.value.Rows.length; i++) {
            rpt_vehNames[response.value.Rows[i].Serial] = response.value.Rows[i].VehicleName;
    }

    // Hiding progress bar, since data is about to be displayed.
    var tmpDiv = document.getElementById("progressBar");
    tmpDiv.style.visibility = "hidden";
    tmpDiv.style.display = "none";

    var divResults = document.getElementById("divResults");
    rpt_Report = new StringBuilder();
    rpt_Report.append(
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"reportTable\" style=\"background-color: Transparent;\">" +
            "<tr>" +
              "<td colspan=\"5\" class=\"reportHeader\">" +
                "&nbsp;Begin: " + rpt_fromDate + "<br>" +
                "&nbsp;End: " + rpt_toDate +
              "</td>" +
            "</tr>" +
            "<tr>" +
              "<td colspan=\"5\" align='center' class=\"reportTitle\">Aggressive Driving Report</td>" +
            "</tr>" +
            "<tr><td colspan='5'>&nbsp;</td></tr>" +
            "<tr>" +
              "<td class=\"reportColTitle\" width=\"40\">Vehicle</td>" +
              "<td class=\"reportColTitle\" width=\"175\">Date/Time</td>" +
              "<td class=\"reportColTitle\" width=\"245\">Location</td>" +
              "<td class=\"reportColTitle\" width:\"60\">Vel 1</td>" +
              "<td class=\"reportColTitle\" width:\"60\">Vel 2</td>" +
           "</tr>");

    if (rpt_history == null || rpt_history.Rows.length == 0) {
        divResults.innerHTML = "<table><tr><td><br>&nbsp;&nbsp;No historical information was found for specified interval</td></tr>";
        window.parent.restartLoadMarkers();
        return null;
    }

    // Hide selection criteria
    document.getElementById("divRpt").style.visibility = "hidden";
    divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"5\" class=\"reportHeader\">&nbsp;</td></tr></table>";
    rpt_Timeout = setTimeout("agressiveDrivingReportLoop2();", 0);

}

function agressiveDrivingReportLoop(response) {
    oSessionKey = document.getElementById("SESSIONKEY");
    var sessionID = oSessionKey.getAttribute("value");
    var divResults = document.getElementById("divResults");

    var vehicleId = rpt_history.Rows[rpt_historySub].VehicleId;
    var lat = rpt_history.Rows[rpt_historySub].lat;
    var lon = rpt_history.Rows[rpt_historySub].lon;
    var vel = parseInt(rpt_history.Rows[rpt_historySub].vel);
    var time = rpt_history.Rows[rpt_historySub].time;
    var KPH = Math.round(vel * 1.60934);
    var lastKPH = Math.round(rpt_lastVel * 1.60934);

    if (rpt_historySub == 0) {
        rpt_lastVehicleId = vehicleId;
        rpt_lastVel = vel;
    }
    if (vehicleId != rpt_lastVehicleId) {
        rpt_lastVehicleId = vehicleId;
        rpt_lastVel = vel;
    }


    if (Math.abs(rpt_lastVel - vel) > rpt_precision) {
        var vehName = vehicleId;
        for (var i = 0; i < rpt_vehNames.Rows.length; i++) {
            if (rpt_vehNames.Rows[i].Serial == vehName) {
                vehName = rpt_vehNames.Rows[i].VehicleName;
                break;
            }
        }

        // checking to see if the address field has a valid address (reverse geocoded on DL)
        if (rpt_history.Rows[rpt_historySub].address != null && rpt_history.Rows[rpt_historySub].address != "" && rpt_history.Rows[rpt_historySub].address.substring(0, 15) != "Unknown Address") {
            rpt_Report.append(
                      "<tr><td>" + vehName + "</td>"
                    + "<td>" + time + "</td><td>"
                    + rpt_history.Rows[rpt_historySub].address.replace("^", " ") + "</td>"
                    + "<td>" + rpt_lastVel + "mph " + lastKPH + "kph</td>"
                    + "<td>" + vel + "mph " + KPH + "kph</td></tr>");
            
        }
        else {
            rpt_Report.append(
                      "<tr><td>" + vehName + "</td>"
                    + "<td>" + time + "</td><td>"
                    + "<span id=\"address_" + rpt_historySub + "\"><a href=\"javascript:void(0);\" onclick=\"javascript:showAddress('" + rpt_historySub + "','" + lat + "','" + lon + "', '0');\" title=\"Click Here to view Address\" >Lat:" + lat + "  Lon:" + lon + "</a></span></td>"
                    + "<td>" + rpt_lastVel + "mph " + lastKPH + "kph</td>"
                    + "<td>" + vel + "mph " + KPH + "kph</td></tr>");
        }

        rpt_linesPrinted++;
        var waitCt = parseInt(rpt_linesPrinted / 100) + 1;
        if (rpt_linesPrinted % waitCt == 0) {
            divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        }
    }


    if (divResults.scrollHeight > 700) {
        divResults.style.top = (700 - divResults.scrollHeight) + "px";
    }
    rpt_historySub++;
    if (rpt_historySub < rpt_history.Rows.length) {
        rpt_lastVehicleId = vehicleId;
        rpt_lastVel = vel;
        rpt_lastTime = time;
        rpt_Timeout = setTimeout("agressiveDrivingReportLoop();", 0);
    }
    else {
        if (rpt_linesPrinted == 0) {
            divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\">&nbsp;&nbsp;No historical information was found for specified interval</td></tr></table>";
        }
        else {
            divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        }
        divResults.style.top = "51px";
        // redisplay selection criteria
        document.getElementById("divRpt").style.visibility = "visible";
        document.getElementById("printRpt").style.visibility = "visible";

        window.parent.restartLoadMarkers();
    }
}

function agressiveDrivingReportLoop2(response) {
    oSessionKey = document.getElementById("SESSIONKEY");
    var sessionID = oSessionKey.getAttribute("value");
    var divResults = document.getElementById("divResults");

    var vehicleId = rpt_history.Rows[rpt_historySub].VehicleId;
    var lat = rpt_history.Rows[rpt_historySub].lat;
    var lon = rpt_history.Rows[rpt_historySub].lon;
    var vel = parseInt(rpt_history.Rows[rpt_historySub].vel);
    var time = rpt_history.Rows[rpt_historySub].time;
    //var KPH = Math.round(vel * 1.60934);
    //var lastKPH = Math.round(rpt_history.Rows[rpt_historySub].prevVel * 1.60934);
    var speed1 = "";
    var speed2 = "";

//    if (rpt_historySub == 0) {
//        rpt_lastVehicleId = vehicleId;
//        rpt_lastVel = vel;
//    }
//    if (vehicleId != rpt_lastVehicleId) {
//        rpt_lastVehicleId = vehicleId;
//        rpt_lastVel = vel;
//    }


    //    if (Math.abs(rpt_lastVel - vel) > rpt_precision) {
    if (rpt_vehNames[vehicleId] != null && rpt_vehNames[vehicleId] != "") {
        vehName = rpt_vehNames[vehicleId];
    }
    else {
        var vehName = vehicleId;
    }
//        for (var i = 0; i < rpt_vehNames.Rows.length; i++) {
//            if (rpt_vehNames.Rows[i].Serial == vehName) {
//                vehName = rpt_vehNames.Rows[i].VehicleName;
//                break;
//            }
//        }

        // Checking if the MPH or KPH is selected
        if (document.getElementById('agrOutputMPH').checked) {
            speed1 = rpt_history.Rows[rpt_historySub].prevVel + "mph";
            speed2 = vel + "mph";
        }
        else {

            //var KPH = Math.round(vel * 1.60934);
            //var lastKPH = Math.round(rpt_history.Rows[rpt_historySub].prevVel * 1.60934);
            speed1 = Math.round(rpt_history.Rows[rpt_historySub].prevVel * 1.60934) + "kph";
            speed2 = Math.round(vel * 1.60934) + "kph";
        }
            
        // checking to see if the address field has a valid address (reverse geocoded on DL)
        if (rpt_history.Rows[rpt_historySub].address != null && rpt_history.Rows[rpt_historySub].address != "" && rpt_history.Rows[rpt_historySub].address.substring(0, 15) != "Unknown Address") {
            rpt_Report.append(
                      "<tr><td>" + vehName + "</td>"
                    + "<td>" + time + "</td><td>"
                    + rpt_history.Rows[rpt_historySub].address.replace("^", " ") + "</td>"
                    + "<td>" + speed1 + "</td>"
                    + "<td>" + speed2 + "</td></tr>");
                    //+ "<td>" + rpt_history.Rows[rpt_historySub].prevVel + "mph " + lastKPH + "kph</td>"
                    //+ "<td>" + vel + "mph " + KPH + "kph</td></tr>");

        }
        else {
            rpt_Report.append(
                      "<tr><td>" + vehName + "</td>"
                    + "<td>" + time + "</td><td>"
                    + "<span id=\"address_" + rpt_historySub + "\"><a href=\"javascript:void(0);\" onclick=\"javascript:showAddress('" + rpt_historySub + "','" + lat + "','" + lon + "', '0');\" title=\"Click Here to view Address\" >Lat:" + lat + "  Lon:" + lon + "</a></span></td>"
                    + "<td>" + speed1 + "</td>"
                    + "<td>" + speed2 + "</td></tr>");
//                    + "<td>" + rpt_history.Rows[rpt_historySub].prevVel + "mph " + lastKPH + "kph</td>"
//                    + "<td>" + vel + "mph " + KPH + "kph</td></tr>");
        }

        rpt_linesPrinted++;
        var waitCt = parseInt(rpt_linesPrinted / 100) + 1;
        if (rpt_linesPrinted % waitCt == 0) {
            divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"5\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        }
//    }


    if (divResults.scrollHeight > 700) {
        divResults.style.top = (700 - divResults.scrollHeight) + "px";
    }
    rpt_historySub++;
    if (rpt_historySub < rpt_history.Rows.length) {
       // rpt_lastVehicleId = vehicleId;
       // rpt_lastVel = vel;
       // rpt_lastTime = time;
        rpt_Timeout = setTimeout("agressiveDrivingReportLoop2();", 0);
    }
    else {
        if (rpt_linesPrinted == 0) {
            divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"5\">&nbsp;&nbsp;No historical information was found for specified interval</td></tr></table>";
        }
        else {
            divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"5\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        }
        divResults.style.top = "51px";
        // redisplay selection criteria
        document.getElementById("divRpt").style.visibility = "visible";
        document.getElementById("printRpt").style.visibility = "visible";

        window.parent.restartLoadMarkers();
    }
}

/////////////////////////////                    Excessive Idling Report
function excessiveIdlingReport_CallBack(response) {
    rpt_history = response.value;

    rpt_GraphArray1 = new Array();
    rpt_GraphArray2 = new Array();
    rpt_chartTitle = null;
    rpt_GraphSub = 0;

    oSESSIONKEY = document.getElementById("SESSIONKEY");
    sessionQueryKey = oSESSIONKEY.getAttribute("value");
    Feed.SVehNm(sessionQueryKey, excessiveIdling_run);
}

function excessiveIdling_run(response) {
    rpt_vehNames = response.value
    rpt_historySub = 0;
    rpt_linesPrinted = 0;

    // Hiding progress bar, since data is about to be displayed.
    var tmpDiv = document.getElementById("progressBar");
    tmpDiv.style.visibility = "hidden";
    tmpDiv.style.display = "none";

    var divResults = document.getElementById("divResults");
    rpt_Report = new StringBuilder();
    rpt_Report.append(
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"reportTable\" style=\"background-color: Transparent;\">" +
            "<tr>" +
              "<td colspan=\"4\" class=\"reportHeader\">" +
                "Begin: " + rpt_fromDate + "<br>" +
                "End: " + rpt_toDate +
              "</td>" +
            "</tr>" +
            "<tr>" +
              "<td  colspan=\"4\" align='center' class=\"reportTitle\"><b>Excessive Idling Report</b></td>" +
            "</tr>" +
            "<tr><td colspan='4'>&nbsp;</td></tr>" +
            "<tr>" +
              "<td class=\"reportColTitle\" width=\"60\">Vehicle</td>" +
              "<td class=\"reportColTitle\" width=\"100\">Time</td>" +
              "<td class=\"reportColTitle\" width=\"420\">Location</td>" +
              "<td class=\"reportColTitle\" width=\"75\">Idle Time</td>" +
             "</tr>");

    if (rpt_history == null || rpt_history.Rows.length == 0) {
        divResults.innerHTML = "<table><tr><td><br>&nbsp;&nbsp;No historical information was found for specified interval</td></tr>";
        window.parent.restartLoadMarkers();
        return null;
    }

    // Hide selection criteria
    document.getElementById("divRpt").style.visibility = "hidden";
    divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
    rpt_Timeout = setTimeout("excessiveIdlingReportLoop();", 0);
}

function excessiveIdlingReportLoop(response) {
    oSessionKey = document.getElementById("SESSIONKEY");
    var sessionID = oSessionKey.getAttribute("value");
    var divResults = document.getElementById("divResults");

    var vehicleId = rpt_history.Rows[rpt_historySub].VehicleId;
    var lat = rpt_history.Rows[rpt_historySub].lat;
    var lon = rpt_history.Rows[rpt_historySub].lon;
    var vel = parseInt(rpt_history.Rows[rpt_historySub].vel);
    var ignitionState = rpt_history.Rows[rpt_historySub].IgnitionState;
    var time = rpt_history.Rows[rpt_historySub].time;
    var secs = 0;
    var locDesc = "";
    if (response != null) {
        locDesc = response.value;
    }

    var vehName = vehicleId;

    if (rpt_historySub == 0) {
        rpt_lastVehicleId = vehicleId;
        rpt_idling = false;
    }

    if (rpt_idling && (vel != 0 || ignitionState != 1 || vehicleId != rpt_lastVehicleId)) {

        rpt_idling = false;
        secs = parseInt((time.getTime() - rpt_lastTime.getTime()) / 1000);
        if (secs >= rpt_precision) {
            if (locDesc == "") {
                rpt_idling = true;
                Feed.MpPntRvGeo(rpt_lastLat, rpt_lastLon, excessiveIdlingReportLoop);
                return null;
            }
            secs = Math.round(secs);
            var mn = parseInt(secs / 60);
            mm = mn;
            var se = secs - (mn * 60);
            var hr = parseInt(mn / 60);
            mn -= (hr * 60);
            var elapseString = "";
            if (hr > 0) {
                elapseString += hr + "h:";
            }
            if (mn > 0 || hr > 0) {
                elapseString += mn + "m:";
            }
            elapseString += se + "s";
            hours = rpt_lastTime.getHours() + "";
            minutes = rpt_lastTime.getMinutes() + "";
            seconds = rpt_lastTime.getSeconds() + "";
            while (hours.length < 2) {
                hours = "&nbsp;&nbsp;" + hours;
            }
            while (minutes.length < 2) {
                minutes = "0" + minutes;
            }
            while (seconds.length < 2) {
                seconds = "0" + seconds;
            }

            for (var i = 0; i < rpt_vehNames.Rows.length; i++) {
                if (rpt_vehNames.Rows[i].Serial == vehName) {
                    vehName = rpt_vehNames.Rows[i].VehicleName;
                    break;
                }
            }

            rpt_Report.append(
                      "<tr><td>" + vehName + "</td>"
                    + "<td>" + hours + ":" + minutes + ":" + seconds + "</td>"
                    + "<td>" + locDesc + "</td>"
                    + "<td>" + elapseString + "</td></tr>");
            locDesc = "";

            rpt_linesPrinted++;
            rpt_GraphArray1[rpt_GraphSub] = vehicleId;
            rpt_GraphArray2[rpt_GraphSub] = secs;
            rpt_GraphSub++;

            var waitCt = parseInt(rpt_linesPrinted / 100) + 1;
            if (rpt_linesPrinted % waitCt == 0) {
                divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
            }
        }
    }
    if (vehicleId != rpt_lastVehicleId) {
        rpt_lastVehicleId = vehicleId;
        rpt_idling = false;
    }
    if (!rpt_idling && vel == 0 && ignitionState == 1) {
        rpt_lastTime = time;
        rpt_lastLat = lat;
        rpt_lastLon = lon;
        rpt_idling = true;
    }
    if (divResults.scrollHeight > 700) {
        divResults.style.top = (700 - divResults.scrollHeight) + "px";
    }
    rpt_historySub++;
    if (rpt_historySub < rpt_history.Rows.length) {
        rpt_Timeout = setTimeout("excessiveIdlingReportLoop();", 0);
    }
    else {
        divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        divResults.style.top = "51px";
        // redisplay selection criteria
        document.getElementById("divRpt").style.visibility = "visible";
        document.getElementById("printRpt").style.visibility = "visible";
        window.parent.restartLoadMarkers();
    }
}

/////////////////////////////                    Switches Report
function switchesReport_CallBack(response) {
    rpt_history = response.value;
    rpt_historySub = 0;
    rpt_linesPrinted = 0;

    // Hiding progress bar, since data is about to be displayed.
    var tmpDiv = document.getElementById("progressBar");
    tmpDiv.style.visibility = "hidden";
    tmpDiv.style.display = "none";

    rpt_Report = new StringBuilder();
    rpt_Report.append(
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"reportTable\" style=\"background-color: Transparent;\">" +
            "<tr>" +
              "<td colspan=\"4\" class=\"reportHeader\">" +
                "Device ID: " + rpt_VehicleId + "<br>" +
                "Begin: " + rpt_fromDate + "<br>" +
                "End: " + rpt_toDate +
              "</td>" +
            "</tr>" +
            "<tr>" +
              "<td colspan=\"4\" align='center' class=\"reportTitle\">Switches Report</td>" +
            "</tr>" +
            "<tr><td colspan='4'>&nbsp;</td></tr>" +
            "<tr>" +
              "<td class=\"reportColTitle\" width=\"200\">Date/Time</td>" +
              "<td class=\"reportColTitle\" width=\"240\">Address</td>" +
              "<td class=\"reportColTitle\" width=\"95\">Speed</td>" +
              "<td class=\"reportColTitle\" width=\"95\">Switches On</td>" +
            "</tr>");

    if (rpt_history == null || rpt_history.Rows.length == 0) {
        var divResults = document.getElementById("divResults");
        divResults.innerHTML = "<table><tr><td><br>&nbsp;&nbsp;No historical information was found for specified interval</td></tr>";
        window.parent.restartLoadMarkers();
        return null;
    }

    // Hide selection criteria
    document.getElementById("divRpt").style.visibility = "hidden";
    var lat = rpt_history.Rows[rpt_historySub].lat;
    var lon = rpt_history.Rows[rpt_historySub].lon;
    Feed.MpPntRvGeo(lat, lon, switchesReportLoop);
}

function switchesReportLoop(response) {
    oSessionKey = document.getElementById("SESSIONKEY");
    var sessionID = oSessionKey.getAttribute("value");
    var divResults = document.getElementById("divResults");

    var lat = rpt_history.Rows[rpt_historySub].lat;
    var lon = rpt_history.Rows[rpt_historySub].lon;
    var vel = parseInt(rpt_history.Rows[rpt_historySub].vel);
    var dKPH = Math.round(vel * 1.60934);
    var time = rpt_history.Rows[rpt_historySub].time;
    var switches = rpt_history.Rows[rpt_historySub].Switches;
    var locDesc = "";

    if (rpt_historySub == 0) {
        locDesc = "Initial vehicle position at <br>";
        rpt_lastSwitches = switches;
    }

    if (rpt_historySub == 0 && response != null) {
        locDesc += response.value + "</td>";
    }
    // checking to see if the address field has a valid address (reverse geocoded on DL)
    else if (rpt_history.Rows[rpt_historySub].address != null && rpt_history.Rows[rpt_historySub].address != "" && rpt_history.Rows[rpt_historySub].address.substring(0, 15) != "Unknown Address") {
        locDesc += rpt_history.Rows[rpt_historySub].address.replace("^", " ") + "</td>";
    }
    else {
        locDesc += "<span id=\"address_" + rpt_historySub + "\"><a href=\"javascript:void(0);\" onclick=\"javascript:showAddress('" + rpt_historySub + "','" + lat + "','" + lon + "', '0');\" title=\"Click Here to view Address\" >Lat:" + lat + "  Lon:" + lon + "</a></span></td>";
    }

    if (switches != rpt_lastSwitches || rpt_historySub == 0) {
        var switchValue = ""
        switch (switches) {
            case 1:
                switchValue = "Sw1";
                break;
            case 2:
                switchValue = "Sw2";
                break;
            case 3:
                switchValue = "Sw1 Sw2";
                break;
            case 4:
                switchValue = "Sw3";
                break;
            case 5:
                switchValue = "Sw1 Sw3";
                break;
            case 6:
                switchValue = "Sw2 Sw3";
                break;
            case 7:
                switchValue = "Sw1 Sw2 Sw3";
                break;
            case 8:
                switchValue = "Sw4";
                break;
            case 9:
                switchValue = "Sw1 Sw4";
                break;
            case 10:
                switchValue = "Sw2 Sw4";
                break;
            case 11:
                switchValue = "Sw1 Sw2 Sw4";
                break;
            case 12:
                switchValue = "Sw3 Sw4";
                break;
            case 13:
                switchValue = "Sw1 Sw3 Sw4";
                break;
            case 14:
                switchValue = "Sw2 Sw3 Sw4";
                break;
            case 15:
                switchValue = "Sw1 Sw2 Sw3 Sw4";
                break;
        }
        rpt_Report.append("<tr><td>" + time + "</td><td>"
                    + locDesc
                    + "<td>" + vel + "mph " + dKPH + "kph</td>");
        rpt_Report.append("<td>" + switchValue + "</td></tr>");
        rpt_linesPrinted++;
        var waitCt = parseInt(rpt_linesPrinted / 100) + 1;
        if (rpt_linesPrinted % waitCt == 0) {
            divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        }
    }
    if (divResults.scrollHeight > 700) {
        divResults.style.top = (700 - divResults.scrollHeight) + "px";
    }
    rpt_historySub++;
    if (rpt_historySub < rpt_history.Rows.length) {
        rpt_lastSwitches = switches;
        rpt_Timeout = setTimeout("switchesReportLoop();", 0);
    }
    else {
        divResults.innerHTML = rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        divResults.style.top = "51px";
        // redisplay selection criteria
        document.getElementById("divRpt").style.visibility = "visible";
        document.getElementById("printRpt").style.visibility = "visible";
        window.parent.restartLoadMarkers();
    }
}


/////////////////////////////                    Stop Start Report
function stopStartReport_CallBack(response) {
    rpt_history = response.value;
    rpt_historySub = 0;
    rpt_linesPrinted = 0;
    rpt_GraphArray1 = new Array();
    rpt_GraphArray2 = new Array();
    rpt_FirstArray = null;
    rpt_chartTitle = null;
    //var WebChartHeading = document.getElementById("WebChartHeading");
    //WebChartHeading.style.visibility = "hidden";

    // Hiding progress bar, since data is about to be displayed.
    var tmpDiv = document.getElementById("progressBar");
    tmpDiv.style.visibility = "hidden";
    tmpDiv.style.display = "none";

    var chartDiv = document.getElementById("WebChartSSR");
    chartDiv.innerHTML = "";
    chartDiv.innerHTML = "<center><p>Loading Report Chart</p></center>";
    chartDiv.innerHTML += "<center><img alt=\"Report Loading\" id=\"Chartloader\" src=\"images/redline2.gif\" width=\"150\" height=\"8\"/></center>";
    var divResults = document.getElementById("divResults");

    // If no records were found matching the criteria display message
    if (rpt_history == null || rpt_history.Rows.length == 0) {
        divResults.style.top = "310px";
        divResults.innerHTML = "<table><tr><td><br>&nbsp;&nbsp;No historical information was found for specified interval</td></tr>";
        chartDiv.innerHTML = "";
        window.parent.restartLoadMarkers();
        return null;
    }

    rpt_IgnitionMovement = document.getElementById("rptIgnition");
    if (rpt_IgnitionMovement.checked) {
        rpt_IgnitionMovement = true;
        rpt_precision = 0;
    }
    else {
        rpt_IgnitionMovement = false;
    }

    rpt_Report = new StringBuilder();
    rpt_reportHeading =
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"reportTable\" style=\"background-color: Transparent;\">" +
            "<tr>" +
              "<td colspan='5' class=\"reportHeader\">" +
                "Device ID: " + rpt_VehicleId + "<br>" +
                "Begin: " + rpt_fromDate + "<br>" +
                "End: " + rpt_toDate +
              "</td>" +
            "</tr>" +
            "<tr><td colspan='5'>&nbsp;</td></tr>" +
            "<tr>" +
              "<td colspan='5' align='center' class='reportTitle'>Stop/Start Report</td>" +
            "</tr>" +
            "<tr><td colspan='5'>&nbsp;</td></tr>" +
            "<tr>" +
              "<td class=\"reportColTitle\" width=\"60\">State</td>" +
              "<td class=\"reportColTitle\" width=\"70\">Elapsed Time</td>" +
              "<td class=\"reportColTitle\" width=\"400\">Location</td>" +
              "<td class=\"reportColTitle\" width=\"85\">Begin Time</td>" +
              "<td class=\"reportColTitle\" width=\"80\">End Time</td>" +
            "</tr>";

    divResults.innerHTML = rpt_reportHeading + "<tr><td colspan=\"5\">&nbsp;</td></tr></table>";
    divResults.style.top = "310px";
    rpt_Timeout = setTimeout("stopStartReportLoop();", 0);

    // Hide selection criteria
    document.getElementById("divRpt").style.visibility = "hidden";
}

function stopStartReportLoop(response) {
    var divResults = document.getElementById("divResults");
    var locDesc = "";
    var stat = "";
    var loc = "";

    if (rpt_historySub < rpt_history.Rows.length) {
        if (response != null) {
            locDesc = response.value;
        }
        // checking to see if the address field has a valid address (reverse geocoded on DL)
        else if (rpt_history.Rows[rpt_historySub].address != null && rpt_history.Rows[rpt_historySub].address != "" && rpt_history.Rows[rpt_historySub].address.substring(0, 15) != "Unknown Address") {
            locDesc = rpt_history.Rows[rpt_historySub].address.replace("^", " ");
        }
        
        oSessionKey = document.getElementById("SESSIONKEY");
        var sessionID = oSessionKey.getAttribute("value");

        var lat = rpt_history.Rows[rpt_historySub].lat;
        var lon = rpt_history.Rows[rpt_historySub].lon;
        var vel = parseInt(rpt_history.Rows[rpt_historySub].vel);
        var time = rpt_history.Rows[rpt_historySub].time;
        var ignition = rpt_history.Rows[rpt_historySub].IgnitionState;
        var secs = 0;

        if (rpt_historySub == 0) {
            if (rpt_IgnitionMovement) {
                if (vel == 0) {
                    rpt_stopped = true;
                }
            }
            else {
                if (ignition == 0) {
                    rpt_stopped = true;
                }
            }
            rpt_lastStartTime = time;
            rpt_lastStopTime = time;
            rpt_lastLat = lat;
            rpt_lastLon = lon;
            rpt_totRunTime = 0;
            rpt_totStopTime = 0;
        }

        if ((!rpt_IgnitionMovement && (vel != 0 && rpt_stopped)) || (rpt_IgnitionMovement && (ignition == 1 && rpt_stopped))) {
            //  restarted 
            //  check to see if we exceeded stop time
            secs = parseInt((time.getTime() - rpt_lastStopTime.getTime()) / 1000);
            if (secs >= rpt_precision) {
                if (locDesc == "") {
                    Feed.MpPntRvGeo(rpt_lastLat, rpt_lastLon, stopStartReportLoop);
                    return null;
                }
                rpt_totStopTime += secs;
                var hr = 0;
                var mn = 0;
                var se = 0;
                var mm = 0;
                // report last running loc and time
                if (rpt_lastStartTime != rpt_lastStopTime) {
                    var rsecs = parseInt((rpt_lastStopTime.getTime() - rpt_lastStartTime.getTime()) / 1000);
                    rpt_totRunTime += rsecs;
                    mn = parseInt(rsecs / 60);
                    mm = mn;
                    se = rsecs - (mn * 60);
                    hr = parseInt(mn / 60);
                    mn -= (hr * 60);
                    var elapseString = "";
                    if (hr > 0) {
                        elapseString += hr + "h:";
                    }
                    if (mn > 0 || hr > 0) {
                        elapseString += mn + "m:";
                    }
                    elapseString += se + "s";
                    if (rpt_IgnitionMovement) {
                        stat = "Ignition On";
                    }
                    else {
                        stat = "Moving";
                    }
                    hours = rpt_lastStartTime.getHours() + "";
                    minutes = rpt_lastStartTime.getMinutes() + "";
                    seconds = rpt_lastStartTime.getSeconds() + "";
                    while (hours.length < 2) {
                        hours = "&nbsp;&nbsp;" + hours;
                    }
                    while (minutes.length < 2) {
                        minutes = "0" + minutes;
                    }
                    while (seconds.length < 2) {
                        seconds = "0" + seconds;
                    }
                    hours2 = rpt_lastStopTime.getHours() + "";
                    minutes2 = rpt_lastStopTime.getMinutes() + "";
                    seconds2 = rpt_lastStopTime.getSeconds() + "";
                    while (hours2.length < 2) {
                        hours2 = "&nbsp;&nbsp;" + hours2;
                    }
                    while (minutes2.length < 2) {
                        minutes2 = "0" + minutes2;
                    }
                    while (seconds2.length < 2) {
                        seconds2 = "0" + seconds2;
                    }
                    rpt_Report.append("<tr><td style='color: Green;'>Running</td>"
                        + "<td>" + elapseString + "</td>"
                        + "<td>" + stat + "</td>"
                        + "<td>" + hours + ":" + minutes + ":" + seconds + "</td>"
                        + "<td>" + hours2 + ":" + minutes2 + ":" + seconds2 + "</td></tr>");
                    rpt_GraphArray2.push(mm);
                    if (rpt_FirstArray == null) {
                        rpt_FirstArray = "green";
                    }
                }
                // report stop loc and time
                mn = parseInt(secs / 60);
                mm = mn;
                se = secs - (mn * 60);
                hr = parseInt(mn / 60);
                mn -= (hr * 60);
                if (rpt_IgnitionMovement) {
                    stat = "Ignition Off";
                }
                else {
                    stat = "Stopped";
                }
                elapseString = "";
                if (hr > 0) {
                    elapseString += hr + "h:";
                }
                if (mn > 0 || hr > 0) {
                    elapseString += mn + "m:";
                }
                elapseString += se + "s";
                hours = rpt_lastStopTime.getHours() + "";
                minutes = rpt_lastStopTime.getMinutes() + "";
                seconds = rpt_lastStopTime.getSeconds() + "";
                while (hours.length < 2) {
                    hours = "&nbsp;&nbsp;" + hours;
                }
                while (minutes.length < 2) {
                    minutes = "0" + minutes;
                }
                while (seconds.length < 2) {
                    seconds = "0" + seconds;
                }
                hours2 = time.getHours() + "";
                minutes2 = time.getMinutes() + "";
                seconds2 = time.getSeconds() + "";
                while (hours2.length < 2) {
                    hours2 = "&nbsp;&nbsp;" + hours2;
                }
                while (minutes2.length < 2) {
                    minutes2 = "0" + minutes2;
                }
                while (seconds2.length < 2) {
                    seconds2 = "0" + seconds2;
                }
                rpt_Report.append("<tr><td style='color: Red;'>" + stat + "</td>"
                        + "<td>" + elapseString + "</td>"
                        + "<td width='400px'>" + locDesc + "</td>"
                        + "<td>" + hours + ":" + minutes + ":" + seconds + "</td>"
                        + "<td>" + hours2 + ":" + minutes2 + ":" + seconds2 + "</td></tr>");
                rpt_GraphArray1.push(mm);
                if (rpt_FirstArray == null) {
                    rpt_FirstArray = "red";
                }
                divResults.innerHTML = rpt_reportHeading + rpt_Report.toString() + "<tr><td colspan=\"6\" class=\"reportHeader\">&nbsp;</td></tr></table>";
                rpt_stopped = false;
                rpt_lastStartTime = time;
            }
            else {
                // set running and revert back to last start running time
                rpt_stopped = false;
            }
        }
        else if ((!rpt_IgnitionMovement && (vel != 0 && !rpt_stopped)) || (rpt_IgnitionMovement && (ignition == 1 && !rpt_stopped))) {
            //  continue with running
        }
        else if ((!rpt_IgnitionMovement && (vel == 0 && !rpt_stopped)) || (rpt_IgnitionMovement && (ignition != 1 && !rpt_stopped))) {
            //  come to a stop
            //  set stop running time
            rpt_lastStopTime = time;
            rpt_stopped = true;
            rpt_lastLat = lat;
            rpt_lastLon = lon;
        }
        if (divResults.scrollHeight > 400) {
            divResults.style.top = 295 - (divResults.scrollHeight - 400) + "px";
        }
        rpt_historySub++;
        rpt_Timeout = setTimeout("stopStartReportLoop();", 0);
    }
    else {
        //  last record logic
        if (response != null) {
            locDesc = response.value;
        }
        // checking to see if the address field has a valid address (reverse geocoded on DL)
        else if (rpt_history.Rows[rpt_historySub-1].address != null && rpt_history.Rows[rpt_historySub-1].address != "" && rpt_history.Rows[rpt_historySub-1].address.substring(0, 15) != "Unknown Address") {
            locDesc = rpt_history.Rows[rpt_historySub-1].address.replace("^", " ");
        }
        if (rpt_stopped) {
            if (locDesc == "") {
                Feed.MpPntRvGeo(rpt_lastLat, rpt_lastLon, stopStartReportLoop);
                return null;
            }
            // print stopped record
            // report stop loc and time
            if (rpt_lastStartTime != rpt_lastStopTime) {
                var rsecs = parseInt((rpt_lastStopTime.getTime() - rpt_lastStartTime.getTime()) / 1000);
                rpt_totRunTime += rsecs;
                var mn = parseInt(rsecs / 60);
                mm = mn;
                var se = rsecs - (mn * 60);
                var hr = parseInt(mn / 60);
                mn -= (hr * 60);
                var elapseString = "";
                if (hr > 0) {
                    elapseString += hr + "h:";
                }
                if (mn > 0 || hr > 0) {
                    elapseString += mn + "m:";
                }
                elapseString += se + "s";
                if (rpt_IgnitionMovement) {
                    stat = "Ignition On";
                }
                else {
                    stat = "Moving";
                }
                hours = rpt_lastStartTime.getHours();
                minutes = rpt_lastStartTime.getMinutes() + "";
                seconds = rpt_lastStartTime.getSeconds() + "";
                while (minutes.length < 2) {
                    minutes = "0" + minutes;
                }
                while (seconds.length < 2) {
                    seconds = "0" + seconds;
                }
                hours2 = rpt_lastStopTime.getHours();
                minutes2 = rpt_lastStopTime.getMinutes() + "";
                seconds2 = rpt_lastStopTime.getSeconds() + "";
                while (minutes2.length < 2) {
                    minutes2 = "0" + minutes2;
                }
                while (seconds2.length < 2) {
                    seconds2 = "0" + seconds2;
                }
                rpt_Report.append("<tr><td style='color: Green;'>Running</td>"
                        + "<td>" + elapseString + "</td>"
                        + "<td>" + stat + "</td>")
                if (hours < 10) {
                    hours = "&nbsp " + hours;
                }
                rpt_Report.append("<td>" + hours + ":" + minutes + ":" + seconds + "</td>");
                if (hours2 < 10) {
                    hours2 = "&nbsp " + hours2;
                }
                rpt_Report.append("<td>" + hours2 + ":" + minutes2 + ":" + seconds2 + "</td></tr>");
                rpt_GraphArray2.push(mm);
                if (rpt_FirstArray == null) {
                    rpt_FirstArray = "green";
                }       
            }
            secs = parseInt((rpt_history.Rows[rpt_history.Rows.length - 1].time.getTime() - rpt_lastStopTime.getTime()) / 1000);
            if (secs > 0) {
                rpt_totStopTime += secs;
                var mn = parseInt(secs / 60);
                var mm = mn;
                var se = secs - (mn * 60);
                var hr = parseInt(mn / 60);
                mn -= (hr * 60);
                var elapseString = "";
                if (hr > 0) {
                    elapseString += hr + "h:";
                }
                if (mn > 0 || hr > 0) {
                    elapseString += mn + "m:";
                }
                elapseString += se + "s";
                if (rpt_IgnitionMovement) {
                    stat = "Ignition Off";
                }
                else {
                    stat = "Stopped";
                }
                hours = rpt_lastStopTime.getHours();
                minutes = rpt_lastStopTime.getMinutes() + "";
                seconds = rpt_lastStopTime.getSeconds() + "";
                while (minutes.length < 2) {
                    minutes = "0" + minutes;
                }
                while (seconds.length < 2) {
                    seconds = "0" + seconds;
                }
                hours2 = rpt_history.Rows[rpt_history.Rows.length - 1].time.getHours();
                minutes2 = rpt_history.Rows[rpt_history.Rows.length - 1].time.getMinutes() + "";
                seconds2 = rpt_history.Rows[rpt_history.Rows.length - 1].time.getSeconds() + "";
                while (minutes2.length < 2) {
                    minutes2 = "0" + minutes2;
                }
                while (seconds2.length < 2) {
                    seconds2 = "0" + seconds2;
                }
                if (hours < 10) {
                    hours = "&nbsp " + hours;
                }
                if (hours2 < 10) {
                    hours2 = "&nbsp " + hours2;
                }
                rpt_Report.append("<tr><td style='color: Red;'>" + stat + "</td>"
                        + "<td>" + elapseString + "</td>"
                        + "<td width='400px'>" + locDesc + "</td>"
                        + "<td>" + hours + ":" + minutes + ":" + seconds + "</td>"
                        + "<td>" + hours2 + ":" + minutes2 + ":" + seconds2 + "</td></tr>");
                rpt_GraphArray1.push(mm);
                if (rpt_FirstArray == null) {
                    rpt_FirstArray = "red";
                }
            }
            else {
                // if last record is Stopped output the last stop location
                if (parseInt(rpt_history.Rows[rpt_historySub - 1].vel) == 0) {
                    rpt_Report.append("<tr><td style='color: Red;'>Stopped</td>"
                            + "<td>0s</td>"
                            + "<td width='400px'>" + locDesc + "</td>"
                            + "<td>" + hours2 + ":" + minutes2 + ":" + seconds2 + "</td>"
                            + "<td>" + hours2 + ":" + minutes2 + ":" + seconds2 + "</td></tr>");
                }
            }
        }
        else {
            // print running record
            var rsecs = parseInt((rpt_history.Rows[rpt_history.Rows.length - 1].time.getTime() - rpt_lastStartTime.getTime()) / 1000);
            rpt_totRunTime += rsecs;
            var mn = parseInt(rsecs / 60);
            var mm = mn;
            var se = rsecs - (mn * 60);
            var hr = parseInt(mn / 60);
            mn -= (hr * 60);
            var elapseString = "";
            if (hr > 0) {
                elapseString += hr + "h:";
            }
            if (mn > 0 || hr > 0) {
                elapseString += mn + "m:";
            }
            elapseString += se + "s";
            rpt_Report.append("<tr><td style='color: Green;'>Running</td>"
                + "<td>" + elapseString + "</td>");
            if (rpt_IgnitionMovement) {
                rpt_Report.append("<td>Ignition On</td>");
            }
            else {
                rpt_Report.append("<td>Moving</td>");
            }
            hours = rpt_lastStartTime.getHours();
            minutes = rpt_lastStartTime.getMinutes() + "";
            seconds = rpt_lastStartTime.getSeconds() + "";
            while (minutes.length < 2) {
                minutes = "0" + minutes;
            }
            while (seconds.length < 2) {
                seconds = "0" + seconds;
            }
            hours2 = rpt_history.Rows[rpt_history.Rows.length - 1].time.getHours();
            minutes2 = rpt_history.Rows[rpt_history.Rows.length - 1].time.getMinutes() + "";
            seconds2 = rpt_history.Rows[rpt_history.Rows.length - 1].time.getSeconds() + "";
            while (minutes2.length < 2) {
                minutes2 = "0" + minutes2;
            }
            while (seconds2.length < 2) {
                seconds2 = "0" + seconds2;
            }
            rpt_Report.append("</td><td>" + hours + ":" + minutes + ":" + seconds + "</td>"
                + "<td>" + hours2 + ":" + minutes2 + ":" + seconds2 + "</td></tr>");
            rpt_GraphArray2.push(mm);
            if (rpt_FirstArray == null) {
                rpt_FirstArray = "green";
            }
            // If final record is stopped print Stopped address. 
            
        }
        var mn = parseInt(rpt_totRunTime / 60);
        var mm = mn;
        var se = rpt_totRunTime - (mn * 60);
        var hr = parseInt(mn / 60);
        mn -= (hr * 60);
        var totRunTime = "";
        if (hr > 0) {
            totRunTime += hr + "h:";
        }
        if (mn > 0 || hr > 0) {
            totRunTime += mn + "m:";
        }
        totRunTime += se + "s";

        mn = parseInt(rpt_totStopTime / 60);
        mm = mn;
        se = rpt_totStopTime - (mn * 60);
        hr = parseInt(mn / 60);
        mn -= (hr * 60);
        var totStopTime = "";
        if (hr > 0) {
            totStopTime += hr + "h:";
        }
        if (mn > 0 || hr > 0) {
            totStopTime += mn + "m:";
        }
        totStopTime += se + "s";

        divResults.innerHTML =
            rpt_reportHeading
            + "<tr><td colspan='5'>&nbsp;</td></tr>"
            + "<tr><td colspan='5'>Total Run Time: " + totRunTime + "</td></tr>"
            + "<tr><td colspan='5'>Total Stop Time: " + totStopTime + "</td>"
            + "</tr><tr><td colspan='5'>&nbsp;</td></tr>"
            + rpt_Report.toString()
            + "<tr><td colspan='5' class=\"reportHeader\">&nbsp;</td></tr></table>";
        divResults.style.top = "304px";
        if (rpt_GraphArray1.length == 0) {
            rpt_GraphArray1.push(null);
        }
        if (rpt_GraphArray2.length == 0) {
            rpt_GraphArray2.push(null);
        }
        if (rpt_FirstArray == "red") {
            Feed.DrwSSGrph(rpt_GraphArray1, rpt_GraphArray2, rpt_FirstArray, rpt_chartTitle);
        }
        else {
            Feed.DrwSSGrph(rpt_GraphArray2, rpt_GraphArray1, rpt_FirstArray, rpt_chartTitle);
        }
        var chartDiv = document.getElementById("WebChartSSR");
        chartDiv.innerHTML = "";
        chartDiv.innerHTML = "<iframe id=\"thechart\" src=\"ChartingSSR.aspx\" frameborder=\"0\" scrolling=\"no\" style=\"height: 295px; width:360px;\" allowtransparency='true'></iframe>";
        //var WebChartHeading = document.getElementById("WebChartHeading");
        //WebChartHeading.style.visibility = "visible";

        // redisplay selection criteria
        document.getElementById("divRpt").style.visibility = "visible";
        document.getElementById("printRpt").style.visibility = "visible";
        window.parent.restartLoadMarkers();
    }
}

/////////////////////////////                    Speeding Report
function speedingReport_CallBack(response) {
    rpt_history = response.value;

    oSESSIONKEY = document.getElementById("SESSIONKEY");
    sessionQueryKey = oSESSIONKEY.getAttribute("value");
    Feed.SVehNm(sessionQueryKey, speedingReport_run);

}

function speedingReport_run(response) {
    rpt_vehNames = response.value
    rpt_historySub = 0;
    rpt_linesPrinted = 0;

    // Hiding progress bar, since data is about to be displayed.
    var tmpDiv = document.getElementById("progressBar");
    tmpDiv.style.visibility = "hidden";
    tmpDiv.style.display = "none";

    var divResults = document.getElementById("divResults");
    rpt_Report = new StringBuilder();
    rpt_reportHeading =
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"reportTable\" style=\"background-color: Transparent;\">" +
            "<tr>" +
              "<td colspan=\"4\" class=\"reportHeader\">" +
                "Begin: " + rpt_fromDate + "<br>" +
                "End: " + rpt_toDate +
              "</td>" +
            "</tr>" +
            "<tr>" +
              "<td colspan='4' align='center' class='reportTitle'>Speeding Report</td>" +
            "</tr>" +
            "<tr><td colspan='4'>&nbsp;</td></tr>" +
            "<tr>" +
              "<td class=\"reportColTitle\" width=\"60\">Vehicle</td>" +
              "<td class=\"reportColTitle\" width=\"240\">Date/Time</td>" +
              "<td class=\"reportColTitle\" width=\"290\">Address</td>" +
              "<td class=\"reportColTitle\" width=\"50\">Speed</td>" +
            "</tr>";

    if (rpt_history == null || rpt_history.Rows.length == 0) {
        divResults.innerHTML = "<table><tr><td><br>&nbsp;&nbsp;No historical information was found that matched your criteria</td></tr>";
        window.parent.restartLoadMarkers();
        return null;
    }

    // Hide selection criteria
    document.getElementById("divRpt").style.visibility = "hidden";
    divResults.innerHTML = rpt_reportHeading + "<tr><td colspan=\"4\" class=\"reportHeader\">&nbsp;</td></tr></table>";
    rpt_Timeout = setTimeout("speedingReportLoop();", 0);

}

function speedingReportLoop(response) {
    var tmpdivResults = document.getElementById("divResults");
    var locDesc = "";
    var stat = "";
    var loc = "";
    if (rpt_historySub > 0) {
        if (rpt_historySub == 0 && response != null) {
            locDesc = response.value;
        }
        // checking to see if the address field has a valid address (reverse geocoded on DL)
        else if (rpt_history.Rows[rpt_historySub].address != null && rpt_history.Rows[rpt_historySub].address != "" && rpt_history.Rows[rpt_historySub].address.substring(0, 15) != "Unknown Address") {
            locDesc += rpt_history.Rows[rpt_historySub].address.replace("^", " ") + "</td>";
        }
        else {
            locDesc = "<span id=\"address_" + rpt_historySub + "\"><a href=\"javascript:void(0);\" onclick=\"javascript:showAddress('" + rpt_historySub + "','" + rpt_history.Rows[rpt_historySub].lat + "','" + rpt_history.Rows[rpt_historySub].lon + "', '0');\" title=\"Click Here to view Address\" >Lat:" + rpt_history.Rows[rpt_historySub].lat + "  Lon:" + rpt_history.Rows[rpt_historySub].lon + "</a></span>";
        }

        var vehName = rpt_VehicleID;
        for (var i = 0; i < rpt_vehNames.Rows.length; i++) {
            if (rpt_vehNames.Rows[i].Serial == vehName) {
                vehName = rpt_vehNames.Rows[i].VehicleName;
                break;
            }
        }
        var KPH = Math.round(rpt_lastVel * 1.60934);

        rpt_Report.append("<tr>"
                         + "<td>" + vehName + "</td>"
                         + "<td>" + rpt_lastTime + "</td>"
                         + "<td>" + locDesc + "</td>"
                         + "<td>" + rpt_lastVel + "<mph " + KPH + "kph</td>"
                         + "</tr>");
        tmpdivResults.innerHTML = rpt_reportHeading + rpt_Report.toString() + "<tr><td colspan=\"4\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        rpt_linesPrinted++;
        if (tmpdivResults.scrollHeight > 700) {
            tmpdivResults.style.top = (700 - tmpdivResults.scrollHeight) + "px";
        }
        rpt_historySub++;
    }


    while (rpt_historySub < rpt_history.Rows.length) {
        oSessionKey = document.getElementById("SESSIONKEY");
        var sessionID = oSessionKey.getAttribute("value");

        var vel = parseInt(rpt_history.Rows[rpt_historySub].vel);
        var time = rpt_history.Rows[rpt_historySub].time;

        if (rpt_history.Rows[rpt_historySub].vel > rpt_precision) {
            rpt_lastTime = rpt_history.Rows[rpt_historySub].time;
            rpt_lastVel = rpt_history.Rows[rpt_historySub].vel;
            rpt_VehicleID = rpt_history.Rows[rpt_historySub].VehicleId;
            rpt_lastLat = rpt_history.Rows[rpt_historySub].lat;
            rpt_lastLon = rpt_history.Rows[rpt_historySub].lon;
            if (rpt_historySub == 0) {
                rpt_historySub++;
                Feed.MpPntRvGeo(rpt_history.Rows[rpt_historySub].lat, rpt_history.Rows[rpt_historySub].lon, speedingReportLoop);
            }
            else {
                rpt_Timeout = setTimeout("speedingReportLoop();", 0);
            }
            return;
        }
        rpt_historySub++;
    }
    tmpdivResults.style.top = "85px";
    // redisplay selection criteria
    document.getElementById("divRpt").style.visibility = "visible";
    document.getElementById("printRpt").style.visibility = "visible";
    window.parent.restartLoadMarkers();
}


//                                     Sent Messages Report
function sentMsgReport_CallBack(response) {


}

//                                     GeoFence Report (Zone Activity)
function geoReport_CallBack(response) {
    rpt_history = response.value;
    rpt_historySub = 0;
    rpt_linesPrinted = 0;

    // Hiding progress bar, since data is about to be displayed.
    var tmpDiv = document.getElementById("progressBar");
    tmpDiv.style.visibility = "hidden";
    tmpDiv.style.display = "none";

    var divResults = document.getElementById("divResults");
    rpt_Report = new StringBuilder();
    rpt_reportHeading = "<table style='width:690px;'>" +
                            "<tr>" +
                                "<td style='width:40px;'>Begin:</td><td>" + rpt_fromDate + "</td>" +
                            "</tr>" +
                            "<tr>" +
                                "<td>End:</td><td>" + rpt_toDate + "</td>" +
                            "</tr>" +
                            "<tr><td colspan='2'>&nbsp;</td></tr>" +
                            "<tr>" +
                                "<td colspan='2' align='center' class='reportTitle'>Zone Activity Report</td>" +
                            "</tr>" +
                            "<tr><td colspan='2'>&nbsp;</td></tr>" +
                        "</table>";
    rpt_reportHeading +=
          "<table id='GeoFenceReportTable' border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"reportTable\" style=\"background-color: Transparent;\">" +
            "<tr>" +
              "<td class='reportColTitle' style='width:130px;'>Device</td>" +
              "<td class='reportColTitle' style='width:020px;'>Type</td>" +
              "<td class='reportColTitle' style='width:150px;'>Zone</td>" +
              "<td class='reportColTitle' style='width:130px;'>Date/Time</td>" +
              "<td class='reportColTitle' style='width:240px;' id='AddressColumn'>Address</td>" +
            "</tr>";

    if (rpt_history == null || rpt_history.Rows.length == 0) {
        divResults.innerHTML = "<table><tr><td><br>&nbsp;&nbsp;No historical information was found that matched your criteria</td></tr>";
        divResults.style.top = "250px";
        window.parent.restartLoadMarkers();
        return null;
    }

    // Hide selection criteria
    document.getElementById("divRpt").style.visibility = "hidden";
    divResults.innerHTML = rpt_reportHeading + "</table>";
    var divResults = document.getElementById("divResults");
    var locDesc = "";


    while (rpt_historySub < rpt_history.Rows.length) {

        // checking to see if the address field has a valid address (reverse geocoded on DL)
        if (rpt_history.Rows[rpt_historySub].address != null && rpt_history.Rows[rpt_historySub].address != "" && rpt_history.Rows[rpt_historySub].address != "Unknown Address") {
            locDesc += rpt_history.Rows[rpt_historySub].address.replace("^", " ");
        }
        else {
            locDesc = "<span id=\"address_" + rpt_historySub + "\"><a href=\"javascript:void(0);\" onclick=\"javascript:showAddress('" + rpt_historySub + "','" + rpt_history.Rows[rpt_historySub].Lat + "','" + rpt_history.Rows[rpt_historySub].Lon + "', '0');\" title=\"Click Here to view Address\" >Lat:" + rpt_history.Rows[rpt_historySub].Lat + "  Lon:" + rpt_history.Rows[rpt_historySub].Lon + "</a></span>";
        }

        rpt_Report.append("<tr>"
                         + "<td>" + rpt_history.Rows[rpt_historySub].DeviceName + "</td>"
                         + "<td>" + rpt_history.Rows[rpt_historySub].Type + "</td>"
                         + "<td>" + rpt_history.Rows[rpt_historySub].Zone + "</td>"
                         + "<td>" + new Date(rpt_history.Rows[rpt_historySub].Time).print("%m/%d %I:%M:%S%p") + "</td>"
                         + "<td>" + locDesc + "</td>"
                         + "</tr>");
        
        rpt_linesPrinted++;
        rpt_historySub++;

    }  // ending while loop

    divResults.innerHTML = rpt_reportHeading + rpt_Report.toString() + "<tr><td colspan='5' class='reportHeader'>&nbsp;</td></tr></table>";
    // position the top of the report output to be below the selection criteria
    divResults.style.top = "250px";
    // redisplay selection criteria
    document.getElementById("divRpt").style.visibility = "visible";
    document.getElementById("printRpt").style.visibility = "visible";
    // restarting the main vehicle update loop
    window.parent.restartLoadMarkers();
    ShowAddressChanged();
}

//                                    Proximity Report
function proximityReport_CallBack(response) {
    rpt_history = response.value;

    oSESSIONKEY = document.getElementById("SESSIONKEY");
    sessionQueryKey = oSESSIONKEY.getAttribute("value");
    Feed.SVehNm(sessionQueryKey, proximityReport_run);

}

function proximityReport_run(response) {
    rpt_vehNames = response.value
    rpt_historySub = 0;
    rpt_linesPrinted = 0;

    // Hiding progress bar, since data is about to be displayed.
    var tmpDiv = document.getElementById("progressBar");
    tmpDiv.style.visibility = "hidden";
    tmpDiv.style.display = "none";

    var divResults = document.getElementById("divResults");
    rpt_Report = new StringBuilder();
    rpt_reportHeading =
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"reportTable\" style=\"background-color: Transparent;\">" +
            "<tr>" +
              "<td colspan=\"4\" class=\"reportHeader\">" +
                "Begin: " + rpt_fromDate + "<br>" +
                "End: " + rpt_toDate +
              "</td>" +
            "</tr>" +
            "<tr>" +
              "<td colspan='4' align='center' class='reportTitle'>Proximity Report</td>" +
            "</tr>" +
            "<tr><td colspan='4'>&nbsp;</td></tr>" +
            "<tr>" +
              "<td class=\"reportColTitle\" width=\"60\">Vehicle</td>" +
              "<td class=\"reportColTitle\" width=\"240\">Date/Time</td>" +
              "<td class=\"reportColTitle\" width=\"290\">Address</td>" +
              "<td class=\"reportColTitle\" width=\"290\">Speed</td>" +
            "</tr>";

    if (rpt_history == null || rpt_history.Rows.length == 0) {
        divResults.innerHTML = "<table><tr><td><br>&nbsp;&nbsp;No historical information was found that matched your criteria</td></tr>";
        divResults.style.top = "250px";
        window.parent.restartLoadMarkers();
        return null;
    }

    // Hide selection criteria
    document.getElementById("divRpt").style.visibility = "hidden";
    divResults.innerHTML = rpt_reportHeading + "<tr><td colspan=\"4\" class=\"reportHeader\">&nbsp;</td></tr></table>";
    rpt_Timeout = setTimeout("proximityReportLoop();", 0);

}

function proximityReportLoop(response) {
    var divResults = document.getElementById("divResults");
    var locDesc = "";
    var stat = "";
    var loc = "";
    if (rpt_historySub > 0) {
        if (response != null) {
            locDesc = response.value;
        }
        else {
            locDesc = "<span id=\"address_" + rpt_historySub + "\"><a href=\"javascript:void(0);\" onclick=\"javascript:showAddress('" + rpt_historySub + "','" + rpt_history.Rows[rpt_historySub].lat + "','" + rpt_history.Rows[rpt_historySub].lon + "', '0');\" title=\"Click Here to view Address\" >Lat:" + rpt_history.Rows[rpt_historySub].lat + "  Lon:" + rpt_history.Rows[rpt_historySub].lon + "</a></span>";
        }

        var vehName = rpt_VehicleID;
        for (var i = 0; i < rpt_vehNames.Rows.length; i++) {
            if (rpt_vehNames.Rows[i].Serial == vehName) {
                vehName = rpt_vehNames.Rows[i].VehicleName;
                break;
            }
        }
        var KPH = Math.round(rpt_lastVel * 1.60934);

        rpt_Report.append("<tr>"
                         + "<td>" + vehName + "</td>"
                         + "<td>" + rpt_lastTime + "</td>"
                         + "<td>" + locDesc + "</td>"
                         + "<td>" + rpt_lastVel + "<mph " + KPH + "kph</td>"
                         + "</tr>");
        divResults.innerHTML = rpt_reportHeading + rpt_Report.toString() + "<tr><td colspan=\"4\" class=\"reportHeader\">&nbsp;</td></tr></table>";
        rpt_linesPrinted++;
        if (divResults.scrollHeight > 700) {
            divResults.style.top = (700 - divResults.scrollHeight) + "px";
        }
        rpt_historySub++;
    }


    while (rpt_historySub < rpt_history.Rows.length) {
        oSessionKey = document.getElementById("SESSIONKEY");
        var sessionID = oSessionKey.getAttribute("value");

        var vel = parseInt(rpt_history.Rows[rpt_historySub].vel);
        var time = rpt_history.Rows[rpt_historySub].time;

        //        if (rpt_history.Rows[rpt_historySub].vel > rpt_precision) {
        rpt_lastTime = rpt_history.Rows[rpt_historySub].time;
        rpt_lastVel = rpt_history.Rows[rpt_historySub].vel;
        rpt_VehicleID = rpt_history.Rows[rpt_historySub].VehicleId;
        rpt_lastLat = rpt_history.Rows[rpt_historySub].lat;
        rpt_lastLon = rpt_history.Rows[rpt_historySub].lon;
        if (rpt_historySub == 0) {
            rpt_historySub++;
            Feed.MpPntRvGeo(rpt_history.Rows[rpt_historySub].lat, rpt_history.Rows[rpt_historySub].lon, speedingReportLoop);
        }
        else {
            rpt_Timeout = setTimeout("proximityReportLoop();", 0);
        }
        return;
        //        }
        rpt_historySub++;
    }

    divResults.style.top = "250px";
    // redisplay selection criteria
    document.getElementById("divRpt").style.visibility = "visible";
    document.getElementById("printRpt").style.visibility = "visible";
    window.parent.restartLoadMarkers();
}

//
//                                                              End of Reports
//
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                                             Offline Reports
//

function openOfflineReports(reportType) {
    if (m_bLoggedIn) {
        reportTypeID = reportType;
        offlineReportType = reportType;
        DAL.TimeZone_SelectAll(getTimeZonesReturn);
    }
    else {
        AlertMessage("You must be logged in to use this feature.");
    }
}

function getTimeZonesReturn(response) {
    if (response.value != null) {
        var ddlTimeZone = document.getElementById("ddlTimeZone");
        ddlTimeZone.options.length = 0;
        for (var x = 0; x < response.value.Rows.length; x++) {
            ddlTimeZone.options[x] = new Option(response.value.Rows[x].DisplayName, response.value.Rows[x].ID);
        }
        ddlTimeZone.selectedIndex = 84;
    }

    Feed.SUsrEml(m_CurrentUser, completeShowOfflineReports);
}

function completeShowOfflineReports(email) {
    fadeout("divReportSelector");
    ddlOLReportsName = document.getElementById("txtOfflineReportName");
    ddldivOLRIdle = document.getElementById("divOLRIdle");
    divOLRVelocityChange = document.getElementById("divOLRVelocityChange");

    var divOLRIdle = document.getElementById("divOLRIdle");

    ddldivOLRVehicles = document.getElementById("divOLRVehicles");
    var currentDate = new Date();
    var month = currentDate.getMonth() + 1;
    var day = currentDate.getDate();
    var year = currentDate.getFullYear();
    document.getElementById("txtStartDate").value = month + "/" + day + "/" + year;
    document.getElementById("txtEndDate").value = month + "/" + day + "/" + year;
    document.getElementById("startHours").value = "00";
    document.getElementById("startMins").value = "00";
    document.getElementById("startSec").value = "00";
    document.getElementById("endHours").value = "23";
    document.getElementById("endMins").value = "59";
    document.getElementById("endSec").value = "59";

    m_divOLROverlay = null;
    m_divOLROverlay = document.getElementById("divOfflineReportsOverlay");
    m_divOLROverlay.style.marginTop = parseInt(0);
    m_divOLROverlay.style.position = "absolute";
    m_divOLROverlay.style.top = "5px";
    m_divOLROverlay.style.left = "-220px";
    OLReMail = document.getElementById("ddlOLReMail");
    if (email != null && email.value != null) {
        OLReMail.value = email.value;
    }
    var divOLRVelocityChange = document.getElementById("divOLRVelocityChange");
    divOLRVelocityChange.style.visibility = "hidden";
    ddldivOLRIdle.style.visibility = "hidden";
    ddldivOLRVehicles.style.visibility = "visible";


    var divSpeed = document.getElementById("divSpeed");
      /*
        1,'Aggressive Driving Report' 
        2,'Device Mileage By State Report'
        3,'Device Mileage Report'
        4,'Device Operating Report'
        5,'Excessive Idling Report'
        6,'Master Report'
        7,'PTO Sensor Report'
        8,'Speed Alert Report'
        9,'Speeding Report'
        10,'Standard Report'
        11,'Start Stop Report'
      */
    switch (reportTypeID) {
        case 2: ddlOLReportsName.innerHTML = "Mileage by State Report"; break;
        case 3: ddlOLReportsName.innerHTML = "Vehicle Mileage Report"; break;
        case 4: ddlOLReportsName.innerHTML = "Vehicle Operating Report"; break;
        case 6: ddlOLReportsName.innerHTML = "Master Listing Report"; break;
        case 7: ddlOLReportsName.innerHTML = "PTO Switches Report"; break;
        case 8: ddlOLReportsName.innerHTML = "Speeding Alert Report"; ddldivOLRVehicles.style.visibility = "hidden"; break;
        case 10: ddlOLReportsName.innerHTML = "Standard Report"; break;
        case 1:
            ddlOLReportsName.innerHTML = "Agressive Driving Report";
            divOLRVelocityChange.innerHTML = "<p class='whiteType10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Velocity Change : "
                                           + "<select name='ddlOLRVelChange' id='ddlOLRVelChange' style='width: 50px; background-color: white; color:#000000; visibility:inherit;' onchange='cleanMap(false);setViewType(false);' onclick='cleanMap(false);setViewType(false);'></select>"
                                           + "in mph in 10 second period"
                                           + "</p>";
            ddlOLRVelChangeList = document.getElementById("ddlOLRVelChange");
            for (var i = 0; i < 8; i++) {
                var amt = (i * 5) + 35;
                ddlOLRVelChangeList.options[i] = new Option(amt, amt);
            }
            divOLRVelocityChange.style.visibility = "visible";
            break;
        case 5:
            ddlOLReportsName.innerHTML = "Excessive Idling Report";
            divOLRIdle.innerHTML = "<p class='whiteType10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Idle Period : "
                                 + "<input type='text' name='idleTime' id='idleTime' value='5' style='width:20px;'/>"
                                 + "<select name='ddlOLRIdlePeriod' id='ddlOLRIdlePeriod' style='width: 75px; background-color: white; color:#000000; visibility:inherit;' onchange='cleanMap(false);setViewType(false);' onclick='cleanMap(false);setViewType(false);'></select>"
                                 + "</p>";
            ddlOLRIdlePeriodList = document.getElementById("ddlOLRIdlePeriod");
            ddlOLRIdlePeriodList.options[0] = new Option("Seconds", "1");
            ddlOLRIdlePeriodList.options[1] = new Option("Minutes", "60");
            ddlOLRIdlePeriodList.options[2] = new Option("Hours", "3600");
            ddlOLRIdlePeriodList.selectedIndex = 1;
            divOLRIdle.style.visibility = "visible";
            break;
        case 9:
            ddlOLReportsName.innerHTML = "Speeding Report";
            divOLRIdle.innerHTML = "<p class='whiteType10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Speed greater than : "
                                 + "<input type='text' name='txtSpeed' id='txtSpeed' value='65' style='width:20px;'/>"
                                 + "</p>";
            ddldivOLRVehicles.style.visibility = "hidden";
            divOLRIdle.style.visibility = "visible";
            break;
        case 11:
            ddlOLReportsName.innerHTML = "Start/Stop Report";
            divOLRVelocityChange.innerHTML = "<p class='whiteType10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='radio' name='rptType' id='rptIgnition' value='Ignition' onclick='ssOrReportTypeClicked();'/> Ignition"
                                 + "<input type='radio' name='rptType' id='rptMovenemt' value='Movement' onclick='ssOrReportTypeClicked()' checked='checked'/>"
                                 + "Movement</td>"
                                 + "</p>"

            divOLRIdle.innerHTML = "<p class='whiteType10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Minimum Stop Time :&nbsp;"
                                 + "<input type='text' name='precisionValue'id='precisionValue' style='width=20px' value='5'/>"
                                 + "&nbsp;"
                                 + "<select name='precisionType' id='precisionType' style='width: 75px; background-color: white; color:#000000; visibility:inherit;' onchange='cleanMap(false);setViewType(false);' onclick='cleanMap(false);setViewType(false);'></select>"
                                 + "</p>";
            precisionList = document.getElementById("precisionType");
            precisionList.options[0] = new Option("Seconds", "1");
            precisionList.options[1] = new Option("Minutes", "60");
            precisionList.options[2] = new Option("Hours", "3600");
            precisionList.selectedIndex = 1;
            divOLRVelocityChange.style.visibility = "visible";
            divOLRIdle.style.visibility = "visible";
            break;
    }

    fadein("divOfflineReportsOverlay");
}

function hideOffilneReportsPop() {
    //MoveControlTray();
    fadeout("divOfflineReportsOverlay");
}

function requestOfflineReport() {
    var secondsOrSpeed = 0;
    /*
    1,'Aggressive Driving Report' 
    2,'Device Mileage By State Report'
    3,'Device Mileage Report'
    4,'Device Operating Report'
    5,'Excessive Idling Report'
    6,'Master Report'
    7,'PTO Sensor Report'
    8,'Speed Alert Report'
    9,'Speeding Report'
    10,'Standard Report'
    11,'Start Stop Report'
    */
    switch (reportTypeID) {
        case 1:  secondsOrSpeed = GetIntFromTextbox("ddlOLRVelChange"); break;  //'Aggressive Driving Report'
        case 5:  secondsOrSpeed = GetIntFromTextbox("idleTime") * GetSelectedValue("ddlOLRIdlePeriod"); break; //'Excessive Idling Report'
        case 6: secondsOrSpeed = 1; break;  //'Master Listing Report' pass 1 to indicate Master Listing Report
        case 9: secondsOrSpeed = GetIntFromTextbox("txtSpeed"); break; //'Speeding Report'
        case 11: secondsOrSpeed = isChecked("rptIgnition") ? 0 : Math.max(1, GetIntFromTextbox("precisionValue") * GetSelectedValue("precisionType")); break; //'Start Stop Report'
    }

    var sessionID = GetValueFromTextbox("SESSIONKEY");
    var eMail = GetValueFromTextbox("ddlOLReMail");
    var startDate = new Date(GetValueFromTextbox("txtStartDate") + " " + GetIntFromTextbox("startHours") + ":" + GetIntFromTextbox("startMins") + ":" + GetIntFromTextbox("startSec"));
    var endDate = new Date(GetValueFromTextbox("txtEndDate") + " " + GetIntFromTextbox("endHours") + ":" + GetIntFromTextbox("endMins") + ":" + GetIntFromTextbox("endSec"));
    var timeZoneID = GetSelectedInt("ddlTimeZone");
    var metric = false;
    var deviceID = GetSelectedInt("ddlOLRVehicles");

    if (startDate >= endDate) {
        AlertMessage("Start date must be before the end date.");
        return false;
    }
    if (isValidEmail(eMail) == false) {
        AlertMessage("It appears that you have entered an invalid e-mail address");
        document.getElementById("ddlOLReMail").focus();
        return false;
    }
    if (secondsOrSpeed < 0) {
        AlertMessage("All speeds and times must be greater than 0");
        return false;
    }
    if (deviceID < 0) { deviceID = 0; }

    DAL.ReportRequest_Insert(sessionID, reportTypeID, eMail, startDate, endDate, timeZoneID, metric, secondsOrSpeed, deviceID, OLSReportCompleted); 
}

function OLSReportCompleted(response) {
    if (response.value == true) {
        ActionCompleted("Your report request has been submitted");
        hideOffilneReportsPop();
    }
    else {
        AlertMessage("Your report request has failed");
    }
}

//                                                              End of Offline Reports
//
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                                                  Define Directions
//

function define_direction(direction, velocity) {
    if (direction == 0 && velocity == 0) { return "Stopped"; }
    if (direction > 348 || direction < 12) { return "North"; };
    if (direction > 11 && direction < 34) { return "NNE"; };
    if (direction > 35 && direction < 57) { return "NE"; };
    if (direction > 56 && direction < 79) { return "ENE"; };
    if (direction > 78 && direction < 102) { return "East"; };
    if (direction > 101 && direction < 124) { return "ESE"; };
    if (direction > 123 && direction < 147) { return "SE"; };
    if (direction > 146 && direction < 169) { return "SSE"; };
    if (direction > 168 && direction < 192) { return "South"; };
    if (direction > 191 && direction < 214) { return "SSW"; };
    if (direction > 213 && direction < 237) { return "SW"; };
    if (direction > 236 && direction < 259) { return "WSW"; };
    if (direction > 258 && direction < 282) { return "West"; };
    if (direction > 281 && direction < 304) { return "WNW"; };
    if (direction > 303 && direction < 327) { return "NW"; };
    if (direction > 328 && direction < 349) { return "NNW"; };
}

function log(message) {
    if (location.hostname == "localhost") {
        if (!log.window_ || log.window_.closed) {
            var win = window.open("", null, "width=400,height=200," +
                                  "scrollbars=yes,resizable=yes,status=no," +
                                  "location=no,menubar=no,toolbar=no");
            if (!win) return;
            var doc = win.document;
            doc.write("<html><head><title>Debug Log</title></head>" +
                      "<body></body></html>");
            doc.close();
            log.window_ = win;
        }
        var logLine = log.window_.document.createElement("div");
        logLine.appendChild(log.window_.document.createTextNode(message));
        log.window_.document.body.appendChild(logLine);
    }
}


function getTextWidth(text) {
    var ea = document.createElement("span");
    ea.setAttribute('font', 'arial');
    ea.setAttribute('fontsize', '14');

    ea.innerHTML = text;
    document.body.appendChild(ea);
    var len = ea.offsetWidth;
    document.body.removeChild(ea);
    return len;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                                              Map Search Functions
//
function MapSearch() {
    clearsearchmarkers();
    var searchFor = document.getElementById("TextSearch").value;
    if (searchFor != null && searchFor != "") {
        FindResultArray = new Array;
        map.Find(searchFor,
            null,   //VELatLong(map.GetCenter()),
            null,
            null,
            null,  //index,
            20,
            true,
            true,
            true,
            true,
            onFindResults);
    }
}

function onFindResults(ShapeLayer, findResults, Place, HasMore, veErrorMessage) {
    if (findResults != null) {
        openSearchResultsWindow();
        FindResultArray = findResults;
        var resultstring = "<font size='1' face='Arial'>";
        for (var i = 0; i < findResults.length; i++) {
            if (ResultInfo[i] != object) {
                var newLatLon = new VELatLong(45, -97);
                ResultInfo[i] = new VEShape(VEShapeType.Pushpin, newLatLon);
                map.AddShape(ResultInfo[i]);
                ResultInfo[i].Hide();
            }
            var lat = FindResultArray[i].LatLong.Latitude;
            var lon = FindResultArray[i].LatLong.Longitude;
            var originalPoint = map.LatLongToPixel(new VELatLong(lat, lon));
            newx = originalPoint.x + 20;
            newy = originalPoint.y + 5;
            pixel = new VEPixel(newx, newy);
            var newInfoLatLon = map.PixelToLatLong(pixel);
            var string = "<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;" + FindResultArray[i].Name + "<br />"
                       + "&nbsp;&nbsp;&nbsp;&nbsp;" + FindResultArray[i].Description + "<br />"
                       + "&nbsp;&nbsp;&nbsp;&nbsp;" + FindResultArray[i].Phone + "<br />";
            var ckwidth = "&nbsp<b>" + FindResultArray[i].Description;
            var wdth = ckwidth.length;
            var divInfoVar = "<div style='color:white; font-family:arial; font-size:12px; background:URL(images/SearchResultPopUp.png) no-repeat top right Transparent; width:319px; height:109px;'>" + string + "</div>";
            ResultInfo[i].SetCustomIcon(divInfoVar);
            ResultInfo[i].SetPoints(newInfoLatLon);
            ResultInfo[i].Hide();
            ResultIds[i] = FindResultArray[i].Shape.GetId();
            FindResultArray[i].Shape.SetCustomIcon("images/redpushpin.gif");
            var aPosition = FindResultArray[i].Description.indexOf(",")
            if (aPosition == 0) {
                resultstring = resultstring
                + "&nbsp;<FONT COLOR='#22b1d8'>" + FindResultArray[i].Name + "</font><br />&nbsp;"
                + FindResultArray[i].Description + "<br />&nbsp;"
                + FindResultArray[i].Phone + "<br /><br/>"
            }
            else {
                var srchdesc = FindResultArray[i].Description.substring(0, aPosition)
                var srchdesc2 = FindResultArray[i].Description.substring(aPosition + 2)
                resultstring = resultstring
                + "&nbsp;<FONT COLOR='#22b1d8'>" + FindResultArray[i].Name + "</font><br />&nbsp;"
                + srchdesc + "<br />&nbsp;"
                + srchdesc2 + "<br />&nbsp;"
                + FindResultArray[i].Phone + "<br /><br/>"
            }

        }
        findresults = null;
        var dsr = document.getElementById("divSR");
        dsr.innerHTML = resultstring;
    }
}


function scrollSearchUp() {
    ssup = true;
    sSearchUp();
}

function scrollSearchUpmup() {
    ssup = false;
}

function sSearchUp() {
    if (ssup == true) {
        var dsr = document.getElementById("divSR");
        var ty = parseInt(dsr.style.top);
        ty = ty - 2 + "px"; dsr.style.top = ty;
        setTimeout("sSearchUp()", (0));
    }
}

function scrollSearchDown() {
    ssdown = true;
    sSearchDown();
}

function scrollSearchDownmup() {
    ssdown = false;
}

function sSearchDown() {
    if (ssdown == true) {
        var dsr = document.getElementById("divSR");
        var ty = parseInt(dsr.style.top);
        if (ty < 0) {
            ty = ty + 2 + "px"; dsr.style.top = ty;
            setTimeout("sSearchDown()", (0));
        }
        else {
            ssdown = false;
        }
    }
}

function scrollAPIUp() {
    saup = true;
    sAPIUp();
}

function scrollAPIUpmup() {
    saup = false;
}

function sAPIUp() {
    if (saup == true) {
        var dsr = document.getElementById("divAPIR");
        var ty = parseInt(dsr.style.top);
        ty = ty - 2 + "px"; dsr.style.top = ty;
        setTimeout("sAPIUp()", (0));
    }
}

function scrollAPIDown() {
    sadown = true;
    sAPIDown();
}

function scrollAPIDownmup() {
    sadown = false;
}

function sAPIDown() {
    if (sadown == true) {
        var dsr = document.getElementById("divAPIR");
        var ty = parseInt(dsr.style.top);
        if (ty < 0) {
            ty = ty + 2 + "px"; dsr.style.top = ty;
            setTimeout("sAPIDown()", (0));
        }
        else {
            sadown = false;
        }
    }
}

function clearAPIScroll() {
    sadown = false;
    saup = false;
}

function followThisVehicle() {
    if (vehicleToFollow == cars.Rows[lastClickedBox].s) {
        //vehicleToFollow = null;
        followThisVehicleOFF();
        hideVehicleActionPane();
        //StreetsideShow(false);
    }
    else {
        with (cars.Rows[lastClickedBox]) {
            setVehicleToFollow(s);
            //vehicleToFollow = s;
            hideVehicleActionPane();
            //StreetsideShow(true, lt, ln, o);
        }
    }
}


function setVehicleToFollow(vehicle) {
    vehicleToFollow = vehicle;
    // checking the center option, since screen is auto centering
    AutoCenterMap(true);
}

function followThisVehicleOFF() {
    //clearTimeout(t_followVehicle);
    vehicleToFollow = null;
    // unchecking the auto center option
    //if (m_bCenterMap == true) {
        AutoCenterMap(false);
    //}
    // Need to uncheck center on the Map Control
    
    
    //StreetsideShow(false);
}

function whichBrs() {
    var agt = navigator.userAgent.toLowerCase();
    if (agt.indexOf("opera") != -1) return 'opera';
    if (agt.indexOf("staroffice") != -1) return 'star office';
    if (agt.indexOf("webtv") != -1) return 'webtv';
    if (agt.indexOf("beonex") != -1) return 'beonex';
    if (agt.indexOf("chimera") != -1) return 'chimera';
    if (agt.indexOf("netpositive") != -1) return 'netpositive';
    if (agt.indexOf("phoenix") != -1) return 'phoenix';
    if (agt.indexOf("firefox") != -1) return 'firefox';
    if (agt.indexOf("safari") != -1) return 'safari';
    if (agt.indexOf("skipstone") != -1) return 'skipstone';
    if (agt.indexOf("msie") != -1) return 'internet explorer';
    if (agt.indexOf("netscape") != -1) return 'netscape';
    if (agt.indexOf("mozilla/5.0") != -1) return 'mozilla';
    if (agt.indexOf('\/') != -1) {
        if (agt.substr(0, agt.indexOf('\/')) != 'mozilla') {
            return navigator.userAgent.substr(0, agt.indexOf('\/'));
        }
        else return 'netscape';
    } else if (agt.indexOf(' ') != -1)
        return navigator.userAgent.substr(0, agt.indexOf(' '));
    else return navigator.userAgent;
}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                                      Dispatch Calls from API
//

function incrementServiceCallViewMode(overrideValue) {
    if (null != overrideValue)
        servicecall_viewmode = overrideValue;

    if (servicecall_viewmode > 3)
        servicecall_viewmode = 0;

    showDispatchCalls(false);
}

function showAPIWindow() {
    if (m_bLoggedIn) {
        showDispatchCalls();
    }
    else {
        AlertMessage("You must be logged in to use this feature.");
    }
}

function hideAPIResultsWindow() {

    // stop timer, since window is being closed.
    clearTimeout(APICallsTimer);

    clearAPImarkers();
    m_divROverlay = document.getElementById("divAPIResults");
    fadeout("divAPIResults");
}

function removeAPIitem(workOrder) {
    //if (prevAPIResultArray != null && prevAPIResultArray.Rows != null && prevAPIResultArray.Rows.length > 0 && APIResultArray != null && APIResultArray.Rows != null && APIResultArray.Rows.length > 0) {
    //   for (var i = 0; i < prevAPIResultArray.Rows.length; i++) {
    //            APIAddressPins[i].Hide();
    //            APIResultInfo[i].Hide();

    //if (prevAPIResultArray[i].workOrder) {
    //}
    try {
        map.DeleteShape(APIAddressPins[workOrder]);
        APIAddressPins[workOrder] = null;
        map.DeleteShape(APIResultInfo[workOrder]);
        APIResultInfo[workOrder] = null;
    } catch (err) {
        //take no action because pushPin does not exist
    }
    // }
    //}
}

function clearAPImarkers() {
    //    if (APIResultArray != null && APIResultArray.Rows != null && APIResultArray.Rows.length > 0) {
    //        for (var i = 0; i < APIResultArray.Rows.length; i++) {
    //            //            APIAddressPins[i].Hide();
    //            //            APIResultInfo[i].Hide();
    //            try {
    //                map.DeleteShape(APIAddressPins[i]);
    //                APIAddressPins[i] = null;
    //                map.DeleteShape(APIResultInfo[i]);
    //                APIResultInfo[i] = null;
    //            } catch (err) {
    //                //take no action because pushPin does not exist
    //            }
    //        }
    //    }

    for (var i in APIAddressPins) {
        try {
            map.DeleteShape(APIAddressPins[i]);
            APIAddressPins[i] = null;
            map.DeleteShape(APIResultInfo[i]);
            APIResultInfo[i] = null;
        }
        catch (err) {
            //take no action because pushPin does not exist
        }
    }
    APIAddressPins = new Array();
    APIResultInfo = new Array();
    APIResultArray = new Array();

}


function openDispatchCallWindow() {

    m_divROverlay = document.getElementById("divAPIResults");
    fadein("divAPIResults");

}

function centerOnAPICall(workOrder) {

    //loop thru APIAddressPins
    //    for (var i = 0; i < APIAddressPins.length; i++) {
    //        if (workOrder == APIAddressPins[i].Title) {
    //            var center = new VELatLong(APIAddressPins[i].Latitude, APIAddressPins[i].Longitude);
    //            map.SetCenter(center);
    //            return;
    //        }
    //    }
    //var i = APIAddressPins.indexOfVEShape(workOrder);
    //if (i != -1) {
    if (APIAddressPins != null && APIAddressPins[workOrder] != null) {
        var center = new VELatLong(APIAddressPins[workOrder].Latitude, APIAddressPins[workOrder].Longitude);
        map.SetCenter(center);
    }
    else {
        var temp = 1;
    }
    //}
    return;

}

function getStatusOptions() {

    // stop timer, since filter window is open.  It is restarted in updateDispatchCalls()
    clearTimeout(APICallsTimer);

    Feed.SStatDispCall(m_CurrentUser, getStatusOptions_callback);

}

function getStatusOptions_callback(result) {

    var tmpArray = null;

    if (result != null) {
        if (APIStatus != null && APIStatus.Rows != null && APIStatus.Rows.length > 0) {
            tmpArray = new Array();
            tmpArray = APIStatus;
        }


        //tmpArray = APIStatus;

        APIStatus = new Array();
        APIStatus = result.value;

        var string = "";

        // This is to maintain state of the status filter checked options.
        // Later this can be replaced with a database table that can save criteria by account, but then all 
        // users signed in for that account will have the same selection criteria.
        for (var i = 0; i < APIStatus.Rows.length; i++) {
            if (tmpArray != null) {
                for (var x = 0; x < tmpArray.Rows.length; x++) {
                    if (APIStatus.Rows[i].status == tmpArray.Rows[x].status) {
                        APIStatus.Rows[i].checked = tmpArray.Rows[x].checked;
                    }
                }
            }

            string += "<label class='whiteType' style='padding-right:3px; display:block;'><input type='checkbox' id='apiBox' name='apiBox' value = '" + i.toString() + "' " + APIStatus.Rows[i].checked + " />" + APIStatus.Rows[i].status + "</label>";
        }

        document.getElementById("APIStatusList").innerHTML = string;
    }
    showAPIStatus();

}

function APIStatusAdd() {

    var APIlist = document.getElementsByName('apiBox');
    for (var i = 0; i < APIlist.length; i++) {
        if (APIlist[i].checked == true) {
            APIStatus.Rows[i].checked = 'checked';
        }
        else {
            APIStatus.Rows[i].checked = '';
        }
    }

    // updating the list with the new filter
    updateDispatchCalls();

}

function showAPIStatus() {
    fadein("divAPIStatus");
}

function hideAPIStatus() {
    fadeout("divAPIStatus");
}

function buildAPIListText(data) {
    var string = "&nbsp;<label style='cursor: pointer;' onclick='centerOnAPICall(\"" + data.workOrder
            + "\");'><FONT COLOR='#22b1d8'>Call #:" + data.workOrder + "</font>"
            + "<P style='float:right;'><font size='1' face='Arial' color='white'>" + data.priority + "</font></P>"
            + "<br />&nbsp;"
            + data.customerName + "<br />&nbsp;"
            + data.street + "<br />&nbsp;"
            + data.city + ", " + data.state + "  " + data.zip + "<br />&nbsp;";
    if (data.contact != null && data.contact != "") {
        string += data.contact.substr(0, 60) + "<br />&nbsp;";
    }
    if (data.contactPhone != null && data.contactPhone != "") {
        string += data.contactPhone + "<br />";
    }
    string += "</label><br/>";

    return string;
}

function buildAPIInfoBoxString(data) {
    var string = "<br /><br />Call #:&nbsp;" + data.workOrder
                       + "&nbsp;&nbsp;<P style='float: right; color:#fff; text-align:center; font: 12px Arial;'>" + data.priority + "  </P>"
                       + "&nbsp;&nbsp;<P style='float: right; color:#fff; text-align:center; font: 12px Arial;'>" + data.status + "-  </P>"
                       + "<br />"
                       + data.description + "<br />"
                       + data.requestedDate + "<br /><br />"
                       + data.customerName + "<br />";

    if (data.caller != null && data.caller != "") {
        string += data.caller;
    }

    if (data.caller != null && data.caller != "" && data.contactPhone != null && data.contactPhone != "") {
        string += " / ";
    }

    if (data.contactPhone != null && data.contactPhone != "") {
        string += data.contactPhone;
    }

    if (data.item != null && data.item != "") {
        string += "<br />" + data.item;
    }

    string += "<br />"

    if (data.street != null && data.street != "") {
        string += "<br />" + data.street;
    }

    if ((data.city != null && data.city != "") || (data.state != null && data.state != "") || (data.zip != null && data.zip != "")) {
        string += "<br />"
        if (data.city != null && data.city != "" && data.state != null && data.state != "") {
            string += data.city + ", " + data.state;
        }
        else if (data.state != null && data.state != "") {
            string += data.state;
        }

        if (data.zip != null && data.zip != "") {
            string += "&nbsp;&nbsp;" + data.zip;
        }
    }

    if (data.comment != null && data.comment != "") {
        string += "<br />" + data.comment;
    }

    string += "<br /><br />";

    if (data.technician != null && data.technician != "") {
        string += "Technician:&nbsp;" + data.technician;
    }

    return string;
}

function buildPushpinText(data) {

    var pin_graphic = 'redpushpin.gif';

    if (0 != servicecall_viewmode)
        pin_graphic = 'pin_body.png'

    var string = "<div style='position:relative; background:url(images/" + pin_graphic + ") no-repeat 0 0; height:30px; width:25px; top:-15px; ";

    // Flag Text Color
    var targetColor = null;

    if (data.newTextColor != null && data.newTextColor != "") {
        // This will be the color specified by API or vehcile text color where technician = vehicleName
        string += "color: #" + data.newTextColor + ";";

        if (servicecall_viewmode == 2)
            targetColor = data.newTextColor;
    }
    else {
        // default color
        string += "color: #fff;";
        if (servicecall_viewmode == 2)
            targetColor = '0066FF';
    }

    var fontSize = null;

    if (0 != servicecall_viewmode)
        fontSize = '8';
        
    if(fontSize == null)
        string += " text-align:center; font: bold 12px Arial;'>";
    else
        string += " text-align:center; font:" + fontSize + "px Arial;'>";

    if (servicecall_viewmode >= 2)
        string += "<div style='position:absolute; border:solid 1px Black; visibility: hidden; ";
    else
        string += "<div style='position:absolute; border:solid 1px Black; ";

    // Flag background color
    if (data.newFlagColor != null && data.newFlagColor != "") {
        // This will be the color specified by API or vehcile color where technician = vehicleName
        string += "background-color: #" + data.newFlagColor + ";";
        if (servicecall_viewmode == 3)
            targetColor = data.newFlagColor;
    }
    else {
        // default color
        string += "background-color: #0066FF;";
        if (servicecall_viewmode == 3)
            targetColor = '0066FF';
    }

    var pin_gradient = "<div style='height:30px; width:25px; top:-15px;'><div style='position: absolute; top:4px; left:4px;width: 9px; height: 9px; background-color: #" + targetColor + "; z-index: 20;'></div><div style='position: absolute; top:0px; left:0px; z-index: 40;'><img src='images/pin_gradient.png'/></div></div>";

    if (0 != servicecall_viewmode)
            string += "top:-18px; left:-8px;'>&nbsp;" + data.workOrder + "&nbsp;</div>" + pin_gradient + "</div>";
    else
        string += "top:-18px; left:-8px;'>&nbsp;" + data.workOrder + "&nbsp;</div></div>";

    return string;
}

function showDispatchCalls(refreshWindow) {

    // stop timer while function is executing.
    clearTimeout(APICallsTimer);

    if(refreshWindow == null)
        Feed.SDispCall(m_CurrentUser, "", null, showDispatchCalls_callback);
    else
        Feed.SDispCall(m_CurrentUser, "", null, showDispatchCalls_callback2);
}

function showDispatchCalls_callback2(result) {

    ProcessDispatchCalls(result, false);
}

function showDispatchCalls_callback(result) {

    ProcessDispatchCalls(result,true);
}

function ProcessDispatchCalls(result,refreshWindow) {

    var workOrder;

    clearAPImarkers();

    if (result.value != null) {
        if(refreshWindow)
            openDispatchCallWindow();
        APIResultArray = result.value;
        var resultstring = "<font size='1' face='Arial'>";
        for (var i = 0; i < APIResultArray.Rows.length; i++) {
            // if invalid lat or lon is entered then do not display item.
            if (APIResultArray.Rows[i].lat != "" && APIResultArray.Rows[i].lon != "" && APIResultArray.Rows[i].lat != null && APIResultArray.Rows[i].lon != null) {
                workOrder = APIResultArray.Rows[i].workOrder;

                if (APIResultInfo[workOrder] != object) {
                    var newLatLon = new VELatLong(45, -97);
                    APIResultInfo[workOrder] = new VEShape(VEShapeType.Pushpin, newLatLon);
                    map.AddShape(APIResultInfo[workOrder]);
                    APIResultInfo[workOrder].Hide();
                }

                var lat = APIResultArray.Rows[i].lat;
                var lon = APIResultArray.Rows[i].lon;
                var originalPoint = map.LatLongToPixel(new VELatLong(lat, lon));
                newx = originalPoint.x;
                newy = originalPoint.y;
                pixel = new VEPixel(newx, newy);
                var newInfoLatLon = map.PixelToLatLong(pixel);

                APIAddressPins[workOrder] = new VEShape(VEShapeType.Pushpin, newInfoLatLon);
                map.AddShape(APIAddressPins[workOrder]);
                APIAddressPins[workOrder].SetTitle(APIResultArray.Rows[i].workOrder);

                var tmpDivText = buildPushpinText(APIResultArray.Rows[i]);

                APIAddressPins[workOrder].SetCustomIcon(tmpDivText);

                // building the popup infobox text display
                var string = buildAPIInfoBoxString(APIResultArray.Rows[i]);

                var divInfoVar = "<div style='color:white; font-family:arial; font-size:12px; background:URL(images/OpenCallPlate.png) no-repeat top right Transparent; width:289px; height:312px; z-index:9999;'><div style='position:absolute; left:13px; top:3px; width:250px;'>" + string + "</div></div>";

                APIResultInfo[workOrder].SetCustomIcon(divInfoVar);
                APIResultInfo[workOrder].SetPoints(newInfoLatLon);
                APIResultInfo[workOrder].Hide();
                APIResultIds[workOrder] = APIAddressPins[workOrder].GetId();

                // building the Open Calls scrolling text
                resultstring = resultstring + buildAPIListText(APIResultArray.Rows[i]);
            } //if (APIResultArray.Rows[i].lat == "" || APIResultArray.Rows[i].lon == "")

        }
        findresults = null;
        var dsr = document.getElementById("divAPIR");
        dsr.innerHTML = resultstring;

        // Turn on timer while the window is open.
        APICallsTimer = setTimeout("updateDispatchCalls()", 10000);
    }
    else {
        // need to add message saying no Call Data Present - Please call (405) 749-1105 for more information
        UserMessage("No Service Call Data Present <br />Contact us for details about integration!");
    }
}

function updateDispatchCalls() {

    // stop timer while function is executing.
    clearTimeout(APICallsTimer);

    hideAPIStatus();
    // building a string to use in the status IN option of the query.
    var tmpString = "";
    var APIlist = document.getElementsByName('apiBox');
    for (var i = 0; i < APIlist.length; i++) {
        if (APIlist[i].checked == true) {
            tmpString += "'" + APIStatus.Rows[i].status + "', ";
        }
    }
    // this is to remove the comma at the end of the string
    tmpString = tmpString.substr(0, tmpString.length - 2);

    Feed.SDispCall(m_CurrentUser, tmpString, APIResultArray, showDispatchCallsUpdate_callback);
}

function showDispatchCallsUpdate_callback(result) {
    var workOrder = "";
    var prevI = 0;
    //var updateWorkorder = true;

    //clearAPImarkers();
    //hideAPIStatus();

    if (result.value != null) {
        //prevAPIResultArray = APIResultArray;
        APIResultArray = result.value;

        var resultstring = "<font size='1' face='Arial'>";
        for (var i = 0; i < APIResultArray.Rows.length; i++) {

            workOrder = "";
            workOrder = APIResultArray.Rows[i].workOrder;

            // removing all workorders that do not exist anymore
            if (APIResultArray.Rows[i].Action == "R") {
                removeAPIitem(APIResultArray.Rows[i].workOrder);
            }
            else {
                // If Update workOrder and object already exists
                if (APIResultArray.Rows[i].Action == "U" && APIAddressPins[workOrder] != null) {
                    
                    var lat = APIResultArray.Rows[i].lat;
                    var lon = APIResultArray.Rows[i].lon;
                    if (APIAddressPins[workOrder].lat != lat || APIAddressPins[workOrder].lon != lon) {
                        var newInfoLatLon = new VELatLong(lat, lon);
                        APIAddressPins[workOrder].SetPoints(newInfoLatLon);
                        APIResultInfo[workOrder].SetPoints(newInfoLatLon);
                    }

                    var tmpDivText = buildPushpinText(APIResultArray.Rows[i]);

                    APIAddressPins[workOrder].SetCustomIcon(tmpDivText);
                    APIAddressPins[workOrder].ShowIcon();

                    // building the popup infobox text display
                    var string = buildAPIInfoBoxString(APIResultArray.Rows[i]);

                    var divInfoVar = "<div style='color:white; font-family:arial; font-size:12px; background:URL(images/OpenCallPlate.png) no-repeat top right Transparent; width:289px; height:312px; z-index:9999;'><div style='position:absolute; left:13px; top:3px; width:250px;'>" + string + "</div></div>";

                    APIResultInfo[workOrder].SetCustomIcon(divInfoVar);
                    if (APIResultInfo[workOrder].GetVisibility == true) {
                        APIResultInfo[workOrder].Hide();
                    }

                } // ending if
                else {
                    // If Add or (Update and no object existed) add new workorder
                    if (APIResultArray.Rows[i].Action != "N") {
                        if (APIResultInfo[workOrder] != object) {
                            var newLatLon = new VELatLong(45, -97);
                            APIResultInfo[workOrder] = new VEShape(VEShapeType.Pushpin, newLatLon);
                            map.AddShape(APIResultInfo[workOrder]);
                            APIResultInfo[workOrder].Hide();
                        }

                        var lat = APIResultArray.Rows[i].lat;
                        var lon = APIResultArray.Rows[i].lon;
                        var originalPoint = map.LatLongToPixel(new VELatLong(lat, lon));
                        newx = originalPoint.x;
                        newy = originalPoint.y;
                        pixel = new VEPixel(newx, newy);
                        var newInfoLatLon = map.PixelToLatLong(pixel);

                        APIAddressPins[workOrder] = new VEShape(VEShapeType.Pushpin, newInfoLatLon);
                        map.AddShape(APIAddressPins[workOrder]);
                        APIAddressPins[workOrder].SetTitle(APIResultArray.Rows[i].workOrder);

                        var tmpDivText = buildPushpinText(APIResultArray.Rows[i]);

                        APIAddressPins[workOrder].SetCustomIcon(tmpDivText);

                        // building the popup infobox text display
                        var string = buildAPIInfoBoxString(APIResultArray.Rows[i]);

                        var divInfoVar = "<div style='color:white; font-family:arial; font-size:12px; background:URL(images/OpenCallPlate.png) no-repeat top right Transparent; width:289px; height:312px; z-index:9999;'><div style='position:absolute; left:13px; top:3px; width:250px;'>" + string + "</div></div>";

                        APIResultInfo[workOrder].SetCustomIcon(divInfoVar);
                        APIResultInfo[workOrder].SetPoints(newInfoLatLon);
                        APIResultInfo[workOrder].Hide();
                        APIResultIds[workOrder] = APIAddressPins[workOrder].GetId();

                    } // ending if
                } // ending else
            } // ending else

            // building the Open Calls scrolling text
            if (APIResultArray.Rows[i].Action != "R") {
                resultstring = resultstring + buildAPIListText(APIResultArray.Rows[i]);
            }
            prevI++;
        } // ending for
        findresults = null;
        var dsr = document.getElementById("divAPIR");
        dsr.innerHTML = resultstring;

        // Turn on timer while the window is open.
        APICallsTimer = setTimeout("updateDispatchCalls()", 5000);
    }
    else {
        clearAPImarkers();
        //UserMessage("No Service Call Data Present. <br />Please check your filter settings.");
        var dsr = document.getElementById("divAPIR");
        dsr.innerHTML = "No Service Call Data Present. <br />Please check your filter settings.";
    }

}



///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                                      Routing
//

function showRoutingRequest() {
    if (m_bLoggedIn) {
        m_divROverlay = null;
        var tStartLoc = document.getElementById("rStartLoc");
        m_divROverlay = document.getElementById("divRoutingPopOverlay");
        m_divROverlay.style.marginTop = parseInt(0);
        m_divROverlay.style.position = "absolute";
        //m_divROverlay.style.visibility = "visible";
        m_divROverlay.style.top = "5px";
        m_divROverlay.style.left = "-220px";
        fadein("divRoutingPopOverlay");
        //MoveControlTray();
        tStartLoc.focus = true;
    }
    else {
        AlertMessage("You must be logged in to use this feature.");
    }
}

function hideRoutingPop() {
    fadeout("divRoutingPopOverlay");
    //MoveControlTray();
}

function MapRouting() {
    hideRouting();

    vloader_src = document.getElementById("vRouting");
    if (vloader_src != null)
        vloader_src.src = cached_loader.src;

    locs = new Array();
    var routeLoc = document.getElementById("rStartLoc");
    if (routeLoc.value == null || routeLoc.value == "") {
        AlertMessage("You must enter a starting location.");
        return;
    }
    locs[0] = routeLoc.value;
    var locSub = 1;
    for (var i = 1; i < 16; i++) {
        routeLoc = document.getElementById("rStop" + i);
        if (routeLoc.value != null && routeLoc.value != "") {
            locs[locSub] = routeLoc.value;
            locSub++;
        }
    }

    routeLoc = document.getElementById("rEndLoc");
    if (routeLoc.value != null && routeLoc.value != "") {
        locs[locSub] = routeLoc.value;
    }
    else {
        locs[locSub] = locs[0];
        routeLoc.value = locs[0];
    }
    if (locs[0] == locs[locSub] && locs[2] == null) {
        AlertMessage("If start and end are the same, at least one 'Stop' is required");
        return;
    }

    if (locs.length < 4) {
        callGetDirections(locs);
        return;
    }
    ckNoOptimize = document.getElementById("ckNoOptimize");
    if (ckNoOptimize.checked == true) {
        callGetDirections(locs);
        return;
    }

    latlonlocs = new Array();
    rSub1 = 0;

    getLLforRoute();
}

function getLLforRoute() {
    if (rSub1 >= locs.length) {
        for (var i = 1; i < locs.length - 2; i++) {
            var distance = 99999;
            for (var j = i + 1; j < locs.length - 1; j++) {
                var tdistance = calcDistance(latlonlocs[i].Latitude, latlonlocs[i].Longitude, latlonlocs[j].Latitude, latlonlocs[j].Longitude)
                if (tdistance < distance) {
                    var temp = latlonlocs[i];
                    latlonlocs[i] = latlonlocs[j];
                    latlonlocs[j] = temp;
                    distance = tdistance;
                }
            }
        }
        callGetDirections(latlonlocs);
        return;
    }
    map.Find(null, locs[rSub1], null, null, null, null, false, false, null, false, addrToLatLonCallback);
}

function addrToLatLonCallback(layer, resultsArray, places, hasMore, veErrorMessage) {
    var place = places[0].LatLong;
    latlonlocs[rSub1] = new VELatLong(place.Latitude, place.Longitude, 0, VEAltitudeMode.Default);
    rSub1++;
    getLLforRoute();
}

function calcDistance(lat1, lon1, lat2, lon2) {
    var R = 6371; // km
    var dLat = degToRad(lat2 - lat1);
    var dLon = degToRad(lon2 - lon1);
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(degToRad(lat1)) * Math.cos(degToRad(lat2)) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    d = d * 0.621371192
    return d;
}

function degToRad(deg) {
    var rad = deg * Math.PI / 180;
    return rad;
}

function callGetDirections(locs) {
    fadein("divCalculatingRoute");
    hideRoutingPop();
    var options = new VERouteOptions;
    // Call this function when map route is determined:
    options.RouteCallback = ShowRouting;

    // MinimizeTime - The route is optimized to minimize time.
    // MinimizeDistance - The route is optimized to minimize distance.
    // Default - No route optimization is done. The route is calculated in the order in which the locations are specified.

    options.RouteOptimize = VERouteOptimize.Default;
    ckTime = document.getElementById("ckTime");
    ckDistance = document.getElementById("ckDistance");
    if (ckTime.checked == true) {
        options.RouteOptimize = VERouteOptimize.MinimizeTime;
    }
    if (ckDistance.checked == true) {
        options.RouteOptimize = VERouteOptimize.MinimizeDistance;
    }

    //	options.DistanceUnit   = VERouteDistanceUnit.Mile; // Default is miles
    options.ShowDisambiguation = false; // Default is true
    options.RouteColor = new VEColor(255, 0, 100, 0.6);  // Default is VEColor(0,169,235,0.7)
    options.RouteWeight = 6;  // Default is 6 pixels
    // this calls the function which returns to ShowRouting(route)
    map.GetDirections(locs, options);
}

function ShowRouting(route) {
    //turns = " </div> ";
    //turns = "";
    turns = "<h3>Turn-by-Turn Directions</h3>";
    turns += "<p class='whiteType10')><b>Distance:</b> " + route.Distance.toFixed(1) + " miles";
    turns += "<br/><b>Time:</b> " + GetRoutingTime(route.Time) + "</p>";

    // Unroll route and populate DIV
    var legs = route.RouteLegs;
    var leg = null;
    var turnNum = 0;  // The turn #
    // Get intermediate legs
    for (var i = 0; i < legs.length; i++) {
        // Get this leg so we don't have to derefernce multiple times
        leg = legs[i];  // Leg is a VERouteLeg object

        var legNum = i + 1;
        turns += "<br/><b>Distance for leg "
		      + legNum + ":</b> "
		      + leg.Distance.toFixed(1)
		      + " miles"
		      + "<br/><b>Time for leg "
		      + legNum
		      + ":</b> "
		      + GetRoutingTime(leg.Time)
		      + "<br/><br/>";

        // Unroll each intermediate leg
        var turn = null;  // The itinerary leg
        var legDistance = null;  // The distance for this leg
        for (var j = 0; j < leg.Itinerary.Items.length; j++) {
            turnNum++;
            turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
            turns += "<b>"
			       + turnNum
			       + "</b>\t"
			       + turn.Text;
            legDistance = turn.Distance;
            // So we don't show 0.0 for the arrival
            if (legDistance > 0) {
                // Round distances to 1/10ths
                turns += " (" + legDistance.toFixed(1) + " miles";

                // Append time if found
                if (turn.Time != null) {
                    turns += "; " + GetRoutingTime(turn.Time);
                }
                turns += ")<br/><br/>";
            }
        }
        turns += "<br/></style>";
    }
    fadeout("divCalculatingRoute");
    m_divROverlay = document.getElementById("TurnByTurnContent");
    m_divROverlay.innerHTML += turns;
    fadein("TurnByTurn");
}
function hideTurnByTurn() {
    fadeout("TurnByTurn");
}


// time is an integer representing seconds
// returns a formatted string
function GetRoutingTime(time) {
    if (time == null) {
        return ("");
    }
    if (time > 60) {
        var seconds = time % 60;
        var minutes = time - seconds;
        minutes = minutes / 60;    // minutes == 1
        if (minutes > 60) {
            var minLeft = minutes % 60;
            var hours = minutes - minLeft;
            hours = hours / 60;

            return (hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
        }
        else {
            return (minutes + " minutes, " + seconds + " seconds");
        }
    }
    else {
        return (time + " seconds");
    }
}

function hideRouting() {
    map.DeleteRoute();
}

function routingNoOptClick() {
    var ckNoOpt = document.getElementById("ckNoOptimize");
    if (ckNoOpt.checked == true) {
        var ckDistance = document.getElementById("ckDistance");
        ckDistance.checked = false;
        var ckTime = document.getElementById("ckTime");
        ckTime.checked = false;
    }
}

function routingTimeClick() {
    var ckTime = document.getElementById("ckTime");
    if (ckTime.checked == true) {
        var ckDistance = document.getElementById("ckDistance");
        ckDistance.checked = false;
        var ckNoOpt = document.getElementById("ckNoOptimize");
        ckNoOpt.checked = false;
    }
}

function routingDistanceClick() {
    var ckDistance = document.getElementById("ckDistance");
    if (ckDistance.checked == true) {
        var ckTime = document.getElementById("ckTime");
        ckTime.checked = false;
        var ckNoOpt = document.getElementById("ckNoOptimize");
        ckNoOpt.checked = false;
    }
}
//                                                 End of Routing
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                                              MOUSE FUNCTIONS
//
function mapMouseClick(e) {
    if (e.elementID != null) {
        if (m_bViewHistory) {
            historyInfoBox.Hide();
            return;
        }
        for (var i = 0; i < PinIds.length; i++) {
            if (e.elementID.substring(0, PinIds[i].length) == PinIds[i]) {
                clickedOnSerial = cars.Rows[i].s;
                infoBoxes[i].hide;
                lastClickedBox = i;
                openVehicleActionPane(i);
                break;
            }
        }
    }
}

function mapMouseDown(e) {
    clearWeatherLoopInterval();
    if (!ControlPanelLockout) {
        if (e.elementID != null) {
            dragShape = map.GetShapeByID(e.elementID);

            if (null == dragShape) return true;

            dragShapeTitle = dragShape.GetTitle();
            if (dragShapeTitle == NewAddressMarker || dragShapeTitle == DestinationMarker) {
                var pixel = map.LatLongToPixel(new VELatLong(dragShape.Latitude, dragShape.Longitude));
                xoffset = e.mapX - pixel.x;
                yoffset = e.mapY - pixel.y;
            }
            else if (dragShapeTitle == "AdvRoutePin") {
                HighlightPinInList(dragShape.GetID());
                return false;
            }
            else if (m_AddressList != null) {
                if (m_AddressList.Rows != null) {
                    for (var i = 0; i < m_AddressList.Rows.length; i++) {
                        if (m_AddressList.Rows[i].name == dragShapeTitle) {
                            var pixel = map.LatLongToPixel(new VELatLong(dragShape.Latitude, dragShape.Longitude));
                            xoffset = e.mapX - pixel.x;
                            yoffset = e.mapY - pixel.y;
                            break;
                        }
                    }
                }
            }
            else {
                if (cars != null) {
                    if (cars.Rows != null) {
                        for (var i = 0; i < cars.Rows.length; i++) {
                            if (dragShapeTitle == cars.Rows[i].s) {
                                dragShape = null;
                                break;
                            }
                        }
                    }
                }
            }
            return true; // prevent the default action
        }
    }
}

function mapMouseMove(e) {
    if (dragShape != null) {
        var x = e.mapX;
        var y = e.mapY;
        pixel = new VEPixel(x, y);
        if (dragShapeTitle == "fenceUL") {
            var LL = map.PixelToLatLong(pixel);
            pixel = new VEPixel(e.mapX, e.mapY + 15);
            LL = map.PixelToLatLong(pixel);
            m_fenceLatUL = LL.Latitude;
            m_fenceLonUL = LL.Longitude;
            drawFence();
        }
        else if (dragShapeTitle == "fenceLR") {
            var LL = map.PixelToLatLong(pixel);
            pixel = new VEPixel(e.mapX, e.mapY + 15);
            LL = map.PixelToLatLong(pixel);
            m_fenceLatLR = LL.Latitude;
            m_fenceLonLR = LL.Longitude;
            drawFence();
        }
        else if (dragShapeTitle == NewAddressMarker) {
            pixel = new VEPixel(x - xoffset, y - yoffset);
            var LL = map.PixelToLatLong(pixel);
            dragShape.SetPoints(LL);
            pixel = new VEPixel(x, y);
            var LL = map.PixelToLatLong(pixel);
            address_lat = document.getElementById("addressLAT");
            address_lon = document.getElementById("addressLON");
            address_lat.value = LL.Latitude;
            address_lon.value = LL.Longitude;
        }
        else if (dragShapeTitle == DestinationMarker) {
            pixel = new VEPixel(x - xoffset, y - yoffset);
            var LL = map.PixelToLatLong(pixel);
            dragShape.SetPoints(LL);
            pixel = new VEPixel(x, y);
            var LL = map.PixelToLatLong(pixel);
        }
        else if (m_AddressList != null) {
            for (var i = 0; i < m_AddressList.Rows.length; i++) {
                if (m_AddressList.Rows[i].name == dragShapeTitle) {
                    for (var j = 0; j < MarkerNames.Rows.length; j++) {
                        if (MarkerNames.Rows[j].image == m_AddressList.Rows[i].image) {
                            pixel = new VEPixel(x - MarkerNames.Rows[j].X_center, y - MarkerNames.Rows[j].Y_center);
                            var LL = map.PixelToLatLong(pixel);
                            dragShape.SetPoints(LL);
                            pixel = new VEPixel(x, y);
                            var LL = map.PixelToLatLong(pixel);
                            address_lat = document.getElementById("addressLAT");
                            address_lon = document.getElementById("addressLON");
                            address_lat.value = LL.Latitude;
                            address_lon.value = LL.Longitude;
                            break;
                        }
                    }
                }
            }
        }
        else if (dragShapeTitle != "") {
            var LL = map.PixelToLatLong(pixel);
            dragShape.SetPoints(LL);
        }
    }




    //Get the Latitude Longitude pair of the mouse pointer.
    //    var latLong = map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
    //    //If latLong is null error exists so exit sub
    //    if (latLong != null) {
    //        //If Latitude or Longitude is null, then map is in a view not yeilding a latLong. 
    //        //Curently Bird's Eye is the only view not supported. This is due to User Agreement with Microsoft.
    //        if (latLong.Latitude == null || latLong.Longitude == null) {
    //            document.getElementById("MouseLat").innerHTML = "Not";
    //            document.getElementById("MouseLng").innerHTML = "available";
    //        } else {
    //            document.getElementById("MouseLat").innerHTML = "&nbsp;" + NumberAlterPrecision(latLong.Latitude, 5, true);
    //            document.getElementById("MouseLng").innerHTML = NumberAlterPrecision(latLong.Longitude, 5, true);
    //        }
    //    }
    //    IE7, IE8, Firefox and Chrome no longer allow scripts to update status bar text
    //    Looking for work around - Rebekah
    //    window.status = latLong.Latitude + ", " + latLong.Longitude;
}

function mapMouseOver(e) {
    if (isAdvRouteStarted) { return true; }
    if (e.elementID != null) {
        var theShape = map.GetShapeByID(e.elementID);
        if (theShape != null) {
            if (theShape.isAddressMarker) {
                ShowAddressDescription(true, theShape.GetTitle(), theShape.GetDescription(), theShape.GetPoints());
                return true;
            }
        }
        if (infoBoxes.size() != 0) {
            for (var i = 0; i < PinIds.length; i++) {
                if (e.elementID.substring(0, PinIds[i].length) == PinIds[i]) {
                    
                    infoBoxes[i].Show();
                }
                else {
                    infoBoxes[i].Hide();
                }
            }
        } else {
            if (theShape.GetID() == historyCarPin.GetID()) {
                historyInfoBox.Show();
            }
        }
        for (var i = 0; i < FindResultArray.length; i++) {
            if (e.elementID.substring(0, ResultIds[i].length) == ResultIds[i]) {
                ResultInfo[i].Show();
            }
            else {
                ResultInfo[i].Hide();
            }
        }
        // if service calls (dispatch calls) are being displayed
        if (APIResultArray != null && APIResultArray.Rows != null) {
            //                for (var i = 0; i < APIResultArray.Rows.length; i++) {
            //                    if (e.elementID.substring(0, APIResultIds[i].length) == APIResultIds[i]) {
            //                        APIResultInfo[i].Show();
            //                    }
            //                    else {
            //                        APIResultInfo[i].Hide();
            //                    }
            //                }
            if (theShape != null && APIResultInfo[theShape.Title] != null) {
                APIResultInfo[theShape.Title].Show();
            }


        }
        
        if (theShape != null && m_AddressList != null && m_AddressList.Rows != null) {
            var theShapeTitle = theShape.GetTitle();
            var pixelPoint = map.LatLongToPixel(theShape.GetPoints()[0]);
            
            if(theShape.GetTitle() != 'fenceUL' && theShape.GetTitle() != 'fenceLR')
            show_address_info(theShape.GetTitle(), theShape.GetDescription(), pixelPoint.x, pixelPoint.y);
            /*
            for (var i = 0; i < m_AddressList.Rows.length; i++) {
                if (theShapeTitle == m_AddressList.Rows[i].name) {
                    addrInfoBox[i].Hide();
                    var originalPoint = map.LatLongToPixel(new VELatLong(m_AddressList.Rows[i].lat * 1, m_AddressList.Rows[i].lon * 1));
                    newx = originalPoint.x + 50;
                    newy = originalPoint.y - 5;
                    pixel = new VEPixel(newx, newy);
                    var newLatLon = map.PixelToLatLong(pixel);
                    addrInfoBox[i].SetPoints(newLatLon);
                    addrInfoBox[i].Show();
                    addrInfoBoxTimer = setTimeout("hideAddressMarkerInfo()", 5000);
                }
                else {
                    addrInfoBox[i].Hide();
                }
            }
            */
        }
        

    }
    return true;
}

function mapMouseOut(e) {
    if (e.elementID != null) {
        var theShape = map.GetShapeByID(e.elementID);
        if (theShape != null) {
            if (theShape.isAddressMarker) {
                ShowAddressDescription(false);
                return true;
            }
            // if mouse off of API service call (dispatch calls) then hide result window
            if (APIResultArray != null && APIResultArray.Rows != null && APIResultInfo[theShape.Title] != null) {
                // only need to hide if it is being displayed
                if (APIResultInfo[theShape.Title].GetVisibility() == true) {
                    APIResultInfo[theShape.Title].Hide();
                }
            }
            if (historyCarPin != null) {
                if (theShape.GetID() == historyCarPin.GetID()) {
                    historyInfoBox.Show();
                }
            }
        }
    }
    return true;
}

function mapMouseUp(e) {
    initWeatherLoopInterval();
    if (dragShape != null) {
        if (dragShapeTitle != "fenceUL" && dragShapeTitle != "fenceLR") {
            var name = dragShapeTitle;
            var lat = dragShape.Latitude + "";
            var lon = dragShape.Longitude + "";
            if (dragShapeTitle != NewAddressMarker) {
                Feed.UAddr(m_CurrentUser, name, lat, lon, postAddressModification);
            }
        }
        if (dragShapeTitle == DestinationMarker) {
            var lat = dragShape.Latitude + "";
            var lon = dragShape.Longitude + "";
            var originalPoint = map.LatLongToPixel(new VELatLong(lat, lon));
            var newLatLon = map.PixelToLatLong(new VEPixel(originalPoint.x + 25, originalPoint.y + 25));
            lat = newLatLon.Latitude;
            lon = newLatLon.Longitude;
            Feed.MpPntRvGeo(lat, lon, DTDlookupLatLonCallback);
            rLat = lat;
            rLon = lon;
        }
        if (dragShapeTitle == "AdvRoutePin") {
            AdvRoutePointDragEnd(dragShape);
        }
    }
    dragShape = null;
    dragShapetiele = null;

    if (e.rightMouseButton) {
        if (isAdvRouteStarted) {
            AdvRouteAddPoint(e.mapX, e.mapY);
        }
    }
}
//
//                                                  END OF MOUSE FUNCTIONS
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//                                                 Address Marker Functions

function getAddressMarkersCallback(result) {

    MarkerNames = new Array();
    if (result != null) {
        MarkerNames = result.value;
    }
    updateAddressMarkers();

}
function addressSelected() {
    if (!m_demoUser || demo2_user) {
        addressListSelection = document.getElementById("ddlAddressList");
        if (addressListSelection != null) {
            if (addressListSelection.options.selectedIndex >= 0) {
                addressListValue = addressListSelection.options[addressListSelection.options.selectedIndex].value;
                Feed.SAcctAdr(addressListValue, addressSelectedCallback);
            }
        }
        else
            AlertMessage("No address list could be found.");
    }
}

function addressSelectedCallback(retAddress) {
    if (retAddress != null) {
        if (retAddress.value != null) {
            dt = retAddress.value;
            if (dt != null && typeof (dt) == "object") {
                if (dt.Rows.length > 0) {
                    aname = document.getElementById("addressName");
                    lat = document.getElementById("addressLAT");
                    lon = document.getElementById("addressLON");
                    address_text = document.getElementById("txtAddressFind");

                    AddrMarkerImage = document.getElementById("AddrMarkerImage");
                    AddrMarkerImage.src = "Images/AddressMarkers/" + dt.Rows[0].image;

                    aname.value = dt.Rows[0].name;
                    lat.value = dt.Rows[0].lat;
                    lon.value = dt.Rows[0].lon;
                    address_text.value = dt.Rows[0].address;
                    var center = new VELatLong(dt.Rows[0].lat, dt.Rows[0].lon);
                    map.SetCenter(center);
                    viewAddressDetail(1);
                }
            }
        }
    }
}

function removeAddressMarkers() {
    if (NewAddressMarkerPresent) {
        NewAddressPin.Hide();
        map.DeleteShape(NewAddressPin);
        NewAddressMarkerPresent = false;
    }
    /*
    for (i = 0; i < MapAddresspins.length; i++) {
        if (MapAddresspins[i] != null) {
            MapAddresspins[i].Hide();
            addrInfoBox[i].Hide();
        }
    }
    */
    //Gonse: Need to clear the shape layer as well
    MapAddresspins = new Array();
    addrInfoBox = new Array();
    address_marker_layer.Hide();
    address_marker_layer.DeleteAllShapes();
    map.DeleteShapeLayer(address_marker_layer);
    address_marker_layer = new VEShapeLayer();
    address_marker_layer.SetClusteringConfiguration(VEClusteringType.Grid);
}

function hideAddressMarkerInfo() {
    clearTimeout(addrInfoBoxTimer);
    for (i = 0; i < addrInfoBox.length; i++) {
        addrInfoBox[i].Hide();
    }
}

function updateAddressMarkers() {
    //Feed.SAddr(m_CurrentUser, updateAddressMarkersCallback);
    if (address_layer_update_signal == false) {
        queue_address_dt = null;
        loadAddressData();
    }
}

var lastABTimeoutEvent = null;

function show_address_info(title, description, x, y) {
    if (title == null || description == null || title == '' || description == '')
        return;
    if (lastABTimeoutEvent != null) {
        clearTimeout(lastABTimeoutEvent);
        lastABTimeoutEvent = null;
    }

    document.getElementById('address_info_box').style.visibility = "visible";
    document.getElementById('address_info_box').style.left = (x + 60) + 'px';
    document.getElementById('address_info_box').style.top = (y - 20) + 'px';

    document.getElementById('address_info_box_title').innerHTML = title;
    document.getElementById('address_info_box_desc').innerHTML = description;

    lastABTimeoutEvent = setTimeout("close_address_info()", 60000);
}

function close_address_info() {
    document.getElementById('address_info_box').style.visibility = "hidden";
}

/******************************************************************************************************************************************************/
function loadAddressData() {

    address_layer_update_signal = true;

    oSessionKey = document.getElementById("SESSIONKEY");
    
    if (oSessionKey != null) {
        var sessionID = oSessionKey.getAttribute("value");
        DAL.GetAddressGroups(sessionID, addresses_group_select_callback);
    }
    
    
}

function addresses_group_select_callback(result) {
    if (null != result.value) {
        var dtResults = result.value;

        targetDDL = document.getElementById("ddlAddressGroupList");

        targetDDL.options.length = 0;

        for (var i = 0; i < dtResults.Rows.length; i++) {
            targetDDL.options[targetDDL.options.length] = new Option(dtResults.Rows[i].name,dtResults.Rows[i].id);
        }

        targetDDL.options.selectedIndex = 0;

        if (targetDDL.options.selectedIndex >= 0)
            load_address_group(targetDDL.options[targetDDL.options.selectedIndex].value);
        else if (targetDDL.options.length >= 1) {
            targetDDL.options.selectedIndex = 1;
            load_address_group(targetDDL.options[targetDDL.options.selectedIndex].value);
        }
    }
}

function load_address_group(addressGroupId){
        oSessionKey = document.getElementById("SESSIONKEY");
        if (oSessionKey != null) {
            var sessionID = oSessionKey.getAttribute("value");
            
            DAL.GetAddressPage(sessionID, lastMaximumId, addressGroupId, CBloadAddressData);
        }
}


function addressGroupSelected() {
    targetDDL = document.getElementById("ddlAddressGroupList");
    queue_address_dt = null;

    var new_address_group_name = document.getElementById("address_group_name");
    new_address_group_name.value = targetDDL.options[targetDDL.options.selectedIndex].text;
    load_address_group(targetDDL.options[targetDDL.options.selectedIndex].value);
}


var last_index_counted = 0;

function CBloadAddressData(result) {
    targetDDL = document.getElementById("ddlAddressGroupList");
    var target_address_group_id = targetDDL.options[targetDDL.options.selectedIndex].value;

    if (null != result.value) {
        if (result.value.Rows.length > 0) {

            if (queue_address_dt == null) {
                queue_address_dt = result.value;
                var ddlAddressList = document.getElementById("ddlAddressList");
                ddlAddressList.options.length = 0;
            }
            else {
                for (var cnt = 0; cnt < result.value.Rows.length; cnt++) {
                    queue_address_dt.addRow(result.value.Rows[cnt]);
                }
            }

            lastMaximumId = result.value.Rows[result.value.Rows.length - 1].id;

            for (var i = 0; i < result.value.Rows.length; i++) {
                var current_row = result.value.Rows[i];

                var new_shape = new VEShape(VEShapeType.Pushpin, new VELatLong(current_row.lat, current_row.lon));

                new_shape.SetTitle(current_row.name);
                new_shape.SetDescription(current_row.address);

                var targetImage = "Standard.png";

                if (current_row.image != null && current_row.image != "")
                    targetImage = current_row.image;

                targetImage = "images/AddressMarkers/" + targetImage;

                new_shape.SetCustomIcon(targetImage);

                full_address_marker_layer.AddShape(new_shape);
            }

            setTimeout('load_address_group(' + target_address_group_id + ');', 500);
            return;
        }
    }
    else {
        alert('null value');
    }
    lastMaximumId = -1;
    address_layer_update_signal = false;

    removeAddressMarkers();
    last_index_counted = 0;
    updateAddressMarkersCallback(queue_address_dt);
}

/******************************************************************************************************************************************************/

function updateAddressMarkersCallback(data) {
    removeAddressMarkers();

    if(data != null){
        
            m_AddressList = data;

            var ddlAddressList = document.getElementById("ddlAddressList");
            ddlAddressList.options.length = 0;
            for (i = 0; i < m_AddressList.Rows.length; i++) {

                if (null == m_AddressList.Rows[i])
                    continue;

                var image = "Standard.png";
                var x_offset = -15;
                var y_offset = -15;
                ddlAddressList.options[ddlAddressList.options.length] = new Option(m_AddressList.Rows[i].name, m_AddressList.Rows[i].id);

                if (m_AddressList.Rows[i].image != null && m_AddressList.Rows[i].image != "") {
                    image = m_AddressList.Rows[i].image.toString();
                }

                if (MarkerNames != null & MarkerNames.Rows != null) {
                    for (var j = 0; j < MarkerNames.Rows.length; j++) {
                        if (MarkerNames.Rows[j].image == image) {
                            x_offset = MarkerNames.Rows[j].X_center;
                            y_offset = MarkerNames.Rows[j].Y_center;
                            break;
                        }
                    }
                }
                var imgloc = "images/AddressMarkers/" + image;

                var originalPoint = map.LatLongToPixel(new VELatLong(m_AddressList.Rows[i].lat, m_AddressList.Rows[i].lon));
                newx = originalPoint.x + x_offset;
                newy = originalPoint.y + y_offset;
                pixel = new VEPixel(newx, newy);
                var newLatLon = map.PixelToLatLong(pixel);

                MapAddresspins[i] = new VEShape(VEShapeType.Pushpin, new VELatLong(m_AddressList.Rows[i].lat, m_AddressList.Rows[i].lon));

                /*************************************************************************************************************/

                /*Gonse: Replacing w/ grouped icon loading*/
                address_marker_layer.AddShape(MapAddresspins[i]);

                MapAddresspins[i].SetTitle(m_AddressList.Rows[i].name);
                MapAddresspins[i].SetDescription(m_AddressList.Rows[i].address);
                MapAddresspins[i].SetCustomIcon(imgloc);
                MapAddresspins[i].ShowIcon();

                newx = originalPoint.x + 50;
                newy = originalPoint.y - 5;
                pixel = new VEPixel(newx, newy);
                var newInfoLatLon = map.PixelToLatLong(pixel);

                /*Gonse: Replacing w/ grouped icon loading*/
                addrInfoBox[i] = new VEShape(VEShapeType.Pushpin, newInfoLatLon);
                addrInfoBox[i].Hide();
                address_marker_layer.AddShape(addrInfoBox[i]);

                /*************************************************************************************************************/

                var string = "<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;" + m_AddressList.Rows[i].name + "<br />"
                       + "&nbsp;&nbsp;&nbsp;&nbsp;" + m_AddressList.Rows[i].address + "<br />";
                //       + "&nbsp;&nbsp;&nbsp;&nbsp;" + FindResultArray[i].Phone + "<br />";
                //var ckwidth = "&nbsp<b>" + FindResultArray[i].Description;
                //var wdth = ckwidth.length;
                //var string = "<div style='color:white; font-family:arial; font-size:12px; background:URL(images/AddressMarkerPopUp.png) no-repeat top right Transparent; width:319px; height:109px;'>" + stringA + "</div>";


                //var string = "<img src='images/AddressMarkerPopup.png' /><br/>"
                //           + "&nbsp;" + m_AddressList.Rows[i].name + "<br />"
                //           + "&nbsp;" + m_AddressList.Rows[i].address + "<br />"
                ////////////////////////////////////////////////////////////////////////////////////////  
                //  ProParkYale logic

                var theaddress = m_AddressList.Rows[i].address;
                var addrname = m_AddressList.Rows[i].name;
                var addressid = m_AddressList.Rows[i].id;
                var arrivalMin = m_AddressList.Rows[i].nextarrival;
                if (arrivalMin == "999") {
                    arrivalMin = "";
                }
                else {
                    if (arrivalMin == "1") {
                        string += "Next bus in " + arrivalMin + " minute"
                    }
                    else {
                        string += "Next bus in " + arrivalMin + " minutes"
                    }
                }

                //////////////////////////////////////////////////

                var divInfoVar = "<div style='color:white; font-family:arial; font-size:12px; background:URL(images/AddressMarkerPopUp.png) no-repeat top right Transparent; width:319px; height:109px;'>" + string + "</div>";
                addrInfoBox[i].SetCustomIcon(divInfoVar);
                addrInfoBox[i].ShowIcon();
                addrInfoIds[i] = MapAddresspins[i].GetId();

            }
        }
    showUserRoute();
    map.AddShapeLayer(address_marker_layer);
    address_marker_layer.Show();
}

function showAddressPane() {
    var point = m_gMap.getCurrentMapType().getProjection().fromLatLngToPixel(m_gMap.fromDivPixelToLatLng(new GPoint(0, 0), true), m_gMap.getZoom());
    var offset = m_gMap.getCurrentMapType().getProjection().fromLatLngToPixel(this.getPoint(), m_gMap.getZoom());
    var anchor = this.getIcon().iconAnchor;
    var width = this.getIcon().iconSize.width;
    //var height= 100;
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width + INFOPANE_OFFSET_X, offset.y - point.y - anchor.y + INFOPANE_OFFSET_Y));
    pos.apply(this.infoPane);
    this.infoPane.style.display = "block";
}

function hideAddressPane() {
    this.infoPane.style.display = "none";
}

function addAddress() {
    //  This is really 'Save Address Markers'
    if (m_demoUser || demo2_user) {
        AlertMessage("Sorry,this feature has been disabled in demonstration mode.");
        return;
    }

    address_text = document.getElementById("txtAddressFind");
    address_name = document.getElementById("addressName");
    address_lat = document.getElementById("addressLAT");
    address_lon = document.getElementById("addressLON");
    if (address_name.value == "" || address_name == null || address_name.value == "New Address Marker") {
        AlertMessage("Name is required");
        return;
    }
    if (address_lat.value == "" || address_lat == null || address_lon.value == "" || address_lon == null || address_lat.value * 1 == 0 || address_lon.value * 1 == 0) {
        AlertMessage("LAT:LON is required");
        return;
    }
    if (address_text.value == "" || address_text == null || address_text.value == "1234 Street Name City,State") {
        AlertMessage("Address is required");
        return;
    }
    if (!isNumeric(address_lat.value) || !isNumeric(address_lat.value)) {
        AlertMessage("LAT:LON is invalid");
        return;
    }

    address_image = document.getElementById("AddrMarkerImage");
    var images = address_image.src.split("/");
    var image = "Standard.png";
    for (var i = images.length; i > -1; i--) {
        if (images[i] != "" && images[i] != null) {
            image = images[i];
            break;
        }
    }

    //alert(m_CurrentUser + ":" + address_name.value + ":" + address_lat.value + ":" + address_lon.value + ":" + address_text.value + ":" + image);

    //queue_address_dt.Rows.addRow({});
    targetDDL = document.getElementById("ddlAddressGroupList");
    var target_address_group_id = targetDDL.options[targetDDL.options.selectedIndex].value;

    Feed.IAddr(m_CurrentUser, address_name.value, address_lat.value, address_lon.value, address_text.value, image, target_address_group_id, address_save_callback)
}

function address_save_callback(result) {

    var isUpdate = false;

    address_image = document.getElementById("AddrMarkerImage");
    var images = address_image.src.split("/");
    var image = "Standard.png";
    for (var i = images.length; i > -1; i--) {
        if (images[i] != "" && images[i] != null) {
            image = images[i];
            break;
        }
    }

    var address_latitude = document.getElementById("addressLAT").value;
    var address_longitude = document.getElementById("addressLON").value;
    var address_name = document.getElementById("addressName").value;
    var address_street = document.getElementById("txtAddressFind").value;
    var address_image = image;

    if(queue_address_dt != null)
    for (var i = 0; i < queue_address_dt.Rows.length; i++) {
        if (null != queue_address_dt.Rows[i] &&
            queue_address_dt.Rows[i].id == result.value) {
            
            queue_address_dt.Rows[i].lat = address_latitude;
            queue_address_dt.Rows[i].lon = address_longitude;
            queue_address_dt.Rows[i].name = address_name;
            queue_address_dt.Rows[i].address = address_street;
            queue_address_dt.Rows[i].image = image;
            
            isUpdate = true;
        }
    }

    
    if (false == isUpdate) {

        if(queue_address_dt == null)
            loadAddressData();

        var appendedRow = new Object();

        appendedRow.id = result.value;
        appendedRow.lat = address_latitude;
        appendedRow.lon = address_longitude;
        appendedRow.address = address_street;
        appendedRow.name = address_name;
        appendedRow.accountid = -1;
        appendedRow.image = image;

        queue_address_dt.addRow(appendedRow);
    }
    

    updateAddressMarkersCallback(queue_address_dt);
    
}

function postAddressModification(result) {
    //alert('action completed: ' + result.value);
}

function address_lazy_delete(address_id) {

    if(queue_address_dt != null)
    for (var i = 0; i < queue_address_dt.Rows.length; i++) {
        if (null != queue_address_dt.Rows[i] &&
            queue_address_dt.Rows[i].id == address_id) {

            //var pixel = map.LatLongToPixel(new VELatLong(queue_address_dt.Rows[i].lat, queue_address_dt.Rows[i].lon));

            var image = queue_address_dt.Rows[i].image;
            var x_offset = -15;
            var y_offset = -15;
            
            /*
            if (MarkerNames != null & MarkerNames.Rows != null) {
                for (var j = 0; j < MarkerNames.Rows.length; j++) {
                    if (MarkerNames.Rows[j].image == image) {
                        x_offset = MarkerNames.Rows[j].X_center;
                        y_offset = MarkerNames.Rows[j].Y_center;
                        break;
                    }
                }
            }
            */

            //widget_delete_toggle(pixel.x + x_offset, pixel.y + y_offset);

            queue_address_dt.Rows[i] = null;
            break;
        }
    }

    updateAddressMarkersCallback(queue_address_dt);
}

function address_editor_view_toggle(type) {
    button0 = document.getElementById("ae_view_addresses");
    button1 = document.getElementById("ae_view_groups");

    addressAddPanel = document.getElementById("addressAdd");
    addressRemovePanel = document.getElementById("addressRemove");
    addressGroupsPanel = document.getElementById("addressGroup");

    //set the class and hide the panels
    if (type == 'addresses') {
        button0.setAttribute('class', 'address_view_selected');
        button1.setAttribute('class', 'address_view');

        addressGroupsPanel.style.visibility = "hidden";
        addressGroupsPanel.style.display = "none";

        addressRemovePanel.style.visibility = "hidden";
        addressRemovePanel.style.display = "none";

        addressAddPanel.style.visibility = "visible";
        addressAddPanel.style.display = "inline";
    }

    if (type == 'groups') {
        button0.setAttribute('class', 'address_view');
        button1.setAttribute('class', 'address_view_selected');

        addressAddPanel.style.visibility = "hidden";
        addressAddPanel.style.display = "none";

        addressRemovePanel.style.visibility = "hidden";
        addressRemovePanel.style.display = "none";

        addressGroupsPanel.style.visibility = "visible";
        addressGroupsPanel.style.display = "inline";
    }
}

function removeAddress() {
    if (m_demoUser || demo2_user) {
        AlertMessage("Sorry, this feature has been disabled in demonstration mode.");
        return;
    }

    addressList = document.getElementById("ddlAddressList");

    if (addressList.options.selectedIndex >= 0) {
        selectedValue = addressList.options[addressList.options.selectedIndex].value;
        address_lazy_delete(selectedValue);
        Feed.DAddr(selectedValue, m_CurrentUser, postAddressModification);
    }
}

function addAddressGroup() {
    current_session = document.getElementById("SESSIONKEY");
    current_session_key = current_session.getAttribute("value");
    var new_address_group_name = document.getElementById("address_group_name");

    var ddlAddressList = document.getElementById("ddlAddressList");
    ddlAddressList.options.length = 0;

    DAL.AddAddressGroup(current_session_key, new_address_group_name.value, add_address_group_callback);
}

function saveAddressGroup() {
    current_session = document.getElementById("SESSIONKEY");
    current_session_key = current_session.getAttribute("value");

    var new_address_group_name = document.getElementById("address_group_name");
    targetDDL = document.getElementById("ddlAddressGroupList");

    var target_address_group_id = targetDDL.options[targetDDL.options.selectedIndex].value;

    DAL.SaveAddressGroup(current_session_key, target_address_group_id, new_address_group_name.value, save_address_group_callback);
}

function add_address_group_callback(result) {
    if (oSessionKey != null) {
        var sessionID = oSessionKey.getAttribute("value");
        DAL.GetAddressGroups(sessionID, force_select_last_address_group);
    }
}

function force_select_last_address_group(result) {
    if (null != result.value) {
        var dtResults = result.value;

        targetDDL = document.getElementById("ddlAddressGroupList");

        targetDDL.options.length = 0;

        for (var i = 0; i < dtResults.Rows.length; i++) {
            targetDDL.options[targetDDL.options.length] = new Option(dtResults.Rows[i].name, dtResults.Rows[i].id);
        }

        targetDDL.options.selectedIndex = targetDDL.options.length - 1;
    }
}

function save_address_group_callback(result) {
    if (null != result.value) {
        var targetDDL = document.getElementById("ddlAddressGroupList");
        var new_address_group_name = document.getElementById("address_group_name");
        targetDDL.options[targetDDL.options.selectedIndex].text = new_address_group_name.value;
    }
}

function viewAddressDetail(id) {
    if (id == -1) {
        alertPanel = document.getElementById("addressAdd");
        alertPanel.style.visibility = "hidden";
        alertPanel.style.display = "none";

        alertPanel = document.getElementById("addressRemove");
        alertPanel.style.visibility = "hidden";
        alertPanel.style.display = "none";
        m_SelectPoint = false;

        alertPanel = document.getElementById("addressGroup");
        alertPanel.style.visibility = "hidden";
        alertPanel.style.display = "none";
    }
    if (id == 1) {
        alertPanel = document.getElementById("addressAdd");

        alertPanel.style.visibility = "visible";
        alertPanel.style.display = "inline";

        alertPanel = document.getElementById("addressRemove");

        alertPanel.style.visibility = "hidden";
        alertPanel.style.display = "none";

        alertPanel = document.getElementById("addressGroup");
        alertPanel.style.visibility = "hidden";
        alertPanel.style.display = "none";

        m_SelectPoint = true;
    }
    if (id == 2) {
        // remove address
        oalertPanel = document.getElementById("addressAdd");
        oalertPanel.style.visibility = "hidden";
        oalertPanel.style.display = "none";

        alertPanel = document.getElementById("addressRemove");
        alertPanel.style.visibility = "visible";
        alertPanel.style.display = "inline";

        alertPanel = document.getElementById("addressGroup");
        alertPanel.style.visibility = "hidden";
        alertPanel.style.display = "none";

        var List = document.getElementById("ddlAddressList");
        if (List.selectedIndex != -1) {
            var table = document.getElementById("addressSelected");
            table.style.display = "inline";
            table.style.visibility = "visible";

            table = document.getElementById("noAddressSelected");
            table.style.display = "none";
            table.style.visibility = "hidden";
        }
        else {
            var table = document.getElementById("noAddressSelected");
            table.style.display = "inline";
            table.style.visibility = "visible";

            table = document.getElementById("addressSelected");
            table.style.display = "none";
            table.style.visibility = "hidden";
        }
        m_SelectPoint = false;
    }
    if (id == 3) { // add marker
        if (NewAddressMarkerPresent != true) {
            var center = map.GetCenter();

            alertPanel = document.getElementById("addressAdd");
            alertPanel.style.visibility = "visible";
            alertPanel.style.display = "inline";

            alertPanel = document.getElementById("addressRemove");
            alertPanel.style.visibility = "hidden";
            alertPanel.style.display = "none";

            alertPanel = document.getElementById("addressGroup");
            alertPanel.style.visibility = "hidden";
            alertPanel.style.display = "none";

            address_text = document.getElementById("txtAddressFind");
            address_name = document.getElementById("addressName");
            address_lat = document.getElementById("addressLAT");
            address_lon = document.getElementById("addressLON");

            address_name.value = NewAddressMarker;
            address_lat.value = center.Latitude;
            address_lon.value = center.Longitude;
            address_text.value = "1234 Street Name City,State";

            AddrMarkerImage = document.getElementById("AddrMarkerImage");
            AddrMarkerImage.src = "Images/AddressMarkers/Standard.png";

            var pixel = map.LatLongToPixel(center);

            pixel.x = pixel.x - 16;
            pixel.y = pixel.y - 16;

            var LL = map.PixelToLatLong(pixel);

            var imgloc = "images/NewTarget.gif";

            NewAddressPin = new VEShape(VEShapeType.Pushpin, LL);
            NewAddressPin.SetTitle(NewAddressMarker);
            NewAddressPin.SetCustomIcon(imgloc);
            map.AddShape(NewAddressPin);
            NewAddressMarkerPresent = true;
        }
    }
}

function showMarkerImages() {
    Feed.SAdrMrk(getAddressMarkerIconsCallback);
}

function getAddressMarkerIconsCallback(result) {
    if (result != null) {
        MarkerNames = result.value;
        var divInfo = "<table style='vertical-align:top;'><tr valign='top' align='center'>";
        for (var i = 0; i < MarkerNames.Rows.length; i++) {
            if (MarkerNames.Rows[i].image != null && MarkerNames.Rows[i].image != "") {
                divInfo += "<td valign='top' width='70px' height='60px' style='cursor:pointer;'><img alt='' valign='top' onclick='useAddressMarkerIcon(" + i + ");' src='images/AddressMarkers/" + MarkerNames.Rows[i].image + "' /></td>";
                var j = (i + 1) % 8;
                if (j == 0) {
                    divInfo += "</tr><tr valign='top' align='center'>";
                }
            }
        }
        divInfo += "</tr></table>"
        divInfo += "<div class='whiteType10' style'text-align:center; width:400px;'><br />&nbsp;&nbsp;&nbsp;More address marker icons coming soon!</div>";
        var divIconSelector = document.getElementById("divAddressMarkerOverlay");
        divIconSelector.innerHTML = divInfo;
        //m_actiondiv = document.getElementById("divAddressesOverlay");
        m_divIOverlay = null;
        m_divIOverlay = document.getElementById("divAddressMarkerSelectorOverlay");
        //m_divIOverlay.style.marginTop = parseInt(0);
        fadein("divAddressMarkerSelectorOverlay");
        m_alertdiv = document.getElementById("divAddressesOverlay");
        m_alertdiv.style.visibility = "hidden";
        m_alertdiv.style.display = "none";
    }
}

function hideAddressMarkerIcons() {
    fadeout("divAddressMarkerSelectorOverlay");
    m_actiondiv = document.getElementById("divAddressesOverlay");
    m_actiondiv.style.visibility = "visible";
    m_actiondiv.style.display = "block";
}

function useAddressMarkerIcon(id) {
    if (ControlPanelLockout == true || m_demoUser || demo2_user) {
        AlertMessage("Sorry, this feature has been disabled in demonstration mode.");
        return;
    }

    var AddrMarkerToUse = MarkerNames.Rows[id].image;
    var AddressMarkerImage = document.getElementById("AddrMarkerImage");
    AddressMarkerImage.src = "images/AddressMarkers/" + AddrMarkerToUse;
    hideAddressMarkerIcons();
}
//
//                                                  End of Address Marker Functions
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//                                                   Alert Functions
function drawFence() {
    if (m_drawingFence == true) {
        map.DeleteAllPolygons();
        var points = new Array(
           new VELatLong(m_fenceLatUL, m_fenceLonUL),
           new VELatLong(m_fenceLatUL, m_fenceLonLR),
           new VELatLong(m_fenceLatLR, m_fenceLonLR),
           new VELatLong(m_fenceLatLR, m_fenceLonUL),
           new VELatLong(m_fenceLatUL, m_fenceLonUL)
        );
        var PId = 1;
        poly = new VEPolygon(PId, points);
        poly.SetOutlineWidth(1);
        poly.SetOutlineColor(new VEColor(0, 0, 0, 1.0));
        poly.SetFillColor(new VEColor(255, 128, 128, 0.5));
        map.AddPolygon(poly);
        if (fenceUL != null) {
            map.DeleteShape(fenceUL);
            fenceUL = null;
        }
        if (fenceLR != null) {
            map.DeleteShape(fenceLR);
            fenceLR = null;
        }
        var originalPoint = map.LatLongToPixel(new VELatLong(m_fenceLatUL, m_fenceLonUL));
        var newNameLatLon = map.PixelToLatLong(new VEPixel(originalPoint.x + 8, originalPoint.y - 8));
        fenceUL = new VEShape(VEShapeType.Pushpin, newNameLatLon);
        fenceUL.SetCustomIcon("images/redpushpin.gif");
        fenceUL.SetDescription("Drag me around the map");
        fenceUL.SetTitle("fenceUL");
        map.AddShape(fenceUL);
        fenceUL.SetZIndex(1100, 1100)
        fenceUL.Show();
        originalPoint = map.LatLongToPixel(new VELatLong(m_fenceLatLR, m_fenceLonLR));
        newNameLatLon = map.PixelToLatLong(new VEPixel(originalPoint.x + 8, originalPoint.y - 8));
        fenceLR = new VEShape(VEShapeType.Pushpin, newNameLatLon);
        fenceLR.SetCustomIcon("images/redpushpin.gif");
        fenceLR.SetDescription("Drag me around the map too");
        fenceLR.SetTitle("fenceLR");
        map.AddShape(fenceLR);
        fenceLR.SetZIndex(1100, 1100)
        fenceLR.Show();
    }
}

function centerMapOnFence() {
    var latCenter = (m_fenceLatUL * 1 + m_fenceLatLR * 1) / 2;
    var lonCenter = (m_fenceLonUL * 1 + m_fenceLonLR * 1) / 2;
    var center = new VELatLong(latCenter, lonCenter);
    map.SetCenter(center);
    points = new Array;
    points[0] = new VELatLong(m_fenceLatUL, m_fenceLonUL);
    points[1] = new VELatLong(m_fenceLatLR, m_fenceLonLR);
    map.SetMapView(points);
}

function alertSelected() {
    if (AlertEditorOpen) {
        if (!m_demoUser || demo2_user) {
            alertListSelection = document.getElementById("ddlAlertList");
            if (alertListSelection != null) {
                if (alertListSelection.options.selectedIndex >= 0) {
                    alertListValue = alertListSelection.options[alertListSelection.options.selectedIndex].value;
                    Feed.SSngAlrt(alertListValue, alertSelectedCallback);
                }
            }
            else {
                AlertMessage("null alert list");
            }
        }
    }
}

function alertSelectedCallback(retAlert) {
    if (!AlertEditorOpen) {
        return;
    }
    if (retAlert != null) {
        if (retAlert.value != null) {
            dt = retAlert.value;
            //depending on the type we display a certain interface
            //for G type pull and fill the values
            //for S type pull and fill the values
            //for P type pull and fill the values
            //for I type pull and fill the values
            if (dt != null && typeof (dt) == "object") {
                if (dt.Rows.length > 0) {
                    if (dt.Rows[0].type == "G") {
                        showGeoAlertDiv();
                        vehicleSelection = document.getElementById("ddlVehicleZoneAlert");
                        //make the geofence visible for this instance
                        zoneName = document.getElementById("zoneName");
                        startHour = document.getElementById("ZSTRTH");
                        startMin = document.getElementById("ZSTRTM");
                        endHour = document.getElementById("ZENDH");
                        endMin = document.getElementById("ZENDM");
                        zEnter = document.getElementById("ZENTER");
                        zExit = document.getElementById("ZEXIT");
                        smscheck = document.getElementById("SMSCHECKGF");
                        emailcheck = document.getElementById("EMAILCHECKGF");
                        smstarget = document.getElementById("SMSTARGETGF");
                        SMSProvider = document.getElementById("SMSPROVIDERGF");
                        emailtarget = document.getElementById("EMAILTARGETGF");
                        zoneName.value = dt.Rows[0].name;
                        // selecting the vehicle in drop down list. rebekah 08/02/09
                        for (i = 0; i < vehicleSelection.options.length; i++) {
                            if (vehicleSelection.options[i].value == dt.Rows[0].vehicle_id) {
                                vehicleSelection.selectedIndex = i;
                                break;
                            }
                        }
                        if (dt.Rows[0].Lo_Hour != null) {
                            startHour.value = dt.Rows[0].Lo_Hour;
                        }
                        while (startHour.value.length < 2) { startHour.value = "0" + startHour.value; }
                        if (dt.Rows[0].Lo_Minute != null) {
                            startMin.value = dt.Rows[0].Lo_Minute;
                        }
                        while (startMin.value.length < 2) { startMin.value = "0" + startMin.value; }
                        if (dt.Rows[0].Hi_Hour != null) {
                            endHour.value = dt.Rows[0].Hi_Hour;
                        }
                        while (endHour.value.length < 2) { endHour.value = "0" + endHour.value; }
                        if (dt.Rows[0].Hi_Minute != null) {
                            endMin.value = dt.Rows[0].Hi_Minute;
                        }
                        while (endMin.value.length < 2) { endMin.value = "0" + endMin.value; }
                        if (endHour.value == "00" && endMin.value == "00") {
                            endHour.value = "23";
                            endMin.value = "59";
                        }
                        if (dt.Rows[0].Enter_Zone == null || dt.Rows[0].Enter_Zone == true) {
                            zEnter.checked = true;
                        }
                        else {
                            zEnter.checked = false;
                        }
                        if (dt.Rows[0].Exit_Zone == null || dt.Rows[0].Exit_Zone == true) {
                            zExit.checked = true;
                        }
                        else {
                            zExit.checked = false;
                        }
                        if (dt.Rows[0].SMSEnabled == "1") {
                            smscheck.checked = true;
                        }
                        else {
                            smscheck.checked = false;
                        }
                        if (dt.Rows[0].EMAILEnabled == "1") {
                            emailcheck.checked = true;
                        }
                        else {
                            emailcheck.checked = false;
                        }
                        var sms = dt.Rows[0].sms;
                        smsval = sms.split("@");
                        smstarget.value = smsval[0];
                        SMSProvider.value = smsval[1];
                        emailtarget.value = dt.Rows[0].email;
                        var latlng = dt.Rows[0].bbl;
                        ltln = latlng.split(",");
                        m_fenceLatUL = ltln[0];
                        m_fenceLonUL = ltln[1];
                        m_fenceLatLR = ltln[2];
                        m_fenceLonLR = ltln[3];
                        m_drawingFence = true;
                        drawFence();
                        centerMapOnFence();
                    }
                    else if (dt.Rows[0].type == "S") {
                        viewAlertDetail(2);
                        zoneName = document.getElementById("zoneSpeedName");
                        vehicleSelection = document.getElementById("ddlVehicleSpeedAlert");
                        speed = document.getElementById("speedThreshold");
                        smscheck = document.getElementById("SMSCHECKSZ");
                        emailcheck = document.getElementById("EMAILCHECKSZ");
                        SMSProvider = document.getElementById("SMSPROVIDERSZ");
                        smstarget = document.getElementById("SMSTARGETSZ");
                        emailtarget = document.getElementById("EMAILTARGETSZ");
                        for (i = 0; i < vehicleSelection.options.length; i++) {
                            if (vehicleSelection.options[i].value == dt.Rows[0].vehicle_id) {
                                vehicleSelection.selectedIndex = i;
                                break;
                            }
                        }
                        speed.value = "" + dt.Rows[0].speed_threshold;
                        zoneName.value = dt.Rows[0].name;
                        if (dt.Rows[0].SMSEnabled == "1") {
                            smscheck.checked = true;
                        }
                        else {
                            smscheck.checked = false;
                        }
                        if (dt.Rows[0].EMAILEnabled == "1") {
                            emailcheck.checked = true;
                        }
                        else {
                            emailcheck.checked = false;
                        }
                        smstarget.value = dt.Rows[0].sms.substring(0, dt.Rows[0].sms.indexOf("@"));
                        SMSProvider.value = dt.Rows[0].sms.substring(dt.Rows[0].sms.indexOf("@") + 1);
                        emailtarget.value = dt.Rows[0].email;
                    }
                    else if (dt.Rows[0].type == "P") {
                        viewAlertDetail(4);
                        panicName = document.getElementById("PANICNAME");
                        smscheck = document.getElementById("SMSCHECKSP");
                        emailcheck = document.getElementById("EMAILCHECKSP");
                        smstarget = document.getElementById("SMSTARGETSP");
                        SMSProvider = document.getElementById("SMSPROVIDERSP");
                        emailtarget = document.getElementById("EMAILTARGETSP");
                        panicName.value = dt.Rows[0].name;
                        if (dt.Rows[0].SMSEnabled == "1") {
                            smscheck.checked = true;
                        }
                        else {
                            smscheck.checked = false;
                        }
                        if (dt.Rows[0].EMAILEnabled == "1") {
                            emailcheck.checked = true;
                        }
                        else {
                            emailcheck.checked = false;
                        }
                        smstarget.value = dt.Rows[0].sms.substring(0, dt.Rows[0].sms.indexOf("@"));
                        SMSProvider.value = dt.Rows[0].sms.substring(dt.Rows[0].sms.indexOf("@") + 1);
                        emailtarget.value = dt.Rows[0].email;
                    }
                    else if (dt.Rows[0].type == "I") {
                        viewAlertDetail(5);
                        ignName = document.getElementById("ignName");
                        SMSCarrier = document.getElementById("SMSPROVIDERIGN");
                        SMSCarrier.value = "txt.att.net";
                        //zoneName = document.getElementById("zoneName"); // com out using ignName instead rebekah 08/02/09
                        vehicleSelection = document.getElementById("ddlVehicleIgnAlert");
                        startHour = document.getElementById("ISTRTH");
                        startMin = document.getElementById("ISTRTM");
                        endHour = document.getElementById("IENDH");
                        endMin = document.getElementById("IENDM");
                        IgnOn = document.getElementById("IGNON");
                        IgnOff = document.getElementById("IGNOFF");
                        smscheck = document.getElementById("SMSCHECKIGN");
                        emailcheck = document.getElementById("EMAILCHECKIGN");
                        smstarget = document.getElementById("SMSTARGETIGN");
                        SMSProvider = document.getElementById("SMSPROVIDERIGN");
                        emailtarget = document.getElementById("EMAILTARGETIGN");
                        ignName.value = dt.Rows[0].name;
                        // selecting the vehicle in drop down list. rebekah 08/02/09
                        for (i = 0; i < vehicleSelection.options.length; i++) {
                            if (vehicleSelection.options[i].value == dt.Rows[0].vehicle_id) {
                                vehicleSelection.selectedIndex = i;
                                break;
                            }
                        }
                        if (dt.Rows[0].Lo_Hour != null) {
                            startHour.value = dt.Rows[0].Lo_Hour;
                        }
                        while (startHour.value.length < 2) { startHour.value = "0" + startHour.value; }
                        if (dt.Rows[0].Lo_Minute != null) {
                            startMin.value = dt.Rows[0].Lo_Minute;
                        }
                        while (startMin.value.length < 2) { startMin.value = "0" + startMin.value; }
                        if (dt.Rows[0].Hi_Hour != null) {
                            endHour.value = dt.Rows[0].Hi_Hour;
                        }
                        while (endHour.value.length < 2) { endHour.value = "0" + endHour.value; }
                        if (dt.Rows[0].Hi_Minute != null) {
                            endMin.value = dt.Rows[0].Hi_Minute;
                        }
                        while (endMin.value.length < 2) { endMin.value = "0" + endMin.value; }
                        if (endHour.value == "00" && endMin.value == "00") {
                            endHour.value = "23";
                            endMin.value = "59";
                        }
                        if (dt.Rows[0].Ign_On == null || dt.Rows[0].Ign_On == true) {
                            IgnOn.checked = true;
                        }
                        else {
                            IgnOn.checked = false;
                        }
                        if (dt.Rows[0].Ign_Off == null || dt.Rows[0].Ign_Off == true) {
                            IgnOff.checked = true;
                        }
                        else {
                            IgnOff.checked = false;
                        }
                        if (dt.Rows[0].SMSEnabled == "1") {
                            smscheck.checked = true;
                        }
                        else {
                            smscheck.checked = false;
                        }
                        if (dt.Rows[0].EMAILEnabled == "1") {
                            emailcheck.checked = true;
                        }
                        else {
                            emailcheck.checked = false;
                        }
                        var sms = dt.Rows[0].sms;
                        smsval = sms.split("@");
                        smstarget.value = smsval[0];
                        SMSProvider.value = smsval[1];
                        emailtarget.value = dt.Rows[0].email;
                    }
                    else if (dt.Rows[0].type == "R") {
                        viewAlertDetail(6);
                        with (dt.Rows[0]) {
                            PopulateVehicleList("ddlAdvRouteVehicles");
                            document.getElementById("alertName").value = name;
                            SelectIndexOfValue("ddlRouteName", RouteID);
                            LoadAdvancedRoute(RouteID);
                            LoadAdvancedRouteAlertVehicles(id);
                            document.getElementById("RSTRTH").value = ((Lo_Hour < 10) ? "0" + Lo_Hour : Lo_Hour);
                            document.getElementById("RSTRTM").value = ((Lo_Minute < 10) ? "0" + Lo_Minute : Lo_Minute);
                            document.getElementById("RENDH").value = ((Hi_Hour < 10) ? "0" + Hi_Hour : Hi_Hour);
                            document.getElementById("RENDM").value = ((Hi_Minute < 10) ? "0" + Hi_Minute : Hi_Minute);
                            document.getElementById("RENTER").checked = Enter_Zone;
                            document.getElementById("REXIT").checked = Exit_Zone;
                            document.getElementById("radAFeet").checked = true;
                            document.getElementById("tbARadius").value = Radius;
                            document.getElementById("SMSCHECKAR").checked = ((SMSEnabled == "1") ? true : false)
                            document.getElementById("SMSTARGETAR").value = SMSNumber;
                            document.getElementById("SMSPROVIDERAR").value = SMSCarrier;
                            document.getElementById("EMAILCHECKAR").checked = ((EMAILEnabled == "1") ? true : false)
                            document.getElementById("EMAILTARGETAR").value = email;
                            document.getElementById("tbARadius").value = Radius;
                            AlertRadiusChanged();
                            isAdvRouteVisible = true;
                        }
                    }
                }
            }
        }
    }
}

function addAlert(type) {
    //  this function actually saves the alert
    if (m_demoUser || demo2_user) { AlertMessage("Sorry, this feature has been disabled in demonstration mode."); return; }
    var smsEnabled = false; // 0 - not enabled, 1 - enabled
    var emailEnabled = false; // 0 - not enabled, 1 - enabled
    gfaz_smslist = "";
    gfaz_SMSPhone = "";
    gfaz_SMSCarrier = "";
    gfaz_emaillist = "";
    gfaz_bbl = "";
    gfaz_loHour = 0;
    gfaz_loMin = 0;
    gfaz_hiHour = 23;
    gfaz_hiMin = 59;
    gfaz_enter = true;
    gfaz_exit = true;
    gfaz_IgnOn = false;
    gfaz_IgnOff = false;
    az_type = '';
    saz_speed = -1;
    az_name = "";
    saz_vehicleid = "";
    var routeID = 0;
    var vehicleList = null;
    var radius = 0;

    if (type == 0) {
        az_type = 'S';
        sthresh = document.getElementById("speedThreshold");
        saz_speed = parseInt(sthresh.value, 10);
        var saz_vehicleddl = document.getElementById("ddlVehicleSpeedAlert");
        saz_vehicleid = saz_vehicleddl.options[saz_vehicleddl.options.selectedIndex].value;
        gfaz_name = document.getElementById("zoneSpeedName");
        gfaz_sms = document.getElementById("SMSCHECKSZ");
        gfaz_email = document.getElementById("EMAILCHECKSZ");
        az_name = gfaz_name.value;
        if (gfaz_sms.checked) {
            smsEnabled = true;
        }
        else {
            smsEnabled = false;
        }
        smscheck = document.getElementById("SMSTARGETSZ");
        smsprovider = document.getElementById("SMSPROVIDERSZ");
        if (smsprovider.options.selectedIndex != -1) {
            smsprovideremail = smsprovider.options[smsprovider.options.selectedIndex].value;
        }
        else {
            smsprovideremail = "";
        }
        smscheck.value = stripID(smscheck.value)
        gfaz_smslist = smscheck.value + "@" + smsprovideremail;
        gfaz_SMSPhone = smscheck.value;
        gfaz_SMSCarrier = smsprovideremail;
        if (gfaz_email.checked) {
            emailEnabled = true;
        }
        else {
            emailEnabled = false;
        }
        emailcheck = document.getElementById("EMAILTARGETSZ");
        gfaz_emaillist = emailcheck.value;
    }
    else if (type == 1) {
        az_type = 'G';
        var saz_vehicleddl = document.getElementById("ddlVehicleZoneAlert");
        saz_vehicleid = saz_vehicleddl.options[saz_vehicleddl.options.selectedIndex].value;
        gfaz_name = document.getElementById("zoneName");
        gfaz_sms = document.getElementById("SMSCHECKGF");
        gfaz_email = document.getElementById("EMAILCHECKGF");
        gfaz_loHour = document.getElementById("ZSTRTH");
        gfaz_loMin = document.getElementById("ZSTRTM");
        gfaz_hiHour = document.getElementById("ZENDH");
        gfaz_hiMin = document.getElementById("ZENDM");
        gfaz_enter = document.getElementById("ZENTER");
        gfaz_exit = document.getElementById("ZEXIT");
        az_name = gfaz_name.value;
        if (gfaz_sms.checked) {
            smsEnabled = true;
        }
        else {
            smsEnabled = false;
        }
        smscheck = document.getElementById("SMSTARGETGF");
        smsprovider = document.getElementById("SMSPROVIDERGF");
        if (smsprovider.options.selectedIndex != -1) {
            smsprovideremail = smsprovider.options[smsprovider.options.selectedIndex].value;
        }
        else {
            smsprovideremail = "";
        }
        smscheck.value = stripID(smscheck.value)
        gfaz_smslist = smscheck.value + "@" + smsprovideremail;
        gfaz_SMSPhone = smscheck.value;
        gfaz_SMSCarrier = smsprovideremail;
        if (gfaz_email.checked) {
            emailEnabled = true;
        }
        else {
            emailEnabled = false;
        }
        emailcheck = document.getElementById("EMAILTARGETGF");
        gfaz_emaillist = emailcheck.value;

        // Display error message to user if geo zone lat or lon is null.  rebekah 08/02/09
        if (m_fenceLatUL == null || m_fenceLonUL == null || m_fenceLatLR == null || m_fenceLonLR == null) {
            AlertMessage("Zone was not selected.  Please select zone on the map.");
            return;
        }

        gfaz_bbl = m_fenceLatUL + "," + m_fenceLonUL + "," + m_fenceLatLR + "," + m_fenceLonLR;

        //  verify times 
        if (isNumeric(gfaz_loHour.value) && isNumeric(gfaz_loMin.value) && isNumeric(gfaz_hiHour.value) && isNumeric(gfaz_hiMin.value)) {
        }
        else {
            AlertMessage("Start and end times must be numeric.");
            return;
        }
        if (gfaz_loHour.value > 23 || gfaz_loMin.value > 59 || gfaz_hiHour.value > 23 || gfaz_hiMin.value > 59) {
            AlertMessage("Start and end times must be between 00:00 and 23:59.");
            return;
        }
        if ((gfaz_hiHour.value < gfaz_loHour.value) || (gfaz_loHour.value == gfaz_hiHour.value && gfaz_hiMin.value < gfaz_loMin.value)) {
            AlertMessage("Start time must be less than End time.  If the alert needs to span over midnight please create two alerts.");
            return;
        }
    }
    else if (type == 3) {
        //"Panic Alert";
        az_type = 'P';
        saz_speed = parseInt(0);
        saz_vehicleid = "-1"
        gfaz_sms = document.getElementById("SMSCHECKSP");
        gfaz_email = document.getElementById("EMAILCHECKSP");
        az_name_temp = document.getElementById("PANICNAME");
        az_name = az_name_temp.value;
        if (gfaz_sms.checked) {
            smsEnabled = true;
        }
        else {
            smsEnabled = false;
        }
        smscheck = document.getElementById("SMSTARGETSP");
        smsprovider = document.getElementById("SMSPROVIDERSP");
        if (smsprovider.options.selectedIndex != -1) {
            smsprovideremail = smsprovider.options[smsprovider.options.selectedIndex].value;
        }
        else {
            smsprovideremail = "";
        }
        smscheck.value = stripID(smscheck.value)
        gfaz_smslist = smscheck.value + "@" + smsprovideremail;
        gfaz_SMSPhone = smscheck.value;
        gfaz_SMSCarrier = smsprovideremail;
        if (gfaz_email.checked) {
            emailEnabled = true;
        }
        else {
            emailEnabled = false;
        }
        emailcheck = document.getElementById("EMAILTARGETSP");
        gfaz_emaillist = emailcheck.value;
    }
    else if (type == 4) {
        //"Ignition Alert";
        saz_speed = parseInt(0);
        az_type = 'I';
        var saz_vehicleddl = document.getElementById("ddlVehicleIgnAlert");
        saz_vehicleid = saz_vehicleddl.options[saz_vehicleddl.options.selectedIndex].value;
        gfaz_name = document.getElementById("ignName");
        gfaz_sms = document.getElementById("SMSCHECKIGN");
        gfaz_email = document.getElementById("EMAILCHECKIGN");
        gfaz_loHour = document.getElementById("ISTRTH");
        gfaz_loMin = document.getElementById("ISTRTM");
        gfaz_hiHour = document.getElementById("IENDH");
        gfaz_hiMin = document.getElementById("IENDM");
        gfaz_IgnOn = document.getElementById("IGNON").checked;
        gfaz_IgnOff = document.getElementById("IGNOFF").checked;
        az_name = gfaz_name.value;
        if (gfaz_sms.checked) {
            smsEnabled = true;
        }
        else {
            smsEnabled = false;
        }
        smscheck = document.getElementById("SMSTARGETIGN");
        smsprovider = document.getElementById("SMSPROVIDERIGN");
        if (smsprovider.options.selectedIndex != -1) {
            smsprovideremail = smsprovider.options[smsprovider.options.selectedIndex].value;
        }
        else {
            smsprovideremail = "";
        }
        smscheck.value = stripID(smscheck.value)
        gfaz_smslist = smscheck.value + "@" + smsprovideremail;
        gfaz_SMSPhone = smscheck.value;
        gfaz_SMSCarrier = smsprovideremail;
        if (gfaz_email.checked) {
            emailEnabled = true;
        }
        else {
            emailEnabled = false;
        }
        emailcheck = document.getElementById("EMAILTARGETIGN");
        gfaz_emaillist = emailcheck.value;
        //  verify times 
        if (isNumeric(gfaz_loHour.value) && isNumeric(gfaz_loMin.value) && isNumeric(gfaz_hiHour.value) && isNumeric(gfaz_hiMin.value)) {
        }
        else {
            AlertMessage("Start and end times must be numeric.");
            return;
        }
        if (gfaz_loHour.value > 23 || gfaz_loMin.value > 59 || gfaz_hiHour.value > 23 || gfaz_hiMin.value > 59) {
            AlertMessage("Start and end times must be between 00:00 and 23:59.");
            return;
        }
        if ((gfaz_hiHour.value < gfaz_loHour.value) || (gfaz_loHour.value == gfaz_hiHour.value && gfaz_hiMin.value < gfaz_loMin.value)) {
            AlertMessage("Start time must be less than End time.  If the alert needs to span over midnight please create two alerts.");
            return;
        }

    } else if (type == 6) {
        az_type = 'R';
        isAdvRouteVisible = true;
        saz_vehicleid = "0";
        az_name = document.getElementById("alertName").value;
        var m_routeID = document.getElementById("ddlRouteName");
        gfaz_sms = document.getElementById("SMSCHECKAR");
        gfaz_email = document.getElementById("EMAILCHECKAR");
        gfaz_loHour = document.getElementById("RSTRTH");
        gfaz_loMin = document.getElementById("RSTRTM");
        gfaz_hiHour = document.getElementById("RENDH");
        gfaz_hiMin = document.getElementById("RENDM");
        gfaz_enter = document.getElementById("RENTER");
        gfaz_exit = document.getElementById("REXIT");
        radius = AdvRouteGetRadiusFeet("tbARadius");
        var minRadius = document.getElementById("tbAMinRadius").value;
        var m_lbAdvRouteVehicleList = document.getElementById("lbAdvRouteVehicleList");
        var m_ddlAdvRouteVehicles = document.getElementById("ddlAdvRouteVehicles");
        smscheck = document.getElementById("SMSTARGETAR");
        smsprovider = document.getElementById("SMSPROVIDERAR");

        routeID = m_routeID.options[m_routeID.options.selectedIndex].value


        vehicleList = "";
        if (m_lbAdvRouteVehicleList.options.length == m_ddlAdvRouteVehicles.options.length - 1) {
            saz_vehicleid = "-1";
        } else {
            for (var x = 0; x < m_lbAdvRouteVehicleList.options.length; x++) {
                vehicleList += m_lbAdvRouteVehicleList.options[x].value + ";";
            }
        }

        if (gfaz_sms.checked) {
            smsEnabled = true;
        }
        else {
            smsEnabled = false;
        }
        if (smsprovider.options.selectedIndex != -1) {
            smsprovideremail = smsprovider.options[smsprovider.options.selectedIndex].value;
        }
        else {
            smsprovideremail = "";
        }
        smscheck.value = stripID(smscheck.value)
        gfaz_smslist = smscheck.value + "@" + smsprovideremail;
        gfaz_SMSPhone = smscheck.value;
        gfaz_SMSCarrier = smsprovideremail;
        if (gfaz_email.checked) {
            emailEnabled = true;
        }
        else {
            emailEnabled = false;
        }
        emailcheck = document.getElementById("EMAILTARGETAR");
        gfaz_emaillist = emailcheck.value;

        //verify
        if (radius < minRadius) { AlertMessage("Notice - alert Deviation is smaller than the Display Width for the route."); } //continue save anyway.

        if (routeID == -1) { AlertMessage("You must choose a route."); return; }
        if (isNaN(radius)) { AlertMessage("Radius must be numeric. Only enter numbers into this field."); return; }
        if (m_lbAdvRouteVehicleList.options.length == 0) { AlertMessage("You must add vehicles to the alert. Select a veheicle on the left and click add."); return; }
        if (!(isNumeric(gfaz_loHour.value) && isNumeric(gfaz_loMin.value) && isNumeric(gfaz_hiHour.value) && isNumeric(gfaz_hiMin.value))) { AlertMessage("Start and end times must be numeric."); return; }
        if (gfaz_loHour.value > 23 || gfaz_loMin.value > 59 || gfaz_hiHour.value > 23 || gfaz_hiMin.value > 59) { AlertMessage("Start and end times must be between 00:00 and 23:59."); return; }
        if ((gfaz_hiHour.value < gfaz_loHour.value) || (gfaz_loHour.value == gfaz_hiHour.value && gfaz_hiMin.value < gfaz_loMin.value)) { AlertMessage("Start time must be less than End time.  If the alert needs to span over midnight please create two alerts."); return; }
    }
    //  verify name present
    if (az_name == "" || az_name == null) {
        AlertMessage("You must supply a name for the alert.");
        return;
    }
    //  check for multiple e-mail addresses - don't allow.    
    count = 0;
    pos = gfaz_emaillist.indexOf("@");
    while (pos != -1) {
        count++;
        pos = gfaz_emaillist.indexOf("@", pos + 1);
    }
    if (count > 1) {
        AlertMessage("Sorry, only one e-mail address per alert.");
        return;
    }
    if (gfaz_emaillist == "" && gfaz_SMSPhone == "") {
        AlertMessage("You must supply an 'SMS TO' and/or 'EMAIL TO'.");
        return
    }
    if (gfaz_sms.checked && gfaz_SMSPhone == "") {
        AlertMessage("You must supply an 'SMS TO.");
        return;
    }
    if (gfaz_sms.checked && gfaz_SMSCarrier == "") {
        AlertMessage("You must supply an 'SMS carrier (After the '@').");
        return;
    }
    if (gfaz_email.checked && gfaz_emaillist == "") {
        AlertMessage("You must supply an 'Email TO.");
        return;
    }
    if (!gfaz_sms.checked && gfaz_SMSPhone != "") {
        AlertMessage("Warning -- saving alert but no sms message will be sent.");
    }
    if (!gfaz_email.checked && gfaz_emaillist != "") {
        AlertMessage("Warning -- saving alert but no email message will be sent.");
    }
    var enter = (gfaz_enter.checked == null) ? true : gfaz_enter.checked;
    var exit = (gfaz_exit.checked == null) ? true : gfaz_exit.checked;
    var dt;
    dt = DAL.SaveAlert(gfaz_bbl,
                    smsEnabled,
                    emailEnabled,
                    "",
                    gfaz_emaillist,
                    gfaz_smslist,
                    gfaz_SMSPhone,
                    gfaz_SMSCarrier,
                    az_type,
                    m_CurrentUser,
                    saz_speed,
                    az_name,
                    saz_vehicleid,
                    GetIntFromTextbox(gfaz_loHour),
                    GetIntFromTextbox(gfaz_loMin),
                    GetIntFromTextbox(gfaz_hiHour),
                    GetIntFromTextbox(gfaz_hiMin),
                    enter,
                    exit,
                    gfaz_IgnOn,
                    gfaz_IgnOff,
                    routeID,
                    vehicleList,
                    radius, true);
    populateAlertList(dt);
    UserMessage("The Alert has been saved.");
}

function removeAlert() {
    if (m_demoUser || demo2_user) {
        AlertMessage("Sorry, this feature has been disabled in demonstration mode.");
        return;
    }
    alertList = document.getElementById("ddlAlertList");
    if (alertList.options.selectedIndex >= 0) {
        selectedValue = alertList.options[alertList.options.selectedIndex].value;
    }
    else {
        selectedValue = null;
    }
    if (m_drawingFence == true) {
        clearFence()
    }
    if (selectedValue != null) {
        Feed.DAlrt(selectedValue, m_CurrentUser, populateAlertList);
    }
}

function viewAlertDetail(id) {
    var imgAEHelp = document.getElementById("AEHelp");

    hideAlertDivs();

    imgAEHelp.setAttribute("onclick", "showvideo('Alert System Overview', true);");
    imgAEHelp.style.visibility = "visible";

    if (id == 1) {
        showGeoAlertDiv();        
        var originalPoint = map.LatLongToPixel(map.GetCenter());
        var newx = originalPoint.x - 100;
        var newy = originalPoint.y - 100;
        pixel = new VEPixel(newx, newy);
        var newLatLon = map.PixelToLatLong(pixel);
        m_fenceLatUL = newLatLon.Latitude;
        m_fenceLonUL = newLatLon.Longitude;
        newx = newx + 200;
        newy = newy + 200;
        pixel = new VEPixel(newx, newy);
        newLatLon = map.PixelToLatLong(pixel);
        m_fenceLatLR = newLatLon.Latitude;
        m_fenceLonLR = newLatLon.Longitude;
        m_drawingFence = true;
        drawFence();
        SMSCarrier = document.getElementById("SMSPROVIDERGF");
        SMSCarrier.value = "txt.att.net";
        imgAEHelp.setAttribute("onclick", "showvideo('Alert Zone', true);");
        imgAEHelp.style.visibility = "visible";
    }
    if (id == 2) {
        alertPanel = document.getElementById("alertAddSpeed");
        alertPanel.style.visibility = "visible";
        alertPanel.style.display = "inline";
        SMSCarrier = document.getElementById("SMSPROVIDERSZ");
        SMSCarrier.value = "txt.att.net";
        imgAEHelp.setAttribute("onclick", "showvideo('Speed Alert', true);");
        imgAEHelp.style.visibility = "visible";
    }
    if (id == 3) {
        alertPanel = document.getElementById("alertRemove");
        alertPanel.style.visibility = "visible";
        alertPanel.style.display = "inline";

        var List = document.getElementById("ddlAlertList");
        if (List.selectedIndex != -1) {
            var table = document.getElementById("alertSelected");
            table.style.display = "inline";
            table.style.visibility = "visible";

            table = document.getElementById("noAlertSelected");
            table.style.display = "none";
            table.style.visibility = "hidden";
        }
        else {
            var table = document.getElementById("noAlertSelected");
            table.style.display = "inline";
            table.style.visibility = "visible";

            table = document.getElementById("alertSelected");
            table.style.display = "none";
            table.style.visibility = "hidden";
        }

        imgAEHelp.setAttribute("onclick", "showvideo('', false);");
        imgAEHelp.style.visibility = "hidden";
    }
    if (id == 4) {
        alertPanel = document.getElementById("alertEditPanic");
        alertPanel.style.visibility = "visible";
        alertPanel.style.display = "inline";
        SMSCarrier = document.getElementById("SMSPROVIDERSP");
        SMSCarrier.value = "txt.att.net";
        imgAEHelp.setAttribute("onclick", "showvideo('Panic Alert', true);");
        imgAEHelp.style.visibility = "visible";
    }
    if (id == 5) {
        alertPanel = document.getElementById("alertEditIgnition");
        alertPanel.style.visibility = "visible";
        alertPanel.style.display = "inline";
        SMSCarrier = document.getElementById("SMSPROVIDERIGN");
        SMSCarrier.value = "txt.att.net";
        zoneName = document.getElementById("ignName");  // changed zoneName to ignName rebekah 08/02/09
        startHour = document.getElementById("ISTRTH");
        startMin = document.getElementById("ISTRTM");
        endHour = document.getElementById("IENDH");
        endMin = document.getElementById("IENDM");
        IgnOn = document.getElementById("IGNON");
        IgnOff = document.getElementById("IGNOFF");
        smscheck = document.getElementById("SMSCHECKIGN");
        emailcheck = document.getElementById("EMAILCHECKIGN");
        smstarget = document.getElementById("SMSTARGETIGN");
        emailtarget = document.getElementById("EMAILTARGETIGN");
        zoneName.value = "";
        startHour.value = "00";
        startMin.value = "00";
        endHour.value = "23";
        endMin.value = "59";
        IgnOn.checked = true;
        IgnOff.checked = true;
        smscheck.checked = false;
        emailcheck.checked = false;
        smstarget.value = "";
        emailtarget.value = "";
        imgAEHelp.setAttribute("onclick", "showvideo('Ignition Alert', true);");
        imgAEHelp.style.visibility = "visible";
    }
    if (id == 6) {//Route Alert
        alertPanel = document.getElementById("alertAddRoute");
        alertPanel.style.visibility = "visible";
        alertPanel.style.display = "inline";
        document.getElementById("alertName").value = "";
        PopulateRouteDdl("ddlRouteName");
        PopulateVehicleList("ddlAdvRouteVehicles");
        ClearList("lbAdvRouteVehicleList");
        document.getElementById("RSTRTH").value = "00";
        document.getElementById("RSTRTM").value = "00";
        document.getElementById("RENDH").value = "23";
        document.getElementById("RENDM").value = "59";
        document.getElementById("RENTER").checked = true;
        document.getElementById("REXIT").checked = true;
        document.getElementById("radAFeet").checked = true;
        document.getElementById("SMSCHECKAR").checked = false;
        document.getElementById("SMSTARGETAR").value = "";
        document.getElementById("EMAILCHECKAR").checked = false;
        document.getElementById("EMAILTARGETAR").value = "";
        isAdvRouteVisible = true;
        imgAEHelp.setAttribute("onclick", "showvideo('Route Alert', true);");
        imgAEHelp.style.visibility = "visible";
    }
}

function hideAlertDivs() {
    var imgAEHelp = document.getElementById("AEHelp");
    alertPanel = document.getElementById("alertAddZone");
    alertPanel.style.visibility = "hidden";
    alertPanel.style.display = "none";
    alertPanel = document.getElementById("alertAddSpeed");
    alertPanel.style.visibility = "hidden";
    alertPanel.style.display = "none";
    alertPanel = document.getElementById("alertRemove");
    alertPanel.style.visibility = "hidden";
    alertPanel.style.display = "none";
    alertPanel = document.getElementById("alertEditPanic");
    alertPanel.style.visibility = "hidden";
    alertPanel.style.display = "none";
    alertPanel = document.getElementById("alertEditIgnition");
    alertPanel.style.visibility = "hidden";
    alertPanel.style.display = "none";
    alertPanel = document.getElementById("alertAddRoute");
    alertPanel.style.visibility = "hidden";
    alertPanel.style.display = "none";

    map.DeleteAllPolygons();
    if (fenceUL != null) {
        map.DeleteShape(fenceUL);
        fenceUL = null;
    }
    if (fenceLR != null) {
        map.DeleteShape(fenceLR);
        fenceLR = null;
    }
    m_drawingFence = false;
    if (m_drawingFence != null) {
        clearFence()
    }
    AdvRouteClearLayer();
    isAdvRouteVisible = false;
}

function showGeoAlertDiv() {
    hideAlertDivs();
    alertPanel = document.getElementById("alertAddZone");
    alertPanel.style.visibility = "visible";
    alertPanel.style.display = "inline";
    zoneName = document.getElementById("zoneName");
    startHour = document.getElementById("ZSTRTH");
    startMin = document.getElementById("ZSTRTM");
    endHour = document.getElementById("ZENDH");
    endMin = document.getElementById("ZENDM");
    zEnter = document.getElementById("ZENTER");
    zExit = document.getElementById("ZEXIT");
    smscheck = document.getElementById("SMSCHECKGF");
    emailcheck = document.getElementById("EMAILCHECKGF");
    smstarget = document.getElementById("SMSTARGETGF");
    emailtarget = document.getElementById("EMAILTARGETGF");
    zoneName.value = "";
    startHour.value = "00";
    startMin.value = "00";
    endHour.value = "23";
    endMin.value = "59";
    zEnter.checked = true;
    zExit.checked = true;
    smscheck.checked = false;
    emailcheck.checked = false;
    smstarget.value = "";
    emailtarget.value = "";
}

function setAlertType(id) {
    speedAlert = document.getElementById("speedAlert");
    gfAlert = document.getElementById("gfAlert");
    if (id == 1) {
        speedAlert.checked = false;
        gfAlert.checked = true;
    }
    if (id == 2) {
        speedAlert.checked = true;
        gfAlert.checked = false;
    }
}

function populateAlertList() {
    alertPanel = document.getElementById("alertRemove");
    alertPanel.style.visibility = "hidden";
    alertPanel.style.display = "none";
    //Feed.SAlrt(m_CurrentUser, populateAlertListCallback);

    var data = DAL.GetAlertList(m_CurrentUser);
    if (data.value != null) {
        m_AlertList = data.value;
        m_ddlAlerts.options.length = 0;
        for (var i = 0; i < m_AlertList.Rows.length; i++) {
            m_ddlAlerts.options[i] = new Option(m_AlertList.Rows[i].name, m_AlertList.Rows[i].id);
        }
    }
}



function fadein(divname) {
    var elemental = document.getElementById(divname);
    elemental.style.display = "block";
    elemental.style.visibility = "visible";
    if (divname != "divMessageWithX"
        && divname != "divBlankMsgWithX"
        && divname != "divAPIStatus"
        && divname != "divVehicleAction"
        && divname != "divColorPopOverLay"
        && divname != "divActionCompleted"
        && divname != "divCalculatingRoute"
        && divname != "divDemoNotification") {
        var CWPosition = getCookie(divname);
        if (CWPosition != null && CWPosition != "") {
            var winplace = CWPosition.split(':');
            elemental.style.top = winplace[0];
            elemental.style.left = winplace[1];
        }
        else {
            if (divname != "divMessageWithX"
                    && divname != "divBlankMsgWithX"
                    && divname != "divAPIStatus"
                    && divname != "divVehicleAction"
                    && divname != "divColorPopOverLay"
                    && divname != "divActionCompleted"
                    && divname != "divCalculatingRoute"
                    && divname != "divDemoNotification") {
                elemental.style.top = "10px";
                elemental.style.left = "300px";
            }
        }
    };
    new Effect.Appear(divname, { queue: 'end', from: 0, to: 1, duration: 0.30 });
    elemental = null;
    CWPosition = null;
    winplace = null;
}

function fadeout(divname) {
    var elemental = document.getElementById(divname);
    if (divname != "divMessageWithX"
        && divname != "divVehicleAction"
        && divname != "divColorPopOverLay"
        && divname != "divActionCompleted"
        && divname != "divCalculatingRoute"
        && divname != "divDemoNotification") {
        setCookie(divname, elemental.style.top + ':' + elemental.style.left);
    }
    new Effect.Fade(divname, { queue: 'end', from: 1, to: 0, duration: 0.30 });
    elemental = null;
}

function MinimizePlate() {
    var pa = document.getElementById('ControlPlate')
    var pb = document.getElementById('MiniPlate')
    pb.style.top = pa.style.top;
    pb.style.left = pa.style.left;
    new Effect.BlindUp('ControlPlate', { duration: 0.25 });
    new Effect.BlindDown('MiniPlate', { queue: 'end', duration: 0.37 });
}

function MaximizePlate() {
    var pb = document.getElementById('ControlPlate')
    var pa = document.getElementById('MiniPlate')
    pb.style.top = pa.style.top;
    pb.style.left = pa.style.left;
    new Effect.BlindUp('MiniPlate', { duration: 0.25 });
    new Effect.BlindDown('ControlPlate', { queue: 'end', duration: 0.37 });
}

function ShowLockedPlate() {
 
    document.getElementById("ControlPlate").style.visibility = "hidden";
    document.getElementById("MiniPlate").style.visibility = "hidden";
    
    // if the user has hidePlate in the queryString do not display control panel    
    if (queryStringParams["Plate"] != 0) {
        var pa = document.getElementById('ControlPlate')
        var pb = document.getElementById('LockedPlate')
        pb.style.top = pa.style.top;
        pb.style.left = pa.style.left;
        new Effect.BlindDown('LockedPlate', { queue: 'end', duration: 0.37 });
    }
}

function openOnlineReports() {
    if (m_bLoggedIn) {
        m_alertdiv = null;
        m_alertdiv = document.getElementById("divReportSelector");
        m_alertdiv.style.position = "absolute";
        fadein("divReportSelector");
    }
    else {
        AlertMessage("You must be logged in to use this feature.");
    }
}

function hideOnlineReports() {
    fadeout("divReportSelector");
}

function openAlerts() {
    if (m_bLoggedIn) {
        if (isAdvRouteVisible) {
            ShowAdvancedRoutePlanning(false,false);
        }
        CheckUncheckAllRoutes(false);
        ShowHideRouteList(false);
        m_alertdiv = null;
        m_alertdiv = document.getElementById("divAlertOverlay");
        m_alertdiv.style.position = "absolute";

        fadein("divAlertOverlay");
        populateAlertList();
        AlertEditorOpen = true;
    }
    else {
        AlertMessage("You must be logged in to use this feature.");
    }
}

function hideAlerts() {
    AlertEditorOpen = false;
    fadeout("divAlertOverlay")
    hideAlertDivs();
    ////MoveControlTray();
    viewAlertDetail(-1);
    MapFencesVisible = false;
}
//
//                                                  End of Alert Functions
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//                                           Function to change arrows on menu items



function loadIconSizes(result) {
    if (result == null) {
        Feed.SIcnFld(loadIconSizes);
    }
    else {
        iNames = new Array();
        iXCenter = new Array();
        iYCenter = new Array();
        // iHeight = new Array();
        //  iWidth = new Array();
        IconFolders = result.value;
        for (var i = 0; i < IconFolders.Rows.length; i++) {
            iNames[i] = IconFolders.Rows[i].iconFolder;
            iXCenter[i] = IconFolders.Rows[i].XCenter;
            iYCenter[i] = IconFolders.Rows[i].YCenter;
            //    iHeight[i] = IconFolders.Rows[i].Hi;
            //    iWidth[i] = IconFolders.Rows[i].Wide;
        }
    }
}

function isValidEmail(str) {
    var at = "@"
    var dot = "."
    var lat = str.indexOf(at)
    var lstr = str.length
    var ldot = str.indexOf(dot)
    if (str.indexOf(at) == -1) {
        return false
    }
    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
        return false
    }
    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
        return false
    }
    if (str.indexOf(at, (lat + 1)) != -1) {
        return false
    }
    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
        return false
    }
    if (str.indexOf(dot, (lat + 2)) == -1) {
        return false
    }
    if (str.indexOf(" ") != -1) {
        return false
    }
    return true
}

//function popCameras() {
//    var vehicleActionPain = document.getElementById("divVehicleAction");

//    var cameraPopLeft = 0;
//    var cameraPopTop = 0;

//    m_divROverlay = document.getElementById("divcameraPopOverLay");
//    m_divROverlay.style.marginTop = parseInt(0);
//    m_divROverlay.style.marginLeft = parseInt(1);
//    m_divROverlay.style.position = "absolute";
//    m_divROverlay.style.visibility = "visible";
//    m_divROverlay.style.width = "435px";
//    m_divROverlay.style.height = "400px";

//    //flip 
//    m_divROverlay.style.zIndex = 999;

//    //top
//    cameraPopTop = parseInt(vehicleActionPain.style.top);
//    cameraPopTop -= 148;
//    m_divROverlay.style.top = cameraPopTop.toString() + "px";

//    //left
//    cameraPopLeft = parseInt(vehicleActionPain.style.left);
//    cameraPopLeft += 160;
//    m_divROverlay.style.left = cameraPopLeft.toString() + "px";

//    showCameraPop();

//    chopacity("divCameraPopOverlay", 1, 85, 1200);
//}

//function showCameraPop() {
//    var cameraPopParent = document.getElementById("divCameraPopOverLay");
//    var cameraPop = document.getElementById("divCamera");

//    if (cameraPop != null) {
//        cameraPop.style.visibility = "visible"
//    }
//    if (cameraPopParent != null) {
//        cameraPopParent.style.visibility = "visible"
//    }
//    cameraPop.innerHTML = '<iframe name="content" src="http://demo.etcorp.com" width="435px" height="400px" scrolling="no"/>'
//}

//function hideCameraPop() {
//    var cameraPopParent = document.getElementById("divCameraPopOverLay");
//    var cameraPop = document.getElementById("divCamera");

//    if (cameraPop != null) {
//        cameraPop.style.visibility = "hidden"
//    }
//    if (cameraPopParent != null) {
//        cameraPopParent.style.visibility = "hidden"
//    }
//}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//                                           Function to show Google Map

//function popGoogleMap(lat, lon) {
//    var GoogleMapPop = document.getElementById("divGoogleMapPopOverLay");

//    var divGoogleMap = document.getElementById("divGoogleMap");
//    GoogleMapPop.style.marginTop = parseInt(0);
//    GoogleMapPop.style.marginLeft = parseInt(1);

//    if (GoogleMapPop != null) {
//        GoogleMapPop.style.visibility = "visible"
//    }
//    divGoogleMap.innerHTML = '<iframe name="content" src="http://maps.google.com/maps?f=q&hl=en&t=h&spn=0.004966,0.013218&q=' + lat + ',' + lon + '" width="1000px" height="800px" FRAMEBORDER=1 scrolling="no"/>'
//    chopacity("divGoogleMapPopOverlay", 1, 99, 1200);
//    hideVehicleActionPane();

////    var element = document.getElementById("framemaster");
////    if (element.up == null || element.down) {
////        //MoveControlTray();
////    }
//}

//function hideGoogleMapPop() {
//    var GoogleMapPopParent = document.getElementById("divGoogleMapPopOverLay");
//    if (GoogleMapPopParent != null) {
//        GoogleMapPopParent.style.visibility = "hidden"
//    }
//}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//                                           Function to show pre-defined user route

function showUserRoute() {

    Feed.SUsrRt(m_CurrentUser, showUserRouteCallback)
}

function showUserRouteCallback(result) {
    layer02 = new VEShapeLayer();
    map.AddShapeLayer(layer02);

    if (result.value != null) {
        var route = new Array();
        route = result.value;
        if (route.Rows.length > 1) {
            for (var i = 1; i < route.Rows.length; i++) {
                var points = new Array(
                    new VELatLong(route.Rows[i - 1].ur_Lat, route.Rows[i - 1].ur_Lon),
                    new VELatLong(route.Rows[i].ur_Lat, route.Rows[i].ur_Lon)
                );
                var vaptrail = new VEShape(VEShapeType.Polyline, points);
                vaptrail.SetLineColor(new VEColor(255, 0, 100, 0.6));
                vaptrail.SetLineWidth(4);
                vaptrail.HideIcon();
                layer02.AddShape(vaptrail);
            }
        }
    }
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                          Santa function called on 12/24 and 12/25
//
function showSanta() {
    getPageSize();
    if (santaDirection == 0) {
        santaLoc = 0;
        santaDirection = 1;
        santaYLoc = (Math.floor(Math.random() * (windowHeight - 80))) + 40;
    }
    var divSantaName = document.getElementById("divSantaName");
    var divSanta = document.getElementById("divSanta");
    var santa = document.getElementById("santa");
    santaLoc += (santaDirection * 8);
    if (santaDirection == 1) {
        if (santaLoc > (windowWidth - 130)) {
            santaYLoc = (Math.floor(Math.random() * (windowHeight - 80))) + 40;
            santaDirection = -1;
            santaLoc = windowWidth - 135;
            santa.src = "images/santaW.png";
            divSanta.style.visibility = "hidden";
            divSanta.style.display = "none";
            divSantaName.style.visibility = "hidden";
            divSantaName.style.display = "none";
            santaTimer = setTimeout("showSanta()", 180000);
            return null;
        }
    }
    else {
        if (santaLoc < 10) {
            santaDirection = 1;
            santaYLoc = (Math.floor(Math.random() * (windowHeight - 80))) + 40;
            santaLoc = 0;
            santa.src = "images/santaE.png";
            divSanta.style.visibility = "hidden";
            divSanta.style.display = "none";
            divSantaName.style.visibility = "hidden";
            divSantaName.style.display = "none";
            santaTimer = setTimeout("showSanta()", 180000);
            return null;
        }
    }
    divSanta.style.visibility = "visible";
    divSanta.style.display = "block";
    divSanta.style.left = santaLoc + "px";
    divSanta.style.top = (santaYLoc + 20) + "px";
    divSantaName.style.visibility = "visible";
    divSantaName.style.display = "block";
    divSantaName.style.left = (santaLoc + 40) + "px";
    divSantaName.style.top = santaYLoc + "px";
    santaTimer = setTimeout("showSanta()", 400);
}
//                                          End of Santa function
//
//
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//                           This area draws a vapor trail from history
//

function showVaporTrailRequest() {
    fadeout("divReportSelector");
    clearWeather();
    //  this stops the vehicle refresh while we are doing the report  
    clearTimeout(m_loadTimeout);
    clearInterval(m_loadInterval);
    m_divROverlay = null;
    m_divROverlay = document.getElementById("divVaporTrailOverlay");
    m_divROverlay.style.marginTop = parseInt(0);
    m_divROverlay.style.position = "absolute";
    m_divROverlay.style.top = "280px";
    m_divROverlay.style.left = "-220px";
    var btnPlayVaporTrail = document.getElementById("btnPlayVaporTrail");
    btnPlayVaporTrail.outerHTML = "<IMG id='btnPlayVaporTrail' alt='' onclick='startVaporTrail();' onmouseout=\"this.src='images/RptRequest0.gif'\" onmouseover=\"this.src='images/RptRequest1.gif'\" src='images/RptRequest0.gif'>";
    m_StatusLine = document.getElementById("txtVaporTrailStatus");
    m_StatusLine.innerHTML = "";
    fadein("divVaporTrailOverlay");
    //chopacity("divVaporTrailOverlay", 1, 85, 1200);
}

function hideVaporTrailPop() {
    VaporTrailStop = true;
    PlayingVaporTrail = false;

    clearMap();

    m_historicalData = null;
    //MoveControlTray();
    fadeout("divVaporTrailOverlay");
    //chopacity("divVaporTrailOverlay", 85, 0, 1200);
    // clear follow vehicle
    followThisVehicleOFF();
    
    // resetting the screen
    m_firstRetrieve = true;
    m_bOptimizeZoom = true;
    m_bCenterMap = true;
    
    var sessionID = document.getElementById("SESSIONKEY").getAttribute("value");
    m_loadTimeout = setTimeout("loadMarkers('" + sessionID + "');", 4000);
}

function startVaporTrail() {
    var btnPlayVaporTrail = document.getElementById("btnPlayVaporTrail");
    if (PlayingVaporTrail == true) {
        if (VaporTrailStop == true) {
            VaporTrailStop = false;
            btnPlayVaporTrail.outerHTML = "<IMG id='btnPlayVaporTrail' alt='' onclick='startVaporTrail();' onmouseout=\"this.src='images/Pause0.gif'\" onmouseover=\"this.src='images/Pause1.gif'\" src='images/Pause0.gif'>";
            setTimeout("drawVaporTrail()", 250);
        }
        else {
            VaporTrailStop = true;
            clearTimeout(VaporTrailTimeout);
            btnPlayVaporTrail.outerHTML = "<IMG id='btnPlayVaporTrail' alt='' onclick='startVaporTrail();' onmouseout=\"this.src='images/Resume0.gif'\" onmouseover=\"this.src='images/Resume1.gif'\" src='images/Resume0.gif'>";
        }
    }
    else {
        var startDate = document.getElementById("txtVTStartDate").value;
        if (startDate == null || startDate == '') {
            AlertMessage("Please select begin date.");
            return false;
        }

        var dtStartHr = document.getElementById("VTstartHours").value;
        var dtStartMin = document.getElementById("VTstartMins").value;
        var dtStartSec = document.getElementById("VTstartSec").value;
        var dtFromDate = new Date(startDate + ' ' + dtStartHr + ':' + dtStartMin + ':' + dtStartSec);
        var endDate = document.getElementById("txtVTEndDate").value;
        if (endDate == null || endDate == '') {
            AlertMessage("Please select end date.");
            return false;
        }
        var dtEndHr = document.getElementById("VTendHours").value;
        var dtEndMin = document.getElementById("VTendMins").value;
        var dtEndSec = document.getElementById("VTendSec").value;
        var dtStartDate = new Date(startDate);
        var dtEndDate = new Date(endDate);
        
        // adding date validation.  Start date/time must be less than end date/time
        if (dtStartDate <= dtEndDate) {
            // now checking time
            if (dtStartHr > dtEndHr || (dtStartHr == dtEndHr && dtStartMin > dtEndMin) || (dtStartHr == dtEndHr && dtStartMin == dtEndMin && dtStartSec > dtEndSec)) {
                AlertMessage("Start Time must be less than the End Time.");
                return false;
            }
        }
        else {
            AlertMessage("Start Date must be before or the same as the End Date.");
            return false;
        }
        
        
        Pto1 = 0;
        Pto2 = 0;
        Pto3 = 0;
        Pto4 = 0;
        ckPto = document.getElementById("ckVTPto1");
        if (ckPto.getAttribute("checked") == true) {
            Pto1 = 1;
        }
        ckPto = document.getElementById("ckVTPto2");
        if (ckPto.getAttribute("checked") == true) {
            Pto2 = 1;
        }
        ckPto = document.getElementById("ckVTPto3");
        if (ckPto.getAttribute("checked") == true) {
            Pto3 = 1;
        }
        ckPto = document.getElementById("ckVTPto4");
        if (ckPto.getAttribute("checked") == true) {
            Pto4 = 1;
        }

        //clean off the map  ClearMap prevents the vapor trail from attaching to the map
        //clearMap();
        if (map.GetShapeLayerCount() > 1) {
            map.DeleteAllShapeLayers();
        }
        //cleanMap(false);
        PlayingVaporTrail = true;
        VaporTrailStop = false;
        m_historicalData = null;
        Feed.SHstPlay(m_VTVehiclesList.value,
                                dtStartDate.getFullYear() + "/" + (dtStartDate.getMonth() + 1) + "/" + dtStartDate.getDate(),
                                dtStartHr + ":" + dtStartMin + ":" + dtStartSec,
                                dtEndDate.getFullYear() + "/" + (dtEndDate.getMonth() + 1) + "/" + dtEndDate.getDate(),
                                dtEndHr + ":" + dtEndMin + ":" + dtEndSec,
                                controlVaporTrail);
        openGeneralNotification("Loading data for vapor trail");
    }
}

function controlVaporTrail(result) {
    hideGeneralNotification();
    m_historicalData = result.value;

    if (m_historicalData == null ||  m_historicalData.Rows.length == 0) {
        AlertMessage("No history present for selected criteria.");
        PlayingVaporTrail = false;
        return;
    }
    var btnPlayVaporTrail = document.getElementById("btnPlayVaporTrail");
    btnPlayVaporTrail.outerHTML = "<IMG id='btnPlayVaporTrail' alt='' onclick='startVaporTrail();' onmouseout=\"this.src='images/Pause0.gif'\" onmouseover=\"this.src='images/Pause1.gif'\" src='images/Pause0.gif'>";
    VaporTrailPoints = new Array();
    historicalIndex = -1;
    layer01 = new VEShapeLayer();
    map.AddShapeLayer(layer01);
    VaporTrailStop = false;
    controlVaporTrail2();
}

function controlVaporTrail2() {
    clearTimeout(VaporTrailTimeout);
    if (VaporTrailStop == false) {
        historicalIndex++;
        if (historicalIndex < m_historicalData.Rows.length) {
            VaporTrailTimeout = setTimeout("drawVaporTrail()", 0);
        }
        else {
            var btnPlayVaporTrail = document.getElementById("btnPlayVaporTrail");
            btnPlayVaporTrail.outerHTML = "<IMG id='btnPlayVaporTrail' alt='' onclick='startVaporTrail();' onmouseout=\"this.src='images/RptRequest0.gif'\" onmouseover=\"this.src='images/RptRequest1.gif'\" src='images/RptRequest0.gif'>";
            m_StatusLine = document.getElementById("txtVaporTrailStatus");
            m_StatusLine.innerHTML = "";
        }
    }
}

function drawVaporTrail() {
    if (VaporTrailStop == false) {
        var lat = m_historicalData.Rows[historicalIndex].lat;
        var lon = m_historicalData.Rows[historicalIndex].lon;
        VaporTrailPoints[historicalIndex] = new VELatLong(lat * 1, lon * 1);
        if (historicalIndex > 0 && historicalIndex < m_historicalData.Rows.length) {
            var doTheDraw = false;
            var LS = m_historicalData.Rows[historicalIndex - 1].Switches;
            var SW = m_historicalData.Rows[historicalIndex].Switches;
            if (Pto1 != 1 && Pto2 != 1 && Pto3 != 1 && Pto4 != 1) {
                doTheDraw = true;
            }
            else if (Pto1 == 1 &&
                        (LS == 1 || LS == 3 || LS == 5 || LS == 7 || LS == 9 || LS == 11 || LS == 13 || LS == 15) &&
                        (SW == 1 || SW == 3 || SW == 5 || SW == 7 || SW == 9 || SW == 11 || SW == 13 || SW == 15)) {
                doTheDraw = true;
            }
            else if (Pto2 == 1 &&
                        (LS == 2 || LS == 3 || LS == 6 || LS == 7 || LS == 10 || LS == 11 || LS == 14 || LS == 15) &&
                        (SW == 2 || SW == 3 || SW == 6 || SW == 7 || SW == 10 || SW == 11 || SW == 14 || SW == 15)) {
                doTheDraw = true;
            }
            else if (Pto3 == 1 &&
                        (LS == 4 || LS == 5 || LS == 6 || LS == 7 || LS == 12 || LS == 13 || LS == 14 || LS == 15) &&
                        (SW == 4 || SW == 3 || SW == 6 || SW == 7 || SW == 12 || SW == 13 || SW == 14 || SW == 15)) {
                doTheDraw = true;
            }
            else if (Pto4 == 1 &&
                        (LS == 8 || LS == 9 || LS == 10 || LS == 11 || LS == 12 || LS == 13 || LS == 14 || LS == 15) &&
                        (SW == 8 || SW == 9 || SW == 10 || SW == 11 || SW == 12 || SW == 13 || SW == 14 || SW == 15)) {
                doTheDraw = true;
            }
            if (doTheDraw == true) {
                m_StatusLine = document.getElementById("txtVaporTrailStatus");
                var tempTime = m_historicalData.Rows[historicalIndex].timestamp;
                m_StatusLine.innerHTML = m_historicalData.Rows[historicalIndex].timestamp;
                var points = new Array(
                    new VELatLong(m_historicalData.Rows[historicalIndex - 1].lat, m_historicalData.Rows[historicalIndex - 1].lon),
                    new VELatLong(m_historicalData.Rows[historicalIndex].lat, m_historicalData.Rows[historicalIndex].lon)
                );
                var vaptrail = new VEShape(VEShapeType.Polyline, points);
                vaptrail.SetLineColor(new VEColor(255, 0, 100, 0.6));
                vaptrail.SetLineWidth(4);
                vaptrail.HideIcon();
                layer01.AddShape(vaptrail);
                map.SetMapView(VaporTrailPoints);
            }
        }
        VaporTrailTimeout = setTimeout("controlVaporTrail2()", 0);
    }
    else
        clearTimeout(VaporTrailTimeout);
}


/////////////////////////
// VIDEOS

function showvideo(name, value) {
    var divVideoOuter = document.getElementById('VideoOuter');
    var video = document.getElementById('Video1');

    // Videos are only available to users that are logged into registered accounts.
    if (!m_bLoggedIn || m_demoUser || demo2_user) {
        AlertMessage("A 'How-To' video on this specific topic</br> is available to registered users.");
        return;
    }
    
    if (value == true) {
        var baseURL = getBaseURL();
        video.innerHTML = '<div class="video-js-box"><video id="Video" name="video" class="video-js" width="640" height="360" controls preload>'
                        + '<source id="MP4" src="' + baseURL + 'Video/MP4/' + name + '.mp4" type="video/mp4; codecs=\'avc1.42E01E, mp4a.40.2\'" />'
                        + '<source id="WebM" src="' + baseURL + 'Video/WebM/' + name + '.webm" type="video/webm; codecs=\'vp8, vorbis\'" />'
                        + '<source id="OGV" src="' + baseURL + 'Video/OGV/' + name + '.ogv" type=\'video/ogg; codecs="theora, vorbis"\' />'
                        + '<object id="flash_fallback_1" class="vjs-flash-fallback" width="640" height="360" type="application/x-shockwave-flash" data="' + baseURL + 'mplay/flowplayer-3.2.5.swf">'
                        + '<param name="movie" value="' + baseURL + 'mplay/flowplayer-3.2.5.swf" />'
//                        + '<param name="allowfullscreen" value="true" />'
                        + '<param id="flashVars" name="flashvars" value=\'config={"playlist":[{"url": "' + baseURL + 'Video/MP4/' + name + '.mp4","autoPlay":false,"autoBuffering":true}]}\' />' 
                        + '</object>'
                        + '</video></div>';

        divVideoOuter.style.visibility = "visible";
        divVideoOuter.style.display = "block";
        VideoJS.setupAllWhenReady();
    }
    else { 
        divVideoOuter.style.visibility = "hidden";
        divVideoOuter.style.display = "none";
        video.innerHTML = "";
    }
    
}


function hideAccordionHelp(selected) {
    
    var arrHelp = document.getElementsByName("accordionHelp");
    var i = 0;
    var selectedId = selected + "Help";
    
    for (i=0; i < arrHelp.length; i++) {
        if (arrHelp[i].id != selectedId) {
            arrHelp[i].style.display = "none";
        }
        else {
            arrHelp[i].style.display = "inline";
        } 
    }
}



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//                           Geo Fences Functions
//

function showGeoFencesOnOff(d) {
    var showGeoFences = document.getElementById("ckShowGeoFences");
    if (showGeoFences.checked == false) {
        map.DeleteAllPolygons();
        m_showGeoFences = true;
    }
    else {
        m_showGeoFences = true;
        MapFencesVisible = false;
    }
}

function updateMapFences() {

    if (m_showGeoFences) {
        Feed.SGeoFnc(m_CurrentUser, updateMapFencesCallback);
    }
}

function updateMapFencesCallback(data) {
    map.DeleteAllPolygons();
    if (data != null) {
        if (data.value != null) {
            var dt = data.value;
            var PId = 0;
            for (i = 0; i < dt.Rows.length; i++) {
                var latlng = dt.Rows[i].bbl;
                ltln = latlng.split(",");
                m_fenceLatUL = ltln[0];
                m_fenceLonUL = ltln[1];
                m_fenceLatLR = ltln[2];
                m_fenceLonLR = ltln[3];
                var points = new Array(
                   new VELatLong(m_fenceLatUL, m_fenceLonUL),
                   new VELatLong(m_fenceLatUL, m_fenceLonLR),
                   new VELatLong(m_fenceLatLR, m_fenceLonLR),
                   new VELatLong(m_fenceLatLR, m_fenceLonUL),
                   new VELatLong(m_fenceLatUL, m_fenceLonUL)
                );
                PId++;
                poly = new VEPolygon(PId, points);
                poly.SetOutlineWidth(1);
                poly.SetOutlineColor(new VEColor(0, 0, 0, 1.0));
                poly.SetFillColor(new VEColor(255, 128, 128, 0.5));
                map.AddPolygon(poly);
            }
        }
    }
    MapFencesVisible = true;
}

function setCookie(c_name, value) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 9999);
    document.cookie = c_name + "=" + escape(value) + ";expires=" + exdate.toGMTString();
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function removeCookie(c_name, value) {
    var exdate = new Date();
    exdate.setDate(datetime());
    document.cookie = c_name + "=" + escape(value) + ";expires=" + exdate.toGMTString();
}

// Example of how to check a cookie :
//--------------------------------------------------------
//function checkCookie() {
//    username = getCookie('username');
//    if (username != null && username != "") {
//        alert('Welcome back ' + username + '!');
//    }
//    else {
//        username = prompt('Please enter your name:', "");
//        if (username != null && username != "") {
//            setCookie('username', username, 365);
//        }
//    }
//}

function trim(str) {
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function convertToDegree(coordinate) {
    var corAbs = Math.abs(Math.round(coordinate * 1000000.));
    var tmpCor = corAbs / 1000000;
    var signCor = coordinate / Math.abs(coordinate);


    return ((Math.floor(tmpCor) * signCor) + '&deg; ' +
             Math.floor(((tmpCor) - Math.floor(tmpCor)) * 60) + '\' ' + 
            (Math.floor(((((tmpCor) - Math.floor(tmpCor)) * 60) - Math.floor(((tmpCor) - Math.floor(tmpCor)) * 60)) * 100000) * 60 / 100000) + '&quot;');

}

function printContent(id) {
    str = document.getElementById(id).innerHTML;
    newwin = window.open('', 'printwin', 'left=100,top=100,width=400,height=400');
    newwin.document.write('<HTML>\n<HEAD>\n');
    newwin.document.write('<TITLE>Print Page</TITLE>\n');
    newwin.document.write('<script>\n');
    newwin.document.write('function chkstate(){\n');
    newwin.document.write('if(document.readyState=="complete"){\n');
    newwin.document.write('window.close()\n');
    newwin.document.write('}\n');
    newwin.document.write('else{\n');
    newwin.document.write('setTimeout("chkstate()",2000)\n');
    newwin.document.write('}\n');
    newwin.document.write('}\n');
    newwin.document.write('function print_win(){\n');
    newwin.document.write('window.print();\n');
    newwin.document.write('chkstate();\n');
    newwin.document.write('}\n');
    newwin.document.write('<\/script>\n');
    newwin.document.write('</HEAD>\n');
    newwin.document.write('<BODY onload="print_win()">\n');
    newwin.document.write(str);
    newwin.document.write('</BODY>\n');
    newwin.document.write('</HTML>\n');
    newwin.document.close();
}

function printSpecial() {
    if (document.getElementById != null) {
        var html = '<HTML>\n<HEAD>\n';

        if (document.getElementsByTagName != null) {
            var headTags = document.getElementsByTagName("head");
            if (headTags.length > 0)
                html += headTags[0].innerHTML;
        }

        html += '\n</HE' + 'AD>\n<BODY>\n';

        var printReadyElem = document.getElementById("printReady");

        if (printReadyElem != null) {
            html += printReadyElem.innerHTML;
        }
        else {
            alert("Could not find the printReady section in the HTML");
            return;
        }

        html += '\n</BO' + 'DY>\n</HT' + 'ML>';

        var printWin = window.open("", "printSpecial");
        printWin.document.open();
        printWin.document.write(html);
        printWin.document.close();
        if (gAutoPrint)
            printWin.print();
    }
    else {
        alert("Sorry, the print ready feature is only available in modern browsers.");
    }
}

// open an excel window
//var newwindow = window.open("url of .xls", "window2", "");
//var pause = 0;
//var wdDialogFileOpen = 80;
//var wdApp = new ActiveXObject("Word.Application");
//var dialog = wdApp.Dialogs(wdDialogFileOpen); 
//var button = dialog.Show(pause);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                              BEGIN COLOR 
//
function popcolortable(fieldID) {
    var parentTextBox = document.getElementById(fieldID);
    var currentColor = parentTextBox.value

    var colors = new Array("#000000", "#000033", "#000066", "#000099", "#0000CC", "#0000FF", "#330000", "#330033", "#330066", "#330099", "#3300CC",
							"#3300FF", "#660000", "#660033", "#660066", "#660099", "#6600CC", "#6600FF", "#990000", "#990033", "#990066", "#990099",
							"#9900CC", "#9900FF", "#CC0000", "#CC0033", "#CC0066", "#CC0099", "#CC00CC", "#CC00FF", "#FF0000", "#FF0033", "#FF0066",
							"#FF0099", "#FF00CC", "#FF00FF", "#003300", "#003333", "#003366", "#003399", "#0033CC", "#0033FF", "#333300", "#333333",
							"#333366", "#333399", "#3333CC", "#3333FF", "#663300", "#663333", "#663366", "#663399", "#6633CC", "#6633FF", "#993300",
							"#993333", "#993366", "#993399", "#9933CC", "#9933FF", "#CC3300", "#CC3333", "#CC3366", "#CC3399", "#CC33CC", "#CC33FF",
							"#FF3300", "#FF3333", "#FF3366", "#FF3399", "#FF33CC", "#FF33FF", "#006600", "#006633", "#006666", "#006699", "#0066CC",
							"#0066FF", "#336600", "#336633", "#336666", "#336699", "#3366CC", "#3366FF", "#666600", "#666633", "#666666", "#666699",
							"#6666CC", "#6666FF", "#996600", "#996633", "#996666", "#996699", "#9966CC", "#9966FF", "#CC6600", "#CC6633", "#CC6666",
							"#CC6699", "#CC66CC", "#CC66FF", "#FF6600", "#FF6633", "#FF6666", "#FF6699", "#FF66CC", "#FF66FF", "#009900", "#009933",
							"#009966", "#009999", "#0099CC", "#0099FF", "#339900", "#339933", "#339966", "#339999", "#3399CC", "#3399FF", "#669900",
							"#669933", "#669966", "#669999", "#6699CC", "#6699FF", "#999900", "#999933", "#999966", "#999999", "#9999CC", "#9999FF",
							"#CC9900", "#CC9933", "#CC9966", "#CC9999", "#CC99CC", "#CC99FF", "#FF9900", "#FF9933", "#FF9966", "#FF9999", "#FF99CC",
							"#FF99FF", "#00CC00", "#00CC33", "#00CC66", "#00CC99", "#00CCCC", "#00CCFF", "#33CC00", "#33CC33", "#33CC66", "#33CC99",
							"#33CCCC", "#33CCFF", "#66CC00", "#66CC33", "#66CC66", "#66CC99", "#66CCCC", "#66CCFF", "#99CC00", "#99CC33", "#99CC66",
							"#99CC99", "#99CCCC", "#99CCFF", "#CCCC00", "#CCCC33", "#CCCC66", "#CCCC99", "#CCCCCC", "#CCCCFF", "#FFCC00", "#FFCC33",
							"#FFCC66", "#FFCC99", "#FFCCCC", "#FFCCFF", "#00FF00", "#00FF33", "#00FF66", "#00FF99", "#00FFCC", "#00FFFF", "#33FF00",
							"#33FF33", "#33FF66", "#33FF99", "#33FFCC", "#33FFFF", "#66FF00", "#66FF33", "#66FF66", "#66FF99", "#66FFCC", "#66FFFF",
							"#99FF00", "#99FF33", "#99FF66", "#99FF99", "#99FFCC", "#99FFFF", "#CCFF00", "#CCFF33", "#CCFF66", "#CCFF99", "#CCFFCC",
							"#CCFFFF", "#FFFF00", "#FFFF33", "#FFFF66", "#FFFF99", "#FFFFCC", "#FFFFFF");

    var total = colors.length;
    var width = 18;
    var cp_contents = "";

    //cp_contents += "<HTML><HEAD><TITLE>Select Color</TITLE></HEAD>";
    //cp_contents += "<BODY MARGINWIDTH=0 MARGINHEIGHT=0 LEFTMARGIN=0 TOPMARGIN=0><CENTER>";
    cp_contents += "<TABLE BORDER=0 CELLSPACING=1 CELLPADDING=1>";

    var use_highlight = (document.getElementById || document.all) ? true : false;

    for (var i = 0; i < total; i++) {
        if ((i % width) == 0) {
            cp_contents += "<TR>";
        }

        cp_contents += '<TD BGCOLOR="' + colors[i] + '"><FONT SIZE="-3"><A HREF=javaScript:ColorPickerSelected("' + colors[i] + '","' + parentTextBox.id + '"); STYLE="text-decoration:none;">&nbsp;&nbsp;&nbsp;</A></FONT></TD>';

        if (((i + 1) >= total) || (((i + 1) % width) == 0)) {
            cp_contents += "</TR>";
        }
    }

    // If the browser supports dynamically changing TD cells, add the fancy stuff
    if (document.getElementById) {
        var width1 = Math.floor(width / 2);
        var width2 = width = width1;
        cp_contents += "<TR><TD COLSPAN='" + width1 + "' style='background-color:" + currentColor + "' id='colorPickerSelectedColor'>&nbsp;</TD><TD style='background-color:White;' COLSPAN='" + width2 + "' ALIGN='CENTER' id='colorPickerSelectedColorValue'>" + currentColor + "</TD></TR>";
    }

    cp_contents += "</TABLE>";
    //cp_contents += "</CENTER></BODY></HTML>";

    thisDiv = document.getElementById("divColours");
    thisDiv.innerHTML = cp_contents;

}

function ColorPickerSelected(color, fieldname) {
    //get parents    
    var parentTextBox = document.getElementById(fieldname);
    var colorPickerSelectedColor = document.getElementById("colorPickerSelectedColor");
    var colorPickerSelectedColorValue = document.getElementById("colorPickerSelectedColorValue");

    //set display
    colorPickerSelectedColorValue.innerText = color
    colorPickerSelectedColor.style.backgroundColor = color;

    //set parent
    parentTextBox.value = color.substring(1, 7);
    parentTextBox.onchange();
}

function Colours(thisDivID) {
    var thisDiv = document.getElementById(thisDivID);
    var colorPopLeft = 0;
    var colorPopTop = 0;

    m_divROverlay = document.getElementById("divColorPopOverLay");
    m_divROverlay.style.marginTop = parseInt(0);
    m_divROverlay.style.marginLeft = parseInt(1);
    //flip 
    m_divROverlay.style.zIndex = 999;
    //top
    colorPopTop = parseInt(thisDiv.style.top);
    colorPopTop -= 148;
    m_divROverlay.style.top = colorPopTop.toString() + "px";
    //left
    colorPopLeft = parseInt(thisDiv.style.left);
    colorPopLeft += 160;
    m_divROverlay.style.left = colorPopLeft.toString() + "px";
    showColorPop();
}

function showColorPop() {
    fadein("divColorPopOverLay");
}

function hideColorPop() {
    fadeout("divColorPopOverLay");
}
//
//                                                            END COLOR
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                     BEGIN GENERIC FUNCTIONS
//  These functions are used by several different areas.

function scrollDiv(divName, direction) {
    switch (direction) {
        case "UP":
            sadown = false;
            saup = true;
            sUp(divName);
            break;

        case "DOWN":
            saup = false;
            sadown = true;
            sDown(divName);
            break;
    } // end switch
}

function scrollUpmup(divName) {
    saup = false;
}

function scrollDownmup(divName) {
    sadown = false;
}

function sUp(divName) {
    if (saup == true) {
        var dsr = document.getElementById(divName);
        var ty = parseInt(dsr.style.top);
        if (ty < parseInt(dsr.style.height)) {
            ty = ty - 2 + "px"; dsr.style.top = ty;
            setTimeout("sUp('" + dsr.id + "')", 1);
        }
        else {
            // If scrolled to the bottom of the list stop scrolling
            saup = false;
        }

    }
}

function sDown(divName) {
    if (sadown == true) {
        var dsr = document.getElementById(divName);
        var ty = parseInt(dsr.style.top);
        if (ty < 0) {
            ty = ty + 2 + "px"; dsr.style.top = ty;
            setTimeout("sDown('" + dsr.id + "')", 1);
        }
        else {
            sadown = false;
        }
    }
}
//
//                                                            END GENERIC
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* Widget Animation */
var widget_delta = 0.0;
var widget_speed = 0.075;
var widget_friction = 0.005;
var widget_rt_epsilon = 800;
var widget_rt_kappa = 0;
var widget_rt_delta = 25;

function widget_delete_toggle(screen_x,screen_y) {
    deleteWidget = document.getElementById('w_delete');
    if (null != deleteWidget) {
        if (deleteWidget.getAttribute('class') == 'widget_delete') {
            widget_delta = 0.0;
            widget_speed = 0.075;
            deleteWidget.setAttribute('class', 'widget_delete_show');
            widget_delete_expand(screen_x, screen_y);
        }
        else {
            deleteWidget.setAttribute('class', 'widget_delete');
        }
    }
}

function widget_delete_expand(screen_center_x,screen_center_y) {
    
    deleteWidget = document.getElementById('w_delete');

    if (null != deleteWidget) {

        widget_size = (widget_delta * 64);
        origin_x = screen_center_x - (widget_size / 2);
        origin_y = screen_center_y - (widget_size / 2);

        deleteWidget.style.left = origin_x + "px";
        deleteWidget.style.top = origin_y + "px";
        
        deleteWidget.style.width = widget_size + "px";
        deleteWidget.style.height = widget_size + "px";

        widget_delta += widget_speed;
        widget_speed -= widget_friction;

        if (widget_delta >= 1.0) {
            widget_speed = -0.075;
            widget_delta = 1.0;
        }

        if (widget_delta < 0) {
            widget_speed = 0.075;
            widget_delta = 0.0;
        }

        widget_rt_kappa += widget_rt_delta;

        if (widget_rt_kappa >= widget_rt_epsilon) {
            widget_rt_kappa = 0;
            widget_delete_toggle();
        }
        else {
            setTimeout('widget_delete_expand(' + screen_center_x + ',' + screen_center_y + ')', widget_rt_delta);
        }
    }
}

