(function($) {

  $.fn.prefix_item_summary = function(c, s) {
    switch(c) {
      case 'ego-rocks': return "EGO Rocks: " + s;
      case 'ego-jam': return "EGO Jam: " + s;
      case 'ego-boost': return "EGO Boost: " + s;
      case 'super-ego': return "Super EGO: " + s;
      case 'big-ego': return "Big EGO: " + s;
      case 'alter-ego': return "Alter EGO: " + s;
      default: return s;
    }
  }

  $.fn.calendar = function(o){
    var s = {
      loading_text: null,
      list: 'event_list',
      calendar: 'ego',
      view: 'list',
      query: null,
      format: null
    };

    if(o) $.extend(s, o);
    return this.each(function(){
      var list = $('<ul class="'+s.list+'">').appendTo(this);
      var loading = $('<p class="loading">'+s.loading_text+'</p>');
      if (s.loading_text) $(this).append(loading);

      var url = 'http://' + location.host + '/calendars/' + s.calendar + '.json?view=' + s.view;
      if (s.query) url += '&' + s.query;

      $.getJSON(url, function(data){
        if (s.format) {
          if (s.loading_text) loading.remove();
          s.format($, list, data);
       } else {
          if (s.loading_text) loading.remove();
          $.each(data.events, function(i,item){
            var location_url = item.url && item.url.match(/http:\/\/maps\.google\./) ? item.url : null;
            var information_url = item.url && !location_url ? item.url : null;
            var summary = '<h4 class="event_summary">' + (information_url ? '<a href="' + information_url + '" target="_blank">' + $.fn.prefix_item_summary(item.calendar, item.summary) + '</a>' : $.fn.prefix_item_summary(item.calendar, item.summary)) + '</h4>';
            var date = '<p class="event_date_and_time">' + item.date_and_time + '</p>';
            var description = '<p class="event_description">' + (item.description ? item.description : '') + '</p>';
            var location = '<p class="event_location">' + (item.location ? (location_url ? '<a href="' + location_url + '" target="_blank">' + item.location + '</a>' : item.location) : '') +'</p>';
            list.append('<li>' + summary + date + location + description + '</li>');

            list.children('li:first').addClass('event_first');
            list.children('li:odd').addClass('event_even');
            list.children('li:even').addClass('event_odd');
          });
        }
      });
    });
  };

})(jQuery);