/***********************************************************************
 *  This Game generates a "wordsearch" matrix for the words            * 
 *  listed in the file wordlist.js and illustrated by the image files. *
 *  The game is complete when all words have been found                *
 *  (c) Alan Hess - 19 Nov 2007 - manxman@bluewin.ch                   *
 *  Sonderpädagogsiche Tagesschule Oberglatt, Switzerland.             * 
 *  FREE FOR NON_COMMERCIAL USE. PLEASE ADVISE OF ANY CHANGES          *
 *  Edit the "wordlist.js" file to set new words and pictures.         *    
 ***********************************************************************/
var vertical;										// if true then vertical words included in grid
var puzzlegrid = new Array; 		// holds letters in the search matrix
var puzzlewidth = gridwidth; 		// sets line width of letter matrix - see wordsearch-definitions.js file..
var puzzlesize = gridwidth * griddepth; // total chars in matrix
var occupied = new Array ; 		// holds status of grid elements - (=1 if part of a word.)
var eolpos = new Array ; 		// holds end of line number markers for the matrix.
var previousclick = 0 ; 		// holds value of previously clicked on letter 
var found = new Array; 			// holds the ref number of words found
var clickable = new Array ; 		// holds status of letter boxes in the grid and if they are clickable
var clickno = 0; 			// count clicks till 2 for word scan
var gameover ;
var n,j;
if (wrongtext==null){var wrongtext = "Wrong! The word is :"};
var version = "2.10";
if (audiofiles==null){var audiofiles=false};
// Program --------------------------------------------------------------

totalwords=w.length; // calculate total word count - now makes "total words = xx" setting redundant
//window.alert(totalwords);

detectbrowser(); // stop problems with IE7
initWS();
showgrid();



//--------------------------------------------------
function processclick(j){ // Main processing function for the game
//process clicks on the matrix , n= position of letter. Top left = 1
//window.alert(j);

var i,k,l;
var word = ""; 		// build word as string from selected grid letters
var typein ; 		// typed in copy of word
var ishit = false; 	// is a word found?


if (clickno>2){clickno=0;previousclick=0;window.alert("reset!")}
clickno++;


if (clickable[j]==true){
 document.board["letter"+j].src=progpath+"selected.gif";
 clickable[j]=false;
  if(previousclick!=0){
    if (previousclick <j){i=previousclick; k=j;} // i and k mark selected word start and finish
		if (previousclick >=j){i=j; k=previousclick;}
					
		if ((k-i) >= gridwidth){step=gridwidth} else {step=1}	
		
		for (n=i;n<=k;n=n+step){word=word+puzzlegrid[n]} // build word from marked selection in puzzle grid
		     
		
		for (n=0;n<=totalwords;n++){  //scan for word in wordlist array "w"
		  if (word==w[n]){
			  found[n]=true; 
				ishit=true;
				previousclick=0; // a word has been found -> no previous click
				clickno=0;
				

				for (l=i;l<=k;l=l+step){document.board["letter"+l].src=progpath+"selected.gif";}
			

				// Now ask for the word to be typed in and compare to original
			  typein = window.prompt(entertext);	
							
				if (typein==null){typein=" "}
				
				if (typein.toUpperCase()!=word.toUpperCase()){found[n]=false} else {found[n]=true}
				
				if (typein.toUpperCase()==word.toUpperCase()){
					document.board["picname"+n].value=w[n]; // enter correct word under corresponding picture below
					
					
					for (l=i;l<=k;l=l+step){
					  document.board["letter"+l].src=progpath+"done.gif";
					  if (occupied[l]==n){clickable[l]=false;} else {clickable[l]=true;}// set all letters of the word as no longer clickable if the word is original and not part of word
            }	
				    } else { 
				    window.alert(wrongtext+" "+w[n]+".");
				    for (l=i;l<=k;l=l+step){document.board["letter"+l].src=progpath+"transparent.gif"; clickable[l]=true;}
				    }
				  
				}
		  }
  }

  if(clickno>=2){
	    document.board["letter"+j].src=progpath+"transparent.gif";
	    document.board["letter"+previousclick].src=progpath+"transparent.gif";
			clickno=0;
			}
  
	if (ishit==false){
	    previousclick=j; // store previous click to scan for word next time
 			clickable[j]=true; // release letter box for clicking
			if(previousclick==0){document.board["letter"+j].src=progpath+"transparent.gif";}
  }
	
	
 
}
gameover=true; // provisionally
for (n=0;n<totalwords;n++){// scan if there are still words to be found
  if(found[n]==false){gameover=false} 
 } 
 if (gameover==true){
 
 window.alert(endtext);
 
 }

}
//--------------------------------------------------
function insertword(n){
  //inserts a word into the matrix
var putok=false;
var j,k,r;
do  {
  k=w[n].length;
  r=0;
  // do the loop until the word does not cross an end of line or the end of puzzle....
  do {   
    rnd=1+Math.floor(Math.random()*puzzlesize);
    endpos=(rnd+w[n].length-1);
    j=0;
    r=1;
    if (endpos>puzzlesize){r=0}
     do {j++} while (rnd>eolpos[j]) ; 
    if(endpos>=eolpos[j]+1){r=0} 
    //window.alert("rnd:"+rnd+" -endpos:" +endpos+" eolpos:"+eolpos[j]+" rep:"+r);
   } while (r==0);      
   // Check if position is already occupied, adjacent or part occupied, adjacent lines....
   putok=true;
   for (j=rnd-1;j<=endpos+1;j++){
	    if (occupied[j]!=0){putok=false }
		  if (occupied[j+puzzlewidth]!=0){putok=false}	 
		  if(j>puzzlewidth){if (occupied[j-puzzlewidth]!=0){putok=false}}	  
		 }
   // Put chars of word into puzzle array and set occupied flags
   if (putok==true){
     for (j=rnd;j<=endpos;j++){ 
	puzzlegrid[j]=w[n].charAt(j-rnd);
	occupied[j]=(n+1) 
     }
   }
}  while (putok==false) // repeat if word collides with another....
}
//---------------------------------------------------
function insertvert(n){
// This will be a function to insert a word vertically...
var putok=false;
var j,k,r,i;
r=0;
k=w[n].length;
// do until word fits space
  
	do{
  rnd=1+Math.floor(Math.random()*puzzlesize);
	endpos=(rnd+(w[n].length-1)*gridwidth);
	j=0;
	r=1;
	if (endpos>puzzlesize){putok=false}
	 else 
	   {putok=true}

	for(j=rnd-1;j<=endpos;j=j+gridwidth){
	  if (occupied[j]!=0){putok=false }
		
	  }	
		if (putok==true){
		
		  i=0;
			for (j=rnd;j<=endpos;j=j+gridwidth){
			  	puzzlegrid[j]=w[n].charAt(i);
					i++;
	        occupied[j]=(n+1) 
			}
		}
	
  } while(putok==false) // repeat if word collides with another....

}
//--------------------------------------------------
function showgrid(){
document.write('<h3 align="center">'+title+'</h3><form name="board">');
document.write('<table align="center" border="0" cellpadding="0" cellspacing="0" name="puzzle"><tr>');
var j = 0;
var c ="";

for (n=1;n<=puzzlesize;n++){
    j++;
		c=puzzlegrid[n];

		//check for special charachters
		if (c.toLowerCase()==" "){c="space"}
		if (c.toLowerCase()=="?"){c="qmark"}
		if (c.toLowerCase()=="-"){c="hyphenkey"}
		if (c.toLowerCase()=="'"){c="apostrophe"}
		if (c.toLowerCase()=="."){c="fullstop"}	
		 
		//check for french accents..

           if(c.toUpperCase()=="È"){c="eal"}
					 if(c.toUpperCase()=="É"){c="ear"}
           if(c.toUpperCase()=="À"){c="aal"}
           if(c.toUpperCase()=="Ê"){c="eah"}
					 if(c.toUpperCase()=="Ô"){c="oah"}
					 
           if(c.toUpperCase()=="ç".toUpperCase()){c="cydila"}

		
		//check for german accents..
		if (c.toLowerCase()=="ü"){c="ue"}
		if (c.toLowerCase()=="ä"){c="ae"}
		if (c.toLowerCase()=="ö"){c="oe"}
		
		document.write('<td width="20" height="20" name="box'+n+'" background="'+progpath+c.toLowerCase()+'.gif"><img width="20" height="20" src= "'+progpath+'transparent.gif" name="letter'+n+'" onClick="processclick('+n+')"></td>');
		if (j>=puzzlewidth){ // new line in grid??

		     document.write('</tr><tr>');
		     j=0;
				}
    }
document.write('</tr></table>');

// show the words for debugging
for (n=1;n<=puzzlesize;n++){
  // change following line "transparent.gif" to "done.gif" to show words in advance
	if (occupied[n]!=0){document.board["letter"+n].src=progpath+"transparent.gif";}
  }
//show the pictures below the grid, max ten to a line
document.write('<br><table align="center"><tr>');
j=0;
k=12;
k=Math.floor(totalwords/2); // show the pictures on two lines.
for (n=1;n<=totalwords;n++){
  j++;
	document.write('<td align="center"><img width="80" height="80" src="'+datapath+n+'.'+imagetyp+'" title="'+w[n-1]+'">');
  if(audiofiles==true){embedplayer(n+".mp3");	}
	document.write('<br><input type="text" value="?" name="picname'+(n-1)+'"></td>');
  if (j>=k){
	  document.write('</tr></tr>');
	  j=0;
	  }
	}
document.write('</tr></table></form>');
document.write('<p align="center">Version : '+version+' STO 2006</p>');


}

//--------------------------------------------------
function initWS(){
 var j,k,n,m
 
 
  // mark end of lines in the eolpos array
	k=0;
	j=0;
  for (n=1;n<=puzzlesize;n++){
		    clickable[n]=true; // allow all boxes to be clicked
				j++;
				if (j==puzzlewidth){
				  k++;
					eolpos[k]=n; // mark end of line positions
					//window.alert(k+" "+eolpos[k]);
					j=0;
				  }
				}
	
	// Fill grid with random letters
	
  for (n=1;n<=puzzlesize;n++){
	  rnd = Math.floor(Math.random()*(26+incspc));
	  rnd = rnd+65; 
			
	  occupied[n]=0;
	  if(rnd!=(26+65)) // check char not the reassigned space code
	   {
		   puzzlegrid[n]=(String.fromCharCode(rnd)) // put the random letter into the grid
			 
			 for(m=0;m<totalwords;m++){ // don't build words from the main list by co-incidence !! - check previous letter
			   if (puzzlegrid[n-1]==w[m].charAt(0) && puzzlegrid[n]==w[m].charAt(1)){
				   //window.alert( w[m].charAt(0)+" "+ w[m].charAt(1));
					   // now alter the current letter if a word is starting to be built by chance.....
				     if(puzzlegrid[n]!="Z"){puzzlegrid[n]=(String.fromCharCode(rnd+1))} else {puzzlegrid[n]=(String.fromCharCode(rnd-1))}
				 }
			 } 
		 }
    
		 
	  else
	   {puzzlegrid[n]=" "} // include spaces in random grid if incspc=1 - (the code is the reassigned space code)
	
	
	}
	//now insert the words amongst the random letters
	for (n = 0;n< totalwords;n++){
	  if (vertical==true){ // set vertical words if required
	  if(Math.floor(Math.random()*2)>=1)
	   {insertvert(n)} else {insertword(n)}
	  }else{
	  insertword(n);}
	  found[n]=false; // start with no words found.
	}
	
}  

//--------------------------------------------------
	function detectPopupBlocker()
	{
		var myTest = window.open("about:blank","","directories=no,height=100,width=100,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,top=0,location=no");
		if (!myTest)
		{
			alert("A popup blocker was detected. Please de-aktivate it.");
		}
		else
		{
			myTest.close();
			//alert("No popup blocker was detected.");
		}
	}
// ----------------------------------------------------
function detectbrowser()
{
var browserName=navigator.appName; 
var A;
var browserVer=parseInt(navigator.appVersion); 

if (browserName=="Netscape")
{ 
 //alert("Hi Netscape User!");
}
else 
{ 
 //window.alert(browserName+" "+browserVer);
 if (browserName=="Microsoft Internet Explorer")
 {
  if (browserVer>=4){A=window.prompt("Please allow user input for this site. - Bitte das Dateneingeben für diese Seite erlauben.")}
 }
 else
  {
    //alert("What ARE you browsing with here?");
   }
}
}
//----------------------------------------------------	

function embedplayer(soundfile){
  var soundfile;
	//window.alert(soundfile);
  
  document.write('<br><object name ="mp3player" width="80" height="10" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"');
  document.write('codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0">');
 
	document.write('<param name="movie" value="'+progpath+'mp3player.swf?src='+soundfile+'" />');
	
  document.write('<embed src="'+progpath+'mp3player.swf?src='+soundfile+'" width="80" height="10" type="application/x-shockwave-flash"');
  document.write('pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>');
}

//-----------------------------
