var Scroller = Class.create({
  initialize: function(element, options) {
    this.element = $(element);
    this.element.scroller = this;
    this.effect = null;
  	this.window = this.element.down('.window');
  	this.knob = this.window.down();
  	this.count = this.knob.childElements().length;
    var autoWidth = this.knob.childElements()[0].getWidth();
  	this.options = Object.extend({ width: autoWidth }, options);
  	this.buttons = this.element.down('.buttons').childElements();
  	this.buttons[0].observe('click', this.moveToRelative.bind(this, -1));
  	this.buttons[this.count+1].observe('click', this.moveToRelative.bind(this, +1));
  	
  	for(var i=0; i < this.count; i++) {
  	  this.buttons[i+1].observe('click', this.moveTo.bind(this, i));
  	}
	
  	//var newSelected = Math.floor( (this.window.offsetLeft - this.knob.offsetLeft) / this.options.width );
  	//find halfway point and go there
  	var newSelected = Math.floor( this.count / 2 );
  	
  	this.selected = null; // let moveTo set it
  	this.moveTo(newSelected, +1);
  },
  
  setSelected: function(selected) {
		
		if(selected < 0)
			selected = this.count - 1;
		else if( selected > (this.count - 1) )
			selected = 0;
		
    this.selected = selected;
    /*
    if( this.selected == 0 ) {
      this.buttons[0].addClassName('disabled');
    } else {
      this.buttons[0].removeClassName('disabled');
    }
    if( this.selected == this.count - 1 ) {
      this.buttons[this.count+1].addClassName('disabled');
    } else {
      this.buttons[this.count+1].removeClassName('disabled');
    }
    */
    this.buttons.each(function(button) {
      button.removeClassName('selected');
    });
    
    this.buttons[this.selected+1].addClassName('selected');
  },
  
  moveTo: function(selected, direction) {
    this.setSelected( selected );
    var position = -this.options.width * this.selected;
    var animate = true;
    
    if( this.effect ) this.effect.cancel();
	   
	  if( (this.selected == 0 && direction > 0) || (this.selected == (this.count - 1) && direction < 0) ) 
			animate = false;
	   
	  if( animate )
		{
			this.effect = new Effect.Move( this.knob, { x: position, mode: 'absolute' } );
		}
	  else  
	  {
			this.knob.setStyle( { left: position + 'px', position: 'absolute' } );
		}
  },
  
  moveToRelative: function(offset) {
  	this.moveTo(this.selected + offset, offset);
  }

});

Event.observe(window,'load', function() {
  var scrollers = $$('.scroller');
  scrollers.each(function(scroller) {
  	new Scroller(scroller);

  });
});
