// Constant Settings

var MAP_WIDTH_DEFAULT = 325;
var MAP_WIDTH_SMALL = 325;

var MAP_WINDOW_WIDTH_ADDITION = 220;
var MAP_WINDOW_HEIGHT_ADDITION = 230;

var METER_PER_FEET = 0.3048;
var KM_PER_MILE = 1.609344;
var NM_PER_MILE = 0.868976242;

var POST_URLS = true;

var OpenWins = new Array();
var OpenWinCount = 0;

var FadeTimers = [];
var InitFadeTimer = null;

var aOnLoadFuncs = new Array();

var ie = false;
var ns4 = false;
var ns6 = false;

var EULAWindow = null;

if (document.all)
  ie = true;
else if (document.layers)
  ns4 = true;
else if (document.getElementById)
  ns6 = true;

///////////////////////////////////////////////////////////
// StringValue Class: For returning string values
function ReturnValue()
{
  this.value = null;
}

String.prototype.trim = function()
{
  a = this.replace(/^\s+/, '');
  return a.replace(/\s+$/, '');
};

///////////////////////////////////////////////////////////
// Onload functions
function AttachOnLoadFunc(func)
{
  window.onload = ExecuteOnLoadFuncs;
}

function AddOnLoadFunc(func)
{
  aOnLoadFuncs[aOnLoadFuncs.length] = func;
}

function ExecuteOnLoadFuncs()
{
  var i, iCount = aOnLoadFuncs.length;

  for (i = 0; i < iCount; i++)
    eval(aOnLoadFuncs[i]);
}

///////////////////////////////////////////////////////////
// EULA functions
function ShowEULA()
{
  var cookie = GetCookie('EULA');
  var frm = null;

  if (cookie == null)
  {
    frm = EULAWin.open(HTMLPath + 'EULA.htm', 500, 400, AcceptEULA, RejectEULA);
    if (frm == null)
    {
      alert(EULA_ERROR);
      location.href = SignOutLink;  // sign out user
    }
  }
}

function AcceptEULA(win)
{
  if (EULAWin)
    EULAWin.close();

  SetCookie('EULA', 1, 3650, null, null, null);
}

function RejectEULA(win)
{
  location.href = SignOutLink;  // sign out user
}

///////////////////////////////////////////////////////////
// Cookie functions

// To use, simple do: Get_Cookie('cookie_name'); 
// replace cookie_name with the real cookie name, '' are required
function GetCookie(check_name)
{
  // first we'll split this cookie up into name/value pairs
  // note: document.cookie only returns name=value, not the other components
  var a_all_cookies = document.cookie.split(';');
  var a_temp_cookie = '';
  var cookie_name = '';
  var cookie_value = '';
  var b_cookie_found = false; // set boolean t/f default f

  for (i = 0; i < a_all_cookies.length; i++)
  {
    // now we'll split apart each name=value pair
    a_temp_cookie = a_all_cookies[i].split('=');

    // and trim left/right whitespace while we're at it
    cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

    // if the extracted name matches passed check_name
    if (cookie_name == check_name)
    {
      b_cookie_found = true;

      // we need to handle case where cookie has no value but exists (no = sign, that is):
      if (a_temp_cookie.length > 1)
        cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));

      // note that in cases where cookie is initialized but no value, null is returned
      return cookie_value;
      break;
    }
    a_temp_cookie = null;
    cookie_name = '';
  }

  if (!b_cookie_found)
    return null;
}

function SetCookie(name, value, expires, path, domain, secure)
{
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime(today.getTime());

  // if the expires variable is set, make the correct expires time, the
  // current script below will set it for x number of days, to make it
  // for hours, delete * 24, for minutes, delete * 60 * 24
  if (expires)
    expires = expires * 1000 * 60 * 60 * 24;

  //alert( 'today ' + today.toGMTString() );// this is for testing purpose only
  var expires_date = new Date(today.getTime() + (expires));
  //alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

  document.cookie = name + "=" + escape(value) +
    ((expires) ? ";expires=" + expires_date.toGMTString() : "") + //expires.toGMTString()
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ((secure) ? ";secure" : "");
}

function Delete_Cookie(name, path, domain)
{
  if (Get_Cookie(name))
    document.cookie = name + "=" + ((path) ? ";path=" + path : "") +
	                          			 ((domain) ? ";domain=" + domain : "") +
			                             ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
///////////////////////////////////////////////////////////
// Common functions

function setPointer(s)
{
  document.body.style.cursor = s; // set mouse pointer
}

function getelement(id)
{
  var el = null;
  var elements = null;

  el = document.all ? document.all[id] : document.getElementById(id);  // for both
  if (typeof (el) == 'undefined')
    el = null;

  if ((el == null) && (document.getElementByName))  // for IE (IE5.5 and earlier?)
  {
    el = document.getElementByName(id);
    if (typeof (el) == 'undefined')
      el = null;
  }

  if ((el == null) && (document.getElementsByName))// for Mozilla
  {
    elements = document.getElementsByName(id); // returns and array
    if (elements && (elements.length > 0))    // use 0th element for el
      el = elements[0];
  }

  return el;
}

function getelementex(id, doc)
{
  var el = null;
  var elements = null;

  if (!doc)
    doc = document;

  el = doc.all ? doc.all[id] : doc.getElementById(id);  // for both
  if (typeof (el) == 'undefined')
    el = null;

  if ((el == null) && (doc.getElementByName))  // for IE (IE5.5 and earlier?)
  {
    el = doc.getElementByName(id);
    if (typeof (el) == 'undefined')
      el = null;
  }

  if ((el == null) && (doc.getElementsByName))// for Mozilla
  {
    elements = doc.getElementsByName(id);      // returns and array
    if (elements && (elements.length > 0))    // use 0th element for el
      el = elements[0];
  }

  return el;
}


function GetURLParam(ParamName)
{
  var sURL = window.document.URL.toString();
  var sResult = "";
  var iStart = 0;
  var iEnd = 0;

  if ((iStart = sURL.indexOf(ParamName + "=")) > 0)
  {
    iStart += ParamName.length + 1;
    if ((iEnd = sURL.indexOf("&", iStart)) > 0)
      sResult = sURL.substring(iStart, iEnd);
    else
      sResult = sURL.substring(iStart);
  }

  return sResult;
}

function showhide(id, show)
{
  var el = getelement(id);
  if ((el == null) || (el.style == null))
    return false;

  if (el)
  {
    if (show)
      el.style.display = 'inline';
    else
      el.style.display = 'none';

    return true;
  }

  return false;
}

function altshowhide(id)
{
  var el = getelement(id);
  if ((el == null) || (el.style == null))
    return false;

  if (el)
  {
    if ((el.style.display == 'inline') || (el.style.display == 'visible'))
      el.style.display = 'none';
    else
      el.style.display = 'inline';

    return true;
  }

  return false;
}

function SetOpacity(id, value)
{
  var el = getelement(id);
  if ((el == null) || (el.style == null))
    return null;

  el.style.opacity = value / 10;
  el.style.filter = 'alpha(opacity=' + value * 10 + ')';
}

function ClearFadeTimers(bCancel)
{
  var i, iCount;

  if (bCancel)
  {
    iCount = FadeTimers.length;
    for (i = 0; i < iCount; i++)
      clearTimeout(FadeTimers[i]);

    if (InitFadeTimer)
      clearTimeout(InitFadeTimer);
  }

  FadeTimers = [];
  InitFadeTimer = null;
}

function FadeIn(id)
{
  var i;

  if (id == null)
    return false;

  ClearFadeTimers(true);
  showhide(id, true);
  for (var i = 0; i <= 11; i++)
    FadeTimers[FadeTimers.length] = setTimeout('SetOpacity("' + id + '",' + i + ');', 20 * i);
}

function FadeOut(id)
{
  var i;

  if (id == null)
    return false;

  ClearFadeTimers(true);
  for (var i = 0; i < 11; i++)
    FadeTimers[FadeTimers.length] = setTimeout('SetOpacity("' + id + '",' + (10 - i) + ')', 20 * i);

  FadeTimers[FadeTimers.length] = setTimeout('showhide("' + id + '",false)', 210);
}

function getOffsetLeft(el)
{
  var ol = null;

  if (typeof (el) == 'string')
    el = getelement(el);

  if (el)
  {
    ol = el.offsetLeft;
    while ((el = el.offsetParent) != null)
      ol += el.offsetLeft;
  }

  return ol;
}

function getOffsetTop(el)
{
  var ot = null;

  if (typeof (el) == 'string')
    el = getelement(el);

  if (el)
  {
    ol = el.offsetTop;
    while ((el = el.offsetParent) != null)
      ot += el.offsetTop;
  }

  return ot;
}

function Open(page, name, width, height)
{
  var winl;
  var wint;
  var win = null;

  if (page.length > 2000)
    RequestNewWindow(page, name, width, height);

  if (width && height)
  {
    if (width < screen.width)
      winl = (screen.width - width) / 2;
    else
      winl = 10;

    if (width < screen.height)
      wint = (screen.height - height) / 2;
    else
      wint = 10;

    win = OpenWins[OpenWinCount++] = this.open(page, name, 'width=' + width + ',height=' + height + ',top=' + wint + ',left=' + winl +
                                               ',toolbar=no,menubar=no,location=no,status=yes,scrollbars=yes,resizable=yes');
  }
  else
    win = OpenWins[OpenWinCount++] = this.open(page, name);

  if (!win || (typeof (win) == "undefined"))
    alert(LOGON_DISABLE_POPUP_BLOCKER);
  else
    OpenWins[OpenWinCount++] = win;
}

function OpenHelp(helppath, bAdmin, bAccount)
{
  var page = "";
  var CurPage = "";


  if (helppath && (helppath.length > 0))
  {
    if ((typeof (bAdmin) != 'undefined') && bAdmin)
      page = HTMLPath + 'help/adminhelp/index.htm?Page=' + helppath;
    else
      page = HTMLPath + 'help/index.htm?Page=' + helppath;
  }
  else
  {
    if ((typeof (bAdmin) != 'undefined') && bAdmin)
    {
      if (CurrentTab == '' || CurrentTab == 'Debug')
        CurPage = '?Page=Debug/Index.htm';
      else if (CurrentTab == 'User')
        CurPage = '?Page=Users/Index.htm';
      else if (CurrentTab == 'Server')
        CurPage = '?Page=Servers/Index.htm';
      else if (CurrentTab == 'Stat')
        CurPage = '?Page=Statistics/Index.htm';

      page = HTMLPath + 'help/adminhelp/index.htm' + CurPage;
    }
    else
    {
      if ((typeof (bAccount) == 'undefined') || !bAccount)
      {
        if (CurrentTab == '' || CurrentTab == 'Vehicle')
          CurPage = '?Page=VehicleTracking/Index.htm';
        else if (CurrentTab == 'Location')
          CurPage = '?Page=CreateLocation.htm';
        else if (CurrentTab == 'Report')
          CurPage = '?Page=Reports/Index.htm';
      }
      else
      {
        if (CurrentTab == '' || CurrentTab == 'User')
          CurPage = '?Page=MySettings/UserSettings/Index.htm';
        else if (CurrentTab == 'Contact')
          CurPage = '?Page=MySettings/ContactSettings/Index.htm';
        else if (CurrentTab == 'Display')
          CurPage = '?Page=MySettings/DisplaySettings/Index.htm';
        else if (CurrentTab == 'Vehicle')
          CurPage = '?Page=MySettings/VehicleSettings/Index.htm';
        else if (CurrentTab == 'Location')
          CurPage = '?Page=MySettings/LocationSettings/Index.htm';
        else if (CurrentTab == 'Trigger')
          CurPage = '?Page=MySettings/UserNotifications/Index.htm';
      }

      page = HTMLPath + 'help/index.htm' + CurPage;
    }
  }

  Open(page, 'Help', 800, 600);
}

function OpenFixed(page, name, width, height)
{
  RequestNewWindow(page, name, width, height);
}

function OpenReport(page, name)
{
  var i, iCount;

  // replace title name with translated name
  if (typeof (aReports) != 'undefined')
  {
    iCount = aReports.length;
    for (i = 0; i < iCount; i++)
      page = page.replace('&title=' + aReports[i][0] + '&', '&title=' + aReports[i][1] + '&');
  }

  RequestNewWindow(page, name, 640, 480);
}

function GetSelectedValue(selectbox)
{
  if (!selectbox || (selectbox.selectedIndex == -1))
    return null;

  return selectbox.options[selectbox.selectedIndex].value;
}

function GetSelectedText(selectbox)
{
  if (!selectbox || (selectbox.selectedIndex == -1))
    return null;

  return selectbox.options[selectbox.selectedIndex].text;
}

function GetSelectedValueFromText(selectbox, text)
{
  var i, iCount;

  if (!selectbox || (selectbox.selectedIndex == -1) || !text || (!text.length))
    return null;

  iCount = selectbox.options.length;
  for (i = 0; i < iCount; i++)
  {
    if (selectbox.options[i].text == text)
      return selectbox.options[i].value
  }

  return null;
}

function GetCheckedValue(checkbox)
{
  var chkbox = checkbox;

  if (typeof (chkbox) == 'string')
    chkbox = getelement(chkbox);

  if (typeof (chkbox.length) == 'undefined')
  {
    if (chkbox.checked)
      return chkbox.value;
  }
  else
  {
    for (i = 0; i < chkbox.length; i++)
    {
      if (chkbox[i].checked)
        return chkbox[i].value;
    }
  }

  return null;
}

function setChoice(radio, value)
{
  var bSelectionMade = false;
  var i, iCount;

  if (!radio)
    return false;

  iCount = radio.length;
  for (i = 0; i < iCount; i++)
  {
    if (radio[i].value == value)
    {
      radio[i].checked = true;
      bSelectionMade = true;
    }
  }

  return bSelectionMade;
}

function SetSelectedValue(selectbox, value, bNoCase)
{
  if (!selectbox)
    return false;

  if (typeof (bNoCase) == "undefined")
    var bNoCase = false;

  return SetValue(selectbox, value, bNoCase);
}

function SetValue(formfield, value, bNoCase)
{
  var LCValue;
  var i, iCount;

  if (!formfield)
    return false;

  if (typeof (bNoCase) == "undefined")
    var bNoCase = false;

  if (bNoCase)
    LCValue = value.toLowerCase();

  if (formfield.options) // is select box
  {
    iCount = formfield.options.length;
    for (i = 0; i < iCount; i++)
    {
      if ((!bNoCase && (formfield.options[i].value == value)) ||
          (bNoCase && (formfield.options[i].value.toLowerCase() == LCValue)))
      {
        formfield.options[i].selected = true;
        return true;
      }
    }
  }
  else if (formfield.value) // textbox, hidden, checkbox, etc.
  {
    formfield.value = value;
    return true;
  }

  return false;
}

function SetSelectedText(selectbox, text)
{
  var i, iCount;
  var sel;

  sel = selectbox;
  if (typeof (sel) == 'string')
    sel = getelement(sel);

  if (!sel)
    return false;

  iCount = sel.options.length;
  for (i = 0; i < iCount; i++)
  {
    if (sel.options[i].text == text)
    {
      sel.options[i].selected = true;
      return true;
    }
  }
  return false;
}

function SetSelectionName(selectbox, value, name)
{
  var i, iCount;

  if (!selectbox || !name.length)
    return false;

  iCount = selectbox.options.length;
  for (i = 0; i < iCount; i++)
  {
    if ((selectbox.options[i].text == value) ||
        (selectbox.options[i].value == value))
    {
      selectbox.options[i].text = name;
      return true;
    }
  }
  return false;
}

function AddSelections(selectbox, aSelections, bAddIdentical)
{
  var i, iCount, j, iSelCount;

  if ((typeof (bAddIdentical) == 'undefined') && !bAddIdentical)
    bAddIdentical = true;

  if (!selectbox || !aSelections ||
      (aSelections.length == 0) || (aSelections[0].length < 2))
    return false;

  iCount = aSelections.length;

  for (i = 0; i < iCount; i++)
  {
    bAdd = true;
    if (!bAddIdentical)
    {
      iSelCount = selectbox.options.length;
      for (j = 0; j < iSelCount; j++)
      {
        if (selectbox.options[j].text == aSelections[i][1]) // text is identical
        {
          bAdd = false;
          break;
        }
      }
    }

    if (bAdd && (aSelections[i].length == 2))
      selectbox.options[selectbox.options.length] = new Option(aSelections[i][1], aSelections[i][0]);
  }

  return true;
}

function RemoveSelection(selectbox, value)
{
  var i, iCount;

  if (!selectbox)
    return false;

  iCount = selectbox.options.length;
  for (i = 0; i < iCount; i++)
  {
    if ((selectbox.options[i].text == value) ||
        (selectbox.options[i].value == value))
    {
      selectbox.options[i] = null;
      return true;
    }
  }
  return false;
}

function DeselectAll(selectbox)
{
  var i, iCount;

  if (!selectbox)
    return false;

  iCount = selectbox.options.length;
  for (i = 0; i < iCount; i++)
    selectbox.options[i].selected = false;
}

function SetCheckedValue(checkbox, value)
{
  var i, iCount;

  if (!checkbox)
    return false;

  iCount = checkbox.length;
  for (i = 0; i < iCount; i++)
  {
    if (checkbox[i].value == value)
    {
      checkbox[i].checked = true;
      return true;
    }
  }
  return false;
}

/////////////////////////////////////////////////////////
// Input Validation Functions

function ValidateEmail(Email)
{
  var valid = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ \"@.!#$%&'*+-/=?^_`{|}~";
  var length = Email.length;
  var bValid;
  var i, iAts = 0;

  if (self.OnCustomValidateEmail && OnCustomValidateEmail(window, Email, bValid))
    return bValid;

  if (length == 0)
  {
    alert(ACCT_INVALID_EMAIL);
    return false;
  }

  for (i = 0; i < length; i++)
  {
    if (valid.indexOf(Email.charAt(i)) == -1)
    {
      alert(ACCT_INVALID_EMAIL);
      return false;
    }

    if (Email.charAt(i) == '@')
      iAts++;
  }

  iAtIndex = Email.indexOf('@');
  if (iAtIndex != -1)
    iDotIndex = Email.indexOf('.', iAtIndex);

  if ((iAts != 1) ||                    // there is more or less than one @
      (iAtIndex <= 0) ||                // no @ or no characters before @
      (iDotIndex == -1) ||              // no dot after @
      ((iDotIndex - iAtIndex) <= 1) ||  // no characters between @ and dot
      ((length - iDotIndex) <= 1))     // no characters after dot
  {
    alert(ACCT_INVALID_EMAIL);
    return false;
  }

  return true;
}

function ValidatePhone(PhoneNumber, bCheckEmpty)
{
  var Result;
  var bValid;

  if (!bCheckEmpty && (PhoneNumber.length == 0))
    return true;

  Result = PhoneNumber.match(/[1]{1}[-][0-9]{3}[-][0-9]{3}[-][0-9]{4}/);
  if (!Result)
    Result = PhoneNumber.match(/[0-9]{3}[-][0-9]{3}[-][0-9]{4}/);
  if (!Result)
    Result = PhoneNumber.match(/[0-9]{3}[-][0-9]{4}/);

  if (PhoneNumber != Result)
  {
    alert(ACCT_INVALID_PHONE);
    return false;
  }

  return true;
}

function ValidateMultipleEmails(EmailAddresses, bCheckEmpty)
{
  var i = 0, iCount;
  var Emails = EmailAddresses.split(';');
  var CommaEmails = EmailAddresses.split(',');

  if (CommaEmails.length > Emails.length)
    Emails = CommaEmails;

  if (EmailAddresses.length > 255)
  {
    alert(ACCT_LONG_EMAIL);
    return false;
  }

  if (bCheckEmpty && EmailAddresses.length == 0)
  {
    alert(ACCT_ENTER_EMAIL);
    return false;
  }
  else if (EmailAddresses.length == 0)
    return true;

  iCount = Emails.length;
  if (iCount == 0)
  {
    alert(ACCT_ENTER_EMAIL);
    return false;
  }

  for (i = 0; i < iCount; i++)
  {
    if (!ValidateEmail(Emails[i]))
      return false;
  }

  return true;
}

function ValidateMultiplePhones(PhoneNumbers, bCheckEmpty)
{
  var i = 0;
  var Value = '';
  var Phones = PhoneNumbers.split(';');
  var CommaPhones = PhoneNumbers.split(',');

  if (CommaPhones.length > Phones.length)
    Phones = CommaPhones;

  if (bCheckEmpty && PhoneNumbers.length == 0)
  {
    alert(ACCT_ENTER_PHONE);
    return false;
  }
  else if (PhoneNumbers.length == 0)
    return true;

  iCount = Phones.length;
  if (iCount == 0)
  {
    alert(ACCT_ENTER_PHONE);
    return false;
  }

  for (i = 0; i < iCount; i++)
  {
    if (!ValidatePhone(Phones[i]))
      return false;
  }

  return true;
}

function OnlyNumbers(textbox)
{
  var accept = "1234567890";

  if (textbox.value.match(/[^0-9]/gi))
  {
    textbox.value = textbox.value.replace(/[^0-9]/gi, '');
    alert('Please only enter numbers.');
    return false;
  }
}

function IsValidId(name)
{
  var str = name;
  var valid = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_ -"
  var i, iCount;

  if (name.length == 0)
    return false;

  iCount = str.length;
  for (i = 0; i < iCount; i++)
  {
    if (valid.indexOf(name.charAt(i)) < 0)
      return false;
  }

  return true;
}

function IsValidUserName(name)
{
  var str = name;
  var valid = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_ -.,&@"
  var i, iCount;

  if (name.length == 0)
    return false;

  iCount = str.length;
  for (i = 0; i < iCount; i++)
  {
    if (valid.indexOf(name.charAt(i)) < 0)
      return false;
  }

  return true;
}

function IsValidAccountName(name)
{
  var str = name;
  var valid = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_ -.,&@"
  var i, iCount;

  iCount = str.length;
  for (i = 0; i < iCount; i++)
  {
    if (valid.indexOf(name.charAt(i)) < 0)
      return false;
  }

  return true;
}

function IsValidNumber(name)
{
  if (text.match(/[^0-9]/gi))
    return false;

  return true;
}

//////////////////////////////////////////////////////////

function isDefined(param)
{
  if (param)
    return true;
  else
  {
    if (param == false)
      return true
    else
      return false
  }
}

function ChangeClass(element, newclass)
{
  if (element == null)
    return false;

  element.className = newclass;
  return true;
}

function SelectDivLink(s)
{
  var div = getelement(s + 'Div');
  var link = getelement(s + 'Link');

  if (div)
    div.style.display = 'inline';
  if (link)
    ChangeClass(link, 'SecMenuItemSel');
}

function UnselectDivLink(s)
{
  var div = getelement(s + 'Div');
  var link = getelement(s + 'Link');

  if (div)
    div.style.display = 'none';
  if (link)
    ChangeClass(link, 'SecMenuItem');
}

function SingleMenuSelectDivLink(s)
{
  var div = getelement(s + 'Div');
  var link = getelement(s + 'Link');

  if (div)
    div.style.display = 'inline';
  if (link)
    ChangeClass(link, 'SingleMenuItemSel');
}

function SingleMenuUnselectDivLink(s)
{
  var div = getelement(s + 'Div');
  var link = getelement(s + 'Link');

  if (div)
    div.style.display = 'none';
  if (link)
    ChangeClass(link, 'SingleMenuItem');
}

function ShowSecMenu(s)
{
  var div = getelement(s);

  if (div)
    div.style.display = 'inline';
}

function HideSecMenu(s)
{
  var div = getelement(s);

  if (div)
    div.style.display = 'none';
}

function ReplaceValue(Incoming, StartTag, EndTag, ReplaceString)
{
  var iStart, iEnd;
  var Temp;

  Temp = Incoming;

  iStart = Temp.indexOf(StartTag)
  if (iStart != -1)
  {
    iStart += StartTag.length;
    if (EndTag.length > 0)
    {
      iEnd = Temp.indexOf(EndTag, iStart)
      if (iEnd != -1)
      {
        Incoming = Temp.substring(0, iStart);
        Incoming += ReplaceString;
        Incoming += Temp.substring(iEnd, Temp.length);
      }
    }
    else  // if EndTag empty, replace rest of string
    {
      Incoming = Temp.substring(0, iStart);
      Incoming += ReplaceString;
    }
  }

  return Incoming;
}

function WriteFooter()
{
  document.write(COMN_FOOTER);
}

function OnTriggerEventChanged(selectbox, textbox, add)
{
  var iSelIndex;
  var EventList = getelement(selectbox);
  var EventNum = getelement(textbox);

  if (!EventList || !EventNum)
    return false;

  if ((add != null) && add)
  {
    if ((iSelIndex = EventList.selectedIndex) != -1)
    {
      if (EventNum.value.length > 0)
        EventNum.value += ",";

      EventNum.value += "" + EventList.options[iSelIndex].value;
    }
  }
  else
  {
    if ((iSelIndex = EventList.selectedIndex) != -1)
    {
      if (EventList.options[iSelIndex].value == "")
      {
        EventNum.readOnly = false;
        return true;
      }

      EventNum.value = EventList.options[iSelIndex].value;
    }

    EventNum.readOnly = true;
  }

  return true;
}

function Trim(string)
{
  while (string.substring(0, 1) == ' ')
    string = string.substring(1, string.length);

  while (string.substring(string.length - 1, string.length) == ' ')
    string = string.substring(0, string.length - 1);

  return string;
}

function zeroPad(num, width)
{
  num = num.toString();

  while (num.length < width)
    num = "0" + num;

  return num;
}

function round(n, dec)
{
  var result;
  result = Math.round(n * Math.pow(10, dec)) / Math.pow(10, dec);
  if (result.toFixed)
    result = result.toFixed(dec);
  return result;
}

function setCaretToEnd(control)
{
  if (control.createTextRange)
  {
    var range = control.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (control.setSelectionRange)
  {
    control.focus();
    var length = control.value.length;
    control.setSelectionRange(length, length);
  }
}

function Request(url, frame, useget)
{
  if (self.OnCustomRequest && OnCustomRequest(window, url, frame))
    return;

  if (POST_URLS && (!useget || (typeof (useget) == 'undefined') || (useget == false)))
    Post(url, frame);
  else
  {
    if ((ie && url.length > 2040) ||
        (ns4 && url.length > 30000) ||
        (ns6 && url.length > 9000))
    {
      alert(COMN_URL_TOO_LONG);
      return;
    }

    if (!frame || (typeof (frame) == 'undefined'))
      location.href = url;
    else
      frame.src = url;
  }
}

function RequestNewWindow(url, formname, width, height, useget)
{
  if (POST_URLS && (!useget || (typeof (useget) == 'undefined') || (useget == false)))
    PostNewWindow(url, formname, width, height);
  else
  {
    if ((ie && url.length > 2040) ||
        (ns4 && url.length > 30000) ||
        (ns6 && url.length > 9000))
    {
      alert(COMN_URL_TOO_LONG);
      return;
    }

    Open(url, name, width, height);
  }
}

/////////////////////////////////////////////////////////
// Form Post: Allows posting of urls in javascript.  This is
//            needed to get around GET url limits.
//            
// NOTE: If loading into a frame, the frame must be named.

var PostForm = null;
var UrlNameValuePairs;

function Post(url, frame)
{
  if (!url && !url.length)
    return -1;

  if (CreateForm(url, frame) < 0)
    return -1;

  PostForm.submit();
  return 1;
}

function PostNewWindow(url, name, width, height)
{
  var Html;

  if (!url && !url.length)
    return -1;

  if (CreateForm(url, null, name) < 0)
    return -1;

  Html = '<html><head><title></title></head><script>';
  Html += 'function Onload(){var frm;if(!window.opener)return;frm = window.opener.getelement(\'' + name + '\');if(!frm){return;}frm.submit();window.focus();}';
  Html += '</script>';
  Html += '<body onload="Onload();">';
  Html += '</body></html>';

  window.newWindowHtml = Html;  // set current window attribute to be used by the new window

  Open('javascript:opener.newWindowHtml', name, width, height);
}

function MakeHiddenForm(action, frame, name)
{
  var Form;
  var doc;
  var now = new Date();

  if (frame)
    doc = frame.document;
  else
    doc = document;

  Form = doc.createElement("form");

  if (name && (typeof (name) != 'undefined'))
  {
    Form.target = "" + name;
    Form.id = "" + name;
  }
  else
    Form.id = "" + now;

  Form.style.visibility = 'hidden';
  Form.style.display = 'none';
  Form.action = action;
  if (frame)
    Form.target = frame.name;

  Form.method = "POST";
  doc.body.appendChild(Form);
  return Form;
}

function CreateForm(url, frame, name)
{
  var input;
  var text;
  var Name, Value;
  var doc;
  var iIndex;

  if (frame)
    doc = frame.document;
  else
    doc = document;

  // Split URL
  UrlNameValuePairs = url.split("?");

  if (UrlNameValuePairs.length == 0)
    return -1;

  // get action
  PostForm = MakeHiddenForm(UrlNameValuePairs[0], frame, name);
  if (!PostForm)
    return -2;

  if ((iIndex = url.indexOf("?")) != -1)
    url = url.substring(iIndex + 1);

  // Parse and create from fields
  UrlNameValuePairs = url.split("&");
  iCount = UrlNameValuePairs.length;
  for (i = 0; i < iCount; i++)
  {
    input = doc.createElement('input');
    input.type = 'text';
    if ((iIndex = UrlNameValuePairs[i].indexOf('=')) != -1)
    {
      Name = UrlNameValuePairs[i].substring(0, iIndex);
      Value = UrlNameValuePairs[i].substring(iIndex + 1);
    }
    else
    {
      Name = "";
      Value = UrlNameValuePairs[i];
    }

    if ((Name.length == 0) && (i == 0))  // most likely the MfcISAPICommand
    {
      input.id = "MfcISAPICommand";
      input.name = "MfcISAPICommand";
      input.value = Value;
    }
    else
    {
      input.id = Name;
      input.name = Name;
      if (Value.length > 0)
        input.value = Value;
      else
        input.value = "";
    }

    // alert(input.id+","+input.value);

    PostForm.appendChild(input);
  }

  return 1;
}

function CreateIFrame(id, src)
{
  var IFrame = getelement(id);

  if (!IFrame)
  {
    IFrame = document.createElement('<iframe id="' + id + '" name="' + id + '">');
    document.body.appendChild(IFrame);
  }

  if (src)
    IFrame.src = src

  //IFrame.width = '200px';
  //IFrame.height = '200px';
  IFrame.style.visibility = 'hidden';
  IFrame.style.display = 'none';

  return document.frames[IFrame.id];
}

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, "");
}

function ExtractString(String, iIndex, Start, End, Return)
{
  var iStart, iEnd;

  Return.value = "";
  iStart = String.indexOf(Start, iIndex);
  if (iStart != -1)
  {
    iStart += Start.length;
    iEnd = String.indexOf(End, iStart);
    if (iEnd != -1)
      Return.value = String.substring(iStart, iEnd);

    return iEnd;
  }

  return -1;
}

function ExtractDelimitedString(String, Delimiter, iIndex, Return)
{
  var i, iStart, iEnd;

  Return.value = "";
  if ((!String) || (!String.length) || (!Delimiter) || (iIndex < 0))
    return false;

  iStart = 0;
  for (i = 0; i < iIndex; i++)
  {
    iStart = String.indexOf(Delimiter, iStart);
    if (iStart == -1)
      return false;

    iStart += Delimiter.length;
  }

  if (iStart != -1)
  {
    iEnd = String.indexOf(Delimiter, iStart);
    if (iEnd != -1)
      Return.value = String.substring(iStart, iEnd);
    else
      Return.value = String.substring(iStart, String.length);

    return true;
  }

  return false;
}

function WriteMapSizes(CurrentMapSize, bHorizontal, bIncludeNoMap, bMain)
{
  var bSelected;

  if (self.OnCustomWriteMapSizes && OnCustomWriteMapSizes(window, CurrentMapSize, bHorizontal, bIncludeNoMap, bMain))
    return;

  if (!bMain)
  {
    document.write('<table cellpadding="0" cellspacing="0" style="font-size:3px">');
    document.write('<tr><td style="width:30px;height:18px;font-size:10px"><a href="javascript:mapwidth(0)">' + MAPWIN_MAPWIDTH_NONE + '</a></td>');

    if (!bHorizontal)
      document.write('</tr><tr>');

    iCount = aMapMapSizes.length;
    for (i = 0; i < iCount; i++)
    {
      if ((aMapMapSizes[i][1] == '0') && !bIncludeNoMap)
        continue;

      if (CurrentMapSize == aMapMapSizes[i][1])
        document.write('<td><table align="center"><tr><td style="width:' + aMapMapSizes[i][2] + 'px;height:' + aMapMapSizes[i][3] + 'px;" align="center" class="MapPopupMapSizeButtonSelected" onmouseover="ChangeClass(this, \'MapPopupMapSizeButtonHover\');" onmouseout="ChangeClass(this, \'MapPopupMapSizeButtonSelected\');" onclick="mapwidth(' + aMapMapSizes[i][1] + ')">' + aMapMapSizes[i][0] + '</td></tr></table></td>');
      else
        document.write('<td><table align="center"><tr><td style="width:' + aMapMapSizes[i][2] + 'px;height:' + aMapMapSizes[i][3] + 'px;" align="center" class="MapPopupMapSizeButton" onmouseover="ChangeClass(this, \'MapPopupMapSizeButtonHover\');" onmouseout="ChangeClass(this, \'MapPopupMapSizeButton\');" onclick="mapwidth(' + aMapMapSizes[i][1] + ')">' + aMapMapSizes[i][0] + '</td></tr></table></td>');

      if ((i != (iCount - 1)) && !bHorizontal)
        document.write('</tr><tr>');
    }

    document.write('</tr></table>');
  }
  else
  {
    bSelected = false;
    iCount = aMainMapSizes.length;
    for (i = 0; i < iCount; i++)
    {
      if (CurrentMapSize == aMainMapSizes[i][1]) // selected
        bSelected = true;
    }

    for (i = 0; i < iCount; i++)
    {
      if ((aMainMapSizes[i][1] == '0') && !bIncludeNoMap)
        continue;

      if ((CurrentMapSize == aMainMapSizes[i][1]) || (!bSelected && (aMainMapSizes[i][1] != '0')))  // select first non-zero size if nothing is selected
      {
        bSelected = true;
        document.write('<input type="radio" name="mapwidth" value="' + aMainMapSizes[i][1] + '" checked="checked"> ' + aMainMapSizes[i][0] + '<br>');
      }
      else
        document.write('<input type="radio" name="mapwidth" value="' + aMainMapSizes[i][1] + '"> ' + aMainMapSizes[i][0] + '<br>');
    }
  }
}

function WriteZooms(ZoomType, CurrentZoom, bMain)
{
  var Type, i, iCount, iZooms = 0;

  if (self.OnCustomWriteZooms && OnCustomWriteZooms(window, CurrentZoom, ZoomType, bMain))
    return;

  if (ZoomType == 'Statute')
    Type = 1;
  else if (ZoomType == 'Metric')
    Type = 2;
  else if (ZoomType == 'Nautical')
    Type = 3;

  if (!bMain)
  {
    document.write('<table border="0" cellpadding="0" cellspacing="2">');
    document.write('<tr><td align="center" style="height:30px;"><a href="javascript:zoomin()"><img border="0" src="' + HTMLPath + 'images/plus.gif" width="20" height="20" alt="' + MAPWIN_ZOOM_IN + '"></a></td></tr>');


    iCount = aMapZooms.length;
    for (i = 0; i < iCount; i++)
    {
      if (aMapZooms[i][0] == Type)
      {
        if ((aMapZooms[i][2] >= (CurrentZoom * 0.98)) && (aMapZooms[i][2] <= (CurrentZoom * 1.02)))
          document.write('<tr><td align="center" class="MapPopupZoomButtonSelected" onmouseover="ChangeClass(this, \'MapPopupZoomButtonHover\');" onmouseout="ChangeClass(this, \'MapPopupZoomButtonSelected\');" onclick="zoom(\'' + aMapZooms[i][2] + '\')">' + aMapZooms[i][1] + '</td></tr>');
        else
          document.write('<tr><td align="center" class="MapPopupZoomButton" onmouseover="ChangeClass(this, \'MapPopupZoomButtonHover\');" onmouseout="ChangeClass(this, \'MapPopupZoomButton\');" onclick="zoom(\'' + aMapZooms[i][2] + '\')">' + aMapZooms[i][1] + '</td></tr>');
      }
    }

    document.write('<tr><td align="center" style="height:30px;"><a href="javascript:zoomout()"><img border="0" align="middle" src="' + HTMLPath + 'images/minus.gif" width="20" height="20" alt="' + MAPWIN_ZOOM_OUT + '"></a></td></tr>');
    document.write('</table>');
  }
  else
  {
    iCount = aMainZooms.length;
    for (i = 0; i < iCount; i++)
    {
      if (aMainZooms[i][0] == Type)
      {
        if ((aMainZooms[i][2] >= (CurrentZoom * 0.98)) && (aMainZooms[i][2] <= (CurrentZoom * 1.02)))
          document.write('<input type="radio" name="Zoom" value="' + aMainZooms[i][2] + '" checked="checked"> ' + aMainZooms[i][1] + '<br>');
        else
          document.write('<input type="radio" name="Zoom" value="' + aMainZooms[i][2] + '"> ' + aMainZooms[i][1] + '<br>');
        iZooms++;
      }
    }
  }
}

