
/*----------------------------------------------------------------------------\
|                            Sortable Table 1.04                              |
|-----------------------------------------------------------------------------|
|                         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 - 2002 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.                         |
|-----------------------------------------------------------------------------|
| Created 2003-01-10 | All changes are in the log above. | Updated 2003-07-04 |
\----------------------------------------------------------------------------*/


function SortableTable(oTable, oSortTypes) {

	this.element = oTable;
	this.tHead = oTable.tHead;
	if(oTable.tBodies){
		this.tBody = oTable.tBodies[0];
	}else{
		alert("Error sorting table. Please check that your table is named correctly and doesn't share the name of another element." );
	}
	this.document = oTable.ownerDocument || oTable.document;

	this.sortColumn = null;
	this.descending = null;

	var oThis = this;
	this._headerOnclick = function (e) {
		oThis.headerOnclick(e);
	};

	// 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);
	}

	this.initHeader(oSortTypes || []);
	stripet(this);
}

function stripet(tableObj)
{
		var rows = tableObj.tBody.rows;
		var m = rows.length;
		for (var x = 0; x < m; x++) 
		{
			rows[x].className = x % 2 ? "even" : "odd";
		}
}
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 () {};

// 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) {
	var cells = this.tHead.rows[0].cells;
	var l = cells.length;
	var img, c;
	for (var i = 0; i < l; i++) {
		c = cells[i];
		img = this.document.createElement("IMG");
		img.src = "media/tabulator/blank.png";
		c.appendChild(img);
		if (oSortTypes[i] != null) {
			c._sortType = oSortTypes[i];
		}
		if (typeof c.addEventListener != "undefined")
			c.addEventListener("click", this._headerOnclick, false);
		else if (typeof c.attachEvent != "undefined")
			c.attachEvent("onclick", this._headerOnclick);
	}
	this.updateHeaderArrows();
};

// remove arrows and events
SortableTable.prototype.uninitHeader = function () {
	var cells = this.tHead.rows[0].cells;
	var l = cells.length;
	var c;
	for (var i = 0; i < l; i++) {
		c = cells[i];
		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);
	}
};

SortableTable.prototype.updateHeaderArrows = function () {
	var cells = this.tHead.rows[0].cells;
	var l = cells.length;
	var img;
	for (var i = 0; i < l; i++) {
		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 = 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) {
	var cell = this.tHead.rows[0].cells[nColumn];
	var val = cell._sortType;
	if (val != "")
		return val;
	return "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 (sSortType == null)
		sSortType = this.getSortType(nColumn);

	// exit if None
	if (sSortType == "None")
		return;

	if (bDescending == null) {
		if (this.sortColumn != nColumn)
			this.descending = true;
		else
			this.descending = !this.descending;
	}

	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 (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);
	stripet(this);
	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) {
	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) {
	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) {
	/*
	switch (sType) {
		case "Number":
			return parseFloat(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();
	}
	*/
	return sText;
};
function datetoint(date){
	newdate = "";
	newdate = date.split(/[^0-9]/);
	newdate = newdate.reverse();
	if(newdate[0].charAt(0) == "0"){
		newdate[0] = newdate[0].substr(1, newdate[0].length);
	}
	newdate = newdate.join('');
	//document.write(newdate + "\n");
	return parseInt(newdate);
}
function getseparator(date) {
	seperatorRegExp = /[^0-9]/;
	seperator = date.match(seperatorRegExp);
	return seperator;	
}
function parseDate(date){
	separator = getseparator(date);
	items = date.split(separator);
}
function isnumber(n){
	return !n.match(/[^0-9.]/);
}
function isnumeric(n){
	return !n.match(/[^0-9]/);
}
function isfilesize(n)
{
	var objRegExp = /\d{1,} (KB|MB|GB|bytes)/i;
	return objRegExp.test(n);
}

function isfiletype(n)
{
	var objRegExp = /.{1,} (Image|File|Folder)/i;
	return objRegExp.test(n);
}

function validDate( strValue ) {
	/************************************************
	DESCRIPTION: Validates that a string contains only
	valid dates with 2 digit month, 2 digit day,
	4 digit year. Date separator can be ., -, or /.
	Uses combination of regular expressions and
	string parsing to validate date.
	Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy
	
	PARAMETERS:
	strValue - String to be tested for validity
	
	RETURNS:
	True if valid, otherwise false.
	
	REMARKS:
	Avoids some of the limitations of the Date.parse()
	method such as the date separator character.
	*************************************************/
	
	var objRegExp = /^\d{1,2,4}(\-|\/|\.)\d{1,2}\1\d{2,4}$/
	//uk first, then us
	//check to see if in correct format
	if(!objRegExp.test(strValue))
		return false; //doesn't match pattern, bad date
	else{
		return true; //found in lookup table, good date
	}
}
SortableTable.prototype.getSortFunction = function (sType, nColumn) 
{
	// need to detect the data type so we can sort correctly
	//Date, DateTime, FileType, FileSize, $
	// String, CaseInsensitiveString, Number, Date, Currency, FileType, FileSize
	
	//Compare Strings
	if(sType == 'String') return compare_string;
	
	//Compare Strings Case Insensitive
	if(sType == 'CaseInsensitiveString') return compare_caseInsensitiveString;
	
	//Compare Numbers
	if(sType == 'Number') return compare_number;
	
	// Compare Dates
	if(sType == 'Date') return compare_date;
	
	// Compare Currencies
	// TODO
	
	// Compare File Types
	if(sType == 'FileType')	return compare_fileType;
	
	// Compare File Sizes
	if(sType == 'FileSize') return compare_fileSize;
	
	// if types aren't specified or aren't in the list above just try doing an auto sort
	
	return compare_default;

};

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;
};



function compare_default(n1, n2) 
{
	n1v = n1.value;
	n2v = n2.value;
	
	// check if both items are file sizes
	if(isfilesize(n1v) && isfilesize(n2v)) return compare_fileSize(n1, n2);
	
	// check if both items are file types
	if(isfiletype(n1v) && isfiletype(n2v)) return compare_fileType(n1, n2);
	
	// check if both items are numbers
	if(n1v.isnumber && n2v.isnumber) return compare_number(n1, n2);
	
	// check if both items are dates
	// TODO
	
	// check if both items are currencies
	// TODO
	
	// default to string sorting
	return compare_caseInsensitiveString(n1, n2);
	
};


// Data Type Comparisons

// sort strings
function compare_string(n1, n2)
{
	n1v = n1.value;
	n2v = n2.value;
	
	if (n1v < n2v){
		return -1;
	}
	
	if (n2v < n1v){
		
		return 1;
	}
	return 0;
}

// sort strings case insensitively
function compare_caseInsensitiveString(n1, n2)
{
	//return 1;
	n1v = n1.value.toLowerCase();
	
	n2v = n2.value.toLowerCase();
	
	if (n1v < n2v)
	{
		return -1;
	}
	
	if (n2v < n1v){
		
		return 1;
	}
	return 0;
}

// sort numbers
function compare_number(n1, n2)
{
	n1v = parseFloat(n1.value);
	n2v = parseFloat(n2.value);
	
	if (n1v < n2v){
		return -1;
	}
	
	if (n2v < n1v){
		
		return 1;
	}
	return 0;
}

// sort file sizes (B, KB, MB, GB)
function compare_fileSize(n1, n2)
{
	n1v = n1.value;
	n2v = n2.value;
	
	size = parseFloat(n1v.substr(0, n1v.indexOf(" ")));
	multiplier = n1v.substr(n1v.indexOf(" ") + 1, n1v.length - 1);
	if(multiplier == "KB") size = size * 1024;
	if(multiplier == "MB") size = size * 1024 * 1024;
	if(multiplier == "GB") size = size * 1024 * 1024 * 1024;
	n1v = size;
	
	size = parseFloat(n2v.substr(0, n2v.indexOf(" ")));
	multiplier = n2v.substr(n2v.indexOf(" ") + 1, n2v.length - 1);
	if(multiplier == "KB") size = size * 1024;
	if(multiplier == "MB") size = size * 1024 * 1024;
	if(multiplier == "GB") size = size * 1024 * 1024 * 1024;
	n2v = size;
	
	if (n1v < n2v){
		return -1;
	}
	
	if (n2v < n1v){
		
		return 1;
	}
	return 0;
}

// sort file types
function compare_fileType(n1, n2)
{
	n1v = n1.value;
	n2v = n2.value;
	
	// folders always come first when sorting by file type
	if(n1v.toLowerCase().indexOf("folder") >= 0 && n2v.toLowerCase().indexOf("folder") >= 0)
	{
		if (n1v.toLowerCase() < n2v.toLowerCase())
		{
			return 1;
		}
		if (n2v.toLowerCase() < n1v.toLowerCase())
		{
			
			return -1;
		}
		return 0;
	}
	
	if(n1v.toLowerCase().indexOf("folder") >= 0)
	{
		return -1;
	}
	if(n2v.toLowerCase().indexOf("folder") >= 0)
	{
		return 1;
	}
	
	if (n1v.toLowerCase() < n2v.toLowerCase())
	{
		return -1;
	}
	if (n2v.toLowerCase() < n1v.toLowerCase())
	{
		return 1;
	}
	return 0;
}


// sort dates
function compare_date(n1, n2)
{
	n1v = date_time_parse(n1.value);
	n2v = date_time_parse(n2.value);
	
	if (n1v < n2v){
		return -1;
	}
	
	if (n2v < n1v){
		
		return 1;
	}
	return 0;
}

// parses a date of the standard date/time format DD/MM/YYYY HH:MM AM
function date_time_parse(d)
{
	day 	= d.substr(0,2);
	month 	= d.substr(3,2);
	year 	= d.substr(6,4);
	hour 	= d.substr(11,2);
	minute 	= d.substr(14,2);
	ampm 	= d.substr(17,2);
	
	if(ampm == "PM") hour += 12;
	
	var dp = new Date(0);
	
	dp.setMinutes(minute);
	dp.setHours(hour);
	dp.setDate(day);
	dp.setMonth(month);
	dp.setFullYear(year);
	
	return dp.getTime();
}