function clearForms()
{
    var i;
    for (i = 0; (i < document.forms.length); i++)
    {
        document.forms[i].reset();
    }
}

function popWindow(url, name)
{
  var contextWindow = window.open(url, name, 'width=800,height=600,resizable=1,scrollbars=1,toolbar=0,status=1');
  contextWindow.focus();
  return false;
}

function popWindowOptions(url, name, options)
{
  var contextWindow = window.open(url, name, options);
  contextWindow.focus();
  return false;
}

function findObj(obj)
{
  var dom = document.getElementById? 1 : 0;
  var ie = document.all? 1 : 0;
  var ns = document.layers? 1 : 0;
  var found, doc;
  doc = document;
  if (!(found = doc[obj]) && ie)
  {
    found = doc.all[obj];
  }
  for (i=0; !found && i < doc.forms.length; i++)
  {
    found = doc.forms[i][obj];
  }
  for (i=0; !found && ns && i < doc.layers.length; i++)
  {
    found = find(obj, doc.layers[i].document);  
  }
  if (!found && dom)
  {
    found = document.getElementById(obj);
  }
  return (found);
}

function show(id)
{
  objectToShow = findObj(id);
  objectToHide = findObj(id+'Password');
  objectToShow.style.display = "";
  objectToHide.style.display = "none";
  objectToShow.focus();
}

function hide(id)
{
  objectToHide = findObj(id);
  objectToShow = findObj(id+'Password');
  objectToShow.style.display = "";
  objectToHide.style.display = "none";
  objectToShow.value = objectToHide.value;
}

function preventPasteWithKeyboardForNetscape(evt)
{
  // onkeypress fires if the user presses Ctrl-V on the keyboard in Netscape.
  // onkeypress does not fire for Ctrl-V in IE.
  var isCtrl;
  var keyCode;
  var keyLetter;
  if(window.event)
  {
    // IE:
    isCtrl = (window.event.ctrlKey) ? true : false;
    keyCode = window.event.keyCode;
  }
  else
  {
    // Netscape
    isCtrl = (evt.ctrlKey) ? true : false;
    keyCode = evt.charCode;
  }
  keyLetter = String.fromCharCode(keyCode).toLowerCase();
  if(isCtrl && keyLetter == "v")
  {
    if (window.event)
    {
      // IE
      return false;
    }
    else
    {
      // Netscape
      evt.preventDefault();
    }
  }
  return true;
}

function hide2(id)
{
  var div;
  if (document.getElementById)
  {
    div = document.getElementById(id).style;
  }
  else if (document.layers)
  {
    div = document.layers[id];
  }
  else if (document.all)
  {
    div = document.all(id).style;
  }
  if (div)
  {
    div.visibility = 'hidden';
  }
}

/**
 * AJAX methods
 *
 * 1) Call retrieveURL from the relevant event on the HTML page (e.g. onclick)
 * 2) Pass the url to contact (e.g. Struts Action) and the name of the HTML form to post
 * 3) When the server responds ...
 *    - the script loops through the response , looking for <span id="name">newContent</span>
 *    - each <span> tag in the *existing* document will be replaced with newContent
 *
 * NOTE: <span id="name"> is case sensitive. Name *must* follow the first quote mark and end in a quote.
 *       Everything after the first '>' mark until </span> is considered content.
 *       Empty sections should be in the format <span id="name"></span>
 */

//global variables
var xmlHttpReq;

function ajaxProductLookup(parameters)
{
  var url = "/do/ajax/productLookup"
  if (parameters && parameters.length)
  {
    url = url + "?" + parameters;
  }
  retrieveURL(url, null);
}

function ajaxOff(id)
{
  var newHtml = "<span id=\"" + id + "\">";
  spanElements = splitTextIntoSpan(newHtml);
  replaceExistingWithNewHtml(spanElements);
}

/**
 * Get the contents of the URL.
 * url - to get content from (e.g. /struts-ajax/sampleajax.do?ask=COMMAND_NAME_1) 
 * nodeToOverWrite - when callback is made
 * nameOfFormToPost - which form values will be posted up to the server as part 
 *					of the request (can be null)
 */
function retrieveURL(url, nameOfFormToPost) 
{
  // get the (form based) params to push up as part of the get request
  if (nameOfFormToPost && nameOfFormToPost.length)
  {
    url = url + getFormAsString(nameOfFormToPost);
  }
    
  // Mozilla/Safari
  if (window.XMLHttpRequest) 
  { 
    xmlHttpReq = new XMLHttpRequest();
    xmlHttpReq.overrideMimeType('text/xml');
    try 
    {
      xmlHttpReq.open("GET", url, true);
      xmlHttpReq.onreadystatechange = processStateChange;
    } 
    catch (e) 
    {
      alert("Problem Communicating with Server\n" + e);
    }
    xmlHttpReq.send(null);
  } 
  // IE
  else if (window.ActiveXObject) 
  { 
    xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    if (xmlHttpReq) 
    {
      xmlHttpReq.open("GET", url, true);
      xmlHttpReq.onreadystatechange = processStateChange;
      xmlHttpReq.send();
    }
  }
}

/*
 * Callback method for when XmlHttpRequest state changes.
 * Used by retrieveUrl().
 */
function processStateChange() 
{
  // complete state
  if (xmlHttpReq.readyState == 4) 
  { 
    // OK status
    if (xmlHttpReq.status == 200) 
    { 
      // split the text response into span elements
      spanElements = splitTextIntoSpan(xmlHttpReq.responseText);
        
      // use these span elements to update the page
      replaceExistingWithNewHtml(spanElements);
    } 
    else 
    {
      strResponse = xmlHttpReq.responseText;
      switch (xmlHttpReq.status)
      {
        // page-not found error
        case 404:
          alert('Error 404: The requested URL could not be found.');
          break;
        // server-side errors
        case 500:
          popupErrorMessage(strResponse);
          break;
        default:
          popupErrorMessage(strResponse);
          break;
      }
    }
  }
}
 
/**
 * gets the contents of the form as a URL encoded String
 * suitable for appending to a url
 * @param formName to encode
 * @return string with encoded form values , beings with &
 */ 
function getFormAsString(formName)
{
  var returnString ="";
 	
  // get the form values
  formElements = document.forms[formName].elements;

  for (var i = formElements.length-1; i >= 0; --i)
  {
    returnString = 
      returnString + "&" +
      escape(formElements[i].name) + "=" + 
      escape(formElements[i].value);
  }

  return returnString; 
 }
 
/**
 * Split the text into <span> elements.
 *
 * @param the text to be parsed
 * @return array of <span> elements - this array can contain nulls
 */
function splitTextIntoSpan(textToSplit)
{
  // split the document
  returnElements = textToSplit.split("</span>")
 	
  // process each of the elements 	
  for (var i = returnElements.length-1; i >= 0; --i)
  {
    // remove everything before the 1st span
    spanPos = returnElements[i].indexOf("<span");		
 		
    // if we find a match, take out everything before the span
    if(spanPos > 0)
    {
      subString = returnElements[i].substring(spanPos);
      returnElements[i] = subString;
    } 
  }

  return returnElements;
}
 
/*
 * Replace html elements in the existing (viewable document)
 * with new elements (from the ajax requested document)
 * where they have the same name AND are <span> elements.
 *
 * @param newTextElements (output of splitTextIntoSpan) in the format <span id=name>texttoupdate
 */
function replaceExistingWithNewHtml(newTextElements)
{
  for (var i = newTextElements.length-1; i >= 0; --i)
  {
    // check that this begins with <span
    if (newTextElements[i].indexOf("<span") > -1)
    {
      // get the name - between the 1st and 2nd quote mark
      startNamePos = newTextElements[i].indexOf('"') + 1;
      endNamePos = newTextElements[i].indexOf('"',startNamePos);
      name = newTextElements[i].substring(startNamePos,endNamePos);
 			
      // get the content - everything after the first > mark
      startContentPos = newTextElements[i].indexOf('>') + 1;
      content = newTextElements[i].substring(startContentPos);
 			
      // check that this element exists in the document
      if( document.getElementById(name))
      {
        // update the existing document with this element
	document.getElementById(name).innerHTML = content;
      }
      else 
      {
        alert("Element:"+name+"not found in existing document");
      }
    }
  }
}

function popupErrorMessage(message)
{
  var popupWindow;

  // create new window and display message
  try
  {
    popupWindow = window.open('', 'Error Message Window');
    popupWindow.document.body.innerHTML = message;
  }
  // if pop-up gets block, inform user
  catch (e)
  {
    alert("An error occurred, but the error message cannot be displayed " +
          "because of your brower's pop-up blocker.\n" +
          "Please allow pop-ups from this web site.");
  }
}
