function pad(num,dg) {
  dg = ( dg == null )? 2 : dg;
  var padding = Math.pow(10, dg);
  var numStr = ""+num;
  var paddingStr = ""+padding;
  if (numStr.length >= paddingStr.length) return num;
  str = ""+(num + padding);
  return str.substring(str.length - dg);
}

function Item(name,pct) { this.name=name; this.pct=pct}

// if lhs == rhs the return value is 0
// if lhs > rhs the return value is 1
// if lhs < rhs the return value is -1 

  /*   1. If there is a tie score with Adrenal, then Adrenal is always Primary
       2. If there is a tie score with Liver, then Liver is always Primary unless Adrenal shows up, then it would be Adrenal.
       3. If there is a tie score between ovary and Thyroid, then Ovary is Primary */


function cmp(lhs, rhs) {                
  if(lhs.pct != rhs.pct) return (lhs.pct > rhs.pct)? 1:-1;                
  //if lhs.pct == rhs.pct
  if("Adrenal" == lhs.name) return  1; // Adrenal > rhs
  if("Adrenal" == rhs.name) return -1; // lhs < Adrenal            
  if("Liver"   == lhs.name) return  1; // Liver > rhs 
  if("Liver"   == rhs.name) return -1; // lhs < Liver 
  if("Ovary"   == lhs.name) return  1; // Ovary > rhs
  if("Ovary"   == rhs.name) return -1; // lhs < Ovary            
  return 0;
}

function calc(Thyroid,Adrenal,Liver,Ovary) {
  var theDiv = document.getElementById('result');
  if (theDiv==null) return;
  
  var text = "";


  arr = new Array(
    new Item("Thyroid",Thyroid),
    new Item("Adrenal",Adrenal),
    new Item("Liver",Liver),
    new Item("Ovary",Ovary)
  )
    
  // sort the array
  arr.sort(cmp);
  arr.reverse();

  theDiv.innerHTML='Primary Body Type: '+ arr[0].name +' ('+arr[0].pct+'%)'; 
  document.bodytypeForm.Contact0_PrimaryBodyType.value=arr[0].name;
  document.bodytypeForm.Contact0_SecondaryBodyType.value=arr[1].name;
  
}
