var kRemoteWinName = "remote"
var kTVMonWinName = "tvmon"
var kWebDirWinName = "wd"
var kStreamWinName = "stream"
var kDocsWinName = "docs"

var kMaxEditBoxLength = 52

// Browser Detection
var agt=navigator.userAgent.toLowerCase()
var isIE  = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1))

var webLanguags = "EN|American English?EK|British English?DE|Deutsch?SP|Espa\u00f1ol?FR|Fran\u00e7ais?IT|Italiano?JA|Japanese.gif?KO|Korean.gif?HU|Magyar?NO|Norsk?PL|Polski?PT|Portugu\u00eas?RU|Russian.gif?ZH|Chinese.gif?FI|Suomi?ZHT|ChineseTraditional.gif"
var dbLanguages = "Japanese|Japanese.gif?Korean|Korean.gif?Russian|Russian.gif?Chinese|Chinese.gif?ChineseT|ChineseTraditional.gif"
var rebootAction = "a_rebootmeter.htm"
// This can be set by the content window to force the naviationg to reload
// when the next page loads. We want to wait for the content page to reload
// instead of directly reload the page so that we are sure the changes that
// we where trying to make are finsihed.
var forceReloadNav = false
var protocolCookie = new CookieDef(0,"/","","0")

var kSelected = "selected"

function GetContentWindow ()
{
  return top.document.getElementById ("contentFrame").contentWindow
}

function GetCurrentPageName () {return document.location.pathname.replace (/^\//, "")}
function Escape (text) {return text.replace (/\\/g, "\\\\")}
function EscapeDoubleQuote (text) {return text.replace (/\"/g, '\\"')}

function GoTo (link)
{
  var mainMenu = parent.mainMenu
  var newMenu = mainMenu.FindMainMenuId (link)
  mainMenu.SetMainMenuID (newMenu)
  mainMenu.SetCurrentPage (link)
  parent.location.reload ()
}

function SetForceNavReload (value)
{
  window.top.forceReloadNav = value
}

function GetLanguageName()
{
  switch(currentLanguage)
  {
    case "ES":
    case "SP": return "Spanish";
    case "JA":
    case "JP": return "Japanese";
    case "PT": return "Portugese";
    case "IT": return "Italian";
    case "EK": return "EnglishUK";
    case "DE":
    case "GR": return "German";
    case "FR": return "French";
    case "ZH": return "Chinese";
    case "ZHT": return "ChineseT";
    case "NO":
    case "NOR": return "Norwegian";
    case "KO": return "Korean";
    case "RU": return "Russian"; 
    case "PL": return "Polish"; 
    case "HU": return "Hungarian"; 
    case "AR": return "Arabic";
    case "FI": return "Finnish";
    default: return "EnglishUS";
  }
}

function numberorder (a,b) {return a-b}    

function MM_findObj(n, d)
{
  var p,i,x  
  if(!d) d=document;
  if((p=n.indexOf("?"))>0&&parent.frames.length)
  {
    d=parent.frames[n.substring(p+1)].document;
    n=n.substring(0,p)
  }
  if(!(x=d[n])&&d.all) x=d.all[n]; 
  for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); 
  return x;
}

function MM_goToURL()
{
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2)
  {
//    alert(args[i]+".location='"+args[i+1]+"'");
    eval(args[i]+".location='"+args[i+1]+"'");
  }
}

function wait(delay,methodCall)
{
  //alert("wait() : delay="+delay+"methodCall="+methodCall);
  setTimeout(methodCall,delay);
}

function MM_reloadPage(init)
{//reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) 
  {document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) { window.location.reload(); }
}

function MM_openBrWindow(theURL,winName,features)
{
  // Make the name unique
  if (winName) winName += sysName.replace(/\W/g,"")
  
  try
  { 
    window.open(theURL,winName,features).focus ()
  }
  catch (e)
  {
    alert (WEB_POPUPBLOCKER_OFF)
  }
}

function ShowHideElement(id, show)
{
  document.getElementById (id).style.visibility =
    (show) ? "visible" : "hidden"
}

function MM_showHideLayers()
{
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_swapImage()
{
  var i,j=0,x,a=MM_swapImage.arguments;

  document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
  if ((x=MM_findObj(a[i]))!=null)
  {
    document.MM_sr[j++]=x;
    if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];
  }
}

function MM_swapImgRestore()
{
  var i,x,a=document.MM_sr;
  
  for(i=0; a&&i<a.length&&(x=a[i])&&x.oSrc; i++) x.src=x.oSrc;
}

function MM_preloadImages()
{
  var d=document;
  
  if(d.images)
  {
    if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0)
    {
      d.MM_p[j]=new Image;
      d.MM_p[j++].src=a[i];
    }
  }
}

function CookieDef(expires,path,domain,secure)
{
  this.secure = secure;
  this.path = path;
  this.domain = domain;
  this.getValue = getCookie;
  this.setValue = setCookie;
  this.expire = deleteCookie;
  if (expires == 0) { this.expires = ""; }
  else 
  {
    var today_date = new Date();
    var expire_seconds = today_date.getTime() + (expires * 24 * 60 * 60  * 1000);
    today_date.setTime(expire_seconds);
    this.expires = today_date.toGMTString();
  }
}
function getCV(offset)
{
  var endstr = document.cookie.indexOf(";", offset);
  if (endstr == -1) endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

function getCookie(name)
{
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCV(j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return "";
}

function setCookie(name,value)
{
  //alert ("value = " + value);
  document.cookie = name + "=" + escape(value) +
    ((this.expires == "") ? "" : ("; expires=" + this.expires)) +
    ((this.path == "") ? "" : ("; path=" + this.path)) +
    ((this.domain == "") ? "" : ("; domain=" + this.domain)) +
    ((this.secure == true) ? "; secure" : "");
}

function deleteCookie(name)
{
  document.cookie = name + "=" + "" + "; expires=Thu,01-Jan-70 00:00:01 GMT";
}

function WA_setCookie(cookieobj, cookiename, cookievalue, cookiecheck, settype)
{
  var theValue = ""; //alert("inside WA_setCookie() " + cookievalue);
  if (settype == 1)
  {
    for (var n=0; n<cookievalue.length; n++)
    {
      if (cookievalue[n].checked) {theValue = cookievalue[n].value;}
    }
  }
  else {theValue = cookievalue;}
  if (cookiecheck) {cookieobj.setValue(cookiename, theValue);}
}

function WA_noCookieRedirect(CookieObj,Location,RedirectTo)
{
  CookieObj.setValue("WA_testCookie","WA_testCookie");
  if (CookieObj.getValue("WA_testCookie") != "WA_testCookie")
  {
    Location.location.href=RedirectTo;
  }
  else
  {
    CookieObj.expire("WA_testCookie");
  }
}

function WA_cookieRedirect(CookieObj,Location,Alike,CookieName,CookieValue,RedirectTo)
{
  if ((CookieObj.getValue(CookieName)==CookieValue)==Alike)
  {
    Location.location.href=RedirectTo;
  }
}

var WACookieDef1 = new CookieDef(365,"/","","0");

function GetBrowserLanguage ()
{
  language = navigator.browserLanguage;
  if (!language) language = navigator.userLanguage;
  if (!language) language = navigator.language;
  if (!language) language = navigator.systemLanguage;
  return language;
}

function GetLanguage ()
{
  language = WACookieDef1.getValue("langchoice");
  // If the user has not already selected a language try to use there browser language.
  if (!language)
  {
    browserLanguage = GetBrowserLanguage ().toUpperCase();
    language = browserLanguage.substr (0,2);
    country = browserLanguage.substr (3,2);
    // For english we may want to use english uk 
//    alert (country);
    if (language == "EN")
    {
      switch (country)
      {
        case "GB":
          language = "EK";
        break;
      }
    }
  }
  
//  alert (language);
  return language;
}

var currentLanguage = GetLanguage() // the current language
//this function returns the correct string based on the current language
function GetLanguageFile()
{
  switch(currentLanguage)
  {
    case "ES":
    case "SP": return "languages_es";
    case "JA":
    case "JP": return "languages_ja";
    case "PT": return "languages_pt";
    case "IT": return "languages_it";
    case "EK": return "languages_ek";
    case "DE":
    case "GR": return "languages_de";
    case "FR": return "languages_fr";
    case "ZH": return "languages_zh";
    case "ZHT": return "languages_ct";
    case "NO":
    case "NOR": return "languages_no";
    case "KO": return "languages_ko";
    case "RU": return "languages_ru"; 
    case "PL": return "languages_pl"; 
    case "HU": return "languages_hu"; 
    case "AR": return "languages_ar";
    case "FI": return "languages_fi";
    default: return "languages_en";
  }
}

function OnUnload ()
{
  // alert (isOOB +", " + document.getElementById ("htmfile").value);
  window.location.replace (document.getElementById ("htmfile").value);
}

function isForcedSecurePage (url)
{
  return url=="/a_security.htm" || url=="/a_passchange.htm" || isOOB;
}

function IsIndexURL (url)
{
  return (url == "/" || url == "/u_index2.htm");
}

var kSecureProtocol = "https:";
      
function CheckSecurity (url, port)
{
  // If the url is empty or equal to the main index page then
  // the navigation functions will take care of checking the security.
  //alert ("Checking Security for "+url);
  if (IsFIPSSupported ())
  {
    if ((!IsIndexURL (url) && !/\.cgi$/.test (url)) || isOOB)
    {
      if (isForcedSecurePage (url) || isSecure)
      {
        if (location.protocol != kSecureProtocol) 
        {
          //alert ("Going Secure HTTP");
          top.protocolCookie.setValue ("protocol", top.location.protocol);
          ChangeProtocols (kSecureProtocol, port);
        }
      }
      else
      {
        var oldProtocol = top.protocolCookie.getValue ("protocol");
        //alert ("oldProtocol = " + oldProtocol);
        if (oldProtocol != "")
        {
         // alert ("Going back to "+oldProtocol);
          top.protocolCookie.setValue ("protocol", "");
          ChangeProtocols (oldProtocol, port);
        }
      }
    }
  }
}

function ChangeProtocols (toProtocol, port)
{
  if (top.location.protocol != toProtocol) 
  {
    top.location.replace (toProtocol + "//" + top.location.hostname +
      ((toProtocol == "http:") ? FormatHTTPPort (port) : "") +  top.location.pathname);
  }
}

function FormatHTTPPort (port)
{
  return ((port != null && port != "" && port != "80") ? (":" + port) : "")
}

function FormatPort (port)
{
  return ((top.location.protocol == "http:") ? FormatHTTPPort (port) : "")
}

function ReloadNav (reloadNav, port, address)
{
  if (reloadNav)
  {
    top.location.replace (top.location.protocol+ "//" +
      ((address) ? (address + "/") : top.location.hostname) + 
      FormatPort (port))
  }
}

function SetImageValue (objectId, value)
{
  var object = objectId;
  if (typeof object == "string") object = document.getElementsByName (objectId)[0]
  // For checkbox images
  object.setAttribute ("checked", (value || value == "True"))
  object.setAttribute ("value", value)
}


function SetObjectValue (objectId, value, executeOnChange)
{
  if (executeOnChange == null ) executeOnChange = true
  
  var object = objectId;
  if (typeof object == "string") object = document.getElementsByName (objectId)[0]
  //alert ("SetObjectValue ("+object.id+", "+value+", "+executeOnChange+")")
  
  if (object)
  {
    //alert ("object.type = " + object.type)
    if (object.type == "radio") SetRadioValue (object, value)
    else if (object.type == "select-one") SetSelectedOption (object, value)
    else if (object.type == "img" || object.tagName == "IMG") SetCheckBoxImage (object, value)
    else if (object.type == "checkbox") object.checked = value
    else if (object.tagName == "SPAN") object.innerHTML = value
    else object.value = value
    if (executeOnChange)
    {
      if (object.onchange) object.onchange ()
      else if (object.onclick) object.onclick ()
    }
  }
  else
  {
    alert ("HTML ERROR SetObjectValue: object '"+objectId+"' not found.")
    return 
  }
  return true
}

function GetValue (objectId, attribute)
{
  var object = (typeof objectId == "string") ?
   document.getElementsByName (objectId)[0] : objectId
  
  // Use the type of the objects acutal value to no what function to use
  // to get the value we are asking for.
  return (typeof GetObjectValue (object) == "boolean") ?
    GetBooleanAttribute (object, attribute) :
    object.getAttribute (attribute)
}

function GetObjectCValue (objectId)
{
  return GetValue (objectId, "cValue")
}

function GetObjectOValue (objectId)
{
  return GetValue (objectId, "oValue")
}

function GetObjectPValue (objectId)
{
  return GetValue (objectId, "pValue")
}

////////////////////////////////////////////////////////////////////////////////
//  Name:        RebootOnChange
//  Description: Description
////////////////////////////////////////////////////////////////////////////////

function RebootOnChange (objectId)
{
  var object = objectId
  if (typeof object == "string") object = document.getElementsByName (objectId)[0]
    
  if (object.getAttribute)
  {
    return GetBooleanAttribute (object, "rebootOnChange")
  }
  else if (object.hasChildNodes ())
  {
    for (var child = 0; child < object.childNodes.length; child++)
    {
      results = RebootOnChange (object.childNodes.item(child))
      if (results != null) return results
    }
  }
  
  return null
}

/*
function RebootOnChange (objectId)
{
  var object = objectId
  if (typeof object == "string") object = document.getElementsByName (objectId)[0]
  return GetBooleanAttribute (object, "rebootOnChange")
}
*/

function HasChanged (object)
{
  if (typeof object == "string") object = document.getElementsByName (object)[0]
  return GetObjectOValue (object) != GetObjectValue (object)
}

function GetObjectValue (objectId)
{
  //alert ("GetObjectValue ("+objectId+")")
  var object = objectId;
  if (typeof object == "string") 
  {
  // If we did not find it in the document lets look for it in 
  // the page data
  
    object = document.getElementsByName (objectId)[0]
    if (!object && page)
{
      //alert ("Looking in page")
      object = page.FindObjectById (objectId)
    }
  }

  if (object)
  {
    if (object.type == "radio") return GetRadioValue (object)
    if (object.type == "select-one") return GetSelectedOption (object);
    if (object.type == "checkbox") return object.checked;
    else if (object.type == "img" || object.tagName == "IMG") return IsChecked (object)
    if (object.tagName == "SPAN") return object.innerHTML
    else return object.getAttribute ("value")
  }
  else
  {
    alert ("HTML ERROR GetObjectValue: object '"+objectId+"' not found.");
    return "";
  }
}

function ClearLastSubmitedData (url)
{
  //alert ("Is top = " + (this.window == window.top));
  // alert ("ClearLastSubmitedData(): " + "document.referrer = \""+document.referrer+"\" document.location =\""+document.location+"\"")
  
  //if (this.window == window.top)
  {
    if (document.referrer == document.location || /\.cgi$/.test (document.location.pathname))
    {
      // IE resets the referrer to "" when you replace the url. Netscape and FireFox
      // do not and will go into an infinite loop of reloading the browser. So if we
      // are not on IE we go to a temp page and back. We may have to tweek this for 
      // other browsers.
      if (isIE)
      {
        window.location.replace ((url == null)? document.referrer : url);
      }
      else
      {
        if (url == null || "/"+url == document.location.pathname) window.location.replace ("a_windowreloader.htm");
        else window.location.replace (url);
      }
    }
  }
}

function UpdateNavReloadCB (object)
{
  SetForceNavReload (GetObjectOValue (object) != object.checked.toString ());
}

function MM_OnLanguageChange(value)
{
  WA_setCookie(WACookieDef1,'langchoice',value,true,0);
  top.location.href = top.location.protocol+"//"+top.location.host;
}

function LoadScript(url)
{
  document.write('<script src="' + url +'" type="text/JavaScript"><\/script>');
}

function GetOOBNextPage (currentPage)
{
  switch (currentPage)
  {
    case "a_oobsetup.htm": return "a_lansettings.htm";
    case "a_lansettings.htm":
      if (!isReagan) return "a_monitors.htm";
    case "a_monitors.htm": 
      if (IsBRI ()) return "a_brinetwork.htm";
      else if (IsPRI ()) return "a_prinetwork.htm";
      else return "a_globaladdressserver.htm";
    case "a_brinetwork.htm": return "a_globaladdressserver.htm";
    case "a_prinetwork.htm": return "a_globaladdressserver.htm";
    case "a_globaladdressserver.htm": return "a_oobsetup7.htm";
    case "a_oobsetup7.htm": 
    {
      // password is changed thru softupdate, don't serve security page (just as in embeddedUI)
      return (isDefaultPassword()) ? "a_security.htm" : "a_rebootmeter.htm";  
    }
//    case "a_oobsetup8.htm": return "a_rebootmeter.htm?"+escape("http://"+location.host);
    case "a_security.htm": return "a_rebootmeter.htm";
    default: return "error";
  }
}

function GetOOBBackPage (currentPage)
{
  switch (currentPage)
  {
    case "a_oobsetup.htm": return null;
    case "a_lansettings.htm": return "a_oobsetup.htm";
    case "a_monitors.htm": return "a_lansettings.htm";
    case "a_brinetwork.htm":
    case "a_prinetwork.htm": return (!isReagan) ? "a_monitors.htm" : "a_lansettings.htm";
    case "a_globaladdressserver.htm":
      if (IsBRI ()) return "a_brinetwork.htm";
      else if (IsPRI ()) return "a_prinetwork.htm";
      else return (!isReagan) ? "a_monitors.htm" : "a_lansettings.htm";
    case "a_oobsetup7.htm": return "a_globaladdressserver.htm";
    case "a_security.htm": return "a_oobsetup7.htm";
  }
}


function SetSelectedOption(list, selectedValue)
{
  for(var i = 0; i < list.options.length; i++)
  {
    if (list.options[i].value == selectedValue || list.options[i].text == selectedValue)
    {
      list.options[i].selected = true;
      return
    }
  }
  if (list.options.length > 0) list.options[0].selected = true
}

function GetRadioValue(button)
{
  var index
  var list = document.getElementsByName (button.name)
  for (index = 0; index < list.length; index++)
  {
    if (list[index].checked)
    {
     // alert ("GetRadioValue: "+list[index].value)
      return list[index].value
    }
  }
  return ""
}

function SetRadioValue(button, value)
{
  var index
  var list = document.all [button.name]
  //alert ("SetRadioValue(button, "+value+")")
  for (index = 0; index < list.length; index++)
  {
    if (list[index].value == value)
    {
      list[index].checked = true
      return
    }
  }
  list[0].checked = true
}

function GetSelectedOptionText(list)
{
  if (list.selectedIndex != -1) return list.options [list.selectedIndex].text
  return ""
}

function GetSelectedOption(list)
{
  if (list.selectedIndex != -1) return list.options [list.selectedIndex].value
  else return ""
}

function ReloadInFrameWork ()
{
  // If this window is the top window then we need to reload it in side the 
  // framework
  if ((window.top == self) && !isOOB && !kAllowDirectHTMLFileAccess && 
    !IsIndexURL (window.location.pathname))
  {
    fileName = window.location.pathname.substring (1);
      // alert ("Reloading " + fileName + " into the frame work.");
    window.location.pathname = "u_index2.htm?startpage="+fileName;
  }
}

function TranslateLangConst (id)
{
  if (!id)
  {
    text = ""
  }
  else
  {
    try
    {
      text = eval (id.toUpperCase ())
    }
    catch (e)
    {
      try
      {
        text = eval (id.toUpperCase ()+"_STR")
      }
      catch (e)
      {
        text = id
      }
    }
  }
  return text
}

function SPrintF (format)
{
  var index  
  for (index = 1; index < arguments.length; index++)
  {
    format = format.replace (/%s|%d/, (arguments[index] != "null") ? arguments[index] : "Unknown")
  }
  return format
}
function CheckForJava ()
{
  if (navigator.javaEnabled ())
  {
    try
    {
      document.write ('<applet code="DetectJVM.class" name="detectjvmapplet" width="0" height="0"></applet>')
      var javaVersion = parseFloat(document.detectjvmapplet.getJavaVersion())
  
      if (javaVersion < 1.2)
      {
        alert (SPrintF (WEB_JAVA_VERSION), javaVersion)
      }
    }
    catch (e)
    {
    }
  }
  else
  {
     alert (JAVAPLUG_REQUIRED)
    //document.location.replace ("u_enablejava.htm")
  }
}

function ResetIfInCall (object, text)
{
  if (callCount > 0)
  {
    alert ((text) ? text : NOT_AVAIL_INACALL)
    ResetObjectToPreviousValue (object, false)
    return true
  }
  return false
}

function ResetObjectToPreviousValue (object, executeOnChange)
{
  if (executeOnChange == null) executeOnChange = true
  
  var pValue = GetObjectPValue (object)
  if (pValue != GetObjectValue (object))
  {
    SetObjectValue (object, pValue, executeOnChange)
  }
}

function Inst2Postfix (instance) {return (instance > 1) ? instance - 1 : ""}
function IsTrue (value) {return /^ *(true|1) *$/i.test (value)}
