// Div Scroller
var divScroller = {

	steps: 20, // Animation steps
	
	// Scroll a div to an X and Y position
	setPrecise: function(div, x, y) {

		// Clear timeout
		if (div.timeoutId) {
			clearTimeout(div.timeoutId);
			div.timeoutId = null;
		}
		
		// Setup
		div.scrollLeft = x;
	
	},
	
	// Scroll a div to an X and Y position
	easePrecise: function(div, x, y) {

		// Check if it is currently animating and set initial time
		if (div.timeoutId && div.t && div.t > (divScroller.steps / 2)) {
			div.t -= Math.floor(divScroller.steps / 2);
		} else {
			div.t = 0;
		}
		
		// Clear timeout
		if (div.timeoutId) {
			clearTimeout(div.timeoutId);
			div.timeoutId = null;
		}

		// Setup
		div.b = div.scrollLeft;
		div.c = x - div.b;
		div.d = divScroller.steps;
		divScroller.animate(div);
	
	},
	
	animate: function(div) {
	
		// New position
		div.scrollLeft = Math.floor(easing.sineInOut(div.t, div.b, div.c, div.d));
		
		// Increment time
		div.t++;
		
		// Timeout
		if (div.t <= div.d) {
		
			// Timeout
			div.timeoutId = setTimeout(function() {divScroller.animate(div);}, 25);
			
		} else {
		
			// Clear variables
			div.t = div.b = div.c = div.d = null;
			
		}
	
	}

};


// Easing functions (from http://www.robertpenner.com/easing/)
//
// t = time, b = begin, c = change, d = duration
// time = current frame, begin is fixed, change is basically finish - begin, duration is fixed (frames),
var easing = {
	
	linear: function(t, b, c, d) {
		return c*t/d + b;
	},
	
	sineInOut: function(t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	
	cubicIn: function(t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	
	cubicOut: function(t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	
	cubicInOut: function(t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	
	bounceOut: function(t, b, c, d) {
		if ((t/=d) < (1/2.75)){
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)){
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)){
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	}

};