grid = new Array (400);
var leftCol, rightCol, topRow, bottomRow,  thisRow, thisCol, deltaR, deltaC
var startR, startC, rLast, cLast, thisRef, searchedWord
function helpWait(uid){
	btn=document.getElementById('b'+uid)
	btn.disabled=true;
	document.body.style.cursor='wait';
	func='help("' + uid + '")';
	//debugger
	setTimeout(func, 50)
}
function clearWait(uid) {
	btn=document.getElementById('b'+uid)
	btn.disabled=false;
	document.body.style.cursor='auto';
}



function help(uid){
	//alert("help for " + uid);
	// If there is a partial word, we need to find out if it can be expanded
	// into a word that isn't yet found. If it is only one character long, we need to try all directions.
	// If the partial word is OK, we need to add the next character
	// If the partial word is a dud or does not exist,
	// we need to delete it and provide the first character of a valid word.
	formName=uid 
	wordSoFar=document[formName]["wordSoFar"].value
	cellsSoFar=document[formName]["cellsSoFar"].value
	leftCol=parseInt(document[formName]["leftCol"].value)
	rightCol=parseInt(document[formName]["rightCol"].value)
	topRow=parseInt(document[formName]["topRow"].value)
	bottomRow=parseInt(document[formName]["bottomRow"].value)
	if (wordSoFar.length == 0){ //only if help is first click
		startNewWord(uid);
		clearWait(uid)
		return
	}
	else{
		//alert('not the first click')
		nextCell=checkWord(uid)
		if (typeof(nextCell) != "object"){
			startNewWord(uid);
			clearWait(uid)
			return
		}
		else{
			//debugger
			checkAnch(nextCell,uid)
			clearWait(uid)
			return
		}
	}		
}


function startNewWord(uid){
	//alert("newWord")
	t1=document.getElementById('words'+uid);
	trs=t1.rows
	wordRows=trs.length
	str="";
	for (r=0; r < wordRows; r++){//these will be word and number found so far as pairs
		uifr=uid + 'r' + r
		uiff=uid + 'f' + r
		w = document.getElementById(uifr).innerHTML
		lc = document.getElementById(uiff).innerHTML
		if (lc == 0){break;}
	}
	//new word is w, find where this word is in the grid
	//alert('need to find ' + w)
	scanGrid(uid)
	findWord(w)
	ref=uid + 'r' + thisRow + 'c' + thisCol
	//alert(w + " " + ref)
	obj=document.getElementById(ref)
	//alert(typeof(obj) + " id=" + obj.id + "  object is:" + obj + " checkAnch follows")
	checkAnch(obj,uid)
}

function findWord(w){	// finds the word 'w' in the grid, setting thisRow and thisCol
	//alert("findWord(w), w= " + w)
	for (r=topRow; r<=bottomRow; r++){
		for (c=leftCol; c<= rightCol; c++){
			i=1*(r*20 + c)*1;
			L=grid[i];
			//alert("newSearchPoint " + L + " at " + r + " " + c +'  ('+ i +')')
			if(w.charAt(0) == L){ //worth persuing)
				wordLength=w.length
				//alert(w + " searching after first letter, " + L + " length= " + wordLength)
				//calculate if there is enough room to left, right, up and down
				rightroom=false; leftroom=false; uproom=false; downroom=false;
				if( (c+wordLength-1) <= rightCol) { rightroom=true; }
				if( (c-wordLength+1) >= leftCol)  { leftroom=true; }
				if( (r+wordLength-1) <= bottomRow){ downroom=true; }
				if( (r-wordLength+1) >= topRow)   { uproom=true; }
				//alert("findWord(): wordLength=" + wordLength + " c=" + c + " lc=" + leftCol + " rc=" + rightCol + " rightroom=" + rightroom + " c+wordLength-1=" + (c+wordLength-1)*1 )
				//debugger
				if(rightroom){ 
					if(getWord(grid,i,L,w,wordLength,1)) {					
						//alert(w + "horiz found")
						thisRow=r; thisCol=c; return 1;
					}
				}
				if(rightroom && uproom){ 
					if(getWord(grid,i,L,w,wordLength,-19)) {
						thisRow=r; thisCol=c; return -19;
					}
				}
				if(uproom){ 
					if(getWord(grid,i,L,w,wordLength,-20)) {
						thisRow=r; thisCol=c; return -20;
					}
				}
				if(leftroom && uproom){ 
					if(getWord(grid,i,L,w,wordLength,-21)) {
						thisRow=r; thisCol=c; return -21;
					}
				}
				if(leftroom){ 
					if(getWord(grid,i,L,w,wordLength,-1)) {
						thisRow=r; thisCol=c; return -1;
					}
				}
				if(leftroom && downroom){ 
					if(getWord(grid,i,L,w,wordLength,19)) {
						thisRow=r; thisCol=c; return 19;
					}
				}
				if(downroom){ 
					if(getWord(grid,i,L,w,wordLength,20)) {
						thisRow=r; thisCol=c; return 20;
					}
				}
				if(rightroom && downroom){ 
					if(getWord(grid,i,L,w,wordLength,21)) {
						thisRow=r; thisCol=c; return 21;
					}
				}						
			}
		}
	}
alert("Couldn't find searched for word: " + w)
}

function getWord(grid,i,L,w,len,inc){ //gets the full word extended to len from L in the inc direction
	foundword=L;
	nextcell=i
	for (k=2 ; k<=len; k++){
		nextcell=nextcell+inc
		foundword=foundword+grid[nextcell];
		//alert("getting word " + w + " found " + foundword + " cell was " + nextcell);
	}
	if (foundword==w){
		//alert ("true " + foundword)
		return true;
	}
	else{
		//alert ("false " + foundword)
		return false;
	}
}


function scanGrid(uid){
	for (r=topRow; r<=bottomRow; r++){
		for(c=leftCol; c<=rightCol; c++){
			i=(r*20 + c)/1;
			cell=uid + "r" + r + "c" + c;
			//alert ('cell=' + cell)
			grid[i]=document.getElementById(cell).firstChild.data;
			//alert("scan " + i + ":" + r + " " + c + " = " + grid[i])
		}	
	}

}
function checkWord(uid){
	//alert("in checkWord, don't know anything yet")
	// Need to know if the word so far can be exended to a full word. 
	// If it is, we return the next letter ID as an object.  Otherwise we don't.
	// If wordsoFar is not a subset of an unfound word, we can give up.
	// Otherwise, cellsSoFar will tell us the direction of the word and the next
	// cell but we need to know that extending is worthwhile
	formName=uid 
	scanGrid(uid)
	wordSoFar=document[formName]["wordSoFar"].value
	cellsSoFar=document[formName]["cellsSoFar"].value
	t1=document.getElementById('words'+uid);
	trs=t1.rows
	wordRows=trs.length
	str="";
	foundCount=0;
	carryOn=false
	for (r=0; r < wordRows; r++){//these will be word and number found so far as pairs
		uifr=uid + 'r' + r
		uiff=uid + 'f' + r
		w = document.getElementById(uifr).innerHTML
		lc = document.getElementById(uiff).innerHTML
		wordArray[r]=w
		wordFound[r]=lc;
		searchedWord=wordArray[r]
		if(wordFound[r] == 0 && wordArray[r].search(wordSoFar)==0){
			//alert("check wordSoFar, could be " + wordSoFar + " cells= " + cellsSoFar)
			//debugger
			direction1=findWord(wordArray[r]) //also gets thisRow, thisCol
			direction2=getDirection(uid, cellsSoFar) // Also sets StartR, startC
			//alert('directions 1, 2 = ' + direction1 + ', ' + direction2)
			
			if (startR==thisRow && startC==thisCol){
				if (direction1==direction2) {
					wExtended=getExtended(thisRow,thisCol)
					if (wExtended.search(searchedWord)==0){
						//create next cell object and return it
						//alert("dn known" )
						ref=uid + 'r' + (rLast + deltaR) +  'c' + (cLast + deltaC)
						//alert(w2 + " " + ref)
						obj=document.getElementById(ref)
						return obj;
					}//w2.search
				}//directions same
				if (direction2==0){
					//try all possible directions
					//debugger
					if (wordOK(uid, 0,1))   {return document.getElementById(thisRef)}
					if (wordOK(uid, -1,1))  {return document.getElementById(thisRef)}
					if (wordOK(uid, -1,0))  {return document.getElementById(thisRef)}
					if (wordOK(uid, -1,-1)) {return document.getElementById(thisRef)}
					if (wordOK(uid, 0,-1))  {return document.getElementById(thisRef)}
					if (wordOK(uid, 1,-1))  {return document.getElementById(thisRef)}
					if (wordOK(uid, 1,0))   {return document.getElementById(thisRef)}
					if (wordOK(uid, 1,1))   {return document.getElementById(thisRef)}				
				}//if d2=0
			}//start positions match
		}//word is subset of unfound word
	}//unfound words to be tested
}
function wordOK(uid, dr,dc){
	wdExtended=getExtended(thisRow,thisCol,dr,dc)
	if (wdExtended.search(searchedWord)==0) {
		thisRef=uid + 'r' + (rLast + deltaR) +  'c' + (cLast + deltaC)
		return true
	}
	else{ return false
	}
}
	


function getExtended(rs,cs){
	if (arguments.length>2){
		deltaR=arguments[2]
		deltaC=arguments[3]
		}
	r=rs
	c=cs
	w=""	
	while (r>=topRow && r<=bottomRow && c>=leftCol && c<=rightCol){
		w=w+grid[r*20+c]
		r=r+deltaR
		c=c+deltaC
	}
	return w;
}

function getDirection(uid,cellString){
//preset global variables
	
	deltaR=0
	deltaC=0
//now let adjacent() work them out again
	x=adjacent(uid,cellString)
//single letter
	if(deltaR==0 && deltaC==0){return 0}
//>1 letter
	switch (true){
		case (deltaR==0 && deltaC==0):
			return 0;
		case (deltaR==0 && deltaC==1):
			return 1;
		case (deltaR==-1 && deltaC==1):
			return -19;
		case (deltaR==-1 && deltaC==0):
			return -20;
		case (deltaR==-1 && deltaC==-1):
			return -21;
		case (deltaR==0 && deltaC==-1):
			return -1;
		case (deltaR==1 && deltaC==-1):
			return 19;
		case (deltaR==1 && deltaC==0):
			return 20;
		case (deltaR==1 && deltaC==1):
			return 21;
	}		
}

	



function checkAnch(o,uid){
	//Get unused word Array ---------------------------------
	wordArray=new Array();
	wordFound=new Array();
	
	//wordTableName="wordTable"
	t1=document.getElementById('words'+uid);
	trs=t1.rows
	wordRows=trs.length
	str="";
	foundCount=0;
	for (r=0; r < wordRows; r++){//these will be word and number found so far as pairs
		uifr=uid + 'r' + r
		uiff=uid + 'f' + r
		w = document.getElementById(uifr).innerHTML
		lc = document.getElementById(uiff).innerHTML
		wordArray[r]=w
		wordFound[r]=lc;
		foundCount+=parseInt(lc);
		str+=w + ", count= " + lc + "\n";
	}
	//alert("words are\n\n" + str)
	
	//---------------------------------------------------------------------------------
	
	//	Initialisation---------------------------------------------------------------------
	newColour=getColour(wordRows,foundCount);
	formName=uid 
	wordSoFar=document[formName]["wordSoFar"].value
	cellsSoFar=document[formName]["cellsSoFar"].value
	startTime=document[formName]["startTime"].value;
	if (startTime==0){
		d = new Date()
		startTime=d.getTime()
		document[formName]["startTime"].value=startTime
	}
	dNow=new Date
	nowTime=dNow.getTime()
	millisecs=nowTime-startTime
	intervalSecs=Math.floor(millisecs/1000)
	intervalMins=Math.floor(intervalSecs/60)
	remainderSecs=intervalSecs%60
	interval=intervalMins + " minutes " + remainderSecs + " seconds";
	
	letter=o.firstChild.data
	tid=document.getElementById('t'+uid);
	clickColor="#CCCCCC";
	o.style.backgroundColor=clickColor //just the anchor, not the table cell
	
	//add letter to word so far.  
	wordSoFar+=letter;
	cellsSoFar+= "#" + o.id;
	//alert ('wordSoFar = ' + wordSoFar)
	//debugger
	//----------------------------------------------------------------------
	// is the latest cell adjacent to the ealier ones?
	if (adjacent(uid, cellsSoFar)){
		//Does it match any unused words?---------------------------------------
		for (i=0; i < wordRows; i++){
			if (wordFound[i] == 0){ //this word is not found yet
				if (wordArray[i]==wordSoFar){		//found it
					//alert("found " + wordSoFar);//------------------------------------
					wordFound[i]=1;					//won't check this one in future
					document.getElementById(uid + 'f' + i).innerHTML=1;
					document.getElementById(uid + 'g' + i).style.visibility="visible"
					cellsArray=cellsSoFar.split("#");
					for (j=1; j<cellsArray.length; j++){// first element is blank hence go from 1 not 0
						document.getElementById('t'+cellsArray[j]).style.backgroundColor="#" + newColour;
						document.getElementById(cellsArray[j]).style.backgroundColor="#" + newColour;
						document.getElementById('c'+cellsArray[j]).innerHTML=newColour;
					}
					document[formName]["cellsSoFar"].value="";
					document[formName]["wordSoFar"].value="";
					//--------------------------------------------------------------
					
					//See if we've got all the words---------------------------------
					if (foundCount+1==wordRows){
						
						alert("Well done - you took " + interval + "\n from your first click")
					}
					//----------------------------------------------------------------
					//alert("quit having found" + wordSoFar);
					return;
					
				}//end of found word
				//we have the start of a word----------------------------------------
				if (wordArray[i].search(wordSoFar)==0){
					//alert('onto something,storing it and returning')
					document[formName]["wordSoFar"].value=wordSoFar;
					document[formName]["cellsSoFar"].value=cellsSoFar;
					return;
				}
				//---------------------------------------------------------------------
			}//end of if word is availble
		}//end of word list
	}//end if adjacent test
	//This is the situation if there are no complete or partial words found-----------------------
	//we want to leave the new letter coloured and record it but any existing stuff should be reset
	//But what if the last cell was already in the word? - need to explicitely reset it
	cellsArray=cellsSoFar.split("#"); //includes final cell
	//alert('cleaning up ' + cellsSoFar + "   " + wordSoFar + '\n arraylength= ' + cellsArray.length)
	for (j=1; j<=cellsArray.length-2; j++){// first element is blank. Not last element!
		prevColour=document.getElementById('c'+ cellsArray[j]).innerHTML
		//alert('j='+j+' previous colour=' + prevColour)
		document.getElementById(cellsArray[j]).style.backgroundColor="#" + prevColour;
		document.getElementById('t'+cellsArray[j]).style.backgroundColor="#" + prevColour;
		
	}//
	//
	document[formName]["cellsSoFar"].value= '#' + o.id;
	document[formName]["wordSoFar"].value=letter
	//explicit reset in case the cell is clicked twice
	document.getElementById(cellsArray[cellsArray.length-1]).style.backgroundColor=clickColor;
	//------------------------------------------------------------------------------------------------
}


function getColour(words,found){
	//alert('wordNr=' + words + '  found=' + found)
	minColour=0X999999;
	maxColour=0XEEFFCC
	spanColour=maxColour-minColour
	incColour=spanColour/words
	outColour=minColour+(incColour*(found))
	outColour=(Math.round(outColour)).toString(16);
	//alert(outColour)
	return outColour
}

function adjacent(uid, cells){
	cellsBare= new Array;
	//alert("cells="+cells)
	cellsA=cells.split("#"); //includes final cell
	cellsLength=cellsA.length-1 //first element is blank. Not last element!
	//debugger
	cellsBare=removeUIDs(cellsA, uid)
	//alert(cellsBare[0] + " " + cellsBare[1] + " " + cellsBare[2] )
	s1=cellsBare[1].split(/[rc]/)
	r1=parseInt(s1[1])
	startR=r1 //needed for help function
	rLast=r1 //may be overwriten later
	c1=parseInt(s1[2])
	startC=c1 //needed for help function
	cLast=c1 //may be overwritten later
	if (cellsLength == 1) return true;
	s2=cellsBare[2].split(/[rc]/)
	r2=s2[1]
	c2=s2[2]
		//alert("r1=" + r1 + "\n c1=" + c1 + "\n r2=" + r2 + "\n c2=" + c2)
	deltaR=r2-r1; //for all tests
	deltaC=c2-c1
	deltaRAbs=Math.abs(deltaR);
	deltaCAbs=Math.abs(deltaC);
	
	//check the second cell is next to the first but not the same
	if (!(deltaRAbs<2 || deltaCAbs<2 ) && (deltaRAbs !=0 || deltaCAbs !=0)){
			return false 
	}
		
	//check the last 2 cells are in the same direction as the first two.
	sLast=cellsBare[cellsLength].split(/[rc]/)
	rLast=parseInt(sLast[1])
	cLast=parseInt(sLast[2])
	sPen=cellsBare[cellsLength-1].split(/[rc]/)
	rPen=sPen[1]
	cPen=sPen[2]
	deltaRLast=rLast-rPen
	deltaCLast=cLast-cPen
	if ((deltaRLast == deltaR) && (deltaCLast == deltaC)){
		return true
	}
	else{//debugger;
	//alert("fail > 2")
		return false
	}
}

function removeUIDs(cellsA, uid){
	//alert("removing")
	cellsB=new Array;
	cellsLength=cellsA.length-1;
	for (j=1; j<=cellsLength; j++){// 
		cellsB[j]=cellsA[j].replace(uid,"X") //replace with x to make sure IE and others have same indexes
	}									     //uid might contain an 'r' or 'c'		
	//alert("1 - " + cellsB[1])
	return cellsB
}

