//v2.96 html-generated code is valid html-transitional

//new in v2.951b
// delay pieces now also rotate
// kfc_mplayer support

var VERSIONNUMBER = "v2.96";
var THISNAME = "ChessDiagram " + VERSIONNUMBER;
var LASTEDITED = "Last edited (DEC-2004)\n\n";

/*
	boardsize is 12*12 by default
	if you edit this, most of the intern database information wouldn't show as intented
	i.e. The start button won't work as intended if the board is less than 12 long
*/

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// USER EDIT BELOW

var BOARDX = 8; //you can edit, numbers between 8 - 32 are recommended, 12 by default
var BOARDY = 8; //you can edit, numbers between 8 - 32 are recommended, 12 by default
var IMG = 40; //board pieces size, recommended values 16 - 64, original imagesize is 38
var PATHCHESS; //path to the chessimages

//if make.chess4player.diagram is used
if (window.parent.PATHCHESS != undefined)
	PATHCHESS = window.parent.PATHCHESS;
//if just chess4player.diagram is used
else	
	//path to the chess images: civ,kfc,newstyle,default
	PATHCHESS = "./images/4player/default/";


var DEADFIELDS;
//if make.chess4player.diagram is used, parsing values
if (window.parent.DEADFIELDS != undefined)
	DEADFIELDS = window.parent.DEADFIELDS;
//if just chess4player.diagram is used
else {
	DEADFIELDS = new Array(


	//building deadfields (outarea)  for the gameboard, the're four 2*2 field corners by default
	//background chessimages
	//the x,y values must be within the BOARDX, BOARDY boundaries, defined above

//	xy(1,1),				xy(1,2), 				xy(2,1), 				xy(2,2), 
//	xy(1,BOARDY-1), 		xy(2,BOARDY-1), 		xy(1,BOARDY),			xy(2,BOARDY),
//	xy(BOARDX-1,1), 		xy(BOARDX-1,2),			xy(BOARDX,1), 			xy(BOARDX,2), 
//	xy(BOARDX-1,BOARDY-1),	xy(BOARDX-1,BOARDY),	xy(BOARDX,BOARDY-1),	xy(BOARDX,BOARDY)

	);
}

// the position string must be valid
// if you make errors here, dont worry, only a warning popup will appear
var STARTPOSITION;   //= "//"; //empty board default, 

;// terminal command onpageload optional
var TERMINALSTART;   //= "clear text|start";

;//
// USER EDIT ABOVE
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~






/*
inspired from maro's chess javascript

If someone wants to use some of the ideas behind this diagram, 
I recommend playing with javascript diagram and implement the code, 
instead of trying to use some code-inspirations from here, as the code is heuristic and 
'not-well-thought', the functions was implemented randomly (was learning javascript) 
and ideas came up along the process of making this.


 - dynamic link position supported, ie. with positiondata,  chess4player.htm?pd=/pkp/8/rk/
 or epd data chess4player.htm?pd=rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
 - 4*8 chess pieces
 - theres a head table which has 3 subtables:  left panel, board area, right panel
 - no special program tricks to make this, very straightforward and not efficient
 - trying to avoid browser object models and use document object model instead
 - making sure the browsers IE/Mozilla support this javascript/html code
 - The board is 12*12, I*J,  2 dimension array and the coordinates are I+1+J*12, where I and J start from 0
 This is used because its easy to calc the coordinates as one int list and that formula is 
 used to calc between 2dim array and long int list in the functions
 - screen is what we see about the placement of pieces, board is intern var to hold info on current placement.
 board var is not used except for making screen picture popup windown
 - gameboard format <td><a href><img></a></td> img wrapped inside <a> and image in td background attrib
the inner image (solid) is in td background attribut, the outer image (moving pieces) is in img src attribute
 - user see coordinates as x=1..12, y=1..12, LN_num=1..144, the intern dataarrays are x=0..11 and LN=num=1..144
 - insert/remove pics is done between using the global chess image obj and the image obj
 defined in the html-board-table from drawTable(), 
 document.Images["LN_?"] where ? is 1..x*y, where x,y is boardDimension. This is the board table
 and the global new Image() vars are the chess constant vars. The document.Images["?"].src are the dynamic value
 - using piece img filenames to manipulate pieces on the board, that is code is dependent on filenames
 - the positiondata and moviedata may contain whitespaces, as they are autoremoved in function

 problems/missings
 - some functions usage/codingstyle could be better
 - slow, because updating all 12*12 array for every change, position is always absolut instead of relative
 - <td background="image_path"></td>, <img src="image_path"> those two image_path can't easyly be compared
 one is saved in memory as absolute path and other relative, used pathName2pieceType() to compare
 - flip image is not always perfect when using delay pieces and removing then.
 - the delay pieces inserted as background images, doesnt work with rotate or move function
 - positiondata string doesnt always work when the one empty piece is in -1 form, instead of just -
 et.c. /-1P-2b-2p/ gives wrong position, but /-P-2b-2p/ is ok, the -1 makes it wrong
 - positiondata could be better. Repeated ///// shold be as /5, like it is for pieces
 - user must be careful about using writeprograms to copy/past and 
 autowrap feature in some writeprograms like notepad, which can make the data corrupt
 because pasting text in the terminal, doesnt support newline.


	positiondataPieceCode, imageName, pieceName
	//
	R = wr = white rook                                  
	N = wn = white knight                                
	B = wb = white bishop                                
	K = wk = white king                                  
	Q = wq = white queen                                 
	P = wp = white pawn                                  
	G = wg = white knightbishy                           
	J = wj = white knightrooky 
	r = br = black rook 
	n = bn = black knight   
	b = bb = black bishop 
	k = bk = black king   
	q = bq = black queen 
	p = bp = black pawn   
	g = bg = black knightbishy 
	j = bj = black knightrooky
	T = rr = red tower      
	H = rn = red horse
	C = rb = red cardinal 
	M = rk = red majestic
	F = rq = red famme   
	W = rp = red worker 
	u = rg = red knightbishy     
	v = rj = red knightrooky                             
	t = gr = green tower                                 
	h = gn = green horse
	c = gb = green cardinal
	m = gk = green majestic
	f = gq = green famme
	w = gp = green worker
	u = gg = green knightbishy
	v = gj = green knightrooky

	//numbers = repeat prev item
	2 = repeat prev item 2 times
	100 = repeat prev item 100 times, etc.
	
	- = ef = 1 empty field
	X = cf = closed field    
	d = mf = mark field (dot)                            
	A = d1 = delay1 field
	D = d2 = delay2 field
	E = d3 = delay3 field
	y,Y = f3,f4 = white/black image first set  
	z,Z = f1,f2 = white/black image second set           
	/ = newline

	% = solidpieces to background startdelimiter
	a = d1 = delay1
	e = d2 = delay2
	o = d3 = delay3

	moviedata
	uses positiondata, and # as marker between positiondata, which delimites the gameframes

 -epikur
*/



// ///////////////////////////////////////////////////////////
// GLOBAL variables

var TERM = ""; //if term is parsed this will get the value, parsed by url query
var PD  = ""; //if pd is parsed this will get the value, parsed by url query
var EPD = ""; //if epd is parsed this will get the value, parsed by url query
var TXT = ""; //if txt is parsed this will get the value, parsed by url query

var IMGS = 20; //panel pieces size, not recommended to edit
var d   = window.document;
var SCROLL = 0; // the scroll couter
if (window.parent.PATH != undefined)
	PATH = window.parent.PATH;
else
	var PATH = "./images/4player/"; //default path to the images

var NUMOFPIECETYPES = 8; //rook,knight,bishop,king,queen,paw,knightbishy,knightrooky
var URL = window.location.href;
	URL = URL.replace( window.location.search.substring(0), ""); //remove queryString if any

//regular expression, filters for PIECECODES for positiondata to load from user
var CHESSCODELIST = "abBcCdefFgGhHjJkKmMnNopPqQrRtTuUvVwWXyYzZ";
//less strict filter, allow as long the char from above are used
var FILTER =      new RegExp("(\\/["+     CHESSCODELIST +"\\-\\d]{0,}){0,}.*");
var FILTERMOVIE = new RegExp("(\\#(\\/["+ CHESSCODELIST +"\\-\\d]{0,}){0,}).*");
//strict filter, allow as long the char from above are used and if board-ysize / delimiter is correct
//var FILTER =      new RegExp("(\\/["+     CHESSCODELIST +"\\-\\d]{0,"+BOARDX+"}){"+BOARDY+"}.*");
//var FILTERMOVIE = new RegExp("(\\#(\\/["+ CHESSCODELIST +"\\-\\d]{0,"+BOARDX+"}){"+BOARDY+"}.*)");

var MPLAYER_COUNTER = 100; //millisec
var MPLAYER_VALUE   = MPLAYER_COUNTER;
var MPLAYER = false;
var SOFTPIECETAKE = true; //piece manipulating on the board
var HTML1 = ""; //string for drawing the html board before gameboard
//var HTMLg = ""; //string for drawing the html gameboard
var HTML2 = ""; //string for drawing the html board after gameboard
var GAME = new Array(); //store game moves to be played
var MOVIEINDEX = -1; //keep index at which game move
var MOVIESPEED = 3000; //msec value, default interval between play
var TIMERSTORE; //array, used for storing forloop of setTimeout commands
var TIMERID; //TIMERID for movieplay
var ISAUTOPLAY = false; // play or stop movie toggle
var TERMINALCOMMAND = "skyblue"; //load/save terminal command, ability to store terminal commands
var IMAGENAMELENGTH = 2;
var SKYBLUE = "#87ceeb"; //body background color
var DARKBLUE = "#8299a5"; //body background color
var BROWN = "#d88b40"; //body background color
var BOARD; //string[][]

/*
//not used
var infoFields = new Array(); //building infofields for the gameboard, info in LN_form
*/

var WELCOMEMESSAGE = "BETA version " + VERSIONNUMBER + "\n\n" + 

"Hello chess player at some level :), you're reading this message from the textarea\n"+
"This diagram-maker is usually somewhat slow, (javascript and not optimised coding implementing) "+
"so please be patient.\n\n"+

"Type help or man in the terminal to read my short manual about this diagram maker "+
"if you want to know what you can do with this diagram-maker or of if you get stocked somewhere.\n"+
"(popup window)\n\n"+

"Positiondata can be saved\n"+
"Double click inside the terminal\n\n"+

"The positiondata you'll get will be printed in the terminal and here at the bottom, scroll down to see it.\n\n"+

"This is how input positiondata could be "+
"for the board-dimension 12x12 with black white setup.\n\n"+

	"/-2RNBKQBNR/P12/////////p12/-2rnbkqbnr/\n\n"+

	"/X\n"+
"This will fill the board with closedfield pieces.\n\n"+

"DYNAMIC LINK doesn't work with make.chess4player, only chess4player\n"+
"Dynamic link with position setup now supported for positiondata (pd) or the general epd string. "+
"ie. chess4player.htm?pd=/k  or  chess4player.htm?epd=rnbq/8/8/8/P\n\n"+

"Dynamic link with terminal commands now supported (term) "+
"ie. chess4player.htm?term=whiteff0000\n\n"+

"Other dynamic arguments are: x,y,size,nodead\n"+
"ie. chess4player.htm?nodead=1&x=8&y=8\n\n"+

"type db5 in the terminal if you're using 8x8 boarddimension and want 2player start setup\n\n"+

"You can get the html-code for current chessboardpicture. But you'll need the chess-images on your server."+
"Type htm, htm2, htm3 or htmbw in the terminal, you can download the images from geocities.com/kungfuchezz\n"+
"Type pic, pic2, pic3 or picbw to see how the html-code will look like\n\n"+

"Terminal support the use of pipe (using multiple commands written in one go)\n\n"+
"Try this in terminal, this will play a movie by loading from intern moviebase index 2:\n"+
"mdb2 | speed3 | play\n\n"+

"Intern stored database and moviebase only work best with board dimension 12x12\n\n"+

"If you want colorchange try these quick commands:\n\n"+
"white 807581|black 3F2055|bg D88B40\n\n"+
"If nothing changes, try clicking the Fi or Fo button at left panel\n\n"+

"Pressing tilde+x or escape+x will get you to terminal, while in terminal or textarea pressing escape will "+
"toggle between those two areas.\n\n"+

"If you type positiondata in the terminal you will get some details about the rules of how positiondata string is used (popup window)\n";


var HELP = 
"<p>"+
	"<h1>" + THISNAME + "</h1>"+
	"Making Gameboard Diagrams<br/><br/>"+

	"<b>QUICK GUIDE</b><br/>"+	
	"(This manual is based on the full ver, some options may be missing in LITE ver)<br/>"+
	"Use the mouse and click on the board to move or set a chesspiece. Click twice on the same piece on the <b>chessboard</b> "+
	"to remove it. "+
	"There's an <b>infotext box</b> at middle bottom which will tell you what you're doing. "+
	"The <b>terminal</b> at right bottom is for inserting commands. "+
	"Above it you'll see a <b>textarea</b> field, there you'll get information about current position, "+
	"how many pieces the're on the board. It is also here you will get the <b>positiondata</b>, "+
	"which is a small cryptic text thing.<br/><br/>"+
	
	"This information holds the current game position, you can copy/save that information, "+
	"and next time you visit this page "+
	"you can insert that positiondata in to the <b>terminal</b> which will retrive the position for you from last visit. "+
	"Below the textarea you'll see the <b>store buttons</b>, the store button "+
	"will append the current screen position to the playlist. "+
	"The store reset will store from beginning and erase the current playlist. For more flexsible way to store, "+
	"use the terminal store commands. You can only do playings with the playlist when you have stored some positions.<br/><br/>"+

	"To the left you'll see a <b>panel</b> with small chesspieces on, you can use this to insert the pieces you want "+
	"on the <b>chessboard</b>. The're also other commands, move your mouse over those buttons to see what the link tells.<br/><br/>"+

	"If you like to setup the board from scratch, the <b>hardplace (HP)</b> button is a good toggle to speed up "+
	"the piece inserting. You'll see the button at the panel or toggle by typing in terminal hp<br/>"+
	"This toggle can enable a 'paint piece' brush for fast inserting multiple pieces of same type"+
	"<br/><br/><br/>"+


	
	"<b>FOREGROUND AND BACKGROUND IMAGES</b><br/>"+
	"The images on the chessboard are based on two layers, foreground and background level. "+
	"The chesspieces are in foreground level, the delay pieces are in background level. "+
	"This is normally the case, however you have ability to put the foreground level images to background "+
	"by typing burn in the terminal. To remove background level pieces type in terminal cs. "+
	"The background images are also named solid pieces"+
	"<br/><br/><br/>"+

	

	"<b>DYNAMIC LINK</b><br/>"+
	"(This is not possible with make.chess4player version)<br/>"+
	"Dynamic link with position setup is supported for positiondata (pd) or the general epd/fen string<br/>"+
	"ie. chess4player.htm?pd=/k  or<br/>"+
	"chess4player.htm?epd=rnbq/8/8/8/P<br/><br/>"+

	"Dynamic link with terminal commands is supported (term)<br/>"+
	"ie. chess4player.htm?term=imagenew|white00ff00|black0000ff<br/><br/>"+

	"You combine dynamic arguments with &, ie.<br/>"+
	"chess4player.diagram.htm?term=ct&pd=/-4Q/<br/><br/>"+

	"Other possible arguments: nodead, x, y, size<br/>"+
	"ie. nodead=1, no outarea/deadfields<br/>"+
	"ie. x=8, x-board size is 8<br/>"+
	"ie. size=50, piece imagesize is 50<br/>"+
	"<br/><br/>"+


	"<b>GENERATING HTML-CODE OF CURRENT CHESSBOARD PICTURE</b><br/>"+
	"You have the ability to get the html-code for current position and implement this on your own htmlfiles<br/>"+
	"You'll need to download the chessimages, which is possible from geocities.com/kungfuchezz<br/>"+
	"type in terminal html to get the html-code. You can preview the picture by typing pic in terminal"+
	"<br/><br/><br/>"+



	"<b>TERMINAL COMMANDS</b><br>"+
	"There's alot of commands most of them used to manipulate current game position<br/>"+
	"(normally you dont have to use terminal, there's plenty of buttons and options in dropdown menu)<br/><br/>"+

	"begin, bg&lt;htmlcolor&gt;, black&lt;htmlcolor&gt;, brown, burn, clear, clear text, config, darkblue, db, dimen, "+
	"end, epd2pd<epd-data>, flip, flip boarder, flip image, frame, frames, frameinsert, frameremove, framereverse, "+
	"framereplace, framefirst, get, getdelay, getframe<index>, getsolid, geturl, help, htm, htm2, htm3, htmbw, iamwhite, iamblack, iamred, iamgreen, "+
	"image newstyle, image kfc, image normal, insert<player>, list, load, mdl, message, "+
	"mirror, movd<int>, moviedb, movieget, movieframe, movieplay, moviespeed, "+
	"movl<int>, movr<int>, movu<int>, mplayer on, mplayer off, mplayer reset, mplayer speed<int>, next, pdl, pic, pic2, pic3, picbw, pieces, put(x,y,c), "+
	"remove<player|custom|dead>, rotate<d|l|r|u>, random, "+
	"prev, placehard, placereverse, placesoft, setposition<positiondata>, "+
	"start, store, setmovie<moviedata>, save, skyblue, solid(x,y,c), white&lt;htmlcolor&gt;<br/><br/>"+

	"<b>Example on how to use the commands</b><br/><br/>" +

	"<b>beg</b>in, goto first frame in playlist<br/>"+
	"<b>bg</b>&lt;htmlcolor&gt;, set background color, ie. bg FF00FF<br/>"+
	"<b>black</b>&lt;htmlcolor&gt;, set the color of the black chessfield colors<br/>"+
	"<b>burn</b>burn the foreground images to background, can be removed again with command: cs<br/>"+
	"<b>db</b>8, get a fixed position 8 stored from intern database<br>"+
	"<b>config</b>, list pieces from board for custom kfcgame config editing<br/>"+
	"<b>dimen</b>sion, tell the boardx, boardy, outarea values<br>"+
	"<b>end</b>, goto last frame in playlist<br/>"+
	"<b>epd2pd</b> 3k4/7K, translate epd-data or FEN-data to positiondata, this would give /-3k-4/-7K/<br/>"+
	"<b>flip</b>, reverse the boardfield colors, black fields to white and vice versa<br>"+
	"<b>flipb</b>oarder, flip boarder on,off in gameboard<br>"+
	"<b>flipi</b>amage, flip boardfield background images in gameboard<br/>"+
	"<b>frame</b>, tell the current frame index<br>"+
	"<b>framef</b>irst, insert as the first frame with this screen position<br/>"+
	"<b>frameins</b>ert, insert this screen to current playlist<br>"+
	"<b>framerem</b>ove, remove current frame<br>"+
	"<b>framerep</b>lace, replace current frame with this screen position<br/>"+
	"<b>framerev</b>erse, reverse the playlist<br/>"+
	"<b>frames</b>, tell the current frames index<br/>"+
	"<b>get</b> will show the positiondata, the key infomartion to the current chess setup<br/>"+
	"<b>getdelay</b> will give the information list for delay pieces on chessboard<br/>"+
	"<b>getframe</b>4, if you have at minimum four frames, it will retrieve frame index 4<br/>"+
	"<b>getsolid</b> will give the information list for solid pieces on chessboard<br/>"+
	"<b>geturl</b> will give the url link with current position saved<br/>"+
	"<b>help</b>, will open new window and show you this you're reading<br/>"+
	"<b>htm</b>, will give you html-code for current board-picture<br/>"+
	"<b>htm2</b>, will give you html-code for current board-picture with chessborder coordinates white POV<br/>"+
	"<b>htm3</b>, will give you html-code for current board-picture with chessborder coordinates black POV<br/>"+
	"<b>htmbw</b>, will give you html-code for current board-picture for both white and black's POV<br/>"+
	"<b>iamw</b>hite, give you start position with the color you want<br>"+
	"<b>image</b> newstyle, change the chesspieces graphic, press start after this command<br>"+
	"<b>ins</b>ert white, insert white player start setup<br>"+
	"<b>l</b>i<b>s</b>t will give you chess picture in textform<br/>"+
	"<b>load, save</b>, will take the position and store/restore it, (dependent on cookies)<br/>"+
	"<b>mdl</b>, moviedata length, tell the length of the stringdata<br/>"+
	"<b>m</b>ovie<b>db</b>3 (moviedatabase), get the intern stored movie number 3<br>"+
	"<b>m</b>ovie<b>get</b>, list the values from stored values into infoTextArea so you can copy/save it<br>"+
	"<b>mir</b>ror x, mirror y, mirror z, this will mirror the board in either x, y or xy line<br/>"+
	"movie<b>frame</b>, info about the count of movieframes stored in gamemovie<br>"+
	"movie<b>play</b>, start the movie<br>"+
	"movie<b>speed</b>2, set the movie speed to 2 secs, use any positive value<br>"+
	"<b>movl</b>5, movr4, movu3, movd2, will move left 5, move right 4, move up 3, move down 2, the max value is 5<br/>"+
	"<b>mp</b>layer on, enable kfc_mplayer support<br/>"+
	"<b>mp</b>layer off, disable kfc_mplayer support<br/>"+
	"<b>mp</b>layer reset, reset kfc_mplayer timecounter<br/>"+
	"<b>mp</b>layer speed 2000, set kfc_mplayer speed<br/>"+
	"<b>next</b>, goto next frame in playlist<br/>"+
	"<b>pdl</b>, positiondata length, tell the length of the stringdata<br/>"+
	"<b>pic</b>ture, popup window with current picture to show how the html-code will look like<br/>"+
	"<b>pic2</b>ture, popup window with current picture to show how the html-code will look like for htm2<br/>"+
	"<b>pic3</b>ture, popup window with current picture to show how the html-code will look like for htm3<br/>"+
	"<b>piece</b> will list current pieces on the gameboard with coordinates<br/>"+
	"<b>placeh</b>ard, the piece panel putting is hard mode<br>"+
	"<b>placer</b>everse, reverse the piece panel putting mode<br>"+
	"<b>places</b>oft, the piece panel putting is soft mode (default)<br>"+
	"<b>prev</b>, goto previous frame in playlist<br/>"+
	"<b>put(x-coordinate,y-coordinate,pieceCode)</b> normal piece placement "+	
		"ie. set(0,0,c), will place green Bishop on coordinate (0,0)<br>"+
	"<b>ran</b>dom will use the current position and make it random<br/>"+
	"<b>rem</b>ove white black, this will remove two chessplayers<br/>"+
	"<b>rem</b>ove custom, this will remove noneplayer chesspieces<br/>"+
	"<b>rem</b>ove dead, this will remove chesspieces on outarea if any<br/>"+
	"<b>rot</b>ate left, rotate right, rotate up, rotate king, this will rotate the gameboard<br/>"+
	"<b>setmovi</b>e, setup a playlist with moviedata information taken from the infoTextArea<br/>"+
	"<b>setpos</b>ition, setup a position with positiondata information taken from the infoTextArea<br/>"+
	"<b>skybl</b>ue, this will set the background color to skyblue<br/>"+
	"<b>solid(x-coordinate,y-coordinate,pieceCode)</b> solid background piece placement "+
		"ie. solid(5,0,Q), will place white queen on coordinate (5,0) "+
	"<b>start</b>, the start position with white in front to you<br/>"+
	"<b>store</b>, save the current pos to a gameplay, which can be used with the panel buttons, begin, play, etc.<br>"+
	"<b>white</b>&lt;htmlcolor&gt;, set the color of the white chessfield colors, works with Mozilla browser<br/><br/>"+

	"<b>/N3/P5/</b> positiondata insert (foreground images), 3 white knights at bottom first row and 5 white pawns at second row<br/>"+
	"<b>%a34e56o12</b> insert background images, delay1 piece at location 34, delay2 at location 56 and delay3 at 12<br/>"+
	"<b>^K3p96</b> insert foreground images, white king at location 3, black pawn at 96<br/><br/>"+

	"If you want to change the board-dimension, you can download this chess4player.diagram<br/>"+
	"from geocities.com/kungfuchezz, and edit the javascript file.<br/>"+
	"Using this on your local machine will also speed up the diagram-making as the program runs faster<br/><br/>"+

	"var BOARDX = (set the boardsize horizontally)<br/>"+
	"var BOARDY = (set the boardsize vertically)<br/>"+
	"var IMG = (set the size of a chessfield for the gameboard)<br/>"+
"</p>";

var POSITIONDATA = 
		"<p>"+
			"<h1>Positiondata in details</h1>"+
			"The syntaxs is <b>/somePieceCodes/somePieceCodes/...</b><br/>"+
			"The string must start with a <b>/</b> and the pieceCodes must be valid. <br/>"+
			"The pieceCodes are:<br/><br/>"+ "    "+CHESSCODELIST + "-<br/><br/>"+
			"One <b>/</b> marks the start of a chessline horizontally from botton and goes upward. "+
			"In between the <b>/</b> marks you define what pieces the're on that chessline. The items goes from left to right. "+
			"The items you can have are the four color chesspieces and some extra other piece elements. "+
			"You can see those elements in the leftpanel.<br/><br/>"+
			
			"Those items are in positiondata value:<br/><br/>"+
			
			"/ = chessline, row delimiter<br/>"+
			"% = solid,background imagelist startdelimiter<br/>"+
			"^ = soft,foreground imagelist startdelimiter<br/><br/>"+

			"R = white rook<br/>"+			
			"N = white knight<br/>"+
			"B = white bishop<br/>"+
			"K = white king<br/>"+
			"Q = white queen<br/>"+
			"P = white pawn<br/>"+
			"G = white knightbishy<br/>"+
			"J = white knightrooky<br/>"+
			"<i>black has the same but the letters in small caps i.e. black rook = r</i><br/><br/>"+

			"T = red rook (tower)<br/>"+
			"H = red knight (horse)<br/>"+
			"C = red bishop (cardinal)<br/>"+
			"M = red king (majestic)<br/>"+
			"F = red queen (famme)<br/>"+
			"W = red pawn (worker)<br/>"+
			"U = red knightbishy<br/>"+
			"V = red knightrooky<br/>"+
			"<i>green has the same but the letters in small caps</i><br/><br/>"+
			
			"- = one empty field<br/>"+
			"3 = repeat prev pieceCode 3 times<br/>"+
			"12 = repeat prev pieceCode 12 times, etc.<br/>"+
			"X = closed field<br/>"+
			"d = mark field (dot)<br/>"+
			"a = delay1<br/>"+
			"e = delay2<br/>"+
			"o = delay3<br/>"+
			"y = light white fieldimage<br/>"+
			"Y = light black fieldimage<br/>"+
			"z = dark white fieldimage<br/>"+
			"Z = dark black fieldimage<br/><br/>"+

			"If you dont fill out with all the items allowed on a chessline, "+
			"the next spaces will be autofilled with empty fields if there's a next / delimiter. "+
			"i.e. the chessline <b>/K/</b> will be filled with one white king following with empty fields. "+
			"If you put more items to the chessline than possible, the rest will be truncated. "+
			"i.e. the chessline for row 12 long <b>/Q14/</b> will only allow 12 white queens inserted.<br/><br/>"+

			"this is a legal positiondata string to be used on board 12x12 size:<br/>"+
			"<b>/-2k2K2/////-5rRtT//////-2q2Q2/</b><br/>"+
			"This string has 4 kings on first chessline (bottom), 4 rooks in middle and 4 queens at top<br/><br/>"+
			
			"If you haven't filled the board and if there isn't a next / delimiter "+
			"the board will be filled with the last piece used. "+
			"i.e. <b>/N</b><br/>"+
			"This string will fill the board with white knights.<br/><br/>"+

			"At the end of positiondata you can add a solidpieces (background-level) list to be included, usually used for delaypieces. "+
			"The % is a startdelimiter for background imagelist. The list is a piececode and one integer number for the location. "+
			"i.e. <b>/B/%e20o30</b> One white bishop and a delay2 piece on location 20 and delay3 on location 30. <br/><br/>"+

			"There's an equilivant command to the <b>%</b> for soft piece inserting.<br/>"+
			"Like the % the <b>^</b> is a startdelimiter for foreground imagelist (like positiondata). "+
			"i.e. <b>^M21H31</b> a red king (Majesty) and a red knight (Horse) on location 21 and 31. "+
			"The <b>^</b> is not a part of the positiondata because they are both foreground imagelevels. <br/><br/>"+

			"<b>moviedata</b><br/>"+
			"moviedata is build with positiondata values<br>"+
			"# is used as a marker for a beginning of one movieframe<br>"+
			"#<i>positiondata</i>#<i>positiondata</i>#<i>positiondata</i><br/>"+
			"This is a moviedata with 3 frames<br/><br/>"+
			"A positiondata and moviedata is unique for each boarddimension (boardsize).<br/>"+
			"Therefore you could get dataerrors if you're using positiondata with another boarddimension<br/>"+
		"</p>";

var ABOUT = THISNAME + " JavaScript\n" +
		"Making custom diagram position to analyse\n\n"+

		"You can load/save positions, make playlist, make link of chessboard-picture"+
		"\nor even generate html-code for current chessboard-picture\n\n"+

		"Best used with latest ver of Internet Explorer or Mozilla\n\n"+
		
		"Beta " + VERSIONNUMBER + "\n" +
		"(02-JAN-2003)\n" +
		LASTEDITED + 
        	"(c) 2003 epikur\n" +
	    	"kunukn@gmail.com";


var LOADERROR_1 = "POSITIONDATA or MOVIEDATA LOADING ERROR!\n"+
					"Intern stored values are by default based on boardsize 12x12\n\n";
		// show loaded data here
var LOADERROR_2 = "\n\n"+
			"Data is missing or is not useable with this boardsize\n"+
			"Be careful about copy/past correct and about adding newlines\n"+
			"Using some writeprograms like notepad may corrupt your data with it's autowrap function\n"+
			"Notice the data above. Most likely the data is shortent due to copy/past and autowrap problem\n"+
			"Examen the data above to see why some data got lost\n"+
			"And avoid autowrapping if you must use the writeprogram you use to store the data\n\n"+

			"The terminal can't read newlines.\n\n"+
			
			"Or else you could try inserting the data in textarea, and type in terminal: setposition\n"+
			"for loading a position or type: setmovie\n"+
			"for loading a movie\n"+
			"This method allows using newlines";


//game positions stored in positiondata string for board-dimension 12x12
//used with db terminal command to retrieve positions
var POSITION = new Array();
POSITION[0]  = "/-2RNBQKBNR-2/-2P8-2/tw-8WT/hw-8WH/cw-8WC/fw-8WM/mw-8WF/cw-8WC/hw-8WH/tw-8WT/-2p8-2/-2rnbkqbnr-2/"; // Iam white
POSITION[1]  = "/-2rnbqkbnr-2/-2p8-2/TW-8wt/HW-8wh/CW-8wc/FW-8wm/MW-8wf/CW-8wc/HW-8wh/TW-8wt/-2P8-2/-2RNBKQBNR-2/"; // Iam black
POSITION[2]  = "/-2THCMFCHT-2/-2W8-2/RP-8pr/NP-8pn/BP-8pb/KP-8pq/QP-8pk/BP-8pb/NP-8pn/RP-8pr/-2w8-2/-2thcfmcht-2/"; // Iam red
POSITION[3]  = "/-2thcmfcht-2/-2w8-2/rp-8PR/np-8PN/bp-8PB/kp-8PQ/qp-8PK/bp-8PB/np-8PN/rp-8PR/-2W8-2/-2THCFMCHT-2/"; // Iam green
POSITION[4]  = "/RNBQKBNR-4/P8-4/-12/-12/-12/-12/p8-4/rnbqkbnr-4/-12/-12/-12/-12/"; // 8x8 board 2player
//dont edit above, iam red, iam black ... depending on them

POSITION[5]   = "/F-7X-3/-6F-X-3/-4F-3X-3/-7FX-3/-F-6X-3/-3F-4X-3/-5F-2X-3/-2F-5X-3/X9-3/-12/-12/-12/"; // 8 queens
POSITION[6]   = "/X";
POSITION[7]   = "/y";
POSITION[8]   = "/Y";
POSITION[9]   = "/z";
POSITION[10]  = "/Z";

//fx. type in console, db6 to get POSITION[5]


//movie database for board-dimension 12x12
var MOVIE = new Array();
MOVIE[0]  = "#/-12/-12/-2RNBQKBNR-2/-2P8-2/-12/-12/-12/-12/-2p8-2/-2rnbqkbnr-2/-12/-12/";
MOVIE[1]  = "#/-2RNBQKBNR-2/-2P8-2/tw-8WT/hw-8WH/cw-8WC/fw-8WM/mw-8WF/cw-8WC/hw-8WH/tw-8WT/-2p8-2/-2rnbkqbnr-2/#/-2R-BQKB-R-2/-2P3-2P3-2/tw-2NP2N-2WT/hw-8WH/cw-8WC/fw-8WM/mw-8WF/cw-8WC/hw-8WH/tw-8WT/-2p8-2/-2rnbkqbnr-2/#/-3RBQKBR-3/-2P3-2P3-2/tw-3P2-3WT/hw-3N2-3WH/cw-8WC/fw-8WM/mw-8WF/cw-8WC/hw-8WH/tw-8WT/-2p8-2/-2rnbkqbnr-2/#/-3R-QK-R-3/-2P-PB2P-P-2/tw-P-P2-P-WT/hw-3N2-3WH/cw-8WC/fw-8WM/mw-8WF/cw-8WC/hw-8WH/tw-8WT/-2p8-2/-2rnbkqbnr-2/#/-3R-QK-R-3/-2P-PB2P-P-2/tw-PdP2dP-WT/hwd3N2d3WH/cwd3-2d3WC/fw-2d4-2WM/mw-8WF/cw-8WC/hw-8WH/tw-8WT/-2p8-2/-2rnbkqbnr-2/";
MOVIE[2]  = "#/-2RNBQKBNR-2/-2P8-2/tw-8WT/hw-8WH/cw-8WC/fw-8WM/mw-8WF/cw-8WC/hw-8WH/tw-8WT/-2p8-2/-2rnbkqbnr-2/#/-2RNBQKBNR-2/-2P4-P3-2/tw-8WT/hw-4P-3WH/cw-8WC/fw-8WM/mw-8WF/cw-8WC/hw-8WH/tw-8WT/-2p8-2/-2rnbkqbnr-2/%o43#/-2RNBQKBNR-2/-2P4-P3-2/tw-8WT/hw-4P-3WH/cw-8WC/fw-8WM/mw-8WF/cw-8WC/hw-8WH/tw-8WT/-2p8-2/-2rnbkqbnr-2/%e43#/-2RNBQKBNR-2/-2P4-P3-2/tw-8WT/hw-4P-3WH/cw-8WC/fw-8WM/mw-8WF/cw-8WC/hw-3p-4WH/tw-8WT/-2p3-p4-2/-2rnbkqbnr-2/%a43o102#/-2RNBQKBNR-2/-2P4-P3-2/tw-8WT/hw-4P-3WH/cw-8WC/fw-8WM/mw-6W-2F/cw-8WC/hw-3p-4WH/tw-8WT/-2p3-p4-2/-2rnbkqbnr-2/%o81e102#/-2RNBQKBNR-2/-2P4-P3-2/tw-8WT/hw-4P-3WH/cw-8WC/fw-8WM/mw-6W-2F/cw-8WC/hw-3p-4WH/tw-8WT/-2p3-p4-2/-2rnbkqbnr-2/%e81a102#/-2RNBQKBNR-2/-2P4-P3-2/tw-8WT/hw-4P-3WH/c-2w-6WC/fw-8WM/mw-6W-2F/cw-8WC/hw-3p-4WH/tw-8WT/-2p3-p4-2/-2rnbkqbnr-2/%o52a81#/-2RNBQKBNR-2/-2P4-P3-2/tw-8WT/hw-4P-3WH/c-2w-6WC/fw-8WM/mw-6W-2F/cw-8WC/hw-3p-4WH/tw-8WT/-2p3-p4-2/-2rnbkqbnr-2/%e52#/-2RNBQKBNR-2/-2P4-P3-2/tw-8WT/hw-4P-3WH/c-2w-6WC/fw-8WM/mw-6W-2F/cw-8WC/hw-3p-4WH/tw-8WT/-2p3-p4-2/-2rnbkqbnr-2/%a52#/-2RNBQKBNR-2/-2P4-P3-2/tw-8WT/hw-4P-3WH/c-2w-6WC/fw-8WM/mw-6W-2F/cw-8WC/hw-3p-4WH/tw-8WT/-2p3-p4-2/-2rnbkqbnr-2/";
MOVIE[3]  = "#/-8/-8/P-7/-Pn-5/-pB-5/p-7/-8/-8/%#/-8/-8/n-7/P2-6/-pB-5/p-7/-8/-8/%o17e25#/-8/-8/n-7/pP-6/-2B-5/p-7/-8/-8/%e17o25#/-8/-8/n-7/p-7/-PB-5/p-7/-8/-8/%a17e25o34#/-8/-8/B-7/p-7/-P-6/p-7/-8/-8/%o17a25e34#/-8/-8/B-7/p-7/-p-6/-8/-8/-8/%e17o34#/-8/-8/-8/pB-6/-p-6/-8/-8/-8/%o26e34";

//fx. type in console, mdb2 to get MOVIE[1]


// ///////////////////////////////////////////////////////////
// LOAD IMAGES, SET COLORS and set variables related to loaded images

//images

//buttons
var rotl = new Image(IMGS,IMGS);
var rotr = new Image(IMGS,IMGS);
var rotu = new Image(IMGS,IMGS);
var rotk = new Image(IMGS,IMGS);
var movl = new Image(IMGS,IMGS);
var movr = new Image(IMGS,IMGS);
var movu = new Image(IMGS,IMGS);
var movd = new Image(IMGS,IMGS);
var mirx = new Image(IMGS,IMGS);
var miry = new Image(IMGS,IMGS);
var remw = new Image(IMGS,IMGS);
var remb = new Image(IMGS,IMGS);
var remr = new Image(IMGS,IMGS);
var remg = new Image(IMGS,IMGS);
var remc = new Image(IMGS,IMGS);
var remd = new Image(IMGS,IMGS);
rotl.src = PATH + "rotl.gif";
rotr.src = PATH + "rotr.gif";
rotu.src = PATH + "rotu.gif";
rotk.src = PATH + "rotk.gif";
movl.src = PATH + "movl.gif";
movr.src = PATH + "movr.gif";
movu.src = PATH + "movu.gif";
movd.src = PATH + "movd.gif";
mirx.src = PATH + "mirx.gif";
miry.src = PATH + "miry.gif";
remw.src = PATH + "remw.gif";
remb.src = PATH + "remb.gif";
remr.src = PATH + "remr.gif";
remg.src = PATH + "remg.gif";
remc.src = PATH + "remc.gif";
remd.src = PATH + "remd.gif";
rotl.name = "rotateLeft";
rotr.name = "rotateRight";
rotu.name = "rotateUp";
rotk.name = "rotateKing";
movl.name = "moveLeft";
movr.name = "moveRight";
movu.name = "moveUp";
movd.name = "moveDown";
mirx.name = "mirrorX";
miry.name = "mirrorY";
remw.name = "removeWhite";
remb.name = "removeBlack";
remr.name = "removeRed";
remg.name = "removeGreen";
remc.name = "removeCustom";
remd.name = "removeDelay";

//empty field (dummy image), closed field (reduce board view)
var eF    = new Image(IMG,IMG);
var cF    = new Image(IMG,IMG);
var mF    = new Image(IMG,IMG);
eF.src = PATH + "ef.gif";
cF.src = PATH + "cf.gif";
mF.src = PATH + "mf.gif";
eF.name = "ef";
cF.name = "cf";
mF.name = "mf";


//boardfield img background
var DEADFIELD_IMG		= cF.src; //corner of chessboard, you can edit the value
var PANEL_IMG		= PATH + "fieldPanel.gif"; //left panel,	you can edit the value
var NOPIECE = eF.src; //invisible image

var f1 = new Image(IMG,IMG);
var f2 = new Image(IMG,IMG);
var f3 = new Image(IMG,IMG);
var f4 = new Image(IMG,IMG);
//delay images
var d1    = new Image(IMG,IMG);
var d2    = new Image(IMG,IMG);
var d3    = new Image(IMG,IMG);

f1.src = PATH + "f1.gif"; //light white field
f2.src = PATH + "f2.gif"; //light black field
f3.src = PATH + "f3.gif"; //dark white field
f4.src = PATH + "f4.gif"; //dark black field
d1.src = PATH + "d1.gif";
d2.src = PATH + "d2.gif";
d3.src = PATH + "d3.gif";
f1.name = "f1";
f2.name = "f2";
f3.name = "f3";
f4.name = "f4";
d1.name = "d1";
d2.name = "d2";
d3.name = "d3";

var DELAYTYPES = new Array('d1', 'd2', 'd3');
var FIELDWHITE;
var FIELDBLACK;

if (window.parent.FIELDWHITE != undefined)
	FIELDWHITE = window.parent.FIELDWHITE;
else
	FIELDWHITE = f1.src; //board cell image,	you can edit the value

if (window.parent.FIELDBLACK != undefined)
	FIELDBLACK = window.parent.FIELDBLACK;
else
	FIELDBLACK = f2.src; //board cell image,	 you can edit the value




//white
var wR    = new Image(IMG,IMG);
var wN    = new Image(IMG,IMG);
var wB    = new Image(IMG,IMG);
var wK    = new Image(IMG,IMG);
var wQ    = new Image(IMG,IMG);
var wP    = new Image(IMG,IMG);
var wG    = new Image(IMG,IMG);
var wJ    = new Image(IMG,IMG);
wR.src = PATHCHESS + "wr.gif";
wN.src = PATHCHESS + "wn.gif";
wB.src = PATHCHESS + "wb.gif";
wK.src = PATHCHESS + "wk.gif";
wQ.src = PATHCHESS + "wq.gif";
wP.src = PATHCHESS + "wp.gif";
wG.src = PATHCHESS + "wg.gif";
wJ.src = PATHCHESS + "wj.gif";
wR.name = "wr";
wN.name = "wn";
wB.name = "wb";
wK.name = "wk";
wQ.name = "wq";
wP.name = "wp";
wG.name = "wg";
wJ.name = "wj";

//black
var bR    = new Image(IMG,IMG);
var bN    = new Image(IMG,IMG);
var bB    = new Image(IMG,IMG);
var bK    = new Image(IMG,IMG);
var bQ    = new Image(IMG,IMG);
var bP    = new Image(IMG,IMG);
var bG    = new Image(IMG,IMG);
var bJ    = new Image(IMG,IMG);
bR.src = PATHCHESS + "br.gif";
bN.src = PATHCHESS + "bn.gif";
bB.src = PATHCHESS + "bb.gif";
bK.src = PATHCHESS + "bk.gif";
bQ.src = PATHCHESS + "bq.gif";
bP.src = PATHCHESS + "bp.gif";
bG.src = PATHCHESS + "bg.gif";
bJ.src = PATHCHESS + "bj.gif";
bR.name = "br";
bN.name = "bn";
bB.name = "bb";
bK.name = "bk";
bQ.name = "bq";
bP.name = "bp";
bG.name = "bg";
bJ.name = "bj";

//red
var rR    = new Image(IMG,IMG);
var rN    = new Image(IMG,IMG);
var rB    = new Image(IMG,IMG);
var rK    = new Image(IMG,IMG);
var rQ    = new Image(IMG,IMG);
var rP    = new Image(IMG,IMG);
var rG    = new Image(IMG,IMG);
var rJ    = new Image(IMG,IMG);
rR.src = PATHCHESS + "rr.gif";
rN.src = PATHCHESS + "rn.gif";
rB.src = PATHCHESS + "rb.gif";
rK.src = PATHCHESS + "rk.gif";
rQ.src = PATHCHESS + "rq.gif";
rP.src = PATHCHESS + "rp.gif";
rG.src = PATHCHESS + "rg.gif";
rJ.src = PATHCHESS + "rj.gif";
rR.name = "rr";
rN.name = "rn";
rB.name = "rb";
rK.name = "rk";
rQ.name = "rq";
rP.name = "rp";
rG.name = "rg";
rJ.name = "rj";
//green

var gR    = new Image(IMG,IMG);
var gN    = new Image(IMG,IMG);
var gB    = new Image(IMG,IMG);
var gK    = new Image(IMG,IMG);
var gQ    = new Image(IMG,IMG);
var gP    = new Image(IMG,IMG);
var gG    = new Image(IMG,IMG);
var gJ    = new Image(IMG,IMG);
gR.src = PATHCHESS + "gr.gif";
gN.src = PATHCHESS + "gn.gif";
gB.src = PATHCHESS + "gb.gif";
gK.src = PATHCHESS + "gk.gif";
gQ.src = PATHCHESS + "gq.gif";
gP.src = PATHCHESS + "gp.gif";
gG.src = PATHCHESS + "gg.gif";
gJ.src = PATHCHESS + "gj.gif";
gR.name = "gr";
gN.name = "gn";
gB.name = "gb";
gK.name = "gk";
gQ.name = "gq";
gP.name = "gp";
gG.name = "gg";
gJ.name = "gj";


// PIECEIMAGES, PIECESOURCES, PIECETYPES, PIECECODES and PIECENAMES have identical size and piecetypes in same order
// f1,f2,f3,f4,mF,cF,eF must be the last 7 values
var PIECEIMAGES = new Array(wR,wN,wB,wK,wQ,wP,wG,wJ,  bR,bN,bB,bK,bQ,bP,bG,bJ,  rR,rN,rB,rK,rQ,rP,rG,rJ, 
	gR,gN,gB,gK,gQ,gP,gG,gJ, d1,d2,d3,    f1,f2,f3,f4, mF, cF, eF);

var PIECESOURCES; //values are in updatePieceSources()

var PIECETYPES = new Array(	'wr','wn','wb','wk','wq','wp','wg','wj',
							'br','bn','bb','bk','bq','bp','bg','bj',
							'rr','rn','rb','rk','rq','rp','rg','rj',
							'gr','gn','gb','gk','gq','gp','gg','gj',
							'd1','d2','d3',
							'f1','f2','f3','f4', 'mf', 'cf', 'ef');

var PIECECODES = new Array('R','N','B','K','Q','P','G','U',  'r','n','b','k','q','p','g','u', 
	'T','H','C','M','F','W','J','V', 't','h','c','m','f','w','j','v', 'a','e','o', 'y','Y','z','Z','d','X','-');

var PIECENAMES = new Array("whiterook", "whiteknight", "whitebishop", 
	"whiteking", "whitequeen", "whitepawn", "whiteknightbishy", "whiteknightrooky", "blackrook", "blackknight", 
	"blackbishop", "blackking", "blackqueen", "blackpawn", "blackknightbishy", "blackknightrooky", "redrook", 
	"redknight", "redbishop", "redking", "redqueen", "redpawn", "redknightbishy", "redknightrooky", "greenrook", 
	"greenknight", "greenbishop", "greenking", "greenqueen", "greenpawn", "greenknightbishy", 
	"greenknightrooky", "delay1","delay2","delay3",".whitefieldtype2", ".blackfieldtype2", ".whitefieldtype1", ".blackfieldtype1",
	".markfield",".closedfield", "nopiece");

var HORIZONTALCHARS = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
							's','t','u','v','w','x','y','z','aa','bb','cc','dd','ee','ff','gg','hh','ii','jj',
							'kk','ll','mm','nn','oo','pp','qq','rr','ss','tt','uu','vv','ww','xx',
							'yy','zz','','','','','','','','','','','','','','','','','','',
							'','','','','','','','','','','','','','','','','','','','',
							'','','','','','','','','',''); //100 char array

//used for kfc config aidlisting
var PLAYERS = new Array("White","Black","Crimson","Jade");
var PIECESTYLES = new Array("rook","knight","bishop","king","queen","pawn","knightbishy","knightrooky");

//pickBoard, pickPanel
var PIECEINHAND = NOPIECE; //ref to imagetype for placing/moving chess pieces
var LASTCLICKCOORDINATE = null;
var FOREGROUNDIMAGESRC = NOPIECE; //foreground field image information save
var BACKGROUNDIMAGESRC = NOPIECE; //background field image information save


//board colors
var PANEL  = "#c9c7b9"; //you can edit the value, if the images below is loaded these wont be visible
//var PANEL  = "#fa9b3c"; //you can edit the value, if the images below is loaded these wont be visible
var WHITE;
var BLACK;

//if make.chess4player.diagram is used
if (window.parent.WHITE != undefined)
	WHITE = window.parent.WHITE;
else
	WHITE  = "#003399"; //you can edit the value

//if make.chess4player.diagram is used
if (window.parent.BLACK != undefined)
	BLACK = window.parent.BLACK;
else
	BLACK  = "#003366"; //you can edit the value



// END global var




// ///////////////////////////////////////////////////////////
// information to user

function about(){
	alert(ABOUT);
}


function help(){

	setMessage("help (popup window)");

	var newWindow = window.open("","help","resizable,scrollbars");
	newWindow.document.open();
	//newWindow.document.bgColor="#ffffff";

	newWindow.document.write(HELP);

	//newWindow.document.close();
	newWindow.focus();
}


function positiondata(){

	setMessage("about positiondata (popup window)");

	var newWindow = window.open("","positiondata","resizable,scrollbars");
	newWindow.document.open();
	//newWindow.document.bgColor=#ffffff;

	newWindow.document.write(POSITIONDATA);

	//newWindow.document.close();
	newWindow.focus();

}

function drawGameBoardPicture(mode){
	
	var html = "";

	if (mode==4){
		html = htmlBothSidesMake();	
	}
	else
		html = htmlMake(mode);	

	var gameboardPicture = window.open("","gameboardPicture","resizable,scrollbars");
	gameboardPicture.document.open();
	gameboardPicture.document.bgColor="#ffffff";
	gameboardPicture.document.write( html );	
	gameboardPicture.document.close();
	gameboardPicture.focus();
}


function infoArea(){

	var newWindow = window.open("","infoArea","resizable,scrollbars");
	newWindow.document.open();
	newWindow.document.bgColor="#ffffff";

	newWindow.document.write(getTextArea());

	//newWindow.document.close();
	newWindow.focus();
}

// ///////////////////////////////////////////////////////////
//used by initBoard()
function board(x,y){

	BOARD = new Array(y); //information for pieces on gameboard
	for (var i=0; i<BOARD.length; i++)
		BOARD[i] = new Array(x);
}


// ///////////////////////////////////////////////////////////
// reset the variables to default
// when specific board position command is used

function resetValues(){
	pieceInhandReset();
	LASTCLICKCOORDINATE = null;
	softPieceSet(true);
}




// ///////////////////////////////////////////////////////////
function updatePieceSources(){
	PIECESOURCES = new Array(	wR.src, wN.src, wB.src, wK.src, wQ.src, wP.src, wG.src,wJ.src,
								bR.src, bN.src, bB.src, bK.src, bQ.src, bP.src, bG.src,bJ.src,
								rR.src, rN.src, rB.src, rK.src, rQ.src, rP.src, rG.src,rJ.src,
								gR.src, gN.src, gB.src, gK.src, gQ.src, gP.src, gG.src,gJ.src,
								d1.src, d2.src, d3.src, 
								f1.src, f2.src, f3.src, f4.src, mF.src, cF.src, eF.src);
}


// ///////////////////////////////////////////////////////////
// load new images, where images are in subfolder relative from original images
// string -> 

function chessImages(imageSet){
	
	var temp = "";
	temp = PATHCHESS.substr( 0, PATHCHESS.lastIndexOf("/"));
	temp = temp.substr( 0, temp.lastIndexOf("/") + 1);
	PATHCHESS = temp + imageSet + "/";


	wR.src = PATHCHESS + "wr.gif";
	wN.src = PATHCHESS + "wn.gif";
	wB.src = PATHCHESS + "wb.gif";
	wK.src = PATHCHESS + "wk.gif";
	wQ.src = PATHCHESS + "wq.gif";
	wP.src = PATHCHESS + "wp.gif";
	wG.src = PATHCHESS + "wg.gif";
	wJ.src = PATHCHESS + "wj.gif";
	bR.src = PATHCHESS + "br.gif";
	bN.src = PATHCHESS + "bn.gif";
	bB.src = PATHCHESS + "bb.gif";
	bK.src = PATHCHESS + "bk.gif";
	bQ.src = PATHCHESS + "bq.gif";
	bP.src = PATHCHESS + "bp.gif";
	bG.src = PATHCHESS + "bg.gif";
	bJ.src = PATHCHESS + "bj.gif";
	rR.src = PATHCHESS + "rr.gif";
	rN.src = PATHCHESS + "rn.gif";
	rB.src = PATHCHESS + "rb.gif";
	rK.src = PATHCHESS + "rk.gif";
	rQ.src = PATHCHESS + "rq.gif";
	rP.src = PATHCHESS + "rp.gif";
	rG.src = PATHCHESS + "rg.gif";
	rJ.src = PATHCHESS + "rj.gif";
	gR.src = PATHCHESS + "gr.gif";
	gN.src = PATHCHESS + "gn.gif";
	gB.src = PATHCHESS + "gb.gif";
	gK.src = PATHCHESS + "gk.gif";
	gQ.src = PATHCHESS + "gq.gif";
	gP.src = PATHCHESS + "gp.gif";
	gG.src = PATHCHESS + "gg.gif";
	gJ.src = PATHCHESS + "gj.gif";

	setMessage("Images " + imageSet + ", click start");

	
	//dont change the order of the exec of these 2 functions below
	updatePieceSources();
	updateLeftPanelImages(); 
	
	return;
}



function updateLeftPanelImages(){

	var elem;
	var s;
	

	for (var i=0; i<PIECETYPES.length ;i++){
		elem = d.getElementById(PIECETYPES[i]);

		if (elem != undefined && elem != null){	
				s = type2source(PIECETYPES[i]);

				//elem.getAttribute("background") == "" )			
				elem.setAttribute("src",s);			
		}
	}
			
	//setMessage("updateLeftPanelImages");
}



// ///////////////////////////////////////////////////////////
// load from POSITION setup
// int ->
// db terminal command

function gamebase(index){

	if (index <= POSITION.length && index > 0){
			loadPosition( POSITION[index-1] );
			setMessage("database "+index+"/"+POSITION.length);
	}
	else
		setMessage("database value invalid = " + index+"/"+POSITION.length);

	return;
}



// ///////////////////////////////////////////////////////////
// load from MOVIE setup
// int ->
// moviedb terminal command

function moviebase(index){

	if (index <= MOVIE.length && index > 0){

		//load from MOVIE
		loadMoviePosition( MOVIE[index-1], index );

		setMovieIndex(0);
	}
	else{
		setMessage("moviedatabase value invalid = " + index);
	}
	return;
}


// ///////////////////////////////////////////////////////////
// Functions to store gameplay
// string with positiondata ->

function store(){

	var thePos = getBoth();

	setMessage("storing ...");
	
	GAME[ GAME.length ] = thePos;

	setMessage("store, " + GAME.length);

	setMovieIndex(GAME.length - 1);

	return;
}


function store_reset(){

	var thePos = getBoth();
	setMessage("new storing ...");
	GAME.length = 0;
	GAME[ GAME.length ] = thePos;

	setMessage("new store, " + GAME.length);
	setMovieIndex(0);
	return;
}

function store_replace(){
	var thePos = getBoth();

	setMessage("store replacing ...");

	if (GAME.length == 0){
		GAME[0] = thePos;
		setMovieIndex(0);
	}
	else if (MOVIEINDEX < GAME.length && MOVIEINDEX >= 0){
		GAME[ MOVIEINDEX ] = thePos;		
		setMessage("store replace:  current frame = " + (MOVIEINDEX + 1) + "/" + GAME.length);
	}
	else {
		var str = "GAME array and MOVIEINDEX mismatch in store_replace()"; 
		//alert(str);
		window.defaultStatus=str;
	}

	return;
}

function store_insert(){

	setMessage("store inserting ...");
	var thePos = getBoth();
	
	if (GAME.length == 0){
		GAME[0] = thePos;
		setMovieIndex(0);
	}
	else if (MOVIEINDEX < GAME.length){
		var frameInserted = MOVIEINDEX + 1;
		GAME = arrayInsert(GAME, MOVIEINDEX, thePos);
		setMovieIndex(MOVIEINDEX+1); //due to ins function
		setMessage("store insert:  current frame = " + (frameInserted + 1) + "/" + GAME.length);
	}
	else {
		var str="GAME array and MOVIEINDEX mismatch in store_insert()";
		//alert(str);
		window.defaultStatus=str;
	}

	return;
}


function store_insertfirst(){

	setMessage("first storing ...");
	var thePos = getBoth();

	GAME.reverse();
	GAME[ GAME.length ] = thePos;
	GAME.reverse();

	setMovieIndex(0);

	setMessage("store insertfirst:  current frame = 1" + "/" + GAME.length);

	return;
}

function store_remove(){

	setMessage("store removing ...");
	
	if (GAME.length == 0){
		setMessage("none stored value");
	}
	else if (MOVIEINDEX < GAME.length && MOVIEINDEX >= 0){
		var frameRemoved = MOVIEINDEX + 1;
		GAME = arrayRemove(GAME, MOVIEINDEX);
		if (MOVIEINDEX != 0)
			setMovieIndex(MOVIEINDEX-1); //due to rem function
		if (GAME.length > 0 && MOVIEINDEX >= 0 && MOVIEINDEX < GAME.length)
			//update screen to prev frame due to remove
			loadPosition( GAME[MOVIEINDEX] );
		setMessage("store removed:  current frame = " + frameRemoved + "/"+ GAME.length);
	}
	else {
		var str="GAME array and MOVIEINDEX mismatch in store_remove()";
		//alert(str);
		window.defaultStatus=str;
	}

	return;
}


function store_get ( num ){

		setMessage("store getting ...");
			

		if (GAME.length == 0){
			setMessage("none stored value");
			setMovieIndex(0);
		}
		else if (num > GAME.length - 1  ||  num < 0 ){
			setMessage("no such stored value " + (num + 1) );
		}
		else {
			loadPosition( GAME[num] );
			setMessage("get stored, " + (num + 1) + "/"+ GAME.length);
			setMovieIndex(num);
		}

	return;
}


function store_reverse(){

	setMessage("store reversing ...");
	
	GAME.reverse();
	setMessage("store reversed:  frames = " + GAME.length);
}


function setMovieIndex( i ){
	MOVIEINDEX = i;
	d.rightForm.movieIndex.value=MOVIEINDEX+1+"/"+GAME.length;
}


// ///////////////////////////////////////////////////////////
//play the stored games with inteval of some secs between positions

function movieplayDo(i){
	while(i-- >= 0){
	

	}
}


function movieplay(){

	TIMERSTORE = new Array();
	var i = 0;
	var MSEC = MOVIESPEED;

	if (GAME.length == 0){
			donePlayMovie(); //reset the vars
			setMessage("none stored value");
			setMovieIndex(0);
		}
	else {
			for (i=0; i<GAME.length; i++){
				TIMERID = setTimeout("positiondata2screen( GAME["+i+"] )", i * MSEC + 1);
				TIMERSTORE.push(TIMERID);
				//appendTextArea("\nplay= "+TIMERID); //debug

				TIMERID = setTimeout("setMessage('movieplay frame " 
					+ (i+1) + "/" + GAME.length + "  speed = "+(MOVIESPEED/1000)+" sec"+"')", i * MSEC + 10);
				TIMERSTORE.push(TIMERID);
				//appendTextArea("\nmes = "+TIMERID); //debug
			}	

		setMovieIndex(GAME.length - 1);

		TIMERID = setTimeout("donePlayMovie()",(GAME.length-1) * MSEC + 2000);
		TIMERSTORE.push(TIMERID);

		//appendTextArea("\nmes = "+TIMERID); //debug
	
		//appendTextArea("\nTimerStore.len= "+TIMERSTORE.length); //debug	
	}

	return;
}
function donePlayMovie(){ //when play is finished, reset
	setMessage("movieplay done");
	d.rightForm.play.value="play";
	ISAUTOPLAY=false;
}



function movieSetSpeed(speed){
	if (speed > 0){
		MOVIESPEED = speed * 1000;
		setMessage("moviespeed = " + speed + " secs");
	}
	else {
		setMessage("movieSetSpeed value not valid = " + speed);
	}

	return;
}


function moviestop(){

	var len = TIMERSTORE.length;
	//appendTextArea("\nTimerStore.len= "+len); //debug	
	for (var i=0; i<len; i++){
		var temp = TIMERSTORE.shift(); //shift is get and remove first item
		clearTimeout( temp );
		//appendTextArea("\nstop= "+temp); //debug
	}
	//clearTimeout(TIMERID); //not used, doesnt work as intended, due to multiple TIMERID assignment in movieplay()

	setMessage("Movie stop");
}

//
function switchAutoPlay(){
	ISAUTOPLAY = (ISAUTOPLAY) ? false : true; //invert val

	if (ISAUTOPLAY){
		d.rightForm.play.value="stop";
		movieplay(); //this also reset play-button-string-value to play
		//appendTextArea("\nplay"); //debug
	}
	else {
		d.rightForm.play.value="play";
		moviestop();
		//appendTextArea("\nstop"); //debug
	}
}



// ///////////////////////////////////////////////////////////
// convert (x,y) coordinate to LN_num form, x=1..12, y=1..12, LN_num=1..144
// int,int -> string

function xy2line( row, col ){
	return ("LN_" + (row+(col-1)*BOARDX) );
}

//alias function
function xy(x,y){
	return xy2line(x,y); 

}




// ///////////////////////////////////////////////////////////
// convert LN_num form to (x,y) coordinate 
// string -> int[]
//x = (num - 1) mod BOARDX + 1;
//y = (num - 1) div BOARDX + 1;

function line2xy( line ){
	
	if (line == null){
		var str = "ERROR! line2xy() line value is null";
		alert(str);  //window.defaultStatus=str; //debug
	}

	else{

		var num = parseInt( line.substr( line.lastIndexOf("_") + 1 ) );
	 	
		var div = Math.floor( (num - 1) / BOARDX ) + 1;
		var mod = num - (div - 1) * BOARDX;
	
		var x = mod;
		var y = div;

		return (new Array(x,y) );
	}
}


// ///////////////////////////////////////////////////////////
function positiondataLength(){
	//setMessage(getTextArea().length);
	setMessage("positiondata length = "+getBoth().length);
}
function moviedataLength(){
	//setMessage(getTextArea().length);
	setMessage("moviedata length = "+getMoviePosition().length);
}

// ///////////////////////////////////////////////////////////
// clear the txt in large info txt area


function clearInfoTextArea(){
	setTextArea("");
	setMessage("Info textarea cleared");
	SCROLL = 0;
	
	return;
}


// ///////////////////////////////////////////////////////////
// reset image values to nothing to the board array
// boardgame --> boardgame

function emptyBoard(){
	for (var j=0; j<BOARDY; j++){
		for (var i=0; i<BOARDX; i++){
			BOARD[j][i] = NOPIECE;
		}
	}

	return;
}

function clearScreen(){
	for (var j=0; j<BOARDY; j++){
		for (var i=0; i<BOARDX; i++){
			getForeground( xy2line(i+1,j+1) ).src = NOPIECE;
		}
	}

	return;
}


// ///////////////////////////////////////////////////////////
// remove pieces from screen
// boardgame --> boardgame

function positionClear(){
	setMessage("Clearing board ..");
		clearScreen();
		removeDelay();
		//resetValues();

	setMessage("The board cleared");

	return;
}


// ///////////////////////////////////////////////////////////

// string which is 2char long -> full name
function type2name(name){
	return PIECENAMES[ arrayIndex(PIECETYPES,name) ];
}

// string which is 2char long -> src path (string)
function type2source(name){
	return PIECESOURCES[ arrayIndex(PIECETYPES,name) ];
}

// string which is 2char long -> pieceCode (string)
function type2code(name){
	return PIECECODES[ arrayIndex(PIECETYPES,name) ];
}

// string which is 1char long -> pieceSource (string)
function code2sources(c){
	var i = arrayIndex(PIECECODES, c);
	if (i<0){
		var str = "!ERROR code2source() not found "+i+"\n"+src;
		//alert(str);
		window.defaultStatus=str;
	}
	return PIECESOURCES[i];
}

//
function source2name( src ){
	var i = arrayIndex(PIECESOURCES, src);
	if (i<0){
		var str = "!ERROR source2name() not found "+i+"\n"+src;
		//alert(str);
		window.defaultStatus=str;
	}
	return PIECENAMES[i];
}
//
function source2type( src ){
	var i = arrayIndex(PIECESOURCES, src);
	if (i<0){
		var str = "!ERROR source2type() not found "+i+"\n"+src;
		//alert(str);
		window.defaultStatus=str;
	}
	return PIECETYPES[i];
}
//
function source2code( src ){
	var i = arrayIndex(PIECESOURCES, src);
	if (i<0){
		var str = "!ERROR source2code() not found "+i+"\n"+src;
		//alert(str);
		window.defaultStatus=str;
	}
	return PIECECODES[i];
}
//
function source2image( src ){
	var i = arrayIndex(PIECESOURCES, src);
	if (i<0){
		var str="!ERROR source2image() not found "+i+"\n"+src
		//alert(str);
		window.defaultStatus=str;
	}
	return PIECEIMAGES[i];
}

// ///////////////////////////////////////////////////////////
// similar to source2type(), diff algorithm

function pathName2pieceType( pathName ){

	//debug
	if (pathName == undefined || pathName == null){
		var str="!ERROR pathName2pieceType()\npathName="+pathName;
		//alert(str);
		window.defaultStatus=str;
		return;
	}

	var res = "ef";

	if (pathName.search(".") != -1){
		res = pathName.substr( pathName.lastIndexOf(".") - IMAGENAMELENGTH, IMAGENAMELENGTH).toLowerCase();
	}
	else {
		var str="ERROR! pathName2pieceType() not a pathName used";
		alert(str);
		window.defaultStatus=str;
	}

	return res;
}


// ///////////////////////////////////////////////////////////
// select a piece from panel to be dropped on board
// string ->   (PIECEINHAND = image object)

function pickPanel( thePiece ){
	
	var p = thePiece;

	if (p == 'prev' || p == 'next' || p == 'begin' || p == 'end' || p == 'moveLeft' || 
		p == 'moveRight' || p == 'moveUp' || p == 'moveDown' || p == 'rotateLeft' || p == 'rotateRight' || 
		p == 'rotateUp' || p == 'rotateKing' || p == 'mirrorX' || p == 'mirrorY' || 
		p == 'removeWhite' || p == 'removeBlack' || p == 'removeRed' || p == 'removeGreen' ||
		p == 'removeCustom' || p == 'removeDelay' || p == 'removeDead' || p == 'clearSolid' || p == 'flipimage' || p == 'fliporder' || 
		p == 'hardplace' || p == 'flipboarder' ||
		p == 'bgSkyblue' || p == 'bgBrown' || p == 'bgDarkblue' || p == 'null' || p ==' ' || 
		p=='txtpic' || p=='kfcconfig') {

			if (p == 'moveLeft')
				moveRight(-1);
			else if (p == 'moveRight')
				moveRight(1);
			else if (p == 'moveUp')
				moveUp(1);
			else if (p == 'moveDown')
				moveUp(-1);
	
			else if (p == 'rotateLeft')
				rotate(1);
			else if (p == 'rotateRight')
				rotate(2);
			else if (p == 'rotateUp')
				rotate(5);
			else if (p == 'rotateKing')
				rotate(6);
	
			else if (p == 'mirrorX')
				rotate(3);
			else if (p == 'mirrorY')
				rotate(4);
	
			else if (p == 'removeWhite')
				removeSet("white");
			else if (p == 'removeBlack')
				removeSet("black");
				else if (p == 'removeRed')
				removeSet("red");
			else if (p == 'removeGreen')
				removeSet("green");
			else if (p == 'removeCustom')
				removeSet("custom");
			else if (p == 'removeDelay')
				removeDelay();
			else if (p == 'removeDead'){
				removeDead();
			}
			else if (p == 'clearSolid')
				clearBackground();

			else if (p == 'begin')
				store_get( 0 );
			else if (p == 'end')
				store_get( GAME.length - 1 );
			else if (p == 'next')
				store_get( MOVIEINDEX + 1);
			else if (p == 'prev')
				store_get( MOVIEINDEX - 1);
	
	
			else if (p == 'txtpic')
				txtpicture();
			else if (p == 'kfcconfig')
				configKFC();
			else if (p == 'flipimage')
				boardFieldImage();
			else if (p == 'fliporder')
				boardOrderFlip();
			else if (p == 'hardplace')
				softPiecePlacement(2);
			else if (p == 'flipboarder')
				boardBorderFlip();
	
	
			else if (p == 'bgSkyblue')
				setBGColor(SKYBLUE);
			else if (p == 'bgBrown')
				setBGColor(BROWN);
			else if (p == 'bgDarkblue')
				setBGColor(DARKBLUE);
			
			
			else if (p == 'null')
				setMessage("button not used yet");
	
			else{
				//appendTextArea(++SCROLL + ": not implemented\n");
				setMessage("button no function");
			}
	
	
			//resetValues();
		}

	else {

			PIECEINHAND = type2source(thePiece);
			var info = "New piece: " + type2name(thePiece);
			
			LASTCLICKCOORDINATE = null; //reset due to new piece use
	
			setMessage(info);
			//appendTextArea(++SCROLL + ": " + info + "\n"); //tell new piece type
	}


	return;
}


// ///////////////////////////////////////////////////////////
// set softpiece take/put
// boolean -> boolean

function softPieceSet( b ){
	SOFTPIECETAKE = b;

	var t = d.getElementById("button_softpiece");

	if ( SOFTPIECETAKE )
		t.setAttribute("bgColor",PANEL);		
	else
		t.setAttribute("bgColor","#5efb6e");
}


function softPiecePlacement(index){

	if (index==0){
		softPieceSet(false);
			setMessage("set hardplacement");
	}
	
	else if (index==1){
		resetValues(); //this includes, softPieceSet(true)
			setMessage("set softplacement");
	}
	
	else if (index==2){
		if (SOFTPIECETAKE){
			softPieceSet(false);
		}
		else {
			resetValues(); //this includes, softPieceSet(true)
		}

		setMessage("hardplacement = " + !SOFTPIECETAKE);
	}
	
	else{
		var str="ERROR! softPiecePlacement(), value not supported " + index
		//alert(str);
		window.defaultStatus=str;
	}
	
	return SOFTPIECETAKE;
}


// ///////////////////////////////////////////////////////////
// return the epd value of delays
function getDelaysFromBackground(){
	var type, src, index;
	var delays = "";

	for (var n=1; n<=BOARDX*BOARDY; n++){
		src = d.getElementById("LN_"+n).getAttribute("background");
		type = pathName2pieceType(src);
		index = arrayIndex(DELAYTYPES, type);

		if ( index != -1)
			delays += type2code(DELAYTYPES[index]) + n;
	}
	if (delays.length>0)
		delays = "%"+delays;

	return delays;
}
//
// return list in numbers, used for rotating/moving board
function getDelaysFromBackgroundData(){
	var type, src, index;
	var delays = "";

	for (var n=1; n<=BOARDX*BOARDY; n++){
		src = d.getElementById("LN_"+n).getAttribute("background");
		type = pathName2pieceType(src);
		index = arrayIndex(DELAYTYPES, type);

		if ( index != -1)
			delays += n + ",";
	}
	return delays;
}

//
function getAllBackgroundFromScreen(){
	var type, src, index;
	var list = "";

	for (var n=1; n<=BOARDX*BOARDY; n++){
		src = d.getElementById("LN_"+n).getAttribute("background");
		type = pathName2pieceType(src);

		if ( type != 'ef') //NOPIECE
			list += type2code(type) + n;
	}
	return "%"+list;
}


function setAllForegroundToBackground(){
	var ref;
	var id;
	for (var j=0;j<BOARDY;j++){
		for (var i=0;i<BOARDX;i++){
			id = xy2line(i+1,j+1);
			ref = getForeground( id );			
			if ( arrayIndex(DEADFIELDS,id) == -1 )//dont burn over OUTAREA fields
				setBackgroundLN( id, ref );
		}
	}	
	positionClear(); //clear foreground as it it's burned to background

	setMessage("burn foreground to background, remove again by typing: cs");
}

function getForeground( lineIndex ){
	var ref = d.images[ lineIndex ];
	if (ref!=undefined && ref!=null)
		return ref;
	else{
		var str="!ERROR getForeground() lineIndex="+lineIndex;
		//alert(str);
		window.defaultStatus=str;
		return eF; //NOPIECE IMAGE
	}
}
// i=0..BOARDX-1, j=0..BOARDY-1
function setForeground( i, j, src ){
	var ref = d.images[ xy2line(i+1,j+1) ];

	if (ref!=undefined && ref!=null)
		d.images[ xy2line(i+1,j+1) ].src = src;
	else{
		var str="!ERROR setForeground() lineIndex="+xy2line(i+1,j+1);
		//alert(str);
		window.defaultStatus=str;
	}
}

function setForegroundLN( LN, src ){
	var ref = d.images[ LN ];

	if (ref!=undefined && ref!=null)
		d.images[ LN ].src = src;
	else{
		var str="!ERROR setForegroundLN() lineIndex="+LN;
		//alert(str);
		window.defaultStatus=str;
	}
}

// ///////////////////////////////////////////////////////////

//solid td background for gameboard
function getBackground( LN ){
	return d.getElementById( LN ).getAttribute("background");
}

//solid td background for gameboard
function setBackgroundLN(LN,p){
	d.getElementById( LN ).setAttribute("background",p.src);
	return;
}


//solid td background for gameboard, same as above but x,y form
// x,y = coordinate,  c = pieceCode in charCodeForm
function setBackground(x,y,c){

	var pieceCode = String.fromCharCode(c);
	var index = arrayIndex(PIECECODES, pieceCode);


	if ( x<BOARDX && x>=0   &&   y<BOARDY  &&  y>=0  && index>=0 ) {
		var field;
		var LN = xy2line(x+1,BOARDY-y);

		field = d.getElementById( LN ).setAttribute( "background", PIECESOURCES[ index ] );
		setMessage("solid background ("+x+","+y+") "+PIECENAMES[ index ]);
	}

	else
		setMessage("setBackground() invalid,  (x,y)=("+x+","+y+") pieceCode = "+pieceCode);

	return;
}

function clearBackground(){
	var LN;
	var field;

	for (var i=1; i<=BOARDX*BOARDY; i++){
		if ( arrayIndex(DEADFIELDS,"LN_"+i) == -1 )
			d.getElementById( "LN_"+i ).setAttribute( "background", NOPIECE );
	}
		setMessage("clearSolid (background images and delay pieces)");
}



function remDelay(){
	var LN;
	var field;
	var ref;

	for (var j=0; j<BOARDY; j++){
		for (var i=0; i<BOARDX; i++){
			LN = xy2line(i+1,j+1);
			ref = d.getElementById( LN ).getAttribute( "background" ); 

			if ( ref == d1.src || ref == d2.src || ref == d3.src )
				d.getElementById( LN ).setAttribute( "background", NOPIECE );
		}
	}
	return;
}

function removeDelay(){
	remDelay();
	setMessage("removeDelay");

	return;
}




// ///////////////////////////////////////////////////////////
// set td background values in the gameboard html from DEADFIELDS[], solid background images
function deadFieldsMake( Xfields ){

	//var field;

	if (Xfields.length > 0){
		for (var i=0; i<Xfields.length; i++){
			setBackgroundLN( Xfields[i],cF );
		}	
	}
	else{
		//alert("DEADFIELDS is empty");
	}
	

	return;
}


// ///////////////////////////////////////////////////////////
// new gamefield image on chessboard, by changing the html, td background attribute

//flip image
function boardFieldImage(){

	var gameFields = d.getElementsByTagName("td");

	for (var i=0; i<gameFields.length; i++){
		
		if ( gameFields[i].getAttribute("background") == FIELDWHITE ){
			gameFields[i].setAttribute("background",NOPIECE);
		}
		else if ( gameFields[i].getAttribute("background") == FIELDBLACK ){
			gameFields[i].setAttribute("background",NOPIECE);
		}

		else if ( gameFields[i].getAttribute("background") == NOPIECE ){
			if ( gameFields[i].getAttribute("bgColor").toLowerCase() == WHITE.toLowerCase() )
				gameFields[i].setAttribute("background",FIELDWHITE);
			else if ( gameFields[i].getAttribute("bgColor").toLowerCase() == BLACK.toLowerCase() )
				gameFields[i].setAttribute("background",FIELDBLACK);
		}
	}

	setMessage("change boardfield image");
	return;
}


// ///////////////////////////////////////////////////////////
// select/insert a piece from/to the game board
// int,int  (1..BOARD),(1..BOARDY)  -> 
// this need cleaning up the code, the pathName2pieceType usage should be avoided and
// the type should be used instead of source

// softplace mode
	// click a spot and nopiece inhand = pickup piece
	// click a spot and piece inhand = put piece and remove lastClickedSpot
	// click same spot as last = remove piece

// hardplace mode
	// click a spot and nopiece inhand = tell user to pick a piece from panel
	// click a spot and piece inhand not same on the field = put piece
	// click a spot and piece inhand same on the field = remove piece

//delay inserted to background, if only delay clicked on the board, remove
//if both piece and delay on same board, move piece, if doubleclick remove delay

function pickBoard( row,col ){

	var LN = xy2line(row,col);	
	var img = getForeground(LN); //image ref
	var status = "";
	var solid = pathName2pieceType( getBackground(LN) );

	var	newCoord = ""+HORIZONTALCHARS[ row-1 ]+""+col+"";
	var oldCoord = null;	

	if (LASTCLICKCOORDINATE != "dont update" && LASTCLICKCOORDINATE != null && LASTCLICKCOORDINATE != undefined){
		var lastxy = line2xy(LASTCLICKCOORDINATE);
		var lastx = HORIZONTALCHARS[ lastxy[0]-1 ];
		var lasty = lastxy[1];
		oldCoord = ""+lastx+""+lasty+"";
	}

	if (!SOFTPIECETAKE && (pathName2pieceType(PIECEINHAND) == pathName2pieceType(NOPIECE) || PIECEINHAND == null) ){

		setMessage("Hardplace: pick a piece from leftpanel or toggle hardplace (HP)");
		return;
	}
	

	else if (LASTCLICKCOORDINATE != LN){
	
		// no piece in hand and there is a piece on the board
		// get piece from board
		if ( SOFTPIECETAKE && pathName2pieceType(PIECEINHAND) == pathName2pieceType(NOPIECE)  &&   pathName2pieceType(img.src) != pathName2pieceType(NOPIECE) ) {
			PIECEINHAND = img.src;
			LASTCLICKCOORDINATE = LN;
	
			status = "get: \t" + type2name( pathName2pieceType(img.src) ) + " "+newCoord;
			//dependent on image name

		}

		//if hardplace mode and inhand same as on the board
		else if ( !SOFTPIECETAKE && ( pathName2pieceType(PIECEINHAND)==pathName2pieceType(img.src) || pathName2pieceType(PIECEINHAND)==solid) ){
	
			status = "hardplacemode remove: " + type2name( pathName2pieceType(PIECEINHAND) )+ "   "+newCoord; 
			//dependent on image name		
	
			//reset
			LASTCLICKCOORDINATE = null;
			//put image on board, if delaypiece to background, else normal
			if ( arrayIndex(DELAYTYPES, pathName2pieceType(PIECEINHAND) ) != -1 ){
				setBackgroundLN(LN, eF );
			}
			else
				img.src = NOPIECE;
		}

		// a piece in hand
		// put piece to board
		else if ( pathName2pieceType(PIECEINHAND) != pathName2pieceType(NOPIECE) ){

			
			var takeinfo = img.src;
			//put image on board, if delaypiece to background, else normal
			if ( arrayIndex(DELAYTYPES, pathName2pieceType(PIECEINHAND) ) != -1 ){
				setBackgroundLN(LN, source2image(PIECEINHAND) );
			}
			else {
				img.src = PIECEINHAND;
			}
			 //only reset to nopiece if softPiecePlacement is marked
			if (SOFTPIECETAKE){
	
				var lastxy;
				var lastx;
				var lasty;

				//take
				if (takeinfo != NOPIECE && LASTCLICKCOORDINATE != null && LASTCLICKCOORDINATE != "dont update"){
					status = "take: \t" + type2name( pathName2pieceType(PIECEINHAND) ) +" "+oldCoord + " " + newCoord + " " +type2name( pathName2pieceType(takeinfo) );
					//dependent on image name					
						//for kfc_mplayer program copy/paste
						if (MPLAYER){
							var texta = status.substr(7)
							texta = texta.substr( 0,texta.lastIndexOf(" ") );
							appendTextArea(texta + " \t"+MPLAYER_VALUE+"\n");
							MPLAYER_VALUE+=MPLAYER_COUNTER;
						}
				}

				//move
				else if (LASTCLICKCOORDINATE != null  &&   LASTCLICKCOORDINATE != "dont update"){
					status = "move: \t" + type2name( pathName2pieceType(img.src) ) +" "+oldCoord+" "+newCoord;
					//dependent on image name
						//for kfc_mplayer program copy/paste
						if (MPLAYER){
							appendTextArea(status.substring(7) + " \t"+MPLAYER_VALUE+"\n");
							MPLAYER_VALUE+=MPLAYER_COUNTER;
						}
				}

				//new insert
				else {
					status = "put: \t" + type2name( pathName2pieceType(PIECEINHAND) ) +" "+newCoord;
					//dependent on image name
					//appendTextArea(status + "\n");
				}

	
				//piece movement, delete the piece moved from				
				if (LASTCLICKCOORDINATE != null){
					getForeground(LASTCLICKCOORDINATE).src = NOPIECE;
				}

				//done placement, then reset values
				pieceInhandReset();
				LASTCLICKCOORDINATE = "dont update";
			}

			else {
				status = "hardplacemode put: \t" + type2name( pathName2pieceType(PIECEINHAND) ) + "   "+newCoord;
				//dependent on image name
			}
		}

		//no inhand and clicked on a spot with nopiece
		else {
			//remove delaypiece on background
			if ( arrayIndex(DELAYTYPES, solid) != -1 ){
				setBackgroundLN(LN,eF);
				status = "removeDelay: \t"+type2name( solid ) + "   "+newCoord;
			}
			else
				status = newCoord + "\t background=" + td_bg( LN )+".gif";
	
			LASTCLICKCOORDINATE = "dont update";
		}

		//update LASTCLICKCOORDINATE
		if (LASTCLICKCOORDINATE != "dont update"){
			LASTCLICKCOORDINATE = LN;
		}
	}


	//click twice on same spot then remove
	else {
	
		status = "sameSpotClick, remove: ";
		//dependent on image name

		if ( arrayIndex(DELAYTYPES, solid) != -1 ){
			status += type2name( solid ); 
			setBackgroundLN(LN,eF);
		}
		else {
			status += type2name( pathName2pieceType( img.src ) );
			img.src = NOPIECE;
		}

		status +=  "   "+newCoord;
		//reset
		LASTCLICKCOORDINATE = null;

		if (SOFTPIECETAKE){
				pieceInhandReset();
		}
	}


	updateCoordinate(row,col);

	//last info piece to user
	setMessage(status);
	//appendTextArea("\n"+ ++SCROLL + ": " + status); //continuely moving info at textarea
	return;
}


// ///////////////////////////////////////////////////////////
function pieceInhandReset(){
	PIECEINHAND = NOPIECE;	
	return;
}






// ///////////////////////////////////////////////////////////
//double click on the board
function pickDouble( row,col ){

	//one pickBoard() call is auto from <a href> link
	pickBoard( row,col );

	//problems with onclick, ondblclick, a href=javascript:fn() and cancelling href call to work with
	//both mozilla and msie, I've decided to make this work with msie.

	return false;
}

// ///////////////////////////////////////////////////////////
// x = 0..BOARDX-1, y = 0..BOARDY-1
// the area in chess board not used, defined as deadfields

function outArea( x,y ){

	//resetValues();
	var coord = xy2line(x+1,y+1);
	var src = getForeground( coord ).src;


	if (src!=NOPIECE){
		resetValues();
		PIECEINHAND = getForeground( coord ).src;
		setMessage("OUTAREA:[" + HORIZONTALCHARS[x] + "" + (y+1) + "]   get " + type2name( pathName2pieceType(PIECEINHAND) ) );
	}
	else {
		setMessage("OUTAREA:[" + HORIZONTALCHARS[x] + "" + (y+1) + "]     background=" + td_bg( coord )+".gif      "+coord);
	}

	getForeground( coord ).src = NOPIECE;

	return;
}


// ///////////////////////////////////////////////////////////
// x,y = coordinate,  c = pieceCode in charCodeForm
function put(x,y,c){

	//alert("(x,y) = (" + x + "," + y + ")  c = " + c);

	var pieceCode = String.fromCharCode(c);
	var index = arrayIndex(PIECECODES, pieceCode);

	if ( x<BOARDX && x>=0   &&   y<BOARDY  &&  y>=0  && index>=0 ) {

		setForeground( x, BOARDY-1-y, PIECESOURCES[index]);
		setMessage("put (" + x + "," + y + ")  name = " + PIECENAMES[index] );
	}
	else {
		setMessage("put() invalid,  (x,y)=("+x+","+y+") pieceCode = "+pieceCode );
	}
}



// ///////////////////////////////////////////////////////////
/*
//NOT USED
function Get(){

	var res = getPosition();
	var info = ++SCROLL + ": The board datalist\n== COPY BELOW ==\n" + 
		res + "\n== COPY ABOVE ==\n\n";

	appendTextArea(info);
	setMessage("get positiondata, see the textArea");

	return res;
}
*/

// ///////////////////////////////////////////////////////////
// translate FEN or EPD to positiondata (pd)
// if FEN data is parsed, the epd string won't be 100% correct, but it will show the position correct
// the extra information from FEN just get truncated when tried to display 'the extra pieces translated'

function epd2pdMake(epd){
	var str = new String(epd);
	var marker = 0;

	for (var i=str.length-1; i>=0; i--){

		//if number, we add '-' as empty fields
		if ( isCharANumber(str.charAt(i)) ){
			marker = i;
			i--;
			while ( str.charAt(i) != undefined && isCharANumber(str.charAt(i)) ){
				i--;
			}

		//avoid datastring as -1, when it should be just -, et.c. /K-1q/ -> /K-q/ 
			if (str.charAt(marker)=='1' && (str.length-1 == marker || !isCharANumber(str.charAt(marker+1)) ) )
				str = str.substr(0,marker) + '-' + str.substr(marker+1);
			else
				str = str.substr(0,marker) + '-' + str.substr(marker);
		}		


	}
	
	//add extra '/' if missing
	if (str.length>0 && str.charAt(0)!='/'){
		str = '/' + str;
	}
	if (str.length>0 && str.charAt(str.length-1)!='/'){
		str = str + '/';
	}

	
	//var pos = str + "|mirx";//NOT USED, mirx reverses horizontally


	//reverse the pd between the '/' delimiters, this reverses the data horizontally
	var arr = str.split("/");
	arr.reverse();
	var pd = arr.join("/");


	return pd;
}

// epd and pd data is very similar, except the order in pd is reversed horizontally
function epd2pd(){	
	var str = getTerminal();
	str = str.replace(/ /g,"");

	if (str.indexOf("epd2pd")==0)
		str = str.replace("epd2pd","");
	else if (str.indexOf("fen2pd")==0)
		str = str.replace("fen2pd","");
	else if (str.indexOf("e2p")==0)
		str = str.replace("e2p","");
	else {
		setMessage("ERROR! epd2pd function");
		return;
	}
	
	var pd = epd2pdMake(str);

	//appendTextArea(++SCROLL + ": The positiondata, translated from epd or fen\n== COPY BELOW ==\n" + 
	//	pd  + "\n== COPY ABOVE ==\n\n");

	loadPosition(pd);
	//setMessage("epd2pd done, see textarea");
	setMessage("epd2pd done");
	return;
}

function loadEpd2pd(){
	setTerminal("epd2pd ");
	setMessage("append FEN or EPD data in terminal: epd2pd <FEN_or_EPD_data>");
	return;
}


// ///////////////////////////////////////////////////////////
function getDelay(){
	var res = getDelaysFromBackground();
	var info;

	if (res.length>0){
		info = ++SCROLL + ": The delay datalist\n== COPY BELOW ==\n" + 
		res  + "\n== COPY ABOVE ==\n\n";
	}
	else{
		info = ++SCROLL + ": The delay datalist\nThere are no delaypieces on background fields\n";
	}	
	appendTextArea(info);
	setMessage("getdelay, see the textArea");

	return;
}
function getAllSolid(){
	var res = getAllBackgroundFromScreen();
	var info;

	if (res.length>0){
		info = ++SCROLL + ": The solid datalist\n== COPY BELOW ==\n" + 
		res  + "\n== COPY ABOVE ==\n\n";
	}
	else{
		info = ++SCROLL + ": The solid datalist\nThere are no solidpieces on background fields\n";
	}	
	appendTextArea(info);
	setMessage("getsolid, see the textArea");

	return;
}


//screen position and delaypieces
function getBoth(){
	var pos = getPosition();
	var delay = getDelaysFromBackground();

	return pos+delay;
}
//
function getBoardAndDelay(){

	var res = getBoth();
	var info = ++SCROLL + ": The position and delay datalist\n== COPY BELOW ==\n" + 
		res + "\n== COPY ABOVE ==\n\n";

	appendTextArea(info);
	setMessage("get position+delay data, see the textArea");

	return res;
}


// ///////////////////////////////////////////////////////////
// positiondata -> bool
function check_positiondata( loadData ){

	var test = FILTER.test( loadData );

	return test;
}


// ///////////////////////////////////////////////////////////
// moviedata -> bool
function check_moviedata( loadData ){

	var test = FILTERMOVIE.test( loadData );

	return test;
}


// ///////////////////////////////////////////////////////////
function positionSetStart(){
	//positionSet("all");
	positionSet('/RNBQKBNR/P8/////p8/rnbqkbnr/'); //twoplayer
}

// ///////////////////////////////////////////////////////////
function selPosition_onchange(){
	var sel = d.rightForm.selPosition;
	var item = sel.options[sel.selectedIndex];

	if (item.value != -1) {
		switch (item.value){


			case "welcomeMessage":
				setTextArea(++SCROLL + ": " + WELCOMEMESSAGE + "\n");
				break;


			case "position4player": 
				positionSet("all");
				break;
			case "position2player": 
				positionSet('/RNBQKBNR/P8/////p8/rnbqkbnr/'); //twoplayer
				break;
			case "positionRandomFromBoard": 
				positionRandomFromBoard();
				break;


			case "imageDefault":
				chessImages("default");
				break;
			case "imageKfc":
				chessImages("kfc");
				break;
			case "imageNewstyle":
				chessImages("newstyle");
				break;
			case "imageMychess":
				chessImages("mychess");
				break;
			case "imageCiv":
				chessImages("civ");
				break;


			
			case "insertWhite": 
				positionSet("white");
				break;
			case "insertBlack": 
				positionSet("black");
				break;
			case "insertRed": 
				positionSet("red");
				break;
			case "insertGreen": 
				positionSet("green");
				break;
			case "epd2pd": 
				loadEpd2pd();
				break;
			case "textareapd": 
				loadPosition( getTextArea() );
				break;
			case "textareamoviepd":
				loadMoviePosition( getTextArea(), 0 );
				break;


			case "burn": 
				setAllForegroundToBackground();
				break;
			case "clearsolid": 
				clearBackground();
				break;
			case "removedead": 
				removeDead();
				break;



			case "pieces":
				pieces();
				break;
			case "boardinfo":
				dimension();
				break;
			case "configkfc": 
				configKFC();
				break;
			case "html": 
				html(1);
				break;
			case "pic": 
				drawGameBoardPicture(1);
				break;
			case "help": 
				help();
				break;
			case "pd": 
				positiondata();
				break;


			case "defaultSelected":
				break;
			default:
				setTextArea(++SCROLL + ": not implemented\n");
				break;
		}
	}

	sel.selectedIndex = sel.options["defaultSelected"]; //because the onchange event should be like onclick
	return;
}


// ///////////////////////////////////////////////////////////
// update the chess screen with the data from board array
// BOARD -> screen

function updateAllScreen(){
		for (var j=0; j< BOARDY; j++){
			for (var i=0; i<BOARDX; i++){
				getForeground( xy2line(i+1,j+1) ).src = BOARD[j][i];
			}
		}

	return;
}

// ///////////////////////////////////////////////////////////
// update the board array with the current screen piece data
// screen -> BOARD

function updateAllBoard(){
		for (var j=0; j< BOARDY; j++){
			for (var i=0; i<BOARDX; i++){
				//if (! isDead(i,j) )
					BOARD[j][i] = getForeground( xy2line(i+1,j+1) ).src;
			}
		}

	return;
}


// ///////////////////////////////////////////////////////////
// x,y = 0..BOARDX-1, 0..BOARDY-1
function isDead(x,y){

	var coordinate = xy2line(x+1,y+1);
	
	for (var i=0; i<DEADFIELDS.length; i++){
		if (DEADFIELDS[i] == coordinate){
			return true;
		}
	}


	return false;
}

function removeDeadDo(){

	for (var j=0; j<BOARDY; j++){
		for (var i=0; i<BOARDX; i++){
			if ( isDead(i,j) )
				setForeground(i,j,NOPIECE);
		}
	}
	return;
}
function removeDead(){
	removeDeadDo();
	setMessage("remove pieces on outarea");
	return;
}

// ///////////////////////////////////////////////////////////
// list the pieces on the board, coordinate and names

function pieces(){

	var str = "";
	var numberOfPieces = 0;
	var src;

	for (var j=0; j<BOARDY; j++){
		for (var i=0; i<BOARDX; i++){
			
			src = getForeground( xy2line(i+1,j+1) ).src;
			if ( src != NOPIECE ){ //dont store empty fields to piecelist from the board
				str += "- " + source2name( src );
				str += " " + HORIZONTALCHARS[i] + (j+1) + "\n"; 
				numberOfPieces++;
			}
		}
	}

	var message = "Pieces on the board\nNumber of pieces = " + numberOfPieces + "\n" + str + "\n";
	appendTextArea(++SCROLL + ": " + message);
	setMessage("Pieces on the board, see textArea for info");

	return;
}



function configKFC(){

	var type, player, pieceType, c = "";

	var strBoardsize = "";
	var strPieces = "";
	var strDead = "";
	var numberOfPieces = 0;
	var numberOfDead = 0;


	//local functions
	function addPiece(x,y,player,piece){
		numberOfPieces++;
		return ("piece { x { " +x+ " } y { " +y+ " } player { " +player+ " } type { "+piece+ " } }");
				//piece { x { 2 } y { 0 } player { Black } type { rook } }
	}
	function addDead(x,y){
		numberOfDead++;
		return ("dead { x { " +x+ " } y { " +y+ " } }");
	}

	//boardsize
	strBoardsize += "width { "+BOARDX+" }\n";
	strBoardsize += "height { "+BOARDY+" }\n";


	//deadfields
	for (var i=0; i<DEADFIELDS.length; i++)	{
		var data = line2xy( DEADFIELDS[i] );
		strDead += addDead( data[0]-1, BOARDY-data[1] ) + "\n";
	}

	//pieces
	for (var j=0; j<BOARDY; j++){
		for (var i=0; i<BOARDX; i++){

			type = source2type( getForeground( xy2line(i+1, j+1) ).src );
			if (type == 'cf'){
				strDead += addDead(i,BOARDY-1-j) + "\n";
			}

			else if ( type != 'ef' && type != 'cf'){ //dont store nopiece and deadfield to piecelist

				c = type.charAt(0);
				switch (c){
					case "w": 
						player = "White";
						break;

					case "b": 
						player = "Black";
						break;
					
					case "r": 
						player = "Crimson";
						break;

					case "g": 
						player = "Jade";
						break;

					default: 
						player = "PLAYER_UNKNOWN";
						break;
				}
				
				c = type.charAt(1);
				switch (c){
					case "r": 
						pieceType = "rook";
						break;
					
					case "b":
						pieceType = "bishop";
						break;
					
					case "n": 
						pieceType = "knight";
						break;

					case "k": 
						pieceType = "king";
						break;

					case "q":
						pieceType = "queen";
						break;

					case "p": 
						pieceType = "pawn";
						break;

					case "g": 
						pieceType = "knightBishy";
						break;

					case "j": 
						pieceType = "knightRooky";
						break;

					default: 
						pieceType = "TYPE_UNKNOWN";
						break;
				}

				
				strPieces += addPiece( i, BOARDY-1-j, player, pieceType ) + "\n";
			}
		}
	}

	var message = "List pieces for kfc config\n\n"+

		"The values for the statements:\n"+
		"width, height, dead, startingPositions\n\n"+

		"Number of deadFields = " + numberOfDead + 
		"\nNumber of pieces = " + numberOfPieces +"\n\n"+

	"  == COPY BELOW ==\n\n"+ 

		strBoardsize +"\n"+
		strDead +"\n"+
		"startingPositions {\n\n"+
		strPieces + "\n"+
		"}\n"+
		"  == COPY ABOVE ==\n"+
		"  - remember to insert those statement/values at the correct place\n\n";
	appendTextArea(++SCROLL + ": " + message);
	setMessage("List pieces for kfc config, see textArea for info");

	return;
}




// ///////////////////////////////////////////////////////////
// build random position using the pieces on the board

function positionRandomFromBoard(){

	setMessage("Random position ...");

	// store pieces		
	var onboard = new Array();
	var src;

	for (var j=0; j<BOARDY; j++){
		for (var i=0; i<BOARDX; i++){
			src = getForeground( xy2line(i+1,j+1) ).src;
			//dont store empty fields to piecelist from the screen
			if (src != NOPIECE)
				onboard[onboard.length] = src;
		}
	}

	//debug
	//if more pieces on the board allowed
	if (onboard.length > BOARDX*BOARDY - DEADFIELDS.length){
		var str="pieces on the board mismatch with OUTAREA and boardsize rule, cant do random";
		alert(str);
		window.defaultStatus=str;
		return;
	}

	
	var p = 0;
	var x,y,t;


	clearScreen();
	resetValues();

	for (p=0; p < onboard.length; p++) {

		x = Math.floor( Math.random()*BOARDX );
		y = Math.floor( Math.random()*BOARDY );
		t = getForeground( xy2line(x+1,y+1) );

		if (t.src == NOPIECE && (!isDead(x,y) ) ) {
				t.src = onboard[p];
		}
		else {
			p--;
		}
	}

	setMessage("Random pos:  position from the board");

	return;
}

// ///////////////////////////////////////////////////////////
// remove some pieces on the board
// boardgame, strint ->

function removeSet(whatChessSet){

	setMessage("remove " + whatChessSet);

	//resetValues();

		//w=white, b=black, r=red, g=green, (c,f,m)=customPieces, [^fmcwbrg]=none
		var player = whatChessSet.substr(0,2); 
		var LN;
		var type;
		var backImg;

		for (var j=0; j<BOARDY; j++){
			for (var i=0; i<BOARDX; i++){
				LN = xy2line(i+1,j+1);
				type = source2type( getForeground( LN ).src );
				
				//player
				if ( type.charAt(0) == player.charAt(0) )
					setForeground(i,j,NOPIECE);
				//custom
				else if ( player == 'cu' && (type == 'cf' || type.charAt(0) == 'f' || type == 'mf') ){
					setForeground(i,j,NOPIECE);
				}

			}
		}
		
	return;
}





// ///////////////////////////////////////////////////////////
// set pieces on board to game start position
// boardgame, string -> boardgame

function positionSet(whatChessSet){
	
	resetValues();

	if(whatChessSet.length > 0 && whatChessSet.charAt(0)== "/")
		loadPosition(whatChessSet);

	else {
	
		if (BOARDX >= 8 && BOARDY >= 8){

		switch (whatChessSet.toLowerCase() ){
			case "all":
				clearScreen();
				posRed();
				posGreen();
				posWhite();
				posBlack();
				//posDeadCorner();
				removeDeadDo();
				
				setMessage("START set position");
				break;
		
			case "white":				
				posWhite();	
				setMessage("WHITE Set position");
				break;
		
			case "black":				
				posBlack();
				setMessage("BLACK set position");
				break;
		
			case "red":
				posRed();
				setMessage("RED set position");
				break;
		
			case "green":				
				posGreen();
				setMessage("GREEN set position");
				break;
	
			case "twoplayer": //not used
				posTwoPlayer();
				setMessage("TWOPLAYER set position");
				break;
	
	
	
			case "none":
				positionClear(); //positionClear will remove the img
				setMessage("NONE set position");
				break;
	
			default:
				setMessage("ERROR! positionSet()");
				break;
			}
		}

		else{
			setMessage("Only if board is minimum 8 x 8");
		}
	
	}
	
	return;
}


function posDeadCorner(){

	var x=BOARDX;
	var y=BOARDY;
	var src = cF.src;

	setForeground( 0,0,src);
	setForeground( 0,1,src);
	setForeground( 1,0,src);
	setForeground( 1,1,src);

	setForeground( 0,y-1,src);
	setForeground( 0,y-2,src);
	setForeground( 1,y-1,src);
	setForeground( 1,y-2,src);

	setForeground( x-1,0,src);
	setForeground( x-1,1,src);
	setForeground( x-2,0,src);
	setForeground( x-2,1,src);

	setForeground( x-1,y-1,src);
	setForeground( x-1,y-2,src);
	setForeground( x-2,y-1,src);
	setForeground( x-2,y-2,src);

	return;
}


function posWhite(){

	var x=BOARDX;
	var y=BOARDY;
	var m = Math.floor( (x-8)/2 );

	//setup white
	setForeground( m+0, 0, wR.src);
	setForeground( m+1, 0, wN.src);
	setForeground( m+2, 0, wB.src);
	setForeground( m+3, 0, wQ.src);
	setForeground( m+4, 0, wK.src);
	setForeground( m+5, 0, wB.src);
	setForeground( m+6, 0, wN.src);
	setForeground( m+7, 0, wR.src);
	setForeground( m+0, 1, wP.src);
	setForeground( m+1, 1, wP.src);
	setForeground( m+2, 1, wP.src);
	setForeground( m+3, 1, wP.src);
	setForeground( m+4, 1, wP.src);
	setForeground( m+5, 1, wP.src);
	setForeground( m+6, 1, wP.src);
	setForeground( m+7, 1, wP.src);
	
	return;
}

function posBlack(){
	
	var x=BOARDX;
	var y=BOARDY;
	var m = Math.floor( (x-8)/2 );

	//setup black
	setForeground( m+0, y-1, bR.src);
	setForeground( m+1, y-1, bN.src);
	setForeground( m+2, y-1, bB.src);
	setForeground( m+3, y-1, bK.src);
	setForeground( m+4, y-1, bQ.src);
	setForeground( m+5, y-1, bB.src);
	setForeground( m+6, y-1, bN.src);
	setForeground( m+7, y-1, bR.src);
	setForeground( m+0, y-2, bP.src);
	setForeground( m+1, y-2, bP.src);
	setForeground( m+2, y-2, bP.src);
	setForeground( m+3, y-2, bP.src);
	setForeground( m+4, y-2, bP.src);
	setForeground( m+5, y-2, bP.src);
	setForeground( m+6, y-2, bP.src);
	setForeground( m+7, y-2, bP.src);

	return;
}

function posRed(){

	var x=BOARDX;
	var y=BOARDY;
	var m = Math.floor( (y-8)/2 );

	//setup red
	setForeground( x-1, m+0, rR.src);
	setForeground( x-1, m+1, rN.src);
	setForeground( x-1, m+2, rB.src);
	setForeground( x-1, m+3, rK.src);
	setForeground( x-1, m+4, rQ.src);
	setForeground( x-1, m+5, rB.src);
	setForeground( x-1, m+6, rN.src);
	setForeground( x-1, m+7, rR.src);
	setForeground( x-2, m+0, rP.src);
	setForeground( x-2, m+1, rP.src);
	setForeground( x-2, m+2, rP.src);
	setForeground( x-2, m+3, rP.src);
	setForeground( x-2, m+4, rP.src);
	setForeground( x-2, m+5, rP.src);
	setForeground( x-2, m+6, rP.src);
	setForeground( x-2, m+7, rP.src);

	return;
}

function posGreen(){

	var x=BOARDX;
	var y=BOARDY;
	var m = Math.floor( (y-8)/2 );

	//setup green
	setForeground( 0, m+0, gR.src);
	setForeground( 0, m+1, gN.src);
	setForeground( 0, m+2, gB.src);
	setForeground( 0, m+3, gQ.src);
	setForeground( 0, m+4, gK.src);
	setForeground( 0, m+5, gB.src);
	setForeground( 0, m+6, gN.src);
	setForeground( 0, m+7, gR.src);
	setForeground( 1, m+0, gP.src);
	setForeground( 1, m+1, gP.src);
	setForeground( 1, m+2, gP.src);
	setForeground( 1, m+3, gP.src);
	setForeground( 1, m+4, gP.src);
	setForeground( 1, m+5, gP.src);
	setForeground( 1, m+6, gP.src);
	setForeground( 1, m+7, gP.src);

	return;
}

function posTwoPlayer(){

	var x=BOARDX-1;
	var y=BOARDY-1;

	//setup white
	setForeground( 2, 2, wR.src);
	setForeground( 3, 2, wN.src);
	setForeground( 4, 2, wB.src);
	setForeground( 5, 2, wQ.src);
	setForeground( 6, 2, wK.src);
	setForeground( 7, 2, wB.src);
	setForeground( 8, 2, wN.src);
	setForeground( 9, 2, wR.src);
	setForeground( 2, 3, wP.src);
	setForeground( 3, 3, wP.src);
	setForeground( 4, 3, wP.src);
	setForeground( 5, 3, wP.src);
	setForeground( 6, 3, wP.src);
	setForeground( 7, 3, wP.src);
	setForeground( 8, 3, wP.src);
	setForeground( 9, 3, wP.src);

	//setup black
	setForeground( 2, 8, bP.src);
	setForeground( 3, 8, bP.src);
	setForeground( 4, 8, bP.src);
	setForeground( 5, 8, bP.src);
	setForeground( 6, 8, bP.src);
	setForeground( 7, 8, bP.src);
	setForeground( 8, 8, bP.src);
	setForeground( 9, 8, bP.src);
	setForeground( 2, 9, bR.src);
	setForeground( 3, 9, bN.src);
	setForeground( 4, 9, bB.src);
	setForeground( 5, 9, bQ.src);
	setForeground( 6, 9, bK.src);
	setForeground( 7, 9, bB.src);
	setForeground( 8, 9, bN.src);
	setForeground( 9, 9, bR.src);

	
	return;
}

// ///////////////////////////////////////////////////////////
// flip html boarder value 1 or 0 on chessboard

function boardBorderFlip(){
	var gameBoarder = d.getElementById("boardGame");

		if ( gameBoarder.getAttribute("border") == "1" ){
			gameBoarder.setAttribute("border","0");
		}
		else if ( gameBoarder.getAttribute("border") == "0" ){
			gameBoarder.setAttribute("border","1");
		}
		else {
			var str="ERROR in boardBorderFlip(), maybe id value missing in html code";
			//alert(str);
			window.defaultStatus=str;
		}

		setMessage("boarder value flipped");
}


// ///////////////////////////////////////////////////////////
// switch the gamefield image on chessboard, by changing the html, td background attribute

//flip order
function boardOrderFlip(){
//alert("ok");
	var gameFields = d.getElementsByTagName("td");
	var refcolor,refimage;

	for (var i=0; i<gameFields.length; i++){

		//td background
		refcolor = gameFields[i].getAttribute("bgColor"); 
		refimage = gameFields[i].getAttribute("background"); 
		
		if (refcolor != undefined && refcolor != null)
			refcolor = refcolor.toLowerCase();


		if ( refcolor == WHITE.toLowerCase() ){
			gameFields[i].setAttribute("bgColor",BLACK );			
			if (refimage == FIELDWHITE || refimage == FIELDBLACK)
				gameFields[i].setAttribute("background",FIELDBLACK);
		}
		else if ( refcolor == BLACK.toLowerCase() ){
			gameFields[i].setAttribute("bgColor",WHITE);
			if (refimage == FIELDWHITE || refimage == FIELDBLACK)
				gameFields[i].setAttribute("background",FIELDWHITE);
		}
	}
	setMessage("boardfield order flipped");

	return;
}

// ///////////////////////////////////////////////////////////
function dimension(){
	var info = "";
	info +=  "WHITE=" + WHITE+"\n";
	info +=  "BLACK=" + BLACK+"\n";
	info +=  "BG=" + d.bgColor+"\n\n";
	info +=  "BOARDX=" + BOARDX+"\n";
	info +=  "BOARDY=" + BOARDY+"\n";
	info +=  "FIELDSIZE=" + IMG+"\n";
	if (DEADFIELDS.length>0){
		info +=  "OUTAREA:\n";
		for (var i=0; i<DEADFIELDS.length; i++){
			var xy = line2xy(DEADFIELDS[i]);
			info +=  "(x,y) = (" +xy[0]+","+xy[1]+ ")  " + DEADFIELDS[i] + "\n";
		}
	}
	
	appendTextArea(++SCROLL + ": \n" + info);
	setMessage("board info, see the textArea");

	return;	
}


// ///////////////////////////////////////////////////////////
//table <td> background set, from LN_? value

function td_bg( LN ){

	var src = d.getElementById( LN ).getAttribute("background");
	return pathName2pieceType(src);
}

// ///////////////////////////////////////////////////////////



// set html body background color
function setBGColor(color){
	d.bgColor=color;

	setMessage("html bgColor = " + color);

	return color;
}


// ///////////////////////////////////////////////////////////
// seems to work with Mozilla, but not with Explorer
// the TD bgColor value dynamic changing for chessboard

function setFieldColor1(){
	//bluefield
	document.rightForm.terminal.value = "white 003399|black 003366";
	terminal_onchange( document.rightForm.terminal );
}
//NOT USED
function setFieldColor2(){
	//darkwhite,black
	document.rightForm.terminal.value = "white 6c6148|black 343024";
	terminal_onchange( document.rightForm.terminal );
}
//NOT USED
function setFieldColor3(){
	//white,black
	document.rightForm.terminal.value = "white dddddd|black 343024";
	terminal_onchange( document.rightForm.terminal );
}

//
function setFieldColorWhite(strColor){
	var stringColor = strColor.toLowerCase();
	stringColor = stringColor.replace(/\s/g, "" );//remove whitespaces

	//add # if there isnt any
	if (stringColor.indexOf("#") < 0) {
		stringColor = "#" + stringColor;
	}

	if (stringColor.length == 7){

		var count = BOARDX*BOARDY;
	
		for (var i=1; i<=count; i++){
			if (d.getElementById("LN_"+i).getAttribute("bgColor").toLowerCase() == WHITE.toLowerCase() ){
				d.getElementById("LN_"+i).setAttribute("bgColor",stringColor);
			}
		}
	
		WHITE = stringColor;
		setMessage("FieldWhite= " + WHITE + " -use Fo button if nothing happend");
	}

	else {
		var str ="color value not valid, arg must be 7 length = " + stringColor; 
		alert(str);
		window.defaultStatus=str;
	}
}
function setFieldColorBlack(strColor){
	var stringColor = strColor.toLowerCase();
	stringColor = stringColor.replace(/\s/g, "" );//remove whitespaces

	//add # if there isnt any
	if (stringColor.indexOf("#") < 0) {
		stringColor = "#" + stringColor;
	}

	if (stringColor.length == 7){

		var count = BOARDX*BOARDY;	
	
		for (var i=1; i<=count; i++){
			if (d.getElementById("LN_"+i).getAttribute("bgColor").toLowerCase() == BLACK.toLowerCase() ){
				d.getElementById("LN_"+i).setAttribute("bgColor",stringColor);				
			}				
		}
	
		BLACK = stringColor;
		setMessage("FieldBlack= " + BLACK + " -use Fo button if nothing happend");
	}

	else {
		var str ="color value not valid, arg must be 7 length = " + stringColor; 
		alert(str);
		window.defaultStatus=str;
	}
}



// ///////////////////////////////////////////////////////////
// rotate current screen
// rotateRight: (x,y) -> (BOARDY - y + 1, x)
// rotateLeft: (x,y) -> (y, BOARDX - x + 1)
// rotateUp: (x,y) -> (BOARDX - x + 1, BOARDY - y + 1)
// mirrorX: (x,y) -> (x, BOARDY - y + 1)
// mirrorX: (x,y) -> (BOARDX - x + 1, y)

// int ->


function rotate(num){

	if (BOARDX == BOARDY || num==3 || num==4 || num==5 || num==6){
	
	var maxX = BOARDX - 1;
	var maxY = BOARDY - 1;
	//working on rotating the delay pieces
	var delayPieces = getDelaysFromBackground();
	if (delayPieces.length > 0) {
		delayPieces = removeHeadFromString(delayPieces); //remove the '%' char
	}

	

	//left
	if (num==1){
		for (var j=0; j<BOARDY; j++){
			for (var i=0; i<BOARDX; i++){
				BOARD[maxX -  i][j] = getForeground( xy2line(i+1,j+1) ).src;
			}
		}
		//also rotate the delay pieces
			if (delayPieces.length>0){
				
				var newDelays = "";
				var ch = ""; //index char
				var num = "";
				var numNew = "";
				var line = "";
				var xy; //array

				for (var i=0; i<delayPieces.length; i++){
					//get delay pieces one by one and transfer
					ch = delayPieces.charAt(i);
					if (ch=='a' || ch=='e' || ch=='o'){ //just put them in new delay
						if (num!="") { //parse new rotated place for delay info
							var xy = line2xy( "LN_"+num );
							line = xy2line(xy[1],maxX+2-xy[0]);
							numNew = parseInt( line.substr( line.lastIndexOf("_") + 1 ) );
							newDelays += numNew;
						}

						newDelays += ch;
						num = ""; //reset num					
					}
					else{
						num += ch;
					}
				}
				if (num!="") { //parse new rotated place for delay info
					var xy = line2xy( "LN_"+num );
					line = xy2line(xy[1],maxX+2-xy[0]);
					numNew = parseInt( line.substr( line.lastIndexOf("_") + 1 ) );
					newDelays += numNew;
				}

				newDelays = "%"+newDelays;

				removeDelay();        //remove old
				setSolid(newDelays);  //insert rotated
				//alert("%"+delayPieces+'\n\n'+newDelays); //debug
			}					
	}

	//right
	else if (num==2){
		for (var j=0; j<BOARDY; j++){
			for (var i=0; i<BOARDX; i++){
				BOARD[i][maxY - j] = getForeground( xy2line(i+1,j+1) ).src; //maxX should be maxY ?
			}
		}
		//also rotate the delay pieces
		if (delayPieces.length>0){
			
			var newDelays = "";
			var ch = ""; //index char
			var num = "";
			var numNew = "";
			var line = "";
			var xy; //array

			for (var i=0; i<delayPieces.length; i++){
				//get delay pieces one by one and transfer
				ch = delayPieces.charAt(i);
				if (ch=='a' || ch=='e' || ch=='o'){ //just put them in new delay
					if (num!="") { //parse new rotated place for delay info
						var xy = line2xy( "LN_"+num );
						line = xy2line(maxY+2-xy[1],xy[0]);
						numNew = parseInt( line.substr( line.lastIndexOf("_") + 1 ) );
						newDelays += numNew;
					}

					newDelays += ch;
					num = ""; //reset num					
				}
				else{
					num += ch;
				}
			}
			if (num!="") { //parse new rotated place for delay info
				var xy = line2xy( "LN_"+num );
				line = xy2line(maxY+2-xy[1],xy[0]);
				numNew = parseInt( line.substr( line.lastIndexOf("_") + 1 ) );
				newDelays += numNew;
			}

			newDelays = "%"+newDelays;

			removeDelay();        //remove old
			setSolid(newDelays);  //insert rotated
			//alert("%"+delayPieces+'\n\n'+newDelays); //debug
		}	
	}
	
	//mirror x
	else if (num==3){
		for (var j=0; j<BOARDY; j++){
			for (var i=0; i<BOARDX; i++){
				BOARD[maxY - j][i] = getForeground( xy2line(i+1,j+1) ).src;
			}
		}
		//also rotate the delay pieces
		if (delayPieces.length>0){
			
			var newDelays = "";
			var ch = ""; //index char
			var num = "";
			var numNew = "";
			var line = "";
			var xy; //array

			for (var i=0; i<delayPieces.length; i++){
				//get delay pieces one by one and transfer
				ch = delayPieces.charAt(i);
				if (ch=='a' || ch=='e' || ch=='o'){ //just put them in new delay
					if (num!="") { //parse new rotated place for delay info
						var xy = line2xy( "LN_"+num );
						line = xy2line(xy[0],maxY+2-xy[1]);
						numNew = parseInt( line.substr( line.lastIndexOf("_") + 1 ) );
						newDelays += numNew;
					}

					newDelays += ch;
					num = ""; //reset num					
				}
				else{
					num += ch;
				}
			}
			if (num!="") { //parse new rotated place for delay info
				var xy = line2xy( "LN_"+num );
				line = xy2line(xy[0],maxY+2-xy[1]);
				numNew = parseInt( line.substr( line.lastIndexOf("_") + 1 ) );
				newDelays += numNew;
			}

			newDelays = "%"+newDelays;

			removeDelay();        //remove old
			setSolid(newDelays);  //insert rotated
			//alert("%"+delayPieces+'\n\n'+newDelays); //debug
		}	
	}

	//mirror y
	else if (num==4){
		for (var j=0; j<BOARDY; j++){
			for (var i=0; i<BOARDX; i++){
				BOARD[j][maxX - i] = getForeground( xy2line(i+1,j+1) ).src;
			}
		}
		//also rotate the delay pieces
		if (delayPieces.length>0){
			
			var newDelays = "";
			var ch = ""; //index char
			var num = "";
			var numNew = "";
			var line = "";
			var xy; //array

			for (var i=0; i<delayPieces.length; i++){
				//get delay pieces one by one and transfer
				ch = delayPieces.charAt(i);
				if (ch=='a' || ch=='e' || ch=='o'){ //just put them in new delay
					if (num!="") { //parse new rotated place for delay info
						var xy = line2xy( "LN_"+num );
						line = xy2line(maxX+2-xy[0],xy[1]);
						numNew = parseInt( line.substr( line.lastIndexOf("_") + 1 ) );
						newDelays += numNew;
					}

					newDelays += ch;
					num = ""; //reset num					
				}
				else{
					num += ch;
				}
			}
			if (num!="") { //parse new rotated place for delay info
				var xy = line2xy( "LN_"+num );
				line = xy2line(maxX+2-xy[0],xy[1]);
				numNew = parseInt( line.substr( line.lastIndexOf("_") + 1 ) );
				newDelays += numNew;
			}

			newDelays = "%"+newDelays;

			removeDelay();        //remove old
			setSolid(newDelays);  //insert rotated
			//alert("%"+delayPieces+'\n\n'+newDelays); //debug
		}	
	}

	//mirror xy
	else if (num==5){
		for (var j=0; j<BOARDY; j++){
			for (var i=0; i<BOARDX; i++){
				BOARD[maxY - j][maxX - i] = getForeground( xy2line(i+1,j+1) ).src;
			}
		}
		//also rotate the delay pieces
		if (delayPieces.length>0){
			var maxC = (BOARDX*BOARDY+1);
			var newDelays = "";
			var ch = ""; //index char
			var num = "";

			for (var i=0; i<delayPieces.length; i++){
				//get delay pieces one by one and transfer
				ch = delayPieces.charAt(i);
				if (ch=='a' || ch=='e' || ch=='o'){ //just put them in new delay
					if (num!="") //parse new rotated place for delay info
						newDelays += (maxC - parseInt(num));

					newDelays += ch;
					num = ""; //reset num					
				}
				else{
					num += ch;
				}
			}
			if (num!="") //parse new rotated place for delay info
				newDelays += (maxC - parseInt(num));

			newDelays = "%"+newDelays;

			removeDelay();        //remove old
			setSolid(newDelays);  //insert rotated
			//alert("%"+delayPieces+'\n\n'+newDelays); //debug
		}		


	}
	
	//switch king/queen for start pos
	else if (num==6){

		if (BOARDX >= 8 && BOARDY >= 8){

			var x1=Math.floor(BOARDX/2-1);
			var x2=x1+1;
			var y1=Math.floor(BOARDY/2-1);
			var y2=y1+1;
			var xm = BOARDX-1;
			var ym = BOARDY-1;
			var src;

			src = getForeground( xy2line(x1+1,0+1) ).src;
			setForeground( x1, 0, getForeground( xy2line(x2+1,0+1) ).src );
			setForeground( x2, 0, src );

			src = getForeground( xy2line(x1+1,ym+1) ).src;
			setForeground( x1, ym, getForeground( xy2line(x2+1,ym+1) ).src );
			setForeground( x2, ym, src );

			src = getForeground( xy2line(0+1,y1+1) ).src;
			setForeground( 0, y1, getForeground( xy2line(0+1,y2+1) ).src );
			setForeground( 0, y2, src );

			src = getForeground( xy2line(xm+1,y1+1) ).src;
			setForeground( xm, y1, getForeground( xy2line(xm+1,y2+1) ).src );
			setForeground( xm, y2, src );

				/*
				BOARD[0][x1)]		BOARD[0][x2)]
				BOARD[0][x2]	=	BOARD[0][x1]	
				BOARD[ym][x1]	=	BOARD[ym][x2]
				BOARD[ym][x2]	=	BOARD[ym][x1]
				BOARD[y1][0]	=	BOARD[y2][0]	
				BOARD[y2][0]	=	BOARD[y1][0]	
				BOARD[y1][xm]	=	BOARD[y2][xm]
				BOARD[y2][xm]	=	BOARD[y1][xm]
				*/

			setMessage("rotate/mirror command, kings");
		}
		else{
			setMessage("Only if board is minimum 12 x 12");
		}

		return;
	}	


	else {
		var str="rotate value not supported = " + num;
		alert(str);
		window.defaultStatus=str;
		return;
	}


	setMessage("rotate/mirror command");
	
	updateAllScreen();


	}
	else{
		setMessage("rot/mir only on squared board");
	}
	
	return;
}


// ///////////////////////////////////////////////////////////
// move current screen
// up: LN -> LN + BOARDX
// down: LN -> LN - BOARDX
// right: LN -> LN++
// left: LN -> LN--

// int -> boardgame

function moveRight(num){

	var maxX = BOARDX - 1;

		for (var j=0; j<BOARDY; j++){
			for (var i=0; i<BOARDX; i++){
				if (i+num >= 0 && i+num < BOARDX)
					BOARD[j][i+num] = getForeground( xy2line(i+1,j+1) ).src;
				else 
					//BOARD[j][maxX - i] = NOPIECE; //pieces lost when out of board
					BOARD[j][maxX - i] = getForeground( xy2line(i+1,j+1) ).src; //warp board
			}
		}
	
	//	alert('move value not supported = ' + num);

	updateAllScreen();

	setMessage("move command");
	return;
}


function moveUp(num){

	var maxY = BOARDY - 1;
	

		for (var j=0; j<BOARDY; j++){
			for (var i=0; i<BOARDX; i++){
				if (j+num >= 0 && j+num < BOARDY)
					BOARD[j+num][i] = getForeground( xy2line(i+1,j+1) ).src;
				else 
					BOARD[maxY - j][i] = getForeground( xy2line(i+1,j+1) ).src; //warp board
					//BOARD[maxY - j][i] = NOPIECE; //pieces lost when out of board
			}
		}
	
	//	alert('move value not supported = ' + num);

	updateAllScreen();

	setMessage("move command");
	return;
}









// ///////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////
// terminal, give current screen position command
// () -> string

function getPosition(){

	var dataResult = "/";
	var pieceIndex;
	var counter = -1;
	var temp = "";
	var currentPiece = null;

	for (var j=0; j<BOARDY; j++){
		counter=1;
		currentPiece = null;

		for (var i=0; i<BOARDX; i++){

			temp = pathName2pieceType( getForeground( xy2line(i+1,j+1) ).src );
			pieceIndex = arrayIndex( PIECETYPES, temp );


			//debug
			if (pieceIndex < 0){
				var str="ERROR! in getPosition(), pieceIndex";
				//alert(str);
				window.defaultStatus=str;
				return;
			}


			//not same piece as last
			if (currentPiece != PIECECODES[ pieceIndex ]){
	
				if (currentPiece!=null)
					dataResult += currentPiece;
				currentPiece = PIECECODES[pieceIndex];
		
				if (counter >= 2){
					dataResult += counter;
					counter = 1;
				}		
			}		

			//dublicated piecetype on same row
			else {
				counter++;				
			}
		
		}	

		
		
		
		if (currentPiece!=null)
			dataResult += currentPiece;
		if (counter>=2)
			dataResult += counter;				

		//if (j < BOARDY-1)
			dataResult += "/";
	}

	//shorten the positiondata length by removing explisit nopiece listings
	var dataResultShorten = dataResult;
	dataResultShorten = dataResultShorten.replace(/(-\d+\/)|(-\/)/g, "/");
	dataResultShorten = dataResultShorten.replace(/(\/{2,})$/g, "/");
	if (dataResultShorten=="/")
		dataResultShorten="//";

return dataResultShorten;
}


// ///////////////////////////////////////////////////////////
function getUrlMake(){
	var url = URL+"?pd="+getBoth(); 
	return url;
}
function getUrl(){
	var url=getUrlMake();

	setMessage("get url with position, see terminal");
	setTerminal(url);
}


// ///////////////////////////////////////////////////////////
// get gamemovie from GAME array
//  -> moviedata
function getMoviePosition(){
	var result = "";

	if (GAME.length == 0){
		setMessage("none stored value");
	}
	else {
		for (var i=0; i<GAME.length; i++){
			result += "#" + GAME[i];
		}

		appendTextArea(++SCROLL + ": The movie datalist\n== COPY BELOW ==\n" + 
			result + "\n== COPY ABOVE ==\n\n");
		setMessage("get moviedata, frames="+GAME.length);
	}

	return result;
}

// ///////////////////////////////////////////////////////////
// load a gamemovie from a string
// string, int ->

function loadMoviePosition( loadDataIn, index ){

	var movieNumber = "";
	if (index != 0){
		movieNumber += index + "  ";
	}

	//remove whitespace, newline etc., seems to work
	var loadData = loadDataIn.replace(/\s/g,"");
	if ( check_moviedata( loadData ) ){
		var list = new Array();
		
		list = loadData.split("#");

		GAME.length = 0; //reset any previous values

		for (var i=1; i<list.length; i++)
		//because the first elem of list array is not used
		{
			GAME[i-1] = list[i];
		}

		setMessage("movie loaded: " + movieNumber + "   frames=" + GAME.length);
	}
	else {
		appendTextArea(++SCROLL + ": Moviedata has invalid value\n");
		setMessage("ERROR moviedata not valid");

			//adding newlines to loadData, to show the user
			var showData = "Data used = ";
			do{
				showData += loadData.substr(0,40) + "\n";
				loadData = loadData.substr(40);
			}while(loadData.length > 40)
			
			showData += loadData; //copy rest
			

			alert(LOADERROR_1 + showData + LOADERROR_2);				
			//window.defaultStatus="";
	}
}

// ///////////////////////////////////////////////////////////
function updateCoordinate(x,y){
	d.middleForm.coordinate.value = ""+HORIZONTALCHARS[x-1]+""+y+"\t("    +(x-1)+","+(BOARDY-y)+")\t"+    xy2line(x,y)+     "\tInHand: "+source2code(PIECEINHAND);
}


// onmouseover chessfield, i=1..BOARDX, j=1..BOARDY
function fieldMouseOver( i,j ){

	/*
	//markerimage when mouseover field
	//dont work with delay images, as they also uses the background place or with hardplace mode
	var LN = xy2line(i,j);
	BACKGROUNDIMAGESRC = getBackground( LN );
	if (PIECEINHAND!=NOPIECE && PIECEINHAND!=null && PIECEINHAND!=undefined){
		d.getElementById( LN ).setAttribute("background",PIECEINHAND);
	}	
	*/
	
	/*
	//testing quick inserting
	var LN = xy2line(i,j);
	setForegroundLN(LN, PIECEINHAND);
	*/
	
	updateCoordinate(i,j);
	return;
}
// onmouseout chessfield, i=1..BOARDX, j=1..BOARDY
function fieldMouseOut( i,j ){

	/*
	//markerimage when mouseover field, dont work with delay images
	//dont work with delay images, as they also uses the background place or with hardplace mode
	var LN = xy2line(i,j);
	d.getElementById( LN ).setAttribute("background",BACKGROUNDIMAGESRC);	
	*/

	return;
}

// ///////////////////////////////////////////////////////////
// Chessboard picture

// take the current screen and list positiondata in overview form to infoTextArea

function txtpicture(){
	
	var info = "";
	var txtpic = "";
	var src;
	
	for (var j=BOARDY-1; j>=0; j--){
		for (var i=0; i<BOARDX; i++){
			
			if (isDead(i,j) )
				src = cF.src;
			else
				src = getForeground(xy2line(i+1,j+1)).src;

			var index = arrayIndex( PIECESOURCES, src );
			txtpic += PIECECODES[ index ];
		}
		txtpic += "\n";
	}


	info +=  ++SCROLL + ": Chessboard picture\n";
	info  += txtpic + "\n";
	appendTextArea(info);
	setMessage("Chessboard picture, see textArea for info");

	return txtpic;
}



// ///////////////////////////////////////////////////////////
// when user loads game, entering data or using load function
// check the positiondata
// positiondata -> string[]

function loadPosition( loadDataIn ){
		
	//remove whitespace, newline etc., seems to work
	var loadData = loadDataIn.replace(/\s/g,"");

	if ( check_positiondata(loadData) ){

		//update the screen
		positiondata2screen( loadData );

		setMessage("load position");
	}

	else {
		appendTextArea(++SCROLL + ": Positiondata has invalid value\n");
		setMessage("ERROR positiondata not valid");

		//adding newlines to loadData, to show the user
		var showData = "Data used = ";
		do{
			showData += loadData.substr(0,40) + "\n";
			loadData = loadData.substr(40);
		}while(loadData.length > 40)
			
		showData += loadData; //copy rest

		alert(LOADERROR_1 + showData + LOADERROR_2);
		//window.defaultStatus="";
		}

	return;
}

// ///////////////////////////////////////////////////////////
function setPieces( arg ){
	listdata2screen(arg);
	setMessage("setPiece (set foreground) loaded");
}

function setSolid( arg ){
	listdata2screen(arg);
	setMessage("setSolid (set background) loaded");
}

function listdata2screen( loadData ){
// take a list either foreground or background pieceslist to be inserted on screen
// a list is build with prefix listtype and repeating piececode and it's location

// algorithm, insert when new code is found and there is recorded a prev code and a number
// skip unknown chars found.


	var data = new String(loadData);	
	var c,code,index;
	var nStr = "";
	var max = BOARDX*BOARDY;
	var solid = false;

	//debug
	if (data.length<1 || (data.indexOf('%') == -1 && data.indexOf('^') == -1) ){
		var str ="!ERROR listdata2screen() data not valid\n"+data; 
		//alert(str);
		window.defaultStatus=str;
	}

	if (data.indexOf('%') != -1)
		//solid listdata
		solid = true;

	//local fn:
	function listdataInsert(i,c,isSolid){
		if (isSolid)
			d.getElementById( "LN_"+i ).setAttribute( "background", code2sources(c) );
		else
			setForegroundLN( "LN_"+i, code2sources(c) );
	}

	data = removeHeadFromString( data ); //remove the identifier char


	while (data.length>0) {
		c = data.charAt(0);
		
		if ( isNaN(c) ){

			if (nStr.length>0 && code!=null){
				index = eval(nStr);
				if (index>0 && index<=max)
					//insert piece
					listdataInsert(index,code,solid);
				else {
					var str= "!ERROR listdata2screen() number index not within the boardarea\n"+index;
					//alert(str);
					window.defaultStatus=str;
					return;
				}
				//reset
				nStr = "";
				code = null;
			}

			code = c;
		}
		
		//number accumulate
		else
			nStr += c;

		data = removeHeadFromString( data );
	}
	//insert the lastone
	if (nStr.length>0 && code!=null){
		index = eval(nStr);
		if (index>0 && index<=max)
			listdataInsert(index,code,solid);
		else
			var str= "!ERROR listdata2screen() value index not within the boardarea\n"+index;
			//alert(str);
			window.defaultStatus=str;
	}
	
	return;
}

// ///////////////////////////////////////////////////////////
// terminal, setup position command
// string[] -> boardgame

function positiondata2screen( loadData ){
// The Algorith is 'hard to read' and clumsy

// '/' is the filling delimiter for a row
// it autofills with nopieces if the codecount dont equal within two '/' chars
// if the last code is a piece and the board isnt full, it autofill with that piece

// If a pieceCode is found and count is max 1, it insert it immediately
// If a number is found and its min two, it insert the num of last pieceCode found
// If a pieceCode is found and count is min 2, it insert prev pieceCode the count value times

	//remove the delaypieces first, if any
	remDelay();


	var data = new String(loadData);
	var solid = new String("");
	var piece = '-'; //the pieceCodes from data
	var src = NOPIECE; //the pieceCode value to insert
	var count = "0"; //string int
	var i,j,c = 0; //i,j=board, c=count of repeats to insert
	var lastIndex = (BOARDX-1)*(BOARDY-1);

	//if terminal ^ or % piece insert is used
	if (data.length>0 && (data.charAt(0)=="^" || data.charAt(0)=="%") ){
		return listdata2screen( data );
	}

	//solid data in string?, then split up
	if (data.indexOf("%") >= 0 ){
		solid = data.substr( data.indexOf("%") );
		data  = data.substr( 0, data.indexOf("%") );
	}



	// char can either be -> number,piece,newline

	//col
	for (j=0; j<BOARDY; j++){

		//newline reset
		src = NOPIECE;
		i=0;		
		count="0";
		if ( data.length>0 && data.charAt(0)=="/" )
			piece = "-";


		//find the newline  identicator and truncate until found
		while ( data.length > 0  &&  data.charAt(0) != '/' ){
			data = removeHeadFromString( data );
			//delaypieces?
			if ( data.length>0 && data.charAt(0)=="%" ){
				solid = data; data = "";
			}
		}		
		
		//remove the head newline '/'
		data = removeHeadFromString( data );

		//row, 
		while (i<BOARDX ){

			//assign new piece from data string
			if (data.length > 0){
				piece = data.charAt(0);			
			}

			//piece = number
			if ( isCharANumber(piece) ) {
				count += piece;
				data = removeHeadFromString( data );
	
				//this was the last data value
				if (data.length==0){
					break;
				}

				//debug
				if (Number(count)<0){
					var str="Error! positiondata2screen() Number(count)!=NaN, count="+count;
					//alert(str);
					window.defaultStatus=str;
					return;
				}
			}

			//piece = nonumber
			else{

				//insert the sum of count for pieceCode
				if ( Number(count) > 1 ){
					c=Number(count);

					while (i<BOARDX && c>1){

						setForeground(i,j,src);
						c--;
						i++;
					}

					//reset
					count="0";
					if (i == BOARDX-1)
						continue;
				}
				
				//newline
				if (piece == '/'){
					
					//fill up nopiece until row is full
					while (i<BOARDX){
						setForeground(i,j,NOPIECE);
						i++;
					}				
				}

				//piece
				else {
					var temp = arrayIndex(PIECECODES,piece);

					//extra test, if FILTER.test should failure
					if (temp<0){
						var str="!ERROR positiondata2screen(), datacode not valid\n\nvalue invalid="+piece;
						//alert(str);
						window.defaultStatus=str;
						return;
					}
					else{
						src = PIECEIMAGES[ temp ].src;
						setForeground(i,j,src);
						i++;
						data = removeHeadFromString( data );
					}
				}
			}
		
		}	
		
		//insert the rest sum of count for pieceCode
		//this is for the last row where the last data value is a number
		if ( Number(count) > 1 ){
					while (i<BOARDX){
						setForeground(i,j,src);
						i++;
					}
		}
	}
	
	//delaypieces?
	if (solid.length>0)
		listdata2screen(solid);

	return;
}


//
function setMessage(str){
	d.middleForm.infoHelp.value = str;
}
function setTextArea(str){
	d.rightForm.infoTextArea.value =  str;
}
function getTextArea(){
	return d.rightForm.infoTextArea.value;
}
function appendTextArea(str){
	d.rightForm.infoTextArea.value +=  str;
}
function setTerminal(str){
	d.rightForm.terminal.value = str;
}
function getTerminal(){
	return d.rightForm.terminal.value;
}
//




// ///////////////////////////////////////////////////////////
// ----------------------------------------------------------
// ///////////////////////////////////////////////////////////

// Terminal
// ref ->

function terminal_onchange(ref){

	//resetValues();
	var termInputList = new Array();

	var termInput = ref.value; //getTerminal();

	// ability to use multible commands in terminal
	// term is specific load/save terminal command, therefore skip multible command
		if (termInput.search(/\|/gi) && termInput.search(/^ ?term/i) == -1){
			termInputList = termInput.split("|");
		}
		else {
			termInputList[0] = termInput;
		} 

	//multible commands
	for (var i=0; i<termInputList.length; i++){
	termInput = termInputList[i];


	

	//load positiondata
	var regExp = new RegExp("^ ?/"); //because i need the '/' char
	if ( termInput.search( regExp ) != -1 ) {
		loadPosition( termInput );
	}
	//load moviedata
	else if (termInput.search(/^ ?#/i) != -1){
			loadMoviePosition( termInput, 0 );
	}

	//load soliddata
	else if ( termInput.search(/^ ?%/) != -1 ) {
		setSolid( termInput );
	}
	//load softdata
	else if ( termInput.search(/^ ?\^/) != -1 ) {
		setPieces( termInput );
	}
		
	//set positiondata from infoTextArea
	else if (termInput.search(/^ ?setgame|^ ?setpos/i) != -1){
		loadPosition( getTextArea() );
	}

	//set moviedata from infoTextArea
	else if (termInput.search(/^ ?setmov|^ ?setplayl/i) != -1){
		loadMoviePosition( getTextArea(), 0 );
	}

	//my personal settings
	else if ( termInput.search(/^ ?my$|^ ?epikur$/i) != -1 ) {
		ref.value = "image kfc|black a06040|white ffc080|start";
		terminal_onchange(ref);

		setMessage("my personal settings");
	}

	//term
	//load/save term command
	else if ( termInput.search(/^ ?term/i) != -1 ) {

			if (termInput.search(/save/i) != -1){
				TERMINALCOMMAND = termInput.substr(termInput.lastIndexOf("save") );
				//make sure there's something to save
				if (TERMINALCOMMAND.length > 4){ //save is 4 char long
					TERMINALCOMMAND = TERMINALCOMMAND.substr(4);
				}
				else
					alert("terminal command save: need argument to save something");					
			}
			else if (termInput.search(/load/i) != -1){
				ref.value = TERMINALCOMMAND;
				terminal_onchange(ref); //recursive
			}
			else
				alert("terminal command: load or save");
	

		setMessage("terminal load/save");
	}


	//get
	else if (termInput.search(/^ ?get$/i) != -1) {
		getBoardAndDelay();
	}
	//getdelay
	else if (termInput.search(/^ ?getdelay$/i) != -1) {
		getDelay();
	}
	//getsolid
	else if (termInput.search(/^ ?getsolid$/i) != -1) {
		getAllSolid();
	}
	//geturl
	else if (termInput.search(/^ ?get ?url$/i) != -1) {
		getUrl();
	}

	//save
	else if (termInput.search(/^ ?save$/i) != -1)
		save();
	
	//load
	else if (termInput.search(/^ ?load$/i) != -1)
		load();
	
	//list
	else if (termInput.search(/^ ?list$|^ ?ls$|^ ?txtp|^ ?tp$/i) != -1)
		txtpicture();

	//softPiecePlacement
	else if (termInput.search(/^ ?place|^ ?hp$/i) != -1){
		if (termInput.search(/^ ?place ?h/i) != -1){
			softPiecePlacement(0);
		}
		else if (termInput.search(/^ ?place ?s/i) != -1){
			softPiecePlacement(1);
		}
		else if (termInput.search(/^ ?place ?r|^ ?sp$/i) != -1){
			softPiecePlacement(2);
		}
		else {
			setMessage("soft piece placement is = " + SOFTPIECETAKE);
		}
	}

	//javascript
	else if (termInput.search(/^ ?js |^ ?javascript /i) != -1  &&  termInput.length > 3){
		var cmd = termInput.replace(/(^ ?js |^ ?javascript )(.*)/i,"$2");
		appendTextArea(++SCROLL + ": javascript command = "+ cmd +"\n");
		eval(cmd); //javascript from terminal
		setMessage("run javascript command");
	}

	//place hard chessboard field background image
	else if (termInput.search(/^ ?solid\(\d*\,\d*\,.{1}\)$/) != -1){

		var termInput = termInput.replace( "solid(", "setBackground(" );
		var termInput = termInput.replace( ")", "" );
		var c = termInput.charCodeAt( termInput.lastIndexOf(',')+1 ); 
		var termInput = termInput.substr(0, termInput.lastIndexOf(',')+1 );

		eval( termInput+c+")" );
	}
	//place soft chessboard field foreground image
	else if (termInput.search(/^ ?set\(\d*\,\d*\,.{1}\)$/) != -1){

		var termInput = termInput.replace( "set(", "put(" );
		var termInput = termInput.replace( ")", "" );
		var c = termInput.charCodeAt( termInput.lastIndexOf(',')+1 ); 
		var termInput = termInput.substr(0, termInput.lastIndexOf(',')+1 );

		eval( termInput+c+")" );
	}
	else if (termInput.search(/^ ?put\(\d*\,\d*\,.{1}\)$/) != -1){

		var termInput = termInput.replace( ")", "" );
		var c = termInput.charCodeAt( termInput.lastIndexOf(',')+1 ); 
		var termInput = termInput.substr(0, termInput.lastIndexOf(',')+1 );

		eval( termInput+c+")" );
	}
	//clear solid
	else if (termInput.search(/^ ?cs$|^ ?clearsolid$/i) != -1){
		clearBackground();
	}
	else if (termInput.search(/^ ?cleardelay$/i) != -1){
		removeDelay();
	}

	//drawGameBoardPicture
	else if (termInput.search(/^ ?picbw$/i) != -1){ //both
		drawGameBoardPicture(4);
	}
	else if (termInput.search(/^ ?pic3$/i) != -1){ //black coord
		drawGameBoardPicture(3);
	}
	else if (termInput.search(/^ ?pic2$/i) != -1){ //white coord
		drawGameBoardPicture(2);
	}	
	else if (termInput.search(/^ ?pic/i) != -1){ //normal
		drawGameBoardPicture(1);
	}

	//infoArea popup
	else if (termInput.search(/^ ?infoarea$/i) != -1){
		infoArea();
	}

	//chessImages
	else if (termInput.search(/^ ?image|^ ?kfc$/i) != -1) {
		if (termInput.search(/^ ?images? ?civ/i) != -1)
			chessImages("civ");
		else if (termInput.search(/^ ?images? ?new/i) != -1) //newstyle
			chessImages("newstyle");
		else if (termInput.search(/kfc/i) != -1) //kungfu chess
			chessImages("kfc");
		else if (termInput.search(/mychess/i) != -1) //mychess
			chessImages("mychess");
		else if (termInput.search(/^ ?images? ?norm|^ ?images? ?defa|^ ?images? ?orig/i) != -1) //default
			chessImages("default");

		else alert('terminal command: image, argument missing or argument incorrect\nkfc, new, civ, mychess, default');
	}


	//debug terminal
	else if (termInput.search(/^ ?debug/i) != -1) {		
		
		//ref.value = "set(1,2,k)|set(2,1,M)|set(2,2,m)|set(1,1,K)";
		//terminal_onchange(ref);

		//ref.value = "white 6C6148|black 343024";
		//terminal_onchange(ref);

		alert( getDelaysFromBackgroundData() );

		//listdata2screen("%o41");

		setMessage("debug");
	}

	//html-code boardpicture
	else if (termInput.search(/^ ?htm$|^ ?html$/i) != -1) {
		html(1);
	}
	else if (termInput.search(/^ ?htm2$|^ ?html2$/i) != -1) {
		html(2);
	}
	else if (termInput.search(/^ ?htm3$|^ ?html3$/i) != -1) {
		html(3);
	}
	else if (termInput.search(/^ ?htmbw$|^ ?htmlbw$/i) != -1) {
		htmlBothSides();
	}


	//remove
	else if (termInput.search(/^ ?rem.|^ ?rm.|^ ?dead$| ?rd$/i) != -1) {
		var str = termInput.substr(2);

		if (str.search(/white\b|w\b/i) != -1)
			removeSet("white");
		if (str.search(/black\b|b\b/i) != -1)
			removeSet("black");
		if (str.search(/red\b|r\b/i) != -1)
			removeSet("red");
		if (str.search(/green\b|g\b/i) != -1)
			removeSet("green");
		if (str.search(/custom\b|c\b/i) != -1)
			removeSet("custom");
		if (str.search(/all\b|a\b/i) != -1)
			positionClear();
		if (str.search(/dead\b|d\b/i) != -1){
			removeDead();
		}
		else if (termInput.search(/^ ?rd$/i) != -1){
			removeDead();
		}
	}

	//rotate
	else if (termInput.search(/^ ?rot./i) != -1) {
		if (termInput.search(/(^ ?rot.*L)|1/i) != -1)
			rotate(1);
		if (termInput.search(/(^ ?rot.*R)|2/i) != -1)
			rotate(2);
		if (termInput.search(/3/i) != -1) //mirror x
			rotate(3);
		if (termInput.search(/4/i) != -1) //mirrox y
			rotate(4);
		if (termInput.search(/(^ ?rot.*U)|5/i) != -1) //mirror xy
			rotate(5);
		if (termInput.search(/(^ ?rot.*K)|6/i) != -1) //switch king & queen for start
			rotate(6);
	}
	//mirror
	else if (termInput.search(/^ ?mir/i) != -1) {
		if (termInput.search(/x|1/i) != -1)
			rotate(3);
		if (termInput.search(/y|2/i) != -1)
			rotate(4);
		if (termInput.search(/z|3/i) != -1)
			rotate(5);
	}

	//move
	else if (termInput.search(/^ ?movl/i) != -1) {
		if (termInput.search(/1/i) != -1)
			moveRight(-1);
		else if (termInput.search(/2/i) != -1)
			moveRight(-2);
		else if (termInput.search(/3/i) != -1)
			moveRight(-3);
		else if (termInput.search(/4/i) != -1)
			moveRight(-4);
		else if (termInput.search(/5/i) != -1)
			moveRight(-5);
		else;
	}
	else if (termInput.search(/^ ?movr/i) != -1) {
		if (termInput.search(/1/i) != -1)
			moveRight(1);
		else if (termInput.search(/2/i) != -1)
			moveRight(2);
		else if (termInput.search(/3/i) != -1)
			moveRight(3);
		else if (termInput.search(/4/i) != -1)
			moveRight(4);
		else if (termInput.search(/5/i) != -1)
			moveRight(5);
		else;
	}
	else if (termInput.search(/^ ?movu/i) != -1) {
		if (termInput.search(/1/i) != -1)
			moveUp(1);
		else if (termInput.search(/2/i) != -1)
			moveUp(2);
		else if (termInput.search(/3/i) != -1)
			moveUp(3);
		else if (termInput.search(/4/i) != -1)
			moveUp(4);
		else if (termInput.search(/5/i) != -1)
			moveUp(5);
		else;
	}
	else if (termInput.search(/^ ?movd/i) != -1) {
		if (termInput.search(/1/i) != -1)
			moveUp(-1);
		else if (termInput.search(/2/i) != -1)
			moveUp(-2);
		else if (termInput.search(/3/i) != -1)
			moveUp(-3);
		else if (termInput.search(/4/i) != -1)
			moveUp(-4);
		else if (termInput.search(/5/i) != -1)
			moveUp(-5);
		else;
	}

	//insert
	else if (termInput.search(/^ ?ins/i) != -1) {
		if (termInput.search(/white\b|w\b/i) != -1)
			positionSet("white");
		if (termInput.search(/black\b|b\b/i) != -1)
			positionSet("black");
		if (termInput.search(/red\b|r\b/i) != -1)
			positionSet("red");
		if (termInput.search(/green\b|g\b/i) != -1)
			positionSet("green");
		if (termInput.search(/two\b|t\b/i) != -1)
			positionSet("twoplayer");
		if (termInput.search(/all\b|a\b/i) != -1)
			positionSet("all");
	}

	//iam
	else if (termInput.search(/^ ?iam/i) != -1){
		var color = "unknown color";

		if (termInput.search(/white|^ ?iam ?w/i) != -1){
			loadPosition( POSITION[0] );
			color="white";
		}
		else if (termInput.search(/black|^ ?iam ?b/i) != -1){
			loadPosition( POSITION[1] );
			color="black";
		}
		else if (termInput.search(/red|^ ?iam ?r/i) != -1){
			loadPosition( POSITION[2] );
			color="red";
		}
		else if (termInput.search(/green|^ ?iam ?g/i) != -1){
			loadPosition( POSITION[3] );
			color="green";
		}
		else;
		
		setMessage("iamcolor command = "+color);
	}

	//store
	else if (termInput.search(/^ ?store|^ ?frame ?rem|^ ?frame ?rev|^ ?frame ?ins|^ ?frame ?f|^ ?frame ?1|^ ?frame ?rep|^ ?frame ?rese/i) != -1){
		if (termInput.search(/new|reset/i) != -1) 
			store_reset();
		else if (termInput.search(/get/) != -1)
			alert('store get not supported in terminal, use panelbuttons');
		else if (termInput.search(/ins/) != -1)
			store_insert();
		else if (termInput.search(/^ ?store ?first|^ ?store ?1|^ ?frame ?f|^ ?frame ?1/) != -1)
			store_insertfirst();
		else if (termInput.search(/^ ?store ?rep|^ ?frame ?rep/) != -1)
			store_replace();
		else if (termInput.search(/rem/) != -1)
			store_remove();
		else if (termInput.search(/rev/) != -1)
			store_reverse();
		else
			store();
	}

	//movie
	else if (termInput.search(/^ ?movie|^ ?play$|^ ?stop$|^ ?m ?get|^ ?get ?m|^ ?getframe|^ ?speed|^ ?frame|^ ?m ?data|^ ?mdb|^ ?prev|^ ?next|^ ?beg|^ ?firs|^ ?end|^ ?last/i ) != -1){

		if (termInput.search(/^ ?movie ?count|^ ?movie ?c|^ ?frames|^ ?movie ?frames/i) != -1)
			setMessage("moviedatabase = " + GAME.length + " frames");
		else if (termInput.search(/^ ?frame\b|^ ?movie ?frame\b/i) != -1)
			setMessage("current frame = " + (MOVIEINDEX + 1) + "/" + GAME.length);
		else if (termInput.search(/^ ?movie ?g|^ ?m ?get|^ ?get ?m/i) != -1) //get movie
			getMoviePosition();
		else if (termInput.search(/^ ?stop$/i) != -1) //movie stop
			moviestop();
		else if (termInput.search(/^ ?speed/i) != -1){ //speed
			if (termInput.search(/\d/) != -1){
				var index = parseInt( termInput.match(/\d{3}|\d{2}|\d/) );
						if (index > 0)
							movieSetSpeed(index);
			}
			else
				setMessage("current moviespeed = " + (MOVIESPEED / 1000) + " sec");
		}
		else if (termInput.search(/^ ?movie ?p|^ ?play$/i) != -1)
			movieplay();
		else if (termInput.search(/^ ?movie ?rev/) != -1)
			store_reverse();
		else if (termInput.search(/^ ?beg|^ ?firs/i) != -1)
			store_get( 0 );
		else if (termInput.search(/^ ?end|^ ?last/i) != -1)
			store_get( GAME.length - 1 );
		else if (termInput.search(/^ ?next/i) != -1)
			store_get( MOVIEINDEX + 1 );
		else if (termInput.search(/^ ?prev/i) != -1)
			store_get( MOVIEINDEX - 1 );
		else if (termInput.search(/^ ?getframe/i) != -1){
				var index = parseInt( termInput.match(/\d{3}|\d{2}|\d/) );
			
					if (index > 0 && index <= GAME.length){
						store_get( index-1 );
					}
					else {
						setMessage("getframe arg invalid = " + index);
					}
			}

		
		else if (termInput.search(/^ ?movie ?db|^ ?movie ?data|^ ?m ?data|^ ?mdb/i) != -1){ //movie database
			if (termInput.search(/\d/) != -1){
				var index = parseInt( termInput.match(/\d{3}|\d{2}|\d/) );
				moviebase(index);
			}
			else {
				setMessage("Movie database size = " + MOVIE.length);
			}
		}
		else alert("movie commands: movieget, movieplay, movieframe, moviespeed<value>, moviedata<value>");
	}


	//database
	else if (termInput.search(/^ ?db/i) != -1){		
			if (termInput.search(/\d/) != -1){
				var index = parseInt( termInput.match(/\d{3}|\d{2}|\d/) );
				gamebase(index);
			}
			else
				setMessage("database command: indexnumber missing, db size is "+POSITION.length);
	}


	//kfc_mplayer support
	else if (termInput.search(/^ ?mplayer reset$|^ ?mp reset$|^ ?mp rst$/i) != -1){
		MPLAYER_VALUE = MPLAYER_COUNTER;
		setMessage("reset: kfc_mplayer timecounter");
	}
	else if (termInput.search(/^ ?mplayer speed|^ ?mp speed/i) != -1){
		if (termInput.search(/\d/) != -1){
			var index = parseInt( termInput.match(/\d{5}|\d{4}|\d{3}|\d{2}|\d/) );
			if (index > 0) {
				MPLAYER_COUNTER=index;
				setMessage("new mplayer speed =" + MPLAYER_COUNTER);
			}
			else
				setMessage("current mplayer speed = " + MPLAYER_COUNTER);
		}
		else
			setMessage("current mplayer speed = " + MPLAYER_COUNTER);

	}
	else if (termInput.search(/^ ?mplayer on$|^ ?mp on$/i) != -1){
		MPLAYER = true;
		setMessage("kfc_mplayer support on");
	}
	else if (termInput.search(/^ ?mplayer off$|^ ?mp off$/i) != -1){
		MPLAYER = false;
		setMessage("kfc_mplayer support off");
	}


	
	//background color
	else if (termInput.search(/^ ?skybl|^ ?bs$/i) != -1){
		setBGColor(SKYBLUE);
	}
	else if (termInput.search(/^ ?darkbl|^ ?bd$/i) != -1){
		setBGColor(DARKBLUE);
	}
	else if (termInput.search(/^ ?brown|^ ?bb$/i) != -1){
		setBGColor(BROWN);
	}
	else if (termInput.search(/^ ?bg/i) != -1){
		var aColor = termInput.replace(/(^ ?bg#|^ ?bg)(.*)/i,"$2");	//remove bg string prefix
		setBGColor(aColor);
	}

	//welcome message
	else if (termInput.search(/^ ?mes|^ ?wel|^ ?hint/i) != -1){
		appendTextArea(++SCROLL + ": " + WELCOMEMESSAGE + "\n");
	}

	//clear text
	else if (termInput.search(/^ ?clear ?t|^ ?clrt$|^ ?ct$/i) != -1){
		clearInfoTextArea();
	}
	//positiondata Length
	else if (termInput.search(/^ ?pdl$/i) != -1){
		positiondataLength();
	}
	//moviedata Length
	else if (termInput.search(/^ ?mdl$/i) != -1){
		moviedataLength();
	}

	//help
	else if (termInput.search(/^ ?help|^ ?man|^ ?faq|^ ?how|^ ?what|^ ?about ?m/i) != -1){
		help();
	}
	
	//epd2pd, FEN stringdata to positiondata translation
	else if (termInput.search(/^ ?epd2pd|^ ?e2p|^ ?fen2pd/i) != -1){
		epd2pd();
	}

	//positiondata
	else if (termInput.search(/^ ?positiond|^ ?gamedata$|^ ?epd|^ ?synt|^ ?rules$|^ ?code$|^ ?about ?gamed/i) != -1){
		positiondata();
	}

	//configKFC
	else if (termInput.search(/^ ?kc$|^ ?list ?kfc$|^ ?pieces? ?kfc&|^ ?kfc ?conf|^ ?conf/i) != -1){
		configKFC();
	}

	//radiobuttons
	else if (termInput.search(/^ ?clear\b|^ ?clr\b/i) != -1){
		positionClear();
	}
	else if (termInput.search(/^ ?start/i) != -1){
		positionSetStart();
	}
	else if (termInput.search(/^ ?ran/i) != -1){
		positionRandomFromBoard();
	}
	else if (termInput.search(/^ ?piec/i) != -1){
		pieces();
	}
	else if (termInput.search(/^ ?about\b|^ ?ver|^ ?epikur$/i) != -1){
		about();
	}

	//flip chessfield colors
	else if (termInput.search(/^ ?flip|^ ?fo$|^ ?fi$|^ ?fb$/i) != -1){
		if (termInput.search(/^ ?flip$|^ ?flip ?o|^ ?fo$/i) != -1)
			boardOrderFlip();
		else if (termInput.search(/^ ?flip ?i|^ ?fi$/i) != -1)
			boardFieldImage();
		else if (termInput.search(/^ ?flip ?b|^ ?fb$/i) != -1)
			boardBorderFlip();
		else 
			alert("flip command argument unknown");
	}

	//set chessfield html colors
	else if (termInput.search(/^ ?white|^ ?black/i) != -1){
		if (termInput.search(/white$/i) != -1){
			setMessage("FieldColorWhite is: " + WHITE);
		}
		else if (termInput.search(/black$/i) != -1){
			setMessage("FieldColorBlack is: " + BLACK);
		}
		else if (termInput.search(/white/i) != -1){
			var argument = termInput.substr( termInput.lastIndexOf("white")+5 );
			setFieldColorWhite(argument);
		}
		else if (termInput.search(/black/i) != -1){
			var argument = termInput.substr( termInput.lastIndexOf("black")+5 );
			setFieldColorBlack(argument);
		}
		else {
			alert("white/black command argument unknown");
		} 			
	}
	else if (termInput.search(/^ ?bluefield$/i) != -1){
		setFieldColor1();
	}

	//NOT USED
	//putPiece, put
	else if (termInput.search(/^ ?x\d{1,}y\d{1,}p/) != -1){
		var x = 1;
		var y = 1;
		var p = eF;

		termInput = termInput.substr( termInput.lastIndexOf("x") + 1);
			x = parseInt( termInput );
		termInput = termInput.substr( termInput.lastIndexOf("y") + 1);
			y = parseInt( termInput );		
		termInput = termInput.substr( termInput.lastIndexOf("p") + 1);
			p = termInput;
		alert("x="+x+ " y="+y+ " p="+p+ " typeof(p)="+typeof(p) );
		//put(x,y,p);
	}

	//burn, set foreground to background
	else if (termInput.search(/^ ?burn$/i) != -1){
		setAllForegroundToBackground();
	}


	//info
	else if (termInput.search(/^ ?inf|^ ?dimen/i) != -1){
		dimension();
	}

	//not supported
	else {
		appendTextArea(++SCROLL + ": terminal not valid\n");
		setMessage("terminal not valid");
	}

	}

	//stay focus on terminal
	terminalFocus();

	return ref;
	//return;
}





// ///////////////////////////////////////////////////////////
// DRAW THE BOARD
// ///////////////////////////////////////////////////////////

// build the board
// () -> string


function drawTable(xSize,ySize,fieldSize) {

var I = 0;
var J = ySize - 1;
var w = fieldSize;
var h = fieldSize;
var boardX = xSize;
var boardY = ySize;
var HTMLg = "";


var nameW = "white";
var nameB = "black";
var td_D = " width=\" " + w + " \" height= \" " + h  + "\"";
var td_B = " <td id=\"" + xy2line(I+1,J+1) + "\"" + td_D;


var bg_deadfield = " bgColor=\""  + PANEL + "\" background=\"" + DEADFIELD_IMG + "\">";
var bg_white  = " bgColor=\""  + WHITE + "\" background=\"" + NOPIECE + "\">";
var bg_black  = " bgColor=\""  + BLACK + "\" background=\"" + NOPIECE + "\">";
var bg_panel  = " bgColor=\""  + PANEL + "\" background=\"" + PANEL_IMG + "\">";
var borderColor = "bgColor=\"#808080\"";
var bg_color = bg_white; //first start color for field in gameboard

// Chess4player Diagram - by epikur
HTML1 += "<p><br/><b>" + THISNAME + "</b></p>";

// table screen
HTML1 +=  "<table border=\"2\" cellpadding=\"1\" cellspacing=\"1\">";
HTML1 += "<tr>";

HTML1 += "<td>";
// table pieces left panel

var leftPanelIndex = 0;
var td_PD = " width=\"" + IMGS + "\" height=\"" + IMGS + "\" ";
var td_PB = "<td " + td_PD + bg_panel + "<a href=\"javascript:pickPanel(";
var td_PB2 = td_PB;
var td_PI = ")\"><img src=\"";
var td_PE = "\"" + td_PD + "border=\"0\"></a></td>";
var td_PT = "<td " + td_PD + " bgColor=\""  + PANEL + "\"><a href=\"javascript:pickPanel(";


HTML1 +=  "<table border=\"1\" cellpadding=\"0\" cellspacing=\"0\">";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'wr'" + td_PI + wR.src + "\" id='wr' alt=\"white rook  (pieceCode=R)"  + td_PE;
HTML1 +=  td_PB + "'br'" + td_PI + bR.src + "\" id='br' alt=\"black rook  (pieceCode=r)"  + td_PE;
HTML1 +=  td_PB + "'rr'" + td_PI + rR.src + "\" id='rr' alt=\"red rook  (pieceCode=T)" + td_PE;
HTML1 +=  td_PB + "'gr'" + td_PI + gR.src + "\" id='gr' alt=\"green rook  (pieceCode=t)" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'wn'" + td_PI + wN.src + "\" id='wn' alt=\"white knight  (pieceCode=N)"  + td_PE;
HTML1 +=  td_PB + "'bn'" + td_PI + bN.src + "\" id='bn' alt=\"black knight  (pieceCode=n)"  + td_PE;
HTML1 +=  td_PB + "'rn'" + td_PI + rN.src + "\" id='rn' alt=\"red knight  (pieceCode=H)" + td_PE;
HTML1 +=  td_PB + "'gn'" + td_PI + gN.src + "\" id='gn' alt=\"green knight  (pieceCode=h)" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'wb'" + td_PI + wB.src + "\" id='wb' alt=\"white bishop  (pieceCode=B)"  + td_PE;
HTML1 +=  td_PB + "'bb'" + td_PI + bB.src + "\" id='bb' alt=\"black bishop  (pieceCode=b)"  + td_PE;
HTML1 +=  td_PB + "'rb'" + td_PI + rB.src + "\" id='rb' alt=\"red bishop  (pieceCode=C)" + td_PE;
HTML1 +=  td_PB + "'gb'" + td_PI + gB.src + "\" id='gb' alt=\"green bishop  (pieceCode=c)" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'wk'" + td_PI + wK.src + "\" id='wk' alt=\"white king  (pieceCode=K)"  + td_PE;
HTML1 +=  td_PB + "'bk'" + td_PI + bK.src + "\" id='bk' alt=\"black king  (pieceCode=k)"  + td_PE;
HTML1 +=  td_PB + "'rk'" + td_PI + rK.src + "\" id='rk' alt=\"red king  (pieceCode=M)" + td_PE;
HTML1 +=  td_PB + "'gk'" + td_PI + gK.src + "\" id='gk' alt=\"green king  (pieceCode=m)" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'wq'" + td_PI + wQ.src + "\" id='wq' alt=\"white queen  (pieceCode=Q)" + td_PE;
HTML1 +=  td_PB + "'bq'" + td_PI + bQ.src + "\" id='bq' alt=\"black queen  (pieceCode=q)" + td_PE;
HTML1 +=  td_PB + "'rq'" + td_PI + rQ.src + "\" id='rq' alt=\"red queen  (pieceCode=F)" + td_PE;
HTML1 +=  td_PB + "'gq'" + td_PI + gQ.src + "\" id='gq' alt=\"green queen  (pieceCode=f)" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'wp'" + td_PI + wP.src + "\" id='wp' alt=\"white pawn  (pieceCode=P)" + td_PE;
HTML1 +=  td_PB + "'bp'" + td_PI + bP.src + "\" id='bp' alt=\"black pawn  (pieceCode=p)" + td_PE;
HTML1 +=  td_PB + "'rp'" + td_PI + rP.src + "\" id='rp' alt=\"red pawn  (pieceCode=W)" + td_PE;
HTML1 +=  td_PB + "'gp'" + td_PI + gP.src + "\" id='gp' alt=\"green pawn  (pieceCode=w)" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'wg'" + td_PI + wG.src + "\" id='wg' alt=\"white knightbishy  (pieceCode=G)" + td_PE; //lite
HTML1 +=  td_PB + "'bg'" + td_PI + bG.src + "\" id='bg' alt=\"black knightbishy  (pieceCode=g)" + td_PE;
HTML1 +=  td_PB + "'rg'" + td_PI + rG.src + "\" id='rg' alt=\"red knightbishy  (pieceCode=U)" + td_PE;
HTML1 +=  td_PB + "'gg'" + td_PI + gG.src + "\" id='gg' alt=\"green knightbishy  (pieceCode=u)" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'wj'" + td_PI + wJ.src + "\" id='wj' alt=\"white knightrooky  (pieceCode=J)" + td_PE;
HTML1 +=  td_PB + "'bj'" + td_PI + bJ.src + "\" id='bj' alt=\"black knightrooky  (pieceCode=j)" + td_PE;
HTML1 +=  td_PB + "'rj'" + td_PI + rJ.src + "\" id='rj' alt=\"red knightrooky  (pieceCode=V)" + td_PE;
HTML1 +=  td_PB + "'gj'" + td_PI + gJ.src + "\" id='gj' alt=\"green knightrooky  (pieceCode=v)" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'cf'" + td_PI + cF.src + "\" alt=\"closed field  (pieceCode=X)" + td_PE;
HTML1 +=  td_PB + "'mf'" + td_PI + mF.src + "\" alt=\"mark field  (pieceCode=d)" + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'f3'" + td_PI + f3.src + "\" alt=\"light white  (pieceCode=z)" + td_PE;
HTML1 +=  td_PB + "'f4'" + td_PI + f4.src + "\" alt=\"ligth black  (pieceCode=Z)" + td_PE;
HTML1 +=  td_PB + "'f1'" + td_PI + f1.src + "\" alt=\"dark white  (pieceCode=y)" + td_PE;
HTML1 +=  td_PB + "'f2'" + td_PI + f2.src + "\" alt=\"dark black  (pieceCode=Y)" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'d1'" + td_PI + d1.src + "\" alt=\"delay1  (pieceCode=a)" + td_PE;
HTML1 +=  td_PB + "'d2'" + td_PI + d2.src + "\" alt=\"delay2  (pieceCode=e)" + td_PE;
HTML1 +=  td_PB + "'d3'" + td_PI + d3.src + "\" alt=\"delay3  (pieceCode=o)" + td_PE;
HTML1 +=  td_PB + "'removeDelay'" + td_PI + remd.src + "\" alt=\"remove delay" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'removeWhite'" + td_PI + remw.src + "\" alt=\"remove white" + td_PE;
HTML1 +=  td_PB + "'removeBlack'" + td_PI + remb.src + "\" alt=\"remove black" + td_PE;
HTML1 +=  td_PB + "'removeRed'"   + td_PI + remr.src + "\" alt=\"remove red" + td_PE;
HTML1 +=  td_PB + "'removeGreen'" + td_PI + remg.src + "\" alt=\"remove green" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "'removeCustom'" + td_PI + remc.src + "\" alt=\"remove custom" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'mirrorX'" + td_PI + mirx.src + "\" alt=\"mirror x" + td_PE;
HTML1 +=  td_PB + "'mirrorY'" + td_PI + miry.src + "\" alt=\"mirror y" + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'rotateLeft'" + td_PI + rotl.src + "\" alt=\"rotate left" + td_PE;
HTML1 +=  td_PB + "'rotateRight'" + td_PI + rotr.src + "\" alt=\"rotate right" + td_PE;
HTML1 +=  td_PB + "'rotateUp'" + td_PI + rotu.src + "\" alt=\"rotate up" + td_PE;
HTML1 +=  td_PB + "'rotateKing'" + td_PI + rotk.src + "\" alt=\"rotate king" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "'moveLeft'" + td_PI + movl.src + "\" alt=\"move left" + td_PE;
HTML1 +=  td_PB + "'moveRight'" + td_PI + movr.src + "\" alt=\"move right" + td_PE;
HTML1 +=  td_PB + "'moveUp'" + td_PI + movu.src + "\" alt=\"move up" + td_PE;
HTML1 +=  td_PB + "'moveDown'" + td_PI + movd.src + "\" alt=\"move down" + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PB + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PT + "'txtpic'" + ")\" onmouseover=\"setMessage('button: txt picture')\"><b>Tp</b></a></td>";
HTML1 +=  td_PT + "'kfcconfig'" + ")\" onmouseover=\"setMessage('button: kfc config')\"><b>Kc</b></a></td>";
HTML1 +=  td_PT + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  "<td " + td_PD + " bgColor=\""  + PANEL + "\" id='button_softpiece'><a href=\"javascript:pickPanel('hardplace'" + ")\" onmouseover=\"setMessage('button: toggle hardplacement')\"><b>HP</b></a></td>";
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PT + "'fliporder'" + ")\" onmouseover=\"setMessage('button: flip b/w field order')\"><b>Fo</b></a></td>";
HTML1 +=  td_PT + "'flipimage'" + ")\" onmouseover=\"setMessage('button: flip b/w image')\"><b>Fi</b></a></td>";
HTML1 +=  td_PT + "'flipboarder'" + ")\" onmouseover=\"setMessage('button: toggle boarder')\"><b>Fb</b></a></td>";
HTML1 +=  td_PT + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "<tr>";
HTML1 +=  td_PT + "'clearSolid'" + ")\" onmouseover=\"setMessage('button: clearSolid (background images and delay pieces)')\"><b>cs</b></a></td>";
HTML1 +=  td_PT + "'removeDead'" + ")\" onmouseover=\"setMessage('button: remove pieces on outarea')\"><b>rd</b></a></td>";
HTML1 +=  td_PT + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  td_PT + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  "</tr>";

HTML1 +=  "<tr>";
HTML1 +=  td_PT + "'bgSkyblue')\" onmouseover=\"setMessage('button: set backgroud skyblue')\"><i>bS</i></a></td>";
HTML1 +=  td_PT + "'bgBrown')\" onmouseover=\"setMessage('button: set backgroud brown')\"><i>bB</i></a></td>";
HTML1 +=  td_PT + "'bgDarkblue')\" onmouseover=\"setMessage('button: set backgroud dark greyblue')\"><i>bD</i></a></td>";
HTML1 +=  td_PT + "' '" + td_PI + eF.src + td_PE;
HTML1 +=  "</tr>";
HTML1 +=  "</table>";
	//end left panel
HTML1 +=  "</td>";

	
HTML1 +=  "<td>";



// table board game area
//HTMLg +=  "<table id=\"boardGame\" border=\"1\" cellpadding=\"0\" cellspacing=\"0\">";
HTMLg +=  "<table id=\"boardGame\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";

	// used for updating the I and J values to the string variables
	//local functions
	function td_Board(i,j){
		td_B = "<td id=\"" + xy2line(i+1,j+1) + "\"" + td_D;
		return td_B;
	}

	function link_img(i,j){
		//debug
		if (i >= boardX  ||  i < 0  ||  j >= boardY  ||  j < 0){
			alert("ERROR! link_img(i,j) i="+i+" j="+j);
			return;
		}
		//problems with onclick, ondblclick, a href=javascript:fn() and cancelling href call to work with
		//both mozilla and msie, I've decided to make this work with msie.
		var ln = xy2line(i+1,j+1);
		var tmp = "<a href='javascript:pickBoard("+(i+1)+","+(j+1)+")' "+
			"ondblclick='return pickDouble(" + (i+1) + "," + (j+1) + ")' onclick='' onmouseover='fieldMouseOver(" + (i+1) + "," + (j+1) + ")' onmouseout='fieldMouseOut(" + (i+1) + "," + (j+1) + ")';>"+
			"<img name='" +ln+ "' src='" + BOARD[J][I] + "' border='0' " + td_D + "></td>";

		return tmp;
	}
	
	function nolink_img(i,j){
		//debug
		if (i >= boardX  ||  i < 0  ||  j >= boardY  ||  j < 0){
			alert("ERROR! link_img(i,j) i="+i+" j="+j);
			return;
		}
		var tmp = "<a href='javascript:outArea(" + (i) + "," + (j) + ")' onclick='' onmouseover='fieldMouseOver(" + (i+1) + "," + (j+1) + ")' onmouseout='fieldMouseOut(" + (i+1) + "," + (j+1) + ")'><img name='" + xy2line(i+1,j+1) + 
					"' src='" + BOARD[J][I] + "' border='0' " + td_D + "></td>";
		return tmp;
	}
	
	//the fieldcolors startcolor at row switch
	function draw_colorFieldSwitch(){
	
		if (bg_color == bg_white)
			bg_color = bg_black;
		else if (bg_color == bg_black)
			bg_color = bg_white;
		else //debug
			alert("ERROR! in draw_colorFieldSwitch()");
	}

//<td width=38 height=38 bgColor=#cc0088 background=pic.gif><a href=javascript:fn()><img name=LN_num></a></td>

//Math.floor(IMG/2) is for reducing the number print size, better visual layout imho
var nummerizeH  = "<td align='center' style='font-size: 60%' width='"+ IMG +"' height='"+ Math.floor(IMG/2) +"' " + borderColor + " background=''><b>";
var nummerizeV  = "<td align='center' style='font-size: 60%' width=\""+ Math.floor(IMG/2) +"\" height='"+ IMG +"' " + borderColor + " background=''><b>";
var nummerizeHV = "<td align='center' style='font-size: 60%' width=\""+ Math.floor(IMG/2) +"\" height='"+ Math.floor(IMG/2) +"' " + borderColor + " background=''><b>";
var v = boardY;
var fontColor1 = "#0000aa"; //0 .. 11 printnumber color
var fontColor2 = "#000000"; //1 .. 12 printnumber color

// START DRAW BOARDFIELDS

//horizontal numbering, top row number print
HTMLg +=  "<tr>";
HTMLg +=  nummerizeHV +"</b></td>";
for (var n=1; n<=boardX; n++)
	HTMLg +=  nummerizeH + "<font color='"+fontColor1+"'>"+(n-1)+"</font>"+ "</b></td>"; //0 .. BOARDX-1 print
	//HTMLg +=  nummerizeH + "</b></td>"; //no number print
HTMLg +=  nummerizeHV + "</b></td>";
HTMLg +=  "</tr>";

//debug
if (I >= boardX  ||  I < 0  ||  J >= boardY  ||  J < 0){
	alert("ERROR! horizontal numbering, top link_img(i,j) i="+I+" j="+J);
	return;
}



//one row forloop iteration
for (var drawBoard = 0; drawBoard < boardY; drawBoard++){

//debug
if (I >= boardX  ||  I < 0  ||  J >= boardY  ||  J < 0){
	alert("ERROR! drawBoardTopCorners link_img(i,j) i="+I+" j="+J);
	return;
}

	
	HTMLg +=  "<tr>";
	//HTMLg +=  "<tr id=\"" + xy2line(I+1,ySize - J) + "\">";

	HTMLg +=  nummerizeV + "<font color='"+fontColor2+"'>"+v+"</font></b></td>"; v--; //the first number print, top left


	//DRAW X*Y FIELDS
	for (var i=0; i < boardX; i++){
		var LN_str = xy2line(I+1,J+1);
		var deadIndex = 0;
		//check if it's a deadField
		for(deadIndex = 0; deadIndex <= DEADFIELDS.length; deadIndex++){
			if (DEADFIELDS[deadIndex] == LN_str){
				HTMLg +=  td_Board(I,J) + bg_color + nolink_img(I,J);
				break;
			}
			else if (deadIndex == DEADFIELDS.length){
				HTMLg +=  td_Board(I,J) + bg_color + link_img(I,J);
				break;
			}
		}
		I++;
		//change fieldcolor for row
		draw_colorFieldSwitch();
	}

	//number print right col
	HTMLg +=  nummerizeV + "<font color='"+fontColor1+"'>"+(boardY-1 - v)+"</font>"+ "</b></td>";  //0 .. BOARDY-1 print
	//HTMLg +=  nummerizeV + "</b></td>";  //no numbers
	
	HTMLg +=  "</tr>";									J--;I=0;


	 //due to rowsize and fieldcolor value switch logic
	if(even(BOARDX) )
		draw_colorFieldSwitch();
}


									 
//horizontal letter numbering, bottom of gameboard
HTMLg +=  "<tr>";
HTMLg +=  nummerizeHV + "</b></td>";
for (var n=1; n<=boardX; n++)
//	HTMLg +=  nummerizeH + "<font color='"+fontColor2+"'>"+ HORIZONTALCHARS[BOARDX-n] + "</font></b></td>";// black point of view
	HTMLg +=  nummerizeH + "<font color='"+fontColor2+"'>"+ HORIZONTALCHARS[n-1] + "</font></b></td>";
HTMLg +=  nummerizeHV + "</b></td>";
HTMLg +=  "</tr>";


//END DRAW BOARDFIELDS




//txt just above the game table
HTMLg +=  "</table>";

//



	// TXT BELOW GAME TABLE
	HTML2 +=  "<form language=\"JavaScript\" name=\"middleForm\">";
		HTML2 +=  "<input type=\"text\" class=\"GUItextCoordinate\" name=\"coordinate\" size=\"60\" ondblclick=\"this.value='the field coordinate';\" onclick=\"blur()\"><br/>";
		HTML2 +=  "<input type=\"button\" class=\"GUIbuttonMiddle\" name=\"buttonClear\" value=\"CLEAR\" onclick=\"positionClear()\">&nbsp;";
		HTML2 +=  "<input type=\"button\" class=\"GUIbuttonMiddle\" name=\"buttonStart\" value=\"START\" onclick=\"positionSetStart()\">&nbsp;";
		HTML2 +=  "<input type=\"button\" class=\"GUIbuttonMiddle\" name=\"buttonRandom\" value=\"RANDOM\" onclick=\"positionRandomFromBoard()\">&nbsp;"; //lite
		HTML2 +=  "<input type=\"button\" class=\"GUIbuttonMiddle\" name=\"buttonPieces\" value=\"PIECES\" onclick=\"pieces()\">&nbsp;";
//		HTML2 +=  "<input type=\"button\" class=\"GUIbuttonMiddle\" name=\"buttonPiecesKFC\" value=\"kfc-config\" onclick=\"configKFC(BOARD)\">&nbsp;";
		HTML2 +=  "<input type=\"button\" class=\"GUIbuttonMiddle\" name=\"buttonAbout\" value=\"ABOUT\" onclick=\"about()\"><br/><br/>";
		HTML2 +=  "<input type=\"text\" class=\"GUItext\" name=\"infoHelp\" size=\"60\" ondblclick=\"this.value='infoHelp telling you what youre doing';\" onclick=\"blur()\"><br/>";
	HTML2 +=  "</form>";


	//end the board game area
	HTML2 +=  "</td>";


	HTML2 +=  "<td>";
	//right panel
HTML2 +=  "<table border=\"1\" cellpadding=\"0\" cellspacing=\"0\" width=\"300\">"; //opera7 seems to need width value

HTML2 +=  "<form name=\"rightForm\">";
	HTML2 +=  "<select class=\"GUIselect\" name=\"selPosition\" size=\"1\" onchange=\"selPosition_onchange()\">";

		HTML2 +=  "<option value=\"defaultSelect\" selected> Options Menu (click)";
		HTML2 +=  "<option value=\"welcomeMessage\">01 - Welcome message";

		HTML2 +=  "<option value=\"-1\">";
		HTML2 +=  "<option value=\"position4player\">11 - Position: 4Player";
		HTML2 +=  "<option value=\"position2player\">12 - Position: 2Player  (db5)";
		HTML2 +=  "<option value=\"positionRandomFromBoard\">13 - Position: Random (ran)";

		HTML2 +=  "<option value=\"-1\">";
		HTML2 +=  "<option value=\"imageDefault\">21 - Image: Default (imagedefa)";
		HTML2 +=  "<option value=\"imageKfc\">22 - Image: Kfc (imagekfc)";
		HTML2 +=  "<option value=\"imageNewstyle\">23 - Image: Newstyle";
		HTML2 +=  "<option value=\"imageMychess\">24 - Image: Mychess";
		HTML2 +=  "<option value=\"imageCiv\">25 - Image: Civ";

		HTML2 +=  "<option value=\"-1\">";
		HTML2 +=  "<option value=\"insertWhite\">31 - Insert: pos white (insw)";
		HTML2 +=  "<option value=\"insertBlack\">32 - Insert: pos black (insb)";
		HTML2 +=  "<option value=\"insertRed\">33 - Insert: pos red";
		HTML2 +=  "<option value=\"insertGreen\">34 - Insert: pos green";
		HTML2 +=  "<option value=\"epd2pd\">35 - Load: insert FEN or EPD data";
		HTML2 +=  "<option value=\"textareapd\">36 - Load: use positiondata from textarea";
		HTML2 +=  "<option value=\"textareamoviepd\">37 - Load: use moviedata from textarea";

		HTML2 +=  "<option value=\"-1\">";
		HTML2 +=  "<option value=\"burn\">41 - Feature: Burn pieces to background";
		HTML2 +=  "<option value=\"clearsolid\">42 - Remove: Background images (cs)";
		HTML2 +=  "<option value=\"removedead\">43 - Remove: Pieces on outarea (rd)";

		HTML2 +=  "<option value=\"-1\">";
		HTML2 +=  "<option value=\"pieces\">51 - List: pieces on the board";
		HTML2 +=  "<option value=\"boardinfo\">52 - List: boardinfo";
		HTML2 +=  "<option value=\"configkfc\">53 - List: Config data for Kfc game";
		HTML2 +=  "<option value=\"html\">54 - List: Generate Html-code (html)";
		HTML2 +=  "<option value=\"pic\">55 - Popup: preview html-code (pic)";
		HTML2 +=  "<option value=\"help\">56 - Popup: user manual";
		HTML2 +=  "<option value=\"pd\">57 - Popup: pd manual (positiondata)";


	HTML2 +=  "</select><br/>";
	HTML2 +=  "<textarea class=\"GUItextarea\" rows=\"20\" cols=\"36\" name=\"infoTextArea\" value=\"\" wrap=\"soft\" onkeypress=\"infoArea_checkKeyPress(event)\">";
		HTML2 +=  WELCOMEMESSAGE;
	HTML2 +=  "</textarea><br/>";

	HTML2 +=  "<input type=\"button\" class=\"GUIbutton\" name=\"clearInfo\" value=\"Clear Text\" onclick=\"clearInfoTextArea()\">&nbsp;";
	HTML2 +=  "<input type=\"button\" class=\"GUIbutton\" name=\"storeAdd\" value=\"store\" onclick=\"store()\">"; //lite
	HTML2 +=  "<input type=\"button\" class=\"GUIbutton\" name=\"storeNew\" value=\"store reset\" onclick=\"store_reset()\"><br/>";
	HTML2 +=  "<input type='button' id='playButton' class='GUIbuttonSpecial' name='play' value='play' onclick='switchAutoPlay()'>&nbsp;";
	HTML2 +=  "<input type=\"button\" class=\"GUIbuttonMovie\" name=\"beg\" value=\"beg\" onclick=\"store_get(0)\">";
	HTML2 +=  "<input type=\"button\" class=\"GUIbuttonMovie\" name=\"end\" value=\"end\" onclick=\"store_get(GAME.length-1)\">";
	HTML2 +=  "<input type=\"button\" class=\"GUIbuttonMovie\" name=\"prev\" value=\"prev\" onclick=\"store_get( MOVIEINDEX - 1 )\">";
	HTML2 +=  "<input type=\"button\" class=\"GUIbuttonMovie\" name=\"next\" value=\"next\" onclick=\"store_get( MOVIEINDEX + 1 )\"><br/>";
	HTML2 +=  "<input type='button' class='GUIbuttonPositiondata' name='get' value='get' onclick='getBoardAndDelay()'>";
	HTML2 +=  "<input type=\"button\" class=\"GUIbuttonPositiondata\" name=\"movieget\" value=\"movieget\" onclick=\"getMoviePosition()\">";
	HTML2 +=  "<input type='button' class='GUIbuttonPositiondata' name='geturl' value='get url' onclick='getUrl()'>&nbsp;&nbsp;";

	//cant remove this one, else the terminal will misfunction, dummy text type
	HTML2 +=  "<input type=\"text\" name=\"movieIndex\" value=\"\" class=\"GUItext2\" size=\"4\" onclick=\"blur()\" ondblclick=\"\">";

	HTML2 +=  "<br/>";
	HTML2 +=  "<b>Terminal</b><br/>";
	HTML2 +=  "<input type=\"text\" name=\"terminal\" size=\"34\" value=\"\" onkeypress=\"terminal_checkKeyPress(event)\" onclick=\"terminalFocus()\" ondblclick=\"this.value=getBoardAndDelay();\">";
	HTML2 +=  "<input type=\"button\" class=\"GUIbutton\" name=\"terminalDO\" value=\"DO\" onclick=\"terminal_onchange( d.rightForm.terminal );\">";

HTML2 +=  "</form>";
HTML2 +=  "</table>";
	//end right panel

	//end screen table
	HTML2 +=  "</td>";
	HTML2 +=  "</tr>";
	HTML2 +=  "</table>";
	HTML2 += "<br/><br/><br/><br/><br/><br/>"; //opera7 layout problem


	return HTMLg;

//end function drawTable
}













// ///////////////////////////////////////////////////////////
// event -> true
function terminal_checkKeyPress(e) {
	e = (e) ? e : ((window.event) ? window.event : "");
	/*
		If the event object arrives as a parameter, 
		it remains assigned to the evt local variable inside the function.
		But if the parameter is null and the browser's window object includes an event property,
		then the window.event object assigns itself to the e variable.
	*/


	if (e){ 
	
		var keycode = e.keyCode;

		//debug
		//setMessage("keycode="+keycode);

		if (keycode == 13) { //enter key
			terminal_onchange( d.rightForm.terminal );
		}
		
		else if (keycode == 27){ //escape key
			d.rightForm.infoTextArea.focus();
		} 

		else{
		} 
			
		return;
	}
}

function infoArea_checkKeyPress(e) {
	e = (e) ? e : ((window.event) ? window.event : "");

	if (e){ 

		var keycode = e.keyCode;

		//debug
		//setMessage("keycode="+keycode);

		
		if (keycode == 27){ //escape key
			terminalFocus();
		} 

		else{
		} 
	}

	return;
}


function terminalFocus(){
	d.rightForm.terminal.focus();
	d.rightForm.terminal.select();
}


// ///////////////////////////////////////////////////////////
function isCharANumber(c){
	return (c.charCodeAt(0) >= 48  &&  c.charCodeAt(0) <= 57);
}


//remove head from data
function removeHeadFromString( s ){


	
	var res = s;
	if ( res.length > 1 )
		res = res.substr(1);
	else
		res = "";

	return res;
}




//return sec
function secTaken(objDate){
	return (objDate.getMilliseconds()/1000);
}



// ///////////////////////////////////////////////////////////
// cookie functions
// load save game

function getCookieValue(cookieName){

	var cookieValue = document.cookie;
	var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "=");
	
	if (cookieStartsAt == -1)
		cookieStartsAt = cookieValue.indexOf(cookieName + "=");
	if (cookieStartsAt == -1)
		cookieValue = null;
	else {
		cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1;
		var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt);
		if (cookieEndsAt == -1)
			cookieEndsAt = cookieValue.length;
		cookieValue = unescape(cookieValue.substring(cookieStartsAt,cookieEndsAt));
	}

	return cookieValue;
}

function setCookie(cookieName, cookieValue, cookiePath, cookieExpires){

	cookieValue = escape(cookieValue);
	
	if (cookieExpires == ""){
		var nowDate = new Date();
		nowDate.setMonth(nowDate.getMonth() + 6);
		cookieExpires = nowDate.toGMTString();
	}

	if (cookiePath != "")
		cookiePath = ";Path=" + cookiePath;
	
	document.cookie = cookieName + "=" + cookieValue + ";expires=" + cookieExpires + cookiePath;
}

function checkCookie(){

	var hasACookie = false;

	var cookieValue = getCookieValue("myDatalist");
	if (cookieValue != null){
		//alert('you have a savegame = ' + cookieValue);
		hasACookie = true;
	}
	else {
		setCookie("myDatalist",getPosition(),"","");
		alert('no savegame stored');
		hasACookie = false;
	}
	
	return hasACookie;
}


function load(){
	if ( checkCookie() );
	loadPosition( getCookieValue("myDatalist") );
	setMessage("position loaded");
}

function save(){
	setCookie("myDatalist",getPosition(),"","");
	setMessage("position saved");
}




// ///////////////////////////////////////////////////////////
// Array functions, add or remove elem to array object


// array,elem -> index of elem placement in array
function arrayIndex(theArray, theElement){
	var index = -1;
	for (var i=0; i<theArray.length; i++){
		if (theElement == theArray[i]){
			index = i;
			break;
		}
	}		
	return index;
}



function arrayInsert(arrayObject, index, arrayElem){

	var newArrayObject = new Array();

	//array object is empty
	if (arrayObject.length == 0){
		newArrayObject[0] = arrayElem;
	}

	//array object is not empty
	else if (index < arrayObject.length && index >= 0){
	
		//check array elem type
		//if ( typeof(arrayObject[0] != toString(arrayElem) ) ){
		//	alert("arrayObject and arrayElem mismatch in arrayInsert()");
		//}
		
		//copy all before including index (insert, not replace)
		for (var i=0; i<=index; i++){
			newArrayObject[i] = arrayObject[i];
		}
		//insert new elem here
		newArrayObject[index+1] = arrayElem;
		//copy all after index
		for (var i=index+1; i< arrayObject.length; i++){
			newArrayObject[i+1] = arrayObject[i];
		}
	}

	//value off error
	else{
		alert("array.length and index mismatch in arrayInsert()");
	}

	return newArrayObject;
}


function arrayRemove(arrayObject, index){

	var newArrayObject = new Array();

	if (arrayObject.length == 0){
		alert("array is empty, cant remove in arrayRemove()");
	}

	else if (index < arrayObject.length && index >= 0){
		//copy all except the index
		for (var i=0; i < arrayObject.length - 1; i++){
			if (i < index)
				newArrayObject[i] = arrayObject[i];
			else
				newArrayObject[i] = arrayObject[i+1];
		}
	}

	else{
		alert("array.length and index mismatch in arrayRemove()");
	}

	return newArrayObject;
}



// is the number even?
// int -> bool
function even(num){	
	return (num%2 == 0);
}

function stringReverse(str) {
   if (!str) return "";
   var revstr="";
   for (var i = str.length-1; i>=0; i--)
       revstr+=str.charAt(i)
   return revstr;
}



//????????????????????????????????????????????
//QueryString main method, collection array of QueryString

	function QueryString(key)
	{
		var value = null;
		for (var i=0;i<QueryString.keys.length;i++)
		{
			if (QueryString.keys[i]==key)
			{
				value = QueryString.values[i];
				break;
			}
		}
		return value;
	}
	QueryString.keys = new Array();
	QueryString.values = new Array();


	function QueryString_Parse()
	{
		var query = window.location.search.substring(1);
		var pairs = query.split("&");
		
		for (var i=0;i<pairs.length;i++)
		{
			var pos = pairs[i].indexOf('=');
			if (pos >= 0)
			{
				var argname = pairs[i].substring(0,pos);
				var value = pairs[i].substring(pos+1);
				QueryString.keys[QueryString.keys.length] = argname;
				QueryString.values[QueryString.values.length] = value;		
				if (argname == "pd")
					PD=value;
				else if (argname == "epd")
					EPD=value;
				else if (argname == "term"){
					TERM=value;
					TERM = unescape(TERM);
				}
				else if (argname == "x"){
					var x = parseInt(value);
					if(typeof(x)=="number"  &&  x>0)
						BOARDX=x;
				}
				else if (argname == "y"){
					var y = parseInt(value);
					if(typeof(y)=="number"  &&  y>0)
						BOARDY=y;
				}
				else if(argname == "size"){
					var i = parseInt(value);
					if(typeof(i)=="number"  &&  i>0)
						IMG=i;
				}	
				else if(argname == "nodead"){					
					DEADFIELDS = new Array(); //clear deadfields
				}
				else if (argname == "txt"){
					TXT=""+unescape(value);
				}
				else if (argname == "mplayer"){
					MPLAYER=true;
				}

			}
		}

	}
//????????????????????????????????????????????


// ///////////////////////////////////////////////////////////
// onload page
// make the board


//dynamic
function initBoardDynamic(boardx,boardy,img){
	if (boardx>0)
		BOARDX=boardx;

	if (boardy>0)
		BOARDY=boardy;
	
	if (img>0)
		IMG=img;

	initBoard();
}


//static
function initBoard(){

	QueryString_Parse(); //get parsed link values if any
	board(BOARDX,BOARDY); //init the BOARD[][]

	updatePieceSources();
	emptyBoard(); //set the pieceinfo for the board to empty, needed by the html build, drawTable()
	
	var HTML = drawTable(BOARDX,BOARDY,IMG);
	var HTMLALL = HTML1 + HTML + HTML2; //initiate the images.name for the board and HTML values
	d.write( HTMLALL ); //make the html
	
	deadFieldsMake( DEADFIELDS );
	


	//parsed terminal
	if (TERM!="") {
		setTerminal(TERM);
		terminal_onchange(d.rightForm.terminal);
	}	
	//terminal command on start
	else if (TERMINALSTART!=undefined && TERMINALSTART!="") {
		setTerminal(TERMINALSTART);
		terminal_onchange(d.rightForm.terminal);
	}

	//parsed position
	if (PD!="") {
		positionSet(PD);
	}
	//parsed position
	else if(EPD!=""){
		var pd = epd2pdMake(EPD); 
		setTerminal(pd);
		terminal_onchange(d.rightForm.terminal);
	}
	 //positiondata init position	
	else if (STARTPOSITION!=undefined && STARTPOSITION!="") {
		positionSet(STARTPOSITION);
	}

	//parsed txt to textarea
	if (TXT!="") {
		setTextArea(TXT);
	}


	
	//alert("loading...");
	terminalFocus();
	
	setMessage("initBoard");
	return;
}


// ///////////////////////////////////////////////////////////
//exament the html code for the chess4player GUI in the textarea
function htmlDebug(){ //NOT USED
	var htmlstr = "";
	var regExp = new RegExp("<","g");
	var regExpMover = new RegExp("onmouseover","g");
	var regExpMout  = new RegExp("onmouseout","g");

	htmlstr += drawTable(BOARDX,BOARDY,IMG);

	//htmlstr = htmlstr.replace(regExpMover,"onMOver_null");
	//htmlstr = htmlstr.replace(regExpMout,"onMOut_null");
	htmlstr = htmlstr.replace(regExp,"\n<");
	
	setTextArea(htmlstr);
}


function html(mode){
	date = new Date();
	setMessage("generating html code...plz wait");

	var epdstr = "<!-- Chess Picture, epd value\n"; 
	var epd = "";
	epd = getBoth();
	epdstr += epd + "\n" + "//-->\n";

	var html = htmlMake(mode);

	setTextArea(epdstr+html);
	setMessage("html code done, time sec = "+secTaken(date));
}


//white and black POV
function htmlBothSidesMake(){
	var htm = "";
	htm += "<table><tr><td>";
	htm += htmlMake(2); //white
	htm += "</td><td width='90' align='left'><img  src='images/whitehat.gif' width='50' height='40' alt=''>";
	htm += "</td><td width='90' align='right'><img src='images/blackhat.gif' width='50' height='40' alt=''></td><td>";

	//flip board up
	rotate(5); //xy flip	

	htm += htmlMake(3); //black
	htm += "</td></tr></table>";
	
	//rotate back to normal
	rotate(5); //xy flip

	return htm;
}

function htmlBothSides(){
	date = new Date();
	setMessage("generating html code...plz wait");

	var epdstr = "<!-- Chess Picture, epd value\n"; 
	var epd = "";
	epd = getBoth();
	epdstr += epd + "\n" + "//-->\n";

	var html = htmlBothSidesMake();

	setTextArea(epdstr+html);
	setMessage("html code for both sides done, time sec = "+secTaken(date));
}



//This Page Is Valid HTML 4.01 Transitional!
function htmlMake(mode){
	//mode, coordinates letters type, mode==1 then just numbers, mode==2 then white pov, mode==3 then black pov

	var size = IMG;
	var html = "";
	var bgcolor = "";
	var background = ""; //img url
	var subfolder = "../";
	var foreground = "";
	var astyle = "style='text-decoration:none'";
	var bordervalue = d.getElementById("boardGame").getAttribute("border"); //fetch the border attribut value

	//Math.floor(size/2) is for reducing the number print size, better visual layout imho
	var bordercol = "bgColor='#808080'";
	var colh = "#990000"; //hori col //cccc00
	var colv = "#0000aa"; //vert col
	var small = Math.floor(size/2);
	var numh  = "<td align='center' style='font-size: 70%;color:"+colh+"' width='"+ size +"' height='"+ small +"' " + bordercol+ ">";
	var numv  = "<td align='center' style='font-size: 70%;color:"+colv+"' width='"+ small +"' height='"+ size +"' " + bordercol+ ">";
	var numhv = "<td align='center' style='font-size: 70%' width='"+ small +"' height='"+ small +"' " + bordercol+ ">";

	//START  HTML BUILD
	//html += "</pre>"; //custom added thml
	html += "<!-- COPY BELOV, chessboard picture //-->\n";
	html +=  "<table border='"+bordervalue+"' cellpadding='0' cellspacing='0'>";
	
	//number hori
	html+="<tr>";
	html+= numhv + "&nbsp;</td>"; //first cell is topleft empty
	for (var x=0; x<BOARDX; x++ ){
		if (mode==1)      html+= numh + "<b>" +x+ "</b></td>";
		else if (mode==2) html+= numh + "<b>" + HORIZONTALCHARS[x].toUpperCase() + "</b></td>"; //real chessboard coords white;
		else			  html+= numh + "<b>" + HORIZONTALCHARS[BOARDX-1-x].toUpperCase() + "</b></td>"; //real chessboard coords black;
	}
	html+="</tr>"


	for (var j=BOARDY-1; j>=0; j-- ){ //iterate all board and get foreground, background image
		html+= "<tr>";

		if (mode==1)      html+= numv + "<b>" + (BOARDY-j-1) + "</b></td>"; //number vert
		else if (mode==2) html+= numv + "<b>" + (j+1) + "</b></td>"; //number vert //real chessboard coords white
		else              html+= numv + "<b>" + (BOARDY-j) + "</b></td>"; //number vert //real chessboard coords black

		for (var i=0; i<BOARDX; i++ ){
			bgcolor = ( ((i % 2) + j) % 2) == 1  ? WHITE : BLACK; //right color select method
			background = getBackground( xy2line(i+1,j+1) );
			foreground = getForeground( xy2line(i+1,j+1) ).src;

			//cut as relative path
			background = background.substr(background.lastIndexOf("images") );
			foreground = foreground.substr(foreground.lastIndexOf("images") );
			//background = subfolder +background.substr(background.lastIndexOf("images") ); //files in a folder
			//foreground = subfolder +foreground.substr(foreground.lastIndexOf("images") );
			
			td = "<td width='" +size+ "' height='" +size+ "'  bgColor='" +
				bgcolor+ "' style='background-image:url(" +background+ ")'>"+ //this is valid html-transitional
				//bgcolor+ "' background='" +background+ "'>"+
					"<img src='" +foreground+ "' width='" +size+ "' height='" +size+ "' alt=''>";	
			
			html+=td;
			html+="</td>";

		}
		html+="</tr>"
	}


	html += "</table>";
	html += "\n<!-- COPY ABOVE, chessboard picture //-->";
	//html += "<pre>"; //custom added thml

	return html;
}

