/* ###############################################################################*/
/* Wintoets afname class
/* (c) 2007 - 2008 De Rode Planeet
/* Author Joris van Montfort <joris@.loft.nu>
/* ###############################################################################*/
//=================================================================================================
function Quiz(id) {
	this.id = id;
	this.questionDiv = $('quiz'+id);
	this.ajaxServer = 'scripts/quizajaxserver.php';

	// User info
	this._userId = null;
	this._userName = null;
	this._userGroup = null;

	// Options
	this.pathToRoot = '';
	this.allowBlankAnswers = false;

	// Memo vars
	this.questionId = '';
	this.memoCheckTimer = '';
	
	// Prelaoder
	this.preloaderHTML =  this.questionDiv.innerHTML;
}
//=================================================================================================
// Initializes the default view
Quiz.prototype.init = function () {
	// Set path to server
	this.ajaxServer = this.pathToRoot+this.ajaxServer;

	var pars = 'action=getStartScreen&quizId='+this.id;
	// Pass user info if this is complete
	if (this._userId && this._userName) {
		pars += '&userId='+this._userId+'&userName='+this._userName+'&userGroup='+this._userGroup;
	}

	new Ajax.Updater('quiz'+this.id,
					  this.ajaxServer,
					  { method: 'get',
					    parameters: pars,
					  	onFailure: this.reportError,
					  	evalScripts: true
					  });
}
//=================================================================================================
// Set user infor, use this method before init()
Quiz.prototype.setUserInfo = function (id, name, group) {
	this._userId = id;
	this._userName = name;
	this._userGroup = group;
}
//=================================================================================================
// Sends the loginform
Quiz.prototype.sendLogin = function () {
	var form = $('quizLoginForm'+this.id);
	if (validateMailform(form)) {
		var pars = 'action=doLogin&quizId='+this.id+'&'+Form.serialize(form);

		new Ajax.Updater('quiz'+this.id,
					  this.ajaxServer,
					  { method: 'get',
					    parameters: pars,
					  	onFailure: this.reportError,
					  	evalScripts: true
					  });
	}
}
//=================================================================================================
// Resets all quiz data for the current user
Quiz.prototype.reset = function () {
	var pars = 'action=reset&quizId='+this.id;
	new Ajax.Updater('quiz'+this.id,
					  this.ajaxServer,
					  { method: 'get',
					    parameters: pars,
					  	onFailure: this.reportError,
					  	evalScripts: true
					  });
}
//=================================================================================================
// Gets the next question in the quiz.
// The current question is sent to the server. Comments and hints will be if needed.
Quiz.prototype.nextQuestion = function () {
	/*var pars = 'action=getNextQuestion&quizId='+this.id+'&'+Form.serialize('quizForm'+this.id);*/
	var form = $('quizForm'+this.id);
	var pars = 'action=getNextQuestion&quizId='+this.id;
	var extraPars;
	var answerGiven = form.elements.length == 0 ? true : false;

	extraPars = this._encodeFormData(form);
	if (extraPars != '') {
		answerGiven = true;
	}
	pars += extraPars;

	if (!this.allowBlankAnswers && !answerGiven) {
		alert ('Kies eerst een antwoord.');
	}else {
		// Show preloader
		this.showPreloader();
		
		new Ajax.Updater('quiz'+this.id,
						  this.ajaxServer,
						  { method: 'get',
						    parameters: pars,
						  	onFailure: this.reportError,
						  	evalScripts: true
						  });
	}
}
//=================================================================================================
Quiz.prototype.previousQuestion = function () {
	var form = $('quizForm'+this.id);
	var pars = 'action=getPrevQuestion&quizId='+this.id;
	pars += this._encodeFormData(form);
	
	// Show preloader
	this.showPreloader();
	
	new Ajax.Updater('quiz'+this.id,
					  this.ajaxServer,
					  { method: 'get',
					    parameters: pars,
					  	onFailure: this.reportError,
					  	evalScripts: true
					  });
}
//=================================================================================================
// Encodes a form to querystring with escaped characters
Quiz.prototype._encodeFormData = function (form) {
	var pars = '';
	// Parameters are encoded using escape to prevent problems with special characters
	for (var i=0; i < form.elements.length; i++) {
		var element = form.elements[i];
		var type = element.type;
		if (type == 'radio' || type == 'checkbox' || type == 'select-one' || type == 'select-multiple' || type == 'text' || type == 'textarea') {
			if (element.name.match('answer')) {
				switch (type) {
					case 'radio':
					case 'checkbox':
						if (element.checked) {
							pars +='&'+element.name+'='+escape(element.value);
						}
					break;
					case 'select-multiple':
						// TODO: neat solution for multiple selects
						pars += '&'+Form.serialize('quizForm'+this.id);
					break;
					default:
						if (element.value != '') {
							pars +='&'+element.name+'='+escape(element.value);
						}
					break;
				}
			}
		}

	}
	return pars;
}
//=================================================================================================
// Displays a message within the quiz
Quiz.prototype.displayQuizMessage = function (title, txt, okAction) {
	// Shortcut reference to the document object
	var d = document;
	var agent = navigator.userAgent.toLowerCase();
	var mObj;

	// If the modalContainer object already exists in the DOM, bail out.
	if(d.getElementById("modalContainer")) return;

	// Create the modalContainer div as a child of the BODY element
	mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
	mObj.id = "modalContainer";
	 // make sure its as tall as it needs to be to overlay all the content on the page
	mObj.style.height = document.documentElement.scrollHeight + "px";

	// Create the DIV that will be the alert
	alertObj = mObj.appendChild(d.createElement("div"));
	alertObj.id = "alertBox";

	// IE lower than 7 doesn't treat position:fixed correctly, so this compensates for positioning the alert
	if(d.all && !window.opera && agent.indexOf("msie 7") == -1){
		alertObj.style.top = document.documentElement.scrollTop + "px";
		// Hide all selectboxes since they wil shine through on IE
		var selects = document.getElementsByTagName('select');
		for (var i=0; i < selects.length;i++){
			selects[i].style.visibility = 'hidden';
		}
	}else{
		// Set postition fixed for non IE browsers
		alertObj.style.position = 'fixed';
	}
	// Center the alert box
	alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";

	// Make draggable (scriptaculous)
	alertDrag = new Draggable('alertBox', {revert:false});

	// Create modalbox content
	messageHtml = '<h1>'+title+'</h1>';
	messageHtml+= '<p>'+unescape(txt)+'</p>'
	switch (okAction) {
		case 'next':
			messageHtml+= '<a href="#" id="closeBtn" onclick="quiz'+this.id+'.onQuizOkNext();return false;">Ok</a>';
		break;
		case 'prev':
			messageHtml+= '<a href="#" id="closeBtn" onclick="quiz'+this.id+'.onQuizOkPrev();return false;">Ok</a>';
		break;
		default:
			messageHtml+= '<a href="#" id="closeBtn" onclick="quiz'+this.id+'._removeQuizMessage();return false;">Ok</a>';
		break;
	}


	alertObj.innerHTML = messageHtml;

	// Set up a function that traces keystrokes
	document.onkeydown = function (e){
		var evt = window.event == null? e : window.event;
   		var key = (evt.charCode) ? evt.charCode: ((evt.keyCode) ? evt.keyCode:((evt.which) ? evt.which:0));
		if (key == 13){
			// Enter key
			onQuizMessageOk(goToNext);
		}else{
			// Disable other keys
			if (window.event){ // IE only
				window.event.keyCode = 505;
			}
			return false;
		}
	}
}
//=================================================================================================
// Fired when ok button is pressed and next question should be loaded
Quiz.prototype.onQuizOkNext = function () {
	this._removeQuizMessage();
	this.nextQuestion();
}
//=================================================================================================
// Fired when ok button is pressed and previous question should be loaded
Quiz.prototype.onQuizOkPrev = function () {
	this._removeQuizMessage();
	this.previousQuestion();
}
Quiz.prototype._unhideSelects = function () {
	// Unhide selects (hidden for IE)
	var selects = document.getElementsByTagName('select');
	for (var i=0; i < selects.length;i++){
		selects[i].style.visibility = 'visible';
	}
}
//=================================================================================================
// Helper function removes the quiz message from the DOM
Quiz.prototype._removeQuizMessage = function () {
	this._unhideSelects();
	alertDrag.destroy();
	document.onkeydown = '';
	document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}
//=================================================================================================
Quiz.prototype.addQuestionMemo = function () {
	var message = escape($F('memoTxt'));
	if (message == '') {
		alert('Geef een memo bericht op a.u.b.');
		return false;
	}

	// Send message
	var args = 'action=addQuestionMemo&questionId='+this.questionId+'&message='+message;
	var myAjax = new Ajax.Request(this.ajaxServer, {method: 'get', parameters: args, onComplete: updateQuestionMemoText()});

	$('memoTxt').value = '';
}
//=================================================================================================
Quiz.prototype.updateQuestionMemoText = function () {
	var pars = 'action=getQuestionMemo&questionId='+this.questionId;
	new Ajax.Updater('questionCurrentMemoTxt',this.ajaxServer, { method: 'get', parameters: pars, onFailure: this.reportError });
}
//=================================================================================================
Quiz.prototype.toggleQuestionMemo = function () {
	var visible = $('questionMemo').style.display == 'none';

	if (visible){
		Element.show('questionMemo');
		// Start updating memo text
		this.memoCheckTimer = setInterval('quiz'+this.id+'.updateQuestionMemoText()', 2000);
	}else{
		 Element.hide('questionMemo');
		 clearInterval(this.memoCheckTimer);
	}
	return false;
}
//=================================================================================================
Quiz.prototype.showPreloader = function () {
	this.questionDiv.update(this.preloaderHTML);
}
//=================================================================================================
Quiz.prototype.reportError = function (request) {
	alert('Er heeft zich een fout voorgedaan bij communicatie met de server.');
}

// ### UTILITY FUNCTIONS ##########################################################################
//=================================================================================================
var quizPopUp;
function openQuizPopUp(id, pathToRoot){
	var height = Math.round(0.75*screen.height);
	quizPopUp = window.open(pathToRoot+'/scripts/showquiz.php?id='+id,'quizPopup','resizable=yes,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,fullscreen=no,dependent=no,width=590,height='+height);
	quizPopUp.focus();
}
//=================================================================================================
function openCalcPopUp(){
	calcPopUp = window.open('scripts/calculator.html','calculator','resizable=no,location=no,menubar=no,scrollbars=no,status=no,toolbar=no,fullscreen=no,dependent=no,width=195,height=185');
	calcPopUp.focus();
}
