var ScrollAnimator = Class.create();
ScrollAnimator.prototype = {
  initialize: function(options)
  {
      this.setOptions(options);
      if (this.options.element && this.options.element.style && this.options.element.style['left'])
      {
          this.start();
      }
  },

  setOptions: function(options) {
    this.options = {
        element:  null,
        elementid: null,
        fps: 35,
        animTimeMS: 1000,
        deltaX: 200,
        button: null
	};

	Object.extend(this.options, options || {});
  },
  
  start: function()
  {      
      this.currentFrame = -1;
      this.totalFrames = ((this.options.animTimeMS * this.options.fps) / 1000 );

      this.stepDelta = this.options.deltaX / this.totalFrames;
      this.currentDelta = 0;
      
      this.origin = parseInt(this.options.element.style.left);
      this.timeout = 1000/this.options.fps;
      
      this.step();
  },

  stop: function()
  {

    if (parseInt(this.options.element.style.left) == this.options.maxX)
    {
      this.options.button.style.display = 'none';
    }
    
  },

  
  step: function()
  {
      this.currentFrame++;
      var step = this.calcStep(this.currentFrame);

      if (step != 0)
      {
        this.currentDelta += step;
        this.moveElement(this.currentDelta);
        setTimeout((function() {this.step()}).bind(this), this.timeout);
      }
      else
      {
        this.stop();
      }
  },

  moveElement: function(offset)
  {
      var thestyle = this.options.element.style;
      var leftpos = Math.round(this.origin + offset);
      if (document.layers)
      {
          thestyle['left'] = leftpos;
      }
      else 
      {
          thestyle['left'] = leftpos + "px";
      }
  },

  calcStep: function(frame)
  {
    if (frame >= this.totalFrames)
    {
      return 0; // Done
    }

    var currentX = Math.round(this.origin + this.currentDelta);
    if ((this.stepDelta > 0) && (currentX + this.stepDelta >= this.options.maxX))
    {
      // Making 'left' more positive, dont add more than we are allowed
      return this.options.maxX - currentX;

    }
    else if ((this.stepDelta < 0) && (currentX + this.stepDelta <= this.options.maxX))
    {
      // Making 'left' more negative, dont subtract more than we are allowed
      return this.options.maxX - currentX;
    }
    return this.stepDelta;
  }
  
};


function scroll_element(id, distance, max, button)
{
  var elem = document.getElementById(id);
  new ScrollAnimator( { element:elem, elementid:id, animTimeMS: 500, deltaX:distance, maxX:max, button:button});
}


