/**
 * Framework Common JavaScript Library
 */

/* Retrieve any arguments passed to the module.*/
var args = new Object();

/* Stores the server-side JavaScript prior to submit.*/
var fwModuleScriptBuffer = '';

/* Store a reference to Open windows.*/
var windowControl;

/* Response URL.*/
var responseURL = '';

/* Variable to control submitting a related page.*/
/* This occurs when one page loads, and must load another page.*/
var submitOnLoadTarget = null;

/* Control variable for page submits.*/
var submitInProcess = false;

/* Control variable for save process.*/
var saveInProcess = false;

/* Control variable for pending modifications.*/
var fwModuleModified = false;

/* Control variable for validation.*/
var fwIgnoreValidation = false;

/* Last key pressed, used for autotab feature.*/
var lastKey = 0;

/* Last submit time.*/
var fwLastSubmitTime = 0;

/**
 * Extend the String object with a trim() function.
 */
String.prototype.trim = new Function("return this.replace(/^\\s+|\\s+$/,'')");

/**
 * Test function.
 */
function hello()
{
  alert("Hello");
}//function hello()

/****************************************************************************
 * Date functions
 ****************************************************************************/
 /**
  * The basis for these functions were contributed by Matt Kruse,
  * and are used with his permission. These functions may be used as
  * part of WebAccel applications by licensed customers, but may not be
  * distributed independently.
  *
  * All functions have been modified to be included as prototypes of
  * the standard Date object.
  *
  * Author: Matt Kruse <matt@mattkruse.com>
  * WWW: http: *www.mattkruse.com/
  *
  * NOTICE: You may use this code for any purpose, commercial or
  * private, without any further permission from the author. You may
  * remove this notice from your final code if you wish, however it is
  * appreciated by the author if at least my web site address is kept.
  *
  * You may *NOT* re-distribute this code in any way except through its
  * use. That means, you can include it in your product, or your web
  * site, or any other form where the code is actually being used. You
  * may not put the plain javascript up on your site for download or
  * include it in your javascript libraries for download.
  * If you wish to share this code with others, please just point them
  * to the URL instead.
  * Please DO NOT link directly to my .js files from your site. Copy
  * the files to your server and use them there. Thank you.
  * ===================================================================

  * ------------------------------------------------------------------
  * These functions use the same 'format' strings as the
  * java.text.SimpleDateFormat class, with minor exceptions.
  * The format string consists of the following abbreviations:
  *
  * Field        | Full Form          | Short Form
  * -------------+--------------------+-----------------------
  * Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
  * Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
  * Day of Month | dd (2 digits)      | d (1 or 2 digits)
  * Day of Week  | EE (name)          | E (abbr)
  * Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
  * Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
  * Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
  * Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
  * Minute       | mm (2 digits)      | m (1 or 2 digits)
  * Second       | ss (2 digits)      | s (1 or 2 digits)
  * AM/PM        | a                  |
  *
  * NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
  * Examples:
  *  "MMM d, y" matches: January 01, 2000
  *                      Dec 1, 1900
  *                      Nov 20, 00
  *  "M/d/yy"   matches: 01/20/00
  *                      9/2/00
  *  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
  */

 Date.MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
 Date.DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
 Date.LZ = function(x) {return(x<0||x>9?"":"0")+x};

 /**
  * Date.isDate ( date_string, format_string )
  * Returns true if date string matches format of format string and
  * is a valid date. Else returns false.
  * It is recommended that you trim whitespace around the value before
  * passing it to this function, as whitespace is NOT ignored!
  */
 Date.isDate = function(val,format)
 {
   var date=Date.getDateFromFormat(val,format);
   if (date==0) { return false; }
   return true;
 }//Date.isDate = function(val,format)

 /**
  * Date.compareDates(date1,date1format,date2,date2format)
  *   Compare two date strings to see which is greater.
  *   Returns:
  *   1 if date1 is greater than date2
  *   0 if date2 is greater than date1 of if they are the same
  *  -1 if either of the dates is in an invalid format
  */
 Date.compareDates = function(date1,dateformat1,date2,dateformat2)
 {
   var d1=Date.getDateFromFormat(date1,dateformat1);
   var d2=Date.getDateFromFormat(date2,dateformat2);
   if (d1==0 || d2==0) {
     return -1;
     }
   else if (d1 > d2) {
     return 1;
     }
   return 0;
 }//Date.compareDates = function(date1,dateformat1,date2,dateformat2)

 /**
  * Date.format (date_object, format)
  * Returns a date in the output format specified.
  * The format string uses the same abbreviations as in Date.getDateFromFormat()
  */
 Date.format = function(date,format)
 {
   format=format+"";
   var result="";
   var i_format=0;
   var c="";
   var token="";
   var y=date.getYear()+"";
   var M=date.getMonth()+1;
   var d=date.getDate();
   var E=date.getDay();
   var H=date.getHours();
   var m=date.getMinutes();
   var s=date.getSeconds();
   var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
   // Convert real date parts into formatted versions
   var value=new Object();
   if (y.length < 4) {y=""+(y-0+1900);}
   value["y"]=""+y;
   value["yyyy"]=y;
   value["yy"]=y.substring(2,4);
   value["M"]=M;
   value["MM"]=Date.LZ(M);
   value["MMM"]=Date.MONTH_NAMES[M-1];
   value["d"]=d;
   value["dd"]=Date.LZ(d);
   value["E"]=Date.DAY_NAMES[E+7];
   value["EE"]=Date.DAY_NAMES[E];
   value["H"]=H;
   value["HH"]=Date.LZ(H);
   if (H==0){value["h"]=12;}
   else if (H>12){value["h"]=H-12;}
   else {value["h"]=H;}
   value["hh"]=Date.LZ(value["h"]);
   if (H>11){value["K"]=H-12;} else {value["K"]=H;}
   value["k"]=H+1;
   value["KK"]=Date.LZ(value["K"]);
   value["kk"]=Date.LZ(value["k"]);
   if (H > 11) { value["a"]="PM"; }
   else { value["a"]="AM"; }
   value["m"]=m;
   value["mm"]=Date.LZ(m);
   value["s"]=s;
   value["ss"]=Date.LZ(s);
   while (i_format < format.length) {
     c=format.charAt(i_format);
     token="";
     while ((format.charAt(i_format)==c) && (i_format < format.length)) {
       token += format.charAt(i_format++);
       }
     if (value[token] != null) { result=result + value[token]; }
     else { result=result + token; }
     }
   return result;
 }//Date.format = function(date,format)

 /**
  * Utility functions for parsing in Date.getDateFromFormat()
  */
 Date._isInteger = function(val)
 {
   var digits="1234567890";
   for (var i=0; i < val.length; i++) {
     if (digits.indexOf(val.charAt(i))==-1) { return false; }
     }
   return true;
 }//Date._isInteger = function(val)

 Date._getInt = function(str,i,minlength,maxlength)
 {
   for (var x=maxlength; x>=minlength; x--) {
     var token=str.substring(i,i+x);
     if (token.length < minlength) { return null; }
     if (Date._isInteger(token)) { return token; }
     }
   return null;
 }//Date._getInt = function(str,i,minlength,maxlength)

 /**
  * Date.getDateFromFormat( date_string , format_string )
  *
  * This function takes a date string and a format string. It matches
  * If the date string matches the format string, it returns the
  * getTime() of the date. If it does not match, it returns 0.
  */
 Date.getDateFromFormat = function(val,format)
 {
   val=val+"";
   format=format+"";
   var i_val=0;
   var i_format=0;
   var c="";
   var token="";
   var token2="";
   var x,y;
   var now=new Date();
   var year=now.getYear();
   var month=now.getMonth()+1;
   var date=1;
   var hh=now.getHours();
   var mm=now.getMinutes();
   var ss=now.getSeconds();
   var ampm="";

   if(format == null || format == '')
   {
    return 0;
   }//if(format == null || format == '')

   while (i_format < format.length) {
     // Get next token from format string
     c=format.charAt(i_format);
     token="";
     while ((format.charAt(i_format)==c) && (i_format < format.length)) {
       token += format.charAt(i_format++);
       }
     // Extract contents of value based on format token
     if (token=="yyyy" || token=="yy" || token=="y") {
       if (token=="yyyy") { x=4;y=4; }
       if (token=="yy")   { x=2;y=2; }
       if (token=="y")    { x=2;y=4; }
       year=Date._getInt(val,i_val,x,y);
       if (year==null) { return 0; }
       i_val += year.length;
       if (year.length==2) {
         if (year > 70) { year=1900+(year-0); }
         else { year=2000+(year-0); }
         }
       }
     else if (token=="MMM"){
       month=0;
       for (var i=0; i<Date.MONTH_NAMES.length; i++) {
         var month_name=Date.MONTH_NAMES[i];
         if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
           month=i+1;
           if (month>12) { month -= 12; }
           i_val += month_name.length;
           break;
           }
         }
       if ((month < 1)||(month>12)){return 0;}
       }
     else if (token=="EE"||token=="E"){
       for (var i=0; i<Date.DAY_NAMES.length; i++) {
         var day_name=Date.DAY_NAMES[i];
         if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
           i_val += day_name.length;
           break;
           }
         }
       }
     else if (token=="MM"||token=="M") {
       month=Date._getInt(val,i_val,token.length,2);
       if(month==null||(month<1)||(month>12)){return 0;}
       i_val+=month.length;}
     else if (token=="dd"||token=="d") {
       date=Date._getInt(val,i_val,token.length,2);
       if(date==null||(date<1)||(date>31)){return 0;}
       i_val+=date.length;}
     else if (token=="hh"||token=="h") {
       hh=Date._getInt(val,i_val,token.length,2);
       if(hh==null||(hh<1)||(hh>12)){return 0;}
       i_val+=hh.length;}
     else if (token=="HH"||token=="H") {
       hh=Date._getInt(val,i_val,token.length,2);
       if(hh==null||(hh<0)||(hh>23)){return 0;}
       i_val+=hh.length;}
     else if (token=="KK"||token=="K") {
       hh=Date._getInt(val,i_val,token.length,2);
       if(hh==null||(hh<0)||(hh>11)){return 0;}
       i_val+=hh.length;}
     else if (token=="kk"||token=="k") {
       hh=Date._getInt(val,i_val,token.length,2);
       if(hh==null||(hh<1)||(hh>24)){return 0;}
       i_val+=hh.length;hh--;}
     else if (token=="mm"||token=="m") {
       mm=Date._getInt(val,i_val,token.length,2);
       if(mm==null||(mm<0)||(mm>59)){return 0;}
       i_val+=mm.length;}
     else if (token=="ss"||token=="s") {
       ss=Date._getInt(val,i_val,token.length,2);
       if(ss==null||(ss<0)||(ss>59)){return 0;}
       i_val+=ss.length;}
     else if (token=="a") {
       if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
       else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
       else {return 0;}
       i_val+=2;}
     else {
       if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
       else {i_val+=token.length;}
       }
     }
   // If there are any trailing characters left in the value, it doesn't match
   if (i_val != val.length) { return 0; }
   // Is date valid for month?
   if (month==2) {
     // Check for leap year
     if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
       if (date > 29){ return 0; }
       }
     else { if (date > 28) { return 0; } }
     }
   if ((month==4)||(month==6)||(month==9)||(month==11)) {
     if (date > 30) { return 0; }
     }
   // Correct hours value
   if (hh<12 && ampm=="PM") { hh=hh-0+12; }
   else if (hh>11 && ampm=="AM") { hh-=12; }
   var newdate=new Date(year,month-1,date,hh,mm,ss);
   return newdate.getTime();
 }//Date.getDateFromFormat = function(val,format)

/****************************************************************************
 * End Date functions
 ****************************************************************************/

/****************************************************************************
 * Number functions
 ****************************************************************************/
/**
 * Number formats are defined in a string with the following syntax:
 *
 * [positiveFormat;][negativeFormat;][groupSeparatorChar;][decimalSeparatorChar;]
 *
 * The positiveFormat is required, all other elements are optional.
 * Valid format characters are:
 *
 * # non-padded digit placeholder
 * 0 padded digit placeholder
 * , grouping separator
 * . decimal separator
 *
 * If groupSeparatorChar or decimalSeparatorChar is provided in the format,
 * these characters are used to replace the standard ',' and '.' chars
 * in the output based on the positiveFormat or negativeFormat strings.
 *
 * All other characters are format characters.
 * Example (USD): $ ###,##0.00;$(###,##0.00);,;.;
 * 1245.56 Output: $1,245.56
 * Example (FR): ###,##0.00 FR;(###,##0.00) FR; ;,;
 * 1245.56 Output: 1 245,56 FR
 */

/**
 * Get a number value from a format, based on a string input.
 * This function also validates the number using the format.
 * If the format is not supplied, it uses the standard decimalSeparator
 * to parse the number.
 * Returns the number as float, or NaN if the number is invalid.
 */
Number.getNumberFromFormat = function(value, format)
{

  var regExp = null;
  var decimalSeparator = '.';
  var groupSeparator = ',';
  var formatSegments = null;
  var matchResult = null;
  var result = 0.0;

  /* Parse the format.*/
  if(format != null)
  {
    formatSegments = format.split(';');
    if(formatSegments.length >= 4)
    {
      decimalSeparator = formatSegments[3];
    }//if(formateSegments.length >= 4)
  }//if(format != null)

  /* Strip the value of non-numeric chars.*/
  regExp = new RegExp("[^0-9-" + decimalSeparator + "]*", 'g');
  value = value.replace(regExp, '');

  /* Ensure the number is valid, having a maximum of one decimalSeparator.*/
  regExp = new RegExp("[" + decimalSeparator + "]", 'g');
  matchResult = value.match(regExp);
  if(matchResult != null)
  {
    if(matchResult.length > 1)
    {
      return NaN;
    }//if(matchResult.length > 1)
  }//if(matchResult != null)

  /* If a decimalSeparator other than '.' is used, replace it.*/
  if(decimalSeparator != '.')
  {
    value = value.replace(regExp, '.');
  }//if(decimalSeparator != '.')

  /* Parse the number as a float.*/
  return parseFloat(value);

}//Number.getNumberFromFormat = function(value, format)

/**
 * Format a number value. Requires a float or integer input.
 * Returns the value as a formatted string, or null if an error occurs.
 */
Number.format = function(value, format)
{
  /* Outline:
   *
   * Validate the value.
   * Convert the value to a string.
   * Parse the positive and negative formats.
   * Set the format to use.
   * Strip any prefix from the format.
   * Get control data.
   * Format to right of decimal.
   * Format to left of decimal.
   * Add any zero pad.
   * Add any prefix.
   */
  var valuePos = -1;
  var formatPos = -1;
  var valueLen = 0;
  var formatLen = 0;
  var i = 0;
  var place = 0;
  var placeCount = 0;
  var valueChar = '';
  var formatChar = '';
  var result = '';
  var posFormat = '';
  var negFormat = '';
  var isNegFormat = false;
  var leftValue = '';
  var leftFormat = '';
  var rightValue = '';
  var rightFormat = '';
  var formatPrefix = '';
  var zeroPad = 0;
  var regExp = null;
  var decimalSeparator = '.';
  var groupSeparator = ',';
  var formatSegments = null;
  var matchResult = null;

  /* Validate the value.*/
  if(isNaN(value) || typeof(value) != 'number')
  {
    alert("The Number.format value parameter is invalid.");
    return null;
  }//if(isNaN(value) || typeof(value) != 'number')

  /* Set the default format if null.*/
  if(format == null)
  {
    format = '0.00;';
  }//if(format == null)

  /* Convert the value to a string.*/
  value = value.toString();

  /* Parse the positive and negative formats.*/
  formatSegments = format.split(';');
  if(formatSegments.length < 1)
  {
    alert("The format is invalid.");
    return null;
  }//if(formatSegments.length < 1)

  posFormat = formatSegments[0];

  if(formatSegments[1] != null)
  {
    negFormat = formatSegments[1];
  }//if(formatSegments[1] != null)
  else
  {
    negFormat = posFormat;
  }//else

  if(formatSegments[2] != null)
  {
    groupSeparator = formatSegments[2];
  }//if(formatSegments[2] != null)

  /* Set the decimalSeparator, or reset it to the default.*/
  if(formatSegments[3] != null)
  {
    decimalSeparator = formatSegments[3];
  }//if(formatSegments[3] != null)
  else
  {
    decimalSeparator = '.';
  }//else

  //alert("posFormat: " + posFormat + " negFormat: " + negFormat
  //  + " groupSeparator: " + groupSeparator + " decimalSeparator: " + decimalSeparator);

  /* Set the format to use.*/
  if(value < 0)
  {
    format = negFormat;
  }//if(value < 0)
  else
  {
    format = posFormat;
  }//else

  /* Strip any prefix from the format.*/
  formatPos = format.indexOf('#');
  if(formatPos == -1)
  {
    formatPos = format.indexOf('0');
  }//if(formatPos == -1)
  if(formatPos == -1 || (format.indexOf(',') != -1 && format.indexOf(',') < formatPos ))
  {
    alert("An invalid format was passed.");
  }//if(formatPos == -1 || (format.indexOf(',') != -1 && format.indexOf(',') < formatPos ))

  formatPrefix = format.substring(0, formatPos);
  format = format.substring(formatPos);

  /* Format to right of decimal.*/

  /* Get control data.*/
  valuePos = value.lastIndexOf('.');
  formatPos = format.lastIndexOf('.');
  if(valuePos != -1)
  {
    rightValue = value.substring(valuePos);
    leftValue = value.substring(0, valuePos);
  }//if(valuePos != -1)
  else
  {
    leftValue = value;
  }//else

  /* Strip any negative sign from the leftValue.*/
  valuePos = leftValue.indexOf('-');
  if(valuePos != -1)
  {
    leftValue = leftValue.substring(valuePos + 1);
  }//if(valuePos != -1)

  if(formatPos != -1)
  {
    rightFormat = format.substring(formatPos);
    leftFormat = format.substring(0, formatPos);
  }//if(formatPos != -1)
  else
  {
    leftFormat = format;
  }//else

  formatLen = rightFormat.length;
  valueLen = rightValue.length;

  /* Loop the format, as any value chars longer than the right of the format are discarded.*/
  for(i=0;i<formatLen;i++)
  {
    if(i < valueLen)
    {
      valueChar = rightValue.charAt(i);
    }//if(i < valueLen)
    else
    {
      valueChar = '';
    }//else

    formatChar = rightFormat.charAt(i);
    switch(formatChar)
    {
      case '.':
        result = decimalSeparator;
        break;
      case '0':
        if(valueChar != '')
        {
          result = result + valueChar;
        }//if(valueChar != '')
        else
        {
          result = result + formatChar;
        }//else
        break;
      case '#':
        if(valueChar != '')
        {
          result = result + valueChar;
        }//if(valueChar != '')
        break;
      default:
        result = result + formatChar;

    }//switch(formatChar)

  }//for(i=0;i<formatLen;i++)

  /* Format to left of decimal.*/

  /* Set control values.*/
  valueLen = leftValue.length;
  formatLen = leftFormat.length;

  /* Compute the placeCount based on comma position.*/
  formatPos = leftFormat.lastIndexOf(',');
  if(formatPos != -1)
  {
    placeCount = formatLen - (formatPos + 1);
  }//if(formatPos != -1)

  /* Get the number of zero chars to pad.*/
  formatPos = leftFormat.indexOf('0');
  if(formatPos != -1)
  {
    zeroPad = formatLen - formatPos;
    /* Zero padding is only valid up to the ',' character in the format.*/
    if(zeroPad > placeCount)
    {
      zeroPad = placeCount;
    }//if(zeroPad > placeCount)
  }//if(formatPos != -1)

  formatPos = leftFormat.length - 1;
  place = 0;

  /* Loop the value, as this determines the length of the result.*/
  for(i=valueLen-1;i>=0;i--)
  {
    valueChar = leftValue.charAt(i);
    result = valueChar + result;

    if(i == 0)
    {
      break;
    }//if(i == 0)

    place++;

    if(place == placeCount && placeCount > 0)
    {
      result = groupSeparator + result;
      place = 0;
    }//if(place == placeCount)
  }//for(i=valueLen-1;i>=0;i--)

  /* Add any zero pad.*/
  if(valueLen < zeroPad)
  {
    for(i=valueLen;i<zeroPad;i++)
    {
      result = '0' + result;
    }//for(i=valueLen;i<zeroPad;i++)
  }//if(i < zeroPad)

  /* Add any Prefix.*/
  result = formatPrefix + result;

  return result;
}//Number.format = function(value, format)

/****************************************************************************
 * End Number functions
 ****************************************************************************/

/****************************************************************************
 * Onload Functions
 ****************************************************************************/

/**
 * Get query arguments.
 */
function getArgs()
{
  var localArgs = new Object();
  var query = location.search.substring(1);
  var nameValuePairs = query.split("&");
  var i = 0;
  var pos = 0;
  var argname = "";
  var value = "";

  for(i=0; i<nameValuePairs.length; i++)
  {
    pos = nameValuePairs[i].indexOf('=');
    if(pos == -1) continue;
    argname = nameValuePairs[i].substring(0, pos);
    value = nameValuePairs[i].substring(pos+1);
    localArgs[argname] = unescape(value);
  }//for(i=0; i<nameValuePairs.length; i++)

  return localArgs;

}//function getArgs()

/**
 * Menu On Load processing.
 */
function doMenuOnLoad(targetFrame)
{

  /* Set up the window control object.*/
  windowControl = new Object();

  /* Show any server messages.*/
  /* If there are server messages, stop further processing.*/
  showFWMessages(targetFrame);

}//function doMenuOnLoad()

/**
 * Perform Menu unload processing.
 */
function doFWMenuOnUnload()
{
  /* Close the user session by calling fwmodulecontrollerservlet.*/
  var url = "fwmodulecontrollerservlet?fwModuleName=none"
    + "&fwModuleAction=closesession";

  /* Disable any onbeforeunload processing.*/
  if(window.onbeforeunload != null)
  {
    window.onbeforeunload = null;
  }//if(window.onbeforeunload != null)
  top.location = url;

}//function doFWMenuOnUnload()

/**
 * Common On Load processing.
 */
function doCommonOnLoad(targetFrame)
{
  /* Initialize the window arguments object.*/
  args = getArgs();
  if(args["fwModuleName"] == null)
  {
    args["fwModuleName"] = targetFrame.document.forms["fwForm"].elements["fwModuleName"].value;
  }//if(args["fwModuleName"] == null)

  /* Perform extension processing.*/
  if(typeof(doAfterCommonOnLoad) == "function")
  {
    doAfterCommonOnLoad(targetFrame);
  }//if(typeof(doAfterCommonOnLoad) == "function")

}//function commonDoOnLoad()

/**
 * Confirm the close with the user. This function is overridden
 * by the Module-type specific code, to check modification of data.
 */
function doOnBeforeUnload()
{
  /* This automatically allows the user to cancel the close.*/
  if(fwModuleModified)
  {
    event.returnValue = "Data on this page has been changed and not saved.\n" +
      "If you exit the page all changes will be lost.";
  }//if(fwModuleModified)
  else
  {
    event.returnValue = "You are about to close the current window.";
  }//else
}//function doOnBeforeUnload()


/** Close the module on unload.
 *
 */
function doFWOnUnload()
{
  /* Close the module instance by calling fwmodulecontrollerservlet.*/
  var url = "fwmodulecontrollerservlet?fwModuleName="
    + args["fwModuleName"] + "&fwModuleAction=close";

  /* Disable any onbeforeunload processing.*/
  if(window.onbeforeunload != null)
  {
    window.onbeforeunload = null;
  }//if(window.onbeforeunload != null)
  top.location = url;

}//function doFWOnUnload()

/**
 * Process a data page onload event for form pages.
 */
function doDataFormOnLoad(targetFrame)
{
  submitInProcess = false;
  if(targetFrame == null)
  {
    return;
  }//if(frameTarget == null)

  /* Process the form.*/
  var fwForm = targetFrame.document.forms["fwForm"];
  if(fwForm != null)
  {
    /* Initialize the form elements.*/
    fwInitForm(fwForm);

    /* Apply formats to data columns.*/
    fwFormatFields(fwForm);

  }//if(fwForm != null)

  /* Show any server messages.*/
  /* If there are server messages, stop further processing.*/
  if(showFWMessages(targetFrame))
  {
    submitOnLoadTarget = null;
    return;
  }//if(showFWMessages(targetFrame))

  /* Submit any related page.*/
  if(submitOnLoadTarget != null)
  {
    submitForm(submitOnLoadTarget, "fwForm");
    submitOnLoadTarget = null;
  }//if(submitOnLoadTarget != null)

  /* Reset the save and modified variables.*/
  if(saveInProcess)
  {
    saveInProcess = false;
    fwModuleModified = false;
  }//if(saveInProcess)

  /* Perform extension processing.*/
  if(typeof(doAfterDataFormOnLoad) == "function")
  {
    doAfterDataFormOnLoad(targetFrame);
  }//if(typeof(doAfterDataFormOnLoad) == "function")

}//function doDataFormOnLoad(targetFrame)

/**
 * Process a data page onload for list pages.
 */
function doDataListOnLoad(targetFrame)
{
  submitInProcess = false;

  /* Show any server messages.*/
  /* If there are server messages, stop further processing.*/
  if(showFWMessages(targetFrame))
  {
    submitOnLoadTarget = null;
    return;
  }//if(showFWMessages(targetFrame))

  /* Submit any related page.*/
  if(submitOnLoadTarget != null)
  {
    submitForm(submitOnLoadTarget, "fwForm");
    submitOnLoadTarget = null;
  }//if(submitOnLoadTarget != null)

  /* Reset the save and modified variables.*/
  if(saveInProcess)
  {
    saveInProcess = false;
    fwModuleModified = false;
  }//if(saveInProcess)

  /* Perform extension processing.*/
  if(typeof(doAfterDataListOnLoad) == "function")
  {
    doAfterDataListOnLoad(targetFrame);
  }//if(typeof(doAfterDataListOnLoad) == "function")

}//function doDataListOnLoad(frameTarget)

/**
 * Process a generic page onload.
 * This is used for blank or other pages which have no data on them.
 */
function doGenericPageOnLoad(targetFrame)
{
  /* Reset the submit variable.*/
  submitInProcess = false;

  /* Reset the save and modified variables.*/
  if(saveInProcess)
  {
    saveInProcess = false;
    fwModuleModified = false;
  }//if(saveInProcess)

}//function doGenericOnLoad(targetFrame)

/**
 * Error Reporter Page OnLoad.
 */
/* timer control variables for doFWErrorReporterOnLoad: */
var timerFlag = 0;
var timerMsg = null;
function doFWErrorReporterOnLoad(targetFrame)
{
  /** Outline:
   * Reset the control variables.
   * Pick up error message from form
   * Skip processing if same error within time interval.
   * Do extension processing - messages/alternate exit strategies
   * Abort processing, or message, if extension calls for that
   * Otherwise, give standard error message
   * Logout the user and return to main menu.
   * Close the frame.
   */

  /* Initialize local control variables. */
  var extControl = new Object();
  extControl["process"] = true;
  extControl["message"] = true;
  /* Set an undefined variable for undefined compares. */
  var undefined;

  /* Reset all control variables. */
  submitOnLoadTarget = null;
  submitInProcess = false;
  saveInProcess = false;
  fwModuleModified = false;

  /* Pick up the error message for passing to extension function, if any. */
  /* The error message is in an fwErrorReporter cell, "exceptionMessage". */
  var errorMsg = targetFrame.document.getElementById("exceptionMessage").innerText;

  /* Multiple error handling logic: */
  if(timerFlag == 0)
  {
    /* set a timer to monitor repeat errors. */
    timerFlag = setTimeout("resetTimerFlag()", 3000);
    timerMsg = errorMsg;
  }
  else
  {
    /* second error while timer still running - check message. */
    if(errorMsg == timerMsg)
    {
      /* same message so skip it. */
      return;
    }//if(errorMsg == timerMsg)
  }//if(timerFlag == 0)

  /* Perform extension processing.*/
  if(typeof(doAfterErrorReporterOnLoad) == "function")
  {
    doAfterErrorReporterOnLoad(targetFrame, extControl, errorMsg);
    if(!extControl["process"])
    {
      return;
    }//if(!extControl["process"])
  }//if(typeof(doAfterErrorReporterOnLoad) == "function")

  /* If no extension ordered message */
  if(extControl["message"])
  {
    alert("A system error has occurred.\n" +
    "Note the error for your system administrator, if desired.\n" +
    "This window will now be switched to login, or closed.");
  }//if(extControl["message"])

  /* Disable any onbeforeunload processing.*/
  if(window.onbeforeunload != null)
  {
    window.onbeforeunload = null;
  }//if(window.onbeforeunload != null)

  /* Initiate logout with the parent - managed windows will have a 'parentWindow' attribute set. */
  if(top.parentWindow !== undefined)
  {
    /* this is a managed child window; i.e., tracked in a windowControl[]. */
    if(typeof top.parentWindow.requestLogout == "function")
    {
      /* requestLogout function exists. */
      top.parentWindow.requestLogout();
    }//if(typeof top.parentWindow.requestLogout == "function")
    window.close();
  }//if(top.parentWindow !== undefined)
  else // will not be null if defined
  {
    /* It is either a popup, opened with showModalDialog or a window opened with
     * window.open.  First check and handle the modal popup as the most frequent case. */
     if(top.dialogArguments !== undefined)
     {
        /* It is a modal dialog.  So, check if it has a parentWindow attribute. */
        var myParent = top.dialogArguments["parentWindow"];
        if( myParent != null)
        {
          /* Then just close the popup and process the requestLogout if it exists. */
          top.close();
          if(typeof myParent.requestLogout == "function")
          {
            /* requestLogout function exists. */
            myParent.requestLogout();
          }
          else
          {
            /* close if no logout to be done. */
            myParent.close();
          }//if(typeof lastParent.requestLogout == "function")
        }//if( myParent != null)
        else
        {
          /* popup has not had 'parentWindow' added to it, so won't be able to do requestLogout. */
          /* All we can do is close the window and let the error occur in the main window. */
          alert("After your popup window closes you should logout of the application.");
          top.close();
        }//if( myParent != null)
     }//if(top.dialogArguments != null)
     else
     {
        /* This is a top level parent or an unmanaged child window.
         * Maybe even a chain of unmanaged windows.  So run down the chain to find
         * the most basic window which has a requestLogout function that can be
         * called.  Then, close the windows in the chain and call the function. */
        var baseWindow = top;
        var lastParent = null;
        do
        {
          /* Get the next parent in the window chain. */
          baseWindow = baseWindow.opener;
          if(baseWindow !== undefined)
          {
            /* Check if this parent supports requestLogout. */
            if(typeof baseWindow.requestLogout == "function")
            {
              lastParent = baseWindow;
            }
          }
          else
          {
            /* out of chain or first one is the base. */
            if(lastParent == null) lastParent = top;
            break; // assumes all windows in chain will have function until bottom.
          }//if(baseWindow !== undefined)

        } while(baseWindow !== undefined);

        if(lastParent != top)
        {
            /* Now close the windows in the chain except the lastParent. */
            baseWindow = top;
            var tempParent = null;
            do
            {
              /* Get the next parent in the window chain and close the child. */
              tempParent = baseWindow.opener;
              if(tempParent !== undefined)
              {
                /* Disable any onbeforeunload processing.*/
                if(baseWindow.onbeforeunload != null)
                {
                  baseWindow.onbeforeunload = null;
                }//if(baseWindow.onbeforeunload != null)
                baseWindow.close();
                baseWindow = tempParent;
              }//if(tempParent !== undefined)
            } while(baseWindow != lastParent);

        }//if(lastParent != top)
        else
        {
          /* this is the top level parent - don't close it */
          if(typeof lastParent.requestLogout == "function")
          {
            /* requestLogout function exists. */
            lastParent.requestLogout();
          }
          else
          {
            /* close if no logout to be done. */
            lastParent.close();
          }//if(typeof lastParent.requestLogout == "function")
        }//if(lastParent != top)
     }//if(top.dialogArguments != null)
  }//if(top.parentWindow !== undefined)

}//function doFWErrorReporterOnLoad(targetFrame)

/* Supporting timer function for doFWErrorReporterOnLoad to control multiple errors. */
function resetTimerFlag()
{
  timerFlag = 0;
  timerMsg = null;
}//function resetTimerFlag()

/**
 * Show any messages on the page.
 */
function showFWMessages(frameTarget)
{
  var fwMessages = null;
  var msg = null;
  var messageCount = 0;
  var displayMessage = '';
  var fwMessageText;
  var j = 0;

  /* Display any errors that may have occurred during Module processing.*/
  /* N.B. Macintosh I.E. 5.0 does not respect namespaces properly which is
   * what resulted in this version replacing the prior algorithm. */
  var fwMessages = frameTarget.document.getElementById("fwMessages");
  if(fwMessages != null)
  {
    /* assume 10 messages is more than enough */
    for( j=1; j <= 10; j++)
    {
      /* Check for each possible message ID */
      msg = frameTarget.document.getElementById("fwMessage" + j);
      if(msg != null)
      {
        /* Display each message in sequence. */
        alert("Application message: \n" + msg.getAttribute("messageText"));
        messageCount++;
      }
      else
      {
        /* No more messages, so exit the loop. */
        break;
      }//if(msg != null)
    }//for( j=1; j <= 10; j++)

    if(messageCount < 1)
    {
      /* No error message return. */
      return false;
    }//if(messageCount < 1)

  /* Error message return. */
    return true;
  }//if(fwMessages != null)

  /* Display any fwMessageText for generic browser independent modules.*/
  fwMessageText = frameTarget.document.forms["fwForm"].elements["fwMessageText"];

  if(fwMessageText != null)
  {
    if(fwMessageText.value != "")
    {
      displayMessage = fwMessageText.value;
      alert("Application message: \n" + displayMessage);
      return true;
    }//if(fwMessageText.value != "")
  }//if(fwMessageText != null)

  return false;

}//function showFWMessages(frameTarget)

/****************************************************************************
 * End Onload Functions
 ****************************************************************************/

/****************************************************************************
 * Opener Functions
 ****************************************************************************/

/**
 * Load the Logon window.
 */
function loadLogon()
{
  window.open("fwLogon.jsp?fwModuleName=genSecurity&fwModuleAction=open", "Logon", "width=423; height=500; top=20; left=185");
}//function loadLogon()

/**
 * Open a Module.
 */
function openModule(moduleType, moduleName, patternImplName)
{
  var url = '';
  var windowOptions = '';

  /* Set the module window options based on the user's resolution.*/
  if(screen.availWidth >= 1280)
  {
    windowOptions = 'width=802,height=530,top=220,left=240,resizable,status=yes';
  }//if(screen.availWidth >= 1280)
  else if(screen.availWidth >= 1024)
  {
    windowOptions = 'width=802,height=530,top=120,left=108,resizable,status=yes';
  }//else if(screen.availWidth >= 1024)
  else if(screen.availWidth >= 800)
  {
    windowOptions = 'width=788,height=540,top=0,left=0,resizable,status=yes';
  }//else if(screen.availWidth >= 800)
  else
  {
    windowOptions = 'width=630,height=423,top=0,left=0,resizable,scrollbars,status=yes';
  }//else

  /* Add to open windows array, check to see if its open and then open it.*/
  if(patternImplName == null)
  {
    patternImplName = 'none';
  }//if(patternImplName == null)
  switch(moduleType)
  {
    case "admin" :
      url = "fwAdminFrame.jsp?fwModuleName=" + moduleName + "&fwModuleAction=open" + "&fwPatternImplName=" + patternImplName;
      break;

    case "slv" :
      url = "fwSLVFrame.jsp?fwModuleName=" + moduleName + "&fwModuleAction=open" + "&fwPatternImplName=" + patternImplName;
      break;
    case "tpg" :
      url = "fwTPGFrame.jsp?fwModuleName=" + moduleName + "&fwModuleAction=open" + "&fwPatternImplName=" + patternImplName;
      break;

  }//switch(moduleType)

  windowControl[moduleName] = window.open(url, moduleName, windowOptions);
}//function openModule(moduleType, moduleName)

/****************************************************************************
 * End Opener Functions
 ****************************************************************************/

/****************************************************************************
 * Server-side Script Functions
 ****************************************************************************/

/* JavaScript control functions for database manipulation.*/
/**
 * Initialize the script buffer.
 * This creates some commonly used control variables which are part of every script.
 */
function initScriptBuffer()
{
  var segment = ''

  /* Reset the script buffer.*/
  fwModuleScriptBuffer = '';

}//function initScript()

/**
 * Build a script segment.
 */
function buildScriptSegment(segment)
{
  /* Concatenate the segment and append a '; ' to terminate it.*/
  fwModuleScriptBuffer = fwModuleScriptBuffer + segment + '; ';
}//function buildScriptSegment(segment)

/**
 * Build a String parameter.
 */
function buildStringParam(paramValue)
{
  return '"' + paramValue + '"';
}//function buildStringParam(paramValue)

/**
 * Build a Number parameter.
 */
function buildNumberParam(paramValue)
{
  return paramValue.toString();
}//function buildNumberParam(paramValue)

/**
 * Build a boolean parameter.
 */
function buildBooleanParam(paramValue)
{
  if(paramValue == null)
  {
    paramValue = false;
  }//if(paramValue == null)
  if(paramValue == '')
  {
    paramValue = false;
  }//if(paramValue == '')
  return paramValue.toString();
}//function buildBooleanParam(paramValue)

/****************************************************************************
 * End Server-side Script Functions
 ****************************************************************************/

/****************************************************************************
 * Framework DataSet Script Functions
 ****************************************************************************/

/**
 * Reset the rowChanged on a dataSet.
 */
function resetRowChanged(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.resetRowChanged(' + buildStringParam(dataSetName) + ' )';
  buildScriptSegment(segment);

}//function resetRowChanged(dataSetName)

/**
 * Set a query parameter.
 */
function setQueryParam(dataSetName, paramName, paramValue)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.setQueryParam(' + buildStringParam(dataSetName) + ', '
    + buildStringParam(paramName) + ', '
    + buildStringParam(paramValue) + ' )';
  buildScriptSegment(segment);

}//function setQueryParam(dataSetName, paramName, paramValue)

/**
 * Execute a query.
 */
function executeQuery(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.executeQuery(' + buildStringParam(dataSetName) + ')';
  buildScriptSegment(segment);

}//function executeQuery(dataSetName)

/**
 * Set the Data Store to a specific row.
 */
function setRow(dataSetName, rowNo)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.setRow(' + buildStringParam(dataSetName) + ', '
    + buildNumberParam(rowNo) + ')';
  buildScriptSegment(segment);

}//function setRow(dataSetName, rowNo)

/**
 * Set the Data Store to the first row.
 */
function setFirstRow(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.setFirstRow(' + buildStringParam(dataSetName) + ')';
  buildScriptSegment(segment);

}//function setFirstRow(dataSetName)

/**
 * Set the Data Store to the next row.
 */
function setNextRow(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.setNextRow(' + buildStringParam(dataSetName) + ')';
  buildScriptSegment(segment);

}//function setNextRow(dataSetName)

/**
 * Set the Data Store to the prior row.
 */
function setPriorRow(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.setPriorRow(' + buildStringParam(dataSetName) + ')';
  buildScriptSegment(segment);

}//function setPriorRow(dataSetName)

/**
 * Set the Data Store to the last row.
 */
function setLastRow(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.setLastRow(' + buildStringParam(dataSetName) + ')';
  buildScriptSegment(segment);

}//function setlastRow(dataSetName)

/**
 * Set the Data Store to the first page.
 */
function setFirstPage(dataSetName, rowsPerPage)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.setFirstPage(' + buildStringParam(dataSetName) + ', '
    + buildNumberParam(rowsPerPage) + ')';
  buildScriptSegment(segment);

}//function setFirstPage(dataSetName, rowsPerPage)

/**
 * Set the Data Store to the next page.
 */
function setNextPage(dataSetName, rowsPerPage)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.setNextPage(' + buildStringParam(dataSetName) + ', '
    + buildNumberParam(rowsPerPage) + ')';
  buildScriptSegment(segment);

}//function setNextPage(dataSetName, rowsPerPage)

/**
 * Set the Data Store to the prior page.
 */
function setPriorPage(dataSetName, rowsPerPage)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.setPriorPage(' + buildStringParam(dataSetName) + ', '
    + buildNumberParam(rowsPerPage) + ')';
  buildScriptSegment(segment);

}//function setPriorPage(dataSetName, rowsPerPage)

/**
 * Set the Data Store to the last page.
 */
function setLastPage(dataSetName, rowsPerPage)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.setLastPage(' + buildStringParam(dataSetName) + ', '
    + buildNumberParam(rowsPerPage) + ')';
  buildScriptSegment(segment);

}//function setLastPage(dataSetName, rowsPerPage)

/**
 * Append a new record to the data set.
 */
function appendRow(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.appendRow(' + buildStringParam(dataSetName) + ')';
  buildScriptSegment(segment);

}//function appendRow(dataSetName)

/**
 * Execute a query if there is no current row for the DataSet.
 */
function executeQueryIfNoRow(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.executeQueryIfNoRow(' + buildStringParam(dataSetName) + ')';
  buildScriptSegment(segment);

}//function executeQueryIfNoRow(dataSetName)

/**
 * Append a new record to the data set if there is no current row.
 */
function appendIfNoRow(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.appendIfNoRow(' + buildStringParam(dataSetName) + ')';
  buildScriptSegment(segment);

}//function appendRow(dataSetName)

/**
 * Insert a new record in the data set.
 */
function insertRow(dataSetName, beforeRowNo)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.insertRow(' + buildStringParam(dataSetName) + ', '
    + buildNumberParam(beforeRowNo) + ')';
  buildScriptSegment(segment);

}//function insertRow(dataSetName, beforeRowNo)

/**
 * Move a row a data set.
 */
function moveRow(dataSetName, rowNo, moveToRowNo)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.moveRow(' + buildStringParam(dataSetName) + ', '
    + buildNumberParam(rowNo) + ', '
    + buildNumberParam(moveToRowNo) + ')';
  buildScriptSegment(segment);

}//function moveRow(dataSetName, rowNo, moveToRowNo)

/**
 * Delete the current record from the data set.
 */
function deleteRow(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.deleteRow(' + buildStringParam(dataSetName) + ')';
  buildScriptSegment(segment);

}//function insertRow(dataSetName, beforeRowNo)

/**
 * Save a specific data set.
 */
function saveDataSet(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.saveBuffer(' + buildStringParam(dataSetName) + ')';
  buildScriptSegment(segment);

  /* Set the save control variable.*/
  saveInProcess = true;
}//function saveDataSet(dataSetName)

/**
 * Clear a specific data set.
 */
function clearDataSet(dataSetName)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.clear(' + buildStringParam(dataSetName) + ')';
  buildScriptSegment(segment);

}//function clearDataSet(dataSetName)

/**
 * Clear child dataSets for the specified parent dataSet.
 * The boolean force is also supported. If force is set
 * to 'false', the childDataSets are only cleared
 * if the row has changed on the parent dataSet. If
 * force is true, the child dataSets are always cleared.
 */
function clearChildDataSets(dataSetName, forceFlag)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == null)
  {
    return;
  }//if(dataSetName == null)
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.clearChildDataSets(' + buildStringParam(dataSetName) + ', '
    + buildBooleanParam(forceFlag) + ')';
  buildScriptSegment(segment);

  /* After the child dataSets are cleared, reset the rowChanged flag for the parent.*/
  resetRowChanged(dataSetName);

}//function clearChildDataSets(dataSetName, forceFlag)

/**
 * Save all data sets.
 */
function saveAllDataSets()
{
  /* Build the script segment.*/
  var segment = 'xmlDataStore.saveAllBuffers()';
  buildScriptSegment(segment);

  /* Set the save control variable.*/
  saveInProcess = true;
}//function saveAllDataSets()

/**
 * Sort a data set..
 */
function sortDataSet(dataSetName, sortString)
{
  /* If the dataSetName is empty, return.*/
  if(dataSetName == '')
  {
    return;
  }//if(dataSetName == '')

  /* Build the script segment.*/
  var segment = 'xmlDataStore.sort(' + buildStringParam(dataSetName) + ', ' + buildStringParam(sortString) + ')';
  buildScriptSegment(segment);

}//function sortDataSet(dataSetName)

/****************************************************************************
 * End Framework DataSet Script Functions
 ****************************************************************************/

/****************************************************************************
 * Form Submit/Control Functions
 ****************************************************************************/

/**
 * Set the response page.
 */
function setResponseURL(pageURL)
{
  /* Set the response URL object.*/
  responseURL = pageURL;
}//function setResponseURL(pageURL)

/**
 * Submit a particular framework data form.
 */
function submitForm(dataFrame, formName)
{
  var lastSubmitDate = null;

  /* Ensure one page loads at a time.*/
  if(submitInProcess)
  {
    return false;
  }//if(submitInProcess)
  submitInProcess = true;
  /* Get the dataframe and form pointers.*/
  var targetForm = dataFrame.document.forms[formName];


  /* Perform form validation.*/
  if(!fwValidateForm(targetForm))
  {
    initScriptBuffer();
    responseURL = '';
    submitInProcess = false;
    return false;
  }//if(!fwValidateForm(targetForm))


  /* Process any doBeforeSubmitForm event.*/
  if(typeof(doBeforeSubmitForm) == "function")
  {
    var extControl = new Object();
    extControl["process"] = true;
    doBeforeSubmitForm(extControl, dataFrame, formName);
    if(!extControl["process"])
    {
      return false;
    }//if(!extControl["process"])
  }//if(typeof(doBeforeSubmitForm) == "function")

  /* Set the fwModuleName parameter on the form.*/
  if(targetForm.elements["fwModuleName"].value == '')
  {
    if(args["fwModuleName"] != null)
    {
      targetForm.elements["fwModuleName"].value = args["fwModuleName"];
    }//if(args["fwModuleName"] != null)
  }//if(targetForm.elements["fwModuleName"].value == '')
  //alert("fwModuleScript: " + fwModuleScriptBuffer);
  /* Set the fwModuleScript parameter on the form.*/
  /* Each form must contain a hidden input field with this name.*/
  /* This script is sent to the server for processing.*/
  targetForm.elements["fwModuleScript"].value = fwModuleScriptBuffer;

  /* Set the targetForm Action URL.*/
  targetForm.action = responseURL;

  /* Prepare the fields for submit.*/
  fwPrepareDataFields(targetForm);

  /* Set the fwLastSubmitTime.*/
  lastSubmitDate = new Date();
  fwLastSubmitTime = lastSubmitDate.getTime();

  /* Submit the form.*/
  targetForm.submit(); 

  /* Clear the fwModuleScriptBuffer variable.*/
  initScriptBuffer();

  /* Clear the responseURL variable.*/
  responseURL = '';
  
  /* Perform extension processing.*/
  if(typeof(doAfterSubmitForm) == "function")
  {
    doAfterSubmitForm();
  }//if(typeof(doAfterSubmitForm) == "function")

  return true;

}//function submitForm(dataFrameName, formName)

function submitFormList(dataFrame, formName)
{
  var lastSubmitDate = null;

  /* Ensure one page loads at a time.*/
  if(submitInProcess)
  {
    return false;
  }//if(submitInProcess)
  submitInProcess = true;
  /* Get the dataframe and form pointers.*/
  var targetForm = dataFrame.document.forms[formName];

  /* Set the fwModuleName parameter on the form.*/
  if(targetForm.elements["fwModuleName"].value == '')
  {
    if(args["fwModuleName"] != null)
    {
      targetForm.elements["fwModuleName"].value = args["fwModuleName"];
    }//if(args["fwModuleName"] != null)
  }//if(targetForm.elements["fwModuleName"].value == '')
  //alert("fwModuleScript: " + fwModuleScriptBuffer);
  /* Set the fwModuleScript parameter on the form.*/
  /* Each form must contain a hidden input field with this name.*/
  /* This script is sent to the server for processing.*/
  targetForm.elements["fwModuleScript"].value = fwModuleScriptBuffer;

  /* Set the targetForm Action URL.*/
  targetForm.action = responseURL;

  /* Set the fwLastSubmitTime.*/
  lastSubmitDate = new Date();
  fwLastSubmitTime = lastSubmitDate.getTime();

  /* Submit the form.*/
  targetForm.submit(); 

  /* Clear the fwModuleScriptBuffer variable.*/
  initScriptBuffer();

  /* Clear the responseURL variable.*/
  responseURL = '';
  
  /* Perform extension processing.*/
  if(typeof(doAfterSubmitForm) == "function")
  {
    doAfterSubmitForm();
  }//if(typeof(doAfterSubmitForm) == "function")

  return true;

}//function submitFormList(dataFrameName, formName)

function submitForm3(dataFrame, formName)
{
  /* Ensure one page loads at a time.*/
  if(submitInProcess)
  {
     //alert("returning false");
    return false;
  }//if(submitInProcess)
  //submitInProcess = true;
  submitInProcess = false

  /* Get the dataframe and form pointers.*/
  var targetForm = dataFrame.document.forms[formName];
  //alert("targetForm: " + targetForm);
  /* Perform form validation.*/
  if(!fwValidateForm(targetForm))
  {
    initScriptBuffer();
    responseURL = '';
    submitInProcess = false;
    return false;
  }//if(!fwValidateForm(targetForm))

  /* Set the fwModuleName parameter on the form.*/
  targetForm.elements["fwModuleName"].value = args["fwModuleName"];
  //alert("fwModuleScript: " + fwModuleScriptBuffer);
  /* Set the fwModuleScript parameter on the form.*/
  /* Each form must contain a hidden input field with this name.*/
  /* This script is sent to the server for processing.*/
  targetForm.elements["fwModuleScript"].value = fwModuleScriptBuffer;

  //alert("submit URL = " + responseURL);
  /* Set the targetForm Action URL.*/
  targetForm.action = responseURL;

  /* Unformat the fields.*/
  //fwUnformatFields(targetForm);

  /* Submit the form.*/
  targetForm.submit();
 alert("submitForm3 - 6");
  /* Clear the fwModuleScriptBuffer variable.*/
  initScriptBuffer();

  /* Clear the responseURL variable.*/
  responseURL = '';

  return true;

}//function submitForm(dataFrameName, formName)

/**
 * Submit a particular framework data form.
 */
function submitForm2(dataFrame, formName)
{
  /* Ensure one page loads at a time.*/
  if(submitInProcess)
  {
    return false;
  }//if(submitInProcess)
  //submitInProcess = true;
  submitInProcess = false;

  /* Get the dataframe and form pointers.*/
  var targetForm = dataFrame.document.forms[formName];
  //alert("target form = " + targetForm);

  /* Perform form validation.*/
  if(!fwValidateForm(targetForm))
  {
    initScriptBuffer();
    responseURL = '';
    submitInProcess = false;
    return false;
  }//if(!fwValidateForm(targetForm))

  /* Set the fwModuleName parameter on the form.*/
  targetForm.elements["fwModuleName"].value = args["fwModuleName"];
  //alert("fwModuleScript: " + fwModuleScriptBuffer);
  /* Set the fwModuleScript parameter on the form.*/
  /* Each form must contain a hidden input field with this name.*/
  /* This script is sent to the server for processing.*/
  targetForm.elements["fwModuleScript"].value = fwModuleScriptBuffer;

  /* Set the targetForm Action URL.*/
  targetForm.action = responseURL;
  targetForm.target = "_parent";
  //alert("target form top = " + targetForm.top);

  /* Unformat the fields.*/
  //fwUnformatFields(targetForm);

  /* Submit the form.*/
  targetForm.submit();

  /* Clear the fwModuleScriptBuffer variable.*/
  initScriptBuffer();

  /* Clear the responseURL variable.*/
  responseURL = '';

  return true;

}//function submitForm2(dataFrameName, formName)


/**
 * Get the parent form for an Input.
 */
function getParentForm(inputField)
{
  var parentObject = null;
  if(inputField == null)
  {
    return null;
  }//if(inputField == null)

  parentObject = inputField.parentElement;
  while(parentObject != null)
  {
    /* If a Form is found, end the loop.*/
    if(parentObject.tagName == 'FORM')
    {
      break;
    }//if(parentObject.tagName == 'FORM')

    /* Get the next parent.*/
    parentObject = parentObject.parentElement;
  }//while

  return parentObject;

}//function getParentForm(inputField)

/**
 * Ensure that all pages are ready.
 */
function fwCheckModuleStatus()
{
  if(submitInProcess)
  {
    alert("Loading in progress...Please try again.");
    return false;
  }//if(submitInProcess)
  return true;
}//function fwCheckModuleStatus()

/**
 * Ensure that all pages are ready.
 * Renamed to make it more consistent.
 */
function fwCheckPageLoadStatus()
{
  if(submitInProcess)
  {
    alert("Loading in progress...Please try again.");
    return false;
  }//if(submitInProcess)
  return true;
}//function fwCheckPageLoadStatus()

/****************************************************************************
 * End Form Submit/Control Functions
 ****************************************************************************/

/****************************************************************************
 * Form Processing Functions
 ****************************************************************************/

/**
 * Process an input field.
 */
function doFWInputOnChange(inputField)
{
  /* If the inputField is null, exit.*/
  if(inputField == null)
  {
    return;
  }//if(inputField == null)

  /* Get the parent Form for the input.*/
  var parentForm = getParentForm(inputField);
  if(parentForm == null)
  {
    return;
  }//if(parentForm == null)

  /* Set the modified attribute of the form.*/
  var modified = parentForm.elements["fwModified"];
  if(modified != null)
  {
    modified.value = 'true';
  }//if(modified != null)

  /* Set the module modified variable.*/
  fwModuleModified = true;

  /* Perform extension processing.*/
  if(typeof(doAfterFWInputOnChange) == "function")
  {
    doAfterFWInputOnChange(inputField);
  }//if(typeof(doAfterFWInputOnChange) == "function")
}//function doFWInputOnChange(inputField)

/**
 * Check if the Module has Modified data.
 * Returns true if pending changes and the user wishes to remain on the current record.
 */
function fwCheckModified()
{
  var msg = '';

  if(fwModuleModified)
  {

    //msg = "Data on the current record has been modified.\n " +
    //      "If you proceed, unsaved data may be lost.\n\n " +
    //      "Press 'OK' to proceed or 'Cancel' to remain on the current record, \n" +
    //      "allowing you to save your changes." ;
    //if(confirm(msg))
    //{
    //  fwModuleModified = false;

    //  /* Supress validation if the user selects Cancel.*/
    //  //fwIgnoreValidation = true;

    //  return false;
    //}//if(confirm(msg))
    //else
    //{
    //  return true;
    //}//else
    /* Modified so that the user is forced to save, ensuring all validation occurs.*/
    msg = "Data on the current record has been modified.\n" +
          "Please save the data or delete the record before proceeding.";
    alert(msg);
    return true;
  }//if(fwModuleModified)

  return false;
}//function fwCheckModified()

/**
 * Framework form init.
 * This function initializes the form extension attributes when the
 * page is loaded.
 */
function fwInitForm(targetForm)
{
  /* Outline:
   *
   * Loop elements.
   * For each Text Input, add each attribute.
   */

  var i = 0;
  var formElement = null;
  var fwOnValidateFcnName = null;

  /* Loop elements.*/
  for(i=0;i<targetForm.elements.length;i++)
  {
    formElement = targetForm.elements[i];

    /* For each Text Input, add each attribute.*/
    /* Skip any framework fields.*/
    if(formElement.id.substring(0,2) == 'fw')
    {
      continue;
    }//if(formElement.id.substring(0,2) == 'fw')

    /* Skip any non-text inputs.*/
    if(formElement.type != "text")
    {
      continue;
    }//if(formElement.type != "text")

    /* Add each attribute.*/
    formElement.fwRequired = formElement.getAttribute("fwRequired");
    formElement.fwDataType = formElement.getAttribute("fwDataType");
    if(formElement.fwDataType == null)
    {
      formElement.fwDataType = "string";
    }//if(formElement.fwDataType == null)
    formElement.fwRangeFrom = formElement.getAttribute("fwRangeFrom");
    formElement.fwRangeTo = formElement.getAttribute("fwRangeTo");
    fwOnValidateFcnName = formElement.getAttribute("fwOnValidate");

    /* Store a pointer to the validate function.*/
    if(fwOnValidateFcnName != null)
    {
      formElement.fwOnValidate = eval(fwOnValidateFcnName);
    }//if(fwOnValidateFcnName != null)
    else
    {
      formElement.fwOnValidate = null;
    }//else

    formElement.fwFormat = formElement.getAttribute("fwFormat");
    formElement.fwEditFormat = formElement.getAttribute("fwEditFormat");
    formElement.fwDataFormat = formElement.getAttribute("fwDataFormat");

    /* If the dataType is date, default the fwEditFormat and fwDataFormat if required.*/
    if(formElement.fwDataType == 'date')
    {
      if(formElement.fwEditFormat == null)
      {
        formElement.fwEditFormat = formElement.fwFormat;
      }//if(formElement.fwEditFormat == null)
      if(formElement.fwDataFormat == null)
      {
        formElement.fwDataFormat = formElement.fwFormat;
      }//if(formElement.fwDataFormat == null)
    }//if(formElement.fwDataType == 'date')

    /* The initial format is always the fwDataFormat when the form is loaded.*/
    formElement.fwCurrentFormat = formElement.fwDataFormat;

    /* The fwErrorValue is used to store any invalid value entered by the user.*/
    formElement.fwErrorValue = null;

  }//for(i=0;i<targetForm.elements.length;i++)

}//function fwInitForm(targetForm)

/**
 * Process the input onfocus event.
 */
function doFWOnFocus(targetElement)
{
  /* Set the fwEditFormat.*/
  fwApplyEditFormat(targetElement);

  /* Highlight the value.*/
  targetElement.select();
}//function doFWOnFocus(targetElement)

/**
 * Set the fwEditFormat for the field.
 */
function fwApplyEditFormat(targetElement)
{
  var dataType = null;
  var formattedValue = '';
  var numberValue = null;
  var rawDateValue = null;
  var dateValue = null;

  /* If the value is empty, do not format.*/
  if(targetElement.value == "")
  {
    targetElement.fwCurrentFormat = targetElement.fwEditFormat;
    return;
  }//if(targetElement.value = "")

  /* If fwEditFormat is null, set the value to fwValue.*/
  if(targetElement.fwEditFormat == null)
  {
    targetElement.value = targetElement.fwValue;
    targetElement.fwCurrentFormat = targetElement.fwEditFormat;
    return;
  }//if(targetElement.fwEditFormat == null)

  dataType = targetElement.fwDataType;
  if(dataType == null)
  {
    dataType = "string";
  }//if(dataType == null)

  /* If fwErrorValue exists, use it to set the edit value.*/
  if(targetElement.fwErrorValue != null)
  {
    targetElement.value = targetElement.fwErrorValue;
    targetElement.fwCurrentFormat = targetElement.fwEditFormat;
    return;
  }//if(targetElement.fwErrorValue != null)

  /* String and numericString dataType values are not formatted during editing.*/
  if(dataType == "string" || dataType == "numericString")
  {
    formattedValue = fwFormatString(targetElement.fwEditFormat, targetElement.value);
  }//if(dataType == "string" || dataType == "numericString")

  /*
   * For number and date types, get a value using the current format
   * and then format it using the fwDataFormat.
   */
  else if(dataType == "number")
  {
    numberValue = Number.getNumberFromFormat(targetElement.value, targetElement.fwCurrentFormat);
    // This case should not occur
    //if(isNaN(numberValue))
    //{
    //  //alert("The number value is invalid.");
    //  formattedValue = targetElement.value;
    //}//if(isNaN(numberValue))
    if(targetElement.fwEditFormat != null)
    {
      formattedValue = Number.format(numberValue, targetElement.fwEditFormat);
    }//if(targetElement.fwEditFormat != null)
    else
    {
      formattedValue = numberValue.toString();
    }//else
  }//else if
  else if(dataType == "date")
  {
    rawDateValue = Date.getDateFromFormat(targetElement.value, targetElement.fwCurrentFormat);
    // This case should not occur
    //if(rawDateValue == 0)
    //{
    //  //alert("The date is invalid.");
    //  formattedValue = "!!" + targetElement.value;
    //}//if(rawDateValue == 0)
    if(targetElement.fwEditFormat != null)
    {
      dateValue = new Date(rawDateValue);
      formattedValue = Date.format(dateValue, targetElement.fwEditFormat);
    }//if(targetElement.fwEditFormat != null)
    else
    {
      formattedValue = targetElement.value;
    }//else
  }//else if(dataType == "date")

  /* Set the value.*/
  targetElement.value = formattedValue;

  /* Set fwCurrentFormat.*/
  targetElement.fwCurrentFormat = targetElement.fwEditFormat;

}//function fwApplyEditFormat(targetElement)

/**
 * Format fields.
 */
function fwFormatFields(targetForm)
{
  /* Outline:
   *
   * Loop form elements.
   * If fwFormat != null, format field.
   */

  var i = 0;
  var formElement = null;

  /* Loop form elements.*/
  for(i=0;i<targetForm.elements.length;i++)
  {
    formElement = targetForm.elements[i];
    fwFormatField(formElement);
  }//for(i=0;i<targetForm.elements.length;i++)

}//function formatFields(targetForm)

/**
 * Process the input onblur event.
 */
function doFWOnBlur(targetElement)
{
  /* Format the field for display using fwFormat.*/
  fwFormatField(targetElement);
}//function doFWOnBlur(targetElement)

/**
 * Format an input field.
 */
function fwFormatField(targetElement)
{
  var dataType = null;
  var formattedValue = '';
  var numberValue = null;
  var rawDateValue = null;
  var dateValue = null;

  //alert("fwFormatField: value: " + targetElement.value + " dataType: " + targetElement.fwDataType);
  if(targetElement.fwFormat == null)
  {
    return;
  }//if(targetElement.fwFormat == null)

  /* Set the data value in the fwValue attribute.*/
  //fwSetDataValue(targetElement);

  /* If the value is empty, do not format.*/
  if(targetElement.value == "")
  {
    targetElement.fwValue = "";
    return;
  }//if(targetElement.value = "")

  dataType = targetElement.fwDataType;
  if(dataType == null)
  {
    dataType = "string";
  }//if(dataType == null)

  /* String and numericString dataType values are not formatted during editing.*/
  if(dataType == "string" || dataType == "numericString")
  {
    targetElement.fwValue = targetElement.value;
    targetElement.fwErrorValue = null;
    formattedValue = fwFormatString(targetElement.fwFormat, targetElement.value);
  }//if(dataType == "string" || dataType == "numericString")

  /*
   * For number and date types, get a value using the current format
   * and then format it using the fwDataFormat.
   */
  else if(dataType == "number")
  {
    numberValue = Number.getNumberFromFormat(targetElement.value, targetElement.fwCurrentFormat);
    if(isNaN(numberValue))
    {
      //alert("The number value is invalid.");
      targetElement.fwErrorValue = targetElement.value;
      targetElement.fwValue = '';
      formattedValue = "!!" + targetElement.value;
    }//if(isNaN(numberValue))
    else if(targetElement.fwFormat != null)
    {
      targetElement.fwValue = Number.format(numberValue, targetElement.fwDataFormat);
      targetElement.fwErrorValue = null;
      formattedValue = Number.format(numberValue, targetElement.fwFormat);
    }//else if(targetElement.fwFormat != null)
    else
    {
      targetElement.fwValue = numberValue.toString();
      targetElement.fwErrorValue = null;
      formattedValue = numberValue.toString();
    }//else
  }//else if
  else if(dataType == "date")
  {
    rawDateValue = Date.getDateFromFormat(targetElement.value, targetElement.fwCurrentFormat);
    if(rawDateValue == 0)
    {
      //alert("The date is invalid.");
      targetElement.fwErrorValue = targetElement.value;
      targetElement.fwValue = '';
      formattedValue = "!!" + targetElement.value;
    }//if(rawDateValue == 0)
    else if(targetElement.fwFormat != null)
    {
      dateValue = new Date(rawDateValue);
      targetElement.fwValue = Date.format(dateValue, targetElement.fwDataFormat);
      targetElement.fwErrorValue = null;
      formattedValue = Date.format(dateValue, targetElement.fwFormat);
    }//else if(targetElement.fwFormat != null)
    else
    {
      targetElement.fwValue = targetElement.value;
      targetElement.fwErrorValue = null;
      formattedValue = targetElement.value;
    }//else
  }//else if(dataType == "date")

  /* Set the value.*/
  targetElement.value = formattedValue;

  /* Set fwCurrentFormat.*/
  targetElement.fwCurrentFormat = targetElement.fwFormat;

}//function fwFormatField(targetElement)

/**
 * Prepare field data for submit, by setting the value to fwValue.
 * This ensures that the fields are submitted to the server using
 * the fwDataFormat.
 */
function fwPrepareDataFields(targetForm)
{
  /* Outline:
   *
   * If no data has been modified, return.
   * Loop form elements.
   * If fwFormat != null, format field.
   */

  var i = 0;
  var formElement = null;

  /* If no data has been modified, return.*/
  if(targetForm.elements["fwModified"].value == 'false')
  {
    return;
  }//if(targetForm.elements["fwModified"].value == 'false')

  /* Loop form elements.*/
  for(i=0;i<targetForm.elements.length;i++)
  {
    formElement = targetForm.elements[i];
    fwPrepareDataField(formElement);
  }//for(i=0;i<targetForm.elements.length;i++)

}//function fwPrepareDataFields(targetForm)

/**
 * Prepare a an input field for submit.
 */
function fwPrepareDataField(targetElement)
{
  /* If fwErrorValue exists, return.*/
  if(targetElement.fwErrorValue != null)
  {
    return;
  }//if(targetElement.fwErrorValue != null)

  /* If a valid format exists, and fwValue is not null, set the field value.*/
  if(targetElement.fwFormat != null && targetElement.fwValue != null)
  {
    targetElement.value = targetElement.fwValue;

    /* Set the fwCurrentFormat.*/
    targetElement.fwCurrentFormat = targetElement.fwDataFormat;

  }//if(targetInput.fwFormat != null && targetInput.fwValue != null)
}//function fwPrepareDataField(targetElement)

/**
 * Perform form validation.
 */
function fwValidateForm(targetForm)
{
  /* Outline:
   *
   * If the fwIgnoreValidation flag is set, return.
   * Only validate if values have been modified.
   * Loop fields.
   * Validate each field.
   */

  var value;
  var i = 0;
  var formElement = null;

  /* If the ignoreValidation flag is set, return.
   * In some instances, such as when the user is deleting a record, or if the
   * user has abandoned changes, validation can be ignored.
   */
  if(fwIgnoreValidation)
  {
    fwIgnoreValidation = false;
    return true;
  }//if(fwIgnoreValidation)

  /* Only validate if values have been modified.*/
  if(targetForm["fwModified"].value != "true")
  {
    return true;
  }//if(targetForm["fwModified"].value != "true")

  /* Loop fields.*/
  for(i=0;i<targetForm.elements.length;i++)
  {
    formElement = targetForm.elements[i];

    /* For each Text Input, add each attribute.*/
    /* Skip any framework fields.*/
    if(formElement.id.substring(0,2) == 'fw')
    {
      continue;
    }//if(formElement.id.substring(0,2) == 'fw')

    /* Skip any non-text inputs.*/
    if(!(formElement.type == "text" || formElement.tagName == "SELECT"))
    {
      continue;
    }//if(!(formElement.type == "text" || formElement.type == "select"))

    /* Get the value.*/
    if(formElement.fwFormat != null && formElement.fwValue != null
      && formElement.fwErrorValue == null)
    {
      value = formElement.fwValue;
    }//if(formElement.fwFormat != null && formElement.fwValue != null
    else
    {
      value = formElement.value;
    }//else

    /* Validate each field.*/
    if(!fwValidateField(formElement, value))
    {
      /* Set the focus on the error field.*/
      formElement.focus();
      return false;
    }//if(!validateInput(formElement))

  }//for(i=0;i<targetForm.elements.length;i++)

  return true;
}//function fwValidateForm(targetForm)

/**
 * Validate an input Field. This is done just prior to submitting the form
 * using the fwDataFormat if provided.
 */
function fwValidateField(targetElement, value)
{
  /* Outline:
   *
   * Check required.
   * Get the dataType.
   * Check data type.
   * Check range.
   * Process extension function.
   */

  var dataType = null;
  var rangeFrom = 0;
  var rangeTo = 0;

  /* Check required.*/
  if(targetElement.fwRequired != null)
  {
    if(targetElement.fwRequired == "true" && value == '')
    {
      alert("A value is required.");
      return false;
    }//if(formElement.fwRequired == "true" && value == '')
  }//if(formElement.fwRequired != null)

  /* Get the dataType.*/
  dataType = targetElement.fwDataType;

  /* If the value is empty, return true.*/
  if(value == '')
  {
    return true;
  }//if(value == '')

  /* Check data type.*/
  if(dataType != null)
  {
    switch(dataType)
    {
      case "string":
        if(!fwCheckStringField(targetElement, value))
        {
          return false;
        }//if(!fwCheckStringField(targetElement, value))
        break;

      case "numericString":
        if(!fwCheckNumericStringField(targetElement, value))
        {
          return false;
        }//if(!fwCheckNumericStringField(targetElement, value))
        break;

      case "number":
        if(!fwCheckNumberField(targetElement, value))
        {
          return false;
        }//if(!fwCheckNumberField(targetElement))

        /* Check any range.*/
        if(!fwCheckRange(targetElement, value))
        {
          return false;
        }//if(!fwCheckRange(targetElement)
        break;

      case "date":
        if(!fwCheckDateField(targetElement, value))
        {
          return false;
        }//if(!fwCheckDateField(targetElement))
        break;

    }//switch(dataType)

  }//if(dataType != null)

  /* Process extension function.*/
  if(targetElement.fwOnValidate != null)
  {
    if(!targetElement.fwOnValidate(targetElement))
    {
      return false;
    }//if(!targetElement.fwOnValidate(targetElement))
  }//if(targetElement.fwOnValidate != null)

  return true;
}//function fwValidateField(targetElement)

/**
 * Check a string value for invalid characters.
 */
function fwCheckStringField(targetInput, value)
{

  var invalidCharExpr = "[\"]";
  var matchResult = null;
  var stringResult = '';

  matchResult = value.match(invalidCharExpr);
  if(matchResult != null)
  {
    stringResult = matchResult.toString();
    if(stringResult != "")
    {
      alert("Double-quote characters are not allowed.");
      return false;
    }//if(stringResult != "")
  }//if(matchResult != null)

  return true;

}//function fwCheckStringField(targetInput, value)

/**
 * Check a number type value.
 */
function fwCheckNumberField(targetElement, value)
{

  var numberValue = null;

  /* If there is an fwErrorValue, the value is invalid.*/
  if(targetElement.fwErrorValue != null)
  {
    alert("The number value is invalid.");
    return false;
  }//if(targetElement.fwErrorValue != null)

  /* If the field has an fwCurrentFormat, it is valid.*/
  if(targetElement.fwCurrentFormat != null)
  {
    return true;
  }//if(targetElement.fwCurrentFormat != null)

  /* Otherwise, check the number using getNumberFromFormat.*/
  numberValue = Number.getNumberFromFormat(targetElement.value, targetElement.fwCurrentFormat);
  if(isNaN(numberValue))
  {
    alert("The number value is invalid.");
    return false;
  }//if(isNaN(numberValue))

  return true;
}//function fwCheckNumberField(targetInput)

/**
 * Check a numericString type value.
 */
function fwCheckNumericStringField(targetInput, value)
{

  var invalidCharExpr = "[^0-9]";
  var matchResult = null;
  var stringResult = '';

  matchResult = value.match(invalidCharExpr);
  if(matchResult != null)
  {
    stringResult = matchResult.toString();
    if(stringResult != "")
    {
      alert("An invalid value was entered. Only numeric characters are allowed.");
      return false;
    }//if(stringResult != "")
  }//if(matchResult != null)

  return true;

}//function fwCheckNumericStringField(targetInput)

/**
 * Check a range.
 */
function fwCheckRange(targetInput, value)
{
  var numberValue = parseFloat(value);
  if(isNaN(numberValue))
  {
    alert("The number value is not valid.");
    return false;
  }//if(isNaN(numberValue))

  if(targetInput.fwRangeFrom != null)
  {
    if(targetInput.fwRangeTo != null)
    {
      rangeFrom = parseInt(targetInput.fwRangeFrom, 10);
      rangeTo = parseInt(targetInput.fwRangeTo, 10);

      if(!(isNaN(rangeFrom) && isNaN(rangeTo)))
      {
        if(numberValue < rangeFrom || numberValue > rangeTo)
        {
          alert("The value must be between: " + rangeFrom + " and: " + rangeTo);
          return false;
        }//if(parseInt(targetInput.value) < rangeFrom || parseInt(targetInput.value) > rangeTo)
      }//if(!(isNaN(rangeFrom) && isNaN(rangeTo)))
    }//if(targetInput.fwRangeTo != null)
  }//if(targetInput.fwRangeFrom != null)

  return true;
}//function fwCheckRange(targetInput)

/**
 * Check a Date type value.
 */
function fwCheckDateField(targetInput, value)
{

  var invalidCharExpr = "[^0-9-\/]+";
  var validDateExpr = new RegExp("[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}");
  var validDateExprMySql = new RegExp("[0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}");
  var matchResult = '';
  var month = 0;
  var day = 0;
  var year = 0;
  var stringResult = '';
  var dateTokens;

  /* Check for invalid characters.*/
  matchResult = value.match(invalidCharExpr);
  if(matchResult != null)
  {
    stringResult = matchResult.toString();
    if(stringResult != "")
    {
      alert("The date value is invalid. Only numbers and '/' characters can be used in a date.");
      return false;
    }//if(stringResult != "")
  }//if(matchResult != null)

  /* Validate the date.*/
  matchResult = value.match(validDateExpr);
  
  matchResultMySql = value.match(validDateExprMySql);
  dateTokens = stringResult.split("/");
  if(matchResult == null || matchResult == "")
  {
    dateTokens = stringResult.split("-");
    
    if(matchResultMySql == null || matchResultMySql == "")
    {
	    alert("A date must be in the format: MM/DD/YYYY or YYYY-MM-DD");
	    return false;    
    }

  }//if(matchResult == null || matchResult == "")

  /* Validate the parts of the date.*/
 if(matchResult != null)
 {
    stringResult = matchResult.toString();
 }
 else
 {
   stringResult = matchResultMySql.toString();
 }
  month = parseInt(dateTokens[0]);
  day = parseInt(dateTokens[1]);
  year = parseInt(dateTokens[2]);

  if(month < 1 || month > 12)
  {
    alert("The month is invalid.");
    return false;
  }//if(month < 1 || month > 12)

  if(day < 1 || day > 31)
  {
    alert("The day of the month is invalid.");
    return false;
  }//if(day < 1 || day > 31)

  switch(month)
  {
    case 2:
      /* If this is a leap-year.*/
      if(year % 4 == 0 && !(year % 1000 ==0))
      {
        if(day > 29)
        {
          alert("The day of the month is invalid.");
          return false;
        }//if(day > 29)
      }//if(year % 4 == 0 && !(year % 1000 ==0))
      else
      {
        if(day > 28)
        {
          alert("The day of the month is invalid.");
          return false;
        }//if(day > 28)
      }//else
      break;

    case 4:
      if(day > 30)
      {
        alert("The day of the month is invalid.");
        return false;
      }//if(day > 30)
      break;

    case 6:
      if(day > 30)
      {
        alert("The day of the month is invalid.");
        return false;
      }//if(day > 30)
      break;

    case 9:
      if(day > 30)
      {
        alert("The day of the month is invalid.");
        return false;
      }//if(day > 30)
      break;

    case 11:
      if(day > 30)
      {
        alert("The day of the month is invalid.");
        return false;
      }//if(day > 30)
      break;
  }//switch(month)

  /* Set the value, as the validated value may be cleaned.*/
  targetInput.value = stringResult;

  return true;

}//function fwCheckDateField(targetInput)

/**
 * Format a string value.
 */
function fwFormatString(format, value)
{
  var valueLen = value.length;
  var formatLen = format.length;
  var i = 0;
  var j = 0;
  var formatChar = '';
  var valueChar = '';
  var result = ''

  /* Format the string with any characters which are not 'X'.*/
  for(i=0;i<formatLen;i++)
  {
    formatChar = format.charAt(i);
    if(formatChar != 'X')
    {
      result = result + formatChar;
    }//if(formatChar != 'X')
    else
    {
      valueChar = value.charAt(j);
      result = result + valueChar;
      j++;
    }//else
  }//for(i=0;i<valueLen;i++)

  return result;
}//function fwFormatString(format, value)

/**
 * Process a Checkbox type input, placing the appropriate value in a
 * hidden input field.
 */
function doFWCbxOnClick(targetCbx, fwInputField, onValue, offValue)
{
  /* If the targetCbx is null, exit.*/
  if(targetCbx == null)
  {
    return;
  }//if(targetCbx == null)

  /* Get the targetInputField, which is the previousSibling.previousSibling (due to an
   * invisible text node).*/
  var targetInputField = targetCbx.previousSibling.previousSibling;
  if(targetInputField == null)
  {
    return;
  }//if(targetInputField == null)

  /* Set the value of the hidden input field.*/
  if(targetCbx.checked)
  {
    targetInputField.value = onValue;
  }//if(targetCbx.checked)
  else
  {
    targetInputField.value = offValue;
  }//else

  /* Process the normal framework on change.*/
  doFWInputOnChange(targetCbx);

}//function doFWCbxOnClick(targetCbx, fwInputField, onValue, offValue)

/**
 * Process a Checkbox onchange event, for backward compatibility.
 */
function doFWCbxOnChange(targetCbx, fwInputField, onValue, offValue)
{
  doFWCbxOnClick(targetCbx, fwInputField, onValue, offValue);
}//function doFWCbxOnChange(targetCbx, fwInputField, onValue, offValue)

/**
 * Process a Select type input, placing the appropriate value in a
 * hidden input field.
 */
function doFWSelectOnChange(targetSelect, fwInputField)
{
  /* If the targetSelect is null, exit.*/
  if(targetSelect == null)
  {
    return;
  }//if(targetSelect == null)

  /* Get the targetInputField, which is the previousSibling.previousSibling (due to an
   * invisible text node).*/
  var targetInputField = targetSelect.previousSibling.previousSibling;
  if(targetInputField == null)
  {
    return;
  }//if(targetInputField == null)

  /* Set the value of the hidden input field.*/
  targetInputField.value = targetSelect.value;

  /* Process the normal framework on change.*/
  doFWInputOnChange(targetSelect);

}//function doFWSelectOnChange(targetSelect, fwInputField)

/**
 * Autotab a field when the max characters are typed.
 * This sets the focus to the next element in tab or source
 * sequence. Tab sequence must be a non-zero number for
 * this function to take it into account.
 */
function doFWAutotabOnKeyup(targetInput)
{
  var key = 0;

  //top.status = "keyCode: " + targetInput.ownerDocument.parentWindow.event.keyCode;
  /* If the keyCode is a tab key, or shift-tab, return.*/
  key = targetInput.ownerDocument.parentWindow.event.keyCode;
  if(key == 9)
  {
    lastKey = key;
    return;
  }//if(key == 9)
  if(lastKey == 9 && key == 16)
  {
    lastKey = 0;
    return;
  }//if(lastKey == 9 && key == 16)

  lastKey = 0;
  //top.status = "length: " + targetInput.value.length + " maxLength: " + targetInput.maxLength;
  var nextElement = null;

  if(targetInput.maxLength)
  {
    if(targetInput.value.length == targetInput.maxLength)
    {
      nextElement = findNextFormElement(targetInput);
      nextElement.focus();
    }//if(targetInput.value.length == targetInput.maxLength)
  }//if(targetInput.maxLength)
}//function doFWAutotabOnKeyup(targetInput)

/**
 * Find the next element in the form.
 */
function findNextFormElement(targetInput)
{
  var i = 0;
  var targetForm = getParentForm(targetInput);
  var formElements = targetForm.elements;
  var tabIndex = targetInput.tabIndex;
  var nextElement = null;

  /* Find the next element.*/
  for(i=0;i<formElements.length;i++)
  {
    /* If the next form element is not visible, skip it.*/
    if(formElements[i].type == 'hidden')
    {
      continue;
    }//if(formElements[i].type == 'hidden')
    
    /* If the targetInput has a valid tabIndex, search by tabIndex.*/
    if(tabIndex > 0)
    {
      if(formElements[i].tabIndex > tabIndex)
      {
        nextElement = formElements[i];
        break;
      }//if(formElements[i].tabIndex > tabIndex)
    }//if(tabIndex > 0)

    /* Otherwise just find the next element.*/
    else
    {
      /* Find a match for the current element.*/
      if(formElements[i] == targetInput)
      {
        i++;
        if(i < formElements.length)
        {
          nextElement = formElements[i];
        }//if(i < formElements.length)
        break;
      }//if(formElements[i] == targetInput)
    }//else
  }//for(i=0;i<formElements.length;i++)

  /* If nextElement is null, no nextElement was found. Set to the first.*/
  if(nextElement == null)
  {
    nextElement = formElements[0];
  }//if(nextElement == null)

  return nextElement;
}//function findNextFormElement(targetInput)

/****************************************************************************
 * End Form Processing Functions
 ****************************************************************************/

/****************************************************************************
 * Common Button Functions
 ****************************************************************************/

/**
 * Bring the Application Panel window to the front.
 */
function openAppPanel()
{
  /* Set focus to the parent window.*/
  window.parent.opener.focus();
}//function openAppPanel()

/**
 * Bring up the print dialog.
 */
function printDocument(targetFrame)
{
  targetFrame.focus();
  window.print();
}//function printDocument()

/**
 * Bring up the help window for the specified topic.
 */
function showHelp(helpTopic)
{
  /* Perform extension processing.*/
  if(typeof(doShowHelp) == "function")
  {
    doShowHelp();
    return;
  }//if(typeof(doShowHelp) == "function")
  alert("No help is available for this view.");
}//function showHelp(helpTopic)

/**
 * Close the module.
 */
function closeModule()
{
  window.close();
}//function closeModule()

/****************************************************************************
 * End Common Button Functions
 ****************************************************************************/

/****************************************************************************
 * Graphics Control Functions
 ****************************************************************************/

/**
 * Swap Image.
 */
function fwSwapImage(targetImage, overSrc)
{
  targetImage.oSrc = targetImage.src;
  targetImage.src = overSrc;
}//function fwSwapImage(targetImage, overSrc)

/**
 * Restore image.
 */
function fwRestoreImage(targetImage)
{
  if(targetImage.oSrc != null)
  {
    targetImage.src = targetImage.oSrc;
  }//if(targetImage.oSrc != null)
}//function fwRestoreImage(targetImage)

/****************************************************************************
 * End Graphics Control Functions
 ****************************************************************************/

/****************************************************************************
 * Cookie functions
 ****************************************************************************/
/**
 * Cookie management object, from JavaScript, The Definitive Guide, Orielly.
 * The constructor function: creates a cookie object for the specified
 * document, with a specified name and optional attributes.
 * Arguments:
 *   document: The Document object that the cookie is stored for. Required.
 *   name:     A string that specifies a name for the cookie. Required.
 *   hours:    An optional number that specifies the number of hours from now
 *             that the cookie should expire.
 *   path:     An optional string that specifies the cookie path attribute.
 *   domain:   An optional string that specifies the cookie domain attribute.
 *   secure:   An optional Boolean value that, if true, requests a secure cookie.
 */
function Cookie(document, name, hours, path, domain, secure)
{
    // All the predefined properties of this object begin with '$'
    // to distinguish them from other properties which are the values to
    // be stored in the cookie.
    this.$document = document;
    this.$name = name;
    if (hours)
        this.$expiration = new Date((new Date()).getTime() + hours*3600000);
    else this.$expiration = null;
    if (path) this.$path = path; else this.$path = null;
    if (domain) this.$domain = domain; else this.$domain = null;
    if (secure) this.$secure = true; else this.$secure = false;
}

/**
 * Store a cookie.
 */
function _Cookie_store()
{
    // First, loop through the properties of the Cookie object and
    // put together the value of the cookie. Since cookies use the
    // equals sign and semicolons as separators, we'll use colons
    // and ampersands for the individual state variables we store
    // within a single cookie value. Note that we escape the value
    // of each state variable, in case it contains punctuation or other
    // illegal characters.
    var cookieval = "";
    for(var prop in this) {
        // Ignore properties with names that begin with '$' and also methods.
        if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function'))
            continue;
        if (cookieval != "") cookieval += '&';
        cookieval += prop + ':' + escape(this[prop]);
    }
    // Now that we have the value of the cookie, put together the
    // complete cookie string, which includes the name and the various
    // attributes specified when the Cookie object was created.
    var cookie = this.$name + '=' + cookieval;
    if (this.$expiration)
        cookie += '; expires=' + this.$expiration.toGMTString();
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    if (this.$secure) cookie += '; secure';

    // Now store the cookie by setting the magic Document.cookie property.
    this.$document.cookie = cookie;
}

/**
 * Load a cookie.
 */
function _Cookie_load()
{
    // First, get a list of all cookies that pertain to this document.
    // We do this by reading the magic Document.cookie property.
    var allcookies = this.$document.cookie;
    if (allcookies == "") return false;

    // Now extract just the named cookie from that list.
    var start = allcookies.indexOf(this.$name + '=');
    if (start == -1) return false;   // Cookie not defined for this page.
    start += this.$name.length + 1;  // Skip name and equals sign.
    var end = allcookies.indexOf(';', start);
    if (end == -1) end = allcookies.length;
    var cookieval = allcookies.substring(start, end);

    // Now that we've extracted the value of the named cookie, we've
    // got to break that value down into individual state variable
    // names and values. The name/value pairs are separated from each
    // other by ampersands, and the individual names and values are
    // separated from each other by colons. We use the split method
    // to parse everything.
    var a = cookieval.split('&');    // Break it into array of name/value pairs.
    for(var i=0; i < a.length; i++)  // Break each pair into an array.
        a[i] = a[i].split(':');

    // Now that we've parsed the cookie value, set all the names and values
    // of the state variables in this Cookie object. Note that we unescape()
    // the property value, because we called escape() when we stored it.
    for(var i = 0; i < a.length; i++) {
        this[a[i][0]] = unescape(a[i][1]);
    }

    // We're done, so return the success code.
    return true;
}//function _Cookie_load()

/**
 * Remove a cookie.
 */
function _Cookie_remove()
{
    var cookie;
    cookie = this.$name + '=';
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

    this.$document.cookie = cookie;
}//function _Cookie_remove()

/**
 * Create a dummy Cookie object, so we can use the prototype object to make
 * the functions above into methods.
 */
new Cookie();
Cookie.prototype.store = _Cookie_store;
Cookie.prototype.load = _Cookie_load;
Cookie.prototype.remove = _Cookie_remove;

/**
 * Save personalization data to a cookie.
 */
function savePersonalizationData(targetFrame, key, valueString)
{
  var persDataCookie = null;
  persDataCookie = new Cookie(targetFrame.document, "persdata", 8760, "/");
  persDataCookie.load();
  persDataCookie[key] = valueString;
  persDataCookie.store();

}//function savePersonalizationData(targetFrame, key, valueString)

/**
 * Get a personalization value.
 */
function getPersonalizationValue(targetFrame, key)
{
  var persDataCookie = null;
  persDataCookie = new Cookie(targetFrame.document, "persdata", 8760, "/");
  if(!persDataCookie.load())
  {
    return '';
  }//if(!persDataCookie.load())
  if(!persDataCookie[key])
  {
    return '';
  }//if(!persDataCookie[key])
  return persDataCookie[key];

}//function getPersonalizationValue(targetFrame, key)

/**
 * Set personalization data parameter for submit.
 */
function setPersonalizationParameter(targetFrame, key)
{
  var persDataCookie = null;
  var dataString
  persDataCookie = new Cookie(targetFrame.document, "persdata", 8760, "/");
  if(!persDataCookie.load())
  {
    return false;
  }//if(!persDataCookie.load())
  if(!persDataCookie[key])
  {
    return false;
  }//if(!persDataCookie[key])
  if(!targetFrame.document.getElementById("fwPersonalizationData"))
  {
    return false;
  }//if(!targetFrame.document.getElementById("fwPersonalizationData"))

  /* Build the dataString: [key]:[value]& */
  dataString = key + ':' + persDataCookie[key] + '&';
  targetFrame.document.getElementById("fwPersonalizationData").value = dataString;
  //alert("dataString: " + dataString);
  return true;

}//function setPersonalizationParameter(targetDocument, key)

/****************************************************************************
 * End Cookie functions
 ****************************************************************************/

