/*
 * Copyright (c) 2008 AKEEBO CORPORATION. All Rights Reserved.
 *
 * This software is the confidential and proprietary information ("Confidential Information") 
 * of AKEEBO CORPORATION ("AKEEBO CORP"). Any disclosure or use of such Confidential Information other 
 * than in accordance with the terms of the license under which it was received is strictly 
 * prohibited.
 *
 * AKEEBO CORP MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF 
 * THE SOFTWARE, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
 * OR NON-INFRINGEMENT. AKEEBO CORP SHALL NOT BE LIABLE FOR ANY DAMAGES
 * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
 * THIS SOFTWARE OR ITS DERIVATIVES.
 */

var gameGenreCurrent = 0;
var gamePage = 1;
//////////////////////////////////////////////
////This function initialize the game panel //
//////////////////////////////////////////////
/////////////////////////////////////////////
////This function selects the reset button //
/////////////////////////////////////////////
function selResetBtn(index) {
	var background = (index == 1 ? "#fcf3b8" : "none");
	document.getElementById("resetGamePanel").style.background = background;
}
//////////////////////////////////////////////
////This function initialize the game panel //
//////////////////////////////////////////////
function resetGame() {
	gameGenreCurrent = 3*gameRowIndex + gameColIndex;
	if(gameGenreCurrent == 0) {
		resetGamePanel();
		createCrackerGamePanel();
	} else if(gameGenreCurrent == 1) {
		initMineSweeper();
	} else if(gameGenreCurrent == 2) {
		reset();
		makeNewGame();
	} else if(gameGenreCurrent == 3) {
		initSudoku();
	} else if(gameGenreCurrent == 4) {
		resetSnakeGame();
	} else if(gameGenreCurrent = 5) {
		tetris();
	}
}
////////////////////////////////////////////////
////This function to exit from the Game panel //
////////////////////////////////////////////////
function escapeGamePanel() {
	if(gameGenreCurrent == 2) {
//		hideSudokuPanel();
	} else if(gameGenreCurrent == 4) {		hideSnakeGame();
	} else if(gameGenreCurrent == 1) {
		reset();
		putTValue();
	}
	if(gameMenuStatus) {
		drawGamePanelMenu();		
	} else {
		showGoPanel();
		gameActive = false; 
		showGuidePanel();
	}
}
	
////////////////////////////////////////////////
////This function to go to fullguide panel //
////////////////////////////////////////////////
function gotoHomeGame(index) {
	var selHomeColor = "";
	selHomeColor = (index == 1 ? "#fcf3b8" : "none");
	document.getElementById("gameHomePanel").style.background = selHomeColor;
}

////////////////////
// Crackers Panel //
////////////////////
var black = -1; // computer is black
var red = 1; // visitor is red
var square_dim = 35;
var piece_toggled = false;
var my_turn = false;
var double_jump = false;
var comp_move = false;
var game_is_over = false;
var safe_from = safe_to = null;
var toggler = null;
var checkerRowPosition = 2;
var checkerColumnPosition = 4;
var togglers = 0;
var selected_c = coord(0,0);
var jump_priority = 10;


function Board() {
	board = new Array();
	for (var i=0;i<8; i++) {
		board[i] = new Array();
		for (var j=0;j<8;j++)
			board[i][j] = Board.arguments[8*j+i];
	}
	board[-2] = new Array(); // prevents errors
	board[-1] = new Array(); // prevents errors
 	board[8] = new Array(); // prevents errors
 	board[9] = new Array(); // prevents errors
}
var board;
Board(1,0,1,0,1,0,1,0,
      0,1,0,1,0,1,0,1,
      1,0,1,0,1,0,1,0,
      0,0,0,0,0,0,0,0,
      0,0,0,0,0,0,0,0,
      0,-1,0,-1,0,-1,0,-1,
      -1,0,-1,0,-1,0,-1,0,
      0,-1,0,-1,0,-1,0,-1);


/////////////////////////////////////////////////////////////////////
// This method prints the message information on the message panel //
/////////////////////////////////////////////////////////////////////
function message(str) {
	try {
		document.getElementById("messagePanel").innerHTML = str;
	} catch(x) {
//		alert(x);
	}
}
////////////////////////////////////////////////
// calculates whether it is a gray (moveable) //
// or black (non-moveable) space 			  //
////////////////////////////////////////////////
function moveable_space(i,j) {
 return (((i%2)+j)%2 == 0);
}
/////////////////////////////////////////////////////// 
// This function is used to get the co-ordinate info //
///////////////////////////////////////////////////////
function Coord(x,y) {
 	this.x = x;
 	this.y = y;
}

function coord(x,y) {
 	c = new Coord(x,y);
 	return c;
}
/////////////////////////////////////////
/// This method updates the game panel //
/////////////////////////////////////////
function createCrackerGamePanel() {
	gamePage = 1;
	gameGenreCurrent = 0;
	//
//	document.getElementById("gameId).innerHTML = "";
//	document.getElementById("gameId").innerHTML = "<table>" + document.getElementById("peeptinPanel").innerHTML + "</table>";
//	return;
	
	resetGamePanel();
	document.getElementById("openChartId").innerHTML = "";
	 var gameHTML = '<table width="320px" align="center" height="240px" style="border:1px solid gray;"><tr><td ><table align="center" style="border:2px solid black;" cellspacing=0 cellpadding=0>';
	  for(var j=0;j<8;j++) {
	  		gameHTML += "<tr>";
	 	 for(var i=0,k=0;i<8;i++) {
	  	 	var styleComp = "";
	 	 	if (moveable_space(i,j)) {
 	 			styleComp += ' style="cursor:pointer;" onclick=\"clicked('+ i + ',' + j + ');\" onmouseover="selectCurBox(' + i + ',' + j + ');" ';
	 	 	}
	 	 	var otherComp ="' width=" + square_dim + " height=" + square_dim +" name='space" + i + "" + j + "' ";
 	 		var imageSpec = "";
 	 		var idStatus = false;
			if (board[i][j]==1) {
				idStatus = true;
				imageSpec ="you1.jpg";
			} else if (board[i][j] == -1) { 
				idStatus = true;
				imageSpec ="me1.jpg";
			} else if (moveable_space(i,j)) { 
				idStatus = true;
				imageSpec ="gray.jpg";
			} else { 
				idStatus = false;
			 	imageSpec ="black.jpg";
			}
//			gameHTML +="<td " + ( idStatus == true ?  "id='checkerId" + j + "" + k +"'" : "" )+ " ><img src='/view/tv/images/widgets/checker/" + imageSpec + "' " + styleComp + " "+ otherComp + "></td>";
			gameHTML +="<td id='checkerId" + j + "" + i +"' width=" + square_dim + " height=" + square_dim +" style='border:1px solid black;'><img src='/view/tv/images/widgets/checker/" + imageSpec + "' " + styleComp + " "+ otherComp + "></td>";
			if(idStatus) {
				k++;
			}
		}
		gameHTML +="</tr>";
	}		
	gameHTML += "</table></td></tr></table>";
	document.getElementById("openChartId").innerHTML = gameHTML;
	document.getElementById("checkerId24").style.border = "1px solid yellow";
//	message(trim(records.key1438));
	message("Please pick up red for play");
}
/////////////////////////////
///Reseting the game panel //
/////////////////////////////
function resetGamePanel() {
	document.getElementById("openChartId").innerHTML = "";
	black = -1; // computer is black
	red = 1; // visitor is red
	square_dim = 25;
	piece_toggled = false;
	my_turn = false;
	double_jump = false;
	comp_move = false;
	game_is_over = false;	
	safe_from = safe_to = null;
	toggler = null;
	togglers = 0;
	Board(1,0,1,0,1,0,1,0,
      0,1,0,1,0,1,0,1,
      1,0,1,0,1,0,1,0,
      0,0,0,0,0,0,0,0,
      0,0,0,0,0,0,0,0,
      0,-1,0,-1,0,-1,0,-1,
      -1,0,-1,0,-1,0,-1,0,
      0,-1,0,-1,0,-1,0,-1);
	selected_c = coord(0,0);
	my_turn = true;
	jump_priority = 10;
	checkerRowPosition = 2;
	checkerColumnPosition = 4;
//	createCrackerGamePanel();
}
////////////////////////////////////////////////////////////////
// This method responses the click action on the selected box //
////////////////////////////////////////////////////////////////
function clicked(i,j) {
//	 unSelCurBox();
	 if (my_turn) {
 		if (integ(board[i][j])==1) {
 			toggle(i,j);
 		} else if (piece_toggled) {
		 	move(selected, coord(i,j));
		} else {
			message("First choose one of red pieces, then move");
//			message(trim(records.key1417));
		}
	 } else {
//		message(trim(records.key1418));
		message("It's not your turn yet. Hang on a sec!");
	 }
}

function toggle(x,y) {
 if (my_turn) {
 	if (piece_toggled)
	 	draw(selected.x,selected.y,"/view/tv/images/widgets/checker/you1"+((board[selected.x][selected.y]==1.1)?"k":"")+".jpg");
	 if (piece_toggled && (selected.x == x) && (selected.y == y)) {
	 	piece_toggled = false;
		 if (double_jump) { my_turn = double_jump = false; computer(); }
		 } else {
			 piece_toggled = true;
			 draw(x,y,"/view/tv/images/widgets/checker/you2"+((board[x][y]==1.1)?"k":"")+".jpg");
		 }
		 selected = coord(x,y);
	 } else {
	 	if ((piece_toggled) && (integ(board[selected_c.x][selected_c.y])==-1))
			 draw(selected_c.x,selected_c.y,"/view/tv/images/widgets/checker/me1"+((board[selected_c.x][selected_c.y]==-1.1)?"k":"")+".jpg");
		 if (piece_toggled && (selected_c.x == x) && (selected_c.y == y)) {
	 		piece_toggled = false;
		 } else {
	 		piece_toggled = true;
			draw(x,y,"/view/tv/images/widgets/checker/me2"+((board[x][y]==-1.1)?"k":"")+".jpg");
	 	}
	 	selected_c = coord(x,y);
	 }
}
//////////////////////////////////////////////
/////The function to draw  the new position //
//////////////////////////////////////////////
function draw(x,y, imageName) {
	document.images["space"+x+""+y].src = imageName;
}

function integ(num) {
 	if (num != null)
 		return Math.round(num);
 	else
 		return null;
}

function abs(num) {
 	return Math.abs(num);
}

function sign(num) {
	if (num < 0)
		return -1;
 	else 
 		return 1;
}

function concatenate(arr1,arr2) {
 // function tacks the second array onto the end of the first and returns result
 	for(var i=0; i<arr2.length; i++)
		arr1[arr1.length+i] = arr2[i];
	return arr1;
}

function legal_move(from,to) {
	if ((to.x < 0) || (to.y < 0) || (to.x > 7) || (to.y > 7)) return false;
		piece = board[from.x][from.y];
		distance = coord(to.x-from.x,to.y-from.y);
	if ((distance.x == 0) || (distance.y == 0)) {
		message("You may only move diagonally.");
//		message(trim(records.key1419) + ".");
		return false;
	}
	if (abs(distance.x) != abs(distance.y)) {
		message("Invalid move.");
//		message(trim(records.key1420) + ".");
		return false;
	}
	if (abs(distance.x) > 2) {
		message("Invalid move.");
//		message(trim(records.key1421) + ".");
		return false;
	}
	if ((abs(distance.x) == 1) && double_jump) {
		return false;
	}
	if ((board[to.x][to.y] != 0) || (piece == 0)) {
		return false;
	}
	if ((abs(distance.x) == 2)
		&& (integ(piece) != -integ(board[from.x+sign(distance.x)][from.y+sign(distance.y)]))) {
		return false;
	}
	if ((integ(piece) == piece) && (sign(piece) != sign(distance.y))) {
		return false;
	}
	return true;
}

function move(from,to) {
	 my_turn = true;
	 if (legal_move(from,to)) {
		 piece = board[from.x][from.y];
		 distance = coord(to.x-from.x,to.y-from.y);
		 if ((abs(distance.x) == 1) && (board[to.x][to.y] == 0)) {
		 swap(from,to);
		 } else if ((abs(distance.x) == 2)
		 && (integ(piece) != integ(board[from.x+sign(distance.x)][from.y+sign(distance.y)]))) {
			 double_jump = false;
			 swap(from,to);
			 remove(from.x+sign(distance.x),from.y+sign(distance.y));
			 if ((legal_move(to, coord(to.x+2,to.y+2)))
			 || (legal_move(to, coord(to.x+2,to.y-2)))
			 || (legal_move(to, coord(to.x-2,to.y-2)))
			 || (legal_move(to, coord(to.x-2,to.y+2)))) {
				 double_jump = true;
				 message("You may complete the double jump or click on your piece to stay still.");
			 }
		 }
		if ((board[to.x][to.y] == 1) && (to.y == 7)) 
			king_me(to.x,to.y);
			selected = to;
		if (game_over() && !double_jump) {
	 		setTimeout("toggle(" + to.x + "," + to.y + ");my_turn = double_jump = false;computer();",1000);
		}
 	}
 	return true;
}



function king_me(x,y) {
	if (board[x][y] == 1) {
		board[x][y] = 1.1; // king you
		draw(x,y,"/view/tv/images/widgets/checker/you2k.jpg");
	} else if (board[x][y] == -1) {
		board[x][y] = -1.1; // king me
		draw(x,y,"/view/tv/images/widgets/checker/me2k.jpg");
	}
}

function swap(from,to) {
	if (my_turn || comp_move) {
		dummy_src = document.images["space"+to.x+""+to.y].src;
		document.images["space"+to.x+""+to.y].src = document.images["space"+from.x+""+from.y].src;
		document.images["space"+from.x+""+from.y].src = dummy_src;
	}
	dummy_num = board[from.x][from.y];
	board[from.x][from.y] = board[to.x][to.y];
	board[to.x][to.y] = dummy_num;
}

function remove(x,y) {
	if (my_turn || comp_move)
		draw(x,y,"/view/tv/images/widgets/checker/gray.jpg");	
	board[x][y] = 0;
}

function Result(val) {
	this.high = val;
	this.dir = new Array();
}

function move_comp(from,to) {
	toggle(from.x,from.y);
	comp_move = true;
	swap(from,to);
	if (abs(from.x-to.x) == 2) {
		remove(from.x+sign(to.x-from.x),from.y+sign(to.y-from.y));
	}
	if ((board[to.x][to.y] == -1) && (to.y == 0)) king_me(to.x,to.y);
	setTimeout("selected_c = coord(" + to.x + "," + to.y + ");piece_toggled = true;", 900);
	setTimeout("bak=my_turn;my_turn=false;toggle(" + to.x + "," + to.y + ");my_turn=bak;", 1000);
	if (game_over()) {
		setTimeout("comp_move = false;my_turn = true;togglers=0;", 600);
		message("Ok. It's your turn. You may make your move.");
//		message(trim(records.key1422) + ".");
	}
 	return true;
}

function game_over() { // make sure game is not over (return false if game is over)
	comp = you = false;
	for(var i=0;i<8;i++) {
		for(var j=0;j<8;j++) {
			if(integ(board[i][j]) == -1) comp = true;
				if(integ(board[i][j]) == 1) you = true;
		}
	}
	if (!comp) 
		message("You beat me!");
//		message(trim(records.key1423) + "!");
	if (!you)
		message("Gotcha! Game over.");
//		message(trim(records.key1424));
	game_is_over = (!comp || !you)
	return (!game_is_over);
}
// the higher the jump_priority, the more often the computer will take the jump over the safe move

function computer() {
 // step one - prevent any jumps
	for(var j=0;j<8;j++) {
		for(var i=0;i<8;i++) {
			if (integ(board[i][j]) == 1) {
				if ((legal_move(coord(i,j),coord(i+2,j+2))) && (prevent(coord(i+2,j+2),coord(i+1,j+1)))) {
					return true;
				} if ((legal_move(coord(i,j),coord(i-2,j+2))) && (prevent(coord(i-2,j+2),coord(i-1,j+1)))) {
					return true;	
				}
			} if (board[i][j] == 1.1) {
				if ((legal_move(coord(i,j),coord(i-2,j-2))) && (prevent(coord(i-2,j-2),coord(i-1,j-1)))) {
					return true;
				} if ((legal_move(coord(i,j),coord(i+2,j-2))) && (prevent(coord(i+2,j-2),coord(i+1,j-1)))) {
					return true;
				}
			}
		}
	}
 // step two - if step one not taken, look for jumps
	for(var j=7;j>=0;j--) {
		for(var i=0;i<8;i++) {
			if (jump(i,j))
				return true;
		}
	}
	safe_from = null;
// step three - if step two not taken, look for safe single space moves
	for(var j=0;j<8;j++) {
		for(var i=0;i<8;i++) {
			if (single(i,j))
				return true;
		}
	}
 // if no safe moves, just take whatever you can get
	if (safe_from != null) {
		move_comp(safe_from,safe_to);
	} else {
		message("You beat me!!");
//		message(trim(records.key1423) + "!");
		game_is_over = true;
	}
	safe_from = safe_to = null;
	return false;
}

function jump(i,j) {
	if (board[i][j] == -1.1) {
		if (legal_move(coord(i,j),coord(i+2,j+2))) {
			move_comp(coord(i,j),coord(i+2,j+2));
			setTimeout("jump("+(i+2)+","+(j+2)+");",500);
			return true;
		} if (legal_move(coord(i,j),coord(i-2,j+2))) {
			move_comp(coord(i,j),coord(i-2,j+2));
			setTimeout("jump("+(i-2)+","+(j+2)+");",500);
			return true;
		}
	} if (integ(board[i][j]) == -1) {
		if (legal_move(coord(i,j),coord(i-2,j-2))) {
			move_comp(coord(i,j),coord(i-2,j-2));
			setTimeout("jump("+(i-2)+","+(j-2)+");",500);
			return true;
		} if (legal_move(coord(i,j),coord(i+2,j-2))) {
			move_comp(coord(i,j),coord(i+2,j-2));
			setTimeout("jump("+(i+2)+","+(j-2)+");",500);
			return true;
		}
	}
	return false;
}
function single(i,j) {
	if (board[i][j] == -1.1) {
		if (legal_move(coord(i,j),coord(i+1,j+1))) {
			safe_from = coord(i,j);
			safe_to = coord(i+1,j+1);
			if (wise(coord(i,j),coord(i+1,j+1))) {
				move_comp(coord(i,j),coord(i+1,j+1));
				return true;
			}
		} 
		if (legal_move(coord(i,j),coord(i-1,j+1))) {
			safe_from = coord(i,j);
			safe_to = coord(i-1,j+1);
			if (wise(coord(i,j),coord(i-1,j+1))) {
				move_comp(coord(i,j),coord(i-1,j+1));
				return true;
			}
		}
	} if (integ(board[i][j]) == -1) {
		if (legal_move(coord(i,j),coord(i+1,j-1))) {
			safe_from = coord(i,j);
			safe_to = coord(i+1,j-1);
			if (wise(coord(i,j),coord(i+1,j-1))) {
				move_comp(coord(i,j),coord(i+1,j-1));
				return true;
			}
		} if (legal_move(coord(i,j),coord(i-1,j-1))) {
			safe_from = coord(i,j);
			safe_to = coord(i-1,j-1);
			if (wise(coord(i,j),coord(i-1,j-1))) {
				move_comp(coord(i,j),coord(i-1,j-1));
				return true;
			}
		}
	}
	return false;
}
function possibilities(x,y) {
	if (!jump(x,y))
		if (!single(x,y))
 			return true;
		else
 			return false;
		else
			return false;
}

function prevent(end,s) {
 	i = end.x;
	j = end.y;
	if (!possibilities(s.x,s.y))
		return true;
	else if ((integ(board[i-1][j+1])==-1) && (legal_move(coord(i-1,j+1),coord(i,j)))) {
		return move_comp(coord(i-1,j+1),coord(i,j));
	} else if ((integ(board[i+1][j+1])==-1) && (legal_move(coord(i+1,j+1),coord(i,j)))) {
		return move_comp(coord(i+1,j+1),coord(i,j));
	} else if ((board[i-1][j-1]==-1.1) && (legal_move(coord(i-1,j-1),coord(i,j)))) {
		return move_comp(coord(i-1,j-1),coord(i,j));
	} else if ((board[i+1][j-1]==-1.1) && (legal_move(coord(i+1,j-1),coord(i,j)))) {
		return move_comp(coord(i+1,j-1),coord(i,j));
	} else {
		return false;
	}
}

function wise(from,to) {
	 i = to.x;
	 j = to.y;
	 n = (j>0);
	 s = (j<7);
	 e = (i<7);
	 w = (i>0);
	 if (n&&e) ne = board[i+1][j-1]; else ne = null;
	 if (n&&w) nw = board[i-1][j-1]; else nw = null;
	 if (s&&e) se = board[i+1][j+1]; else se = null;
	 if (s&&w) sw = board[i-1][j+1]; else sw = null;
	 eval(((j-from.y != 1)?"s":"n")+((i-from.x != 1)?"e":"w")+"=0;");
	 if ((sw==0) && (integ(ne)==1)) return false;
	 if ((se==0) && (integ(nw)==1)) return false;
	 if ((nw==0) && (se==1.1)) return false;
	 if ((ne==0) && (sw==1.1)) return false;
	 return true;
}

my_turn = true;

function selectCurBox(col, row) {
	unSelCurBox();
	checkerRowPosition = row;
	checkerColumnPosition = col;
	selCurBox();
}

function selCurBox() {
//	return;
	var curBox = "checkerId" + checkerRowPosition + "" + checkerColumnPosition;
	try {
		document.getElementById(curBox).style.border = "1px solid yellow";
	} catch (x) {
		
	}
}

function unSelCurBox() {
	var curBox = "checkerId" + checkerRowPosition + "" + checkerColumnPosition;
	try {
		document.getElementById(curBox).style.border = "1px solid black";
	} catch (x) {
		
	}
}
function gameKeyHandler(keyCodeNum) {
	if(gameGenreCurrent == 1) {
		ticTacKeyHandler(keyCodeNum);
		return;
	} else if(gameGenreCurrent == 2) {
		sudokuKeyHandler(keyCodeNum);
		return;
	} else if(gameGenreCurrent == 3) {
		mineSweeperkeyHandler(keyCodeNum);
		return;
	} else if(gameGenreCurrent == 4) {
		snakeKeyHandler(keyCodeNum);
		return;
	} else if(gameGenreCurrent == 5) {
		tetrisKeyHandler(keyCodeNum);
		return;
	} else if(gameGenreCurrent == 6) {
		chessKeyHandler(keyCodeNum);
		return;
	}
	
	switch(keyCodeNum) {
		case rcLEFT:
			if(gamePage == 0) {
				 gamePage = 1;
			} else if(gamePage == 1) {
				document.getElementById("resetGamePanel").style.background = "none";
				unSelCurBox();
				--checkerColumnPosition;
				if(checkerColumnPosition < 0) {
					checkerColumnPosition += 8;
				}
				selCurBox();
			}
			break;
		case rcRIGHT:
			if(gamePage == 0) {
				 gamePage = 1;
			} else if(gamePage == 1) {
				document.getElementById("resetGamePanel").style.background = "none";
				unSelCurBox();
				++checkerColumnPosition;
				if(checkerColumnPosition > 7) {
					checkerColumnPosition -= 8;
				}
				selCurBox();
			}
			break;
		case rcUP:
			if(gamePage == 0) {
				if(gameGenreCurrent == 0) { // first one									
					break;
				} 
				gameGenreCurrent--;
				// if the cursor is moving up, no scroll is needed
				if(gameGenreCursor != 0) { // move cursor
					gameGenreCursor--;					
					changeGameGenreCursor();
				} else { // scroll
					var start = gameGenreCurrent; 
					var end = gameGenreCurrent + 9;	
					--gameGenreClicks;
					scrollGameGenrePage(start, end);							
				}			
				gameGenreSelected = gameGenreCurrent;
				buildGameTitleCache();		
			} else if(gamePage == 1) {
				document.getElementById("resetGamePanel").style.background = "none";
				unSelCurBox();
				--checkerRowPosition;
				if(checkerRowPosition < 0) {
					checkerRowPosition += 8;
				} 
				selCurBox();
			}
			break;
		case rcDOWN:
			if(gamePage == 0) {
				if(gameGenreCurrent == gameGenreTotal) { // last one
//					message(13);												
					break;
				} 
				gameGenreCurrent++;
				// if the cursor is moving down, no scroll is needed
				if(gameGenreCursor < gameGenreMax) { // move cursor
//					message("111");
					gameGenreCursor++;					
					changeGameGenreCursor();
				} else { // scroll
//					message("111");
					var start = gameGenreCurrent - 9; 
					var end = gameGenreCurrent;		
					++gameGenreClicks;	
					scrollGameGenrePage(start, end);							
				}			
				gameGenreSelected = gameGenreCurrent;
				buildGameTitleCache();					
			} else if(gamePage == 1) {
				unSelCurBox();
				++checkerRowPosition;
				if(checkerRowPosition > 7) {
					checkerRowPosition -= 1;
					if(document.getElementById("resetGamePanel") != null)
						document.getElementById("resetGamePanel").style.background = "green";
				} else {
					selCurBox();
				}
			}
			break;
		case rcOK:
			if(gamePage == 0) {
			} else if(gamePage == 1) {
//				alert(document.getElementById("resetGamePanel").style.background);
				if((document.getElementById("resetGamePanel").style.background).indexOf("green") >= 0) {
					document.getElementById("resetGamePanel").style.background = "none";
					resetGame();
				} else {
					unSelCurBox();
					clicked(checkerColumnPosition, checkerRowPosition);
				}
			}
			break;
		case rcMENU:
			 escapeGamePanel();
			 break;
	}
}
/////////////////////////
// Crackers Panel ends //
/////////////////////////

/////////////////////////
///// Tic Tac Toe vars //
/////////////////////////
var pause = 0;
var all = 0;
var aValue = 0;
var bValue = 0;
var cValue = 0;
var dValue = 0;
var eValue = 0;
var fValue = 0;
var gValue = 0;
var hValue = 0;
var iValue = 0;
var temp="";
var ok = 0;
var cf = 0;
var choice=9;
var aRandomNumber = 0;
var comp = 0; 
var t = 0;
var wn = 0;
var ls = 0;
var ts = 0;
var xImage = "./view/tv/images/widgets/ticTacToe/x.png";
var oImage = "./view/tv/images/widgets/ticTacToe/o.png";
var blank = "./view/tv/images/widgets/ticTacToe/blank.png"

var curTicTacPosition = 0;
var gamePanelStatus = 1;

function help() {
	message("Welcome to Tic-Tac-Toe!  You play as the X's and the computer is the O's.  Select the square you want to put your X into by clicking them.  You cannot occupy aValue square that is already occupied. The first player to get three squares in a row wins.  Good Luck!!")
}

function logicOne() {
	if ((aValue==1)&&(bValue==1)&&(cValue==1)) all=1;
	if ((aValue==1)&&(dValue==1)&&(gValue==1)) all=1;
	if ((aValue==1)&&(eValue==1)&&(iValue==1)) all=1;
	if ((bValue==1)&&(eValue==1)&&(hValue==1)) all=1;
	if ((dValue==1)&&(eValue==1)&&(fValue==1)) all=1;
	if ((gValue==1)&&(hValue==1)&&(iValue==1)) all=1;
	if ((cValue==1)&&(fValue==1)&&(iValue==1)) all=1;
	if ((gValue==1)&&(eValue==1)&&(cValue==1)) all=1;
	if ((aValue==2)&&(bValue==2)&&(cValue==2)) all=2;
	if ((aValue==2)&&(dValue==2)&&(gValue==2)) all=2;
	if ((aValue==2)&&(eValue==2)&&(iValue==2)) all=2;
	if ((bValue==2)&&(eValue==2)&&(hValue==2)) all=2;
	if ((dValue==2)&&(eValue==2)&&(fValue==2)) all=2;
	if ((gValue==2)&&(hValue==2)&&(iValue==2)) all=2;
	if ((cValue==2)&&(fValue==2)&&(iValue==2)) all=2;
	if ((gValue==2)&&(eValue==2)&&(cValue==2)) all=2;
	if ((aValue != 0)&&(bValue != 0)&&(cValue != 0)&&(dValue != 0)&&(eValue != 0)&&(fValue != 0)&&(gValue != 0)&&(hValue != 0)&&(iValue != 0)&&(all == 0)) all = 3;
} 

function logicTwo() {
	if ((aValue==2)&&(bValue==2)&&(cValue== 0)&&(temp=="")) temp="C";
	if ((aValue==2)&&(bValue== 0)&&(cValue==2)&&(temp=="")) temp="B";
	if ((aValue== 0)&&(bValue==2)&&(cValue==2)&&(temp=="")) temp="A";
	if ((aValue==2)&&(dValue==2)&&(gValue== 0)&&(temp=="")) temp="G";
	if ((aValue==2)&&(dValue== 0)&&(gValue==2)&&(temp=="")) temp="D";
	if ((aValue== 0)&&(dValue==2)&&(gValue==2)&&(temp=="")) temp="A";
	if ((aValue==2)&&(eValue==2)&&(iValue== 0)&&(temp=="")) temp="I";
	if ((aValue==2)&&(eValue== 0)&&(iValue==2)&&(temp=="")) temp="E";
	if ((aValue== 0)&&(eValue==2)&&(iValue==2)&&(temp=="")) temp="A";
	if ((bValue==2)&&(eValue==2)&&(hValue== 0)&&(temp=="")) temp="H";
	if ((bValue==2)&&(eValue== 0)&&(hValue==2)&&(temp=="")) temp="E";
	if ((bValue== 0)&&(eValue==2)&&(hValue==2)&&(temp=="")) temp="B";
	if ((dValue==2)&&(eValue==2)&&(fValue== 0)&&(temp=="")) temp="F";
	if ((dValue==2)&&(eValue== 0)&&(fValue==2)&&(temp=="")) temp="E";
	if ((dValue== 0)&&(eValue==2)&&(fValue==2)&&(temp=="")) temp="D";
	if ((gValue==2)&&(hValue==2)&&(iValue== 0)&&(temp=="")) temp="I";
	if ((gValue==2)&&(hValue== 0)&&(iValue==2)&&(temp=="")) temp="H";
	if ((gValue== 0)&&(hValue==2)&&(iValue==2)&&(temp=="")) temp="G";
	if ((cValue==2)&&(fValue==2)&&(iValue== 0)&&(temp=="")) temp="I";
	if ((cValue==2)&&(fValue== 0)&&(iValue==2)&&(temp=="")) temp="F";
	if ((cValue== 0)&&(fValue==2)&&(iValue==2)&&(temp=="")) temp="C";
	if ((gValue==2)&&(eValue==2)&&(cValue== 0)&&(temp=="")) temp="C";
	if ((gValue==2)&&(eValue== 0)&&(cValue==2)&&(temp=="")) temp="E";
	if ((gValue== 0)&&(eValue==2)&&(cValue==2)&&(temp=="")) temp="G";
}

function logicThree() {
	if ((aValue==1)&&(bValue==1)&&(cValue==0)&&(temp=="")) temp="C";
	if ((aValue==1)&&(bValue==0)&&(cValue==1)&&(temp=="")) temp="B";
	if ((aValue==0)&&(bValue==1)&&(cValue==1)&&(temp=="")) temp="A";
	if ((aValue==1)&&(dValue==1)&&(gValue==0)&&(temp=="")) temp="G";
	if ((aValue==1)&&(dValue==0)&&(gValue==1)&&(temp=="")) temp="D";
	if ((aValue==0)&&(dValue==1)&&(gValue==1)&&(temp=="")) temp="A";
	if ((aValue==1)&&(eValue==1)&&(iValue==0)&&(temp=="")) temp="I";
	if ((aValue==1)&&(eValue==0)&&(iValue==1)&&(temp=="")) temp="E";
	if ((aValue==0)&&(eValue==1)&&(iValue==1)&&(temp=="")) temp="A";
	if ((bValue==1)&&(eValue==1)&&(hValue==0)&&(temp=="")) temp="H";
	if ((bValue==1)&&(eValue==0)&&(hValue==1)&&(temp=="")) temp="E";
	if ((bValue==0)&&(eValue==1)&&(hValue==1)&&(temp=="")) temp="B";
	if ((dValue==1)&&(eValue==1)&&(fValue==0)&&(temp=="")) temp="F";
	if ((dValue==1)&&(eValue==0)&&(fValue==1)&&(temp=="")) temp="E";
	if ((dValue==0)&&(eValue==1)&&(fValue==1)&&(temp=="")) temp="D";
	if ((gValue==1)&&(hValue==1)&&(iValue==0)&&(temp=="")) temp="I";
	if ((gValue==1)&&(hValue==0)&&(iValue==1)&&(temp=="")) temp="H";
	if ((gValue==0)&&(hValue==1)&&(iValue==1)&&(temp=="")) temp="G";
	if ((cValue==1)&&(fValue==1)&&(iValue==0)&&(temp=="")) temp="I";
	if ((cValue==1)&&(fValue==0)&&(iValue==1)&&(temp=="")) temp="F";
	if ((cValue==0)&&(fValue==1)&&(iValue==1)&&(temp=="")) temp="C";
	if ((gValue==1)&&(eValue==1)&&(cValue==0)&&(temp=="")) temp="C";
	if ((gValue==1)&&(eValue==0)&&(cValue==1)&&(temp=="")) temp="E";
	if ((gValue==0)&&(eValue==1)&&(cValue==1)&&(temp=="")) temp="G";
}

function clearOut() {
	try {
	document.getElementById("myTicToeScore").innerHTML = "0";
	document.getElementById("compTicToeScore").innerHTML = "0";
	document.getElementById("ticTacToeTies").innerHTML = "0";
	} catch(x) {
		
	}
}

function checkSpace() {
	if ((temp=="A")&&(aValue==0)) {
		ok=1;
		if (cf==0) aValue=1;
		if (cf==1) aValue=2;
	}
	if ((temp=="B")&&(bValue==0)) {
		ok=1;
		if (cf==0) bValue=1;
		if (cf==1) bValue=2;
	}
	if ((temp=="C")&&(cValue==0)) {
		ok=1;
		if (cf==0) cValue=1;
		if (cf==1) cValue=2;
	}
	if ((temp=="D")&&(dValue==0)) {
		ok=1;
		if (cf==0) dValue=1;
		if (cf==1) dValue=2;
	}
	if ((temp=="E")&&(eValue==0)) {
		ok=1;
		if (cf==0) eValue=1;
		if (cf==1) eValue=2;
	}
	if ((temp=="F")&&(fValue==0)) {
		ok=1
		if (cf==0) fValue=1;
		if (cf==1) fValue=2;
	}
	if ((temp=="G")&&(gValue==0)) {
		ok=1
		if (cf==0) gValue=1;
		if (cf==1) gValue=2;
	}
	if ((temp=="H")&&(hValue==0)) {
		ok=1;
		if (cf==0) hValue=1;
		if (cf==1) hValue=2;
	}
	if ((temp=="I")&&(iValue==0)) {
		ok=1;
		if (cf==0) iValue=1; 
		if (cf==1) iValue=2; 
	}
}

function highLightBoxSpace(index) {
	try {
		document.getElementById("box" + curTicTacPosition).style.background = "none";
		curTicTacPosition = index;
		document.getElementById("box" + curTicTacPosition).style.background = "OliveDrab";
	} catch (exception) {
		
	}
}
function yourChoice(chName, curPosition) {
	if(curPosition != null) {
		highLightBoxSpace(curPosition);
	} 
	try {
		pause = 0;
		if (all!=0) 
			ended();
		if (all==0) {
			cf = 0;
			ok = 0;
			temp=chName;
			checkSpace();
			if (ok==1) {
//				alert(x);
				document.images[chName].src = xImage;
			}
			if (ok==0)
				taken();
			process();
			if ((all==0)&&(pause==0)) 
				myChoice();
		   }
	} catch(exception) {
//		alert(exception);
	}
}
function taken() {
	message("That square is already occupied.  Please select another square.")
//	message(trim(records.key1425));
	pause=1;
}
function myChoice() {
	temp="";
	ok = 0;
	cf=1;
	logicTwo();
	logicThree();
	checkSpace();
	while(ok==0) {
		aRandomNumber=Math.random()
		comp=Math.round((choice-1)*aRandomNumber)+1;
		if (comp==1) temp="A";
		if (comp==2) temp="B";
		if (comp==3) temp="C";
		if (comp==4) temp="D";
		if (comp==5) temp="E";
		if (comp==6) temp="F";
		if (comp==7) temp="G";
		if (comp==8) temp="H";
		if (comp==9) temp="I";
		checkSpace();
	}
	document.images[temp].src= oImage;
	process();
	}
	function ended() {
		message("The game has over. To play a new game click reset button.")
//		message(trim(records.key1426));
	}
	function process() {
	logicOne();
	if (all==1){ 
		message("You won, congratulations!");
//		message(trim(records.key1427));
		wn++; 
	}
	if (all==2){ 
		message("Gotcha! I win!");
//		message(trim(records.key1437)); 		 
		ls++;
	}
	if (all==3){ 
		message("We tied.");
//		message(trim(records.key1428)); 
		ts++; 
	}
	if (all!=0) {
		try {
		document.getElementById("myTicToeScore").innerHTML = wn;
		document.getElementById("compTicToeScore").innerHTML = ls;
		document.getElementById("ticTacToeTies").innerHTML = ts;
		} catch(x) {
			
		}
	}
}
function playAgain() {
	if (all==0) {
		message("This will restart the game and clear all the current scores."); 
		reset();
	}
	if (all>0) reset();
}

function reset() {
	all = 0;
	aValue = 0;
	bValue = 0;
	cValue = 0;
	dValue = 0;
	eValue = 0;
	fValue = 0;
	gValue = 0;
	hValue = 0;
	iValue = 0;
	temp="";
	ok = 0;
	cf = 0;
	choice=9;
	aRandomNumber = 0;
	curTicTacPosition = 0;
	comp = 0; 
	document.images.A.src= blank;
	document.images.B.src= blank;
	document.images.C.src= blank;
	document.images.D.src= blank;
	document.images.E.src= blank;
	document.images.F.src= blank;
	document.images.G.src= blank;
	document.images.H.src= blank;
	document.images.I.src= blank;
	if(document.getElementById("messagePanel"))
		document.getElementById("messagePanel").innerHTML = "";
}

function putTValue() {
	unselTicTacPanels();
	pause = 0;
	wn = 0;
	ls = 0;
	ts = 0;
	t = 0;
}

function makeNewGame() {
	unselTicTacPanels();
	if (t==0) {
		t=2; myChoice();
	}
	t--;
}

function unselTicTacPanels() {
	for(var i = 0; i < 9; i++) {
		if(document.getElementById("box" + i) != null)
			document.getElementById("box" + i).style.background = "DarkSlateGray";
	}
//	message(trim(records.key1429) + "!"); 
}

function createTicTacToePanel() {
	gamePanelStatus = 1;
	gameGenreCurrent = 1;
	document.getElementById("openChartId").innerHTML = "";
	var statusInfo = 1;
	var ticTacToeDim = "65px";
	var ticTacToeHTML = '<table align="center" height="220px" width="100%" style="border:1px solid gray;"><tr><td><img valign="middle" width="15px" height="15px" onclick="homePanelVod(1);" style="cursor: pointer;" src="/view/mobi/images/home.png" alt=""/><img valign="middle" width="15px" height="15px" id="resetGamePanel" style="cursor: pointer;" src="/view/tv/images/widgets/cancel.png" onmouseover="selResetBtn(1);" onclick="resetGame();" onmouseout="selResetBtn(2);" alt=""/></td></tr><tr><td width="316px" align="center" style="text-align:center;"><table width="316px" align="center" style="color:OliveDrab;text-align:center;">';
		ticTacToeHTML += '<tr>'
						+'<td  id="box0"' + (statusInfo == 1 ? ' onclick=\'yourChoice("A", 0);\' style="cursor:pointer;border:1px solid gray;background:DarkSlateGray;" ' : ' style="border:1px solid gray;background:DarkSlateGray;" ' )+ ' width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" border="0" ><img width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" src="/view/tv/images/widgets/ticTacToe/blank.png" name="A" alt="Top-Left" ></td>'
						+'<td  id="box1"' + (statusInfo == 1 ? ' onclick=\'yourChoice("B", 1);\' style="cursor:pointer;border:1px solid gray;background:DarkSlateGray;" ' : ' style="border:1px solid gray;background:DarkSlateGray;" ' )+ '  width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" border="0"  ><img width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" src="/view/tv/images/widgets/ticTacToe/blank.png" name="B" alt="Top-Center" ></td>'
						+'<td  id="box2"' + (statusInfo == 1 ? ' onclick=\'yourChoice("C", 2);\' style="cursor:pointer;border:1px solid gray;background:DarkSlateGray;" ' : ' style="border:1px solid gray;background:DarkSlateGray;" ' )+ ' width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" border="0" height="100" ><img width="'+ticTacToeDim+'" height="'+ticTacToeDim+'"  src="/view/tv/images/widgets/ticTacToe/blank.png" name="C" alt="Top-Right" ></td>'
		ticTacToeHTML += '</tr>'
		ticTacToeHTML += '<tr>'
						+'<td  id="box3"' + (statusInfo == 1 ? ' onclick=\'yourChoice("D", 3);\' style="cursor:pointer;border:1px solid gray;background:DarkSlateGray;" ' : ' style="border:1px solid gray;background:DarkSlateGray;" ' )+ ' width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" border="0" ><img width="'+ticTacToeDim+'" height="'+ticTacToeDim+'"  src="/view/tv/images/widgets/ticTacToe/blank.png" name="D" alt="Top-Left" ></td>'
						+'<td  id="box4"' + (statusInfo == 1 ? ' onclick=\'yourChoice("E", 4);\' style="cursor:pointer;border:1px solid gray;background:DarkSlateGray;" ' : ' style="border:1px solid gray;background:DarkSlateGray;" ' )+ ' width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" border="0" ><img width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" src="/view/tv/images/widgets/ticTacToe/blank.png" name="E" alt="Top-Center" ></td>'
						+'<td  id="box5"' + (statusInfo == 1 ? ' onclick=\'yourChoice("F", 5);\' style="cursor:pointer;border:1px solid gray;background:DarkSlateGray;" ' : ' style="border:1px solid gray;background:DarkSlateGray;" ' )+ ' width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" border="0" ><img width="'+ticTacToeDim+'" height="'+ticTacToeDim+'"  src="/view/tv/images/widgets/ticTacToe/blank.png" name="F" alt="Top-Right" ></td>'
		ticTacToeHTML += '</tr>'
		ticTacToeHTML += '<tr>'
						+'<td  id="box6"' + (statusInfo == 1 ? ' onclick=\'yourChoice("G", 6);\' style="cursor:pointer;border:1px solid gray;background:DarkSlateGray;" ' : ' style="border:1px solid gray;background:DarkSlateGray;" ' )+ ' width="'+ticTacToeDim+'" height="'+ticTacToeDim+'"  border="0" ><img width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" src="/view/tv/images/widgets/ticTacToe/blank.png" name="G" alt="Top-Left" ></td>'
						+'<td  id="box7"' + (statusInfo == 1 ? ' onclick=\'yourChoice("H", 7);\' style="cursor:pointer;border:1px solid gray;background:DarkSlateGray;" ' : ' style="border:1px solid gray;background:DarkSlateGray;" ' )+ ' width="'+ticTacToeDim+'" height="'+ticTacToeDim+'"  border="0" ><img width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" src="/view/tv/images/widgets/ticTacToe/blank.png" name="H" alt="Top-Center" ></td>'
						+'<td  id="box8"' + (statusInfo == 1 ? ' onclick=\'yourChoice("I", 8);\' style="cursor:pointer;border:1px solid gray;background:DarkSlateGray;" ' : ' style="border:1px solid gray;background:DarkSlateGray;" ' )+ ' width="'+ticTacToeDim+'" height="'+ticTacToeDim+'"  border="0" ><img width="'+ticTacToeDim+'" height="'+ticTacToeDim+'" src="/view/tv/images/widgets/ticTacToe/blank.png" name="I" alt="Top-Right" ></td>'
		ticTacToeHTML += '</tr>'
					+'</table></td></tr></table>';
		document.getElementById("openChartId").innerHTML = ticTacToeHTML;
		document.getElementById("box0").style.background = "darkoliveGreen";

//		message(trim(records.key1429) + "!"); 
}
function selTicTacPanel(index) {
	try {
		document.getElementById("box" + index).style.background = "darkoliveGreen";
	} catch(x) {
		curTicTacPosition = 0;
		gamePanelStatus = 2;
		if(document.getElementById("resetGamePanel"))
			document.getElementById("resetGamePanel").style.background = "OliveDrab";
	}
}

function ticTacKeyHandler(keyCodeNum) {
	if(document.getElementById("box" + curTicTacPosition) != null)
		document.getElementById("box" + curTicTacPosition).style.background = "DarkSlateGray";
	if(document.getElementById("resetGamePanel") != null)	
		document.getElementById("resetGamePanel").style.background = "none";
	switch(keyCodeNum) {
		case rcLEFT:
			gamePanelStatus = 1;
			try {
				--curTicTacPosition;
//				document.getElementById("box" + curTicTacPosition).style.background = "OliveDrab";
				selTicTacPanel(curTicTacPosition);
			} catch (x) {
				curTicTacPosition += 3;
//				document.getElementById("box" + curTicTacPosition).style.background = "OliveDrab";
				selTicTacPanel(curTicTacPosition);
			}
			break;
		case rcRIGHT:
			try {
				++curTicTacPosition;
				selTicTacPanel(curTicTacPosition);
//				document.getElementById("box" + curTicTacPosition).style.background = "OliveDrab";
			} catch (x) {
//				curTicTacPosition = 0;
				gamePanelStatus = 2;
				document.getElementById("resetGamePanel").style.background = "OliveDrab";
			}
			break;
		case rcDOWN:
			gamePanelStatus = 1;
			try {
				curTicTacPosition += 3;
				selTicTacPanel(curTicTacPosition);
//				document.getElementById("box" + curTicTacPosition).style.background = "OliveDrab";
			} catch (x) {
				curTicTacPosition -= 9;
				selTicTacPanel(curTicTacPosition);
//				document.getElementById("box" + curTicTacPosition).style.background = "OliveDrab";
			}
			break;
		case rcUP:
			gamePanelStatus = 1;
			try {
				curTicTacPosition -= 3;
				selTicTacPanel(curTicTacPosition);
//				document.getElementById("box" + curTicTacPosition).style.background = "OliveDrab";
			} catch (x) {
				curTicTacPosition += 9;
				selTicTacPanel(curTicTacPosition);
//				document.getElementById("box" + curTicTacPosition).style.background = "OliveDrab";
			}
			break;
		case rcOK:
			if(gamePanelStatus == 1) {
				selTicTacPanel(curTicTacPosition);
//				document.getElementById("box" + curTicTacPosition).style.background = "DarkSlateGray";
				var curCode = getTicTacCode(curTicTacPosition);
				yourChoice(curCode);
			} else if(gamePanelStatus == 2) {
				gamePanelStatus = 1;
				document.getElementById("resetGamePanel").style.background = "none";
				resetGame();
				curTicTacPosition = 0;
				selTicTacPanel(curTicTacPosition);
//				document.getElementById("box" + curTicTacPosition).style.background = "OliveDrab";
			}
			break;
		case rcMENU:
			reset();
			putTValue();
			if(gameMenuStatus) {
				drawGamePanelMenu();
			} else {
				showGoPanel();
				gameActive = false; 
				showGuidePanel();
			}
			break;
		case rcREFRESH:
			refreshSTB();
			break;
	}
}

function getTicTacCode(index) {
	var code = "";
	switch(index) {
		case 0:
			code = "A";
			break;
		case 1:
			code = "B";
			break;
		case 2:
			code = "C";
			break;
		case 3:
			code = "D";
			break;
		case 4:
			code = "E";
			break;
		case 5:
			code = "F";
			break;
		case 6:
			code = "G";
			break;
		case 7:
			code = "H";
			break;
		case 8:
			code = "I";
			break;
	}
	return code;
}


//////////////////////
// Tic Tac Toe Ends //
//////////////////////

////////////////////////
// sudoku game begins //
////////////////////////
/*
	function updateSudokuPanel() {
		var p =0;
		var q = 0;
		var sudokuHTML = "";
		var fst = 0;
		var scnd = 0;
		var third = 0;
		var fourth = 0;
		
		for(var i = 0; i < 9; i++) {
			if(i/3 == 0) {
				sudokuHTML += '<tr>';
			}
			for(var j=0; j < 9; j++) {
				if(j/3 == 0) {
					sudokuHTML += '<td style="border:1px solid black;" id="sudokuSection' + q + '"><table>';
				}
				var curI = i/3;
				
				if(curI == 0 && j/3 == 0) {
					sudokuHTML += '<tr>';
				}
				sudokuHTML += '<td id="sudokuSection_' + (i + '_' + j) + '" width="30px" height="30px" style="border:1px solid black;">' + (++p) + '</td>';
				if(curI == 0 && j/3 == 0) {
					sudokuHTML += '</tr>';
				}
				
				if(j/3 == 0) {
					sudokuHTML += '</table></td>';
				}
				
				
			}
			if(i/3 == 0) {
				sudokuHTML += '</tr>';
			}
		}
		
		
//		for(var i = 0; i < 3; i++) {
//			sudokuHTML += '<tr>';
//			for(var j=0; j < 3; j++) {
//				sudokuHTML += '<td style="border:1px solid black;" id="sudokuSection' + q + '"><table>';
//				for(var k = 0; k < 3; k++) {
//					sudokuHTML += '<tr>';
//					for(var l=0; l < 3; l++) {
//						 sudokuHTML += '<td id="sudokuSection_' + ((q + k) + '_' + (q - (3*i) +l)) + '" width="30px" height="30px" style="border:1px solid black;">' + (fst + ',' + scnd + ',' + third + ',' + fourth ) + '</td>';
//						++fourth;
//					}
//					sudokuHTML += '</tr>';
//					++third;
//				}
//				sudokuHTML += '</table><td>';
//				++q;
//				++scnd;
//			}
//			sudokuHTML += '</tr>';
//			++fst;
//		}
//		document.getElementById("sudoku").innerHTML = sudokuHTML;
	return sudokuHTML;
	}
//	function initSudoku()
//	{	
////		updateSudokuPanel();
//		document.getElementById("gameId").innerHTML = '<table>' + document.getElementById("sudoku").innerHTML + '</table>';
//}
*/

	var sudokuGameStatus = false;
	var squareObjects = new Array();
	var level = 1;	// 1 is lowest level
	var countSquares = [36,36,34,32,31,30];
	var gameFinished = false;
	function shuffleBoard()	{
		for(var counter=0;counter<30;counter++){
			var number1 = Math.ceil(Math.random()*9);
			var number2 = Math.ceil(Math.random()*9);
			while(number2==number1){
				number2 = Math.ceil(Math.random()*9);
			}	

			var tmpObjects1 = new Array();
			var tmpObjects2 = new Array();
			for(var no=0;no<squareObjects.length;no++){	
				var txtObj = squareObjects[no].getElementsByTagName('SPAN')[0];	
				try {	
					if(txtObj.innerHTML == number1)tmpObjects1.push(txtObj);	
					if(txtObj.innerHTML == number2)tmpObjects2.push(txtObj);
				} catch(x) {
					
				}
			}
			for(var no=0;no<tmpObjects1.length;no++){
				tmpObjects1[no].innerHTML = number2;	
				tmpObjects2[no].innerHTML = number1;	
			}
		}
		resetVisibleNumberArray();
		showColumnsInGroup();
	}
	
	function resetVisibleNumberArray() {
		for(var no=0;no<=9;no++){
			visibleNumberArray[no] = 0;
		}		
	}
	
	function newGame() {
		var obj = document.getElementById('sudoku');
		var subObjects = obj.getElementsByTagName('DIV');
		for(var no=0;no<subObjects.length;no++){
			if(subObjects[no].className=='sudokuSquare'){
				subObjects[no].style.backgroundColor='';	
				var spans = subObjects[no].getElementsByTagName('SPAN');
				spans[0].style.display='none';
				spans[1].innerHTML = '';
			}
		}	
	}
	
	var visibleNumberArray = new Array();

	function randomizeArray(a,b) {
		return Math.random() - Math.random();
	}
//	var countItnow = 0;	
	function showCell(inputDiv)	{
		var span = inputDiv.getElementsByTagName('SPAN')[0];
		span.style.display='';
		inputDiv.style.backgroundColor='#DDD';
//		alert(inputDiv)
		span.style.color='#317082';
		var typingSpan = inputDiv.getElementsByTagName('SPAN')[1];
		typingSpan.style.display='none';			
		
	}
	var getNumArray = new Array();
	function showColumnsInGroup(){	
		var object = document.getElementById('sudoku');
		var cellsRevealed = new Array();
		var numberArray = new Array();
		var groupCountArray = new Array();
		var maxInGroup=5;
		if(level<=0)level=1;
		if(level==1)maxInGroup=4;
		for(var no=0;no<countSquares[level];no++) {			
			do {
				var row = Math.floor(Math.random()*9);
				var col = Math.floor(Math.random()*9);
				var obj = document.getElementById('square_' + row + '_' + col);
				var parentID = obj.parentNode.id;
				var span = obj.getElementsByTagName('SPAN')[0];	
				if(!numberArray[span.innerHTML])numberArray[span.innerHTML]=0;
				if(!groupCountArray[parentID])groupCountArray[parentID]=0;
			} while(cellsRevealed[row + '_' + col] || numberArray[span.innerHTML]>(3+Math.ceil(level/2)) || groupCountArray[parentID]>=maxInGroup);
			cellsRevealed[row + '_' + col] = true;
			getNumArray[row][col] = true;
			if(!numberArray[span.innerHTML])numberArray[span.innerHTML]=0;
			numberArray[span.innerHTML]++;
			groupCountArray[parentID]++;
			showCell(obj);
		}
	}
	
	function changeNow() {
		for (var i = 0; i < 9; i++) {
			getNumArray[i] = new Array(9);
			for(var j = 0; j< 9; j++) {
				getNumArray[i][j] = false;
			}
		}
	}
	
	
	var higlightedCell;
	var selVacBox = 0;
	function highlightSquare(e,inputObj){
		if(!inputObj)
			inputObj = this;	
		var inputIds = inputObj.id.toString();
		inputIds = inputIds.substring(inputIds.indexOf("_") + 1, inputIds.length);
		var idIndex = inputIds.split("_");
		var indexRow = parseInt(idIndex[0]);
		var indexCol = parseInt(idIndex[1]);
		if(getNumArray[indexRow][indexCol] == true) {
			if(inputObj.style.backgroundColor == "green") {
				inputObj.style.backgroundColor = "#FFFFFF";
			}
			sudokuGameStatus = true;
			return;
		}

		if(gameFinished)
			return;
		sudokuGameStatus = false;
		inputObj.className='sudokuSquareHighlighted';
		if(higlightedCell && higlightedCell!=inputObj) {
			higlightedCell.className='sudokuSquare';
		} 
		higlightedCell = inputObj;
	}
	
	// 
	function isGameFinished() {
		var obj = document.getElementById('sudoku');
		var subDivs = obj.getElementsByTagName('DIV');
		var allOk = true;
		for(var no=0;no<subDivs.length;no++){
			if(subDivs[no].className.indexOf('sudokuSquare')>=0 && !subDivs[no].style.backgroundColor){
				var spans = subDivs[no].getElementsByTagName('SPAN');
				if(spans[0].innerHTML != spans[1].innerHTML){
					allOk=false;
					break;
				}
			}	
		}
		if(allOk) {
			message(trim(records.key1430) + "!"); 
		}
		
	}
	//
	function initSudoku() {
		gameGenreCurrent = 2;
		changeNow();
		document.getElementById("gameId").innerHTML = '<table>' + document.getElementById("sudokuPanel").innerHTML + '</table>';
		message("Enter the unique number between 1 to 9 in a column or row!");
//		message(trim(records.key1431)); 
		gameFinished = false;
//		document.getElementById('hintDiv').style.display='none';
//		document.getElementById(inputObj.id).style.background ='none';
		var matrix = new Array();
		for(var rowCounter=0;rowCounter<9;rowCounter++) {
			matrix[rowCounter] = new Array();
			for(var colCounter=0;colCounter<9;colCounter++) {
				var curVal = colCounter/1;
				var number = curVal + 1 + (rowCounter*3) + Math.floor(rowCounter/3)%3;
				if(number>9)number = number % 9;
				if(number==0)number=9;
				matrix[rowCounter][colCounter] = number;				
			}			
		}
		// Switching rows
		for(var no=0;no<9;no+=3){
			for(var no2=0;no2<3;no2++) {
				row1 = Math.floor(Math.random()*3);	
				row2 = Math.floor(Math.random()*3);	
				while(row2==row1) {
					row2 = Math.floor(Math.random()*3);	
				}
				row1 = row1 + no;
				row2 = row2 + no;			
				var tmpMatrix = new Array();
				tmpMatrix = matrix[row1];
				matrix[row1] = matrix[row2];
				matrix[row2] = tmpMatrix; 				
			}			
		}
		// 
		// Switching columns
		
		for(var no=0;no<9;no+=3){
			for(var no2=0;no2<3;no2++){
				col1 = Math.floor(Math.random()*3);	
				col2 = Math.floor(Math.random()*3);	
				while(col2==col1) {
					col2 = Math.floor(Math.random()*3);	
				}
				col1 = col1 + no;
				col2 = col2 + no;			

				var tmpMatrix = new Array();
				for(var no3=0;no3<matrix.length;no3++){
					tmpMatrixValue = matrix[no3][col1];
					matrix[no3][col1] = matrix[no3][col2];				
					matrix[no3][col2] = tmpMatrixValue;				
				}
			}	
		}
		for(var no=0;no<matrix.length;no++){
			for(var no2=0;no2<matrix[no].length;no2++){				
				var obj = document.getElementById('square_' + no + '_' + no2);
				var spanObjects = obj.getElementsByTagName('SPAN');
				var span = spanObjects[0];
				span.innerHTML = matrix[no][no2];		
				span.style.display='none';	
				spanObjects[1].style.display = '';
				spanObjects[1].style.color='#000';	
				spanObjects[1].innerHTML = '';
				highlightSquare(false,obj);
//				obj.onkeydown = highlightSquare;
				squareObjects.push(obj);						
			}			
		}
//		if(document.all){
//			document.body.onkeydown = insertNumber;
//		}else{
//			document.documentElement.onkeydown = insertNumber;
//		}
		newGame();
		shuffleBoard();
	}
	var sudkuGamePanel = 1;
	var curHelpPosition = 0;
	var sudokuGameStatus = false;
	function sudokuKeyHandler(keyCodeNum) {
		if(sudkuGamePanel == 1) {
//			if(!higlightedCell)return;
//			if(gameFinished)return;
			var span = higlightedCell.getElementsByTagName('SPAN')[1];
			var numbers = higlightedCell.id.split('_');
			var row = numbers[1]/1;
			var col = numbers[2]/1;
			var nextObject = false;
		}
		switch(keyCodeNum) {
			case rcREFRESH:
				refreshSTB();
				break;
			case rcMENU:
				if(gameMenuStatus) {
					drawGamePanelMenu();
				} else {
					showGoPanel();
					gameActive = false; 
					showGuidePanel();
				}
				break;
			case rcLEFT:
				if(sudkuGamePanel == 1) {
					if(col>0){
						nextObject = document.getElementById('square_' + row + '_' + (col/1-1));
						if(nextObject.style.backgroundColor){
							while(col>0 && nextObject.style.backgroundColor){
								col = col-1;
								nextObject = document.getElementById('square_' + row + '_' + col);
							}
						}
						if(nextObject.style.backgroundColor)
							nextObject = false;
					}
					if(nextObject){
						highlightSquare(false,nextObject);
					} 
				} else if(sudkuGamePanel == 2) {
					sudkuGamePanel = 1;
					document.getElementById("helpPanel" + curHelpPosition).style.color = "white";
				}
				break;
			case rcRIGHT:
				if(sudkuGamePanel == 2) {
					document.getElementById("helpPanel" + curHelpPosition).style.color = "yellow";
				}
				if(sudkuGamePanel == 1) {
					if(col<8) {
						nextObject = document.getElementById('square_' + row + '_' + (col/1+1));
						if(nextObject.style.backgroundColor){
							while(col<8 && nextObject.style.backgroundColor){
								col = col+1;
								nextObject = document.getElementById('square_' + row + '_' + col);
							}
						}				
					}
					if(nextObject){
						highlightSquare(false,nextObject);
						if(sudokuGameStatus) {
							sudkuGamePanel = 2;
							document.getElementById("helpPanel" + curHelpPosition).style.color = "yellow";
						}
					} else {
						sudkuGamePanel = 2;
						document.getElementById("helpPanel" + curHelpPosition).style.color = "yellow";
					} 
				} 
				break;
			case rcUP:
				if(sudkuGamePanel == 1) {
					if(row>0){
						nextObject = document.getElementById('square_' + (row-1) + '_' + col);
						if(nextObject.style.backgroundColor){
							while(row>0 && nextObject.style.backgroundColor){
								row = row-1;
								nextObject = document.getElementById('square_' + row + '_' + col);
							}
						}				
					}
					if(nextObject){
						highlightSquare(false,nextObject);
					} 
				} else if(sudkuGamePanel == 2) {
					if(document.getElementById("helpPanel" + curHelpPosition)) {
						document.getElementById("helpPanel" + curHelpPosition).style.color = "white";
					}
					--curHelpPosition;
					if(document.getElementById("helpPanel" + curHelpPosition)) {
						document.getElementById("helpPanel" + curHelpPosition).style.color = "yellow";
					} else {
						++curHelpPosition;
						document.getElementById("helpPanel" + curHelpPosition).style.color = "yellow";
					}
				}
				break;
			case rcDOWN:
				if(sudkuGamePanel == 1) {
					if(row<8){
						nextObject = document.getElementById('square_' + (row+1) + '_' + col);
						if(nextObject.style.backgroundColor){
							while(row<8 && nextObject.style.backgroundColor){
								row = row+1;
								nextObject = document.getElementById('square_' + row + '_' + col);
							}
						}	
					}
					if(nextObject){
						highlightSquare(false,nextObject);
					}
				} else if(sudkuGamePanel == 2) {
					if(document.getElementById("helpPanel" + curHelpPosition)) {
						document.getElementById("helpPanel" + curHelpPosition).style.color = "white";
					}
					++curHelpPosition;
					if(document.getElementById("helpPanel" + curHelpPosition)) {
						document.getElementById("helpPanel" + curHelpPosition).style.color = "yellow";
					} else {
						--curHelpPosition;
						document.getElementById("helpPanel" + curHelpPosition).style.color = "yellow";
					}
				}
				break;
			case rcOK:
				if(sudkuGamePanel == 2) {
					if(curHelpPosition == 0) {
						revealAll();
					} else if(curHelpPosition == 1) {
						initSudoku();
					} else if( curHelpPosition == 2) {
						showHint();
					} else if( curHelpPosition == 3) {
						switchLevel(1,this);
					} else if(curHelpPosition == 4) {
						switchLevel(2,this);
					} else if(curHelpPosition == 5) {
						switchLevel(3,this);
					} else if(curHelpPosition == 6) {
						switchLevel(4,this);
					}
				}
				break;
			case rcONE:
			case rcTWO:
			case rcTHREE:
			case rcFOUR:
			case rcFIVE:
			case rcSIX:
			case rcSEVEN:
			case rcEIGHT:
			case rcNINE:
				if(nextObject){
					highlightSquare(false,nextObject);
				}
				var keyString = keyCodeNum -48;
				if(keyCodeNum>48 && keyCodeNum<=57) {				
					var theChar = keyString.toString();//String.fromCharCode(keyCodeNum);
					span.innerHTML = theChar;
				}		
			break;
		}
		isGameFinished();
	}
	
	function selHelpPanel() {
		if(document.getElementById("helpPanel" + curHelpPosition)) {
			document.getElementById("helpPanel" + curHelpPosition).style.color = "yellow";
		}
	}
	function unselHelpPanel() {
		if(document.getElementById("helpPanel" + curHelpPosition)) {
			document.getElementById("helpPanel" + curHelpPosition).style.color = "none";
		}
	}
	
	var curNumPosition = 1; 
	function putNumber(index) {
		putSudokuNumber(index);
		var theChar = document.getElementById("sudokuKey" + index).innerHTML;
		var span = higlightedCell.getElementsByTagName('SPAN')[1];
		span.innerHTML = theChar;
		isGameFinished();
	}
	
	function putSudokuNumber(index) {
		if(document.getElementById("sudokuKey" + curNumPosition)) {
			document.getElementById("sudokuKey" + curNumPosition).style.background = "DarkOliveGreen";
		}
		curNumPosition  = index;
		if(document.getElementById("sudokuKey" + index)) {
			document.getElementById("sudokuKey" + index).style.background = "OliveDrab";
		}
	}
	
	function resetSudokuNumbers() {
		for(var i = 1; i < 10; i++) {
			if(document.getElementById("sudokuKey" + i)) {
				document.getElementById("sudokuKey" + i).style.background = "DarkOliveGreen";
			}
		}
	}
	
	function selKeyBoard(str) {
		resetSudokuNumbers();
		nextObject = document.getElementById('square_' + str);
		if(nextObject) {
			highlightSquare(false,nextObject);
		}
		if(document.getElementById("sudokuKey" + 1)) {
			document.getElementById("sudokuKey" + 1).style.background = "OliveDrab";
		}
		curNumPosition  = 1;
	}	
	
	function insertNumber(e) {
//		document.getElementById('hintDiv').style.display='none';

//		if(document.all)e = event;
//		if(!higlightedCell)return;
//		if(gameFinished)return;
//		if (e.keyCode) code = e.keyCode; else if (e.which) code = e.which;
		var span = higlightedCell.getElementsByTagName('SPAN')[1];
		
		var numbers = higlightedCell.id.split('_');
		var row = numbers[1]/1;
		var col = numbers[2]/1;
		var nextObject = false;
			
		if(code==39){ // Right arrow
			if(col<8){
				nextObject = document.getElementById('square_' + row + '_' + (col/1+1));
				if(nextObject.style.backgroundColor){
					while(col<8 && nextObject.style.backgroundColor){
						col = col+1;
						nextObject = document.getElementById('square_' + row + '_' + col);
					}
				}				
			}
		}
		if(code==37){ // Left arrow
			if(col>0){
				nextObject = document.getElementById('square_' + row + '_' + (col/1-1));
				if(nextObject.style.backgroundColor){
					while(col>0 && nextObject.style.backgroundColor){
						col = col-1;
						nextObject = document.getElementById('square_' + row + '_' + col);
					}
				}
				if(nextObject.style.backgroundColor)nextObject = false;
			}
		}
		if(code==38){ // UP arrow
			if(row>0){
				nextObject = document.getElementById('square_' + (row-1) + '_' + col);
				if(nextObject.style.backgroundColor){
					while(row>0 && nextObject.style.backgroundColor){
						row = row-1;
						nextObject = document.getElementById('square_' + row + '_' + col);
					}
				}				
			}
		}		 
		if(code==40){ // down Arrow
			if(row<8){
				nextObject = document.getElementById('square_' + (row+1) + '_' + col);
				if(nextObject.style.backgroundColor){
					while(row<8 && nextObject.style.backgroundColor){
						row = row+1;
						nextObject = document.getElementById('square_' + row + '_' + col);
					}
				}	
			}
		}
		
		if(nextObject){
			highlightSquare(false,nextObject);
		}
		
		if(code==46 || code==8){	// Delete
			span.innerHTML = '';
			if(code==8)return false;
		}
		if(code>96 && code<=105)
			code-=48;
		if(code>48 && code<=57){				
			var theChar = String.fromCharCode(code);
			span.innerHTML = theChar;
		}		
		
		isGameFinished();
	}	
	
	function helpMe() {
		if(gameFinished)return false;
		
		if(confirm('Do you want me to reveal a number for you?')) {
			var allreadyRevealed = true;
			var counter = 0;
			do {
				var row = Math.floor(Math.random()*9);
				var col = Math.floor(Math.random()*9);
				
				var el = document.getElementById('square_'+row+'_'+col);	
				
				var spans = el.getElementsByTagName('SPAN');
				if(spans[1].innerHTML.length==0){
					spans[1].innerHTML = spans[0].innerHTML;
					spans[1].style.color='#FF0000';
					allreadyRevealed =  false;					
				}	
				if(el.style.backgroundColor)allreadyRevealed=true;
				counter++
			} while(allreadyRevealed && counter<500);		
		}
		isGameFinished();
	}
		
	function isCorrect(divObj) {
		var spans = divObj.getElementsByTagName('SPAN');
		if(spans[0].innerHTML==spans[1].innerHTML || spans[1].innerHTML.length==0)return true;
		return false;		
	}
	
	function getTopPos(inputObj) {
	  var returnValue = inputObj.offsetTop;
	  while((inputObj = inputObj.offsetParent) != null) {
	  	returnValue += inputObj.offsetTop;
	  }
	  return returnValue;
	}
	
	function getLeftPos(inputObj) {
		var returnValue = inputObj.offsetLeft;
		while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
		return returnValue;
	}
		
	function getPossibleNumbers(inputObj) {
		var noArray = new Array();
		var countNumbers = 0;
		var spans = inputObj.getElementsByTagName('SPAN');
		if(spans[0].innerHTML ==spans[1].innerHTML)return 0;
		
		var parentDiv = inputObj.parentNode;
		var subDivs = parentDiv.getElementsByTagName('DIV');
		for(var no=0;no<subDivs.length;no++) {
			if(subDivs[no]!=inputObj) {
				var spans = subDivs[no].getElementsByTagName('SPAN');
				if(spans[0].innerHTML == spans[1].innerHTML || subDivs[no].style.backgroundColor.length>1){
					if(!noArray[spans[0].innerHTML]){
						noArray[spans[0].innerHTML] = true;		
						countNumbers++;
					}		
				}
			}	
		}
	
		var numbers = inputObj.id.split('_');
		var row = numbers[1];
		var col = numbers[2];
		
		for(var no=0;no<9;no++) {			
			var obj = document.getElementById('square_' + row + '_' + no);
			if(obj!=inputObj){
				var spans = obj.getElementsByTagName('SPAN');	
				if(spans[0].innerHTML == spans[1].innerHTML || !spans[0].style.display){
					if(!noArray[spans[0].innerHTML]){
						noArray[spans[0].innerHTML] = true;		
						countNumbers++;
					}			
				}
			}
			
			var obj = document.getElementById('square_' + no + '_' + col);
			if(obj!=inputObj){
				var spans = obj.getElementsByTagName('SPAN');	
				if(spans[0].innerHTML == spans[1].innerHTML || !spans[0].style.display){
					if(!noArray[spans[0].innerHTML]){
						noArray[spans[0].innerHTML] = true;	
						countNumbers++;
					}				
				}
			}
		}	

		return countNumbers;
	}
	
	function showHint()	{
//		var hintDiv = document.getElementById('hintDiv');
//		var hintDivInner = hintDiv.getElementsByTagName('DIV')[0];
		var maxExistingNo = 0;	
		var objectToTry =false;	
		for(var row=0;row<9;row++){
			for(var col=0;col<9;col++){
				var obj = document.getElementById('square_' + row + '_' + col);
				if(obj.style.backgroundColor)continue;
				if(!isCorrect(obj)){
//					hintDivInner.innerHTML = 'This one is wrong';
					var numbers = obj.id.split('_');
					if(obj != null)
						document.getElementById(obj.id).style.background = "red";
//					hintDiv.style.left = getLeftPos(obj) + 'px';
//					hintDiv.style.top = getTopPos(obj) - 50 + 'px';
//					hintDiv.style.display='none';		
					return;			
				}	
				var existingNumbers = getPossibleNumbers(obj);	
				if(existingNumbers>maxExistingNo){
					maxExistingNo = existingNumbers;
					objectToTry = obj;				
				}	
			}
		}
		
		if(objectToTry) {
//			hintDivInner.innerHTML = 'Try this one ';
			var numbers = objectToTry.id.split('_');
//			message(numbers);
//			hintDiv.style.background = "green";
//			message(objectToTry.id);
			var idCur = objectToTry.id;
			document.getElementById(idCur).style.background	= "orange";
//			hintDiv.style.left = getLeftPos(objectToTry) + 'px';
//			hintDiv.style.top = getTopPos(objectToTry) - 50 + 'px';
//			hintDiv.style.display='block';				
			
		}
	}
	
	
	function revealAll() {
		for(var row=0;row<9;row++) {
			for(var col=0;col<9;col++) { 
				var obj =document.getElementById('square_'+row+'_'+col);
				var spans = obj.getElementsByTagName('SPAN');
				spans[0].style.display='';
				spans[1].style.display='none';	
				spans[1].style.color='#000000';	
			}
		}
		gameFinished=true;
	}
	
	function switchLevel(initLevel,linkObj)	{
		var confirmSwitch = gameFinished;
		if(!confirmSwitch){
			message('Starting the new game of ' + getSudokuGameLevel(initLevel) + ' level');
//			message(trim(records.key1432) + " " + getSudokuGameLevel(initLevel) + " " + trim(records.key1433)); 
			confirmSwitch = true;
		}
		if(confirmSwitch) {
			var parentObj = linkObj.parentNode.parentNode;
			var links = parentObj.getElementsByTagName('A');
			for(var no=0;no<links.length;no++) {
				links[no].style.fontWeight='normal';
			}
			linkObj.style.fontWeight = 'bold';
			level = initLevel;
			setTimeout('initSudoku()',20);		
		}
	}
	
	function getSudokuGameLevel(index) {
		var gameLevel = "beginner";
		switch(index) {
			case 1:
				gameLevel = "beginner";
				break;
			case 2:
				gameLevel = "moderate";
				break;
			case 3:
				gameLevel = "hard";
				break;
			case 4:
				gameLevel = "expert";
				break;
		}
		return gameLevel;
	}
	
//////////////////////
// sudoku game ends //
//////////////////////

///////////////////////////////////
// minesweeper game panel begins //
///////////////////////////////////

// Constants initialized by the server-side PHP script
var width = 16;        // squares in x direction
var total = 160;//256;       // total squares
var mines = 40;       // number of mines to lay
// End constants

/* "adjacent" and "exposed" are indexed by square number = y*width+x */
  
/* "adjacent" contains the board layout and derived state.  adjacent[i] is
   the count of mines adjacent to square i, or "mine" if square i contains
   a mine.  */
var adjacent = new Array();         // count of adjacent mines
var mine = 9;                       // adjacency count for a mine
  
/* "exposed" contains the exposure state of the board.
   Values > "unexposed" represent exposed squares; these either have the
   distinquished values "exploded" or "incorrect", or some greater value
   (left over from the pending exposure queue) for plain old exposed
   squares.  Values <= "unexposed" include plain old unexposed squares, or
   one of the markers.

   During the "expose" method, the queue of pending exposures is a linked
   list through this array, using array indexes.  The method holds the head
   and tail.  "listEnd" is the tail marker.
*/
var exposed = new Array();          // exposure state / pending exposures
var listEnd = -1;                   // end marker in "exposed"
var incorrect = -2;                 // incorrect flag, at end of game
var exploded = -3;                  // exploded mine (at end of game!)
var unexposed = -4;                 // default state at start of game
var flagged = -5;                   // marker flag by user
var queried = -6;                   // query flag by user

var erasing = 0;                    // smiley absent during initialization
var sad = 1;                        // smiley value after loss
var bored = 2;                      // smiley value during game
var happy = 3;                      // smiley value after win
  
var flags = 0;                      // count of flags currently set
var remaining = 0;                  // count of unexposed squares
var sadness = happy;                // whether smiley is sad
var startTimeDate;                      // time of first click, if any
var timer = false;                  // periodic elapsed time updater

var sqColor = [
	"#000000", "#3333cc", "#006600",
	"#cc0000", "#660066", "#006666",
	"#000000", "#000000", "#000000"];

function setMines() {
	// update remaining mines display
	var elt = document.getElementById("mines");
	var count = mines - flags;
	elt.innerHTML = (count < -99 ? "-&#x221E;" : "" + count);
}

function setElapsed() {
	// update elapsed time display
	var elt = document.getElementById("timer");
	if (timer) {
		var now = new Date();
		var secs = Math.floor((now.getTime() - startTimeDate.getTime())/1000);
		elt.innerHTML = ((secs > 999) ? "&#x221E;" : "" + secs);
	} else {
		elt.innerHTML = "&nbsp;";
	}
}

function setHappy() {
	// update the happy/sad icon display
	var smiley = document.getElementById("smiley");
	smiley.src =
		(sadness == erasing ? "view/tv/images/widgets/minesweeper/erasing.jpg" :
		(sadness == sad ? "view/tv/images/widgets/minesweeper/sad.jpg" :
		(sadness == bored ? "view/tv/images/widgets/minesweeper/bored.jpg" :
		"view/tv/images/widgets/minesweeper/happy.jpg")));
}

function setSq(thisSquare) {
// update square display, based on "exposed" and "adjacent"
	var sq = null; 
	try {
		sq = document.getElementById("sq-" + thisSquare);
	} catch(x) {
	}
	
	var exp = exposed[thisSquare];
	if (exp <= unexposed) {
		// unexposed squares, including flagged or queried
		var s;
		if (exp == unexposed) {
			s = "&nbsp;";x
		} else if (exp == flagged) {
			s = "&#x203B;";
		} else {
			s = "?";
		}
		/// 
		try {
			sq.innerHTML = s;
		} catch(x) {
		}
		sq.style.border = "#eeeeee 1px outset";
		sq.style.backgroundColor = "GhostWhite";
		sq.style.color = "black";
	} else {
		// exposed squares
		var adj = adjacent[thisSquare];
		var s;
		var c = "#000000";
		if (exp == exploded) {
			s = "&#x203B;";
			c = "#ff0000";
		} else if (exp == incorrect) {
			s = "&#x00D7;";
			c = "#ff0000";
		} else if (adj == mine) {
			s = "&#x203B;";
		} else if (adj == 0) {
			s = "&nbsp;";
		} else {
			s = "" + adj;
			c = sqColor[adj];
		}
		sq.innerHTML = s;
		sq.style.border = "#bbbbbb 1px solid";
		sq.style.backgroundColor = "#bbbbbb";
		sq.style.color = c;
	}
}

function timerAction() {
	// Called via setTimeout
	// Update the elapsed time, and schedule another call if wanted
	// Note: setInterval is similar, but stops (Safarai 1.3) after
	// user has navigated away then returned to the page.
	if (timer) {
		setElapsed();
		setTimeout("timerAction()", 100);
	}
}

function startTimer() {
//	return; // Stoping the running timer 
	startTimeDate = new Date();
	timer = true;
	timerAction();
}

function endGame(outcome) {
	// Turn off the timer and update the smiley
	timer = false;
	sadness = outcome;
	setHappy();
}

function applyToNeighbours(thisSquare, f) {
	// Apply given function to each existing neighbours of given square
	// This is the only part of the program that knows the topology
	// The performance of this function has a visible effect on the program
	var x = thisSquare % width;
	if (thisSquare >= width) { // there's a row above
		if (x > 0) f(thisSquare - width - 1);
		f(thisSquare - width);
		if (x+1 < width) f(thisSquare - width + 1);
	}
	if (x > 0) f(thisSquare - 1);
	if (x+1 < width) f(thisSquare + 1);
	if (thisSquare < total-width) { // there's a row below
		if (x > 0) f(thisSquare + width - 1);
		f(thisSquare + width);
		if (x+1 < width) f(thisSquare + width + 1);
	}
}

var tail = listEnd;                  // tail of pending exposures

function expose1(thisSquare) {
	// Expose square and add to pending exposure list.
	if (exposed[thisSquare] <= unexposed &&
										exposed[thisSquare] != flagged) {
		remaining--;
		exposed[thisSquare] = listEnd;
		exposed[tail] = thisSquare;
		tail = thisSquare;
		setSq(thisSquare);
	}
}
///////////////////////////////////////////////////////////////////////////////
/////The Click method that is called when the box is got clicked or pressed  //
///////////////////////////////////////////////////////////////////////////////
function clickSq(event, thisSquare) {
	if(!event) event = window.event; // IE versus the rest
	if (sadness != bored) { 
		return false; // Game over: do nothing
	}
//	alert(thisSquare);
	if (!timer) startTimer();
	if (exposed[thisSquare] > unexposed) {
		// already exposed: do nothing
//	} else if (!event.which && event.button == 0) {
//		// mouse-up after right-click on IE: do nothing
//	} else 
//	if (event.shiftKey || event.button == 2) {
//		// flag or unflag
//		var exp = exposed[thisSquare];
//		if (exp == unexposed) {
//			exposed[thisSquare] = flagged;
//			flags++;
//			setMines();
//		} else if (exp == flagged) {
//			exposed[thisSquare] = queried;
//			flags--;
//			setMines();
//		} else if (exp == queried) {
//			exposed[thisSquare] = unexposed;
//		}
//		setSq(thisSquare);
	} else if (adjacent[thisSquare] == mine) {
		// exposing a mine: explode it and expose other mines
		remaining--;
		exposed[thisSquare] = exploded;
		setSq(thisSquare);
		var i;
		for (i = 0; i < total; i++) {
			if (i==thisSquare) {
			} else if (adjacent[i] == mine && exposed[i] != flagged) {
				remaining--;
				exposed[i] = listEnd;
				setSq(i);
			} else if (adjacent[i] != mine && exposed[i] == flagged) {
				remaining--;
				exposed[i] = incorrect;
				setSq(i);
			}
		}
		endGame(sad);
	} else {
		// expose the square, if not already exposed
		// If square has 0 adjacency, expose surrounding squares,
		// and iterate
		if (exposed[thisSquare] == flagged) {
			flags--;
			setMines();
		}
		remaining--;
		exposed[thisSquare] = listEnd;
		tail = thisSquare;
		setSq(thisSquare);
		var pending = thisSquare;
		// Until pending reaches the end of the exposure list, expose
		// neighbors
		while (pending != listEnd) {
			if (adjacent[pending]==0) applyToNeighbours(pending, expose1);
			pending = exposed[pending];
		}
		if (remaining==mines) {
			// End of game: flag all remaining unflagged mines
			var i;
			for (i = 0; i < total; i++) {
				if (adjacent[i] == mine && exposed[i] <= unexposed &&
												exposed[i] != flagged ) {
					exposed[i] = flagged;
					flags++;
					setSq(i);
				}
			}
			setMines();
			endGame(happy);
		}
	}
	highlightMinesweeper(thisSquare);
	return false;
}

function neighbourIsMine(thisSquare) {
	// Increase adjacency count, if this isn't itself a mine
	if (adjacent[thisSquare] != mine) adjacent[thisSquare]++;
}

function layMines() {
	// Lay the mines
	var laid = 0;
	while (laid < mines) {
		var target = Math.floor(Math.random() * total);
		// Despite what others might say, it's possible that "target
		// = total".  This is because although Math.random() is < 1,
		// in an extreme case the multiplication by "total" will round up.
		// We need to allow for this, if we really care about correctness.
		if (target < total && adjacent[target] != mine) {
			adjacent[target] = mine;
			applyToNeighbours(target, neighbourIsMine);
			laid++;
		}
	}
}
// 
function eraseRows() {
	// erase square contents
	var i;
	for (i = 0; i < total; i++) {
		adjacent[i] = 0;
		if (exposed[i] != unexposed) {
			exposed[i] = unexposed;
//			alert(7);
			setSq(i);
		}
	}
}
// Forked part of erase
function erase2() {
	// Forked part of erase
	eraseRows();
	layMines();
	sadness = bored;
	setHappy();
	return false;
}

function erase() {
	// Erase the board.  Uses "sadness" to disable clicks meanwhile
	if (sadness != erasing) {
		flags = 0;
		setMines();
		remaining = total;
		endGame(erasing);
		setElapsed();
		setTimeout("erase2()", 1); // allow repaint of score area
	}
}

function clickSmiley(event) {
	// Click in the smiley face.
	if (!event) event = window.event; // IE versus the rest
	if (event.button != 2) erase();
	return false;
}
////////////////////////////////////////////
// Function to built new minseweeper game //
////////////////////////////////////////////
function initMineSweeper() {
	total = 160;
	curMsPage = 0;
	curMSPosition = 0;
	gameGenreCurrent = 3;
	document.getElementById("gameId").innerHTML = "";
	message("Please click on reset for starting new game");
	try {
//		message(trim(records.key1434));
	} catch(x) {
//		alert(1);
	}
	//	document.getElementById("gameId").innerHTML = '<table align="center" style="text-align:center;">' + document.getElementById("mineSweeperPanel").innerHTML + '</table>';
	document.getElementById("gameId").innerHTML = '<table align="left" style="text-align:left;margin-left:80px;" width="425px" height="325px">' + document.getElementById("mineSweeperPanel").innerHTML + '</table>';
	//	return;
	try {
		var sqTable = document.getElementById("sqTable");
		sqTable.onselectstart = function() { 
			return false; 
		};
	} catch(x) {
//		alert(2);
	}
	var i;
	for (i = 0; i < total; i++) {
		var sq = document.getElementById("sq-" + i);
//		sq.oncontextmenu = sq.onmousedown;
	}
	showGamePanel();
	try {
		erase();
	} catch(x) {
	}
	try {
		highlightMinesweeper(0);
	} catch(x) {
	}
}
function highlightMinesweeper(index) {
	unselMinesweeper(curMSPosition);
	curMSPosition = index;
	try {
		document.getElementById("sq-" + index).style.backgroundColor = "darkkhaki";
	} catch(x) {
//		alert(7);
	}
}

function unselMinesweeper(index) {
	try {
		curMSPosition = index;
		document.getElementById("sq-" + index).style.backgroundColor = "GhostWhite";
	} catch(x) {
//		alert(8);
	}
}
var curMSPosition = 0;
var curMsPage = 0;
function mineSweeperkeyHandler(keyCodeNum) {
	switch(keyCodeNum) {
		case rcLEFT:
			if(curMsPage == 0) {
				unselMinesweeper(curMSPosition);
				--curMSPosition;
				try {
					highlightMinesweeper(curMSPosition)
				} catch(x) {
					++curMSPosition;
				}
			} 
			break;
		case rcRIGHT:
			if(curMsPage == 0) {
				unselMinesweeper(curMSPosition);
				++curMSPosition;
				try {
					highlightMinesweeper(curMSPosition)
				} catch(x) {
					--curMSPosition;
				}
			} 
			break;
		case rcUP:
			if(curMsPage == 0) {
				unselMinesweeper(curMSPosition);
				curMSPosition -= 16;
				try {
					highlightMinesweeper(curMSPosition)
				} catch(x) {
					curMSPosition += 16;
					document.getElementById("smiley").style.border = "1px solid red";
					curMsPage = 1;
				}
			} else if(curMsPage == 2){
				curMsPage = 0;
				document.getElementById("resetGamePanel").style.background = "none";
				highlightMinesweeper(curMSPosition);
			} 
			break;
		case rcDOWN:
			if(curMsPage == 0) {
				unselMinesweeper(curMSPosition);
				curMSPosition += 16;
				try {
					highlightMinesweeper(curMSPosition);
				} catch(x) {
					curMSPosition -= 16;
					curMsPage = 2;
					document.getElementById("resetGamePanel").style.background = "green";
				}
			} else if(curMsPage == 1){
				document.getElementById("smiley").style.border = "0px solid red";
				curMsPage = 0;
				highlightMinesweeper(curMSPosition);
			} 
			break;
		case rcMENU:
			if(gameMenuStatus) {
				drawGamePanelMenu();
			} else {
				showGoPanel();
				gameActive = false; 
				showGuidePanel();
			}
			break;
		case rcOK:
//			var obj = document.getElementById('sq-'+ curMSPosition);
			if(curMsPage == 0) {
				clickSq(false, curMSPosition);
			} else if(curMsPage == 1) {
				curMsPage = 0;
				curMSPosition = 0;
				document.getElementById("smiley").style.border = "0px solid red";
				erase();
			} else if(curMsPage == 2) {
				document.getElementById("resetGamePanel").style.background = "none";
				curMsPage = 0;
				curMSPosition = 0;
				resetGame();
			}
			break;
		case rcREFRESH:
			refreshSTB();	
			break;
	}
}	

////////////////////////////
// Minesweeper Panel ends //
////////////////////////////
/********************************/

var i;
Richtung = '+1';
var block = 0;
var zuEnde = 0;
var Zelle;
var Countdown = 3;
var Leckerli;
var Level = 0;
var Fruechte;
var blah, fnord = false;
var Snake = new Array();
var Kopf;

function Tastendruck(Druck) {
	if (document.all) k = window.event.keyCode; else k = Druck.which;

	if (k == 37 && !block && Richtung != '+1')  { Richtung = '-1';  block = 1; }
	if (k == 38 && !block && Richtung != '+20') { Richtung = '-20'; block = 1; }
	if (k == 39 && !block && Richtung != '-1')  { Richtung = '+1';  block = 1; }
	if (k == 40 && !block && Richtung != '-20') { Richtung = '+20'; block = 1; }
}

var C3 = [48, 49, 67, 70, 90, 109, 130, 147, 150, 168, 169];
var C2 = [48, 49, 67, 70, 90, 109, 128, 147, 167, 168, 169, 170];
var C1 = [49, 68, 69, 87, 89, 109, 129, 149, 167, 168, 169, 170, 171];
var Smiley = [27, 28, 29, 30, 31, 32, 46, 53, 65, 68, 71, 74, 85, 88, 91, 94, 105, 114, 125, 127, 132, 134, 145, 148, 149, 150, 151, 154, 166, 173, 187, 188, 189, 190, 191, 192];
var Frowny = [27, 28, 29, 30, 31, 32, 46, 53, 65, 68, 71, 74, 85, 88, 91, 94, 105, 114, 125, 129, 130, 134, 145, 148, 151, 154, 166, 173, 187, 188, 189, 190, 191, 192];
var Jubel1 = [27, 28, 29, 30, 31, 32, 41, 46, 53, 58, 61, 65, 68, 71, 74, 78, 81, 85, 88, 91, 94, 98, 102, 103, 104, 105, 114, 115, 116, 117, 125, 127, 128, 129, 130, 131, 132, 134, 145, 148, 149, 150, 151, 154, 166, 173, 187, 188, 189, 190, 191, 192];
var Jubel2 = [20, 39, 41, 47, 48, 49, 50, 51, 52, 58, 62, 66, 73, 77, 83, 85, 88, 91, 94, 96, 104, 105, 108, 111, 114, 115, 125, 134, 145, 147, 148, 149, 150, 151, 152, 154, 165, 168, 169, 170, 171, 174, 186, 193, 207, 208, 209, 210, 211, 212];

// Leer:
var Wall0     = []
var noFruit0  = []
// Rechteck in der Mitte:
var Wall1     = [67, 68, 69, 70, 71, 72, 87, 92, 107, 112, 127, 132, 147, 148, 149, 150, 151, 152]
var noFruit1  = [88, 89, 90, 91, 108, 109, 110, 111, 128, 129, 130, 131]
// 2 Dreiecke:
var Wall2     = [40, 59, 60, 61, 78, 79, 81, 82, 97, 98, 102, 103, 116, 117, 121, 122, 137, 138, 140, 141, 158, 159, 160, 179]
var noFruit2  = [80, 99, 100, 101, 118, 119, 120, 139]
// Auto:
var Wall3     = [46, 47, 48, 49, 50, 51, 52, 53, 54, 65, 70, 75, 83, 84, 86, 87, 88, 89, 90, 91, 92, 93, 94, 96, 102, 110, 117, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 143, 146, 153, 156, 164, 165, 174, 175]
var noFruit3  = [66, 67, 68, 69, 71, 72, 73, 74, 85, 95, 103, 104, 105, 106, 107, 108, 109, 111, 112, 113, 114, 115, 116, 144, 145, 154, 155]
// JS:
var Wall4     = [68, 71, 72, 73, 74, 75, 76, 77, 88, 91, 108, 111, 112, 113, 114, 115, 116, 117, 128, 137, 148, 157, 162, 163, 164, 165, 166, 167, 168, 171, 172, 173, 174, 175, 176, 177]
var noFruit4  = [92, 93, 94, 95, 96, 97]
// 5 Sternchen
var Wall5     = [15, 34, 36, 44, 55, 63, 65, 84, 110, 129, 131, 141, 150, 157, 160, 162, 176, 178, 181, 197]
var noFruit5  = [35, 64, 130, 140, 161, 177, 180, 200, 201]
// 3 Karos:
var Wall6     = [23, 36, 42, 44, 55, 57, 61, 65, 74, 78, 82, 84, 95, 97, 103, 110, 116, 129, 131, 148, 152, 169, 171, 190]
var noFruit6  = [43, 56, 62, 63, 64, 75, 76, 77, 83, 96, 130, 149, 150, 151, 170]
// Kreuz
var Wall7     = [10, 30, 50, 70, 90, 100, 101, 102, 103, 104, 115, 116, 117, 118, 119, 130, 150, 170, 190, 210]
var noFruit7  = []
// Misel:
var Wall8     = [61, 62, 63, 64, 65, 67, 69, 70, 71, 73, 74, 75, 77, 81, 83, 85, 87, 89, 93, 97, 101, 103, 105, 107, 109, 110, 111, 113, 114, 115, 117, 121, 125, 127, 131, 133, 137, 141, 145, 147, 149, 150, 151, 153, 154, 155, 157, 158, 159]
var noFruit8  = [82, 84, 90, 91, 94, 95, 102, 104, 129, 130, 134, 135]
// 8 Quadrate und ein Rechteck in der Mitte:
var Wall9     = [21, 22, 23, 25, 26, 27, 32, 33, 34, 36, 37, 38, 41, 43, 45, 47, 52, 54, 56, 58, 61, 62, 63, 65, 66, 67, 72, 73, 74, 76, 77, 78, 89, 90, 109, 110, 129, 130, 141, 142, 143, 145, 146, 147, 152, 153, 154, 156, 157, 158, 161, 163, 165, 167, 172, 174, 176, 178, 181, 182, 183, 185, 186, 187, 192, 193, 194, 196, 197, 198]
var noFruit9  = [42, 46, 53, 57, 162, 166, 173, 177]
// 4 kleine und ein großes Kreuz:
var Wall10    = [24, 30, 35, 42, 43, 45, 46, 50, 53, 54, 56, 57, 64, 70, 75, 101, 102, 103, 104, 105, 106, 107, 108, 109, 111, 112, 113, 114, 115, 116, 117, 118, 144, 150, 155, 162, 163, 165, 166, 170, 173, 174, 176, 177, 184, 190, 195]
var noFruit10 = [44, 55, 164, 175]
// Inka-Gesicht:
var Wall11    = [21, 22, 23, 24, 25, 26, 27, 32, 33, 34, 35, 36, 37, 38, 47, 52, 61, 62, 63, 64, 65, 67, 72, 74, 75, 76, 77, 78, 87, 89, 90, 92, 101, 102, 103, 104, 105, 106, 107, 109, 110, 112, 113, 114, 115, 116, 117, 118, 121, 138, 141, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 158, 161, 178, 181, 182, 183, 184, 185, 186, 187, 192, 193, 194, 195, 196, 197, 198]
var noFruit11 = []
// symmetrisches Labyrinth:
var Wall12    = [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 41, 58, 61, 63, 64, 65, 66, 67, 68, 71, 72, 73, 74, 75, 76, 78, 81, 83, 96, 98, 103, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 116, 121, 123, 136, 138, 141, 143, 144, 145, 146, 147, 148, 151, 152, 153, 154, 155, 156, 158, 161, 178, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198]
var noFruit12 = []
// Patience:
var Wall13    = [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 41, 61, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 121, 139, 141, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 161, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198]
var noFruit13 = []
// 2 Euros:
var Wall14    = [21, 22, 23, 24, 25, 26, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 48, 50, 68, 70, 81, 82, 83, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 97, 98, 108, 109, 110, 121, 122, 123, 124, 125, 126, 127, 128, 130, 131, 132, 133, 134, 135, 136, 137, 138, 148, 150, 168, 170, 181, 182, 183, 184, 185, 186, 187, 188, 190, 191, 192, 193, 194, 195, 196, 197, 198]
var noFruit14 = [29, 49, 69, 89, 101, 102, 103, 104, 105, 106, 107, 111, 112, 113, 114, 115, 116, 117, 118, 129, 149, 169, 189]

var snakeStartInt = null;
var clearSnakeInt = null;
var clearSnakeActionInt = null;
var clearSnakeGridInt = null;
////////////////////////////////////
// Function to start the new game //
////////////////////////////////////
function Start() {	
	message("Chase the fruits for getting more points!");
//	message(trim(records.key1435) + "!");
	document.getElementById('nG').style.visibility = 'hidden';
	document.getElementById('Level').firstChild.nodeValue = 'Level ' + (Level + 1);
	block = 1;
	if (Countdown && !fnord) {
		resetSnake();
		for (i = 0; i < eval('C' + Countdown).length; i++) {
			Zelle = 'Zelle' + eval('C' + Countdown)[i];
			document.getElementById(Zelle).style.backgroundColor = 'black';
		}
		Countdown--;
		snakeStartInt = window.setTimeout("Start()", 1000);
	} else if (!fnord) {
		resetSnake();
		Fruechte = 10;
		document.getElementById('frucht').value = Fruechte;
		while (Snake[0]) Snake.pop();
		Snake.push(198, 199, 200, 201, 202, 203, 204, 205, 206);
		Kopf = 206;
		block = 0;
		zuEnde = 0;
		Richtung = '+1';
		Happen();
		Hindernisse();
		document.getElementById('pause').style.visibility = 'hidden';
		Verlauf();
	}
}

function Pause() {
	fnord = !fnord;
	if (fnord) document.getElementById('pause').value = "Weiter"; else document.getElementById('pause').value = "Pause";
	Countdown = 3;
	Start();
}

function Happen() {
	Leckerli = Math.floor((Math.random() * 1000) % 220);
	for (i = 0; i < Snake.length; i++) if (Leckerli == Snake[i]) Happen();
	for (i = 0; i < eval('Wall' + Level).length; i++) if (Leckerli == eval('Wall' + Level)[i]) Happen();
	for (i = 0; i < eval('noFruit' + Level).length; i++) if (Leckerli == eval('noFruit' + Level)[i]) Happen();
	document.getElementById('Zelle' + Leckerli).style.backgroundColor = 'red';
}

function Hindernisse() {
	for (i = 0; i < eval('Wall' + Level).length; i++)
		document.getElementById('Zelle' + eval('Wall' + Level)[i]).style.backgroundColor = '#444444';
}
function Verlauf() {
	Kopf = eval(Kopf + Richtung);
	if (Kopf < 0 || Kopf > 219 || (!(Kopf%20) && Richtung == '+1') || (!((Kopf+1)%20) && Richtung == '-1')) zuEnde = 1;
	for (i = 1; i < Snake.length; i++) if (Kopf == Snake[i]) zuEnde = 1;
	for (i = 0; i < eval('Wall' + Level).length; i++) if (Kopf == eval('Wall' + Level)[i]) zuEnde = 1;

	if (!zuEnde) {
		if (Kopf != Leckerli) {
			blah = Snake.shift();
			Snake.push(Kopf);
		} else {
			Fruechte--;
			document.getElementById('frucht').value = Fruechte;
			Snake.push(Kopf);
			Happen();
		}
		Schlange_malen();
		if (Fruechte) {
			block = 0;
			clearSnakeInt = window.setTimeout("Verlauf()",300);
		} else {
			Smiley_malen();
			block = 1;
			Level++;
			if (Level == 15) {
				clearSnakeActionInt = window.setTimeout("Jubel(1)",500);
			} else {
				Countdown = 3;
				if (!fnord) { 
					snakeStartInt = window.setTimeout("Start()",2000);
				}
			}
		}
	} else {
		clearSnakeGridInt = window.setTimeout("Frowny_malen()",500);
		Countdown = 3;
	}
}

function Jubel(x) {
	resetSnake();	
	snakePanelPage = 1; 
	message("Press Ok to start new game!");
//	message(trim(records.key1436));
	unselSnakeKeyPanel();
	document.getElementById('nG').style.visibility = 'visible';
	if (x) {
		for (i = 0; i < Jubel1.length; i++) {
			Zelle = 'Zelle' + Jubel1[i];
			document.getElementById(Zelle).style.backgroundColor = 'black';
		}
	} else {
		for (i = 0; i < Jubel2.length; i++)
		{
			Zelle = 'Zelle' + Jubel2[i];
			document.getElementById(Zelle).style.backgroundColor = 'black';
		}
	}
	x++;
	x %= 2;
	setTimeout("Jubel("+x+")",150);
}

function Smiley_malen() {
	resetSnake();
	document.getElementById('pause').style.visibility = 'visible';
	for (i = 0; i < Smiley.length; i++)
	{
		Zelle = 'Zelle' + Smiley[i];
		document.getElementById(Zelle).style.backgroundColor = 'black';
	}
	zuEnde = 0;
}

function Frowny_malen() {
	resetSnake();
	snakePanelPage = 1;
	message("Press Ok to start new game!");
//	message(trim(records.key1436));
	unselSnakeKeyPanel();
	document.getElementById('nG').style.visibility = 'visible';
	for (i = 0; i < Frowny.length; i++) {
		Zelle = 'Zelle' + Frowny[i];
		document.getElementById(Zelle).style.backgroundColor = 'black';
	}
}

function Schlange_malen() {
	Zelle = 'Zelle' + Snake[0];
	document.getElementById(Zelle).style.backgroundColor = '#87AC3B';
	for (i = 1; i < Snake.length; i++) {
		Zelle = 'Zelle' + Snake[i];
		document.getElementById(Zelle).style.backgroundColor = 'black';
	}
}
//////////////////////////////////////////////
// Function to reseting the snake variables //
//////////////////////////////////////////////
function resetSnake() { 
	resetSnakeInt();
	for (i = 0; i < 220; i++) {
		Zelle = 'Zelle' + i;
		document.getElementById(Zelle).style.backgroundColor = '#87AC3B';
	}
}
/////////////////////////////////////////////
// Function to initialize snake game panel //
/////////////////////////////////////////////
function initSnakeGame() {
	gameGenreCurrent = 4;
//	document.onkeydown = Tastendruck;
	var Zeilen, Spalten;
	var Index = 0;
	var snakeHTML = "";
	resetSnakeInt();
	document.getElementById("gameId").innerHTML = "";
	snakeHTML += '<table border="1" style="color:#aaabab;border: 20px solid DarkOliveGreen;" cellspacing="0" cellpadding="0">';
	for (Zeilen = 0; Zeilen < 11; Zeilen++) {
		snakeHTML += '<tr>';
		for (Spalten = 0; Spalten < 20; Spalten++) {
			snakeHTML += '<td id="Zelle' + Index + '" class="snake" ><\/td>';
			Index++;
		}
		snakeHTML += '<\/tr>';
	}
	snakeHTML +='<\/table>';
	document.getElementById("snakePanel").innerHTML = snakeHTML;
	document.getElementById("gameId").innerHTML = '<table align="left" style="margin-left:50px;">' +  document.getElementById("snakeGamePanel").innerHTML + '</table>';
	if(document.getElementById('nG') != null) {
		snakePanelPage = 1;
		unselSnakeKeyPanel();
		document.getElementById('nG').style.visibility = 'visible';
	}
	message("Press Ok to start new game!");
//	message(trim(records.key1436));	
}
var snakePanelPage = 1;
var curSnakeVerical = 0;
var curSnakeHorrizontal = 0;
var rcLEFT = 37;
var rcUP = 38;
var rcRIGHT = 39;
var rcDOWN = 40;
/////////////////////////////////////////////
// Function to reseting the snake timeouts //
/////////////////////////////////////////////
function resetSnakeInt() {
	if(snakeStartInt) {
		window.clearTimeout(snakeStartInt);
		snakeStartInt = null;
	}
	if(clearSnakeInt) {
		window.clearTimeout(clearSnakeInt);
		clearSnakeInt = null;
	}
	if(clearSnakeActionInt) {
		window.clearTimeout(clearSnakeActionInt);
		clearSnakeActionInt = null;
	}
	if(clearSnakeGridInt) {
		window.clearTimeout(clearSnakeGridInt);
		clearSnakeGridInt = null;
	}
}

function unselSnakeKeyPanel() {
	for(var i = 1; i < 5; i++) {
		try {
//			document.getElementById("snakeMove" + i).style.border = "0px solid green";
			document.getElementById("snakeMove" + i).style.background = "";
		} catch(x) {
			continue;
		}
	}
}

function selSnakeKeyPanel(index) {
	try {
		document.getElementById("snakeMove" + index).style.background = "LightBlue";
//		document.getElementById("snakeMove" + index).style.border = "1px solid green";
	} catch(x) {
		
	}
}

////////////////////////////////////
// Function to handle key actions //
////////////////////////////////////
function snakeKeyHandler(keyCodeNum) {
	switch(keyCodeNum) {
		case rcLEFT:
			if(snakePanelPage == 2) {
				if (!block && Richtung != '+1') { 
					Richtung = '-1';  block = 1;
					unselSnakeKeyPanel();
					selSnakeKeyPanel(1);
				}
			}
			break;
		case rcRIGHT:
			if(snakePanelPage == 2) {
				if (!block && Richtung != '-1') { 
					unselSnakeKeyPanel();
					selSnakeKeyPanel(2); 
					Richtung = '+1';  block = 1; 
				}
			}
			break;
		case rcUP:
			if(snakePanelPage == 2) {
				if (!block && Richtung != '+20') { 
					Richtung = '-20'; block = 1; 
					unselSnakeKeyPanel();
					selSnakeKeyPanel(3);
				}
			}
			break;
		case rcDOWN:
			if(snakePanelPage == 2) {
				if (!block && Richtung != '-20') { 
					Richtung = '+20'; block = 1; 
					unselSnakeKeyPanel();
					selSnakeKeyPanel(4);
				}
			}
			break;
		case rcMENU:
			
			document.getElementById('gameId').innerHTML = "";
			resetSnakeInt();
			if(document.getElementById('nG') != null)
				document.getElementById('nG').style.visibility = 'hidden';
			if(gameMenuStatus) {
				drawGamePanelMenu();
			} else {
				showGoPanel();
				gameActive = false; 
				showGuidePanel();
			}
			break;
		case rcREFRESH:
			refreshStb();
			break;
		case rcOK:
			if(snakePanelPage == 1) {
				snakePanelPage = 2;
				Level=0;
				Start();
			} 
			break;
	}
}
//////////////////////////////////////
// Function to handle mouse actions //
//////////////////////////////////////
function snakeKeyAction(index) {
	switch(index) {
		case 1:
			snakeKeyHandler(rcUP);
			break;
		case 2:
			snakeKeyHandler(rcLEFT);
			break;
		case 3:
			snakeKeyHandler(rcRIGHT);
			break;
		case 4:
			snakeKeyHandler(rcDOWN);
			break;
	}
}
/////////////////////////////////
// Hiding the snake game panel //
/////////////////////////////////
function hideSnakeGame() {
	document.getElementById('gameId').innerHTML = "";
//	resetSnakeGame();
	resetSnake();
	resetSnakeInt();
	if(document.getElementById("nG") != null) {
		document.getElementById('nG').style.visibility = 'hidden';
	}
}
///////////////////////////////////
// Reseting the snake game panel //
///////////////////////////////////
function resetSnakeGame() {
	resetSnake();
	resetSnakeInt();
	snakePanelPage = 2;
	Level=0;
	Start();
}

///////////////////////////
// Snake Game Panel Ends //
///////////////////////////


///////////////////////////////
//////// Game Panel Ends //////
///////////////////////////////
