var iSizeSmallWidth = 70;
var iSizeSmallHeight = 45;
var iSizeBigWidth = 331;
var iSizeBigHeight = 212;
var oCard;
var bPodiumDragger = false;

var bVoted = false;
var iCurrentPage = 1;


$(document).ready(function() {
	if($('#card-contest-title').length){
		$('#docTitle').html($('#card-contest-title').html());
	}
	
	if(!$('#card-contest').hasClass('already-voted')){
		$('#podium .droppable').droppable({
			hoverClass: 'active',
			accept: '.draggable,.shadow',
			drop: function(event, ui) {
				dropCardToPodium($(this));
			}
		});
		
		$('#podium-form').submit(function() {
			if(!$('#btnVote').is(':disabled')){

				$('#btnVote').attr('disabled', 'disabled');
				$('#cards-list .draggable').draggable('destroy');
				$('#podium-form .shadow').draggable('destroy');
				$('#cards-list span.votes').show();
				
				bVoted = true;
				showCardsForPage(iCurrentPage);

				$(this).find('.filled').each(function(index) {
					$(this).removeClass('filled');
					$(this).addClass('voted');
				});
				

				$.ajax({
					url: "/_/ajax/_card_vote.html",
					type: "POST",
					dataType: "xml",
					data: {
						place1hdn: getGuidFromPath($('#place1hdn').val()),
						place2hdn: getGuidFromPath($('#place2hdn').val()),
						place3hdn: getGuidFromPath($('#place3hdn').val()),
						postback: true
					},
					success: function(xml) {
						$('#podium-bottom').hide();

						if($(xml).find('ok').length > 0){
							$('#podium-voted').show();
						}else{
							$('#podium-error').show();
						}
					},
					error: function() {
						$('#podium-bottom').hide();
						$('#podium-error').show();
					}
				});
				return false;
			}else{
				return false;
			}
		});

		$(window).resize(function() {
			repositionPodium();
		});

		$(window).scroll(function() {
			repositionPodium();
		});

		repositionPodium();
		
		//	Проверяем аяксом, может ли голосовать пользователь - может быть, надо спрятать подиум, если у него все закэшилось
		checkIfCanVote();
	}else{
		bVoted = true;
	}
	
	showCardsForPage(1);
	bindPaginator();
});

function showVotedState(){
	$('#alreadyVoted').show();
	$('#manual').hide();
	
	$('#podium').hide();
	$('#cards-list .draggable').draggable('destroy');
	$('#podium-form .shadow').draggable('destroy');
	$('#card-contest').addClass('already-voted');
}

function showNotVotedState(){
	$('#alreadyVoted').hide();
	$('#manual').show();
	
	$('#podium').show();
	$('#card-contest').removeClass('already-voted');
}


function showCardsForPage( iPage ){
	
	$('#cards-list').html('');
	var sBody = '';
	
	for (var i=0; i < aCards.length; i++) {
		if(iPage == aCards[i][0]){
			if(iContestID == 97){
				sBody += '<div class="card" style="margin-bottom:55px;width:328px;"><h2>&laquo;'+ aCards[i][5] +'&raquo;</h2><p>'+ aCards[i][6] +'<strong>'+ aCards[i][1] +'</strong>';
			}else{
				sBody += '<div class="card" style="float:left;margin-bottom:19px;width:254px;"><strong>'+ aCards[i][1] +'</strong>';
			}
			
			if(bVoted){
				if(aCards[i][2].length > 15){
					sBody += '<br /><span>'+ aCards[i][2] +'</span>';
				}else{
					sBody += '<span class="votes">'+ aCards[i][2] +'</span>';
				}
			}
			
			if(iContestID == 97){
				sBody += '</p><img src="'+ aCards[i][3] +'" width="331" height="212" class="draggable" />';
			}else{
				sBody += '</p><img src="'+ aCards[i][3] +'" width="254" height="161" class="draggable" />';
			}
			
			//	archive, winners
			if(aCards[i][4] == '1' && iPage == 1 && i<3){
				if(iContestID == 97){
					sBody += '<div class="winner-final winner-'+ (i+1) +'" />';
				}else{
					sBody += '<div class="winner winner-'+ (i+1) +'" />';	
				}
			}
			
			sBody += '</div>';
		}
	};
	
	$('#cards-list').html(sBody + '<div class="clear"></div>');
	fixHeightForCards();
	
	if(!bVoted){
		$('#cards-list .draggable').draggable({
			revert: 'invalid', // when not dropped, the item will revert back to its initial position
			containment: $('#card-contest').length ? '#card-contest' : 'document', // stick to demo-frame if present
			helper: function(event) {
				return createDragger($(this));
			},
			cursorAt: { cursor: 'move', top: 25, left: 36 }
		});
	}
}

function fixHeightForCards(){
	var iMaxHeight = 0;
	$('#cards-list .card').each(function(index) {
		if($(this).height() > iMaxHeight){
			iMaxHeight = $(this).height();
		}
	});

	$('#cards-list .card').css('height', iMaxHeight + 'px');
}

//	Если заполенены все три input - разблокируем кнопку
function validateVoteForm(){
	var sHiddenName;
	var bError = false;
	
	for (var i=1; i <= 3; i++) {
		sHiddenName = 'place'+ i +'hdn';
		if($('#' + sHiddenName).val() == ''){
			bError = true;
		}
	};
	
	if(bError){
		$('#btnVote').attr('disabled', 'disabled');
	}else{
		$('#btnVote').attr('disabled', '');
	}
}

//	Выдвигаем подиум наружу, чтобы получить нормальный fixed
function movePodiumOutside(){
//	var code = $('#podium').html();
	$('#podium').appendTo('body');
}

var podiumTimeoutID;

//	Двигаем подиум в нужное место по горизонтали
function repositionPodium(){
	var iPosition = $(window).scrollTop() - 50;
	var iHeight = $(document).height() - 800;
	if($.browser.msie && $.browser.version <= 6){
		iHeight = $(document).height() - 600;
		iPosition += 60;
	}
	if(iPosition > iHeight){
		iPosition = iHeight;
	}
	if(iPosition < 0){
		iPosition = 0;
	}
	
	if($.browser.msie){
		if($.browser.version <= 6){
			iPosition -= 300;
			if(iPosition < 0){
				iPosition = 0;
			}
		}
		$('#podium').css('top', iPosition + 'px');
	}else{
		movePodium(iPosition);
	}
}

function movePodium(iPosition){
	$('#podium').stop();
	
	$('#podium').animate({
		top:iPosition + "px"
	}, 400);
}

function getGuidFromPath(sPath){
	var iPosition = sPath.indexOf('/design_final/') + 14;
	var iLength = 36;

	sPath = sPath.substring(iPosition,(iPosition + iLength));
	return sPath;
}

function checkIfCanVote(){
	$.ajax({
		url: "/_/ajax/_card_contest_check_voted.html",
		type: "POST",
		dataType: "xml",
		success: function(xml) {
			if($(xml).find('voted').length > 0){
				if($(xml).find('voted').attr('result') == '1'){
					bVoted = true;
					showVotedState();
					showCardsForPage(iCurrentPage);
				}
			}

		},
		error: function() {
		}
	});
	
	if(!bVoted){
		showNotVotedState();
	}
}


function resizeToSmall(){
	$('#dragger img').animate({
		width:iSizeSmallWidth + "px",
		height:iSizeSmallHeight + "px"
	}, 300);
}

function resizeToNormal(){
	$('#dragger img').attr('width', iSizeBigWidth);
	$('#dragger img').attr('height', iSizeBigHeight);
	$('#dragger').removeClass('invisible');
}

function createDraggerAnimated(img){

	var sCode = '<div id="dragger" class="invisible"><img src="'+ $(img).attr('src') +'" width="'+ iSizeSmallWidth +'" height="'+ iSizeSmallHeight +'" /></div>';
	oCard = $(img);
	window.setTimeout(resizeToNormal, 0);
	window.setTimeout(resizeToSmall, 50);
	bPodiumDragger = false;

	return $(sCode);
}

function createDragger(img){
	var sCode = '<div id="dragger"><img src="'+ $(img).attr('src') +'" width="'+ iSizeSmallWidth +'" height="'+ iSizeSmallHeight +'" /></div>';
	oCard = $(img);
	bPodiumDragger = false;

	return $(sCode);
}

function createDraggerPodium(img){
	var sCode = '<div id="dragger_small"><img src="'+ $(img).attr('src') +'" width="'+ $(img).attr('width') +'" height="'+ $(img).attr('height') +'" /></div>';
	oCard = img;
	bPodiumDragger = true;

	return $(sCode);
}

function dropCardToPodium(div){
	var sSrcNew = $(oCard).attr('src');

	//	Ищем эту карту на подиуме. Если бы не IE, этот код бы занял одну строчку
	$('#podium img').each(function(index) {
		var sSrc = $(this).attr('src');
		var iLength = $(oCard).attr('src').length;
		sSrc = sSrc.substring(sSrc.length-iLength, sSrc.length);
		if(sSrc == $(oCard).attr('src')){
			if(bPodiumDragger && $(div).find('img:visible').length > 0){
				//	Меняем местам
				$(this).attr('src', $(div).find('img').attr('src'));
			}else{
				//	Убираем дубль
				$(this).parent().fadeOut('normal').html('');
			}
		}
	});

	$(div).html('<div class="filled"><img src="'+ sSrcNew +'" width="'+ iSizeSmallWidth +'" height="'+ iSizeSmallHeight +'" class="card" /><div class="shadow"></div></div>');

	updateHiddenFields();
	validateVoteForm();

	$(div).find('.shadow').draggable({
		revert: 'invalid', // when not dropped, the item will revert back to its initial position
		containment: $('#podium').length ? '#podium' : 'document', // stick to demo-frame if present
		helper: function(event) {
			return createDraggerPodium($(this).prev());
		},
		cursorAt: { cursor: 'move', top: 25, left: 36 }
	});
}

function updateHiddenFields(){
	for (var i=1; i <= 3; i++) {
		var sHiddenName = 'place'+ i +'hdn';
		$('#' + sHiddenName).val('');
	};

	$('#podium-form div.droppable img').each(function(index) {
		var sSrc = $(this).attr('src');
		var sPosition = $(this).parent().parent().attr('id');
		
		var sHiddenName = sPosition + 'hdn';
		$('#' + sHiddenName).val(sSrc);
	});

}

function bindPaginator(){
	$('.b-paginator span').click(function() {
		if(!($(this).hasClass('selected'))){
			$('.b-paginator span.selected').removeClass('selected');
			var iPage = $(this).text() * 1;
			
			$('.b-paginator span.page-' + iPage).addClass('selected');
			
			iCurrentPage = iPage;
			showCardsForPage(iCurrentPage);
		}
	});
}
