function loadGrid(puzzle) {
	with(puzzle) {
		return [
			[a1, b1, c1, d1, e1, f1, g1, h1, i1],
			[a2, b2, c2, d2, e2, f2, g2, h2, i2],
			[a3, b3, c3, d3, e3, f3, g3, h3, i3],
			[a4, b4, c4, d4, e4, f4, g4, h4, i4],
			[a5, b5, c5, d5, e5, f5, g5, h5, i5],
			[a6, b6, c6, d6, e6, f6, g6, h6, i6],
			[a7, b7, c7, d7, e7, f7, g7, h7, i7],
			[a8, b8, c8, d8, e8, f8, g8, h8, i8],
			[a9, b9, c9, d9, e9, f9, g9, h9, i9],
			[a1, a2, a3, a4, a5, a6, a7, a8, a9],
			[b1, b2, b3, b4, b5, b6, b7, b8, b9],
			[c1, c2, c3, c4, c5, c6, c7, c8, c9],
			[d1, d2, d3, d4, d5, d6, d7, d8, d9],
			[e1, e2, e3, e4, e5, e6, e7, e8, e9],
			[f1, f2, f3, f4, f5, f6, f7, f8, f9],
			[g1, g2, g3, g4, g5, g6, g7, g8, g9],
			[h1, h2, h3, h4, h5, h6, h7, h8, h9],
			[i1, i2, i3, i4, i5, i6, i7, i8, i9],
			[a1, b1, c1, a2, b2, c2, a3, b3, c3],
			[d1, e1, f1, d2, e2, f2, d3, e3, f3],
			[g1, h1, i1, g2, h2, i2, g3, h3, i3],
			[a4, b4, c4, a5, b5, c5, a6, b6, c6],
			[d4, e4, f4, d5, e5, f5, d6, e6, f6],
			[g4, h4, i4, g5, h5, i5, g6, h6, i6],
			[a7, b7, c7, a8, b8, c8, a9, b9, c9],
			[d7, e7, f7, d8, e8, f8, d9, e9, f9],
			[g7, h7, i7, g8, h8, i8, g9, h9, i9]
		];
	}
}

function checkSudoku(puzzle) {
	// debug
	//var dbg = window.open().document;

	var grid = loadGrid(puzzle);
	var firstBlank;

	for (var line = 0; line < grid.length; line++) {
		var used = new Array;
		for (var index = 0; index < 9; index++) {
			var cell = grid[line][index];
			//alert(cell);
			//dbg.write(cell.name);

			if (cell.value == '') {
				if (!firstBlank) {
					firstBlank = cell;
				}
			} else if (cell.value.length > 1
				  || cell.value < '1' || cell.value > '9') {
				alert('Invalid value in cell ' + cell.name + '.');
				cell.focus();
				return;
			} else {
				var val = parseInt(cell.value);
				if (used[val]) {
					alert('Duplicate value in cells ' + used[val].name
					  + ' and ' + cell.name + '.');
					if (used[val].type == 'text') {
						used[val].focus();
					} else {
						cell.focus();
					}
					return;
				} else {
					used[val] = cell;
				}
			}
		}
	}

	if (firstBlank) {
		alert('Looks good so far.  Keep going!');
		firstBlank.focus();
	} else {
		alert('Well done, you\'ve solved it!');
	}
}


function clearSudoku(puzzle) {
	var grid = loadGrid(puzzle);

	for (var row = 0; row < 9; row++) {
		for (var cell = 0; cell < 9; cell++) {
			if (grid[row][cell].type == 'text') {
				grid[row][cell].value = '';
			}
		}
	}
}

