//
//  scroller.js
//

var Scroller = Class.create({
  initialize: function (wrapper, plane, options) {
    this.wrapper = wrapper;
    this.plane = plane;
    this.options = Object.extend({
      speed: 0.4,
      framesPerSecond: 60.0
    }, options);
    this.updateGeometry();
    this.registerMouseEvents();
    this.startTimer();
  },
  
  registerMouseEvents: function () {
    Event.observe(this.plane, "mouseover", this.stopTimer.bind(this));
    Event.observe(this.plane, "mouseout", this.startTimer.bind(this));
  },
  
  updateGeometry: function () {
    this.startY = this.wrapper.getHeight();
    this.endY   = -this.plane.getHeight();
  },
  
  updatePlane: function () {
    var origin = parseFloat(this.plane.style.top);
    var step   = this._timeDelta() / 10.0;
    if (!origin) origin = 0.0;
    origin = origin - this.options.speed * step;
    if (origin < this.endY)
      origin = this.startY;
    this.plane.style.top = origin + "px";
  },
  
  shouldScrollPlane: function () {
    return this.plane.getHeight() > this.wrapper.getHeight();
  },
  
  _timeDelta: function () {
    var delta = new Date().getTime() - this.lastUpdate;
    this.lastDelta = this.lastDelta + 
      ((delta - this.lastDelta) * 0.9);
    this.lastUpdate = new Date().getTime();
    return this.lastDelta;
  },
  
  startTimer: function () {
    this.lastUpdate = new Date().getTime();
    this.lastDelta = 0.0;
    this.stopTimer();
    if (this.shouldScrollPlane()) {
      this.interval = setInterval(
        this.updatePlane.bind(this), 
        1000.0 / this.options.framesPerSecond);
    }
  },
  
  stopTimer: function () {
    if (this.interval)
      clearInterval(this.interval);
  }
});

Event.observe(window, "load", function () {
  $$("div.scroller").each(function (element) {
    new Scroller(element, element.down("div.plane"));
  });
});
