/*
 * JavaScript to recalculate food servings and quantities
 * without reloading the page.
 *
 * All the rows in these four arrays MUST match.
 *
 * NOTE: After changing this file, if it will have problems if browsers cache it,
 * it's necessary to rename this file and update the food.php - to prevent caching.
 */

// Array of nutrient fields
var nutrient_names = new Array(
	'calories',
	'kilojoules',
	'total_fat',
	'saturated_fatty_acids',
	'trans_fatty_acids',
	'cholesterol',
	'sodium',
	'total_carbohydrate',
	'fiber',
	'sugars',
	'protein',
	'calcium',
	'potassium',
    'alcohol'
);

var nutrient_acc = new Array(
	0,
	0,
	1,
	1,
	1,
	0,
	0,
	1,
	1,
	1,
	1,
	1,
	1,
    1
);

var daily_names = new Array(
	null,
	null,
	'total_fats_daily_pc',
	'saturated_fat_daily_pc',
	null,
	'cholesterol_daily_pc',
	'sodium_daily_pc',
	'total_carbohydrate_daily_pc',
	'fiber_daily_pc',
	null,
	null,
	null,
	null,
    null
);

var daily_req = new Array(
	null,
	null,
	65,
	20,
	null,
	300,
	2400,
	300,
	25,
	null,
	null,
	null,
	null,
    null
);

/*
 * A helper function that rounds to a certain number of decimal places
 */
function myRound(val, dps) {
	return Math.round(val * Math.pow(10, dps)) / Math.pow(10, dps);
}

/*
 * Checks that value is a number
 * From: http://www.codetoad.com/javascript/isnumeric.asp
 */
function isNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var NumPeriods = 0;
	var Char;

	// Check for single period case
	if (sText == '.') return false;

	for (i = 0; i < sText.length && IsNumber == true; i++) {
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
			break;
		}
		else if (Char == '.') NumPeriods++;
	}
	if (NumPeriods > 1) IsNumber = false;

	return IsNumber;
}

/*
 * Updates nutrients whenever quantity or serving is changed
 */
function updateNutrients() {
	var qty = document.frmfood.amount.value;
	// Check that they've typed a number
	if (isNumeric(qty)) {
		var size = serving_sizes[document.frmfood.unit.selectedIndex];
		if (type != 'S')
			var scale = qty * size / base;
		else
			var scale = qty;
		var i;
		var elem;

		// Update all nutrient fields
		for (i = 0; i < nutrient_names.length; i++) {
			// Update the nutrient field
			elem = document.getElementById(nutrient_names[i]);
			if (elem) {
				if (nutrient_bases[i] === null)
					elem.innerHTML = '-';
				else
					elem.innerHTML = myRound(nutrient_bases[i] * scale, nutrient_acc[i]);
			}
			// Check if there's a percentage field as well
			if (daily_names[i] !== null) {
				elem = document.getElementById(daily_names[i]);
				if (elem) {
					// Always use 0% instead of -
					elem.innerHTML = myRound((nutrient_bases[i] * scale / daily_req[i]) * 100, 0);
				}
			}
		}

		// Set total fat calories
		var total_fat_cals = 0;
		var total_fat_elem = document.getElementById('total_fat');
		if (total_fat_elem) {
			if (total_fat_elem.innerHTML == '-') total_fat_cals = 0;
			else total_fat_cals = total_fat_elem.innerHTML * 9;
		}

		elem = document.getElementById('total_fat_cals');
		if (elem) {
			elem.innerHTML = myRound(total_fat_cals, 0);
		}

		// Set total carb calories
		var total_carbohydrate_cals = 0;
		var total_carbohydrate_elem = document.getElementById('total_carbohydrate');
		if (total_carbohydrate_elem) {
			if (total_carbohydrate_elem.innerHTML == '-') total_carbohydrate_cals = 0;
			else total_carbohydrate_cals = total_carbohydrate_elem.innerHTML * 4;
		}

		elem = document.getElementById('total_carbohydrate_cals');
		if (elem) {
			elem.innerHTML = myRound(total_carbohydrate_cals, 0);
		}

		// Set protein calories
		var protein_cals = 0;
		var protein_elem = document.getElementById('protein');
		if (protein_elem) {
			if (protein_elem.innerHTML == '-') protein_cals = 0;
			else protein_cals = protein_elem.innerHTML * 4;
		}

		elem = document.getElementById('protein_cals');
		if (elem) {
			elem.innerHTML = myRound(protein_cals, 0);
		}

		// Set alcohol calories
		var alcohol_cals = alcohol_base * scale * 7;

		elem = document.getElementById('alcohol_cals');
		if (elem) {
			elem.innerHTML = myRound(alcohol_cals, 0);
		}
	}

	// update the 'addfoodtodiary' link for new quantity and measurement
	if (document.getElementById('addfoodtodiary')) {
		document.getElementById('addfoodtodiary').href = '/personal/mealplan/?fromdb=yes&food_id=' + document.frmfood.food_id.value + '&measurement_id=' + document.frmfood.unit.value + '&quantity=' + document.frmfood.amount.value + '&action=add_food&add_food_stage=3';
	}
	if (document.getElementById('printfood')) {
		document.getElementById('printfood').href = '/foods/print.php?food_id=' + document.frmfood.food_id.value + '&unit=' + document.frmfood.unit.value + '&amount=' + document.frmfood.amount.value;
	}

}
