/* Définition des variables */
var myQuizz = null;

/* Déclaration de la classe Quizz */
var Quizz = Class.create();
Quizz.prototype = {  
	//Déclaration des variables
	quizzXmlFile : "includes/quizz/quizz.xml",
	quizzXmlDoc : null,
	quizzContainerName : "quizzContainer",
	submitButtonId : "submitQuizzResponse",
	questionsList : [],
	questionsSelection : [],
	questionActiveOffset: null,
	questionOffset: 0,
	nbAnswer: 0,
	nbTotalAnswer: 5,
	nbCorrectAnswer: 0,
    /**
     * Constructeur
     */
    initialize: function() { 
        this.loadXmlQuestions();
    },
    /**
     * Constructeur
     */
    loadXmlQuestions: function() { 
		
		var obj = this;
		if (window.ActiveXObject) {  
		    this.quizzXmlDoc = new ActiveXObject("Microsoft.XMLDOM");   
		    this.quizzXmlDoc.onreadystatechange = function () {
		        if (obj.quizzXmlDoc.readyState == 4) obj.createQuestionsList();
		    };
		}
		else if (document.implementation && document.implementation.createDocument) {  // Gestion pour firefox
		    
		    this.quizzXmlDoc = document.implementation.createDocument("", "", null);
		    this.quizzXmlDoc.onload = function() { 
                        //alert ('ok2');
                        obj.createQuestionsList();
                }
		}
		else {
		    alert('Your browser can\'t handle this script');
		    return;
		}
        this.quizzXmlDoc.load(this.quizzXmlFile);
    },
    /**
     * createQuestionsList
     * Crée un tableau de question a partir du xml
     */
    createQuestionsList: function() {
        var xQuizz = this.quizzXmlDoc.getElementsByTagName('question');
		//Remplissage du tableau de questions
		for (var i=0; i < xQuizz.length; i++) {
		  var infos = [];
		  infos['question'] = xQuizz[i].firstChild.nodeValue;
		  infos['choix1'] = xQuizz[i].getAttribute("choix1");
		  infos['choix2'] = xQuizz[i].getAttribute("choix2");
		  infos['choix3'] = xQuizz[i].getAttribute("choix3");
		  infos['choix4'] = xQuizz[i].getAttribute("choix4");
		  infos['reponse'] = xQuizz[i].getAttribute("reponse");
		  this.questionsList[i] = infos;
		}
		this.chooseQuestions();
    },
    /**
     * chooseQuestion
     * Effectue le choix de la question aleatoirement
     */
    chooseQuestions: function() {
        var nbChoice = this.questionsList.length;
        var tirage = new Array;
        nombres="";
        for (i=0 ;i<nbChoice ;i++)
        {
            nombre = Math.floor(Math.random() * nbChoice);
            tirage[i]= nombre;
            for (t=0 ; t<i ;t++){
              if (tirage[t] == nombre) {
                 i=i-1;
              }
            }
        }
        for (i=0 ;i < tirage.length ;i++) {
            this.questionsSelection[i] = this.questionsList[tirage[i]];
        }
        this.displayQuestion(this.questionOffset);
        //this.displayRegisterForm();
    },
    /**
     * displayQuestion
     * Affiche le contenu de la question
     */
    displayQuestion: function(offset) {
        var obj = this;
        parametres = $H({ section: 'displayQuestion', 
                           c1: obj.questionsSelection[offset]['choix1'], 
                           c2: obj.questionsSelection[offset]['choix2'],
                           c3: obj.questionsSelection[offset]['choix3'],
                           c4: obj.questionsSelection[offset]['choix4'],
                           q: obj.questionsSelection[offset]['question'],
                           id: offset,
                           nbr: obj.nbAnswer,
                           nbq: obj.nbTotalAnswer
                            }).toQueryString()
                           
        new Ajax.Updater(obj.quizzContainerName, "includes/quizz/controller/switch.php",
	    {
	        method:'post',
	        parameters: parametres,
	        onLoaded:function (requester) {
	            
	        },
	        onComplete:function (requester) {
	           obj.addSubmitListener();
	        }       
	    });
    },
    /**
     * addSubmitListener
     * Ecouteur pour la soumission d'une reponse
     */
    addSubmitListener: function() {
       var form = $('quizzForm');
       //addListener(form, 'submit', checkForm);
       Event.observe('quizzForm', 'submit', this.validateForm, true);
    },
    /**
     * validateForm
     * Verifie la validité de la reponse
     */
    validateForm: function(e) {
       Event.stop(e);
       var check = false;
       if ($('answer-1').checked) {
            check = true;
       }
       if ($('answer-2').checked) {
            check = true;
       }
       if ($('answer-3')) {
            if ($('answer-3').checked) {
	            check = true;
	       }
       }
       if ($('answer-4')) {
            if ($('answer-4').checked) {
                check = true;
           }
       }
       if (!check) {
            alert ('Vous devez choisir une reponse');
       }
       else {
            /*$('answer-1').disabled = true;
            $('answer-2').disabled = true;
            $('answer-3').disabled = true;*/
            $('quizzForm').disabled = true;
            myQuizz.submitForm();
       }
    },
    /**
     * submitForm
     * Soumet la reponse
     */
    submitForm: function() {
        var questionId = $('answer-id').value;
        var reponseJuste = this.questionsSelection[questionId]['reponse'];
        var reponse = 0;
        if ($('answer-1').checked) reponse=1;
        else if ($('answer-2').checked) reponse=2;
        else if ($('answer-3').checked) reponse=3; 
        if (reponseJuste == reponse) {
          this.nbCorrectAnswer++;
        }
        else {
            //alert ('tout faux');
        }
        this.questionOffset++;
        this.nbAnswer++;
        if (this.nbAnswer == this.nbTotalAnswer) {
            //this.saveResults();
            this.displayRegisterForm();
        }
        else {
            this.displayQuestion(this.questionOffset);
        }
    },
    /**
     * displayRegisterForm
     * Affiche le formulaire d'identification
     */
    displayRegisterForm: function() {
        var obj = this;
        new Ajax.Updater(obj.quizzContainerName, "includes/quizz/controller/switch.php",
        {
            method:'post',
            parameters:'section=displayRegisterForm',
            onLoaded:function (requester) {},
            onComplete:function (requester) {
               myFormChecker = new FormChecker('registerQuizzForm', 'myQuizz.submitRegisterForm();');
            }       
        });
    },
     /**
     * saveResults
     * Sauvegarde les résultats dans la base de données
     */
    saveResults: function() {
        alert ('resultats: '+this.nbCorrectAnswer+'/'+this.nbTotalAnswer+'');
    },
    /**
     * displayTirage
     * Affiche le tirage au sort
     */
    displayTirage: function() {
        var obj = this;
        new Ajax.Updater(obj.quizzContainerName, "includes/quizz/controller/switch.php",
        {
            method:'post',
            parameters:'section=displayTirage',
            onLoaded:function (requester) {},
            onComplete:function (requester) {
               //myFormChecker = new FormChecker('registerQuizzForm', 'myQuizz.submitRegisterForm();');
            }       
        });
    },
    /**
     * submitRegisterForm
     * Soumet le formulaire d'identification
     */
    submitRegisterForm: function() {
        var obj = this;
        params = Form.serialize('registerQuizzForm');
        new Ajax.Updater(obj.quizzContainerName, 'includes/quizz/controller/switch.php',
        {
            method:'post',
            parameters:'section=saveRegisterForm&nbr='+obj.nbCorrectAnswer+'&nbq='+obj.nbTotalAnswer+'&'+params,
            onLoaded: function(requester) {},
            onComplete: function(requester) {
                /*new Ajax.Updater(obj.quizzContainerName, 'includes/quizz/controller/switch.php',
                {
                   method:'post',
                   parameters:'section=displayResults&nbr='+obj.nbCorrectAnswer+'&nbq='+obj.nbTotalAnswer+''
                });*/
            }
        });
    }
}


Event.observe(window, 'load', initQuizz, true);
//addListener(window, 'load', initQuizz);

function initQuizz() {
    myQuizz = new Quizz();
}


function addListener(element, baseName, handler) {
    if (element.addEventListener)
        element.addEventListener(baseName, handler, false);
    else if (element.attachEvent)
        element.attachEvent('on' + baseName, handler);
} // addListener
