/**
 * This object acts as a helper for the results shown on the course dates
 * page. The constructor requires an object termed "eventMeta", which is
 * a mapping from eventId -> filterable properties. This object simply cycles
 * through the eventMeta array, identify whether the row in question is within
 * the result set, and then shows/hides the row as appropriate.
 * @todo currently hard coded to work on one page. If we need to reuse this,
 * turn it into a jQuery plugin.
 *
 * @version $Revision: 194 $ / $Date: 2009-09-23 10:31:21 +0100 (Wed, 23 Sep 2009) $
 */
DateFilterer = function(eventMeta) {
   this.activeFilters = {};
   this.filteredEvents = {};
   this.eventMeta = eventMeta;


   /**
    * toggleFilter()
    *
    * @param filterName {string}
    * @param value {string}
    *
    * @return Boolean if the filter is "activated" or false if "deactivated"
    */
   this.toggleFilter = function(filterName, value) {
      
      // if a filter already exists with this name and value, then remove it
      if (this.activeFilters[filterName] && this.activeFilters[filterName] == value) {
         this.activeFilters[filterName] = false;
         return false;
      }
      
      // date greater than/less than filters are mutually exclusive
      if (filterName == 'datelt' && this.activeFilters.dategt) {
         delete this.activeFilters.dategt;
         return false;
      }

      if (filterName == 'dategt' && this.activeFilters.datelt) {
         delete this.activeFilters.datelt;
         return false;
      }

      this.activeFilters[filterName] = value;
      return true;
   }
   
   /**
    * Run through the eventMeta array, and test each entry against the filters
    * @return array of events which satisfy current filters.
    */
   this.execute = function() {
      // wipe the filtered events
      filteredEvents = {};

      var now = (new Date().getTime())/1000;
      for (eventId in this.eventMeta) {
         var eventMeta = this.eventMeta[eventId];
         for (filterName in this.activeFilters) {
            var ok = true;
            
            if (this.activeFilters.datelt && (now + this.activeFilters.datelt) < eventMeta.d) {               
               ok = false;
            }
            
            if (ok && this.activeFilters.dategt && (now + this.activeFilters.dategt) > eventMeta.d) {
               ok = false;
            }            
            
            if (ok && this.activeFilters.region && this.activeFilters.region != eventMeta.r) {
               ok = false;
            }
            
            if (ok) {
               filteredEvents[eventId] = true;
            }
            
         }
      }
      this.filteredEvents = filteredEvents;
   }
}
