/* 
 This file was generated by Dashcode.  
 You may edit this file to customize your widget or web page 
 according to the license.txt file included in the project.
 */

var animalsArray = new Array();  // working array to hold data
var count = 1;  // array index
var guess = false; // guess toggle
var q = ""; // database text value
var thisguess = ""; // a program-guessed animal
var newanimal = ""; // a user-added animal
var newquestion = ""; // a user-added question
var prefix = ""; // grammar check
var hide=false; // show/hide list

var message1 = "Think of an animal and I will try to guess what it is.";
var message2 = "Let's play again! Think of another animal and I will try to guess what it is.";
var message3 = "Are you thinking of an animal?";
var message4 = "I give up! The animal you were thinking of was a ?";
var message5 = "Please type in a question which would help me distinguish a";

//
// Function: load()
// Called by HTML body element's onload event when the web application is ready to start
//
function load()
{
   dashcode.setupParts();
   initGuesses();
}

//
// save typing
//
function $(id) {
	return document.getElementById(id);
}   

//
// Function: flipToFront(event)
// Flip to the front view to show the normal utility view
//
function flipToFront(event)
{
    var views = document.getElementById('views');
    var front = document.getElementById('front');
    if (views && views.object && front) {
        views.object.setCurrentView(front, true);
    }
}

//
// Function: flipToSettings(event)
// Flip to the back view to present user customizable settings
//
function flipToSettings(event)
{
    var views = document.getElementById('views');
    var settings = document.getElementById('settings');
    if (views && views.object && settings) {
        views.object.setCurrentView(settings);
    }
}


//
// Function: showError(errorString)
// Show an error
//
function showError(errorString)
{
    var element = document.getElementById('message');
    element.value = errorString;
}

//
// Function: clearSettings()
// Reset settings to defaults
//
function clearSettings(event)
{
         animalsArray.length = 0; // remove animals from memory
        initGuesses();          
        alert("Game reset to defaults!"); 
 }

//
// Function: initGuesses()
// Initialize the guesses array to defaults
//
function initGuesses()
{  
            animalsArray[0] = 10;
            animalsArray[1] = "/QDoes it swim/Y2/N3/";
            animalsArray[2] = "/QDoes it have legs/Y5/N4/";
            animalsArray[3] = "/QDoes it fly/N7/Y6/";
            animalsArray[4] = "/AWHALE";
            animalsArray[5] = "/ACROCODILE";
            animalsArray[6] = "/ABUTTERFLY";
            animalsArray[7] = "/QDoes it have fur/Y9/N8/";
            animalsArray[8] = "/AELEPHANT";        
            animalsArray[9] = "/ATIGER";         
}

//
// sets up the game when the play button is pressed
//
function setupPlay(event)
{
    if (count > 1) {return};
    hideList();
    $("box1").style.visibility = "visible";
    $("message").style.visibility = "visible";  $("message").innerText = message1;
    $("box2").style.visibility = "visible";
    $("smallmessage").style.visibility = "visible";  $("smallmessage").innerText = message3;  
    $("button4").style.visibility = "visible";
    $("button5").style.visibility = "visible"; $("button5").object.setEnabled(false);
    guess = false;      
  }

//
// Yes button code
function yesResponse(event)
{ var yes = "Y";
    response = "";
    processResponses(yes); 
}

//
//No button code
function noResponse(event)
{
  var no = "N";
  response = "";
  processResponses(no); 
}

//
//function to deal with yes/no answers from response buttons
//
function processResponses(response)   
{ 
    if ( $("message").innerText.substring(0,5) == "For a")
        { processNewAnimal(response); } 
      if (guess) { processGuesses(response) } else if ($("smallmessage").innerText == message3)
             { printQuestions(); }
          else { processAnswers(response); }
}

//
// extract and print questions from working array
//
function printQuestions()
{
    $("button5").object.setEnabled(true); //enable the No button
    q = animalsArray[count];
    var upto = q.indexOf('/',1); 
    var questiontext = q.substring(2,upto) + "?"; 
        
    $("smallmessage").innerText = questiontext;
}

//
// work through the array looking for matches
//
function processAnswers(response)
{
    var t = "/" + response; 
        for (var i=2; i<(q.length)-1; i++)
            { var z = q.substring(i,i+2); 
            if (z == t) { break; }
            }
              for (var j = (i+1); j<q.length; j++)
                {  var u = q.substring(j,j+1);
                if (u == "/")
                     { var v = q.substring(i+2,j); break; } 
                } 
        count = v*1; // change string value to integer
        checkAnimals();   
}

//
// prints the next question or takes a guess
//
function checkAnimals()
{
    q = animalsArray[count]; var l = q.length;
    if (l == 0) { showError("DB error, try resetting game"); }
    if (q.substring(0,2) == "/Q") 
        { printQuestions(); } else
            {  thisguess = q.substring(2,l);
                checkGrammar(thisguess);
                $("smallmessage").innerText = "Is it a" + prefix + thisguess + "?"; 
                 guess = true;            
         }
}

// 
// new game if correct, add animal if not
//
function processGuesses(response)
{  guess = false;
    if (response == "Y") 
        { $("message").innerText = message2;  count=1;
         $("smallmessage").innerText = message3; $("button5").object.setEnabled(false); } else
        { $("message").innerText = message4;
          $("smallmessage").style.visibility = "hidden";
          $("textfield").style.visibility = "visible";
          $("button4").object.setEnabled(false); //disable the buttons
          $("button5").object.setEnabled(false); 
          $("textfield").focus();
                    }
}

//
// defines a new animal and new question
//
function addAnimal()
{   
    newanimal = $("textfield").value; $("textfield").value = ""; 
    newanimal = newanimal.toUpperCase(); 
    checkGrammar(newanimal); var temp = prefix;
    checkGrammar(thisguess); 
    $("message").innerText = message5 + temp + newanimal + " from a" + prefix + thisguess; 
}

//
// receives answer
//
function getNewAnswer()
{   
    checkGrammar(newanimal);
    $("message").innerText = "For a" + prefix + newanimal + " the answer would be ?";
    $("textfield").style.visibility = "hidden";
    $("box2").style.visibility = "hidden";
    $("smallmessage").style.visibility = "hidden";
    $("button4").object.setEnabled(true); //enable the buttons
    $("button5").object.setEnabled(true); 
    prefix = "";
}

//
// places the answer appropriately
//
function processNewAnimal(response)
{
    var B ="";
    if (response == "Y") { B = "N"; } 
    if (response == "N") { B = "Y"; }
    var Z = animalsArray[0]; Z = Math.round(Z);  // get rid of the decimals
    animalsArray[0] = Z+2;
    animalsArray[Z] = animalsArray[count];
    animalsArray[Z+1] = "/A" + newanimal;
    var newentry = "/Q" + capitalise(newquestion) + "/" + response + Math.round(Z+1) + "/" + B + Z + "/";
    animalsArray[count] = newentry; // insert new question
                            
        $("message").innerText = message2; 
        $("box2").style.visibility = "visible";
        $("smallmessage").style.visibility = "visible";
        $("smallmessage").innerText = message3;
        count = 1; guess = false;  // next game
}


//
// corrects message for animals beginning with vowel
//
function checkGrammar(word)
{   var wordtocheck = word.substring(0,1).toUpperCase(); 
    switch (wordtocheck)
     {
       case "A":
       prefix = "n ";
       break;
       case "E":
       prefix = "n ";
       break;
       case "I":
       prefix = "n ";
       break;
       case "O":
       prefix = "n ";
       break;
       case "U":
       prefix = "n ";
       break;
       default:
       prefix = " ";
     }
return prefix;
}

//
// capitalise first letter of question for PC users
//
function capitalise(newquestion)
{
newquestion = newquestion.charAt(0).toUpperCase() + newquestion.substring(1,(newquestion.length));

    if (newquestion.charAt(newquestion.length-1) == "?") {
    newquestion = newquestion.substring(0,newquestion.length-2); }  // remove added question mark
    return newquestion;
}

//
// processes text field values when enter/submit/done key is pressed
//
function processUserInput(event)
{ 
   if ( $("message").innerText.substring(0,6) == "I give") { addAnimal();}
   else if ( $("message").innerText.substring(0,6) == "Please") {
   newquestion = $("textfield").value; capitalise(newquestion); $("textfield").value = "";  getNewAnswer(); }
}



//
// list generation 
//
function populateList()
{
    var theSel = document.getElementById("animalList"); // first empty the list
    var selIndex = theSel.selectedIndex;
    if (selIndex != -1) {
      for(i=theSel.length-1; i>=0; i--)
    {
         theSel.options[i] = null;
    }
    if (theSel.length > 0) {
      theSel.selectedIndex = selIndex == 0 ? 0 : selIndex - 1;
    }
  }    
        
    var listArray = new Array();
    listArray[0] =("Animals I know");
    var j = 1;
    for (var i = 1; i < animalsArray.length; i++)
        {   var content = animalsArray[i]; 
            var partcontent = content.substring(0,2); 
            if (partcontent == "/A") { 
            listArray[j] = new Array(content.substring(2,content.length));
             j++  }
       
    }
         
    for ( var i = 0; i < j+1; i++) {

// create option elements to add 
		var userOption = document.createElement("OPTION");
		// set the option element text and value attributes
		userOption.text = listArray[i];
		userOption.value = "";
		// add the options element to the popup menu
		$('animalList').options.add(userOption,i);
      }  
    userOption.text = "(List to hide)";  // also tell them it's a toggle
    userOption.value = "";
    $('animalList').options.add(userOption);
    
}


//
// show/hide list toggle
//
function showList(event)
{
    if (hide) { hideList();  } else {
    $("animalList").style.visibility = "visible";
         populateList();
         hide=true; }
}

//
function hideList()
{  
    
    $("animalList").style.visibility = "hidden";
     hide = false;
}

//
//No Save message
//
function noSave(event)
{
  alert("Not implemented in this version. See info on reverse side.");
}


// The End.





