
function TableSort(oTable, oSortTypes) {
	this.sortTypes = oSortTypes || [];
	this.sortColumn = null;
	this.descending = null;
	this.lastImageId = null;
  this.sortImage 		= new Image();
  this.sortImageUp	= new Image();
  this.sortImageDown = new Image();

  /* Allow Multiple Arrow Styles, Read Prefix From XHTML */
  var sortEnt = document.getElementById("sort_key_0");
  var sortSrc = sortEnt.src;
  var srcBits = sortSrc.split("/");
  var imgName = srcBits[srcBits.length-1];
  var imgBits = imgName.split("_");
  var imgPrefix = imgBits[0];

  this.sortImage.src = "/images/" + imgPrefix + "_sort.gif";
	this.sortImageUp.src = "/images/" + imgPrefix + "_sort_up.gif";
	this.sortImageDown.src = "/images/" + imgPrefix + "_sort_down.gif";


  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);
	}
}

TableSort.gecko = navigator.product == "Gecko";
TableSort.msie = /msie/i.test(navigator.userAgent);
// Mozilla is faster when doing the DOM manipulations on
// an orphaned element. MSIE is not
TableSort.removeBeforeSort = TableSort.gecko;

TableSort.prototype.onsort = function () {};
// shared between all instances. This is intentional to allow external files
// to modify the prototype
TableSort.prototype._sortTypeInfo = {};

TableSort.prototype.setTable = function (oTable) {
	this.element = oTable;
	this.setTBody( oTable.tBodies[0] );
};

TableSort.prototype.setTBody = function (oTBody) {
	this.tBody = oTBody;
};

TableSort.prototype.setSortTypes = function ( oSortTypes ) {
	this.sortTypes = oSortTypes || [];
};

// IE returns wrong cellIndex when columns are hidden
TableSort.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;
};

TableSort.prototype.getSortType = function (nColumn) {
	return this.sortTypes[nColumn] || "String";
};


TableSort.prototype.changeSortImage = function(nColumn) {
	var sortImageId = "sort_key_"+nColumn;

	if (this.descending) {
		document.getElementById(sortImageId).src = this.sortImageDown.src;
	} else {
    document.getElementById(sortImageId).src = this.sortImageUp.src;
	}

	if (this.lastImageId && this.sortColumn!=nColumn) {
		document.getElementById(this.lastImageId).src = this.sortImage.src;
	}

	this.lastImageId = sortImageId;
}

// 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
TableSort.prototype.sort = function (nColumn, sSortType,direction) {
	if (!this.tBody) return;
	if (sSortType == null)
		sSortType = this.getSortType(nColumn);

  if (this.sortColumn != nColumn)
    this.descending = (sSortType=="String" || sSortType=="CareersString" || sSortType=="Date" || sSortType=="ExpenseRatio" || sSortType=="tSort") ? false : true;
  else
    this.descending = !this.descending;

  this.changeSortImage(nColumn);
	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;

  a.sort(f);

	if (this.descending) a.reverse();

	if (TableSort.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 (TableSort.removeBeforeSort) {
		// insert into doc
		p.insertBefore(tBody, nextSibling);
	}

	this.destroyCache(a);

	if (typeof this.onsort == "function") this.onsort();
};

TableSort.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;
};

TableSort.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;
	}
};

TableSort.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 = TableSort.getInnerText(c);

  return this.getValueFromString(s, sType);
};

TableSort.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 += TableSort.getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				s += cs[i].nodeValue;
				break;
		}
	}
	return s;
};

TableSort.prototype.getValueFromString = function (sText, sType) {
	if (this._sortTypeInfo[sType])
		return this._sortTypeInfo[sType].getValueFromString( sText );
	return sText;
};

TableSort.prototype.getSortFunction = function (sType, nColumn) {
	if (this._sortTypeInfo[sType])
		return this._sortTypeInfo[sType].compare;
	return TableSort.basicCompare;
};

TableSort.prototype.destroy = function () {
	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.tBody = null;
	this.document = null;
	this._headerOnclick = null;
	this.sortTypes = null;
	this.onsort = null;
};

// Adds a sort type to all instance of TableSort
// 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

TableSort.prototype.addSortType = function (sType, fGetValueFromString, fCompareFunction, fGetRowValue) {
	this._sortTypeInfo[sType] = {
		type:				sType,
		getValueFromString:	fGetValueFromString || TableSort.idFunction,
		compare:			fCompareFunction || TableSort.basicCompare,
		getRowValue:		fGetRowValue
	};
};

// this removes the sort type from all instances of TableSort
TableSort.prototype.removeSortType = function (sType) {
	delete this._sortTypeInfo[sType];
};

TableSort.basicCompare = function compare(n1, n2) {
	if (n1.value < n2.value)
		return -1;
	if (n2.value < n1.value)
		return 1;
	return 0;
};

TableSort.idFunction = function (x) {
	return x;
};

TableSort.toUpperCase = function (s) {
	return s.toUpperCase();
};

TableSort.careersString = function (s) {
  var tempString = s.toUpperCase();

  return tempString.replace(/^\s+/, '');
}

//Removes all non-ascii characters (bewtween 64 & 90, 97 & 122 incl.)
//so that the crazy-bad production search that doesn't search normally
//will be mimiced here. In the improved version.
TableSort.toCrazyLetterOnlyCase = function (s) {
	var t= "";
	var z = s.length;
	for (var i = 0; i < z; i++){
		var c = s.charCodeAt(i);
		if ((c > 47 && c < 58) || (c > 64 && c < 91) || (c > 96 && c < 123))
			t += s.charAt(i);
	}
	return t.toUpperCase();
};

//Makes strings with NA a super priority.
TableSort.NASearch = function (s) {
	if (s.indexOf("N/A") == 0)
		return " ";
	else return s;
};

TableSort.toDate = function (s) {
  var parts = s.split("/");
	var d = new Date(0);
  //year, month, day for parameters
  d.setFullYear(parts[2],parts[0],parts[1]);
  return d.valueOf();
};

TableSort.getNumber = function (s) {
  //remove commas, currency signs and asterisks before testing number
  s = s.replace(/[$*,%K]/g,"");
  if (isNaN(Number(s))) {
    s="-9999999";
  }

  return Number(s);
}

// add sort types
TableSort.prototype.addSortType("Number", TableSort.getNumber);
TableSort.prototype.addSortType("ExpenseRatio", TableSort.getNumber);
TableSort.prototype.addSortType("CaseInsensitiveString", TableSort.toUpperCase);
TableSort.prototype.addSortType("Date", TableSort.toDate);
TableSort.prototype.addSortType("DateDescend", TableSort.toDate);
TableSort.prototype.addSortType("String", TableSort.toUpperCase);
TableSort.prototype.addSortType("CareersString", TableSort.careersString);
TableSort.prototype.addSortType("Options", TableSort.toUpperCase);
//where we DON'T sort in the normal alphabetical manner! Hooray for diversity!
TableSort.prototype.addSortType("tSort", TableSort.toCrazyLetterOnlyCase);
TableSort.prototype.addSortType("na", TableSort.NASearch);
// None is a special case
