var tableSort = Array();

function reorder_table_by_data(id, rownum)
{
	rowArray = [];
	
	var iTable = $(id);
	var iBody = $(id).getElementsByTagName('tbody')[0];
	var iRows = iBody.rows;
	
	for(r = 0; r < iRows.length; r ++)
	{
		k = iRows.item(r).cells.item(rownum).textContent;
		
		rowArray.push([k, iRows.item(r)]);
		iRows.item(r).parentNode.removeChild(iRows.item(r));
		r --;
	}
	
	rowArray.sort();
	
	// if we previously sorted by this row then reverse direction
	if(iTable.sorted)
	{
		if(iTable.sorted.rownum == rownum)
		{
			if(iTable.sorted.direction == false)
			{
				rowArray.reverse();
			}
			iTable.sorted.direction = !iTable.sorted.direction;
		} else {
			iTable.sorted.rownum 	= rownum;
			iTable.sorted.direction	= false;
		}
	} else {
		iTable.sorted = {
			done: 	true,
			rownum:	rownum,
			direction:	false
		}; 
	}
	
		
	for(o = 0; o < rowArray.length; o ++)
	{
	    r = iBody.appendChild(rowArray[o][1]);
	}
	
	iTable.highlight_rows();
	
}

table_methods = {
	make_sortable: function(element)
	{
		iHead = element.getElementsByTagName('thead');
		iRows = iHead[0].rows[0].getElementsByTagName('td');
		
		for(i = 0; i < iRows.length; i++)
		{
			iRows[i].setAttribute('onclick', 'reorder_table_by_data("' + element.id + '", ' + i + ');');	
		
		}
	},
	
	highlight_rows: function(element)
	{
		iBody = element.getElementsByTagName('tbody')[0];
		iRows = iBody.rows;
		
		for(r = 0; r < iRows.length; r++)
		{
			iRows[r].className = 'highlight' + (r%2);
		}	
		
		return true;
	},
	
	table_format: function(element)
	{
		element.highlight_rows();
		element.make_sortable();
	},
	
	sortByRow: function(element, rownum)
	{
		rowArray = [];
		
		var iTable = element;
		var iBody = element.getElementsByTagName('tbody')[0];
		var iRows = iBody.rows;
		
		for(r = 0; r < iRows.length; r ++)
		{
			k = iRows.item(r).cells.item(rownum).textContent;
			
			rowArray.push([k, iRows.item(r)]);
			iRows.item(r).parentNode.removeChild(iRows.item(r));
			r --;
		}
		
		rowArray.sort();
		
		// if we previously sorted by this row then reverse direction
		if(iTable.sorted)
		{
			if(iTable.sorted.rownum == rownum)
			{
				if(iTable.sorted.direction == false)
				{
					rowArray.reverse();
				}
				iTable.sorted.direction = !iTable.sorted.direction;
			} else {
				iTable.sorted.rownum 	= rownum;
				iTable.sorted.direction	= false;
			}
		} else {
			iTable.sorted = {
				done: 	true,
				rownum:	rownum,
				direction:	false
			}; 
		}
		
			
		for(o = 0; o < rowArray.length; o ++)
		{
		    r = iBody.appendChild(rowArray[o][1]);
		}
		
		iTable.highlight_rows();
			
	
	}
	
}


Element.addMethods(table_methods);

