jQuery(document).ready(function($) {
  // Table highlighting on hover.
  $('.stripe tr').mouseover(function() { $(this).addClass('over'); }).mouseout(function() { $(this).removeClass('over'); });

  // Open links with class of 'new_window' in a new window.
  $('a.new_window').click(function() {
    window.open($(this).attr('href'));
    return false;
  });

  // Hide date select submit button since we can do JS.
  $('#date_form input[type=submit]').hide();

  // Date select event handlers.
  $('#start_date, #end_date').change(function() {
    var days = days_between($('#start_date').val(), $('#end_date').val());
    if (days < 2) {
      $('#num_days').html('<span class="error">at least 2 nights</span>');
    } else {
      $('#num_days').html('' + days + ' nights');
      $('#date_form').submit();
    }
  });

  // Form validation.
  $('#date_form').submit(function() {
    if (days_between($('#start_date').val(), $('#end_date').val()) >= 2) {
      return true;
    }

    alert('Please pick a travel period of at least 2 nights');
    return ;
  });

  $('#origin').change(function() {
    $('#origin_form').submit();
  });

  // Make #rates table sortable.
  $.tablesorter.addParser({
    id: 'price_text',
    type: 'numeric',
    is: function(s) {
      return false;
    },
    format: function(s, table, cell) {
      // Remove currency code and any ','.
      if (s.match('N/A') || s.match('sold out')) {
        return 1.7976931348623157e+308; // theoretically largest number
      }
      return s.replace(/,/g, '').match(/\w+ (\d+)/)[1];
    }
  });
  $('#rates table').tablesorter({
    widgets: ['zebra'],
    sortList: [[3, 0]],
    headers: {
      1 : { sorter: 'price_text' },
      2 : { sorter: 'price_text' },
      3 : { sorter: 'price_text' },
      4 : { sorter: 'price_text' }
    }
  });

  // Travel period picker.
  $('#date_picker .selectable a').click(function() {

    // If there is no already clicked date, record this as the first clicked date.
    
    // Otherwise, if there is no already clicked date, record this as the second clicked date, and:
    //   1. if 2 days or more, redirect to page,
    //   2. if under 2 days, pop an appropriate message that trips should be at least 2 days long.

    return false;
  });

  function days_between(start, end) {
    var x = parseInt(start.replace(/-/g, ''));
    var y = parseInt(end.replace(/-/g, ''));
    return y - x;
  }
});