var Scroll = new Class({
	initialize: function() {
		// Set height of div
		this.div = $(document.body).getElement('div.scroll').getPrevious();
		this.height = this.div.getSize().y;
		height = this.div.getPrevious().getSize().y.toInt();
		
		// Get scroll (whole thing), knob (slider's zone), handle (the box that moves)
		this.scroll = $(document.body).getElement('div.scroll');
		this.knob = $(document.body).getElement('div.knob');
		this.handle = $(document.body).getElement('div.handle');
		
		// Set height if necessary
		if (height<this.height) {
			this.div.setStyle('height', (height>600 ? 600 : height));
			
			// Initialize heights
			this.scroll.setStyle('height', this.div.getSize().y);
			this.knob.setStyle('height', this.scroll.getSize().y.toInt());
			this.scroll.getElement('span').setStyle('height', this.knob.getSize().y.toInt()-9);
			
			// Initialize actions
			this.start();
		}
	},
	start: function() {
		obj = this;
		// Slider
		this.mySlider = new Slider(this.knob, this.handle, {
			mode: 'vertical', 
			onChange: function(step) { obj.div.getElement('div').setStyle('margin-top', -((obj.height-obj.div.getSize().y.toInt())*(step/100))); }
		});
		// Mousewheel events
		this.div.addEvent('mousewheel', function(e) {
			e.stop(); // So that it won't move the whole window
			obj.action(-e.wheel, true);
		});
		this.scroll.cloneEvents(this.div);
/*
		// Arrow buttons
		$each(this.scroll.getElements('a'), function(item, index) {
			item.addEvents({
				'mousedown': function() { item.scroll = obj.action.periodical(1, obj, new Array(index, false)); },
				'mouseup': function() { if (item.scroll!=undefined) $clear(item.scroll); },
				'mouseleave': function() { if (item.scroll!=undefined) $clear(item.scroll); }
			});
		});
*/
	},
	action: function(index, wheel) {
		// Only if handle is not at start or end
		if ((this.mySlider.step>0 && index<=0) ||
			(this.mySlider.step<100 && index>0)) {
		
			// Wheel event (move up or down the step)
			if (wheel) this.mySlider.step = this.mySlider.step+index.round();
			// Else arrow event (move up or down step)
			else this.mySlider.step = this.mySlider.step+(index==0 ? -1 : 1);
			
			// Reset slider's step to between 0 and 100
			if (this.mySlider.step>100) this.mySlider.step=100;
			else if (this.mySlider.step<0) this.mySlider.step=0;
			
			// Set content and handle's positions with current knob's step
			var top = ((this.knob.getSize().y.toInt()-this.handle.getSize().y.toInt())*(this.mySlider.step/100)).round();
			this.handle.setStyle('top', top);
			this.div.getElement('div').setStyle('margin-top', -((this.height-this.div.getSize().y.toInt())*(this.mySlider.step/100)));
		}
	}
});

var scroll;
window.addEvent('domready', function() { scroll = new Scroll; });
