//========================================================================
//   "WebWordSearch"  JavaScript WordSearch 
//
//   Copyright (C) 2001-2003  Jan Mulder
//
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation; either version 2 of the License, or
//   (at your option) any later version, and as long as this notice is
//   kept unmodified at the top of the script source code.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License (license.txt) for more details.
//
//   Contact: Jan Mulder info@EnglishCafe.co.uk
//  
//   Last updated: 31st January 2003
//=======================================================================

var wordsLeft = wordList.length;
var numWords = wordsLeft;
var doneLoading = false;
var isScored = false;
var isWordList = false;
var doneWords = new Array();

var progressBar = '||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||';

// check for NS version 4 or less
var isNS4 = false;

if ( (navigator.appName == "Netscape") && ( (navigator.userAgent).indexOf("Gecko") == -1)  )
  isNS4 = true;  
  
function doFunction(aFunction)
{
 if (aFunction.indexOf('(') > -1)
   eval( aFunction );
 else
   eval(aFunction+'()');
}

function updateProgress(ims)
{
 var cnt=0;

 for(var i = 0; i < ims.length; i++)
  if(ims[i].complete || ims[i].errored) cnt++;

 if(ims.length > 0)
    window.status='Loading wordsearch  ['+Math.round((cnt / imageCount)*100)+'%] ' + progressBar.substring(0, cnt);

 if(cnt < ims.length)
 {
  tempArray = ims;
  setTimeout("updateProgress(tempArray)",200);
 }
 else
  onComplete();
}

function onComplete()
{
 window.status='Done';
 doneLoading = true;
}

function preloadImages()
{
 this.length = preloadImages.arguments.length;
 imageCount = this.length;
 for (var i = 0; i < this.length; i++)
 {
  this[i] = new Image();
  this[i].errored=false;
  this[i].onerror=new Function("this["+i+"].errored=true");
  this[i].src = preloadImages.arguments[i];
 }
 updateProgress(this);
}

var pictures = new preloadImages(
 sourceDir+"a.gif", sourceDir+"b.gif", sourceDir+"c.gif", sourceDir+"d.gif", sourceDir+"e.gif", sourceDir+"f.gif",
 sourceDir+"g.gif", sourceDir+"h.gif", sourceDir+"i.gif", sourceDir+"j.gif", sourceDir+"k.gif", sourceDir+"l.gif",
 sourceDir+"m.gif", sourceDir+"n.gif", sourceDir+"o.gif", sourceDir+"p.gif", sourceDir+"q.gif", sourceDir+"r.gif",
 sourceDir+"s.gif", sourceDir+"t.gif", sourceDir+"u.gif", sourceDir+"v.gif", sourceDir+"w.gif", sourceDir+"x.gif",
 sourceDir+"y.gif", sourceDir+"z.gif",
 sourceDir+"blank.gif", sourceDir+"done.gif", sourceDir+"selected.gif"
);

function getPageName( strPath ) {
var thisPage = strPath.substring(
               strPath.lastIndexOf('/')+1, 
               strPath.length+1
               );
return thisPage;	
}	

function strReverse( str  ) {
  var strRev = "";	
  for (var i=0; i<str.length; i++)
    strRev += str.charAt(str.length-i-1);
  return strRev;  
}

function check(row, col) { 
  relRow = row - oldRow;
  relCol = col - oldCol;
  
  ///////////////////////////////////////////////////////////////////////////////////
  // It's only a possuble word if the selection was horizontal, vertical or diagonal
  var isPossible = ( relRow == 0 || relCol == 0 || relRow == relCol ) ? true : false;
  
  //////////////////////////////////////////////////////////
  // selLength is the length of the currently selected word
  selLength = Math.max( Math.abs(relRow), Math.abs(relCol) );
  
  /////////////////////////////////////////////////////////////
  // Normalise relRow/relCol to 1 or -1 depending on direction
  if (relRow != 0) relRow = relRow/Math.abs(relRow);
  if (relCol != 0) relCol = relCol/Math.abs(relCol);

  //////////////////////////////////////////////
  // oldRow is only -1 at the start of the game
  if (oldRow != -1) {
    ////////////////////////////////////////////////////
    // Get the prev selected letter and change the image
    selectedLetter = oldCol + puzzleWidth*oldRow;
    document["box" + selectedLetter].src = oldImg;
  } 
  ////////////////////////////////////////////////////////
  // Get the current selected letter and change the image 
  selectedLetter = col + puzzleWidth*row;
  oldImg = sourceDir + getPageName(document["box" + selectedLetter].src);  
  document["box" + selectedLetter].src = sourceDir + "selected.gif";
    
  //////////////////////////
  // is it a possible word?
  if (isPossible) { 	
    
    selectedWord = "";
    /////////////////////////////////////////////////////////////////
    // Get the selected word by adding all the letters between the 
    // previous and current selected letters to selectedWord
    selectedLetter = oldCol + puzzleWidth*oldRow;    
    for(i=0; i<=selLength; i++) {  
      selectedWord += puzzleGrid.charAt(selectedLetter);
      selectedLetter += relCol + puzzleWidth*relRow;
    }

    //////////////////////////////////
    // Allow for selecting in reverse
    if (relRow < 0 || relCol < 0)
      selectedWord = strReverse(selectedWord);

    selectedWord = selectedWord.toLowerCase();
    
    /////////////////////////
    // See if match is found
    found = -1;
    for(i=0; i<wordsLeft; i++) { 
      if( wordList[i].toLowerCase() == selectedWord ) { 
      	found = i; 
      } 
    }
 
    //////////////
    // If found... 
    if( found != -1 ) { 
      selectedLetter = oldCol + puzzleWidth*oldRow;      
      for(j=0; j<=selLength; j++) { 
        document["box" + selectedLetter].src = sourceDir + "done.gif";
        oldImg = sourceDir + "done.gif";
        selectedLetter += relCol + puzzleWidth*relRow;
      }
      selectedWord = wordList[found];
      for(i=found; i<=numWords; i++) { 
        wordList[i] = wordList[i+1];
      }
      wordsLeft = wordsLeft - 1;
      wordList[numWords] = selectedWord;
      
      doneWords[doneWords.length] = selectedWord;

      if (isScored)
        document.scoreForm.wordsLeft.value = wordsLeft; 
      
      if (isWordList) {
        document.listForm.wordList.value = doneWords.join("\n"); 
        document.listForm.wordsFound.value = doneWords.length;
      }  
      
      ////////////////////////
      // found all the words?
      if( wordsLeft == 0 ) { 
        if (doneAction != '') {
		  stopTimer();
		  //doFunction(doneAction);
		  
        }
      }
      //====================== 
    } 
  }
  oldRow = row;
  oldCol = col;
} 

function drawWordSearch() {
 document.write('<table cellspacing=0 cellpadding=0 bgcolor="white">');
 var puzzleHeight = Math.floor(puzzleGrid.length/puzzleWidth);
 
 for (i = 0; i < puzzleHeight; i++)
 {
  document.write('<tr>');
  for (j = 0; j < puzzleWidth; j++)
    document.write(
      "<TD background=\"" + sourceDir + puzzleGrid.charAt(i*puzzleWidth+j).toLowerCase() + ".gif\" WIDTH=\"20\" HEIGHT=\"20\">"
      + "<A HREF=\"javascript:check("+i+","+j+")\">"      
      + "<IMG SRC=\"" + sourceDir + "blank.gif\" WIDTH=\"21\" HEIGHT=\"21\" ALIGN=\"BOTTOM\" BORDER=\"0\" NAME=\"box" + (i*puzzleWidth+j) + "\">"      
      + "</A></TD>\n"
    );
  document.write('</tr>');
 }
 document.write("</table>");
 oldRow = -1;
 oldCol = -1; 
 oldImg = sourceDir + "blank.gif";
	startTimer();
}

function drawScore() {
  isScored = true;
  document.writeln('<FORM name="scoreForm">');
  document.writeln(
  '<TABLE border="1" cellspacing="0" cellpadding="1"><TR>'
  +'<TD ><IMG border=0 SRC="' + sourceDir + 'dotclear.gif" width="85" height="20"><input type="text" size="3" name="wordsLeft" value="'+numWords+'"></TD>'
  +'</TR></TABLE></FORM>'
  );
  document.scoreForm.wordsLeft.value = wordsLeft; 
}	

function drawWordList( rows, cols ) {
  isWordList = true;
  document.writeln('<FORM name="listForm">');
  document.writeln(
  '<TABLE border="1" cellspacing="0" cellpadding="0"><TR>'
  + '<TD align=right background="' + sourceDir + 'wordlist.gif">'
  + '<IMG border=0 SRC="' + sourceDir + 'dotclear.gif" width="85" height="21">'
  + '<input type="text" size="3" name="wordsFound" value="'+numWords+'">'
  + '<IMG border=0 SRC="' + sourceDir + 'dotclear.gif" width="2" height="10">'
  + '<br><textarea name=wordList rows=' + rows + ' cols=' + cols + ' class=wordsearch></textarea></TD>'
  +'</TR></TABLE></FORM>'
  ); 
  document.listForm.wordList.value = doneWords.join("\n"); 
  document.listForm.wordsFound.value = 0;
}

function initWS() {
  if (isScored)
    document.scoreForm.wordsLeft.value = wordsLeft; 
  if (isWordList) {
    document.listForm.wordList.value = doneWords.join("\n"); 
    document.listForm.wordsFound.value = 0;
  }  
}
    
