/**
 * @fileoverview league.js
 * 
 * Repository for JavaScript functions used by the screen footy/league.php.
 * 
 * @author Chris 'Chopper' Vincent (29 July 2008)
 */

/**
 * Global Variables
 */
var sDir = "desc";	// Sort direction variable
var sCol = 0;		// Sort column variable

/**
 * Function called from the screen to sort the table by a particular column
 * @param [Object] theCell The column header to sort the table by
 * @param [Integer] colNum The index of the column to sort the table by
 */
function sortTable(theCell, colNum)
{	
	// Get the TBODY node
	var tBody = theCell.parentNode;
	while(tBody.nodeName!="TBODY")
	{
    	tBody = tBody.parentNode;
	}
	
	// Set the sort column variable
	sCol = colNum;
	for ( i=0, l=tBody.rows[0].cells.length; i<l; i++ )
	{
		if ( i != colNum )
		{
			tBody.rows[0].cells[i].className = "";
		}
	}
	
	// Setup array of the current table rows
	var tabOrd = new Array();
  	for ( i=0, l=tBody.rows.length; i<l; i++ )
  	{
    	tabOrd[i] = tBody.rows[i+1];
  	}
	
	// Set the sort order and set the cell class appropriately
	if ( theCell.className == "sortdown" )
	{
		// Currently sorted descending, change order to ascending
		sDir = "asc";
		theCell.className = "sortup";
	}
	else
	{
		// Currently sorted ascending, change order to descending
		sDir = "desc";
		theCell.className = "sortdown";
	}

	// Sort the array of rows and insert back into the table
  	tabOrd.sort(compRows);
  	for( i=0,r=1; r<tBody.rows.length; i++,r++ )
  	{
    	tBody.insertBefore(tabOrd[i], tBody.rows[r]);
  	} 
} 

/**
 * Custom sort function to compare the contents of two table cells.  At present,
 * the function will only sort integer values so will only work on points/weekly points
 * columns.
 * 
 * @param [Object] a First table row object to compare
 * @param [Object] b Second table row object to compare
 * @return [Integer] 0 if the appropriate cell in rows a and b are equal otherwise 1 or -1 
 * depending upon the sort order specified
 */
function compRows(a, b)
{
	// Extract the cell value from the two rows to be compared
	var aCellValue = parseInt(a.cells[sCol].innerHTML);
	var bCellValue = parseInt(b.cells[sCol].innerHTML);
	
	if( sDir == "desc" )
	{
    	if(aCellValue > bCellValue) return -1;
    	if(aCellValue < bCellValue) return 1;
  	} 
  	else 
  	{
    	if(aCellValue > bCellValue) return 1;
    	if(aCellValue < bCellValue) return -1;
  	}
  	return 0;
}