Element.implement({
	scrollBy: function(x, y) {
		if(!x) x = 0;
		if(!y) y = 0;
		var scroll = this.getScroll();
		
		this.scrollTo(scroll.x + x, scroll.y + y);
	}
});

Scroller = new Class({
	speed: 30,

	initialize: function(el, speed) {
		if(speed) this.speed = speed;
	
		this.el = document.id(el);
		//this.el.setStyle('overflow', 'hidden');
		
		var changeHandler = (function(step) {this.scrollXToPercent(step);}).bind(this);
		this.slider = new Slider('scrollbar', 'knob', {
			mode:'vertical',
			onChange: changeHandler
		});
		
		$('scroll-up').addEvent('click', this.scrollUp.bind(this));
		$('scroll-down').addEvent('click', this.scrollDown.bind(this));
		
		this.el.addEvent('scroll', this.updateSlider.bind(this));
		
		this.checkScrollbarVisibility();
		//this.visibilityChecker = this.checkScrollbarVisibility.periodical(200, this);
	},
	
	checkScrollbarVisibility: function() {
		if(this.hasToScroll()) {
			$$(['scrollbar', 'knob', 'scroll-up', 'scroll-down']).setStyle('visibility', 'visible');
			clearInterval(this.visbilityChecker);
		}
	},
	
	scrollDown: function() {
		this.scrollBy(0, this.speed);
	},
	
	scrollUp: function() {
		this.scrollBy(0, -this.speed);
	},
	
	scrollRight: function() {
		this.scrollBy(this.speed, 0);
	},
	
	scrollLeft: function() {
		this.scrollBy(-this.speed, 0);
	},
	
	scrollBy: function(x, y) {	
		this.el.scrollBy(x, y);
		this.updateSlider();
	},
	
	scrollXToPercent: function(percent) {
		var pos = (this.el.getScrollSize().y - this.el.getSize().y) * percent / 100;
		this.el.scrollTo(0, pos);
	},
	
	updateSlider: function() {
		var percent = 100 * this.el.getScroll().y / (this.el.getScrollSize().y - this.el.getSize().y);
		this.slider.set(percent);
	},
	
	hasToScroll: function() {
		var hasToScroll = (this.el.getScrollSize().y - this.el.getSize().y > 0);
		return hasToScroll;
	}
});

window.addEvent('domready', function() {
	document.contentScroller = new Scroller('content');
});
