/*

	Dave Hill's
	Sudoku Game Javascript
	----------------------
	
	Accepts keys 0-9,W,A,S,D as well as mouse clicks on Cells.
	
	Completely cross browser compatible, works with:
	
	- Firefox 2.0 
	- Firefox 3.0 beta
	- Firefox 3.0 beta for OS X
	- Internet Explorer 6.0
	- Internet Explorer 7.0
	- Internet Explorer 8.0 beta
	- Safari 2.0
	- Safari 3.0
	- Opera 9 (with some keyboard issues)
	
	Notes:
	
	Divs are not allowed to start with numbers as an ID. We have had to start them with a c.
	This has required a few extra string conversions so that we can trim away the unnecesary
	letter.
	
	Internet Explorer has once again caused havoc with easy coding. However I have succeeded.


*/


//Set the puzzle variables
var startThis 		= "000000000000000000000000000000000000000000000000000000000000000000000000000000000";
var completeThis 	= "000000000000000000000000000000000000000000000000000000000000000000000000000000000";

var startEasy	 	= "046280000500600740200000000005032070021000480030170500000000005094001007000096830";
var completeEasy 	= "946287351583619742217543698865432179721965483439178526678324915394851267152796834";

var startNormal 	= "000800017430000000002000900200008000097603480000700005006000100000000048580001000";
var completeNormal 	= "659824317431597826872136954265948731197653482348712695926485173713269548584371269";

var startHard 		= "900001050765000000100300008000006040000218000090400000600004002000000837030100005";
var completeHard 	= "983721654765849321124365798817956243346218579592473186678534912451692837239187465";

//Set the key listeners on the document
document.onkeypress = captureKey;

//Global variable for the last clicked item
var lastClickId;

//Global variable for check count
var checkCount = 0;

//Functions to load the different puzzles
function loadEasy(){checkCount = 0; lastClickId = null; startThis = startEasy; completeThis = completeEasy; go(); setStatus("Easy difficulty selected.");}
function loadNormal(){checkCount = 0; lastClickId = null; startThis = startNormal; completeThis = completeNormal;go(); setStatus("Normal difficulty selected.");}
function loadHard(){checkCount = 0; lastClickId = null; startThis = startHard; completeThis = completeHard;go(); setStatus("Hard difficulty selected.");}
function loadLast(){checkCount = 0; lastClickId = null; go(); setStatus("Puzzle reset.");}

//Function to reset the colours
function resetColours(){for (i = 1; i <= 9; i++){for (j = 1; j <= 9; j++){k = (i*10) + j;el = document.getElementById("c" + k);el.className = el.className.replace("cellCorrect","").replace("cellIncorrect","").replace("cellSelected","");}}}

//Function for loading puzzle
function go(){
	//Clear the board colours to white
	resetColours()

	//Keep track of where we are in the puzzle string
	charCount = 0;
	//For each row
	for (i = 1; i <= 9; i++)
	{
		//For each column
		for (j = 1; j <= 9; j++)
		{
			var k;
			//Get the element ID and the Char for this box
			k = (i*10) + j;
			l = startThis.charAt(charCount);
			if (l=="0") l=" ";
			
			//Print to the box and increase the charcount for the next box
			var el = document.getElementById("c" + k);
			el.innerHTML = l;
			charCount=charCount + 1;
			
			//Add click listener on the box
			el.onclick = cellClick;
		}
	}
}

//Called by the event handler
function cellClick(e)
{	
	//Detect browser
	if(window.event){
		//Internet Explorer.
		lastClickId = window.event.srcElement.id;
	}else{
		//Firefox and others...
		lastClickId = this.id;
	}
	
	lastClickId = lastClickId + "";
	lastClickId = lastClickId.replace("c","")
	//Set the clicked cell
	selectCell();
	
}

function selectCell(){
	//Clear the board to white
	resetColours();
	//Set cell to pale yellow
	var thisCell = document.getElementById("c" + lastClickId);
	thisCell.className = thisCell.className + " cellSelected";
	
	if (thisCell.innerHTML == " " || thisCell.innerHTML == ""){
		cellStatus = "Cell is empty.";
	}else{
		cellStatus = "Contains number " + thisCell.innerHTML + ".";
	}
	var sudokuStatus = document.getElementById('sudokuStatus');
	setStatus("Column " + lastClickId.toString().charAt(1) + " row " + lastClickId.toString().charAt(0) + " selected. "+cellStatus );
}

function moveSelect(moveAmount){
	//Move based upon key numbers, however we need some rules for when we go off the edge.
	//For this we need the direction and where using numbers.
	if (!lastClickId){
		//Always want it to start on cell 11, no matter what they press
		lastClickId = 11;
	}
	else if (moveAmount < 0){
		lastClickId = parseInt(lastClickId) + moveAmount;
		
		if(lastClickId < 10)
		{
			lastClickId = parseInt(lastClickId) + 90;
		}
		
		if(lastClickId == 10){
			lastClickId = 99;
		}
		
		if(lastClickId.toString().charAt(1) == 0){
			lastClickId = parseInt(lastClickId) - 1;
		}
	}
	else if(moveAmount > 0){
		lastClickId = parseInt(lastClickId) + moveAmount;
		
		if(lastClickId > 100)
		{
			lastClickId = parseInt(lastClickId) - 90;
		}
		
		if(lastClickId == 100){
			lastClickId = 11;
		}
		
		if(lastClickId.toString().charAt(1) == 0){
			lastClickId = parseInt(lastClickId) + 1;
		}
	}
	//Rules applied, got the correct cell number, select the cell.
	selectCell()

}

//Called by the event handler
function captureKey(e){
	
	//Detect browser
	if (window.event){
		//Internet explorer
		char = window.event.keyCode;
	}else{	
		//Firefox and others...
		char = e.charCode
	}
	
	//If arrow key pressed
	if(char == 119 || char == 97 || char == 115 || char == 100)
	{
		switch(char){
			case 119: {moveSelect(-10); break;}
			case 97: {moveSelect(-1); break;}
			case 115: {moveSelect(10); break;}
			case 100: {moveSelect(1); break;}
			default: {lastClickId = 11; selectCell(); break;}
		}
	}

	//If 0 to 9 pressed, if 0 then make it a space
	if(char > 47 && char < 58)
	{
		var c;
		c = String.fromCharCode(char);
		if (c=="0") c=" ";
		document.getElementById("c" + lastClickId).innerHTML =c;
	}	
}

//Check current against the complete string
function checkComplete(){


	//Keep track of how many times they have clicked check.
	checkCount++;
	if (checkCount > 3){
		//Clear the board to white
		resetColours();
		
		//Display a game over message.
		setStatus("Game Over! Too many checks.");
	} else {
		
		//Keep track of where we are in the puzzle string
		charCount = 0;
		
		//Keep track of the incorrect count
		incorrectCount = 0;
		
		//For each row
		for (i = 1; i <= 9; i++)
		{
			//For each column
			for (j = 1; j <= 9; j++)
			{
				var k;
				//Get the element ID and the Char for this box
				k = (i*10) + j;
				l = completeThis.charAt(charCount);
				if (l=="0") l=" ";
				
				//Print to the box and increase the charcount for the next box
				var el = document.getElementById("c" + k);
				if (el.innerHTML == l)
				{
					//Correct!
					el.className = el.className + " cellCorrect";
				}else{
					//Incorrect.
					el.className = el.className + " cellIncorrect";
					incorrectCount ++ ;
				}
				charCount=charCount + 1;
				
				if (el.addEventListener) {
					//Decent web browsers...
					el.addEventListener ("click",cellClick,false);
					el.cellid = k;
				} else {
					//Internet Explorer
					el.onclick = cellClick;
					el.cellid = k;
				}
			}
		}
		
		//If no wrong answers, tell them, otherwise tell them how many.
		if(incorrectCount == 0){
			setStatus("Congratulations! Correct answer.");
		}else{
			setStatus(incorrectCount + " errors found.");
		}
	}
}

//Sets the status text above the Sudoku game, accepts a string input.
function setStatus(statusText)
{
	var sudokuStatus = document.getElementById('sudokuStatus');
	return sudokuStatus.innerHTML = statusText;
}
