var QCM = function(template) {
	this.node = document.createElement("form");
	this.list = [];
	this.id = QCM.createId();
	this.messageTrue = template.hasAttribute("messageTrue") ? template.getAttribute("messageTrue") : "Bonne réponse !";
	this.messageFalse = template.hasAttribute("messageFalse") ? template.getAttribute("messageFalse") : "Faux !";
	this.result = new ExerciceResult();
	this.init(template);
};

QCM.count = 0;

QCM.createId = function() {
	return "qcm." + (++QCM.count);
};

QCM.prototype.init = function(template) {
	var self = this;
	this.node.className = "qcm";

	var table = document.createElement("table");
	this.node.appendChild(table);
	this.node.onsubmit = function() { self.onsubmit(); return false; };

	var choices = document.getChildsByTagName(template, "choice");
	for (var i = 0; i < choices.length; i++) {
		var item = new QCMItem(choices[i], this.id + "." + i);
		this.list.push(item);
		table.appendChild(item.node);
	}

	var button = document.createElement("button");
	button.appendChild(document.createTextNode("Ok"));
	this.node.appendChild(button);

	this.node.appendChild(this.result.node);
};

QCM.prototype.getWrongItem = function() {
	for (var i = 0; i < this.list.length; i++) {
		var item = this.list[i];
		if (item.value() != item.answer)
			return item;
	}
	return false;
};

QCM.prototype.onsubmit = function() {
	var wrongItem = this.getWrongItem();
	if (wrongItem) {
		this.result.set(false, wrongItem.msg ? wrongItem.msg : this.messageFalse);
	}
	else {
		this.result.set(true, this.messageTrue);
	}
};

var QCMItem = function(template, id) {
	this.node = document.createElement("tr");
	this.answer = template.getAttribute("result") == "true" ? true : false;
	this.msg = template.getAttribute("message");
	this.id = id;
	this.init(template);
};

QCMItem.prototype.init = function(template) {
	var td = document.createElement("td");
	this.node.appendChild(td);

	this.nodeInput = document.createElement("input");
	this.nodeInput.type = "checkbox";
	this.nodeInput.value = template.getAttribute("value");
	this.nodeInput.id = this.id;
	td.appendChild(this.nodeInput);

	var td = document.createElement("td");
	this.node.appendChild(td);

	var label = document.createElement("label");
	label.setAttribute("for", this.id); 
	td.appendChild(label);
	document.moveChilds(template, label);
};

QCMItem.prototype.value = function() {
	return this.nodeInput.checked;
};

