var command = {
	TVA: { NORMAL: 19.6, REDUIT: 5.5 },
	cats: {},
	port: [],
	addCategorie: function(idBaseCat, tva) {
		this.cats['c' + idBaseCat] = { tva: tva, prods: {} };
	},
	addProduit: function(idBaseProd, idBaseCat, poids, prix) {
		var cat = this.cats['c' + idBaseCat];
		if (cat) { cat.prods['p' + idBaseProd] = { poids: poids, prix: prix, nb: 0 }; }
		else { console.debug("command.addProduit : La cat\xe9gorie " + idBaseCat + " n'existe pas"); }
	},
	addPort: function(poids, frais) {
		this.port.push({ poids: poids, frais: frais });
	},
	majPrix: function(champ) {
		var res = /^(c\d+)(p\d+)$/.exec(champ.id);
		if (!res) {
			console.debug('command.majPrix : Identifiant HTML invalide : ' + champ.id);
			return;
		}
		var catId = res[1];
		var prodId = res[2];
		if (!this.cats[catId]) {
			console.debug('command.majPrix : Cat\xe9gorie invalide : ' + catId);
			return;
		}
		var prod = this.cats[catId].prods[prodId];
		if (!prod) {
			console.debug('command.majPrix : Produit invalide : ' + prodId);
			return;
		}
		var nb = parseInt(champ.options[champ.selectedIndex].value, 10);
		prod.nb = nb;
		if (!this.validePoidsTotal()) {
			while (--nb > 0) {
				prod.nb = nb;
				if (this.validePoidsTotal()) { champ.selectedIndex = nb; break; }
			}
			if (nb === 0) {	alert("Vous ne pouvez pas commander ce produit,\nla commande d\xe9passerait 10 Kg !"); }
			else { alert("Votre commande a \xe9t\xe9 ajust\xe9e,\ncar elle d\xe9passait 10 Kg !"); }
		}
		var prixCell = dojo.byId(champ.id + '_t');
		if (nb === 0) {
			champ.selectedIndex = 0;
			prod.nb = 0;
			prixCell.innerHTML = "\xa0";
		} else { prixCell.innerHTML = this.affPrix(prod.nb * prod.prix); }
		this.affTotaux();
		rucher.affErreur('');
	},
	validePoidsTotal: function() {
		var cpt = { poids: 0 };
		for (var catId in this.cats) { this.calculePoids(this.cats[catId], cpt); }
		if (cpt.poids / 1000 > command.port[command.port.length - 1].poids) { return false; }
		return true;
	},
	calculePoids: function(cat, cpt) {
		for (var prodId in cat.prods) {
			var prod = cat.prods[prodId];
			if (prod.nb > 0) { cpt.poids += prod.nb * prod.poids; }
		}
	},
	calculeFraisPort: function(poids) {
		if (poids == 0) { return 0; }
		var ports = command.port;
		for (var i = 0; i < ports.length; i++) { if (poids <= ports[i].poids) { return ports[i].frais; }}
		return -1;
	},
	affTotaux: function() {
		var total = this.calculeTotaux();
		var totalTtc = total.tvaNormal + total.tvaReduit;
		dojo.byId("prix_total").innerHTML = this.affPrix(totalTtc);
		var htNm = total.tvaNormal / (1 + command.TVA.NORMAL / 100);
		htNm = Math.round(htNm * 100) / 100;
		var tvaNm = total.tvaNormal - htNm;
		dojo.byId("tva_nm").innerHTML = this.affPrix(tvaNm);
		var htRd = total.tvaReduit / (1 + command.TVA.REDUIT / 100);
		htRd = Math.round(htRd * 100) / 100;
		var tvaRd = total.tvaReduit - htRd;
		dojo.byId("tva_rd").innerHTML = this.affPrix(tvaRd);
		dojo.byId("prix_ht").innerHTML = this.affPrix(htNm + htRd);
		var poidsKg = total.poids / 1000;
		dojo.byId("poids_total").innerHTML = this.affPrix(poidsKg);
		dojo.byId("poids_port").innerHTML = this.affPrix(poidsKg);
		var frais = this.calculeFraisPort(poidsKg);
		dojo.byId("frais_port").innerHTML = this.affPrix(frais);
		dojo.byId("total_ttc").innerHTML = this.affPrix(totalTtc + frais);
	},
	calculeTotaux: function() {
		var total = { tvaNormal: 0, tvaReduit: 0, poids: 0 };
		for (var catId in this.cats) { this.calculeTotal(this.cats[catId], total); }
		return total;
	},
	calculeTotal: function(cat, total) {
		for (var prodId in cat.prods) {
			var prod = cat.prods[prodId];
			if (prod.nb > 0) {
				if (cat.tva === command.TVA.NORMAL) { total.tvaNormal += prod.nb * prod.prix; }
				else { total.tvaReduit += prod.nb * prod.prix; }
				total.poids += prod.nb * prod.poids;
			}
		}
	},
	affPrix: function(valeur) {
		var arrondi = Math.round(valeur * 100) / 100;
		var aff = arrondi.toString();
		var point = aff.indexOf('.');
		if (point < 0) { return aff + ",00"; }
		if (aff.length - point - 1 === 1) { return aff.substring(0, point) + "," + aff.charAt(point + 1) + '0';	}
		else { return aff.substring(0, point) + "," + aff.substring(point + 1); }
	},
	submit: function() {
		var errMsg = '';
		var isCommand = false;
		for (var catId in this.cats) { if (isCommand = this.isCommandCat(this.cats[catId])) { break; }}
		if (isCommand) {
			if (!rucher.validSet('adr_nom')) { errMsg = "Entrez votre nom"; }
			else if (!rucher.validSet('adr_adr1')) { errMsg = "Entrez l'adresse de livraison"; }
			else if (!rucher.validSet('adr_cp')) { errMsg = "Entrez le code postal de livraison"; }
			else if (!rucher.validInt('adr_cp', 5)) { errMsg = "Entrez un code postal valide"; }
			else if (!rucher.validSet('adr_ville')) { errMsg = "Entrez la ville de livraison"; }
		} else { errMsg = 'Sélectionnez au moins un produit'; }
		if (errMsg) { rucher.affErreur(errMsg + " avant d'imprimer"); }
		else { dojo.byId('form_command').submit(); }
	},
	isCommandCat: function(cat) {
		for (var prodId in cat.prods) {	if (cat.prods[prodId].nb > 0) { return true; }}
		return false;
	},
	getPortFP: function() {
		var html = ['<div id="f_port" class="center"><h2>Frais de Port (Colissimo)</h2><table>'];
		html.push("<tr><td>jusqu'\xe0</td><td>frais</td></tr>");
		for (var i = 0; i < this.port.length; i++) {
			var o = this.port[i];
			html.push(((i % 2) ? '<tr>' : '<tr class="alternate">') + '<td>'  + o.poids + ' Kg</td>');
			html.push('<td>' + this.affPrix(o.frais) + ' &#8364;</td></tr>');
 		}
		html.push('</table></div>');
		return html.join('');
	}
}
dojo.addOnLoad(function() { dojo.byId("form_command").reset(); });
