var ctx = gra.getContext('2d');
var keys = [];

setInterval(function(){	
	if(keys[38]) player.dir="up";
	if(keys[40]) player.dir="down";
	if(keys[37]) player.dir="left";
	if(keys[39]) player.dir="right";
	
	if(player.dir!="none"){
		if(player.dir=="up") player.y-=0.03;
		if(player.dir=="down") player.y+=0.03;
		if(player.dir=="left") player.x-=0.03;
		if(player.dir=="right") player.x+=0.03;
		
		player.count+=0.03;
		
		if(player.count>=1) player.count = 0, player.dir="none", console.log("AJAX"), sendData("game.php?p=move&x="+player.x+"&y="+player.y, false);
	}
	
	ctx.clearRect(0,0, 640, 480);
				
	if(typeof gameData!="undefined"){
		for(var e in gameData.players){
			if(e!=player.login){
				var otherPlayer = gameData.players[e];
				ctx.fillStyle = "#000000";
				ctx.fillText(otherPlayer.login, otherPlayer.x*40, otherPlayer.y*40-5); // -5, aby tekst był na bardziej górze
				ctx.fillStyle = otherPlayer.color;
				ctx.fillRect(otherPlayer.x*40, otherPlayer.y*40,40,40);
			}else{
				ctx.fillStyle = "#000000";
				ctx.fillText(player.login, player.x*40, player.y*40-5); // -5, aby tekst był na bardziej górze
				ctx.fillStyle = player.color;
				ctx.fillRect(player.x*40, player.y*40,40,40);
			}
		}
	}
},1000/60);

setInterval(function(){
	sendData("game.php?", true);
},1000);

function sendData(url, loadGameData){
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function() {
		if(this.readyState == 4 && this.status == 200) {
			if(loadGameData){
				gameData = JSON.parse(this.responseText);
				//console.log(this.responseText);
			}
		}
	};
	xmlhttp.open("GET", url, true);
	xmlhttp.send();
}

window.addEventListener('keydown', function(e){
	keys[e.keyCode] = true;
});

window.addEventListener('keyup', function(e){
	delete keys[e.keyCode];
});
