(function ($){
  $.fn.extend ({
    newsstackPlugin : function (options)
    {
      if (!$.event._newsstackCleanup) $.event._newsstackCleanup = [];


      options = $.extend( {
        },
        options );

      return this.each (function () {
        if (!this._newsstackController) {
          this._newsstackController = new NewsstackPlugin (this);
          $.event._newsstackCleanup[$.event.guid] = this._newsstackController;
          $.event._newsstackCleanup[$.event.guid++].init (options);
        }
      });
    },

    _newsstackDestroy : function ()
    {
      return _eachCall.call (this, 'cleanup');
    }
  });


  var _eachCall = function (f, a1, a2, a3)
  {
    return this.each (function () {
      if (this._newsstackController)
        this._newsstackController[f](a1, a2, a3);
    });
  };


  $(window).bind('unload', function() {
    var els = $.event._newsstackCleanup || [];
    for (var i in els) {
      $(els[i].ele)._newsstackDestroy();
    }
  });


  function NewsstackPlugin(ele)
  {
    this.ele = ele;
    this.$ele = $(this.ele);
  };
  $.extend(NewsstackPlugin.prototype, {
    bindToObj: function(fn) {
      var self = this;
      return function() {
        return fn.apply(self, arguments)
      };
    },

    init : function(s)
    {
      $("span.previous a", this.$ele).bind("click",this.bindToObj(this.previousClick));
      $("span.next a", this.$ele).bind("click",this.bindToObj(this.nextClick));
    },

    previousClick : function(evt) {
      evt.preventDefault();
      var $tgt = $(evt.target);
      if (! $tgt.is("li"))
        $tgt = $tgt.parents("li:first");
      
      var no = $tgt.attr("uid");
      no--;
      var max = $tgt.attr("max");
      
      if (parseInt(no) <= 0)
        no = parseInt(max);
      
      var $next = $tgt.siblings("li[uid="+no+"]");

      if ($next.length == 0)
        $next = $next = this.$ele.find("li:first");
      
      if ($next.length == 1)
        this.show($next);      
    },
    
    nextClick : function(evt) {
      evt.preventDefault();
      var $tgt = $(evt.target);
      if (! $tgt.is("li"))
        $tgt = $tgt.parents("li:first");
      
      var no = $tgt.attr("uid");
      no++;
      var max = $tgt.attr("max");
      
      if (parseInt(no) > parseInt(max))
        no = 1;
      
      var $next = $tgt.siblings("li[uid="+no+"]");

      if ($next.length == 0)
        $next = $next = this.$ele.find("li:first");
      
      if ($next.length == 1)
        this.show($next);      
    },
  
    show : function($ele) {
      $("li",this.$ele).hide();
      $ele.show();
    },

    cleanup : function()
    {
      $("span.previous a", this.$ele).unbind("click",this.bindToObj(this.previousClick));
      $("span.next a", this.$ele).unbind("click",this.bindToObj(this.nextClick));      
    }
  });
})(jQuery);

