//
// JavaScript for all web pages
//

// define global variables
var form = null;
var formSubmitted = false;
var errCode     = "";
var errField    = "";
var errFieldNdx = 0;
var errFieldDsc = "";
var validChars  = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";


// initializes a page
function initPage(hasForm) {
  setStatus("");
  if (hasForm) {
    form = document.forms[0];
    formSubmitted = false;
    errFieldNdx = -1;
    if (form.ErrCode != null)  errCode  = form.ErrCode.value;
    else errCode = "";
    if (form.ErrField != null) errField = form.ErrField.value;
    else errField = "";
    return initForm();
  } else return true;
}

// verifies that a form has been submitted as the result
// of a chosen action vs. by an assumed action (such as
// Enter being pressed in an input field)
function isSubmitted() {
  return formSubmitted;
}

// submits a selected function
function submitFunction(ffSelect) {
  if (!form) return false; // form not loaded
  if (ffSelect.selectedIndex <= 0) return false; // no selection
  return submitForm(ffSelect.options[ffSelect.selectedIndex].value);
}

// determines if one string (src) contains another string (arg
// (case-sensitive)
function contains(src, arg) {
  return (src.indexOf(arg) >= 0);
}

// determines if one string (src) contains another string (arg)
// (case-insensitive)
function containsIgnoreCase(src, arg) {
  return contains(src.toLowerCase(), arg.toLowerCase());
}

// determines if one string (src) equals another string (arg)
// (case-insensitive)
function equalsIgnoreCase(src, arg) {
  return (src.toLowerCase() == arg.toLowerCase());
}

// determines if one string (src) ends with another string (arg)
// (case-sensitive)
function endsWith(src, arg) {
  return (src.lastIndexOf(arg) == (src.length - arg.length));
}

// determines if one string (src) starts with another string (arg)
// (case-sensitive)
function startsWith(src, arg) {
  return (src.indexOf(arg) == 0);
}

// returns the primary version of the user's browser
function getBrowserVersion() {
  var tempstr, version;
  tempstr = navigator.appVersion.toLowerCase();
  if (isMicrosoft()) {
    tempstr = tempstr.substring(tempstr.indexOf("msie") + 4);
    version = trim(tempstr.substring(0, tempstr.indexOf(";")));
  } else if (isNetscape()) {
    version = trim(tempstr.substring(0, tempstr.indexOf(".")));
  } else {
    version = trim(tempstr.substring(0, tempstr.indexOf(".")));
  }
  return version;
}

// returns a cookie value by variable name
function getCookie(name) {
  var allcookies = document.cookie;
  if ((allcookies == null) || (allcookies == "")) return null;
  var varname = name + "=";
  var cookies = allcookies.split(";");
  for (var i = 0; i < cookies.length; i++) {
    if (contains(cookies[i], varname)) {
      return unescape(trim(cookies[i]).substring(varname.length));
    }
  }
  return null;
}

// sets a cookie variable name and value (expires with session)
function setCookie(name, value) {
  document.cookie = name + "=" + escape(value) + "; path=/";
}

// corrects for Mac javascript date bug
// IMPORTANT:  this function should only be called once
// for any given date object
function fixDateObject(date) {
  var base = new Date(0);
  var skew = base.getTime(); // dawn of Unix time
  if (skew > 0) {            // should be 0 except on the Mac
    date.setTime(date.getTime() - skew);
  }
}

// go back to a previous page
function goBack() {
  var i;
  var frompage = self.location.pathname;
  if ((i = frompage.lastIndexOf("/")) >= 0) {
    frompage = frompage.substring(i + 1);
  }
  doServlet(encodeURL("GoBack?" + frompage), "mainframe");
  return true;
}

// sets the error field index
function setErrFieldNdx() {
  for (var i = 0; i < form.elements.length; i++) {
    if (form.elements[i].name == errField) {
      errFieldNdx = i;
      break;
    }
  }
  return true;
}

// sets the error field focus
function setErrFieldFocus() {
  if ((errFieldNdx < 0)
  ||  (errFieldNdx >= form.elements.length)) return;
  // if the error field is a text input field,
  // select the field's text
  if ((form.elements[errFieldNdx].type == "text")
  ||  (form.elements[errFieldNdx].type == "password")) {
    form.elements[errFieldNdx].select();
  }
  // set the focus to the error field
  if ((form.elements[errFieldNdx].type == "checkbox")
  ||  (form.elements[errFieldNdx].type == "file")
  ||  (form.elements[errFieldNdx].type == "password")
  ||  (form.elements[errFieldNdx].type == "radio")
  ||  (form.elements[errFieldNdx].type == "select-one")
  ||  (form.elements[errFieldNdx].type == "select-multiple")
  ||  (form.elements[errFieldNdx].type == "text")
  ||  (form.elements[errFieldNdx].type == "textarea")) {
    form.elements[errFieldNdx].focus();
  }
}

// sets the text for the status bar
function setStatus(statustext) {
  self.status = unescape(statustext);
  return true;
}

// shows the help window
function showHelp() {

  var helpFrame, helpWindow;

  // initialize for the help that is to be displayed
  if (isManage())       helpFrame = "docs/manage/help.html";
  else if (isPublish()) helpFrame = "docs/publish/help.html";
  else if (isStage())   helpFrame = "docs/stage/help.html";

  // show the help window
  helpWindow = window.open("", "Help");
  if (helpWindow.frames.length < 3) {
    helpWindow.location = getCookie("siteHttp") + helpFrame;
  } else {
    helpWindow.focus();
  }

  return false; // cancel hyperlink
}

// opens a popup window that is centered on the user's screen
// and returns a reference to the popup window object
function openPopup(name, resizable, width, height) {
  // create the base popup window parameters
  var params = "resizable=" + (resizable  ? "yes" : "no")
             + ",scrollbars=no"
             + ",width="  + width
             + ",height=" + height;
  // if supported, add parameters for centering
  // the popup
  if (getBrowserVersion() >= 4) {
    var posX = (screen.availWidth  / 2) - ((width  / 2) + 2);
    var posY = (screen.availHeight / 2) - ((height / 2) + 12);
    if (isNetscape()) {
      params += ",screenX=" + posX + ",screenY=" + posY;
    } else {
      params += ",left=" + posX + ",top=" + posY;
    }
  }
  // open and return the popup window
  return window.open("", name, params);
}

// determines if the user's browser is Microsoft
function isMicrosoft() {
  return containsIgnoreCase(navigator.appVersion, "MSIE");
}

// determines if the user's browser is Netscape
function isNetscape() {
  return ((containsIgnoreCase(navigator.appName, "Netscape")) ||
          (containsIgnoreCase(navigator.userAgent, "Gecko")));
}

// determines if the content management frameset is active
function isManage() {
  return getCookie("siteMode") == "manage";
}

// determines if the published content frameset is active
function isPublish() {
  return getCookie("siteMode") == "publish";
}

// determines if the staged content frameset is active
function isStage() {
  return getCookie("siteMode") == "stage";
}

// reloads the banner frame...
// invoked directly by various template onunload() events or
// indirectly by the reloadFrames() function below
function reloadBanner() {
  if (isNetscape()) parent.bannerframe.location.reload();
  else {
    if (isManage()) {
      doServlet(encodeURL("manage/M_Banner"), "bannerframe");
    } else if (isPublish()) {
      doServlet(encodeURL("publish/P_Banner"), "bannerframe");
    } else if (isStage()) {
      doServlet(encodeURL("stage/S_Banner"), "bannerframe");
    } else {
    }
  }
}

// reloads the navbar frame...
// invoked directly by various template onunload() events or
// indirectly by the reloadFrames() function below
function reloadNavbar() {
  if (isNetscape()) parent.navbarframe.location.reload();
  else {
    if (isManage()) {
      doServlet(encodeURL("manage/M_Navbar"), "navbarframe");
    } else if (isPublish()) {
      doServlet(encodeURL("publish/P_Navbar"), "navbarframe");
    } else if (isStage()) {
      doServlet(encodeURL("stage/S_Navbar"), "navbarframe");
    } else {
    }
  }
}

// reloads the categories frame...
// invoked directly by various template onunload() events or
// indirectly by the reloadFrames() function below
function reloadCategories() {
  if (isManage()) {
    if (isNetscape()) parent.contentsframe1.location.reload();
    else doServlet(encodeURL("manage/M_Categories"), "contentsframe1");
  }
}

// reloads the banner, navbar and categories frame...
// invoked directly by various template onunload() events
function reloadFrames() {
  reloadBanner();
  reloadNavbar();
  reloadCategories();
}

// returns the given string with leading and trailing spaces removed
function trim(s) {
  var len = 0;
  if (s != null) len = s.length;
  if (len == 0) return s;
  var i = 0;
  var j = len - 1;
  while ((s.charAt(i) == " ") && (i <= j)) i++;
  while ((s.charAt(j) == " ") && (j >= i)) j--;
  return s.substring(i, j + 1);
}

// determines if the user has cookies enabled.  if cookies
// are not enabled, displays a message then redirects to a
// blank page and returns false
function areCookiesEnabled() {

  // attempt to set a test cookie
  setCookie("cookies", "enabled");
  var result = (getCookie("cookies") == "enabled");

  // cookies are not enabled
  if (!result) {
    alert("Cookies must be enabled in order to access this site.");
    top.location.replace("/cms/html/Blank.html");
  }

  return result;
}

// determines if the browser is in a looping state by checking if
// a request for this same page was previously requested within the
// past few seconds.  if looping is detected, redirects to an error
// page and returns true
//
// currently only checks requests for _ReMain.html files
function isBrowserLooping() {

 // determine the current page's name
 var i;
 var pagename = self.location.pathname;
 if ((i = pagename.lastIndexOf("/")) >= 0) {
   pagename = pagename.substring(i + 1);
 }

 // if this is not a request for _ReMain, exit
 if (!contains(pagename, "_ReMain.html")) return false;

 // retrieve the last time a request was made and determine
 // if more than 2000 milliseconds have elapsed. if so, exit
 var lastrequest = getCookie(pagename);
 var thisrequest = new Date().getTime();
 setCookie(pagename, thisrequest);
 if (lastrequest == null) return false;
 if (thisrequest - lastrequest > 2000) return false;

 // the web browser appears to be looping
 top.location.replace("/cms/html/BrowserError.html");
 return true;
}

// displays a common popup message for functions not implemented
function notImplemented(selection) {
  alert("The selected function (" + selection + ") is not yet implemented.");
  return false;  // cancel hyperlink
}

// processes the servlet at the given url and places the results in
// the given target frame. if the target frame is not supplied, the
// mainframe is defaulted. assumes http (non-ssl) if the url is not
// fully qualified.  assumes the url has already been encoded with
// the current session id
function doServlet(url, targetframe) {
  if (!targetframe) targetframe = "mainframe";
  if (startsWith(url, "http")) {
    parent[targetframe].location.replace(url);
  } else {
    parent[targetframe].location.replace(getCookie("siteHttp") + url);
  }
  return false; // cancel hyperlink
}

// encodes the given url with the current session id
function encodeURL(url) {
  var i, path, parm;
  var jid = getCookie("jsessionid");
  if (!jid) jid = getCookie("JSESSIONID");
  if (!jid) return url;
  else {
    if ((i = url.indexOf("?")) >= 0) {
      path = url.indexOf(0, i);
      parm = url.indexOf(i);
    } else {
      path = url;
      parm = "";
    }
    return path + ";jsessionid=" + jid + parm;
  }
}

// enables all fields on the form. some browsers do not submit
// disabled fields to the server, so some form fields may not
// be included in the submitted data if they are disabled
function enableAllFields() {
  for (var i = 0; i < form.elements.length; i++) {
    try { form.elements[i].disabled = false; } catch (e) {}
  }
  return true;
}

// returns the form's index for the given form field object, or
// returns negative one (-1) if the field object is not found
function getFormFieldIndex(ffObject) {
  for (var i = 0; i < form.elements.length; i++) {
    if (form.elements[i] == ffObject) return i;
  }
  return -1;
}

// returns an array of the form's current form field
// values. the elements in the array are in the same
// sequence as they appear within the form
function getFormFieldValues() {

  var i, j, fldobj;
  fldvals = new Array(form.elements.length);

  // iterate through the form's fields
  for (i = 0; i < form.elements.length; i++) {
    fldobj = form.elements[i];
    fldvals[i] = "";
    // for checked checkboxes or radio buttons...
    if (((fldobj.type == "checkbox") && (fldobj.checked))
    ||  ((fldobj.type == "radio")    && (fldobj.checked))) {
      fldvals[i] = fldobj.value;
    // for text entry fields...
    } else if ((fldobj.type == "password")
           ||  (fldobj.type == "text")
           ||  (fldobj.type == "textarea")) {
      fldvals[i] = trim(fldobj.value);
    // for single-selection dropdowns...
    } else if ((fldobj.type == "select-one")
           &&  (fldobj.selectedIndex >= 0)) {
      fldvals[i] = fldobj.options[fldobj.selectedIndex].value;
    // for multiple-selection dropdowns...
    } else if ((fldobj.type == "select-multiple")
           &&  (fldobj.selectedIndex >= 0)) {
      for (j = 0; j < fldobj.options.length; j++) {
        if (fldobj.options[j].selected) {
          fldvals[i] += fldobj.options[j].value;
        }
      }
    }
  }

  // return the form's field values
  return fldvals;
}

// dumps the contents of the given frame to a popup window
// (works only for Internet Explorer 4.0 and higher)
function dumpFrameContents(framename) {

  if (!isMicrosoft()) {
    alert("This function works only in Internet Explorer.");
    return false; // cancel hyperlink
  }

  if (!parent[framename]) {
    alert("The requested frame (" + framename + ") does not exist.");
    return false; // cancel hyperlink
  }

  var dumpwindow = window.open("", "Dump", "resizable=yes,scrollbars=yes,width=800,height=600");
  dumpwindow.document.open("text/plain", "replace");

  var srcdoc = parent[framename].document.all.tags("HTML");
  for (var i = 0; i < srcdoc.length; i++) {
    dumpwindow.document.writeln(srcdoc[i].innerHTML);
  }
  dumpwindow.document.close();

  return false; // cancel hyperlink
}

