var tableSort = Array();

function reorder_table_by_titles(id, rownum)
{
	var rowArray = [];

	iBody = $(id).getElementsByTagName('tbody')[0];
	iRows = iBody.rows;

	for(r = 0; r < iRows.length; r ++)
	{
		rowArray.push([iRows.item(r).cells.item(rownum).title, 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(tableSort[id])
	{
		if(tableSort[id]['rownum'] == rownum)
		{
			if(tableSort[id]['direction'] == false)
			{
				rowArray.reverse();
			}
			tableSort[id]['direction'] = !tableSort[id]['direction'];
		} else {
			tableSort[id]['rownum'] = rownum;
			tableSort[id]['direction'] = false;
		}
	} else {
		tableSort[id] = new Array();
		tableSort[id]['rownum'] = rownum;
		tableSort[id]['direction'] = false;
	}


	for(o = 0; o < rowArray.length; o ++)
	{
	    r = iBody.appendChild(rowArray[o][1]);
	}

	$(id).highlight_rows();

}

var 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_titles("' + 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();
	}
}


Element.addMethods(table_methods);

