var CourseName = '';

function StartUp(){
	RemoveBottomNavBarForIE();

//If there's only one question, no need for question navigation controls
	if (QsToShow < 2){
		document.getElementById('QNav').style.display = 'none';
	}
	

	GetUserName();

	

	
	CompleteEmptyFeedback();

	SetUpQuestions();
	ClearTextBoxes();
	CreateStatusArray();
	
//Check search string for q parameter
	if (document.location.search.length > 0){
		if (ShuffleQs == false){
			var JumpTo = parseInt(document.location.search.substring(1,document.location.search.length))-1;
			if (JumpTo <= QsToShow){
				ChangeQ(JumpTo);
			}
		}
	}
}

function ShowHideQuestions(){
	FuncBtnOut(document.getElementById('ShowMethodButton'));
	document.getElementById('ShowMethodButton').style.display = 'none';
	if (ShowingAllQuestions == false){
		for (var i=0; i<QArray.length; i++){
				QArray[i].style.display = '';
			}
		document.getElementById('Questions').style.listStyleType = 'decimal';
		document.getElementById('OneByOneReadout').style.display = 'none';
		document.getElementById('ShowMethodButton').innerHTML = ShowOneByOneCaption;
		ShowingAllQuestions = true;
	}
	else{
		for (var i=0; i<QArray.length; i++){
				if (i != CurrQNum){
					QArray[i].style.display = 'none';
				}
			}
		document.getElementById('Questions').style.listStyleType = 'none';
		document.getElementById('OneByOneReadout').style.display = '';
		document.getElementById('ShowMethodButton').innerHTML = ShowAllQuestionsCaption;
		ShowingAllQuestions = false;	
	}
	document.getElementById('ShowMethodButton').style.display = 'inline';
}

function CreateStatusArray(){
	var QNum, ANum;
//For each item in the item array
	for (QNum=0; QNum<I.length; QNum++){
//Check if the question still exists (hasn't been nuked by showing a random selection)
		if (document.getElementById('Q_' + QNum) != null){
			State[QNum] = new Array();
			State[QNum][0] = -1; //Score for this q; -1 shows question not done yet
			State[QNum][1] = new Array(); //answers
			for (ANum = 0; ANum<I[QNum][3].length; ANum++){
				State[QNum][1][ANum] = 0; //answer not chosen yet; when chosen, will store its position in the series of choices
			}
			State[QNum][2] = 0; //tries at this q so far
			State[QNum][3] = 0; //incrementing percent-correct values of selected answers
			State[QNum][4] = 0; //penalties incurred for hints
			State[QNum][5] = ''; //Sequence of answers chosen by number
		}
		else{
			State[QNum] = null;
		}
	}
}





function CheckMCAnswer(QNum, ANum, Btn){
//if question doesn't exist, bail
//	alert('Got to here 1');
	
	if (State[QNum].length < 1){return;}
	
//Get the feedback
	Feedback = I[QNum][3][ANum][1];
	
	
//Now show feedback and bail if question already complete
//	alert('Got to here 2');
//	alert('QNum='+QNum);

		if (QNum == 0) {
			CourseName = Btn.value;
// alert('CourseName='+CourseName);
		}
		
	if (State[QNum][0] > -1){
	

//Add an extra message explaining that the question
// is finished if defined by the user
		if (strQuestionFinished.length > 0){Feedback += '<br />' + strQuestionFinished;}

//Show the feedback
		ShowMessage(Feedback);
		return;
	}
	
//Hide the button while processing
	Btn.style.display = 'none';

//Increment the number of tries
	State[QNum][2]++;
	
//Add the percent-correct value of this answer
	State[QNum][3] += I[QNum][3][ANum][3];
	
//Store the try number in the answer part of the State array, for tracking purposes
	State[QNum][1][ANum] = State[QNum][2];
	State[QNum][5] += String.fromCharCode(65+ANum) + ',';
	
//Should this answer be accepted as correct?
	if (I[QNum][3][ANum][2] < 1){
//It's wrong

//Mark the answer
		Btn.innerHTML = IncorrectIndicator;
		
//Check whether this leaves just one MC answer unselected, in which case the Q is terminated
		var RemainingAnswer = FinalAnswer(QNum);
		if (RemainingAnswer > -1){
//Behave as if the last answer had been selected, but give no credit for it
//Increment the number of tries
			State[QNum][2]++;		
		
//Calculate the score for this question
			CalculateMCQuestionScore(QNum);

//Get the overall score and add it to the feedback
			CalculateOverallScore();
			if ((ContinuousScoring == true)||(Finished == true)){
				Feedback += '<br />' + YourScoreIs + ' ' + Score + '%.';
				WriteToInstructions(YourScoreIs + ' ' + Score + '%.');
			}
		}
	}
	else{
//It's right
//Mark the answer
		Btn.innerHTML = CorrectIndicator;
				
//Calculate the score for this question
		CalculateMCQuestionScore(QNum);

//Get the overall score and add it to the feedback
		if (ContinuousScoring == true){
			CalculateOverallScore();
			if ((ContinuousScoring == true)||(Finished == true)){
				Feedback += '<br />' + YourScoreIs + ' ' + Score + '%.';
				WriteToInstructions(YourScoreIs + ' ' + Score + '%.');
			}
		}
	}
	
//Show the button again
	Btn.style.display = 'inline';
	
//Finally, show the feedback	
	ShowMessage(Feedback);
	
//Check whether all questions are now done
	CheckFinished();
}

function CalculateMCQuestionScore(QNum){
	var Tries = State[QNum][2] + State[QNum][4]; //include tries and hint penalties
	var PercentCorrect = State[QNum][3];
	var TotAns = GetTotalMCAnswers(QNum);
	var HintPenalties = State[QNum][4];
	
//Make sure it's not already complete

	if (State[QNum][0] < 0){
//Allow for Hybrids
		if (HintPenalties >= 1){
			State[QNum][0] = 0;
		}
		else{
//This line calculates the score for this question
			State[QNum][0] = ((TotAns-((Tries*100)/State[QNum][3]))/(TotAns-1));
		}
		if (State[QNum][0] < 0){
			State[QNum][0] = 0;
		}
	}
}

function GetTotalMCAnswers(QNum){
	var Result = 0;
	for (var ANum=0; ANum<I[QNum][3].length; ANum++){
		if (I[QNum][3][ANum][4] == 1){ //This is an MC answer
			Result++;
		}
	}
	return Result;
}

function FinalAnswer(QNum){
	var UnchosenAnswers = 0;
	var FinalAnswer = -1;
	for (var ANum=0; ANum<I[QNum][3].length; ANum++){
		if (I[QNum][3][ANum][4] == 1){ //This is an MC answer
			if (State[QNum][1][ANum] < 1){ //This answer hasn't been chosen yet
				UnchosenAnswers++;
				FinalAnswer = ANum;
			}
		}
	}
	if (UnchosenAnswers == 1){
		return FinalAnswer;
	}
	else{
		return -1;
	}
}


function CalculateOverallScore(){
	var TotalWeighting = 0;
	var TotalScore = 0;
	
	for (var QNum=0; QNum<State.length; QNum++){
		if (State[QNum] != null){
			if (State[QNum][0] > -1){
				TotalWeighting += I[QNum][0];
				TotalScore += (I[QNum][0] * State[QNum][0]);
			}
		}
	}
	Score = Math.floor((TotalScore/TotalWeighting)*100);
}

function CheckFinished(){
	var FB = '';
	var AllDone = true;
	for (var QNum=0; QNum<State.length; QNum++){
		if (State[QNum] != null){
			if (State[QNum][0] < 0){
				AllDone = false;
			}
		}
	}
	if (AllDone == true){
	
//Report final score and submit if necessary
		CalculateOverallScore();
		FB = YourScoreIs + ' ' + Score + '%.';
		if (ShowCorrectFirstTime == true){
			var CFT = 0;
			for (QNum=0; QNum<State.length; QNum++){
				if (State[QNum] != null){
					if (State[QNum][0] >= 1){
						CFT++;
					}
				}
			}
			FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
		}
		WriteToInstructions(FB);
		
		Finished == true;

		TimeOver = true;
		Locked = true;
		

		setTimeout('SendResults(' + Score + ')', 50);


		Finished = true;
		Detail = '<?xml version="1.0"?><hpnetresult><fields>';
		for (QNum=0; QNum<State.length; QNum++){
			if (State[QNum] != null){
				if (State[QNum][5].length > 0){
					Detail += '<field><fieldname>Question #' + (QNum+1) + '</fieldname><fieldtype>question-tracking</fieldtype><fieldlabel>Q ' + (QNum+1) + '</fieldlabel><fieldlabelid>QuestionTrackingField</fieldlabelid><fielddata>' + State[QNum][5] + '</fielddata></field>';
				}
			}
		}
		Detail += '</fields></hpnetresult>';
		setTimeout('Finish()', SubmissionTimeout);
	}
}





//CORE CODE FOR CHECKING SHORT ANSWER GUESSES AGAINST ANSWER ARRAYS

var CaseSensitive = false;
var ShowAlsoCorrect = true;
var PleaseEnter = 'Please enter a guess.';
var HybridTries = 2;
var PartlyIncorrect = 'Your answer is partly wrong: ';
var CorrectList = '<br> Correct answers: ';
var NextCorrect = 'Next correct letter in the answer: ';
var CurrBox = null;

function TrackFocus(BoxID){
	InTextBox = true;
	CurrBox = document.getElementById(BoxID);
}

function LeaveGap(){
	InTextBox = false;
}

function TypeChars(Chars){
	if (CurrBox != null){
//		if (CurrBox.style.display != 'none'){
			CurrBox.value += Chars;
			CurrBox.focus();
//		}
	}
}

function CheckGuess(Guess, Answer, CaseSensitive, PercentCorrect, Feedback){
	this.Guess = Guess;
	this.Answer = Answer;
	this.PercentCorrect = PercentCorrect;
	this.Feedback = Feedback;
	if (CaseSensitive == false){
		this.WorkingGuess = Guess.toLowerCase();
		this.WorkingAnswer = Answer.toLowerCase();
	}
	else{
		this.WorkingGuess = Guess;
		this.WorkingAnswer = Answer;				
	}
	this.Hint = '';
	this.HintPenalty = 1/Answer.length;
	this.CorrectStart = '';
	this.WrongMiddle = '';
	this.CorrectEnd = '';
	this.PercentMatch = 0;
	this.DoCheck();
}

function CheckGuess_DoCheck(){
//Check if it's an exact match
	if (this.WorkingAnswer == this.WorkingGuess){
		this.PercentMatch = 100;
		this.CorrectStart = this.Guess;
	return;
	}
//Figure out how much of the beginning is correct
	var i = 0;
	var CorrectChars = 0;
	while (this.WorkingAnswer.charAt(i) == this.WorkingGuess.charAt(i)){
		i++;
		CorrectChars++;
	}
//Stash the hint
	this.Hint = this.Answer.charAt(i);
	
	this.CorrectStart = this.Guess.substring(0, i);
	
//If there's more to the answer, look at the rest of it
	if (i<this.Guess.length){
	
//Figure out how much of the end is correct
		var j = this.WorkingGuess.length-1;
		var k = this.WorkingAnswer.length-1;
		while ((j>=i)&&((this.WorkingAnswer.charAt(k) == this.WorkingGuess.charAt(j))&&(CorrectChars < this.Answer.length))){
			CorrectChars++;
			j--;
			k--;
		}
		this.CorrectEnd = this.Guess.substring(j+1, this.Guess.length);
		this.WrongMiddle = this.Guess.substring(i, j+1);
	}
	if (TrimString(this.WrongMiddle).length < 1){this.WrongMiddle = '_';}
//Calculate match score based on how much of the guess is correct
	if (CorrectChars < this.Answer.length){
		this.PercentMatch = Math.floor(100*CorrectChars)/this.Answer.length;
	}
	else{
		this.PercentMatch = Math.floor((100 * CorrectChars)/this.Guess.length);
	}	
}

CheckGuess.prototype.DoCheck = CheckGuess_DoCheck;

function CheckAnswerArray(CaseSensitive){
	this.CaseSensitive = CaseSensitive;
	this.Answers = new Array();
	this.Score = 0;
	this.Feedback = '';
	this.Hint = '';
	this.HintPenalty = 0;
	this.MatchedAnswerLength = 1;
	this.CompleteMatch = false;
	this.MatchNum = -1;
}

function CheckAnswerArray_AddAnswer(Guess, Answer, PercentCorrect, Feedback){
	this.Answers.push(new CheckGuess(Guess, Answer, this.CaseSensitive, PercentCorrect, Feedback));
}

CheckAnswerArray.prototype.AddAnswer = CheckAnswerArray_AddAnswer;

function CheckAnswerArray_ClearAll(){
	this.Answers.length = 0;
}

CheckAnswerArray.prototype.ClearAll = CheckAnswerArray_ClearAll;

function CheckAnswerArray_GetBestMatch(){
//First check for a 100% match
	for (var i=0; i<this.Answers.length; i++){
		if (this.Answers[i].PercentMatch == 100){
			this.Feedback = this.Answers[i].Feedback;
			this.Score = this.Answers[i].PercentCorrect;
			this.CompleteMatch = true;
			this.MatchNum = i;
			return;
		}
	}
//Now check for the best alternative match
	var PercentMatch = 0;
	var BestMatch = -1;
	for (i=0; i<this.Answers.length; i++){
		if ((this.Answers[i].PercentMatch > PercentMatch)&&(this.Answers[i].PercentCorrect == 100)){
			BestMatch = i;
			PercentMatch = this.Answers[i].PercentMatch;
		}
	}
	if (BestMatch > -1){
		this.Score = this.Answers[BestMatch].PercentMatch;
		this.Feedback = PartlyIncorrect + ' ';
		this.Feedback += '<span class="Answer">' + this.Answers[BestMatch].CorrectStart;
		this.Feedback += '<span class="Highlight">' + this.Answers[BestMatch].WrongMiddle + '</span>';
		this.Feedback += this.Answers[BestMatch].CorrectEnd + '</span>';
		this.Hint = '<span class="Answer">' + this.Answers[BestMatch].CorrectStart;
		this.Hint += '<span class="Highlight">' + this.Answers[BestMatch].Hint + '</span></span>';
		this.HintPenalty = this.Answers[BestMatch].HintPenalty;
	}
	else{
		this.Score = 0;
		this.Feedback = '';
	}
}

CheckAnswerArray.prototype.GetBestMatch = CheckAnswerArray_GetBestMatch;

function CheckShortAnswer(QNum){
//bail if question doesn't exist or exercise finished
	if ((State[QNum].length < 1)||(Finished == true)){return;}
	
//bail if question already complete
	if (State[QNum][0] > -1){return;}

//Get the guess
	var G = document.getElementById('Q_' + QNum + '_Guess').value;
	
//If no guess, bail with message; no penalty
	if (G.length < 1){
		ShowMessage(PleaseEnter);
		return;
	}

//Increment tries
	State[QNum][2]++;
	
//Create a check object
	var CA = new CheckAnswerArray(CaseSensitive);

	CA.ClearAll();
	for (var ANum=0; ANum<I[QNum][3].length; ANum++){
		CA.AddAnswer(G, I[QNum][3][ANum][0], I[QNum][3][ANum][3], I[QNum][3][ANum][1]);
	}
	CA.GetBestMatch();
	
//Store any match in the state tracking field
	if (CA.MatchNum > -1){
		State[QNum][5] += String.fromCharCode(65+CA.MatchNum) + ',';
	}

//Add the percent correct value for this answer to the Q State (works for all
//situations, wrong or right
	State[QNum][3] += CA.Score;
	
//Now branch, based on the nature of the match
//Is it a complete match?
	if (CA.CompleteMatch == true){
		
//Is it with a wrong answer, or a right answer?
		if (CA.Score == 100){
//It's right
			CalculateShortAnsQuestionScore(QNum);
//Get correct answer list if required, assuming there are any other correct alternatives
			if (ShowAlsoCorrect == true){
				var AlsoCorrectList = GetCorrectList(QNum, G, false);
				if (AlsoCorrectList.length > 0){
					CA.Feedback += '<br />' + CorrectList + '<br />' +  '<span class="Answer">' + AlsoCorrectList + '</span>';
				}
			}	
		
//Get the overall score and add it to the feedback
			if (ContinuousScoring == true){
				CalculateOverallScore();
				CA.Feedback += '<br />' + YourScoreIs + ' ' + Score + '%.';
				WriteToInstructions(YourScoreIs + ' ' + Score + '%.');
			}
			ShowMessage(CA.Feedback);
//Put the answer in
			ReplaceGuessBox(QNum, G);
			CheckFinished();
			return;
		}
	}
	
//Otherwise, it's a match to a predicted wrong/partially correct, or a partial
//match to a right answer
	if (CA.Feedback.length < 1){CA.Feedback = DefaultWrong;} 
	ShowMessage(CA.Feedback);

//If necessary, switch a hybrid question to m/c
	if (State[QNum][2] >= HybridTries){
		SwitchHybridDisplay(QNum);
	}
}

function CalculateShortAnsQuestionScore(QNum){
	var Tries = State[QNum][2] + State[QNum][4]; //include tries and hint penalties;
	var PercentCorrect = State[QNum][3];
	var HintPenalties = State[QNum][4];

//Make sure it's not already complete
	if (State[QNum][0] < 0){
		if (HintPenalties >= 1){
			State[QNum][0] = 0;
		}
		else{
			State[QNum][0] = (PercentCorrect/(100*Tries));
		}
		if (State[QNum][0] < 0){
			State[QNum][0] = 0;
		}
	}
}

function SwitchHybridDisplay(QNum){
	if (document.getElementById('Q_' + QNum + '_Hybrid_MC') != null){
		document.getElementById('Q_' + QNum + '_Hybrid_MC').style.display = '';
		if (document.getElementById('Q_' + QNum + '_SA') != null){
			document.getElementById('Q_' + QNum + '_SA').style.display = 'none';
		}
	}
}

function GetCorrectArray(QNum){
	var Result = new Array();
	for (var ANum=0; ANum<I[QNum][3].length; ANum++){
		if (I[QNum][3][ANum][2] == 1){ //This is an acceptable correct answer
			Result.push(I[QNum][3][ANum][0]);
		}
	}	
	return Result;
}

function GetCorrectList(QNum, Answer, IncludeAnswer){
	var As = GetCorrectArray(QNum);
	var Result = '';
	for (var ANum=0; ANum<As.length; ANum++){
		if ((IncludeAnswer == true)||(As[ANum] != Answer)){
			Result += As[ANum] + '<br />';
		}
	}
	return Result;
}

function GetFirstCorrectAnswer(QNum){
	var As = GetCorrectArray(QNum);
	if (As.length > 0){
		return As[0];
	}
	else{
		return '';
	}
}

function ReplaceGuessBox(QNum, Ans){
	if (document.getElementById('Q_' + QNum + '_SA') != null){
		var El = document.getElementById('Q_' + QNum + '_SA');
		while (El.childNodes.length > 0){
			El.removeChild(El.childNodes[0]);
		}
		var A = document.createElement('span');
		A.setAttribute('class', 'Answer');
		var T = document.createTextNode(Ans);
		A.appendChild(T);
		El.appendChild(A);
	}
}





function ShowHint(QNum){
//bail if question doesn't exist or exercise finished
	if ((State[QNum].length < 1)||(Finished == true)){return;}
	
//bail if question already complete
	if (State[QNum][0] > -1){return;}

//Get the guess
	var G = document.getElementById('Q_' + QNum + '_Guess').value;
	
//If no guess, give the first correct bit
	if (G.length < 1){
		var Ans = GetFirstCorrectAnswer(QNum);
		var Hint = Ans.charAt(0);
		ShowMessage(NextCorrect + '<br />' + Hint);
//Penalty for hint
		State[QNum][4] += (1/Ans.length);
		return;
	}

//Increment tries
	State[QNum][2]++;
	
//Create a check object
	var CA = new CheckAnswerArray(CaseSensitive);

	CA.ClearAll();
	for (var ANum=0; ANum<I[QNum][3].length; ANum++){
//Use only correct answers
		if (I[QNum][3][ANum][2] == 1){
			CA.AddAnswer(G, I[QNum][3][ANum][0], I[QNum][3][ANum][3], I[QNum][3][ANum][1]);
		}
	}
	CA.GetBestMatch();
	if (CA.CompleteMatch == true){
//It's right!
		CheckShortAnswer(QNum);
		return;
	}
	else{
		if (CA.Hint.length > 0){
			ShowMessage(NextCorrect + '<br />' + CA.Hint);
			State[QNum][4] += CA.HintPenalty;
		}
		else{
			ShowMessage(DefaultWrong + '<br />' + NextCorrect + '<br />' + GetFirstCorrectAnswer(QNum)[0]);
		}
	}
}













//CODE FOR HANDLING SENDING OF RESULTS

var UserName = '';
var StartTime = (new Date()).toLocaleString();


var ResultForm = '<html><body><form name="Results" action="https://apps.carleton.edu/its/hotpotatoes/netid_only/HotPotatoesMail.cgi" method="post" enctype="x-www-form-encoded">';
ResultForm += '<input type="hidden" name="course" value=""></input>';
ResultForm += '<input type="hidden" name="recipient" value=""></input>';
