/*
* TableSorter
* (c) 2005 by Q42 Internet B.V.
* Written by Martin Kool
*
* Description:
*
* - Sorts a table clientside on column values, ascending and descending, by simply clicking on a column
*
* Usage:
*
* - Include this script
* - Columns should be defined as TH elements inside a THEAD (or: do not create lousy html)
* - Just add an onclick="tableSorter.sort()" on the thead element of the table you'd like to sort
*/

function TableSorter()
{
}
TableSorter.prototype =
{
  colNumber : 0
  ,
  trs : null
  ,
  tbody : null
  ,
  sort : function()
  {
    var initialized = this.__init(event.srcElement);
    if (!initialized)
      return;
    
    var sortArray = [];

    // fill array with 2-length arrays: [lowercase text to sort, tr]
    for (var i=0; i<this.trs.length; i++)
    {
      if (this.trs[i].childNodes[this.colNumber].className.indexOf("date") == 0)
        sortArray.push([this.trs[i].childNodes[this.colNumber].className.substring(4,14).toLowerCase(), this.trs[i]]);
      else
        sortArray.push([this.trs[i].childNodes[this.colNumber].innerText.toLowerCase(), this.trs[i]]);
    }

    // remember the current array contents
    var beforeSort = sortArray.toString();
    
    // sort using the sort method below
    sortArray.sort(this.__sortMethod);
    
    // compare sortresults, and if it's the same as it was, reverse it
    var afterSort = sortArray.toString();
    if (beforeSort == afterSort)
      sortArray.reverse();

    // replace the tr's accordingly
    for (var i=0; i<sortArray.length; i++)      
      this.tbody.appendChild(sortArray[i][1]);
  }
  ,
  // looks up the th, table and tbody elements, and prepares the tr's
  __init : function(el)
  {
    for (var th = el; th.parentNode && th.tagName != "TH"; th = th.parentNode);
    for (var table = el; table.parentNode && table.tagName != "TABLE"; table = table.parentNode);
    
    if (!th || th.tagName != "TH" || !table || table.tagName != "TABLE")
      return false;
    
    this.colNumber = 0;
    for (var temp = th; temp = temp.previousSibling; this.colNumber++);
        
    this.tbody = table.getElementsByTagName("tbody")[0];
    this.trs = this.tbody.childNodes;
    return true;    
  }
  ,
  // sorter method used by array.sort()
  __sortMethod : function(a, b)
  {
    if (a[0] == b[0])
      return 0;
    else
      return (a[0] < b[0])? -1 : 1
  }
}
var tableSorter = new TableSorter();