/**
 * Quiz Loader Class
 * All the logics which are required to display a quiz/quiz result
 *
 * @author Lee Boonstra, <lee.boonstra@efocus.nl>
 * @since 1.0, 28 jan, 2010
 * @copyright eFocus
 * @uses MooTools 1.2.4 More, <http://www.mootools.net>
 * @uses QuizApp, QuizView & ResultApp, ResultsView 
 */

var HashCookie = {};
var objQuiz = $H({});
var objScore = $H({});
var intQuestionIndex = 0;	

QuizLoader = new Class({
	Implements: [Options],
	options: {
		JSON_PATH: '../js/JSON/',
		IS_LOADED_FROM_INDEX: false
	},
	initialize: function(options){
		//fix IE6, but would break FF if Quiz=this.
		if(Browser.Engine.trident == true && Browser.Engine.version == 4){
			Quiz = this;
		}

		/*
		 * Initialize the JSON Quiz paths
		 * The JSON object is based on the url param id and random list 1 or 2 (quiz.html?id=1-2).
		 * When the quiz is restarted take the other quiz version.
		 */
		this.setOptions(options);
		if (this.options.IS_LOADED_FROM_INDEX == false) {
			this.strCurrentQuizId = this.getQuizId();
			var strHashCookieName = 'score-' + this.strCurrentQuizId;
			this.getQuiz(this.options.JSON_PATH + "quiz-" + this.strCurrentQuizId + ".json",strHashCookieName);
		}
	},
	getQuizId: function(){
		/*
		 * Get the QUIZ ID, based on URL parameter ID, and random version 1 or 2.
 		 * @returns {string} full quiz id
		 */
		var strQuizId = "1-1";
		var strQuizListId = getUrlParam("id");	
		
		if (strQuizListId.indexOf("-") != -1) {
			strQuizId = strQuizListId;
		} else if(strQuizListId != ""){
			strQuizId = strQuizListId + "-" + $random(1, 2);
		}
		
		return strQuizId;
	},
	getOtherQuizId: function(strCurrentQuizId){
		/*
		 * Get the other Quiz Id.
		 * Always when the Quiz version is created, random version 1 or 2 has
		 * been generated, when the quiz is restarted take the other version.
		 * So you'll never fill in the same quizlist twice.
		 * @param {String} current quiz id
		 * @return {String} quiz id with next version
		 */
		var intQuizListId = strCurrentQuizId.substring(0,1);
		var intQuizVersion = strCurrentQuizId.substring(2);
		
		if(intQuizVersion == 1){
			strCurrentQuizId = intQuizListId + "-2";
		} else {
			strCurrentQuizId = intQuizListId + "-1";
		}
		return strCurrentQuizId;
	},
	setOtherQuizPage: function(){
		/*
		 * Start the other Quiz version.
		 * Always when the Quiz version is created, random version 1 or 2 has
		 * been generated, when the quiz is restarted take the other version.
		 * So you'll never fill in the same quizlist twice.
		 */
		var strUrl = window.location.href;
		var strNewUrl = strUrl.split("?");
		var strNewUrl2 = strNewUrl[1].replace("#", "");
		/*
		 * Onduidelijk waar objQuiz.id vandaan komt, deze is niet correct
		 * Andere methode gebruiken om juiste id te verkrijgen
		 * @author A. Kuijer
		 */
		var strCurrentID = strNewUrl2.substring(3,strNewUrl2.length);
		var strNewQuizId = this.getOtherQuizId(strCurrentID);
		//window.location.href = strNewUrl[0] + "?id=" + strNewQuizId;
		window.location.href = strNewUrl[0] + "?id=" + strNewQuizId;
	},
	setQuizStartLinks: function(intQuizNum){
		/*
		 * Get QuizLinks.
		 * Check for Quiz Cookies, if there are quiz cookies and a whole quiz has been completed
		 * then offer links for viewing results and restarting.
		 * @param {int} number of the quiz list
		 */
		
		var myHashCookie1 = new Hash.Cookie('score-' + intQuizNum + '-1', { duration: 31 });
		var myHashCookie2 = new Hash.Cookie('score-' + intQuizNum + '-2', { duration: 31 });
		var elQuizLink = new Element('a');
		var elResultLink = new Element('a');

		elQuizLink.addClass("link");
		elQuizLink.addClass("start-quiz");

		elQuizLink.set("href","quiz.html?id=" + intQuizNum);
		elQuizLink.set("html","Doe de test");

		//set the result link
		if (myHashCookie1.get('answers') != null && myHashCookie1.get('answers').user.answer[14].input != "") {
			elResultLink.set("href","quiz.html?id="+ intQuizNum + "-1&results=true");
	
		} else if (myHashCookie2.get('answers') != null && myHashCookie2.get('answers').user.answer[14].input != ""){
			elResultLink.set("href","quiz.html?id="+ intQuizNum + "-2&results=true");
		}

		//set the result link and the restart link
		if (myHashCookie1.get('answers') != null && myHashCookie1.get('answers').user.answer[14].input != "" ||
			myHashCookie2.get('answers') != null && myHashCookie2.get('answers').user.answer[14].input != "") {
				elQuizLink.addClass("restart");
				elResultLink.addClass("link");
				elQuizLink.set("href","quiz.html?id=");
				elQuizLink.set("html","Doe de quiz opnieuw");
				elResultLink.set("html","Bekijk het resultaat");
				$$("div.quiz-links-" + intQuizNum).adopt(elResultLink);
		}
	
		$$("div.quiz-links-" + intQuizNum).adopt(elQuizLink);
		
		//event for the restart button
		$$('a.restart').addEvent('click', function(){
			myHashCookie1.empty();
			myHashCookie2.empty();
		});		
	},
	isResultPage: function(){
		if(getUrlParam("results")=="true"){
			Results = new ResultsView();
		}
	},
	getQuiz: function(strUrl,strId){
		/*
		 * JSON request for retrieving the Quiz JSON lists.
		 * On complete try to load score JSON from cookie or another JSON request
		 * @param {String} with URL to get the Quiz JSON from
		 * @returns void - ajax call
		 */
		var request = new Request.JSON({
			method: 'get',
			headers: {
				'Content-Type': 'text/json; charset=utf-8'
			},
			url: strUrl,
			onComplete: function(results) {
				if(results.quiz.stat == "ok"){
					//set Quiz Object;
					objQuiz.extend(results.quiz);					
					//load score from JSON object, if cookie exist load score from cookie
					HashCookie = new Hash.Cookie(strId, {
						duration: 31
					});

					if(HashCookie.get('answers') == null){
						this.getScore(this.options.JSON_PATH + "score.json");
					} else {					
						objScore.extend(HashCookie.get('answers'));
						//start the quiz
						this.setQuestionIndex();
					}
				};
			}.bind(this)
		});
		request.send();
	},
	getScore: function(strUrl){
		/*
		 * JSON request for retrieving the score JSON
		 * On Complete set the HashCookie.
		 * @param {String} with URL to get the Score JSON from
		 * @returns void - ajax call
		 */	
		var request = new Request.JSON({
			method: 'get',			
			url: strUrl,			
			onComplete: function(results) {
				if(results.answers.stat == "ok"){
					objScore.extend(results.answers);
					this.setCookie(objScore);
					//start the quiz
					this.setQuestionIndex();
				};
			}.bind(this)
		});
		request.send();
	},
	setCookie: function(obj) {
		/*
		 * Set the HashCookie for the first time.
		 * @param {object} to set in cookie
		 */
		HashCookie.set('answers', obj);
		objScore = HashCookie.get('answers');

	},
	extendCookie: function(obj) {
		/*
		 * Update HashCookie when already exist.
		 * @param {object} to set in cookie
		 */	
		HashCookie.extend('answers', obj);
		objScore = HashCookie.get('answers');
	},
	clearCookie: function(){
		HashCookie.empty();
	}
});	
