$(function() {

	var STEPS = 8,
		STEP_DURATION = 60,
		SHOW_1ST_DURATION = 2500,
		SHOW_DURATION = 4000,
		PAUSE_LATENCY = 250,

		current = 1,
		children = [],
		count = $('.rotpub div.nomargin').length,
		width = $('.rotpub').width(),
		zIndex = count,
		step = 0,
		pause = false;

	function easeOpacity(t, c) { // Out Quad
		return -c * (t /= STEPS) * (t - 2);
	}

	function easeLeft(t, c) { // Out back
		return c * ((t = t / STEPS - 1) * t * (2.70158 * t + 1.70158) + 1);
	}

	function setCss(left, opacity, zIndex) {
		var element = children[current];
		element.style.left = left + 'px';
		element.style.opacity = opacity;
		element.style.filter = 'alpha(opacity=' + (opacity * 100) + ')';
		zIndex && (element.style.zIndex = zIndex);
	}

	function animate() {
		if (++step == STEPS) {
			setCss(0, 0.999);
			(++current >= count) && (current = 0);
			setTimeout(next, SHOW_DURATION);
		} else {
			setCss(width - easeLeft(step, width), easeOpacity(step, 0.999));
			setTimeout(animate, STEP_DURATION);
		}
	}

	function next() {
		if (pause) {
			setTimeout(next, PAUSE_LATENCY);
		} else {
			step = 0;
			setCss(-width, 0, ++zIndex);
			setTimeout(animate, STEP_DURATION);
		}
	}

	if (count > 1) {
		$('.rotpub div.nomargin')
			.bind('mouseover', function() { pause = true; })
			.bind('mousemove', function() { pause = true; })
			.bind('mouseout',  function() { pause = false; })
			.css({'position': 'absolute', 'top': 0 })
			.each(function(i) {
				children.push($(this)[0]);
				$(this).css({'left': 0, 'zIndex': count - 1 - i});
			});
		setTimeout(next, SHOW_1ST_DURATION);
	}

});
