var verifyInProgress = false;

function newGame (type) {
	$('#gamestatus').load('/mod/kanagame/x/?new='+type);
	loadGame();
}

function loadGame (){
	url = '/mod/kanagame/x/?load';
 	$.getJSON(url,'',function(json) {
		if (json[10] > 0) playGame(json);
		else endGame(); 
    });
}

function endGame () {
	$("#gamedeck").load('/mod/kanagame/x/?end');
	$('#gamestatus').html('');
}

function playGame (json) {
	$("#gamedeck").html('');
 	cards = new Array(9);
	for (i = 0; i < 9; i++) {
		cards[i] = getCard(json[i]);
		cards[i].attr('id','card-'+i)
		.animate({opacity: 1
    			}, (Math.random() * 1500) );
    		if (i != 4) 
    	cards[i].click(function () {verify(this);});
    	$("#gamedeck").append(cards[i]);
		if ( i % 3 == 0 ) cards[i].css('clear','both');
	}
	$('#correctKey').val(json[i]);
	
	if (json[12] > 0) gameStatus = '; Klaidos: ' + json[12];
	else gameStatus = '';
	$('#gamestatus').html('<br/><b>Liko: ' + json[10] + ' iš ' + json[11]  + gameStatus + '</b>');
}

function clearDeck () {
	for(i = 0; i< 9; i++) {
	$("#card-"+i).animate({ opacity: 0 }, (Math.random() * 1000) );
	}
}

function nextDeck (x,color) {
      	$(x).animate({ 
 			backgroundColor: color,
        	opacity: 0
      		}, 1500 , function() {
      			clearDeck();
     		}).
      		animate ( {opacity: 0}, 1000, function() {
      			loadGame();	
      		});
}

function getCard (x) {
	return $('<div class="card"><p>'+x+'</p></div>').css('opacity','0');
	}
	
function verify(x) {
	if (!verifyInProgress) verifyInProgress = true;
	else return;
	ret = -1;
	url = '/mod/kanagame/x/?verify='+$(x).attr('id')+'&hash='+$("#correctKey").val();
	$.getJSON(url,'',function(json) {
		if ( json[0] ) color = "#00ff00";
		else color = "#ee0000";
		nextDeck (x,color);
    });
    verifyInProgress = false;
}
