// Maintains sort state and doles out comparator functions for that state.
var SortState = Class.create({
  // Changes the current sort field. If the new field is the same as the old one, the sort order will be reversed.
  changeSortField: function(newField) {
    if(! this._sortComparators[newField]) throw new Error("Invalid sort field");
    
    // Reverse the sort if we're selecting the same one
    if(newField == this._sortField) {
      this._sortDirections[newField] = ! this._sortDirections[newField];
    }
    
    this._sortField = newField;
  },
  // Returns a comparator function for the current sort order.
  getSortComparator: function() {
    return this._sortComparators[this._sortField];
  },
  // Returns true iff the sort order should be reversed.
  isSortReversed: function() {
    return !! this._sortDirections[this._sortField];
  },
  // Returns all of the possible sort fields
  getSortFields: function() {
    return Object.keys(this._sortComparators);
  },
  // Returns to the original state.
  reset: function() {
    this._sortField = null;
    this._sortDirections = {};
  },
  // Takes a hash of comparator functions keyed by field name.
  initialize: function(comparators) {
    this._sortComparators = comparators;
    this.reset();
  },
  
  _sortField: null, // current field name
  _sortDirections: null, // obj keyed by field. true entry = reverse sort.
  _sortComparators: null // hash of comparator functions keyed by field name
});

var TRIP_SORT_ORDERS = {
  price: function(tripA, tripB) {
    return tripA.price - tripB.price;
  },
  depart: function(tripA, tripB) {
    return minutesSinceMidnight(tripA.outbound.departure.time) - minutesSinceMidnight(tripB.outbound.departure.time);
  },
  arrive: function(tripA, tripB) {
    return minutesSinceMidnight(tripA.inbound.arrival.time) - minutesSinceMidnight(tripB.inbound.arrival.time);
  },
  duration: function(tripA, tripB) {
    return tripA.totalDuration - tripB.totalDuration;
  }
};