var selectable = '';
var action = '';
var positions = new Array();
var ballpos;
var lastroll = 0;
var kickoff = 0;
var lastmove = '';

var score = new Array();
var thisMove = '';
var curmoveno = 99;
var nextmoveno = 99;

var animateCount = 100;
var curAnimateMove = -1;
var undoing = 0;

var xbase = -5;
var ybase = -10;
var swidth = 42.5;
var sheight = 42.5;
var SELSIZE = 36;
var INDSIZE = 39;

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;
  
//  window.status = '(' + tempX + ',' + tempY + ')';

  var i = 0;
  while(i < selectable.length && selpos == '') {
    py = ybase + getCodeFromChar(selectable.substring(i,i+1)) * sheight;
    px = xbase + getCodeFromChar(selectable.substring(i+1,i+2)) * swidth;
    if(myturn==1) {py = 10 * sheight + 24 - py; px = 7 * swidth - 10 - px;}
    if(tempX >= px && tempX < px+39 && tempY >= py && tempY < py+39) {
      selpos = selectable.substring(i,i+2);
	}
	i += 2;
  }
  
  i = 0;
  while(i < positions.length) {
    py = ybase + getCodeFromChar(positions[i].substring(0,1)) * sheight;
    px = xbase + getCodeFromChar(positions[i].substring(1,2)) * swidth;
    if(myturn==1) {py = 10 * sheight + 24 - py; px = 7 * swidth - 10 - px;}
    if(tempX >= px && tempX < px+39 && tempY >= py && tempY < py+39) {
      if(playernames[i] != '') { showPlayerName(px,py + sheight,playernames[i]); }
      i = 10;
	} else {
	  hidePlayerName();
	  i++;	
	}
  }
  return selpos;
}

function moveImg(myturn,e) {
 	var selpos = getCursorPos(myturn,e);
	var sel = document.getElementById('selector');
	if(selpos == '') {
		sel.style.width = 0;
		sel.style.height = 0;
		document.body.style.cursor = 'default';
	} else {
		py = ybase + getCodeFromChar(selpos.substring(0,1)) * sheight;
		px = xbase + getCodeFromChar(selpos.substring(1,2)) * swidth;
		if(myturn==1) {py = 10 * sheight + 24 - py; px = 7 * swidth - 10 - px;}
		sel.style.left = px;
		sel.style.top = py;	
		sel.style.width = SELSIZE;
		sel.style.height = SELSIZE;    
		document.body.style.cursor = 'pointer';
	}
 	
}

function showPlayerName(px,py,name) {
 	if(document.getElementById('divPlayername')) {
		var divPlayername = document.getElementById('divPlayername');
		divPlayername.style.top = py;
		divPlayername.style.left = px;
		showText('divPlayername', name);
		divPlayername.style.visibility = 'visible';
	}
}

function hidePlayerName() {
 	if(document.getElementById('divPlayername')) {
		var divPlayername = document.getElementById('divPlayername');
		divPlayername.style.visibility = 'hidden';
		document.body.style.cursor = 'default';
	}
}

function getPosX(posc, iam) {
  posx = posc.charCodeAt(0) - 65;
  if(iam == 1) { posx = 11 - posx; }
  return posx;
}

function getPosY(posc, iam) {
  posy = posc.charCodeAt(1) - 48;
  if(iam == 1) { posy = 7 - posy; }
  return posy;
}

function doMove(xmove, smove) {
// alert('doMove ' + xmove + ', ' + smove);
  if(smove.substring(0,1) == '+') {
	smove = smove.substring(1,5);
	ballpos = smove.substring(2,4);
  }
  if(smove.substring(0,1) == 'S') {
   	for(var i=1; i < smove.length; i=i+2) {
		positions[(i-1)/2] = smove.substring(i,i+2);
	}
  } else {
	var from = smove.substring(0,2);
	var to = smove.substring(2,4);
	var x, moving;
	for(var i=0; i<10; i++) {
		if(positions[i]==from || positions[i]==to) { 
		 	positions[i]=to; 
		 	if(i<5) { moving = 0; } else { moving = 1; }
		}
	}
	if(smove.length>4) {
	 	if(smove.indexOf('!') < 0) {
	 	 	x = smove.length - 2;
		} else {
			x = smove.indexOf('!') - 2;
			if(xmove > 2) { score[moving]++; }
		}
		ballpos = smove.substring(x,x+2);
	}
  }
  lastmove = smove;
}

function buildFieldUntilMove(moveno) {
	score[0] = 0;
	score[1] = 0;
	positions = new Array();
	ballpos = '';
	var i = 0;
	while(i <= moveno && i < move.length) {
	 	doMove(i, move[i]);
		i++;
	}
}

function clearField() {
	for(var i = 0; i < 10; i++) {
	 	var playerImg = document.getElementById('player' + i);
		playerImg.style.width = 0;
		playerImg.style.height = 0;
	 	var backnumImg = document.getElementById('backnum' + i);
	 	if(backnumImg != null) {
			backnumImg.style.width = 0;
			backnumImg.style.height = 0;
		}
	}
 	var ballImg = document.getElementById('ball');
	ballImg.style.width = 0;
	ballImg.style.height = 0;
	clearMoveInd();
	clearSelectable();
}

function clearMoveInd() {
	for(var i=0; i < 3; i++) {
	 	var moveIndImg = document.getElementById('moveInd' + i);
		moveIndImg.style.width = 0;
		moveIndImg.style.height = 0;
	}	
}

function showGameAtMove(moveno) {
 	clearField();
 	if(moveno == 99) { curmoveno = move.length - 1; } else { curmoveno = moveno; }
 	nextmoveno = curmoveno;
 	xmove = curmoveno - 1;
	buildFieldUntilMove(xmove);
	if(curmoveno < 2) { lastroll = -1; kickoff = 0; }
	if(curmoveno == 2) { lastroll = Math.abs(roll[0] - roll[1]); kickoff = 1; }
	if(curmoveno > 2) {	lastroll = roll[xmove]; kickoff = 0; }
	hideAllBlocks();
 	showGame();
 	if(showAnimation == 1 && undoing == 0) { startAnimateMove(xmove + 1, move[xmove+1]); }
 	if(curmoveno >= 0) { doMove(nextmoveno, move[curmoveno]); }
	thisMove = '';
	if(myturn==1 && moveno==99) {
	 	if(curmoveno >= 0 && move[curmoveno].substring(0,1) != '+') {
	 		nextmoveno = curmoveno + 1;
	 	}
		if(nextmoveno < 2) { lastroll = -1; kickoff = 0; }
		if(nextmoveno == 2) { lastroll = Math.abs(roll[0] - roll[1]); kickoff = 1; }
		if(nextmoveno > 2) {		 	
		 	if(move[curmoveno].substring(0,1) != '+') { lastroll = roll[curmoveno]; kickoff = 0; }
		}
		document.getElementById('divMove').style.display = 'block';
		document.getElementById('divResignBtn').style.display = 'block';
		if(moveno == 99) {
		 	if(curmoveno < 1) {
				showText('divMove', 'Place your keeper');
				if(iam==0) { selectable = 'K3K4'; } else { selectable = 'B3B4'; }
				action = 'place';
				thisMove = 'S';
			}
			if(curmoveno == 1) {
				showText('divMove', 'Kickoff');
				if(iam==0) { if(move[0].indexOf('G3') >= 0) { ballpos = 'G3';} else { ballpos = 'G4';}}
				if(iam==1) { if(move[1].indexOf('F3') >= 0) { ballpos = 'F3';} else { ballpos = 'F4';}}
				action = 'kickball';
				thisMove = ballpos + ballpos;
				selectable = getPosForBallX(1, thisMove);
				selectable = selectable.replace('A3', '');
				selectable = selectable.replace('A4', '');
				selectable = selectable.replace('L3', '');
				selectable = selectable.replace('L4', '');
			}
			if(curmoveno > 1) {
				var bp0 = ballpos.substring(0,1);
				if(bp0 == 'A' || bp0 == 'L') {
					showText('divMove', 'Place your keeper');					
					action = 'kickout';
					thisMove = positions[5*iam];
					if(iam==0) { selectable = 'K3K4'; } else { selectable = 'B3B4'; }
				} else if(move[curmoveno].substring(0,1) == '+'){
				 	showText('divMove', 'Select square to kick the ball to');
				 	action = 'kickball';
				 	ballpos = move[curmoveno].substring(3,5);
				 	thisMove = ballpos + ballpos;
				 	selectable = getPosForBall(thisMove);
				} else {
					showText('divMove', 'Select player to move');
					action = 'move1';
					for(var i=0; i<5; i++) {
						if(iam == 0) { selectable += positions[i]; } else { selectable += positions[i+5]; }
					}
				}
			}
		}
	} else {
		showText('divMove', '');
	}
	if(showAnimation == 0 || undoing == 1) { showGame(); }
	undoing = 0;
}

function showGame() {
 	var i = 0;
 	var ballatplayer = 0;
 	while(i < positions.length) {
	 	var playerImg = document.getElementById('player' + i);
		playerImg.style.width = 23;
		playerImg.style.height = 37;
		var topx = -10 + getPosX(positions[i],iam) * sheight;
		var leftx = 2 + getPosY(positions[i],iam) * swidth;
		playerImg.style.top = topx;
		playerImg.style.left = leftx; 	 	
		if(positions[i] == ballpos) { ballatplayer = 1; }
		if(numbersonback > 0 && i != 0 && i != 5) {
			var numberImg = document.getElementById('backnum' + i);
			numberImg.style.width = 6;
			numberImg.style.height = 9;
			var di, dj;
			if((i < 5 && iam != 1) || (i > 5 && iam == 1)) {
				topx += 25 - 12 * numbersonback;
				leftx += 9 * numbersonback;
			} else {
				topx += 3 + 12 * numbersonback;
				leftx += 19 - 10 * numbersonback;
			}
			numberImg.style.top = topx;
			numberImg.style.left = leftx; 	 	
		}
		i++;
	}
	if(ballpos != '') {
	 	var ballImg = document.getElementById('ball');
		ballImg.style.width = 25 - 13 * ballatplayer;
		ballImg.style.height = 25 - 13 * ballatplayer;
		ballImg.style.top = -4 + getPosX(ballpos,iam) * sheight + 18 * ballatplayer;
		ballImg.style.left = 2 + getPosY(ballpos,iam) * swidth + 13 * ballatplayer;		
	}
	for(var i = 0; i < 2; i++) {
		showText('spanScore' + i, score[i]);		
	}
	if(document.getElementById('divKickoff')) {
		if(kickoff == 1) {
			document.getElementById('dieYellowImg').src = 'images/general/dice/dieyellow' + roll[0] + '.gif';		
			document.getElementById('dieRedImg').src = 'images/general/dice/diered' + roll[1] + '.gif';		
			document.getElementById('divKickoff').style.display = 'block';
		} else {
		 	if(lastroll > 0) {
				document.getElementById('divKickoff').style.display = 'none';
				var dieClr = "blue";
				if((nextmoveno % 2 == 0 && roll[0] > roll[1]) || (nextmoveno % 2 == 1 && roll[0] < roll[1])) { dieClr = "yellow"; } else { dieClr = "red"; }
				document.getElementById('dieImg').src = 'images/general/dice/die' + dieClr + lastroll + '.gif';
				document.getElementById('divDie').style.display = 'block';
			} else {
				document.getElementById('divKickoff').style.display = 'none';
				document.getElementById('divDie').style.display = 'none';			
			}
		}
	}
	
	var x = lastmove.length;
	var xs = 0;
	var moveInd0 = document.getElementById('moveInd0');
	if(x > 1 && lastmove.substring(0,1) != "S") { xs = INDSIZE; } else { xs = 0; }
	moveInd0.style.width = xs;
	moveInd0.style.height = xs;
	if(xs > 0) {
		moveInd0.style.top = -11 + getPosX(lastmove.substring(0,2),iam) * sheight;
		moveInd0.style.left = -7 + getPosY(lastmove.substring(0,2),iam) * swidth;	
	}
	var moveInd1 = document.getElementById('moveInd1');
	if(x > 3 && lastmove.substring(0,1) != "S") { xs = INDSIZE; } else { xs = 0; }
	moveInd1.style.width = xs;
	moveInd1.style.height = xs;
	if(xs > 0) {
		moveInd1.style.top = -11 + getPosX(lastmove.substring(2,4),iam) * sheight;
		moveInd1.style.left = -7 + getPosY(lastmove.substring(2,4),iam) * swidth;	
	}
	var moveInd2 = document.getElementById('moveInd2');
	if(x > 5 && lastmove.substring(0,1) != "S") { xs = INDSIZE; } else { xs = 0; }
	moveInd2.style.width = xs;
	moveInd2.style.height = xs;
	if(xs > 0) {
		if(lastmove.substring(x-1,x) == '!') { x--; }
		moveInd2.style.top = -11 + getPosX(lastmove.substring(x-2,x),iam) * sheight;
		moveInd2.style.left = -7 + getPosY(lastmove.substring(x-2,x),iam) * swidth;	
	}
}

function fieldClick(myturn,e) {
 	stopAnimation();
 	var selpos = getCursorPos(myturn,e);
 	if(selpos != '') {
		document.body.style.cursor = 'default';
 		hideAllBlocks();
	 	clearSelectable();
		if(action == 'move1') {
		 	thisMove = selpos;
		 	lastmove = selpos;
		 	showGame();
		 	selectable = getPosForPlayer(selpos);
			document.getElementById('divDie').style.display = 'block';
			document.getElementById('divMove').style.display = 'block';
			document.getElementById('divUndo').style.display = 'block';
			document.getElementById('divResignBtn').style.display = 'block';
			showText('divMove', 'Select square to move player to');
			action = 'move2';
		} else if(action == 'move2') {
			thisMove = thisMove + selpos;
			if(showAnimation == 1) { startAnimateMove(99, thisMove); }
			doMove(nextmoveno, thisMove);
//			showGame();
			if(selpos != ballpos) {
				// Move complete for player
				document.getElementById('divDie').style.display = 'block';
				document.getElementById('divConfirm').style.display = 'block';
				if(curmoveno >= 70 || (curmoveno >= 50 && score[0] != score[1])) {
					showText('divMove', 'Game over');
					document.getElementById('divMove').style.display = 'block';
				} 
				document.getElementById('divConfirmBtn').style.display = 'block';
				document.getElementById('divResignBtn').style.display = 'block';
				document.post.move.value = thisMove;
//				document.post.gameend.value = gameend;
//				document.post.score0.value = score[0];
//				document.post.score1.value = score[1];
			} else {
				action = 'kickball';
				selectable = getPosForBall(thisMove);
				document.getElementById('divDie').style.display = 'block';
				document.getElementById('divMove').style.display = 'block';
				document.getElementById('divUndo').style.display = 'block';
				document.getElementById('divResignBtn').style.display = 'block';
				showText('divMove', 'Select square to kick the ball to');				
			}
		} else if(action == 'kickball') {
			var kickfrom = thisMove.substring(thisMove.length-2,thisMove.length);
			thisMove = thisMove + selpos;
			if(showAnimation == 1) { startAnimateMove(99, kickfrom + kickfrom + selpos); }
			if(selpos.substring(0,1) == 'A' || selpos.substring(0,1) == 'L') { doMove(nextmoveno, thisMove + '!'); } else { doMove(nextmoveno, thisMove); }
			var done = 1;
			for(var i=0; i<10; i++) {
				if(positions[i] == selpos) { done = 0; }
			}
			if(kickoff == 1) {
				document.getElementById('divKickoff').style.display = 'block';
			} else {
				document.getElementById('divDie').style.display = 'block';
			}
			if(done == 0) {
				if(thisMove.length >= 20) {
					alert("Move too long. Please redo your move using less passes.");
					showGameAtMove(99);
				} else {
			 		selectable = getPosForBall(thisMove);
			 		if(curmoveno == 1) {
						selectable = selectable.replace('A3', '');
						selectable = selectable.replace('A4', '');
						selectable = selectable.replace('L3', '');
						selectable = selectable.replace('L4', '');
					}
					document.getElementById('divMove').style.display = 'block';
					document.getElementById('divUndo').style.display = 'block';
				}
			} else {
				if(move[curmoveno].substring(0,1) == '+') {
					thisMove = move[curmoveno].substring(1,5) + thisMove.substring(4,thisMove.length);								
				}
				correctPlayerInGoalArea();
				document.getElementById('divConfirm').style.display = 'block';
				if(curmoveno >= 70 || (curmoveno >= 50 && score[0] != score[1])) {
					showText('divMove', 'Game over');
					document.getElementById('divMove').style.display = 'block';
				} 
				document.getElementById('divConfirmBtn').style.display = 'block';
				document.getElementById('divResignBtn').style.display = 'block';
				document.post.move.value = thisMove;								
			}
//			showGame();
		} else if(action == 'place') {
			thisMove = thisMove + selpos;
			if(showAnimation == 1) { startAnimateMove(100 + iam, thisMove); }
		 	if(iam == 0) { doMove(nextmoveno, thisMove); } else { doMove(nextmoveno, move[0] + thisMove.substring(1,11)); }
//			showGame();
			if(thisMove.length == 11) {
				document.getElementById('divConfirm').style.display = 'block';
				document.getElementById('divConfirmBtn').style.display = 'block';
				document.getElementById('divResignBtn').style.display = 'block';
				document.post.move.value = thisMove.substring(1,11);				
			} else {
				showText('divMove', 'Place a player on the field');
				document.getElementById('divMove').style.display = 'block';
				document.getElementById('divUndo').style.display = 'block';
				document.getElementById('divResignBtn').style.display = 'block';
				var countdef = 0;
				var countoff = 0;
				for(var i=3; i<thisMove.length; i=i+2) {
					if(thisMove.substring(i,i+1) < 'F') { countoff++; }
					if(thisMove.substring(i,i+1) == 'F') {
						if(thisMove.substring(i+1,i+2) < '3' || thisMove.substring(i+1,i+2) > '4') { countoff++; }
					}
					if(thisMove.substring(i,i+1) == 'G') {
						if(thisMove.substring(i+1,i+2) < '3' || thisMove.substring(i+1,i+2) > '4') { countdef++; }
					}
					if(thisMove.substring(i,i+1) > 'G') { countdef++; }
				}
				var sel0;
				if(iam == 0) { sel0 = 'G3G4'; } else { sel0 = 'F3F4'; }
				if(countoff < 2 && countoff + countdef < 3) { 
					sel0 = sel0 + 'B1B2B5B6C1C2C3C4C5C6D1D2D3D4D5D6E1E2E3E4E5E6F1F2F5F6';
				}
				if(countdef < 2 && countoff + countdef < 3) { 
					sel0 = sel0 + 'G1G2G5G6H1H2H3H4H5H6I1I2I3I4I5I6J1J2J3J4J5J6K1K2K5K6';
				}
				selectable = '';
				for(var i=0; i<sel0.length; i=i+2) {
				 	var x = sel0.substring(i,i+2);
				 	var p = 1;
					if(thisMove.indexOf(x) >= 0) { p = 0; }
					if(p == 1 && iam == 1) { if(move[0].indexOf(x) >= 0) { p = 0; }}
					if(p == 1 && iam == 0 && x == 'J3') { if(thisMove.indexOf('J4') >= 0) { p = 0; }}
					if(p == 1 && iam == 0 && x == 'J4') { if(thisMove.indexOf('J3') >= 0) { p = 0; }}
					if(p == 1 && iam == 1 && x == 'C3') { if(thisMove.indexOf('C4') >= 0) { p = 0; }}
					if(p == 1 && iam == 1 && x == 'C4') { if(thisMove.indexOf('C3') >= 0) { p = 0; }}
					if(p == 1) {
						selectable = selectable + sel0.substring(i,i+2);
					}
				}
			}
		} else if(action == 'kickout') {
			thisMove = thisMove + selpos;
			if(showAnimation == 1) { startAnimateMove(99, thisMove); }
			doMove(nextmoveno, thisMove);
//			showGame();
			document.getElementById('divKickout').style.display = 'block';
			document.getElementById('divUndo').style.display = 'block';
			document.getElementById('divResignBtn').style.display = 'block';
			document.post.move.value = '+' + thisMove;				
		}
	}
	if(showAnimation == 0) { showGame(); }
}

function clearSelectable() {
 	selectable = '';
	var sel = document.getElementById('selector');
	sel.style.width = 0;
	sel.style.height = 0;
}

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

function hideAllBlocks() {
 	if(document.getElementById('divMove')) {
		document.getElementById('divKickoff').style.display = 'none';
		document.getElementById('divDie').style.display = 'none';
		document.getElementById('divMove').style.display = 'none';
		document.getElementById('divKickout').style.display = 'none';
		document.getElementById('divUndo').style.display = 'none';
		document.getElementById('divConfirm').style.display = 'none';
		document.getElementById('divResign').style.display = 'none';
		document.getElementById('divResignBtn').style.display = 'none';
		document.getElementById('divConfirmBtn').style.display = 'none';
		document.getElementById('divConfirmResign').style.display = 'none';
	}
}

function getPosForPlayer(playerpos) {
  kickball = false;
  startpos = playerpos;
  posexself = '';
  for(var i=0; i<10; i++) {
   	 if(positions[i] != playerpos) {
	 	posexself = posexself + positions[i];
	 }
  }
  for(var x=0; x<lastroll; x++) {
    postogo = '';
    for(var i=0; i<startpos.length ; i+=2) {
	  posx = startpos.charCodeAt(i);
	  posy = startpos.charCodeAt(i+1);
	  for(var r=0;r<4;r++) {	    
	    if(r==0) {posxx = posx+1; posyy = posy;}
	    if(r==1) {posxx = posx; posyy = posy+1;}
	    if(r==2) {posxx = posx-1; posyy = posy;}
	    if(r==3) {posxx = posx; posyy = posy-1;}
	    if(posxx>=65 && posxx<=76 && posyy>=48 && posyy<=55) {
			posc = String.fromCharCode(posxx, posyy);
			if(posc == ballpos) { kickball = true;} else {
			 	if(posexself.indexOf(posc) < 0) {
				 	postogo = xAddToString(postogo, posc);
				}
			}
		}
	  }      
	}
	startpos = postogo;
  }
  if(playerpos != positions[iam*5]) {
  	//fieldplayer can't be in goalarea  	
  	postogo = postogo.replace('B3', '');
  	postogo = postogo.replace('B4', '');
  	postogo = postogo.replace('K3', '');
  	postogo = postogo.replace('K4', '');
  } else {
  	//keeper can't be in opponent goalarea  
  	if(iam==0) {
	  	postogo = postogo.replace('B3', '');
	  	postogo = postogo.replace('B4', '');
	}
    if(iam==1) {
	  	postogo = postogo.replace('K3', '');
	  	postogo = postogo.replace('K4', '');
  	}
  }
  // you can always get to the ball, even if it's in the goalarea
  if(kickball) { postogo = postogo + ballpos; }
  if(playerpos != positions[iam*5]) {
  	//only one fieldplayer in the box, even if the ball is there
  	if(iam==0) {
  		if(postogo.indexOf('J3') >= 0) {
			j = getPlayerIndOfPos('J4', playerpos);
			if(j > 0 && j < 5) { postogo = postogo.replace('J3', ''); }
		}
  		if(postogo.indexOf('J4') >= 0) {
			j = getPlayerIndOfPos('J3', playerpos);
			if(j > 0 && j < 5) { postogo = postogo.replace('J4', ''); }
		}
  	}
  	if(iam==1) {
  		if(postogo.indexOf('C3') >= 0) {
			j = getPlayerIndOfPos('C4', playerpos);
			if(j > 5) { postogo = postogo.replace('C3', ''); }
		}
  		if(postogo.indexOf('C4') >= 0) {
			j = getPlayerIndOfPos('C3', playerpos);
			if(j > 5) { postogo = postogo.replace('C4', ''); }
		}
  	}
  }
  var i=0;
  while(i < postogo.length) {
	var x = postogo.substring(i,i+2);
	if(x != ballpos) {
		if(!isLegalMove(playerpos + x)) {
			postogo = postogo.replace(x, '');
		} else {
		 	i = i + 2;
		}
	} else {
		i = i + 2;
	}
  }
  return postogo;
}

function getPosForBall(move) {
  return getPosForBallX(0, move);
}

function getPosForBallX(kickout, move) {
  sel = '';
  rem = remainingAfterMove(kickout);
  max = 0;
  for(var i=0; i<rem.length; i++) {
  	if(rem.substring(i,i+1) > max) { max = rem.substring(i,i+1); }
  }
  dist = 1;
  for(di=1; di<9; di++) {
	  dx = getDx(di);
      dy = getDy(di);
	  // kick in straight line
	  posx = ballpos.charCodeAt(0);
	  posy = ballpos.charCodeAt(1);
	  for(dist=1; dist <= max; dist++) {
	    posx += dx;
	    posy += dy;
	    if((posx==65 && (iam==1 || posy-dy<51 || posy-dy>52)) || (posx==76  && (iam==0 || posy-dy<51 || posy-dy>52)) || posy < 49 || posy > 54) { dist = 9; } else {
		    posc = String.fromCharCode(posx, posy);
		    j = getPlayerIndOfPos(posc, 'xx');
		    if(j >= 0) {
		  	  if(posx==65 || posx==76) {
				sel = xAddToString(sel, posc);
			  } else {
			   		if((iam==0 && j<5) || (iam==1 && j>=5)) {
					  sel = xAddToString(sel, posc);
				  	}
			  }
			  dist = 9;
			} else {
			  if(rem.indexOf(dist) >= 0 || posx==65 || posx==76) {
			  	sel = xAddToString(sel, posc);			    
				if(posx==65 || posx==76) { dist = 9;}
			  }
			  if(dist < max) {
			  	// kick with curve
			  	for(crv=-1;crv < 2; crv+=2) {
				  posxx = posx;
				  posyy = posy;
			 	  dxx = getDx(di+crv);
				  dyy = getDy(di+crv);
				  for(dd=dist+1; dd <= max; dd++) {
				    posxx += dxx;
				    posyy += dyy;
				    if((posxx==65 && (iam==1 || posyy-dyy<51 || posyy-dyy>52)) || (posxx==76  && (iam==0 || posyy-dyy<51 || posyy-dyy>52)) || posyy < 49 || posyy > 54 ) { dd = 9; } else {
					    posc = String.fromCharCode(posxx, posyy);
					    j = getPlayerIndOfPos(posc, 'xx');
					    if(j >= 0) {
					   		if((iam==0 && j<5) || (iam==1 && j>=5)) {
						  		sel = xAddToString(sel, posc);
						  	}
						  	dd = 9;
						} else {
						  if(rem.indexOf(dd) >= 0 || posxx==65 || posxx==76) {
						  	sel = xAddToString(sel, posc);
							if(posxx==65 || posxx==76) { dd = 9;}
						  }
						}
					}
				  }
				}
			  }
			}
		}
	  }
  }
  // check for illegal moves
  var i = 0;
  while(i<sel.length) {
   	 var selx = sel.substring(i,i+2);
	 if(!isLegalMove(move + selx)) { sel = sel.replace(selx, ''); } else { i += 2; }
  }
  return sel;
}

function getDx(i) {
	if((i>0 && i<4) || (i==9)) { return -1; } else { if(i>4 && i<8) { return 1;} else { return 0;}}
}

function getDy(i) {
	if(i<2 || i>6) { return -1; } else { if(i>2 && i<6) { return 1;} else { return 0;}}
}

function remainingAfterMove(kickout) {
  rem = '';
  kickstart = thisMove.substring(2,4);
  ksx = thisMove.charCodeAt(2);
  ksy = thisMove.charCodeAt(3);
  kickdist = 0;
  for(var i=4;i<thisMove.length;i+=2) {
  	ksxx = thisMove.charCodeAt(i);
  	ksyy = thisMove.charCodeAt(i+1);
  	xd = Math.abs(ksxx-ksx);
  	yd = Math.abs(ksyy-ksy);
  	if(xd > yd) { kickdist += xd - 1; } else { kickdist += yd - 1; }
  	ksx = ksxx;
  	ksy = ksyy;
  }
  startpos = thisMove.substring(0,2);
  if(startpos == thisMove.substring(2,4) || kickout == 1) { rem = String.fromCharCode(lastroll - kickdist + 48); } else {
	  for(var x=0; x<lastroll; x++) {
	    postogo = '';
	    for(var i=0; i<startpos.length; i+=2) {
		  posx = startpos.charCodeAt(i);
		  posy = startpos.charCodeAt(i+1);
		  for(var r=0;r<4;r++) {	    
		    if(r==0) {posxx = posx+1; posyy = posy;}
		    if(r==1) {posxx = posx; posyy = posy+1;}
		    if(r==2) {posxx = posx-1; posyy = posy;}
		    if(r==3) {posxx = posx; posyy = posy-1;}
		    if(posxx>=65 && posxx<=76 && posyy>=48 && posyy<=55) {
				posc = String.fromCharCode(posxx, posyy);
				if(posc == thisMove.substring(2,4)) {
				   rr = lastroll - x - kickdist;
				   if(rr > 0) { rem = xAddToString(rem, String.fromCharCode(rr + 48)); }
				} else {
				 	if(getPlayerIndOfPos(posc, thisMove.substring(0,2)) < 0) {
				 	 	postogo = xAddToString(postogo, posc);
					}
				}
			}
		  }      
		}
		startpos = postogo;
	  } 
  }
  return rem;
}

function getPlayerIndOfPos(pos, excl) {
	var j = 0;
	while(j < positions.length && (positions[j] != pos || positions[j] == excl)) { j++; }
	if(j >= positions.length) { j = -1; }
	return j;
}

function xAddToString(org, addition) {
	if(org.indexOf(addition) < 0) {
		org = org + addition;
	}
	return org;
}

function confirmKeeper() {
	window.location = 'game.php?gameid=' + gameid + '&placekeeper=' + thisMove;
}

function isLegalMove(move) {
 	// check for kill-joy rules: see if opp can reach ball
 	var fld = new Array(12);
 	var playersinfield = 1;
 	for(var i=0; i<12; i++) {
 	 	fld[i] = new Array(8);
		for(var j=0; j<8; j++) {
			fld[i][j] = 0;
		}
	}
 	for(var i=0; i<2; i++) {
		for(var j=0; j<5; j++) {
			fld[getPosX(positions[i*5+j],0)][getPosY(positions[i*5+j],0)] = 1 + i;
		}
	}
	if(fld[getPosX(move.substring(2,4),0)][getPosY(move.substring(2,4),0)] == 0) {
		fld[getPosX(move.substring(2,4),0)][getPosY(move.substring(2,4),0)] = fld[getPosX(move.substring(0,2),0)][getPosY(move.substring(0,2),0)];
		fld[getPosX(move.substring(0,2),0)][getPosY(move.substring(0,2),0)] = 0;
	}
	var found = 1;
	var ok = 0;
	if(move.length > 4) {
	 	var xx = getPosX(move.substring(move.length-2,move.length),0);
	 	if(xx == 0 || xx == 11) { ok = 1; } else {
			fld[xx][getPosY(move.substring(move.length-2,move.length),0)] = 9;
		}
	} else {
		fld[getPosX(ballpos,0)][getPosY(ballpos,0)] = 9;
	}
	while(found == 1 && ok == 0 && playersinfield > 0) {
	 	found = 0;
	 	playersinfield = 0;
		for(var i=1; i<11; i++) {
			for(var j=1; j<7; j++) {
				if(fld[i][j] == 2 - iam) {
				 	ok += setFld(fld,i+1,j,2-iam);
				 	ok += setFld(fld,i-1,j,2-iam);
				 	ok += setFld(fld,i,j+1,2-iam);
				 	ok += setFld(fld,i,j-1,2-iam);
				 	fld[i][j]=5;
					found = 1;
				}
				if(fld[i][j] == 1 + iam) { playersinfield++; }
			}
		}
	}
	return (ok > 0 && playersinfield > 0);
}

function setFld(fld,i,j,v) {
  ret = 0;
  if(i>0 && i<11 & j>0 && j<7) {
  	if(fld[i][j]==9) { ret=1;} else {
	    if(fld[i][j]==0) {fld[i][j]=v;}
	}
  }
  return ret;
}

function correctPlayerInGoalArea() {
	var playerStartPos = thisMove.substring(0,2);
	var playerEndPos = thisMove.substring(2,4);
	var newpos = "";
	if(playerEndPos == "B3" || playerEndPos == "B4" || playerEndPos == "K3" || playerEndPos == "K4") {
		if(((playerEndPos == "B3" || playerEndPos == "B4") && playerEndPos == positions[5]) 
		|| ((playerEndPos == "K3" || playerEndPos == "K4") && playerEndPos == positions[0])) {
			// ignore goalkeeper in own goalarea
		} else {
			// move player out of goalarea
			if(playerEndPos == "B3") {
				if(squareIsEmpty("C3") && countFieldPlayersInBox(playerStartPos, "B") == 0) { newpos = "C3"; }
				if(newpos == "" && squareIsEmpty("B2")) { newpos = "B2"; }
				if(newpos == "" && squareIsEmpty("B5")) { newpos = "B5"; }
				if(newpos == "" && squareIsEmpty("C2")) { newpos = "C2"; }
				if(newpos == "") {
					var x = 68;
					while(!squareIsEmpty(String.fromCharCode(x)+"3")) { x++; }
					newpos = String.fromCharCode(x)+"3";
				}
			}
			if(playerEndPos == "B4") {
				if(squareIsEmpty("C4") && countFieldPlayersInBox(playerStartPos, "B") == 0) { newpos = "C4"; }
				if(newpos == "" && squareIsEmpty("B5")) { newpos = "B5"; }
				if(newpos == "" && squareIsEmpty("B2")) { newpos = "B2"; }
				if(newpos == "" && squareIsEmpty("C5")) { newpos = "C5"; }
				if(newpos == "") {
					var x = 68;
					while(!squareIsEmpty(String.fromCharCode(x)+"4")) { x++; }
					newpos = String.fromCharCode(x)+"4";
				}
			}
			if(playerEndPos == "K3") {
				if(squareIsEmpty("J3") && countFieldPlayersInBox(playerStartPos, "K") == 0) { newpos = "J3"; }
				if(newpos == "" && squareIsEmpty("K2")) { newpos = "K2"; }
				if(newpos == "" && squareIsEmpty("K5")) { newpos = "K5"; }
				if(newpos == "" && squareIsEmpty("J2")) { newpos = "J2"; }
				if(newpos == "") {
					var x = 73;
					while(!squareIsEmpty(String.fromCharCode(x)+"3")) { x--; }
					newpos = String.fromCharCode(x)+"3";
				}
			}
			if(playerEndPos == "K4") {
				if(squareIsEmpty("J4") && countFieldPlayersInBox(playerStartPos, "K") == 0) { newpos = "J4"; }
				if(newpos == "" && squareIsEmpty("K5")) { newpos = "K5"; }
				if(newpos == "" && squareIsEmpty("K2")) { newpos = "K2"; }
				if(newpos == "" && squareIsEmpty("J5")) { newpos = "J5"; }
				if(newpos == "") {
					var x = 73;
					while(!squareIsEmpty(String.fromCharCode(x)+"4")) { x--; }
					newpos = String.fromCharCode(x)+"4";
				}
			}
			doMove(nextmoveno, thisMove.substring(2,4) + newpos);
			thisMove = thisMove.substring(0,2) + newpos + thisMove.substring(4);
			doMove(nextmoveno, thisMove);
		}
	}
}

function squareIsEmpty(square) {
	var empty = (square != ballpos);
	if(empty) {
		for(var i=0; i<10; i++) {
			if(positions[i] == square) { empty = false; }
		}
	}
	return empty;
}

function countFieldPlayersInBox(ignorePos, box) {
 	var cnt = 0;
	if(iam == 0 && box == "K") {
		for(var i=1; i<5; i++) {
			if(positions[i] != ignorePos && (positions[i] == "J3" || positions[i] == "J4")) { cnt++; }
		}
	}
	if(iam == 1 && box == "B") {
		for(var i=6; i<10; i++) {
			if(positions[i] != ignorePos && (positions[i] == "C3" || positions[i] == "C4")) { cnt++; }
		}
	}
	return cnt;
}

