﻿//------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Date		     Changed By             Description
// ---------	 ---------------        ----------------------------------------------------------------------------------------------------------------------------
// 01/10/2008       Dinesh              Added Email validation method 
// 02/21/2008       Chakravarthi        Added new functions IsValidDecimalNumber,KeyInteger,IsValidNumber and IsValidInteger
// 02/22/2008       Pramod              Modified  "IsValidInteger()" method   
// 02/26/2008       Chakravarthi        Added common javascript functions   
// 03/28/2008       Manav               Added "Validatepaste()" function
// 04/17/2008       Manav               Modified IsValidInteger function to check in lower case.
// 04/25/2008       Dinesh              Added GetDateTime function to format the date in last report and history screen
// 05/28/2008       Dinesh              Added FormatAssetGroup function to format Asset Group column
// 06/13/2008       Dinesh              Modified FormatAssetGroup function to show ... if only the assets belongs to many assets and added GetBatteryUsage function
// 06/13/2008       Pramod              Added a new method ExpandCollapse() to use expand or collapse functionality
// 06/26/2008       Pramod              Added a new method ExpandCollapse() to use expand or collapse functionality with two parameters
// 07/22/2008       Pramod              Modified GetBatteryUsage() related to the Battery Usage calculation formula
// 07/25/2008       Pramod              Modified ExpandCollapse() name to ExpandCollapsePanel() to avoid ambiguity
// 07/29/2008       Pramod              Added ConfirmEditUser() to show alert or Confirm message based on User permission to edit User information
// 09/11/2008       Pramod              Added ShowInvoice() to open a new window for Invoice link
// 10/10/2008       Pramod              Added DisableAnchor() to enable/disble anchor tag both in IE and Firefox
// 15/1/2009        Dinesh              Added GetDatePart() method
// 01/20/2009       Dinesh              Modified to Support MultiBrowser event key validation(Integer validation). 
// 04/07/2009       Pramod              Modified to Support MultiBrowser event key validation(Decimal validation). 
// 05/04/2009       Pramod              Modified GetBatteryUsage method to fix Battery Usage calculation
// 05/14/2009       Mathan              Modified GetBatteryUsage method to fix Battery Usage calculation
// 06/23/2009       Mathan              Renamed mapajax.aspx to map.aspx
// 08/03/2009       Ajtih Gopinath      added MapOLLocation functtion
// 10/13/2009       Mathan              Renamed MapOL.aspx to Map.aspx 

//------------------------------------------------------------------------------------------------------------------------------------------------------------------


/*** GENERAL JS FUNCTIONS ***/

//opens new window with packet details
function ShowPacketDetails(packetKey)
{
    window.open("../Tracking/PacketDetails.aspx?ref="+packetKey,"_blank","resizable=yes,location=no,menubar=no,toolbar=no,scrollbars=yes,width=320");
}

//opens new window UDP Rx packet details
function ShowUDPRxDetails(udpRxKey)
{
    window.open("../Administration/UDPRxDetails.aspx?ref="+udpRxKey,"_blank","location=no,menubar=no,toolbar=no,scrollbars=yes,width=320,height=480px");
}

//opens new window Stat2 packet details
function ShowStat2Details(udpRxKey)
{
    window.open("../Administration/Stat2Details.aspx?ref="+udpRxKey,"_blank","location=no,menubar=no,toolbar=no,scrollbars=yes,width=320,height=650px");
}
//opens new window Stat3 packet details
function ShowStat3Details(udpRxKey)
{
    window.open("../Administration/Stat3Details.aspx?ref="+udpRxKey,"_blank","location=no,menubar=no,toolbar=no,scrollbars=yes,width=320");
}
//opens new window Stat4 packet details
function ShowStat4Details(udpRxKey)
{
    window.open("../Administration/Stat4Details.aspx?ref="+udpRxKey,"_blank","location=no,menubar=no,toolbar=no,scrollbars=yes,width=320,height=480px");
}
// shows location
function MapLocation(lat, lon, localMap, key)
{
    if(localMap)
        window.open('../Tracking/Map.aspx?lat='+lat+'&lon='+lon+'&key='+key,"_blank","location=no,menubar=no,toolbar=no,scrollbars=no,width=760px,height=500px");
    else
        window.open('http://www.mapquest.com/maps/map.adp?searchtype=address&formtype=latlong&latlongtype=decimal&latitude='+lat+'&longitude='+lon);
}

//displays icon based on ddl selection
function ShowEventIcon(ddlID, imgID)
{
    var ddl = document.getElementById(ddlID);
    var img = document.getElementById(imgID);
    if(ddl && img)
    {
        var imgStr = ddl.options[ddl.selectedIndex].value;
        imgStr = GetImageURL(imgStr.split('-')[1]);
        img.src = imgStr;
    }
}

//enables/disables control
function ToggleEnabled(id, enabled)
{
    var ctrl = document.getElementById(id);
    if(ctrl)
    {
        if(enabled == true)
            ctrl.disabled = '';
        else
            ctrl.disabled = 'disabled';
    }
}

//returns image url based on the event name (param argument) or blank image if null
function GetImageURL(param)
{
    var url = '../images/general/';
    if(param == '' || param == null)
        url += 'spacer.gif';
    else
        url += param;
    if(url.indexOf('.gif') == -1)
        url += '.gif';
    return url;
}

function ShowBannerWindow(srcHTML)
{
    var bannerWindow = window.open();
    bannerWindow.document.write(srcHTML);
    bannerWindow.document.close();
    //alert(srcHTML);
    return false;
}
function IsChecked(flag)
{
    if(flag == true)
        return 'checked="checked"';
    else
        return '';
}
//returns display style for the element based on the flag
function GetVisibleStyle(flag)
{
    if(flag == true)
        return 'display:inline;';
    else
        return 'display:none;';
}
//returns grid column index of DataField or -1 if not found
function GetColumnIndex(grid, dataField)
{
    for(var i=0; i< grid.Table.Columns.length; i++)
    {
        if(grid.Table.Columns[i].DataField == dataField)
            return i;
    }
    //none found
    return -1;
}
//returns the first number of characters
function GetString(str, len)
{
    if(!str)
        return '';
    if(str.length <= len)
        return str;
    return str.substring(0,len)+'..';
}
//shows/hides div tag with the given id
function TogglePanel(id)
{
    var elem = GetElement('div', id);
    if(elem)
    {
        if(elem.style.display == 'none')
            elem.style.display = 'block';
        else
            elem.style.display = 'none';
    }
}
//finds element of 'tag' type with the given id in the document
function GetElement(tag, id)
{
    var elems = document.getElementsByTagName(tag);
    for(j=0;j<elems.length; j++)
    {
        var ctrl = elems[j];
        if(ctrl.id == id || (ctrl.id && ctrl.id.substring(ctrl.id.lastIndexOf("_")+1,ctrl.id.length) == id))
        {
            return ctrl;
        }
    }
}
//displays the element with selected item id and hides non selected
function ddlSelectionChanged(ddlId)
{
    var ddl = document.getElementById(ddlId);
    if(ddl)
    {
        for(var i = 0; i<ddl.options.length; i++)
        {
            var elem = document.getElementById(ddl.options[i].value);
            if(elem)
            {
                if(ddl.options[i].value == ddl.value)
                {
                    elem.style.display = 'block';
                }
                else
                {
                    elem.style.display = 'none';
                }
            }
        }
    }
}
//syncs selected items in both ddls, repopulates versions if necessary
function ddlSyncSelection(sourceId, destId, reloadVersion)
{
    var ddlSrc = document.getElementById(sourceId);
    var ddlDest = document.getElementById(destId);
    if(ddlSrc && ddlDest)
    {
        var id = ddlSrc.value;
        for(var i = 0; i<ddlDest.options.length; i++)
        {
            if(ddlDest.options[i].value == id)
            {
                ddlDest.value = id;
                if(reloadVersion == true)
                {
                    ctl00_maincontent_KeypadFormVersionsCallback.Callback(id);
                }
            }
        }
    }
}
//doesn't accept anything other than characters (also added to accept 'Enter' - keyCode=13)
function AlphaFieldKeyDown(event, txtId, maxChars, alphaOnly)
{
    if(document.getElementById(txtId).value.length >= maxChars && event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39 && event.keyCode != 38 && event.keyCode != 40)
    {
        event.returnValue = false;
        return;
    }
    if(alphaOnly)
    {
        if((event.keyCode >= 48 && event.keyCode <= 57)||(event.keyCode >= 96 && event.keyCode <= 105))
        {
            event.returnValue = false;
            return;
        }
    }
    /* accept 'Enter' as well */
//    if(event.keyCode == 13)
//    {
//        event.returnValue = false;
//        return;
//    }
}

//doesn't accept anything other than numbers
function NumFieldKeyDown(event)
{
    if(event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 8 || event.keyCode == 46 || (event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105))
    {
    }
    else
    {
        event.returnValue = false;
    }
}
//doesn't accept anything other than decimals
function DecimalFieldKeyDown(event, txtId)
{
    if(event.keyCode == 190 || event.keyCode == 110 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 8 || event.keyCode == 46 || (event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105))
    {
        if(event.keyCode == 190 || event.keyCode == 110)
        {
            var elem = document.getElementById(txtId);
            if(elem.value.indexOf('.')>=0)
                event.returnValue = false;
        }
    }
    else
    {
        event.returnValue = false;
    }
}
//if param is empty string or null returns '--', otherwise returns param
function ConvertToDisplay(param)
{
    if(param && param.toString().replace(/^\s*|\s*$/g,"").length > 0)
        return param;
    else
        return '--';
}

function ShowBufferedNotif(bufferedFlag, rxmtFlag)
{
    var result = '';
    if(rxmtFlag == true)
        result = "<span style='color:blue'>/</span>";
    else
        if(bufferedFlag == true)
            result = "<span style='color:red'>/</span>";
        
    return result;
}

// converts date to MM/DD hh:mm tt format, returns '--' if param is null
// shows ':' in color depending on input flags
function ConvertDate(param, bufferedFlag, rxmtFlag)
{
    if(param)
    {
        var dt = new Date(param);
        var conv ='';
        var temp = dt.getMonth()+1;
        if(temp < 10)
            conv = '0';
        conv = conv + temp.toString()+'/';  
        temp = dt.getDate();
        if(temp<10)
            conv = conv +'0';
        conv = conv + temp.toString()+' ';
        var ampm;
        temp = dt.getHours();
        if(temp == 0)
        {
            temp = 12;
            ampm = 'AM';
        } 
        else
        {
            if(temp < 12)
                ampm = 'AM';
            else
            {
                if(temp > 12)
                    temp = temp - 12;
                ampm = 'PM';
            }
        }
        if(temp < 10)
            conv = conv + '0';
        conv = conv + temp.toString();
        
        if(rxmtFlag == true)
            conv += "<span style='color:blue'>:</span>";
        else
            if(bufferedFlag == true)
                conv += "<span style='color:red'>:</span>";
            else
                conv += ":";
        
        temp = dt.getMinutes();
        if(temp < 10)
            conv = conv + '0';
        conv = conv + temp.toString() + ' '+ampm;
        return conv;
    }
    else
        return '--';
}

//converts text to decimal; returns null if error
function GetDecimalFromText(text)
{
    if(text == null || text.length == null || text.length == 0)
        return null;
        
    var dotIndex;
    dotIndex = text.indexOf('.');
    if(dotIndex != -1 && dotIndex != text.lastIndexOf('.'))//more than 1 period found in the string
        return null;
        
    if(dotIndex != -1 && text.length == 1)//the only char is '.'
        return null;
    
    var numStr = '0123456789';
    var isNum = true;
    for(var i=0; i<text.length; i++)
    {
        if(i != dotIndex)
        {
            if(numStr.indexOf(text.substring(i, i)) == -1)
                isNum = false;
        }
    }
    if(!isNum)
        return null;
    else
    {
        if(dotIndex == 0)
            text = '0'+text;
            
        if(dotIndex == -1)
            return 1*text;
        else
        {
            if((text.length - 3) > dotIndex)//more than 2 digits after the period
                return null;
            else
                return 1*text;
        }
    }
    return null;
}
//returns integer value from text; returns null if unable to convert
function GetIntegerFromText(text)
{
    if(text == null || text.length == null || text.length == 0)
        return null;
        
    var numStr = '0123456789';
    var isNum = true;
    for(var i=0; i<text.length; i++)
    {
        if(numStr.indexOf(text.substring(i, i)) == -1)
            isNum = false;
    }
    if(!isNum)
        return null;
    else
    {
        return 1*text;
    }
}
//returns true is chars only, returns false if 'text' contains at least 1 digit
function IsAlphaOnly(text)
{
    if(text == null || text.length == null || text.length == 0)
        return true;
        
    var numStr = '0123456789';
    var isAlpha = true;
    for(var i=0; i<text.length; i++)
    {
        if(numStr.indexOf(text.substring(i, i)) != -1)
            isAlpha = false;
    }
    return isAlpha;
}

/* UNIT CONVERSIONS BASED ON MetricFlag -----------------------------------------------------------------------*/

// returns temperature with account-based degrees sign (C or F) if not null and not '--'
// this function is registered on the server and replaces GetTemp(temp) function
function GetTemperatureFromF(temp, metricFlag)
{
    if(temp == "0" || (temp && temp != "--"))
    {
        if(metricFlag != 'true')
            return temp + ' F';
        else // convert to C degrees
            return Math.round((temp - 32)*5/9) + ' C';
    }
    else
        return '--';
}

function GetDistanceFromMiles(dist, metricFlag)
{
    if(dist == "0" || (dist && dist != "--"))
    {
        if(metricFlag != 'true')
        {
            //if(offsetLocal)
            //    dist += offsetLocal;
            return Math.round(dist*10)/10 + ' mi';
        }
        else
        {
            //convert to km
            var distM = dist*1.609;
            //if(offsetLocal)
            //    distM += offsetLocal;
            return Math.round(distM*10)/10 + ' km';
        }
    }
    else
        return '--';
}

function GetSpeedFromMph(speed, metricFlag)
{
    if(speed && speed != '--')
    {
        if(metricFlag != 'true')
            return speed + ' mph';
        else // convert to kmh
            return Math.round(speed*1.609) + ' km/h';
    }
    else
        return '--';
}

// converts feet to miles and feet format
function GetDistanceFromFeet(dist, metricFlag)
{
	var result = "--";
	if (dist && dist != '--')
	{
	    result = "";
	    if(metricFlag != 'true')
	    {
		    var miles = 0, feet = 0;

            if((dist%2640) == 0)
                result = dist/5280 + ' mi';
		    else
		    {
		        miles = Math.floor(dist / 5280);
		        feet = dist % 5280;
			    if (miles > 0)
				    result = miles + " mi ";
			    if (feet > 0)
				    result += feet + " ft";
		    }
		}
		else
		{
		    var km = 0, m = 0;
		    m = dist;
		    //m = Math.round(dist*0.3048);

            if((m%500) == 0)
                result = m/1000 + ' km';
		    else
		    {
		        km = Math.floor(m / 1000);
		        m = m % 1000;
			    if (km > 0)
				    result = km + " km ";
			    if (m > 0)
				    result += m + " m";
		    }
		}
	}
	return result;
}

/* END UNIT CONVERSIONS ---------------------------------------------------------------------------------------*/

//Email validation script
function ValidateEmailID(src) 
{
     var emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*(\.\w{2,3})+$/;
       
     var regex = new RegExp(emailReg);
     return regex.test(src);
}


//Validate decimal and fractional positions in a number
//value - Specify field value
//noOfPrecision - Specify no of digit are allowed
//noOfScale - Specify no of decimals are allowed
function IsValidDecimalNumber(value, noOfPrecision, noOfScale)
{
    if (isNaN(value) || value == "") 
        return false;
    else 
    {
        if (value.indexOf('.') == -1) 
            value += ".";
        precisionPart   = value.substring(0, value.indexOf('.'));
        scalePart       = value.substring(value.indexOf('.')+1, value.length);
        if ( (scalePart.length > noOfScale) || (precisionPart.length > noOfPrecision))
            return false;
        else 
            return true;
    }            
}

//Allow the user to enter only integer numbers (0 to 9)
//e - value of key pressed
function KeyInteger(e)
{
    var key = window.event ? e.keyCode : e.which; //Supports both IE and netscape browser. 
    if ((key < 48 || key > 57) && key != 8) {		
        if (window.event) //IE 
        {
	        e.keyCode = false;
	         if(e.returnValue)
	            e.returnValue = false;
	    }
        else if(key != 8 && key != 0) // netscape
	        return false;
    }
}

//To validate maximum & minimum ranges of integer value
//Vaue - Specify field value
//type - Specify field datatype
//allowNegative - Specify if the field allow negative numbers
function IsValidInteger(value, type, allowNegative)
{
    var maximumTinyIntValue   = 255;
    var minimumTinyIntValue   = 0;
    var maximumSmallIntValue  = 32767;
    var minimumSmallIntValue  = "-32768";
    var maximumIntValue       = 2147483647;
    var minimumIntValue       = "–2147483648";
    var maximumBigIntValue    = 9223372036854775807;
    var minimumBigIntValue    = "–9223372036854775808";
        
    switch(type.toLowerCase())
    {
        case "bigint":
        {
            if (allowNegative == "true")
            {
                maximumValue = maximumBigIntValue;
                minimumValue = minimumBigIntValue;
            }
            else
            {
                maximumValue = (maximumBigIntValue * 2) - 1;
                minimumValue = 0;
            }
                
            break;
        }
        case "int":
        {
            if (allowNegative == "true")
            {
                maximumValue = maximumIntValue;
                minimumValue = minimumIntValue;
            }
            else
            {
                maximumValue = (maximumIntValue * 2) - 1;
                minimumValue = 0;
            }
                
            break;
        }
        case "smallint":
        {
            if (allowNegative == "true")
            {
                maximumValue = maximumSmallIntValue;
                minimumValue = minimumSmallIntValue;
            }
            else
            {
                maximumValue = (maximumSmallIntValue * 2) - 1;
                minimumValue = 0;
            }
            
            break;
        }
        case "tinyint":
        {
            maximumValue = maximumTinyIntValue;
            minimumValue = 0;
                
            break;
        }
        default: 0;
    }
    
    if(value > maximumValue || value < minimumValue)
        return false;
    else
        return true;
}

//Validate for both +ve and -ve integer numbers
//Vaue - Specify field value
function IsValidNumber(value)
{
  if(value==null)
    return false;

  if (value.length==0)
    return true;

  for (var count = 0; count < value.length; count++) 
  {
    var charAtPosition = value.charAt(count)
    if (count == 0 && charAtPosition == "-")
          continue

    if (charAtPosition < "0" || charAtPosition > "9") 
          return false
 }
 return true
}


//LTrim(string) : Removes leading space from a string
//string - Specify the field value
//Returns a copy of a string without leading spaces
function LTrim(string)
/*PURPOSE: Remove leading blanks from our string.
   IN: string - the string we want to LTrim*/
{
   var whitespace = new String(" \t\n\r");

   var s = new String(string);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...

      var position=0, count = s.length;

      // Iterate from the far left of string until we
      // don't have any more whitespace...
      while (position < count && whitespace.indexOf(s.charAt(position)) != -1)
         position++;

      // Get the substring from the first non-whitespace
      // character to the end of the string...
      s = s.substring(position, count);
   }
   return s;
}

//RTrim(string) : Removes trailing space from a string
//string - Specify the field value
//Returns a copy of a string without trailing spaces.
function RTrim(string)
/* PURPOSE: Remove trailing blanks from our string.
   IN: string - the string we want to RTrim*/
{
   // We don't want to trip JUST spaces, but also tabs,
   // line feeds, etc.  Add anything else you want to
   // "trim" here in Whitespace
   var whitespace = new String(" \t\n\r");

   var s = new String(string);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      // We have a string with trailing blank(s)...

      var count = s.length - 1;       // Get length of string

      // Iterate from the far right of string until we
      // don't have any more whitespace...
      while (count >= 0 && whitespace.indexOf(s.charAt(count)) != -1)
         count--;

      // Get the substring from the front of the string to
      // where the last non-whitespace character is...
      s = s.substring(0, count+1);
   }

   return s;
}

//Trim(string) : Returns a copy of a string without leading or trailing spaces
//string - Specify the field value
function Trim(string)
/*PURPOSE: Remove trailing and leading blanks from our string.
   IN: string - the string we want to Trim
   RETVAL: A Trimmed string!*/
{
   return RTrim(LTrim(string));
}

//Allow the user to enter only decimal numbers (0 to 9 and dot)
//eventObj     - Event
//control      - Control
function KeyDecimal(eventObj, control)
{
    var key = window.event ? eventObj.keyCode : eventObj.which; //Supports both IE and netscape browser. key != 13
    if (key != 46 && (key < 48 || key > 57) && key != 8) 
    {		
       if (window.event) //IE 
        {
	        eventObj.keyCode = false;
            if(eventObj.returnValue)
                eventObj.returnValue = false;
        }
        else if(key != 8 && key != 0) // netscape
	        return false;
    }
    else if (key == 46) { //validating multiple dot's
        var DecimalValue = control.value;
        if (DecimalValue.indexOf('.') != -1)
        {
            if (window.event) //IE
	        { 
		        eventObj.keyCode = false;
                if(eventObj.returnValue)
                    eventObj.returnValue = false;
		    }
            else if(key != 8 && key != 0) // netscape
                return false;
        }
    }
}

//Format the decimal number 
// control       - Control
// lengthScale   - No of decimal positions 
function FormatDecimal(control, lengthScale)
{
    var DecimalValue = control.value;
    if (DecimalValue.indexOf('.') != -1)
    {
        var Scale;
        Scale = DecimalValue.substring(DecimalValue.lastIndexOf('.') + 1); 
        if (Scale.length >= parseInt(lengthScale))
        {
            //Trim the decimal digits in the right of the decimal point. If exceed the max scale.
            control.value = DecimalValue.substring(0,DecimalValue.lastIndexOf('.') + 1 + lengthScale);                    
        }
    }       
}

//validate for integer number
// number   - Number to be validate
function IsInteger(number)
{   var counter;
    for (counter = 0; counter < number.length; counter++)
    {   
        // Check that current character is number.
        var currentChar = number.charAt(counter);
        if (((currentChar < "0") || (currentChar > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

//Validates whether the data pasted in textbox is only digits if not it will not paste
function ValidatePaste()
{
    return IsInteger(window.clipboardData.getData('Text'));
}

function GetDateTime(value)
{
    if(value)
    {
        var monthAbbrev = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
        var date        = new Date(value);
        var conv        = '';        
        var datepart    = date.getMonth();// + 1;
        conv            = conv + monthAbbrev[datepart] + '&nbsp;';  
        datepart        = date.getDate();
        if(datepart<10)
            conv = conv +'0';
        conv = conv + datepart.toString() + ' ';
        var ampm;
        datepart = date.getHours();
        if(datepart == 0)
        {
            datepart = 12;
            ampm = 'AM';
        } 
        else
        {
            if(datepart < 12)
                ampm = 'AM';
            else
            {
                if(datepart > 12)
                    datepart = datepart - 12;
                ampm = 'PM';
            }
        }
        if(datepart < 10)
            conv = conv + '0';
        conv = conv + datepart.toString();        
        conv += ":";        
        datepart = date.getMinutes();
        if(datepart < 10)
            conv = conv + '0';
        conv = conv + datepart.toString() + '&nbsp;' + ampm;
        return conv;
    }
    else
        return '--';        
} 

function GetDatePart(value)
{
    if(value)
    {
        var monthAbbrev = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
        var date        = new Date(value);
        var conv        = '';        
        var datepart    = date.getMonth();// + 1;
        conv            = conv + monthAbbrev[datepart] + '&nbsp;';  
        datepart        = date.getDate();
        if(datepart<10)
            conv = conv +'0';
        conv = conv + datepart.toString() + ' ';
        return conv;
    }
    else
        return '--';        
} 


function FormatAssetGroup(assetGroups)
{
    var group = '--';
    if (assetGroups != null)
    {
        var groups = assetGroups.split(',');
        if (groups.length > 0)
        {
            group = groups[0]
            
            if (group != '')                
                group = group.split('|')[1];
                
            if (groups.length > 1)
                if (Trim(groups[1]) != '')
                    group = group + ', ...';              
        }        
    }
    return  group; 
}

// Format Battery Usage field with % used
function GetBatteryUsage(batteryMeter, batteryTypeFlag)
{
    if(batteryMeter == "0" || (batteryMeter && batteryMeter != "--"))
    {
        if(batteryTypeFlag)
            return batteryMeter + ' (' + Math.round(((batteryMeter * 100.0) / (19.0 * 1000.0 * 3600.0)) * 10)/10.0 + '% used)';
        else 
            return batteryMeter + ' (' + Math.round(((batteryMeter * 100.0) / (7.0 * 1000.0 * 3600.0))* 10)/10.0 + '% used)';
    }
    else
        return '--';
}

// Method used for expand and collapse functionality
<!--

isIE = (document.all)? true:false
function ExpandCollapse(id)
{
    try
    {
	    var expandGrid      = "../../images/lines/plus.gif";
	    var collapseGrid    = "../../images/lines/minus.gif";
	    var expandalt       = "Expand";
	    var collapsealt     = "Collapse";
	    
	    var expand              = document.getElementById('C'+id);
	    var collaps             = document.getElementById('E'+id);
	    
	    if(collaps.style.display=='none')
	    {
		    expand.alt  = collapsealt;
		    expand.src  = collapseGrid;
		    if(isIE)
		    {
			    collaps.style.display='block';
		    }
		    else
		    {
			    collaps.style.display='table-row';	
		    }
	    }
	    else
	    {
		    expand.src  = expandGrid;
		    expand.alt  = expandalt;
		    
		    collaps.style.display='none';
	    }
	}
	catch (e) {}
}


// Method used for expand and collapse functionality
// id - control id to expand or collapse
// path - Path for expand/collapse image
function ExpandCollapsePanel(id, path)
{
    try
    {
	    var expandGrid      = path + "plus.gif";
	    var collapseGrid    = path + "minus.gif";
	    var expandalt       = "Expand";
	    var collapsealt     = "Collapse";
	    
	    var expand      = document.getElementById('C'+id);
	    var collaps     = document.getElementById('E'+id);
	    
	    if(collaps.style.display=='none')
	    {
		    expand.alt  = collapsealt;
		    expand.src  = collapseGrid;
		    if(isIE)
		    {
			    collaps.style.display='block';
		    }
		    else
		    {
			    collaps.style.display='table-row';	
		    }
	    }
	    else
	    {
		    expand.src  = expandGrid;
		    expand.alt  = expandalt;
		    
		    collaps.style.display='none';
	    }
	}
	catch (e) {}
}

//Show alert or Confirm message based on User permission to edit User information
//isPermitted - 1 if the user has permission to edit user details else 0
function ConfirmEditUser(isPermitted)
{
    if(isPermitted == '1')
    {
        if(confirm("This contact is a User of the system. You must have administrative rights to edit the information.\nYou will be redirected to a different page and any unsaved changes will be lost.\nContinue?"))
            return true;
        else 
            return false;  
    }
    else if(isPermitted == '0')
    {
        alert("This contact is a User of the system. You must have administrative rights to edit the information.");
        return false;
    }
}

//opens new window with Show Invoice link
function ShowInvoice(basePath, invoiceAccount)
{
    window.open(basePath + "?ar="+invoiceAccount,"_blank");
}

// Used to Enable/Disable Anchor tag
// obj      - Object to be enabled/disabled
// disable  - Whether to enable / disable the object (true/false)
function DisableAnchor(obj, disable)
{ 
    if(disable)
    {
        var href = obj.getAttribute("href");
        if(href && href != "" && href != null)
        {
            obj.setAttribute('href_bak', href);
        }
        obj.removeAttribute('href');
        obj.style.color="gray";
    }
    else
    {
        if(obj.attributes['href_bak']!=null)
            obj.setAttribute('href', obj.attributes['href_bak'].nodeValue);

        obj.style.color="#000099";
    }
} 


// shows location
function MapAJAXLocation(lat, lon, localMap, key)
{
    if(localMap)
        window.open('../Tracking/Map.aspx?lat='+lat+'&lon='+lon+'&key='+key,"_blank","location=no,menubar=no,toolbar=no,scrollbars=no,width=760px,height=525px");
    else
        window.open('http://www.mapquest.com/maps/map.adp?searchtype=address&formtype=latlong&latlongtype=decimal&latitude='+lat+'&longitude='+lon);
}

// shows location
function MapOLLocation(lat, lon, localMap, key)
{
    if(localMap)
        window.open('../Tracking/Map.aspx?lat='+lat+'&lon='+lon+'&key='+key,"_blank","location=no,menubar=no,toolbar=no,scrollbars=no,width=760px,height=525px");
    else
        window.open('http://www.mapquest.com/maps/map.adp?searchtype=address&formtype=latlong&latlongtype=decimal&latitude='+lat+'&longitude='+lon);
}