Event.observe(window, 'load', function (e){
	attachTextValidation();
});

var herdSize = 0;
var emptyRate = 0;
var numberEmptyCows = 0;
var usingCombi5 = 0;
var additionalCalves = 0;
var fiftyPercentHeifers = 0;
var heiferValue = 0;
var marketValueOfHeifer = 0;
var inCalfHeiferValue = 0;
var marketValueInCalfHeifers = 0;
var marketValueInBreedingCow = 0;
var replacementBreederValue = 0;
var bullCalves = 0;
var sellBullCalf=0;
var conceptionBenefitLower = 0;
var conceptionBenefitUpper = 0;
var averageMilkSolidsPerCow = 0;
var currentProduction = 0;
var increasePercentLower = 0;
var increasedProductionLower = 0;
var increasePercentUpper = 0;
var increasedProductionUpper = 0;
var milkSolidsPayment = 0;
var valueOfIncreasedProductionLower = 0;
var valueOfIncreasedProductionUpper = 0;
var costPerVetVisit = 0;
var vistsPerYear = 0;
var totalVetCost = 0;
var reduceVetLower = 0;
var vetSavingsLower = 0;
var reduceVetUpper = 0;
var vetSavingsUpper = 0;
var subTotalLower = 0;
var subTotalUpper = 0;
var litresRequired = 0;
var combiFiveCostPerLitre = 0;
var combiFiveCost = 0;
var netProfitLower = 0;
var netProfitUpper = 0;
var roiLower = 0;
var roiUpper = 0;

$('usingCombi5').observe('onChange', function (e){
	e.stop();
	valid = performValidation(e);

	if (valid)
	{
		conceptionRate();
	}
	return false;
});

$('increaseUpto').observe('onChange', function (e){
	e.stop();
	valid = performValidation(e);

	if (valid)
	{
		improvedProduction();
	}
	return false;
});

$('reduceByUpto').observe('onChange', function (e){
	e.stop();
	valid = performValidation(e);

	if (valid)
	{
		reducedVetCosts();
	}
	return false;
});


$('calculateSubmit').observe('click', function (e){
	e.stop();
	valid = performValidation(e);

	if (valid)
	{
	    window.scrollTo(0,0);
		performCalculation();	
		$('pageheading1').hide();
		$('form1').hide();
		$('form2').hide();
		$('form3').hide();
		$('form4').hide();
		$('submitbutton').hide();
		$('anotherCalc').show();
		$('pageheading2').show();
		$('results').show();
		do_sIFR();

	}
	return false;
});

$('anotherCalc').observe('click', function (e){
	e.stop();
		window.scrollTo(0,0);
		performCalculation();	
		$('pageheading1').show();
		$('form1').show();
		$('form2').show();
		$('form3').show();
		$('form4').show();
		$('submitbutton').show();
		$('anotherCalc').hide();
		$('pageheading2').hide();
		$('results').hide();
		do_sIFR();

});

$('calculator').observe('submit', function (e){
	e.stop();
	valid = performValidation(e);


	if (valid)
	{
		performCalculation();	
	}	
	return false;
});

function attachTextValidation() {
	
	var f = $('calculator');
	var texts = f.getInputs('text');
		
	for (var i=0, len=texts.length; i < len; i++ ){
		
		texts[i].observe('change', function (e){
			validateText(e.target);
		});
		
		texts[i].observe('blur', function (e){
			validateText(e.target);
		});
		
	}	
}

function validateText(n){

	var isValid = true;
	var value = n.value;

	n = $(n);
	
	if (value == null || 0 >=value.length )
		value = "zzzz";
			
	value = (value.replace(/\W*/,'')) * 1;
		
	var validationIcon = null;
	if( null != $(n.parentNode).select('img').length==1) {
		var imageNodes = $(n.parentNode).select('img');
		validationIcon = $(n.parentNode).select('img')[imageNodes.length - 1];
	}		


		//we attach different classes to the inputs to determine how to validate.
		// eg big num.. must be a number between 5 and six digits
		if ( n.hasClassName('bigNum') ){
			if (isNaN(value))
				isValid = false;
				
			isValid = ( value >= 100000 && value < 10000000);
			
		} else if (n.hasClassName('optNum')){
			isValid = !isNaN(value);			
		} else {
			if (isNaN( value ) || 0 > value || 0 >= value.length){
				isValid = false;
			} else {
				isValid = true;
			}
		}
	//add additional checks here.. that make the text dependant on another item.
	
	
	if (isValid){
		validationIcon.src = "/images/tick.gif";
		return true;		
	} else {
		validationIcon.src = "/images/cross.gif";
		return false;		
	}
}



function validateTextFields() {
	var f = $('calculator');
	var texts = f.getInputs('text');
	var textsAreValid = true;
	
	var validText=false;
	for (var i=0, len=texts.length; i < len; i++ ){
		validText = validateText(texts[i]);
		if (!validText) {
			textsAreValid = false;
		}
	}
	return textsAreValid;
}

function performValidation(e){
	var textsAreValid = validateTextFields();
	return textsAreValid;
}

	


function conceptionRate(){
	
	//conceptionBenefits
	if($('usingCombi5').value == ''){
		$('numberEmptyCows').value = '';
		$('additionalCalves').value = '';
		$('fiftyPercentHeifers').value = '';
		$('marketValueOfHeifer').value = '';
		$('marketValueInCalfHeifers').value = '';
		$('marketValueInBreedingCow').value = '';
		$('sellBullCalf').value = '';
		$('conceptionBenefitLowerTotal').value = '';
		$('conceptionBenefitUpperTotal').value = '';
		$('avgMilkSolids').value = '';
			
	}
	else{
		
		herdSize = $('noHerdCows').value * 1;//make sure its a bloody Number

		emptyRate =  $('currentEmptyRate').value * 1;
		emptyRate = emptyRate / 100;

		numberEmptyCows = herdSize * emptyRate;
		$('numberEmptyCows').update( commaSeperation( Math.ceil( numberEmptyCows )+"",'3,3'));
		
		usingCombi5 = $('usingCombi5').value * 1;
		usingCombi5 = usingCombi5 / 100;
		
		additionalCalves =  numberEmptyCows - ( herdSize * usingCombi5 );
		$('additionalCalves').update( commaSeperation( Math.ceil( additionalCalves )+"",'3,3'));

		fiftyPercentHeifers = additionalCalves / 2;
		$('fiftyPercentHeifers').update( commaSeperation( Math.ceil( fiftyPercentHeifers)+"",'3,3'));
	
		heiferValue= $('heiferCalves').value * 1;
		
		marketValueOfHeifer = fiftyPercentHeifers * heiferValue ;
		$('marketValueOfHeifer').update( commaSeperation( Math.ceil( marketValueOfHeifer )+"",'3,3'));
	
		inCalfHeiferValue = $('calfHeifers').value * 1;
		
		marketValueInCalfHeifers = fiftyPercentHeifers * inCalfHeiferValue;
		$('marketValueInCalfHeifers').update( commaSeperation( Math.ceil( marketValueInCalfHeifers )+"",'3,3'));
		
		replacementBreederValue = $('replacements').value * 1;
		
		marketValueInBreedingCow = fiftyPercentHeifers * replacementBreederValue;
		$('marketValueInBreedingCow').update( commaSeperation( Math.ceil( marketValueInBreedingCow )+"",'3,3'));

		bullCalves = $('bullCalves').value * 1;
		
		sellBullCalf = fiftyPercentHeifers * bullCalves;
		$('sellBullCalf').update(  commaSeperation( Math.ceil( sellBullCalf )+"",'3,3'));

		conceptionBenefitLower = marketValueOfHeifer + sellBullCalf;
		$('conceptionBenefitLower').update( commaSeperation(  Math.ceil( conceptionBenefitLower )+"",'3,3'));
		$('conceptionBenefitLowerTotal').update( commaSeperation(  Math.ceil( conceptionBenefitLower )+"",'3,3'));
		
		conceptionBenefitUpper = marketValueInBreedingCow + sellBullCalf ;
		$('conceptionBenefitUpper').update( commaSeperation(  Math.ceil( conceptionBenefitUpper )+"",'3,3'));
		$('conceptionBenefitUpperTotal').update( commaSeperation(  Math.ceil( conceptionBenefitUpper )+"",'3,3'));
		}
		
		
}

function improvedProduction(){

	if($('increaseUpto').value == ''){
		
		$('currentProduction').value = '';
		$('increasedProductionLower').value = '';
		$('increasedProductionUpper').value = '';
		$('valueOfIncreasedProductionLower').value = '';
		$('valueOfIncreasedProductionLowerTotal').value = '';
		$('valueOfIncreasedProductionUpper').value = '';
		$('valueOfIncreasedProductionUpperTotal').value = '';	
	}
	else{
		
		herdSize = $('noHerdCows').value * 1;
		averageMilkSolidsPerCow = $('avgMilkSolids').value * 1;
		currentProduction =  herdSize * averageMilkSolidsPerCow;
		$('currentProduction').update( commaSeperation(  Math.ceil( currentProduction )+"",'3,3'));
		
		increasePercentLower = $('increase').value * 1;
		increasePercentLower = increasePercentLower / 100;
		increasedProductionLower = currentProduction * increasePercentLower;
		$('increasedProductionLower').update( commaSeperation(  Math.ceil( increasedProductionLower )+"",'3,3'));

		increasePercentUpper = $('increaseUpto').value * 1;
		increasePercentUpper = increasePercentUpper / 100;
		increasedProductionUpper = currentProduction * increasePercentUpper;
		$('increasedProductionUpper').update( commaSeperation(  Math.ceil( increasedProductionUpper )+"",'3,3'));

		milkSolidsPayment = $('forecastPayout').value *1;
		
		valueOfIncreasedProductionLower = increasedProductionLower * milkSolidsPayment;
		$('valueOfIncreasedProductionLower').update( commaSeperation(  Math.ceil( valueOfIncreasedProductionLower )+"",'3,3'));
		$('valueOfIncreasedProductionLowerTotal').update( commaSeperation(  Math.ceil( valueOfIncreasedProductionLower )+"",'3,3'));
		
		valueOfIncreasedProductionUpper = increasedProductionUpper * milkSolidsPayment;
		$('valueOfIncreasedProductionUpper').update( commaSeperation(  Math.ceil( valueOfIncreasedProductionUpper )+"",'3,3'));
		$('valueOfIncreasedProductionUpperTotal').update( commaSeperation(  Math.ceil( valueOfIncreasedProductionUpper )+"",'3,3'));

	}
}

function reducedVetCosts(){

	if($('reduceByUpto').value == ''){
		
		$('totalVetCost').value = '';
		$('vetSavingsLower').value = '';
		$('vetSavingsLowerTotal').value = '';
		$('vetSavingsUpper').value = '';
		$('vetSavingsUpperTotal').value = '';		
		
	}
	else{
		costPerVetVisit = $('costVetVisit').value *1;
		vistsPerYear = $('currentVetVisits').value *1;
		totalVetCost = costPerVetVisit * vistsPerYear;
		$('totalVetCost').update( commaSeperation(  Math.ceil( totalVetCost )+"",'3,3'));
		
		reduceVetLower = $('reduceBy').value *1;
		reduceVetLower = reduceVetLower / 100;
		vetSavingsLower = totalVetCost * reduceVetLower;
		$('vetSavingsLower').update( commaSeperation(  Math.ceil( vetSavingsLower )+"",'3,3'));
		$('vetSavingsLowerTotal').update( commaSeperation(  Math.ceil( vetSavingsLower )+"",'3,3'));

		
		reduceVetUpper = $('reduceByUpto').value *1;
		reduceVetUpper = reduceVetUpper / 100;
		vetSavingsUpper = totalVetCost * reduceVetUpper;
		$('vetSavingsUpper').update( commaSeperation( Math.ceil( vetSavingsUpper )+"",'3,3'));
		$('vetSavingsUpperTotal').update( commaSeperation( Math.ceil( vetSavingsUpper )+"",'3,3'));
	}
}

function performCalculation(){
	
	//conceptionBenefits
	conceptionRate();
	
	//production
	improvedProduction();

	//vet
	reducedVetCosts();
	
	//totals.
	valueOfIncreasedProductionLower = increasedProductionLower * milkSolidsPayment;
	valueOfIncreasedProductionUpper = increasedProductionUpper * milkSolidsPayment;
	
	conceptionBenefitLower = marketValueOfHeifer + sellBullCalf;
	conceptionBenefitUpper = marketValueInBreedingCow + sellBullCalf ;
	
	costPerVetVisit = $('costVetVisit').value *1;
	vistsPerYear = $('currentVetVisits').value *1;
	totalVetCost = costPerVetVisit * vistsPerYear;
	
	reduceVetLower = $('reduceBy').value *1;
	reduceVetLower = reduceVetLower / 100;
	vetSavingsLower = totalVetCost * reduceVetLower;
	
	reduceVetUpper = $('reduceByUpto').value *1;
	reduceVetUpper = reduceVetUpper / 100;
	vetSavingsUpper = totalVetCost * reduceVetUpper;
	
	
	subTotalLower = Math.ceil(valueOfIncreasedProductionLower) + Math.ceil(conceptionBenefitLower) - Math.ceil(vetSavingsLower);
	$('subTotalLower').update( commaSeperation(( subTotalLower )+"",'3,3'));
	
	subTotalUpper = Math.ceil(valueOfIncreasedProductionUpper) + Math.ceil(conceptionBenefitUpper) - Math.ceil(vetSavingsUpper);
	$('subTotalUpper').update( commaSeperation(( subTotalUpper )+"",'3,3'));
	
	
	litresRequired = herdSize;
	$('litresRequired').update( Math.ceil( litresRequired ));
	
	combiFiveCostPerLitre = $('costCombi').value * 1;
	combiFiveCost = (litresRequired * combiFiveCostPerLitre);
	$('combiFiveCostLower').update( commaSeperation(  Math.ceil( combiFiveCost )+"",'3,3'));
	$('combiFiveCostUpper').update( commaSeperation(  Math.ceil( combiFiveCost )+"",'3,3'));
	
	
	netProfitLower = subTotalLower - combiFiveCost;
	netProfitUpper = subTotalUpper - combiFiveCost;
	
	$('netProfitLower').update( commaSeperation(  Math.ceil( netProfitLower )+"",'3,3'));
	$('netProfitUpper').update( commaSeperation(  Math.ceil( netProfitUpper )+"",'3,3'));
	
	roiLower = 	(netProfitLower / (combiFiveCost)) * 100;
	roiUpper = 	(netProfitUpper / (combiFiveCost)) * 100;
	
	$('roiLower').update( Math.round( roiLower ));
	$('roiUpper').update( Math.round( roiUpper ));
	
	
}

function commaSeperation(number, commaSeperaterList)
       {
               //My array
               var myArray = commaSeperaterList.split(',');

               var newNum = "";
               var newNum2 = "";
               var count = 0;

               //decimal number check
               if (number.indexOf('.') != -1){ //number ends with a decimal point
               if (number.indexOf('.') == number.length-1){
               number += "00";
               }
               if (number.indexOf('.') == number.length-2){ //number ends with a single digit
               number += "0";
               }

               var a = number.split(".");
               number = a[0]; //the part we will commaSeperation
               var end = '.' + a[1] //the decimal place we will ignore and add back later
               }
               else {var end = "";}

               var q=0;
               //add the commas
               for (var k = number.length-1; k >= 0; k--)
               {
                   ar = myArray[q]

                       var oneChar = number.charAt(k);
                       if (count == ar)
                       {
                               newNum += ",";
                               newNum += oneChar;
                               count = 1;
                               q++;
                               continue;
                       }
                       else
                       {
                               newNum += oneChar;
                               count ++;
                       }
               } 
               //re-reverse the string
               for (var k = newNum.length-1; k >= 0; k--){
               var oneChar = newNum.charAt(k);
               newNum2 += oneChar;
       }

return newNum2 + end;
}

/*
function showValidationError(){
	
	var popUp = $('validationErrors');
	if ( null == popUp)
		return;
		
	popUp.show();
	
	var icon = $('calculateSubmit');
	
	var iconDims = icon.getDimensions();
	var iconOffset = icon.viewportOffset();
	var iconScrollOffset = icon.cumulativeScrollOffset();
			
	popUp.style.left = ( iconOffset.left - popUp.getWidth() - 20 + iconScrollOffset.left ) + 'px' ;
	popUp.style.top = (iconOffset.top - (iconDims.height/2) + 10  + iconScrollOffset.top) + 'px';
	
	new Effect.Opacity( 'validationErrors', { from: 0.0, to: 1.0, duration: 0.2 });	
}

function hideValidationError() {
	new Effect.Opacity( 'validationErrors', { 
		from: 1.0, 
		to: 0.0, 
		duration: 0.2
		}
		
	);
	$('validationErrors').hide();
}*/

