$.fn.alternateRowColors = function() {
  $('tbody tr:odd', this).removeClass('even').addClass('odd');
  $('tbody tr:even', this).removeClass('odd').addClass('even');
  return this;
};


$(document).ready(function() {
  $('table.striped').each(function() {
    $(this).bind('stripe', function() {
      var rowIndex = 0;
      $('tbody tr:not(.filtered)', this).each(function(index) {
        if ($('th',this).length) {
          $(this).addClass('subhead');
          rowIndex = -1;
        } else {
          if (rowIndex % 2 == 0) {
            $(this).removeClass('odd').addClass('even');
          }
          else {
            $(this).removeClass('even').addClass('odd');
          }
        };
        rowIndex++;
      });
    });
    $(this).trigger('stripe');
  });
});

/***************************************
   =FILTERING
-------------------------------------- */

$(document).ready(function() {
  $('table.filterable').each(function() {
    var $table = $(this);

    $table.find('th').each(function (column) {
      if ($(this).is('.filter-column')) {
        var $filters = $('<div class="filters"><h3 class="headline">Click below to filter by ' + $(this).text() + '.</h3></div>');
        var keywords = {};

        $table.find('tbody tr td').filter(':nth-child(' + (column + 1) + ')').each(function() {
          keywords[$(this).text()] = $(this).text();
        });

        $('<div class="filter">All</div>').click(function() {
          $table.find('tbody tr').removeClass('filtered').not('.collapsed').show();
          $(this).addClass('active').siblings().removeClass('active');
          $table.trigger('stripe');
        }).addClass('clickable active').appendTo($filters);

        $.each(keywords, function (index, keyword) {
          $('<div class="filter"></div>').text(keyword).bind('click', {'keyword': keyword}, function(event) {
            $table.find('tbody tr').each(function() {
              if ($('td', this).filter(':nth-child(' + (column + 1) + ')').text() == event.data['keyword']) {
                $(this).removeClass('filtered').not('.collapsed').show();
              }
              else if ($('th',this).length == 0) {
                $(this).addClass('filtered').hide();
              }
            });

            $(this).addClass('active').siblings().removeClass('active');
            $table.trigger('stripe');
          }).addClass('clickable').appendTo($filters);

        });
        $filters.insertBefore($table);
      }
    });
  });
});

