//
//	A JavaScript Library that contains the following functions
//
//	initialiseQuiz(n)
//	randomInteger(max)
//	quizFinished()
//	hash(x)
//	getUserName()
//	isAlphabeticString(inString)
//

/* ------------------------------------------------------------------------------
(c) Copyright 1998-1999, M P Docker and the Sixth Form College, Farnborough.
See http://www.mp-docker.demon.co.uk/terms_and_conditions.html 
for terms and conditions of use.

Version 1.0 - last updated 21/11/98.
------------------------------------------------------------------------------ */

function initialiseQuiz(n){
	scoreForQuiz = 0
	readyToStartAgain = false
	disabled = false
	questionsRemaining = numberOfQuestions	
		for (i = 1; i <= n; i++){
		askedAlready[i] = false
	}
	questionIndex = randomInteger(n)
	askedAlready[questionIndex] = true
}

function randomInteger(max){
	if (testingMode == true){
		if (firstTime == true){
			firstTime = false
			testingCounter = 0
		}
		else{
			testingCounter++
		}
		if (testingCounter >= max){
			firstTime = true
			readyToStartAgain = true
		}
		return testingCounter
	}
	else{
		return parseInt(((max+1)*Math.random()+1).toString()) - 1
	}
}

function quizFinished(){
	getUserName()
	clearanceCode = hash(userName + levelName)
	alert("Your personalised clearance code is " + clearanceCode + ".")
	readyToStartAgain = true
}

function hash(x){
	var y = 0
	for (var i = 0; i < x.length; i++){	
		y += 999999*(i+1)*parseInt(key.indexOf(x.charAt(i)))
	}
	return 1000 + (y % 9000)
}

function getUserName(){
	validUserName = false
	while (validUserName == false){	
		userName = prompt("Enter your name, e.g. John Smith.", "")
		validUserName = true
		if (userName == null){
			alert("You must enter a name.")
			validUserName = false
			continue
		}
		if (userName.indexOf(" ") == -1){
			alert("Enter two names with a space between.")
			validUserName = false
			continue
		}       
		if (userName.indexOf(" ") < 2 || userName.lastIndexOf(" ") > userName.length - 3){
			alert("You must enter at least two letters per name.")
			validUserName = false
			continue
		}
		if (isAlphabeticString(userName) == false){
			alert("A name can only contain letters.")
			validUserName = false
			continue
    		}
	}
}

function isAlphabeticString(inString){
	if (inString == null){return false}
	if (inString.length == 0){return false} 
	inString = inString.toLowerCase()
	var refString = " abcdefghijklmnopqrstuvwxyz" 
	for (var i = 0; i < inString.length; i++){
		var tempChar = inString.substring(i, i+1)
    	if (refString.indexOf(tempChar, 0) == -1){return false}
	}
	return true
}

