// JavaScript Document
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();

//for (prop in C){
//	alert(prop + ': ' + C[prop]);
//}



//CODE FOR HANDLING NAV BUTTONS AND FUNCTION BUTTONS

//[strNavBarJS]
function NavBtnOver(Btn){
	if (Btn.className != 'NavButtonDown'){Btn.className = 'NavButtonUp';}
}

function NavBtnOut(Btn){
	Btn.className = 'NavButton';
}

function NavBtnDown(Btn){
	Btn.className = 'NavButtonDown';
}
//[/strNavBarJS]

function FuncBtnOver(Btn){
	if (Btn.className != 'FuncButtonDown'){Btn.className = 'FuncButtonUp';}
}

function FuncBtnOut(Btn){
	Btn.className = 'FuncButton';
}

function FuncBtnDown(Btn){
	Btn.className = 'FuncButtonDown';
}

function FocusAButton(){
	if (document.getElementById('CheckButton1') != null){
		document.getElementById('CheckButton1').focus();
	}
	else{
		if (document.getElementById('CheckButton2') != null){
			document.getElementById('CheckButton2').focus();
		}
		else{
			document.getElementsByTagName('button')[0].focus();
		}
	}
}




//CODE FOR HANDLING DISPLAY OF POPUP FEEDBACK BOX

var topZ = 1000;

function ShowMessage(Feedback){
	var Output = Feedback + '<br /><br />';
	document.getElementById('FeedbackContent').innerHTML = Output;
	var FDiv = document.getElementById('FeedbackDiv');
	topZ++;
	FDiv.style.zIndex = topZ;
	FDiv.style.top = TopSettingWithScrollOffset(30) + 'px';

	FDiv.style.display = 'block';

	ShowElements(false, 'input');
	ShowElements(false, 'select');
	ShowElements(false, 'object');
	ShowElements(true, 'object', 'FeedbackContent');

//Focus the OK button
	setTimeout("document.getElementById('FeedbackOKButton').focus()", 50);
	
//
}

function ShowElements(Show, TagName, ContainerToReverse){
// added third argument to allow objects in the feedback box to appear
//IE bug -- hide all the form elements that will show through the popup
//FF on Mac bug : doesn't redisplay objects whose visibility is set to visible
//unless the object's display property is changed

	//get container object (by Id passed in, or use document otherwise)
	TopNode = document.getElementById(ContainerToReverse);
	var Els;
	if (TopNode != null) {
		Els = TopNode.getElementsByTagName(TagName);
	} else {
		Els = document.getElementsByTagName(TagName);
	}

	for (var i=0; i<Els.length; i++){
		if (TagName == "object") {
			//manipulate object elements in all browsers
			if (Show == true){
				Els[i].style.visibility = 'visible';
				//get Mac FireFox to manipulate display, to force screen redraw
				if (C.mac && C.gecko) {Els[i].style.display = '';}
			}
			else{
				Els[i].style.visibility = 'hidden';
				if (C.mac && C.gecko) {Els[i].style.display = 'none';}
			}
		} 
		else {
			// tagName is either input or select (that is, Form Elements)
			// ie6 has a problem with Form elements, so manipulate those
			if (C.ie) {
				if (C.ieVer < 7) {
					if (Show == true){
						Els[i].style.visibility = 'visible';
					}
					else{
						Els[i].style.visibility = 'hidden';
					}
				}
			}
		}
	}
}



function HideFeedback(){
	document.getElementById('FeedbackDiv').style.display = 'none';
	ShowElements(true, 'input');
	ShowElements(true, 'select');
	ShowElements(true, 'object');
	if (Finished == true){
		Finish();
	}
}


//GENERAL UTILITY FUNCTIONS AND VARIABLES

//PAGE DIMENSION FUNCTIONS
function PageDim(){
//Get the page width and height
	this.W = 600;
	this.H = 400;
	this.W = document.getElementsByTagName('body')[0].clientWidth;
	this.H = document.getElementsByTagName('body')[0].clientHeight;
}

var pg = null;

function GetPageXY(El) {
	var XY = {x: 0, y: 0};
	while(El){
		XY.x += El.offsetLeft;
		XY.y += El.offsetTop;
		El = El.offsetParent;
	}
	return XY;
}

function GetScrollTop(){
	if (typeof(window.pageYOffset) == 'number'){
		return window.pageYOffset;
	}
	else{
		if ((document.body)&&(document.body.scrollTop)){
			return document.body.scrollTop;
		}
		else{
			if ((document.documentElement)&&(document.documentElement.scrollTop)){
				return document.documentElement.scrollTop;
			}
			else{
				return 0;
			}
		}
	}
}

function GetViewportHeight(){
	if (typeof window.innerHeight != 'undefined'){
		return window.innerHeight;
	}
	else{
		if (((typeof document.documentElement != 'undefined')&&(typeof document.documentElement.clientHeight !=
     'undefined'))&&(document.documentElement.clientHeight != 0)){
			return document.documentElement.clientHeight;
		}
		else{
			return document.getElementsByTagName('body')[0].clientHeight;
		}
	}
}

function TopSettingWithScrollOffset(TopPercent){
	var T = Math.floor(GetViewportHeight() * (TopPercent/100));
	return GetScrollTop() + T; 
}

//CODE FOR AVOIDING LOSS OF DATA WHEN BACKSPACE KEY INVOKES history.back()
var InTextBox = false;

function SuppressBackspace(e){ 
	if (InTextBox == true){return;}
	if (C.ie) {
		thisKey = window.event.keyCode;
	}
	else {
		thisKey = e.keyCode;
	}

	var Suppress = false;

	if (thisKey == 8) {
		Suppress = true;
	}

	if (Suppress == true){
		if (C.ie){
			window.event.returnValue = false;	
			window.event.cancelBubble = true;
		}
		else{
			e.preventDefault();
		}
	}
}

if (C.ie){
	document.attachEvent('onkeydown',SuppressBackspace);
	window.attachEvent('onkeydown',SuppressBackspace);
}
else{
	if (window.addEventListener){
		window.addEventListener('keypress',SuppressBackspace,false);
	}
}

function ReduceItems(InArray, ReduceToSize){
	var ItemToDump=0;
	var j=0;
	while (InArray.length > ReduceToSize){
		ItemToDump = Math.floor(InArray.length*Math.random());
		InArray.splice(ItemToDump, 1);
	}
}

function Shuffle(InArray){
	var Num;
	var Temp = new Array();
	var Len = InArray.length;

	var j = Len;

	for (var i=0; i<Len; i++){
		Temp[i] = InArray[i];
	}

	for (i=0; i<Len; i++){
		Num = Math.floor(j  *  Math.random());
		InArray[i] = Temp[Num];

		for (var k=Num; k < (j-1); k++) {
			Temp[k] = Temp[k+1];
		}
		j--;
	}
	return InArray;
}

function WriteToInstructions(Feedback) {
	document.getElementById('InstructionsDiv').innerHTML = Feedback;

}




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 '';
        }
}

function FindLongest(InArray){
	if (InArray.length < 1){return -1;}

	var Longest = 0;
	for (var i=1; i<InArray.length; i++){
		if (InArray[i].length > InArray[Longest].length){
			Longest = i;
		}
	}
	return Longest;
}

//UNICODE CHARACTER FUNCTIONS
function IsCombiningDiacritic(CharNum){
	var Result = (((CharNum >= 0x0300)&&(CharNum <= 0x370))||((CharNum >= 0x20d0)&&(CharNum <= 0x20ff)));
	Result = Result || (((CharNum >= 0x3099)&&(CharNum <= 0x309a))||((CharNum >= 0xfe20)&&(CharNum <= 0xfe23)));
	return Result;
}

function IsCJK(CharNum){
	return ((CharNum >= 0x3000)&&(CharNum < 0xd800));
}

//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'));
		}
	}
}




document.onkeypress = KeyPress;

function KeyPress(e) {
	var InKey = 0;
	if (C.gecko) {InKey=e.which;}
	if (C.ie) {InKey=event.keyCode;}
	
	var TheKey = String.fromCharCode(InKey).toUpperCase();
	if (TheKey == 'R'){
		StartUp();
		return false;	
	}
	var TheKeyNum = InKey - 64;
	if (TheKeyNum > 32){TheKeyNum -= 32;}
	if ((TheKeyNum > 0)&&(TheKeyNum <= NumberOfOptions)){
		CheckAnswer(TheKeyNum);
		return false;
	}

	return true;
}

var CorrectIndicator = ':-)';
var IncorrectIndicator = 'X';
var StorySoFar = new Array();
var NumberOfOptions = 3;
var OptionsThisQ = 3;
var YourScoreIs = 'Puntuaci&#x00F3;n:';
var strTimesUp = 'Your time is over!';

var CurrentAnswer = '';
var CurrentNumber = 0;
var CurrentCorrect = 0;
var TotalPoints = 0;
var ScoredPoints = 0;
var TotalSegments = 0;
var ThisQScore = 0;
var FinalScore = 0;
var AllDone = false;
var Finished = false;
var TimeOver = false;
var SegmentsToShow = 0;

var StartTime = (new Date()).getTime();
var Captions = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var ChoiceTemplate = '';
var OperaButton = '<a href="javascript:CheckAnswer([ChoiceNum], this)">[ChoiceLetter]</a>';

function CreateChoiceButtons(){
	var TheButtons = document.getElementById('ChoiceDiv');
	if (TheButtons == null){return;}
	var Output = '';
	var Btn;
	Output += '<table border="0" cellpadding="8" class="ExerciseTable"><tbody>';

	for (var i=1; i<=OptionsThisQ; i++){
		Btn = ChoiceTemplate;
		Btn = Btn.replace(/_ChoiceNum_/g, i);
		Btn = Btn.replace(/\[ChoiceLetter\]/g, '&nbsp;&nbsp;'+Captions.charAt(i-1)+'&nbsp;&nbsp;');
		Output += Btn;
	}
	Output += '</tbody></table>';
	TheButtons.innerHTML = Output;
}

function StartUp(){

	ChoiceTemplate = document.getElementById('ChoiceButtons').innerHTML;
//for Opera, need to replace button with link
	if (C.opera){
		ChoiceTemplate = ChoiceTemplate.replace(/<button.*<\/button>/, OperaButton);
	}
	
	CreateChoiceButtons();

	TotalSegments = Segments.length;

	CurrentNumber = 0;
	ShowQuestion();
	ThisQScore = OptionsThisQ-1;
	document.getElementById('Story').innerHTML = '';
	document.getElementById('ScoreBox').innerHTML = '';
	StorySoFar.length = 0;

	AllDone = false;


}

function ShowQuestion(){

	var i, j, Num;
	
	var Range = TotalSegments - CurrentNumber;

	var DistractorPool = new Array();
	var Distractors = new Array();
	DistractorPool.length = 0;
	Distractors.length = 0;
	
//Find out how many distractors are available	
	for (i=CurrentNumber+1; i<Segments.length; i++){
		DistractorPool[DistractorPool.length] = i;
	}	
	
//If it's less than the number of allowed choices, we're getting to the end;
//reduce the number of choices, and rewrite the button set
	if ((DistractorPool.length+1) < OptionsThisQ){
		while ((DistractorPool.length+1) < OptionsThisQ){
			OptionsThisQ--;
		}
	}
	
	CreateChoiceButtons();
	TotalPoints += OptionsThisQ-1;
	var ChoiceSegments = new Array();

	var RightAnswer = RemoveSlashes(Segments[CurrentNumber]);
	ChoiceSegments[0] = RightAnswer;
	
	for (i=1; i<OptionsThisQ; i++){
		Num = Math.floor(DistractorPool.length  *  Math.random());
		ChoiceSegments[ChoiceSegments.length] = RemoveSlashes(Segments[DistractorPool[Num]]);
		for (j=Num; j<DistractorPool.length-1; j++){
			DistractorPool[j] = DistractorPool[j+1];
		}
		DistractorPool.length--;
	}
	Shuffle(ChoiceSegments);
	
//Find where the right answer ended up
	for (i=0; i<ChoiceSegments.length; i++){
		if (ChoiceSegments[i] == RightAnswer){
			CurrentCorrect = i+1;
		}
	}
	
	for (i=1; i<=OptionsThisQ; i++){
			document.getElementById('Choice'+i).innerHTML = ChoiceSegments[i-1];
	}

	ThisQScore = OptionsThisQ-1;

}

function CheckAnswer(Chosen, Btn){

	if ((CurrentNumber == TotalSegments)||(AllDone == true)){
		return;
	}
	if (Btn.innerHTML == IncorrectIndicator){
		return;
	}
	if (CurrentCorrect == Chosen){
		StorySoFar[StorySoFar.length] = SlashesToReturn(Segments[CurrentNumber]);
		CurrentNumber++;
		if (CurrentNumber >= TotalSegments - 1){
			StorySoFar[StorySoFar.length] = SlashesToReturn(Segments[TotalSegments-1]);
		}
		
		setTimeout("ShowStorySoFar()", 50);
	
		ScoredPoints += ThisQScore;
		
		if (CurrentNumber < TotalSegments-1){
			var CurrentScore = CalculateScore();
			document.getElementById('ScoreBox').innerHTML = CurrentScore + '%';
			ShowQuestion();
		}
		else{
			document.getElementById('ChoiceDiv').innerHTML = '';
			FinalScore = CalculateScore();
			document.getElementById('ScoreBox').innerHTML = FinalScore + '%';
			ShowMessage(YourScoreIs + ' ' + FinalScore + '%');

			AllDone = true;
			Finish();
		}	
	}
	else{
		Btn.innerHTML = IncorrectIndicator;
		document.getElementById('ScoreBox').innerHTML = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
		if (ThisQScore > 0){
			ThisQScore--;
		}
	}
}

function CalculateScore(){
	return Math.floor(100*ScoredPoints/TotalPoints);
}

function Finish(){
//If there's a form, fill it out and submit it
	var F = document.getElementById('store');
	if (F != null){
		F.starttime.value = StartTime;
		F.endtime.value = (new Date()).getTime();
		F.mark.value = FinalScore;
		F.submit();
	}
}

function SlashesToReturn(InString){
	var LineEnd = ' ';
	while (InString.charAt(InString.length-1) == '/'){
		InString= InString.substring(0, InString.length-1);
		LineEnd += '<br />';
	}
	return InString + LineEnd;
}

function RemoveSlashes(InString){
	while (InString.charAt(InString.length-1) == '/'){
		InString= InString.substring(0, InString.length-1);
	}
	return InString;
}



function CalculateTotalPoints(){
	var j=NumberOfOptions;
	TotalPoints = 0
	for (var i=0; i<TotalSegments-1; i++){
		while (j>TotalSegments-(CurrentNumber-1)){j--;};
		TotalPoints += j;
	}
}



function ShowText(HowManySegments){
	SegmentsToShow = HowManySegments;
	if (HowManySegments == 0){
		document.getElementById('ShowPartText').style.display = 'inline';
		document.getElementById('ShowWholeText').style.display = 'none';
	}
	else{
		document.getElementById('ShowPartText').style.display = 'none';
		document.getElementById('ShowWholeText').style.display = 'inline';
	}
	ShowStorySoFar();
}

function ShowStorySoFar(){
	var StartFrom = 0;
	if ((SegmentsToShow > 0)&&(StorySoFar.length > SegmentsToShow)){
		StartFrom = StorySoFar.length - SegmentsToShow;
	}
	var Output = '';
	for (var i=StartFrom; i<StorySoFar.length; i++){
		Output += StorySoFar[i];
	}
	document.getElementById('Story').innerHTML = Output;
}

var Segments = new Array();
Segments[0]='Se ha supuesto hasta ahora que todo ';
Segments[1]='nuestro conocer debe regirse por los objetos. ';
Segments[2]='Sin embargo, todos los intentos realizados ';
Segments[3]='bajo tal supuesto con vistas a establecer a ';
Segments[4]='priori, mediante conceptos, algo sobre dichos ';
Segments[5]='objetos -algo que ampliara nuestro ';
Segments[6]='conocimiento- desembocaban en el fracaso. ';
Segments[7]='Intentemos, pues, por una vez, si no ';
Segments[8]='adelantaremos m\u00E1s en las tareas de la ';
Segments[9]='metaf\u00EDsica suponiendo que los objetos ';
Segments[10]='deben conformarse a nuestro conocimiento, ';
Segments[11]='cosa que concuerda ya mejor con la deseada ';
Segments[12]='posibilidad de un conocimiento a priori de ';
Segments[13]='dichos objetos, un conocimiento que pretende ';
Segments[14]='establecer algo sobre \u00E9stos antes de que ';
Segments[15]='nos sean dados. Ocurre aqu\u00ED como con ';
Segments[16]='los primeros pensamientos de Cop\u00E9rnico. ';
Segments[17]='Este, viendo que no consegu\u00EDa explicar los  ';
Segments[18]='movimientos celestes si aceptaba que todo ';
Segments[19]='el ej\u00E9rcito de estrellas giraba alrededor del ';
Segments[20]='espectador, prob\u00F3 si no obtendr\u00EDa mejores ';
Segments[21]='resultados haciendo girar al espectador y ';
Segments[22]='dejando las estrellas en reposo. En la ';
Segments[23]='metaf\u00EDsica se puede hacer el mismo ensayo, ';
Segments[24]='en lo que ata\u00F1e a la intuici\u00F3n de los objetos. ';
Segments[25]='Si la intuici\u00F3n tuviera que regirse por la ';
Segments[26]='naturaleza de los objetos, no veo c\u00F3mo ';
Segments[27]='podr\u00EDa conocerse algo a priori sobre esa ';
Segments[28]='naturaleza. Si, en cambio, es el objeto  (en ';
Segments[29]='cuanto objeto de los sentidos) el que se rige ';
Segments[30]='por la naturaleza de nuestra facultad de intuici\u00F3n, ';
Segments[31]='puedo representarme f\u00E1cilmente tal posibilidad.';
