if(this.Ajax == undefined) {
	// load prototype if not already running
	document.write('<s' + 'cript language="javascript" src="/Bravo_Quiz/prototype1.6.js"></s' + 'cript>');
}
var _top = this;

function BravoQuiz (templateURL, quizID, quizDIV) {
	if(_top.Ajax == undefined) {
		return setTimeout(_top.BravoQuiz, 150, templateURL, quizID, quizDIV)
	}
	var instance = QUIZ_INSTANCE = this;
	var templateCode = '';
	var dataSource = '';
	var root = $(quizDIV);
	var numCorrect = 0;
	var pctCorrect = 0;
	var currentQuestion = 0;
	var currentQuestionID = 0;
	var totalQuestions = 0;
	var currentQuestionObj;
	var quizConfig = '';
	var quizQuestions = '';
	var quizResponses = '';
	var isLastQuestion = false;
	this.setTemplate = function (response) {
		templateCode = response.responseText;
		var e = new Element('div').update('Template Loaded...<br\>Initializing Quiz Data...');
		root.insert(e);
		var fail = function (transport) {
			var e = new Element('div').update("Error: Couldn't get Quiz Data: " + transport.responseText);
			root.insert(e);
		}
		var showLoading = function (transport) {
			var e = new Element('div').update("Loading Quiz Data...");
			root.insert(e);
		}
		var showLoaded = function (transport) {
			var e = new Element('div').update("Quiz Data Loaded.");
			root.insert(e);
		}
		var showProgress = function (transport) {
			return;
			var e = new Element('div').update("Parsing quiz data...");
			root.insert(e);
		}
		var showSuccess = function (transport) {
			var e = new Element('div').update("Parse complete.");
			root.insert(e);
			QUIZ_INSTANCE.setDataSource(transport);
		}
		new Ajax.Request('getData.php', {parameters:{id:quizID}, onSuccess: showSuccess, onFailure: fail, onLoading: showLoading, onLoaded: showLoaded, onInteractive: showProgress});
	}
	this.setDataSource = function (transport) {
		if(transport.responseText.toLowerCase().indexOf('parser error') > -1) {
			var e = new Element('div').update("<h1>Error converting XML to JSON</h1>" + transport.responseText);
			root.insert(e);
		}
		var json = eval("(" + transport.responseText + ")");
		quizConfig = json.quiz.config;
		quizQuestions = json.quiz.questions.question;
		quizResponses = json.quiz.responseSet.response;
		var e = new Element('div').update('Building Quiz...');
		root.insert(e);
		setTimeout(function() {QUIZ_INSTANCE.buildQuiz();}, 500);
	}
	this.buildQuiz = function () {
		if(!quizResponses) return alert('Error: There are no quiz responses set');
		if(!quizQuestions) return alert('Error: There are no quiz questions set');
		if(!Object.isArray(quizQuestions)) {
			quizQuestions = [quizQuestions];
		}
		if(!Object.isArray(quizResponses)) {
			quizResponses = [quizResponses];
		}
		totalQuestions = quizQuestions.length;
		var e = new Element('div').update('Showing Question 1...');
		root.insert(e);
		this.showQuestion(0);
	}
	this.showQuestion = function (id) {
		if(id != null) currentQuestionID = id;
		currentQuestionObj = quizQuestions[currentQuestionID];
		isLastQuestion = (currentQuestionID + 1 == quizQuestions.length);
		var tmpl = new Template(templateCode);
		var caption = this.stripslashes(currentQuestionObj.qCaption);
		var replace = {
			quizTitle: this.stripslashes(quizConfig.name),
			quizSummary: this.stripslashes(quizConfig.summary),
			totalQuestionsNumber: totalQuestions,
			correctCount: numCorrect,
			currentQuestionNumber: (currentQuestionID+1),
			questionTitle: this.stripslashes(currentQuestionObj.name),
			photoURL: currentQuestionObj.qImage,
			caption: caption,
			choices: this.getChoices(currentQuestionObj.answers.answer),
			button: this.getButton(quizConfig.submitImage, 'submit')
		};
		root.update(tmpl.evaluate(replace));
		if(caption == null || caption == '') $('captionRow').remove();
		if(replace.photoURL == null || replace.photoURL == '') {
			$$('.shadow3').each(function (s) {s.up(0).remove();});
		}
		$('quiz_complete').remove();
		$('quiz_answer').remove();
		if(quizConfig.radioImage_on.length && quizConfig.radioImage_off.length) {
			_top.initARC('answerForm', 'radioOn', 'radioOff',quizConfig.radioImage_on, quizConfig.radioImage_off);
		}
	}
	this.getAnswer = function (id) {
		var ans = currentQuestionObj.answers.answer;
		for(var i=0; i<ans.length; i++) {
			if(Number(ans[i].answerID) == Number(id)) return this.stripslashes(ans[i].name);
		}
		if(id == '') return "You didn't provide an answer.";
		return 'no answer found';
	}
	this.getChoices = function (answers) {
		if(!Object.isArray(answers)) {
			var answers = [answers];
		}
		var html = '<form id="answerForm">';
		for(var i=0; i<answers.length; i++) {
			html += '<div><input type="radio" id="radio' + i + '" name="answerChoice" value="' + answers[i].answerID + '"> <label for="radio' + i + '">' + this.stripslashes(answers[i].name) + '</label></div>';
		}
		html += '</form>';
		return html;
	}
	this.getButton = function (imageURL, buttonName) {
		var altName = buttonName.substr(0,1).toUpperCase() + buttonName.substr(1);
		if(imageURL == null || imageURL == '') return '<input type="submit" onclick="QUIZ_INSTANCE.' + buttonName + 'Question()" name="submit" value="' + altName + '"/>';
		else return '<a href="#" onclick="QUIZ_INSTANCE.' + buttonName + 'Question(); return false;"><img src="' + imageURL + '" border="0" /></a>';
	}
	this.submitQuestion = function () {
		var answerID = $$('input:checked[type="radio"][name="answerChoice"]').pluck('value');
		parent.adRefresh();
		this.showAnswer(answerID);
	}
	this.showAnswer = function(id) {
		if(id == '') var id = 0;
		var isCorrect = false;
		if(id == currentQuestionObj.correctID) {
			numCorrect++;
			pctCorrect = Math.round(numCorrect/totalQuestions*10);
			var isCorrect = true;
		}
		if(isCorrect) {
			var answerHTML = 'great job';
		} else {
			var answerHTML = 'great job';
		}
		var caption = this.stripslashes(currentQuestionObj.aCaption);
		var nextButton = isLastQuestion ? this.getButton(quizConfig.completeImage, 'complete') : this.getButton(quizConfig.nextImage, 'next');
		var tmpl = new Template(templateCode);
		var replace = {
			quizTitle: this.stripslashes(quizConfig.name),
			quizSummary: this.stripslashes(quizConfig.summary),
			totalQuestionsNumber: totalQuestions,
			correctCount: numCorrect,
			currentQuestionNumber: (currentQuestionID+1),
			questionTitle: this.stripslashes(currentQuestionObj.name),
			photoURL: currentQuestionObj.aImage,
			caption: caption,
			submittedAnswer: this.getAnswer(id),
			correctAnswer: this.getAnswer(currentQuestionObj.correctID),
			button: nextButton
		};
		root.update(tmpl.evaluate(replace));
		if(caption == null || caption == '') $('captionRow').remove();
		if(replace.photoURL == null || replace.photoURL == '') {
			$$('.shadow3').each(function (s) {s.up(0).remove();});
		}
		$('quiz_complete').remove();
		$('quiz_choices').remove();
		if(isCorrect) $('quiz_answer_incorrect').remove();
		else $('quiz_answer_correct').remove();
	}
	this.completeQuestion = function () {
		var response = this.getResponse();
		var tmpl = new Template(templateCode);
		var replace = {
			quizTitle: this.stripslashes(quizConfig.name),
			quizSummary: this.stripslashes(quizConfig.summary),
			totalQuestionsNumber: totalQuestions,
			correctCount: numCorrect,
			currentQuestionNumber: (currentQuestionID+1),
			endImageURL: quizConfig.endImage,
			responseTitle: response.title,
			responseSummary: response.summary
		};
		root.update(tmpl.evaluate(replace));
		$('quiz_questions').remove();
	}
	this.getResponse = function () {
		for(var i=0;i<quizResponses.length; i++) {
			if(Number(quizResponses[i].low) <= pctCorrect && Number(quizResponses[i].high) >= pctCorrect) {
				return {title: this.stripslashes(quizResponses[i].name), summary: this.stripslashes(quizResponses[i].summary)};
			}
		}
		return false;
	}
	this.nextQuestion = function () {
		currentQuestionID++;
		parent.adRefresh();
		this.showQuestion(currentQuestionID);
	}
	this.stripslashes = function (str) {
		if(str == null) return '';
		return str.split("\\").join("");
	}
	this.onFailLoadTemplate = function (transport) {
		var e = new Element('div', "Error: Couldn't load template file: " + templateURL);
		root.insert(e);
	}
	this.initialize = function () {
		var e = new Element('div').update('Initializing Quiz from Template:' + templateURL);
		root.insert(e);
		var req = new Ajax.Request(templateURL, {onSuccess: this.setTemplate.bind(this), onFailure: this.onFailLoadTemplate.bind(this)});
	}
	this.initialize();
}
function customiseInputs(formId, onClassRadio, offClassRadio, onRadioImage, offRadioImage) {
	if(!document.getElementById) return;

	var prettyForm = $(formId);
	if(!prettyForm) return;
	//onReset, reset radios to initial values
	prettyForm.onreset = function() { customiseInputs(formId, onClassRadio, offClassRadio, onRadioImage, offRadioImage); }
	
	//attach an easy to access .label reference to form elements
	addLabelProperties(prettyForm);
	var inputs = prettyForm.getElementsByTagName('input');
	for (var i=0; i < inputs.length; i++) {
			
		if( inputs[i].type=="radio" && inputs[i].label && onClassRadio && offClassRadio){
			//hide element
			inputs[i].style.position="absolute"; inputs[i].style.top = "-1000px";
			//initialise element
			inputs[i].label.className=offClassRadio;
			inputs[i].label.style.background = 'transparent url(\'' + offRadioImage + '\') no-repeat 0% 50%';
			//when the label is clicked, call toggleLabelStyle and toggle the label
			inputs[i].label.onclick = function (){ toggleLabelStyle(formId, this, onClassRadio, offClassRadio, onRadioImage, offRadioImage); return false; };
			//enable keyboard navigation
			inputs[i].onclick = function (){ toggleLabelStyle(formId, this.label, onClassRadio, offClassRadio, onRadioImage, offRadioImage); };
			//if the radio was checked by default, change this label's style to checked
			if(inputs[i].defaultChecked || inputs[i].checked){ toggleLabelStyle(formId, inputs[i].label, onClassRadio, offClassRadio, onRadioImage, offRadioImage); }
		}
		
		if( inputs[i].type=="radio" && inputs[i].label ){
			//Attach keyboard navigation
			if(!this.ie){ //IE has problems with this method
				//You could set these to grab a passed in class name if you wanted to
				//do something a bit more interesting for keyboard states. But for now the
				//generic dotted outline will do for most elements.
				inputs[i].label.style.margin = "1px";
				inputs[i].onfocus = function (){ this.label.style.border = "1px dotted #333"; this.label.style.margin="0px"; return false; };
				inputs[i].onblur  = function (){ this.label.style.border = "none"; this.label.style.margin="1px"; return false; };
			}
		}
	}
}
function initARC(formId, onClassRadio, offClassRadio, onRadioImage, offRadioImage) {
    var agt=navigator.userAgent.toLowerCase();
	var img1 = (new Image()).src = offRadioImage;
	var img2 = (new Image()).src = onRadioImage;
	
    // Browser Detection stuff
    this.major = parseInt(navigator.appVersion);
    this.ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    this.ie3    = (this.ie && (this.major < 4));
    this.ie4    = (this.ie && (this.major == 4) && (agt.indexOf("msie 4")!=-1) );
	this.iemac  = (this.ie && (agt.indexOf("mac")!=-1));

	if( !(this.iemac || ie3 || ie4) ){
		customiseInputs(formId, onClassRadio, offClassRadio, onRadioImage, offRadioImage);
	}
}
function addLabelProperties(f){
	if(typeof f.getElementsByTagName == 'undefined') return;
	var labels = f.getElementsByTagName("label"), label, elem, i = j = 0;
	
	while (label = labels[i++]){
		if(typeof label.htmlFor == 'undefined') return;
		elem = $(label.htmlFor);
		//elem = f.elements[label.htmlFor]; /* old method */
		
		if(typeof elem == 'undefined'){
			//no label defined, find first sub-input
			var inputs = label.getElementsByTagName("input");
			if(inputs.length==0){
				continue;
			} else {
				elem=inputs[0];
			}
		} else if(typeof elem.label != 'undefined') { // label property already added
			continue;
		} else if(typeof elem.length != 'undefined' && elem.length > 1 && elem.nodeName != 'SELECT'){
			for(j=0; j<elem.length; j++){
				elem.item(j).label = label;
			}
		}
		elem.label = label;
	}
} 
function toggleLabelStyle(formId, label, onClass, offClass, onRadioImage, offRadioImage){
	if(!document.getElementById || !label) return;
		
	var form = $(formId); //label.form;
	if(!form) return;
	
	//find radio associated with label (if in htmlFor form)
	if(label.htmlFor) {
		var e = $(label.htmlFor);
		
		if(e.type=="checkbox"){
			e.label.className = (e.label.className==onClass) ? offClass : onClass;
			e.checked = (e.label.className==onClass);
		} else if(e.type=="radio"){
			var radioGroup = form.elements[e.name];
			if(!radioGroup) return;
			
			for(var i=0; i<radioGroup.length; i++){
				if(radioGroup[i].label){
					radioGroup[i].label.className = ((radioGroup[i].checked=(radioGroup[i].id == e.id)) && radioGroup[i].label) ? onClass : offClass;
					radioGroup[i].label.style.background = 'transparent url(\'' + ((radioGroup[i].label.className == offClass) ? offRadioImage : onRadioImage) + '\') no-repeat 0% 50%';
				}
			}
		}
	}
}
