var mtr_per_sec;
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}
function isblank(s){
  //function checks for whitespace in input
  for(var i=0;i<s.length;i++){
    var c=s.charAt(i);
    if((c != ' ') && (c != '\n') && (c != '')){
	  return false;
	}
  }
  return true;
}
function verify(f){
  //f.height_type[1].checked;
  var empty_fields="";
  var type_error="";
  var msg;
  for(var i=0;i<f.length;i++){
    var e=f.elements[i];
	//does the optional object exist for the element, test this by comparing e.optional to null
	if(e.optional != null){
	  //does e require a value? i.e. is optional false?
	  if(!e.optional){
	    //if we get to here, then it's not an optional field
		//so test to see if there's a value
	    if((e.value==null)||(e.value=='')||isblank(e.value)){
		  //here if no value is found
	      empty_fields += "\n" + e.name + " is empty";
		  //exit out of the loop, bypassing the next test
		  continue;
	    }        //end of if((e.value==null)||(e.value=='')||isblank(e.value))
	  }          //end of if(!e.optional)
	}            //end of if(e.optional != null)
	//here if previous test passed, now test the datatype
	//does the datatype object exist for the element, test this by comparing e.datatype to null
	if(e.datatype != null){
	  //which datatype should the element be?
	  switch(e.datatype){
	    case 1:
		  alert(typeof e.value);
		  break;
		case 2:
		  //the value should be an integer, first check to see that it's Not A Number
		  if(isNaN(parseFloat(e.value))){
		    type_error += "\n" + e.name + " is not a number\n";
			continue;
		  }
		  //here if the first test is passed, now see if it's a float
		  if(parseFloat(e.value)%1) type_error += "\n" + e.name + " is not a whole number\n";
		  break;
		case 3:
		  alert(typeof e.value);
		  break;
		default:
		  break;
	  }
	}
  }              //end of for(var i=0;i<f.length;i++)
  if(!empty_fields && !type_error){
    return true;
  }else{
    msg ="_______________________________________________________\n\n";
	msg+="The calculation was not performed because of the following error(s):\n";
	msg+="Please correct the error(s) and re-submit.\n";
	msg+="_______________________________________________________\n";
	if(empty_fields){
	  msg+=empty_fields;
	  if(type_error) msg+="\n\n";
	}
	msg+=type_error;
	alert(msg);
	return false;
  }
}
function calculate_BMI(f){
  
  var height;
  var weight;
  var BMI;
  if(!f.height_type[0].checked){
    height = convert_inches_to_cm(f.height.value);
  }else{
    height = f.height.value;
  }
  //convert height from cm to m
  height = height/100;
  if(!f.weight_type[0].checked){
    weight = convert_lb_to_kg(f.weight.value);
  }else{
    weight = f.weight.value;
  }
  BMI = weight/(Math.pow(height,2));
  return BMI;
  
}
function convert_inches_to_cm(h){
  return h*2.54;
}
function convert_lb_to_kg(w){
  return w*0.4535924;
}
function calculate_maxhr(f){
  return Math.round(209-(f*0.9));
}
function calculate_maxhr2(f){
  return Math.round(209-(f*0.7));
}
function calculate_KARV(f){
  var hmax=f.MAX_HR.value;
  var hmin=f.MIN_HR.value;
  var pc=f.KARV_PC.value;
  var karv=((hmax-hmin)/100)*pc;
  karv=karv+parseFloat(hmin);
  return Math.round(karv);
}
function calculate_pace(f){
  var ttl_dist;
  var ttl_time;
  //Do we have any split times?
  if(f.fourh_m_split.value || f.fourh_s_split.value || f.onek_m_split.value || f.onek_s_split.value || f.onem_m_split.value || f.onem_s_split.value){
    //Do we have all the split times
    if(f.fourh_m_split.value && f.fourh_s_split.value && f.onek_m_split.value && f.onek_s_split.value && f.onem_m_split.value && f.onem_s_split.value){
	  //move on to the next check
	}else{
	  calculate_splits(f);
	}
  }else{
    mtr_per_sec=0;
  }
  //Does a value for the overall distance been entered
  if(n=f.pace_dist.value){
    if(f.pace_dist_unit[0].checked){
	  ttl_dist=n*1609.344;
	}else if(f.pace_dist_unit[1].checked){
	  ttl_dist=n*1000;
	}else if(f.pace_dist_unit[2].checked){
	  ttl_dist=n;
	}
  }
  //Does a value for the overall time exist
  if(n=checkNaN(parseInt(f.pace_time_mins.value)*60)+checkNaN(parseInt(f.pace_time_secs.value))){
    ttl_time=n;
  }
  if(mtr_per_sec && ttl_time && ttl_dist){
    //Do nothing because all fields are complete
	alert("There is nothing to calculate, all fields are complete")
  }else{
    if((mtr_per_sec && ttl_time) || (mtr_per_sec && ttl_dist) || (ttl_dist && ttl_time)){
	  //The core of the operation, we're here if we have 2 out of 3 and therefore need to work out the third
      if(mtr_per_sec && ttl_time){
	    //Need to work out the total distance here
		ttl_dist=mtr_per_sec*ttl_time;
		if(f.pace_dist_unit[0].checked){
	      var form_dist=ttl_dist/1609.344;
	    }else if(f.pace_dist_unit[1].checked){
	      var form_dist=ttl_dist/1000;
	    }else if(f.pace_dist_unit[2].checked){
	      var form_dist=ttl_dist;
	    }
		document.pace_calc.pace_dist.value=form_dist.toFixed(2);
		return;
	  }
	  if(mtr_per_sec && ttl_dist){
	    //Need to work out the total time here
		ttl_time=Math.round(ttl_dist/mtr_per_sec);
		document.pace_calc.pace_time_mins.value=Math.floor(ttl_time/60);
		document.pace_calc.pace_time_secs.value=Math.round(ttl_time%60);
		return;
	  }
	  if(ttl_dist && ttl_time){
	    //Need to work out the splits, have to work out mtr_per_sec first
		mtr_per_sec=ttl_dist/ttl_time;
		var nfourh_time=400/mtr_per_sec;
		var nonek_time=1000/mtr_per_sec;
		var nonem_time=1609.344/mtr_per_sec;
		document.pace_calc.fourh_m_split.value=Math.floor(nfourh_time/60);
		document.pace_calc.onek_m_split.value=Math.floor(nonek_time/60);
		document.pace_calc.onem_m_split.value=Math.floor(nonem_time/60);
		document.pace_calc.fourh_s_split.value=Math.round(nfourh_time%60);
		document.pace_calc.onek_s_split.value=Math.round(nonek_time%60);
		document.pace_calc.onem_s_split.value=Math.round(nonem_time%60);
		return;
	  }
	}else{
	  if(ttl_dist){
	    alert("Not enough info to calculate, either enter a total time to work out your splits, or enter a split time to work out your total time");
	  }
	  if(ttl_time){
	    alert("Not enough info to calculate, either enter an overall distance to work out your splits, or enter a split time to work out your total distance");
	  }
	}
  }
}
function calculate_splits(d){
//function to look and see if there are any discrepancies in the supplied split data
//it will only work if a time for one of the splits is supplied
//it errors and returns false if more info is supplied
  var fourh_time=0;
  var onek_time=0;
  var onem_time=0;
  var fourh_time=checkNaN(parseInt(d.fourh_m_split.value)*60)+checkNaN(parseInt(d.fourh_s_split.value));
  var onek_time=checkNaN(parseInt(d.onek_m_split.value)*60)+checkNaN(parseInt(d.onek_s_split.value));
  var onem_time=checkNaN(parseInt(d.onem_m_split.value)*60)+checkNaN(parseInt(d.onem_s_split.value));
  if((fourh_time && onek_time) || (fourh_time && onem_time) || (onek_time && onem_time)){
    //Throw it out and return 0 because there could be conflicting values
    alert("Only enter values for one split distance");
	return 0;
  }
  if(fourh_time){
    mtr_per_sec=400/fourh_time;
  }
  if(onek_time){
    mtr_per_sec=1000/onek_time;
  }
  if(onem_time){
    mtr_per_sec=1609.344/onem_time;
  }
  var nfourh_time=400/mtr_per_sec;
  var nonek_time=1000/mtr_per_sec;
  var nonem_time=1609.344/mtr_per_sec;
  document.pace_calc.fourh_m_split.value=Math.floor(nfourh_time/60);
  document.pace_calc.onek_m_split.value=Math.floor(nonek_time/60);
  document.pace_calc.onem_m_split.value=Math.floor(nonem_time/60);
  document.pace_calc.fourh_s_split.value=Math.round(nfourh_time%60);
  document.pace_calc.onek_s_split.value=Math.round(nonek_time%60);
  document.pace_calc.onem_s_split.value=Math.round(nonem_time%60);
}
function checkNaN(n){
//simple function that checks for NaN values and returns 0 if found
  if(isNaN(n)){
    return 0;
  }else{
    return n;
  }
}
function calculate_mps(d){
//function that returns the value of meters per second

}
function clear_splits(n){
//function that clears the splits from the other two distances depending on which distance is modified
  if(n==1){
    //clear 1K and 1M fields
	document.pace_calc.onek_m_split.value="";
	document.pace_calc.onek_s_split.value="";
	document.pace_calc.onem_m_split.value="";
	document.pace_calc.onem_s_split.value="";
  }else if(n==2){
    document.pace_calc.fourh_m_split.value="";
	document.pace_calc.fourh_s_split.value="";
	document.pace_calc.onem_m_split.value="";
	document.pace_calc.onem_s_split.value="";
  }else if(n==3){
    document.pace_calc.fourh_m_split.value="";
	document.pace_calc.fourh_s_split.value="";
	document.pace_calc.onek_m_split.value="";
	document.pace_calc.onek_s_split.value="";
  }
}
function getPercentage(num,percentage){
	return Math.round((num/100)*percentage);
}
function calculateZones(a){
	var maxHR=calculate_maxhr2(a);
	var maxHR50=getPercentage(maxHR,50);
	var maxHR60=getPercentage(maxHR,60);
	var maxHR70=getPercentage(maxHR,70);
	var maxHR80=getPercentage(maxHR,80);
	var maxHR90=getPercentage(maxHR,90);
	var zone1=document.getElementById('zone1');
	var zone2=document.getElementById('zone2');
	var zone3=document.getElementById('zone3');
	var zone4=document.getElementById('zone4');
	var zone5=document.getElementById('zone5');
	var maxHRSpan=document.getElementById('maxhr');
	zone1.innerHTML=maxHR50 + " - " + maxHR60;
	zone2.innerHTML=maxHR60 + " - " + maxHR70;
	zone3.innerHTML=maxHR70 + " - " + maxHR80;
	zone4.innerHTML=maxHR80 + " - " + maxHR90;
	zone5.innerHTML=maxHR90 + " - " + maxHR;
	maxHRSpan.innerHTML=maxHR;
}
function getHR(restHR,maxHR,percentage){
	var diff=maxHR-restHR;
	var perc=percentage/100;
	var num=diff*perc;
	var total=parseInt(num)+parseInt(restHR);
	return total;
}
function calculateZones2(a,b){
	var restingHR=a;
	var maxHR=b;
	var zone1=document.getElementById('zone1');
	var zone2=document.getElementById('zone2');
	var zone3=document.getElementById('zone3');
	var zone4=document.getElementById('zone4');
	var zone5=document.getElementById('zone5');
	var maxHR50=getHR(restingHR,maxHR,50);
	var maxHR60=getHR(restingHR,maxHR,60);
	var maxHR70=getHR(restingHR,maxHR,70);
	var maxHR80=getHR(restingHR,maxHR,80);
	var maxHR90=getHR(restingHR,maxHR,90);
	zone1.innerHTML=maxHR50 + " - " + maxHR60;
	zone2.innerHTML=maxHR60 + " - " + maxHR70;
	zone3.innerHTML=maxHR70 + " - " + maxHR80;
	zone4.innerHTML=maxHR80 + " - " + maxHR90;
	zone5.innerHTML=maxHR90 + " - " + maxHR;
}
function simpleHRsubmit(theForm){
	theForm.age.optional=false;
	theForm.age.datatype=2;
	if(verify(theForm)){
		calculateZones(theForm.age.value);
		return false;
	}
}
function advancedHRSubmit(theForm){
	document.adv_hr.restingHR.optional=false;
	document.adv_hr.restingHR.datatype=2;
	document.adv_hr.maxHR.optional=false;
	document.adv_hr.maxHR.datatype=2;
	if(verify(document.adv_hr)){
		calculateZones2(document.adv_hr.restingHR.value,document.adv_hr.maxHR.value);
		return false;
	}
}
function paceCalc(theForm){
	if(verify(document.pace_calc)){
		calculate_pace(document.pace_calc);
	}
}
function doBMI(theForm){
  document.body_mass_index.height.optional=false;
  document.body_mass_index.weight.optional=false;
  document.body_mass_index.height.datatype=2; //Integer required
  document.body_mass_index.weight.datatype=2; //Integer required
  if(verify(document.body_mass_index)){
    var n=calculate_BMI(document.body_mass_index);
    document.body_mass_index.BMI.value=n.toFixed(2);
  }
}
