var ppm_dim = 17;

function doError(message) {
    $("#error").css("display", "block").text(message);
    allIsSane = false;
}

function updateMatrix(arr) {
    lastModification = arr[0];
    for(y = 0; y < ppm_dim; y++) {
        for(x = 0; x < ppm_dim; x++) {
           var f = arr[y+1][x];
           if(f == "0") {
                $("#" + x + "-" + y).attr("src", "gfx/gridOff.png");
           } else {
                $("#" + x + "-" + y).attr("src", "gfx/gridOn.png");
           }
        }
    }
}

function clickMatrix(x,y)
{
if(allIsSane) {

$.ajax({
	url: 'click.php?x=' + x + '&y=' + y + '&lastModification=' + lastModification ,
	type: 'POST',
	dataType: 'html',
	data: "",
	timeout: 1000,
	error: function(){
	    doError("Sorry, communication with web server failed. Please refresh the page.");
	},
	success: function(res){
	    if(res == "CONFLICT") {
	        doError("There seem to be edit conflicts. Public Pixel Matrix is not designed to be edited by several people at once. Sorry, I know this sucks!");
	    } else if(res == "ERROR") {
	        doError("This error should never happen. But well, it did! So what now?");
	    } else {
	        arr = res.split("\n");
	        if(arr[0] >= lastModification) {
	            updateMatrix(arr);
	        }
	    }
	}
    });
}
}

