//*************************************************************
//*                                                           *
//*                         INIT                              *
//*                                                           *
//*************************************************************
var IE4 = (document.all) ? true : false;
var NS4 = (document.layers) ? true : false;
var NS6 = (document.getElementById && !document.all) ? true : false;


// Override window.onLoad() handler...
window.onload = function() {
  // Resize the ScrollingContentPane div...
  var objScrollingContentPane = document.getElementById ("ScrollingContentPane");
  if (objScrollingContentPane) {
    var objParent = objScrollingContentPane.parentNode;
    objScrollingContentPane.style.height     = (objParent.clientHeight - objScrollingContentPane.offsetTop) + "px";
    objScrollingContentPane.style.visibility = "visible";
  }

  // Move focus into the first editable field...
  if (document.forms.length > 0) {
    for (var i = 0; i < document.forms[0].elements.length; i++) {
      if (!document.forms[0].elements[i].readOnly) {
        document.forms[0].elements[i].focus();
        break;
      }
    }
  }
}


//*************************************************************
//*                                                           *
//*                       FUNCTIONS                           *
//*                                                           *
//*************************************************************

function FormUtils ()
{
  // INIT
  // initialize the member function references
  // for the class prototype
  if (typeof(_query_prototype_called) == 'undefined')
  {
    _query_prototype_called = true;

    FormUtils.prototype.SetTextValue      = _SetTextValue;
    FormUtils.prototype.SetRadioValue     = _SetRadioValue;
    FormUtils.prototype.SetSelectValue    = _SetSelectValue;
    FormUtils.prototype.IsEmpty           = _IsEmpty;
    FormUtils.prototype.IsRadioEmpty      = _IsRadioEmpty;
    FormUtils.prototype.IsCheckboxEmpty   = _IsCheckboxEmpty;
    FormUtils.prototype.IsPositiveInteger = _IsPositiveInteger;
    FormUtils.prototype.IsValidEmail      = _IsValidEmail;
  }

  // ********************* //
  // *   SetTextValue    * //
  // ********************* //
  function _SetTextValue (objFormField, szValue)
  {
    objFormField.value = szValue;
  }

  // ********************* //
  // *   SetRadioValue   * //
  // ********************* //
  function _SetRadioValue (objFormField, szValue)
  {

    for (i = 0; i < objFormField.length; i++)
    {
      if (objFormField[i].value.toUpperCase () == szValue.toUpperCase ())
      {
        objFormField[i].checked = true;
        objFormField.value      = szValue;
        break;
      }
      else
      {
        objFormField[i].checked = false;
      }
    }
  }

  // ********************* //
  // *   SetSelectValue  * //
  // ********************* //
  function _SetSelectValue (objFormField, szValue, szAddIfNotFound)
  {
    var lItemFound = false;

    for (i = 0; i < objFormField.length; i++)
    {
      if (objFormField[i].value == szValue) {
        // Item found
        lItemFound = true;

        // Select item
        objFormField.selectedIndex = i;
        break;
      }
    }

    // Add if not found...
    if ((lItemFound == false) &&
        (String (szAddIfNotFound).toUpperCase() == "ADD")) {
      objFormField[objFormField.length] = new Option (szValue, szValue);
      objFormField.selectedIndex        = objFormField.length - 1;
    }
  }

  // ******************* //
  // *     IsEmpty     * //
  // ******************* //
  function _IsEmpty (objFormField, silent)
  {
    var szValue = String (objFormField.value);
        szValue = szValue.replace (/^\s*/, "");     /* left trim spaces */
        szValue = szValue.replace (/\s*$/, "");     /* right trim spaces */

    if (!objFormField.disabled)
    {
      if (objFormField.value == '')
      {
        if (!silent) {
          alert (objFormField.title + ":\nPlease specify a value.");
        }
        objFormField.focus ();
        return (true);
      }
    }

    return (false);
  }

  // ****************** //
  // *  IsRadioEmpty  * //
  // ****************** //
  function _IsRadioEmpty (objFormField)
  {
    var isSelected = false;

    if (!objFormField[0].disabled)
    {
      for (i = 0; i < objFormField.length; i++)
      {
        if (objFormField[i].checked  == true)
        {
          isSelected = true;
          break;
        }
      }

      if (!isSelected )
      {
        alert (objFormField[0].title + ":\nPlease select one option.");
        objFormField[0].focus ();
        return (true);
      }
    }
    else {
      return false;
    }
  }

  // ********************* //
  // *  IsCheckboxEmpty  * //
  // ********************* //
  function _IsCheckboxEmpty (objFormField, silent)
  {
    var isEmpty = false;

    if (!objFormField.disabled)
    {
      isEmpty = !objFormField.checked;
      if (isEmpty)
      {
        if (!silent) {
          alert (objFormField.title + ":\nPlease select.");
        }
        objFormField.focus ();
        return (true);
      }
    }
    else {
      return false;
    }
  }

  // *********************** //
  // *  IsPositiveInteger  * //
  // *********************** //
  function _IsPositiveInteger(objFormField) {
    if (!objFormField.disabled) {
      if ((parseInt(objFormField.value, 10) != objFormField.value) || (objFormField.value < 0)) {
        alert (objFormField.title + ":\nPlease enter a valid positive number.");
        objFormField.focus ();
        return false;
      }
    }

    return true;
  }

  // *********************** //
  // *    IsValidEmail     * //
  // *********************** //
  function _IsValidEmail(objFormField) {
    if (!objFormField.disabled) {
      var emailExpr = "^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$";
      var objRegExp = new RegExp(emailExpr);
      if (objRegExp.test(objFormField.value) == false) {
        alert (objFormField.title + ":\nPlease enter a valid email address.");
        objFormField.focus ();
        return false;
      }
    }

    return true;
  }
}  // FormUtils Object

/* ------------------------------------------- */

function formslib_IsValidFloat (objField)
{

  if (!objField.disabled)
  {
    if ( String (parseFloat (objField.value)) == "NaN")
    {
      alert (objField.title + ":\nPlease specify a valid decimal number.");
      objField.focus ();
      return (false);
    }
  }

  return (true);
}

/* ------------------------------------------- */

function formslib_IsValidInteger (objField, lAllowEmpty)
{
  if (!objField.disabled)
  {
    // Allow empty value
    if (lAllowEmpty && objField.value == "")
    {
      return (true);
    }

    // Check if integer
    if (String (parseInt (objField.value, 10)) == "NaN")
    {
      alert (objField.title + ":\nPlease specify a valid integer number.");

      objField.focus ();
      return (false);
    }
  }

  return (true);
}

function isNull (szValue)
{
  return (szValue == null);
}


function formslib_SetCheckboxValue (oObject, szValue)
{
  oObject.checked = (oObject.value.toUpperCase () == szValue.toUpperCase ());
}

/* ------------------------------------------- */

function DisableForm (objForm, szExceptionList)
{
  // Purpose    : Disable form elements, except for those not specified to
  // Parameters : objForm         = HTML Form object                                        [required]
  //              szExceptionList = comma separated list of field names not to be disabled  [optional]
  // Example    : DisableForm (document.forms[0], "Back")

  /* Split exception list... */
  var ExceptionArray = (szExceptionList != null) ? szExceptionList.split (",") : null;

  /* Loop through form elements... */
  for (i = 0; i < objForm.length; i++)
  {
    var lDisableField = true;
    var objField      = objForm.elements[i];

    // Check if current field has to be left enabled...
    if (ExceptionArray)
    {
      for (j = 0; j < ExceptionArray.length; j++)
      {
        if (objField.name.toUpperCase () == ExceptionArray[j].toUpperCase ())
        {
          lDisableField = false;
          break;
        }
      }
    }

    // Disable field...
    if (lDisableField)
    {
      objField.disabled = true;
    }
  }
} // function DisableForm

/* ------------------------------------------- */

function DisableFormButtons (objForm)
{
  // Purpose    : Disable form buttons
  // Parameters : objForm         = HTML Form object                                        [required]
  // Example    : DisableFormButtons (document.forms[0])

  /* Loop through form elements... */
  for (i = 0; i < objForm.length; i++)
  {
    var objField      = objForm.elements[i];

    if ((objField.type.toUpperCase () == "SUBMIT") ||
        (objField.type.toUpperCase () == "BUTTON") ||
        (objField.type.toUpperCase () == "RESET" ))
    {
      objField.disabled = true;
    }

  }
} // function DisableFormButtons

/* ------------------------------------------- */

function highlightRow (objTableRow) {
  // Purpose: Highlist current ListPanel row

  if (objTableRow) {
    objTableRow.className = "highlight";
  }
}

function dehighlightRow (objTableRow) {
  // Purpose: Remove highlist current ListPanel row

  if (objTableRow) {
    objTableRow.className = "";
  }
}

/* ------------------------------------------- */

function openCenterWindow (url, name, height, width) {
  var features  = "height=" + height + ",innerHeight=" + height;
      features += ",width=" + width  + ",innerWidth="  + width;
  if (window.screen) {
    var ah = screen.availHeight - 30;
    var aw = screen.availWidth  - 10;

    var xc = (aw - width) / 2;
    var yc = (ah - height) / 2;

    features += ",left=" + xc + ",screenX=" + xc;
    features += ",top="  + yc + ",screenY=" + yc;
  }
  return window.open(url, name, features);
}



/****************************************************************/
/* Name   : SortableTable class                                 *
/* Purpose: Display a table sortable by clicking on each column */
/****************************************************************/
function SortableTable (tableId) {
  // Member variables
  this.tableId          = tableId;
  this.tableContainerId = "CONTAINER_" + tableId;
  this.divHeaderId      = "DIV_HEAD_"  + tableId;
  this.tableHeaderId    = "HEAD_"      + tableId;
  this.divBodyId        = "DIV_BODY_"  + tableId;
  this.tableBodyId      = "BODY_"      + tableId;
  this.tableFooterId    = "FOOT_"      + tableId;
  this.className        = tableId;
  this.headerRow        = null;
  this.detailRows       = new Array();
  this.footerText       = null;
  this.ascIndicator     = "";
  this.descIndicator    = "";
  this.sortedCol        = -1;
  this.sortedOrd        = "*NONE";

  // Methods
  this.setAscendingIndicator  = _setAscendingIndicator;
  this.setDescendingIndicator = _setDescendingIndicator;
  this.addHeaderColumn        = _addHeaderColumn;
  this.addDetailRow           = _addDetailRow;
  this.addFooterText          = _addFooterText;
  this.sortByColumn           = _sortByColumn;
  this.displayTable           = _displayTable;
  this.resizeTable            = _resizeTable;
  this.addOnLoadEvent         = _addOnLoadEvent;
  this.stripHtmlTags          = _stripHtmlTags;


  /*
   * Set ascending order image indicator...
   */
  function _setAscendingIndicator (ascIndicator) {
    this.ascIndicator = ascIndicator;
  }

  /*
   * Set descending order image indicator...
   */
  function _setDescendingIndicator (descIndicator) {
    this.descIndicator = descIndicator;
  }

  /*
   * Add column to the table header...
   */
  function _addHeaderColumn (columnText, columnWidth) {
    if (this.headerRow == null) {
      this.headerRow = new Array();
    }

    // Add new header column...
    var i = this.headerRow.length;
    this.headerRow[i]             = new Object();
    this.headerRow[i].columnText  = columnText;
    this.headerRow[i].columnWidth = columnWidth;
  }

  /*
   * Add a detail line...
   */
  function _addDetailRow() {
    var countRows = this.detailRows.length;
    this.detailRows[countRows] = new Array();
    for (var i=0; i < arguments.length; i++) {
      this.detailRows[countRows][i]          = new Object();
      this.detailRows[countRows][i].text     = arguments[i];
      this.detailRows[countRows][i].sortData = this.stripHtmlTags(arguments[i]);
    }
  }

  /*
   * Add a footer row
   */
  function _addFooterText(footerText) {
    this.footerText = footerText;
  }

  /*
   * Sort table details...
   */
  function _sortByColumn (column) {
    // If sorting the same column, reverse sort order...
    if (this.sortedCol == column) {
      if (this.sortedOrd == "asc") {
        this.sortedOrd = "desc";
      } else {
        this.sortedOrd = "asc";
      }
    // Otherwise, default to ASCENDING order...
    } else {
      this.sortedOrd = "asc";
    }

    // Hide previous sort indicator...
    var objSpan = document.getElementById (this.tableId + "_TH_" + this.sortedCol);
    if (objSpan) {
      objSpan.style.visibility = "hidden";
    }

    // Show current sort indicator...
    var objSpan = document.getElementById (this.tableId + "_TH_" + column);
    if (objSpan) {
      objSpan.style.visibility = "visible";
      if (this.sortedOrd == "asc") {
        objSpan.innerHTML = '&nbsp;<IMG SRC="' + this.ascIndicator + '">';
      } else {
        objSpan.innerHTML = '&nbsp;<IMG SRC="' + this.descIndicator + '">';
      }
    }

    // Ascending order...
    if (this.sortedOrd == "asc") {
      this.detailRows.sort ( function sort (a, b) {
                               if (a[column].sortData < b[column].sortData) {
                                 return -1;
                               } else if (a[column].sortData > b[column].sortData) {
                                 return +1;
                               } else {
                                 return 0;
                               };
                             }
                           );
    } else {
      // Descending order...
      this.detailRows.sort ( function sort (a, b) {
                               if (a[column].sortData > b[column].sortData) {
                                 return -1;
                               } else if (a[column].sortData < b[column].sortData) {
                                 return +1;
                               } else {
                                 return 0;
                               };
                             }
                           );
    }

    // Remember which column was sorted for future reference...
    this.sortedCol = column;

    // Display sorted data...
    var objTbody  = document.getElementById (this.tableBodyId);
    if (objTbody) {
      var rowsArray = objTbody.rows;
      for (var i = 0, n = rowsArray.length; i < n; i++) {
        var objCols    = rowsArray[i].cells;
        var detailCols = this.detailRows[i];
        for (var j = 0, m = objCols.length; j < m; j++) {
          var objCell = objCols[j];
              objCell.innerHTML = detailCols[j].text;
        }
      }
    }
  }

  /*
   * Resize sortable table once browser has finished drawing the table...
   */
  function _resizeTable () {
      // Enlarge container DIV to fill parent...
      var objContainerDiv = document.getElementById (this.tableContainerId);
      var objHeaderTable  = document.getElementById (this.tableHeaderId);
      var objFooterTable  = document.getElementById (this.tableFooterId);
      var objDivBody      = document.getElementById (this.divBodyId);

      objContainerDiv.style.width  = objContainerDiv.parentNode.style.width;
      objContainerDiv.style.height = (objContainerDiv.parentNode.clientHeight - objContainerDiv.offsetTop) + "px";

      // Enlarge content to fill conteiner DIV...
      objDivBody.style.height = (objContainerDiv.clientHeight -
                                 objHeaderTable.clientHeight  -
                                 objFooterTable.clientHeight) + "px";

      // Resize header table to have same width as the body table..
      var objHeaderTable = document.getElementById (this.tableHeaderId);
      var objBodyTable   = document.getElementById (this.tableBodyId);
      objHeaderTable.style.width = objBodyTable.clientWidth + "px";

      // Paint the blank spot from the right corner with the TH background color...
      var objDivHeader      = document.getElementById (this.divHeaderId);
      var objHeaderCell     = objHeaderTable.rows[0].cells[0];
      var szBackgroundColor = "";
      if (objHeaderCell && objHeaderCell.currentStyle) {
        szBackgroundColor = objHeaderCell.currentStyle['backgroundColor'];
      } else if (objHeaderCell && objHeaderCell.ownerDocument.defaultView.getComputedStyle) {
        szBackgroundColor = objHeaderCell.ownerDocument.defaultView.getComputedStyle(objHeaderCell, '').getPropertyValue("background-color");
      }
      objDivHeader.style.background = szBackgroundColor;
  }


  /*
   * Display Table
   */
  function _displayTable() {
    var objtableContainer = document.getElementById (this.tableContainerId);

    // Table has never been displayed before...
    if (objtableContainer == null) {
      // Register the table into the document attributes
      document.SortableTable = this;

      // Build table...
      document.write ('<DIV ID="' + this.tableContainerId + '" CLASS="' + this.className + '" STYLE="width: 400px; overflow: auto">');

      // Draw the table header...
      if (this.headerRow != null) {
        document.write ('<DIV ID="' + this.divHeaderId + '">');
        document.write ('<TABLE ID="' + this.tableHeaderId + '" CLASS="' + this.className + '" CELLSPACING="0" CELLPADDING="0">');
        document.write ('  <THEAD>');
        document.write ('    <TR>');
        for (var i = 0, n = this.headerRow.length; i < n; i++) {
          document.write ('    <TH onClick="document.SortableTable.sortByColumn(' + i + ');" STYLE="cursor: pointer; width: ' + this.headerRow[i].columnWidth + '">');
          document.write (this.headerRow[i].columnText);
          // Span used to hold the sort indicator...
          document.write ('      <SPAN ID="' + this.tableId + "_TH_" + i + '" STYLE="visibility: hidden">&nbsp;<IMG SRC="' + this.ascIndicator + '"></SPAN>');
          document.write ('    </TH>');
        }
        document.write ('    </TR>');

        document.write ('  </THEAD>');
        document.write ('</TABLE>');
        document.write ('</DIV>');
      }

      // Display detail lines...
      document.write ('<DIV ID="' + this.divBodyId + '" STYLE="width: 100%; overflow: auto; overflow-x: hidden;">');
      document.write ('<TABLE ID="' + this.tableBodyId + '"  CLASS="' + this.className + '" STYLE="width: 100%;" CELLSPACING="0" CELLPADDING="0">');
      document.write ('  <TBODY>');
      for (var i = 0, n = this.detailRows.length; i < n; i++) {
        var detailCols = this.detailRows[i];
        document.write ('<TR>');
        for (var j = 0, m = detailCols.length; j < m; j++) {
          document.write ('<TD STYLE="width: ' + this.headerRow[j].columnWidth + '">');
          document.write (detailCols[j].text);
          document.write ('</TD>');
        }
        document.write ('</TR>');
      }
      document.write ('  </TBODY>');
      document.write ('</TABLE>');
      document.write ('</DIV>');

      // Display footer line...
      if (this.footerText) {
        document.write ('<TABLE ID="' + this.tableFooterId + '"  CLASS="' + this.className + '" STYLE="width: 100%;" CELLSPACING="0" CELLPADDING="0">');
        document.write ('  <TFOOT>');
        document.write ('    <TR>');
        document.write ('      <TD>' + this.footerText + '</TD>');
        document.write ('    </TR>');
        document.write ('</TFOOT>');
      }
      document.write ('  </TABLE>');
      document.write ('</DIV>');

      // Override onLoad() function to resize table elements...
      this.addOnLoadEvent();
    }
  }

  /*
   * addOnLoadEvent function - add resizeTable event onLoad
   */
  function _addOnLoadEvent() {
    window.onload = function() {
      document.SortableTable.resizeTable();
    }
  }

  /*
   * String HTML tags from the input string
   */
  function _stripHtmlTags (szString) {
    var regExp = new RegExp ("<[^>]*>", "g")
    var string = String (szString);
    return string.replace (regExp, "");
  }
}

/* EOF */
