var metric; 
var VO2max;

function initGlobals() {
	metric = false; 
	VO2Max = -1; 
}

function  runConversion() {
	
	var time = 0;		// race time in seconds. 
	var rlength = 0;	// race length in meters. 
	var speed;			// speed in meters / min. 
	
	metric = true;
	
	time += document.forms.time.hours.value * 60; 
	time += document.forms.time.minutes.value * 1; 
	time += document.forms.time.seconds.value / 60; 
	
	if(time <= 0 || isNaN(time)) {
		alert("Molimo unesite vrijeme"); 
		return; 
	}
	
	rlength += document.forms.leng.number.value * 1; 
	
	if(rlength <= 0 || isNaN(rlength)) { 
		alert("Molimo unesite dužinu."); 
		return;
	}
	
	rlength *= 1000; 
	
	speed = rlength / time; 
	
	VO2Max  = velToVO2(speed) / timeToPercentVO2Max(time) ;
	makeCalculations();
}

function makeCalculations () {
		
	if(VO2Max <= 0) return; 
		
	var velEasy		= VO2ToVel(VO2Max * .7); 
	var velTempo	= VO2ToVel(VO2Max * .88);
	var velMaximum	= VO2ToVel(VO2Max);
	var velSpeed	= VO2ToVel(VO2Max * 1.1);
	var velLong		= VO2ToVel(VO2Max * .6);
	var velYasso    = velMaximum * 1.95;  
	
	var toAppend = metric ? " min/km" : " min/mile" ;  

	var paceEasy		= "" + timeConvert(velEasy)		+ toAppend;
	var paceTempo		= "" + timeConvert(velTempo)	+ toAppend; 
	var paceMaximum		= "" + timeConvert(velMaximum)	+ toAppend;
	var paceSpeed		= "" + timeConvert(velSpeed)	+ toAppend;


	var paceLong		=  "" + timeConvert(velEasy) + " - ";
		paceLong		+= "" + timeConvert(velLong) + toAppend;

	var oldMetric = metric;
	metric = false;
	var paceYasso		= "" + timeConvert(velYasso)	+ " min/800";
	metric = oldMetric; 

	document.forms.output.Easy.value		= paceEasy;
	document.forms.output.Tempo.value		= paceTempo; 
	document.forms.output.Maximum.value		= paceMaximum; 
	document.forms.output.Speed.value		= paceSpeed; 
	document.forms.output.Long.value		= paceLong; 
	document.forms.output.Yasso.value		= paceYasso;			
}
// Toggle output type of paces. 

	
// Takes a velocity and converts it to a VO2 level. 	
function velToVO2 (vel) {
	return (-4.60 + 0.182258 * vel + 0.000104 * vel * vel);
}
	
// Takes a VO2 measurement and converts it to a velocity. 
function  VO2ToVel (VO2) {
	return (29.54 + 5.000663 * VO2 - 0.007546 * VO2 * VO2);
}

// Takes a time in minutes and uses EQ 2 to convert it to a percent of VO2 maximum. 	
function timeToPercentVO2Max (minutes) {
	return (.8 + 0.1894393 * Math.exp(-.012778 * minutes) 
			   + 0.2989558 * Math.exp(-.1932695 * minutes)); 
}

// Takes a speed in meters / minute a converts it to a string representing a pace in 
// minutes per mile or km. 	
function timeConvert (speed) {
		var ans; 
		if(!metric) ans = (1 / speed) * 1609;
		else		ans = (1 / speed) * 1000; 
		minutes = Math.floor(ans);
		seconds = Math.floor((ans - minutes) * 60);
		if(seconds > 9) return "" + minutes + ":" + seconds;
		else return "" + minutes + ":0" + seconds;
}
