/* 
 * Functions to calculate Body Mass Index (BMI) and Basel Metabolic Rate (BMR)
 * Inputs come from forms, inputs and results stored in cookies so they can
 * initialize the forms next time a user visits.
 */

function StartUp (){
	var s;
	var i;

	document.bmiForm.bmiFeet.value = getCookie ('c_feet');
	document.bmiForm.bmiInches.value = getCookie ('c_inches');
	document.bmiForm.bmiWeight.value = getCookie ('c_weight');

	document.bmrForm.bmrAge.value = getCookie ('c_age');
	s = getCookie ('c_sex');
	if (s == '') s = 'bmrFemale';
	for (i = 0; i < document.bmrForm.bmrSex.length; i++)
		if (document.bmrForm.bmrSex[i].value == s)
			document.bmrForm.bmrSex[i].checked = true;

	s = getCookie ('c_target');
	if (s == '') s = 'Fill out the form above and press Calculate BMI to see your target.';
	document.getElementById ('bmi_target_id').innerHTML = s;

	s = getCookie ('c_bmr');

	if (s != '') displayBMR (s);
}

function displayBMR (bmr) {
	document.getElementById ('bmrNone').innerHTML = 'Daily calories: ' + bmrToStr (bmr * 1.2);
	document.getElementById ('bmrLight').innerHTML = 'Daily calories: ' + bmrToStr (bmr * 1.375);
	document.getElementById ('bmrModerate').innerHTML = 'Daily calories: ' + bmrToStr (bmr * 1.55);
	document.getElementById ('bmrHeavy').innerHTML = 'Daily calories: ' + bmrToStr (bmr * 1.725);
}

function getCookie (c_name) {
	if (document.cookie.length > 0)
	{
		c_start = document.cookie.indexOf (c_name + '=');
		if (c_start != -1)
	    {
		    c_start = c_start + c_name.length + 1;
		    c_end = document.cookie.indexOf (';', c_start);
		    if (c_end == -1) c_end = document.cookie.length;
		    return unescape (document.cookie.substring (c_start, c_end));
	    }
	}
	return '';
}

function setCookie (c_name, value) {
var exdate = new Date ();

	exdate.setDate (exdate.getDate () + 365);
	document.cookie = c_name + '=' + escape (value) + ';expires=' + exdate.toGMTString ();
}

function isDigit (num) {
	if (num.length > 1) {return false;}
	var string = "1234567890";
	if (string.indexOf (num) != -1) {return true;}
	return false;
	}

function isInteger (val) {
	for (var i = 0; i < val.length; i++) {
			if (!isDigit (val.charAt(i))){return false;}
		}
	return true;
	}

function isNumber (elem, helperMsg) {
	if (!isInteger (elem.value)) {
		alert (helperMsg);
		elem.focus ();
		return false;
		}
	return true;
	}

function LTrimAll (str) {
var i = 0;

	if (str == null) {return str;}
    while (str.charAt(i) == " " || str.charAt (i) == "\n" || str.charAt (i) == "\t")
        i++;
	return str.substring (i, str.length);
	}

function RTrimAll (str) {
var i = str.length - 1;

	if (str == null) {return str;}
    while (str.charAt (i) == " " || str.charAt (i) == "\n" || str.charAt (i) == "\t")
        i--;
	return str.substring (0, i + 1);
	}

function TrimAll (str) {
	return (LTrimAll (RTrimAll (str)));
	}

function isEmpty (elem, helperMsg) {
	elem.value = TrimAll (elem.value);
	if (elem.value.length == 0) {
		alert (helperMsg);
		elem.focus ();
		return true;
	}
	return false;
}

function checkSet (id, name, errMsg, cookie) {
	var elem;

	elem = document.getElementById (id);
	if (isEmpty (elem, errMsg)) return -1;
	if (!isNumber (elem, name + ' must be a whole number only.')) return -1;
	setCookie (cookie, elem.value);
	return parseInt (elem.value);
}

function calculateBMI(){
var s = '';
var i, f, w, b, j, min, max;

	f = checkSet ('feet_id', 'Height', 'Please enter your height in feet.', 'c_feet');
	if (f < 0) return false;
	i = checkSet ('inches_id', 'Inches', 'How many inches over ' + f + 'ft. are you?', 'c_inches');
	if (i < 0) return false;
	w = checkSet ('weight_id', 'Weight', 'Please enter your weight in pounds.', 'c_weight');
	if (w < 0) return false;

	i = f * 12 + i; // inches
	i = i * i; // squared
	b = (w * 703) / i; // weight in pounds divided by inches squared

	b = b + '';
	j = b.indexOf ('.');
	if (j != -1 && (b.length - j) > 2) b = b.substring (0, j + 2); // reduce to one decimal place
	if (b[b.length - 1] == '0') b = b.substring (0, b.length - 2); // remove .0 if decimal is zero

	min = i / 38; // min target weight assuming target BMI of 18.5
	min = min + '';
	j = min.indexOf ('.');
	if (j != -1) { min = min.substring (0, j); } // truncate to whole number

	max = i / 28.23 + 1; // max target weight assuming target BMI of 24.9, round up to give em a break :)
	max = max + '';
	j = max.indexOf ('.');
	if (j != -1) { max = max.substring (0, j); } // truncate to whole number

	s = 'Your BMI is ' + b + '. Normal weight for your height is between ' + min + ' and ' + max + '.';

	document.getElementById ('bmi_target_id').innerHTML = s;
	setCookie ('c_target', s);

    return true;
}

function bmrToStr (bmr) {
var x;

	bmr = bmr + '';
	x = bmr.indexOf ('.');
	if (x != -1) bmr = bmr.substring (0, x); // remove decimal
	x = bmr.length;
	if (x > 3) bmr = bmr.substring (0, x - 3) + ',' + bmr.substring (x - 3);
	return (bmr);
}

// BMR Calculation for men BMR = 66 + ( 6.23 x weight in pounds ) + ( 12.7 x height in inches ) - ( 6.8 x age in years )
// BMR Calculation for women 	BMR = 655 + ( 4.35 x weight in pounds ) + ( 4.7 x height in inches ) - ( 4.7 x age in years )
// If you get little to no exercise 	Daily calories needed= BMR x 1.2
// If you exercise lightly(1-3 days per week) 	Daily calories needed= BMR x 1.375
// If you exercise moderately (3-5 days per week) 	Daily calories needed= BMR x 1.55
// If you exercise heavily (6-7 days per week) 	Daily calories needed= BMR x 1.725-->
function calculateBMR () {
var a, f, i, w, x, bmr;

	f = checkSet ('feet_id', 'Height', 'Please enter your height in feet.', 'c_feet');
	if (f < 0) return false;
	i = checkSet ('inches_id', 'Inches', 'How many inches over ' + f + 'ft. are you?', 'c_inches');
	if (i < 0) return false;
	w = checkSet ('weight_id', 'Weight', 'Please enter your weight in pounds.', 'c_weight');
	if (w < 0) return false;

	a = checkSet ('age_id', 'Age', 'Please enter your age.', 'c_age');
	if (f < 0) return false;
	
	calculateBMI ();

	for (x = 0; x < document.bmrForm.bmrSex.length; x++)
		if (document.bmrForm.bmrSex[x].checked) {
			setCookie ('c_sex', document.bmrForm.bmrSex[x].value);
			if (document.bmrForm.bmrSex[x].value == 'bmrMale') {
				bmr = 66 + (6.23 * w) + (12.7 * (f * 12 + i)) - (6.8 * a);
			} else {
				bmr = 655 + (4.35 * w) + (4.7 * (f * 12 + i)) - (4.7 * a);
			}
		}

	setCookie ('c_bmr', bmr);
	
	displayBMR (bmr);

    return true;
}

