// swim5.js
// javascript for Charlemagne swim game
// copyright (C)  2007-2009 All rights reserved
// copied from swim4 on 3 Aug 2009
// 09/25/07 made im a two dimensional array
// 09/25/07 changed from setTimer to setInterval so no window hangs
// 09/25/07 made arx and ary a two deminsional array
// 09/25/07 when going from 2 to 3 must set arx and ary at curind for wakeup
// 08/03/09 gcp enhanced to make charlamagne and suzieq bigger 

var timerflag = 0 // flag to show timer state 1 = on 0 = off, off initially
var fishind     // charlemagne=0, suzieQ = 1, other=2
var numfish = 2 // number of fish
var ci          // counter for number of fish
// the state of each fish, 1=random swim, 2= swim to cursor, 3= park, 4= follow cursor
var state = new Array() 
var cval  = new Array()   // number of image to use as he swims

var fromx = new Array()  //from position x for each fish used in swimto
var fromy = new Array()
var tox   = new Array()  // to position for each fish
var toy   = new Array()

var i                    // counter for items
var soundarray = new Array()

ver=parseInt(navigator.appVersion)
ie4=(ver>3  && navigator.appName!="Netscape" && navigator.appName!="Opera")?1:0
op= navigator.appName=="Opera"?1:0
ns4=(ver>3  && navigator.appName=="Netscape")?1:0
ns3=(ver==3 && navigator.appName=="Netscape")?1:0
//alert("appName =" + navigator.appName + " ver=" + ver)

var im  = new  Array()     // to hold fish immages
im[0] = new Array()        // to hold array for first fish
im[1] = new Array()        // to hold array for second fish

var arx = new  Array()     // arrays to hold trail values
arx[0] = new Array()       // make it two dimension for each fish
arx[1] = new Array()
var ary = new  Array()
ary[0] = new Array()
ary[1] = new Array()

var delx                   // place to hold offset of picture
var dely

var newind   = new Array() // index for trail new item
var curind   = new Array() // index for out item
var fishname = new Array() // one name for each fish matches in img statement
var statetext = new Array  // place to store text for status message

// ****************  come here on load
function initialize()
  {
  // set state for fish initially to park
  for (ci=0; ci<=(numfish-1); ci++ )
    {
    state[ci] = 1 // set to random swim initially
    cval[ci]  = 4 // set initial facing direction to right
    fromx[ci] = 0 // set initial position of fish must agree with html
    fromy[ci] = 0 
    swimtimelength[ci] = 8 // initial random swim time
    swimdir[ci] = 2 // start fishes swiming south east
// alert("fromx in initialize = " + fromx + "  ci = " + ci)
    } // end initialize for each fish

  // fish 1
  // cval = 1 up left, 2 down left, 3 left, 4 right, 5 up right, 6 right down 
  charl0 = new Image(52,54)
  charl0.src ="charlemagneleftup52x54.gif"
  charl1 = new Image(52,54)
  charl1.src="charlemagneleftdown52x54.gif"
  charl2 = new Image(52,54)
  charl2.src="charlemagneleft52x54.gif"
  charl3 = new Image(52,54)
  charl3.src="charlemagneright52x54.gif"
  charl4 = new Image(52,54)
  charl4.src="charlemagnerightup52x54.gif"
  charl5 = new Image(52,54)
  charl5.src="charlemagnerightdown52x54.gif"



  // fish 2
  // cval = 1 up left, 2 down left, 3 left, 4 right, 5 up right, 6 right down 
  char20 = new Image(55,58)
  char20.src ="suzieqleftup55x58.gif"
  char21 = new Image(55,58)
  char21.src="suzieqleftdown55x58.gif"
  char22 = new Image(55,58)
  char22.src="suzieqleft55x58.gif"
  char23 = new Image(55,58)
  char23.src="suzieqright55x58.gif"
  char24 = new Image(55,58)
  char24.src="suzieqrightup55x58.gif"
  char25 = new Image(55,58)
  char25.src="suzieqrightdown55x58.gif"


  im[0][0]=charl0
  im[0][1]=charl1
  im[0][2]=charl2
  im[0][3]=charl3
  im[0][4]=charl4
  im[0][5]=charl5
  im[1][0]=char20
  im[1][1]=char21
  im[1][2]=char22
  im[1][3]=char23
  im[1][4]=char24
  im[1][5]=char25

  statetext[0]="            "
  statetext[1]="Random Swim "
  statetext[2]="Swim To Hand"
  statetext[3]="Sleep       "
  statetext[4]="Follow Hand "

  //  code to initialize offsets 
  delx=-( document.getElementById("pictdiv").offsetLeft)
  dely=-( document.getElementById("pictdiv").offsetTop)

  // set up the initial positions of the fish so they can swim to cursor
  // note 8 is the current index at the start and must be matched with that value
  // elsewhere in the code
  for (ci=0; ci<=(numfish-1); ci++)
    {
    // for each fish 0 out the moving arrays
    prime(ci,0,0) // sets array to 0 and sets curind[ci] = 8 and newind[ci] = 0
    } // end of priming trailing arrays



  // set the fishs names for moving them
  fishname[0] = "charlemagne"
  fishname[1] = "suzieq"
  fishind = 0                  // set fish to charlemagne at beginning
  setstatuscolor(0,"lightgreen")    // show colors in status bar
  setstatuscolor(1,"lightpink")

   
//   gcpstartTimer() // start the random swim

  } // end initialize

// ********************  set status in the status bar
function setstatus(whichfish)
  {
  // get the cells in the status table
  srow=document.getElementById("status").rows[0].cells
  if (whichfish == 0 )
    {
    // show for charlemagne
    srow[1].innerHTML=statetext[state[whichfish]]
    }
  if (whichfish == 1 )
    {
    // show for charlemagne
    srow[4].innerHTML=statetext[state[whichfish]]
    }
  // if not 0 or 1 then dont change status
  } // end of setstatus

// ********************  set status cell color in the status bar
function setstatuscolor(cwhichfish,cwhichcolor)
  {
  var dwhichcolor
  var cwhichfish
  // get the cells in the status table
  srow=document.getElementById("status").rows[0].cells
  if (cwhichfish == 0 )
    {
    // show for charlemagne
    srow[0].style.background=cwhichcolor
    srow[1].style.background=cwhichcolor
    }
  if (cwhichfish == 1 )
    {
    // show for charlemagne
    srow[3].style.background=cwhichcolor
    srow[4].style.background=cwhichcolor
    }
  // if not 0 or 1 then dont change color
  } // end of setstatus



// ********************* function to set state on click
function conclick(gcpevent)
  {
// the state of each fish, 1=random swim, 2= swim to cursor, 3= park, 4= follow cursor
// alert("got to conclick state[fishind] = " + state[fishind])



  if (state[fishind] == 1) 
    {
    // random fish swim to cursor
    state[fishind]=2
    setstatus(fishind) // set the status to new state for this fish
    tox[fishind] = gcpevent.clientX + delx //  get coordinates
    toy[fishind] = gcpevent.clientY + dely //
// alert(" swim to tox[fishind] = " + tox[fishind] + "  toy[fishind] = " + toy[fishind])
    gcpswimcursor(fishind,gcpevent) // start the swimming
    }
  else if (state[fishind] == 2) 
    {
    // swim to cursor fish parked
    state[fishind]=3
    setstatus(fishind) // set the status to new state for this fish
    // if we do this we must set the current index so fish can start again
    arx[fishind][curind[fishind]] = fromx[fishind]
    ary[fishind][curind[fishind]] = fromy[fishind]
    } 
  else if (state[fishind] == 3) 
    {
    // parked fish to swim randomly
    state[fishind]=1
    setstatus(fishind) // set the status to new state for this fish
    // now must set the fromx and from y locations to the arx[curind[fishind]] value
    fromx[fishind] = arx[fishind][curind[fishind]]
    fromy[fishind] = ary[fishind][curind[fishind]]
    }
  else if (state[fishind] == 4) 
    {
    // follow cursor fish parked
    state[fishind]=3
    setstatus(fishind) // set the status to new state for this fish
    }
  else 
    {
    alert("in conclick, fishind = " + fishind + "  unknown state = " + state[fishind] ) // shouldn't get here
    }
//    alert("fish state after onclick = " + state[fishind] )
  } // end conclick

// *******************************************************************
// ********************** function to change fish when shift is pressed
// event e is passed in, sets global variable fishind to show fish
// fishind = 0 = charlemagne 1= suzie 2= other
function ckeypress(e)
  {
  // get the character pressed
// alert("got to keypressed")
  var keynum
  var keychar

  if(ie4)
    {
    // IE
    keynum = e.keyCode
    }

  else  
    {
    // Netscape/Firefox/Opera
    keynum = e.which
    }

  keychar = String.fromCharCode(keynum)
  // get a fish number
  if (keychar == "c")
    {
    if (fishind == 1) 
      {
      // charlemagne
      fishind = 0
      setstatuscolor(0,"lightgreen")
      setstatuscolor(1,"lightpink")
      }
    else if (fishind == 0)
      {
      // had to flip on c because in opera other chars were used to move between fields
      // suzieQ
      fishind = 1
      setstatuscolor(0,"lightpink")
      setstatuscolor(1,"lightgreen")
      } 
    } // end key is c for change
  else
    {
    // any other key ignore
    }
// alert(" out of keypress key = " + keychar + "  fishind = " + fishind)
  }  // end ckeypress

var gcpevent
// ******************** funtion to handle mouse moves
function conmousemove(gcpevent)
  {
// alert("in conmousemove move ci = " + ci + "  state = " + state[ci] + "  x = " + gcpevent.clientX )
  // check if timer should be on  turns out the conmousemove has precedence over the
  // onmousein function and so starttimer does not get called from the window.
  if (t == 0 )
    {
    // turn it on cause we are moving
    gcpstartTimer()
    } // end timer not started

  for (ci=0; ci<=numfish-1; ci++)
    {
    // do nothing for state 1, 2, and 3
    if (state[ci] == 4) 
      {
// alert("in conmousemove move state = " + state[ci] + "  x = " + gcpevent.clientX + "  ci = " + ci )
      gcpmove(ci,gcpevent.clientX,gcpevent.clientY) // move the fish after the cursor
      }
    } // end for each fish
  } // end conmousemove

var t = 0 // used for timeout functon return must be initially 0
// ********************* funtion to stop timer
function gcpstopTimer()
  {
// alert("got to stopTimer")
  // stops timing on variable t
  if (t == 0)
    {
    // error so abort stoping timer
    alert("timer error timer not going please refresh page, t = " + t)
    return
    }
  // we use a try catch here because if interval timer not stopped we have problem
  // because multiple timers may get started.
  try
    {
    clearInterval(t) // stop the interval timer
    }
  catch(err)
    {
    alert("error stopping timer, please refresh page, t= " + t)
    return
    }
    // if no error interval is stopped so set t to 0
    t=0     
  } // end gcpstopTimer

// ******************** function to start timer
function gcpstartTimer()
  {
// alert("got to gcpstartTimer")
  if (t == 0) 
    {
    // timer is stopped so start timer again
    t = setInterval("ctimer()",150) 
    }
  else if (t==null)
    {
     return // a startup condition in opera
    }
  else
    {
    // if we get here there is an error cause it is supposed to be stopped
    alert("timer error, timer not stopped, fish will not swim randomly or to cursor t =" + t)
    }
  } // end gcpstartTimer

// ******************** function to handle timer callback
function ctimer()
  {
  for (ci=0; ci<=numfish-1; ci++)
    {
// alert("got to ctimer and state = " + state[ci] + "  ci = " + ci)
    // do nothing for state 4 and 3
    if (state[ci] == 1) 
      {
      gcprand(ci) // random swim
      }
    if (state[ci] == 2) 
      {
      gcpswimcursor(ci) // swim to cursor
      }
    } // end for each fish on timeout
  } // end ctimer

//  ******************** play sound clip input is file
function playsound(a) 
  {
  // set the player controls
  document.Player.URL = a
  try
    {
    document.Player.controls.play();
    }
  catch(err)
    {
    // problem with netscape and player controls so catch error and continue
    }
  } // end playsound

// ******** code for the trailing cursor ****************************
var newind = new Array() // indices for trail
var curind = new Array()

// *************** come here when state changes to trailing
// this code primes the trailing array
function prime(fishid,clientx,clienty)
  {
// alert(" in prime fishid = " + fishid + "  clientx = " + clientx + "  delx = " + delx)
  // prime the trailing array with points
  for (i=0; i <= 28; i++) 
    {
    arx[fishid][i] = clientx+delx
    ary[fishid][i] = clienty+dely
    }

  newind[fishid]=0 // index to put new coords
  curind[fishid]=8 // index to remove old coords
// alert(" in prime arx[fishid][8] = " + arx[fishid][8] )
} // end arm

// ********  function gcpmove to actually do the moving
//  uses delx, dely, arx, ary, lastind, curind, newind, cval, offx, offy

var lastind = new Array() // index of last point  for current used to find direction
var offx = new Array() // offset for moving right left 
var offy = new Array() // offset for moving up down
var movex // pos to move fish to used in boundry checking
var movey // pos to move fish to used in boundry checking


function gcpmove(fishid,clientx,clienty)
  {
// alert("in gcpmove clientx = " + clientx + "  clienty = " + clienty )
  // first test for internet explorer
//  if (ie4==1) 
//    {    
    // get cursor position and save it at new cursor
    arx[fishid][newind[fishid]]=clientx+delx   
    ary[fishid][newind[fishid]]=clienty+dely  
// alert("in firstmove = clientx+delx = " + arx[fishid][newind[fishid]])
    // set new coordinates

    // first find the last index to help choose direction fish faces
    if (curind[fishid] == 1) { lastind[fishid]=29} 
    else {lastind[fishid] = curind[fishid] -1}

    // Now choose image for which direction fish is going
    // cval = 0 up left, 1 down left, 2 left, 3 right, 4 up right, 5 right down 
    if ( (arx[fishid][curind[fishid]] - arx[fishid][lastind[fishid]]) > 0) 
      {
      // we are moving right
      if ((ary[fishid][curind[fishid]] - ary[fishid][lastind[fishid]]) < 0)
        {
        // we are moving right up
        cval[fishid] = 4
        offx[fishid] = +15
        offy[fishid] = +15
        }
      else if ((ary[fishid][curind[fishid]] - ary[fishid][lastind[fishid]]) > 0)
        {
        // we are moving right down
        cval[fishid] = 5
        offx[fishid] = -15
        offy[fishid] = -15
        }
      else
        {
        // we are right level
        cval[fishid] = 3
        offx[fishid] = -15
        offy[fishid] = 0
        }
      } // end if right
    else if ( (arx[fishid][curind[fishid]] - arx[fishid][lastind[fishid]]) < 0) 
      {
      // we are moving left
      if (( ary[fishid][curind[fishid]] - ary[fishid][lastind[fishid]]) < 0)
        {
        // we are moving left up
        cval[fishid] = 0
        offx[fishid] = -15
        offy[fishid] = +15
        }
      else if ((ary[fishid][curind[fishid]] - ary[fishid][lastind[fishid]]) > 0)
        {
        // we are moving left down
        cval[fishid] = 1
        offx[fishid] = -15
        offy[fishid] = -15
        }
      else
        {
        // we are left level
        cval[fishid] = 2
        offx[fishid] = -15
        offy[fishid] = 0
        }
      } // end if left
    else
      {
      // moving straight up or down so leave it same
      }
// alert("fishid = " + fishid + "  curind[fishid] = " + curind[fishid])
// alert("arx[fishid][curind[fishid]] =" + arx[fishid][curind[fishid]])
    // check for swimming off page
    movex = arx[fishid][curind[fishid]]-10 
    movey = ary[fishid][curind[fishid]]-10
    if (movex < 0 ) { movex = 0 }
    if (movex > maxx) { movex = maxx }
    if (movey < 0 ) { movey = 0}
    if (movey > maxy) { movey = maxy }
    document.getElementById(fishname[fishid]).style.left=movex
    document.getElementById(fishname[fishid]).style.top =movey
//alert("got to after get element")
    // set direction fish faces
    document.getElementById(fishname[fishid]).src=im[fishid][cval[fishid]].src
//  document.getElementById(fishname[fishid]).style.z-index=8

      
    newind[fishid]= newind[fishid] + 1  // increment the indexs
    curind[fishid]= curind[fishid] + 1
    if (newind[fishid] >= 29) 
      {
      newind[fishid] = 0 // loop the indexs
      }
    if (curind[fishid] >= 29) 
      {
      curind[fishid] = 0
      }	
    return false
 //   } // end of ie4
  }  // end of gcpmove fish

var gcp1event // event passed in
// *********************************************************************************
// ************* funtion to swim a fish to the cursor not warp it
// takes fishind as input
function gcpswimcursor(whichfish,gcp1event)
  {
// alert("in swim while whichfish = " + whichfish + "  state = " + state[whichfish] + "  fromx = " + fromx[whichfish] + "  tox = " + tox[whichfish] + "  fromy = " + fromy[whichfish] + "  toy = " + toy[whichfish])
      if (fromy[whichfish] == toy[whichfish] && fromx[whichfish] == tox[whichfish]) 
        {
        // get out if already there
// alert(" in swim to cursor switch to state 4")
        state[whichfish] = 4 // follow cursor after you get to cursor
        setstatus(whichfish) // set the status to new state for this fish
        // prime the array with coordinates for this location
        // subtract delx and dely since prime adds it back
        prime(whichfish,tox[whichfish]-delx,toy[whichfish]-dely) 
        return
        }
      if (fromx[whichfish] < tox[whichfish])
        { 
        fromx[whichfish] = fromx[whichfish] + 5
        cval[whichfish] = 3 // face right
        if (fromx[whichfish] > tox[whichfish]) {fromx[whichfish] = tox[whichfish]}
        }
      else if (fromx[whichfish] > tox[whichfish])
        {
        fromx[whichfish] = fromx[whichfish] - 5
        cval[whichfish] = 2 // face left
        if (fromx[whichfish] < tox[whichfish]) {fromx[whichfish] = tox[whichfish]}
        }
      if (fromy[whichfish] < toy[whichfish])
        {
        fromy[whichfish] = fromy[whichfish] + 5
        if (fromy[whichfish] > toy[whichfish]) {fromy[whichfish] = toy[whichfish]}
        }
      else if (fromy[whichfish] > toy[whichfish])
        {
        fromy[whichfish] = fromy[whichfish] - 5
        if (fromy[whichfish] < toy[whichfish]) {fromy[whichfish] = toy[whichfish]}
        }
      // actually move the fish here
// alert("whichfish = " + whichfish + "  fromx = " + fromx[whichfish] )
      document.getElementById(fishname[whichfish]).style.left=fromx[whichfish]
      document.getElementById(fishname[whichfish]).style.top=fromy[whichfish]
      document.getElementById(fishname[whichfish]).src=im[whichfish][cval[whichfish]].src
  } // end function swimto


// ********** 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
  }

var maxx = 645 // width of display based on picture shown in html
var maxy = 445 // max height of display
var swimdir = new Array()     // direction in which fish swims randomly
var swimtimelength = new Array() // number of cycles to swim in one direction

// ***************** gcprand random swim
function gcprand(whichfish)
  {
  var whichfish // tells what fish it is
  // only come here if state is correct so just do the swim
  swimtimelength[whichfish] = swimtimelength[whichfish] - 1
// alert( "gcprand swimtimelength = " + swimtimelength[whichfish]) 
  if (swimtimelength[whichfish] == 0 )
    {
    // must change direction and length of swim
    // swimdir is 0= north, 1= northeast,2= east, 3= south east, 4=south
    // 5= south west, 6= west, 7= north west
    swimdirold = swimdir[whichfish] // same old direction
    swimdir[whichfish] = randc(8)-1 // number between 0 and 7
    // now get a length in cycles 1 to 40
    swimtimelength[whichfish] = randc(40) 
    }  // end check direction

  // Also choose image for which direction fish is going
  // cval = 0 up left, 1 down left, 2 left, 3 right, 4 up right, 5 right down 
  // now calculate the move to swim
  if (swimdir[whichfish] == 0 )
    { 
    // swim north
    if (swimdirold == 2 || swimdirold == 1) {cval[whichfish]=0}        // go up right
    else if (swimdirold == 3 || swimdirold == 5) { cval[whichfish]=4}  // go up left
    fromy[whichfish] = fromy[whichfish] - randc(10)
    if (fromy[whichfish] < 0) { fromy[whichfish] = 0; swimtimelength[whichfish] = 1}
    }
  else if (swimdir[whichfish] == 0 )
    { 
    // swim north east
    cval[whichfish]=4
    fromx[whichfish] = fromx[whichfish] + randc(10)
    if (fromx[whichfish] > maxx) { fromx[whichfish] = maxx; swimtimelength[whichfish] = 1}
    fromy[whichfish] = fromy[whichfish] - randc(10)
    if (fromy[whichfish] < 0) { fromy[whichfish] = 0;       swimtimelength[whichfish] = 1}
    } 

  else if (swimdir[whichfish] == 1 )
    { 
    // swim east
    cval[whichfish]=3
    fromx[whichfish] = fromx[whichfish] + randc(10)
    if (fromx[whichfish] > maxx) { fromx[whichfish] = maxx; swimtimelength[whichfish] = 1}
    } 

  else if (swimdir[whichfish] == 2 )
    { 
    // swim south east
    cval[whichfish]=5
    fromx[whichfish] = fromx[whichfish] + randc(10)
    if (fromx[whichfish] > maxx) { fromx[whichfish] = maxx; swimtimelength[whichfish] = 1}
    fromy[whichfish] = fromy[whichfish] + randc(10)
    if (fromy[whichfish] > maxy) { fromy[whichfish] = maxy; swimtimelength[whichfish] = 1}
    } 

  else if (swimdir[whichfish] == 3 )
    { 
    // swim south
    if (swimdirold == 2 || swimdirold == 1) {cval[whichfish]=1}       // go down left
    else if (swimdirold == 3 || swimdirold == 5) { cval[whichfish]=5} // go down right
    fromy[whichfish] = fromy[whichfish] + randc(10)
    if (fromy[whichfish] > maxy) { fromy[whichfish] = maxy; swimtimelength[whichfish] = 1}
    } 

  else if (swimdir[whichfish] == 4 )
    { 
    // swim south west
    cval[whichfish]=1
    fromx[whichfish] = fromx[whichfish] - randc(10)
    if (fromx[whichfish] <= 0) { fromx[whichfish] = 0;      swimtimelength[whichfish] = 1}
    fromy[whichfish] = fromy[whichfish] + randc(10)
    if (fromy[whichfish] > maxy) { fromy[whichfish] = maxy; swimtimelength[whichfish] = 1}
    } 

  else if (swimdir[whichfish] == 5 )
    { 
    // swim west
    cval[whichfish]=2
    fromx[whichfish] = fromx[whichfish] - randc(10)
    if (fromx[whichfish] <= 0) { fromx[whichfish] = 0; swimtimelength[whichfish] = 1}
    } 

  else if (swimdir[whichfish] == 6 )
    { 
    // swim north west
    cval[whichfish]=0
    fromx[whichfish] = fromx[whichfish] - randc(10)
    if (fromx[whichfish] <= 0) { fromx[whichfish] = 0; swimtimelength[whichfish] = 1}
    fromy[whichfish] = fromy[whichfish] - randc(10)
    if (fromy[whichfish] <= 0) { fromy[whichfish] = 0; swimtimelength[whichfish] = 1}
    } 
  else 
    {
    // bad direction value do nothing
// alert("bad direction value swimdir[whichfish] = " + swimdir[whichfish])
    }

  // actually move the fish here
// alert("in gcprand whichfish = " + whichfish + "  fromx[whichfish] = " + fromx[whichfish])
  document.getElementById(fishname[whichfish]).style.left=fromx[whichfish]
  document.getElementById(fishname[whichfish]).style.top =fromy[whichfish]
  // now the direction gif
  document.getElementById(fishname[whichfish]).src=im[whichfish][cval[whichfish]].src

  } // end gcprand


