/**
 * @author kevin
 */

$(document).ready( function() {
	BMI.init();
});

var BMI = {
	inch2meter: 0.0254,
	lb2kilogram: 0.45359237,
	openingMessage: 'Please fill in the values to calculate your BMI.',
	init: function() {	
		$('#bmiSubmit').click( function(event) {
			event.preventDefault();
			var output = BMI.calculate();
			$('#message').fadeOut('slow', function() {
				$(this).attr( 'class', output[2] ).html( output[0] ).fadeIn('slow');
			} );
			$('#bmi_image').fadeOut( 'slow', function() {
				$(this).css({ backgroundPosition: output[1] }).fadeIn('slow');
			} );	
		} );
	},
	calculate: function() {
		var feet = parseInt( $('#hf').attr( 'value' ) );
		var inches = parseInt( $('#hi').attr( 'value' ) );
		var lbs = parseInt( $('#wp').attr( 'value' ) );
		
		if ( feet ) { $('#hf').val( feet ); }	
		else { $('#hf').val( '' ); }
		
		if ( inches || inches == 0 ) { $('#hi').val( inches ); }	
		else { $('#hi').val( '' ); }
			
		if ( lbs ) { $('#wp').val( lbs ); }	
		else { $('#wp').val( '' ); }
		
		if ( feet && ( inches || inches == 0 ) && lbs ) {
			var height = BMI.inch2meter * ( ( feet * 12 ) + inches );
			var bmi = ( BMI.lb2kilogram * lbs ) / ( height * height );
			bmi = bmi.toFixed(1);
			var message = 'Your BMI is ' + bmi;
			var bmiImgClass = '';
			if ( bmi <= 18.5 ) {
				bmiImgClass = '-228px';
			}
			else if ( bmi > 18.5 && bmi <= 24.9 ) {
				bmiImgClass = '-455px';
			}
			else if ( bmi > 24.9 && bmi <= 29.9 ) {
				bmiImgClass = '-683px';
			}
			else if ( bmi > 29.9 ) {
				bmiImgClass = '-911px';
			}
			var output = [ message, bmiImgClass, 'bmivalue' ];
			return output;
		}
		else {	
			var bmiImgClass = '';
			var output = [ BMI.openingMessage, bmiImgClass, '' ];
			return output;
		}
	}
};

