// JavaScript Document
<!--

function selectUnits() {
  // get selection
  var selectInput = document.forms['unitsForm'].elements['units'];
  var units = selectInput.options[selectInput.selectedIndex].value;

  // show/hide divs
  var calculatorNames = ['imperial', 'metric'];
  for (var i = 0; i < calculatorNames.length; i++) {
    var calculator = document.getElementById(calculatorNames[i]);
    if (units == calculatorNames[i]) calculator.style.display = 'inline';
    else calculator.style.display = 'none';
  }

  // show warning
  invalidate();
}

function getFloat(formElements, elementName) {
  // to do ... trim before parse
  var result = parseFloat(formElements[elementName].value);
  if (isNaN(result)) result = 0;
  return result;
}

function calculate() {
  // get selection
  var selectInput = document.forms['unitsForm'].elements['units'];
  var units = selectInput.options[selectInput.selectedIndex].value;
  
  // calculate BMI
  var metres;
  var kilograms;
  var formElements = document.forms[units + 'Form'].elements;
  if ('imperial' == units) {
    metres = getFloat(formElements, 'heightFt') * 12 * 2.54 / 100;
    metres += getFloat(formElements, 'heightInches') * 2.54 / 100;
    kilograms = getFloat(formElements, 'weightLb') / 2.2;
  } else {
    metres = getFloat(formElements, 'heightMetres');
    metres += getFloat(formElements, 'heightCm') / 100.0;
    kilograms = getFloat(formElements, 'weightKg');
  }
  bmi = kilograms / (metres * metres);

  // check result
  if (isNaN(bmi) || 0 >= bmi) {
    document.getElementById('bmiProblem').style.display = 'inline';
    return false;
  }

  // update BMI description
  var bmiContent = 'Your BMI is ' + bmi.toFixed(1) + '.  ';
  if (20 > bmi || (25 <= bmi && 27 >= bmi)) {
    bmiContent += 'This BMI may be associated with health problems in some people.  A BMI between 20 and 25 is considered healthy.';
  } else if (20 <= bmi && 25 > bmi) {
    bmiContent += 'This is between 20 and 25, which is considered the healthy range for most people.';
  } else {
    // bmi > 27
    bmiContent += 'As BMI grows beyond 27, there is an increasing risk of developing health problems.';
  }
  document.getElementById('bmi').firstChild.data = bmiContent;
  document.getElementById('bmi').style.display = 'inline';
  
  // hide warning text
  validate();

  // don't go anywhere
  return false;
}

function invalidate() {
  // show warning text, if a calculation has been done already
  if ('inline' == document.getElementById('bmi').style.display) {
    document.getElementbyId('bmi').style.display = 'none';
    document.getElementById('invalidWarning').style.display = 'inline';
  }
}

function validate() {
  // hide warning text
  document.getElementById('invalidWarning').style.display = 'none';
  document.getElementById('bmiProblem').style.display = 'none';
}

-->