$(function() {
	Pod.require(['tournamentVars'], function(tournamentVars) {
		var targetDiv = $('#js_div_prizes');
		var ul = null;
		var perPage = 10;

		for(var i = 0; i < tournamentVars.prizes.length; ++i) {
			var flushUl = i % 5 == 0;
			if (flushUl && ul) {
				targetDiv.append(ul);
				ul = null;
			}
			if (!ul) {
				ul = $('<ul>');
			}
			ul.append($('<li>'+(i+1)+' место - '+tournamentVars.prizes[i]+'</li>'));
		}
		if (ul && ul.children().length > 0) {
			targetDiv.append(ul);
		}


		function updateParticipantsTable(data, isWinners) {
			var participants = data.list;
			var tbody = $('.tournament_winners_table tbody');
			$('#js_column_prize_name').text(isWinners
					? 'Выигрыш'
					: 'Количество баллов'
			);
			tbody.empty();
			if(participants.length == 0) {
				tbody.append(isWinners
						? '<tr><td colspan="3">Список победителей отсутствует</td></tr>'
						: '<tr><td colspan="3">Станьте первым участником турнира!</td></tr>');
				return;
			}
			$.each(participants, function(index, participant) {
				tbody.append(
						$('<tr>').append(
								$('<td>').text(participant.place),
								$('<td>').text(participant.name),
								$('<td>').html(isWinners ? participant.prize : Math.ceil(participant.points))
						).addClass(CONFIG_GLOBAL.uid == participant.uid ? 'active' : ''));
			});
			for (var i = participants.length; data.offset > 0 && i < perPage; ++i) {
				tbody.append(
						$('<tr>').append(
								$('<td>'),
								$('<td>'),
								$('<td>')
						));
			}
		}

		function loadParticipantsPage(pageNum) {
			tournamentVars.pageNum = pageNum;
			$.pagination({
				number: tournamentVars.participantsAmount,
				perPage: perPage,
				now: pageNum+1
			});
			var offset = parseInt(pageNum) * perPage;
			$.ajax({
				url: '/tournaments/'+tournamentVars.id+'/' + (tournamentVars.finished ? 'winners' : 'participants') + '.json',
				data: {'limit': perPage, 'offset': offset},
				dataType: 'json',
				type: 'get',
				context: this,
				success: function (response) {
					updateParticipantsTable(response.data, tournamentVars.finished);
				}
			});
		}

		window.onhashchange = function () {
			var currentPageNumber = $.pagination.getCurrentPageFromHash();
			if (!currentPageNumber) {
				return;
			}
			currentPageNumber = currentPageNumber ? currentPageNumber - 1 : 0;
			loadParticipantsPage(currentPageNumber);
		};

		$(function() {
			if ($.pagination.getCurrentPageFromHash()) {
				window.onhashchange();
			} else {
				loadParticipantsPage(0);
			}
		})
	});
});
