// JavaScript Document




var S = {
	
	el : '',
	step: '',
	knob : '',
	amount : 2,
	speed : 50,
	interval : '',
	
	scrollElement: function(e, ui){
		if(arguments.length == 2){
			S.el.scrollTop( ui.position.top * S.step ); 
		}else{
			S.el.scrollTop(e * S.step);	
		}
	},
	
	scrollDown: function(e, a){
		var n = parseInt(S.knob.css('top'));
		if(arguments.length == 2){
			n = n + a;
		}else{
			n = n + S.amount;
		}
		if( n > (S.knob.parent().height() - S.knob.height()) ){
			n = S.knob.parent().height() - S.knob.height();  
			S.cancelAutoScroll();
		}
		S.knob.css('top', n);
		S.scrollElement(n);
	},
	
	scrollUp: function(e, a){
		var n = parseInt(S.knob.css('top'));
		if(arguments.length == 2){
			n = n - a;
		}else{
			n = n - S.amount;
		}
		n = n - S.amount;
		if( n < 0){
			n = 0; 
			S.cancelAutoScroll();
		}
		S.knob.css('top', n);
		S.scrollElement(n);
	},
	
	autoScrollDown: function(){
		S.interval = setInterval(S.scrollDown, 1000 / S.speed);
	},
	
	autoScrollUp: function(){
		S.interval = setInterval(S.scrollUp, 1000 / S.speed);
	},
	
	cancelAutoScroll: function(){
		clearInterval(S.interval);
	},
	
	beginKeyScroll: function(){
		$(window).keydown( function(e){
			if(e.which == 40){
				S.autoScrollDown();	
			}else if(e.which == 38){
				S.autoScrollUp();
			}
		});
		$(window).keyup( function(){
			S.cancelAutoScroll();						  
		});
	},
	
	endKeyScroll: function(){
		$(window).unbind('keydown');
	},
		
	mousewheelScroll: function(e, d){
		e.preventDefault();
		if(d == 1){
			S.scrollUp(null, 10);
		}else{
			S.scrollDown(null, 10);
		}
	},
	
	calculate: function(){
		$('#scrollbar').show();
		if(S.el.length == 0){
			$('#scrollbar').hide();
			return false;
		}
		var a = S.el.height() / S.el[0].scrollHeight;
		if( a > 1 ) a = 1;
		var perc = a * 100;
		S.knob.css('height', perc+'%');
		S.step = ( S.el[0].scrollHeight - S.el.height() ) / ( S.knob.parent().height() - S.knob.height() );
		if(perc > 99){
			$('#scrollbar').hide();
			return false;
		}
		S.reset();
		return true;
	},
	
	reset: function(){
		S.el.scrollTop(0);
		S.knob.css('top', 0);
	},

	init: function(){
		$('#scroll-top, #scrollbar-bottom, #content-media').unbind();
		S.el = $('#content-media');
		S.knob = $('#scrollbar-knob');
		S.knob.draggable({
			axis : 'y',
			containment : 'parent',
			cursor : 'n-resize',
			drag : S.scrollElement
		});
		if( S.calculate() ){
			$('#scrollbar-top').mousedown(S.autoScrollUp);
			$('#scrollbar-bottom').mousedown(S.autoScrollDown);
			$('#scrollbar-top, #scrollbar-bottom').mouseup(S.cancelAutoScroll);
			$('#scrollbar-top, #scrollbar-bottom').mouseout(S.cancelAutoScroll);
			S.el.mousewheel(S.mousewheelScroll);
		}
	}

}


$(document).ready( S.init );
						
