// check if we are opening a saved version of the current homework
// this only happens if the user requests it
// at which point a temporary cookie UseSaved is written with value true

var theUserName = ''; // this is defined in the first statement of the 
	// user's file
var 	loggedIn = false;
var isLive = false;

var usingSaved = false;

var savedHWFile = getCookie("Opening");
if ((savedHWFile != "")&& (savedHWFile != null)) {
// alert(savedHWFile);
	theUserName = extractName(savedHWFile); 
	loggedIn = true;
	wasSaved = true;
	var thefileName = pathPrefix + "homeworkManagement/userFiles/" + savedHWFile;
	include_dom(thefileName);
	}

function extractName(theString) {
// alert (theString.substring(8, theString.length-3));
return (theString.substring(8, theString.length-3));
}

function handleFocus() {
var theCheck = getCookie("PassingControl");
if ((theCheck != "")&& (theCheck != null)) {
// alert(theLanguage);
 	setCookie('PassingControl',"",yesterday,'/');
	var theFileN = getCookie("Opening");
	if ((theFileN!= "")&& (theFileN!= null)) {
// alert(savedHWFile);
		theUserName = extractName(theFileN); 
		loggedIn = true;
		wasSaved = true;
		var thefileName = pathPrefix + "homeworkManagement/" + theFileN;
		include_dom(thefileName);
		}
	var theNameSt = "";
	if (theLanguage == "en") theNameSt = theUserName + " logged in";
	else theNameSt = theUserName + " sesi&oacute;n iniciado";
	document.getElementById("loggedInBox").innerHTML = theNameSt;
	ShowContent("logOutText"); // in utils
	HideContent("logInText");
	ShowContent("loggedInBox");

	}
}

function PutLoginDialogs (lang) {

if (isLive) {
	var logInWord = "Log in";
	if (lang == "es") logInWord = "Iniciar sesi&oacute;n";
	var logOutWord = "Log out " + theUserName;
	if (lang == "es") logOutWord = "Terminar sesi&oacute;n " + theUserName;

	var theText = '<span id = "loggedInBox" onClick = " packageAndSave(homework_set)" style = "{ position:fixed; left:2px; bottom:2px; border: 1px solid; border-color: charcoal; font-family: Arial, Verdana, Helvetica, sans-serif; font-size: 10px; color: charcoal; background-color: #FB7F7F; visibility: hidden }"></span>';
	document.writeln(theText);


	var openWinStr = "Javascript: sesame('" + pathPrefix + "homeworkManagement/login.html',500,500)";
	theText2LogIn = '<span id = "logInText" style = "{visibility : hidden}"><a href = " ' + openWinStr  + '">' + logInWord + '</a></span>';
	theText2LogOut = '<span id = "logOutText" style = "{visibility : hidden; position: relative; left:-40px}"><a href = "Javascript: handleLogOut()">' + logOutWord + '</a></span>'; 

	document.writeln(theText2LogIn);
	document.writeln(theText2LogOut); 


	
	if (loggedIn) {
		var theNameSt = "";
		if (lang == "en") theNameSt = theUserName + " logged in. Click to save work.";
		else theNameSt = theUserName + " sesi&oacute;n iniciado. Haz clic para ahorrar trabajo.";
		document.getElementById("loggedInBox").innerHTML = theNameSt;
		ShowContent("logOutText"); // in utils
		HideContent("logInText");
		ShowContent("loggedInBox");
	
		}
	else {
		ShowContent("logInText");
		HideContent("loggedInBox");
		}
		
	} // is isLive
} // drawLoggedInBox

function handleLogOut() {
setCookie('Opening',"",yesterday,'/');
loggedIn = false;
HideContent("loggedInBox");
HideContent("logOutText");
ShowContent("logInText");
} // 

function packageAndSave(homeworkSet) {
// the perl target equals "hole" 
// first get the user's name
var savedHWFile = getCookie("Opening");
alert("Opening" + savedHWFile);
if (savedHWFile != "") {
	var thefileName = pathPrefix + "/homeworkManagement/userFiles/" + savedHWFile;
	include_dom(thefileName);
	loggedIn = true;
// alert(thefileName);
	}
else {
	alert("You can only save your work if you are logged in. To log in, click on the Login link at the top of the page");
	loggedIn = false;
	}
if (loggedIn) {
	var theStr = pathPrefix + "homeworkManagement/saveHandler.pl?userfile=" + "/homeworkManagement/userFiles/" + savedHWFile + "&homework_set=" + homeworkSet;
	for (var i = 0; i <= theQuestionNameDataNames.length-1; i++) {
		var theCmd = "theValue = " + theQuestionNameDataNames[i];
		eval(theCmd); 
		theStr += "&" + theQuestionNameDataNames[i] + "=" + theValue;
		}
	var thecmd = "frames[" + quoteMark + "hole" + quoteMark + "].location = '" + theStr + "'";
	alert(thecmd);
	eval(thecmd);
	} // if loggedIn
}






function updateHomework() {
// reads the appropriate cookie and marks done exercises.

} // updateHomework

// exercise numbering
var exerciseNumber = 1;
function writeExerciseNumber() {
var nStr = exerciseNumber.toString();
document.writeln('<b>' + nStr + '. </b>');
exerciseNumber += 1;
}

function setExerciseNumber(n){
exerciseNumber = n;
}



// answer routines
function showA(topicName, name, num, width, height) {
var theFileName = topicName + "Ans/" + name + num.toString() + "help.html";
sesame(theFileName, width, height);
} // C

function clearA(name, num) {
// alert('here');
var picString = 'pic' + name + num.toString();
var ansString = name + num.toString();
document.images[picString].src = '../elts/smallblank.gif';
var cmd = 'document.' + name + '.' + ansString + '.value = ""';
var doIt = eval(cmd); } // clearA


function peekA(name, num) {
// alert('here');
var picString = 'pic' + name + num.toString();
var ansString = name + num.toString();
// alert(picString);
document.images[picString].src = '../elts/smallblank.gif';
var cmd = 'document.' + name + '.' + ansString + '.value = ' + 'Ans' + name + '[' + num.toString() + ']';
// alert(cmd);
var doIt = eval(cmd); } // peekA


function checkLinearEq(name, num, accuracy, isExp){
// does exponential ones as well if isExp is true
// alert('here');
var picString = 'pic' + name + num.toString();
var ansString = name + num.toString();
var theIns = "var correctAns = " + "Ans" + name + "[" + num.toString() + "]";
var act = eval(theIns);
var acc = parseFloat(accuracy);
if (isNaN(acc)) acc = .0005;
// alert(acc)
try{
	var vv = checkAnswerandValue(name, ansString, correctAns, 1, 20, acc, 'x=0', ' t = 0' , ' ' );
	if (vv == 0) document.images[picString].src = '../elts/smallq.gif';
	else if (vv == 1) {

		x = 0; t = 0;
		var theAct = "var theSubmittedAns = document." + name + "." + ansString + ".value;";
		var act = eval(theAct);
		var corrInt = myEval(correctAns);
		var inputInt = myEval(theSubmittedAns);
		x = 1; t = 1;
		if (isExp) {
			var corrSlope = myEval(correctAns) / corrInt;
			var inputSlope = myEval(theSubmittedAns) / inputInt;
			}
		else {
		 	var corrSlope = myEval(correctAns) - corrInt;
			var inputSlope = myEval(theSubmittedAns) - inputInt;
			}
// alert(Math.abs(corrSlope- inputSlope) + "," + acc);
		if (Math.abs(corrSlope - inputSlope) < acc) document.images[picString].src = '../elts/smallcheck.gif'; 
		else document.images[picString].src = '../elts/smallx.gif';

		}
	else document.images[picString].src = '../elts/smallx.gif';
	}
catch (error)
	{
 	 document.images[picString].src = '../elts/smallq.gif';
	}

}// checkLinearEq

function checkA(name, num, accuracy, isText){
// alert('here');
var picString = 'pic' + name + num.toString();
var ansString = name + num.toString();
var theIns = "var correctAns = " + "Ans" + name + "[" + num.toString() + "].toString()";
var act = eval(theIns);
var acc = parseFloat(accuracy);
if (isNaN(acc)) acc = .0005;
// alert(acc)
var vv = 0;
if (isText) {
	var theIns2 = "var inputAns = document." + name + "." + name + num.toString() + ".value";
act = eval(theIns2);
	var theSt = stripSpaces(inputAns.toLowerCase());
	theSt = replaceSubstring(theSt,"/","per");
	if (theSt == '') vv = 0;
	else if (theSt == correctAns) vv = 1; 
	else vv = 6;
	if (vv == 1) document.images[picString].src = '../elts/smallcheck.gif';
	else if (vv == 0) document.images[picString].src = '../elts/smallq.gif'; 
	else document.images[picString].src = '../elts/smallx.gif';
	}// for text
else try {
// alert(name + "," + ansString + "," + correctAns + "," + acc);
	vv = checkAnswerandValue(name, ansString, correctAns, 1, 20, acc, 'x=0.45', ' t = 0.34' , ' ' );

	if (vv == 1) document.images[picString].src = '../elts/smallcheck.gif';
	else if (vv == 0) document.images[picString].src = '../elts/smallq.gif'; 
	else document.images[picString].src = '../elts/smallx.gif'; 
// alert(picString);
	}
catch (error)
	{
 	 document.images[picString].src = '../elts/smallq.gif';
	}

}// checkA

function checkARange(name, num1, num2, accuracy, isText) {
for (var i = num1; i <= num2; i++) {
	checkA(name, i, accuracy, isText);
	} // i
} // checkARange

function clearARange(name, num1, num2) {
for (var i = num1; i <= num2; i++) {
	clearA(name, i);
	} // i
} // clearARange

function peekARange(name, num1, num2) {
for (var i = num1; i <= num2; i++) {
	peekA(name, i);
	} // i
} // peekARange

function showHideTextanswer(Qstring, number) {
var theAnsDiv = Qstring + "AnsText";
var theAnsArrayName = "Ans" + Qstring;
// alert(theAnsDiv);
var theAns = document.getElementById(theAnsDiv)
if (theAns.innerHTML == "") { 
	var appl = "theAns.innerHTML = " + theAnsArrayName + "[" + number.toString() + "];";
// alert(appl);
	var doIt = eval(appl);
	try{jsMath.ProcessBeforeShowing(theAns)}
	catch (error) {}
	}
else {
	var appl = "theAns.innerHTML = '';";
	var doIt = eval(appl);
	}

} // showHideTextanswer


// ************** General Utilities
function pickOne() {
var argArr = pickOne.arguments;
var n = argArr.length-1;
return(pickOne.arguments[randomInt(0,n)]);
}

function randomInt(a,b) {
// returns a random integer in the range [a, b]
return(a + Math.floor(Math.random()*(b-a+1)));
}

function randomSequence(n) {
// Returns an array A[i] whose ith entries are a random
// permutation of 1,..,n
var outArr = new Array();
var slot = new Array();
for (var i = 1; i <= n; i++) slot[i] = i;
for (var i = 1; i <= n; i++) {
	var j = randomInt (1,n-i+1); // number of slots left
	outArr [i] = slot [j];
	for (var k = j; k <= n-i; k++) {
		slot[k] = slot[k+1];
		} // k
	} // i
return (outArr);
} // randomSequence
// alert(randomSequence(10));

function shuffle(A) {
// A can be an array of arrays.
// internally shuffles each of these arrays
var APrime = A.slice();
var len = A.length;
for (var i = 0; i <= len-1; i++) {
	var len_i = A[i].length;
	var Copy = A[i].slice();
	var P = randomSequence(len_i);
	for (var j = 0; j <= len_i-1; j++) {
		APrime[i][j] = Copy[P[j+1]-1];
		} //j
	} // i
// alert(APrime);
return(APrime);
} // shuffle


function permute(A) {
// A is an array of arrays
// returns an array B of all possible permutation strings
// starting with B[1];
var B = new Array();
var len = A.length;
var theArgument = " A[0][i0]";
for (var i = 1; i <= len-1; i++) {
	var st = i.toString();
	theArgument += "+ A[" + st + "][i"+ st + "]";
	} // i
var count = 0;
var innerInstruction = "count += 1; B[count] = " + theArgument;
// alert(theArgument);
var theLoop = innerInstruction;
for (var n = 0; n <= len-1; n++ ) {
	theLoop = nestedLoopString(theLoop,n, 0, A[n].length-1)
	} // n
// alert(theLoop);
var executeThis = eval(theLoop);
// alert(B);
return(B);
} // permute
// permute([ ["increases by ","decreases by "], ["2", "4"], [" thousand kilos per ", " kilos per "," million kilos per "],["square meter", "hundred square meters", "million square meters"] ]);

// the next is needed for the permutation one above
function nestedLoopString(inString,n, fromNum, toNum) {
// n is a variable name appended to i
var iName = "i" + n.toString();
var theSt = "for (var " + iName + " = " + fromNum.toString() + "; " + iName + " <= " + toNum.toString() + "; " + iName + "++){";
var outString = theSt + inString + "}";
// alert(outString);
return (outString);
} // nestedLoopString


function generateMultipleChoiceArray(numChoices, correctCh, A ) {
// A is an array of choice array strings
// so an item is a concatenoation of random choices from each array
// eg A = [ ['red', 'green'] , ['mustang', 'pontiac'] ]
// will generate four possible choices
// zeroth position of output array is the index of the correct choice

var outArray = new Array();
// first pick a slot for the correct answer, if nonempty
if (correctCh != "") {
	var k = randomInt(1,numChoices);
	outArray[k] = correctCh;
	outArray[0] = k;
	} 
var B = permute(shuffle(A)); 
// alert(B);
	// the set of all permutations of a shuffled
	// version of A
var counter = 1;
for (var i = 1; i <= numChoices; i++) {
	if (i == k) i += 1;
	if (B[counter] == correctCh) {
		counter += 1;
		outArray[i] = B[counter]}
	else (outArray[i] = B[counter]);
	counter += 1;
	} // i
// alert(outArray);
return (outArray);
} // generateMultipleChoiceArray

// the following is not used
function randomizeSentenceArray() {
var len = randomizeSentenceArray.arguments.length;
var choicesMade = new Array();
// alert(len);
var nc, rn, outString = "";
for (var i = 0; i <= len-1; i++) {
	nc = randomizeSentenceArray.arguments[i].length;
	rn = randomInt(0,nc-1); 
// alert(i + ", rn = " + rn);
	choicesMade[i] = rn;
	outString += (randomizeSentenceArray.arguments[i]) [rn];
	}// i
// alert(outString);
return(outString);
}




// ******************COOKIE ROUTINES *****************
var cookiesEnabled = false;
var now = new Date();
var oneDay = new Date(now.getTime() + 60000 * 60 * 24);
var oneYear = new Date(now.getTime() + 60000 * 60 * 24 * 365);
var yesterday = new Date(now.getTime() - 60000 * 60 * 24);

function cookieTest() {
// returns false if cookies are not enabled
var now = new Date();
var twosecs = new Date(now.getTime() + 1000 * 2)
setCookie('cookieTest','You will meet a tall dark stranger.', twosecs);
var testing = getCookie('cookieTest');
if(testing == null) {cookiesEnabled = false; return(false) }
else {cookiesEnabled = true; return(true) }
} // cookieTest

// ********************Old Cookie Routines **********************

function setCookie (cookieName, cookieValue, expires, path, domain, 
secure) {
  document.cookie = 
    escape(cookieName) + '=' + escape(cookieValue) 
    + (expires ? '; EXPIRES=' + expires.toGMTString() : '')
    + (path ? '; PATH=' + path : '')
    + (domain ? '; DOMAIN=' + domain : '')
    + (secure ? '; SECURE' : '');
}

function getCookie (cookieName) {
  var cookieValue = null;
  var posName = document.cookie.indexOf(escape(cookieName) + '=');
  if (posName != -1) {
    var posValue = posName + (escape(cookieName) + '=').length;
    var endPos = document.cookie.indexOf(';', posValue);
    if (endPos != -1)
      cookieValue = unescape(document.cookie.substring(posValue, 
endPos));
    else
      cookieValue = unescape(document.cookie.substring(posValue));
  }
  return cookieValue;
}

// ***************** End of Old Cookie Routines *****************

// the ones below eset the path to top directory

function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                + ";expires="+expire.toGMTString() + ";path=/";
}


function ReadCookie(cookieName) {
 var theCookie=""+document.cookie;
 var ind=theCookie.indexOf(cookieName);
 if (ind==-1 || cookieName=="") return ""; 
 var ind1=theCookie.indexOf(';',ind);
 if (ind1==-1) ind1=theCookie.length; 
 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}



// *** Randomizing/Savable things

function randomizeNum (number, n, delta) {
// adds delta times a random integer in [-n, n]
return (randomInt(-n,n)* delta + number);
}

function randomizeArr (inArrayName, numPoints, n, delta, minVal, maxVal, rounding) {
// inArrayName needs to be global to the document 
// Also it needs to start with the 1st entry (not the zeroth)
// and needs to be IN QUOTES here
// (one per question or part of question)
// That very array has values stored in "studentNameData.js"
// under the name "inArraySaved"
// eg if the array is xCoordsQ2[] then xCoordsQ2Saved = ...
// must be resident in studentNameData.js
// adds delta times a random integer in [-n, n] to each entry
// gives minimum and maximum values in slots numPoints + 1, numPoints + 2
// If the page has been launched from an "open" command
// then the cookie entry "UseSaved" need to have value true
// this cookie only lasts until the page is loaded
// then it is deleted at the end of loading (onload = delete cookie)
// also the file studentNameData.js needs to have been loaded 
// (this is again done via the cookie "UseSaved")
var outArray = new Array();

	var theCmd = "outArray = " + inArrayName + ".slice()";
	var doIt = eval(theCmd);
	var xvar = 0;
	var maxValue, minValue;
	for (var i = 1; i <= numPoints; i++) {
		xvar = outArray [i];
		outArray [i] = parseFloat(roundDec(randomizeNum(xvar,n, delta) , rounding));
		if (outArray [i] > maxVal) outArray [i] = maxVal;
		else if (outArray [i] < minVal) outArray [i] = minVal;
		if (i == 1) { maxValue = outArray [i]; minValue = outArray [i]}
		else if (outArray [i] > maxValue) maxValue = outArray [i];
		else if (outArray [i] < minValue) minValue = outArray [i];
		} // i
	outArray [numPoints + 1] = minValue;
	outArray [numPoints + 2] = maxValue;

return(outArray);
}

