var theBigTotal;

function bigTotal()
{
	theBigTotal = 0;
	$('.total-field').each(function() {
		//console.debug('Total : '+parseFloat($(this).val()));
		theBigTotal += parseFloat($(this).val());
	});
	$("#panier-total-box").html("TOTAL GÉNÉRAL HT = <b>"+theBigTotal.toFixed(2)+" €</b>");
}

function calculTotal(box_id)
{
	var totals = new Array();
	var globalTotal = 0;
	
	box_id = '#option-prix-box-'+box_id;
	
	// on récupère le produit_id etcreveneur_id
	var produit_id = $(box_id + " .produit-id-field").val();
	var revendeur_id = $(box_id + " .revendeur-id-field").val();
	var key = revendeur_id+'_'+produit_id;
	
	// on prend prix et prixoptions pour cette key
	var currentPrix = prix[key];
	var currentOptionsPrix = optionsPrix[key];
	
	var totalQuantity = 0;
	
	$(box_id+" .prix-line").each(function() {
		totalQuantity += parseInt($(this).find(".quantity-field").val());
	});
	
	var closestQuantity = 0;
	var closestPrix = 0;
	var diff;
	
	/*for each (var p in currentPrix) {
		diff = p.quantity-totalQuantity;
		if ( (diff <= 0) && (diff <= (p.quantity - closestQuantity)) ) {
			closestQuantity = p.quantity;
			closestPrix = p.prix;
		}
	}*/
	$.each(currentPrix, function () {
		diff = this.quantity-totalQuantity;
		if ( (diff <= 0) && (diff <= (this.quantity - closestQuantity)) ) {
			closestQuantity = this.quantity;
			closestPrix = this.prix;
		}
	});
	
	// si en dessous des quantités min, on n'a pas encore de prix, on prend le 1er
	if (closestQuantity == 0) {
		closestQuantity = currentPrix[0].quantity;
		closestPrix = currentPrix[0].prix;
	}
	
	$(box_id+" .prix-line").each(function() {
		
		var currentQuantity = parseInt($(this).find('.quantity-field').val());

		var total = closestPrix * currentQuantity;
		var prixOption = 0;
		var optionvalue_id;

		$(this).find(".options-values-field").each(function() {

			optionvalue_id = $(this).val();
			if (currentOptionsPrix[optionvalue_id][closestQuantity]) {
				prixOption = currentOptionsPrix[optionvalue_id][closestQuantity] * currentQuantity;
			} else {
				prixOption = 0;
			}

			total += prixOption;
		});

		totals.push(total);
		globalTotal += total;
	});

	$(box_id+" .total-line").each(function() {
		$(this).html( totals.shift().toFixed(2)+'€' );
	});
	$(box_id+" .total_prix").html(globalTotal.toFixed(2)+'€');
	$(box_id+" .total-field").val(globalTotal);
	
	bigTotal();
}
