/**
 * MagicRSS.
 * Usage:
 * $(selector).magicRss({
 *    url: rss feed url,
 *    items: items count,
 *    itemLength: an item length,
 *    itemTemplate: rss feed item template,
 *    wrapperTemplate: wrapper template    
 * });
 * 
 * @version $Id$
 */
(function($) {
  RssReader = function(el, options) {
    this.$el = $(el);
    
    // configurable {
    this.url = '';
    this.items = 3;
    this.itemLength = 100;
    this.itemTemplate = '';
    this.wrapperTemplate = '';
    // }
    
    $.extend(this, options);
  }
  
  RssReader.prototype = {
    read: function() {
      this.load();
    },
    
    processData: function(data) {
      var items = '';
      var _this = this;
      var count = 0;
      $('item', data).each(function() {
        if((count ++) >= _this.items)
          return false;
          
        items += _this._applyItemTemplate(this);
      });
      this.$el.html(this._applyWrapperTemplate(items));
    },
    
    _applyItemTemplate: function(data) {
      var $data = $(data);
      var template = $(this.itemTemplate).html();
      
      var date = $('pubDate', $data).text();
      var values = {
        'magic-rss-link': $('link', $data).text(),
        'magic-rss-title': $('title', $data).text(),
        'magic-rss-date': $.strftime('%d.%m.%Y %H:%M', new Date(date)),
        'magic-rss-description': $.trim($('description', $data).text()).substr(0, this.itemLength) + '...'
      }
      
      return this._applyValues(template, values);
    },
    
    _applyWrapperTemplate: function(items) {
      var template = $(this.wrapperTemplate).html();
      return this._applyValues(template, {
        'magic-rss-items': items
      });
    },
    
    _applyValues: function(template, values) {
      var splitted = template.split('%');
      for(var i = 1, l = splitted.length; i < l; i += 2) {
        if(splitted[i] == '') {
          splitted[i] = '%';
          continue;
        }
        
        var value = values[splitted[i]];
        if(value !== undefined) 
          splitted[i] = value;
        else {
          splitted[i - 1] += '%';
          splitted[i] += '%';
        }
      }
      return splitted.join('');
    },
    
    load: function() {
      var _this = this;
      $.get(this.url, function(data) {
        _this.processData(data);
      });
    }
  }
  
  $.fn.extend({
    magicRss: function(options) {
      this.each(function() {
        var reader = new RssReader(this, options);
        reader.read();
      });
    }
  });
})(jQuery);

