// JavaScript Document

var qz = document.getElementsByTagName('div');
var showit = '';
for (i=0;i<qz.length;i++) {
	if (qz[i].getAttribute('title')) {
		if (qz[i].getAttribute('title').substring(0,4) == 'quiz') {
			qname = qz[i].getAttribute('id');
			fname = qz[i].getAttribute('title').substring(5);
			
			eval('var '+ qname +'= new Quiz("'+fname+'", "'+qname+'")');
			showit += qname + '.show(1);';
		}
	}
}
eval(showit);

// constructor
function Quiz(fn, nm) {
	this.name = nm;

	// load xml file
	try {// Firefox, Opera 8.0+, Safari, IE7
		xmlReq = new XMLHttpRequest();
	} catch(e) {// Old IE
		try {
			xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(e) {
			alert ("Your browser does not support XMLHttpRequest or XMLHTTP!");
			return;  
		}
	}
	
	
//	var xmlReq = new window.XMLHttpRequest();
	xmlReq.open("GET", fn, false);
	xmlReq.send("");
	this.xDoc = xmlReq.responseXML;
	
	Quiz.prototype.show = function(id) {
		var html = this.getHtml(id, 0);
		var pid = id
		while (pid>1) {
			id = pid
			pid = this.findPid(pid);
			html = this.getHtml(pid, id) + html;
		}
		document.getElementById(this.name).innerHTML = '<table>'+html+'</table>';
	}
	
	Quiz.prototype.getHtml = function (id, goto) {
		var q = this.xDoc.getElementsByTagName("question");
		var html = '<tr>';
		for (i=0;i<q.length;i++) { // loop through questions
			if (q[i].getAttribute('id')==id) { // create html
				aNodes = q[i].getElementsByTagName("answer"); // get answers
				if (aNodes.length>0) {
					html += '<td style="width: 320px;">'+q[i].getElementsByTagName("text")[0].childNodes[0].nodeValue+'</td>'; // get question (text)
		
					html += '<td>';
					for (j=0;j<aNodes.length;j++) {
						if (aNodes[j].getAttribute('goto')==goto) {
								html += aNodes[j].childNodes[0].nodeValue + '<input name="'+this.name+id+'" type="radio" id="'+this.name+id+'_'+j+'" value="radio" checked="checked" />';
						} else {
								html += aNodes[j].childNodes[0].nodeValue + '<input name="'+this.name+id+'" type="radio" id="'+this.name+id+'_'+j+'" value="radio" onClick="'+this.name+'.show('+aNodes[j].getAttribute('goto')+');"/>';
						}
					}
					html += '</td>';
				} else {
						html += '<td colspan="2">'+q[i].getElementsByTagName("text")[0].childNodes[0].nodeValue+'</td>'; // get end result (text)
				}
			}
		}
		html += '</tr>'
		return html;
	}
	
	Quiz.prototype.findPid = function(id) {
		var q = this.xDoc.getElementsByTagName("question");
		for (i=0;i<q.length;i++) { // loop through questions
			aNodes = q[i].getElementsByTagName("answer"); 
			for (j=0;j<aNodes.length;j++) { // loop through answers and find corresponding goto
				if (aNodes[j].getAttribute('goto')==id)
					return q[i].getAttribute('id');
			}
		}
	}
}