(function($){
  $.fn.Items = function(left, right){
    var page  = 0;
    var index = 0;
    var items = [];
    
    var element = $(this);
    left    = $(left);
    right   = $(right);
    
    var toggleLoading = function(on){
      element.toggleClass('loading', on);
    }
    
    var toggleLeft = function(on){
      left.toggle(on);
    }
    
    var toggleRight = function(on){
      right.toggle(on);
    }
    
    var toggleFooter = function(on){
      element.find('.footer').toggle(on);
    }
    
    var toggleEmpty = function(on){
      if(on){
        element.find('.title').empty();
        element.find('.body').empty();
        element.find('.link').empty();
        toggleFooter(false);
        element.find('.empty').show();
      } else {
        element.find('.empty').hide();
      }
    }
    
    var updateItem = function(attrs){
      var title = element.find('.title');
      title.html(attrs.title);
      title.attr('title', attrs.title);
      if(attrs.type == 'image'){
        var img = element.find('.body').empty().append("<img src='" + attrs.src + "' />");
        if(attrs.link)
          img.wrapInner("<a href='" + attrs.link + "'></a>");
      } else if (attrs.type == 'video') {
        element.find('.body').empty().flash(
          {
            src:                attrs.embed.swf,
            width:              "100%",
            height:             300,
            allowScriptAccess:  "never",
            allowFullScreen:    true,
            flashvars:          attrs.embed.vars
          }, {
            version: "9.0.0"
          }
        );
      }
      element.find('.footer').html(attrs.caption);
      element.find('.link').empty();
      if(attrs.link){
        element.find('.footer').wrapInner("<a href='" + attrs.link + "'></a>");
        element.find('.link').html("<a href='" + attrs.link + "'>Link</a>");
      }
    }
    
    var watchItem = function(ind){
      var item = items[index];
      if(!item) return;
      toggleEmpty(false);
      toggleFooter(true);
      updateItem(item);
    }
    
    element.loadItems = function(data){
      toggleLoading(false);
      if(data.length > 0){
        items = items.concat(data);
        toggleRight(true);
      }
      watchItem(0);
    }
    
    element.nextItem = function(){
      if((index + 2) == items.length) {
        toggleRight(false);
      }
      
      watchItem(++index);
      element.trigger('items:next');
      toggleLeft(true);
    }
    
    element.previousItem = function(){
      if(index == 0) return;
      
      watchItem(--index);
      element.trigger('items:previous');
      toggleRight(true);
      
      if(index == 0) toggleLeft(false);
    }
    
    left.click(function(){
      element.previousItem();
      return false;
    });
    right.click(function(){
      element.nextItem();
      return false;
    });
    
    toggleLeft(false);
    toggleRight(false);
    toggleFooter(false);
    
    return element;
  };
})(jQuery)
