﻿/// <reference name="jquery-1.3.1.min.js"/>

$.fn.tablesort = function(option) {
  var table = this;
  return this.each(function() {
    $(this).find('th').each(function(col) {
      $(this).addClass('headercell');
      if ($(this).attr('rel') == 'sortnum') {
        $(this).click(function() { sort(this, col - 1, 'num') });
      }
      if ($(this).attr('rel') == 'sortstring') {
        $(this).click(function() { sort(this, col - 1, 'string') });
      }
      col++;

    });
    colorOdd();
  });

  function colorOdd() {
    var i = 0;
    $("*").removeClass('odd');
    $(table).find('tr').each(function() {
      if (i++ % 2 == 1)
        $(this).addClass('odd');
    });
  }


  function sort(el, c, type) {
    var rows = $(table).find("tbody > tr").get();
    rows.sort(function(a, b) {
      var keyA = $(a).children('td').eq(c).text().toUpperCase();
      var keyB = $(b).children('td').eq(c).text().toUpperCase();
      if (keyA < keyB) return -1;
      if (keyA > keyB) return 1;
      return 0;
    });

    $(table).find('td').removeClass('sortcell');
    $(table).find('td:nth-child(' + (c + 1) + ')').addClass('sortcell');

    $.each(rows, function(index, row) {
      $(table).children('tbody').append(row)
    });
    colorOdd();

  };

};
