// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
var sortedTables = []
function initSorts() {
    // Find all tables with class sortable and make them sortable
    if (!document.getElementsByTagName) return;
    tbls = $A(document.getElementsByTagName("table"));
    tbls.findAll(function(t){ 
      return t.id && Element.hasClassName(t,'sortable');  
    }).each( function (table){
        var types = detectColumnTypes(table);
        var sorted = new SortableTable(table, types);
        sortedTables.push(sorted);
        
        // Store table sort in location hash
        sorted.onsort = function(){
          h = '#'+(sorted.element.id + "=" + sorted.descending + ":" + sorted.sortColumn);
          location.replace(h);
        };
        
        // Resort table
        var sort_params;
        if (sort_params = location.hash.match(/#(.+)=(.+):(.+)/)){
          if (sort_params[1] == table.id){
            desc = sort_params[2] == 'true';
            col = parseInt(sort_params[3]);
            sorted.sort(col,desc);
          }
        }
      });
}

function detectColumnTypes(table) {
  if (table.rows.length <= 1) return [] ;
  var types = [];
	var colCount = table.tHead.rows[0].cells.length;
	
	for( j=0; j < colCount; j++){
  	var itm = "";
	  if( Element.hasClassName(table.tHead.rows[0].cells[j],'unsorted') ){
	    types[j] = "None";
    } else {      
  	  for( i=1; i < table.rows.length && itm.match(/^\s*$/); i++){
    		itm = SortableTable.getInnerText(table.rows[i].cells[j]);
    		itm = itm.match(/^\s*(.*)\s*$/)[1];
    	}
      sortfn = "CaseInsensitiveString";
      if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d?\d?$/)) sortfn = "Date";
      if (itm.match(/^[\d\.\,]+$/)) sortfn = "Number";
      types[j] = sortfn;
    }
  }
  return types;
}

Event.observe(window, 'load', initSorts);