$(document).ready(function() {
	$('.displayTable .teams').wrapInner('<div class="wrapper"/>');
	var totalHeight = 0;
	var outerHeight = $('.displayTable .teams').height();
	var difference = 0;
	var steps = 0;
	var faktor = 0
	var currentStep = 0;
	var a = 0;
	var b = 0;

	$('.displayTable .teams .wrapper .entry').each(function() {
		var height = $(this).outerHeight();
		totalHeight += height;
	});

	difference = totalHeight - outerHeight;
	steps = Math.floor(totalHeight/outerHeight);
	faktor = 100 / steps / 100;

	if(totalHeight > outerHeight) {
		$('.displayTable .nextButton').removeClass("inactive");
		$('.displayTable .prevButton').removeClass("inactive");
	} else {
		$('.displayTable .nextButton').addClass("inactive");
		$('.displayTable .prevButton').addClass("inactive");
	}

	$('.displayTable .nextButton').click(function(event) { goToStep('next'); });
	$('.displayTable .prevButton').click(function(event) { goToStep('prev'); });

	// Get Active entry and scroll to active
	var positionEntry = $('.displayTable .teams .entry.active').position();
	setCurrentStep(positionEntry.top);

	initButtons();

	function setCurrentStep(position) {
		var currentPosition = position;
		
		for(var i=steps; i>=0; i--) {
			var marginTop = difference * faktor * i;
			if(currentPosition > marginTop) {
				currentStep = i;
				break;
			}
		}
		$('.displayTable .teams .wrapper').css("margin-top", (marginTop * -1) + "px" );
	}

	function goToStep(step) {
		if(step == "next") currentStep++;
		if(step == "prev") currentStep--;

		if(currentStep > steps) currentStep = steps;
		if(currentStep < 0) currentStep = 0;

		initButtons();
		var marginTop = -(difference * faktor * currentStep);
		$('.displayTable .teams .wrapper').stop().animate({"margin-top": marginTop + "px"});
	}

	function initButtons() {
		var marginTop = -(difference * faktor * currentStep);
		if(marginTop == 0) $('.displayTable .prevButton').addClass("inactive");
		else $('.displayTable .prevButton').removeClass("inactive");

		var marginTopCmp = (totalHeight - outerHeight) * -1;
		
		if(Math.round(marginTop) == marginTopCmp) $('.displayTable .nextButton').addClass("inactive");
		else $('.displayTable .nextButton').removeClass("inactive");
	}
});
