﻿/// <reference path="../VeJavaScriptIntellisenseHelper.js" />
/*
global.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.
*/

var map = null;//uncomment for production
//var map = new VEMap();//uncomment at design time to enable intellisense

var full_address_marker_layer = null;
var address_marker_layer = null;
var lastMaximumId = -1;
var address_layer_update_signal = false;
var queue_address_dt = null;
var trigger_address_update = false;

var disable_pto_alerts = false;

var servicecall_viewmode = 0;

var m_bLoggedIn = false;

var vehicleList = null;
var MessageFromDriverTimer = null;
var DriverMessageNumber = 0;
var DriverGMessageNumber = 0;
var EightThousandPresent = false;
var m_AddressList = null;
var demo2_user = false;
var ChatDemo = false;

var requestedHeight = 0;
var requestedWidth = 0;

var dummyUser = null;
var dummyPwd = null;

var TheBrowser = null;

var ControlPanelLockout = false;
var AddressMarkersVisible = false;
var dragShape = null;
var dragShapetitle = null;

var TOOLTIP_OFFSET_X = -10;
var TOOLTIP_OFFSET_Y = -8;
var TOOLTIP_OFFSET_X2 = -5;
var TOOLTIP_OFFSET_Y2 = -12;
var INFOPANE_OFFSET_X = 0;
var INFOPANE_OFFSET_Y = 0;
var m_firstRetrieve = true;

var e;

// Santa Clause fields
var santaTimer = null;
var santaDirection = 0;
var santaLoc = 0;
var santaYLoc = null;

// Hold fields for Reports
var rpt_reportName = null;
var rpt_VehicleID = null;
var rpt_fromDate = null;
var rpt_toDate = null;
var rpt_History = new Array();
var rpt_historySub = null;
var rpt_Timeout = null;
var rpt_Report =null;
var rpt_lastVehicleId = null;
var rpt_lastLat = null;
var rpt_lastLon = null;
var rpt_lastOri = null;
var rpt_lastVel = null;
var rpt_lastTime = null;
var rpt_precision = null;
var rpt_precisionType = null;
var rpt_linesPrinted = null;
var rpt_miles = null;
var rpt_idling = null;
var rpt_lastSwitches = null;
var rpt_stopped = null;
var rpt_lastStopTime = null;
var rpt_lastStartTime = null;
var rpt_totRunTime = null;
var rpt_totStopTime = null;
var rpt_IgnitionMovement = null;
var rpt_vehNames = new Array();
var offlineReportType = null;
var Pto1 = 0;
var Pto2 = 0;
var Pto3 = 0;
var Pto4 = 0;
var rpt_GraphArray1 = new Array();
var rpt_GraphArray2 = new Array();
var rpt_FirstArray = null;
var rpt_chartTitle = null;
//var rpt_GraphSub1 = 0;
//var rpt_GraphSub2 = 0;

// Routing 
var locs = null;
var latlonlocs = null;
var rSub1 = 0;
var rLat = null;
var rLon = null;

//Viewing Type 
var m_groupView = false;
var m_StartupView = "";

//HISTORICAL PLAYBACK
var historicalPlaybackTimer = null;
var m_historicalMarker = null;
var m_historicalData = null;
var historicalIndex = 0;
var current_hindex = 0;
var DEFAULT_HISTORICAL_TIMEOUT = 3000;
var historicalTimeout = DEFAULT_HISTORICAL_TIMEOUT;
var historicalPlaybackDirection = 1; //1 forward, -1 backwards
var historicalDateChanged = false;
var historicalCenterCount = 10;
var historicalZoomCount = 0;
var historyIconFolder = null;
var historyXCenter = null;
var historyYCenter = null;
var historyTagOffset = null;
var historyWidth = null;
var historyHeight = null;
var historyLastDirection = 0;

var VaporTrailPoints = new Array;
var VaporTrailStop = false;
var PlayingVaporTrail = false;
var VaporTrailTimeout = null;

//VEHICLE GROUP EDITOR
var m_ddlVehicleGroupEditor = null;
var m_vehicleGroups = null;

//VEHICLE DRIVER EDITOR
var m_ddlVehicleDriversEditor = null;
var m_vehicleDrivers = null;

//var glbCurrentMarkerInfo = null;
var currentpanicentries = null;

//Activity Tray
var ActivityTray = false;
var Activitytop = 0;
var Activitybase = 0;

var ActWindowHeader = "<img alt='' src='images/ActivityPlateDown.png' id='ActivityPanel' onclick='MoveActivityTray();' style='visibility: visible;'/>" +
                        "<div style='overflow: hidden; background-color:transparent; opacity: 0.90; filter: alpha(opacity=90); position: absolute; width: 640px; height: 18px; left: 3px; top: 25px; visibility: visible; valign: top;' id='ActivHeader'>" +
                           "<table id='jsGrid1' bgcolor='transparent' cellpadding='2px' cellspacing='0px' valign='top'>" +
                            "<tr class='data hdr'>" +
                              "<td><b>&nbsp;Date/Time&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></td>" +
                              "<td><b>&nbsp;VehicleID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></td>" +
	                          "<td><b>&nbsp;&nbsp;&nbsp;Latitude&nbsp;&nbsp;&nbsp;</b></td>" +
	                          "<td><b>&nbsp;&nbsp;&nbsp;Longitude&nbsp;&nbsp;</b></td>" +
	                          "<td><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Speed&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></td>" +
	                          "<td><b>Heading</b></td>" +
	                          "<td><b>Satellites</b></td>" +
	                          "<td><b>Ignition</b></td>" +
	                          "<td><b>Panic</b></td>" +
	                          "<td><b>Aux 1</b></td>" +
	                          "<td><b>Aux 2</b></td>" +
	                        "</tr></table>" +
	                    "</div>" +
	                    "<div style='overflow: hidden; background-color:transparent; opacity: 0.90; filter: alpha(opacity=90); position: absolute; width: 639px; height: 268px; left: 6px; top: 40px; visibility: visible;' id='ActivityMask'>" +
                            "<div style='overflow: hidden; background-color:transparent; opacity: 0.90; filter: alpha(opacity=90); position: absolute; width: 640px; height: 510px; left: 0px; top: 0px; visibility: visible;' id='ActScroller'>" +
                        "</div></div>";

var ActivityHeader = "<table id='jsGrid' bgcolor='transparent' cellpadding='2px' cellspacing='0px' valign='top'>" +
                    "<tr class='data hdr'>" +
                      "<td><b>&nbsp;Date/Time&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></td>" +
                      "<td><b>&nbsp;VehicleID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></td>" +
	                  "<td><b>&nbsp;&nbsp;&nbsp;Latitude&nbsp;&nbsp;&nbsp;</b></td>" +
	                  "<td><b>&nbsp;&nbsp;&nbsp;Longitude&nbsp;&nbsp;</b></td>" +
	                  "<td><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Speed&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></td>" +
	                  "<td><b>Heading</b></td>" +
	                  "<td><b>Satellites</b></td>" +
	                  "<td><b>Ignition</b></td>" +
	                  "<td><b>Panic</b></td>" +
	                  "<td><b>Aux 1</b></td>" +
	                  "<td><b>Aux 2</b></td>" +
	                "</tr>";
var ActivityOut = ActivityHeader + "</table>";
var accenture = "";
var rowtoggle;
var ActivityContent = new Array;
var ActivityCount = 0;
var ssdown = false;
var ssup = false;

// Drawing alert zone fields
var fenceUL = null;
var fenceLR = null;
var m_drawingFence = false;
var m_fenceLatUL = 0;
var m_fenceLonUL = 0;
var m_fenceLatLR = 0;
var m_fenceLonLR = 0;
//var MapFences = new Array();
var MapFencesVisible = false;
var AlertEditorOpen = false;
var m_showGeoFences = false;

//MISC
//var m_bLoggedIn = false;
var m_bResizing = false;
var m_bRepeat = false;
var m_bViewHistory = false;
var m_strDateTime;
var m_gMap;
var m_bOptimizeZoom = true;
var m_bOptimizeZoomSet = false;
var m_bCenterMap = false;
var m_showTraffic = false;
var t_showTraffic = null;
var m_divMap;
var m_lDivHeight = 0;
var m_lDivWidth = 0;

//Drop-down Vehicle lists
var m_ddlVehicles = null;
var m_AlertVehicleList;
var m_ZoneVehicleList;
var m_OLRVehiclesList;
var m_VTVehiclesList;
var m_IGNVehicleList;

var m_ddlCannery;
var m_CanneryList;
var m_ddlAlerts;
var MarkerNames = new Array();

var m_divROverlay;
var object = new Array();
var zoomvalue = 0;
var m_gMarkers = new Array();
var windowWidth;
var windowHeight;
var m_TriggerMapControl = false;
var cached_loader;
//var m_drawingFence = false;
var m_CurrentUser = null;
var m_AlertList;
var m_demoUser = false;
var m_SelectPoint = false;
var queryStringParams = new Array();
var m_AddressControl = null;
var m_AddressType = null;
var m_setValue = false;
var m_setHistoryValue = false;
var m_loadTimeout = null;
var m_loadInterval = null;
var m_maxHistoricalCenterCount = 10;

// Chat 
var ChatIsOpen = false;
var m_checkMesagesTimeout = null;
var ChatMsgNo = 0;
var ChatLines = new Array();
var ChatWaitTime = 10000;

var clickedOnSerial = null;

var cars = new Array();
var lastCars = new Array();
var MapAddresspins = new Array();
var PinIds = new Array();
var addrInfoBox = new Array();
var addrInfoIds = new Array();
var addrInfoBoxTimer = null;

var IconFolders = new Array();
var IconFolderToUse = null;
var iNames = new Array();
var iXcenter = new Array();
var iYCenter = new Array();
var iHeight = new Array();
var iWidth = new Array();

var carPins = new Array();
//var carPanics = new Array();
var carInPanic = false;
var maxCarsInPanic = 0;
var lastClickedBox = 0;
var vehicleToFollow = null;
var t_followVehicle = null;

var NewAddressMarker = "New Address Marker";
var NewAddressMarkerPresent = false;
var xoffset = 0;
var yoffset = 0;

var DestinationMarker = "Destination Marker";
var DestinationPinPresent = false;

var historyCarPin = null;
var historyNameTag = null;
var historyInfoBox = null;

// Global API Open Call fields
var APIResultArray = new Array();
var APIResultIds = new Array();
var APIResultInfo = new Array();
var APIAddressPins = new Array();
var prevAPIResultArray = new Array();
var APIStatus = new Array();
var APICallsTimer = null;

var FindResultArray = new Array();
var ResultIds = new Array();
var ResultInfo = new Array();

var dragObject = null;
var dragStartX = 0;
var dragStartY = 0;
var dragClickStartX = 0;
var dragClickStartY = 0;
var dragging = false;
var wereloadingmarkers = false;
var safariPadding = "25px 0px 0px 0px";
var novdatapresent = false;
var CanneryPost = "";
var dtime = ""; // constantly updated date/time in uniform cross-browser format
var m_loadMarkerRunning = false;
//var cnavunitlist = "";

//Calculate and store user's current GMT offset
var GMTOffset = (new Date()).getTimezoneOffset() / 60;

//Weather
var weatherType = null;
var weatherTimes = new Array();
var weatherTimesDisplay = new Array();
var currentFrame = 7;
var newestFrame = 7;
var weatherFrameInterval = null;
var weatherUpdateInterval = null;
var currentWeatherServerNumber = 0;
var isWeather = false;
var isWeatherLooping = false;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                          isNumeric Function
function isNumeric(value) {
    validchars = "1234567890";
    for (i = 0; i < value.length; i++) {
        if (validchars.match(value.charAt(i)) == null)
            return false;
    }
    return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//                           String-Builder Function because IE is so slow in string handling
//

// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder() {
    this.strings = new Array("");
}

// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value) {
    if (value) {
        this.strings.push(value);
    }
}

// Clears the string buffer
StringBuilder.prototype.clear = function () {
    this.strings.length = 1;
}

// Converts this instance to a String.
StringBuilder.prototype.toString = function () {
    return this.strings.join("");
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//                           String functions
//
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

String.IsNullOrEmpty = function (value) {
    var isNullOrEmpty = true;
    if (value) {
        if (typeof (value) == 'string') {
            if (trim(value," ").length > 0)
                isNullOrEmpty = false;
        }
    }
    return isNullOrEmpty;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function PopulateVehicleArray() {
    if (m_CurrentUser != null && m_CurrentUser != '' && m_CurrentUser != -1) {
        var response;
        response = DAL.GetVehicleIDBySession(m_CurrentUser);
        vehicleList = response.value;
    }
}
function PopulateVehicleList(listID) {
    ClearList(listID);
    var list = document.getElementById(listID);
    if (vehicleList == null) {
        PopulateVehicleArray();
        if (vehicleList == null) { return; }
    }
    list[0] = new Option("All Vehicles", "-1");
    for (var i = 0; i < vehicleList.Rows.length; i++) {
        list.options[i + 1] = new Option(vehicleList.Rows[i].Name, vehicleList.Rows[i].Serial);
    }
}


//Find value in the list and mark as the selected index.
function SelectIndexOfValue(listID, value) {
    var list = document.getElementById(listID);
    for (var i = 0; i < list.options.length; i++) {
        if (list.options[i].value == value) {
            list.selectedIndex = i;
            break;
        }
    }
}
//Find display text in the list and mark as the selected index.
function SelectIndexOfText(listID, text) {
    var list = document.getElementById(listID);
    for (var i = 0; i < list.options.length; i++) {
        if (list.options[i].text == text) {
            var value = list.options[i].value;
            list.selectedIndex = i;
            return value;
        }
    }
}
//Get Selected value from ddl
function GetSelectedValue(list) {
    if (typeof (list) == "string")
        list = document.getElementById(list);
    return list.options[list.selectedIndex].value;
}
function GetSelectedInt(list) {
    var val = GetSelectedValue(list);
    if (isNaN(val)) { return null; }
    return parseInt(val, 10);
}
//Get Selected text from ddl
function GetSelectedText(list) {
    if (typeof (list) == "string")
        list = document.getElementById(list);
    return list.options[list.selectedIndex].text;
}
//Add selected item from a list with ID=listFromID to a list with ID=listTo, if list does not contain item.
//Adds all items if the value of the option at the first selected index is -1.
function AddItemToList(listFromID, listToID) {
    var listFrom = document.getElementById(listFromID);
    var listTo = document.getElementById(listToID);

    if (listFrom == null) { return; }
    if (listFrom.selectedIndex == -1) { return; }

    if (listFrom.options[listFrom.selectedIndex].value != -1) {
        if (listTo != null) {
            for (i = 0; i < listTo.length; i++) {
                if (listTo.options[i].value == listFrom.options[listFrom.selectedIndex].value) {
                    return;
                }
            }
            listTo.options[listTo.length] = new Option(listFrom.options[listFrom.selectedIndex].text, listFrom.options[listFrom.selectedIndex].value);
        }
    }
    else {
        listTo.options.length = 0;
        for (i = 1; i < listFrom.options.length; i++) {
            listTo.options[listTo.options.length] = new Option(listFrom.options[i].text, listFrom.options[i].value);
        }
    }
}
//Add new option to list at specified index or at the end if index is null or negative.
function ListInsertItem(listID, option, index) {
    var list = document.getElementById(listID);
    if (index == null || index < 1 || list.length == index) {
        list.options[list.length] = option;
    } else {
        var elOptOld = list.options[index];
        try {
            list.add(option, elOptOld); // standards compliant; doesn't work in IE
        }
        catch (ex) {
            list.add(option, index); // IE only
        }
    }
}
//Removes the selected item from the list. If value=true the list is cleared.
function RemoveItemFromList(listID, value) {
    var list = document.getElementById(listID);
    if (list == null) { return; }
    if (value) {
        //Clear list
        list.options.length = 0;

    } else {
        //Remove selected item
        if (list.selectedIndex != -1) {
            list.remove(list.selectedIndex);
        }
    }
}
//Removes all items from the list.
function ClearList(listID) {
    var list = document.getElementById(listID);
    list.options.length = 0;
}
//Set selected on all items of the list to false.
function ClearSelected(listID) {
    var list = document.getElementById(listID);
    if (list == null) { return; }
    while(list.selectedIndex != -1) { 
        list.options[list.selectedIndex].selected = false;
    }
}
//Set selected on all item of the list to true.
function SelectAllOptions(listID) {
    var list = document.getElementById(listID);
    if (list == null) { return; }
    for (var i = 0; i < list.options.length; i++) {
        list.options[i].selected = true;
    }
}

//Gets an string from the textbox.
function GetValueFromTextbox(tb) {
    if (typeof (tb) == "string")
        tb = document.getElementById(tb);
    return tb.value;
}
//Gets an integer from the textbox. Returns null if walue isNAN.
function GetIntFromTextbox(tb) {
    if (typeof (tb) == "string")
        tb = document.getElementById(tb);
    if (isNaN(tb.value)) { return null; }
    return parseInt(tb.value, 10);
}
//Gets an float from the textbox. Returns null if walue isNAN.
function GetFloatFromTextbox(tb) {
    if (typeof (tb) == "string")
        tb = document.getElementById(tb);
    if (isNaN(tb.value)) { return null; }
    return parseFloat(tb.value, 10);
}
//Returns true if checkbox/radiobutton is checked. Returns false if not checked or doesn't exist or is not a checkbox/radiobutton.
function isChecked(elemID) {
    var elem = document.getElementById(elemID);
    if (elem == null) { return false; }
    if (elem.checked == true) { return true; }
    else { return false; }
}
function SetFocus(elem) {
    if (typeof (elem) == "string")
        elem = document.getElementById(elem);
    elem.focus();
}
function Disable(elem, value) {
    if (typeof (elem) == "string")
        elem = document.getElementById(elem);
    elem.disabled = value;
}
function ToggleItemVisibility(elem, inherit) {
    if (typeof (elem) == "string")
        elem = document.getElementById(elem);
    if (elem.style.visibility == "hidden") {
        if (inherit) {
            elem.style.visibility = "inherit";
        } else {
            elem.style.visibility = "visible";
        }
    } else {
        elem.style.visibility = "hidden";
    }
}
function ShowItem(elem, value) {
    if (typeof (elem) == "string")
        elem = document.getElementById(elem);
    if (value) {
        elem.style.visibility = "visible";
    } else {
        elem.style.visibility = "hidden";
    }
}
function ShowItemBlock(elem, value) {
    if (typeof (elem) == "string")
        elem = document.getElementById(elem);
    if (value) {
        elem.style.visibility = "visible";
        elem.style.display = "block";
    } else {
        elem.style.visibility = "hidden";
        elem.style.display = "none";
    }
}
function ShowItemInherit(elem, value) {
    if (typeof (elem) == "string")
        elem = document.getElementById(elem);
    if (value) {
        elem.style.visibility = "inherit";
    } else {
        elem.style.visibility = "hidden";
    }
}

function NumberAlterPrecision(num, decimalPlaces, round, fixed) {
    ///<summary>Alters precision of num to decimalPlaces precision.</summary>
    ///<param name="num">the number to perform function on.</param>
    ///<param name="decimalPlaces">the number of decimal places to keep. Pass 0 for integer precision.</param>
    ///<param name="round">Boolean true to round false to truncate.</param>
    ///<param name="fixed">Boolean true returns decimalPlaces number of digits precision with trailing 0s. false doesn't return trailing 0s.</param>
    ///<returns>num</returns>
    if (decimalPlaces < 1) { return ((round) ? Math.round(num) : Math.floor(num)); }
    var f = Math.pow(10, decimalPlaces);
    var num = ((round) ? Math.round(num * f) / f : Math.floor(num * f) / f);
    if (fixed) {
        return num.toFixed(decimalPlaces);
    } else {
        return num;
    }
}
//1 miles = 1.609344 kilometers
function MilesToKilometers(miles) {
    return miles * 1.609344;
}
//1 kilometer = 0.621371192 miles
function KilometersToMiles(kilometers) {
    return kilometers * 0.621371192;
}
//1 foot = 0.3048 meters
function FeetToMeters(feet) {
    return feet * 0.3048;
}
//1 meter = 3.2808399 feet
function MetersToFeet(meters) {
    return meters * 3.2808399
}

//GeoCodeCalc JavaScript Class: Used to calculate the distance between two lat/lon pairs.
var GeoCodeCalc = {};
GeoCodeCalc.EarthRadiusInMiles = 3956.0;
GeoCodeCalc.EarthRadiusInKilometers = 6367.0;
GeoCodeCalc.ToRadian = function(v) { return v * (Math.PI / 180);};
GeoCodeCalc.DiffRadian = function(v1, v2) {
return GeoCodeCalc.ToRadian(v2) - GeoCodeCalc.ToRadian(v1);
};
GeoCodeCalc.CalcDistance = function(lat1, lng1, lat2, lng2, radius) {
return radius * 2 * Math.asin( Math.min(1, Math.sqrt( ( Math.pow(Math.sin((GeoCodeCalc.DiffRadian(lat1, lat2)) / 2.0), 2.0) + Math.cos(GeoCodeCalc.ToRadian(lat1)) * Math.cos(GeoCodeCalc.ToRadian(lat2)) * Math.pow(Math.sin((GeoCodeCalc.DiffRadian(lng1, lng2)) / 2.0), 2.0) ) ) ) );
};

function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}
function FormatDate(tmpDate) {
    if (typeof (tmpDate) == "string")
        tmpDate = new Date(tmpDate);
    var month = tmpDate.getMonth() + 1;
    var day = tmpDate.getDate();
    var year = tmpDate.getFullYear();

    if (month < 10) { month = "0" + month; }
    if (day < 10) { day = "0" + day; }

    return month + "/" + day + "/" + year;
}
function FormatDateTime(tmpDate) {
    if (typeof (tmpDate) == "string")
        tmpDate = new Date(tmpDate);
    var month = tmpDate.getMonth() + 1;
    var day = tmpDate.getDate();
    var year = tmpDate.getFullYear();
    var hours = tmpDate.getHours();
    var minutes = tmpDate.getMinutes();
    var seconds = tmpDate.getSeconds();

    if (month < 10) { month = "0" + month; }
    if (day < 10) { day = "0" + day; }
    if (hours < 10) { hours = "0" + hours; }
    if (minutes < 10) { minutes = "0" + minutes; }
    if (seconds < 10) { seconds = "0" + seconds; }

    return month + "/" + day + "/" + year + " " + hours + ":" + minutes + ":" + seconds;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                              BEGIN Manipulate CSS 
//
function findStyleSheet(styleSheetId) {
    for (i = 0; i < document.styleSheets.length; i++) {
        if (document.styleSheets[i].title == styleSheetId)
            return document.styleSheets[i];
    }
    return null;
}
function GetCSSRules(styleSheetId) {
    var styleSheet = findStyleSheet(styleSheetId);
    return styleSheet.cssRules ? styleSheet.cssRules : styleSheet.rules;
}
function InsertCSSRule(CssId, selectorText, value, index) {
    var styleSheet = findStyleSheet(CssId);
    if (null == styleSheet)
        return;
    if (styleSheet.insertRule) {
        styleSheet.insertRule(selectorText + "{" + value + "}", index);
    } else {
        styleSheet.addRule(selectorText, value, index);
    }
}
function ModifyCSSRule(CssId, selectorText, value) {
    var theRules = GetCSSRules(CssId);

    if (null == theRules)
        return;

    var theRule = theRules[GetCSSRuleIndexBySelector(theRules, selectorText)];

    if (theRule) {
        theRule.style.cssText = value;
    } else {
        InsertCSSRule(CssId, selectorText, value, 0);
    }

}
function DeleteCSSRule(CssId, selectorText) {
    var styleSheet = findStyleSheet(CssId);
    if (null == styleSheet)
        return;

    if (styleSheet.deleteRule) {
        styleSheet.deleteRule(GetCSSRuleIndexBySelector(styleSheet, selectorText));
    } else {
        styleSheet.removeRule(GetCSSRuleIndexBySelector(styleSheet, selectorText));
    }
}
function GetCSSRuleIndexBySelector(rules, selectorText) {
    selectorText = selectorText.toLowerCase();
    for (i = 0; i < rules.length; i++) {
        if (rules[i].selectorText.toLowerCase() == selectorText)
            return i;
    }
}
//                                                              END Manipulate CSS 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                              BEGIN Events

function hookEvent(element, eventName, callback) {
    ///<summary>Crossbrowser way to hook events.</summary>
    ///<param name="element">the element or the element id</param>
    ///<param name="eventName">the name of the event to hook without "on"</param>
    ///<param name="callback">a reference to the javascript function to call on event occurance</param>
    ///<returns>null</returns>
    if (typeof (element) == "string")//If ID is passed in, get the element.
        element = document.getElementById(element);
    if (element == null)//If element is null, exit.
        return;
    if (element.addEventListener)
        element.addEventListener(eventName, callback, false); //W3C compliant
    else if (element.attachEvent)
        element.attachEvent("on" + eventName, callback); //Microsoft's way
}
function unhookEvent(element, eventName, callback) {
    ///<summary>Crossbrowser way to unhook events.</summary>
    ///<param name="element">the element or the element id</param>
    ///<param name="eventName">the name of the event to unhook without "on"</param>
    ///<param name="callback">a reference to the javascript function to unhook from event occurances</param>
    ///<returns>null</returns>
    if (typeof (element) == "string")//If ID is passed in, get the element.
        element = document.getElementById(element);
    if (element == null)//If element is null, exit.
        return;
    if (element.removeEventListener)
        element.removeEventListener(eventName, callback, false); //W3C compliant
    else if (element.detachEvent)
        element.detachEvent("on" + eventName, callback); //Microsoft's way
}
function getEvent(e) {
    ///<summary>Crossbrowser way to get the eventArgs.</summary>
    ///<param name="e">eventArgs</param>
    ///<returns>eventArgs</returns>
    if (!e)//W3C compliant eventArgs are passed already.
        e = window.event; //Microsoft's way
    return e;
}
function getEventTarget(e) {
    ///<summary>Crossbrowser way to get the event target.</summary>
    ///<param name="e">eventArgs</param>
    ///<returns>event target</returns>
    e = getEvent(e);
    if (e.target)
        return e.target; //W3C compliant
    return e.srcElement; //Microsoft's way
}
function cancelEvent(e) {
    ///<summary>Crossbrowser way to cancel the event.</summary>
    ///<param name="e">eventArgs</param>
    ///<returns>false</returns>
    e = getEvent(e);
    if (e.stopPropagation)
        e.stopPropagation(); //W3C compliant
    if (e.preventDefault)
        e.preventDefault(); //Firefox
    e.cancelBubble = true; //Microsoft's way
    e.cancel = true; //various others
    e.returnValue = false; //various others
    return false;
}
function getPointerX(e) {
    ///<summary>Crossbrowser way to get the x coord of the mouse from an event.</summary>
    ///<param name="e">eventArgs</param>
    ///<returns>int x coord</returns>
    return event.pageX || (event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
}
function getPointerY(e) {
    ///<summary>Crossbrowser way to get the ycoord of the mouse from an event.</summary>
    ///<param name="e">eventArgs</param>
    ///<returns>int ycoord</returns>
    return event.pageY || (event.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
}

//                                                              END Events
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
