var colorNormal = 'darkgray';
var colorClash = 'red';
var colorError = '#F06000';

var currentSel = null;
var currentNumber = 1;
var numFilled = 0;

var diffLabels = ['SIMPLE','EASY','MEDIUM','HARD','IMPOSSIBLE'];

var theDifficulty = 0;
var thePuzzle =   [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var theSolution = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];

var isComplete = false;

function tdMouseOver() {
	if (this != currentSel) {
		this.style.backgroundColor = 'yellow';
	}
}

function tdMouseOut() {
	if (this != currentSel) {
		this.style.backgroundColor = 'white';
	}
}

function tdClick() {
	if (this.getAttribute('fixed') != 1) {
		if (this.innerHTML == currentNumber) {
			this.innerHTML = '';
			this.style.color = colorNormal;
			numFilled--;
		}
		else if (!checked) {
			this.innerHTML = currentNumber;
			checkCell(this.getAttribute('idx')-1);
			numFilled++;

			if (numFilled >= 81) {
				checkSolution(false);
			}
		}
	}
}

function tdSelect() {
	if (currentSel) {
		currentSel.style.backgroundColor = 'white';
	}

	currentSel = this;
	currentSel.style.backgroundColor = 'darkgray';
	currentNumber = currentSel.innerHTML;
}

function initGrid() {
	document.getElementById('diff').innerHTML = diffLabels[theDifficulty];
	var cells = document.getElementById('grid').getElementsByTagName('td');

	numFilled = 0;
	for (var i=0; i<cells.length; i++) {
		cells[i].setAttribute('idx', i+1);
		if (thePuzzle[i] != 0) {
			cells[i].innerHTML = thePuzzle[i];
			cells[i].style.color = 'black';
			cells[i].style.fontWeight = 'bold';
			cells[i].setAttribute('fixed', 1);
			numFilled++;
		}
		else {
			cells[i].innerHTML = '&nbsp;';
			cells[i].style.color = colorNormal;
			cells[i].style.fontWeight = 'normal';
			cells[i].setAttribute('fixed', 0);
		}
	}

	startTimer();
}

var theTime = 0;
var theInterval = null
function startTimer() {
	if (theInterval) {
		clearInterval(theInterval);
		theTime = 0;
	}
	theInterval = setInterval(updateTime, 1000);
}

function updateTime() {
	theTime++;

	var secs = theTime % 60;
	var mins = (theTime - secs) / 60;

	document.getElementById('time').innerHTML = mins + ':' + (secs < 10 ? '0' : '') + secs;
}

function resizeTables() {
	var tables = document.getElementsByTagName('table');
	var tdWidth = tables[1].getElementsByTagName('td')[7].offsetWidth;

	for (var k=0; k<2; k++) {
		var cells = tables[k].getElementsByTagName('td');
		for (var j=0; j<9; j++) {
			cells[j].style.width = tdWidth + 'px';
		}
	}

	var w = tables[0].offsetWidth + 'px';
	for (var i=1; i<tables.length; i++) {
		tables[i].style.width = w;
	}
	document.getElementById('full').style.width = w;
}

function showMenu(parent, name) {
	alert(name);
}

function checkCell(idx) {
	var theCell = document.getElementById('grid').getElementsByTagName('td')[idx];
	var val = theCell.innerHTML;

	var row = (idx - (idx % 9)) / 9;
	var col = idx % 9;

	// Check that the same number doesn't exist in the same row and column
	for (var i=0; i<9; i++) {
		if ((getCellValue(row, i) == val && i != col) ||
				(getCellValue(i, col) == val && i != row)) {
			theCell.style.color = colorClash;
			return;
		}
	}

	// ... and the same 3x3 grid
	var gridRow = (row - (row % 3));
	var gridCol = (col - (col % 3));
	for (var i=gridRow; i<gridRow+3; i++) {
		for (var j=gridCol; j<gridCol+3; j++) {
			if (!(i == row && j == col) && getCellValue(i, j) == val) {
				theCell.style.color = colorClash;
				return;
			}
		}
	}

	theCell.style.color = colorNormal;
}

function checkSolution(_mark) {
	isComplete = false;
	var cells = document.getElementById('grid').getElementsByTagName('td');
	for (var i=0; i<81; i++) {
		if (cells[i].innerHTML != theSolution[i]) {
			if (_mark) {
				if (!isNaN(parseInt(cells[i].innerHTML))) {
					cells[i].style.color = colorError;
					cells[i].setAttribute('status', 'error');
				}
			}
			else {
				return;
			}
		}
	}
	
	if (_mark) {
		return;
	}

	document.getElementById('finishTime').innerHTML = document.getElementById('time').innerHTML;

	showDialog('dlgCongrats', true);
	clearInterval(theInterval);
	isComplete = true;
}

function getCellValue(row, col) {
	var idx = (row * 9) + col;
	return document.getElementById('grid').getElementsByTagName('td')[idx].innerHTML;
}

function loadPuzzle(difficulty) {
	var url = 'puzzle.php?d=' + difficulty;
//	AjaxJSON.doGet(url, puzzleLoaded);
	ajDoGet(url, puzzleLoaded);
}

function puzzleLoaded(p)
{
	theDifficulty = p[0];
	if (theDifficulty == -1) {
		alert('Server Error: ' + p[1]);
	}
	else {
		thePuzzle = p[1];
		theSolution = p[2];
		initGrid();
	}
}

function imgHigh(img) {
	img.style.borderColor = 'darkgray';
	img.style.borderStyle = 'outset';
}

function imgLow(img) {
	img.style.borderColor = 'white';
	img.style.borderStyle = 'solid';
}

var paused = 0;
function pause(btn) {
	if (isComplete) {
		return;
	}
	
	if (paused == 0) {
		paused = 1;
		btn.style.backgroundColor = 'silver';
		btn.style.borderStyle = 'inset';
		btn.style.borderColor = 'darkgray';

		showDialog('dlgPaused', false);

		clearInterval(theInterval);
	}
	else {
		paused = 0;
		btn.style.backgroundColor = 'white';
		btn.style.borderStyle = 'outset';
		btn.style.borderColor = 'white';

		hideDialog('dlgPaused');

		theInterval = setInterval(updateTime, 1000);
	}
}

var checked = 0;
function check(btn) {
	if (isComplete) {
		return;
	}
	
	if (checked == 0) {
		checked = 1;
		btn.style.backgroundColor = 'silver';
		btn.style.borderStyle = 'inset';
		btn.style.borderColor = 'darkgray';
		checkSolution(true);
	}
	else {
		checked = 0;
		btn.style.backgroundColor = 'white';
		btn.style.borderStyle = 'outset';
		btn.style.borderColor = 'white';

		var cells = document.getElementById('grid').getElementsByTagName('td');
		for (var i=0; i<81; i++) {
			if (cells[i].getAttribute('status') == 'error') {
				cells[i].style.color = colorNormal;
				cells[i].setAttribute('status', '');
			}
		}
	}
}

function newGame() {
	var difficulty = 0;

	var dlgNew = document.getElementById('dlgNew');
	var radios = dlgNew.getElementsByTagName('input');
	for (var i=0; i<radios.length; i++) {
		if (radios[i].checked) {
			difficulty = radios[i].value;
			break;
		}
	}

	loadPuzzle(difficulty);
}

function resetGame() {
	initGrid();
}

var theDlg = null;

function showDialog(name, full) {
	if (theDlg && theDlg.isVisible())
		theDlg.hide();
		
	theDlg = new Dialog(name, full ? 'full' : 'partial');
	theDlg.show();
}

function hideDialog(name) {
	if (theDlg && theDlg.isVisible())
		theDlg.hide();
}

function keyPressed(e) {
	if (e.which >= 49 && e.which <= 58) {
		var key = e.which - 49;
		document.getElementById('numbers').getElementsByTagName('td')[key].onclick();
	}
}


