//
// DHTML List API - Copyright (c) 2003 interactivetools.com, inc.
//


// Note: IE doesn't maintain whether a checkbox is checked when swapping nodes, so don't use them in list rows!


// -----------------------------------------------------------------------------

function list_init(listname, maxRows) {
  var tableBody = document.getElementById(listname + '_body');
  var listData = document.getElementById(listname + '_data');
  var addRow = document.getElementById(listname + '_add_row');

  // store information about this list
  list_init.globals[listname] = new Object;
  list_init.globals[listname].maxRows = maxRows;
  list_init.globals[listname].noRows = false;
  list_init.globals[listname].next_unique_id = 1;

  // remove any existing rows from the table (so list_init can be called multiple times?)
/*  var tableRows = _getTableRows(tableBody);
  for (var n=0; n<tableRows.length; n++) {
    var thisRow = tableRows[n];
    thisRow.parentNode.removeChild(thisRow);
  }*/

  // get data from hidden fields
  var hiddenFields = listData.getElementsByTagName('input');
  var listRows = new Array();
  for (var n=0; n < hiddenFields.length; n++) {
    var placeholders = query2obj(hiddenFields[n].value);
    placeholders.data = hiddenFields[n].value;
    placeholders.unique_id = list_init.globals[listname].next_unique_id;
    listRows.push( placeholders );

    // increment unique_id for next time
    list_init.globals[listname].next_unique_id++;
  }
  setInnerHTML(listData, '');

  // create rows (obey maxRows rule)
  var htmlRows = "";
  if (listRows.length > 0) {
    for (var n=0; n < listRows.length && !(maxRows && n >= maxRows); n++) {
      htmlRows += templateCell(listname + '_row', listRows[n]);
    }
  } else {
    htmlRows += templateCell(listname + '_norows', {});
    list_init.globals[listname].noRows = true;
  }

  _appendRowsWithTmpHTML(tableBody, htmlRows);

  // hide the add_row if there are too many items
  if (listRows.length >= list_init.globals[listname].maxRows) {
    DisableBranch(addRow);
    //addRow.style.display = 'none';
  } else {
    EnableBranch(addRow);
    //addRow.style.display = '';
  }

  list_recolour(listname);
}

list_init.globals = new Object();

// -----------------------------------------------------------------------------

function list_append(listname, placeholders) {
  var tableBody = document.getElementById(listname + '_body');
  var addRow = document.getElementById(listname + '_add_row');
  var maxRows = list_init.globals[listname].maxRows;
  var tableRows = _getTableRows(tableBody);
  var rows = tableRows.length;

  // remove "norows" row, if it's there
  if (list_init.globals[listname].noRows == true) {
    tableRows[0].parentNode.removeChild(tableRows[0]);
    list_init.globals[listname].noRows = false
    rows--;
  }

  // are we allowed to add another item?  (maxRows)
  if (rows >= maxRows) {
    alert("Too many items");
    return;
  }

  // if we'll reach the limit after adding this one, hide the "add_row"
  if (rows + 1 == maxRows) {
    DisableBranch(addRow);
    //addRow.style.display = 'none';
  }

  // assign this new row a unique_id
  placeholders.unique_id = list_init.globals[listname].next_unique_id;

  // create new row
  var htmlRows = templateCell(listname + '_row', placeholders);
  _appendRowsWithTmpHTML(tableBody, htmlRows);

  // increment unique_id for next time
  list_init.globals[listname].next_unique_id++;

  list_recolour(listname);
}

// -----------------------------------------------------------------------------

function list_erase(listname, sourceElement) {
  var tableBody = document.getElementById(listname + '_body');
  var addRow = document.getElementById(listname + '_add_row');

  // remove parent row
  var thisRow = getParentByTagName(sourceElement, 'TR');
  thisRow.parentNode.removeChild(thisRow);

  // if there are no items left, display "norows" message
  var tableRows = _getTableRows(tableBody);
  if (tableRows.length == 0) {
    var htmlRows = templateCell(listname + '_norows', {});
    _appendRowsWithTmpHTML(tableBody, htmlRows);
    list_init.globals[listname].noRows = true;
  }

  // redisplay "add_row"
  EnableBranch(addRow);
  //addRow.style.display = '';

  list_recolour(listname);
}

// -----------------------------------------------------------------------------

function list_move(listname, selectedItem, direction) {
  var tableBody = document.getElementById(listname + '_body');
  var tableRows = _getTableRows(tableBody);

  // sanity checking
  if (direction != 'up' && direction != 'down') { return alert("list_move: direction must be 'up' or 'down'"); }

  // find parent table row
  var selectedRow = getParentByTagName(selectedItem, 'TR');

  var selectedIndex = -1;
  for (var n=0; n<tableRows.length; n++) {
    if (tableRows[n] == selectedRow) {
      selectedIndex = n;
    }
  }
  if (selectedIndex == -1) { return alert("list_move: unable to find index of TR in table"); }

  // are we moving up off the top?
  if (direction == 'up' && selectedIndex == 0) {
    for (var n=tableRows.length-2; n>=0; n--) {
      _swapNode(tableRows[n+1], tableRows[n]);
    }
  
  // are we moving down off the bottom?
  } else if (direction == 'down' && selectedIndex == tableRows.length - 1) {
    for (var n=0; n<=(tableRows.length-2); n++) {
      _swapNode(tableRows[n], tableRows[n+1]);
    }
  
  // otherwise, just swap with the next item
  } else {
    var targetIndex = selectedIndex + ((direction == 'up') ? -1 : 1);
    var targetRow = tableRows[targetIndex];
    _swapNode(tableRows[selectedIndex], targetRow);
  }

  list_recolour(listname);
}

// -----------------------------------------------------------------------------

function list_recolour(listname) { 

  var tableBody = document.getElementById(listname + '_body');
  var tableRows = _getTableRows(tableBody);
  var classOrder = ['lRowEven', 'lRowOdd'];

  // re-arrange rows in table
  for (var n=0; n<tableRows.length; n++) {
    var thisRow = tableRows[n];

    // update bgcolor
    var className = classOrder[ n % classOrder.length ];
    thisRow.className = className;  // setAttribute('class') doesn't work in IE6
  }

}

// -----------------------------------------------------------------------------
/*
function list_sort(listname) { 
  var tableBody = document.getElementById(listname + '_body');
  var tableRows = _getTableRows(tableBody);
//  var tableRows = tableBody.getElementsByTagName('tr');
  var myRowOrder = getElementsByName(tableBody, listname + '_order');

  // create list of rows
  var myRows = [];
  for (var n=0; n<tableRows.length; n++) {
    var thisOrder = parseInt( myRowOrder[n].value );
    myRows.push({ element: tableRows[n], order: thisOrder });
  }

  // sort list of rows
  myRows.sort(
   function(value1, value2) {
    var order1 = parseInt(value1.order) || 0;
    var order2 = parseInt(value2.order) || 0;
    if      (order1 < order2)  { return -1; }
    else if (order1 == order2) { return 0; }
    else if (order1 > order2)  { return 1; }
  });

  // re-arrange rows in table
  for (var n=0; n<tableRows.length; n++) {
    alert(n + " <=> " + (5-myRows[n].order));
    var thisRow = myRows[n].element;
    _swapNode( tableRows[n], tableRows[n] );
  }

  list_recolour(listname);
}
*/
// -----------------------------------------------------------------------------

function getParentByTagName(sourceElement, tagName) {
  var el = sourceElement;
  while (el.nodeName.toUpperCase() != tagName.toUpperCase()) {
    el = el.parentNode;
    if (el == null) { return alert("getParentByTagName: unable to find " + tagName + " parentNode"); }
  }
  return el;
}

// -----------------------------------------------------------------------------

function getElementsByName(sourceElement, targetName) {

  var results = new Array();

  // search child nodes
  for (var n=0; n<sourceElement.childNodes.length; n++) { 
    var thisNode = sourceElement.childNodes[n];

    // Does this node match our criteria?
    if (thisNode.name == targetName) {
      results.push(thisNode);

    // Do we need to search the children?
    } else {
      var childResults = getElementsByName(thisNode, targetName);
      for (var x=0; x<childResults.length; x++) { 
        results.push(childResults[x]);
      }
    }
  }
  return results;
}

// -----------------------------------------------------------------------------

function _swapNode(source, target) {  // emulate swapnode for mozilla
  if (typeof source == 'string') { source = document.getElementById(source); }
  if (typeof target == 'string') { target = document.getElementById(target); }
  if (source == target) { return; }

  // use builtin features if available
  if (source.swapNode) {
    source.swapNode(target);
    return;
  }

  var sourceParent = source.parentNode;
  var targetParent = target.parentNode;
  var tempSource   = source.cloneNode(true); // document.createElement('SPAN');

/*
  DOMViewerObj = tempSource;
  DOMViewerName = 'tempSource';
  window.open('/sb/core/source/cgi/_utils/domviewer.html');
  return;
*/

  var origSource = sourceParent.replaceChild(tempSource, source);
  var origTarget = targetParent.replaceChild(origSource, target);
  sourceParent.replaceChild(origTarget, tempSource);
}

// -----------------------------------------------------------------------------

function _appendRowsWithTmpHTML(tableBody, htmlRows) {
  var tmpHTML = document.getElementById('tmpHTML');

  // insert temp table
  //alert(getInnerHTML(tmpHTML));
  //alert('<table border=1>' + htmlRows + '</table>');
  setInnerHTML(tmpHTML, '<table border=1>' + htmlRows + '</table>');
  //alert(getInnerHTML(tmpHTML));
  var tmpTable = tmpHTML.getElementsByTagName('table')[0];

  var tmpRows = _getTableRows(tmpTable, 'appendRowsWithTmpHTML');

  // copy rows over
  for (var n=0; n<tmpRows.length; n++) {
    var tmpRow = tmpRows[n];
    tmpRow.removeAttribute('id', 0);
    tableBody.appendChild( tmpRow );
  }

  // erase tmp table
  //setInnerHTML(tmpHTML, '');
}

// -----------------------------------------------------------------------------

function _getTableRows(sourceElement) {
//  if (typeof sourceElement == 'string') { sourceElement = document.getElementById(sourceElement); }

  var rows = new Array();

  // search child nodes
  for (var n=0; n<sourceElement.childNodes.length; n++) { 
    var thisNode = sourceElement.childNodes[n];

    // Have we found the requested tag?
    if (thisNode.nodeName == 'TR') {
      rows.push(thisNode);

    // Do we need to search the children?  (eg. table -> tbody -> tr)
    } else {
      var childRows = _getTableRows(thisNode, 'recurse');
      for (var x=0; x<childRows.length; x++) { 
        rows.push(childRows[x]);
      }
    }
  }
  return rows;
}

// -----------------------------------------------------------------------------

