/* 
	Sine Scrollbars by Mr Speaker
	http://www.mrspeaker.net/
	January 2010
*/
var scrbar = {
	sin_div : 3,
	sin_mul : 100,

	screen_width : 0,
	offset_left : 50,
	scroll_width : 15,
	scroll_height: 15,
	
	bars : [],
	frame : 0,
	dir : true,
	
	hover_y : -1,
	hover_x : -1
};
	
scrbar.init = function(){
	// Attach resize listener
	$( window ).resize( function(){ scrbar.adjustBars(); } );
	$( "#board" ).bind({
		mousemove : function( e ){
			scrbar.hover_y = Math.floor(e.pageY/scrbar.scroll_height);
			scrbar.hover_x = e.pageX;
		},
		mouseout : function(){
			scrbar.hover_y = -1;
			scrbar.hover_x = -1;
		}
	});
	this.screen_width = $( window ).width();
	this.addBars( this.getNumBars(), 0 );
	
	setInterval(function(){	scrbar.update(); }, 200);
};
	
scrbar.update = function(){
	++this.frame;
	
	// Update sine mulitplier
	this.sin_mul += this.dir ? 10 : -10;
	if( this.sin_mul > 1500 || this.sin_mul < 10 ){
		this.dir = !this.dir;
	}

	for( var i = 0, numBars = this.bars.length; i < numBars; i++ ){
		var barWidth = this.screen_width * ( 100 / this.scroll_width );
		
		// Figure out scroll pos
		var scroll_left = ( this.sin_mul * Math.sin( ( i + this.frame ) / this.sin_div ) );
		
		var close = Math.abs( i - this.hover_y );
		if( this.hover_y != -1 && close < 3 ){
			scroll_left = scroll_left - (((( this.screen_width / 2 ) - this.hover_x)* (3-close))*3);
		}

		// Scrollbar pos
		var offset = ( this.offset_left / 100 ) * barWidth;
		
		// Centre the scrollbar
		var ex = ( this.offset_left / ( 100 / this.scroll_width ) / 100 ) * barWidth;
		offset -= ex;
		offset = ~~( scroll_left + offset );

		// Update scroll bar
		this.bars[ i ]
			.stop()
			.animate( { scrollLeft: offset }, "fast" );
	}
	// Move siney back to middle if mousing over
	if( this.hover_y != -1 ){
		var mid = this.screen_width / 2;
		this.hover_x += this.hover_x < mid ? 25 : -25;
		if(Math.abs(this.hover_x - mid) < 10){
			this.hover_y = -1;
		}
	}
};
	
scrbar.addBars = function( num, start ){
	for( var i = 0; i < num; i++ ){
		var bar = $( "<div/>" )
			.addClass( "bar" )
			.appendTo( "#board" );
		
		$( "<div/>" )
			.css({ 
				height: this.scroll_height + "px",
				width: this.screen_width * ( 100 / this.scroll_width )
			})
			.appendTo( bar );

		this.bars.push( bar );
	}
};
	
scrbar.removeBars = function( num ){
	$( "#board" )
		.find( ".bar" )
		.eq( -num )
		.nextAll()
		.andSelf()
		.remove();
	this.bars = this.bars.slice( 0, -num );
};
	
scrbar.adjustBars = function(){
	// figure out height changes
	var oldBars = this.bars.length;
	var newBars = this.getNumBars();
	
	if( oldBars == newBars )return;
	if( newBars > oldBars ){
		this.addBars( newBars - oldBars, oldBars );
	} 
	else {
		this.removeBars( oldBars - newBars );
	}
};
	
scrbar.getNumBars = function(){
	return ~~( $( window ).height() / this.scroll_height );
};
