var selectable = '';

var score = new Array();
var board = new Array();
var animboard = new Array();
var curmoveno = 9999;
var nextmoveno = 9999;
var lastroll = 0;

var animateCount = 100;
var curAnimateMove = -1;

var action = '';
var thisMove = '';
var movesCurRound = 0;
var movesUsedForWin = new Array();

function abs(i) {
	if(i<0) { return -i; } else { return i; }
}

function getCursorPos(myturn,e) {
	var posx = 0;
	var posy = 0;
	var selpos = '';
	if (!e) var e = window.event;
	if (e.clientX || e.clientY) 	{
		posx = e.clientX + (document.documentElement.scrollLeft ?
		   document.documentElement.scrollLeft :
		   document.body.scrollLeft);
		posy = e.clientY + (document.documentElement.scrollTop ?
		   document.documentElement.scrollTop :
		   document.body.scrollTop);
	}
	else if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}

  var fielddiv = document.getElementById('fielddiv');
  var tempX = posx - fielddiv.offsetLeft;
  var tempY = posy - fielddiv.offsetTop;
  
  var i = 0;
  while(i < selectable.length && selpos == '') {
    pyy = selectable.charCodeAt(i) - 48;
    pxx = selectable.charCodeAt(i+1) - 48;;
    py = (8 - pyy - pxx) * PIECEDIST + PIECEOFFSET;
    px = (4 - pyy + pxx) * PIECEDIST + PIECEOFFSET;
    if(myturn==1) {py = 449 - py; px = 449 - px;}
    if(abs(tempX - px) + abs(tempY - py) < PIECEDIST) {
      selpos = selectable.substring(i,i+2);
	}
	i += 2;
  }
//  window.status = '(' + tempX + ',' + tempY + ') selectable=' + selectable + '(' + selectable.length + ')  selpos=' + selpos;

  return selpos;
}

function moveImg(myturn,e) {
 	var selpos = getCursorPos(myturn,e);
	var sel = document.getElementById('selector');
	if(selpos == '') {
		sel.style.visibility = 'hidden';
		document.body.style.cursor = 'default';
	} else {
	    pyy = selpos.charCodeAt(0) - 48;
	    pxx = selpos.charCodeAt(1) - 48;
	    if(iam == 1) {
		    py = (pyy + pxx) * PIECEDIST;
		    px = (4 + pyy - pxx) * PIECEDIST;	
		} else {
		    py = (8 - pyy - pxx) * PIECEDIST;
		    px = (4 - pyy + pxx) * PIECEDIST;	
		}
		sel.style.left = px;
		sel.style.top = py;	
		sel.style.visibility = 'visible';
		document.body.style.cursor = 'pointer';
	}
}

function getTargetSelectable(selpos) {
	var i = selpos.charCodeAt(0) - 48;
	var ii;
	if(iam == 1) { ii = i - 1; } else { ii = i + 1; }
	var j = selpos.charCodeAt(1) - 48;
	var jj;
	if(iam == 1) { jj = j - 1; } else { jj = j + 1; }
	var xsel = '';
	if(ii < 5 && ii >= 0) { xsel += '' + ii + j; }
	if(jj < 5 && jj >= 0) { xsel += '' + i + jj; }
	if(ii < 5 && ii >= 0 && jj < 5 && jj >= 0) { xsel += '' + ii + jj; }
	return xsel;
}

function fieldClick(myturn, e) {
 	stopAnimation();
 	var selpos = getCursorPos(myturn,e);
 	if(selpos != '') {
		document.body.style.cursor = 'default';
 		hideAllBlocks();
	 	clearSelectable();
	 	if(action == 'selectpiece') {
	 	 	thisMove = selpos;
			showText('divMove', 'Select square to move to');
			showBlock('divDie');
			showBlock('divMove');
			action = 'selecttarget';
			selectable = getTargetSelectable(selpos);
			showSelectable();
		} else if(action == 'selecttarget') {
			thisMove = thisMove + '-' + selpos;
		 	var i = selpos.charCodeAt(0) - 48;
		 	var j = selpos.charCodeAt(1) - 48;
			if(board[i][j] != "") { thisMove += "!"; }
			startAnimateMove(9999, '', '', thisMove, 1);
			doMove(thisMove);

			showBlock('divDie');
			showBlock('divConfirm');
			showBlock('divConfirmBtn');
			showBlock('divResignBtn');
			
			var roundend = 0;
			var gameend = 0;
			if(thisMove.substring(thisMove.length-2,thisMove.length) == '44' || thisMove.substring(thisMove.length-2,thisMove.length) == '00' || thisMove.substring(thisMove.length-3,thisMove.length) == '44!' || thisMove.substring(thisMove.length-3,thisMove.length) == '00!') {
				roundend = 1;
			} else {
				var c0 = 0;
				var c1 = 0;
				for(i=0; i<5; i++) {
					for(j=0; j<5; j++) {
						if(board[i][j] != "") {
							if(board[i][j].substring(0,1) == "0") { c0++; } else { c1++; }
						}
					}
				}
				if(c0 == 0 || c1 == 0) { roundend = 1; }
//				writeDebug("c0=" + c0 + "  c1=" + c1);
			}
			if(roundend == 1) {
				if(score[iam] >= gameendscore) { 
				 	gameend = 1; 
					showText('divMove', 'Game over');
					showBlock('divMove');
				}
//				writeDebug("roundend score=" + score[0] + "-" + score[1] + "   gameendscore=" + gameendscore);
			}
			var newmove = "+";
			if(curmoveno == 0) { newmove += gameendscore; }
			if(movesetup[curmoveno] != "") { newmove += "=" + movesetup[curmoveno]; }
			newmove += "." + moveroll[curmoveno] + "x" + thisMove.replace('-', '');
			document.post.move.value = newmove;
			document.post.gameend.value = gameend;
			document.post.roundend.value = roundend;
			document.post.score0.value = score[0];
			document.post.score1.value = score[1];
			document.post.gameendscore.value = gameendscore;
			document.post.movesUsedToWinRound0.value = movesUsedForWin[0];
			document.post.movesUsedToWinRound1.value = movesUsedForWin[1];
	writeDebug("POST move=" + newmove + " gameend=" + gameend + " roundend=" + roundend + " score=" + score[0] + "-" + score[1] + " movesUsedForWin=" + movesUsedForWin[0] + "-" + movesUsedForWin[1]);
		}
	}
}

function updateMovesUsedForWin(i) {
	movesUsedForWin[i] = movesUsedForWin[i] + movesCurRound;
	movesCurRound = 0;	
}

function doMove(smove) {
// writeDebug('doMove ' + smove);
 	movesCurRound++;
	board[smove.substring(3,4)][smove.substring(4,5)] = board[smove.substring(0,1)][smove.substring(1,2)];
	board[smove.substring(0,1)][smove.substring(1,2)] = '';
	if(smove.substring(3,5) == '44') { score[0]++; updateMovesUsedForWin(0); } else
	if(smove.substring(3,5) == '00') { score[1]++; updateMovesUsedForWin(1); } else {
		var c0 = 0;
		var c1 = 0;
		for(var i=0; i<5; i++) {
			for(var j=0; j<5; j++) {
				if(board[i][j] != "") {
					if(board[i][j].substring(0,1) == "0") { c0++; } else { c1++; }
				}
			}
		}
		if(c0 == 0) { score[1]++; updateMovesUsedForWin(1); }
		if(c1 == 0) { score[0]++; updateMovesUsedForWin(0); }
//		writeDebug("doMove c0=" + c0 + " c1=" + c1);
	}
// writeDebug("doMove("+ smove+") movesCurRound=" + movesCurRound + "  movesUsedForWin=" + movesUsedForWin[0] + "," + movesUsedForWin[1]);
}

function doSetUpMove(smove) {
// writeDebug("doSetUpMove("+ smove+")");
 	clearBoard();
 	board[0][0] = "0" + smove.substring(0,1);
 	board[0][1] = "0" + smove.substring(1,2);
 	board[0][2] = "0" + smove.substring(2,3);
 	board[1][0] = "0" + smove.substring(3,4);
 	board[1][1] = "0" + smove.substring(4,5);
 	board[2][0] = "0" + smove.substring(5,6);
 	board[4][4] = "1" + smove.substring(6,7);
 	board[4][3] = "1" + smove.substring(7,8);
 	board[4][2] = "1" + smove.substring(8,9);
 	board[3][4] = "1" + smove.substring(9,10);
 	board[3][3] = "1" + smove.substring(10,11);
 	board[2][4] = "1" + smove.substring(11,12);
}

function animateMove(moveno, smove, tmove) {
// writeDebug("animateMove(" + moveno + "," + smove + "," + tmove + ")   curAnimateMove=" + curAnimateMove + "   animateCount=" + animateCount);
 	if(curAnimateMove== moveno) {
	 	if(animateCount < 100) {
			animateCount+=3;
		 	var i = smove.charCodeAt(2) - 48;
		 	var j = smove.charCodeAt(3) - 48;
		 	if(iam == 1) { dt = i+j; dl = 4+i-j; } else { dt = 8-i-j; dl = 4-i+j; }
			var fromt = PIECEDIST * dt + PIECEOFFSET - PIECESIZE/2;
			var froml = PIECEDIST * dl + PIECEOFFSET - PIECESIZE/2;
		 	i = smove.charCodeAt(5) - 48;
		 	j = smove.charCodeAt(6) - 48;
		 	if(iam == 1) { dt = i+j; dl = 4+i-j; } else { dt = 8-i-j; dl = 4-i+j; }
			var tot = PIECEDIST * dt + PIECEOFFSET - PIECESIZE/2;
			var tol = PIECEDIST * dl + PIECEOFFSET - PIECESIZE/2;
			var tt = ((100 - animateCount) * fromt + animateCount * tot) / 100;
			var tl = ((100 - animateCount) * froml + animateCount * tol) / 100;
//writeDebug("smove=" + smove + "   from=" + fromt + "," + froml + "  to=" + tot + "," + tl + "   ij=" + i + "," + j);
//writeDebug("showPiece(" + smove.substring(0,2) + "," + tt + "," + tl + ", 100,7)");
			showPiece(smove.substring(0,2), tt, tl, 100, 7);
			setTimeout("animateMove(" + moveno + ", '" + smove+ "', '" + tmove + "')", 10);
	 	} else {
	 	 	if(tmove != "") {
				startAnimateMove(moveno, '', tmove, '', 0);
			} else {
		 	 	stopAnimation(false);				
			}
		}
	}
}

function animateSetUpMove(moveno, tmove, smove) {
// writeDebug("animateSetUpMove(" + moveno + "," + tmove + "," + smove + ")   curAnimateMove=" + curAnimateMove + "   animateCount=" + animateCount);
 	if(curAnimateMove== moveno) {
	 	if(animateCount < 100) {
			animateCount+=5;
			if(moveno == 0 && animateCount < 50) { animateCount = 50; }
			if(animateCount < 50) {
				for(var i=0; i<2; i++) {
					for(var j=1; j<7; j++) {
						var piece = document.getElementById('piece' + i + j);
						if(piece.style.visibility == 'visible') {
						 	o = 100 - 2 * animateCount;
							piece.style.opacity = o / 100;
							piece.style.filter = 'alpha(opacity=' + o + ')';
							var number = document.getElementById('number' + i + j);
							number.style.opacity = o / 100;
							number.style.filter = 'alpha(opacity=' + o + ')';								
						}
					}
				}
			} else {
			 	showPieces(2 * animateCount - 100, 1);
			}
			setTimeout("animateSetUpMove(" + moveno + ", '" + tmove+ "', '" + smove + "')", 10);
	 	} else {
	 	 	if(smove != "") {
				startAnimateMove(moveno, '', '', smove, 0);
			} else {
		 	 	stopAnimation(false);				
			}
		}
	}
}

function copyBoardToAnimBoard() {
	for(i=0; i<5; i++) {
	 	animboard[i] = new Array();
		for(j=0; j<5; j++) {
			animboard[i][j] = board[i][j];
		}
	}
}

function startAnimateMove(moveno, pmove, tmove, smove, refresh) {
// writeDebug('startAnimateMove('+ moveno + ',' + pmove + ',' + tmove + ',' + smove + ',' + refresh + ')');
 	curAnimateMove = moveno;
 	animateCount = 0;
 	if(true) {
		startAnimation();
		if(pmove != "") {
		 	if(refresh == 1) { copyBoardToAnimBoard(); }
			var i = pmove.substring(0,1);
			var j = pmove.substring(1,2);
			pmove = animboard[i][j] + pmove;				
		 	animateMove(moveno, pmove, tmove);				
		} else if(tmove != "") {
			for(i=0; i<5; i++) {
			 	animboard[i] = new Array();
				for(j=0; j<5; j++) {
					animboard[i][j] = '';
				}
			}
	 	 	animboard[0][0] = "0" + tmove.substring(0,1);
	 	 	animboard[0][1] = "0" + tmove.substring(1,2);
	 	 	animboard[0][2] = "0" + tmove.substring(2,3);
	 	 	animboard[1][0] = "0" + tmove.substring(3,4);
	 	 	animboard[1][1] = "0" + tmove.substring(4,5);
	 	 	animboard[2][0] = "0" + tmove.substring(5,6);
	 	 	animboard[4][4] = "1" + tmove.substring(6,7);
	 	 	animboard[4][3] = "1" + tmove.substring(7,8);
	 	 	animboard[4][2] = "1" + tmove.substring(8,9);
	 	 	animboard[3][4] = "1" + tmove.substring(9,10);
	 	 	animboard[3][3] = "1" + tmove.substring(10,11);
	 	 	animboard[2][4] = "1" + tmove.substring(11,12);
		 	animateSetUpMove(moveno, tmove, smove);	
		} else if(smove != ""){
		 	if(refresh == 1) { copyBoardToAnimBoard(); }
			var i = smove.substring(0,1);
			var j = smove.substring(1,2);
			smove = animboard[i][j] + smove;				
		 	animateMove(moveno, smove, "");	
		}
		for(i=0; i<5; i++) {
			s='';
			for(j=0;j<5;j++) {
				if(animboard[i][j]=='') { s = s + '..-';} else { s = s + animboard[i][j] + '-'; }
			}
//			writeDebug(smove + ' ' + s);
		}
 	} else {
		stopAnimation(false);
	}
}

function buildFieldUntilMove(moveno) {
	score[0] = 0;
	score[1] = 0;
	
	var i = 0;
	while(i <= moveno && i < move.length) {
//writeDebug("buildFieldUntilMove("+moveno+")  " + i + "=" + move[i]);
		if(movesetup[i] != "") { doSetUpMove(movesetup[i]); }
	 	if(move[i] != '') { doMove(move[i]); }
		i++;
	}
}

function clearField() {
// writeDebug('clearField');
 	for(var i=0; i<2; i++) {
		for(var j=1; j<7; j++) {
			var piece = document.getElementById('piece' + i + j);
			piece.style.visibility = 'hidden';
			var number = document.getElementById('number' + i + j);
			number.style.visibility = 'hidden';
		}
	}
	clearBoard();
	clearSelectable();
}

function clearBoard() {
	for(var i=0; i<5; i++) {
	 	board[i] = new Array();
		for(var j=0; j<5; j++) {
			board[i][j] = "";
		}
	}	
}

function showGameAtLastMove() {
// writeDebug("showGameAtLastMove");
	showGameAtMove(9999);
}

function showGameAtMove(moveno) {
 	if(moveno == 9999) { curmoveno = move.length - 1; } else { curmoveno = moveno; }
 	if(moveroll[curmoveno] == 0) {
 	 	// empty move: break off function
 	 	curAnimateMove = moveno;
 	 	stopAnimation(false);
		return;
	}
 	clearField(); 
 	movesCurRound = 0;
 	movesUsedForWin[0] = 0;
 	movesUsedForWin[1] = 0;
 	nextmoveno = curmoveno;
 	if(move[curmoveno] == '' && !playingMoves) { 
	  	xmove = curmoveno - 1; 
	  	if(xmove >= 0) {
			if(move[xmove] == '') { xmove--; }
		}
	} else { 
	 	xmove = curmoveno; 
	}
	buildFieldUntilMove(xmove-1);
	lastroll = moveroll[curmoveno];
writeDebug("showGameAtMove(" + moveno + ")  curmoveno=" + curmoveno + "  xmove=" + xmove + "   move=" + move[curmoveno] + "  lastroll=" + lastroll);
 	showGame();
	if(curmoveno == xmove || movesetup[curmoveno] == "") {
		startAnimateMove(xmove, '', movesetup[xmove], move[xmove], 1);
		if(movesetup[xmove] != '') { doSetUpMove(movesetup[xmove]); }
		doMove(move[xmove]);
	} else {
	 	var smove = '';
		if(xmove >= 0) { 
		 	smove = move[xmove];
		 	if(movesetup[xmove] != '') { doSetUpMove(movesetup[xmove]); } 
		}
		startAnimateMove(curmoveno, smove, movesetup[curmoveno], '', 1);
		if(smove != '') { doMove(smove); }
		doSetUpMove(movesetup[curmoveno]);
	}
	hideAllBlocks();
	showDie();
	if(myturn==1 && moveno==9999) {
	 	var min = 0;
	 	var minsel = '';
	 	var max = 7;
	 	var maxsel = '';
	 	for(var i=0; i<5; i++) {
			for(var j=0; j<5; j++) {
				if(board[i][j].substring(0,1) == iam) {
					var v = board[i][j].substring(1,2);
					if(v > min && v <= lastroll) { min = v; minsel = "" + i + j; }
					if(v < max && v >= lastroll) { max = v; maxsel = "" + i + j; }
				}
			}
		}
		if(min == max) { selectable = minsel; } else { selectable = minsel + maxsel; }
		if(selectable.length > 2) {
		 	action = 'selectpiece';
		 	showText('divMove', 'Select the stone to move');
		} else {
			action = 'selecttarget';
		 	thisMove = selectable;
			selectable = getTargetSelectable(thisMove)
			showText('divMove', 'Select square to move to');
		}
	 	showBlock('divMove');
		showBlock('divResignBtn');
		showSelectable();
//writeDebug("showGameAtMove min=" + min + " max=" + max + " minsel=" + minsel + " maxsel=" + maxsel);
	} else {
		showText('divMove', '');
	} 
}

function showPieces(o, anim) {
// writeDebug("showPieces " + o);
 	for(var i=0; i<5; i++) {
		for(var j=0; j<5; j++) {
		 	var p;
		 	if(anim == 1) { p = animboard[i][j]; } else { p = board[i][j]; }
			if(p != "") {
//			 	writeDebug("showPieces " + p + " " + i + "," + j);
				if(iam == 1) {
			 		showPiece(p, PIECEDIST * (i+j) + PIECEOFFSET - PIECESIZE/2, PIECEDIST * (4+i-j) + PIECEOFFSET - PIECESIZE/2, o, 5);
				} else {
			 		showPiece(p, PIECEDIST * (8-i-j) + PIECEOFFSET - PIECESIZE/2, PIECEDIST * (4-i+j) + PIECEOFFSET - PIECESIZE/2, o, 5);
			 	}
			}
		}
	}	
}

function showPiece(p, t, l, o, z) {
	var piece = document.getElementById('piece' + p);
	piece.style.top = t;
	piece.style.left = l;
	piece.style.visibility = 'visible';
	piece.style.opacity = o/100;
	piece.style.filter = 'alpha(opacity=' + o + ')';
	piece.style.zIndex = z;
	var number = document.getElementById('number' + p);
	number.style.top = t+21;
	number.style.left = l+25;
	number.style.visibility = 'visible';
	number.style.opacity = o/100;
	number.style.filter = 'alpha(opacity=' + o + ')';
	number.style.zIndex = z + 1;
}

function hidePieces() {
 	for(var i=0; i<2; i++) {
		for(var j=1; j<7; j++) {
			var piece = document.getElementById('piece' + i + j);
			piece.style.visibility = 'hidden';
			piece.style.zIndex = 5;
			var number = document.getElementById('number' + i + j);
			number.style.visibility = 'hidden';
			number.style.zIndex = 6;
		}
	}
}

function showGame() {
// writeDebug("showGame board=" + getBoard() + "  nextmoveno=" + nextmoveno);
 
	showDie();
	hidePieces();
	showPieces(100, 0);
	for(var i = 0; i < 2; i++) {
		showText('spanScore' + i, score[i]);		
	} 
}

function showDie() {
 	if(document.getElementById('dieImg')) {
		var dieClr = "blue";
		if(nextmoveno % 2 == 0) { dieClr = "yellow"; } else { dieClr = "red"; }
		document.getElementById('dieImg').src = 'images/general/dice/die' + dieClr + lastroll + '.gif';
	 	showBlock('divDie');	
 	}
}

function showSelectable() {
 	for(var i=0; i<3; i++) {
 	 	var sel = document.getElementById('selectable'+i);
		if(selectable.length > 2*i) {
		    pyy = selectable.charCodeAt(i*2) - 48;
		    pxx = selectable.charCodeAt(i*2+1) - 48;
		    if(iam == 1) {
			    py = (pyy + pxx) * PIECEDIST;
			    px = (4 + pyy - pxx) * PIECEDIST;	
			} else {
			    py = (8 - pyy - pxx) * PIECEDIST;
			    px = (4 - pyy + pxx) * PIECEDIST;	
			}
			sel.style.left = px;
			sel.style.top = py;	
			if(action == 'selectpiece') {
				sel.src = 'images/einstein/selectablepos.gif';
			} else {
				sel.src = 'images/einstein/selectable.gif';
			}
			sel.style.visibility = 'visible';	
//			writeDebug("showSelectable " + i + "-" + selectable.substring(i*2,i*2+2) + " (" + py + "," + px + ")");
		} else {
			sel.style.visibility = 'hidden';
		}
	}
}

function clearSelectable() {
	selectable = '';
	var sel = document.getElementById('selector');
	sel.style.visibility = 'hidden';
	for(var i=0; i<3; i++) {
		sel = document.getElementById('selectable'+i);
		sel.style.visibility = 'hidden';
	}
	document.body.style.cursor = 'default';	
}

function resignGame() {
	clearSelectable();
	hideAllBlocks();
	showBlock('divResign');
	showBlock('divConfirm');
	showBlock('divConfirmResign');
}

function hideAllBlocks() {
	hideBlock('divDie');
	hideBlock('divMove');
	hideBlock('divUndo');
	hideBlock('divConfirm');
	hideBlock('divResign');
	hideBlock('divResignBtn');
	hideBlock('divConfirmBtn');
	hideBlock('divConfirmResign');
}

function getBoard() {
 var s = '';
 for(var i=0; i<5; i++) {
	for(var j=0; j<5;j++) {
		s =s + board[i][j] + ',';
	}
	s=s+'=';
}
	return s;
}
