// via: http://forum.mootools.net/topic.php?id=148&page=2
// zu: http://www.speed-co.de/
// Ki: Klassen: a.scrolltop, a.scrollbot
Fx.ScrollWindow = Fx.Base.extend({

	initialize: function(options){
		this.setOptions(options);
		this.now = [];
		var b = document.body;
		var stop = this.clearTimer.bind(this);
		if (!this.options.continuer){
			if (b.addEventListener) b.addEventListener('DOMMouseScroll', stop, false);
			else b.onmousewheel = stop;
		}
	},

	setNow: function(){
		[0,1].each(function(i){
			this.now[i] = this.compute(this.from[i], this.to[i]);
		}, this);
	},

	scrollTo: function(x, y){
		if (this.timer && this.options.wait) return;
		var left = Window.getScrollLeft();
		var top =  Window.getScrollTop();
		var width = Window.getWidth();
		var height = Window.getHeight();
		var fullWidth = Window.getScrollWidth();
		var fullHeight = Window.getScrollHeight();
		var maxScrollWidth = fullWidth - width;
		var maxScrollHeight = fullHeight - height;
		if (x > maxScrollWidth) x = maxScrollWidth;
		if (y > maxScrollHeight) y = maxScrollHeight;
		return this.custom([left, top], [x, y]);
	},

	toElement: function(el){
		return this.scrollTo($(el).getLeft(), $(el).getTop());
	},

	increase: function(){
		window.scrollTo(this.now[0], this.now[1]);
	}
});
var SmoothScrollWindow = new Class({	
	anchorName: '',
	scroller: null,
	elements: [],
	
	initialize: function(_elements, options){	
		this.elements = _elements;
		options = Object.extend({ onComplete: this.setLocationAnchor.bind(this) }, options || {}); //extend the options with the oncomplete
		Window.onDomReady( this.findAllAnchors.pass(options, this) );	//start when dom is ready (onload)
	},
	
	findAllAnchors: function(options) {
		this.scroller = new Fx.ScrollWindow(options);	
		
		var els = [];
		this.elements.each(function(el){				//convert the array of 'elements'
			els.extend($S(el));					//to the wanted DOM elements
		});
		els.each( this.addEventsToAnchor.bind(this) );
	},
	
	addEventsToAnchor: function(el) {
		el.onclick=function(){return false};				//delete the old anchor event
		el.addEvent('click', this.scrollToAnchor.pass(el, this) );	//set the new scrolling event
	},
	
	scrollToAnchor: function(el) {
		this.anchorName = el.href.substr(el.href.search(/#/)+1);	//extract the anchor name
		this.scroller.toElement(document.getElementsByName(this.anchorName)[0]);
	},
	
	setLocationAnchor: function() {
		window.location.href = "#"+this.anchorName;
	}
});

new SmoothScrollWindow(['a.scrollbot', 'a.scrolltop'], {duration: 1500, wait: false, transition: Fx.Transitions.cubicOut});