// Backport the String.trim() function if it's not available
if(typeof(String.prototype.trim) === "undefined") {
  String.prototype.trim = function() {
    return String(this).replace(/^\s+|\s+$/g, '');
  };
}

$(function() {
  // Add a parser for date column
  $.tablesorter.addParser({
    id: 'dates',
    is: function(s) {
      return false;
    },
    format: function(s) {
      return Date.parse(s.trim());
    },
    type: 'numeric'
  });
  
  // Add a parser for the tickets column
  $.tablesorter.addParser({
    id: 'tickets',
    is: function(s) {
      return false;
    },
    format: function(s) {
      return s.trim().toLowerCase().replace(/buy tickets/, 0)
        .replace(/coming soon/, 1)
        .replace(/sold out/, 2)
        .replace(/free/, 3)
    },
    type: 'numeric'
  });
  
  $('#eventsModule table').tablesorter({
    sortList: [[2, 0]],
    sortForce: [[2, 0]],
    headers: {
      2: {sorter: 'dates'},
      3: {sorter: 'tickets'},
    }
  });
  
  function alternate_rows() {
    $('#eventsModule table tbody tr').removeClass('row1 row2');
    $('#eventsModule table tbody tr:visible:even').addClass('row1');
    $('#eventsModule table tbody tr:visible:odd').addClass('row2');
  }
  
  // Reapply the alternating row colors
  $('#eventsModule table').bind('sortEnd', function() {
    alternate_rows();
  });
  
  //---------------------------------------------------------------------------
  // Disabled per SR-3727
  //
  // function filter_events(dateText) {
  //   
  //   // Parse the date, and format it with date.js
  //   var selected_date = Date.parse(dateText).toString('MMMM d, yyyy');
  //   
  //   $('td.eventDateCell').each(function() {
  //     if ($(this).text().trim() == selected_date) {
  //       $(this).parent().show();
  //     } else {
  //       $(this).parent().hide();
  //     }
  //   });
  //   
  //   alternate_rows();
  // }
  // 
  // // Establish the datepicker
  // $('#id_date').datepicker({
  //   showOn: 'button',
  //   buttonImage: '/projects/nationalgeographicevents/c/skins/default/assets/hidden.gif',
  //   buttonImageOnly: true,
  //   showButtonPanel: false,
  //   changeMonth: false,
  //   changeYear: false,
  //   nextText: '>>',
  //   prevText: '<<',
  //   dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  //   showAnim: 'fadeIn',
  //   minDate: 0,
  //   onSelect: function(dateText, inst) {
  //     filter_events(dateText);
  //   }
  // });
  // 
  // // override the date sort link
  // $('.eventDateCell').unbind();
  // $('.eventDateCell').click(function() {
  //   $('#id_date').datepicker("show");
  //   return false;
  // });
});
