var Scroller = Class.create({
  initialize: function(container, items, options) {
    this.container = $(container);
    this.container.setStyle({position: 'relative'});
    this.container.cleanWhitespace();
    this.item_selector = items;
    this.items = this.container.select(items).collect(function(e) {
      e.getTotalWidth(); // Precalc total width
      return new Scroller.Item(e, container);
    });
    this.options = $H({
      delay: 40,
      distance: 2
    }).merge(options || {});
    this.last_move = 0
    this.first_item = this.container.down(items);

    new PeriodicalExecuter(this.move.bind(this), this.options.get('delay') / 1000)
  },

  move: function() {
    this.last_move += this.options.get('distance');
    this.items.each((function(e) {
      e.move(this.options.get('distance'))
    }).bind(this));

    if(this.last_move >= this.first_item.getTotalWidth()) {
      this.container.appendChild(this.first_item);
      this.items.each((function(e) {
        e.move(-1 * this.first_item.getTotalWidth());
      }).bind(this));
      this.first_item = this.container.down(this.item_selector);
      this.last_move = 0;
    }
  }
});

Scroller.Item = Class.create({
  initialize: function(item, container) {
    this.item = item;
    this.container = container;
    this.item.setStyle({position: 'relative'});
  },

  move: function(distance) {
    var existing = parseInt(this.item.getStyle('left'));
    if(isNaN(existing)) existing = 0;
    this.item.setStyle({left: existing + -1 * distance + 'px'})
  }
});

Element.addMethods({
  getTotalWidth: function(element) {
    if(element.totalWidth) return element.totalWidth;
    element.totalWidth = element.getWidth();
    ['margin-left', 'margin-right'].each(function(s) {
      var amt = parseInt(element.getStyle(s));
      if(!isNaN(amt)) element.totalWidth += amt;
    });
    return element.totalWidth;
  }
});
