// war2.js - use with sink.html, fire.html or space.html
// All code and interface design are copyright Mike Capstick
// 210611 added sounds
// 300511 1. allows questions to contain a mixture of 4 or 5 distractors
//        2. simplified html files by moving code into this file
//        3. number of questions now unrestricted
//        4. test for empty tails to allow for other question banks to be used 

// 210411 - added support for quiz title
   if(typeof title!='string'){title=''} //  use quiz title if available
   
   maxterms=questions.length-1;  // how many questions in bank
   distractornum=0; // allows 4 or 5 distractors in a question

   //initialise parts of a question as a set of arrays
   stemarray=new Array();
   answer=new Array();
   adistract=new Array();
   bdistract=new Array();
   cdistract=new Array();
   ddistract=new Array();
   edistract=new Array();  //added to allow 5 distractors
   tail=new Array();
   var thisquestion=0;

//populate the questions arrays
for (i=0;i<maxterms;i++)
     { thisquestion=i+1;
       testsplit=questions[thisquestion].split('~');

        if ((testsplit[5]=='A')||(testsplit[5]=='B')||
            (testsplit[5]=='C')||(testsplit[5]=='D'))
             {distractornum=4;}  //  only 4 distractors, hide 5th
        else {distractornum=5;}

        shakeup(); // function to shuffle the answers

        stemarray[i]=testsplit[0];
        adistract[i]=testsplit[1];
        bdistract[i]=testsplit[2];
        cdistract[i]=testsplit[3];
        ddistract[i]=testsplit[4];
        if (distractornum==5)
           {edistract[i]=testsplit[5];
            answer[i]=testsplit[6];
            tail[i]=testsplit[7];
           }
        else {answer[i]=testsplit[5];
              tail[i]=testsplit[6];
             }
      }

// global variables
var response='0';       // set response to wrong
var hits=0;             // used to count hits
var questions=0;        // number of questions in this quiz (review)
ammo=maxterms;

// preload explosion
 soundfiles=['start.swf','correct1.swf','wrong1.swf','explode.swf'];

 for (i=0;i<soundfiles.length;i++)  //preload sound files
     {soundfiles[i]= new Object();}
     
function startup(){
   soundplayer('start.swf');
   document.getElementById('title').innerHTML=title+' '+aboxtitle;
}

function shakeup(){
   // function by <chris.wright@ mail.com> to shuffle the answers in some QGM games
   // input array testsplit[], [0]=Question, [1]-[4]=possible answers, [5]=key A-D to correct answer
   var abcde="ABCDE";
   var i // need to declare this to protect other counters
   for(i=1; i<=distractornum; i++)
      {
       var aa=testsplit[distractornum+1]; //the original answer position
       var x=aa.charCodeAt(0)-64; // convert ASCII code for answer into number in range 1-4
       var newplace=Math.ceil(Math.random()*distractornum);
       var temp=testsplit[newplace];
       testsplit[newplace]=testsplit[i];
       testsplit[i]=temp; //swap index with newplace
       if(i==x){testsplit[distractornum+1]=abcde.substring(newplace-1,newplace);}
       // if moving the answer, correct the answer flag
       if(newplace==x){testsplit[distractornum+1]=abcde.substring(i-1,i);} 
      }
}

function loadquestions(){
   // build questions and distractors into a string and randomise location of correct answer
   selectstring='';
   for (i=0;i<maxterms;i++)  //loop through questions
       {
          stem='q'+(i+1);  //build stem id

          // build stem and start select boxes
          selectstring=selectstring+"<span id='"+stem+"'>"+stemarray[i]+"</span> \n";
          selectstring=selectstring+"<select onchange='assess(this);' size='1' onfocus='unselected(this)' ";
          selectstring=selectstring+"id='question"+i+1+"'>\n";
          selectstring=selectstring+"<option value='0'></option>\n";

          // build the distractors A to D - 1st check if distractor is correct answer
          if (answer[i]=="A"){value=1} else{value=0}
          optionA="<option value='"+value+"'>"+adistract[i]+"</option>\n";

          if (answer[i]=="B"){value=1} else{value=0}
          optionB="<option value='"+value+"'>"+bdistract[i]+"</option>\n";
          
          if (answer[i]=="C"){value=1} else{value=0}
          optionC="<option value='"+value+"'>"+cdistract[i]+"</option>\n";

          if (answer[i]=="D"){value=1} else{value=0}
          optionD="<option value='"+value+"'>"+ddistract[i]+"</option>\n";

          optionE='';  //initialise possible 5th option as empty string
          // if edistract exists in this question add it as an option
          if(typeof edistract[i]=='string')
             {
              if (answer[i]=="E"){value=1} else{value=0}
              optionE="<option value='"+value+"'>"+edistract[i]+"</option>\n";
             }
             
          // if tail doesn't exist in question let it be empty string
          if(typeof tail[i]!='string'){tail[i]='';} 
          
          // fill select boxes with questions
          selectstring=selectstring+optionA+optionB+optionC+optionD+optionE+"</select> "+tail[i]+"<br />\n";

       }
   document.getElementById('questionsdiv').innerHTML=selectstring;
  
}

function resetgame(){
 response='0';  	// set response to wrong
 hits=0;        	// used to count hits
 questions=0;   	// set number of questions to 0
 document.getElementById('a1').style.visibility='hidden';
 document.getElementById('b1').style.visibility='hidden';
 document.getElementById('c1').style.visibility='hidden';
 document.getElementById('d1').style.visibility='hidden';
 document.getElementById('a2').style.visibility='hidden';
 document.getElementById('b2').style.visibility='hidden';
 document.getElementById('c2').style.visibility='hidden';
 document.getElementById('d2').style.visibility='hidden';
 document.getElementById('a3').style.visibility='hidden';
 document.getElementById('b3').style.visibility='hidden';
 document.getElementById('c3').style.visibility='hidden';
 document.getElementById('d3').style.visibility='hidden';
 document.getElementById('a4').style.visibility='hidden';
 document.getElementById('b4').style.visibility='hidden';
 document.getElementById('c4').style.visibility='hidden';
 document.getElementById('d4').style.visibility='hidden';
}

// The unselected function stops users from changing a selected answer
// It is called by an onfocus event. If an answer was picked it focus is sent to the window

function unselected(x){
   if(response=='1') //check the player has fired their correct amswer shot 
      {document.getElementById('resetbutton').focus(); //make drop box lose focus by focussing elsewhere
       alertboxer('<h1>Information</h1><p>You must fire a shot by Clicking  on a Map location.</p>');
       } 
   else{
        if (x.selectedIndex !=0)
           {document.getElementById('resetbutton').focus(); //make drop box lose focus by focussing elsewhere
	    if (gametype=='army') 
	       {alertboxer('<h1>Information</h1><p>That answer is locked in Soldier and cannot be changed !</p>');}
	    if (gametype=='fleet')
	       {alertboxer('<h1>Information</h1><p>That answer is locked in Sailor and cannot be changed !</p>');}
	    if (gametype=='space')
	       {alertboxer('<h1>Information</h1><p>That answer is locked in Space Cadet and cannot be changed !</p>');}
           }
       }
}

function assess(answer){             // assess a selected response
 // First we blur the current object to lock in the answer
 // we force loss of focus to prevent changes by focusing on the reset button
 //window.focus(); didn't  work for ns7, needs focus 
      document.getElementById('resetbutton').focus(); 

      questions=questions+1; // increment question(ammo) count - see fleet destroyed section
    // answer = this,  passed from onChange event by user selection
    // stores option value, 1 or 0 (correct or incorrect), in variable   response
     response = answer.options[answer.selectedIndex].value;

    //check response, increment score if correct and display result
      if (response=='1')
         {soundplayer('correct1.swf');
          answer.style.color='green';
          alertboxer("<h1>Correct</h1><p><img src='tick.gif' alt='tick' /><br /> Target a location on the Map and Fire at will !</p>");
         }
    else
         {soundplayer('wrong1.swf');
          answer.style.color='red';
          alertboxer("<h1>Incorrect</h1><p><img src='cross.gif' alt='tick' /><br /> Permission to fire denied !</p>"); 
          if (questions==ammo&&hits!=7)  // are we out of ammo
             {outofammo();}
         }
}

function outofammo(){ // check is no more questions available

   if (gametype=='army')
      {alertboxer("<h1>Information</h1><p>Looks like you're out of ammo Soldier !,<br /> Hit the New Game button to play again</p>")}
   if (gametype=='fleet')  
      {alertboxer("<h1>Information</h1><p>Looks like you're out of ammo Sailor !,<br /> Hit the New Game button to play again</p>");}
   if (gametype=='space')  
      {alertboxer("<h1>Information</h1><p>Looks like you're out of plasma bolts Space Cadet ,<br /> Hit the New Game button to play again</p>");}
}

function allowplay(x){
 // is player allowed a turn ?
   if(response=='1')
       {// allowed a turn, has cell been targeted before
         if(document.getElementById(x).style.visibility=='visible')
           { alertboxer('<h1>Information</h1><p>This location has been attacked already, Try another</p>');}
         else {showexplosion(x);
               soundplayer('explode.swf');
              }
       }
   else{
	if (gametype=='army')
	   {alertboxer("<h1>Information</h1><p>Soldier, before you can fire a shot you must answer a question correctly</p>")}
	if (gametype=='fleet')
           {alertboxer("<h1>Information</h1><p>Sailor, before you can fire a shot you must answer a question correctly</p>")}
	if (gametype=='space')
           {alertboxer("<h1>Information</h1><p>Space cadet, before you can fire a shot you must answer a question correctly</p>")}
	}
}

function showexplosion(x){
  // store cell while displaying explosion
  cellcontents=document.getElementById(x).parentNode.innerHTML;
  
  document.getElementById('cell'+x).style.backgroundColor='black';
  document.getElementById('cell'+x).innerHTML="<img src='smallexplosion.gif' alt=''/>";
  ship=x;
  timer=setTimeout("fireshot(ship)",1200);
}

function fireshot(x){
  document.getElementById('cell'+x).innerHTML=cellcontents;
  document.getElementById('cell'+x).style.backgroundColor='transparent';
  document.getElementById(x).style.visibility='visible';
  response='0';  // reset response to zero - must get another question right to fire again

  document.getElementById(ship).style.visibility="visible";
 if (gametype=='army')
    {if (document.getElementById(ship).innerHTML=="B")
        {alertboxer("<h1>Congratulations</h1><p>Excellent, You hit part of their Military Base</p>");}
     if (document.getElementById(ship).innerHTML=="M")
        {alertboxer("<h1>Congratulations</h1><p>You hit their Missile Launcher</p>");}
     if (document.getElementById(ship).innerHTML=="S")
        { alertboxer("<h1>Congratulations</h1><p>You Killed an enemy Soldier</p>");}
     if (document.getElementById(ship).innerHTML=="x")
        { alertboxer("<h1>Information</h1><p>You missed, Soldier</p>");}
 
     // Is the army destroyed  - count hits if any cell has a vehicle that is hit
     if (document.getElementById(ship).innerHTML=="B"||
         document.getElementById(ship).innerHTML=="M"||
         document.getElementById(ship).innerHTML=="S")
        {hits=hits+1;
         if (hits==7)
            {message='';
             message='<h1>Congratulations</h1><p>The Army is destroyed.<br />';
             message=message+' Congratulations on your promotion to Captain !<br /> Hit the New Game button to play again</p>';
             alertboxer(message);
             resetgame(); 
            }
        }                  
      if (questions==ammo&&hits!=7)  // are we out of ammo
         {outofammo();}
   }

if (gametype=='fleet')   
   {
     if (document.getElementById(ship).innerHTML=="B")
        { alertboxer("<h1>Congratulations</h1><p>Excellent, You hit their Battleship</p>"); }
     if (document.getElementById(ship).innerHTML=="M")
        { alertboxer("<h1>Congratulations</h1><p>You hit their Mine Sweeper</p>"); }
     if (document.getElementById(ship).innerHTML=="S")
        { alertboxer("<h1>Congratulations</h1><p>You destroyed an enemy Submarine</p>"); }
     if (document.getElementById(ship).innerHTML=="x")
        { alertboxer("<h1>Information</h1><p>You missed, Sailor</p>"); }
                          
      // Is the naval fleet destroyed  - count hits if any cell has a ship that is hit
     if (document.getElementById(ship).innerHTML=="B"||
         document.getElementById(ship).innerHTML=="M"||
         document.getElementById(ship).innerHTML=="S")
        {hits=hits+1;
         if (hits==7)
            {message='';
             message='<h1>Congratulations</h1><p>The Fleet is destroyed.<br /> Congratulations on your promotion to Captain !'
             message=message+'<br /> Hit the New Game button to play again.</p>';
             alertboxer(message);
             resetgame();
             }
         }
     if (questions==ammo&&hits!=7)  // are we out of ammo
        {outofammo();}
   }

if (gametype=='space')  
   {if (document.getElementById(ship).innerHTML=="B")
       { alertboxer("<h1>Congratulations</h1><p>Excellent, You hit their Star Base</p>"); }
    if (document.getElementById(ship).innerHTML=="M")
        { alertboxer("<h1>Congratulations</h1><p>You hit their Mind Control Ship</p>"); }
     if (document.getElementById(ship).innerHTML=="S")
        { alertboxer("<h1>Congratulations</h1><p>You vapourised a Star Fighter</p>"); }
     if (document.getElementById(ship).innerHTML=="x")
        { alertboxer("<h1>Information</h1><p>You missed, Space Cadet</p>"); }
            
     // Is the space fleet destroyed  - count hits if any cell has a ship that is hit
     if (document.getElementById(ship).innerHTML=="B"||
         document.getElementById(ship).innerHTML=="M"||
         document.getElementById(ship).innerHTML=="S")
        {hits=hits+1;
         if (hits==7)
            {message='';
             message='<h1>Congratulations</h1><p>The Alien Fleet is destroyed.<br /> Congratulations on your promotion to Space Captain !'
             message=message+'<br /> Hit the New Game button to play again.</p>';
             alertboxer(message);
             resetgame();
            }
        }
     if (questions==ammo&&hits!=7)  // are we out of ammo
        {outofammo();}
      }
}

function soundplayer(sound)
{ // add the swf sound to player object, flashobject
  flashobject='<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"' + '\n' +
 	'codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab\"' + '\n' +
 	'width=0 height=0 id=untitled>' + '\n' +
        '<param name=movie value=\"' + sound + '\">' + '\n' +
        '<param name=quality value=low>' + '\n' +
        '<embed name=\"' + this.playerID + '\"' + '\n' +
	       'src=\"' + sound + '\" quality=low ' + '\n' +
	       ' width=0 height=0 type=\"application/x-shockwave-flash\"' + '\n' +
        '</embed></object>';
   // add the string to an element sndplayer at end of page with innerHTML method
   document.getElementById("sndplayer").innerHTML=flashobject;
}
