event.add(window, "load", init_sort, false);

function init_sort() {
    // Find all tables with class sort_me and make them sortable
    nodeList_table = document.getElementsByTagName("table");
    for (i_table = 0; i_table < nodeList_table.length; i_table++)
    {
        cur_table = nodeList_table[i_table];
        if (cur_table.className.indexOf("sort_me") != -1) 
				{
            make_sortable(cur_table);
        }
    }
}

function make_sortable(table)
{
    if (table.rows && table.rows.length > 0)
    {
        var first_row = table.rows[0];
    }
    if (!first_row)
    {
   	 return;
   	}
    
    // We have a first row: assume it's the header, and make its contents clickable links
    for (var i = 0; i < first_row.cells.length; i++)
    {
        cur_cell = first_row.cells[i];
        value = cur_cell.innerHTML;

        cur_cell.innerHTML = '<a href="#" onclick="sort(this, ' + i + '); return false;">' + value + '<span class="sortarrow" style="visibility: hidden;"></span></a>';
    }
}

// Zero padding
function pad0(string, newlength)
{
  var pad = "";
  var len = newlength - string.length;
  for (i = 0; i < len; i++)
  {
    pad += "0";
  }
  return pad + string;
}

function format_data(item)
{
	sort_value = item.toLowerCase();

	// Convert date to YYYYMMDD format for sort comparison purposes.
  // If the item matches a date pattern (M/D/Y)
	if(item.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/))
	{
		// Find where are the slashes are.
		slash_count = 0;
		from_index = new Array();
		from_index[0] = item.indexOf("\/");
		while(from_index[slash_count] != -1)
		{
			slash_count++;
			from_index[slash_count] = item.indexOf("\/", from_index[slash_count - 1] + 1);
		}
	
		// Extract the numbers from the slashes.
		month = pad0(item.substr(0, from_index[0]), 2);
		day = pad0(item.substr(from_index[0] + 1, from_index[1] - from_index[0] - 1), 2);
		year = item.substr(from_index[1] + 1);
		
		// Two digit years less than 50 are treated as 20XX.
		// Greater than 50 are treated as 19XX.
		if(year.length == 2)
		{
			if(year < 50)
			{
				year = "20" + year;
			}
			else
			{
				year = "19" + year;
			}
		}
		sort_value = year + month + day;
	}
	
	// If the item matches a Percent patten (contains a percent sign)
  if (item.match(/%/))
  {
   // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
   sort_value = item.replace(/[^0-9.-]/g,'');
   sort_value = parseFloat(sortValue);
  }

  // If item starts with a "(" and ends with a ")" then remove them and put a negative sign in front
  if (item.substr(0,1) == "(" & item.substr(item.length - 1,1) == ")")
  {
   item = "-" + item.substr(1, item.length - 2);
  }
  
	// If the item matches a numeric pattern
	if (item.match(/(\d*,\d*$)|(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/))
	{
		// Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
		sort_value = item.replace(/[^0-9.-]/g,'');
		if(isNaN(sort_value))
		{
			sort_value = 0;
		}
		else
		{
			sort_value = parseFloat(sort_value);
		}
	}
	return sort_value;
}

function sort_compare (curr_value, next_value, direction)
{
 // Since the elements of this array are actually arrays themselves, just sort
 // on the first element which contiains the value, not the second which contains
 // the original row position
	if(direction == "d")
	{
		dir = -1;
	}
	else
	{
		dir = 1;
	}
	
  if (curr_value == next_value) return 0;
  if (curr_value < next_value) return dir * -1;
  if (curr_value > next_value) return dir * 1;
}



function sort_by_column(table, col_num, direction)
{
	return table.sort(function(a,b) { return sort_compare(a[col_num], b[col_num], direction);});
}

function sort(el, sort_column)
{
	direction = el.getAttribute("direction");
	siblings = el.parentNode.parentNode.cells;
	
	// Clicking the column header of an unsorted column defualts to descending.
	if(el.lastChild.style.visibility == "hidden")
	{
		direction = "d";
		el.setAttribute("direction", "d");
	}
	
	if (direction == "a")
	{
			arrow = '&nbsp;&uarr;';
			el.setAttribute("direction", "d");
	}
	else
	{
			arrow = '&nbsp;&darr;';
			el.setAttribute("direction", "a");
	}
	
	direction = el.getAttribute("direction");
	// Delete any other arrows there may be showing
	
	for(i = 0; i < siblings.length; i++)
	{
		siblings[i].firstChild.lastChild.style.visibility = "hidden";
	}
	el.lastChild.style.visibility = "visible";
	el.lastChild.innerHTML = arrow;
				
	// Traverse back up until we find which table to sort.
	while(el.tagName.indexOf("TABLE") == -1)
	{
		el = el.offsetParent;
	}
	
	table = el;

	// How many rows?
	num_rows = table.rows.length;

	// How many columns?
	num_cols = table.rows[0].cells.length;
	
	// Create the 2d array to hold the table data.
	// Do we want to remove the header row from our data?
	if(table.tHead)
	{
		skip_header = 1;
	}
	else
	{
		skip_header = 0;
	}
	
	array_table = new Array(num_rows);
	for(i = 0; i < num_rows - skip_header; i++)
	{
		array_table[i] = new Array(num_cols + 1);
		for(j = 0; j < num_cols; j++)
		{
			array_table[i][j] = format_data(table.rows[i + skip_header].cells[j].innerHTML);
		}
		// Add an extra column which contains the row number.
		// We will be using this for reference after the column-sort.
		array_table[i][num_cols] = i;
	}
	sorted_array_table = sort_by_column(array_table, sort_column, direction);
	
	new_positions = new Array();
	for(i = 0; i < num_rows - skip_header; i++)
	{
		new_positions[i] = sorted_array_table[i][num_cols];
	}
	//swap_rows(table, new_positions, num_rows, skip_header);
	
	cloned_table_rows = new Array();

	for(i = 0; i < num_rows - skip_header; i++)
	{
		cloned_table_rows[i] = document.createElement("tr");
		cloned_table_rows[i] = table.rows[i + skip_header].cloneNode(true);
	}
	
	for(i = 0; i < num_rows - skip_header; i++)
	{
		table.rows[i + skip_header].parentNode.replaceChild(cloned_table_rows[new_positions[i]], table.rows[i + skip_header]);
	}
	stripe_class.stripe();
}
