// SCROLABLE CLASS //
var Scrollable = Class.create();
Scrollable.prototype = {
  initialize: function(element,SLElement,SRElement,speed) {
    this.element = $(element);
	this.SLElement = $(SLElement);
	this.SRElement = $(SRElement);
    this.active = false;
	this.timer = new Timer(this);
	// set cursor //
	this.SRElement.style.cursor = 'pointer';
	this.SLElement.style.cursor = 'pointer';
	
    this.eventMouseDownL = this.startScroll.bind(this,-speed);
    this.eventMouseDownR = this.startScroll.bind(this,speed);
    this.eventMouseUp   = this.endScroll.bind(this);
    


    Event.observe(this.SRElement, 'mouseover', this.eventMouseDownR);
    Event.observe(this.SLElement, 'mouseover', this.eventMouseDownL);
  },
  startScroll: function(dir) {
    Event.observe(this.SRElement, 'mouseout', this.eventMouseUp);
    Event.observe(this.SLElement, 'mouseout', this.eventMouseUp);

	this.finishCounter = 1;
	this.scrollPoint = 0;
	this.active = true;	
	this.speed = dir;
	this.scroll = this.scrollby.bind(this);
	this.scroll();
  },
  endScroll: function(event) {
	this.active = false;
  },
  scrollby: function() {
  	
	if(this.active) {
		this.element.scrollLeft += parseFloat(this.speed);

		if(this.scroller) this.timer.clearTimeout(this.scroller);
		this.scroller = this.timer.setTimeout("scrollby", 10);
	}
	else {
		images = $$('#'+this.element.id+' img');
		cpoints = Array();
		cpoints[0] = 0;
		for(var i=0; i<images.length; i++) {
			var last = cpoints[i];
			if(!last) last = 0;
			cpoints[i+1] = last + images[i].width + 4;
		}
		for(var i=0; i<cpoints.length; i++) {
			if(this.element.scrollLeft>cpoints[i] && this.element.scrollLeft<cpoints[i+1]) {
				if(this.speed>0) this.scrollPoint = cpoints[i+1];
				else if(this.speed<0) this.scrollPoint = cpoints[i];
				
				if(this.scroller) this.timer.clearTimeout(this.scroller);
				this.scroller = this.timer.setTimeout("scrollFinish", 10);
			}
		}
	}
  },
  scrollFinish: function() {
	this.finishCounter++;
	if( this.element.scrollLeft < this.scrollPoint && this.speed > 0 ) {
		this.element.scrollLeft += parseInt(this.speed);
		if(this.scroller) this.timer.clearTimeout(this.scroller);
		this.scroller = this.timer.setTimeout("scrollFinish", 10);
	}
	else if( this.element.scrollLeft > this.scrollPoint && this.speed < 0 ) {
		this.element.scrollLeft += parseInt(this.speed);
		if(this.scroller) this.timer.clearTimeout(this.scroller);
		this.scroller = this.timer.setTimeout("scrollFinish", 10);
	}
  }
}