/*
 * Fetches/shows a by-state list of events.  Can be configured in terms of how
 * many events from each state to show (default is 1--the next one).
 */

(function($) {
  this.EventWidget = Widget.extend({
    defaultOptions: {
      listSize: 1       // How many events to show per state
    },
    events: {},
    selectedState: null,
    
    // Helper to fetch events in a by-state listing
    getEvents: function(listSize) {
      return sjson('/events/services/getStateEvents', {listSize: listSize});
    },
    
    // Constructor--fetch records and set selected value
    init: function(container, options) {
      this.setContainer(container);
      this.setOptions(options);
      
      this.events = this.getEvents(this.options.listSize);
    },
    
    // Set the currently selected state
    setState: function(state) {
      this.selectedState = state;
      this.render();
    },
    
    // Renderer--draw our widget into our container
    render: function() {
      this.container.empty();
      var events = this.events[this.selectedState];
      
      if (events instanceof Array) {
        for (var i = 0; i < events.length; ++i) {
          var e = events[i];
          
          // Diveders in case there are several
          if (i > 0) { this.container.append(document.createElement('hr')); }
          
          // Title
          this.container.append($('<h2><a href="/events/detail/' + e.id + '">'+ e.name + '</a></h2><br />'));
          this.container.append($('<p><strong>Starts:</strong> ' + parseIsoDate(e.start_date).toLocaleDateString() + '</p>'));
          this.container.append($('<p><strong>Location:</strong> ' + e.location + '</p>'));
          
        }
      } else {
        this.container.append(document.createTextNode("No upcoming events in that state..."));
      }
    }
  });
})(jQuery);
