function sortTableClick()
{
	var t=sortedTables[$(this).parent().parent().parent().parent().attr("alt")];
	var c=$(this).parent().attr("alt");
	if(c==t.currentColumn) t.ascending=!t.ascending;
	else t.currentColumn=c;
	t.sortTable();
	t.rewriteTable();
}

function sortedTable(table)
{
	this.ascending=true;
	this.currentColumn=0;
	this.sortedColumns=[];
	this.sortedRows=[];
	this.tableReference=table;
	
	var tmp=$(table).children("thead").children("tr").children("th");
	$(table).attr("alt",sortedTables.length);
	for(var i=0;i<tmp.length;i++)
	{
		$(tmp[i]).attr("alt",i);
		this.sortedColumns.push($(tmp[i]).text());
		var m=$(tmp[i]).children("a");
		m.addClass("htext");
		m.click(sortTableClick);
	}
	var tmp=$(table).children("tbody").children("tr");
	for(var i=0;i<tmp.length;i++)
	{
		var row=[];
		var t=$(tmp[i]).children("td");
		for(var k=0;k<t.length;k++)
		{
			var bt=$(t[k]).text();
			if(bt.toLowerCase()!="view") row.push($(t[k]).text());
			else row.push($(t[k]).html());
		}
		this.sortedRows.push(row);
	}
	this.sortTable();
};
sortedTable.prototype.sortTable=function()
{
	currentColumn=this.currentColumn;
	this.sortedRows.sort(this.sortFunction);
	if(!this.ascending) this.sortedRows.reverse();
}
sortedTable.prototype.sortFunction=function(a,b)
{
	if(a[currentColumn]<b[currentColumn]) return -1;
	else if(a[currentColumn]>b[currentColumn]) return 1;
	else if(a[currentColumn]==b[currentColumn]) return 0;
}
sortedTable.prototype.rewriteTable=function()
{
	var tmp=$(this.tableReference).children("tbody").children("tr");
	var i=0;
	for(r in this.sortedRows)
	{
		var t=$(tmp[i++]).children("td");
		for(var k=0;k<t.length;k++)
		{
			$(t[k]).html(this.sortedRows[r][k]);
		}
	}
}

var currentColumn=0;
var sortedTables=new Array();
function init_sorter()
{
	$("table.sorted").each(function()
	{
		sortedTables.push(new sortedTable(this));
	});
}

$().ready(init_sorter);
