//********************Global Vars****************************//
/**
 *  global vars to hold default data from the data set
 *  and user-manipulated variables in html forms
 */

// user defined vars from initial screen
var crop, acres, state, irrigationType, waterCost;

// user's system operating costs
var water, energy, fertilizer, chemical, irrigationLabor, maintenance, cultivation, equipment, harvestCosts, et;

// user's system yield variables
var yield, unit, pricePerUnit;

// irrigation efficiency
var et;

// user's system investment formulas
var growerNet = 1000;
var costShare = 0;
var netSystemCost = 1000;

// drip micro operating costs
var microWater, microEnergy, microFertilizer, microChemical, microIrrigation, microMaintenance, microCultivation, microEquipment, microHarvest, microRevenue, microEt;

// drip micro yield and investment values
var	microInvestment, microYield, userYield;

// objects to hold information subsets
var cropData;

// Irrigation type "Constants" 
var UNIFORMITY, ENERGY, FERTILIZER, CHEMICAL, IRRIGATION, MAINTENANCE, CULTIVATION, EQUIPMENT, HARVEST, YIELD, REVENUE, MULTIPLIER;

var DRIP_MICRO = .88;

// constant lower and upper bounds
var LOWER_BOUND = .1;
var UPPER_BOUND = 4.0;

//******************End Global Vars************************//
 
 

//******************Page Functions******************************//

/**
 * generic method for getting an html element in a non-browser specific way
 */
function getElement(which)
{
	var elem;
  	if( document.getElementById ) // this is the way the standards work
    	elem = document.getElementById( which );
  	else if( document.all ) // this is the way old msie versions work
      	elem = document.all[which];
  	else if( document.layers ) // this is the way nn4 works
    	elem = document.layers[which];
  	return elem;
}

/**
 * hides the element(div) passed in by name
 */
function hideLayer( whichLayer )
{
  	var elem = getElement(whichLayer);
  	vis = elem.style;
    vis.display = 'none';
}

/**
 * shows the element(div) passed in by name
 */
function showLayer( whichLayer )
{
 	 var elem = getElement(whichLayer);
 	 vis = elem.style;
 	 vis.display = 'block';
}

/**
 * hides all the elements(div) defined for the page but this one
 */
function hideAllBut(which)
{
	if (which != "basic")
		hideLayer("basic");
	else
		showLayer("basic");
		
	if(which != "summary")
		hideLayer("summary");
	else
		showLayer("summary");
		
	if(which != "operating")
		hideLayer("operating");
	else
		showLayer("operating");
		
	if(which != "cropYield")

		hideLayer("cropYield");
	else
		showLayer("cropYield");
		
	if(which != "investmentCost")
	{
		hideLayer("investmentCost");
	}
	else
		showLayer("investmentCost");
}


/**
 * gets all the unique crop names from the data set and populates html select
 */
function listCrops()
{	
	var cropSelect = getElement("crop");
	var stateSelect = getElement("state");
	var region = eval("dataSet.stateRegion." + removeNonJSONChars(stateSelect.options[stateSelect.selectedIndex].value));
	var crops = eval("dataSet.regionCrops." + removeNonJSONChars(region));

	crops.sort();
	
	cropSelect.options.length = 0;
	cropSelect.options[0] = new Option( "Select a crop", 1000);
	
	for(i=0; i<crops.length; i++)
	{
		cropSelect.options[i+1] = new Option( crops[i], crops[i]);
	}
//IE hack...expands dropdown without changing initial select box width
//	dropdown_menu_hack(cropSelect);
}

/**
 * gets all the states names from the data set and populates html select
 */
function listStates()
{
	var statesArray = new Array();
	var stateSelect = getElement("state");
	var states = dataSet.states;
	var state;
	
	states.sort();
	
	stateSelect.options[0] = new Option( "Select a state", 1000);
	
	for(i=0; i<states.length; i++)
	{
		state = states[i];
		stateSelect.options[i+1] = new Option( state, states[i]);
	}
}

/**
 * Clear all errors on the page
 */
function clearErrors()
{
	var divs = document.getElementsByTagName('div');
	
	for(var i=0; i<divs.length;i++)
	{
		if(divs[i].id.indexOf("Error") != -1)
		{
			divs[i].innerHTML = "";
		}
	}
}

/**
 * make sure we have everything ready to start
 */
function startEstimator()
{
	clearErrors();
	if (validate())
	{
		initFields();
		new Lightbox.base('box1');
	}	
}

/**
 * creates GET and window to pass all report variables to IA contact page
 * @return
 */
function passReportDataToIA()
{
	// base url
	var ia = "contact.aspx";

	// user entered values
	ia += "?crop=" + crop;
	ia += "&state=" + state;
	ia += "&acres=" + acres;
	ia += "&irrigationType=" + irrigationType;

	// crop data
	ia += "&water=" + getElement("water").innerHTML;
	ia += "&energy=" + getElement("energy").innerHTML;
	ia += "&fertilizer=" + getElement("fertilizer").innerHTML;
	ia += "&chemical=" + getElement("chemical").innerHTML;
	ia += "&irrigationLabor=" + getElement("irrigationLabor").innerHTML;
	ia += "&maintenance=" + getElement("maintenance").innerHTML;
	ia += "&cultivation=" + getElement("cultivation").innerHTML;
	ia += "&equipment=" + getElement("equipment").innerHTML;
	ia += "&harvestCosts=" + getElement("harvestCosts").innerHTML;
	ia += "&pricePerUnit=" + getElement("pricePerUnit").innerHTML;
	ia += "&yield=" + getElement("yield").innerHTML;
	
	// micro drip results
	ia += "&waterMicro=" + getElement("waterMicro").innerHTML;
	ia += "&energyMicro=" + getElement("energyMicro").innerHTML;
	ia += "&fertilizerMicro=" + getElement("fertilizerMicro").innerHTML;
	ia += "&chemicalMicro=" + getElement("chemicalMicro").innerHTML;
	ia += "&irrigationLaborMicro=" + getElement("irrigationLaborMicro").innerHTML;
	ia += "&maintenanceMicro=" + getElement("maintenanceMicro").innerHTML;
	ia += "&cultivationMicro=" + getElement("cultivationMicro").innerHTML;
	ia += "&equipmentMicro=" + getElement("equipmentMicro").innerHTML;
	ia += "&harvestCostsMicro=" + getElement("harvestCostsMicro").innerHTML;
	ia += "&pricePerUnitMicro=" + getElement("pricePerUnitMicro").innerHTML;
	ia += "&yieldMicro=" + getElement("yieldMicro").innerHTML;
	
	ia += "&growerNet=" + getElement("growerNet").innerHTML;
	ia += "&costShare=" + getElement("costShare").innerHTML;
	ia += "&netSystemCost=" + getElement("netSystemCost").innerHTML;
	
	// multiplication constants
	ia += "&IRRIGATION_TYPE_MULTIPLIER=" + MULTIPLIER;
	ia += "&UNIFORMITY_CONST=" + UNIFORMITY;
	ia += "&DRIP_MICRO_CONST=" + DRIP_MICRO;
	ia += "&ENERGY_CONST=" + ENERGY;
	ia += "&FERTILIZER_CONST=" + FERTILIZER;
	ia += "&CHEMICAL_CONST=" + CHEMICAL;
	ia += "&IRRIGATION_CONST=" + IRRIGATION;
	ia += "&MAINTENANCE_CONST=" + MAINTENANCE;
	ia += "&CULTIVATION_CONST=" + CULTIVATION;
	ia += "&EQUIPMENT_CONST=" + EQUIPMENT;
	ia += "&HARVEST_CONST=" + HARVEST; 
	ia += "&YIELD_CONST=" + YIELD;
	ia += "&REVENUE=" + REVENUE;
	
	// result
	ia += "&payback=" + calculateYearsToPayback();
	ia += "&additionalAcres=" + formatCurrency(calculateAdditionalIrrigatableLand());
	
	// co-brand
	if (cobrand) { ia += "&cb=" + cobrand; }
	
	window.open(ia);
}

//******************End Page Functions*****************//



//******************Variable Assignment Functions******//

/**
 * called to populate the initial drop down lists
 */
function init()
{
	hideAllBut("basic");
	listStates();
}

/**
 * once basic data has been entered, this loads the selected data set (state/region and crop defaults)
 * and then sets the non-editable fields as well as the user editable fields with the default data
 */
function initFields()
{	 
	initCropData();	
	
	setMultiplicationCoefficients();
	
	setVarsFromDataSet();
		
	setOperatingCostFields();
	setCropDataFields();
	setInvestmentFields();
	
	calculate();
}

/**
 * sets the operating cost fields for user selection and microdrip based on the irrigation type multiplier
 */
function setOperatingCostFields()
{
	//set original data set into hidden fields for report-crop, acres, state, irrigationType
	getElement("selectedCrop").innerHTML = "Crop: "+crop;
	getElement("selectedState").innerHTML = "State: "+state;
	getElement("selectedAcres").innerHTML = "Acres: "+acres;
	getElement("selectedIrrigationType").innerHTML = "Current Irrigation System: "+irrigationType;

	//alert("Setting operating cost fields");
	getElement("water").innerHTML = formatCurrency(water);
	getElement("energy").innerHTML = formatCurrency(energy);
	getElement("fertilizer").innerHTML = formatCurrency(fertilizer);
	getElement("chemical").innerHTML = formatCurrency(chemical);
	getElement("irrigationLabor").innerHTML = formatCurrency(irrigationLabor);
	getElement("maintenance").innerHTML = formatCurrency(maintenance);
	getElement("cultivation").innerHTML = formatCurrency(cultivation);
	getElement("equipment").innerHTML = formatCurrency(equipment);

	getElement("waterField").value = formatCurrency(water);
	getElement("energyField").value = formatCurrency(energy);
	getElement("fertilizerField").value = formatCurrency(fertilizer);
	getElement("chemicalField").value = formatCurrency(chemical);
	getElement("irrigationLaborField").value = formatCurrency(irrigationLabor);
	getElement("maintenanceField").value = formatCurrency(maintenance);
	getElement("cultivationField").value = formatCurrency(cultivation);
	getElement("equipmentField").value = formatCurrency(equipment);
	
	//alert("setting micro operating cost fields");
	microWater = formatCurrency(calculateAnnualWaterCostPerAcreForMicro());
	microEnergy = formatCurrency(energy * ENERGY);
	microFertilizer = formatCurrency(fertilizer * FERTILIZER);
	microChemical = formatCurrency(chemical * CHEMICAL);
	microIrrigation = formatCurrency(irrigationLabor * IRRIGATION);
	microMaintenance = formatCurrency(maintenance * MAINTENANCE);
	microCultivation = formatCurrency(cultivation * CULTIVATION);
	microEquipment = formatCurrency(equipment * EQUIPMENT);
	
	getElement("waterMicro").innerHTML = microWater;
	getElement("energyMicro").innerHTML = microEnergy;
	getElement("fertilizerMicro").innerHTML = microFertilizer;
	getElement("chemicalMicro").innerHTML = microChemical;
	getElement("irrigationLaborMicro").innerHTML = microIrrigation;
	getElement("maintenanceMicro").innerHTML = microMaintenance;
	getElement("cultivationMicro").innerHTML = microCultivation;
	getElement("equipmentMicro").innerHTML = microEquipment;
	
	//alert("setting micro operating cost multiplier fields");
	
	// update "constants"
	getElement("waterConstField").value = MULTIPLIER;
	getElement("energyConstField").value = ENERGY;
	getElement("fertilizerConstField").value = FERTILIZER;
	getElement("chemicalConstField").value = CHEMICAL;
	getElement("irrigationConstField").value = IRRIGATION;
	getElement("maintenanceConstField").value = MAINTENANCE;
	getElement("cultivationConstField").value = CULTIVATION;
	getElement("equipmentConstField").value = EQUIPMENT;

}

/**
 * sets the crop data fields from global vars
 */
function setCropDataFields()
{
	unit = cropData.yield.yieldUnit;
	
	//alert("Setting crop yield fields - " + yield + ", " + unit + ", " + pricePerUnit + ", " + harvestCosts);
	getElement("yield").innerHTML = formatCurrency(yield) + " " + unit;
	//alert("yieldField = " + getElement("yield").innerHTML);
	getElement("pricePerUnit").innerHTML = formatCurrency(pricePerUnit);
	getElement("harvestCosts").innerHTML = formatCurrency(harvestCosts);
	
	getElement("yieldField").value = formatCurrency(yield);
	getElement("pricePerUnitField").value = formatCurrency(pricePerUnit);
	getElement("harvestCostsField").value = formatCurrency(harvestCosts);
	
	//alert("setting micro crop yield fields");
	microYield = yield * YIELD;
	microRevenue = pricePerUnit * REVENUE;
	microHarvest = harvestCosts * HARVEST;
	
	getElement("yieldMicro").innerHTML = formatCurrency(microYield) + " " + unit;
	getElement("pricePerUnitMicro").innerHTML = formatCurrency(microRevenue);
	getElement("harvestCostsMicro").innerHTML = formatCurrency(microHarvest);

	getElement("harvestConstField").value = HARVEST;
	getElement("yieldConstField").value = YIELD;
	getElement("revenueConstField").value = REVENUE;

}

/**
 * sets investment cost fields from global vars
 */
function setInvestmentFields()
{
	//alert("setting investment fields");
	getElement("growerNet").innerHTML = formatCurrency(growerNet);
	getElement("costShare").innerHTML = formatCurrency(costShare);
	getElement("netSystemCost").innerHTML = formatCurrency(calculateNetSystemInvestmentCostPerAcre());
	
	getElement("growerNetField").value = formatCurrency(growerNet);
	getElement("costShareField").value = formatCurrency(costShare);
	getElement("netSystemCostField").value = formatCurrency(calculateNetSystemInvestmentCostPerAcre());
}


/**
 * sets the global vars from the default data set and basic user info
 */
function setVarsFromDataSet()
{	
	var selIrrigation = getElement("irrigationType");
	irrigationType = selIrrigation.options[selIrrigation.selectedIndex].value;
	waterCost = getElement("waterCost").value;
	acres = getElement("acres").value;
	
	et = cropData.efficiency.et;
	
	water = calculateAnnualWaterCostPerAcre();
	energy = cropData.operating.energy;
	fertilizer = cropData.operating.fertilizer;
	chemical = cropData.operating.chemical;
	irrigationLabor = cropData.operating.irrigationLabor;
	maintenance = cropData.operating.maintenance;
	cultivation = cropData.operating.cultivation;
	equipment = cropData.operating.equipment;

	yield = cropData.yield.yield;
	pricePerUnit = cropData.yield.marketPricePerUnit;
	harvestCosts = cropData.yield.harvestCosts;

	/**alert("water cost = " + waterCost + "\n" +
	"acres = " + acres + "\n" +
	"irrigation type = " + irrigationType + "\n" +
	"energy = " + cropData.operating.energy + "\n" + 
	"fertilizer = " + cropData.operating.fertilizer + "\n" + 
	"chemical = " + cropData.operating.chemical + "\n" + 
	"irrigationLabor = " + cropData.operating.irrigationLabor + "\n" + 
	"maintenance = " + cropData.operating.maintenance + "\n" + 
	"cultivation = " + cropData.operating.cultivation + "\n" + 
	"equipment = " + cropData.operating.equipment + "\n" + 
	"yield = " + cropData.yield.yield + "\n" + 
	"pricePerUnit = " + cropData.yield.marketPricePerUnit + "\n" + 
	"harvestCosts = " + cropData.yield.harvestCosts + "\n" + 
	"et = " + cropData.efficiency.et);
	*/
}

/**
 * sets the global vars based upon field values
 */
function setVarsFromFields()
{
	 //alert("setting vars from updated fields");
	 
	 var selCrop = getElement("crop");
	 crop = selCrop.options[selCrop.selectedIndex].value;
	 var selState = getElement("state");
	 state = selState.options[selState.selectedIndex].value;
	 var selIrrigation = getElement("irrigationType");
	 irrigationType = selIrrigation.options[selIrrigation.selectedIndex].value;
	 acres = getElement("acres").value;
	 
	 water = stripCommas(getElement("waterField").value);
	 energy = stripCommas(getElement("energyField").value);
	 fertilizer = stripCommas(getElement("fertilizerField").value);
	 chemical = stripCommas(getElement("chemicalField").value);
	 irrigationLabor = stripCommas(getElement("irrigationLaborField").value);
	 maintenance = stripCommas(getElement("maintenanceField").value);
	 cultivation = stripCommas(getElement("cultivationField").value);
	 equipment = stripCommas(getElement("equipmentField").value);
	 
	 //alert("yieldField = " + getElement("yieldField").value);
	 yield = stripCommas(getElement("yieldField").value);
	 pricePerUnit = stripCommas(getElement("pricePerUnitField").value);
	 harvestCosts = stripCommas(getElement("harvestCostsField").value);
	 
	 growerNet = stripCommas(getElement("growerNetField").value);
	 costShare = stripCommas(getElement("costShareField").value);
	 netSystemCost = stripCommas(getElement("netSystemCostField").value);
	 
	 // update "constants"
	 MULTIPLIER = getElement("waterConstField").value;
	 ENERGY =  getElement("energyConstField").value;
	 FERTILIZER =  getElement("fertilizerConstField").value;
	 CHEMICAL =  getElement("chemicalConstField").value;
	 IRRIGATION =  getElement("irrigationConstField").value;
	 MAINTENANCE =  getElement("maintenanceConstField").value;
	 CULTIVATION =  getElement("cultivationConstField").value;
	 EQUIPMENT =  getElement("equipmentConstField").value;
	 HARVEST =  getElement("harvestConstField").value;
	 YIELD =  getElement("yieldConstField").value;
	 REVENUE =  getElement("revenueConstField").value;
}

/**
 * uses crop/state information to select the default data set from the dataSet
 */
function initCropData()
{
	var selCrop = getElement("crop");
	crop = selCrop.options[selCrop.selectedIndex].value;
	 
	var stateSelect = getElement("state");
	var region = eval("dataSet.stateRegion." + removeNonJSONChars(stateSelect.options[stateSelect.selectedIndex].value));
	 
	cropData = eval("dataSet.regionalData." + removeNonJSONChars(region.toString()) + ".cropData." + removeNonJSONChars(crop));
	//alert("cropData(dataSet.regionalData." + removeNonJSONChars(region.toString()) + ".cropData." + removeNonJSONChars(crop) + ")");
}

/*
 * 
 */
function updateWaterVariables()
{
	var waterValue = getElement("waterField").value;
	waterCost = formatCurrency(calculateWaterCost(waterValue));
}

/**
 * sets irrigation type "constants" from the dataset for use as global vars
 * made user-editible in version 2.
 */
function setMultiplicationCoefficients()
{
	var selIrrigation = getElement("irrigationType");
	var irrigationType = selIrrigation.options[selIrrigation.selectedIndex].value;	
	var multiplicationCoefficients = eval("dataSet.irrigationConstants." + irrigationType);

	UNIFORMITY = multiplicationCoefficients.uniformity;
	ENERGY =  multiplicationCoefficients.energy;
	FERTILIZER =  multiplicationCoefficients.fertilizer;
	CHEMICAL =  multiplicationCoefficients.chemical;
	IRRIGATION =  multiplicationCoefficients.irrigationLabor;
	MAINTENANCE =  multiplicationCoefficients.maintenance;
	CULTIVATION =  multiplicationCoefficients.cultivation;
	EQUIPMENT =  multiplicationCoefficients.equipment;
	HARVEST =  multiplicationCoefficients.harvestCosts;
	YIELD =  multiplicationCoefficients.yield;
	REVENUE =  multiplicationCoefficients.revenuePerUnit;
	MULTIPLIER = multiplicationCoefficients.dripMicroMultiplier;

}
//****************End Variable Assignment Functions ********//


//****************Calculation Functions********************//
/**
 * calculates the final values given user-defined/changes values and 
 * constants global vars
 */ 
function calculate()
{
	clearErrors();
	setVarsFromFields();
	setOperatingCostFields();
	setInvestmentFields();
	setCropDataFields();
	
	userYield = calculateYieldFormula();

	// sets static fields with calculated values (difference between user and microdrip)
	
	var payback = calculateYearsToPayback();
	var additionalAcres = calculateAdditionalIrrigatableLand();

	if (payback > 0) {
	    getElement("yieldDiff").innerHTML = formatCurrency(additionalAcres) + " acres";
	    getElement("investmentYears").innerHTML = payback + " years";

	    getElement("yieldDiffBanner").innerHTML = formatCurrency(additionalAcres);
	    getElement("investmentBanner").innerHTML = payback;

	    getElement("yieldDiffOverlay").innerHTML = formatCurrency(additionalAcres);
	    getElement("investmentOverlay").innerHTML = payback;

	    vitshow("reportresult1"); vithide("reportresult2");
	    vitshow("childRight1"); vithide("childRight2");
	    vitshow("olReport1"); vithide("olReport2");
	}
	else {
	    getElement("reportresult2").innerHTML = "<strong>With the given conditions, payback is not possible.</strong>";
	    vitshow("reportresult2"); vithide("reportresult1");
	    getElement("childRight2").innerHTML = '<p><span class="h2">THANK YOU</span> for your input.</p><p><span class="h2">With the given conditions, payback is not possible.</span></p>';
	    vitshow("childRight2"); vithide("childRight1");
	    getElement("olReport2").innerHTML = '<p><span class="h2">THANK YOU</span> for your input.</p><p><span class="h2">With the given conditions, payback is not possible.</span></p>';
	    vitshow("olReport2"); vithide("olReport1");
	}
	
	hideAllBut("summary");
}

function vithide(id) {
    var elmnt = getElement(id);
//    elmnt.setAttribute("style", "display:none");
    elmnt.style.display = "none";
}
function vitshow(id) {
    var elmnt = getElement(id);
//    elmnt.setAttribute("style", "");
    elmnt.style.display = "inline";
}


/**
 * (Crop ET / Irrigation Eff) x Water Cost per Acre Foot
 */
function calculateAnnualWaterCostPerAcre()
{	
	return (et / UNIFORMITY) * waterCost; 
}

/**
 * 
 */
function calculateWaterCost(waterValue)
{
	return (waterValue/et) * UNIFORMITY;
}

/**
 * (Crop ET / Irrigation Eff) x Water Cost per Acre Foot
 */
function calculateAnnualWaterCostPerAcreForMicro()
{
	return (et / UNIFORMITY) * waterCost * MULTIPLIER; 
}

/**
 * (Grower Net per Acre - Cost Share)
 */
function calculateNetSystemInvestmentCostPerAcre()
{
	return growerNet - costShare;
}

/**
 * Grower Net Investment / (potential increased revenue + potential decreased costs) 
 */
function calculateYearsToPayback()
{
    var a = calculateNetSystemInvestmentCostPerAcre();
    var b = calculateYieldDiff();
    var c = calculateOperatingCostsDiff();
    var d = b + c;

    if (d < 0) {
        return d;
    }
    else {
        var e = formatCurrency(a / d);
        return e;
    }
//    return formatCurrency(calculateNetSystemInvestmentCostPerAcre() / (calculateYieldDiff() + calculateOperatingCostsDiff()));
}

/**
 * difference between user selected value and drip value
 */
function calculateYieldDiff()
{
    var a = calculateMicroYieldFormula();
    var b = calculateYieldFormula();
	return calculateMicroYieldFormula() - calculateYieldFormula();	
}

/**
 * difference between user selected operating costs and drop operating costs
 */
function calculateOperatingCostsDiff()
{
    var a = calculateOperatingCosts();
    var b = calculateMicroOperatingCosts();
    
	return calculateOperatingCosts() - calculateMicroOperatingCosts();
}

/**
 * straight up calculation from global vars
 */
function calculateYieldFormula()
{
	return yield * pricePerUnit; 
}

/**
 * calculates yield with Micro costs
 */
function calculateMicroYieldFormula()
{
	return microYield * microRevenue;
}

/**
 * calculates sum of operating costs for user selected values
 */
function calculateOperatingCosts()
{
    var a = parseInt(calculateAnnualWaterCostPerAcre());
    var b = parseInt(energy) + parseInt(chemical);
    var c = parseInt(fertilizer);
    var d = parseInt(irrigationLabor);
    var e = parseInt(maintenance);
    var f = parseInt(cultivation);
    var g = parseInt(equipment);
    var h = parseInt(harvestCosts);
    
	return parseInt(calculateAnnualWaterCostPerAcre()) + parseInt(energy) + parseInt(chemical) + parseInt(fertilizer) + parseInt(irrigationLabor) + parseInt(maintenance) + parseInt(cultivation) + parseInt(equipment) + parseInt(harvestCosts);
}

/**
 * calculates sum of operating costs for drip micro
 */ 
function calculateMicroOperatingCosts()
{
    var a = parseInt(calculateAnnualWaterCostPerAcreForMicro());
    var b = parseInt(microEnergy);
    var c = parseInt(microChemical);
    var d = parseInt(microFertilizer);
    var e = parseInt(microIrrigation);
    var f = parseInt(microMaintenance);
    var g = parseInt(microCultivation);
    var h = parseInt(microEquipment);
    var j = parseInt(microHarvest);

	return parseInt(calculateAnnualWaterCostPerAcreForMicro()) + parseInt(microEnergy) + parseInt(microChemical) + parseInt(microFertilizer) + parseInt(microIrrigation) + parseInt(microMaintenance) + parseInt(microCultivation) + parseInt(microEquipment) + parseInt(microHarvest);
}

/**
 *  ((drip-micro % / current system %) - 1) x total acres entered
 */
function calculateAdditionalIrrigatableLand()
{
	return ((DRIP_MICRO /  UNIFORMITY) - 1) * acres;
}

/**********************End Calculation Functions****************************/

/************************Housekeeping and Validation*****************/
// used to format numbers (and currency) to strip zeroes past the hundredths place and 
// add zeroes to Integers
function formatCurrency(num) 
{
	var num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;

	return num + '.' + cents;
}

/**
 * removes commas from string
 */
function stripCommas(numString) 
{
    var re = /,/g;
    return numString.replace(re,"");
}

/**
 * validates that user entered value is a number
 */
function validateNumber(field)
{
	clearErrors();
	var value = getElement(field).value;
	var errorField = field + "Error";
	
	if(isNaN(value))
	{
		setTimeout(function(){getElement(field).focus()}, 10);
		setTimeout(function(){getElement(errorField).innerHTML = "You must enter a valid number for this field."}, 11);
		return false;
	}	
	return true;
}

/**
 * removes a dash from strings
 */
function stripDash(string)
{
	return string.replace("-", "");
}

/**
 * Validate user entered values from drop downs and 
 * fields on the initial screen
 */
function validate()
{
	var ok = true;
	var selCrop = getElement("crop");
	
	if(selCrop.options[selCrop.selectedIndex].value == 1000)
	{
		getElement("cropError").innerHTML = "You must select a crop to continue.";
		ok = false;
	} 
	
	var selState = getElement("state");
	if(selState.options[selState.selectedIndex].value == 1000)
	{
		getElement("stateError").innerHTML = "You must select a state to continue.";
		ok = false;
	}
	
	
	var selIrrigation = getElement("irrigationType");
	if(selIrrigation.options[selIrrigation.selectedIndex].value == 1000)
	{
		getElement("irrigationError").innerHTML = "You must select a irrigation type to continue.";
		ok = false;
	} 
	
	
	if(getElement("acres").value == "" || isNaN(getElement("acres").value))
	{
		getElement("acresError").innerHTML = "You must enter a valid number for acres.";
		ok = false;
	}	
	
	
	if(getElement("waterCost").value == "" || isNaN(getElement("waterCost").value))
	{
		getElement("waterCostError").innerHTML = "You must enter a valid number for water cost.";
		ok = false;
	}
	if (!ok)
		return false;
		
	return true;
	
}

/**
 * validates user edited "constant" multipliers to ensure that 
 * they are valid numbers and they are within range
 */
function validateConstValue(field)
{
	clearErrors();
	if (getElement(field) == null)
	{
		alert("field - " + field + " not found");
		return;
	}
	
	var value = getElement(field).value;
	var errorField = field + "Error";
	
	if(isNaN(value))
	{
		setTimeout(function(){getElement(field).focus()}, 10);
		setTimeout(function(){getElement(errorField).innerHTML = "You must enter a valid number for this field."}, 11);
		return false;
	}	
	
	if(validateRange(value) == false)
	{
		setTimeout(function(){getElement(field).focus()}, 10);
		setTimeout(function(){getElement(errorField).innerHTML = "You must enter a valid number range \n(between  " + LOWER_BOUND + " and " + UPPER_BOUND + " for this field."}, 11);
		return false;
	}
	return true;
}

function throwYieldAlert()
{
	var alert = "Please change drip-micro % for harvest cost to same decimal for accuracy";
	var errorField = getElement("yieldConstFieldError");
	
	errorField.innerHTML = alert;
}

/**
 * validates a number for a globally defined range
 */
function validateRange(value)
{
	var num = (+value);
	if (num < LOWER_BOUND || num > UPPER_BOUND)
		return false;
		
	return true;
}

/**
 * Used to remove spaces from JSON map keys
 * @param string
 * @return
 */
function removeNonJSONChars(string) 
{
	//alert("have " + string + ", returning " + string.replace(/(\s|-|\(|\)|,)/g, ""));
	return string.replace(/(\s|-|\(|\)|,|\/)/g, "");
}

/**
 * Iterates over objects and displays the result
 */
function iterateOverObject(anObject)
{
	for (var propName in anObject) 
	{
		alert(propName + " = " + anObject[propName]);
	}
}

/********************End Housekeeping Functions*************************/



// this is it... stop reading