jQuery(function($) {
	if ($('#balls-container').hasClass('roll')) {
		rollBalls(false);
		setTimeout(function() {rollBalls(true, -50);}, 3500);
		setTimeout(function() {rollBalls(false);}, 6000);
		// setTimeout(function() {rollBalls(true, 150);}, 7500);
	}
	else if ($('#balls-container').hasClass('bounce')) {
		bounceBalls();
	}
	
	$('#balls-container h1').addClass('swish');
	
	var lineCurrent = 0,
		lineTotal = $('#balls-container h1 span').each(function(i, el) {
		$(el).css({
			'opacity': i > 0 ? 0 : 1,
			'display': i > 0 ? 'none' : 'block'
		});
	}).length;
	
	setTimeout(function() {
		var next = lineCurrent + 1;
		
		if (next >= lineTotal) {
			next = 0;
		}
		
		$('#balls-container h1 span').eq(lineCurrent).animate({
			opacity: !jQuery.browser.msie ? 0 : 1
		}, 400, function() {
			$(this).css('display', 'none');
		});
		$('#balls-container h1 span').eq(next).animate({
			opacity: 1
		}, 400, function() {
			$(this).css('display', 'block');
		});
		
		lineCurrent = next;
	},5900);
});

function rollBalls(back, start) {
	var movementTime = 2000,
		opacityTime = 1500,
		startOffset = -10,
		endOffset = 110;
	
	if (!jQuery.browser.msie) {
		$('#balls-container .ball').css('opacity', back ? 1 : 0);
		$('#balls-container .ball').animate({
			'opacity': back ? 0 : 1
		}, {
			duration: opacityTime,
			queue: false,
			delay: (back ? 1 : 0) * (movementTime - opacityTime)
		});
	}
	
	for (var i=1; i <= 4; i++) {
		if (!back) {
			var offsetX = (endOffset - startOffset) * (i - 1) / 3 + startOffset;
		} else {
			var offsetX = start;
		}
		
		$('#ball-' + i).animate(jQuery.browser.msie ? {'background-position-x': offsetX + '%', 'background-position-y': '50%'} : {'background-position': offsetX + '% 50%'}, movementTime);
	}
};

function bounceBalls() {
	var bounceTime = 3000,
		startOffset = -10,
		endOffset = 110;
	
	for (var i=1; i <= 4; i++) {
		var offsetX = (endOffset - startOffset) * (i - 1) / 3 + startOffset;
		$('#ball-' + i).animate(jQuery.browser.msie ? {'background-position-x': offsetX + '%', 'background-position-y': '100%'} : {'background-position': offsetX + '% 100%'}, {
			duration: bounceTime - 200 + Math.random() * 400,
			easing: 'easeOutBounce'
		});
	}
};

// 120 - 10 = (110 - (-10)) * 3/3 - 10
// 80  - 10 = (110 - (-10)) * 2/3 - 10
// 40  - 10 = (110 - (-10)) * 1/3 - 10
// 0   - 10 = (110 - (-10)) * 0/3 - 10

