jQuery(function( $ ){
	$('#wrapper').serialScroll({
		target:'.container',
		items:'div.inner,div.players',
		prev:'img.prev',
		next:'img.next',
		axis:'xy',
		duration: 1000,
		force:true,
		easing: "easeOutBounce",
		scrolltop: true,
		onBefore:function(button, e, elem, $pane, $items, pos ){
//			Check if the element is a player
			if (($items[pos]) && ($($items[pos]).hasClass('players'))) {				
				
//				$('div#playerSelection div.players')
//					.not($items[pos])
//					.not($items[pos+1])
//					.not($items[pos-1])
//						.hide();
				$('div#playerSelection div.players').removeClass('current_player');
				$($items[pos]).show().next().show().next().show();
			}
			if (e.preventDefault)
				e.preventDefault();
			if( this.blur )
				this.blur();
		},
		onAfter:function(element){
			var i = 0, x = 0, z = 0;
			if ($(element).hasClass('players')) {
				$(element).addClass('current_player');
				
				i = parseInt($('div.container').scrollLeft(), 10);
				x = parseInt($(element).width(),10);
				z = parseInt($(element).prev().width(),10);
				
				$('div#playerSelection div.players')	
					.not($(element))
					.not($(element).prev().prev())
					.not($(element).next().next())
						.hide();
				
				$('div#playerSelection div.firecrackerblocks')					
					.not($(element).prev())
					.not($(element).next())
						.hide();
				
				if ($(element).prev().prev().size() > 0) {
					if (!$(element).prev().prev().is(':visible')) {
						$('div.container').scrollLeft(i+x+z);
						$(element).prev().show().prev().show();
					} else {					
						if ($(element).prev().prev().prev().size() > 0)
							$('div.container').scrollLeft(i-(x+z+20));
					}
				}
				
//				if (($(element).next().next().size() === 0) && ($(element).prev().prev().is(':visible'))) {
//					var i = parseInt($('div.container').scrollLeft(), 10);
//					var x = parseInt($(element).css('width').replace(/\D/g,''), 10) + 20;
//					$('div.container').scrollLeft(i-x);
//					$('div#playerSelection div.players').not(element).hide();
//				}else {
//				}
//				if (!$(element).prev().prev().is(':visible')) {					
//					$('div.container').scrollLeft(i+x);
//					$(element).prev().prev().show();
//				} else {					
//					$('div.container').scrollLeft(i-(x+20));
//				}
////				if ($(element).next().next().is(':visible'))
////					$('div.container').scrollLeft(i-x);
////				else
////					$('div.container').scrollLeft(i+x);
//				if (!$(element).next().next().is(':visible')) {					
//					$('div.container').scrollLeft(i+x);
//					$(element).next().next().show();
//				}
//				$('div.container').scrollLeft(i+x);
//				$('div.container').scrollLeft(i+x);
			} else {
				$('div#playerSelection div.players, div#playerSelection div.firecrackerblocks').hide();	
			}
		}
	});
});




/**
 *  Estrutura atual das index
 *  0 - 4: div.inner
 *  > 5 div.players
 */

function goto(index) {
	$('div.container').trigger('goto', [index]);
	return false;
}
