// Determine weight metric from radio buttons
function getWeightMetricValue(form)
	{
	//initial
	weightMetric=0;

	for (var i=0; i < form.weightmetric.length; i++)
	   	{
	   	if (form.weightmetric[i].checked)
	   	   {
	   	   var weightMetric = form.weightmetric[i].value;
	   	   }
	   	}
	 		return weightMetric;
}

// Validates that a radio button is not empty
function validateEmptyRadioButton(elem, helperMsg)
{
	if(elem == 0)
	{
		alert(helperMsg);
		//elem.focus(); // set the focus to this input
		return false;
	}
	return true;
}

// Validates that a text field is not empty
function validateEmptyTextField(elem, helperMsg)
{
	if(elem.length == 0)
	{
		alert(helperMsg);
		//elem.focus(); // set the focus to this input
		return false;
	}
	return true;
}

// Validates that the text feild is numerical
function validateNumeric(elem, helperMsg)
{

	if(isNaN(elem))
	{
		alert(helperMsg);
		//elem.focus();
		return false;
	}
	else
	{
		return true;
	}
}

// This function calculates lbm 
function lbmCalc(weight,bodyfat,weightMetric)
{	
	//var inches=parseInt(inches);
	bodyfatpercent=bodyfat/100; // decimal format

	if (weightMetric=="pounds")
	{
       		bflbs=weight*bodyfatpercent;
        	lbmlbs=weight-bflbs;
		bfklgs=bflbs/2.2;
		lbmklgs=lbmlbs/2.2;
	}
	else
	{
		bfklgs=weight*bodyfatpercent;
		lbmklgs=weight-bfklgs;
		bflbs=bfklgs*2.2;
                lbmlbs=lbmklgs*2.2;
	}

	// round
	bflbs=Math.round(bflbs);
	lbmlbs=Math.round(lbmlbs);
	bfklgs=Math.round(bfklgs);
	lbmklgs=Math.round(lbmklgs);

	return bflbs;
	return lbmlbs;
	return bfklgs;
	return lbmklgs;
}

//Main
function calculateLBM(form) 
{
	// variables start here 
	var weight=form.weight.value;
	var bodyfat=form.bodyfat.value;
	var weightMetric=getWeightMetricValue(form);
	//variables end here 

	// start validation of the form here 
	validateEmptyRadioButton(weightMetric,'Please choose a weight metric.');
	validateEmptyTextField(weight,'Please enter your weight.');
	validateEmptyTextField(bodyfat,'Please enter your body fat.');
	validateNumeric(weight,'Please only enter numbers in the fields.');
	validateNumeric(bodyfat,'Please only enter numbers in the fields.');
	//end validation of the form here
	
	// calculate lbm
	lbmCalc(weight,bodyfat,weightMetric);

	form.bflbs.value = bflbs;
	form.bfklgs.value = bfklgs;
	form.lbmlbs.value = lbmlbs;
	form.lbmklgs.value = lbmklgs;
}

