
var fatFactor     = 8.99; //calories/gram
var carbFactor 	  = 3.99; //calories/gram
var proteinFactor = 3.99; //calories/gram

//thisPct expects a percent in decimal form, less than 1 (.5 = 50%, pass .5 not a whole number percent like 50)
//nutrientType can be any of: 'carb' / 'protein' / 'fat' / 'alcohol'
function calcGramsFromPct(dailyCals, thisPct, nutrientType) {
	var convFactor = (nutrientType == 'carb'
				? carbFactor
				: ( nutrientType == 'protein'
					? proteinFactor
					: ( nutrientType == 'fat' ? fatFactor : 0 )
				  )
			);

	if (!convFactor) { return 0; }
	
	var theGrams = ((dailyCals * thisPct) / convFactor );
	//alert('Daily Calories: ' + dailyCals + '\nPercent: ' + thisPct + '\nNutrient: ' + nutrientType + '\n\nTOTAL GRAMS: ' + theGrams);
	return theGrams;//force illegal division by zero for unknown nutrient types
}


function updateFormNumbers(profileId) {
	if (!(profileId > 0)) {return 0;}
	
	eval('var total_calories = parseFloat(document.edit_nutritional_profile.p_'+profileId+'_total_calories.value);');
	
	
	
	var total_calories = parseFloat(eval('document.edit_nutritional_profile.p_'+profileId+'_total_calories.value'));
	if (!(total_calories > 0)) {return 0;}

	var calories_from_carbohydrate 	= parseFloat(eval('document.edit_nutritional_profile.p_'+profileId+'_calories_from_carbohydrate.value'));
	if (calories_from_carbohydrate) setGramsLayer('p_'+profileId+'_grams_from_carbs', calcGramsFromPct(total_calories, calories_from_carbohydrate / 100, 'carb') );
	if (calories_from_carbohydrate) setCalsLayer('p_'+profileId+'_cals_from_carbs', (total_calories * calories_from_carbohydrate / 100) );

		var calories_from_sugars 	= parseFloat(eval('document.edit_nutritional_profile.p_'+profileId+'_calories_from_sugars.value'));
		if (calories_from_sugars)   setGramsLayer('p_'+profileId+'_grams_from_sugars', calcGramsFromPct(total_calories, calories_from_sugars / 100, 'carb') );
		if (calories_from_sugars)   setCalsLayer('p_'+profileId+'_cals_from_sugars', (total_calories * calories_from_sugars / 100) );

	//var calories_from_fiber 		= parseFloat(document.edit_nutritional_profile.calories_from_fiber.value);
	//if (calories_from_fiber)   		setGramsLayer('grams_from_fiber', calcGramsFromPct(total_calories, calories_from_fiber / 100, 'carb') );
	var calories_from_protein 		= parseFloat(eval('document.edit_nutritional_profile.p_'+profileId+'_calories_from_protein.value'));
	if (calories_from_protein)  	setGramsLayer('p_'+profileId+'_grams_from_protein', calcGramsFromPct(total_calories, calories_from_protein / 100, 'protein') );
	if (calories_from_protein)  	setCalsLayer('p_'+profileId+'_cals_from_protein', (total_calories * calories_from_protein / 100) );

	var calories_from_total_fat 	= parseFloat(eval('document.edit_nutritional_profile.p_'+profileId+'_calories_from_total_fat.value'));
	if (calories_from_total_fat)   	setGramsLayer('p_'+profileId+'_grams_from_fat', calcGramsFromPct(total_calories, calories_from_total_fat / 100, 'fat') );
	if (calories_from_total_fat)   	setCalsLayer('p_'+profileId+'_cals_from_fat', (total_calories * calories_from_total_fat / 100) );
	
		var calories_from_saturated_fat 		= parseFloat(eval('document.edit_nutritional_profile.p_'+profileId+'_calories_from_saturated_fat.value'));
		if (calories_from_saturated_fat)   		setGramsLayer('p_'+profileId+'_grams_from_fat_saturated', calcGramsFromPct(total_calories, calories_from_saturated_fat / 100, 'fat') );
		if (calories_from_saturated_fat)   		setCalsLayer('p_'+profileId+'_cals_from_fat_saturated', (total_calories * calories_from_saturated_fat / 100) );
		
		var calories_from_monounsaturated_fat 	= parseFloat(eval('document.edit_nutritional_profile.p_'+profileId+'_calories_from_monounsaturated_fat.value'));
		if (calories_from_monounsaturated_fat)  setGramsLayer('p_'+profileId+'_grams_from_fat_monounsaturated', calcGramsFromPct(total_calories, calories_from_monounsaturated_fat / 100, 'fat') );
		if (calories_from_monounsaturated_fat)  setCalsLayer('p_'+profileId+'_cals_from_fat_monounsaturated', (total_calories * calories_from_monounsaturated_fat / 100) );
		
		var calories_from_polyunsaturated_fat 	= parseFloat(eval('document.edit_nutritional_profile.p_'+profileId+'_calories_from_polyunsaturated_fat.value'));
		if (calories_from_polyunsaturated_fat)  setGramsLayer('p_'+profileId+'_grams_from_fat_polyunsaturated', calcGramsFromPct(total_calories, calories_from_polyunsaturated_fat / 100, 'fat') );
		if (calories_from_polyunsaturated_fat)  setCalsLayer('p_'+profileId+'_cals_from_fat_polyunsaturated', (total_calories * calories_from_polyunsaturated_fat / 100) );
		
		var calories_from_trans_fat 			= parseFloat(eval('document.edit_nutritional_profile.p_'+profileId+'_calories_from_trans_fat.value'));
		if (calories_from_trans_fat)   			setGramsLayer('p_'+profileId+'_grams_from_fat_trans', calcGramsFromPct(total_calories, calories_from_trans_fat / 100, 'fat') );
		if (calories_from_trans_fat)   			setCalsLayer('p_'+profileId+'_cals_from_fat_trans', (total_calories * calories_from_trans_fat / 100) );
		
		//var calsPerFruitServing 			= parseFloat(eval('document.edit_nutritional_profile.p_'+profileId+'_calsPerFruitServing.value'));
		//if (calsPerFruitServing)   			setServingsLayer('p_'+profileId+'_numFruitServings', (total_calories / calsPerFruitServing) );
		
		updateAllCourseNumbers();
/*
	document.edit_nutritional_profile.FIBTG_targetLimit.value = parseFloat(document.edit_nutritional_profile.calories_from_fiber.value);
	document.edit_nutritional_profile.CHOLE_targetLimit.value = parseFloat(document.edit_nutritional_profile.cholesterol.value);
	document.edit_nutritional_profile.NA_targetLimit.value = parseFloat(document.edit_nutritional_profile.sodium.value);
	document.edit_nutritional_profile.K_targetLimit.value = parseFloat(document.edit_nutritional_profile.potassium.value);
	document.edit_nutritional_profile.CA_targetLimit.value = parseFloat(document.edit_nutritional_profile.calcium.value);
	document.edit_nutritional_profile.FE_targetLimit.value = parseFloat(document.edit_nutritional_profile.iron.value);
	document.edit_nutritional_profile.VITK_targetLimit.value = parseFloat(document.edit_nutritional_profile.vitamink.value);
	
		
	grams_from_carbs
	grams_from_sugars
	grams_from_fiber
	grams_from_protein
	grams_from_fat
	grams_from_fat_saturated
	grams_from_fat_monounsaturated
	grams_from_fat_polyunsaturated
	grams_from_fat_trans
	*/
}

function setGramsLayer(spanID, grams) {
	var tgs = '';
	if ( grams > 0 && grams < 1) {
		tgs = Math.round(grams*1000) + ' mg';
	} else {
		tgs = Math.round(grams) + ' grams';
	}

	document.getElementById(spanID).innerHTML = '&nbsp; &nbsp; (' + tgs + ')';
	eval('document.edit_nutritional_profile.' + spanID + '_value.value = ' + grams);
}
function setCalsLayer(spanID, cals) {
	var tgs = cals + ' calories';

	document.getElementById(spanID).innerHTML = '&nbsp; &nbsp; (' + tgs + ')';
	eval('document.edit_nutritional_profile.' + spanID + '_value.value = ' + cals);
}
function setServingsLayer(spanID, svgs) {
	var tgs = svgs + ' servings';

	document.getElementById(spanID).innerHTML = '&nbsp; &nbsp; (' + tgs + ')';
	eval('document.edit_nutritional_profile.' + spanID + '_value.value = ' + svgs);
}

function loadTemplate(templateID) {
	//alert(templateID);
	if (templateID > 0) {
		callAjax('?m=user&a=edit_nutritional_profile&print=1&taction=loadTemplateProfile&templateID=' + templateID, false, null);
		//alert('done');
	}
	return void(0); 
}

function updateCourseLimitTotal(profileId, nutCode, unit, dailyMassFieldName, textFieldEntryName, calorieType) {
	var total = 0;
	var tf = document.edit_nutritional_profile;
	var limit = 0;
	var color = '#7cc045'; //green

	var str = ' ( parseFloat(tf.p_' + profileId + '_' + nutCode + '_breakfastLimitValue.value) > 0 ? parseFloat(tf.p_' + profileId + '_' + nutCode + '_breakfastLimitValue.value) : 0 ) + '
				   +' ( parseFloat(tf.p_' + profileId + '_' + nutCode + '_lunchLimitValue.value) > 0 ?     parseFloat(tf.p_' + profileId + '_' + nutCode + '_lunchLimitValue.value) : 0 )  + '
				   +' ( parseFloat(tf.p_' + profileId + '_' + nutCode + '_dinnerLimitValue.value) > 0 ?    parseFloat(tf.p_' + profileId + '_' + nutCode + '_dinnerLimitValue.value) : 0 )  + '
				   +' ( parseFloat(tf.p_' + profileId + '_' + nutCode + '_snackLimitValue.value) > 0 ?     parseFloat(tf.p_' + profileId + '_' + nutCode + '_snackLimitValue.value) : 0 ) ';
	total = eval(str);
	
	if (unit == '%') {
		limit = 100;
		if (total < 100) {
			color = '#ffcc00'; //orange
		} else if (total > 100) {
			color = 'red'; //red
		}
	} else {
		limit = parseFloat(eval('tf.p_' + profileId + '_' + dailyMassFieldName + '.value'));
		if (total < limit) {
			color = '#ffcc00';
		} else if (total > limit) {
			color = 'red';
		}
	}
	color = '#ffcc00'; //turning off color stuff for now
	
	
	var command        = 'tf.p_' + profileId + '_' + nutCode + '_nutrientTargetType.options[tf.p_' + profileId + '_' + nutCode + '_nutrientTargetType.selectedIndex].value';
	var matchType      = eval(command);
	var matchDeviation = parseFloat(eval('tf.p_' + profileId + '_' + nutCode + '_nutrientTargetDeviation.value'));
	
	var limitDisplay = "";
	var dailyCalories = parseInt(eval('tf.p_' + profileId + '_total_calories.value'));
		
	var actualValue    = parseFloat(eval('tf.p_' + profileId + '_' + textFieldEntryName + '.value'));
	var actualMass     = 0;
	var actualCals     = 0;

	if (unit == '%' && nutCode != 'ENERC_KCAL') {
		actualCals 	   = ((actualValue/100)*dailyCalories); //(nutCode == 'ENERC_KCAL' ? 100 : actualValue))/100;
		if (calorieType != '') {
			actualMass 	   = calcGramsFromPct(dailyCalories, (actualValue/100), calorieType);
		}
	}
	
    //alert(unit + '//' + actualMass);
	actualCals = Math.round( actualCals );
	if (unit == 'servings') {
	    roundDigitsMultiplier = 10;
	    actualMass = actualMass;
	} else {
	    roundDigitsMultiplier = 1;
	    actualMass = Math.round( actualMass );
    }
    //alert(unit + '//' + roundDigitsMultiplier + '//' + actualMass);

	targetMass = generateRange(actualMass, matchType, matchDeviation);
	targetCals = generateRange(actualCals, matchType, matchDeviation);
	
	var meals = new Array();
		meals[0] = 'breakfast';
		meals[1] = 'lunch';
		meals[2] = 'dinner';
		meals[3] = 'snack';
	
	var meal;
	var bottomPct = 0;
	var topPct = 0;
	var bottomGrams = 0;
	var topGrams = 0;
	
	var bottomTarget = 0;
	var topTarget = 0;
	
	for(i=0; i < 4; i++) {
		if (unit == '%') {
			meal          = meals[i];
			
			bottomValue     = parseFloat(eval('tf.p_' + profileId + '_' + nutCode + '_'+meal+'Limit_bottom.value'));
			bottomValue     = ( bottomValue > 0 ? bottomValue : 0 );
			bottomPct 	    = ((bottomValue/100)*(nutCode == 'ENERC_KCAL' ? 100 : actualValue))/100;
			topValue        = parseFloat(eval('tf.p_' + profileId + '_' + nutCode + '_'+meal+'Limit_top.value'));
			topValue        = ( topValue > 0 ? topValue : 0 );
			topPct          = ((topValue/100)*(nutCode == 'ENERC_KCAL' ? 100 : actualValue))/100;
			
			bottomTarget += bottomValue;
			topTarget    += topValue;

			//alert(actualValue + '//' + bottomValue + '//' + topValue + '//' + bottomPct + '//' + topPct + '//' + calorieType);
			if (calorieType != '') {
				var bottomGrams = calcGramsFromPct(dailyCalories, bottomPct, calorieType);
				var topGrams    = calcGramsFromPct(dailyCalories, topPct, calorieType);
			} else {
				var bottomGrams = 0;
				var topGrams    = 0;
			}

			//alert(breakfastLimitBottomGrams + '//' + breakfastLimitTopGrams + '//' + parseFloat(eval('tf.' + nutCode + '_breakfastLimit_bottom.value')) + '//' + parseFloat(eval('tf.' + nutCode + '_breakfastLimit_top.value')) + '//' + actualValue + '//' + calorieType);
			//alert(nutCode + '\n' + bottomGrams + '//' + topGrams + '\n' + bottomPct + '//' + topPct);
			
			if (topGrams > 0 || bottomGrams > 0) {
				eval(' tf.p_' + profileId + '_' + nutCode + '_'+meal+'RangeCalcMass.value = \'(' + formatRange(new Array(Math.round( bottomGrams ), Math.round( topGrams ))) + ' grams)\'');
			} else {
				eval(' tf.p_' + profileId + '_' + nutCode + '_'+meal+'RangeCalcMass.value = \'\'');
			}
			if (bottomPct > 0 || topPct > 0) {
				eval(' tf.p_' + profileId + '_' + nutCode + '_'+meal+'RangeCalcCals.value = \'(' + formatRange(new Array(Math.round( (bottomPct)*dailyCalories ), Math.round( (topPct)*dailyCalories ))) + ' calories)\'');
			} else {
				eval(' tf.p_' + profileId + '_' + nutCode + '_'+meal+'RangeCalcCals.value = \'\'');
			}
		} else {
			meal         = meals[i];
			bottomTarget += parseFloat(eval('tf.p_' + profileId + '_' + nutCode + '_'+meal+'Limit_bottom.value'));
			topTarget    += parseFloat(eval('tf.p_' + profileId + '_' + nutCode + '_'+meal+'Limit_top.value'));
			
		}
	}
	
	limitDisplayValues = generateRange(actualValue, matchType, matchDeviation);
	limitDisplayValues[0] = Math.round(limitDisplayValues[0]);
	limitDisplayValues[1] = Math.round(limitDisplayValues[1]);
	limitDisplay = formatRange(limitDisplayValues);
	limitTargets = generateRange((unit == '%' ? 100 : actualValue), matchType, matchDeviation); //actualValue
	
	eval(' tf.p_' + profileId + '_' + nutCode + '_totalLimit_bottom.value = \'' + bottomTarget + '\'');
	eval(' tf.p_' + profileId + '_' + nutCode + '_totalLimit_top.value = \'' + topTarget + '\'');
	eval(' tf.p_' + profileId + '_' + nutCode + '_targetLimit_bottom.value = \'' + limitTargets[0] + '\'');
	eval(' tf.p_' + profileId + '_' + nutCode + '_targetLimit_top.value = \'' + limitTargets[1] + '\'');
	eval(' tf.p_' + profileId + '_' + nutCode + '_dailyLimitDisplay.value = \'('
				+ actualValue + (nutCode == 'ENERC_KCAL' ? ' Calories' : unit)
				+ ( actualMass > 0 ? ') (' + actualMass + ' g' : '' )
				+ ( actualCals > 0 && nutCode != 'ENERC_KCAL' ? ') (' + actualCals + ' Calories' : '' )
				+ ')\'');
	eval(' tf.p_' + profileId + '_' + nutCode + '_dailyLimitDeviationCalc.value = \'('
				+ limitDisplay + ' ' + (nutCode == 'ENERC_KCAL' ? 'Calories' : unit)
				+ ( (targetMass[0] > 0 || targetMass[1] > 0)
					? ') (' + formatRange(new Array(Math.round(targetMass[0]*roundDigitsMultiplier)/roundDigitsMultiplier, Math.round(targetMass[1]*roundDigitsMultiplier)/roundDigitsMultiplier)) + ' ' + ( unit == '%'
																														? ' g'
																														: ( nutCode != 'ENERC_KCAL' ? unit : '' )
																														)
					: '' )
				+ ( targetCals[0] > 0 || targetCals[1] > 0
					? ') (' + formatRange(new Array(Math.round(targetCals[0]*roundDigitsMultiplier)/roundDigitsMultiplier, Math.round(targetCals[1]*roundDigitsMultiplier)/roundDigitsMultiplier)) + ' Calories'
					: '' )
				+ ')\'');

	totalBox = document.getElementById('p_' + profileId + '_' + nutCode + '_totalLimit_bottom');
	totalBox.style.backgroundColor = color;
	totalBox = document.getElementById('p_' + profileId + '_' + nutCode + '_totalLimit_top');
	totalBox.style.backgroundColor = color;
	//alert('Limit: ' + limit + '\nTotal: ' + total + '\nColor: ' + color);
}

function formatRange(limits) {
	bottomLimit = limits[0];
	topLimit    = limits[1];
	
	var limitDisplay = "";
	if (bottomLimit > 0 && topLimit  > 0) {
		limitDisplay = bottomLimit + ' - ' + topLimit;
	} else if (bottomLimit > 0) {
		limitDisplay = bottomLimit + '+';
	} else if (topLimit  > 0) {
		limitDisplay = '<' + topLimit;
	}
	return limitDisplay;	
}
function generateRange(value, matchType, matchDeviation) {
	var bottomLimit = 0;
	var topLimit = 0;
	//alert(command + '\n' + matchType + '//' + matchDeviation);
	
	if (matchType == '<') {
		bottomLimit = (matchDeviation > 0 ? ( value - (value*(matchDeviation/100)) ) : 0 );
		topLimit    = value;
	} else if (matchType == '=') {
		bottomLimit = ( value - (value*(matchDeviation/2/100)) );
		topLimit    = ( value + (value*(matchDeviation/2/100)) );
	} else if (matchType == '>') {
		bottomLimit = value;
		topLimit    = (matchDeviation > 0 ? ( value + (value*(matchDeviation/100)) ) : 0 );
	}
	return new Array(bottomLimit, topLimit);
}

function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];
 
  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
} 

//this functions looks doo-doo-duh stupid, but i designed it to disable everything but the selected item...

function disableEnableRedGreenVerbage(nutrientCode, redOrGreenEnable) {
	var commands = '';
	if (redOrGreenEnable != 'green') {
		commands += "document.edit_nutritional_profile.{$key}_greenVerbage.disabled = true;\n";
		commands += "document.edit_nutritional_profile.{$key}_greenVerbage.style.backgroundColor = '#cccccc';\n"; 
		commands += "document.getElementById('{$key}_greenVerbage_formText').style.color = '#999999';\n\n"; 
	}
	if (redOrGreenEnable != 'red') {
		commands += "document.edit_nutritional_profile.{$key}_redVerbage.disabled = true;\n";
		commands += "document.edit_nutritional_profile.{$key}_redVerbage.style.backgroundColor = '#cccccc';\n"; 
		commands += "document.getElementById('{$key}_redVerbage_formText').style.color = '#999999';\n\n"; 
	}
	if (redOrGreenEnable != 'default') {
		commands += "document.getElementById('{$key}_defaultVerbage_formText').style.color = '#999999';\n\n"; 
	}

	if (redOrGreenEnable == 'green') {
		commands += "document.edit_nutritional_profile.{$key}_greenVerbage.disabled = false;";
		commands += "document.edit_nutritional_profile.{$key}_greenVerbage.style.backgroundColor = '#ffffff';\n"; 
		commands += "document.getElementById('{$key}_greenVerbage_formText').style.color = '#009900';\n\n";
	}
	if (redOrGreenEnable == 'red') {
		commands += "document.edit_nutritional_profile.{$key}_redVerbage.disabled = false;\n";
		commands += "document.edit_nutritional_profile.{$key}_redVerbage.style.backgroundColor = '#ffffff';\n"; 
		commands += "document.getElementById('{$key}_redVerbage_formText').style.color = '#cc0000';\n\n";
	}
	if (redOrGreenEnable == 'default') {
		commands += "document.getElementById('{$key}_defaultVerbage_formText').style.color = '#000000';\n\n";
	}
	
	if (commands != '') {
		commandsNew = commands.replace(/\{\$key\}/g, nutrientCode);
		if (nutrientCode == 'ENERC_KCAL') {
			//alert('Red or Green? ' + redOrGreenEnable + '\n\n' + commandsNew);
		}
		eval(commandsNew);
	}
}



