/*
*
* Copyright (c) 2009 Ikon srl, by Marco Venuti
* 
*/

(function($) {
  /*
  * A basic news vertical scroller.
  *
  * @param    delay      Delay (in milliseconds) between iterations. Default 4 seconds (5000ms)
  * @example  $(".news_scroller").newsScroller(5000);
  *
  * per poter calcolare correttamente l'altezza dell'elemto da scrollare
  * usare per gli items:  clear: both; float: left;
  *
  */
  $.fn.newsScroller = function(minItems, delay, speed) {
    minItems = minItems || 1 << 30;  // if less than minItems don't start the animation
    delay = delay || 5000;
    speed = speed || 250;
    initScroller = function(el) {
      stopScroller(el);
      el.items = $('>*', el);
      el.items.show();
      if (el.items.length <= minItems)
        return;
      startScroller(el);
    };
    startScroller = function(el) {
      el.scrollitemfn = setInterval(function() { this.doScrollItem(el) }, delay)
    };
    stopScroller = function(el) {
      clearInterval(el.scrollitemfn);
    };
    pauseScroller = function(el) {
      el.pause = true;
    };
    resumeScroller = function(el) {
      el.pause = false;
    };
    doScrollItem = function(el) {
      if (el.pause || el.pauseAnim || el.items.length <= minItems)
        return;
      // pause until animation has finished
      el.pauseAnim = true;
      el.items = $(el.items.selector, el.items.context);
      var itm1 = $(el.items[0]);
      var itm2 = itm1.clone(true);
      itm1.animate({ marginTop: -itm1.height() + 'px' }, speed, function() {
        itm1.remove();
        $(el.items.context).append(itm2);
        el.pauseAnim = false;
      });
    };
    //
    this.each(function() {
      initScroller(this);
      $(this).hover(function() { pauseScroller(this); }, function() { resumeScroller(this); });
    });
    return this;
  };

})(jQuery);

