// Note: on 5/26, this has been released under the more broad free-use Apache Software License 2.
// Details: This component may be obtained, modified and distributed free of charge for personal as well as commercial use. Please see the license for the complete terms and exact wording.
// http://webfx.eae.net/dhtml/sortabletable/sortabletable.html
// http://webfx.eae.net/license/asl2
// http://www.apache.org/licenses/LICENSE-2.0
// Modfied by J.F. Kelley, search for "JFK"
/*----------------------------------------------------------------------------\
|                            Sortable Table 1.12                              |
|-----------------------------------------------------------------------------|
|                         Created by Erik Arvidsson                           |
|                 ( http://webfx.eae.net/contact.html#erik )                  |
|                      For WebFX ( http://webfx.eae.net/ )                    |
|-----------------------------------------------------------------------------|
| A DOM 1 based script that allows an ordinary HTML table to be sortable.     |
|-----------------------------------------------------------------------------|
|                  Copyright (c) 1998 - 2004 Erik Arvidsson                   |
|-----------------------------------------------------------------------------|
| This software is provided "as is", without warranty of any kind, express or |
| implied, including  but not limited  to the warranties of  merchantability, |
| fitness for a particular purpose and noninfringement. In no event shall the |
| authors or  copyright  holders be  liable for any claim,  damages or  other |
| liability, whether  in an  action of  contract, tort  or otherwise, arising |
| from,  out of  or in  connection with  the software or  the  use  or  other |
| dealings in the software.                                                   |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| This  software is  available under the  three different licenses  mentioned |
| below.  To use this software you must chose, and qualify, for one of those. |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Non-Commercial License          http://webfx.eae.net/license.html |
| Permits  anyone the right to use the  software in a  non-commercial context |
| free of charge.                                                             |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Commercial license           http://webfx.eae.net/commercial.html |
| Permits the  license holder the right to use  the software in a  commercial |
| context. Such license must be specifically obtained, however it's valid for |
| any number of  implementations of the licensed software.                    |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| GPL - The GNU General Public License    http://www.gnu.org/licenses/gpl.txt |
| Permits anyone the right to use and modify the software without limitations |
| as long as proper  credits are given  and the original  and modified source |
| code are included. Requires  that the final product, software derivate from |
| the original  source or any  software  utilizing a GPL  component, such  as |
| this, is also licensed under the GPL license.                               |
|-----------------------------------------------------------------------------|
| 2003-01-10 | First version                                                  |
| 2003-01-19 | Minor changes to the date parsing                              |
| 2003-01-28 | JScript 5.0 fixes (no support for 'in' operator)               |
| 2003-02-01 | Sloppy typo like error fixed in getInnerText                   |
| 2003-07-04 | Added workaround for IE cellIndex bug.                         |
| 2003-11-09 | The bDescending argument to sort was not correctly working     |
|            | Using onclick DOM0 event if no support for addEventListener    |
|            | or attachEvent                                                 |
| 2004-01-13 | Adding addSortType and removeSortType which makes it a lot     |
|            | easier to add new, custom sort types.                          |
| 2004-01-27 | Switch to use descending = false as the default sort order.    |
|            | Change defaultDescending to suit your needs.                   |
| 2004-03-14 | Improved sort type None look and feel a bit                    |
| 2004-08-26 | Made the handling of tBody and tHead more flexible. Now you    |
|            | can use another tHead or no tHead, and you can chose some      |
|            | other tBody.                                                   |
|-----------------------------------------------------------------------------|
| Created 2003-01-10 | All changes are in the log above. | Updated 2004-08-26 |
\----------------------------------------------------------------------------*/

var sortabletable_global_descending = 0;  // JFK 20070620 -- see StringNB


Array.prototype.stableFFswap=function(a, b) // JFK 20070919 to accomodate Mozilla's frustrating non-stable sort.
{
   var tmp=this[a];
   this[a]=this[b];
   this[b]=tmp;
}

Array.prototype.stableFFsort=function(comparator)   // JFK 20070919 to accomodate Mozilla's frustrating non-stable sort.
{
   if (!comparator) comparator = function (v1, v2) { return v1 - v2; };
   var length = this.length;
   for (var i=1; i < length; i++)
   {
      for (var j = i; j > 0; j--) if (comparator(this[j], this[j-1]) < 0) this.stableFFswap(j, j-1);
   }
}

var sortabletable_global_isFF = (navigator.userAgent.toLowerCase().indexOf('firefox') != -1)  // JFK 20070919

function SortableTable(oTable, oSortTypes) {

 this.sortTypes = oSortTypes || [];

 this.sortColumn = null;
 this.descending = null;

 var oThis = this;
 this._headerOnclick = function (e) {
  oThis.headerOnclick(e);
 };

 if (oTable) {
  this.setTable( oTable );
  this.document = oTable.ownerDocument || oTable.document;
 }
 else {
  this.document = document;
 }


 // only IE needs this
 var win = this.document.defaultView || this.document.parentWindow;
 this._onunload = function () {
  oThis.destroy();
 };
 if (win && typeof win.attachEvent != "undefined") {
  win.attachEvent("onunload", this._onunload);
 }
}

SortableTable.gecko = navigator.product == "Gecko";
SortableTable.msie = /msie/i.test(navigator.userAgent);
// Mozilla is faster when doing the DOM manipulations on
// an orphaned element. MSIE is not
SortableTable.removeBeforeSort = SortableTable.gecko;

SortableTable.prototype.onsort = function () {};

// default sort order. true -> descending, false -> ascending
SortableTable.prototype.defaultDescending = false;

// shared between all instances. This is intentional to allow external files
// to modify the prototype
SortableTable.prototype._sortTypeInfo = {};

SortableTable.prototype.setTable = function (oTable) {
 if ( this.tHead )
  this.uninitHeader();
 this.element = oTable;
 this.setTHead( oTable.tHead );
 this.setTBody( oTable.tBodies[0] );
};

SortableTable.prototype.setTHead = function (oTHead) {
 if (this.tHead && this.tHead != oTHead )
  this.uninitHeader();
 this.tHead = oTHead;
 this.initHeader( this.sortTypes );
};

SortableTable.prototype.setTBody = function (oTBody) {
 this.tBody = oTBody;
};

SortableTable.prototype.setSortTypes = function ( oSortTypes ) {
 if ( this.tHead )
  this.uninitHeader();
 this.sortTypes = oSortTypes || [];
 if ( this.tHead )
  this.initHeader( this.sortTypes );
};

// adds arrow containers and events
// also binds sort type to the header cells so that reordering columns does
// not break the sort types
SortableTable.prototype.initHeader = function (oSortTypes) {
 if (!this.tHead) return;
 var cells = this.tHead.rows[0].cells;
 var doc = this.tHead.ownerDocument || this.tHead.document;
 this.sortTypes = oSortTypes || [];
 var l = cells.length;
 var img, c;
 for (var i = 0; i < l; i++) {
  c = cells[i];
  if (this.sortTypes[i] != null && this.sortTypes[i] != "None") {
   img = doc.createElement("IMG");
   img.src = "images/blank.png";
   c.appendChild(img);
   if (this.sortTypes[i] != null)
    c._sortType = this.sortTypes[i];
   if (typeof c.addEventListener != "undefined")
    c.addEventListener("click", this._headerOnclick, false);
   else if (typeof c.attachEvent != "undefined")
    c.attachEvent("onclick", this._headerOnclick);
   else
    c.onclick = this._headerOnclick;
  }
  else
  {
   c.setAttribute( "_sortType", oSortTypes[i] );
   c._sortType = "None";
  }
 }
 this.updateHeaderArrows();
};

// remove arrows and events
SortableTable.prototype.uninitHeader = function () {
 if (!this.tHead) return;
 try { // sometimes this just fails inexplicably.  Often when exiting the page.
   var cells = this.tHead.rows[0].cells;
   var l = cells.length;
   var c;
   for (var i = 0; i < l; i++) {
    c = cells[i];
    if (c._sortType != null && c._sortType != "None") {
     c.removeChild(c.lastChild);
     if (typeof c.removeEventListener != "undefined")
      c.removeEventListener("click", this._headerOnclick, false);
     else if (typeof c.detachEvent != "undefined")
      c.detachEvent("onclick", this._headerOnclick);
     c._sortType = null;
     c.removeAttribute( "_sortType" );
    }
   }
  }
 catch(e) {
   //alert("Prototype warning from SortableTable.uninitHeader(): " + e) // JFK This happens a LOT.
   window.status = "Prototype warning from SortableTable.uninitHeader(): " + e // JFK This happens a LOT.
   }
};

SortableTable.prototype.updateHeaderArrows = function () {
 if (!this.tHead) return;
 var cells = this.tHead.rows[0].cells;
 var l = cells.length;
 var img;
 for (var i = 0; i < l; i++) {
  if (cells[i]._sortType != null && cells[i]._sortType != "None") {
   img = cells[i].lastChild;
   if (i == this.sortColumn)
    img.className = "sort-arrow " + (this.descending ? "descending" : "ascending");
   else
    img.className = "sort-arrow";
  }
 }
};

SortableTable.prototype.headerOnclick = function (e) {
 // find TD element
 var el = e.target || e.srcElement;
 while ((el.tagName != "TD") && (el.tagName != "TH")) // JFK Add test for TH
  el = el.parentNode;


 this.sort(SortableTable.msie ? SortableTable.getCellIndex(el) : el.cellIndex);
};

// IE returns wrong cellIndex when columns are hidden
SortableTable.getCellIndex = function (oTd) {
 var cells = oTd.parentNode.childNodes
 var l = cells.length;
 var i;
 for (i = 0; cells[i] != oTd && i < l; i++)
  ;
 return i;
};

SortableTable.prototype.getSortType = function (nColumn) {
 return this.sortTypes[nColumn] || "String";
};

// only nColumn is required
// if bDescending is left out the old value is taken into account
// if sSortType is left out the sort type is found from the sortTypes array

SortableTable.prototype.sort = function (nColumn, bDescending, sSortType) {
 if (!this.tBody) return;
 if (sSortType == null)
  sSortType = this.getSortType(nColumn);

 // exit if None
 if (sSortType == "None")
  return;

 if (bDescending == null) {
  if (this.sortColumn != nColumn) {
   this.descending = this.defaultDescending;
   sortabletable_global_descending = -1  // JFK 20070620
   }
  else {
   this.descending = !this.descending;
   sortabletable_global_descending = this.descending ? 0 : 1 // JFK 20070620
   }
 }
 else
  this.descending = bDescending;
 this.sortColumn = nColumn;

 if (typeof this.onbeforesort == "function")
  this.onbeforesort();

 var f = this.getSortFunction(sSortType, nColumn);
 var a = this.getCache(sSortType, nColumn);
 var tBody = this.tBody;

 if (sortabletable_global_isFF) a.stableFFsort(f); // JFK 20070919
 else a.sort(f);                                   // JFK 20070919 (the else part)


 if (this.descending) {
  a.reverse();
  }


 if (SortableTable.removeBeforeSort) {
  // remove from doc
  var nextSibling = tBody.nextSibling;
  var p = tBody.parentNode;
  p.removeChild(tBody);
 }

 // insert in the new order
 var l = a.length;
 for (var i = 0; i < l; i++)
  tBody.appendChild(a[i].element);

 if (SortableTable.removeBeforeSort) {
  // insert into doc
  p.insertBefore(tBody, nextSibling);
 }

 this.updateHeaderArrows();

 this.destroyCache(a);

 if (typeof this.onsort == "function")
  this.onsort();
};

SortableTable.prototype.asyncSort = function (nColumn, bDescending, sSortType) {
 var oThis = this;
 this._asyncsort = function () {
  oThis.sort(nColumn, bDescending, sSortType);
 };
 window.setTimeout(this._asyncsort, 1);
};

SortableTable.prototype.getCache = function (sType, nColumn) {
 if (!this.tBody) return [];
 var rows = this.tBody.rows;
 var l = rows.length;
 var a = new Array(l);
 var r;
 for (var i = 0; i < l; i++) {
  r = rows[i];
  a[i] = {
   value:  this.getRowValue(r, sType, nColumn),
   element: r
  };
 };
 return a;
};

SortableTable.prototype.destroyCache = function (oArray) {
 var l = oArray.length;
 for (var i = 0; i < l; i++) {
  oArray[i].value = null;
  oArray[i].element = null;
  oArray[i] = null;
 }
};

SortableTable.prototype.getRowValue = function (oRow, sType, nColumn) {
 // if we have defined a custom getRowValue use that
 if (this._sortTypeInfo[sType] && this._sortTypeInfo[sType].getRowValue)
  return this._sortTypeInfo[sType].getRowValue(oRow, nColumn);

 var s;
 var c = oRow.cells[nColumn];
 if (typeof c.innerText != "undefined")
  s = c.innerText;
 else
  s = SortableTable.getInnerText(c);
 return this.getValueFromString(s, sType);
};

SortableTable.getInnerText = function (oNode) {
 var s = "";
 var cs = oNode.childNodes;
 var l = cs.length;
 for (var i = 0; i < l; i++) {
  switch (cs[i].nodeType) {
   case 1: //ELEMENT_NODE
    s += SortableTable.getInnerText(cs[i]);
    break;
   case 3: //TEXT_NODE
    s += cs[i].nodeValue;
    break;
  }
 }
 return s;
};

SortableTable.prototype.getValueFromString = function (sText, sType) {
 if (this._sortTypeInfo[sType])
  return this._sortTypeInfo[sType].getValueFromString( sText );
 return sText;
 /*
 switch (sType) {
  case "Number":
   return Number(sText);
  case "CaseInsensitiveString":
   return sText.toUpperCase();
  case "Date":
   var parts = sText.split("-");
   var d = new Date(0);
   d.setFullYear(parts[0]);
   d.setDate(parts[2]);
   d.setMonth(parts[1] - 1);
   return d.valueOf();
  case "CaseInsensitiveStringNB":                   // JFK 20071115
   return sText.toUpperCase();
  case "Dollar":                                    // JFK 20071115
   return Number(sText.replace(/[,\x24]/g,""))
  case "DollarNB":                                  // JFK 20071115
   return Number(sText.replace(/[,\x24]/g,""))
  case "DollarCents":                               // JFK 20071115
   return Number(sText.replace(/[,\x24]/g,""))
  case "DollarCentsNB":                             // JFK 20071115
   return Number(sText.replace(/[,\x24]/g,""))
  case "Percent":                                   // JFK 20071115
   return Number(sText.replace(/%/g,""))
 }
 return sText;
 */
 };

SortableTable.prototype.getSortFunction = function (sType, nColumn) {
 if (this._sortTypeInfo[sType])
  return this._sortTypeInfo[sType].compare;
 return SortableTable.basicCompare;
};

SortableTable.prototype.destroy = function () {
 this.uninitHeader();
 var win = this.document.parentWindow;
 if (win && typeof win.detachEvent != "undefined") { // only IE needs this
  win.detachEvent("onunload", this._onunload);
 }
 this._onunload = null;
 this.element = null;
 this.tHead = null;
 this.tBody = null;
 this.document = null;
 this._headerOnclick = null;
 this.sortTypes = null;
 this._asyncsort = null;
 this.onsort = null;
};

// Adds a sort type to all instance of SortableTable
// sType : String - the identifier of the sort type
// fGetValueFromString : function ( s : string ) : T - A function that takes a
//    string and casts it to a desired format. If left out the string is just
//    returned
// fCompareFunction : function ( n1 : T, n2 : T ) : Number - A normal JS sort
//    compare function. Takes two values and compares them. If left out less than,
//    <, compare is used
// fGetRowValue : function( oRow : HTMLTRElement, nColumn : int ) : T - A function
//    that takes the row and the column index and returns the value used to compare.
//    If left out then the innerText is first taken for the cell and then the
//    fGetValueFromString is used to convert that string the desired value and type

SortableTable.prototype.addSortType = function (sType, fGetValueFromString, fCompareFunction, fGetRowValue) {
 this._sortTypeInfo[sType] = {
  type:    sType,
  getValueFromString: fGetValueFromString || SortableTable.idFunction,
  compare:   fCompareFunction || SortableTable.basicCompare,
  getRowValue:  fGetRowValue
 };
};

// this removes the sort type from all instances of SortableTable
SortableTable.prototype.removeSortType = function (sType) {
 delete this._sortTypeInfo[sType];
};

SortableTable.basicCompare = function compare(n1, n2) {
 if (n1.value < n2.value)
  return -1;
 if (n2.value < n1.value)
  return 1;
 return 0;
};

SortableTable.idFunction = function (x) {
 return x;
};

SortableTable.toUpperCase = function (s) {
 return s.toUpperCase();
};

SortableTable.toDate = function (s) {
 var parts = s.split("-");
 var d = new Date(0);
 d.setFullYear(parts[0]);
 d.setDate(parts[2]);
 d.setMonth(parts[1] - 1);
 return d.valueOf();
};

SortableTable.toDateMDYSlash = function (s) {
 var parts = s.split("/");
 var d = new Date(0);
 d.setFullYear(parts[2]);
 d.setDate(parts[1]);
 d.setMonth(parts[0] - 1);
 return d.valueOf();
};

SortableTable.toDateYMDDash = function (s) {
 var parts = s.split("-");
 var d = new Date(0);
 d.setFullYear(parts[0]);
 d.setDate(parts[2]);
 d.setMonth(parts[1] - 1);
 return d.valueOf();
};


SortableTable.toDateMmDdYyyy= function (s) { // JFK 20070228
 var parts = s.split(" ");
 var d = new Date(0);
 d.setFullYear(parts[2]);
 d.setDate(parts[1]);

 switch (parts[0].toUpperCase().substring(0,3)) {
   case "JAN":var mmm=0;break;
   case "FEB":var mmm=1;break;
   case "MAR":var mmm=2;break;
   case "APR":var mmm=3;break;
   case "MAY":var mmm=4;break;
   case "JUN":var mmm=5;break;
   case "JUL":var mmm=6;break;
   case "AUG":var mmm=7;break;
   case "SEP":var mmm=8;break;
   case "OCT":var mmm=9;break;
   case "NOV":var mmm=10;break;
   case "DEC":var mmm=11;break;
   break;
   }
 d.setMonth(mmm);
 return d.valueOf();
};

SortableTable.toDateDdMmYyyy= function (s) { // JFK 20070228
 var parts = s.split(" ");
 var d = new Date(0);
 d.setFullYear(parts[2]);
 d.setDate(parts[0]);

 switch (parts[1].toUpperCase().substring(0,3)) {
   case "JAN":var mmm=0;break;
   case "FEB":var mmm=1;break;
   case "MAR":var mmm=2;break;
   case "APR":var mmm=3;break;
   case "MAY":var mmm=4;break;
   case "JUN":var mmm=5;break;
   case "JUL":var mmm=6;break;
   case "AUG":var mmm=7;break;
   case "SEP":var mmm=8;break;
   case "OCT":var mmm=9;break;
   case "NOV":var mmm=10;break;
   case "DEC":var mmm=11;break;
   break;
   }
 d.setMonth(mmm);
// alert(s + " / " + d.toString())
 return d.valueOf();
};

SortableTable.StringNB = function (s) { // JFK 20070620
 //window.status=sortabletable_global_descending
 if (s == "") {
   if (sortabletable_global_descending != 0) return "ZZZZZZZ"
   else return "AAAAAAAAAAAA"
   }
 else return s
}

SortableTable.CaseInsensitiveStringNB = function (s) { // JFK 20070620
 //window.status=sortabletable_global_descending
 if (s == "") {
   if (sortabletable_global_descending != 0) return "ZZZZZZZ"
   else return "AAAAAAAAAAAA"
   }
 else return s
}

SortableTable.toCommaNumber = function (s) { // JFK 20070604
 return Number(s.replace(/[,\x24]/g,"")) // JFK 20071115 added $
};

SortableTable.toCommaNumberNB = function (s) { // JFK 20070906
 if (s == "") {
   if (sortabletable_global_descending != 0) return Number.MAX_VALUE
   else return 0-Number.MAX_VALUE
   }
 else return Number(s.replace(/[,\x24]/g,""))  // JFK 20071115 added $
};

SortableTable.NumberNB = function (s) { // JFK 20070620
 if (s == "") {
   if (sortabletable_global_descending != 0) return Number.MAX_VALUE
   else return 0-Number.MAX_VALUE
   }
 else return Number(s)
}

SortableTable.toGMKNB = function (val) { // JFK 20070620
 var s=val.split(" ")[0]
 var gmk = val.split(" ")[1]

 if (s == "") {
   if (sortabletable_global_descending != 0) return Number.MAX_VALUE
   else return 0-Number.MAX_VALUE
   }
 else {
   if      (gmk=="G") s=s*1000000000
   else if (gmk=="M") s=s*1000000
   else if (gmk=="K") s=s*1000
   return Number(s)
   }
}

SortableTable.toPercent = function (s) { // JFK 20071016
 return Number(s.replace(/%/g,"")) // JFK 20071115
};


// add sort types
SortableTable.prototype.addSortType("String");
SortableTable.prototype.addSortType("StringNB", SortableTable.StringNB); // JFK 20070620
SortableTable.prototype.addSortType("CaseInsensitiveString", SortableTable.toUpperCase);
SortableTable.prototype.addSortType("CaseInsensitiveStringNB", SortableTable.CaseInsensitiveStringNB); // JFK 20070620

SortableTable.prototype.addSortType("Number", Number);
SortableTable.prototype.addSortType("NumberNB", SortableTable.NumberNB); // JFK 20070620
SortableTable.prototype.addSortType("CommaNumber", SortableTable.toCommaNumber); // JFK 20070604
SortableTable.prototype.addSortType("CommaNumberNB", SortableTable.toCommaNumberNB); // JFK 20070906

SortableTable.prototype.addSortType("Percent", SortableTable.toPercent); // JFK 20071016

SortableTable.prototype.addSortType("Date", SortableTable.toDate);
SortableTable.prototype.addSortType("DateDdMmYyyy", SortableTable.toDateDdMmYyyy); // JFK 20070228
SortableTable.prototype.addSortType("DateMmDdYyyy", SortableTable.toDateMmDdYyyy); // JFK 20070228 Format: (?) Jan 31 2007
SortableTable.prototype.addSortType("DateMmDdYyyySLASH", SortableTable.toDateMDYSlash); // JFK 20090326 1/31/2009
SortableTable.prototype.addSortType("DateYMDDASH", SortableTable.toDateYMDDash); // JFK 20090403 2009-1-31

SortableTable.prototype.addSortType("Dollar", SortableTable.toCommaNumber); // JFK 20071115
SortableTable.prototype.addSortType("DollarCents", SortableTable.toCommaNumber); // JFK 20071115
SortableTable.prototype.addSortType("DollarCentsNB", SortableTable.toCommaNumberNB); // JFK 20071115
SortableTable.prototype.addSortType("DollarNB", SortableTable.toCommaNumberNB); // JFK 20071115

SortableTable.prototype.addSortType("GMKNB", SortableTable.toGMKNB); // JFK 20090403 e.g., 1.21 G
// None is a special case
