var compfunc = new Array();

compfunc['alpha'] = function(a, b) {
	if (a > b) return 1;
	if (a < b) return -1;
	return 0;
}

compfunc['numeric'] = function(a, b) {
	return parseFloat(a) - parseFloat(b);
}

compfunc['date'] = function(a, b) {
	return new Date(Date.parse(a)).getTime() - new Date(Date.parse(b)).getTime();
}

function prepColumns(thead) {
	th = thead.getElementsByTagName('TH');
	for (var i = 0; i < th.length; i++)
		th[i].setAttribute('num', i);
}

function firstRealChild(parent) {
	var child = parent.firstChild;
	while (child && child.nodeType != 1) child = child.nextSibling;
	return child;
}

function nextRealSibling(el) {
	do el = el.nextSibling
	while (el && el.nodeType != 1);
	return el;
}

function assignTRValues(tbody, colnum) {
	var tr = firstRealChild(tbody);
	while (tr) {
		var td = firstRealChild(tr);
		var value;
		for(var i = 0; i < colnum; i++)
			td = nextRealSibling(td);
		tr.value = td.firstChild.data;
		tr = nextRealSibling(tr);
	}
}

function assignTROddEven(tbody) {
	var tr = firstRealChild(tbody);
	var odd = false;
	while (tr) {
		tr.className = odd ? '' : 'odd';
		odd = !odd;
		tr = nextRealSibling(tr);
	}
}

function sortTable(th) {
	var desc = th.desc;
	th.desc = !th.desc;
	
	//GET RID OF THIS LINE IF YOU EVER PLAN ON USING IT!!!
	th.title = (th.desc) ? 'sorted ASC, \nclick to sort DESC' : 'sorted DESC, \nclick to sort ASC';
	
	var table = th.parentNode.parentNode.parentNode;
	var thead = table.getElementsByTagName('THEAD')[0];
	var tbody = table.getElementsByTagName('TBODY')[0];

	// determine which column number they clicked by looking at the num attribute.  
	// If it's not set, go ahead and set it.
	colnum = th.getAttribute('num');
	if (!colnum) {
		prepColumns(thead);
		colnum = th.getAttribute('num');
	}
        
	var mode = table.getElementsByTagName('COL')[colnum].className;
	assignTRValues(tbody, colnum);
	sortChildren(tbody, 'value', mode, desc);
	assignTROddEven(tbody);
}

function sortChildren(parentElement, sortProperty, mode, desc){
	var children = [];
	var el = firstRealChild(parentElement);
	if (el) {
		var i = 0;
    
		while (el) {
			children[i] = new String(el[sortProperty]);
			children[i++].object = el;
			el = nextRealSibling(el);
		}
    
		children.sort(compfunc[mode]);
		if (desc) children.reverse();
		for(i = 0; i < children.length; i++)
			parentElement.appendChild(children[i].object);
	}
}