// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
var lastIndex;

function SortableGrid(parent, childName, colName){
	this.parent = parent;			// 'parent' node
	this.childName = childName;		// nodeName for 'children'
	this.colName = colName;			// nodeName for 'columns'

	// build array of 'child' nodes
	this.items = this.parent.getElementsByTagName(childName);
	this.N = this.items.length;

	// define methods
	this.get = function(i, col){
		var retval = null;
		var node = null;
		var sort;
	
		if(this.colName) {
			// sort by col'th element of i'th child
			node = this.items[i].getElementsByTagName(this.colName)[col];
		}
	
		if(null != (sort = node.getAttribute("sortValue"))) {
			// use 'sort' attribute if available
			retval = sort;
		} else if(node.childNodes.length > 0) {
			retval = node.firstChild.nodeValue;
		} else {
			return "";
		}
	
		if(parseFloat(retval) == retval) return parseFloat(retval);
		return retval;		
	}
	this.compare = function(val1, val2, desc){ return (desc) ? val1 > val2 : val1 < val2; }
	this.exchange = function(i, j){ this.parent.insertBefore(this.items[i], this.items[j]); }
	this.sort = function (col, desc){
		//sort them all
		for(var j=this.N-1; j > 0; j--) {
			for(var i=0; i < j; i++) {
				if(this.compare(this.get(i+1, col), this.get(i, col), desc)) {
					this.exchange(i+1, i);
				}
			}
		}
		
		//update the row bg colors.
		for (var i=0; i<this.N; i++){
			this.items[i].className = "sortableRow" + (i%2==0 ? "1" : "2");
		}
	}
}


function sortIt(id, index){
	//get the headers, and how it sorts and whether or not its the active column.
	var dataTable = document.getElementById(id);
	var headers = dataTable.getElementsByTagName("th");
	var desc = headers[index].getAttribute("desc");
	var active = headers[index].getAttribute("active");
	
	//if this is the active column, switch the way it sorts
	if (active=="true"){
		desc = (desc=="true" ? "false" : "true");
		headers[index].setAttribute("desc", desc);
	}
		
	//sort over body of table, using TR as the col and TD as the row.
	dataTable = dataTable.getElementsByTagName("TBODY")[0];
	myTable = new SortableGrid(dataTable, "tr", "td");
	myTable.sort(index, desc=="true");
	
	//this is how we handle the header display
	for (var i=0; i<headers.length; i++){
		if (headers[i].getAttribute("sortable")!=null){
			headers[i].setAttribute("active","false");
			removeClass(headers[i], "sortingAsc");
			removeClass(headers[i], "sortingDesc");
			if (i==index){ 
				headers[i].setAttribute("active","true"); 
				appendClass(headers[i], (desc=="true" ? 'sortingDesc' : 'sortingAsc'));
			}
		}
	}
}
