// takes a table and the last row of the header and makes each cell a link, that
// when clicked, sorts that column. The link has the class "sortlink", and the arrow
// image has the class "sortimg" . If a link or image with those classes already exists in
// the cell, the program uses that one instead
// inspired by http://www.workingwith.me.uk/standardista_table_sorting/
// Dependencies: jquery.yi.js

(function($){
// the sorttable sets the class of the table to fixPNG so transparent PNG's are OK
var upimg = "/images/up.png";
var dnimg = "/images/down.png";

$.fn.sorttable = function(){
  return this.addClass('fixPNG').each(function() {
    var table = this;
    if (!table|| !table.tHead || !table.tHead.rows || table.tHead.rows.length < 1) return; // simple paranoid argument checking
    var row = table.tHead.rows[this.tHead.rows.length-1].cells; // last row of header
    $.each (row, function(i){
      // find or create the link to sort the column
      var link = $(row[i]).find("a.sortlink");
      if (link.size() == 0){
        // have to create our own link
        link = $.A({className: "sortlink",href: "#"}); // todo: remove link; just make it clickable
        // move everything from the cell into the link, then add the link to the cell
        link.append(row[i].childNodes);
        $(row[i]).append(link);
      } // if
      // add the necessary information to the link
      link.click($.fn.sorttable.sort).attr('title','Click to sort');
      $.extend(link[0],{
        xTable: table,
        xCell: row[i],
        xCol: i
      });
      // find or create the image
      var img = $(row[i]).find("img.sortimg");
      if (img.size() > 0){
        table.xSortcol = i; // figure that this must be the column that was sorted on
        table.xSortdir = 1; // assume ascending; we should try to parse the image source but I'm lazy
      }else{
        img = $.IMG ({className: "sortimg",src: upimg}).appendTo ($(row[i])).hide();
      } // if
    }); // each row 
  }); // each table
}; // sorttable
    

$.fn.sorttable.sort = function(){
  var table = this.xTable;
  // copy the list of rows into a real array
  if (!table.xRows){
    table.xRows = [];
    for (var i = 0, r = table.tBodies[0].rows, l = r.length; i < l; ++i) table.xRows.push(r[i]);
  }
  // why [].slice.call(table.tBodies[0].rows, 0) doesn't work is beyond me
  if (table.xSortcol == this.xCol){
    // reverse direction
    table.xSortdir *= -1;
    table.xRows.reverse();
  }else{
    table.xSortcol = this.xCol;
    table.xSortdir = 1; // ascending
    // this just uses case-insensitive string sorting. If you want more sophisticated sorting,
    // see http://kryogenix.org/code/browser/sorttable/
    table.xRows.sort (function (a, b){
      var atext = $(a.cells[table.xSortcol]).text().toLowerCase();
      var btext = $(b.cells[table.xSortcol]).text().toLowerCase();
      if (atext == btext) return 0;
      if (atext < btext) return -1;
      return 1;
    });
  }
  $(table.tBodies[0]).append (table.xRows); // put them back
  // re-stripe if needed
  $(table).filter('.made_stripe').stripe(2);
  // set the indicators
  $(table).find("img.sortimg").hide();
  $(this.xCell).find("img.sortimg").imgsrc(table.xSortdir > 0 ? upimg : dnimg).show();
  return false; // don't try to use the link
} // sort
    
// simple table striping; assigns classes 'stripe0', 'stripe1', 'stripe2', etc. to successive rows of a table body,
// mod n
// when restriping, if you go to a lower stripe number, it will mess up.
// also adds a class 'stripehover' when the mouse is on it
// based on http://15daysofjquery.com/table-striping-made-easy/5/
$.fn.stripe = function(n){
  if (!n || n < 1) n = 2;
  return this.each( function(){
    $.each(this.tBodies, function(){
      $.each(this.rows, function (i) {
        for (var j = 0; j < n; ++j) $(this).removeClass ("stripe"+j);
        $(this).addClass ("stripe"+(i%n)).hover(
          function() {$(this).addClass("stripehover");},
          function() {$(this).removeClass("stripehover");});
        }); // each row
    }); // each tBody
  }); // each table
}; // stripe   

// define stripe_2, stripe_3 etc.
$.each([2,3,4,5], function(i,e){$.fn.stripe[e+'']=e});

$.fn.imgsrc = function (src){
  return this.each( function(){this.src = src;});
}; // imgsrc

})(jQuery);

