
window.addEvent('domready', function(){
	$$('.container').each(function(cont, idxcont){
		var sb = new scrollBox(cont, {
			'duration': 25,
			'increment': 5,
			'buttonheight': 15
		});
	});
	
});


var scrollBox = new Class({
	Extends: Options,
	
	options: {
		'buttonheight': 20,
		'increment': 10,
		'duration': 40,
		'classes':{
			'up': 'button-up',
			'down': 'button-down'
		}
	},
	
	initialize: function(box, options){
		this.box = $(box);
		this.content = new Element('div');
		this.content.set('html', this.box.get('html'));
		this.box.empty();
		this.box.adopt(this.content);
		
		this.setOptions(options);
		this.totIncrement = 0;
		this.maxIncrement = -1*this.content.getCoordinates().height;
		this.internalID = null;
		
		var fx = new Fx.Morph(this.content, {
			duration: this.options.duration,
			transition: Fx.Transitions.Back.easeInOut,
			wait: true
		});
		
		var up = new Element('div', {
			'class': this.options.classes.up,
			'styles':{
				'position': 'absolute',
				'width': this.box.getCoordinates().width,
				'top': this.box.getCoordinates().top,
				'left': this.box.getCoordinates().left,
				'height': this.options.buttonheight
			},
			'events':{
				'mouseenter': function(){
					$clear(this.internalID);
					this.internalID = this.scroll.periodical(this.options.duration, this, [fx, 1]);
				}.bind(this),
				'mouseout': function(){
					$clear(this.internalID);
				}.bind(this)
			}
		});
		
		var down = new Element('div', {
			'class': this.options.classes.down,
			'styles':{
				'position': 'absolute',
				'width': this.box.getCoordinates().width,
				'top': this.box.getCoordinates().top + this.box.getCoordinates().height - this.options.buttonheight,
				'left': this.box.getCoordinates().left,
				'height': this.options.buttonheight
			},
			'events':{
				'mouseenter': function(){
					$clear(this.internalID);
					this.internalID = this.scroll.periodical(this.options.duration, this, [fx, -1]);
				}.bind(this),
				'mouseout': function(){
					$clear(this.internalID);
				}.bind(this)
			}
		});
		$(document.body).adopt(up);
		$(document.body).adopt(down);
	},
	
	
	scroll: function(fx, dir){
		var allowScrolling = (dir>0 && this.totIncrement<0) || (dir<0 && this.totIncrement>(this.maxIncrement-this.options.increment+this.box.getCoordinates().height));
		if(allowScrolling){
			fx.cancel();
			fx.start({
				'margin-top': [this.totIncrement, this.totIncrement+(this.options.increment * dir)]
			});
			this.totIncrement = this.totIncrement+(this.options.increment*dir);
		}else{
			$clear(this.internalID);
		}
	}
	
});


