// WHR Calculator
// Copyright - Property of DietandFitnessToday.com 2006
// No part of this document may be reproduced in any form
//

var bodyType= new Array(
	'Normal',
	'Medium risk of obesity problems',
	'High risk of obesity problems'
);

function calculateWHR(){

  var frm    = document.mainForm;
  var waistCm   = frm.waistCm.value;
  var waistInch = frm.waistInch.value;
  var hipCm     = frm.hipCm.value;
  var hipInch   = frm.hipInch.value;
  var sex       = frm.sex.options[0].text;

  var anum=/(^\d+$)|(^\d+\.\d+$)/;
  var wtNo = 0;
  var htNo = 0;

  // verify waist input 
  if (waistCm && waistInch){
    alert('Please enter a single waist measure in one of two rows');
    frm.waistCm.focus();
    return;
  }	

  if (waistCm){
    if (!anum.test(waistCm)){
      frm.waistCm.focus();
      alert('Please type a valid waist measure');
      return;
    }
  }else if(waistInch){
    if (!anum.test(waistInch)){
      frm.waistInch.focus();
      alert('Please type a valid waist measure');
      return;
    }else{
      waistCm = waistInch * 2.54;
    }
  }else{
      frm.waistCm.focus();
      alert('Please type a valid waist measure');
      return;
  }

  // verify hip input 
  if (hipCm && hipInch){
    alert('Please enter a single hip measure in one of two rows');
    frm.hipCm.focus();
    return;
  }

  if (hipCm){
    if (!anum.test(hipCm)){
      frm.hipCm.focus();
      alert('Please type a valid hip measure');
      return;
    }
  }else if(hipInch){
    if (!anum.test(hipInch)){
      frm.hipInch.focus();
      alert('Please type a valid hip measure');
      return;
    }else{
      hipCm = hipInch * 2.54;
    }
  }else{
      frm.hipCm.focus();
      alert('Please type a valid hip measure');
      return;
  }

  var whr =  waistCm / hipCm;
  var j;
  window.status = "test is " + sex;
  if (sex == "male"){
    if (whr < 0.9){
      j = 0;
    }else if (whr < 1){
      j = 1;
    }else{
      j = 2;
    }
  }else{
    if (whr < 0.8){
      j = 0;
    }else if (whr < 0.9){
      j = 1;
    }else{
      j = 2;
    }
  }
  frm.whr.value=sprintf(whr,2);
  frm.outputDescription.value = bodyType[j];
}

function clearAllFields(){
  var frm = document.mainForm;
  frm.waistCm.value='';
  frm.waistInch.value='';
  frm.hipCm.value='';
  frm.hipInch.value='';

  frm.whr.value='';
  frm.outputDescription.value='';
}

function sprintf(num, decimalNum){
  var tmpNum = num;

  // Return the right number of decimal places
  tmpNum *= Math.pow(10,decimalNum);
  tmpNum = Math.floor(tmpNum);
  tmpNum /= Math.pow(10,decimalNum);
  var tmpStr = new String(tmpNum);

  return tmpStr;
}

