//
// 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";
var ROWSHADE_LT = "#F8F8FF";
var ROWSHADE_DK = "#EEEEFF";

// verifies that the form has no errors
function checkForm() {
  return formSubmitted;
}

// initializes a page
function initPage(hasForm) {
  setStatus("");
  if (hasForm) {
    form = document.forms[0];
    formSubmitted = false;
    try { form.autocomplete = "off"; } catch (e) {}
    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;
}

// submit a page
//function submitPage(param) {
//  if (formSubmitted) return false;
//  else return submitForm(param);
//}

// 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);
  parent.mainframe.location.replace(getCookie("storeHttp") + "GoBack?" + frompage);
  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 for the selected help topic
function showHelp(helpTopic) {

  var helpName, helpFrame, helpText, helpWindow;

  // default to the standard user help
  if ((helpTopic == null) || (helpTopic == "")) helpTopic = "";

  // initialize for the help that is to be displayed
  if (startsWith(helpTopic, "Adm")) {
    helpName  = "AdminHelp";
    helpFrame = "html/admin/admhelp.html?";
    helpText  = "html/admin/admhelptext.html#";
  } else if ((startsWith(helpTopic, "Csr"))
         ||  (startsWith(helpTopic, "Sfi"))) {
    helpName  = "SfiHelp";
    helpFrame = "html/sfi/sfihelp.html?";
    helpText  = "html/sfi/sfihelptext.html#";
  } else {
    helpName  = "UserHelp";
    helpFrame = "html/help.html?";
    helpText  = "html/helptext.html#";
  }

  // show the help window
  helpWindow = openPopup(helpName, true, 520, 480);
  if (helpWindow.frames.length < 3) {
    helpWindow.location = getCookie("storeHttp") + helpFrame + helpTopic;
  } else {
    helpWindow.helptextframe.location = getCookie("storeHttp") + helpText + helpTopic;
    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. assumes
// no scrollbars
function openPopup(name, resizable, width, height) {
  return openPopup2(name, resizable, false, width, height);
}

// opens a popup window that is centered on the user's screen
// and returns a reference to the popup window object
function openPopup2(name, resizable, scrollbars, width, height) {
  // create the base popup window parameters
  var params = "resizable="   + (resizable  ? "yes" : "no")
             + ",scrollbars=" + (scrollbars ? "yes" : "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 site administration frameset is active
function isSiteAdmin() {
  return getCookie("storeMode") == "siteadmin";
}

// determines if the sfi account selection frameset is active
function isSfiSelect() {
  return getCookie("storeMode") == "sfiselect";
}

// determines if the sfi shopping frameset is active
function isSfiShopping() {
  return getCookie("storeMode") == "sfishopping";
}

// determines if the standard shopping frameset is active
function isShopping() {
  return getCookie("storeMode") == "shopping";
}

// 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 (isSfiShopping()) {
      parent.bannerframe.location.replace(getCookie("storeHttp") + "sfi/SfiBanner");
    } else {
      parent.bannerframe.location.replace(getCookie("storeHttp") + "Banner");
    }
  }
}

// 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 (isSfiShopping()) {
      parent.navbarframe.location.replace(getCookie("storeHttp") + "sfi/SfiNavbar");
    } else if (isShopping()) {
      parent.navbarframe.location.replace(getCookie("storeHttp") + "Navbar");
    }
  }
}

// reloads the categories frame...
// invoked directly by various template onunload() events or
// indirectly by the reloadFrames() function below
function reloadCategories() {
  if ((isShopping()) || (isSfiShopping())) {
    var reload = getCookie("reloadcategories");
    setCookie("reloadcategories", "false");
    if ((reload != null) && (reload == "true")) {
      if (isNetscape()) parent.contentsframe1.location.reload();
      else parent.contentsframe1.location.replace(getCookie("storeHttp") + "Categories");
    }
  }
}

// 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);
}

// shows a selected special
function showSpecial(specialcode) {
//alert(getCookie("storeHttp") + "Specials?Type=" + specialcode);
  parent.contentsframe2.location.replace(getCookie("storeHttp") + "Specials?Type=" + specialcode);
  return false; // cancel hyperlink
}

// 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
  var exp = new Date();
  exp.setMonth(exp.getMonth()+1);
  document.cookie = "cookies" + "=" + escape("enabled") + "; path=/; expires=" + exp.toGMTString();

  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("/ecomm/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 ReShop.html and ReLogon.html
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 ReShop or ReLogon, exit
  if ((pagename != "ReShop.html")
  &&  (pagename != "ReLogon.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("/ecomm/html/BrowserError.html");
  return true;
}

// sets the alternating table row shading for the current page.
// handles up to 3 different sets of table rows per page
function shadeRows() {
  var i, j, rows, cells, shade;
  // the 1st set of table rows (default)
  rows = document.getElementsByName("rowshade");
  for (i = 0; i < rows.length; i++) {
    shade = (i % 2 == 0 ? ROWSHADE_LT : ROWSHADE_DK);
    cells = rows[i].getElementsByTagName("td");
    for (j = 0; j < cells.length; j++) {
      cells[j].style.backgroundColor = shade;
    }
  }
  // the 2nd set of table rows
  rows = document.getElementsByName("rowshade2");
  for (i = 0; i < rows.length; i++) {
    shade = (i % 2 == 0 ? ROWSHADE_LT : ROWSHADE_DK);
    cells = rows[i].getElementsByTagName("td");
    for (j = 0; j < cells.length; j++) {
      cells[j].style.backgroundColor = shade;
    }
  }
  // the 3rd set of table rows
  rows = document.getElementsByName("rowshade3");
  for (i = 0; i < rows.length; i++) {
    shade = (i % 2 == 0 ? ROWSHADE_LT : ROWSHADE_DK);
    cells = rows[i].getElementsByTagName("td");
    for (j = 0; j < cells.length; j++) {
      cells[j].style.backgroundColor = shade;
    }
  }
}
