var selectCellIndex = -1;
var selectCellId = "";
var board = "";
var origBoard = "";
var givens = new Array(80);
var session = '';
var sfw = '';
var currentLevel = "1";
var currentLan = "en";
var enabled = false;
var front = false;

function enable() {
	enabled = true;
}

function setSfw() {
	sfw = 'sfw';
}

function setWidget() {
	sfw = 'wid';
}

function setFront() {
	front = true;
}

function setSession(ses) {
	session = ses;
}

function getSession() {
	return session;
}

function setSessionLevel(level) {
	currentLevel = level;
}

function setSessionLanguage(lan) {
	currentLan = lan;
}

function loadNewGame() {
	window.location = "http://" + location.hostname + location.pathname + "?level=" + currentLevel + "&lang=" + currentLan;
}

function loadNewLevel(level) {
	window.location = "http://" + location.hostname + location.pathname + "?level=" + level + "&lang=" + currentLan;
}

function displayHelp() {
	var showHelp = new Boolean(true);
  try {
		if (getCookie("sudbeworldhelp").length > 0) showHelp = false;
  } catch(err) {}
	if (showHelp) {
		setCookie("sudbeworldhelp", "true", 999);
		showPopup("help.php?first=true&lang=" + currentLan);	
	}
}

function displaySFWHelp() {
	var showHelp = new Boolean(true);
  try {
		if (getCookie("sudbeworldsfwhelp").length > 0) showHelp = false;
  } catch(err) {}
	if (showHelp) {
		setCookie("sudbeworldsfwhelp", "true", 999);
		showPopup("sfwhelp.php?lang=" + currentLan + "&first=true");	
	}
}

function showSubmit() {
	var newBoard = "";
	for (i = 0; i < 81; i++) {
		var innerC = document.getElementById("sudbrdcell" + i).innerHTML + "";
		if (innerC.length == 1) {
			newBoard = newBoard + innerC.charAt(0);
		} else {
			newBoard = newBoard + "0";
		}
	}
	var url = "submit.php?lang="+currentLan+"&submit=true&session=" + session + "&board=" + newBoard;
	showPopup(url);
}

function showPopup(url) {
	var includeWWW = "";
	var tmpLoc = location + "";
	if (tmpLoc.indexOf("www.") >= 0) includeWWW = "www.";
	if (front) {
		GB_show("Sudoku World", "http://"+includeWWW+"sudokuworld.be/" + url, 271, 295, null);
	} else if (sfw == 'wid') {
		GB_show("Sudoku World", "http://"+includeWWW+"sudokuworld.be/" + url, 270, 269, null);
  } else {
		GB_showCenter("Sudoku World", "http://"+includeWWW+"sudokuworld.be/" + url, 442, 549, null)
  }
}

function hidePopup() {
	document.getElementById("popupcontinner").innerHTML = "&nbsp;";
	document.getElementById("popup").style.display = "none";
}

function clearFilled() {
	loadBoard(origBoard, '', '');
}

function setCookie(c_name, value, expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name) {
	if (document.cookie.length>0)  {
  	c_start=document.cookie.indexOf(c_name + "=");
  	if (c_start!=-1) { 
    	c_start=c_start + c_name.length+1;
    	c_end=document.cookie.indexOf(";",c_start);
    	if (c_end==-1) c_end=document.cookie.length;
    	return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
	return "";
}

//Sudoku functions

function loadBoard(newBoard, prefilled, preGivens) { 
	board = newBoard; 
	origBoard = newBoard;
	for (i = 0; i < board.length; i++) { 
		if (board.charAt(i) == "0") { 
			document.getElementById("sudbrdcell" + i).style.background = "url(gfx/emptygrad"+sfw+".gif)"; 
			document.getElementById("sudbrdcell" + i).innerHTML = "&nbsp;"; 
			document.getElementById("sudbrdcell" + i).style.color = "#999999";
		} else { 
			document.getElementById("sudbrdcell" + i).innerHTML = "" + board.charAt(i); 
			document.getElementById("sudbrdcell" + i).style.fontWeight = "bold";
			document.getElementById("sudbrdcell" + i).style.fontStyle = "normal";
			document.getElementById("sudbrdcell" + i).style.color = "#000000";
		} 
	} 

  //Try to load givens
	if (preGivens != null && preGivens.length > 0) {
		indGivens = preGivens.split(':');
		for (i = 0; i < indGivens.length; i++) {
			if (indGivens[i] != null && indGivens[i].length > 0) {
				subIndGivens = indGivens[i].split('-');
				if (subIndGivens.length == 2) {
					gid = parseInt(subIndGivens[0]);
					givens[gid] = "" + subIndGivens[1];
					selectCellId = "sudbrdcell" + gid;
					selectCellIndex = gid;
					setSelectedCellContents(getGivensTable(givens[gid]));
				}
			}
		}
	}

  //Try to load prefilled
  if (prefilled != null && prefilled.length > 0) {
		prefilled = basicDecode(prefilled);
		if (prefilled.length == 81) {
			for (i = 0; i < prefilled.length; i++) {
				if (IsNumeric(prefilled.charAt(i) + "")) {
					document.getElementById("sudbrdcell" + i).innerHTML = prefilled.charAt(i); 
				}
			}
		}
	}
}

function setCellHigh(cellId, highlight) { 
	if (!enabled) return;
	if (cellId == selectCellId) { return; } 
	var tmpIndexIndex = cellId.replace("sudbrdcell", ""); 
	if (highlight) { 
		if (board.charAt(tmpIndexIndex) != "0") { 
			document.getElementById(cellId).className = "cellhighlightgiven"; 
		} else { 
			document.getElementById(cellId).className = "cellhighlight"; 
			document.getElementById(cellId).style.background = "url(gfx/emptygradhigh"+sfw+".gif)"; 
		} 
	} else { 
		if (board.charAt(tmpIndexIndex) != "0") { 
			document.getElementById(cellId).className = "cell"; 
			document.getElementById(cellId).style.background = "url(gfx/givengrad"+sfw+".gif)"; 
		} else { 
			document.getElementById(cellId).className = "cell"; 
			document.getElementById(cellId).style.background = "url(gfx/emptygrad"+sfw+".gif)"; 
		} 
	} 
}

function clearGivens() { 
	if (selectCellId != "") { 
		givens[selectCellIndex] = ""; 
		drawGivens(true); 
	} 
}

function selectGiven(id) { 
	if (!enabled) return;
	var newId = id - 1; 
	if (id > 0 && id < 10 && selectCellId != "") { 
		if (givens[selectCellIndex] == null || givens[selectCellIndex].indexOf("" + id) == -1) { 
			if (givens[selectCellIndex] == null) { 
				givens[selectCellIndex] = ""; 
			} 
			givens[selectCellIndex] = givens[selectCellIndex] + ("" + id); 
		} else { 
			givens[selectCellIndex] = givens[selectCellIndex].replace("" + id, ""); 
		} 
		drawGivens(true); 
	} 
}

function drawGivens(updateCell) { 
  if (sfw == 'wid' || sfw == 'frt') return;
	if (selectCellId != "") { 
		for (i = 0; i < 9; i++) { 
			document.getElementById("givenid" + (i + 1)).className = "givenid"; 
		} 
		givCount = 0; 
		if (givens[selectCellIndex] != null && givens[selectCellIndex] != "") { 
			for (i = 0; i < givens[selectCellIndex].length; i++) { 
				document.getElementById("givenid" + givens[selectCellIndex].charAt(i)).className = "givenidhighlight"; 
				givCount++; 
			} 
		} 
		if (updateCell) {
			if (givCount > 0) { 
				setSelectedCellContents(getGivensTable(givens[selectCellIndex])); 
			} else {
				setSelectedCellContents("");
			}
		}
	} 
}

function getGivensTable(givens) { 
	var cont1 = givens.indexOf("1") == -1 ? "&nbsp;&nbsp;" : "1"; 
	var cont2 = givens.indexOf("2") == -1 ? "&nbsp;&nbsp;" : "2"; 
	var cont3 = givens.indexOf("3") == -1 ? "&nbsp;&nbsp;" : "3"; 
	var cont4 = givens.indexOf("4") == -1 ? "&nbsp;&nbsp;" : "4"; 
	var cont5 = givens.indexOf("5") == -1 ? "&nbsp;&nbsp;" : "5"; 
	var cont6 = givens.indexOf("6") == -1 ? "&nbsp;&nbsp;" : "6"; 	
	var cont7 = givens.indexOf("7") == -1 ? "&nbsp;&nbsp;" : "7"; 
	var cont8 = givens.indexOf("8") == -1 ? "&nbsp;&nbsp;" : "8"; 
	var cont9 = givens.indexOf("9") == -1 ? "&nbsp;&nbsp;" : "9"; 
	var tableContents = '<div class="givenidinner"><table border="0" cellspacing="0" cellpadding="0" cellspacing="0" width="100%" height="100%">' +
		'<tr><td align="center">' + cont1 + '</td>' +
		'<td align="center">' + cont2 + '</td>' +
		'<td align="center">' + cont3 + '</td>' +
		'</tr><tr><td align="center">' + cont4 + '</td>' +
		'<td align="center">' + cont5 + '</td>' +
		'<td align="center">' + cont6 + '</td>' +
		'</tr><tr><td align="center">' + cont7 + '</td>' +
		'<td align="center">' + cont8 + '</td>' +
		'<td align="center">' + cont9 + '</td></tr></table></div>';
	return tableContents; 
}

function setSelectedCellContents(cont) { 
	if (!enabled) return;
	if (selectCellId != "") { 
		document.getElementById(selectCellId).innerHTML = "&nbsp;"; 
		if (cont == 0) { 
			document.getElementById(selectCellId).innerHTML = "&nbsp;"; 
		} else { 
			document.getElementById(selectCellId).innerHTML = cont; 
		} 

		finished = new Boolean(true);
		for (i = 0; i < 81; i++) {
			var innerC = document.getElementById("sudbrdcell" + i).innerHTML + "";		
			if (innerC.length == 1) {
				if (innerC.charAt(0) == "0") {
					finished = false;
					break;
				}
			} else {
				finished = false;
				break;
			}
		}
		if (finished) showSubmit();
	} 
}

function selectCell(cellId) { 
	if (!enabled) return;
	var tmpIndexId = cellId; 
	var tmpIndexIndex = tmpIndexId.replace("sudbrdcell", ""); 
	if (board.charAt(tmpIndexIndex) != 0) { return; } 
	if (document.getElementById(tmpIndexId).className != "cellselected") { 
		if (selectCellId != "") { 
			document.getElementById(selectCellId).className = "cell"; 
			document.getElementById(selectCellId).style.background = "url(gfx/emptygrad"+sfw+".gif)"; 
		} 
		document.getElementById(cellId).className = "cellselected"; 
		selectCellId = tmpIndexId; 
		selectCellIndex = tmpIndexIndex; 
	} else { 
		document.getElementById(cellId).className = "cell"; 
		document.getElementById(cellId).style.background = "url(gfx/emptygrad"+sfw+".gif)"; 
		selectCellId = ""; 
		selectCellIndex = -1; 
	} 
	drawGivens(false); 
}

function getFilled() {
	var computed = "";
	//Get the filled in elements
	for (i = 0; i < board.length; i++) { 
		if (board.charAt(i) == "0") {
			if (document.getElementById("sudbrdcell" + i).innerHTML.length == 1 && (givens[i] == null || givens[i] == "")) {
				computed = computed + document.getElementById("sudbrdcell" + i).innerHTML;
			} else {
				computed = computed + "0";
			}
		} else {
			computed = computed + "0";
		}
	}
	return basicEncode(computed);
}

function getGivens() {
	var givenStr = "";
	//Get the givens
	for (i = 0; i < givens.length; i++) {
		if (givens[i] != null && givens[i] != "") {
			givenStr = givenStr + ":" + i + "-" + givens[i];
		}
	}
	return basicEncode(givenStr);
}

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
  return null;
} 

function getPageHeight() {
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}

function getPageWidth() {
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return myWidth;
}

function handleNumberEvent() { 
	shortcut("1", function () {clearGivens();setSelectedCellContents(1);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("a", function () {clearGivens();setSelectedCellContents(1);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("2", function () {clearGivens();setSelectedCellContents(2);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("b", function () {clearGivens();setSelectedCellContents(2);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("3", function () {clearGivens();setSelectedCellContents(3);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("c", function () {clearGivens();setSelectedCellContents(3);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("4", function () {clearGivens();setSelectedCellContents(4);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("d", function () {clearGivens();setSelectedCellContents(4);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("5", function () {clearGivens();setSelectedCellContents(5);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("e", function () {clearGivens();setSelectedCellContents(5);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("6", function () {clearGivens();setSelectedCellContents(6);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("f", function () {clearGivens();setSelectedCellContents(6);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("7", function () {clearGivens();setSelectedCellContents(7);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("g", function () {clearGivens();setSelectedCellContents(7);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("8", function () {clearGivens();setSelectedCellContents(8);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("h", function () {clearGivens();setSelectedCellContents(8);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("9", function () {clearGivens();setSelectedCellContents(9);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("i", function () {clearGivens();setSelectedCellContents(9);}, {type:"keydown", propagate:true, target:document}); 
	shortcut("backspace", function () {setSelectedCellContents(0);clearGivens();}, {type:"keydown", propagate:true, target:document}); 
	shortcut("delete", function () {setSelectedCellContents(0);clearGivens();}, {type:"keydown", propagate:true, target:document}); 
}

function basicEncode(mesg) {
  prevLen = "";
  while (prevLen != mesg) {
    prevLen = mesg;
    mesg = mesg.replace('00', 'A');
    mesg = mesg.replace('AA', 'B');
    mesg = mesg.replace('BB', 'C');
    mesg = mesg.replace('CC', 'D');
		mesg = mesg.replace(':', 'E');
		mesg = mesg.replace('-', 'F');
  }
  return mesg;
}

function basicDecode(mesg) {
  prevLen = "";
  while (prevLen != mesg) {
    prevLen = mesg;
    mesg = mesg.replace('D', '0000000000000000');
    mesg = mesg.replace('C', '00000000');
    mesg = mesg.replace('B', '0000');
    mesg = mesg.replace('A', '00');
		mesg = mesg.replace('E', ':');
		mesg = mesg.replace('F', '-');
  }
  return mesg;
}

function IsNumeric(strString) {
	if (strString == '1') return true;
	if (strString == '2') return true;
	if (strString == '3') return true;
	if (strString == '4') return true;
	if (strString == '5') return true;
	if (strString == '6') return true;
	if (strString == '7') return true;
	if (strString == '8') return true;
	if (strString == '9') return true;
	return false;
}

function shortcut(shortcut, callback, opt) { 
	var default_options = {type:"keydown", propagate:false, target:document}; if (!opt) { opt = default_options; } else { for (var dfo in default_options) { if (typeof opt[dfo] == "undefined") { opt[dfo] = default_options[dfo]; } } } var ele = opt.target; if (typeof opt.target == "string") { ele = document.getElementById(opt.target); } var ths = this; var func = function (e) {e = e || window.event;if (e.keyCode) {code = e.keyCode;} else if (e.which) {code = e.which;}var character = String.fromCharCode(code).toLowerCase();var keys = shortcut.toLowerCase().split("+");var kp = 0;var shift_nums = {'`':"~", '1':"!", '2':"@", '3':"#", '4':"$", '5':"%", '6':"^", '7':"&", '8':"*", '9':"(", '0':")", '-':"_", '=':"+", ';':":", '\'':"\"", ',':"<", '.':">", '/':"?", '\\':"|"};var special_keys = {esc:27, escape:27, tab:9, space:32, 'return':13, enter:13, backspace:8, scrolllock:145, scroll_lock:145, scroll:145, capslock:20, caps_lock:20, caps:20, numlock:144, num_lock:144, num:144, pause:19, 'break':19, insert:45, home:36, 'delete':46, end:35, pageup:33, page_up:33, pu:33, pagedown:34, page_down:34, pd:34, left:37, up:38, right:39, down:40, f1:112, f2:113, f3:114, f4:115, f5:116, f6:117, f7:118, f8:119, f9:120, f10:121, f11:122, f12:123};for (var i = 0; k = keys[i], i < keys.length; i++) {if (k == "ctrl" || k == "control") {if (e.ctrlKey) {kp++;}} else if (k == "shift") {if (e.shiftKey) {kp++;}} else if (k == "alt") {if (e.altKey) {kp++;}} else if (k.length > 1) {if (special_keys[k] == code) {kp++;}} else {if (character == k) {kp++;} else {if (shift_nums[character] && e.shiftKey) {character = shift_nums[character];if (character == k) {kp++;}}}}}if (kp == keys.length) {callback(e);if (!opt.propagate) {e.cancelBubble = true;e.returnValue = false;if (e.stopPropagation) {e.stopPropagation();e.preventDefault();}return false;}}}; if (ele.addEventListener) { ele.addEventListener(opt.type, func, false); } else if (ele.attachEvent) { ele.attachEvent("on" + opt.type, func); } else { ele["on" + opt.type] = func; } 
}
