var game_finished=0;
function f_check_game()
{
	f_resetClassName();
	error = 0;
	for(var i = 0; i < 81; i++)
	{
		var cell = document.getElementById('cell' + i.toString());
						
		if ((cell.value.length != 1) || (cell.className == 'insumark'))
			continue;
			
		if (cell.value != solution.charAt(i))
		{
			document.getElementById('td' + i.toString()).className = origTDStyles[i] + ' wrongTD'; 
			curTDStyles[i] = document.getElementById('td'+i.toString()).className;	
			error++;
		}
	}
	if (error == 0){
		document.getElementById('TopMessage').innerHTML = "Great job! No Error. Keep going.";
		document.getElementById('error_img').style.display="none";
		document.getElementById('success_img').style.display="";
		document.getElementById('TopMessage_tbl').className = "CongratMessage";

	}
	else if (error == 1)
		error_Message("Found " + error.toString() + " error. Highlighted in red.");
	else
		error_Message("Found " + error.toString() + " errors. Highlighted in red.");
}

function f_Mark(cell_no)
{
	var cell = document.getElementById('cell' + cell_no.toString());
	var v = cell.value;
	
	if (v.length != 1) return true;
		
	if (cell.className != 'insumark')
	{			
		f_resetClassName();
		cell.className = 'insumark'; 
	}	
	else check_input(cell_no);
}

function check_input(cell_no)
{
	var cell = document.getElementById('cell' + cell_no.toString());
	var v = cell.value;
	
	f_resetClassName();
	cell.className = 'insu'; 
	
	if (v == '')
		return true;
		
	if (v.length > 1) 
	{
		cell.className = 'insumark'; 
		return true;
	}
	
	game = get_CurrentGame();
	game = game.substr(0, cell_no) + v + game.substr(cell_no+1, 81);
	undo_stack.push(cell_no);
	
	if (game == solution)
	{
		cell.blur();
		f_show_winner();
		game_finished=1;
		return true;
	}
	
	digits=/[123456789]/;
	if( (v.length > 0) && (!digits.test(v)))
	{	
		error_Message("Invalid entry!");
		cell.value = "";
		return false;	
	}
	
	var row = row_num(cell_no);
	for (var i = row*9; i < (row+1)*9; i++)
	{
		if (( i != cell_no ) && (game.charAt(i) == v))
		{ 
			// found a duplicate in a row
			f_warn('row',cell_no);
			break;
		} 
	}

	var col = col_num(cell_no);
	for (var i = 0; i < 9; i++)
	{
		if (((i*9+col) != cell_no) && (game.charAt(i*9+col) == v))
		{
			f_warn('col',cell_no);
			break;
		}
	} 

	var startBlock = start_block_num(cell_no);

	for (var i = startBlock; i < (startBlock + 3 + 2*9); i += 9) 
	{
		for (var j = 0; j < 3; j++)
		{
			if (((i+j) != cell_no) && (v == game.charAt(i+j)))
			{
				f_warn('block',cell_no);
				break;
			}
		}
	}
	
	cell.className = origCellStyles[cell_no];
	return true;
}

function row_num(c)
{
   return (c - (c % 9)) / 9;
}

function col_num(c)
{   
	return c % 9;
}

function block_num(c)
{ 	//returns block number 0 to 8 from left to right and top to bottom
	var row = row_num(c);
	var col = col_num(c);
	return (row - row%3)+(col - col%3)/3;
}

function start_block_num(c)
{
	return ((Math.floor(c / 27) * 27) + (Math.floor(col_num(c) / 3) * 3));
}

function f_hint()
{
	if(game_finished==1)
		return true;
	f_resetClassName();
	game = get_CurrentGame();
	
	var i = 0;
	var loop = true;
	var c = 0;
	
	for(i = 0; i < 81; i++)
	{
		var cell = document.getElementById('cell'+i);
		if ((!cell.readOnly) && (cell.value == ""))
			c++;
	}

	var ran_number = Math.floor(Math.random()*c);
	i = 0;
	var r = 0;
	
	while ((i < 81) && (loop == true))
	{
		var cell = document.getElementById('cell'+i.toString());

		if ((!cell.readOnly) && (cell.value == ""))
		{
			if (r >= ran_number)
			{
				document.getElementById('cell'+i.toString()).value = solution.charAt(i);
				document.getElementById('cell' + i.toString()).className = origCellStyles[i] + ' insuHint';
				game = game.substr(0, i) + solution.charAt(i) + game.substr(i+1, 81);
				undo_stack.push(i);
				loop = false;
			}
			else r++;
		}
		i++;
	}
}

function f_reset_grid()
{
  //Tam disable this so the grid is reset even the game is finished 2007.02.22
	//if(game_finished==1)
	//	return true;
	if (get_CurrentGame() != solution)
	{
		ans = window.confirm("Are you sure you want to abandon the current game and reset the grid?");
		if (!ans)
			return;
	}
	
	document.frm.reset();
	f_resetClassName();
}

function f_print()
{
	window.open('print.php?game_id='+ get_CurrentLevel()+ game_id.toString(), 'Print');
}

function f_solution()
{
	if(game_finished==1)
		return true;
	if (get_CurrentGame() != solution)
	{
		ans = window.confirm("Are you sure you want to view the solution of the current game?");
		if (!ans)
			return;
	}

	for(var i = 0; i < 81; i++)
	{
		if (document.getElementById('cell'+i.toString()).className == 'insumark')
			document.getElementById('cell'+i.toString()).className = 'insu'; 
	}

	f_resetClassName();
	
	for(var i = 0; i < 81; i++)
	{
		var cell=document.getElementById('cell'+i.toString());
		if (!cell.readOnly)
		{
			document.getElementById('cell'+i).value = solution.charAt(i);
			document.getElementById('cell'+i).className = origCellStyles[i] + ' insuHint';    
		}    
	}
}

function f_undo()
{
	if(game_finished==1)
		return true;
	f_resetClassName();
	cell_no = undo_stack.pop();
	if (typeof cell_no != 'undefined')
	{
		document.getElementById('cell'+cell_no.toString()).value = '';
		document.getElementById('cell'+cell_no.toString()).className = origCellStyles[cell_no]; 
	} 
}

function f_solve_puzzle()
{
	initial_game = get_CurrentGame();
	game = "";
	cell_counter = 0;
	
	game_arr = new Array(81);
	
	for (i = 0; i < 81; i++)
	{
		var v = document.getElementById('cell'+i).value;
		if (v.length == 1) 
			game_arr[i] =  v;
		else
			game_arr[i] =  0;
	}
	
	direction = 1;
	f_solve();	
}

function f_solve()
{
	while ((cell_counter >= 0) && (cell_counter <81) && (initial_game.charAt(cell_counter) != '0') )
	{
		cell_counter += direction;
	}
	
	if (cell_counter < 0) 
	{
		alert('This Sudoku puzzle cannot be solved');
		return false;
	}
	else if (cell_counter >= 81) 
	{
		alert('This Sudoku puzzle has been successfully solved');
		return true;
	}

	while (game_arr[cell_counter] < 10)
	{
		game_arr[cell_counter] += 1;
		if (game_arr[cell_counter] == 10)
		{
			game_arr[cell_counter] = 0;
			document.getElementById('cell' + cell_counter).value='';
			direction = -1; // backtracking
			break;
		}

		document.getElementById('cell' + cell_counter).value = game_arr[cell_counter];//shown puzzle
		
		//check_valid sudoku
		isValid = true;
		
		var row = row_num(cell_counter);
		for (i = row*9; i < (row+1)*9; i++)
		{
			if ((i != cell_counter ) && (game_arr[cell_counter] == game_arr[i]))
			{ 
				// found a duplicate in a row
				isValid = false;
				break;
			} 
			
		}
		
		if (!isValid)
			continue;
			
		var col = col_num(cell_counter);
		for (var i = 0; i < 9; i++)
		{
			if (((i*9 + col) != cell_counter) && (game_arr[cell_counter] == game_arr[i*9+col])) 
			{
				// found a duplicate in a col
				isValid = false;
				break;
			}
		} 
	
		if (!isValid)
			continue;
			
		var startBlock = start_block_num(cell_counter);
	
		for (var i = startBlock; (i < (startBlock + 3 + 2*9)) && isValid; i += 9) 
		{
			for (var j = 0; j < 3; j++)
			{
				if (((i+j) != cell_counter) && (game_arr[cell_counter] == game_arr[i+j]))
				{
					// found a duplicate in a block
					isValid = false;
					break;
				}
			}
		}
		
		if (isValid)
		{
			direction = 1;
			break;
		}
	}
	
	cell_counter += direction;
	if ((cell_counter >= 0) || (cell_counter < 81)) window.setTimeout(f_solve, 3);
}

function f_new_game()
{

  if(page_name!="index"){
//	if(1==2){
		game_finished=0;
		document.rightbar.submit();
	}
	else{
	if (get_CurrentGame() != solution) 
	{
		ans = window.confirm("Are you sure to start a new game?");
		if (!ans)
			return;
	}
	game_finished=0;
	SetCookie("cookieLevel", get_CurrentLevel(), 3650);
	//document.frm.submit();
	document.getElementById("CongratDiv").style.display = 'none';
	var url = 'rpc.php?level='+ get_CurrentLevel() + '&sid=' + Math.random();
	loadXMLDoc(url);
	undo_stack = new Array();
	document.body.style.cursor = 'wait';
	}
}

function get_CurrentGame()
{
	lgame = "";
	for (i = 0; i < 81; i++)
	{
		var v = document.getElementById('cell'+i).value;
		if ((v.length == 1) && (document.getElementById('cell'+i).className != 'insumark'))
			lgame = lgame + v;
		else
			lgame = lgame + "0";
	}
	
	return lgame;
}

function get_CurrentLevel()
{
	if (document.getElementById('level1').checked)
		return 1;
	else if (document.getElementById('level2').checked)
		return 2;
	else if (document.getElementById('level3').checked)
		return 3;
	else if (document.getElementById('level4').checked)
		return 4;

	//return getRadioCheckedValue(document.forms['frm'].elements['level']);
}

function error_Message(errStr)
{ 
	document.getElementById('TopMessage').innerHTML = errStr;
	if(errStr!="&nbsp;"){
		document.getElementById('error_img').style.display="";
		document.getElementById('success_img').style.display="none";
		document.getElementById('TopMessage_tbl').className = "WarnMessage";
	}
	else{
		document.getElementById('error_img').style.display="none";
		document.getElementById('success_img').style.display="none";
	}
}

function getRadioCheckedValue(radioObj)
{
	if(!radioObj)
		return "";
		
	var radioLength = radioObj.length;
	
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	
	for(var i = 0; i < radioLength; i++)
	{
		if(radioObj[i].checked) 
		{
			return radioObj[i].value;
		}
	}
	
	return "";
}

function SetCookie(cookieName, cookieValue, nDays) 
{
	var today = new Date();
	var expire = new Date();
	
	if (nDays == null || nDays == 0) 
		nDays=1;
		
	expire.setTime(today.getTime() + 3600000*24*nDays);
	
	document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
}

function highlight(i)
{
	if(!document.getElementById('chk_highlight').checked)
		return true;
	
	for(var j = 0; j < 81; j++)
	{
		if((row_num(j)==row_num(i)) || (col_num(j)==col_num(i)) || ( block_num(j)==block_num(i)))
		{
			document.getElementById('td'+j.toString()).className = origTDStyles[j] + ' highlightTD';
		}
	}

	document.getElementById('td'+i.toString()).className = origTDStyles[i] + ' highlightTDCell';
}

function dehighlight(i)
{
	if(!document.getElementById('chk_highlight').checked)
		return true;

	for(var j = 0; j < 81; j++)
	{
		document.getElementById('td'+j.toString()).className = curTDStyles[j];				
	}
}

function f_warn(elem_type, cell_no)
{
	if(!document.getElementById('chk_warning').checked)
		return true;
		
	for(var i = 0; i < 81; i++)
	{
		if( ((elem_type=='row') && (row_num(i)==row_num(cell_no))) ||
		    ((elem_type=='col') && (col_num(i)==col_num(cell_no))) ||
		    ((elem_type=='block') && (block_num(i)==block_num(cell_no))) )
		{
			if (getValueAt(cell_no) == getValueAt(i))
				document.getElementById('td'+i.toString()).className =  origTDStyles[i] + ' warningTD';
			//else
				//document.getElementById('td'+i.toString()).className =  origTDStyles[i] + ' warningTD';
	
			curTDStyles[i] = document.getElementById('td'+i.toString()).className;	
		}
	}

	error_Message("You have made some duplicates, highlighted in red!");
}

function f_resetClassName()
{
	error_Message('&nbsp;');
	for(var i = 0; i < 81; i++)
	{
		document.getElementById('td'+i.toString()).className =  origTDStyles[i]; 
		curTDStyles[i] = document.getElementById('td'+i.toString()).className;
	}
}

function getValueAt(cell_no)
{
	var cell = document.getElementById('cell' + cell_no.toString());
	var v = cell.value;
	if ((v.length == 1) && (cell.className != 'insumark'))
		return v;
	else
		return '0';
}

function f_ChangeSize(mult)
{
	if(game_finished==1)
		return true;

	lCSSRule = hFindCSSRule('table.su td');
	
	if((parseFloat(lCSSRule.style.width)<16)&&(mult<1))
		return true;
	else if((parseFloat(lCSSRule.style.width)>40)&&(mult>=1))
		return true;
	else{

	sizeMult = sizeMult*mult;
	SetCookie("savedMult", sizeMult, 3650);
	

	lCSSRule = hFindCSSRule('input.insu');
	lCSSRule.style.fontSize = (origInsuFS*sizeMult).toString() + 'px';
	lCSSRule.style.width =  (origInsuWidth*sizeMult).toString() + 'px';
	lCSSRule.style.height =  (origInsuHeight*sizeMult).toString() + 'px';
	
	lCSSRule = hFindCSSRule('input.insuro');
	lCSSRule.style.fontSize = (origInsuRoFS*sizeMult).toString() + 'px';
	lCSSRule.style.width =  (origInsuRoWidth*sizeMult).toString() + 'px';
	lCSSRule.style.height =  (origInsuRoHeight*sizeMult).toString() + 'px';

	lCSSRule = hFindCSSRule('input.insumark');
	lCSSRule.style.fontSize = (origInsuMarkFS*sizeMult).toString() + 'px';
	lCSSRule.style.width =  (origInsuMarkWidth*sizeMult).toString() + 'px';
	lCSSRule.style.height =  (origInsuMarkHeight*sizeMult).toString() + 'px';
	
	lCSSRule = hFindCSSRule('table.su td');
	lCSSRule.style.width =  (origsuTDWidth*sizeMult).toString() + 'px';
	lCSSRule.style.height =  (origsuTDHeight*sizeMult).toString() + 'px';
	//error_Message('sizeMult: ' + sizeMult.toString() + ' new size: '+ lCSSRule.style.width+ ' '+ lCSSRule.style.height);
	}
}

function hFindCSSRule(selectorText)
{
	for (i = 0; i < document.styleSheets.length; i++)
	{
		var mySheet = document.styleSheets[i];
		var myRules = mySheet.cssRules ? mySheet.cssRules : mySheet.rules;
		
		for (var j = 0; j < myRules.length; j++)
		{
			if (myRules[j].selectorText.toLowerCase() == selectorText)
			{ 
				return myRules[j];
			}
		}
	}
}
timerID=0;
CongratDivHeight=0;
IntervalHeight=0;
function f_show_winner()
{

/*
	if(navigator.userAgent.indexOf("Firefox")!=-1)
	alert('firefox');
	else alert('ie');
*/
	document.getElementById('TopMessage').innerHTML = "Congratulation! you have solved this game";
	document.getElementById('success_img').style.display="";
	document.getElementById('error_img').style.display="none";
	document.getElementById('TopMessage_tbl').className = "CongratMessage";
	if(navigator.userAgent.indexOf("MSIE")!=-1)
		return true;
//	alert(document.getElementById('GameBoard').style.width);
	lCSSRule = hFindCSSRule('input.insu');
	w = parseFloat(lCSSRule.style.width);
	s = parseFloat(lCSSRule.style.fontSize);
	document.getElementById('CongratDiv').style.top = '0px';
	if(navigator.userAgent.indexOf("Firefox")!=-1)
		document.getElementById('CongratDiv').style.left = (document.getElementById('GameTable').offsetLeft).toString()+'px';
	else
//		document.getElementById('CongratDiv').style.left = (document.getElementById('GameTable').offsetLeft).toString()+'px';
//		document.getElementById('CongratDiv').style.left = (-document.getElementById('GameTable').offsetWidth).toString()+'px';
		document.getElementById('CongratDiv').style.left = '1px';
	document.getElementById('CongratTable').style.width=(document.getElementById('GameTable').offsetWidth).toString()+'px';
	IntervalHeight = document.getElementById('GameTable').offsetHeight/50;
	CongratDivHeight=IntervalHeight;
	timerID=setTimeout('f_show_CongratDiv();', 1000);

	document.getElementById('CongratDiv').style.fontSize=s.toString()+'px';
	document.getElementById('CongratDiv').style.display= 'inline';
	document.getElementById('GameTable').style.Opacity=.1;
	document.getElementById('CongratDiv').focus();
}
function f_show_CongratDiv(){
	if(CongratDivHeight<document.getElementById('GameTable').offsetHeight){
		document.getElementById('CongratTable').style.height = CongratDivHeight.toString()+'px';
		timerID=setTimeout('f_show_CongratDiv();', 50);
	}
	else{
		document.getElementById('CongratTable').style.height = document.getElementById('GameTable').offsetHeight.toString()+'px';
		timerID=clearTimeout(timerID);
		timerID=setTimeout('f_show_CongratMessage();', 300);

		
	}
	CongratDivHeight=CongratDivHeight+IntervalHeight;
	//alert(CongratDivHeight);
}
function f_show_CongratMessage(){
		//document.getElementById('CongratMessage').style.Opacity= 1;
		document.getElementById('CongratMessage').style.display= 'inline';
}
var req;

function loadXMLDoc(url) 
{
	req = false;

    if(window.XMLHttpRequest) 
	{
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }		
    } 
	else if(window.ActiveXObject) 
	{
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} 
		catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} 
			catch(e) {
          		req = false;
        	}
		}
    }
	
	if(req) 
	{
		req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send(null);
	}
}

function processReqChange() {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var response = req.responseText;
			data = response.split('|');
			document.getElementById('levelName').innerHTML = data[0]+' puzzle ' +data[1]+' - Difficulty: '+data[2];			
			game_id = data[3];
			solution = data[4];
			document.getElementById('GameBoard').innerHTML = data[5];			
			getOrigStyles();
			f_resetClassName();
			document.body.style.cursor = 'default';
        } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
        }
    }
}

function getOrigStyles()
{
	for(var i = 0; i < 81; i++)
	{
		origTDStyles[i] = document.getElementById('td'+i.toString()).className;
		origCellStyles[i] = document.getElementById('cell'+i.toString()).className;
		curTDStyles[i] = origTDStyles[i];
	}
}

function hSaveOrigCSS()
{
	lCSSRule = hFindCSSRule('input.insu');
	origInsuFS = parseFloat(lCSSRule.style.fontSize);
	origInsuWidth = parseFloat(lCSSRule.style.width);
	origInsuHeight = parseFloat(lCSSRule.style.height);

	lCSSRule = hFindCSSRule('input.insuro');
	origInsuRoFS = parseFloat(lCSSRule.style.fontSize);
	origInsuRoWidth = parseFloat(lCSSRule.style.width);
	origInsuRoHeight = parseFloat(lCSSRule.style.height);

	lCSSRule = hFindCSSRule('input.insumark');
	origInsuMarkFS = parseFloat(lCSSRule.style.fontSize);
	origInsuMarkWidth = parseFloat(lCSSRule.style.width);
	origInsuMarkHeight = parseFloat(lCSSRule.style.height);

	lCSSRule = hFindCSSRule('table.su td');
	origsuTDWidth = parseFloat(lCSSRule.style.width);
	origsuTDHeight = parseFloat(lCSSRule.style.height);
}
function f_chk_highlight(){
  if(document.getElementById('chk_highlight').checked)
      SetCookie("cookie_chk_highlight", 'on', 3650);
  else
      SetCookie("cookie_chk_highlight", '', 3650);
  
}
function f_chk_warning(){
  if(document.getElementById('chk_warning').checked)
      SetCookie("cookie_chk_warning", 'on', 3650);
  else
      SetCookie("cookie_chk_warning", '', 3650);  
  
}
