var milkLiterSources = [];

$(document).ready(function() {
	addListener('#wm_125_units_month', 125, '#wm_125_auto_value');
	addListener('#wm_250_units_month', 250, '#wm_250_auto_value');
	addListener('#wm_350_units_month', 350, '#wm_350_auto_value');
	addListener('#wm_4L_units_month', 4000, '#wm_4L_auto_value');
	addListener('#cm_125_units_month', 125, '#cm_125_auto_value');
	addListener('#cm_250_units_month', 250, '#cm_250_auto_value');
	addListener('#cm_350_units_month', 350, '#cm_350_auto_value');
	addListener('#cm_4L_units_month', 4000, '#cm_4L_auto_value');
	
	milkLiterSources.push('#wm_125_auto_value');
	milkLiterSources.push('#wm_250_auto_value');
	milkLiterSources.push('#wm_350_auto_value');
	milkLiterSources.push('#wm_4L_auto_value');
	milkLiterSources.push('#wm_other_liters_month');
	milkLiterSources.push('#cm_125_auto_value');
	milkLiterSources.push('#cm_250_auto_value');
	milkLiterSources.push('#cm_350_auto_value');
	milkLiterSources.push('#cm_4L_auto_value');
	milkLiterSources.push('#cm_other_liters_month');
	
	$('#cm_other_liters_month').keyup(updateMilkLitersGrandTotal);
	$('#wm_other_liters_month').keyup(updateMilkLitersGrandTotal);
	
	updateMilkLitersGrandTotal();
});

function addListener(source, size, target) {
	$(source).keyup(function()  {
		calculateLiters($(source).val(), size, $(target));
	});
	calculateLiters($(source).val(), size, $(target));
}

function calculateLiters(value, millileters, target) {
	if(value == '' || value == null) {
		target.html('-');
	} else if(isNaN(parseFloat(value))) {
		target.html('invalid value');
	} else {
		target.html(value * millileters / 1000);
	}
	
	updateMilkLitersGrandTotal();
}

function updateMilkLitersGrandTotal() {
	var total = 0;
	var length = milkLiterSources.length;
	
	for(var i = 0; i < length; i++) {
		var source = $(milkLiterSources[i]);
		var value = source.html() || source.val();
		
		if(!isNaN(parseFloat(value))) {
			total += parseFloat(value);
		}
	}
	
	$('#total_auto_value').html(total);
}