/*
 * This function parses comma-separated name=value argument pairs from
 * the query string of the URL. It stores the name=value pairs in 
 * properties of an object and returns that object.
 */
function getArgs() {
    var args = new Object();
    var query = location.search.substring(1);  // Get query string.
    var pairs = query.split(",");              // Break at comma.
    for(var i = 0; i < pairs.length; i++) {
	var pos = pairs[i].indexOf('=');       // Look for "name=value".
	if (pos == -1) continue;               // If not found, skip.
	var argname = pairs[i].substring(0,pos);  // Extract the name.
	var value = pairs[i].substring(pos+1); // Extract the value.
	args[argname] = unescape(value);          // Store as a property.
    }
    return args;                               // Return the object.
}

/*
 * We could have used getArgs() in the previous bouncing window example
 * to parse optional animation parameters from the URL.
 */
var args = getArgs();                 // Get arguments.
if (args.x) x = parseInt(args.x);     // If arguments are defined...
if (args.y) y = parseInt(args.y);     // ... override default values.
if (args.w) w = parseInt(args.w);
if (args.h) h = parseInt(args.h);
if (args.dx) dx = parseInt(args.dx);
if (args.dy) dy = parseInt(args.dy);
if (args.interval) interval = parseInt(args.interval);

//---------------#ban initialize--------------------;
function banini() {
	ban= new Array(21*21);
	for (jj=0;jj<21;jj++) {
		for (ii=0;ii<21;ii++) {
			if ((jj==0)||(jj==20)||(ii==0)||(ii==20)) { ban[ii+jj*21]=3;}
			else { ban[ii+jj*21]=0; }
		}
	}	
	hama = new Array(0,0,0);
	kou = 0;
	teban = 1;	
	tenum=0;
}

//--------# &poscheck(*ban, $teban, $posx, $posy, *kou, *hama)------;
 function poscheck(teban,posx,posy,kou,hama) {
	agepos = new Array(0);		//new return parameter(last tori()); 	
	nxt= new Array(1,-1,21,-21);
	var kk=0;
	var teki = 3 - teban;		//if teban=1 then teki=2; 
	var pos = posx + posy * 21; 
	var koupos = 0;
	var sc = 0;					//sc=0--->tonari aki nasi;
	var tc = 0;					//tori isi count;
	var mc = 0;					//mc=0--->tonari zenbu teki;	
	var flag = 0;				//flag=0--->ren no aki mo nasi;  
	if (ban[pos] != 0) { return (0);}		//isi ari;
	if (kou == pos) {return(0);}			//zenkai= kou;
	for (kk=0;kk<nxt.length;kk++) {
		if (ban[pos+(nxt[kk])] == 0) { sc=1;flag=1;}	//tonari aki;
	}
 	ban[pos] = teban;			//kari oki;
	// tonari tori
	for(kk=0;kk<nxt.length;kk++) { 	
		if (ban[pos + nxt[kk]] == teki) {					
		 	if (dame( pos + nxt[kk], teki) == 0) {koupos = pos + nxt[kk]; tc += tori( pos + nxt[kk], 0); flag = 1;}
    		else {modosi( pos + nxt[kk], teki);}			
		}
   	}	

	for (kk=0;kk<nxt.length;kk++) {	
	   if (ban[pos + nxt[kk]] == teban) {
	  		mc = 1;
			if (flag == 0) {
	    		if (dame( pos + nxt[kk], teban) != 0) {flag = 1;} //tonari ren dame ari
	     		modosi( pos + nxt[kk], teban);
	     	}
	   }
	}

  if (flag == 0) { 
    ban[pos] = 0;				//kari oki hagasi =>jisatu te;
  } else {
    hama[teban] += tc;			//hama count;
    if ((sc == 0) && (tc == 1) && (mc == 0)) {
      	kou = koupos;				// (tonari=akinasi,tori=1, tonari=zenbuteki) =>  kou!;
    } else {
    	kou = 0;
    }
  }

return (flag);				//flag=1(OK!) flag =0 (jisatute or kou not OK); 
}


//  &dame(*ban, $pos, $teban);
//  local(*ban, $pos, $teban) = @_;
function dame(pos,teban) {
	var dd = 0;
	for (dd=0;dd<nxt.length;dd++) {
		ban[pos] = 6;
  		if (ban[pos + nxt[dd]] == 0) {return (1);} 
  		if ((ban[pos+nxt[dd]]!= 0) && (ban[pos + nxt[dd]] == teban)) {
    		if (dame( pos + nxt[dd], teban) != 0) {return (1);}
  		}
  	}
	return (0);          // tonari=akinasi,tonari=mikata,ren dama=akinasi==>return(0);
}

//  &tori(*ban, $pos, $tc);
//  local(*ban, $pos, $tc) = @_;
function tori(pos,tc) {
	var tt=0;
	var	agey= Math.floor(pos/21);
	var agex=pos-21*agey;
	agepos=agepos.concat(agex,agey);
	 ban[pos] = 0;
	for (tt=0;tt<nxt.length;tt++) {
		if (ban[pos + nxt[tt]] == 6) {tc = tori( pos + nxt[tt], tc);}
	}
	 return (tc + 1);	// tori count;
}


//  &modosi(*ban, $pos, $isi);
//  local(*ban, $pos, $isi) = @_;
function modosi(pos,isi) {
	var mm=0;
	ban[pos] = isi;
	for (mm=0;mm<nxt.length;mm++) {
		if (ban[pos + nxt[mm]] == 6) {modosi( pos + nxt[mm], isi);}
	}  
}
//-----------function for Scoring-------------------------------;
//Aki Count;
function space() {				//output=jikazu(aki,kuroji,siroji);
/*
//	sban =new Array(21*21);		//for copy of ban(21*21);
//	jikazu=new Array(0,0,0);		//(aki,kuroji,siroji);
//	nxt= new Array(1,-1,21,-21);
//	var kazu=0;
//	bflg=0;
//	wflg=0;
//	sban=ban;		//copy from poscheck goban;
//	for (ii=0;ii<21;ii++) {
//		for (jj=0;jj<21;jj++) {
//			pos=ii+jj*21;		
//			sban[pos]=ban[pos];
//		}	
//	}
*/

	ii=0;jj=0;
	for (ii=1;ii<=19;ii++) {
		for (jj=1;jj<=19;jj++) {
			pos=ii+jj*21;
			bflg=0;wflg=0;
			iflg=0;
//			akict=0;		//over flow protect max=(19*13);
			if (sban[pos]==0) {							//aki-area check;
				aki(pos);						// check if surrounded by black or white;
				if ((bflg==4)&&(wflg==0)) {iflg=bflg;}
				if ((bflg==0)&&(wflg==5)) {iflg=wflg;}
				if (iflg!=0) {							//sarounded;
					kazu=0;
					jimark(pos);				//turn to kuro or siro-ji mark;
					jikazu[iflg-3]=jikazu[iflg-3]+kazu;		//jikazu=(check,kuro.siro);
				}
			}
		}
	}	
	//check mark no modosi (sini isi wo tori nozoku tokino jyunbi);
	for (ii=1;ii<=19;ii++) {
		for (jj=1;jj<=19;jj++) {
			pos=ii+jj*21;
			if (sban[pos]==9) { sban[pos]=0;}
		}
	}			
}

function aki(pos) {
var kk=0;
	if (sban[pos]==0) {sban[pos]=9;}						//9=check mark;
	for (kk=0;kk<nxt.length;kk++) {
		npos=pos+nxt[kk];
		if (sban[npos]==0)  {aki(npos);}
		if ((sban[npos]==1)||(sban[npos]==4)) {bflg=4;}		//for kuro torinozoki fool safe; 
		if ((sban[npos]==2)||(sban[npos]==5)) {wflg=5;}		//for siro torinozoki fool safe;
	}	
}

function jimark(pos) {
	var ll=0;
	if (sban[pos]==9) {
		sban[pos]=iflg;				// turn to kuro,siro-ji
		var	posy= Math.floor(pos/21);
		var posx=pos-21*posy;
		zahyo='Z'+sgfco[posx-1]+sgfco[posy-1];
		if (iflg==4) {document.images[zahyo].src=sblk.src;}
		if (iflg==5) {document.images[zahyo].src=swht.src;}

		kazu=kazu+1;
	}								//count kuro,siro-ji;
	for (ll=0;ll<nxt.length;ll++) {
		if (sban[pos+nxt[ll]]==9) {
			jimark(pos+nxt[ll]);}
	}		
}	

//----------function remove of dead stone-------------------------;

function takeout(pos) { 		//pos=(1-19)+(1-19)*21;
//	sban= new Array(21,21);
//	sban=ban;
//	var tc = 0;
	agepos = new Array(0);		//new return parameter(last tori()); 	
	nxt= new Array(1,-1,21,-21);
	if ((sban[pos]==1)||(sban[pos]==2)) {
		ageisi=sban[pos];
		renage(pos);
//		hama[ageisi]+=tc;
	}
}

function renage(pos) {
	var kk=0;
	var	agey= Math.floor(pos/21);
	var agex=pos-21*agey;
	agepos=agepos.concat(agex,agey);
//	tc=tc+1;
	ageisi=sban[pos];			//b=1,w=2;
	sban[pos]=0;
	hama[3-ageisi]+=1;		//if ageisi=1(b)->hama[2],2(w)->hama[1];
	for (kk=0;kk<nxt.length;kk++) {
		if (sban[pos+nxt[kk]]==ageisi) {renage(pos+nxt[kk]);}
		if (sban[pos+nxt[kk]]==ageisi+3) {jimodosi(pos+nxt[kk]);}		//ji modosi;
	}
}

function jimodosi(mod) {
	var mm=0;
	modosiji=sban[mod];		//ji b=4, w=5;
	sban[mod]=0;
	jikazu[modosiji-3] -=1;

	var	posy= Math.floor(mod/21);
	var posx=mod-21*posy;
	zahyo='Z'+sgfco[posx-1]+sgfco[posy-1];
	document.images[zahyo].src=empty.src;

	for (mm=0;mm<nxt.length;mm++) {
		if (sban[mod+nxt[mm]]==modosiji) {
			jimodosi(mod+nxt[mm]);
		}
	}
}

//------reset of visibility of stone (all hidden)-----------------;
function allhide() {
		for (ii=1;ii<=19;ii++) {
			for (jj=1;jj<=19;jj++) {
				if ((ban[ii+jj*21])!=0) {
					ban[ii+jj*21]=0;
					zahyo='Z'+sgfco[ii-1]+sgfco[jj-1];
					document.images[zahyo].src=empty.src;		//png/empty.gif';
				}
			}	
		}
}

function bansim(ten) {
	if (sg) { 
		if (ten >= sg.length) {ten=sg.length;}
		if (ten <= 0) {ten=0;}
	} else { ten=0;	}
	tenum=0;

	if (ten==0) {					//all reset;
		for (ii=1;ii<=19;ii++) {
			for (jj=1;jj<=19;jj++) {
				if ((ban[ii+jj*21])!=0) {
					ban[ii+jj*21]=0;
					zahyo='Z'+sgfco[ii-1]+sgfco[jj-1];
					document.images[zahyo].src=empty.src;		//png/empty.gif';
				}
			}	
		}
		hama= new Array(0,0,0);
		kou=0;
		teban=1;
	}
	if((ten==0)&&(addsg)) {				//okiishi set;
		for (ii=0;ii<addsg.length;ii++) {
			bw = addsg[ii].match(/W|B/);
        	if (bw == 'W') {teban=2;}
			if (bw == 'B') {teban=1;}
			pos=addsg[ii].match(/[a-s][a-s]/);
			posx=pos[0].charCodeAt(0)-96;		//a=1;
			posy=pos[0].charCodeAt(1)-96;
			poscheck(teban,posx,posy,kou,hama);
		}
	}
	if(ten >= 1) {									//move after play;
		for (ii=0;ii< sg.length;ii++) {					
//			bw = sg[ii].match(/W|B|AW|AB/);	
			bw = sg[ii].match(/W|B/);
			
			if (tenum < ten) {
        		if (bw == 'W') {teban=2; tenum++;}
				if (bw == 'B') {teban=1; tenum++;}
//				bw=sg[ii].match(/W|B/);
				pos=sg[ii].match(/[a-s][a-s]/);
				posx=pos[0].charCodeAt(0)-96;		//a=1;
				posy=pos[0].charCodeAt(1)-96;
				poscheck(teban,posx,posy,kou,hama);
			}	
		}
	}
}

//----------------isi display------------------------;
// all isi display;
//
function isidsp() {
	for (ii=1;ii<=19;ii++) {
		for (jj=1;jj<=19;jj++) {
			if ((ban[ii+jj*21])!=0) {
				zahyo='Z'+sgfco[ii-1]+sgfco[jj-1];			
				if (ban[ii+jj*21]==1) {document.images[zahyo].src=blk.src;}
				if (ban[ii+jj*21]==2) {
					rnd = Math.floor((3-1+1) * Math.random() + 1);
					if(rnd == 2){document.images[zahyo].src=whtc.src;}
					else if(rnd == 1){document.images[zahyo].src=whtb.src;}
					else{			document.images[zahyo].src=wht.src;	}
				}
			}
		}	
	}
}

//-----------ban itte move-------------------------------------;
function banitte(teban,posz) {
	var flag=0;
	posx=posz.charCodeAt(0)-96;
	posy=posz.charCodeAt(1)-96;
	zahyo='Z'+posz;

	if (poscheck(teban,posx,posy,kou,hama)) {
		flag=1;
		if (ban[posx+posy*21]==1) {
		document.images[zahyo].src=blk.src;
		}
		if (ban[posx+posy*21]==2) {
			//document.images[zahyo].src=wht.src;
			rnd = Math.floor((3-1+1) * Math.random() + 1);
			if(rnd == 2){document.images[zahyo].src=whtc.src;}
			else if(rnd == 1){document.images[zahyo].src=whtb.src;}
			else{			document.images[zahyo].src=wht.src;	}
		}
		if (agepos.length > 0){
			for (ii=0;ii<agepos.length;ii += 2) {
				agex=agepos[ii];
				agey=agepos[ii+1];
				zahyo='Z'+sgfco[agex-1]+sgfco[agey-1];
				document.images[zahyo].src=empty.src;
			}
		}
	}
	return(flag);			
}	
//------------------Last New move display---------------------------;
function lastmv(ten,step) {				//B&W:stepback=1 / BorW:stepback=2;
	if(ten>0) {
		pos=sg[ten-1].match(/[a-s][a-s]/);
		zahyo='Z'+pos[0];
		bw=sg[ten-1].match(/W|B/);
		if (bw=='B') {document.images[zahyo].src=nblk.src;}
		if (bw=='W') {document.images[zahyo].src=nwht.src;}
	}
	bk=step;
	for (ii=1;ii<=bk;ii++) {
		ten=ten-1;
		if(ten-1>=0) {
			pos=sg[ten-1].match(/[a-s][a-s]/);
			posz=pos[0];
			zahyo='Z'+pos[0];
			posx=posz.charCodeAt(0)-96;
			posy=posz.charCodeAt(1)-96;
			if (ban[posx+posy*21]==1) {	document.images[zahyo].src=blk.src;}
			if (ban[posx+posy*21]==2) {
				//document.images[zahyo].src=wht.src;
					rnd = Math.floor((3-1+1) * Math.random() + 1);
					if(rnd == 2){document.images[zahyo].src=whtc.src;}
					else if(rnd == 1){document.images[zahyo].src=whtb.src;}
					else{			document.images[zahyo].src=wht.src;	}

			}
		}
	}
}
//---------------------red guide mark display for next move-----------------;
function gmark(setfl) {		//gbgn=guide top, gend=guide end; set(setfl=1)/reset(setfl=0);
	if (tumego!='yes') {
		if (gbgn>=sg.length) {gbgn=sg.length-1;}	//追加2004-06-19
		if (gend>=sg.length) {gend=sg.length-1;}	//追加2004-06-19

		if ((ten<=gbgn) || (ten>=gend)){		//reset previous guide mark;
			for (kk=gbgn;kk<=gend;kk++) {
				pof=sg[kk].match(/[a-s][a-s]/);
				pofz=pof[0];
				pofx=pofz.charCodeAt(0)-96;
				pofy=pofz.charCodeAt(1)-96;
				if (ban[pofx+pofy*21] == 0 ) {
					zahyo='Z'+pofz;
					document.images[zahyo].src=empty.src;
				}
			} 
			gbgn=ten;
			gend=ten;
		}

		if ((setfl==1)&&(ten>=gbgn)) {			//new guide mark;
			fd= Math.floor(Math.random() * 8)*2+2;	//rand of 2,4,6,..
			if (ten+fd >= sg.length) {fd=sg.length-ten-1;}
				gbgn=ten;
				gend=fd+ten;
					for(kk=gbgn;kk<=gend;kk++) { 
						pof=sg[kk].match(/[a-s][a-s]/);
						pofz=pof[0];
						pofx=pofz.charCodeAt(0)-96;
						pofy=pofz.charCodeAt(1)-96;
						if (ban[pofx+pofy*21] == 0 ) {
							zahyo='Z'+pofz;
							document.images[zahyo].src=sred.src;
						}
					}
		}
	}
}

//==========sgftext to array conversion============================;
function sgfarray(sgftext) {		
//	sgftext=document.test.tarea.value;

	if (!sgftext) {sgftext='';}
	sgfline=sgftext.replace(/\r\n|\n/g,"$@");			//for comment(\r\n) ;
	sgftext=sgftext.replace(/\r\n|\n/g,'');
	if (sgftext.match(/;(Black|White)\[\w\w\]/)) {
		sgftext=sgftext.replace(/AddBlack\[/g,"AB\[");
		sgftext=sgftext.replace(/AddWhite\[/g,"AW\[");
		sgftext=sgftext.replace(/Black\[/g,"B\[");
		sgftext=sgftext.replace(/White\[/g,"W\[");
		sgftext=sgftext.replace(/Comment\[/g,"C\[");
		sgfline=sgfline.replace(/AddBlack\[/g,"AB\[");
		sgfline=sgfline.replace(/AddWhite\[/g,"AW\[");
		sgfline=sgfline.replace(/Black\[/g,"B\[");
		sgfline=sgfline.replace(/White\[/g,"W\[");
		sgfline=sgfline.replace(/Comment\[/g,"C\[");
		sgfline=sgfline.replace(/\(\$\@/g,"\(");
		sgfline=sgfline.replace(/\;\$\@/g,"\;");
	}	

//----array of addstone befor start---------------;
	addbtext='';
	addwtext='';
//	adbsg=sgftext.match(/AB([\[a-s\]]+?)[^\[a-s\]]/);		//in case Perl match;
//	adbsg=sgftext.match(/AW([\[a-s\]]+?)[^\[a-s\]]/);
//	adbsg=sgftext.match(/[^;]AB(\[\w\w\])+/);				//in case JavaScript;
//	adwsg=sgftext.match(/[^;]AW(\[\w\w\])+/);

	adbsg=sgftext.match(/AB(\[\w\w\])+/);	
	adwsg=sgftext.match(/AW(\[\w\w\])+/);		

	if (adbsg) {
		adbsg=adbsg[0].match(/(\[.+?])+/g);
		addbtext=adbsg[0].replace(/(\[\w\w\])/g,";AB$1");
	}
	if (adwsg) {
		adwsg=adwsg[0].match(/(\[\w\w\])+/g);
		addwtext=adwsg[0].replace(/(\[\w\w\])/g,";AW$1");
	}
	addsgtext = addbtext+addwtext;
	addsg = addsgtext.match(/;(AW|AB)\[\w\w\]/g);	//;AB[xy];AW[vw]->OK;
//	addsg = (;AB[aa];AB[bb];...;AW[gh];AW[ij]..);
//---array of move after start---------------------; 

	sg = sgftext.match(/;(W|B|AW|AB)\[\w\w\]/g);	//no branch type sgf;

//--------------top coment  before start---------------------;
	sgfline=sgfline.replace(/^\(\$\@;/,'\(;');
	comtop=sgfline.match(/\(;(.+?);/);
	comtop=RegExp.$1;
	comtop=comtop.replace(/(AB|AW)(\[\w\w\])+/g,'');
	comtop=comtop.replace(/\]\$\@/g,'\]');		//xx[..]\r\n;
	comtop=comtop.replace(/\]/g,'\]\$\@');
	comtop=comtop.replace(/\$\@/g,"\r\n");

//---------- coment after start-------------------------------;
	comsg=new Array();	
//	sgfline=sgfline.replace(/\r\n|\n/g,"$@");	
	complay=sgfline.match(/;[B|W|AW|AB]\[.+/);	//start=;B|;W  last =")";
	if (complay) {
		comsg=complay[0].match(/(.*?)[\;|\)]/g);		//comsg[ii]="...;" or "...)";
		for (ii=0;ii<comsg.length;ii++) {
			comtemp=comsg[ii].match(/C\[.+?\]/);
			if (!comtemp) {
				comsg[ii]='';
			}	else	{
				 comsg[ii]=comtemp[0].replace(/\$\@/g,"\r\n");
			}
		}
	}	
}

//================Button Control==================================;
//---------replay control----------------------------;
//nn=0-----ReLaod(reading kifu and goto end);
//nn=1-----start from first move;
//nn=2-----move back;
//nn=3-----move forward;
//nn=4-----goto end without re-reading kifu;
//nn=6----Write;

function replay(nn) {
	//alert(mode+"+"+nn);
	keyc=1;					// utu: keyc=0 & no comment increase;
	if ((nn == 6)&&(mode==0)) {
//		allhide();
		dt=new Date();
		dy=dt.getYear();
		dm=dt.getMonth();
		dm=dm+1;
		dd=dt.getDate();
		sgftext="(;GN[bodobiew];DT[" + dy + "/" +dm+ "/"+ dd +"]\n"
		ten=document.control.repnum.value;
			for (ii=0; ii<ten;ii++) {
				sgftext=sgftext+sg[ii];
				if ((ii+1) % 10 == 0) {sgftext=sgftext+"\n";}
			}
			sgftext=sgftext + ")\n";
			document.sgf.kifu.value=sgftext;
			
		if (ten==0)  {
			sg = new Array('');
			document.control.repnum.value=0;
		} 
	}	


//ReLoad;
	if ((nn == 0)&&(mode!=1)) {
//	if ((nn==0)&&(mode==0)) {
		if (mode==4) { mode=3;}	//UpLoad mode-->Make mode;
		sgfcheck = document.sgf.kifu.value;			//if new kifu-->textarea;
		sgfcheck = sgfcheck.replace(/\r\n|\n/g,'');
		if (sgfcheck) {
			if (sgfcheck.match(/;B|;W/)) {
				sgftext=sgfcheck;			//Kifu Change!;
				allhide();
				sgfarray(sgftext);
				document.sgf.kifu.value=comtop;
				ten=0;
				banini();
				bansim(ten);
//				isidsp();
				ten=sg.length;
				bansim(ten);
				isidsp();
				document.control.repnum.value=ten;				
			} else {				
					sgfarray(sgftext);
					ten=0;
					bansim(ten);
					isidsp();
					document.control.repnum.value=ten;
//					ten=document.control.repnum.value;
//					if (ten>sg.length) {ten=sg.length;}
//					bansim(ten);
//					isidsp();
			}
		}		
	}	

// to bigin;
	if ((nn == 1)&&((mode==0)||(mode==2)||(mode==3))) {
//	if ((nn==1)&&(mode!=1)) {
//	if ((nn==1)&&(mode==0)) {

			if (sg) {
//				playstart();
				ten=0;
				bansim(ten);
				isidsp();
				document.control.repnum.value=0;
//				ten=0;
	}
//alert(addsg)
	}
// to the end;
	if ((nn == 4)&&((mode==0)||(mode==2)||(mode==3))) {
//	if ((nn==4)&&(mode==0)) {
//		playstart();
		ten=0;
		bansim(ten);
		if (sg) {ten=sg.length;} 	
//		ten = eval(document.control.maxnum.value);
		bansim(ten)	//ten=max;
		isidsp();
		document.control.repnum.value=ten;
	}
	
// backword;
	ten=eval(document.control.repnum.value) ;
	if ((nn == 2)&&((mode==0)||(mode==2)||(mode==3))&&(ten!=0)) {
//	if ((nn==2)&&(mode==0)&&(ten=!0)) {
//		playstart();
		ten=0;
		bansim(ten);
		ten = eval(document.control.repnum.value)-1;
//		maxnum=eval(document.control.maxnum.value);
		maxnum=sg.length;
		if (ten>maxnum) {ten=maxnum;}
		if (ten<0) {ten=0;} 
		bansim(ten)	//ten=max;
		isidsp();
	}

//forword;
	if ((nn == 3)&&((mode==0)||(mode==2)||(mode==3))&&(sg)) {
//	if ((nn==3)&&(mode==0)&&(sg)) {
////		banini();
		ten=eval(document.control.repnum.value) ;
		
		if (ten+1<=sg.length) {
			ten=ten+1;
			bw=sg[ten-1].match(/W|B/);
			if (bw == 'W') {teban=2;}
			if (bw == 'B') {teban=1;}
			pos=sg[ten-1].match(/[a-s][a-s]/);
			posz=pos[0];
			banitte(teban,posz);
			document.control.repnum.value=ten;	
		  }
	}

//Jump
	if ((nn == 5)&&((mode==0)||(mode==2)||(mode==3))) {
//	if ((nn=5)&&(mode==0)) {
//		playstart();
		ten=0;
		bansim(ten);
		ten = eval(document.control.repnum.value);
//		maxnum=eval(document.control.maxnum.value);
		if (sg) {maxnum=sg.length;} else {maxnum=0;}
		if (ten>maxnum) {ten=maxnum;}
		if (ten<0) {ten=0;} 
		bansim(ten)	//ten=max;
		isidsp();
	}

	

//---------end of button control-----------------; 

	hitcom='';
	putform();
	
}

//==========================================================;
//---------------- utu:isi put on board------------------;
//
//mode:0=view&study,1=score; 2=next, 3=make;
//
function utu(ipos) {				//ipos=0-360;
	keyc=0;			// Button control:keyc=1 for comment change;
	
		jj=Math.floor(ipos/19);
		ii=ipos - jj*19;
		posz=sgfco[ii]+sgfco[jj];
		pos=(ii+1)+(jj+1)*21;			//for ban,sban;
		ten=eval(document.control.repnum.value);
		if (!sg) {sg =new Array(); ten=0; }

		//hitcom='';
		//hitcom='dummy';
//------------------------tsumero!------------------------;
	if ((mode==2)&&(sg.length>=1)&&(ten<sg.length))  { 
		if (sg[ten].match(/B/)) {teban=1;}		//black;
		if (sg[ten].match(/W/)) {teban=2;}		//white;
		sgfhit='['+posz+']';
		reg=sg[ten].match(/\[\w\w\]/);
		if (reg==sgfhit) {
			hitcom="atari !";
			atari=atari+1;
			banitte(teban,posz);
			if (!document.control.bdhit[0].checked) {
//			if (!document.control.bdhit.checked) {

  				if (ten+1<sg.length) {
					ten=ten+1;
					bw=sg[ten].match(/W|B/);
					if (bw == 'W') {teban=2;}
					if (bw == 'B') {teban=1;}
					pos=sg[ten].match(/[a-s][a-s]/);
					posz=pos[0];
					banitte(teban,posz);
				}
			 }
			if (ten+1<=sg.length) {
				ten=ten+1;
			}
			document.control.repnum.value=ten;
			if (ten+1<sg.length) {
			//teban mark 
				if(teban == 1){	document.teban.src = twht.src;}
				else{			document.teban.src = tblk.src;}
			}
		}
		else {
			hitcom="hazure!";
			hazure=hazure+1;
		}
	}
//------------------------no of guide move display--------------;
////		if(!tumego) {					//in case of tumego:tumego='yes'; 
//			fd= Math.floor(Math.random() * 8)*2+2;			//rand of 2,4,6,8..16 
//			if (ten+fd > sg.length) {fd=sg.length-ten-1;}
//			rfrm=ten;					//for memory to reset;
//			rend=fd+ten;
//							
//			for(kk=0;kk<=fd;kk++) { 
//				pof=sg[ten+kk].match(/[a-s][a-s]/);
//				pofz=pof[0];
//				pofx=pofz.charCodeAt(0)-96;
//				pofy=pofz.charCodeAt(1)-96;
//				if (ban[pofx+pofy*21] == 0 ) {
//					zahyo='Z'+pofz;
//					document.images[zahyo].src=sred.src;
//				}
//			}	
////		}
//		ope=1;			//show guid mark;
//		gmark(ten,ope);
//	}
	

//--------------------make------------------------------------;
	if (mode==3) { 
	utufl=1;							//for comment torikomi;
	ten=eval(document.control.repnum.value);
		if (document.control.set[0].checked) {
			if (document.control.bws[0].checked) {
				teban=1;
				addbtext=addbtext+';B['+posz+']';
				banitte(teban,posz);
			}
			if (document.control.bws[1].checked) {
				teban=2;
				addwtext=addwtext+';W['+posz+']';
				banitte(teban,posz);		
	 		}
		}
		if (document.control.set[1].checked) {
			teban=3-teban;			
			if (document.control.bws[0].checked && (ten==0) ) { teban=1; }
			if (document.control.bws[1].checked && (ten==0) ) { teban=2; }
			if (teban==1) {sgfadd=';B['+posz+']';} else {sgfadd=';W['+posz+']';}
//				ten=ten+1;
				banitte(teban,posz);
				sg[ten]=sgfadd;
				sgftext="";
				for (ii=0;ii<sg.length;ii++) {
					sgftext=sgftext+sg[ii];
				}	
//				sgftext=sgftext+sgfadd;		
				ten=ten+1;

		}
	
	
	addsgtext=addbtext+addwtext;
	addsg=addsgtext.match(/\;(W|B)\[\w\w\]/g);
	document.control.repnum.value=ten;
	}
	
//------------------------------------------------------------------;		
	if (mode==0) {					//mode:0=view&study,1=score; 2=next, 3=make;
		if (sg.length>0) {
		if (document.control.bdhit[1].checked) {teban=3-teban;}		// Oki-Isi;
			if ((ten==0)&&(sg[0].match(/W/))) {teban=1;}		//start from B or W;
			if ((ten==0)&&(sg[0].match(/B/))) {teban=2;}
		} else {teban=2;}
		
		ten=ten+1;
		teban=3-teban;
		if (banitte(teban,posz)) { 			//if OK;
			if (teban==1) {sgfadd=';B['+posz+']';}
			if (teban==2) {sgfadd=';W['+posz+']';}

			if (sgtext='') {sg='';}
//			if (sg.length) {
				if (ten > sg.length) {
					sg=sg.concat(sgfadd);
//					sg=sg.push(sgfadd);
				} else {
					sg[ten-1]=sgfadd;
				}
				if (modify==-1) {modify=ten-1;}	//for mode change (study=>next);
				//			}		
		} else {				// if not OK;
			teban=3-teban; 
			ten=ten-1;
		} 

	} else if (mode==1) {								//scoring;
		takeout(pos);
		if (agepos.length > 0){
			for (ii=0;ii<agepos.length;ii += 2) {
				agex=agepos[ii];
				agey=agepos[ii+1];
				zahyo='Z'+sgfco[agex-1]+sgfco[agey-1];
					document.images[zahyo].src=empty.src;
			}
		}
		space();
	}
//------------------------------------------------------------------;	

	putform();
}

//-----------------------------------------------------------------;
function putform() {
	
	document.control.repnum.value=ten;			// te number;
	if (mode==0) {
		//document.control.keisan.value='Study';
			if (ten==0) {
				//document.sgf.kifu.value=comtop;
			} else if ((keyc==1)&&(ten < comsg.length)) {
				//document.sgf.kifu.value=comtop+comsg[ten];
				document.sgf.kifu.value=comsg[ten];
			}
			step=1;
			lastmv(ten,step);
			
	} 
	if (mode==1) { 
		score= new Array(0,0,0);
		msg=new Array(0,0,0);
		score[1]=hama[1]+jikazu[1];score[2]=hama[2]+jikazu[2];

		msg[0]= "Black :"+score[1]+" ("+jikazu[1]+" + hama:"+hama[1]+")";
		msg[1]= "White :"+score[2]+" ("+jikazu[1]+" + hama:"+hama[2]+")";
		d = score[1] - score[2];
		if(d < 0){
			d = d*(-1);
			result = 'W+'+d;
		}
		else{		result = 'B+'+d;	}
		msg[2]= "Result : "+ result;
		document.sgf.kifu.value=msg[0]+"\r\n"+msg[1]+"\r\n"+msg[2];
		//document.control.keisan.value='Scoring';
	} 
	
//-----------------next mode---------------------------;
	if ((mode==2)&&(sg)) {
		//document.control.keisan.value='Next';		
		//if(ten==0) {			//scoring for net mode-->hit rate display;
		//	comtemp=comtop;
		//}
		//else {
			comtemp=comsg[ten];
/*
			if (hitcom==''){				// inc/dec/Jump;
				comtemp=comsg[ten];
			}
			else if (hitcom=='atari !') {
				comtemp= '';
				for (ii=1;ii<=ten;ii++) {				
					if (comsg[ii]!='') {
						//comtemp=comtemp+comsg[ii]+"\r\n";
						//comtemp=comtemp+comsg[ii];
						comtemp = comsg[ii];
					}
				}			
			}
*/

		//}
		//comtemp=comtemp.replace(/$@/,"\r\n");

		document.control.repnum.value=ten;
// Netscape エラー対応2004-06-19
// http://sb.xrea.com/showthread.php?threadid=6289

//		if ((hitcom != 'hazure!')&&(ten>0)) {	//if atari! or null;
		if ((document.hitcom != 'hazure!')&&(ten>0)) {	//if atari! or null;
			if (!document.control.bdhit[0].checked) {step=2;}else{step=1;}
			lastmv(ten,step);
		}
			ten = eval(document.control.repnum.value);	
					if ( ten >= sg.length) {
						hitcom= "End";
					}
			
			//document.control.keisan.value=hitcom;
			if(hitcom == 'atari !'){
				document.hit.src=ok.src;
			}
			else if(hitcom == 'hazure!'){
				document.hit.src=ng.src;
			}
			else {
				document.hit.src=no.src;
			}
/*
		if ((hitfl==0)&&(ten==0)) {document.sgf.kifu.value=comtop;}	
		if ((hitfl==0)&&(ten!=0)) {
			//document.sgf.kifu.value=comtop+"\r\n"+comtemp;
			document.sgf.kifu.value = comtemp;
			//if(comtemp != ''){	alert(comtemp);	}			
		}	
*/

//		if (hitfl==1) {
// Netscape エラー対応2004-06-19
// http://sb.xrea.com/showthread.php?threadid=6289
		if (document.hitfl==1) {
			if(comtemp != ''){
				comtemp = comtemp.replace(/C\[/g,"");
				comtemp = comtemp.replace(/\]/g,"");
				document.sgf.kifu.value = comtemp;
				document.hit.src=guide.src;
				//window.status = comtemp;	//ステータスバーにコメント表示
				//alert(comtemp);
			}
			else{
				document.sgf.kifu.value = '';
			}
    		document.control.p1.value = atari;
    		document.control.p2.value = hazure;
		}	
		setfl=1;
		gmark(setfl);
	}
//--------------------------make mode------------------------------;
	if ((sg)&&(mode==3)) {
		//document.control.keisan.value='Make';
		temp=document.sgf.kifu.value;
		if (((ten==0)||((ten==1)&&(!addsg))) && (temp=='')&&(utufl==1)) {	
			comsg= new Array();
			com='黒白先では？'; comsg[0]='C['+com+']'; comtop='';
			gn=gn=new Array();gn[0]='次の一手';

				dt=new Array(); 
				dd = new Date();
				yy = dd.getYear();
				mm = dd.getMonth() + 1;
				dd = dd.getDate();
				if (yy < 2000) { yy += 1900; }
				if (mm < 10) { mm = "0" + mm; }
				if (dd < 10) { dd = "0" + dd; }
				dt[0]=yy + "/" + mm + "/" + dd;
//			}
//				document.sgf.kifu.value='GN['+gn[0]+']\r\nDT['+dt[0]+']\r\nC['+com+']\r\n';
		}
		
		if ((ten==1) && (gn||dt)  && (utufl==1)) {
			gn=temp.match(/GN\[(.*)?\]/m);	//ten==0 for change of GN and DT;
			if (gn) {gn[0]=RegExp.$1;} 
			dt=temp.match(/DT\[(.*)?\]/m);
			if (dt) {dt[0]=RegExp.$1;}
			comtop=temp.match(/C\[(.*?)\]/m);	//
			if (comtop) {com=RegExp.$1;}
			if (com=='黒白先では？') {
				if (teban==1) { com='黒先では？';} else {com='白先では？';}
			}
			if(comtop) {comsg[0]='C['+com+']';}
		}

		if((ten>1)&&(utufl==1)) {								//read coment		
			if (document.sgf.kifu.value == '') { 
				comsg[ten-1]=''; 
			} else {
				temp=temp.replace(/\r\n/gm,"\$\@");
				temp=temp.replace(/C\[(.*)?\]/m,RegExp.$1);
				temp=temp.replace(/\$\@/g,"\r\n");				
				comsg[ten-1]='C['+temp+']';
			}
		}
		temp=document.sgf.kifu.value;
		temp=temp.match(/GN\[.*\]/);	
		if ((ten==0) && (!temp) && (gn)) {
//			document.sgf.kifu.value='GN['+gn[0]+']\r\nDT['+dt[0]+']\r\nC['+com+']\r\n';
			document.sgf.kifu.value='GN['+gn[0]+']\r\nDT['+dt[0]+']\r\n'+comsg[0]+'\r\n';
		}
		if (ten >=1) {
			if (comsg[ten]) {	
				temp=comsg[ten];
				temp=temp.replace(/C\[/,"");
				temp=temp.replace(/\]$/,"");
				document.sgf.kifu.value=temp;	
			}	
			if (!comsg[ten]) {document.sgf.kifu.value="";}
		}
	utufl=0;

	}	
}
			
//================scoring=================================;
function scoring() {
//	if ((mode==0)||(mode==2)) {
//	if (mode!=1) {	
	if(mode==0) {
		mode=1;
		sban =new Array(21*21);		//for copy of ban(21*21);
		jikazu=new Array(0,0,0);		//(aki,kuroji,siroji);
		nxt= new Array(1,-1,21,-21);
		for (ii=0;ii<21;ii++) {
			for (jj=0;jj<21;jj++) {
				pos=ii+jj*21;		
				sban[pos]=ban[pos];
			}	
		}
		space();
		putform();
	}
	else if (mode==1) {
		mode=0; 
		for (ii=0;ii<21;ii++) {
			for (jj=0;jj<21;jj++) {
				pos=ii+jj*21;		
				zahyo='Z'+sgfco[ii-1]+sgfco[jj-1];
				if ((sban[pos]==4)||(sban[pos]==5)) {
					document.images[zahyo].src=empty.src;
				}
			}
		}
		replay(5);		//jump to repnum;
	}
	if (mode==2) {
		if(hitfl==0) {hitfl=1;}else{hitfl=0;}
		//if (hitfl==1) {	hitcom='Scoring';}
		//if (hitfl==0) {hitcom='Next mode';}
	}
	putform();
}
//====================================================;
function study() {     		   //Study mode=0 <---->Next mode=2;
	if (mode==2) {
		mode=0;
		//document.control.keisan.value='Study';
		document.control.bdhit[0].click();			//B&W;
		setfl=0;
		gmark(setfl);	
		modify=-1;			//add stone at study mode;
	} else {
		if (mode==0) {
			mode=2;
			//document.control.keisan.value='Next';
    		document.control.bdhit[1].click();			//BorW;	
			//document.chgmode.src=next.src;
			sgfarray(sgftext);		//Reset sg of study mode;
				ten=0;
				bansim(ten);
				ten=eval(document.control.repnum.value);
				if (modify!=-1) {ten=modify;}			//modify at study mode;
				if (ten<0) {ten=0;} 
				if (ten>sg.length) {ten=sg.length;}
				bansim(ten);
				isidsp();
				document.control.repnum.value=ten;
			setfl=1;
			gmark(setfl);
		}		
	}
	putform();
}	
//=========================Double reset=====================;
function dblreset() {
	if ((mode==3)&&(sg)) {
			if (sg.length>0) {
//				playstart();
				ten=0;
				bansim(ten);
				isidsp();
				document.control.repnum.value=0;
				ten=0;
				sg.length=0;
			} else {	
				allhide(); 
				addsg.length=0;
				addsgtext=''; addbtext=''; addwtext='';
				if (comsg) {comsg.length=0;}
				sgftext='';
				document.sgf.kifu.value='';
			}
	}		
}

//==================================================================;
// by hide-w
function watch() {
	ss = 0;
	mm = 0;
	hp = 0;
	x = 0;
	tid = setTimeout('watch()', 1000);
	sec += 1;
	mm = Math.floor(sec/60);
	ss = sec % 60;
	if(ss < 10){	ss = "0" + ss;	}
	document.control.time.value = mm + ":" + ss;
	x = atari - hazure + 1;
	if(x <= 0){		x = 1;	}
	hp = limit - Math.floor(sec/x);
	document.control.point.value = hp;

	//replay(3);	//一手進めてみる。

	//for(i=1;;) {	window.status = '*';	}
	if(hp <= 0){
		clearTimeout(tid);
		document.hit.src = owa.src;		//Time Over!
		//document.createStyleSheet('ngstyle.css');
				//↑Netscape 7 ではエラーになる。
		alert('Time over!');
	}
	else if(hitcom == 'End'){
		clearTimeout(tid);
		//document.createStyleSheet(stylename);
		//document.bgColor="00ff00";
		//document.hit.src = end.src;		//Game Clear!
		//alert('Clear!\nO : '+atari+'\nX : '+hazure+'\nT : '+sec);
		//alert('Clear!\n');
	}
	if(hp <= 0 || hitcom == 'End'){
		if(document.control.url.value != ''){
			uri = document.control.url.value;
		}
		else{
			if(document.control.day.value != ''){
				day = document.control.day.value;
			}
			else{
				td = new Date()
				day = td.getDay()
			}
			uri = "./result.cgi?w="+day+"&r="+atari+"_"+hazure+"_"+sec;
		}		
		location.href = uri;
	}
}

