// identify2.js
// Script to create identify fish game, copied from identify1.js
// g patton 9/12/07 created
// updated 8/30/07 to loop to create page
// 8/31/07 made true or false a class since cant modify onclick
// 9/1/07 fixed the code to make choices so they are all unique
// 9/1/07 fixed class stuff which is different for IE and netscape
// 9/1/07 discoered that IE can't color a button lightgray so used gray
// 9/1/07 note Array must start with capital className must have capital N
// 9/1 07 all variables should be specified especially global ones
//        or else pass them in but that is harder
// 9/1/07 brought over from old computer
// 9/12/07 put sounds in an array to preload them plays faster
// 9/12/07 fixed spelling of piranha
// 9/12/07 fixed so sound wouldn't bomb opera
// 9/12/07 added levels of reward based on right and wrong answers


//  ********************  SOUND FUNCTIONS required embed bgsound
ver=parseInt(navigator.appVersion)
ie4=(ver>3  && navigator.appName!="Netscape" && navigator.appName!="Opera")?1:0
op= navigator.appName=="Opera"?1:0
//alert("navigator.appName = " + navigator.appName + "  version = " + ver)
//ns4=(ver>3  && navigator.appName=="Netscape")?1:0
//ns3=(ver==3 && navigator.appName=="Netscape")?1:0
//alert("appName =" + navigator.appName + " ver=" + ver)

// ************ first preload sounds added 9/12/07
var gsnd = new Array()
    gsnd[0] = "soundtrue.wav"
    gsnd[1] = "soundfalse.wav"
    gsnd[2] = "soundwon.wav"

var a // argument passed in to playsound
//  ******************** play sound clip input is file
function playsound(a) 
  {
  // set the player controls
//alert("got to play sound a = " + a)
  if (op)
    {
     // skip playing for now if opera
    }
  else
    {  document.Player.URL = a
//alert("document.Player = " + document.Player)

      // not opera so try sound
      try
        {
        document.Player.controls.play();
        }
      catch(err)
        {
        // problem with netscape and player controls so catch error and continue
        }
    } // end else not opera
  } // end playsound

// *************  function to stop sound not needed for ie
// function stopSound() {
// document.Player.controls.stop();
// }
 
var cwrong = 0 // count number wrong
var cright = 0 // count number right
var srow // row of status results table
var parent // must put this here and not in functions gcptrue and gpfalse to work in IE
var selid // variable in which to compose ids containing rows and cols for later identification
var cpr = 3 // columns per row
var numrows = 2 // number of rows
var cpp = 3 // choices per picture
var tempans = new Array() // array to hold answers per picture while we randomize them
var j // index to picture and answer array
var irows // index into the rows of pictures

// preload the gifs for won and lost
var large = new Array() 
    large[0] = "wwon440x77.gif"         // won
    large[1] = "wgoodtry440x77.gif"     // < 2 wrong < 7 right
    large[2] = "wtryagain440x77.gif"    // all else
    large[3] = "btransparent440x77.gif" // for reset

// ************** function to handle clicks on answers
function ansclick(id1) 
  {
  // first get the id field and then parse for the column (picture) number
  idlable=id1.getAttribute("id")
//alert("idlable = " + idlable)
  picturenumber = parseInt(idlable)
//alert("pictrenumber = " + picturenumber)

  // get class to see if it is true or false
if (!ie4) { classatrib =id1.getAttribute("class") }
else { classatrib =id1.getAttribute("classname") }
//alert(" id1 class attribute = " + classatrib )
  if (classatrib=="true")
    {
    // case for true
    // make button background green
    id1.style.background="green"
    cright++
    srow=document.getElementById("status").rows[0].cells
    srow[2].innerHTML=cright
    // parent must go last or count doesnt work in IE
    // update the status array
    statupdate(picturenumber,2)
//    parent=id1.parentNode
//    parent.style.background="#4CC36B"
    playsound(gsnd[0])
    }
  else
    {
    // it is false
    id1.style.background="#FB1E5C"
    cwrong++
    srow=document.getElementById('status').rows[0].cells
    srow[4].innerHTML=cwrong

    // set the status array
    statupdate(picturenumber,1)
//    parent=id1.parentNode
//    parent.style.background="aqua"
    playsound(gsnd[1])
    } // end false
  // after every entry check to see if they are done and have won
  // checkstatus returns 0 if not done, 1 if some false, 2 if all true
//alert("got to checkstatus gcpstatcheck() = " + gcpstatcheck() )
  if (gcpstatcheck()>0) 
    {
    // you have finished
    // check if any wrong
    if (cwrong>0)
      {
      if (cwrong <= 2 && cright < 7 )
        {
        // not bad so encourage good try
        largestatusup(large[1])
        }
      else
        {
        //say try again
        largestatusup(large[2])
        }
      } // end some wrong
    else
      {
      // none wrong so say you won
      largestatusup(large[0])
      playsound(gsnd[2])
      }
    } // end checkstatus
  } // end ansclick

// keep track of status with a status array one for each picture
// as entries are made pdate the array and if all are green end game
var statarray =new Array()

// *******   function to initialize the status array
function statinitialize()
  {
    // initiallize the array
    for (istat=1; istat<=numrows*cpr; istat++)
      {
      statarray[istat]=0
    }
  }// end statinitialize

// ******* funtion to update a picture status
function statupdate(picnumber,statusvalue)
  {
//alert("in statupdate piccnumber = " + picnumber + " statusalue = " + statusvalue)
  statarray[picnumber]=statusvalue
  } // end statupdate

// *************  funtion to check the status array 
// function to check status array, returns 0 if incomplete, 1 is some false, 2 if true
function gcpstatcheck()
  {
  statval = 2
  for (ist2=1; ist2<= numrows*cpr; ist2++)
    {
    if (statarray[ist2]<statval){statval=statarray[ist2]}
//alert("statval=" + statval)
    }
  return statval
  } // end gcpstatcheck


// global array of answers 
var ans = new Array()
    ans[0] = "Piranha             "
    ans[1] = "Moray Eels          "
    ans[2] = "Lion Fish           "
    ans[3] = "Clown Trigger Fish  "
    ans[4] = "Short Nose Batfish  "
    ans[5] = "Ribbon Eel          "
    ans[6] = "Moon Jellyfish      "
    ans[7] = "Leafy Sea Dragons   "
    ans[8] = "Blue Jellyfish      "
    ans[9] = "Giant Albino Gourami"
    ans[10] = "Goldfish            "
    ans[11] = "Lobster             "
    ans[12] = "Mandarin Fish       "
    ans[13] = "Shark               "
    ans[14] = "Turtles             "
    ans[15] = "Wimple              "
    ans[16] = "Palette Fish        "

// global array of pictures  must be same as global array
var pict = new Array()
    pict[0] = "idpirhana200x150.jpg"
    pict[1] = "idmorayeels200x150.jpg"
    pict[2] = "idlionfish200x150.jpg"
    pict[3] = "idclowntriggerfishs200x150.jpg"
    pict[4] = "idshortnosedbatfish200x150.jpg"
    pict[5] = "idribboneel200x150.jpg"
    pict[6] = "idmoonjellies200x150.jpg"
    pict[7] = "idleafyandweedyseadragons200x150.jpg"
    pict[8] = "idblueblubberjellyfish200x150.jpg"
    pict[9] = "idgiantalbinogourami200x150.jpg"
    pict[10] = "idgoldfish200x150.jpg"
    pict[11] = "idlobster200x150.jpg"
    pict[12] = "idmandarin200x150.jpg"
    pict[13] = "idshark200x150.jpg"
    pict[14] = "idturtles200x150.jpg"
    pict[15] = "idwimple200x150.jpg"
    pict[16] = "idpalette200x150.jpg"



// ***********  funcction to create a unique array of numbers from 1 to the size of the pict and ans arrays
var num = new Array() // the array as global
var number = pict.length // max pictures must match array size
function createarray()
{
  //initialize the status array to all false
  statinitialize()
  // first create a array num of unique random numbers for the max pictures
  if (pict.length != ans.length) {alert("pict length not equal to ans length")}

  var counter = 1

  for(i=1; i <= number; i++)
    {
        num[i] = i
    }
//alert("before " + num[1] + num[2] + num[3] + num[4] + num[5] + num[6] + num[7] + num[8] )

  // now reverse the array and populate downward randomly
  // last number goes in random slot, random slot goes to last number
  // then array is shortened by 1
  for (c=number; c >1; c-- )
    {
    // get a random number less than or equal to c
    rnum = randc(c) // function given below
    temp=num[rnum]
    num[rnum] = num[c]
    num[c] = temp
    }
//alert("after " + num[1] + " " + num[2] + " " + num[3] + " " +  num[4]  + " " + num[5] + " " + num[6] + " " +  num[7] + " " + num[8] )

} // end of create array

var m // counter for array to hold choices
var n // dupe chek counter
var truea // slot in answers for correct answer
var cpp // choices per picture
var tempansone // place to store true answer in swap
var k // index to array where final answer indexs are stored

// ********  function to create the game board
function createidentifygame()
{
  // create an array of unique numbers
  createarray() // creates an array in num of size of pics array

  // a status table first
  document.write( '<table  id="status" border="0" bgcolor="aqua" > ')
  document.write( '<tr><td >Game Status&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td> ')
  document.write( '<td >  Right = </td><td>0</td> ')
  document.write( '<td >&nbsp;&nbsp;&nbsp;&nbsp;Wrong = </td><td>0</td></tr> ')
  // document.write( '</table> ')


  // we basically create a table with 6 pictures, 3 to a row and then 3 choices under 
  // the pictures.  Each choice has a right or wrong onclick return.  
  // after each click we update a matrix of right and wrong and if all are right
  // we say you won.

  // write initial table parts
  document.write( '<table width="100%" border="0" > ')

  j = 1 // set index into picture and answer array but array starts at 0 so we sbtract one later
  // write numrows rows

  for (irows=1; irows<=numrows; irows++)
    {
      // write a row
      document.write( '<tr> ')
      // write cpr pictures in a row
      for (pici=1; pici <= cpr; pici++)
        {
        // cpp pitures per row each in a td cell
        document.write( '<td width="30%" align="center" ><br>')
        // write a picture
        selid =  (pici+(cpp*(irows-1))) + "c0"
//alert("selid write pict = " + selid)
        document.write( '<img id="' + selid + '" src="' + pict[num[j]-1] + '" width="200" height="150" ><br>')

        // fill in a temp table. 1st slot is true answer, 2nd answer not 1st, 3rd answer not 1 or 2 etc.
        // find the slot to put it in and then swap 1 and slot
        m=1  // initialize counter used in while loop
        while ( m<=cpp)
          {
//alert("in while m = " + m )
          if (m==1)
            { 
//alert("in if where m=1 m = " + m )
            // put in true answer
            tempans[m]=num[j]-1
            m++
//alert("in if after m=1;  increase m = " + m )
            }
          else
            {
//alert("in else m = " + m )
            // get a new choice
            answer=randc(number) // number between 1 and number of pictures
            tempans[m]=num[answer]-1
            m++ // provisionally increase m here and subtarct later if it is a dup will start at 3
            // now check for dup
            for (n=1; n<=(m-2); n++)
              {
//alert(" for n< m-2 m = " + m + " n = " + n )
              if (num[answer]-1 == tempans[n] )
                {
                m--
                }
            } //end for
         } // end else
      } //end while choices per picture

      // now swap 1 to the slot where the true choice should go
      truea = randc(cpp)
      tempansone = tempans[1]
      tempans[1]= tempans[truea]
      tempans[truea] = tempansone

//alert("tempans[1] = " + tempans[1] + " tempans[2] = " + tempans[2] + " tempans[3] = " + tempans[3] + " truea = " + truea)
      // now write out the buttons using the numbers in the temp array
      for (k=1; k<=cpp; k++)
        {
        if (k==truea)
          {
          // write true line with class true
          selid = (pici + (cpp*(irows-1))) + "c" + k
          document.write( '<input class="true" id="' + selid + '" type="button" value="' + ans[tempans[k]] + '" onclick="ansclick(this)"><br> ')
          }
        else
          {
          // write false line
          selid = (pici+(cpp*(irows-1))) + "c" + k
          document.write( '<input class="false" id="' + selid + '" type="button" value="' + ans[tempans[k]] + '" onclick="ansclick(this)"><br> ')
          }
        } // end for which wrote out the buttons
 //       document.write(' <br> ')  // a space after the choices       
        j++ // increment to next picture
        // end the choices so write td
        document.write( '</td>')
      } // end picture
     document.write( '</tr>')
    }// end write a row
  // end table
  document.write( '</table> ')
  } // end create identify game

//**********************************************************************************
// ****************  function to reset the page with different pictures and choices
function resetpage()
{
  // take out any text over the screen
  largestatusup(large[3])
  // set the right wrong counts to 0
  cright = 0
  cwrong = 0
  srow=document.getElementById("status").rows[0].cells
  srow[2].innerHTML=cright
  srow=document.getElementById('status').rows[0].cells
  srow[4].innerHTML=cwrong

  //initialize the status array to all false
  statinitialize()
  //  this funcction uses the logic of the original write but gets the IDs and 
  // replaces the source and text

  // first create a new array of unique numbers
  createarray() // creates an array in num of size of pics array
  j = 1 // set index into picture and answer array but array starts at 0 so we sbtract one later
  // write numrows rows

  for (irows=1; irows<=numrows ; irows++)
    {
      // write a row
      for (pici=1; pici <=cpr ; pici++)
        {
        selid =  (pici+(cpp*(irows-1))) + "c0"
//alert("selid = " + selid)

        document.getElementById(selid).src=pict[num[j]-1]
        // fill in a temp table. 1st slot is true answer, 2nd answer not 1st, 3rd answer not 1 or 2 etc.
        // find the slot to put it in and then swap 1 and slot
        m=1  // initialize counter used in while loop
        while ( m<=cpp)
          {
//alert("in while m = " + m)
          if (m==1)
            { 
//alert("in if m = " + m)
            // put in true answer
            tempans[m]=num[j]-1
            m++
            }
          else
            {
//alert("in else m = " + m)
            // get a new choice
            answer=randc(number) // number between 1 and number of pictures
            tempans[m]=num[answer]-1
            m++ // provisionally increase m here and subtarct later if it is a dup
            // now check for dup
            for (n=1; n<=(m-2); n++)
              {
//alert("in for  m = " + m + "  n = " + n )
              if (num[answer]-1 == tempans[n] )
                {
                m--
                }
            } //end for
         } // end else
      } //end while choices per picture

      // now swap 1 to the slot where the true choice should go
//alert ("in swap for reset ")
      truea = randc(cpp)
      tempansone = tempans[1]
      tempans[1]= tempans[truea]
      tempans[truea] = tempansone

      // now write out the buttons using the numbers in the temp array
      for (k=1; k<=cpp; k++)
        {
        if (k==truea)
          {
          // write true line with class true
          selid =  (pici+(cpp*(irows-1))) + "c" + k
//alert("selid for reset true = " + selid) 
          document.getElementById(selid).value=ans[tempans[k]]
          // must check for ie4 here since class attribute is classname in ie4
          if (ie4) { document.getElementById(selid).setAttribute("className","true") }
          else {  document.getElementById(selid).setAttribute("class","true") }
//alert("got to after ie4 check")
          // had to use gray and not lightgray since ie didn't like lightgray
          document.getElementById(selid).style.background="gray"
//alert("got to after change element background")
          // reset picture background when you insert true value since it is only once per td
          parent=document.getElementById(selid).parentNode
          parent.style.background="aqua"
//alert("got to after parent")
          }
        else
          {
          // write false line
            selid = (pici+(cpp*(irows-1))) + "c" + k
//alert("selid for reset false = " + selid) 
            document.getElementById(selid).value=ans[tempans[k]]
          if (ie4) { document.getElementById(selid).setAttribute("className","false") }
          else {  document.getElementById(selid).setAttribute("class","false") }
            document.getElementById(selid).style.background="gray"
          }
        } // end for which wrote out the buttons
// *old code starts here check it out
        j++ // increment to next picture
//alert(" got to inc to next picture in reset")
        // end the choices so write td
      } // end picture
    }// end write a row
  // end table
} // end resetpage


// ********** function to get random integer from 1 to num, returns the integer
function randc(num)
  {
  jrand = Math.round(Math.random()*100) // get an integer between 1 and 100
  if (jrand >= num) 
    {
    jrand = (jrand - ((Math.floor(jrand/num))*num)) + 1 // mod the num
    }
  else
    {
    jrand++
    }
  return jrand
  }


// ***********  function to print up large status over screen
function largestatusup(file)
  {
  document.getElementById("largestatus").setAttribute("src",file)
  }
