var puzzle = [];
var zeropos = 15;
var background = "";
var moves = 0;
var done = false;

function array_range(a, b) {
	var c = [];
	for (var i=a; i<=b; ++i)
		c.push(i);
	return c;
}

function game_over() {
	var over = true;
	$.each(puzzle, function (i, item) {
		if (item != i)
			over = false;
	})
	return over;
}

function swap_puzzle(x, flag) {
	var tmp = puzzle[x];
	puzzle[x] = puzzle[zeropos];
	puzzle[zeropos] = tmp;
	if (flag) {
		$('#cell' + x)
			.removeClass("cell" + puzzle[zeropos])
			.addClass("cellempty")
			.css({backgroundImage: "url()"});
		$('#cell' + zeropos)
			.removeClass("cellempty")
			.addClass("cell" + puzzle[zeropos])
			.css({backgroundImage: background});
		if (game_over()) {
			$("#cell15")
			  .removeClass("cellempty")
			  .addClass("cell15")
			  .css({backgroundImage: background});
			alert("Congratulations!");
// 			alert("Congratulations! You solved the puzzle in " + moves + " moves!");
			done = true;
		}
	};
	zeropos = x;
}

function shuffle() {
	for (var i = 0; i < 150; i++) {
		// build list of possible swap positions
		var a = [];
		if (Math.floor(zeropos / 4) != 0) a.push(zeropos - 4);
		if (Math.floor(zeropos / 4) != 3) a.push(zeropos + 4);
		if (zeropos % 4 != 0) a.push(zeropos - 1);
		if (zeropos % 4 != 3) a.push(zeropos + 1);
		// pick one at random and swap
		swap_puzzle(a[Math.floor(Math.random() * a.length)], false);
	};
}

function click_cell(x) {
	if (done)
		return;
	if(x == zeropos - 4) return swap_puzzle(zeropos - 4, true);
	if(x == zeropos + 4) return swap_puzzle(zeropos + 4, true);
	if(x == zeropos - 1) return swap_puzzle(zeropos - 1, true);
	if(x == zeropos + 1) return swap_puzzle(zeropos + 1, true);
	// click in same row
	if (Math.floor(x/4) == Math.floor(zeropos/4)) {
		if (x < zeropos)
			for (var i=zeropos-1; i>=x; --i)
				click_cell(i);
		else
			for (var i=zeropos+1; i<=x; ++i)
				click_cell(i);
	}
	// click in same column
	else if (x % 4 == zeropos % 4) {
		if (x < zeropos)
			for (var i=zeropos-4; i>=x; i -= 4)
				click_cell(i);
		else
			for (var i=zeropos+4; i<=x; i += 4)
				click_cell(i);
	}
}

function begin(photo) {
	puzzle = array_range(0, 15);
	zeropos = 15;
	background = "url(images/" + photo + ")";
	shuffle();
	$.each(array_range(0, 15), function(i, x) {
		var div = $("<div>")
			.attr({id: "cell"+i})
			.click(function () {
					click_cell(i);
					++moves;
					return false;
				});
		if (i == zeropos)
			div.addClass("cell cellempty");
        else {
			div.addClass("cell cell"+puzzle[i])
			div.css({backgroundImage: background});
		}
		$('#main').append(div);
	});
	done = false;
}

