// Globals
var theText = ["",""]; // bilingual sentences; en, es
var thebgColor = "DDFFDD";
var X = 0;
var x = 0;
var y = 0;
var h = 0;
var xh = 0;
var hx = 0;
var t = 0;
var th = 0;
var ht = 0;
var a = 0;
var b = 0;
var guesses = 0;
var quoteMark = unescape( '%22' );
var singlequoteMark = unescape( '%27' );

// ********** little checkmarks etc
var theBlankUrl = pathPrefix + "calcTutElts/smallblank.gif";
var theCheckUrl = pathPrefix + "calcTutElts/vsmallcheck.gif";
var theXUrl = pathPrefix + "calcTutElts/vsmallcross.gif";
var theQUrl = pathPrefix + "calcTutElts/vsmallq.gif";

// ********** button names
var checkWord = "Check";
var clearWord = "Clear";
var helpWord = "Help!";
var peekWord = "Peek";
var hintWord = "Hint";
var resetWord = "Reset";
var freeHintWord = "Free Hint";
var showHideExWord = "Show/Hide Examples";
var quizWord = "QUIZ";
var warmupWord = "WARMUP";
var questionWord = "QUESTION";
var yesWord = "Yes!";
var wrongWord = "Wrong!";
var correctWord = "Correct!";
var goodWord = "Very&nbsp;good!";
var blankWord = "Enter your answer first.";
var blanksWord = "Enter all answers first.";
var accurateWord = "Your answer is not accurate enough.";
var simplifyWord = "You should simplify your answer more.";
var guessPhrase = "That looks like a guess to me...";
var dontThinkSoPhrase = "I don't think so...";
var parenMissingPhrase = "I think you are missing some important parentheses...";
var signWrong = "There is a wrong sign somewhere...";
var undefinedWord = "undefined";
var numberWords = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
var healthQuest = "Need health?";
var healthIncreased = "Your health has increased by 20 points.";
var healthFailed = "Nope. Sorry. No health points earned. The correct answer was ";
var niceWork = "<div style = 'font-size: 12px; font-family: Arial; font-weight: bold; color: C93344'><center>Nice work! You have now passed the 80% mark!</center></div>";
var closeWinPhrase = "Just close this window to return to the tutorial.";
var noteString = "<b class = boxhead>Note </b>";
var exampleString = "<b class = boxhead>Example</b>";
var examplesString = "<b class = boxhead>Examples</b>";
var gameVersion = "Game version";
var letWord = "Let";

if (theLanguage == "es") {
	checkWord = "Verificar";
	clearWord = "Borrar";
	helpWord = "&iexcl;Ayuda!";
	peekWord = "Vistazo";
	hintWord = "Pista";
	resetWord = "Reiniciar"
	freeHintWord = "Pista Gratis";
	showHideExWord = "Mostrar/esconder ejemplos";
	quizWord = "CONCURSO";
	warmupWord = "CALIENTAMENTO";
	questionWord = "PREGUNTA";
	yesWord = "&iexcl;S&iacute;!";
	wrongWord = "&iexcl;Incorrecto!";
	correctWord = "&iexcl;Correcto!";
	goodWord = "&iexcl;Muy&nbsp;bien!"
	blankWord = "Ingrese primero su respuesta.";
	blanksWord = "Ingrese primero todas las respuestas";
	accurateWord = "Su respuesta debe ser m&aacute;s exacta.";
	simplifyWord = "Su respuesta debe ser simplificada.";
	guessPhrase = "A mi parece que est&aacute; divinando...";
	dontThinkSoPhrase = "No lo creo...";
	parenMissingPhrase = "Parece que falta unos par&eacute;ntesis importantes...";
	signWrong = "Hay un signo equivocado en alguno sitio...";
	undefinedWord = "indefinido";
	numberWords = ["cero", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"];
	healthQuest = "&iquest;Necesita salud?";
	healthIncreased = "Su salud ha subido por 20 puntos.";
	healthFailed = "No. Disculpe. No gan&oacute; ningunos puntos de salud. La respuesta correcta es ";
	niceWork = "<div style = 'font-size: 12px; font-family: Arial; font-weight: bold; color: C93344'><center>&iexcl;Muy bien! Ya ha pasado el nivel de 80%!</center></div>";
	closeWinPhrase = "Cierra esta ventana para regresar al tutorial.";
	noteString = "<b class = boxhead>Nota </b>";
	exampleString = "<b class = boxhead>Ejemplo</b>";
	examplesString = "<b class = boxhead>Ejemplos</b>";
	gameVersion = "Versi&oacute;n juego";
	letWord = "Sea";
	}


// *** Error Handler ******
function myErrorTrap(message,url,linenumber) {
this.parent.bottom.window.location = "wrong.html";
return (true);
} // end of on error
// ********************

// ********** Adding format examples
function addFormatButton(index,theText) {
//index is 1, 2, 3  for multiple buttons
if (theText == undefined) theText = showHideExWord;
var thedivName = "formatTableDiv" + index.toString();
var theCode = "if(" + thedivName + ".innerHTML=='')document.getElementById('" + thedivName + "').innerHTML=formatTable;else{" + thedivName + ".innerHTML=''}"
var theFormName = "formatForm" + index.toString();
// document.writeln("<form name = " +  theFormName + ">";
drawButton(theText, theCode);
document.writeln("<DIV id = " + thedivName + "></DIV>");
// document.writeln("</form>";
}




// *********** Tracing arrows on graphs 

function addTraceArrows(theGraph) {
var theStr = '<input type=' + quoteMark + 'button' + quoteMark + ' class = ' + quoteMark + 'myButtons' + quoteMark + ' value = ' + quoteMark + '&larr;' + quoteMark + ' onmousedown=' + quoteMark + ' currentGraphjs = ' + theGraph.id + '; directionjs = 0; moveX.start();' + quoteMark + ' onmouseup=' + quoteMark + 'moveX.stop();' + quoteMark + ' onmouseout=' + quoteMark + 'moveX.stop();' + quoteMark + '> &nbsp; <input type=' + quoteMark + 'button' + quoteMark + ' class = ' + quoteMark + 'myButtons' + quoteMark + ' value = ' + quoteMark + '&rarr;' + quoteMark + ' onmousedown=' + quoteMark + ' currentGraphjs = ' + theGraph.id + '; directionjs = 1; moveX.start();' + quoteMark + ' onmouseup=' + quoteMark + 'moveX.stop();' + quoteMark + ' onmouseout=' + quoteMark + 'moveX.stop();' + quoteMark + '>';
document.writeln(theStr);
}


//***** Headings for tutorials in one or more parts

function writeTopicHeadings() {
var numParts = topicHeadings.length;
var theStr = "<span class = headings2>";
var thisTutStr = "This tutorial: ", partWord = "Part ";
if (theLanguage == "es") {
	thisTutStr = "Este tutorial; ", partWord = "Parte ";
	}
for (var i = 1; i <= numParts; i++) {
	if (i == thisTutPart) theStr += thisTutStr + partWord + capLetter(i) + ": " + topicHeadings[i-1];
	else {
		var theLinkSt = topicURLs[i-1] + ".html";
		if (playing) theLinkSt = topicURLs[i-1] + "g.html";
		theStr += '<a href = "' + theLinkSt + '" target = "_top" class = "headings2Lite">';
		theStr += partWord + capLetter(i) + ": " + topicHeadings[i-1];
		theStr += "</a>";
		} // links to other parts
	if (i < numParts) theStr += "<br>";
	} // i
theStr += "</span>";
document.writeln(theStr)
} // writeTopicHeadings


//***** Headings for quizzes, lines and other items

function writeQ(number, lang, hideQ){
if (hideQ) document.writeln(QSymbol(number, lang, false));
else document.writeln(QSymbol(number, lang, true));
}

function QSymbol(number, lang, showQ) {
var theText = '';
// as in Q for question
if (!showQ) theText = '<img name = "Q' + number.toString() + 'check" src = "../../calcTutElts/smallblank.gif">';
else {
	if (theLanguage == "en") theText = '<p><b class = boxhead>Q</b><img name = "Q' + number.toString() + 'check" src = "../../calcTutElts/smallblank.gif">';
	else theText = '<p><b class = boxhead>P</b><img name = "Q' + number.toString() + 'check" src = "../../calcTutElts/smallblank.gif">';
	}
return(theText);
}

function writeHeading(theTitle, what) {
if (what == "finite") {
	var theText = '<center><table width = 90%><tr><td nowrap class = myButtons width = 80 align = center>' + theTitle + '</td><td nowrap><img src = ' + quoteMark + '../../calcTutElts/pinkbuttonbg.gif' + quoteMark + ' width = 100% height = 4></td></tr></table></center>'
	}
else if (what == "gold") {
	var theText = '<center><table width = 90%><tr><td nowrap class = myButtons width = 80 align = center>' + theTitle + '</td><td nowrap><img src = ' + quoteMark + '../../calcTutElts/goldbuttonbg.gif' + quoteMark + ' width = 100% height = 4></td></tr></table></center>'
	}
else {
	var theText = '<center><table width = 90%><tr><td nowrap class = myButtons width = 80 align = center>' + theTitle + '</td><td nowrap><img src = ' + quoteMark + '../../calcTutElts/buttonbg.gif' + quoteMark + ' width = 100% height = 4></td></tr></table></center>'
	}
document.writeln(theText);
}

function drawLine(what) {
if (what == "finite") {
	var theText = '<center><table width = 90%><tr><td><img src = ' + quoteMark + '../../calcTutElts/pinkbuttonbg.gif' + quoteMark + ' width = 100% height = 4></td></tr></table></center>'
	}
else if (what == "gold") {
	var theText = '<center><table width = 90%><tr><td><img src = ' + quoteMark + '../../calcTutElts/goldbuttonbg.gif' + quoteMark + ' width = 100% height = 4></td></tr></table></center>'
	}
else{
	var theText = '<center><table width = 90%><tr><td><img src = ' + quoteMark + '../../calcTutElts/buttonbg.gif' + quoteMark + ' width = 100% height = 4></td></tr></table></center>'
	}
document.writeln(theText);
}

function clearResponse() {
writeBottomMessage('');
}

function buttonString(theName,theCode) {
var buttonStr = '<input type="button" class = "myButtons" onmouseover="this.className= ' + singlequoteMark + 'myButtons myButtonsHov' + singlequoteMark + '" onmouseout="this.className= ' + singlequoteMark + 'myButtons' + singlequoteMark + '"  value = "' + theName + '" onClick=' + theCode + '>';
return(buttonStr);
} 

function drawButton(theName, theCode) {
document.writeln(buttonString(theName,theCode));
} 

function drawButtonOpen(theName) {
var buttonOpenStr = '<input type="button" class = "myButtons" onmouseover="this.className= ' + singlequoteMark + 'myButtons myButtonsHov' + singlequoteMark + '" onmouseout="this.className= ' + singlequoteMark + 'myButtons' + singlequoteMark + '"  value = "' + theName + '" onClick="';
document.writeln(buttonOpenStr);
}

function sesame(url,hsize,vsize){ 
// Default size is 550 x 400
        var tb="toolbar=0,directories=0,status=0,menubar=0"
        tb+=",scrollbars=1,resizable=1,"
    var tbend="width="+hsize+",height="+vsize;
    if(tbend.indexOf("<undefined>")!=-1){tbend="width=550,height=400"}
        tb+=tbend;
        Win_1 = window.open(url,"win1",tb);
	Win_1.focus();
    }


// Bottom Window handlers



function writeBottomWrong(theMessage) {
var theString = "";
if (theMessage == "") theString = '<center><img src = "../../calcTutElts/wrong.gif">';
else theString = '<center><table><tr><td align = center><img src = "../../calcTutElts/smallx.gif"><br><table><tr><td class = messageStyle>'
theString += theMessage ;
theString += '</td></tr></table></center>';
parent.left.document.getElementById("message").innerHTML = theString;
} // writeBottomWrong

function writeBottomCorrect() {
var theString = '<center><img src = "../../calcTutElts/check.gif"></center>'
parent.left.document.getElementById("message").innerHTML = theString;
} // writeBottomCorrect

function writeBottomSmile(theMessage,x) {
// x = 0 gives usual checkmark no comment
// x = 1 gives one smile (with a space or text as the message)
// x = 2 gives another
// x = 3 gives a third
// x = 4 gives the mexican
if (x == 0) writeBottomCorrect();
else {
	var theString = "";
	if ((theMessage == "")&& (theLanguage == "en")) theString = '<center><img src = "../../calcTutElts/bigsmiley.gif">';
	else if ((theMessage == "")&& (theLanguage == "es")) theString = '<center><img src = "../../calcTutElts/bigsmileyes.gif">';
	else if (x == 2) theString = '<center><img src = "../../calcTutElts/smiley2.gif"><br><table><tr><td>';
	else if (x == 3) theString = '<center><img src = "../../calcTutElts/smiley3.gif"><br><table><tr><td>';
	else if (x == 4) theString = '<center><img src = "../../calcTutElts/smileyMex.gif"><br><table><tr><td>';
	else theString = '<center><img src = "../../calcTutElts/smiley.gif"><br><table><tr><td class = messageStyle>'
	theString += theMessage ;
	theString += '</td></tr></table></center>';
	parent.left.document.getElementById("message").innerHTML = theString;
	} // x >= 1
} // writeBottomSmile

function writeBottomMmmh(theMessage) {
var theString = '<center><table><tr><td align = center class = messageStyle><img src = "../../calcTutElts/mmh.gif"><br>'
theString += theMessage ;
theString += '</td></tr></table></center>';
parent.left.document.getElementById("message").innerHTML = theString;

} // writeBottomMmmh

function writeBottomMessage(theMessage) {
if ((writeBottomMessage.arguments).length == 0) var theMessage = ''
var theString = '<center><table><tr><td class = messageStyle>'
theString += theMessage ;
theString += '</td></tr></table></center>';
parent.left.document.getElementById("message").innerHTML = theString;
} // writeBottomMessage

function appendBottomMessage(theMessage) {
var theString = '<center><table><tr><td class = messageStyle>'
theString += theMessage ;
theString += '</td></tr></table></center>';
parent.left.document.getElementById("message").innerHTML += theString;
} // writeBottomMessage



function writeBottomYell(theMessage) {
var theString = '<center><table><tr><td class = messageStyle><center><img src = "../../calcTutElts/yell.gif"></center>'
theString += theMessage ;
theString += '</td></tr></table></center>';
parent.left.document.getElementById("message").innerHTML = theString;
} // writeBottomMessage

function writeBottomYell2(theMessage) {
var theString = '<center><table><tr><td align = center class = messageStyle><img src = "../../calcTutElts/yell2.gif"><br>'
theString += theMessage ;
theString += '</td></tr></table></center>';
parent.left.document.getElementById("message").innerHTML = theString;
} // writeBottomMessage


// ********* Answer checking routines *********
// the following two routines are can be used in both tutorials and 
// review exercises to do answer checking and "peeking"
// handles both strings and numerical values.

// These routines use one or two other string utilities in this file
// example of html code that uses this:
// 
// <form name = "Form1">
//  <input type=text size=35 value="" name="Q1a">
// <input type="button" value = "Check" onClick = 
// "if (checkAnswer('Form1','Q1a',3,3.1419)) winopen('correct.html','bottom'); 
// else winopen('wrong.html','bottom') ">
// <input type="button" value = "Peek" onClick="togglePeek('Form1','Q1a', '3.1419')">
//

function checkAnswer(formName,fieldName,Option,correctAnswer) {
// returns true if the answer is correct, else returns false
// Option1 compares the string (spaces stripped case insensitive) with the desired string
// Option 2 compares a modified string: changes X to x, Y to y, Z to z, 
// and removes * before comparing
// Option 3 evaluates the string 
// Option 4 checks to see if the string is blank & returns true if blank
// Option 5 here is for 5 decimal places accuraqcy

var theCommand = ""; 
var theString = "";
var a1 = eval("theString = stripSpaces(document."+ formName + "." + fieldName + ".value"+")" );
if (theString != "") {
if (Option == 1)
	{
	var act1 = eval("theString = stripSpaces(document."+ formName + "." + fieldName + ".value"+")" );
	if (theString.toLowerCase() == correctAnswer.toLowerCase()) return (true);
	else return (false);
	} // Option 1
else if (Option == 2)
	{
	var act1 = eval("theString = stripSpaces(document."+ formName + "." + fieldName + ".value"+")" );
	theString = replaceChar (theString,"X","x");
	theString = replaceChar (theString,"Y","y");
	theString = replaceChar (theString,"Z","z");
	theString = replaceChar (theString,"A","a");
	theString = replaceChar (theString,"B","b");
	theString = replaceChar (theString,"C","c");
	theString = stripChar(theString,"*");
	if (theString == correctAnswer) return (true);
	else return (false);
	} // Option 2
else if (Option == 3)
	{
	var act1 = eval("theString = document."+ formName + "." + fieldName + ".value" );
	// check to see if the string looks is ok for eval
	if (looksLikeANumber(theString)) 
		{
		var x = eval(theString);
		var err = Math.abs(x - correctAnswer);
		if (err < 0.00005) return (true);
		else return (false);
		}
	else return (false);
	return(false);
	} // Option 3

	else if (Option == 5)
	{
	var act1 = eval("theString = document."+ formName + "." + fieldName + ".value" );
	// check to see if the string looks is ok for eval
	if (looksLikeANumber(theString)) 
		{
		var x = eval(theString);
		var err = Math.abs(x - correctAnswer);
		if (err < 0.000005) return (true);
		else return (false);
		}
	else return (false);
	return(false);
	} // Option 5

else if (Option == 6)
	{
	var act1 = eval("theString = document."+ formName + "." + fieldName + ".value" );
	// check to see if the string looks is ok for eval
	if (looksLikeANumber(theString)) 
		{
		x = myEval(theString);	 // x must be global
		var theResult = false;
		var theString2 = 'if (' + correctAnswer + ') theResult = true;' ;
// alert(theString2);
		act2 = eval(theString2);

		return(theResult);
		}
	else return (false);
	} // Option 6


} // endif non-empty
else if (Option == 4) return(true); // in case of empty string
}


function checkAnswerandValue(formName,fieldName,correctAnswer,minLength, maxLength, maxTolerance, assig1,assig2,assig3,assig4) {
// use this to check for simplified expressions
// evaluates the input string in the specified form 
// & returns 1 if the answer is correct (agrees with correctAnswer)
// to within 0.00005 and is the right length otherwise set "maxerror" = whatever
// as one of the assignments
// returns 2 if the answer is right but string too long (unsimplified)
// returns 3 if answer is right but string too short 
// returns 0 if the answer is blank
// returns 666 if gameState = "dead"; 
// else returns 6;
// it evalutes the input string at sthe specified values 
// Each assigi has the form "x=2" or "h=2.3" 
// minLength & maxLength are the permissible ranges of an input string
// maxTolerance is the largest possible error
// NOTE: requires GLOBAL variables x, h, or whatever is assigned

var theString = "";
var maxerror = maxTolerance; 	
var a1 = eval("theString = stripSpaces(document."+ formName + "." + fieldName + ".value"+")" );
theString = theString.toLowerCase();
// alert(theString + ", " + assig1);
if (assig1 != "") var b1 = eval(assig1);  // set the values equal to numbers
if (assig2 != "") var b2 = eval(assig2);
if (assig3 != "") var b3 = eval(assig3);
if (assig4 != "") var b4 = eval(assig4);
// alert(theString);
if (theString == "console") {bringUpConsole(); return(0);} 
else if (gameState == 'dead') return(666);
else if (theString == "") return(0);
else if (godMode) return(1);
else {
	theString = stripChar (theString, "$");		// for dollar signs
	theString = stripChar (theString, ",");		// for longer numbers
	theString = theString.toLowerCase();
	try{
//alert(theString);
		var val = myEval (theString);
//alert(val);
		var correctVal = myEval(correctAnswer);
//alert(correctAnswer + " = " +  correctVal + ";  " + theString + " = "  + val);
		var err = Math.abs(val - correctVal);
//alert(err);
		if (err < maxerror)
			{
			if (theString.length > maxLength) return(2);
			else if  (theString.length < minLength) return(3);
			else return(1);
			}
		else return (6);
		}
	catch(error) {
//alert("ERROR: x = " + x + ", the String is " + theString + ". The correct answer is " + correctAnswer);
//alert(correctAnswer + " = " +  correctVal + ";  " + theString + " = "  + val);
		return(6)
		}
	} // endif non-empty
} // end checkAnswerandValue



function togglePeek(formName,fieldName,expression) {
// displays the given expression in formName.fieldname if not already visible
// if already visible, it hides it

var theCommand = "";
var theString = "if (document." + formName + "." + fieldName + ".value != '" + expression + "') document." + formName + "." + fieldName + ".value = '" + expression + "';  else document." + formName + "." + fieldName + ".value = '';"
// alert(theString)
var act1 = eval(theString);
return(true);
}

// ************** end of answer handling routines *************

// *** Quiz Questions Object (for filling in answers)
function quizQuestion(name) {
this.id = name;
this.formName = ''; // will be assigned one by the quiz items generator
this.questionName = ''; // typically "Q7" or whatever -- assigned by generator
this.number = 0; // assigned by generator
this.text = ""; // question text to insert before the answer
this.textAlign = "left"; // can be right or center
this.postText = ""; // text to insert after the answer
this.correctAnswer = "";
this.accuracy = .0005;
this.maxAnsLength = 30;
this.fieldLength = 10;
this.buttonsUnder = false; // puts buttons under when true
this.buttonsUnderInput = false;
this.reward = 4;
this.punishment = 3;
this.wrongAnsResponse = wrongWord; // response if wrong
this.wrongAnswers = [[]]; 
// Each entry in wrong answer array has form [wrong answer str, feedback]
this.helpButtonText = helpWord; // set to "" for no button
this.commands = ['x=6.76', 'y=1.23',undefinedWord + ' = 666.666', ''] // up to four commands for the answer checker
this.wrongCommands = []; //add some if you want things done in the event of a wrong answer
this.correctConseqence = ""; // further actions to take if correct

} // quizQuestion

function generateQuizItems(startNum, inArray, randomize, qsPerLine) {
// generates a set of single item numerical questions &puts them
// on the document, qsPerLine per line (default 1)
// startNum = the starting question number on the quiz
// randomizes if randomize = true   TODO
// each item in inArray is an object of type quizQuestion (see above):
// action of the help button expects a function called "helpActions()";
// action of the hint buttons require "hintActions()"--- TODO
// fieldLength is the size of the input fields
var theString = "<table>";
var numQs = inArray.length - 1; // number of questions
var numPL = 1; // atcual number per line
if (qsPerLine > 1) numPL = qsPerLine;
for (var i = 0; i <= numQs; i++) { 
	var qNum = startNum + i;
	var Qname = "Q" + qNum.toString();
	var theFormName = "theForm" + Qname;
	inArray[i].questionName = Qname;
	inArray[i].formName = theFormName;
	inArray[i].number = qNum;
	if (i%numPL == 0) theString += "<tr>";
	theString += "<form name = '" + theFormName + "'>";
	theString += "<td nowrap align = " + inArray[i].textAlign + ">" + inArray[i].text +"</td>";
	theString += '<td nowrap><input type=text size=' + (inArray[i].fieldLength).toString() + ' value="" name="part1">' + inArray[i].postText  + '<input type=text style = "visibility: hidden; width: 1px" size = 1></td><td>';
	var imagename = Qname + 'check';
	theString += '<img name = "' + Qname + 'check" src = "../../calcTutElts/smallblank.gif">';
	theString +=  "&nbsp;";
	if (inArray[i].buttonsUnder) theString += "</td></tr><tr><td colspan = 4 align = center>";
	else if (inArray[i].buttonsUnderInput) theString += "</td></tr><tr><td></td><td colspan = 4 align = center>";
	else theString += "</td><td>";
	theString += buttonString(checkWord,"checkSingleAnswer(" + inArray[i].id + ")");
	var clearCommand = "document." + theFormName + ".part1.value = ''"
	clearCommand += ";clearResponse();";
	clearCommand += "document.images['" + imagename + "'].src = '../../calcTutElts/smallblank.gif'";
	theString += "&nbsp;" + buttonString(clearWord,'"' + clearCommand + '"');
	
	if (inArray[i].helpButtonText != "") {
		var helpCommand = "if(gameState=='dead')beep(1);else helpActions(" + qNum.toString() +")";
		theString += "&nbsp;" + buttonString(inArray[i].helpButtonText,'"' + helpCommand + '"');
		} // if there is a help button
//if (i == 2) alert(helpCommand);
	theString += "</form>";
	theString += "</td>";
	if (i%numPL == numPL-1) {
		theString += "</tr>";
		if (inArray[i].buttonsUnderInput) theString += "<tr><td height = 5> </td></tr>"; // seperate the items more
		}
	}
theString += "</table>";
//alert(theString);
document.writeln(theString);
} // generateQuizItems

function checkSingleAnswer(theQuestion) {
// theQuestion is a quizQuestion object

// blank out the check etc
clearResponse();
var imagename = theQuestion.questionName + "check";
document.images[imagename].src = '../../calcTutElts/smallblank.gif';


var uu = checkAnswerandValue(theQuestion.formName, 'part1', theQuestion.correctAnswer, 1, theQuestion.maxAnsLength, theQuestion.accuracy, theQuestion.commands[0], theQuestion.commands[1], theQuestion.commands[2], theQuestion.commands[3]);

var vv = checkAnswerandValue(theQuestion.formName, 'part1', theQuestion.correctAnswer, 1, 30, .05, theQuestion.commands[0], theQuestion.commands[1], theQuestion.commands[2], theQuestion.commands[3]);
var ww = 0, wrongAnsIndex = 0;

for (var j = 0; j <= theQuestion.wrongAnswers.length-1; j++) {	
	if ((theQuestion.wrongCommands).length > 0) ww = checkAnswerandValue(theQuestion.formName, 'part1', theQuestion.wrongAnswers[j][0], 1, theQuestion.maxAnsLength, theQuestion.accuracy, theQuestion. wrongCommands [0], theQuestion. wrongCommands [1], theQuestion.wrongCommands [2], theQuestion. wrongCommands [3]);
	else ww = checkAnswerandValue(theQuestion.formName, 'part1', theQuestion.wrongAnswers[j][0], 1, theQuestion.maxAnsLength, theQuestion.accuracy, theQuestion.commands[0], theQuestion.commands[1], theQuestion.commands[2], theQuestion.commands[3]);
//alert(ww);
	if (ww == 1) {wrongAnsIndex = j; break} 
	}

if (uu == 666) beep(1); // dead
		else {
		if (uu == 1) {
			if (parent.playingGame) { 
				dealWithSuccess(theQuestion.number, theQuestion.reward, pickOne(0, 1, 2, 3, 4),yesWord);
			}
			else {
				writeBottomSmile(yesWord, pickOne(0, 1, 2, 3, 4));
				}
			document.images[imagename].src = '../../calcTutElts/vsmallcheck.gif'; 
			if (theQuestion.correctConseqence != '') var doIt = eval(theQuestion.correctConseqence);
			}
		else if (uu == 0) document.images[imagename].src = '../../calcTutElts/vsmallq.gif';
		else if (uu == 2) writeBottomMessage(simplifyWord);

		else if (ww == 1) {
			if (parent.playingGame) dealWithWrongAns (theQuestion.number,theQuestion.punishment,3, theQuestion.wrongAnswers[wrongAnsIndex][1]);


			else {
				writeBottomYell (theQuestion.wrongAnswers[wrongAnsIndex][1]);
				document.images[imagename].src = '../../calcTutElts/vsmallcross.gif';
				}
			}
		else if (vv == 1) {
			if (parent.playingGame)dealWithFailure(theQuestion.punishment-1,1, accurateWord);
			else writeBottomYell2(accurateWord);
			}



		else {
			if (parent.playingGame) dealWithWrongAns (theQuestion.number, theQuestion.punishment,pickOne(0, 1, 2), theQuestion.wrongAnsResponse);
			else {
				writeBottomWrong(theQuestion.wrongAnsResponse);
				document.images[imagename].src = '../../calcTutElts/vsmallcross.gif';
				}
			}


		} // if not dead

// alert("ww = " + ww + " , corrAns = " + theQuestion.correctAnswer);

} // checkSingleAnswer

// ***end of Quiz Questrions onject material

// **** Multiple Choice Object
// *** Quiz Questions Object (for filling in answers)
function multipleChoice(name) {
this.id = name;
this.text = ""; // question text to insert before the choices
this.position = "ul"; // can be "center" or even "p" or "br"
this.showQ = true; // Show symbol "Q" before question
this.postText = ""; // text to insert after the choices
this.ramdomize = true;
this.shuffle = []; // will be assigned either manually for non-game or
// automatically by game
this.choices = []; // zeroth item the correct one
this.numToDisplay = 1; // number of choices to actually show
this.numberPerLine = 2; // puts buttons under when true
this.punishment = 4;
this.wrongAnsResponse = []; 
this.helpButtonText = helpWord; // set to "" for no button
this.correctConseqence = ""; // further actions to take if correct
} // multipleChoice

function generateMultipleChoice(qNum, inArr) {

// generates a multiple choice item
// startNum = the question number on the tutorial
// each item in inArr is an object of type multipleChoice (see above):
// action of the help button expects a function called "helpActions()";
// action of the hint buttons require "helpActions()"
document.writeln("<div style = 'position: relative; top: 1em;'>" + QSymbol(qNum, theLanguage, inArr.showQ) + inArr.text + "</div><" + inArr.position + "><table><tr>");
var numChoices = (inArr.choices).length - 1; // number of questions starts at 0
var numShowing = inArr.numToDisplay
var qShuffle = inArr.shuffle;
//alert(inArr.ramdomize)
if (inArr.ramdomize) {
	var qShuffle = randomSequenceZero(numChoices);
// alert(qShuffle);
	// make sure choice 0 included
	var zeroIn = false;
	for (var i = 0; i <= numShowing-1; i++) 	{
		if (qShuffle[i] == 0) {zeroIn = true; break}
		}
	if (!zeroIn) {
// alert("HEREEEE")
 	var pick = randomInt(0, numShowing-1);
qShuffle[pick] = 0;
	}
	}

for (var i = 0; i <= numShowing-1; i++) {
	document.writeln("<td>");
	var Qname = qNum.toString() + qShuffle[i].toString();
	document.writeln('<img name = "' + Qname + 'check2" src = "../../calcTutElts/smallblank.gif">')
	var theArg1 = "&nbsp;"+ String.fromCharCode(64+i+1) + "&nbsp;";
	var theCode = "";
	if ((qShuffle[i] == 0) || (godMode)) {
		var theLotto = pickOne(2,3,4);
		if (theLotto == 4) theWord = "&iexcl;Muy&nbsp;bien!";
		else theWord = goodWord;
		theCode = "dealWithSuccess(" + qNum.toString() + ",theRewards[" + qNum.toString() + "]," + theLotto.toString() + ",'" + theWord.toString() + "');" + inArr.correctConseqence + ";";
		theCode += "document.images['" + qNum.toString() + "0check2'].src='../../calcTutElts/vsmallcheck.gif'";
		}
	else theCode = " failureMultipleChoice(" + inArr.id + "," + inArr.punishment.toString() + "," + qShuffle[i].toString() + ")";
//alert(theCode);
	if (i == 9) theArg1 = "&nbsp;"+ String.fromCharCode(64+i+1) + "&nbsp;&nbsp;";
	else if (i == 10) theArg1 = "&nbsp;"+ String.fromCharCode(64+i+1) + "&nbsp; ";
	drawButton(theArg1, theCode);
	document.writeln('</td><td>');
	document.writeln(inArr.choices[qShuffle[i]])
	document.writeln('</td>');
	if ((i+1)% inArr.numberPerLine != 0) document.writeln('<td width = 40></td>');
	else document.writeln('</tr><tr>'); 
	} // i
if (inArr.helpButtonText != "") {
		var helpCommand = "if(gameState=='dead')beep(1);else helpActions(" + qNum.toString() +")";
		document.writeln("<tr><td colspan = 2><img src = '../../calcTutElts/smallblank.gif'>&nbsp;" + buttonString(inArr.helpButtonText,'"' + helpCommand + '"') + "</td></tr>");
		} // if there is a help button
document.writeln("</table></" + inArr.position + ">");
document.writeln(inArr.postText);

} // generateMultipleChoice

function failureMultipleChoice(theQuiz,punishment,j) {
// alert(j)
dealWithFailure (punishment,2, theQuiz.wrongAnsResponse [j])
}


// ************* end of question generating routines


// ************** score adjustment 

function dealWithSuccess(questionNum, points, smileyNum, comment) {
try {
	var picSrc = "'../../calcTutElts/vsmallcheck.gif'";
	var theCommand = "document.images['Q" + questionNum.toString() + "check'].src = " + picSrc + ";";
	var doIt = eval(theCommand);
	}
catch(error) {}
if (gameState == "notPlaying"){ writeBottomSmile(comment, smileyNum)}
else {
	if (QuestionDone[questionNum]) dealWithDoubleDipping(questionNum);
	else {
		tasksDone += 1;
		numberOfSubmissions += 1;
		QuestionDone[questionNum] = true;
		
		totalScore += theDeltaFactor*points;
		numberRight += 1;
		percentageCorrect = Math.round(100*tasksDone/numTasks);
		health += Math.round((100-percentageCorrect)*3*points/100);
		if ((!fanfareSounded) && (percentageCorrect > 80)) {
			beep(15); // fanfare
			fanfareSounded = true;
			writeBottomMessage(niceWork)
			}
		else {
			var theBeepNum = pickOne(2,5);
			beep(theBeepNum);
			if (smileyNum == 0) writeBottomCorrect();
			else writeBottomSmile(comment, smileyNum);
			}
		showMeters();
	
		// now decide if any new keys are earned for later
		if (questionNum >= 3) checkForKeys(); 
			// dont wnat distracting keys popping up early
		}
	}// if playing
} // dealWithSuccess


function dealWithFailure(points, frownNum, comment) {
// pick a sound
// frownnum: 0 = x, 1 = yell, 2 = frog 3 = Mmmhhh

if (gameState != "notPlaying"){ 
	if (!healthVialsStarted) startHealthVials();
	numberOfSubmissions += 1;
	var theBeepNum = pickOne(3,9,10,11,12);
	beep(theBeepNum);
	totalScore -= theDeltaFactor*points;
	health -= Math.round((150-percentageCorrect)*2*points/100);
	}
if (frownNum == 0) writeBottomWrong(comment);
else if (frownNum == 1)writeBottomYell(comment);
else if (frownNum == 2)writeBottomYell2(comment);
else writeBottomMmmh (comment);

if (gameState != "notPlaying") showMeters();
} // dealWithFailure

function dealWithWrongAns (questionNum, points, frownNum, comment) {
// same as DWFailure
// but puts an "x" next to the specific question
// pick a sound
// frownnum: 0 = x, 1 = yell, 2 = frog 3 = Mmmhhh
if (!healthVialsStarted) startHealthVials();
numberOfSubmissions += 1;
var theBeepNum = pickOne(3,9,10,11,12);
beep(theBeepNum);
totalScore -= theDeltaFactor*points;


health -= Math.round((150-percentageCorrect)*2*points/100);
if (frownNum == 0) writeBottomWrong(comment);
else if (frownNum == 1)writeBottomYell(comment);
else if (frownNum == 2)writeBottomYell2(comment);
else writeBottomMmmh (comment);

try {
	var picSrc = "'../../calcTutElts/vsmallcross.gif'";
	var theCommand = "document.images['Q" + questionNum.toString() + "check'].src = " + picSrc + ";";
	var doIt = eval(theCommand);
	}
catch(error) {}



showMeters();
} // dealWithFailure


function dealWithHelp(points) { 
if (gameState == "dead") beep(1);
else {
	// pick a sound
	pressedHelpNumTimes += 1;
	if (freeHintTally > 0) {
		freeHintTally -= 1;
		}
	else {
		totalScore -= Math.round(Math.sqrt(pressedHelpNumTimes)*theDeltaFactor*points);
health -= Math.round((150-percentageCorrect)*2*points/100);
		if (theLanguage == "en") appendBottomMessage('Help decreases your score and your health.');
else if (theLanguage == "es") appendBottomMessage('Ayuda baja su resultado y salud.');
		showMeters();
		} // no free hint
	} // if not dead
} // dealWithFailure

function dealWithDoubleDipping() {
beep(1);
if (theLanguage == "en") writeBottomYell('You already got it right once. No seconds!');
else if (theLanguage == "es") writeBottomYell('&iexcl;Ya lo ha contestado correctamente una vez!');
// put a check mark up anyway
try {
	var questionNum = dealWithDoubleDipping.argument[0];
	var picSrc = "'../../calcTutElts/vsmallcheck.gif'";
	var theCommand = "document.images['Q" + questionNum.toString() + "check'].src = " + picSrc + ";";
	var doIt = eval(theCommand);
	}
catch(error) {}

}

function dealWithHealthAnswer() {
healthVialsStarted = false; 
// allow another health vial to be activated
processHealthResponse(); 
// above utility is defined in the health file for each tutorial
}// dealWithHealthAnswer

function dealWithDeath() {
gameState = "dead";
// clear heath timers
try {
	for (var i = 0; i <= maxNumHealths-1; i++) clearTimeout(timers[30 + i]);
	}
catch(error) {}
if (theLanguage == "en") flashBottomWarning("<p>You are dead, and the game will no longer function properly.<p><p>Sorry. Reload the page to play again.<p>&nbsp;",0);
else if (theLanguage == "es") flashBottomWarning("<p>Est&aacute; muerto y no m&aacute;s funcionar&aacute; el juego.<p><p>Discuple. Reinicie la p&aacute;gina para jugar de nuevo.<p>&nbsp;",0);

} // dealWithDeath

function dealWithEnd() {
var endMessage = ["<p>Nice job!! You are more than ready to go on to the next topic... <p>&nbsp;", "<p>More than adequate! Go on to the next topic. (Reload to play again.) <p>&nbsp;", "<p>Adequate! Go on to the next topic. (Reload to play again.)<p>&nbsp;", "<p>Needs a little more work. (Reload to play again.)<p>&nbsp;", "<p>Needs a lot more work! (Reload to play again.) <p>&nbsp;"];

cendMessage = ["<p>&iexcl;Muy bien! Est&aacute; listo para adelantar al siguiente tema. (Reinicie para jugar de nuevo.) <p>&nbsp;", "<p>&iexcl;Bastante bien! Vaya al siguiente tema. (Reinicie para jugar de nuevo.)<p>&nbsp;", "<p>&iexcl;Normal! Puede ir al siguiente tema. <p>&nbsp;", "<p>Necesita m&aacute;s trabajo. (Reinicie para jugar de nuevo.)<p>&nbsp;", "<p> Necesita mucho m&aacute;s trabajo. (Reinicie para jugar de nuevo.) <p>&nbsp;"];

gameState = "dead";
if (totalScore >= 90) flashBottomWarning(endMessage[0],3);
else if (totalScore >= 85) flashBottomWarning(endMessage[1], 3);
else if (totalScore >= 75) flashBottomWarning(endMessage[2], 2);
else if (totalScore >= 50) flashBottomWarning(endMessage[3], 2);
else flashBottomWarning(endMessage[4], 1);

// handle cookie scores
// this is a cookie with value [0, highest score on Game 1, Game 2,.. ]
// up to 100 games. 
gameScores[gameNumber] = totalScore; // temporary in case no cookie present
var theString = 'gameScores = [' + gameScores.toString() + '];';
var theCheck = getCookie(theTotalScoreCookie);
if ((theCheck == "") || (theCheck == null)) {
// alert(theLanguage);
 	setCookie(theTotalScoreCookie, theString, oneYear,'/');
	}
else {
	var doIt = eval(theCheck); // this will reset gameScores to saved value
	if (gameScores[gameNumber] < totalScore) gameScores[gameNumber] = totalScore;
	theString = 'gameScores = [' + gameScores.toString() + '];';
	setCookie(theTotalScoreCookie, theString, oneYear,'/');
	} 

}

function dealWithQuit() {
// need to include some reference to the number of questions still to answer 
// at present if the score is 50 (none answered is says "not bad"


if (gameState != "dead") {
var quittingGame = false;
	if (theLanguage == "en") quittingGame = confirm('Are you sure you want to quit? You cannot resume the game once you quit unless you reload and start all over.');
	else quittingGame = confirm('Esta seguro que desee terminar? Si termine no puede resumir el juego a menos que reinicia y empezar de nuevo.');
if(quittingGame) {	
	var percentAnswered = tasksDone/numTasks;
	totalScore *= percentAnswered;
	dealWithEnd();
	}
	} // if not already dead
else beep(1);
}//



function flashBottomWarning(content,theType) {
// when theType = 0 for death, 1 for near death 2 for ok 3 for good
backtrackingStep = 0;
arrowKeyHit = false;
infoDepth = 0; // get rid of whatever they are reading
var theFileName = pathPrefix + 'GameManagement/sounds';
if (theType == 0) beep(13) // death
else if (theType >= 3) activateSound("victory_fanfare","mp3", theFileName,40,false); // all clear victory
else beep(4);
var flashHeading = ["DEAD", "VICTORY!" ];
if (theLanguage == "es") flashHeading = ["MUERTO", "&iexcl;VICTORIA!" ];

var theStuff = parent.left.document.getElementById("message");
var theHTML = "<center><div id = theWarning style = '{margin-right: 5px}' ><table cellpadding = 0 cellspacing = 0><tr><td>";
theHTML += closeBox;
if (theType == 0) theHTML += "<b><font style = ' font-size: 16px'>" + flashHeading[0] + "</font></b><br>";
else if (theType <= 2) theHTML += "<b><font style = ' font-size: 16px'>GAME OVER</font></b><br>";
else theHTML += "<b><font style = ' font-size: 24px'>" + flashHeading[1] + "</font></b><br>";
theHTML += content;
theHTML += "</td></tr></table></div></center>";
if(theType == 0) {var bgColor1 = '#A01F00'; var bgColor2 = '#FF0000'}
else if (theType <= 2) {var bgColor1 = '#E07817'; var bgColor2 = '#F7C749'}
else {var bgColor1 = '#00A01F'; var bgColor2 = '#00FF00'}
//alert(theHTML);
theStuff.innerHTML = theHTML;
theStuff.style.visibility = 'visible'; 
theStuff.style.display = '';

timers [22] = setTimeout("parent.left.document.getElementById('theWarning').style.backgroundColor = " + quoteMark +  bgColor1  + quoteMark + ";", 200);
timers [23] = setTimeout("parent.left.document.getElementById('theWarning').style.backgroundColor = " + quoteMark +  bgColor2  + quoteMark + ";", 400);
timers [24] = setTimeout("parent.left.document.getElementById('theWarning').style.backgroundColor = " + quoteMark +  bgColor1  + quoteMark + ";", 600);
timers [25] = setTimeout("parent.left.document.getElementById('theWarning').style.backgroundColor = " + quoteMark +  bgColor2  + quoteMark + ";", 800);
timers [26] = setTimeout("parent.left.document.getElementById('theWarning').style.backgroundColor = " + quoteMark +  bgColor1  + quoteMark + ";", 1000);


} // flashWarning


// ************** end of score adjustment


// ***** Various misc utilis

function pickOneG() {
// if not playing, returns the first argument
// otherwise one of the remaining ones selected at random
var argArr = pickOneG.arguments;
var n = argArr.length-1;
if (playing) return(pickOneG.arguments[randomInt(1,n)]);
else return(pickOneG.arguments[0]);
} // pickOneG

function randomIntG(n,a,b) {
// if not playing returns n
// otherwise a random integer in the range [a, b]
if (playing) return(a + Math.floor(Math.random()*(b-a+1)));
else return(n);
}

function randomNonzeroIntG(n, a, b) {
// returns a nonzero random integer in the range [a, b] if playing
// otherwise n
if (playing) return(randomNonzeroInt(a, b));
else return(n);
}


function numberWord(n) {
if ((n >= 0) && (n <= 10)) return(numberWords[n]);
else return(n.toString());
}







