
/* ---------------------------------------------------------------------------------------------------------------------------------------------------- 
Functions to calculate the Cost of fencing and planting waterways   */
/* --------------------------------------
See if the input field is empty
-----------------------------------------*/
function IsFieldEmpty(TextObject){
	if (TextObject.value.length == 0){
		TextObject.focus();
		TextObject.select();
		return true;}
	for (var i = 0; i<TextObject.value.length; i++){
		var ch = TextObject.value.charAt(i);
		if ((ch != " ") && (ch != "\t")){
			return false;}	
	}
	TextObject.focus();
	TextObject.select();
	return true;		
}

function CheckAllDigits(TextObject){
	var string_length = TextObject.value.length;
	for(var i=0; i < string_length; i++)	{
        var ch = TextObject.value.substring(i,i+1);
        if (ch < "0" || "9" < ch)
        	return false;
    }
	return true;
}

function IsStringInteger(MyString){
	var string_length = MyString.length;
	for(var i=0; i < string_length; i++)	{
        var ch = MyString.substring(i,i+1);
        if (ch < "0" || "9" < ch)
        	return false;
    }
	return true;
}

/* --------------------------------------
Recalculate total 
-----------------------------------------*/
function Recalculate(QtyObject,PriceObject,TotalObject){	
	if(QtyObject.value == "0")	{
		TotalObject.value = "";
		QtyObject.value = "";
		QtyObject.focus();
	}

	if (QtyObject.value == "" || PriceObject.value == "")	{
		TotalObject.value = "";	
		CalculateTotal();
		}
	var calculate=true;
	if (!IsPriceValid(PriceObject))	{
		calculate = false;
	}
		
	 if (!IsQuantityValid(QtyObject))
	{
		calculate = false;
	}
	
	if (!calculate)
		return false;
	
	/*begin recalculation!*/
	CalculateSubTotal(QtyObject,PriceObject,TotalObject);
	CalculateTotal();
	
	return true;
}

/* --------------------------------------
Accepts string containing a floating number with more than two places after the decimal, and rounds it to the format 
-----------------------------------------*/
function RoundPrice(PriceString)
{
	var RoundUp = 0;
	var ThirdPlaceChar = PriceString.charAt(PriceString.indexOf(".") + 3);
	var ThirdPlaceDigit = parseInt(ThirdPlaceChar);
	var SecondPlaceChar = PriceString.charAt(PriceString.indexOf(".") + 2);
	var SecondPlaceDigit = parseInt(SecondPlaceChar);
	
	if (ThirdPlaceDigit >= 5)
		RoundUp = 1;
	
	/*round up, if necessary*/
	if (RoundUp)
		SecondPlaceDigit = ++SecondPlaceDigit;

	PriceString = PriceString.substring(0,(PriceString.indexOf(".") + 2) ) + SecondPlaceDigit;
	return PriceString;						
}

/* --------------------------------------
-----------------------------------------*/
function CalculateTotal()
{

	var SubObject = document.getElementById('Subtotal');
	var T1Object = document.getElementById('Total_1');
	var T2Object = document.getElementById('Total_2');
	var T3Object = document.getElementById('Total_3');
	var T4Object = document.getElementById('Total_4');
	var T5Object = document.getElementById('Total_5');
	var T6Object = document.getElementById('Total_6');
	var T7Object = document.getElementById('Total_7');
	var T8Object = document.getElementById('Total_8');
	var T9Object = document.getElementById('Total_9');
	var T10Object = document.getElementById('Total_10');
	var T11Object = document.getElementById('Total_11');
	var T12Object = document.getElementById('Total_12');
	var T13Object = document.getElementById('Total_13');
	var T14Object = document.getElementById('Total_14');
	var T15Object = document.getElementById('Total_15');
	var T16Object = document.getElementById('Total_16');
	var T17Object = document.getElementById('Total_17');
	var T18Object = document.getElementById('Total_18');
	var T19Object = document.getElementById('Total_19');
	var T20Object = document.getElementById('Total_20');
	var T21Object = document.getElementById('Total_21');
	var T22Object = document.getElementById('Total_22');

	/*Strip dollar signs off all book totals*/
	StripDollar(T1Object);
	StripDollar(T2Object);
	StripDollar(T3Object);
	StripDollar(T4Object);
	StripDollar(T5Object);
	StripDollar(T6Object);
	StripDollar(T7Object);
	StripDollar(T8Object);
	StripDollar(T9Object);
	StripDollar(T10Object);
	StripDollar(T11Object);
	StripDollar(T12Object);
	StripDollar(T13Object);
	StripDollar(T14Object);
	StripDollar(T15Object);
	StripDollar(T16Object);
	StripDollar(T17Object);
	StripDollar(T18Object);
	StripDollar(T19Object);
	StripDollar(T20Object);
	StripDollar(T21Object);
	StripDollar(T22Object);
	
	var sub = 0;
	if (T1Object.value != "")
		{sub = sub + parseFloat(T1Object.value);
		T1Object.value = "$" + T1Object.value;}
	if (T2Object.value != "")
		{sub = sub + parseFloat(T2Object.value);
		T2Object.value = "$" + T2Object.value;}
	if (T3Object.value != "")
		{sub = sub + parseFloat(T3Object.value);
		T3Object.value = "$" + T3Object.value;}
	if (T4Object.value != "")
		{sub = sub + parseFloat(T4Object.value);
		T4Object.value = "$" + T4Object.value;}
	if (T5Object.value != "")
		{sub = sub + parseFloat(T5Object.value);
		T5Object.value = "$" + T5Object.value;}
	if (T6Object.value != "")
		{sub = sub + parseFloat(T6Object.value);
		T6Object.value = "$" + T6Object.value;}
	if (T7Object.value != "")
		{sub = sub + parseFloat(T7Object.value);
		T7Object.value = "$" + T7Object.value;}
	if (T8Object.value != "")
		{sub = sub + parseFloat(T8Object.value);
		T8Object.value = "$" + T8Object.value;}
	if (T9Object.value != "")
		{sub = sub + parseFloat(T9Object.value);
		T9Object.value = "$" + T9Object.value;}
	if (T10Object.value != "")
		{sub = sub + parseFloat(T10Object.value);
		T10Object.value = "$" + T10Object.value;}
	if (T11Object.value != "")
		{sub = sub + parseFloat(T11Object.value);
		T11Object.value = "$" + T11Object.value;}
	if (T12Object.value != "")
		{sub = sub + parseFloat(T12Object.value);
		T12Object.value = "$" + T12Object.value;}
	if (T13Object.value != "")
		{sub = sub + parseFloat(T13Object.value);
		T13Object.value = "$" + T13Object.value;}
	if (T14Object.value != "")
		{sub = sub + parseFloat(T14Object.value);
		T14Object.value = "$" + T14Object.value;}
	if (T15Object.value != "")
		{sub = sub + parseFloat(T15Object.value);
		T15Object.value = "$" + T15Object.value;}
	if (T16Object.value != "")
		{sub = sub + parseFloat(T16Object.value);
		T16Object.value = "$" + T16Object.value;}
	if (T17Object.value != "")
		{sub = sub + parseFloat(T17Object.value);
		T17Object.value = "$" + T17Object.value;}
	if (T18Object.value != "")
		{sub = sub + parseFloat(T18Object.value);
		T18Object.value = "$" + T18Object.value;}
	if (T19Object.value != "")
		{sub = sub + parseFloat(T19Object.value);
		T19Object.value = "$" + T19Object.value;}
	if (T20Object.value != "")
		{sub = sub + parseFloat(T20Object.value);
		T20Object.value = "$" + T20Object.value;}
	if (T21Object.value != "")
		{sub = sub + parseFloat(T21Object.value);
		T21Object.value = "$" + T21Object.value;}
	if (T22Object.value != "")
		{sub = sub + parseFloat(T22Object.value);
		T22Object.value = "$" + T22Object.value;}
				
	if (sub == 0)
	{
		SubObject.value = "";
		return false;
	}
	
	/*reformat places after decimal*/
	SubString = "" + sub;
	SubLength = SubString.length;
	
	/*if total is an integer, add ".00"*/
	if (SubString.indexOf(".") == -1)
		SubObject.value = "$" + sub + ".00";	
	/* if total is in the format $x.x as "0"	*/
	else if(SubString.indexOf(".") == (SubLength - 2) )
		SubObject.value = "$" + sub + "0";
	else
		SubObject.value = "$" + SubString.substring(0,(SubString.indexOf(".") + 3) )	
	return true;
}

/* --------------------------------------
                          */
function StripDollar(TextObject)
{
	/*If price begins with a $ sign, strip it off!*/
	var PriceLength = TextObject.value.length;
	if(TextObject.value.charAt(0) == "$")
	{
		TextObject.value = TextObject.value.substring(1,PriceLength);
	}
	return true;
}

function CalculateSubTotal(QtyObject,PriceObject,TotalObject)
{
	if (QtyObject.value == "" || PriceObject.value == "")
	{
		TotalObject.value = "";	
		return false;
	}

	StripDollar(PriceObject);
	var qty = parseFloat(QtyObject.value);
	var price = parseFloat(PriceObject.value);	
	
	var total = qty * price;
	PriceObject.value = "$" + PriceObject.value;
	
	/*reformat places after decimal*/
	TotalString = "" + total;
	TotalLength = TotalString.length;
	
	/*if total is an integer, add ".00"*/
	if (TotalString.indexOf(".") == -1)
		TotalObject.value = "$" + total + ".00";	
	/* if total is in the format $x.x ass "0"	*/
	else if(TotalString.indexOf(".") == (TotalLength - 2) )
		TotalObject.value = "$" + total + "0";
	else
		TotalObject.value = "$" + TotalString.substring(0,(TotalString.indexOf(".") + 3) )
			
		
	return true;	
}

/* --------------------------------------
Ensure that price is in the correct format (i.e. $3.00)*/
function IsPriceValid(TextObject)
{
	/* If price begins with a $ sign, strip it off!*/
	var PriceLength = TextObject.value.length;
	if(TextObject.value.charAt(0) == "$")
	{
		TextObject.value = TextObject.value.substring(1,PriceLength);
	}
	
	/*Make sure field is not null, if it is, return false*/
	if(IsFieldEmpty(TextObject))
	{
			return false;
	}	
	
	/* recalc PriceLength*/
	var PriceLength = TextObject.value.length;
	
	/*check to see if the remaining string holds an integer value*/
	if(CheckAllDigits(TextObject))
	{
		TextObject.value = "$" + TextObject.value + ".00";
		return true;
	}
	else if( (TextObject.value.charAt(PriceLength-3) == ".") &&
		(IsStringInteger(TextObject.value.substring(0,PriceLength-3))) &&
		(IsStringInteger(TextObject.value.substring(PriceLength-1,PriceLength))) )	
	{
		TextObject.value = "$" + TextObject.value;
		return true;
	}
	else
	{
		TextObject.value = "";
		alert("Invalid price format.\n Valid format examples:\n$3.00 , $3 , 3 , or 3.00");
		TextObject.focus();	
		return false;
	}
}
/* --------------------------------------
Check to make sure Quantity is a non-zero integer*/
function IsQuantityValid(TextObject)
{
	/*Make sure field is not null, if it is, return false*/
	if(IsFieldEmpty(TextObject))
	{
		return false;
	}
	

	if(!CheckAllDigits(TextObject))
	{
		alert("Value must be a number");
		TextObject.value = "";
		TextObject.focus();
		return false;
	}
	else
		return true;			
}

/* ---------------------------------------------------------------------------------------------------------------------------------------------------- 
 Functions to calculate Effluent Application Rates*/
/* --------------------------------------
calculate the distance an irrigator needs to travel (in metres) per hour 
Inputs: Three floats: irrigator output, depth and spray (from form fields irrOutput, irrDepth, irrSpray)
Outputs: output / depth / spray = metres per hour
Function is called when any one of the form fields is changed and loses focus.
The calculation is made and result diplayed in irrTotal unless the result is NaN
-----------------------------------------*/
function calculateTotalEff()
{
	var eOutput = parseFloat(document.getElementById('irrOutput').value)
	var eDepth = parseFloat(document.getElementById('irrDepth').value)
	var eSpray = parseFloat(document.getElementById('irrSpray').value)
	eTotal = eOutput/eDepth/eSpray
	if (isNaN(eTotal)){
		document.getElementById('irrTotal').value = ""}
	else{
		document.getElementById('irrTotal').value = round_decimals(eTotal, 2)}
}

/* --------------------------------------
Calulate area covered by the spray head 
Inputs: One floats: radius of spray (from form field sAreaRadius)
Outputs: radius * radius * pi = area covered by the spray head in square metres
Function is called when the form fields is changed and loses focus.
The calculation is made and the result dispplayed in the sAreaTotal and calSprayQty_form.sArea unless the result is NaN
Spray quantity is calculated and displayed in sEffQty
Spray time is calculated and displayed in sMinutes
-----------------------------------------*/
function calculateSprayArea()
{
	var sRadius = parseFloat(document.getElementById('sAreaRadius').value)
	areaTotal = (sRadius * sRadius) * 3.1416
	if (isNaN(areaTotal)){
	document.getElementById('sAreaTotal').value = ""}
	else{
	document.getElementById('sAreaTotal').value = round_decimals(areaTotal, 3)
	document.getElementById('sArea').value = round_decimals(areaTotal, 3)}
	calculateSprayQuantity()
	calculateSprayTime()
}
/* --------------------------------------
Calculate quantity of effluent required to cover the area to the desired depth
Inputs: Two floats: desired depth, area coverd (from form field sDepth, sArea), 
Outputs: depth / 1000 * spray area = quantity of effluent required in cubic metres
Function is called when the form fields are changed and loses focus.
The calculation is made and the result displayed in the sEffQty and calSprayTime_form.sQtyEff unless the result is NaN
Spray time is calculated and displayed in sMinutes
-----------------------------------------*/
function calculateSprayQuantity()
{
	var sDepth = parseFloat(document.getElementById('sDepth').value)
	var sArea = parseFloat(document.getElementById('sArea').value)
	sEffQty = (sDepth/1000) * sArea
	if (isNaN(sEffQty)){
		document.getElementById('sEffQty').value = ""}
	else{
		document.getElementById('sEffQty').value = round_decimals(sEffQty, 2)
		document.getElementById('sQtyEff').value = round_decimals(sEffQty, 2)}
	calculateSprayTime()
}

/* --------------------------------------
Calculate time the spray head can stay in one position 
Inputs: Two floats: quantity of effluent, pump capacity (from form field sQtyEff, sPumpCap), 
Outputs: quantity / capacity * 60 = number of minutes the spray head can stay in any one position
Function is called when the form fields are changed and loses focus.
The calculation is made and the result displayed in sMinutes unless the result is NaN
-----------------------------------------*/
function calculateSprayTime()
{
	var sPumpCap = parseFloat(document.getElementById('sPumpCap').value)
	var sQtyEff = parseFloat(document.getElementById('sQtyEff').value)
	sMinutes = sQtyEff/sPumpCap * 60
	if (isNaN(sMinutes)){
		document.getElementById('sMinutes').value = ""}
	else{
    		document.getElementById('sMinutes').value = round_decimals(sMinutes , 2)}
	
}

/* --------------------------------------
calculate the distance an irrigator needs to travel (in metres) per hour 
Inputs: Three floats: volumet, depth and spray swath (from form field tVolume, tDepth, tSpray), 
Outputs: volume / depth / spray = metres to travel to empty each load
Function is called when the form fields are changed and loses focus.
The calculation is made and the result displayed in tTotal unless the result is NaN
-----------------------------------------*/
function calculateTotalSlurry()
{
	var tVolume = parseFloat(document.getElementById('tVolume').value)
	var tDepth = parseFloat(document.getElementById('tDepth').value)
	var tSpray = parseFloat(document.getElementById('tSpray').value)
	var tTotal = tVolume/tDepth/tSpray
	if (isNaN(tTotal)){
		document.getElementById('tTotal').value = ""}
	else{	
	document.getElementById('tTotal').value = round_decimals(tTotal, 2)}	
}

/* ---------------------------------------------------------------------------------------------------------------------------------------------------- 
Functions to calculate Nitrogen budget for dairy farmers */
/* --------------------------------------
Calculate fertiliser input
Inputs: Two floats: rating and application rate (from form field nRating, appRate), 
Outputs: rating / 100 * app rate = Fertiliser N input
Function is called when the form fields are changed and loses focus.
The calculation is made and the result displayed in fertNinput unless the result is NaN
Functions calDairyTotalInput, calDairyNSurplus are called
-----------------------------------------*/
function calDairyFertNInput()
{
	var eRating = parseFloat(document.getElementById('nRating').value)
	var eRate = parseFloat(document.getElementById('appRate').value)
	eTotal = eRating/100*eRate
     if (isNaN(eTotal) ){
		document.getElementById('fertNinput').value = ""}
     else{
    		document.getElementById('fertNinput').value = round_decimals(eTotal, 2)}
	calDairyTotalInput()
     calDairyNSurplus()
}

/* --------------------------------------
calulate clover input 
Inputs one integer (from form field eClover)
Output cloverNfixed
Function is called when the form fields are changed
Total input is calculated and displayed in totalNInputs
Nitrogen surplus is calculated and displayed in farmNSurplus
-----------------------------------------*/
function calDairyCloverNInput(eClover)
{
	document.getElementById('cloverNfixed').value = eClover
	calDairyTotalInput()
     calDairyNSurplus()
}

/* --------------------------------------
calclate Effluent N input
Inputs one integer (from form field eEffluent)
Output EffluentNInput
Function is called when the form fields are changed
Functions calDairyTotalInput, calDairyNSurplus are called
-----------------------------------------*/
function calDairyEffluentNInput(eEffluent)
{
	document.getElementById('EffluentNInput').value = eEffluent
	calDairyTotalInput()
     calDairyNSurplus()
}

/* --------------------------------------
Calculate total input
Inputs: three floats fertiliser, clover, effluent (from form fields ertNinput, cloverNfixed, EffluentNInput)
Output: fertiliser + clover + effluent = Total N Inputs
Funtion is called from functions calDairyFertNInput, calDairyCloverNInput, calDairyEffluentNInput
The calculation is made and the result displayed in totalNInputs unless the result is NaN
Function calDairyNSurplus is called
-----------------------------------------*/
function calDairyTotalInput()
{
	var eFert = parseFloat(document.getElementById('fertNinput').value)
	var eClover = parseFloat(document.getElementById('cloverNfixed').value)
	var eEffluent = parseFloat(document.getElementById('EffluentNInput').value)
	var eInput = eFert + eClover + eEffluent
      if (isNaN(eInput)){
	document.getElementById('totalNInputs').value = ""}
	else{
	document.getElementById('totalNInputs').value = round_decimals(eInput,2)}
     calDairyNSurplus()
}

/* --------------------------------------
Calclate total output 
Inputs: three floats fertiliser, clover, effluent (from form fields ertNinput, cloverNfixed, EffluentNInput)
Output: fertiliser + clover + effluent = Total N Inputs
Funtion is called from functions calDairyFertNInput, calDairyCloverNInput, calDairyEffluentNInput
The calculation is made and the result displayed in totalNInputs unless the result is NaN
Function calDairyNSurplus is called
-----------------------------------------*/
function calDairyTotalOutput()
{
	var emilkSolids = parseFloat(document.getElementById('milkSolids').value)
	eOutput = round_decimals(emilkSolids * 0.068, 4)
	if (isNaN(eOutput)){
	document.getElementById('totalNOutputs').value = ""}
	else{
	document.getElementById('totalNOutputs').value = eOutput}
     calDairyNSurplus()
}

/* --------------------------------------
Calculate Farm Nitrogen Surplus
Inputs: two floats total inputs, total outputs (from form fields totalNInputs, totalNOutputs)
Output: inputs - outputs = Total N Surplus
Funtion is called from functions calDairyFertNInput, calDairyCloverNInput, calDairyEffluentNInput, calDairyTotalOutput
The calculation is made and the result displayed in farmNSurplus unless the result is NaN
-----------------------------------------*/
function calDairyNSurplus()
{
	var eInput = parseFloat(document.getElementById('totalNInputs').value)
	var eOutput = parseFloat(document.getElementById('totalNOutputs').value)
	eSurplus = eInput - eOutput
	if (isNaN(eSurplus)){
	document.getElementById('farmNSurplus').value = ""}
      else{
	document.getElementById('farmNSurplus').value = round_decimals(eSurplus, 2)}
}

/* ---------------------------------------------------------------------------------------------------------------------------------------------------- 
Functions to calculate Nitrogen budget for drystock farmers   */
/* --------------------------------------
Calculate Fertiliser N input
Inputs: two floats nitrogen rating, rate of application (from form fields nRating, appRate)
Output: rating / 100 * app rate = Fertiliser N input
Function is called when the form fields are changed and loses focus.
The calculation is made and the result displayed in fertNinput unless the result is NaN
-----------------------------------------*/
function calDryFertNInput()
{
	var eRating = parseFloat(document.getElementById('nRating').value)
	var eRate = parseFloat(document.getElementById('appRate').value)
	eTotal = eRating/100*eRate
 	if (isNaN(eTotal)){
		document.getElementById('fertNinput').value = ""}
	else{
		document.getElementById('fertNinput').value = round_decimals(eTotal, 4)}
	calDryTotalInput()
}

/* --------------------------------------
Clover N fixed 
Inputs one integer (from form field eClover)
Output cloverNfixed
Function is called when the form fields are changed
Function calDryTotalInput is called
-----------------------------------------*/
function calDryCloverNInput(eClover)
{
	document.getElementById('cloverNfixed').value = eClover
     calDryTotalInput()
}

/* --------------------------------------
calculate Total N Inputs 
Inputs: two floats fertiliser input, clover input (from form fields fertNinput, cloverNfixed)
Output: fert
Function is called when the form fields are changed and loses focus.
The calculation is made and the result displayed in fertNinput unless the result is NaN
Function calDryNSurplus is called
-----------------------------------------*/
function calDryTotalInput()
{
	var eFert = parseFloat(document.getElementById('fertNinput').value)
	var eClover = parseFloat(document.getElementById('cloverNfixed').value)
	var eDryTotal = round_decimals(eFert + eClover, 4)
	if (isNaN(eDryTotal)){
		document.getElementById('totalNInputs').value = ""}
	else{
		document.getElementById('totalNInputs').value = eDryTotal}
	calDryNSurplus()
}

/* --------------------------------------
Calculate wool output
Inputs: One float: wool sold (from form field woolOut), 
Outputs: wool sold * 0.165 = N in wool
Function is called when the form field is changed and loses focus.
The calculation is made and the result displayed in totalWoolOutputs unless the result is NaN
Function calDryTotalNOutput is called
-----------------------------------------*/
function calDryNWoolOutput()
{
	var eWoolOut = parseFloat(document.getElementById('woolOut').value)
	document.getElementById('totalWoolOutputs').value = round_decimals(eWoolOut * 0.165, 4)
	calDryTotalNOutput()
}

/* --------------------------------------
Calculate Stock sold output
Inputs: One float: Stock sold  (from form field stockOut), 
Outputs: stock sold * 2 = N in animals
Function is called when the form field is changed and loses focus.
The calculation is made and the result displayed in totalStockOutputs unless the result is NaN
Function calDryTotalNOutput is called
-----------------------------------------*/
function calDryNStockOutput()
{
	var eStockOut = parseFloat(document.getElementById('stockOut').value)
	var eStockTotal =  round_decimals(eStockOut * 2, 4)
	if (isNaN(eStockTotal)){
		document.getElementById('totalStockOutputs').value = ""}
	else{
		document.getElementById('totalStockOutputs').value = eStockTotal}
     calDryTotalNOutput()
}
/* --------------------------------------
Calculate liveweight sold output
Inputs: One float: liveweight sold (from form field liveOut), 
Outputs: liveweight sold * 0.03 = N in animals
Function is called when the form field is changed and loses focus.
The calculation is made and the result displayed in totalLiveOutputs unless the result is NaN
Function calDryTotalNOutput is called
-----------------------------------------*/
function calDryNLiveOutput()
{
	var eLiveOut = parseFloat(document.getElementById('liveOut').value)
	var eLiveTotal =  round_decimals(eLiveOut * 0.03, 4)
	if (isNaN(eLiveTotal)){
	document.getElementById('totalLiveOutputs').value =""}
	else{
	document.getElementById('totalLiveOutputs').value =eLiveTotal}
     calDryTotalNOutput()
}

/* --------------------------------------
Calculate total output
Inputs: two floats : wool and either stock sold or liveweight sold (from form fields totalWoolOutputs,totalStockOutputs,totalLiveOutputs) 
Outputs: wool + stock = total output or wool + liveweight = total output
Function is called from calDryNWoolOutput, calDryNStockOutput, calDryNLiveOutput
The calculation is made and the result displayed in totalNOutputs unless the result is NaN
Function calDryNSurplus is called
-----------------------------------------*/
function calDryTotalNOutput()
{
	var eWool = parseFloat(document.getElementById('totalWoolOutputs').value)
	
	if (document.getElementById('totalStockOutputs').value != "") {
		
		var eStock = parseFloat(document.getElementById('totalStockOutputs').value)
		var tOutput = eWool + eStock	
		if (isNaN(tOutput)){
			document.getElementById('totalNOutputs').value =""
		}
		else{
			document.getElementById('totalNOutputs').value = round_decimals(tOutput,4)
		}
		calDryNSurplus()
		}
	else{
		var eLive = parseFloat(document.getElementById('totalLiveOutputs').value)
		var tOutput = eWool + eLive
		if (isNaN(tOutput)){
	  		document.getElementById('totalNOutputs').value =""	}
		else{
			document.getElementById('totalNOutputs').value = round_decimals(tOutput,4)}
	  	}
	calDryNSurplus()
}
/* --------------------------------------
Calculate Farm N surplus
Inputs: two floats : total inputs, total outputs (from form fields totalNInputs, totalNOutputs)
Outputs: inputs - outputs = surplus
Function is called from calDryTotalNOutput, calDryTotalInput
The calculation is made and the result displayed in farmNSurplus unless the result is NaN
-----------------------------------------*/
function calDryNSurplus()
{
	var eInput = parseFloat(document.getElementById('totalNInputs').value)
	var eOutput = parseFloat(document.getElementById('totalNOutputs').value)
	var eSurplus =  eInput - eOutput
	if (isNaN(eSurplus)){	
		document.getElementById('farmNSurplus').value = ""}
	else{
		document.getElementById('farmNSurplus').value =  round_decimals(eSurplus,2)}
}
/* ---------------------------------------------------------------------------------------------------------------------------------------------------- 
Calculate Phosphate budget for dairy farmers */
/* --------------------------------------
Calculate fertiliser input
Inputs: two floats : P rating, application rate (from form fields pRating, appRate)
Outputs: rating / 100 * apllication rate = Fertiliser P input
Function is called when the form fields are changed and loses focus.
The calculation is made and the result displayed in fertPinput unless the result is NaN
Function calDairyTotalPInput is called
-----------------------------------------*/
function calDairyFertPInput()
{
	var eRating = parseFloat(document.getElementById('pRating').value)
	var eRate = parseFloat(document.getElementById('appRate').value)
	var eFert = round_decimals(eRating/100*eRate, 4)
	if (isNaN(eFert)){
		document.getElementById('fertPinput').value = ""}
	else{
		document.getElementById('fertPinput').value = eFert}
	calDairyTotalPInput()		
}
/* --------------------------------------
Calculate Effluent P input
Inputs: one floats : Effluent P input (from form fields eEffluent)
The result displayed in EffluentPInput
Function calDairyTotalPInput is called
-----------------------------------------*/
function calDairyEffluentPInput(eEffluent)
{
	document.getElementById('EffluentPInput').value = eEffluent
	calDairyTotalPInput()
}
/* --------------------------------------
Calulate total input
Inputs: two floats : fertiliser input, effluent input (from form fields fertPinput, EffluentPInput)
Outputs: fertiliser + 3 + effluent = total input
Function is called from calDairyEffluentPInput, calDairyFertPInput
The calculation is made and the result displayed in totalPInputs unless the result is NaN
Function calDairyPSurplus is called
-----------------------------------------*/
function calDairyTotalPInput()
{
	var eFert = parseFloat(document.getElementById('fertPinput').value)
	var eEffluent = parseFloat(document.getElementById('EffluentPInput').value)
	var eTotalInput = eFert + 3 + eEffluent
	if (isNaN(eTotalInput)){
		document.getElementById('totalPInputs').value = ""}
	else{
		document.getElementById('totalPInputs').value = eTotalInput}
	calDairyPSurplus()
}

/* --------------------------------------
Calclate total output 
Inputs: one float : Milk production (from form fields milkSolids)
Outputs: milk * 0.012 = P in milk
Function is called from calDairyEffluentPInput, calDairyFertPInput
The calculation is made and the result displayed in totalPInputs unless the result is NaN
Function calDairyPSurplus is called
-----------------------------------------*/
function calDairyTotalPOutput()
{
	var emilkSolids = parseFloat(document.getElementById('milkSolids').value)
	var eTotal = round_decimals(emilkSolids * 0.012, 4)
	if (isNaN(eTotal)){
	document.getElementById('totalPOutputs').value = ""}
	else{
	document.getElementById('totalPOutputs').value = eTotal}
	calDairyPSurplus()
}

/* --------------------------------------
Calculate Farm Phosphate Surplus
Inputs: two floats : total input, total output (from form fields totalPInputs, totalPOutputs)
Outputs: inputs - outputs = surplus
Function is called from calDairyTotalPOutpu, calDairyTotalPInput
The calculation is made and the result displayed in farmPSurplus unless the result is NaN
-----------------------------------------*/
function calDairyPSurplus()
{
	var eInput = parseFloat(document.getElementById('totalPInputs').value)
	var eOutput = parseFloat(document.getElementById('totalPOutputs').value)
	var eSurplus = eInput - eOutput
	if (isNaN(eSurplus)){
		document.getElementById('farmPSurplus').value = ""}
	else{
		document.getElementById('farmPSurplus').value = round_decimals(eSurplus, 2)}
}
/* ---------------------------------------------------------------------------------------------------------------------------------------------------- 
Calculate Phosphate budget for drystock farmers */
/* --------------------------------------
Calculate total inputs
Inputs: two floats : p rating, rate of application (from form fields pRating, appRate)
Outputs:	rating / 100 * application rate = Fertiliser P input
			fertiliser input + 3 = total inputs
Function is when the form fields are changed and loses focus.
The calculation is made and the result displayed in farmPSurplus unless the result is NaN

-----------------------------------------*/
function calDryFertPInput()
{
	var eRating = parseFloat(document.getElementById('pRating').value)
	var eRate = parseFloat(document.getElementById('appRate').value)
	var ePInput = round_decimals(eRating/100*eRate, 4)
		if  (isNaN(ePInput)){
		document.getElementById('fertPinput').value = ""}
	else{
		document.getElementById('fertPinput').value = ePInput}
	calDryPSurplus()

	var ePTotalFert = parseFloat(document.getElementById('fertPinput').value)
	var eTotalInput = round_decimals(ePTotalFert + 3, 4)
	if (isNaN(eTotalInput)){
		document.getElementById('totalPInputs').value = ""}
	else{
		document.getElementById('totalPInputs').value = eTotalInput}
	calDryPSurplus()
}

/* --------------------------------------
Calculate P in wool 
Inputs: one float : wool sold (from form fields pRating, appRate)
Outputs:	wool * 0.01 = P in wool
Function is called when the form fields are changed and loses focus.
The calculation is made and the result displayed in totalWoolOutputs unless the result is NaN
Functions calDryTotalPOutput, calDryPSurplus are called
-----------------------------------------*/
function calDryWoolPOutput()
{
	var eWoolOut = parseFloat(document.getElementById('woolOut').value)
	var eWool = round_decimals(eWoolOut * 0.01, 4)
	if (isNaN(eWool)){
		document.getElementById('totalWoolOutputs').value = ""}
	else{
		document.getElementById('totalWoolOutputs').value = eWool}
	calDryTotalPOutput()
	calDryPSurplus()
}

/* --------------------------------------
Calculate N in animals - Stock 
Inputs:one float : stock sold (from form field stockOut)
Outputs:	stock * 0.5 = P in animals
Function is called when the form fields are changed and loses focus.
The calculation is made and the result displayed in totalStockOutputs unless the result is NaN
Functions calDryTotalPOutput, calDryPSurplus are called
-----------------------------------------*/
function calDryStockPOutput()
{
	var eStockOut = parseFloat(document.getElementById('stockOut').value)
	var eStock = round_decimals(eStockOut * 0.5, 4)
	if (isNaN(eStock)){
		document.getElementById('totalStockOutputs').value = ""}
	else{
		document.getElementById('totalStockOutputs').value = eStock}
     calDryTotalPOutput()
	calDryPSurplus()
}

/* --------------------------------------
Calculate N in animals - liveweight 
Inputs:one float : liveweight sold (from form field stockOut)
Outputs:	liveweight * 0.008 = P in animals
Function is called when the form fields are changed and loses focus.
The calculation is made and the result displayed in totalStockOutputs unless the result is NaN
Functions calDryTotalPOutput, calDryPSurplus are called
-----------------------------------------*/
function calDryLivePOutput()
{
	var eLiveOut = parseFloat(document.getElementById('liveOut').value)
	var ePOutput = round_decimals(eLiveOut * 0.008, 4)
	if (isNaN(ePOutput)){
		document.getElementById('totalLiveOutputs').value = ""}
	else{
		document.getElementById('totalLiveOutputs').value = ePOutput}
     calDryTotalPOutput()
	calDryPSurplus()
}

/* --------------------------------------
Calculate Total P outputs 
Inputs: two float : wool sold, either stock sold 0r liveweight sold (from form field totalWoolOutputs, totalStockOutputs, totalLiveOutputs)
Outputs:	wool + stock sold = total outputs
	or		wool + liveweight = total outputs
Function is called from calDryStockPOutput, calDryLivePOutput
The calculation is made and the result displayed in totalPOutputs unless the result is NaN
Function calDryPSurplus is called
-----------------------------------------*/
function calDryTotalPOutput()
{
	var eWool = parseFloat(document.getElementById('totalWoolOutputs').value)
	if (document.getElementById('totalStockOutputs').value != "") {
		var eStock = parseInt(document.getElementById('totalStockOutputs').value)
		var eTotalOutP = round_decimals(eWool + eStock, 4)
		if (isNaN(eTotalOutP)){
			document.getElementById('totalPOutputs').value = ""}
		else{
			document.getElementById('totalPOutputs').value = eTotalOutP}		
	   }
	else{
       	var eLive = parseFloat(document.getElementById('totalLiveOutputs').value)
		var eTotalOutP = round_decimals(eWool + eLive, 4)
		if (isNaN(eTotalOutP)){
			document.getElementById('totalPOutputs').value = ""}
		else{
			document.getElementById('totalPOutputs').value = eTotalOutP}		
	}
	calDryPSurplus()
}

/* --------------------------------------
Calculate Farm P surplus/deficit 
Inputs: two float : total inputs, total outputs (from form field totalPInputs, totalPOutputs)
Outputs:	inputs - outputs = surplus/deficit 
Function is called from calDryFertPInput, calDryTotalPOutput
The calculation is made and the result displayed in farmPSurplus unless the result is NaN
-----------------------------------------*/
function calDryPSurplus()
{
	var eInput = parseFloat(document.getElementById('totalPInputs').value)
	var eOutput = parseFloat(document.getElementById('totalPOutputs').value)
	var eSurplus = round_decimals(eInput - eOutput, 2)
	if (isNaN(eSurplus)){
		document.getElementById('farmPSurplus').value =  ""}
	else{
		document.getElementById('farmPSurplus').value =  eSurplus}	
}
/* ---------------------------------------------------------------------------------------------------------------------------------------------------- 
Calculate Desired Application Depth*/

function validDepth()
{
	
	var eNKgHa = parseFloat(document.getElementById('nApplied').value)
	
	if (eNKgHa > 150){
	document.getElementById('nApplied').focus()
		alert('You need to irrigate less N - 150 kg is the max.')
		}	
	else{
		calculateTotalDepth()
	}
}


/* --------------------------------------
calculate the Desired Application Depth 
Inputs: two float : amount of nitrogen to be applied, nitrogen content of effluent(from form field nApplied, nContent)
Outputs:	amount / content / 1000 = Depth in millimetres
Function is called from when form fields are changed and lose focus
The calculation is made and the result displayed in irrTotal unless the result is NaN
-----------------------------------------*/
function calculateTotalDepth()
{
	var eNKgHa = parseFloat(document.getElementById('nApplied').value)
	var eEffluent = parseFloat(document.getElementById('nContent').value)
	eTotal = eNKgHa/eEffluent/10000
	if (isNaN(eTotal)){
		document.getElementById('irrTotal').value = ""}
	else{
		document.getElementById('irrTotal').value = round_decimals(eTotal, 2)}
		totalMessage()
}

function totalMessage()
{
	document.getElementById('Message').value = ""
	var eTotal = parseFloat(document.getElementById('irrTotal').value)	
	if (eTotal > 25){
		document.getElementById('Message').value = "You need several smaller irrigations - 25 mm is the max"}
}
/* ---------------------------------------------------------------------------------------------------------------------------------------------------- 
Global Functions */
/* --------------------------------------
Round decimals to desired number 
Inputs: one float : original number, decimals
Outputs:	amount / content / 1000 = Depth in millimetres
The calculation is made and the result displayed in irrTotal unless the result is NaN
-----------------------------------------*/
function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

/* --------------------------------------
pad decimals with zeros to desired number 

-----------------------------------------*/
function pad_with_zeros(rounded_value, decimal_places) {
    /* Convert the number to a string */
    var value_string = rounded_value.toString()
    /* Locate the decimal point */
    var decimal_location = value_string.indexOf(".")
    /* Is there a decimal point?*/
    if (decimal_location == -1) {
        /* If no, then all decimal places will be padded with 0s */
        decimal_part_length = 0
        /* If decimal_places is greater than zero, tack on a decimal point */
        value_string += decimal_places > 0 ? "." : ""
    }
    else {
        /* If yes, then only the extra decimal places will be padded with 0s */
        decimal_part_length = value_string.length - decimal_location - 1
    }
	/* Calculate the number of decimal places that need to be padded with 0s */
    var pad_total = decimal_places - decimal_part_length
        if (pad_total > 0) {
              /*  Pad the string with 0s */
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

/* --------------------------------------
Validate that input is a valid number  
Input 1 integer
checks if the number is an integer
Outputs: Boolean
Function is called wen the form filed are cahnged and lose focus.
-----------------------------------------*/
function validate_char(field) { 
 if (isNaN(field.value)){
   alert("Value must be a number");
   field.focus()
   return false;
 } 
/* --------------------------------------
-----------------------------------------*/
function CheckAllDigits(TextObject){
	var string_length = TextObject.value.length;
	for(var i=0; i < string_length; i++)	{
        var ch = TextObject.value.substring(i,i+1);
        if (ch < "0" || "9" < ch)
        	return false;
    }
	return true;
}
} 
