// Copyright (c) 2006 Peter Kovacs.

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

var SortableTable = {
  Version: "0.0.1",
  UpStyle: 'up',
  DownStyle: 'down',
  
  // sort the table based on the given column.  
  // ColumnIndex is required because Safari doesn't support cellIndex.
  // sortFunction is an optional iterator (function( value, index ))
  sortTable: function( table, column, columnIndex )
  {
    if( $(column).className == SortableTable.UpStyle )
    { $(column).className = SortableTable.DownStyle; }
    else
    { $(column).className = SortableTable.UpStyle; }

    // Remove all other classNames, since we only sort on one column per table.
    for( var i = 0; i < $(table).tHead.rows[0].cells.length; ++i )
    { 
      if( $(table).tHead.rows[0].cells[i] != $(column) && $(table).tHead.rows[0].cells[i].className != 'nosort' )
      { $(table).tHead.rows[0].cells[i].className = ''; }
    }


    if( $(table).tBodies.length == 0 ||
	$(table).tBodies[ 0 ].rows.length == 0 ||
	$(table).tBodies[ 0 ].rows[ 0 ].cells.length < columnIndex )
    { return; }

    // do we have an input field?
    var ItemInnerHTML = $(table).tBodies[0].rows[0].cells[ columnIndex ].innerHTML;
    if (ItemInnerHTML.match(/<input.*?/)) {
      var Item = "input";
    } else {	
      var Item = $(table).tBodies[0].rows[0].cells[ columnIndex ].innerHTML.stripTags().strip();
    }
    
    // you can't call sort directly on rows, so copy to an array.
    var Data = new Array();
    for( var i = 0; i < $(table).tBodies[0].rows.length; ++i )
    { Data[i] = $(table).tBodies[0].rows[i]; }
  
    if (Item.match(/^input/)) {
		  Data = Data.sortBy( function( value, index ) {
			  var this_item = value.cells[ columnIndex ].innerHTML;
			  var parsed_value = this_item.substring(this_item.lastIndexOf('value="') + 7); 
        var parsed_value = parsed_value.substring(0, (parsed_value.indexOf('"'))); 
			  var Val = parseFloat(parsed_value);
        return isNaN( Val ) ? 0 : Val;
      });
    } 
		else if (Item.match(/^[£$]/))
    { 
      Data = Data.sortBy( function( value, index ) { 
        return parseFloat( value.cells[ columnIndex ].innerHTML.stripTags().replace(/[^0-9.]/g,'') ); 
      } );
    }
    else if (Item.match(/^[\d\.]+$/))
    { 
      Data = Data.sortBy( function( value, index ) {
        var Val = parseFloat( value.cells[ columnIndex ].innerHTML.stripTags() );
        return isNaN( Val ) ? 0 : Val;
      });
    }
    // Handle columns that are actually dates.
    else if( Date.parse( Item ) )
    {
      Data = Data.sortBy( function( value, index ) {
	      return Date.parse( value.cells[ columnIndex ].innerHTML.stripTags() );
      });
    }
    // Default is case insensitive search.
    else
    { 
      Data = Data.sortBy( function( value, index ) {
        return value.cells[ columnIndex ].innerHTML.stripTags().toLowerCase();
      });
    }

    if( $(column).className == SortableTable.DownStyle )
    { Data.reverse(); }

    for ( var i=0; i < Data.length; i++) 
    { $(table).tBodies[0].appendChild( Data[i] ); }
  },
  
  load: function() {
    
    if( typeof Prototype == 'undefined' )
    { throw( "sortable requires Prototype JavaScript framework." ); }
    
    Event.observe( window, 'load', function() {
      // Find all tables with class sortable and make them sortable
      var tables = document.getElementsByClassName("sortable");
      tables.each( function( table ) 
      {
        if( table.tHead == undefined )
        { return; }

        for( var j = 0; j < table.tHead.rows[ 0 ].cells.length; ++j )
        {
          // nosort
          if (table.tHead.rows[0].cells[j].className == 'nosort') {
            continue;
          }
          
          var Cell = table.tHead.rows[ 0 ].cells[ j ];
          // Workaround for safari brokenness with cellIndex.
          Cell.columnIndex = j;
          Event.observe( Cell, 'click', function(e) {
	          var Obj = Event.element( e );
            SortableTable.sortTable( Event.findElement( e, 'table' ), Obj, Obj.columnIndex );
            StripeTable(table.id);
          } );
        }
      });
      
    } );

  }
}

SortableTable.load();




