// Body Mass Index Assessment Tool
// Author: apatten@einsteinindustries.com

EI.namespace("EI.DocShop.Tools");

EI.DocShop.Tools.EvaluationBMI_es = function() {

	var _evaluationForm, _evaluationResultElt, _selectedItems, _BMI, _idealWeight, _weight, _feet, _inches, _height, _sex, _bmi_chart_row;

	var _evaluationResponse = ["<h3>Resultados de evaluación:</h3>"];

	var _evaluationResponseText = [ // TODO: translations needed
		'', // "A body mass index of less than <strong>18.5</strong> indicates that you are underweight for your height and need to increase your caloric intake. You may want to consider changing your diet and trying to increase muscle mass through proper exercise to boost your immunity and decrease your risk of future health problems.",
		'', // "A body mass index between <strong>18.5</strong> and <strong>25</strong> puts you at the ideal weight for your height. This BMI range is associated with good health and a longer than average life span. Most men and women look and feel their best at this body weight. Even if you fall within this range, it is important to stick to a proper diet and exercise regularly to maintain a healthy amount of body fat.",
		'', // "A body mass index between <strong>25</strong> and <strong>30</strong> means you are considered overweight for your height. At this BMI range, you are likely taking in more calories than you need to. This makes you statistically more vulnerable to health problems. Through healthy diet and regular exercise you can lower your weight, which in time will decrease your risk of illness and extend your overall life expectancy.",
		'', // "A body mass index between <strong>30</strong> and <strong>35</strong> means you are considered obese. Obesity is associated with significant health problems, including diabetes, heart disease, and high blood pressure. If you are not getting enough exercise and exceeding your recommended calories per day, your goal should be a significant change in lifestyle. If you have tried to lose weight and been unsuccessful, consider contacting your physician for advice.",
		'', // "A body mass index between <strong>35</strong> and <strong>40</strong> is considered very obese. At this BMI range, you are significantly overweight for your height and at risk for serious health problems, including heart disease. You can lower your risk of obesity-related illness drastically by exercising regularly and avoiding high calorie foods. You can also talk to your doctor to find out if you are a good candidate for bariatric surgery.",
		'' // "A body mass index exceeding <strong>40</strong> puts you at a dangerous weight for your height and indicates an unhealthy lifestyle. To reduce your risk of serious illness associated with morbid obesity, you need to make healthy living your priority. Your physician may recommend nutrition counseling to improve your diet and increased exercise, or determine if you are a good candidate for bariatric surgery."
	]

	var _errorMessage = ["<h3>Error:</h3>"];

	var _errorMessageText = {
		'invalidWeight'   : '<p>Por favor, ingrese un número para su <strong>peso</strong></p>',
		'invalidHeightFt' : '<p>Por favor, ingrese un número para <strong>las pulgadas</strong></p>',
		'invalidHeightIn' : '<p>Por favor, ingrese un número para <strong>las pies</strong></p>',
		'negativeNumber'  : '<p>Por favor, ingrese números positivos</p>',
		'invalidRangeIn'  : '<p>Las pulgadas tiene que ser un número entre 0 y 11.</p>',
		'invalidRangeFt'  : '<p>Por favor, ingrese un número realistico para su altura.</p>'
	}

	function initialize() {
		_evaluationForm = $('bmi_evaluation_form');
		if (_evaluationForm) {
			_evaluationForm.observe('submit', function(e){
				processEvaluation();
				Event.stop(e);
			});
		}
	}

	function getInput() {
		_weight = $F(_evaluationForm['weight']);
		_feet = $F(_evaluationForm['feet']);
		_inches = $F(_evaluationForm['inches']);
		
		if(_weight.length == 0 || _feet.length == 0 || _inches.length == 0) {
			return false;
		} else {
			_weight = Number(_weight);
			_feet = Number(_feet);
			_inches = Number(_inches);
			_sex = _evaluationForm.select('input:checked')[0].value;
			return true;
		}
	}
	
	function processEvaluation() {
		_evaluationResultElt = $('bmi_evaluation_results');
		resetMessages();
		
		if(getInput()) {
			validateFormInput();

			if(_errorMessage.length > 1){
				displayErrors();
			} else {
				_height = _feet * 12 + _inches;

				_BMI = calculateBMI();
				_idealWeight = calculateIdealWeight();
				displayResult();
			}
		}
	}

	function calculateIdealWeight(){
		if (_sex == 'male') {
			return (2.2046226 * (50.0 + (2.3 * (_height - 60))));
		} else {
			return (2.2046226 * (45.5 + (2.3 * (_height - 60))));
		}
	}

	function calculateBMI(){
		return (_weight / (_height * _height)) * 703;
	}

	function validateFormInput(){
		if(isNaN(_weight)) {
			_errorMessage.push(_errorMessageText['invalidWeight']);
		}
		if(isNaN(_feet)) {
			_errorMessage.push(_errorMessageText['invalidHeightFt']);
		}
		if(isNaN(_inches)) {
			_errorMessage.push(_errorMessageText['invalidHeightIn']);
		}
		if(_weight < 0 || _feet < 0 || _inches < 0) {
			_errorMessage.push(_errorMessageText['negativeNumber']);
		}
		if(_inches > 11) {
			_errorMessage.push(_errorMessageText['invalidRangeIn']);
		}
		if(_feet > 10) {
			_errorMessage.push(_errorMessageText['invalidRangeFt']);
		}
	}

	function displayResult(){
		if (_evaluationResultElt && _BMI) {
			_evaluationResultElt.removeClassName('hidden');
			_evaluationResponse.push("<div id='user_bmi'><span>" + _BMI.toFixed(2) + "</span><br />Resultadas del IMC</div>");
			if(_BMI < 18.5) {
				_evaluationResponse.push(_evaluationResponseText[0]);
				_bmi_chart_row = 'underweight';
			} else if (_BMI < 25) {
				_evaluationResponse.push(_evaluationResponseText[1]);
				_bmi_chart_row = 'normal';
			} else if (_BMI < 30) {
				_evaluationResponse.push(_evaluationResponseText[2]);
				_bmi_chart_row = 'overweight';
			} else if (_BMI < 35) {
				_evaluationResponse.push(_evaluationResponseText[3]);
				_bmi_chart_row = 'obese';
			} else if (_BMI < 40) {
				_evaluationResponse.push(_evaluationResponseText[4]);
				_bmi_chart_row = 'obese';
			} else {
				_evaluationResponse.push(_evaluationResponseText[5]);
				_bmi_chart_row = 'morbid';
			}
			
			_evaluationResponse.push('<p>Su peso ideal es: <strong>'+ _idealWeight.toFixed(0) +' libras</strong></p>');
			
			$(_bmi_chart_row).addClassName('active');
			_evaluationResultElt.update(_evaluationResponse.join(''));
			new Effect.Highlight(_evaluationResultElt, {startcolor:'#ffffff'});
		}
	}

	function displayErrors(){
		if (_evaluationResultElt) {
			_evaluationResultElt.removeClassName('hidden');
			_evaluationResultElt.update(_errorMessage.join(''));
			new Effect.Highlight(_evaluationResultElt, {startcolor:'#ff0000'});
		}
	}

	function resetMessages(){
		_evaluationResultElt.innerHTML = '';
		_evaluationResultElt.addClassName('hidden');
		
		if(_bmi_chart_row) {
			$(_bmi_chart_row).removeClassName('active');
		}		
		_errorMessage = [_errorMessage[0]];
		_evaluationResponse = [_evaluationResponse[0]];
	}
	
	document.observe('dom:loaded', initialize);

}();