function Client(){
//if not a DOM browser, hopeless
	this.min = false; if (document.getElementById){this.min = true;};

	this.ua = navigator.userAgent;
	this.name = navigator.appName;
	this.ver = navigator.appVersion;  

//Get data about the browser
	this.mac = (this.ver.indexOf('Mac') != -1);
	this.win = (this.ver.indexOf('Windows') != -1);

//Look for Gecko
	this.gecko = (this.ua.indexOf('Gecko') > 1);
	if (this.gecko){
		this.geckoVer = parseInt(this.ua.substring(this.ua.indexOf('Gecko')+6, this.ua.length));
		if (this.geckoVer < 20020000){this.min = false;}
	}
	
//Look for Firebird
	this.firebird = (this.ua.indexOf('Firebird') > 1);
	
//Look for Safari
	this.safari = (this.ua.indexOf('Safari') > 1);
	if (this.safari){
		this.gecko = false;
	}
	
//Look for IE
	this.ie = (this.ua.indexOf('MSIE') > 0);
	if (this.ie){
		this.ieVer = parseFloat(this.ua.substring(this.ua.indexOf('MSIE')+5, this.ua.length));
		if (this.ieVer < 5.5){this.min = false;}
	}
	
//Look for Opera
	this.opera = (this.ua.indexOf('Opera') > 0);
	if (this.opera){
		this.operaVer = parseFloat(this.ua.substring(this.ua.indexOf('Opera')+6, this.ua.length));
		if (this.operaVer < 7.04){this.min = false;}
	}
	if (this.min == false){
		alert('Your browser may not be able to handle this page.');
	}
	
//Special case for the horrible ie5mac
	this.ie5mac = (this.ie&&this.mac&&(this.ieVer<6));
}

var C = new Client();



//CODE FOR HANDLING DISPLAY OF POPUP FEEDBACK BOX
function ShowMessage(Feedback){
confirm (Feedback);
}

//GENERAL UTILITY FUNCTIONS AND VARIABLES


function EscapeDoubleQuotes(InString){
	return InString.replace(/"/g, '&quot;')
}

function TrimString(InString){
        var x = 0;

        if (InString.length != 0) {
                while ((InString.charAt(InString.length - 1) == '\u0020') || (InString.charAt(InString.length - 1) == '\u000A') || (InString.charAt(InString.length - 1) == '\u000D')){
                        InString = InString.substring(0, InString.length - 1)
                }

                while ((InString.charAt(0) == '\u0020') || (InString.charAt(0) == '\u000A') || (InString.charAt(0) == '\u000D')){
                        InString = InString.substring(1, InString.length)
                }

                while (InString.indexOf('  ') != -1) {
                        x = InString.indexOf('  ')
                        InString = InString.substring(0, x) + InString.substring(x+1, InString.length)
                 }

                return InString;
        }

        else {
                return '';
        }
}


//SETUP FUNCTIONS
//BROWSER WILL REFILL TEXT BOXES FROM CACHE IF NOT PREVENTED
function ClearTextBoxes(){
	var NList = document.getElementsByTagName('input');
	for (var i=0; i<NList.length; i++){
		if ((NList[i].id.indexOf('Guess') > -1)||(NList[i].id.indexOf('Gap') > -1)){
			NList[i].value = '';
		}
		if (NList[i].id.indexOf('Chk') > -1){
			NList[i].checked = '';
		}
	}
}

//EXTENSION TO ARRAY OBJECT
function Array_IndexOf(Input){
	var Result = -1;
	for (var i=0; i<this.length; i++){
		if (this[i] == Input){
			Result = i;
		}
	}
	return Result;
}
Array.prototype.indexOf = Array_IndexOf;

//IE HAS RENDERING BUG WITH BOTTOM NAVBAR
function RemoveBottomNavBarForIE(){
	if ((C.ie)&&(document.getElementById('Reading') != null)){
		if (document.getElementById('BottomNavBar') != null){
			document.getElementById('TheBody').removeChild(document.getElementById('BottomNavBar'));
		}
	}
}




//HOTPOTNET-RELATED CODE

var HPNStartTime = (new Date()).getTime();
var SubmissionTimeout = 30000;
var Detail = ''; //Global that is used to submit tracking data

function Finish(){
//If there's a form, fill it out and submit it
	if (document.store != null){
		Frm = document.store;
		Frm.starttime.value = HPNStartTime;
		Frm.endtime.value = (new Date()).getTime();
		Frm.mark.value = Score;
		Frm.detail.value = Detail;
		Frm.submit();
	}
}





//JCLOZE CORE JAVASCRIPT CODE

function ItemState(){
	this.ClueGiven = false;
	this.HintsAndChecks = 0;
	this.MatchedAnswerLength = 0;
	this.ItemScore = 0;
	this.AnsweredCorrectly = false;
	this.Guesses = new Array();
	return this;
}

var Feedback = '';
var Correct = 'Correct! Well done.';
var Incorrect = 'Some of your answers are incorrect. Incorrect answers have been left in place for you to change.'; 
var CaseSensitive = false;
var YourScoreIs = 'Your score is ';
var Finished = false;
var Locked = false;
var Score = 0;
var CurrentWord = 0;
var Guesses = '';
var TimeOver = false;

State = new Array();

I = new Array();
ISMS = new Array();
ISMS[0] = 'memories'; 
ISMS[1] = 'hopes to'; 
ISMS[2] = 'believe'; 


function StartUp(){
	RemoveBottomNavBarForIE();
//Show a keypad if there is one	(added bugfix for 6.0.4.12)
	if (document.getElementById('CharacterKeypad') != null){
		document.getElementById('CharacterKeypad').style.display = 'block';
	}
	
	State.length = 0;
	for (var i=0; i<I.length; i++){
		State[i] = new ItemState();
	}

	ClearTextBoxes();
	
	//размер  et_text
	//SetEtTextHeight();
}

//устанавливаем высоту элемента et_text
/*function SetEtTextHeight() {
	var et_text = document.getElementById('et_text');
	if (et_text == null)
		return;
		
	var x,y, text_width, text_heigth;	
	if (self.innerHeight) {	
		x = self.innerWidth;	
		y = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {	
		x = document.documentElement.clientWidth;	
		y = document.documentElement.clientHeight;	
	} else if (document.body) {	
		x = document.body.clientWidth;	
		y = document.body.clientHeight;	
	}
	text_width = x - 480 - 50;
	text_heigth = y - 100;
	//et_text.style.width = text_width + 'px';
	et_text.style.height = text_heigth + 'px';
}*/

function SaveCurrentAnswers(){
	var Ans = '';
	for (var i=0; i<I.length; i++){
		Ans = GetGapValue(i);
		if ((Ans.length > 0)&&(Ans != State[i].Guesses[State[i].Guesses.length-1])){
			State[i].Guesses[State[i].Guesses.length] = Ans;
		}
	}
}

function CompileGuesses(){
	var F = document.getElementById('store');
	if (F != null){
		var Temp = '<?xml version="1.0"?><hpnetresult><fields>';
		var GapLabel = '';
		for (var i=0; i<State.length; i++){
			GapLabel = 'Gap ' + (i+1).toString();
			Temp += '<field><fieldname>' + GapLabel + '</fieldname>';
			Temp += '<fieldtype>student-responses</fieldtype><fieldlabel>' + GapLabel + '</fieldlabel>';
			Temp += '<fieldlabelid>JClozeStudentResponses</fieldlabelid><fielddata>';
			for (var j=0; j<State[i].Guesses.length; j++){
				if (j>0){Temp += '| ';}
				Temp += State[i].Guesses[j] + ' ';	
			}	
  		Temp += '</fielddata></field>';
		}
		Temp += '</fields></hpnetresult>';
		Detail = Temp;
	}
}

function CheckAnswers(){
	if (Locked == true){return;}
	SaveCurrentAnswers();
	var AllCorrect = true;

//Check each answer
	for (var i = 0; i<I.length; i++){

		if (State[i].AnsweredCorrectly == false){
//If it's right, calculate its score
			if (CheckAnswer(i, true) > -1){
				var TotalChars = GetGapValue(i).length;
				State[i].ItemScore = (TotalChars-State[i].HintsAndChecks)/TotalChars;
				if (State[i].ClueGiven == true){State[i].ItemScore /= 2;}
				if (State[i].ItemScore <0 ){State[i].ItemScore = 0;}
				State[i].AnsweredCorrectly = true;
//Drop the correct answer into the page, replacing the text box
				SetCorrectAnswer(i, GetGapValue(i));
//Clear hints    
if (document.getElementById('answerString' + i) != null){
      var element = document.getElementById('answerString' + i);
      element.innerText = ''; // for IE
      element.textContent = ''; // for the rest of the known world
    }
			}
			else{
//Otherwise, increment the hints for this item, as a penalty
				State[i].HintsAndChecks++;

//then set the flag
				AllCorrect = false;
			}
		}
	}

//Calculate the total score
	var TotalScore = 0;
	for (i=0; i<State.length; i++){
		TotalScore += State[i].ItemScore;
	}
	TotalScore = Math.floor((TotalScore * 100)/I.length);

//Compile the output
	Output = '';

	if (AllCorrect == true){
		Output = Correct;
	}

	Output += YourScoreIs + ' ' + TotalScore + '%.';
	if (AllCorrect == false){
		Output += Incorrect;
	}
	ShowMessage(Output);
	
	Score = TotalScore;
	CompileGuesses();
	
	if ((AllCorrect == true)||(Finished == true)){
		TimeOver = true;
		Locked = true;
		Finished = true;
		setTimeout('Finish()', SubmissionTimeout);
	}

}

function CheckAnswersSMS(nums){
	var AllCorrect = true; 
	//Check each answer
	for (var i = 0; i<nums.length; i++){
                var ans = CheckAnswerSMS(i, true);
		if (ans == 1){
                  //do nothing
                }else if (ans == 0){
			//Drop the correct answer into the page, replacing the text box
			SetCorrectAnswerSMS(i, GetGapValueSMS(i));
		}else{
			//set the flag
			AllCorrect = false;
		}
	}

	//Compile the output
	Output = '';

	if (AllCorrect == true){
		Output = Correct;
	}

	if (AllCorrect == false){
		Output += Incorrect;
	}
	ShowMessage(Output);
	
	CompileGuesses();
	
	if ((AllCorrect == true)||(Finished == true)){
		TimeOver = true;
		Locked = true;
		Finished = true;
		setTimeout('Finish()', SubmissionTimeout);
		//set pswsms, replacing the text box
		Setpswsms();
	}
}

function CheckAnswerSMS(GapNum, MarkAnswer){
    //if the user have made a correct answer
    if (document.getElementById('GapSMS' + GapNum) == null){
        return 1;
    }

        var Guess = GetGapValueSMS(GapNum);
	var UpperGuess = '';
	var UpperAnswer = '';
	UpperGuess = Guess.toUpperCase();

	var Match = -1;
	UpperAnswer = ISMS[GapNum].toUpperCase();

	if (TrimString(UpperGuess) == UpperAnswer){
		Match = 0;
	}
	return Match;
}

function CheckBeginning(Guess, Answer){
	var OutString = '';
	var i = 0;
	var UpperGuess = '';
	var UpperAnswer = '';

	if (CaseSensitive == false) {
		UpperGuess = Guess.toUpperCase();
		UpperAnswer = Answer.toUpperCase();
	}
	else {
		UpperGuess = Guess;
		UpperAnswer = Answer;
	}

	while (UpperGuess.charAt(i) == UpperAnswer.charAt(i)) {
		OutString += Guess.charAt(i);
		i++;
	}
	OutString += Answer.charAt(i);
	return OutString;
}


function GetGapValue(GNum){
	var RetVal = '';
	if ((GNum<0)||(GNum>=I.length)){return RetVal;}
	if (document.getElementById('Gap' + GNum) != null){
		RetVal = document.getElementById('Gap' + GNum).value;
		RetVal = TrimString(RetVal);
	}
	else{
		RetVal = State[GNum].Guesses[State[GNum].Guesses.length-1];
	}
	return RetVal;
}

function GetGapValueSMS(GNum){
	var RetVal = '';
	if ((GNum<0)||(GNum>=ISMS.length)){return RetVal;}
	if (document.getElementById('GapSMS' + GNum) != null){
		RetVal = document.getElementById('GapSMS' + GNum).value;
		RetVal = TrimString(RetVal);
	}
	return RetVal;
}

function SetGapValue(GNum, Val){
	if ((GNum<0)||(GNum>=I.length)){return;}
	if (document.getElementById('Gap' + GNum) != null){
		document.getElementById('Gap' + GNum).value = Val;
		document.getElementById('Gap' + GNum).focus();
	}
}

function SetCorrectAnswer(GNum, Val){
	if ((GNum<0)||(GNum>=I.length)){return;}
	if (document.getElementById('GapSpan' + GNum) != null){
		document.getElementById('GapSpan' + GNum).innerHTML = Val;
	}
}

function SetCorrectAnswerSMS(GNum, Val){
	if ((GNum<0)||(GNum>=ISMS.length)){return;}
	if (document.getElementById('GapSpanSMS' + GNum) != null){
		document.getElementById('GapSpanSMS' + GNum).innerHTML = Val;
	}
}

function Setpswsms(){
	if (document.getElementById('pswsms') != null){
		document.getElementById('pswsms').innerHTML = '<p>&#1055;&#1072;&#1088;&#1086;&#1083;&#1100;: ab8d54</p>';
	}
}


function FindCurrent() {
	var x = 0;
	FoundCurrent = -1;

//Test the current word:
//If its state is not set to already correct, check the word.
	if (State[CurrentWord].AnsweredCorrectly == false){
		if (CheckAnswer(CurrentWord, false) < 0){
			return CurrentWord;
		}
	}
	
	x=CurrentWord + 1;
	while (x<I.length){
		if (State[x].AnsweredCorrectly == false){
			if (CheckAnswer(x, false) < 0){
				return x;
			}
		}
	x++;	
	}

	x = 0;
	while (x<CurrentWord){
		if (State[x].AnsweredCorrectly == false){
			if (CheckAnswer(x, false) < 0){
				return x;
			}
		}
	x++;	
	}
	return FoundCurrent;
}

function GetHint(GapNum){
	Guess = GetGapValue(GapNum);

	if (CheckAnswer(GapNum, false) > -1){return ''}
	
        RightBits = CheckBeginning(Guess, I[GapNum]);
	
	var Result = I[GapNum].substring(0,RightBits.length);
//Add another char if the last one is a space
	if (Result.charAt(Result.length-1) == ' '){
		Result = I[GapNum].substring(0,RightBits.length+1);
	}
	return Result;
}


function CheckAnswer(GapNum, MarkAnswer){
	var Guess = GetGapValue(GapNum);
	var UpperGuess = '';
	var UpperAnswer = '';
	if (CaseSensitive == false){
		UpperGuess = Guess.toUpperCase();
	}
	else{
		UpperGuess = Guess;
	}

	var Match = -1;
		if (CaseSensitive == false){
			UpperAnswer = I[GapNum].toUpperCase();
		}
		else{
			UpperAnswer = I[GapNum];
		}
		if (TrimString(UpperGuess) == UpperAnswer){
			Match = 0;
			if (MarkAnswer == true){
				State[GapNum].AnsweredCorrectly = true;
			}
		}
	return Match;
}

function ShowHintOld(){
	if (Locked == true){return;}
	var CurrGap = FindCurrent();
	if (CurrGap < 0){return;}

	var HintString = GetHint(CurrGap);

	if (HintString.length > 0){
		SetGapValue(CurrGap, HintString);
		State[CurrGap].HintsAndChecks += 1;
	}
}

function ShowHint() {
  for (var i=0; i<I.length; i++){
    if (State[i].AnsweredCorrectly == true)
      continue;
    if (document.getElementById('answerString' + i) != null){
      var element = document.getElementById('answerString' + i);
      element.innerText = I[i]+' '; // for IE
      element.textContent = I[i]; // for the rest of the known world
    }
  }
}

function OpenDetails(name){
		var txt = document.getElementById(name + "text");
		txt.style.display = "block";
		var cls = document.getElementById(name + "close");
		cls.style.display = "block";
		var dtls = document.getElementById(name + "details");
		dtls.style.display = "none";
};

function CloseDetails(name){
		var txt = document.getElementById(name + "text");
		txt.style.display = "none";
		var cls = document.getElementById(name + "close");
		cls.style.display = "none";
		var dtls = document.getElementById(name + "details");
		dtls.style.display = "block";
};
function OpenHiddenAnswer(name){
		var txt = document.getElementById(name + "hidden_answer_text");
		txt.style.display = "block";
		var dtls = document.getElementById(name + "hidden_answer_details");
		dtls.style.display = "none";
};
