/**
 * @author fred
 */
var ContentScroller = Class.create({
	
	keyScrollDistance:		20,
	mouseScrollDistance:	60,
	pageScrollDistance:		null,
	
	sliders:	null,
	scroller:	null,
	
	container:	null,
	content:	null,
	
	initialize: function( handles, tracks, container, content, options )
	{

		options = options || {};
		
		this.container	= $(container);
		this.content	= $(content);
		
		this.keyScrollDistance		= options.keyScrollDistance		|| this.keyScrollDistance;
		this.mouseScrollDistance	= options.mouseScrollDistance	|| this.mouseScrollDistance;
		this.pageScrollDistance		= options.pageScrollDistance	|| this.container.getHeight();
		
		this.scroller = new SmoothScroller( container, options.onStop );
		
		this.sliders = new DynamicSliders( handles, tracks,{
			axis:		'vertical',
			range:		$R( 0,  this.content.getHeight()-this.container.getHeight() ),
			onSlide:	this.scroller.dragTo.bind(this.scroller),
			onChange:	this.scroller.scrollTo.bind(this.scroller)
		} );
		
		MouseWheelListener.addHandler( this.onMouse.bind(this) );
		
		Event.observe( document, 'keydown', this.onKeyDown.bindAsEventListener(this) );
		Event.observe( document, 'keypress', this.pressKeyCheck.bindAsEventListener(this) );
	},
	
	scrollTo: function( element )
	{
		var pos = $(element).cumulativeOffset().top - this.container.cumulativeOffset().top;
		
		//check version of opera
		//if( Prototype.Browser.Opera )
			//pos += this.container.scrollTop;
		
		this.sliders.animateTo( pos, true );
		this.scroller.scrollTo(pos);
	},
	
	updateSliders: function()
	{
		this.sliders.setRange( $R( 0, this.content.getHeight()-this.container.getHeight()) );
	},
	
	onMouse: function( delta )
	{
		this.sliders.setValue( this.sliders.getValue() - delta*this.mouseScrollDistance );
	},
	
	onKeyDown: function( event )
	{
		switch( event.keyCode )
		{
			case Event.KEY_UP:
				this.sliders.setValue( this.sliders.getValue()-this.keyScrollDistance );
				this.preventKeyScrolling( event );
				break;
			
			case Event.KEY_DOWN:
				this.sliders.setValue( this.sliders.getValue()+this.keyScrollDistance );
				this.preventKeyScrolling( event );
				break;
			
			case Event.KEY_PAGEUP:
				this.sliders.setValue( this.sliders.getValue()-this.pageScrollDistance );
				this.preventKeyScrolling( event );
				break;
				
			case Event.KEY_PAGEDOWN:
				this.sliders.setValue( this.sliders.getValue()+this.pageScrollDistance );
				this.preventKeyScrolling( event );
				break;
		}
	},
	
	pressKeyCheck: function( event )
	{
		switch( event.keyCode )
		{
			case Event.KEY_UP:
			case Event.KEY_DOWN:
			case Event.KEY_PAGEUP:
			case Event.KEY_PAGEDOWN:
				this.preventKeyScrolling( event );
		}
	},
	
	preventKeyScrolling: function( event )
	{
		if( event.preventDefault ) 
			event.preventDefault();
		
		if( event.stopPropagation )
			event.stopPropagation();
		
		event.returnValue = false;
	}
});
