// This file contains JavaScript functions to display Text Puzzles
// Version 2, Peter Jipsen (c) 2002-9-5

ppList=[];      //list of puzzle pieces
innerHTMLppList=[]; //innerHTML of original pieces
perm=[];        //permutation that scrambles the pieces
nameStr="";     //name of the student
swap=true;      //default puzzle move behaviour
numbered=true;  //by default puzzle pieces are numbered
graded=false;   //global flag (correct pieces are shown when true)
start=new Date(); //timer variable
now=new Date();   //timer variable

function getElementsWithClass(containingEl, tagName, className1){

    var returnedCollection = new Array(0);
    
    var collection = containingEl.getElementsByTagName(tagName);
    
    for(var i = 0; i < collection.length; i++)
        if(collection[i].className==className1)
            returnedCollection[returnedCollection.length] = collection[i];

    return returnedCollection;
}

function updatePieces(showCorrect){
  for (var i=0; i<ppList.length; i++) {
    ppList[i].innerHTML=(
showCorrect && innerHTMLppList[perm[i]]==innerHTMLppList[i]?
innerHTMLppList[perm[i]]:
(numbered?"<i id='puzzleNum'>"+(i<9?"&nbsp; "+(i+1):i+1)+".</i>":"")+
"<input type=radio name=select value='"+i+
"'><a onClick='movePieces("+i+
")'><img border='0' width='15' height='13' \
src='../TP/puzzlePiece.gif' alt='Insert here'> "+
innerHTMLppList[perm[i]]+"</a>");
  }
  if (!graded) now=new Date();
  sec=Math.floor((parent.now-parent.start)/1000);
  document.getElementById("timer").innerHTML=
    "<p align='right'>Time: "+(sec>=60?Math.floor(sec/60)+
    " min ":"")+sec%60+" sec</p>";
}

function initPuzzlePieces(){
  document.body.innerHTML='<form>'+t2h(document.body.innerHTML)+
"</form><div id='timer'></div>\
<div id='bottom'><input type=button value='Check' \
onClick='grade()'><p><b>Brief Instructions for solving \
this Text Puzzle:</b> The \
<b style='background-color:yellow'>\
<img src=../TP/puzzlePiece.gif> puzzle pieces</b> \
above have been shuffled, and your task is \
to move them around so that they end up in the correct position. \
Click a <b style='background-color:yellow'>\
<img src=../TP/puzzlePiece.gif> puzzle piece</b> \
to select it, \
then click another <b style='background-color:yellow'>\
<img src=../TP/puzzlePiece.gif> puzzle piece</b> \
to move (or swap) the selected piece to \
that particular position. When you think you are done, \
click on the Check button.</p></div>\
<hr><center><img src=../TP/puzzlePiece.gif> <b style='color:purple'>\
Text Puzzles</b> <img src=../TP/puzzlePiece.gif> by \
<a href=http://www.chapman.edu/~jipsen target=new>Peter Jipsen</a> \
<img src=../TP/puzzlePiece.gif> <b style='color:purple'>\
Chapman University</b> <img src=../TP/puzzlePiece.gif></center>";

  ppList = getElementsWithClass(document,"span","TP");
//alert(ppList.length);
  if (ppList.length==0) 
    ppList = document.getElementsByTagName("span");
  var n=ppList.length;
  for (var i=0; i<n; i++) {
    perm[i]=i;
    innerHTMLppList[i]=ppList[i].innerHTML;
  }
  var t;
  for (var i=0; i<n; i++) {//swap perm[i] with perm[random]
    j=Math.floor(n*Math.random());
    t=perm[i];
    perm[i]=perm[j];
    perm[j]=t;
  } 
  updatePieces(false);
  start=new Date();
}

function movePieces(k){
//find checked radio button, remove line, insert at k.
  var n=document.forms[0].elements.length;
  var i=0;
  var t;
  while(i<n && !document.forms[0].elements[i].checked) i++;
  if (i<n) {
    i=eval(document.forms[0].elements[i].value);
    if (i!=k) {
      if (swap || i==k-1) {
        t=perm[i];
        perm[i]=perm[k];
        perm[k]=t;
      } else if (i<k)
        perm=perm.slice(0,i).concat(perm.slice(i+1,k),[perm[i]],perm.slice(k));
      else
        perm=perm.slice(0,k).concat([perm[i]],perm.slice(k,i),perm.slice(i+1));
    }else{
      i=0;
      while (i<n && document.forms[0].elements[i].value!=k) i++;
      document.forms[0].elements[i].checked=false;
      }
    updatePieces(graded);
  }else{
    i=0;
    while (i<n && document.forms[0].elements[i].value!=k) i++;
    document.forms[0].elements[i].checked=true;
//alert("k="+k+" n="+n+" i="+i);
  }
  return false;
}

function storeName() {
  nameStr=document.getElementById("nametext").value;
  var d=new Date();
  botobj=document.getElementById("bottom");
  botobj.innerHTML="You got "+correct+" out of "+ppList.length+
" correct, or "+percent+"%.<p>Text Puzzle completed by <b>"+
    nameStr+"</b> on "+d.toLocaleString()+
    ".</p><p>\"Yes, I did it on my own without any \
help\": _________________________________</p>";
}

function grade(){
  correct=0;
  for (var i=0; i<perm.length; i++) {
    correct=correct+(innerHTMLppList[perm[i]]==innerHTMLppList[i]?1:0);
  }
  graded=true;
  percent=Math.round(100*correct/ppList.length);
  swap=true;
  updatePieces(true);
  botobj=document.getElementById("bottom");
  botobj.innerHTML=
"You got "+correct+" out of "+ppList.length+
" correct, or "+percent+"%. <p>"+
(percent==100?
"Well done. You seem to know what's going on.":
(percent>=80?
"Pretty good. Finish the last few steps and try another puzzle.":
(percent>=65?
"Fairly decent. Finish the puzzle, then reload the page and \
try it again.":
(percent>=50?
"Not so good. Look carefully at what lines are not yet in the \
right place. Finish the puzzle without guessing, then reload \
the page and try it again.":
"Oh-oh. Read the relevant chapter(s) in your textbook, then \
reload the page and retry this puzzle several times."))))+"</p>"+
(parent.nameStr==""?
"<p>Finished? Type your name: \
<input id='nametext' type=text size=25 name=yourName> Click \
<input type=button value=Enter onClick='storeName()'> \
and then print this page.<br>(Don't worry, your score and \
name are not recorded anywhere.)</p>":"");
}



