var fieldHeight = 0;
var fieldWidth = 0;
var field = new Array();
var thisMove = "";
var startPos = "";
var selector = "";
var curmoveno = 99;
var selectedPos = "";
var action = "";
var score = new Array();
var damage = new Array();
var boatpos = new Array();
var touchBuoyLine = new Array();
var buoysrounded = new Array();
var buoysshown = new Array();
var buoymoveno = 99;
var crashed = new Array(false, false);
var animateCount = 100;
var curAnimateMove = -1;
var activePresel = 0;
var dieToRemove = 99;
var gameend = 0;

var numImages = 46;
// Preloading dice images
/*
var diceImg = new Array();
for(var i=0; i<=6; i++) {
	diceImg[i] = new Image(31,31);
	diceImg[i].src = "images/general/dice/dieblue" + i + ".gif";
}
*/
function moveImg(i,j) {
	if(field[i][j].substring(0,1) == "B") {
	 	buoynr = field[i][j].substring(1,2);
	 	document.getElementById('buoy' + buoynr).style.visibility = "visible";
	}
	var selpos = -1;
	var sel = selector.split(")");
	var f = 0;
	while(selpos == -1 && f < sel.length) {
	 	var asel = sel[f].split(",");
	 	if(asel[0] == "(" + i && asel[1] == j) { selpos = f; }
		f++;
	}
	if(selpos >= 0) {
		var sel = document.getElementById("selector");
		sel.style.top = i * GIFY;
		sel.style.left = j * GIFX;
		sel.style.visibility = 'visible';
		selectedPos = i + "," + j;
	} else {
		document.getElementById("selector").style.visibility = 'hidden';
		selectedPos = "";
	}
//	window.status = '(' + i + ',' + j + ') ' + field[i][j] + '  sel:' + selector + " --> " + selectedPos;
}

function moveOut(i,j) {
	if(field[i][j].substring(0,1) == "B") {
	 	buoynr = field[i][j].substring(1,2);
	 	if(buoysshown[buoynr] == 0) {
	 		document.getElementById('buoy' + buoynr).style.visibility = "hidden";
	 	}
	}
}

function setPostValues() {
	document.post.move.value = thisMove;
	document.post.gameend.value = gameend;
	document.post.score0.value = score[0];
	document.post.score1.value = score[1];
	document.post.damage0.value = damage[0];
	document.post.damage1.value = damage[1];
	document.post.buoysrounded0.value = '' + buoysrounded[0][0] + buoysrounded[0][1] + buoysrounded[0][2];
	document.post.buoysrounded1.value = '' + buoysrounded[1][0] + buoysrounded[1][1] + buoysrounded[1][2];
}

function clickImg(i,j) {
	if(action == "selectstartpos") {
		if(field[i][j].indexOf("S") >= 0 && field[i][j].indexOf("0") >= 0) {
		 	hideAllBlocks();
		 	hidePreselectors();
			thisMove = thisMove + String.fromCharCode(i+48,j+48);
			doMove(curmoveno+1, thisMove);
			showGame();
			if(move.length == 0) {
			 	setPostValues();
				showBlock("divConfirm");
				showBlock('divConfirmBtn');
				showBlock('divResignBtn');
			}
			if(move.length == 1) {
			 	showBlock('divConfirmRed');
			 	showBlock('divUndo');
			}
		}
	} else if(action == "selectnewpos")	 {
	 	var z = selector.split("(");
	 	var f = 0;
	 	var x = z[f].split(",");
	 	while(f < z.length && (x[0] != i || x[1] != j)) { f++; x = z[f].split(","); }
	 	if(f < z.length) {
		 	hideAllBlocks();
		 	hidePreselectors();
		 	if(thisMove == "") {
				var dice = getDice(curmoveno-1, true);
				if(dieToRemove < 99) {
					dice = dice.substring(0,dieToRemove) + dice.substring(dieToRemove+1,dice.length);
				}
				thisMove = dice + ",";
			}
			thisMove = thisMove + String.fromCharCode(parseInt(x[3].substring(0,1))+48,i+48,j+48);
			if(x[2] != 0) { thisMove = thisMove + '*'; }
			startAnimateMove(curmoveno+1, thisMove);
			doMove(curmoveno+1, thisMove);
		 	setPostValues();
		 	if(gameend == 1) {
				showText('divMove', 'Game over');
				showBlock('divMove');
			}
		 	showDice(getDiceX(thisMove), iam);
			showBlock("divConfirm");
			showBlock('divConfirmBtn');
			showBlock('divResignBtn');
		}
	} else {
		writeDebug("clickImg: undefined action: " + action);
	}
}

function clicked(i) {
 	var x;
 	if(i==9 && action == "selectstartpos") {
		x = selectedPos.split(",");
	} else {
		if(i==9) { i = activePresel; }
 		var z = selector.split("(");
		x = z[i+1].split(",");
	}
//	writeDebug('clicked '+ i + ' action:' + action + ' selectedPos:' + selectedPos + ' x:' + x[0] + ',' + x[1]);
	clickImg(parseInt(x[0]), parseInt(x[1]));
}

function preselMove(i) {
	var z = selector.split("(");
	if(i > 4) {
		var j = 1;
		while(i > 4 && j < z.length) {
			var x = z[j].split(',');
			if ((x[0] == boatpos[i-7].charCodeAt(1) - 48) && (x[1] == boatpos[i-7].charCodeAt(2) - 48)) {
				i = j - 1;
			}
			j++;
		}
	}
 	activePresel = i;
	if(i < 4) {
		var x = z[i+1].split(",");
		moveImg(parseInt(x[0]), parseInt(x[1]));
	}
}

function preselMoveOut() {
 	if(activePresel < 4) {
	 	var z = selector.split("(");
		var x = z[activePresel+1].split(",");
		moveOut(parseInt(x[0]), parseInt(x[1]));
	}
}

function clickCBDie(i) {
	var i = 0;
	var cnt  = 0;
	while(i < 10) {
	 	if(document.getElementById("cbDie" + i)) {
			if(document.getElementById("cbDie" + i).checked) { cnt++; }
		}
		i++;
	}
	document.getElementById("btnRoll").disabled = (cnt == 0);
}

function clickRemoveDie(i) {
 	hideAllBlocks();
	dieToRemove = i;	
	var dice = getDice(curmoveno-1, true);
	showDiceToRoll(dice, iam);
	showBlock("divUndo");
	hidePreselectors();
	selector = getNewPos(dice);
	showSelector(dice);	
}

function confirmRed() {
 	hideAllBlocks();
	showText('divMove', 'Rolling the dice, please wait...');
	showBlock('divMove');
	document.getElementById('hiddenFrame').src = 'nolimit/getroll.php?gameid=' + gameid + '&moveno=' + (curmoveno+2) + '&move=' + thisMove + '.*,&userno=' + iam;
}

function drawField() {
 	var fieldImg = new Array();
 	var buoyImg = new Array();
 	for(var i=1; i<4; i++) {
		buoyImg[i] = new Array();
	}
	fieldDrawn = 1;
	fieldHeight = board.charCodeAt(0) - 48;
	fieldWidth = board.charCodeAt(1) - 48;
	var fieldRows = board.substring(2).split('#');
	for(var i=0; i< fieldHeight; i++) {
	 	var fieldRow = fieldRows[i].split(".");
	 	field[i] = new Array();
	 	fieldImg[i] = new Array();
	 	if(i % 2 == 0) {
			for(var j=0; j < fieldWidth/2; j++) {
			 	if(fieldRow[j] == '') { fieldRow[j] = '.'; }
				field[i][j*2] = fieldRow[j];
				field[i][j*2+1] = '.';
			}
		} else {
			for(var j=0; j < fieldWidth/2; j++) {
			 	if(fieldRow[j] == '') { fieldRow[j] = '.'; }
				field[i][j*2+1] = fieldRow[j+1];
				field[i][j*2] = '.';
			}
		}
	}
	var dy = 0;
	var pics = new Array();
	var x;
	var buoyDiv = new Array();
	for(var i=1; i<4; i++) { buoyDiv[i] = new Array(); }
	for(var i=0; i< fieldHeight; i++) {
	 	for(var j=0; j < fieldWidth; j++) {
	 	 	if(field[i][j] != '.') {
		 	 	var posx = i * GIFY;
		 	 	var posy = j * GIFX;
		 	 	var img;
		 	 	var zindex = 1;
		 	 	if(field[i][j].substring(0,1) == "B") {
		 	 	 	img = field[i][j];
		 	 	} else if(field[i][j].substring(0,1) == "0") {
		 	 	 	img = "0";
		 	 	 	x = field[i][j].indexOf("B");
		 	 	 	while(x > 0) {
		 	 	 	 	buoynr = field[i][j].substring(x+1,x+2);
		 	 	 	 	zindex = parseInt(buoynr) + 3;
		 	 	 	 	bl = buoyImg[buoynr].length;
		 	 	 	 	buoyDiv[buoynr].push("<img id='buoy" + buoynr + bl + "' style='position:absolute; top:" + posx + "px; left:" + posy + "px; z-index:" + zindex + ";' onMouseOver='moveImg(" + i + ", " + j + ");' onMouseOut='moveOut(" + i + ", " + j + ");' onClick='clickImg(" + i + ", " + j + ");'>");
		 	 	 	 	buoyImg[buoynr][bl] = field[i][j].substring(x+2,x+3);
		 	 	 	 	var xx = field[i][j].substring(x+1,field[i][j].length).indexOf("B");
		 	 	 	 	if(xx > 0) { x = x + xx + 1; } else { x = xx; }
					}
		 	 	 	x = field[i][j].indexOf("x");
		 	 	 	if(x > 0) {
						img = img + field[i][j].substring(x+1,x+3);
					}
		 	 	 	if(field[i][j].indexOf("S") > 0) { 
						img = "1"; 
						startPos = startPos + "(" + i + "," + j + ")";
					}
		 	 	 	if(field[i][j].indexOf("F") > 0) { img = "9"; }
					zindex = 2;
		 	 	} else {
					img = "X";
				}
				pics.push("<img id='field" + i + "_" + j + "' style='position:absolute; top:" + posx + "px; left:" + posy + "px; z-index:" + zindex + ";' onMouseOver='moveImg(" + i + ", " + j + ");' onMouseOut='moveOut(" + i + ", " + j + ");' onClick='clickImg(" + i + ", " + j + ");'>");
				fieldImg[i][j] = img;
			}
		}
	}
	var fieldDiv = document.getElementById("innerFieldDiv");
	for(var i=1; i<4; i++) {
		pics.push("<div id='buoy" + i + "' style='visibility:hidden;'>" + buoyDiv[i].join("") + "</div>");
	}
	fieldDiv.innerHTML = pics.join("");
	for(var i=0; i< fieldHeight; i++) {
 		for(var j=0; j < fieldWidth; j++) {
 	 		if(field[i][j] != '.') {
 	 		 	document.getElementById('field' + i + '_' + j).src = document.getElementById('tile' + fieldImg[i][j]).src;
 	 		}
 	 	}
 	}
 	for(var i=1; i<4; i++) {
		for(var j=0; j<buoyImg[i].length; j++) {
			document.getElementById('buoy' + i + j).src = document.getElementById('tile'+ buoyImg[i][j]).src;
		}
	}

}

function clearField() {
 	for(var i=0; i<2; i++) {
		score[i] = 0;
		damage[i] = 0;
		boatpos[i] = '';
		buoysrounded[i] = new Array(5, 5, 5);
		touchBuoyLine[i] = new Array(0, 0);
		crashed[i] = false;
	}
	for(var i=1; i<4; i++) {
		document.getElementById('buoy' + i).style.visibility = 'hidden';
	}
	gameend = 0;
	document.getElementById('boat0').style.visibility = 'hidden';	
	document.getElementById('boat1').style.visibility = 'hidden';
	document.getElementById('prevboat0').style.visibility = 'hidden';	
	document.getElementById('prevboat1').style.visibility = 'hidden';
	document.getElementById('crash0').style.visibility = 'hidden';	
	document.getElementById('crash1').style.visibility = 'hidden';
	hidePreselectors();
}

function hidePreselectors() {
	for(var i=0; i<3; i++) {
		document.getElementById('preselector'+i).style.visibility = 'hidden';
	}
	document.getElementById("selector").style.visibility = 'hidden';
	selector = '';
}

function rightDir(dir, dirx) {
	return ((dirx == 7 && (dir == 2 || dir == 3)) || (dirx ==8 && (dir ==5 || dir == 6)));
}
function do1Move(tomove, pos0, dest) {
// writeDebug('do1Move(' + tomove + ',' + pos0 + ',' + dest + ')');
	var dir = parseInt(dest.substring(0,1));
	var dx = getXDir(dir);
	var dy = getYDir(dir);
	var px = pos0.charCodeAt(1) - 48 + dx;
	var py = pos0.charCodeAt(2) - 48 + dy;
	var pos1 = dest.substring(0,1) + String.fromCharCode(px+48,py+48);
	if(score[tomove] == 3 && field[px][py].indexOf('F') >= 0) {
		score[tomove]++;
		gameend = 1;
//		writeDebug('game over');
	} else {
		if(dir != 1 && dir != 4) {
		 	var crossing = 0;
			for(var i=1; i<4; i++) {
				var bl = field[px][py].indexOf('B' + i);
				if(bl >= 0) {
					if(i == score[tomove] || i == score[tomove]+1) {
					 	crossing = 1;
						var dirx = parseInt(field[px][py].charAt(bl+2));
						touchBuoyLine[tomove] = new Array(i, dirx);
						//check for wrong direction
						if(rightDir(dir, dirx)) { buoysrounded[tomove][i-1]++; }
	//					writeDebug(tomove + ' HIT BUOY ' + i + ' dir:' + dir + ' dirx:' + dirx + ' field:' + field[px][py] + ' buoysrounded:' + buoysrounded[tomove][0] + buoysrounded[tomove][1] + buoysrounded[tomove][2]);
					}
				}
			}
			if(crossing == 0 && touchBuoyLine[tomove][0] != 0) {
				if(!rightDir(dir, touchBuoyLine[tomove][1])) { buoysrounded[tomove][touchBuoyLine[tomove][0]-1]--; }
	//			writeDebug(tomove + ' OFF BUOY ' + touchBuoyLine[tomove][0] + ' dir:' + dir + ' dirx:' + touchBuoyLine[tomove][1] + ' buoysrounded:' + buoysrounded[tomove][0] + buoysrounded[tomove][1] + buoysrounded[tomove][2]);
				touchBuoyLine[tomove][0] = 0;
			}
			if(score[tomove] < 4) {
				score[tomove] = 0;
				while(score[tomove] < 3 && buoysrounded[tomove][score[tomove]] > 5) { score[tomove]++; }
			}
		}
	}
	return pos1;
}

function doMove(smoveno, smove) {
// writeDebug('doMove('+ smoveno + ',' + smove + ')');
	var tomove = (smoveno % 2);
	var totroll = 0;
	if(smove.indexOf(".") >= 0) {
		amove = smove.split(".");
		boatpos[tomove] = amove[0].substring(amove[0].length - 3, amove[0].length);
		smove = amove[1];
	}
	if(smove.indexOf(",") >= 0) {
		amove = smove.split(",");
		smove = amove[1];
		totroll = getTotRoll(amove[0], 99);
	}
	if(smove.length > 0) {
	 	crashed[tomove] = (smove.indexOf('*') >= 0);
	 	smove = smove.replace('*', '');
	 	var dest = smove.substring(smove.length - 3, smove.length);
	 	var cnt = 0;
	 	if(boatpos[tomove] != '') {
		 	var pos0 = dest.substring(0,1) + boatpos[tomove].substring(1,3);
	 		while(pos0 != dest) { pos0 = do1Move(tomove, pos0, dest); cnt++; }
	 	}
	 	boatpos[tomove] = dest;
	 	if(crashed[tomove]) { 
		  	damage[tomove] += (totroll - cnt); 
		 	// Crash blocked by other boat?
		 	var dx = getXDir(parseInt(dest.substring(0,1)));
		 	var dy = getYDir(parseInt(dest.substring(0,1)));
		 	if(boatpos[1-tomove].substring(1,3) == String.fromCharCode(dest.charCodeAt(1)+dx, dest.charCodeAt(2)+dy)) {
				damage[tomove]--;
			}
		 	if(damage[tomove] > 3 && score[tomove] < 4) { gameend = 1; score[1-tomove] = 4; }
	 	}
	 	if(smoveno >= 69) { gameend = 1; }
//	 	writeDebug('doMove(' + smoveno + ',"' + smove + '") - boatpos:' + boatpos[tomove] + ' - damage:' + damage[tomove] + ' - score:' + score[tomove] + ' - gameend:' + gameend );
//	 	if(totroll != cnt) { writeDebug('BOING ' + totroll + '-' + cnt + ' damage'); }
	}
}

function setMove(smoveno, smove) {
// writeDebug('setMove ' + smoveno + ': ' + smove);
 	move[smoveno] = smove;
 	showGameAtMove(99);
}

function buildFieldUntilMove(xmove) {
 	clearField();
	var i = 0;
	while(i <= xmove && i < move.length) {
	 	doMove(i, move[i]);
		i++;
	}
}

function animateMove(xmove, boatno, from, to) {
// writeDebug('animateMove ' + xmove + ', ' + boatno + ', ' + from + ', ' + to + ' curAnimateMove=' + curAnimateMove + ' animateCount=' + animateCount);
 	if(xmove == curAnimateMove && xmove >= 0 && from != '') {
		animateCount+=3;
		if(animateCount > 100) { animateCount = 100; }
		var img = document.getElementById('boat' + boatno);
		var fromx = (from.charCodeAt(1) - 48) * GIFY;
		var fromy = (from.charCodeAt(2) - 48) * GIFX ;
		var tox = (to.charCodeAt(1) - 48) * GIFY;
		var toy = (to.charCodeAt(2) - 48) * GIFX ;
		var dir = to.charCodeAt(0) - 48;
		img.src = document.getElementById('boat' + boatX[boatno] + dir).src;
		img.style.top = ((100 - animateCount) * fromx + animateCount * tox) / 100;
		img.style.left = ((100 - animateCount) * fromy + animateCount * toy) / 100;
		img.style.visibility = 'visible';		
		if(animateCount < 100) {
			setTimeout("animateMove(" + xmove + ", " + boatno + ", '" + from + "', '" + to + "')", 5);
		} else {
	 	 	stopAnimation(false);
		}
	} else {
		setTimeout("stopAnimation(false)", 5);
	}
}
function startAnimateMove(xmove, smove) {
// writeDebug('startAnimateMove('+ xmove + ',' + smove + ')');
 	boatno = xmove % 2;
	document.getElementById('crash' + boatno).style.visibility = 'hidden';	
	if(curAnimateMove >= 0) { stopAnimation(false); }
 	curAnimateMove = xmove;
 	animateCount = 0;
 	if(smove.indexOf(",") < smove.length - 1) {
		startAnimation();
		var pos = boatpos[boatno];
		if(smove.indexOf('.') >= 0) { pos = smove.substring(0,3); }
		// Show prev position
		if(pos != '') {
			var img = document.getElementById('prevboat' + boatno);
			var dir = pos.charCodeAt(0) - 48;
			img.src = document.getElementById('boat' + boatX[boatno] + dir).src;
			img.style.top = (pos.charCodeAt(1) - 48) * GIFY;
			img.style.left = (pos.charCodeAt(2) - 48) * GIFX;
			img.style.visibility = 'visible';		
		}
		smove = smove.replace('*', '');
	 	animateMove(xmove, boatno, pos, smove.substring(smove.length-3, smove.length));	
 	} else {
		setTimeout("stopAnimation(false)", 5);
	}
}

function addImage() {
	cntImagesLoaded++;
// 	writeDebug('addImage  cntImagesLoaded=' + cntImagesLoaded);
	showText('divMove', 'Loading images (' + Math.floor(100 * cntImagesLoaded / numImages) + '%)');
	showBlock('divMove');
	if(cntImagesLoaded == numImages && pageLoaded == 1) {
		showGameAtMove(99);
	}
}

function showGameAtMove(moveno) {
// 	writeDebug('showGameAtMove(' + moveno + ')   cntImagesLoaded=' + cntImagesLoaded);
 	pageLoaded = 1;
 	action = '';
 	if(cntImagesLoaded == numImages) {
//		writeDebug('showGameAtMove running');
	 	dieToRemove = 99;
	 	thisMove = '';
	 	selector = '';
	 	if(fieldDrawn == 0) { drawField(); }
	 	clearField(); 
	 	if(moveno == 99) { 
		  	curmoveno = move.length - 1; 
			buoymoveno = curmoveno - 1;
			if(move.length > 1 && move[move.length - 1].substring(0,1) == "+") { buoymoveno--; }
		} else { 
		 	curmoveno = moveno; 
		 	buoymoveno = curmoveno;
		}
	 	xmove = curmoveno - 1;
		buildFieldUntilMove(xmove);
	 	showGame();
	 	if(curmoveno >= 0 && move[curmoveno].substring(0,1) != '+') {
		 	startAnimateMove(curmoveno,move[curmoveno]);
	 		doMove(curmoveno, move[curmoveno]);
	 	}
		hideAllBlocks();
		
		if(myturn==1 && moveno==99) {
	//	 	writeDebug('move.length:' + move.length + ' move:' + move[move.length -1] + ' curmoveno:' + curmoveno);
			if(move.length < 2) {
			 	action = "selectstartdir";
				showText('divMove', 'Select the direction of your boat');
				showBlock('divMove');
				showBlock('divSelectDir');
			} else if(move.length > 1 && move[move.length - 1].substring(0,1) == "+") {
			 	if(move.length == 2) { 
				  	boatpos[iam] = move[move.length - 1].substring(1,4); 
				  	showGame();
				}
				action = "selectnewpos";
				var dice = getDice(curmoveno, true);
				selector = getNewPos(dice);
			 	thisMove = move[move.length - 1].substring(1, move[move.length - 1].length);
			 	curmoveno--;
				selxx = selector.split("(");
				if(selxx.length > 2) {
					showDice(dice, iam);
					showText('divMove', 'Select the new position of your boat');
					showBlock('divMove');
					showSelector(dice);
			 	} else {
					selzz = selxx[1].split(",");
					clickImg(parseInt(selzz[0]), parseInt(selzz[1]));
				}
			} else {
			 	action = "selectnewpos";
				var dice = getDice(curmoveno-1, true);
				showDiceToRoll(dice, iam);
				selector = getNewPos(dice);
				showSelector(dice);
			}
			showBlock('divResignBtn');
		} else {
			showDice(getDice(curmoveno), curmoveno%2);
		}
	}
}

function showGame() {
	for(var i=0; i<2; i++) {
		if(boatpos[i] != '') {
			var bdir = boatpos[i].substring(0,1);
			var bx = boatpos[i].charCodeAt(1) - 48;
			var by = boatpos[i].charCodeAt(2) - 48;
			var img = document.getElementById('boat' + i);
			img.src = document.getElementById('boat' + boatX[i] + bdir).src;
			img.style.top = bx * GIFY;
			img.style.left = by * GIFX;
			img.style.visibility = 'visible';
		 	var img = document.getElementById('crash' + i);
			if(crashed[i]) {
				var dx =0;
				var dy = 0;
			 	if(bdir == 1) { dx = 6; dy = -2; } 
			 	if(bdir == 2) { } //no change
			 	if(bdir == 3) { dy = 10; }
			 	if(bdir == 4) { dx = 6; dy = 12; }
			 	if(bdir == 5) { dx = 13; dy = 10; }
			 	if(bdir == 6) { dx = 13; }
			 	img.style.top = bx *GIFY + dx;
			 	img.style.left = by * GIFX + dy;
			 	img.style.visibility = 'visible';
			} else {
				img.style.visibility = 'hidden';
			}
		}
	}
	for(var i=0; i<2; i++) {
		showText('spanScore'+i, score[i]);
		showText('spanDamage'+i, damage[i]);
	}
// Show buoy lines
	buoysshown = new Array(0, 0, 0, 0);
	if(score[buoymoveno%2] > 0 && score[buoymoveno%2] < 4) {
		document.getElementById('buoy' + score[buoymoveno%2]).style.visibility = "visible";
		buoysshown[score[buoymoveno%2]] = 1;
//		writeDebug('1: buoy ' + score[x%2] + ' buoymoveno:' + buoymoveno);
	}
	if(score[buoymoveno%2] >= 0 && score[buoymoveno%2] < 3) {
	 	var nextbuoy = score[buoymoveno%2] + 1;
		document.getElementById('buoy' + nextbuoy).style.visibility = "visible";
		buoysshown[nextbuoy] = 1;
//		writeDebug('2: buoy ' + nextbuoy + ' buoymoveno:' + buoymoveno);
	}
}

function showSelector(dice) {
	var selTemp = selector.split("(");
	var i = 1;
	var cnt = 1;
	while (i < selTemp.length) {
	 	var selPos1 = selTemp[i].split(',');
	 	if(selPos1[0] == boatpos[iam].charCodeAt(1)-48 && selPos1[1] == boatpos[iam].charCodeAt(2)-48 && selPos1[2] != 0) { cnt++; }
	 	selPos0 = selPos1;
		i++;
	}
//	writeDebug('selector:' + selector + ' - boatpos:' + boatpos[iam] + ' - i:' + i + ' - cnt:' + cnt);
	if(cnt < i || i <= 2) {
		i = 0;
		while (i < selTemp.length-1) {
			var selPos = selTemp[i+1].split(",");
			var img = document.getElementById('preselector' + i);
			if(selPos[2] == "0") {
				img.src = document.getElementById('preselector').src;
			} else {
				img.src = document.getElementById('preselectorcrash').src;
			}
			img.style.top = parseInt(selPos[0]) * GIFY;
			img.style.left = parseInt(selPos[1]) * GIFX;
			img.style.visibility = 'visible';
			i++;
		}
	} else {
	 	i = 1;
	 	var txt = 'Select the direction of your boat BEFORE crashing<br>';
	 	while(i < selTemp.length) {
			var selPos = selTemp[i].split(',');
			var newdir = selPos[3].split(')');
			txt = txt + "<a href=\"#\" onClick=\"setDirection(" + newdir[0] + "," + dice + ");\"><img src='images/nolimit/boat" + boatX[iam] + newdir[0] + ".gif'></a>";
			i++;
		}
		document.getElementById('divMove').innerHTML = txt + "<br>";
		showBlock('divMove');
	}
}

function showDice(dice, clr) {
    if(document.getElementById("divRoll")) {
		var txt = "<br>";
		for(var i=0; i<dice.length; i++) {
	 		txt = txt + "<img src='images/general/dice/die" + dieX[clr] + dice.substring(i, i+1) + ".gif'> ";
		}
		document.getElementById("divRoll").innerHTML = txt;
		showBlock("divRoll");
	}
}

function showDiceToRoll(dice, clr) {
 	var dicetoroll = '';
	var txt = '';
	for(var i=0; i<dice.length; i++) {
	 	if(i != dieToRemove) {
	 		txt = txt + "<td>";
			if(dieToRemove == 99) {
				txt = txt + "<img id='imgRemoveDie" + i + "' src='images/nolimit/but_remove.gif' onClick=\"clickRemoveDie(" + i + ");\"><br>";
			}
			txt = txt + "<img src='images/general/dice/die" + dieX[clr] + dice.substring(i, i+1) + ".gif'><br><input id='cbDie" + i + "' type='checkbox' name='rolldie" + i + "' onClick=\"clickCBDie(" + i + ");\"></td>";
			dicetoroll = dicetoroll + dice.substring(i, i+1);
	 	}
	}
	if(dieToRemove == 99) {
	 	txt = txt + "<td><img src='images/general/dice/die" + dieX[clr] + "0.gif'><br><input id='cbDie" + i + "' type='checkbox' name='rolldie" + i + "' onClick=\"clickCBDie(" + i + ");\"></td>";
	}
	if(txt != '') {
 		txt = "<table border='0'><tr valign='bottom' align='center'><td><input id='btnRoll' type='button' name='rollDice' value='Roll:' disabled='disabled' onClick='rollDice();'></td>" + txt + "</table><br><b>Warning</b>: ROLL can NOT be undone!";
 	}
 	if(dice == '' || dicetoroll == '') {
 	 	txt = txt + '<p>';
 	 	if(dice == '') { txt = txt + '<b>OR</b><p>'; }
		txt = txt + "Turn your boat without moving<p>";
		var dir = parseInt(boatpos[iam].substring(0,1));
		for(var i=-1; i<2; i++) {
			var newdir = (dir + 5 + i) % 6 + 1;
			txt = txt + "<a href=\"#\" onClick=\"setDirection(" + newdir + ",'');\"><img src='images/nolimit/boat" + boatX[iam] + newdir + ".gif'></a>";
		}
	}
	document.getElementById("divRoll").innerHTML = txt;
	
	showBlock("divRoll");
}

function setDirection(sdir, dice) {
// writeDebug('setDirection sdir=' + sdir + ' dice=' + dice + ' dieToRemove=' + dieToRemove);
	if(action == "selectstartdir") {
		thisMove = sdir;
		hideAllBlocks();
		selector = startPos;
		showText('divMove', 'Select the startposition');
		showBlock('divMove');
		showBlock('divUndo');
		action = "selectstartpos";
	} else if(action == "selectnewpos") {
		hideAllBlocks();
		hidePreselectors();
//		writeDebug('setDirection ' + thisMove);
		if(thisMove == '') { 
			thisMove = ',' + sdir + boatpos[iam].substring(1,3);
			if(dice != '') { 
				if(dieToRemove < 99) {
				 	dice = '' + dice;
					dice = dice.substring(0,dieToRemove) + dice.substring(dieToRemove+1,dice.length);
				}
				thisMove = dice + thisMove;
			}
		} else {
		 	showDice(thisMove.substring(0,thisMove.length-1), iam);
			thisMove = thisMove + sdir + boatpos[iam].substring(1,3);
		}
		if(dice != '') { 
		 	thisMove = thisMove + '*';
		}		
//		writeDebug('setDirection thisMove=' + thisMove);
		doMove(curmoveno+1, thisMove);
		showGame();
	 	if(gameend == 1) {
			showText('divMove', 'Game over');
			showBlock('divMove');
		}
	 	setPostValues();
		showBlock("divConfirm");
		showBlock('divConfirmBtn');
		showBlock('divResignBtn');
	} else {
		writeDebug("setDirection unknown action:" + action);
	}
}

function resignGame() {
	hideAllBlocks();
	hidePreselectors();
	document.getElementById('divResign').style.display = 'block';
	document.getElementById('divConfirm').style.display = 'block';
	document.getElementById('divConfirmResign').style.display = 'block';
}

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

function rollDice() {
	hideAllBlocks();
	showText('divMove', 'Rolling the dice, please wait...');
	showBlock('divMove');
	var i = 0;
	thisMove = '';
	var dice = getDice(curmoveno-1, true);
	while(i < 10) {
	 	if(document.getElementById("cbDie" + i)) {
			if(document.getElementById("cbDie" + i).checked) {
				thisMove = thisMove + "*";
			} else {
				thisMove = thisMove + dice.substring(i,i+1);
			}
		}
		i++;
	}
	document.getElementById('hiddenFrame').src = 'nolimit/getroll.php?gameid=' + gameid + '&moveno=' + (curmoveno+2) + '&move=' + thisMove + ',&userno=' + iam;
	document.post.rolleddice.value = 'true';
}

function getDice(xmove, fornextmove) {
 	return getDiceX(move[xmove], fornextmove);
}

function getDiceX(smove, fornextmove) {
// 	writeDebug('getDiceX ' + smove);
 	var dice = "";
 	if(!fornextmove) { smove = smove.replace('*', ''); }
 	if(!(smove.substring(smove.length-1,smove.length) == '*')) {
		if(smove.substring(0,1) == "+") { smove = smove.substring(1,smove.length); }
	 	var amove;
		if(smove.indexOf(".") >= 0) {
			amove = smove.split(".");
			smove = amove[1];
		}
		if(smove.indexOf(",") >= 0) {
			amove = smove.split(",");
			dice = amove[0];
		}
	}
// 	writeDebug('getDiceX  --> ' + dice);
	return dice;
}

function getNewPos(dice) {
	var totroll = getTotRoll(dice, dieToRemove);
	curdir = parseInt(boatpos[iam].substring(0,1));
	var newpos = get1NewPos(totroll, curdir);
	if(totroll > 0) { 
	 	newpos = newpos + get1NewPos(totroll, (curdir+4) % 6 + 1); 
		newpos = newpos + get1NewPos(totroll, curdir % 6 + 1);
	}
	newpos = getMinDamageMoves(newpos);
	return newpos;
}

function getTotRoll(dice, nodie) {
 	var totroll = 0;
	for(var i=0; i<dice.length; i++) {
	 	if(i != nodie) {
			totroll = totroll + parseInt(dice.substring(i, i+1));
		}
	}
//	writeDebug('getTotRoll ' + dice + ' nodie:' + nodie + ' tot:' + totroll);
	return totroll;	
}

function get1NewPos(totroll, dir) {
	var px = boatpos[iam].charCodeAt(1) - 48;
	var py = boatpos[iam].charCodeAt(2) - 48;
	var i = 0;
	var newpos = '';
	dx = getXDir(dir);
	dy = getYDir(dir);
	var dmg = 0;
	while(i < totroll && dmg == 0) {
		if(px + dx >= 0 && py + dy >= 0 && px + dx <= 22 && py + dy <= 40 && field[px+dx][py+dy].substring(0,1) == "0") {
			px += dx;
			py += dy;
		} else {
		 	dmg = totroll - i;
		}
		i++;
	}
	if(boatpos[1-iam].substring(1,3) == String.fromCharCode(px+48,py+48)) {
		px -= dx;
		py -= dy;
	}
	if(newpos == '') {
		newpos = "(" + px + "," + py + "," + dmg + "," + dir + ")";
	}
	return newpos;
}

function getXDir(dir) {
	if(dir == 1) { dx = 0; }
	if(dir == 2) { dx = -1; }
	if(dir == 3) { dx = -1; }
	if(dir == 4) { dx = 0; }
	if(dir == 5) { dx = 1; }
	if(dir == 6) { dx = 1; }
	return dx;
}

function getYDir(dir) {
	if(dir == 1) { dy = -2; }
	if(dir == 2) { dy = -1; }
	if(dir == 3) { dy = 1; }
	if(dir == 4) { dy = 2; }
	if(dir == 5) { dy = 1; }
	if(dir == 6) { dy = -1; }
	return dy;
}

function getMinDamageMoves(moves) {
	var xmove = moves.split(")");
	var goodmoves = '';
	var mindamage = 99;
	for(var i=0; i<xmove.length-1; i++) {
		var xx = xmove[i].split(",");
		var d = parseInt(xx[2]);
		if(d < mindamage) {
			mindamage = d;
			goodmoves = xx[0] + "," + xx[1] + "," + xx[2] + "," + xx[3] + ")";
		} else if(d == mindamage) {
			goodmoves = goodmoves + xx[0] + "," + xx[1] + "," + xx[2] + "," + xx[3] + ")";
		}
	}
	return goodmoves;
}
