// Get SCORM version
var SCORM_Version;
var timedTest = false;
var questionId = new Array();

if(typeof(parent.topEmpty.LMSGetValue) == "function") {
	SCORM_Version = "1.2";
} else if (typeof(parent.topEmpty.doGetValue) == "function") {
	SCORM_Version = "2004";
} else {
	SCORM_Version = "none";
}

//This document will eventually be divided into two sections, The top section will contain all the important 
//methods that can be called while the bottom half will contain smaller methods that the public methods will call. 

//Function creates the Internet Explorer or other browser xml document reader.  The variable
//dname is the name of the XML document that will be loaded and open for manipulation
function loadTestXML(dname) 
{
	var xmlhttp=false;	
	isLocal=false;
	
	var isIE = -1;
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
		isIE = parseFloat( RegExp.$1 );
	}	
	
	/* running locally on IE6, IE7 */      
	 if(location.protocol=="file:"){
	  if(!xmlhttp)try{ xmlhttp=new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){xmlhttp=false;}
	  if(!xmlhttp)try{ xmlhttp=new ActiveXObject("Microsoft.XMLDOM");; }catch(e){xmlhttp=false;}
	  isLocal=true;
	 }                                                                                ; 
	/* IE7, Firefox, Safari, Opera, Chrome...  */
	 if(!xmlhttp)try{ xmlhttp=new XMLHttpRequest(); }catch(e){xmlhttp=false;}
	/* IE6 */
	 if(typeof ActiveXObject != "undefined"){
	  if(!xmlhttp)try{ xmlhttp=new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){xmlhttp=false;}
	  if(!xmlhttp)try{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){xmlhttp=false;}
	 }
	
	if(isLocal==true && isIE!=-1) {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");		
		xmlDoc.async = "false";
		xmlDoc.load(dname);
		return(xmlDoc);
	} else {
		xmlhttp.open("GET",dname,false);
		xmlhttp.onreadystatechange=function(){
		if(xmlhttp.readyState!=4)return;
	
		};//onreadystatechange
		xmlhttp.send(null);
	
		xmlDoc=xmlhttp.responseXML;	
		return(xmlDoc);
	}

}

//function initalizes the object that will interact with the XML document
//later functionality will be to create an initilization variable that allows dynamic loading
function init(file)
{
    
	parent.topEmpty.manifestDoc=loadTestXML(file);
	//alert("xmlDoc is loaded, ready for use");
}

function initProgress(file)
{
	parent.topEmpty.progressDoc=loadTestXML(file);
	//alert("Progress xmlDoc is loaded, ready for use!");
}

function initGlobal(file)
{
	parent.topEmpty.globalDoc=loadTestXML(file);
	//alert(parent.topEmpty.globalDoc)
	getSettings();
}

//This function will create an original function list that remains in the original order. 
function getQuestionList()
{
	try {
		parent.topEmpty.orgquestionList=parent.topEmpty.manifestDoc.getElementsByTagName("imsmd:identifier");
	} catch (err) {
		parent.topEmpty.orgquestionList=parent.topEmpty.manifestDoc.getElementsByTagName("identifier");
	}
}

//Function prints either the original question list from the XML file or it prints the randomized array containing the new
//question order
//passing a 0 = original list
//passing a 1 = randomized list
//passing a 2 = link array
//passing a 3 = distractor list 
function printList(a)
{
	if(a==0)
	{
		for (var i=0; i<parent.topEmpty.orgquestionList.length; i++)
		{ 
			document.write(i + ". " +parent.topEmpty.orgquestionList[i].childNodes[0].nodeValue);
			space();
		}	
	}
	else if(a==1)
	{
		for (var i=0; i<parent.topEmpty.randomList.length; i++)
		{ 
			document.write(i + ". " +parent.topEmpty.randomList[i]);
			space();
		}	
	}
	else if(a==2)
	{
		for(var i=0; i<parent.topEmpty.linkArray.length; i++)
		{
			document.write(i + ". " + parent.topEmpty.linkArray[i]);
			space();
		}
	}
	else if(a==3)
	{	
		document.write("A. " +parent.topEmpty.distractorRan[0]);
		space();
		document.write("B. " +parent.topEmpty.distractorRan[1]);
		space();
		document.write("C. " +parent.topEmpty.distractorRan[2]);
		space();
		document.write("D. " +parent.topEmpty.distractorRan[3]);
	}
	else
	{
		//alert("list not found");
	}
	space();
}


//function randomizes the questions into a new list called randomList
//this random list will be used to load other XML documents containing the actual question items
function randomize()
{
	for(var i=0; i<parent.topEmpty.orgquestionList.length; i++)
	{
		var success = false;
		var g = Math.floor(Math.random()*parent.topEmpty.orgquestionList.length);
	
		while(success==false)
		{
			if(parent.topEmpty.randomList[g]==undefined)
			{
				parent.topEmpty.randomList[g]      = parent.topEmpty.orgquestionList[i].childNodes[0].nodeValue;
				parent.topEmpty.linkArray[g]       = parent.topEmpty.manifestDoc.getElementsByTagName("resource")[i].getAttribute("href");
				try {
				parent.topEmpty.interactionType[g] = parent.topEmpty.manifestDoc.getElementsByTagName("imsqti:interactionType")[i].childNodes[0].nodeValue;
				} catch(err) {
				parent.topEmpty.interactionType[g] = parent.topEmpty.manifestDoc.getElementsByTagName("interactionType")[i].childNodes[0].nodeValue;
				}
				success=true;
			}
			else
			{
			g=Math.floor(Math.random()*parent.topEmpty.orgquestionList.length);
			}
		}
	}
	addLink();
 }

//generates a new array called linkArray that uses the data from randomList to generate the links to the xml files
//a new array is used to preserve data, must like the orgquestionList is not scrabled itself 
function generatelinkArray()
{
	for (var i=0; i<parent.topEmpty.randomList.length; i++)
	{ 
		//alert(parent.topEmpty.linkArray[i] + " Interaction Type: " + parent.topEmpty.interactionType[i]);
	}
}

//Function allows the main page to call a parameterless start call for the purpose of initilizaing the question sequence 
function start()
{
	//Switch these methods to disable instead of hiding the button for better visual layout. 
	document.getElementById("next").style.visibility = "hidden";
	document.getElementById("back").style.visibility = "hidden";
	document.getElementById("buttonSpace").innerHTML=" ";
	//alert(testPath[0] + "/imsmanifest.xml");
	init(testPath[0] + "/imsmanifest.xml");
	initGlobal(testPath[0] + "/globalSettings.xml");
	initProgress("../../xml/progress.xml");
	//initGlobal("../../xml/globalSettings.xml");
	isTestBank();
	checkTimedTest();
	if(testBank == "false")
	{
		getQuestionList();
		randomize();
		generatelinkArray();
		nextQuestion();
	}
	else
	{
		runTestBank();
	}
}

//function creates the first question document reader
function loadQuestion(txt)
{
	parent.topEmpty.questionDoc=loadTestXML(testPath[0] + "/" + txt);
	if(!vistedAllQuestions)
	{
		parent.topEmpty.questionIndex++;
		maxQuestions++;
	}
}

function loadQuestionTB(txt)
{
	//alert(txt);
	if (typeof(txt) != "undefined") {		
		parent.topEmpty.questionDoc=loadTestXML(txt);
	}
	
	if(!vistedAllQuestions)
	{
		parent.topEmpty.questionIndex++;
		maxQuestions++;
	}
	
}

//function retrives the question embedded in the xml document 
function getQuestion() {
    question = parent.topEmpty.questionDoc.getElementsByTagName("prompt")[0].childNodes[0].nodeValue;

    // Replace BB code for underline
    question = question.replace(/[[]u[]]/gi, "<u>");
    question = question.replace(/[[]\/u[]]/gi, "</u>");

    // Replace BB code for bold
    question = question.replace(/[[]b[]]/gi, "<strong>");
    question = question.replace(/[[]\/b[]]/gi, "</strong>");

    // Replace BB code for italics
    question = question.replace(/[[]i[]]/gi, "<i>");
    question = question.replace(/[[]\/i[]]/gi, "</i>");

    return question;
}

function getQuestionSpecial()
{
	var question="";
	var txt = "inlineChoiceInteraction";
	var begin;
	var end;
	var string1;
	var string2;
	question = parent.topEmpty.questionDoc.getElementsByTagName("p")[0].xml;
	begin = question.indexOf("inlineChoiceInteraction");
	end = question.indexOf("/inlineChoiceInteraction");
	string1=question.slice(0,begin-1);
	string2=question.slice(end + txt.length+2);
	question = string1 + createDropDown() +string2;
	return question;
}

function getQuestionTextEntry()
{
	var question ="";
	question = parent.topEmpty.questionDoc.getElementsByTagName("p")[0].xml;
	var txt="textEntryInteraction";
	var begin;
	var end;
	var string1;
	var string2;
	begin = question.indexOf(txt);
	end = question.indexOf("/textEntryInteraction");
	string1 = question.slice(0,begin-1);
	string2 = question.slice(end + txt.length+2);
	question = string1 + createTextArea() + string2;
	return question;
}

//loads  the next question obviously, it is supposed to incriment based on the position of the 
//question index.  It needs work, not perfect though. 
function nextQuestion()
{
	//alert("beginning next question sequence");
	var z = parent.topEmpty.questionIndex;
	if(testBank == "false")
	{
		//alert("Test Bank is false");
		loadQuestion(parent.topEmpty.linkArray[parent.topEmpty.questionIndex]);
	}
	else
	{
		//alert("Test Bank is true");
		loadQuestionTB(parent.topEmpty.linkArray[parent.topEmpty.questionIndex]);
	}
	if(z < getQuestionLength())
	{
		//alert("Loading next question now");
		document.getElementById("pictureArea").innerHTML="";
		parent.topEmpty.isGoodToGo = false;
		displayQuestion(z);
		addQuestion(z);
		addDistractor(z);
		//nullify();
	}
	else
	{
		//alert("Test Finished");
		document.getElementById("questionID").innerHTML="";
		document.getElementById("correct").innerHTML="";
		document.getElementById("keys").innerHTML="";
		document.getElementById("pictureArea").innerHTML="";
		//document.getElementById("next").style.visibility = "";
		if(parent.topEmpty.displayResults=="true")
		{
			//alert("Will Display Results");
			if(testBank == "false")
			{
				displayRslts();
			}
			else
			{
				//alert(runReview());
				if(runReview())
				{
					reviewQuestions();
				}
				else
				{
					displayTestBankResults();
				}
			}
		}
		//parent.topEmpty.document.getElementById("grade").innerHTML="Grade :" + parent.topEmpty.totalGrade + " / " + parent.topEmpty.possibleGrade;
		//printProgressXML();
	}
}

//Returns number of questions or "links" in the linkArray
function getQuestionLength()
{
	return parent.topEmpty.linkArray.length;
}

//Retrives Discractors from xmlQuestionDoc 
function getDistractorsChoiceInteraction()
{
	parent.topEmpty.distractorArray = parent.topEmpty.questionDoc.getElementsByTagName("simpleChoice");
}

function getDistractorsInlineInteraction()
{
	parent.topEmpty.distractorArray = parent.topEmpty.questionDoc.getElementsByTagName("inlineChoice");
}

function randomizeDistractors()
{
	if(vistedAllQuestions == false)
	{
		if(canRandomizeDistractors())
		{
			var temp = new Array();
			for(var i=0; i<parent.topEmpty.distractorArray.length; i++)
			{
				var success = false;
				var g = Math.floor(Math.random()*parent.topEmpty.distractorArray.length);
				while(success==false)
				{
					if(parent.topEmpty.distractorRan[g]==undefined)
					{
						parent.topEmpty.distractorRan[g]=parent.topEmpty.distractorArray[i].childNodes[0].nodeValue;
						temp[g] = parent.topEmpty.keyValues[i];
						success=true;
					}
					else
					{
						g=Math.floor(Math.random()*parent.topEmpty.distractorArray.length);
					}
				}
			}
			parent.topEmpty.keyValues   = temp;
			savedKeyArray[frmCount-1]   = temp;
			savedOrderArray[frmCount-1] = parent.topEmpty.distractorRan;
			//alert("distractors randomized");
		}
		else
		{
			var temp = new Array();
			for(var i=0; i<parent.topEmpty.distractorArray.length; i++)
			{
				parent.topEmpty.distractorRan[i]=parent.topEmpty.distractorArray[i].childNodes[0].nodeValue;
				temp[i] = parent.topEmpty.keyValues[i];	
			}
			parent.topEmpty.keyValues   = temp;
			savedKeyArray[frmCount-1]   = temp;
			savedOrderArray[frmCount-1] = parent.topEmpty.distractorRan;
			//alert("distractors ARE NOT randomized");
		}
	}
	else
	{
		parent.topEmpty.keyValues     = savedKeyArray[frmCount-1];
		parent.topEmpty.distractorRan = savedOrderArray[frmCount-1];
	}
}

function canRandomizeDistractors()
{
	return true;
}

//sets both arrays back to zero to avoid the wrong distractors as well as creating infinite
//loops for the system
function nullify()
{
	parent.topEmpty.distractorRan   = new Array();
	parent.topEmpty.distractorArray = new Array();
	parent.topEmpty.keyValues       = new Array(); 
	parent.topEmpty.mapValue	    = new Array();
	parent.topEmpty.correctResponse = new Array();
}

//funtion will add each question link to the XML file as well as the distractors appending it to the link.  A method for adding the question is also needed 
function addLink()
{
	//alert("addlink");
	/* for(var i=0; i<parent.topEmpty.linkArray.length; i++)
	{
		newel=parent.topEmpty.progressDoc.createElement("link");
		newtext=parent.topEmpty.progressDoc.createTextNode(parent.topEmpty.linkArray[i]);
		newel.appendChild(newtext);
		var x=parent.topEmpty.progressDoc.getElementsByTagName("userprogress")[0];
		x.appendChild(newel);
	} */
}

function addDistractor(int)
{
	/* for(var i=0; i<parent.topEmpty.distractorRan.length; i++)
	{
		var newq=parent.topEmpty.progressDoc.createElement("distractor");
		var newqtext=parent.topEmpty.progressDoc.createTextNode(parent.topEmpty.distractorRan[i]);
		newq.appendChild(newqtext);
		var f = parent.topEmpty.progressDoc.getElementsByTagName("question")[int];
		f.appendChild(newq);
	} */
}

function addQuestion(int)
{
	/* var newq = parent.topEmpty.progressDoc.createElement("question");
	if(parent.topEmpty.interactionType[int] == "choiceInteraction")
	{
		var newqtext = parent.topEmpty.progressDoc.createTextNode(parent.topEmpty.questionDoc.getElementsByTagName("prompt")[0].childNodes[0].nodeValue);
	}
	else
	{
		var newqtext = parent.topEmpty.progressDoc.createTextNode(parent.topEmpty.questionDoc.getElementsByTagName("p")[0].childNodes[0].nodeValue);
	}
	newq.appendChild(newqtext);
	var f = parent.topEmpty.progressDoc.getElementsByTagName("link")[int];
	f.appendChild(newq); */
}

function addAnswer(z, text)
{
	//alert(z + " " + text);
	/* var newq = parent.topEmpty.progressDoc.createElement("response");
	var newqtext = parent.topEmpty.progressDoc.createTextNode(text);
	newq.appendChild(newqtext);
	var f = parent.topEmpty.progressDoc.getElementsByTagName("question")[z];
	f.appendChild(newq); */
}

//will be used to display multiple choice questions currently unfinished 
function displayQuestion(int)
{ 		
	//alert("displayQuestion function");
	if(parent.topEmpty.interactionType[int] == "choiceInteraction")
	{
		//alert("Will Display Choice");
		displayChoiceInteraction();
	}
	else if(parent.topEmpty.interactionType[int] == "truefalse")
	{
		//alert("Will Display Inline");
		displayChoiceInteraction();
	}
	else if(parent.topEmpty.interactionType[int] == "inlineInteraction")
	{
		//alert("Will Display Inline");
		displayInlineInteraction();
	}
	else if(parent.topEmpty.interactionType[int] == "textEntryInteraction")
	{
		//alert("Will Display Text");
		displayTextEntryInteraction();
	}
	else
	{
		alert("Question Type Not Supported");
	}
}

//Prints the progress XML to ensure it is saving correctly.  Currently not able to display or go through the nodes as I wish
//I would like it to display Link:question:distractor:distractor:distractor:distractor
//this method was updated and now it works, but it prints everything out sideways, maybe have to loop through
//nodes using relationships but this method is smaller and cleaner and the user will never actually see it
function printProgressXML()
{	
	var x=parent.topEmpty.progressDoc.getElementsByTagName("userprogress")[0];
	//parent.topEmpty.document.getElementById("text").innerHTML="<xmp>" + x.xml + "</xmp>";
	//document.write("<xmp>" + x.xml + "</xmp>");
	alert("<xmp>" + x.xml + "</xmp>");
}

function intro()
{
	/*var introText = "<form><center>";
	introText = introText + "<input name='begin' id='begin' type=\"button\" value=\"Begin!\" onclick=\"parent.content.start()\">";
	introText = introText + "</center></form>";
	document.getElementById("buttonSpace").innerHTML=introText;*/
	changeBegin();
}

function firstTime()
{
	return parent.topEmpty.beginning;
}

function isWritten()
{	
	var g = parent.topEmpty.written;
	parent.topEmpty.written = true;
	return g;
}

function changeBegin()
{
	parent.topEmpty.beginning = false;
	resetTestVars();
	start();
}

//function goes to next line
function space()
{
	document.write("<br />");
}

//this function will eventually contain all the code used to iterate through the questions and handle other events.  Main function most likely 
//besides initilization 
//Functions below this block of stars will be used to help grade items coming from the Quiz engine and Test Banks. 
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************

function mySubmit(form)
{
	gradeSystem(form);
	if(parent.topEmpty.isGoodToGo)
	{
		//alert(frmCount);
		gradeArray[frmCount-2] = 1;
		
		nullify();
	
		if(vistedAllQuestions == false)
		{
			nextQuestion();
		}
		else
		{
			reviewQuestions();
		}
	}
	else 
	{
		if(alerted == false)
		{
			alert("Please make a selection.");
		}
		else
		{
			alerted = false;
		}
	}
}

function getKeyValuesChoiceInteraction()
{
	var x = parent.topEmpty.questionDoc.getElementsByTagName("simpleChoice");
	for(var i=0; i<x.length; i++)
	{
		parent.topEmpty.keyValues[i] = parent.topEmpty.questionDoc.getElementsByTagName("simpleChoice")[i].getAttribute("identifier");
		//alert("Key Values: " + parent.topEmpty.keyValues[i]);
	}
}

function getKeyValuesInlineInteraction()
{
	var x = parent.topEmpty.questionDoc.getElementsByTagName("inlineChoice");
	for(var i=0; i<x.length; i++)
	{
		parent.topEmpty.keyValues[i] = parent.topEmpty.questionDoc.getElementsByTagName("inlineChoice")[i].getAttribute("identifier");
	}
}

function displayKeys()
{
	var key = parent.topEmpty.keyValues[0] + " ";
	for(var i=1; i<parent.topEmpty.keyValues.length; i++)
	{
		key = key + parent.topEmpty.keyValues[i]+" ";
	}
	return key;
}

function gradeChoice(form)
{
	var temp = parent.topEmpty.correctResponse.length;
	selectdLMSAnswer[frmCount-1] = null;
	//alert(temp);
	var temptemp = 0;
	var temptemptemp = 0;
	var gone = 0;
	var tempSaveArray = new Array();
	var arrayCount    = 0; 
	
	for(var Count = 0; Count<parent.topEmpty.keyValues.length; Count++)
	{
		if(form.choice[Count].checked)
		{
			//alert("Button " + form.choice[Count].value + " is selected");
			parent.topEmpty.isGoodToGo = true;
			//alert("Passed Choice: " + form.choice[Count].value);
			tempSaveArray[arrayCount] = Count;
			arrayCount++;
			if(selectdLMSAnswer[frmCount-1] == null)
			{
				selectdLMSAnswer[frmCount-1] = form.choice[Count].value;
			}
			else
			{
				selectdLMSAnswer[frmCount-1] = selectdLMSAnswer[frmCount-1] + "[,]" + form.choice[Count].value;
			}
			modifySubmitedAnswer(frmCount-1);
			//alert("SELECTED ANSWER LMS: " + selectdLMSAnswer[frmCount-1]);
			if(choiceCompare(form.choice[Count].value))
			{
				//alert("Correct!!");
				if(gone == 0)
				{
					parent.topEmpty.totalGrade ++;
					gone++;
				}
				temptemp++;
			}
			else
			{
				temptemptemp++
				//alert("Wrong!!! :( ");
			}
		}
	}
	savedAnswerArray[frmCount-2] = tempSaveArray;
	if(temp==temptemp && temptemptemp == 0)
	{
		//addAnswer(parent.topEmpty.questionIndex-1, "correct");
		savedCorrectArray[frmCount-2] = "correct";
	}
	else
	{
		//addAnswer(parent.topEmpty.questionIndex-1, "incorrect")
		if (SCORM_Version == "1.2") {
			savedCorrectArray[frmCount-2] = "wrong";
		} else if (SCORM_Version == "2004") {
			savedCorrectArray[frmCount-2] = "incorrect";
		}
	}
}

function gradeInline(form)
{	
	//alert("Begin inline drop down grading");
	parent.topEmpty.isGoodToGo = true;
	savedAnswerArray[frmCount-2] = form.list.selectedIndex;
	//alert("saved index of selected element");
    var Result = parent.topEmpty.keyValues[form.list.selectedIndex];
	//alert(Result);
	selectdLMSAnswer[frmCount-1] = Result;
	modifySubmitedAnswer(frmCount-1);
	//alert("SELECTED ANSWER LMS: " + selectdLMSAnswer[frmCount-1]);
	if(choiceCompare(Result))
	{
		//alert("Correct Response to Inline Drop Down");
		parent.topEmpty.totalGrade ++;
		//addAnswer(parent.topEmpty.questionIndex-1, "correct");
		savedCorrectArray[frmCount-2] = "correct";
		//alert("end correct response procedure");
	}
	else
	{
		//alert("Incorrect Response to inline Drop down");
		//addAnswer(parent.topEmpty.questionIndex-1, "incorrect");
		savedCorrectArray[frmCount-2] = "incorrect";
		return;
		//alert("end incorrect response process");
	}
	//alert("completed grading");
}

var alerted = false;

function gradeText(form)
{
	var txt = form.inputbox.value;
	selectdLMSAnswer[frmCount-1] = txt;
	savedAnswerArray[frmCount-2] = txt; 
	//alert("SELECTED ANSWER LMS: " + selectdLMSAnswer[frmCount-1]);
	if(txt.length < 1)
	{
		alerted = true;
		alert("Please enter your answer");
	}
	else
	{
		parent.topEmpty.isGoodToGo = true;	
		var crtxt = parent.topEmpty.correctResponse[0];
		if(txt.length > crtxt.length || txt.length < crtxt.length)
		{
			addAnswer(parent.topEmpty.questionIndex-1, "incorrect");
			savedCorrectArray[frmCount-2] = "incorrect";
			return
		}
		else if(txt == crtxt)
		{
			parent.topEmpty.totalGrade++;
			addAnswer(parent.topEmpty.questionIndex-1, "correct");
			savedCorrectArray[frmCount-2] = "correct";
			return;
		}
		else
		{
			addAnswer(parent.topEmpty.questionIndex-1, "incorrect");
			savedCorrectArray[frmCount-2] = "incorrect";
			return;
		}	
	}
}

function choiceCompare(txt)
{
	//alert("Value To Be Tested: " + txt);
	for(var i=0; i<=parent.topEmpty.correctResponse.length; i++)
	{
		//alert("Inner loop of Choice Compare reached");
		//alert("Value that is Test Criteria" + parent.topEmpty.correctResponse[i]);
		if(txt==parent.topEmpty.correctResponse[i])
		{
			return true;
		}
	}
	return false;
}

//functions below this block of stars will be concerned with the display formatting of questions. 
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************

frmCount = 1;

// Simply for displaying letters, instead of numbers, next to each choice's RB or CB.
var abcs = new Array(8);
	abcs[0] = "a";
	abcs[1] = "b";
	abcs[2] = "c";
	abcs[3] = "d";
	abcs[4] = "e";
	abcs[5] = "f";
	abcs[6] = "g";
	abcs[7] = "h";

function displayChoiceInteraction()
{	
	//alert("Beginning of displaying Choice");
	testGCR();
	//alert("Completed testgcr");
	getDistractorsChoiceInteraction();
	//alert("completed distractors call");
	getKeyValuesChoiceInteraction();
	//alert("completed key values");
	randomizeDistractors();
	//alert("completed randomization");
	hasImage();
	//alert("checked image");
	hasSenario();
	//alert("End of choice function calls");
	var button = chooseButtonType();
	var promptText = "Question " + frmCount + " of " + parent.topEmpty.linkArray.length + "<br /><br /><br />";
	promptText = promptText + getQuestion();
	var buttonText = "<input type=\"button\" id=\"submitBtn\" value=\"Submit!\" onclick=\"parent.content.mySubmit(document.forms.question" + frmCount + ")\" />";
	if(runReview())
	{
		buttonText = buttonText + " " + "<input type=\"button\" value=\"Mark and Skip!\" onclick=\"markQuestion()\" />";
	}
	var questionText = "<form name=\"question" + frmCount + "\">";
	questionText = questionText + "<table border=\"0\" cellpadding=\"3\">";
	
	for(var i=0; i<parent.topEmpty.distractorRan.length; i++)
	{
		questionText += "<tr><td>" + abcs[i] +".</td>";
		questionText += "<td><input type=\""+button+"\" name=\"choice\" value=\"" + parent.topEmpty.keyValues[i] +"\" ";		
		
		if (parent.topEmpty.showCorrect)
		{
		    for (var j=0; j<parent.topEmpty.correctResponse.length; j++)
		    {	       
		        if (parent.topEmpty.keyValues[i] == parent.topEmpty.correctResponse[j])
		        {
		            questionText += "checked=\"true\" ";
		        }
		    }
		}
		questionText += markPreviousAnswerChoice(i) + "></td><td>" + parent.topEmpty.distractorRan[i] + "</td></tr>";
	}
	questionText = questionText + "</table>";
	questionText = questionText + "</form>";
	document.getElementById("questionSpace").innerHTML = promptText + "<br /><br />";
	document.getElementById("choiceSpace").innerHTML   = questionText;
	document.getElementById("buttonSpace").innerHTML   = buttonText;

	var str = parent.topEmpty.linkArray[frmCount - 1];

	if (parent.topEmpty.showIDs) {	    
	    document.getElementById("questionID").innerHTML = str.substr(0, str.length-4);
	}
	/*if (parent.topEmpty.showCorrect) {
	    document.getElementById("correct").innerHTML="Correct Response Value: " + getCorrectResponseValue();
	}*/
	getCorrectResponse();
	//document.getElementById("keys").innerHTML="Question Keys: " + displayKeys();
	//parent.topEmpty.document.getElementById("grade").innerHTML="Grade :" + parent.topEmpty.totalGrade+ " / " + parent.topEmpty.possibleGrade;
	if(gradeArray[frmCount-1] == 1)
	{
		gradeArray[frmCount-1]  = 1;
	}
	else
	{
		gradeArray[frmCount-1]  = 0;
	}
    markedArray[frmCount - 1] = 0;
    questionId[frmCount - 1] = str.substr(0, str.length - 4);
	frmCount++;
	
	if (parent.topEmpty.showCorrect) {
		document.getElementById('submitBtn').focus();
	}
}

function displayInlineInteraction()
{
	testGCR();
	getKeyValuesInlineInteraction();
	getDistractorsInlineInteraction();
	randomizeDistractors();
	hasImage();
	hasSenario();
	var promptText = "Question " + frmCount + " of " + parent.topEmpty.linkArray.length + "<br /><br /><br />";
	//promptText = promptText + getQuestion();
	var buttonText = "<input type=\"button\" value=\"Submit!\" id=\"submitBtn\" onclick=\"parent.content.mySubmit(document.forms.question" + frmCount + ")\">";
	if(runReview())
	{
		buttonText = buttonText + " " + "<input type=\"button\" value=\"Mark and Skip!\" onclick=\"markQuestion()\" />";
	}
	var questionText = "<form name=\"question" + frmCount + "\">";
	questionText = questionText + getQuestionSpecial();
	questionText = questionText + "</form>";
	document.getElementById("questionSpace").innerHTML = promptText + "<br /><br />";
	document.getElementById("choiceSpace").innerHTML   = questionText + "<br />";
	document.getElementById("buttonSpace").innerHTML   = buttonText;
	var str = parent.topEmpty.linkArray[frmCount - 1];
	if (parent.topEmpty.showIDs) {
	    
	    document.getElementById("questionID").innerHTML = str.substr(0, str.length-4);
	}
	/*if (parent.topEmpty.showCorrect) {
	    document.getElementById("correct").innerHTML="Correct Response Value: " + getCorrectResponseValue();
	}*/
	
	getCorrectResponse();
	//document.getElementById("keys").innerHTML="Question Keys: " + displayKeys();
	//parent.topEmpty.document.getElementById("grade").innerHTML="Grade :" + parent.topEmpty.totalGrade+ " / " + parent.topEmpty.possibleGrade;
	if(gradeArray[frmCount-1] == 1)
	{
		gradeArray[frmCount-1]  = 1;
	}
	else
	{
		gradeArray[frmCount-1]  = 0;
	}
markedArray[frmCount - 1] = 0;
questionId[frmCount - 1] = str.substr(0, str.length - 4);
	frmCount++;
	
	if (parent.topEmpty.showCorrect) {
		document.getElementById('submitBtn').focus();
	}
}

function displayTextEntryInteraction()
{
	document.getElementById("questionSpace").innerHTML ="";
	document.getElementById("choiceSpace").innerHTML   ="";
	document.getElementById("buttonSpace").innerHTML   ="";
	testGCR();
    hasImage();
	hasSenario();
	var promptText = "Question " + frmCount + " of " + parent.topEmpty.linkArray.length + "<br /><br /><br />";
	var buttonText   = "<input type=\"button\" value=\"Submit!\" id=\"submitBtn\" onclick=\"parent.content.mySubmit(document.forms.question" + frmCount + ")\" />";
	
	if(runReview())
	{
		buttonText = buttonText + " <input type=\"button\" value=\"Mark and Skip!\" onclick=\"markQuestion()\" />";
	}
	var questionText = "<form name=\"question" + frmCount + "\" >";
	questionText = questionText + getQuestionTextEntry();
	questionText = questionText + "</form>";
	
	document.getElementById("questionSpace").innerHTML = promptText + "<br />";	
	document.getElementById("choiceSpace").innerHTML   = "<br />" + questionText;
	document.getElementById("buttonSpace").innerHTML   = buttonText;
	var str = parent.topEmpty.linkArray[frmCount - 1];
	if (parent.topEmpty.showIDs) {
	    
	    document.getElementById("questionID").innerHTML = str.substr(0, str.length-4);
	}
	/*if (parent.topEmpty.showCorrect) {
	    document.getElementById("correct").innerHTML="Correct Response Value: " + getCorrectResponseValue();
	}*/
	
	getCorrectResponse();
	//document.getElementById("keys").innerHTML="Question Keys: " + displayKeys();
	//parent.topEmpty.document.getElementById("grade").innerHTML="Grade :" + parent.topEmpty.totalGrade+ " / " + parent.topEmpty.possibleGrade;
	document.getElementById("textinput").focus();
	if(gradeArray[frmCount-1] == 1)
	{
		gradeArray[frmCount-1]  = 1;
	}
	else
	{
		gradeArray[frmCount-1]  = 0;
	}
	markedArray[frmCount-1] = 0;
	questionId[frmCount - 1] = str.substr(0, str.length - 4);
    frmCount++;
	
	if (parent.topEmpty.showCorrect) {
		document.getElementById('submitBtn').focus();
	}
}

/* function adjustSize()
{
	//alert("Adjust Size Reached");
	adjustIFrameSize(newid);
}

function adjustIFrameSize(id)
{
	//alert("adjust funtion reached");
	var myIframe = document.getElementById(id);
	if(myFrame)
	{
		if(myIframe.contentDocument && myIframe.contentDocument.body.offsetHeight)
		{
			myIframe.height = myIframe.contentDocument.body.offsetHeight;
		}
		else if(myIframe.Document && myIframe.Document.body.scrollHeight)
		{
			myIframe.height = myIframe.Document.body.scrollHeight;
		}
	}
} */

function chooseButtonType()
{
	var x = parent.topEmpty.questionDoc.getElementsByTagName("responseDeclaration")[0].getAttribute("cardinality");
	if(x == "multiple")
	{
		return "checkbox";
	}
	return "radio";
}

function createDropDown()
{
	var dropdown;
	dropdown = "<SELECT NAME=\"list\">"
	for(var i=0; i<parent.topEmpty.distractorArray.length; i++)
	{
	    dropdown += "<OPTION ";
	    if (parent.topEmpty.showCorrect)
		{
		    for (var j=0; j<parent.topEmpty.correctResponse.length; j++)
		    {	       
		        if (parent.topEmpty.keyValues[i] == parent.topEmpty.correctResponse[j])
		        {
		            dropdown += "selected ";
		        }
		    }
		}
		dropdown += markPreviousAnswerDropDown(i) + ">" + parent.topEmpty.distractorRan[i] + "</OPTION>";
	}
	dropdown = dropdown + "</SELECT>";
	return dropdown;
}

function createTextArea()
{
	var textArea = "<span style=\"z-index:4;\">";
	if(gradeArray[frmCount-1] == 1)
	{
		textArea = "<input type=\"text\" name=\"inputbox\" id=\"textinput\" value=\"" + savedAnswerArray[frmCount-1] + "\"/>";
	}
	else
	{
		textArea = "<input type=\"text\" name=\"inputbox\" id=\"textinput\" value=\"";
		
		if(parent.topEmpty.showCorrect)
		{
		    textArea += parent.topEmpty.correctResponse[0] + "\"/>";
		}
		else
		{
		    textArea += "Enter Answer Here\"  onfocus='this.value=\"\"'/>";
		}
	}
	textArea += "</span>";
	return textArea;
}

function focusTextBox(id)
{
	document.getElementById(id).focus();
}

function gradeSystem(form)
{
	//alert(parent.topEmpty.interactionType[parent.topEmpty.questionIndex-1]);
	var choose = false;
	while(choose == false)
	{
		//alert(parent.topEmpty.questionIndex);
		//alert(parent.topEmpty.interactionType[parent.topEmpty.questionIndex-1]);
		if(vistedAllQuestions)
		{
			parent.topEmpty.questionIndex++;
		}
		
		if(parent.topEmpty.interactionType[parent.topEmpty.questionIndex-1] == "choiceInteraction")
		{
			//alert(parent.topEmpty.interactionType[parent.topEmpty.questionIndex-1]);
			//alert("grade choice");
			gradeChoice(form);
			choose = true;
		}
		else if(parent.topEmpty.interactionType[parent.topEmpty.questionIndex-1] == "truefalse")
		{
			//alert(parent.topEmpty.interactionType[parent.topEmpty.questionIndex-1]);
			//alert("grade inline Drop Down");
			gradeChoice(form);
			choose = true;
		}
		else if(parent.topEmpty.interactionType[parent.topEmpty.questionIndex-1] == "inlineInteraction")
		{
			//alert(parent.topEmpty.interactionType[parent.topEmpty.questionIndex-1]);
			//alert("grade inline Drop Down");
			gradeInline(form);
			choose = true;
		}
		else if(parent.topEmpty.interactionType[parent.topEmpty.questionIndex-1] == "textEntryInteraction")
		{
			//alert("Grade In Line Fill In The Blank");
			choose=true;
			gradeText(form);
		}
		else
		{
			alert("grading not supported");
			parent.topEmpty.isGoodToGo = true;
			choose = true;
		}
	}
}

function testGCR()
{
	var count = 0;
	var x = parent.topEmpty.questionDoc.getElementsByTagName("correctResponse")[0].childNodes;
	//alert(parent.topEmpty.questionDoc.getElementsByTagName("correctResponse")[0].childNodes[0].nodeValue);
	var y = parent.topEmpty.questionDoc.getElementsByTagName("correctResponse");
	
	for(var i=0; i < x.length; i++) {
		
		//alert(y[i].getElementsByTagName('value')[i].firstChild.nodeValue);
		
		parent.topEmpty.correctResponse[count] = x[i].childNodes[0].nodeValue;
		//parent.topEmpty.correctResponse[count] = x[i].getElementsByTagName('value')[i].firstChild.nodeValue;
		count++;
	}

	/*while(y != undefined)
	{
			alert(y.childNodes[0].nodeValue);
		parent.topEmpty.correctResponse[count] = y.childNodes[0].nodeValue;
		//alert(parent.topEmpty.correctResponse[count]);
		count++;
		y=y.nextSibling;
	}
	*/
	parent.topEmpty.possibleGrade = parent.topEmpty.possibleGrade + parent.topEmpty.correctResponse.length;
}

var correctLMSAnswer = new Array();
var selectdLMSAnswer = new Array();
function getCorrectResponse()
{
	var sub;
	var tempText;
	var count=parent.topEmpty.correctResponse.length;
	for(var i=0; i<count; i++)
	{
		if(sub==undefined)
		{
			sub = parent.topEmpty.correctResponse[i]+"<br />";
			tempText = parent.topEmpty.correctResponse[i];
		}
		else
		{
			sub=sub+parent.topEmpty.correctResponse[i]+"<br />";
			tempText = tempText + "[,]" + parent.topEmpty.correctResponse[i];
		}
	}
	correctLMSAnswer[frmCount] = tempText;
	modifyCorrectAnswer(frmCount);
	//alert(correctLMSAnswer[frmCount]);
	return sub;
}

// For debug mode: Returns the value(s), not the key, of the correct response(s).
function getCorrectResponseValue()
{
    var ret;
	var count=parent.topEmpty.correctResponse.length;
	
	if(parent.topEmpty.interactionType[frmCount-1] == "textEntryInteraction") 
	{
	    return parent.topEmpty.correctResponse[0];
	}
	else 
	{
	    ret = "";
	    var valArr = new Array();
	    for(var i=0; i<count; i++) 
	    {
	        for(var j=0; j<parent.topEmpty.distractorArray.length; j++)
	        {
	            if (parent.topEmpty.correctResponse[i] == parent.topEmpty.distractorArray[j].getAttribute("identifier")) 
                {
                    valArr.push(parent.topEmpty.distractorArray[j].childNodes[0].nodeValue);
                }
	        } 
	    }
	    if (valArr.length > 1) 
	    {	   
	        for(var i=0; i<valArr.length; i++) 
	        {
	            ret += "<div style=\"padding-left:5px;padding-top:3px;\">&#8226;&nbsp;";
                ret += valArr[i];
                ret += "</div>";
            }
        }
        else 
        {
            return valArr[0];
        }
	}
	return ret;
}

function writeCheck()
{
	//var check = "<font size=\"5\" color=\"green\" face=\"wingdings\">&#254;</font>";
	var check = "<img src='../../includes/HTML/green_checkmark.png' alt='Green checkmark passed' title='Green checkmark passed' />";
	return check;
}

function writeX()
{
	//var x = "<font size=\"5\" color=\"red\" face=\"wingdings\">&#253;</font>";
	x = "<img src='../../includes/HTML/red-x.png' alt='Red X Failed' title='Red X Failed' />";
	return x;
}

function choiceXCheck(i)
{
	var x;
	if(savedCorrectArray[i] == "correct")
	{
		x = writeCheck();
	}
	else
	{
		x = writeX();
	}
	return x;
}

function displayRslts()
{
	if(parent.topEmpty.display508 == "true")
	{
		displayResult508();
	}
	else
	{
		displayResultStandard();
	}
}

function displayResultStandard()
{
	document.getElementById("choiceSpace").innerHTML   ="";
	document.getElementById("buttonSpace").innerHTML   ="";
	document.getElementById("correct").innerHTML = "";
	document.getElementById("questionID").innerHTML = "";
	
	document.getElementById("senarioPicture").style.visibility = 'hidden';
	document.getElementById("senarioSpace").innerHTML = "";
	//alert("display standard");
	var responseText;
	responseText = "<center><table border=\"1\" cellpadding=\"2\">";
	for(var i=0; i<parent.topEmpty.linkArray.length; i++)
	{
		responseText = responseText + "<tr><td>" + choiceXCheck(i) + "<td>Question " + (i +1) + "</td><td>" + savedCorrectArray[i] + "</td></tr>";
	}	
	responseText = responseText + "</table></center>";
	document.getElementById("questionSpace").innerHTML=responseText;
	// Show next button
	//document.getElementById("a1").style.visibility = 'visible';
}	

function displayResult508()
{
	alert("display 508");
}

function getSettings()
{
    parent.topEmpty.showCorrect = parent.topEmpty.globalDoc.getElementsByTagName("showCorrect")[0].childNodes[0].nodeValue == "true";
    parent.topEmpty.showIDs = parent.topEmpty.globalDoc.getElementsByTagName("showUniqueIDs")[0].childNodes[0].nodeValue == "true";  
	parent.topEmpty.displayResults = parent.topEmpty.globalDoc.getElementsByTagName("displayResults")[0].childNodes[0].nodeValue;  
	parent.topEmpty.display508 = parent.topEmpty.globalDoc.getElementsByTagName("custom508")[0].childNodes[0].nodeValue;      
	parent.topEmpty.displayStandard = parent.topEmpty.globalDoc.getElementsByTagName("displayStandard")[0].childNodes[0].nodeValue;
}

function resetTestVars()
{
	//alert("function called");
	testBank                        = null;               
	parent.topEmpty.manifestDoc     = null;
	parent.topEmpty.questionDoc     = null;
	parent.topEmpty.progressDoc     = null;
	parent.topEmpty.globalDoc  	    = null;
	parent.topEmpty.displayResults  = false;
	parent.topEmpty.display508      = false;
	parent.topEmpty.displayStandard = false;
	parent.topEmpty.showCorrect     = "false";
	parent.topEmpty.showIDs   		= "false";
	parent.topEmpty.beginning       = true; 
	parent.topEmpty.written 		= false;
	parent.topEmpty.isGoodToGo      = false;
	passingGrade = 0;
	attemptAbsoluteDurationLimit    = "";
	parent.topEmpty.questionIndex   = 0; 
	parent.topEmpty.testLength	    = 0;
	parent.topEmpty.totalGrade      = 0;
	parent.topEmpty.possibleGrade   = 0;
	correctLMSAnswer                = new Array();
	tbResource                      = new Array();
	parent.topEmpty.correctResponse = new Array();
	parent.topEmpty.orgquestionList = new Array();
	parent.topEmpty.randomList      = new Array();
	parent.topEmpty.linkArray       = new Array();
	parent.topEmpty.distractorArray = new Array();
	parent.topEmpty.distractorRan   = new Array();
	parent.topEmpty.keyValues       = new Array();
	parent.topEmpty.interactionType = new Array();
	parent.topEmpty.mapValue	    = new Array();
}

//Anything Below these lines is used for test bank functionality
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
var tbObjectiveDoc;
var testBank;
var tCorrect        = 0;
var linkCount       = 0;
var passingGrade    = 0;
var startProgDoc = 0;
var attemptAbsoluteDurationLimit = "";
var score           = 0;
var insertPicked    = 0;
var tbResource      = new Array();
var questionQuanity = new Array();
var randomQuestions = new Array();
var pickedQuestions = new Array(); 
var tempLinkArray   = new Array(); 
var totalQuestions  = new Array();
var choosenQuestion = new Array();
var objectives      = new Array();
var pickedQ         = new Array();

function runTestBank()
{
	//alert("Test Bank Run Mode");
    getPassingGrade();
	getTBResourceLinks();
	getObjectives();
	getQuestionQuanity();
	getPickedQuestions();
	getPickedList();
	getRandomQuestions();
	generateLinkArrayTB();
	addLink();
	nextQuestion();
}

function isTestBank()
{
	testBank = parent.topEmpty.manifestDoc.getElementsByTagName("testBank")[0].childNodes[0].nodeValue;  
	//alert("Is a TestBank: " + testBank);
	//alert("If you are prepared to take the exam please hit OK to continue");
}

function getPassingGrade()
{
	passingGrade = parent.topEmpty.manifestDoc.getElementsByTagName("passingGrade")[0].childNodes[0].nodeValue;  
	//alert(passingGrade);
}

function getAttemptAbsoluteDurationLimit() {
    return parent.topEmpty.manifestDoc.getElementsByTagName("attemptAbsoluteDurationLimit")[0].childNodes[0].nodeValue;
    //alert(attemptAbsoluteDurationLimit);
}

function getTBResourceLinks()
{
	tbResource = parent.topEmpty.manifestDoc.getElementsByTagName("manifest");
	for(var i=0; i<tbResource.length; i++)
	{
		//alert(tbResource[i].childNodes[0].nodeValue); 
	}
}

function getQuestionQuanity()
{
	questionQuanity = parent.topEmpty.manifestDoc.getElementsByTagName("questionQuanity");
	for(var i=0; i<questionQuanity.length; i++)
	{
		//alert(questionQuanity[i].childNodes[0].nodeValue); 
	}
}

function getPickedQuestions()
{
	pickedQuestions = parent.topEmpty.manifestDoc.getElementsByTagName("pickedQuestions");
}

function getRandomQuestions()
{
	randomQuestions = parent.topEmpty.manifestDoc.getElementsByTagName("randomQuestions");
}

function getPickedList()
{
	pickedQ = parent.topEmpty.manifestDoc.getElementsByTagName("pickedQ");
}

function getObjectives()
{
	objectives = parent.topEmpty.manifestDoc.getElementsByTagName("objective");
}

function initObjectManifest(file)
{
	tbObjectiveDoc = loadTestXML(file);
	//alert("loading " + file);
}

function generateLinkArrayTB()
{
	for(var i=0; i<tbResource.length; i++)
	{
		var leftOff=0;
		choosenQuestion = new Array();
		initObjectManifest(tbResource[i].childNodes[0].nodeValue);
		totalQuestions = tbObjectiveDoc.getElementsByTagName("resource");
		
		//alert(pickedQuestions[i].childNodes[0].nodeValue);
		if(pickedQuestions[i].childNodes[0].nodeValue >= 1)
		{
			//alert("will pick specific questions");
			for(var z = 0; z<pickedQuestions[i].childNodes[0].nodeValue; z++)
			{
				parent.topEmpty.linkArray[linkCount] = parent.topEmpty.manifestDoc.getElementsByTagName("page")[i].childNodes[0].nodeValue + pickedQ[insertPicked].childNodes[0].nodeValue + ".xml";
				//alert(parent.topEmpty.linkArray[linkCount]);
				for(var h=0; h<totalQuestions.length; h++)
				{
					//alert((pickedQ[insertPicked].childNodes[0].nodeValue+".xml"));
					//alert(tbObjectiveDoc.getElementsByTagName("resource")[h].getAttribute("href"));
					if((pickedQ[insertPicked].childNodes[0].nodeValue+".xml") == tbObjectiveDoc.getElementsByTagName("resource")[h].getAttribute("href"))
					{
						try {
							parent.topEmpty.interactionType[linkCount] = tbObjectiveDoc.getElementsByTagName("imsqti:interactionType")[h].childNodes[0].nodeValue;
						} catch(err) {
							parent.topEmpty.interactionType[linkCount] = tbObjectiveDoc.getElementsByTagName("interactionType")[h].childNodes[0].nodeValue;
						}
						//alert("choosen pushed");
						choosenQuestion[z] = h;
						leftOff++;
					}
				}
				linkCount++;
				insertPicked++;
			}
		}
	
		if(randomQuestions[i].childNodes[0].nodeValue > 0)
		{
			for(var g=0; g<randomQuestions[i].childNodes[0].nodeValue; g++)
			{
				//alert("Total Questions: " + totalQuestions.length);
				var push = Math.floor(Math.random()*totalQuestions.length);
				var gtg2 = false;
				while(gtg2 == false)
				{
					if(notChoosen(push) == true)
					{
						//alert("Value used in random question generation: " + push);
						//alert(notChoosen(push));
						parent.topEmpty.linkArray[linkCount] = parent.topEmpty.manifestDoc.getElementsByTagName("page")[i].childNodes[0].nodeValue+tbObjectiveDoc.getElementsByTagName("resource")[push].getAttribute("href");						
						
						try {
						parent.topEmpty.interactionType[linkCount] = tbObjectiveDoc.getElementsByTagName("imsqti:interactionType")[push].childNodes[0].nodeValue;
						} catch(err) {
						parent.topEmpty.interactionType[linkCount] = tbObjectiveDoc.getElementsByTagName("interactionType")[push].childNodes[0].nodeValue;
						}
						
						//alert(parent.topEmpty.linkArray[linkCount] + " " + parent.topEmpty.interactionType[linkCount]);
						choosenQuestion[(g + leftOff)] = push;
						linkCount++;
						gtg2 = true;
					}
					else
					{
						push = Math.floor(Math.random()*totalQuestions.length);
						//alert("Attempting random again");
					}
				}
			}
		}
		else
		{
			//alert("There are no random Questions in this exam");
		}
	}
	//parent.topEmpty.linkArray = tempLinkArray;
}

function notChoosen(num)
{
	var truth = true;
	
	if(choosenQuestion.length == 0)
	{
		//alert("Returning true from first part of loop");
		truth = true;
	}
	else
	{
		//alert("entering second loop check");
		for(var i=0; i<choosenQuestion.length; i++)
		{
			//alert("the comparision number :" + num + " The array value: " + choosenQuestion[i]);
			if(num == choosenQuestion[i])
			{
				truth = false;
			}
		}
	}
	//alert(truth);
	return truth;
}

function displayTestBankResults()
{
    //alert(checkAllGraded());
    if (timedTest) {
        clearTimeout(testTimer);
        document.getElementById("countDown").innerHTML = "";
    }

	if(checkAllGraded())
	{
		document.getElementById("senarioPicture").style.visibility = 'hidden';
		document.getElementById("senarioSpace").innerHTML  ="";
		document.getElementById("questionSpace").innerHTML ="";
		document.getElementById("choiceSpace").innerHTML   ="";
		document.getElementById("buttonSpace").innerHTML   ="";
		//alert("thank you for taking the exam");
		//alert("Out of :" + linkCount + " You correctly answered: " + parent.topEmpty.totalGrade);
	
		var responseText;
		responseText = "<table border=\"1\" cellpadding=\"2\">";
		responseText = responseText + "<tr><td><center><b> Objective </b></center></td><td><center><b>Number Correct</b></center></td></tr>";
		for(var i=0; i<objectives.length; i++)
		{
			responseText = responseText + "<tr><td>" + objectives[i].childNodes[0].nodeValue + "</td><td><center>" + numCorrect(i) + " / " + numQuestion(i) + "</center></td></tr>";
		}
		responseText = responseText + "<tr><td class=\"testText\" style=\"text-align:right;\"><b> Test Complete <b></td><td> " + testComplete() + " " + Math.round(score) +" / 100 </td></tr>";
		responseText = responseText + "</table>";
		
		// Add instructions telling user to close the window when they're done
		responseText = responseText + "<div style=\"padding-top:5px;\"><br />Close the window when you've finished reviewing these results.</div>"
		
		document.getElementById("testFeedBack").innerHTML=responseText;
		document.getElementById("testFeedBack").style.visibility = 'visible';
	}
	else
	{
		alert("Please answer all questions before proceeding");
	}
}

function numCorrect(num)
{
	var correct=0;
	var questions;
	questions = questionQuanity[num].childNodes[0].nodeValue;
	for(var g=0; g<questions; g++)
	{
		if(savedCorrectArray[startProgDoc] == "correct")
		{
			correct++;
			startProgDoc++;
			tCorrect++;
		}
		else
		{
			startProgDoc++;
		}
	}
	return correct;
}

function numQuestion(num)
{
	var total;
	total = questionQuanity[num].childNodes[0].nodeValue;
	return total;
}

function getTotalQuestions() {

    xmlQuestionQuantity = parent.topEmpty.manifestDoc.getElementsByTagName("questionQuanity");
    totalQuestions = 0;

    for (var i = 0; i < xmlQuestionQuantity.length; i++) {
        totalQuestions += parseInt(xmlQuestionQuantity[i].childNodes[0].nodeValue); 
    }
    //alert(totalQuestions)
    return totalQuestions;
}

function testComplete()
{
	var display;
	//alert(tCorrect)
	//alert((maxQuestions-1));
	if (timedTest) {
	    score = Math.round(((tCorrect / getTotalQuestions()) * 100));	    
	} else {
		score = Math.round(((tCorrect / (maxQuestions-1))*100));
	}
	//Math.round(score);
	//alert(score);
	if(score >= passingGrade)
	{
		submitLMS("passed",score);		
		display = writeCheck();
	}
	else
	{    
		submitLMS("failed",score);
		display = writeX();
	}
	return display;
}

function submitLMS(passFail,LMSScore)
{
	try
	{
		//alert("We will be attempting submitting to the LMS now");
		//printProgressXML();
		if(SCORM_Version != "none")
		{			
			if (SCORM_Version == "2004") {
				window.parent.topEmpty.doSetStatus("completed");
				window.parent.topEmpty.doSetValue( "cmi.score.scaled", LMSScore/100 );
				window.parent.topEmpty.doSetValue( "cmi.score.raw", LMSScore );	        
				window.parent.topEmpty.doSetValue( "cmi.success_status", passFail );
			} else if (SCORM_Version == "1.2") {
				window.parent.topEmpty.LMSSetValue("cmi.core.score.raw", LMSScore);
				window.parent.topEmpty.LMSSetValue("cmi.core.lesson_status", passFail);
			}
	        
			for(var i = 0; i<maxQuestions-1; i++)
			{
				if (SCORM_Version == "2004") {
				    window.parent.topEmpty.doSetValue("cmi.interactions." + i + ".id", "Q-" + (i+1) + "-" + questionId[i]);							
					//window.parent.topEmpty.doSetValue("cmi.interactions." + i + ".type", submitInteractionType(i));
					window.parent.topEmpty.doSetValue("cmi.interactions." + i + ".type", "choice");				
					window.parent.topEmpty.doSetValue("cmi.interactions." + i + ".correct_responses.0.pattern", correctLMSAnswer[i+1]);				
					window.parent.topEmpty.doSetValue("cmi.interactions." + i + ".learner_response", selectdLMSAnswer[i+1]);				
					window.parent.topEmpty.doSetValue("cmi.interactions." + i + ".result", getProDocResponse(i));
				} else if (SCORM_Version == "1.2") {
					window.parent.topEmpty.LMSSetValue("cmi.interactions." + i + ".type", "choice");
					window.parent.topEmpty.LMSSetValue("cmi.interactions." + i + ".correct_responses.0.pattern", correctLMSAnswer[i+1]);
					window.parent.topEmpty.LMSSetValue("cmi.interactions." + i + ".student_response",selectdLMSAnswer[i+1]);
					window.parent.topEmpty.LMSSetValue("cmi.interactions." + i + ".result", getProDocResponse(i));
				}
				
			}
		}
		else
		{
			//alert("API Not Initialized");
		}
	}
	catch(err)
	{
		//alert("sorry did not work");
	}
}

function getProgressDocLength()
{
	return maxQuestions;
}

function getProDocResponse(num)
{
	return savedCorrectArray[num];
}

function submitInteractionType(num)
{
	var interaction;
	//alert("Interaction Type is: " + parent.topEmpty.interactionType[num]);
	if(parent.topEmpty.interactionType[num] == "choiceInteraction")
	{
		interaction = "multiple_choice";
		return interaction;
	}
	else if(parent.topEmpty.interactionType[num] == "truefalse")
	{
		interaction = "true-false";
		return interaction;
	}
	else if(parent.topEmpty.interactionType[num] == "inlineInteraction")
	{
		interaction = "multiple_choice";
		return interaction;
	}
	else if(parent.topEmpty.interactionType[num] == "textEntryInteraction")
	{
		interaction = "fill_in";
		return interaction;
	}
	else
	{
		//alert("Interaction Type Not Supported");
	}
}

function modifyCorrectAnswer(num)
{
	//alert(parent.topEmpty.interactionType[num-1]);
	if(parent.topEmpty.interactionType[num-1] != "textEntryInteraction")
	{
		var answerText = correctLMSAnswer[num];
		//alert("This is your text for modification: " + answerText);
		answerText = answerText.replace(/a/i, "1");
		answerText = answerText.replace(/b/i, "2");
		answerText = answerText.replace(/c/i, "3");
		answerText = answerText.replace(/d/i, "4");
		answerText = answerText.replace(/e/i, "5");
		answerText = answerText.replace(/f/i, "6");
		answerText = answerText.replace(/g/i, "7");
		answerText = answerText.replace(/h/i, "8");
		correctLMSAnswer[num] = answerText;
	}
	else if(parent.topEmpty.interactionType[num-1] == "textEntryInteraction")
	{
		var answerText = correctLMSAnswer[num];
		correctLMSAnswer[num] = answerText;
		
	}
	else
	{
		alert("error on LMS submission");
	}
}

function modifySubmitedAnswer(num)
{
	var answerText = selectdLMSAnswer[num];
	//alert("This is your text for modification: " + answerText);
	answerText = answerText.replace(/a/i, "1");
	answerText = answerText.replace(/b/i, "2");
	answerText = answerText.replace(/c/i, "3");
	answerText = answerText.replace(/d/i, "4");
	answerText = answerText.replace(/e/i, "5");
	answerText = answerText.replace(/f/i, "6");
	answerText = answerText.replace(/g/i, "7");
	answerText = answerText.replace(/h/i, "8");
	selectdLMSAnswer[num] = answerText;
}

//Code Below these stars relate to displaying and manipulating images in the quiz engine and Test Bank. 
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************

function hasImage()
{
	var image;
	var srcLink;
	var height;
	var width;
	var alt;
	
	try
	{
		if(parent.topEmpty.questionDoc.getElementsByTagName("img")[0].getAttribute("src") != "")
		{
			//alert("Question has an image");
			srcLink =parent.topEmpty.questionDoc.getElementsByTagName("img")[0].getAttribute("src");
			height  =parent.topEmpty.questionDoc.getElementsByTagName("img")[0].getAttribute("height");
			width   =parent.topEmpty.questionDoc.getElementsByTagName("img")[0].getAttribute("width");
			alt     =parent.topEmpty.questionDoc.getElementsByTagName("img")[0].getAttribute("alt");
			image = "<img src=\"../../images/" + srcLink + "\" height=\"" + height + "\" width=\"" + width + "\" alt=\"" + alt +"\" />";
			//alert(image);
			document.getElementById("pictureArea").innerHTML=image;
		}
		else
		{
			//alert("Question has no associated image");
			document.getElementById("pictureArea").innerHTML="";
		}
	}
	catch(err)
	{
		//alert("Error Description: " + err.description);
	}
}

//Code Below these stars relate to enabling or disabling special key strokes
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************

function disableKeysInit()
{
	var inputs = document.getElementsByTagName("input"); 
	
	// Search all our input fields.... 
	for( var t = 0; t < tags.length; t++) { 
		var tag = tags[t];

		var nodeName = tag.nodeName.toLowerCase(); 
		var type = tag.type.toLowerCase(); 
		
		// Check it's input text, or SELECT
		if ( (nodeName == "input" && type == "text") ||
			 (nodeName == "select")) { 
			addEvent( tag, "focus", pkDisable);
			addEvent( tag, "blur", pkEnable);
		} 
	}
	addEvent(document, "keydown", keyPressed); 
	document._pkEnabled = true; 
}
function pkDisable(e) { 
	document._pkEnabled = false; 
}

function pkEnable(e) { 
	document._pkEnabled = true; 
}

function addEvent(elm, evType, fn, useCapture) 
{ 
	//Credit: Function written by Scott Andrews 
	//(slightly modified) 
	var ret = 0;

	if (elm.addEventListener) 
		ret = elm.addEventListener(evType, fn, useCapture); 
	else if (elm.attachEvent) 
		ret = elm.attachEvent('on' + evType, fn); 
	else 
		elm['on' + evType] = fn;
	return ret; 
}

function kH(e) 
{
	var pK = e ? e.which : window.event.keyCode;
	return (pK != 13);
}
function backspace_kH(e) 
{
	var pK = e ? e.which : window.event.keyCode;
	return !(pK == 8 && event.srcElement.type != 'text');
}
document.onkeypress = kH;
document.onkeydown = backspace_kH;

if (document.layers) 
{
	document.captureEvents(Event.KEYDOWN);
	document.captureEvents(Event.KEYPRESS);
}

//Code Below these stars relates to either incorporating a senario or not incorporation a senario
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************

var scenarioDoc;

function hasSenario()
{
	var scenario;
	var srcLink;
	
	document.getElementById("senarioPicture").style.visibility = 'hidden';
	document.getElementById("senarioSpace").innerHTML = "";
	//document.getElementById("questionSpace").style.width = '600px';
	//document.getElementById("choiceSpace").style.width = '600px';
	
	try
	{
		if(parent.topEmpty.questionDoc.getElementsByTagName("scenario")[0].getAttribute("src") != "")
		{
			srcLink =parent.topEmpty.questionDoc.getElementsByTagName("scenario")[0].getAttribute("src");
			initScenarioDoc(srcLink);
			scenario = scenarioDoc.getElementsByTagName("scenario")[0].childNodes[0].nodeValue;
			//alert("The Scenario is: " + scenario);
			document.getElementById("questionSpace").style.width = '350px';
			document.getElementById("choiceSpace").style.width = '350px';
			document.getElementById("senarioSpace").innerHTML ="<h4>Scenario:</h4>" + scenario;
			document.getElementById("senarioSpace").style.visibility = 'visible';
			document.getElementById("senarioPicture").style.visibility = 'visible';
		}
		else
		{
			//alert("Question has no associated image");
			//document.getElementById("pictureArea").innerHTML="";
		}
	}
	catch(err)
	{
		//alert("Error Description: " + err.description);
	}
}

function initScenarioDoc(file)
{
	scenarioDoc =loadTestXML(file);
	//alert("Progress xmlDoc is loaded, ready for use!");
}

//Code Below these stars is used to run a review section that could be implemented at the end of an exam. before the final submission. 
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
//******************************************************************************************************************************************
var reviewLinkArray    = new Array();
var answeredIndex      = new Array(); 
var gradeArray         = new Array(); 
var markedArray        = new Array();
var savedOrderArray    = new Array();
var savedAnswerArray   = new Array(); 
var savedKeyArray      = new Array();
var savedCorrectArray  = new Array();
var vistedAllQuestions = false;
var allquestionsGraded = false;
var maxQuestions       = 0;

function runReview()
{
	var review;
	
	try {
		if (parent.topEmpty.globalDoc.getElementsByTagName("displayReview")[0].childNodes[0].nodeValue) {
			review = parent.topEmpty.globalDoc.getElementsByTagName("displayReview")[0].childNodes[0].nodeValue;
		} else {
			review = false;
		}
	} catch(e) {
		review = false;
	}
	
	if(review == "true")
	{
		return true;
	}
	return false;
}

function reviewQuestions()
{
	vistedAllQuestions = true;
	document.getElementById("correct").innerHTML = "";
	document.getElementById("questionID").innerHTML = "";
	document.getElementById("senarioPicture").style.visibility = 'hidden';
	document.getElementById("senarioSpace").innerHTML = "";
	document.getElementById("questionSpace").innerHTML ="";
	document.getElementById("choiceSpace").innerHTML   ="";
	document.getElementById("buttonSpace").innerHTML   ="";
	document.getElementById("choiceSpace").style.width = '90%';
	
	//alert("Reviewing Questions");
	var count      = 0;
	var innerCount = 0;
	var reviewText = "";
	var reviewMessage = "";
		
	if (parent.topEmpty.manifestDoc.getElementsByTagName("reviewMessage")[0].childNodes[0] != null)
	{
		reviewMessage = parent.topEmpty.manifestDoc.getElementsByTagName("reviewMessage")[0].childNodes[0].nodeValue;
		reviewText = "<div style=\"padding-bottom:5px;\">" + reviewMessage + "<br /><br /></div>";
	}
	
	reviewText = reviewText + "<div style=\"height:350px;width:100%; overflow:auto;\"><table border=\"1\" cellpadding=\"6\">";
	
	for(var i=0; i<markedArray.length; i++)
	{
		//alert("inner loop reached");
		count = i;
		if(innerCount == 0)
		{
			reviewText = reviewText + "<tr>";
		}
		if(innerCount < 2)
		{
			//alert("less then three");
			//reviewText = reviewText + "<td><a href=\"javascript:gotoQuestion(" +count+");\">Question" + (count+1) + "</a></td><td>" + markStatusIs(count) + ", " + gradeStatusIs(count) +", " + isAnsweredCorrect(count) + " </td>";
			reviewText = reviewText + "<td><a href=\"javascript:gotoQuestion(" +count+");\">Question" + (count+1) + "</a></td><td>" + markStatusIs(count) + ", " + gradeStatusIs(count) +" </td>";
			innerCount++;
		}
		else
		{
			//alert("starting new row");
			//reviewText = reviewText + "<td><a href=\"javascript:gotoQuestion(" +count+");\">Question" + (count+1) + "</a></td><td>" + markStatusIs(count) + ", " + gradeStatusIs(count) +", " + isAnsweredCorrect(count) + " </td>";
			reviewText = reviewText + "<td><a href=\"javascript:gotoQuestion(" +count+");\">Question" + (count+1) + "</a></td><td>" + markStatusIs(count) + ", " + gradeStatusIs(count) +" </td>";
			reviewText = reviewText + "</tr>";
			innerCount = 0;
		}
	}
	reviewText = reviewText + "</table></div>";
	var buttonText = "<input type=\"button\" value=\"Submit and display results!\" onclick=\"displayTestBankResults()\"><br />";
	document.getElementById("choiceSpace").innerHTML = reviewText;
	document.getElementById("buttonSpace").innerHTML   = buttonText;
}

function gotoQuestion(num)
{
	frmCount = (num+1);
	parent.topEmpty.questionIndex = num;
	//alert(frmCount);
	nextQuestion();
}

function checkAllGraded()
{	
	if (timedTest) {
		allquestionsGraded = true;
		return allquestionsGraded;
	} else {
		for(var i=0; i<gradeArray.length; i++)
		{
			if(gradeArray[i] == 0)
			{
				return allquestionsGraded;
			}
		}
		allquestionsGraded = true;
		return allquestionsGraded;
	}
}

function markQuestion()
{
	if(gradeArray[frmCount-2] == 0)
	{
		savedCorrectArray[frmCount-2] = "unanswered";
	}
	markedArray[frmCount-2] = 1;
	nullify();
	parent.topEmpty.isGoodToGo = true;
	//alert(markedArray[num] + " " + parent.topEmpty.isGoodToGo);
	if(vistedAllQuestions == false)
	{
		nextQuestion();
	}
	else
	{
		reviewQuestions();
	}
}

function markStatusIs(num)
{
	if(markedArray[num] == 1)
	{
		return "Marked";
	}
	return "Answered";
}

function gradeStatusIs(num)
{
	if(gradeArray[num] == 1)
	{
		return "Graded";
	}
	return "unGraded";
}

function markPreviousAnswerChoice(num)
{
	if(gradeArray[frmCount-1] == 1)
	{
		var toMarkArray = new Array();
		toMarkArray = savedAnswerArray[frmCount-1];
		for(var i=0; i<toMarkArray.length; i++)
		{
			if(toMarkArray[i] == num)
			{
				return "checked";
			}
		}
	}
	else			
	{
		return "";
	}
}

function markPreviousAnswerDropDown(num)
{
	if(gradeArray[frmCount-1] == 1)
	{
		if(savedAnswerArray[frmCount-1] == num)
		{
			return "selected";
		}
	}
}

var maxTimeAllowed;
var timeAction;
var testStartTime;

function convertToMilliseconds(time) {
	arTime = new Array();
	arTime = time.split(":");
	// arTime[0] contains hours, 
	// arTime[1] contains minutes
	// arTime[2] contains seconds

	var milliseconds = ( (parseInt(arTime[0])*60*60) + (parseInt(arTime[1])*60) + parseInt(arTime[2]) ) *1000;

	return milliseconds;
}

function checkTimedTest() {

    if (SCORM_Version == "1.2") {
        if (typeof (parent.topEmpty.LMSGetValue("cmi.student_data.max_time_allowed")) == "string" && parent.topEmpty.LMSGetValue("cmi.student_data.max_time_allowed") != "") {
            timedTest = true;
            startTimedTest();            
        }
    } else if (SCORM_Version == "2004") {
        if (typeof (parent.topEmpty.doGetValue("cmi.max_time_allowed")) == "string" && parent.topEmpty.doGetValue("cmi.max_time_allowed") != "") {
            timedTest = true;
            startTimedTest();
        }
    } else if (SCORM_Version == "none") {
        if (getAttemptAbsoluteDurationLimit() != "False") {
            timedTest = true;
            startTimedTest();
        }
    }
}

testTimer = "";
timeAction = "";

function startTimedTest() {

    if (SCORM_Version == "1.2") {
        // retrieving values from LMS 
        maxTimeAllowed = parent.topEmpty.LMSGetValue("cmi.student_data.max_time_allowed");
        timeAction = parent.topEmpty.LMSGetValue("cmi.student_data.time_limit_action");
    } else if (SCORM_Version == "2004") {
        maxTimeAllowed = parent.topEmpty.doGetValue("cmi.max_time_allowed");
        timeAction = parent.topEmpty.doGetValue("cmi.time_limit_action");
    } else if (SCORM_Version == "none") {
        maxTimeAllowed = getAttemptAbsoluteDurationLimit();
        timeAction = "exit,message";
    }
	  // *convert maxTimeAllowed to milliseconds
      
	var mta_ms = convertToMilliseconds(maxTimeAllowed);

	  /*Use a setTimeout JavaScript function to execute after the time has elapsed  */
	
	createTimer(mta_ms);

}

function endTimedTest(action) {
    
	switch (action) {
	     case "exit,message":
	         alert("The time allotted for this assessment has expired. Any unanswered questions will be marked as incorrect. Select OK to submit your responses.");
			if (SCORM_Version == "1.2") {
				parent.topEmpty.LMSSetValue( "cmi.core.exit", "time-out" );
			} else if (SCORM_Version == "2004") {
				parent.topEmpty.doSetValue( "cmi.exit", "time-out" );
			}
			break;
	    case "continue,message":
	        alert("The time allotted for this assessment has expired. Any unanswered questions will be marked as incorrect. Select OK to submit your responses.");
			if (SCORM_Version == "1.2") {
				parent.topEmpty.LMSSetValue("cmi.core.exit", "time-out" );
			} else if (SCORM_Version == "2004") {
				parent.topEmpty.doSetValue( "cmi.exit", "time-out" );
			}
			break;
    }

	displayTestBankResults();

}

countDownHours = 0;
countDownMinutes = 0;

function createTimer(milSeconds) {

    var newdiv = document.createElement('div');
    newdiv.setAttribute('id', 'countDown');    

    function two(x) {return ((x>9)?"":"0")+x}
    function three(x) {return ((x>99)?"":"0")+((x>9)?"":"0")+x}

    var sec = Math.floor(milSeconds / 1000)
    milSeconds = milSeconds % 1000
    t = three(milSeconds)

    var min = Math.floor(sec / 60)
    sec = sec % 60
    t = two(sec)

    var hr = Math.floor(min / 60)
    min = min % 60
    countDownMinutes = 1+parseInt(two(min))

    var day = Math.floor(hr / 60)
    hr = hr % 60
    countDownHours = two(hr)
    //t = day + ":" + t
    
    document.body.appendChild(newdiv);

    countDown();
}


function countDown() {
    countDownMinutes--;
    if (countDownMinutes == -01) {
        countDownMinutes = 59;
        countDownHours = countDownHours - 1;
    } else {
        countDownHours = countDownHours;
    }
    if (countDownMinutes <= 9) { countDownMinutes = "0" + countDownMinutes; }
    time = (countDownHours <= 9 ? countDownHours : countDownHours) + ":" + countDownMinutes;
    document.getElementById("countDown").innerHTML = "Time Remaining: " + time;
    testTimer = window.setTimeout("countDown();", 60000);
    if (countDownHours == '00' && countDownMinutes == '00') { countDownMinutes = "00"; endTimedTest(timeAction); }
}

//This method is purely used for testing purpose in creating the remediation section.  It uses an array to indicated whether or not the user
//answered the question correctly and allows me as the developer to make sure that only the correct parameters are used for grading as in 
//no out of bounds exceptions.  While it is not to be used in the final run time it is reccomended to keep this method for checking correctness
function isAnsweredCorrect(num)
{
	return savedCorrectArray[num];
}