/************************************************************************/
/*                                                                      */
/* Copyright 2007-2009 by Stan Reckard     (www.artbylogic.com)              */
/*                                                                      */
/* This file and its contents are copyrighted by Stan Reckard, all      */
/* rights reserved. No content, programming code or images may be sold, */
/* published or distributed without express permission from the author. */
/* Do not remove copyright notices.  By violating these terms you may   */
/* be held liable for any resulting loss or damage.                     */
/*                                                                      */
/* No support, guarantee or warranty is offered or implied. By using    */
/* any of this code you assume full risk and responsibility for that    */
/* use.                                                                 */
/*                                                                      */
/************************************************************************/

var reset = false;
var centerBackground;
var outTableMargin;
var navBarDivDisplay;
var mainTblW;
var outTableW;

function restoreLastRating(currRating) {
	
	var rating = readCookie("rating");
	if (rating) {
		// found the cookie
		//alert('found cookie rating =' + rating);
		
		// Make sure the value of the cookie is a valid rating
		var difficultyArr = new Array('Easiest[1]', 'Easy[1]', 'Easy[2]', 	'Medium[1]', 'Medium[2]', 
							   'Hard[1]', 'Hard[2]', 'Hard[3]', 'Hard[4]', 'Hard[5]', 
							   'VeryHard[3]', 'VeryHard[4]', 'Grueling[1]', 'Grueling[2]');
		var cnt = difficultyArr.length;

		var cRating = "Easiest[1]";  // default
		//var cRating = document.sudoku.rating.value;  // the default is the current rating
		for (var k=0; k < cnt; k++) {
			if (difficultyArr[k] == rating) {
				cRating = difficultyArr[k];
				break;
			}
		}
		rating = cRating;
		
		
		//var el = document.getElementById('ratingPick');
		if (currRating != rating) {
			//document.sudoku.rating.value = rating;  // assign it
			
			// Allow users to bookmark a category and level of difficulty
			//document.sudoku.action = "dailySudoku.htm?rating=" + rating;
			//document.sudoku.submit();
			location.href = "dailySudoku.htm?rating=" + rating;
		}
	}

}  // end restoreLastRating



// Initialization for the puzzle
function initPuzzle() {
	// If there is a cookie named "rating" then retrieve the rating and initialize the puzzle to that rating
	//var rating = readCookie("rating");
	//if (rating) {
	//	// found the cookie
	//	//alert('found cookie rating =' + rating);
	//	
	//	// Make sure the value of the cookie is a valid rating
	//	var difficultyArr = new Array('Easiest[1]', 'Easy[1]', 'Easy[2]', 	'Medium[1]', 'Medium[2]', 
	//						   'Hard[1]', 'Hard[2]', 'Hard[3]', 'Hard[4]', 'Hard[5]', 
	//						   'VeryHard[3]', 'VeryHard[4]', 'Grueling[1]', 'Grueling[2]');
	//	var cnt = difficultyArr.length;
	//
	//	var cRating = document.sudoku.rating.value;  // the default is the current rating
	//	for (var k=0; k < cnt; k++) {
	//		if (difficultyArr[k] == rating) {
	//			cRating = difficultyArr[k];
	//			break;
	//		}
	//	}
	//	rating = cRating;
	//	
	//	
	//	var el = document.getElementById('ratingPick');
	//	if (el) {
	//		if (document.sudoku.rating.value != rating) {
	//			document.sudoku.rating.value = rating;  // assign it
	//			
	//			// Allow users to bookmark a category and level of difficulty
	//			document.sudoku.action = "dailySudoku.htm?rating=" + rating;
	//			document.sudoku.submit();
	//			
	//			return false;  // we don't want it to submit again so tell it not to.
	//		}
	//	}
	//}

	checkComplete(true);
	if (typeof(setSudokuFocus) == "function")
		setSudokuFocus();   
	reset = false;
	
	return true;
}


function gotoPuzzle(puzzIdx) {
  document.sudoku.pln.value = puzzIdx;  // puzzle index 
  document.sudoku.submit();	
}


function prevRating(rating) {

	var difficultyArr = new Array('Easiest[1]', 'Easy[1]', 'Easy[2]', 	'Medium[1]', 'Medium[2]', 
	                       'Hard[1]', 'Hard[2]', 'Hard[3]', 'Hard[4]', 'Hard[5]', 
						   'VeryHard[3]', 'VeryHard[4]', 'Grueling[1]', 'Grueling[2]');
	var cnt = difficultyArr.length;

	var pRating = rating;
	// Don't start at 0 since we can't go previous to the first one.
	for (var k=1; k < cnt; k++) {
		//alert(difficultyArr[k]);
		if (difficultyArr[k] == rating) {
			pRating = difficultyArr[k-1];
			break;
		}
	}
	
	// Save the rating choice to a cookie
	eraseCookie("rating");
	createCookie("rating", pRating, 365);  // save cookie for a year
	
	document.sudoku.rating.value = pRating; 
	document.sudoku.action = "http://www.artbylogic.com/puzzles/sudoku/dailySudoku.htm"; // remove rating from GET.
	document.sudoku.submit();	
}


function nextRating(rating) {

	var difficultyArr = new Array('Easiest[1]', 'Easy[1]', 'Easy[2]', 	'Medium[1]', 'Medium[2]', 
	                       'Hard[1]', 'Hard[2]', 'Hard[3]', 'Hard[4]', 'Hard[5]', 
						   'VeryHard[3]', 'VeryHard[4]', 'Grueling[1]', 'Grueling[2]');
	var cnt = difficultyArr.length;

	var pRating = rating;
	// Don't start at 0 since we can't go previous to the first one.
	for (var k=0; k < (cnt-1); k++) {
		//alert(difficultyArr[k]);
		if (difficultyArr[k] == rating) {
			pRating = difficultyArr[k+1];
			break;
		}
	}
	
	// Save the rating choice to a cookie
	eraseCookie("rating");
	createCookie("rating", pRating, 365);  // save cookie for a year
	
	document.sudoku.rating.value = pRating; 
	document.sudoku.action = "http://www.artbylogic.com/puzzles/sudoku/dailySudoku.htm"; // remove rating from GET.
	document.sudoku.submit();	
}


function solvePuzzle() {
	agree=confirm("Are you sure you want to solve the puzzle?");
	if (!agree)
		return;

	document.sudoku.solveIt.value = 1;
	document.sudoku.submit();
}

function printPuzzle() {
	
	setTDwh(67, 67, 20,  33, 43,  20, 12,  0, 0);

	var elMainTbl = document.getElementById('mainTbl');
	if (elMainTbl) {
		//elCenterX.style.backgroundColor = 'white';
		mainTblW = elMainTbl.style.width;
		elMainTbl.style.width = '620px';
	}
	
	var elCenterX = document.getElementById('centerHorizontallyX');
	if (elCenterX) {
		centerBackground = elCenterX.style.background;
		elCenterX.style.background = 'white';
	}
	var elOutTable = document.getElementById('outTable');
	if (elOutTable) {
		outTableMargin = elOutTable.style.margin;
		elOutTable.style.margin = '0';
		outTableW = elOutTable.style.width;
		elOutTable.style.width = '622px';
	}
	var elNavBarDiv = document.getElementById('navBarDiv');
	if (elNavBarDiv) {
		navBarDivDisplay = elNavBarDiv.style.display;
		elNavBarDiv.style.display = 'none';
	}
	
	var elBody = document.getElementsByTagName('body');
	if (elBody) {
		bodyBackgroundColor = elBody[0].style.backgroundColor;
		elBody[0].style.backgroundColor = 'white';
	}

    var elMainContent = document.getElementById('mainContent');
	if (elMainContent) {
		mainContentBackgroundColor = elMainContent.style.backgroundColor;
		elMainContent.style.backgroundColor = 'white';
	}

    var elLeftSide = document.getElementById('leftSide');
	if (elLeftSide) {
		leftSideDisplay = elLeftSide.style.display;
		elLeftSide.style.display = 'none';
	}

    // setTDwh(90, 90, 22,  70, 66,  26, 13,  6, 0);
    //setTDwh(67, 67, 20,  53, 51,  16, 8,  4, 0);

	window.print();

	document.body.style.cursor = "wait";	// hourglass
	setTimeout("restorePuzzleSize()", 3000);
}

function restorePuzzleSize() {
	//setTDwh(45, 45, 16,  35, 33,  9, 2,  3, 0);
	setTDwh(45, 45, 16,  24, 28,  10, 2,  0, 0);
	
	
	var elCenterX = document.getElementById('centerHorizontallyX');
	if (elCenterX) {
		elCenterX.style.background = centerBackground;
	}


	var elNavBarDiv = document.getElementById('navBarDiv');
	if (elNavBarDiv) {
		elNavBarDiv.style.display = navBarDivDisplay;
	}
	
	var elBody = document.getElementsByTagName('body');
	if (elBody) {
		elBody[0].style.backgroundColor = bodyBackgroundColor;
	}

    var elMainContent = document.getElementById('mainContent');
	if (elMainContent) {
		elMainContent.style.backgroundColor = mainContentBackgroundColor;
	}

    var elLeftSide = document.getElementById('leftSide');
	if (elLeftSide) {
		elLeftSide.style.display = leftSideDisplay;
	}

	
	var elMainTbl = document.getElementById('mainTbl');
	if (elMainTbl) {
		//if (mainTblW.length == 0)
		//	elMainTbl.style.width = 'auto';  // 400px
		//else
			elMainTbl.style.width = mainTblW;
 	}	
	
	var elOutTable = document.getElementById('outTable');
	if (elOutTable) {
		//if (outTableMargin.length == 0)
		//	elOutTable.style.margin = 'auto';
		//else
			elOutTable.style.margin = outTableMargin;
		//if (outTableW.length == 0)
		//	elOutTable.style.width = 'auto';
		//else
			elOutTable.style.width = outTableW;
	}
	
	
	
	document.body.style.cursor = "auto";
}

function setTDwh(w, h, fs,  iw, ih,  ipl, ipt,  iml, imt) {
    var obj = getElementsByClass("inTbl");

	for(i=0;i<obj.length;i++) {
	   obj[i].style.fontSize = fs + "pt";
	   obj[i].style.height = h + "px";
	   obj[i].style.width = w + "px";

	   if (1 && (obj[i].childNodes.length)) {
	      // [object Text] (nodeType==3) or [object HTMLInputElement] (nodeType == 1)
	      cobj = obj[i].childNodes[0];
	   	  //alert(cobj + ' ' + cobj.nodeType);
		  if (cobj.nodeType == 1) {
		     // [object HTMLInputElement]

			 cobj.style.width = iw + "px";  //"56px";
	         cobj.style.height = ih + "px";  //parseInt(h)-25 + "px";

	         cobj.style.fontSize = fs + "pt";

			 cobj.style.paddingLeft = ipl + "px";  // "14px";
			 cobj.style.paddingTop = ipt + "px";  // "6px";

			 cobj.style.marginLeft = iml + "px";  // "7px";
			 cobj.style.marginTop = imt + "px";  // "6px";
			 cobj.style.marginBottom = "0px";
		  }
	   }
	}
}


function pickedDifficulty() {
	reset = true;
	//initPuzzle();
	var el = document.getElementById('ratingPick');
	if (el) {
		// Save the rating choice to a cookie
		eraseCookie("rating");
		createCookie("rating", el.value, 365);  // save cookie for a year

		document.sudoku.rating.value = el.value;
		// Allow users to bookmark a category and level of difficulty
		document.sudoku.action = "dailySudoku.htm?rating=" + el.value;
		document.sudoku.submit();
	}
	reset = false;
}


function resetPuzzle() {
   // Ask user are they sure they want to clear out the entries
   agree=confirm("Are you sure you want to clear out all entered entries?");
   if (!agree)
      return;

   reset = true;
   //initPuzzle();
   document.sudoku.submit();
   reset = false;
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


function checkDigit(rw, cl, pln) {
	//alert('check for cell at row=' + rw + ' col=' + cl);
	var rating, digit;
	inName = eval('document.sudoku.in' + rw.toString() + cl.toString());
	digit = inName.value;
	//alert('[' + digit + ']');
	if (!isDigit(digit)) 
		return true;

	rating = document.sudoku.rating.value;
	//alert('rating=' + rating);

	var postVars = "dcol=" + cl + "&drow=" + rw + "&digit=" + digit + "&pln=" + pln + "&rating=" + rating;
	//alert('postVars=' + postVars);

	ajaxCheckDigit("checkDigitEntry.php", postVars, rw, cl, digit);

	return true;
}



// Posts postVars
//function ajaxCheckDigit(url, postVars, rw, cl, digit) {
function ajaxCheckDigit(url, postVars, rw, cl, digit) {
	var x, hstr, sep;
	if (document.getElementById) {
		x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
	}
	if (x) {
		x.onreadystatechange = function() {
			if (x.readyState == 4 && x.status == 200) {				
				if (x.responseText == "0") {
					// success - digit is correct
					// TO DO: put digit into the puzzle (i.e remove input field)
					//alert('digit is correct');
					showDigitValidity(rw, cl, true);
					checkComplete(true);
				}
				else {
					//alert(x.responseText);
					//alert('digit is incorrect. Response=' + x.responseText);
					//alert('digit is incorrect.');
					incrementIncorrectEntries();
					showDigitValidity(rw, cl, false);
				}
			}
		}  // end function()

		try {
			x.open("POST", url, true);	 // 3rd param: asnynchronous=true

			// When POSTing data, need to set the MIME type or the server will discard the POST data. Do after x.open()
			x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

			x.send(postVars);
			//x.send(null);

		} catch (e) {
			alert(e);
		}

	} // end if (x)
}


// This javascript function is used by Sudoku puzzles created at www.art-by-logic.com
function showDigitValidity(r, c, valid) {
	var replace=true;
	var highlightEmptyCells = true;
	//solnText = document.getElementById("solution");
	//alert(solnText.innerHTML);
	//alert(solnText.innerHTML.charAt(1));
	baseInput = "document.sudoku.in";
	baseStatic = "cell";

	idx = r * 9 + c;
	strRC = r.toString() + c.toString();

	inName = eval(baseInput + strRC);
	if (inName) {
	   //alert(inName.value);
	   //alert(solnText.innerHTML[idx]);	// doesn't work in IE
	   //alert(solnText.innerHTML.charAt(idx));

	   if (!inName.value.length || (inName.value == ' ')) {
		  // empty cell - change background color of input cell to indicate it has not been filled in.
		  inName.style.color = "black"; // set in case they cleared an incorrect entry.
		  //if (highlightEmptyCells)
			 //inName.style.backgroundColor = "PapayaWhip"; // PapayaWhip,MistyRose,PaleGoldenRod
		  if (!highlightEmptyCells)
			 inName.style.backgroundColor = "WhiteSmoke";
	   }
	   //else if (inName.value != digit)
	   else if (!valid) {
		  // change the text color of the input cell to red to indicate a wrong digit.
		  inName.style.color = "red";
		  inName.style.backgroundColor = "WhiteSmoke";
	   }
	   else {
		  // correct entry - make sure text color is black to indicate a correct entry
		  //inName.style.color = "black";
		  //inName.style.backgroundColor = "WhiteSmoke";
		  if (replace) {
			 // Make the valid entry look like static entries - i.e. no input field
			 //stName = eval(baseStatic + strRC);  // object HTMLTableCellElement
			 stName = "cell" + strRC;

			 //alert(document.getElementById(stName).innerHTML);
			 elST = document.getElementById(stName);
			 if (elST) {
			 	elST.innerHTML = inName.value;
				elST.style.color = "blue";
				//elST.style.backgroundColor = "WhiteSmoke";
			 }
		  }
		  else {
			 inName.style.backgroundColor = "WhiteSmoke";
			 inName.value = "";
		  }
	   }
	}
	else {
	   // skip static entries as they will be correct
	}

	return false;
}




// This javascript function is used by Sudoku puzzles created at www.art-by-logic.com
function checkComplete(highlightEmptyCells) {
  //solnText = document.getElementById("solution");
  //alert(solnText.innerHTML);
  //alert(solnText.innerHTML.charAt(1));
  baseInput = "document.sudoku.in";
  baseStatic = "cell";

  var str = "";

  correctCnt = 0;
  for (r=0; r < 9; r++) {
     for (c=0; c < 9; c++) {
	    idx = r * 9 + c;
		strRC = r.toString() + c.toString();

		inName = eval(baseInput + strRC);
		if (inName) {
		   //alert(inName.value);
		   //alert(solnText.innerHTML[idx]);	// doesn't work in IE
		   //alert(solnText.innerHTML.charAt(idx));

		   if (!inName.value.length) {
		      // empty cell - change background color of input cell to indicate it has not been filled in.
			  inName.style.color = "black"; // set in case they cleared an incorrect entry.
			  //if (highlightEmptyCells)
			  	 //inName.style.backgroundColor = "PapayaWhip"; // PapayaWhip,MistyRose,PaleGoldenRod
			  if (!highlightEmptyCells)
			     inName.style.backgroundColor = "WhiteSmoke";
		   }
		   else {

			  stName = "cell" + strRC;
			  elST = document.getElementById(stName);
			  if (elST) {
				 if (elST.style.color == "blue")
				 	correctCnt++;
		      	 //str = str + "\n" + elST.innerHTML;
				 //str = str + "\n" + elST.style.color;
			  }


			  //if (highlightEmptyCells)
			  	 //inName.style.backgroundColor = "PapayaWhip"; // PapayaWhip,MistyRose,PaleGoldenRod
			  if (!highlightEmptyCells)
			     inName.style.backgroundColor = "WhiteSmoke";
		   }
		}
		else {
		   // skip static entries as they will be correct
		   correctCnt++;
		}
	 }
  }

  //alert(str);

  if (correctCnt == 81) {
     alert('Congratulations.  You have solved the puzzle!');
  }

  var entriesLeft = 0;
  entriesLeft = 81 - correctCnt;
  document.getElementById("entriesLeft").innerHTML = entriesLeft;

  //idCell = "cell11";
  //cellTxt = document.getElementById(idCell);
  //alert(cellTxt.innerHTML);

  return false;
}


function incrementIncorrectEntries() {
	var incorrectCnt = document.getElementById('incorrectEntries').innerHTML;
	//alert(incorrectCnt);
	incorrectCnt++;
	document.getElementById('incorrectEntries').innerHTML = incorrectCnt;
	//document.getElementById("entriesLeft").innerHTML = incorrectCount;
}

//-------------------------------------------------------------------
// isDigit(value)
//   Returns true if value is a 1-character digit
//-------------------------------------------------------------------
function isDigit(num) {
	if ((num.length>1) || !num.length) {return false;}
	var string="1234567890";
	if (string.indexOf(num)!=-1){return true;}
	return false;
}

function showInstructions() {
	var el = document.getElementById('showInstructions');
	if (el) {
		//el.style.zIndex = 600;
		el.style.visibility = 'visible';  // 'hidden'
		el.style.width = "700px";
		el.style.left = "50px";
		disableSelection(el);
	}
}
function closeInstructions() {
	var el = document.getElementById('showInstructions');
	if (el) {
		el.style.visibility = 'hidden';
		// Shrink so it won't prevent the user from setting the cursor on a cell in the Sudoku grid.
		el.style.width = "5px";
		el.style.left = "50px";
	}
}


// disable text selection
function disableSelection(target){
	if (typeof target.onselectstart!="undefined") //IE route
		target.onselectstart=function(){return false}
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
		target.style.MozUserSelect="none"
	else  { //All other route (ie: Opera)
		target.onmousedown=function(){return false;}
		//target.onclick=function() {return true;}
	}	
	target.style.cursor = "default"
}
