Event.observe(window, 'load', function(event) {
	Sondage = Class.create({
		//
		initialize : function () {
			this._debug = true;
			this.url  = "sondages/getSondages.php";
			this._load();
		},
		// chargement des données du formulaire
		_load : function () {
			new Ajax.Request(this.url, {
				method     :'post',
				requestHeaders : {Accept: 'application/json'},
				onCreate   : function (){
					//alert('a request has been initialized');
				}, 
				onSuccess  : function (transport) {
					var json = transport.responseText.evalJSON(true);
					if ((typeof json == "undefined") || (json.length == 0)){
						// aucun sondage trouvé
						var divFeuille = $("bloc-feuilles");
						divFeuille.update("");
						var divReponse = new Element ('div', {'id': 'divReponse', 'class' : 'divReponse'});
						divReponse.update ("Pas de sondage disponible pour le moment");
						divFeuille.insert({bottom : divReponse});
					}
					else{
						questionnaire.load(json);
					}
				},
				onFailure  : function() { 
					alert('Something went wrong...');
					return;
				}
			});
		}
	});
	Questionnaire = Class.create({

		initialize : function () {},
		load : function (json) {
			
			this.form = "formSondage";
			this.url = "sondages/saveSondages.php";
			this.json = json;
			this.nbQuestion = this.json.length;
			this.currentQuestion = 1;
			this._create();
		},
		_create : function (){
			// génération du formulaire du sondage
			var liQuestion;
			var spanQuestion;
			var tagBr = new Element('br');
			var labelRadio;
			var btnRadio;
			var divQuestions = $('divUlContent');
			var ulContent = new Element ('ul', {'id': 'ulContent'});
			ulContent.addClassName('ulContent');
			var numQuestion;
		
			for (var i = 0; i < this.nbQuestion; i++)
			{
				var obj = this.json[i];
				numQuestion = i + 1;
				liQuestion = new Element("li", {"id" : "question_"+ numQuestion});
				liQuestion.addClassName('liQuestion');
				for (var key in obj)
				{
					var pattern = "artt_reponse";
					if (key.indexOf(pattern) != -1 && key != "artt_reponse_correcte"){
						var num = key.substr(pattern.length);
						// création du bouton radio
						btnRadio = new Element("input", {
							"name"  : "reponse_"+ numQuestion,
							"id"    : "reponse_"+ numQuestion,
							"type"  : "radio",
							"value" : num
						});
						btnRadio.addClassName('sondageRadioBox');
						liQuestion.insert({bottom : btnRadio});
						// création du label
						labelRadio = new Element("label", {"for"  : "reponse_"+ numQuestion}).update(obj[key]);
						liQuestion.insert({bottom : labelRadio});
						liQuestion.insert({bottom : "<br />"});
					}
					else{
						if (key == "artt_question"){
							// questions
							spanQuestion = new Element("span", {}).update(numQuestion + "/" + this.nbQuestion + " - "+obj[key]);
							liQuestion.insert({bottom : spanQuestion});	
							liQuestion.insert({bottom : "<br />"});
						}
					}
					ulContent.insert({bottom : liQuestion});
				}
				divQuestions.insert({bottom : ulContent});
			}
		},
		// gestion des changements de question
		change : function (direction){
			var transitionFX = Effect.Transitions.linear;
			var durationFX = 0.6;
			
			// on vérifie que le bouton radio est checké
			var radioOk   = false;
			var radioList = Form.getInputs(this.form,'radio','reponse_'+this.currentQuestion);
			for (var key in radioList){
				if (radioList[key].checked){
					radioOk = true;
				}
			}
			if (radioOk && direction == 0){
				// dernière étape envoi des données
				this._send();
				return;
			}
			if (radioOk || direction < 0)
			{
				if ($("msgError")){
					$("msgError").setStyle({display: 'none', visibility: 'hidden'});
				}
				// gestion du déplacement
				if (direction > 0){ // left
					if (this.currentQuestion < this.nbQuestion){
						this.currentQuestion += direction; 
						var moveFX = new Effect.Move($('divUlContent'), { x: -340, y: 0, mode: 'relative', transition : transitionFX, duration : durationFX });
					}
				}
				else{ // right
					if (this.currentQuestion > 1){
						this.currentQuestion += direction; 
						var moveFX = new Effect.Move($('divUlContent'), { x: 340, y: 0, mode: 'relative', transition : transitionFX, duration : durationFX  });
					}
				}
				// gestion de l'affichage des boutons
				if (this.currentQuestion == 1){
					$("btnLeft").setStyle({display: 'none', visibility: 'hidden'});
				}
				else{
					$("btnLeft").setStyle({display: 'block', visibility: 'visible'});
				}
				if (this.currentQuestion == this.nbQuestion){
					$("btnRight").setStyle({display: 'none', visibility: 'hidden'});
					// 
					$("btnSubmit").setStyle({display: 'block', visibility: 'visible'});
					$("btnSubmit").observe("click", function(){
						// vérification avant envoi
						questionnaire.change(0);
					});
				}
				else{
					$("btnRight").setStyle({display: 'block', visibility: 'visible'});
					$("btnSubmit").setStyle({display: 'none', visibility: 'hidden'});
				}	
			}
			else{
				if ($("msgError")){
					$("msgError").setStyle({display: 'block', visibility: 'visible'});
				}
			}
		},
		_send : function (){
			//  avant envoi des données
			var radioList;
			var params = {};
			params["total"] = this.nbQuestion;
			var num = 0;
			// Vérification et création de l'objet des paramêtres
			for (var i = 0; i < this.nbQuestion; i++)
			{
				num = i + 1;
				radioList = Form.getInputs(this.form,'radio','reponse_'+num);
				for (var key in radioList)
				{
					if (radioList[key].checked)
					{
						paramName = "reponse_q_"+num
						radioValue = radioList[key].value;
						params[paramName] = radioValue;
					}
				}
			}
			new Ajax.Request(this.url, {
				method     :'post',
				parameters : params,
				requestHeaders : {Accept: 'application/json'},
				onCreate   : function (){
					//alert('a request has been initialized');
				}, 
				onSuccess  : function (transport) {
					var response = transport.responseText;
					questionnaire._responseHandler(response);
				},
				onFailure  : function() { 
					//alert('Something went wrong...');
					return;
				}
			});
		},
		// gestion de la réponse
		_responseHandler : function(response){
			var divFeuille = $("bloc-feuilles");
			divFeuille.update("");
			var divReponse = new Element ('div', {'id': 'divReponse', 'class' : 'divReponse'});
			if (response == "ERROR"){
				divReponse.update ("Une erreur est survenue, veuillez nous excuser.");
			}
			else if (response == "EXISTS"){
				divReponse.update ("Vous avez d&eacute;j&agrave; particip&eacute; &agrave; ce sondage.<br />Seul votre premier vote a &eacute;t&eacute; pris en compte.");
			}
			else{
				var resultat = parseFloat(response); // forcer un flottant
				divReponse.update ("Merci de votre participation.<br />Votre r&eacute;sultat : " + resultat+ " % de bonnes r&eacute;ponses.<br><br>Pour vous perfectionner, <a class=\"vert\" href=\"" + racine + "16/demande-participation.html\">d&eacute;couvrez nos formations</a>");
			}
			divFeuille.insert({bottom : divReponse});
		}
	});
	if (sondageVar == "nok"){
		var questionnaire = new Questionnaire;
		var sondage = new Sondage;
		
		// Boutons
		if ($("btnSubmit")){
			$("btnSubmit").setStyle({display: 'none', visibility: 'hidden'});
		}
		if ($("btnLeft")){
			var btnLeft = $("btnLeft")
			
			btnLeft.observe("mouseover", function(event){
				var img = this.firstDescendant();
				img.writeAttribute ("src", racine + "medias/commun/btn-precedent-on.jpg");
			});
			btnLeft.observe("mouseout", function(event){
				var img = this.firstDescendant();
				img.writeAttribute ("src", racine + "medias/commun/btn-precedent.jpg");
			});
			btnLeft.observe("click", function(event){
				questionnaire.change(-1);
			});
			btnLeft.setStyle({display: 'none', visibility: 'hidden'});
		}
		if ($("btnRight")){
			var btnRight = $("btnRight")
			
			btnRight.observe("mouseover", function(event){
				var img = this.firstDescendant();
				img.writeAttribute ("src", racine + "medias/commun/btn-suivant-on.jpg");
			});
			btnRight.observe("mouseout", function(event){
				var img = this.firstDescendant();
				img.writeAttribute ("src", racine + "medias/commun/btn-suivant.jpg");
			});
			btnRight.observe("click", function(event){
				questionnaire.change(1);
			});
			btnRight.setStyle({display: 'block', visibility: 'visible'});
		}
	}
	else{
		var divFeuille = $("bloc-feuilles");
		divFeuille.update("");
		var divReponse = new Element ('div', {'id': 'divReponse', 'class' : 'divReponse'});
		divReponse.update ("Vous avez d&eacute;j&agrave; particip&eacute; &agrave; ce sondage.<br />Seul votre premier vote a &eacute;t&eacute; pris en compte.");
		divFeuille.insert({bottom : divReponse});
	}
});

