var selelectedSolutionId;

var impactCalculators = new Array(
                                  new ImpactCalculation(1, "Input the number of kilometers you drive each year (the average in North America is about 20,000).  Next, input the fuel economy of the hybrid vehicle you own or intend to purchase in litres per 100km or MPG.  A good reference of new hybrid fuel economy is <a href='http://www.fueleconomy.gov/feg/compx2008f.jsp?hiddenField=hybrid&year=2007&si=true' target='_new'>here</a>.<br/><br/>The average fuel economy of all vehicles in North America right now is about 11.2 L/100km or 21 MPG.  There are many hybrid models to choose from that give fuel economy as good as 5 L/100km or 47 MPG.", new Array(new FormulaInput("How far do you drive per year?", "distance", "20000"), new FormulaInputSelect("Distance units", new Array("km", "miles")), new FormulaInput("What is the fuel economy of the hybrid in L/100km or MPG?", "L/100km or MPG"), new FormulaInputSelect("Units", new Array("L/100km", "MPG"))), hybridVehicleCalculate),
                                  new ImpactCalculation(2, "Estimating the exact savings of a solar water heater is fairly difficult, but here we will assume the \"average\" North American home.  This lets us use the average values for solar intensity.  If you live in a very hot or very cold area, the values may differ by 10 or 20%.", new Array(new FormulaInputSelect("How many people are in your household?", new Array("1", "2", "3", "4", "5+"))), solarWaterCalculate),
                                  new ImpactCalculation(3, "Input the average number of kilometers per week you use sustainable transportation, including walking, biking and public transit. The calculated savings are compared to driving the same distance minus any recurring cost such as a transit pass.  Savings are actually higher when compared to the cost of vehicle ownership, but that is highly variable so won't be considered here.<br/><br/>To estimate how much you travel per month consider a typical weekday as a start and work up from there to find a rough estimate.<br/><br/>Use your judgement for the monthly recurring cost.  Entering a value of $80 for a transit pass, for example, may not reflect your true costs if your alternative was to purchase a vehicle, maintain it, and pay insurance.  In such a case leaving the value as zero may be appropriate.", new Array(new FormulaInput("Approximately how far per month?", "distance"), new FormulaInputSelect("Distance units", new Array("km", "miles")), new FormulaInput("Input any monthly recurring cost?", "dollars", "0")), sustainableTransportationCalculate),
                                  new ImpactCalculation(4, "Input the average number of kilometers per week you bike or walk to work. If necessary, change the number of months per year this is achieved. If winter doesn't allow you to use this form of transportation, input a lower number than 12.  The calculated savings are compared to driving the same distance.", new Array(new FormulaInput("How far per week?", "distance"), new FormulaInputSelect("Distance units", new Array("km", "miles")), new FormulaInput("How many months/year?", "months", "12")), bikeToWorkCalculate),
                                  new ImpactCalculation(8, "Input the number of CF bulbs you will install.  The calculations assume an average daily usage per bulb of approximately 3-6 hours.", new Array(new FormulaInput("How many bulbs?", "bulbs")), cfBulbCalculate),
                                  new ImpactCalculation(9, "Input the average number of loads of laundry done in your household per week.  If you live in a colder climate and can't hang-dry during the winter months, enter a lower value for months/year.  (Although, clothes can still be hang-dryed outside or inside)", new Array(new FormulaInput("How many loads/week?", "loads"), new FormulaInput("How many months/year?", "months", "12")), hangDryCalculate),
                                  new ImpactCalculation(10, "The actual savings provided by a programmable thermostat depend on a large number of factors such as how you set the old thermostat, how much you set the new thermostat to adjust at times of the day, etc.  We will therefore base the calculation of how much the average person would save when using the programmable thermostat in a reasonable way.", new Array(), programmableThermostatCalculate),
                                  new ImpactCalculation(11, "Input the average number of loads of laundry done in your household per week where you will change from hot to cold water.", new Array(new FormulaInput("How many loads/week?", "loads")), coldWaterWashCalculate),
                                  new ImpactCalculation(12, "Input the average yearly kilowatt-hours your household consumes.  If you don't know exactly, use this as a guide: the average household kWh consumed per year in North America ranges between 5,000 to 15,000.  A typical single person in an apartment would be closer to 6,000 and a typical family with multiple children in a house would be closer to 12,000.  A typical working couple with no children would be around 8,000.  Normally when you sign up with a clean energy provider they tell you how many extra cents per kWh they will charge, above normal utility rates.  This is usually around 3 cents.", new Array(new FormulaInput("How many kWh/year?", "kWh", "8000"), new FormulaInput("How much extra do you pay per kWh?", "kWh", "0.03")), cleanEnergyCalculate),
                                  new ImpactCalculation(13, "Input the number of showerheads replaced with low-flow equivalents.  The estimated saving for the average household is $150 and 135kg CO2 per year per showerhead.", new Array(new FormulaInput("How many showerheads?", "showerheads", "1")), lowFlowShowerCalculate),
                                  new ImpactCalculation(14, "The savings from lowering the temperature of a water heater depend on the original temperature, which depending on the model can be difficult to determine.  We will therefore base the savings calculation on the average household setting of at least 55C or 140F being reduced to 45C or 120F.", new Array(), lowerWaterHeaterCalculate),
                                  new ImpactCalculation(15, "Input the number of kilometers you drive each year (the average in North America is about 20,000).  Next, input the fuel economy of the hybrid vehicle you own or intend to purchase in L/100km.  A good reference of new vehicle fuel economy is <a href='http://www.fueleconomy.gov/feg/bestworst.shtml' target='_new'>here</a>.<br/><br/>The average fuel economy of all vehicles in North America right now is about 11.2 L/100km or 21 MPG.  There are many hybrid models to choose from that give fuel economy as good as 5 L/100km or 47 MPG.", new Array(new FormulaInput("How far do you drive per year?", "distance", "20000"), new FormulaInputSelect("Distance units", new Array("km", "miles")), new FormulaInput("What is the fuel economy of the vehicle in L/100km or MPG?", "L/100km or MPG"), new FormulaInputSelect("Units", new Array("L/100km", "MPG"))), conventionalVehicleCalculate),
                                  new ImpactCalculation(16, "Recyclable materials include papers, cardboard, glass, plastic and aluminum (some locations accept other metals as well).  Input the amount of these recyclable materials you actually recycle on a typical week.", new Array(new FormulaInputSelect("How much recyclable material does your household recycle?", new Array("All", "Most", "Some")), new FormulaInput("How many people are in your household?", "People", "1")), recycleCalculate),
                                  new ImpactCalculation(17, "Input the amount of carbon offsets you have purchased.  The CO2 reduction will be immediately added to your profile.  You can add this for each separate purchase you have made.", new Array(new FormulaInput("How many tons of CO2 were offset?", "Tons"), new FormulaInput("How much did the offsets cost?", "Dollars")), offsetsCalculate),
                                  new ImpactCalculation(18, "Select the old appliance you are replacing, or have replaced, from the list below.  This option will use the average savings of a model manufactured before 1993 compared to a new model today.<br/><br/><b>OR</b><br/><br/>Enter the number of kWh per year the new appliance uses compared to the old.  This may not be easy to find for older models, so you may want to use the values from the Full Details page linked below.  For new models the average yearly kWh usage is shown on the Energy Star sticker.", new Array(new FormulaInputSelect("Appliance, or select Custom", new Array("Fridge", "Freezer", "Clothes Washer", "Clothes Dryer", "Dish Washer", "Television", "Custom")), new FormulaInput("Custom: kWh savings per year", "kWh", "", false)), oldApplianceCalculate),
                                  new ImpactCalculation(19, "The average person of developed countries consumes 8-11 ounces, or 200-300g, of meat per day.  Input below how much below that average you try to consume.  For example, a person trying to consume only 50% of the average might not eat meat for lunch and have only a small portion with dinner, or might only eat meat every other day.  100% would mean a vegetarian.  The cash savings are listed as zero because it would entirely depend on a persons own eating habits.", new Array(new FormulaInputSelect("Percent less than average meat consumption (%)", new Array("10", "20", "30", "40", "50", "60", "70", "80", "90", "100"))), lessMeatCalculate),
                                  new ImpactCalculation(20, "The savings from a water heater blanket are fairly standardized, so no questions are required to be answered.  Simply hit Calculate to see the results or Add it to your profile.", new Array(), waterHeaterBlanketCalculate),
                                  new ImpactCalculation(21, "The CO2 offset by composting is largely based on how many people are in your household, assuming most eligible material is being composted for them all.  Adjust your answer below accordingly.", new Array(new FormulaInputSelect("How many people are in your household?", new Array("1", "2", "3", "4", "5", "6", "7", "8")), new FormulaInputSelect("How much money do you save per year not having to buy fertilizer?", new Array("0", "20", "40", "60", "80", "100", "150"))), compostingCalculate),
                                  new ImpactCalculation(22, "The savings from a tankless water heater compared to a natural gas tank is almost entirely based on the number of residents in your home.", new Array(new FormulaInputSelect("How many people are in your household?", new Array("1", "2", "3", "4", "5", "6", "7", "8"))), tanklessWaterCalculate),
                                  new ImpactCalculation(23, "Input the number of bags you currently use per week.  If you are already enjoying reusable bags, input the number of bag-uses per week.", new Array(new FormulaInputSelect("How many bags do you use per week?", new Array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"))), reusableBagsCalculate),
                                  new ImpactCalculation(24, "With this calculator you can enter an ongoing action that doesn't fit within the other choices.  For example, if you regularly perform some action that you can estimate saves 10 pounds of CO2 per day, just multiply that number by 365 (3,650) and divide by 2,200 pounds in a ton.  Here that would give about 1.6 tons per year.", new Array(new FormulaInput("Name your custom ongoing action", "name", ""), new FormulaInput("How many tons of CO2 do you estimate this saves per year?", "co2_savings", "1"), new FormulaInput("How much money do you estimate this saves per year?", "cash_savings", "1")/*, new FormulaInputSelect("What category best describes this action?", new Array("Renewable Energy", "Transportation", "Conservation", "Nature and Environment", "Politics", "Consumer Products", "Recycling"))*/), customOngoingCalculate),
                                  new ImpactCalculation(25, "With this calculator you can enter a one-time action that doesn't fit within the other choices.  For example, if you decided to take a train instead of flying on vacation and can estimate that CO2 savings to be 1 ton of CO2, enter that value below.", new Array(new FormulaInput("Name your custom one-time action", "name", ""), new FormulaInput("How many tons of CO2 do you estimate this saves?", "co2_savings", "1"), new FormulaInput("How much money do you estimate this saves?", "cash_savings", "1")/*, new FormulaInputSelect("What category best describes this action?", new Array("Renewable Energy", "Transportation", "Conservation", "Nature and Environment", "Politics", "Consumer Products", "Recycling"))*/), customOnetimeCalculate),
                                  new ImpactCalculation(26, "The cash and CO2 savings depend on the size of gas mower being replaced or not purchased, and the size of the mowing area.  A riding mower would count as Large.", new Array(new FormulaInputSelect("What size of gas mower?", new Array("Average", "Small", "Large")), new FormulaInputSelect("What size of mowing area?", new Array("Average", "Small", "Large"))), gasMowerCalculate)
                                  );

function getImpactCalculator(oSolution) {
    for (var i = 0; i < impactCalculators.length; i++) {
        if (impactCalculators[i].solutionId == oSolution.id) {
            return impactCalculators[i];
        }
    }
    return null;
}

/**
 * Calculate the impact of the currently selected solution.
 */
function calculateImpact() {
    var solution = getSolution(selectedSolutionId);
    var calculator = getImpactCalculator(solution);
    var arrValues = new Array();
    // Collect input params
    for (var i = 0; ; i++) {
	var input = document.getElementById("calcInput" + i);
	if (input == null) {
	    break;
	}
        if (input.options != null) {
            arrValues[arrValues.length] = input.options[input.selectedIndex].value;
        } else {
            var formulaInput = calculator.inputs[i];
	    if (input.value == "" && formulaInput.required) {
		alert("Please enter a value for '" + formulaInput.name + "'");
		return;
	    } else if (formulaInput.units != "name" && isNaN(input.value) && formulaInput.required) {
		alert("Please enter a valid number value for '" + formulaInput.name + "'");
		return;
	    }
	    arrValues[arrValues.length] = input.value;
        }
    }

    if (calculator != null) {
        var memberImpact = calculator.calculator(arrValues);

        if (memberImpact == null) {
            return null;
        }

        var objResults = document.getElementById("calcResults");
        if (solution.isOngoing()) {
          objResults.innerHTML = "Each year you could save up to <b>" + kgToPounds(memberImpact.co2Savings) + " lbs</b> or <b>" + memberImpact.co2Savings + " kg</b> of CO2 emissions";
          if (memberImpact.cashSavings > 0) {
            objResults.innerHTML += " and up to <b>$" + memberImpact.cashSavings + "</b>";
          }
        } else {
          objResults.innerHTML = "You could save up to <b>" + kgToPounds(memberImpact.co2Savings) + " lbs</b> or <b>" + memberImpact.co2Savings + " kg</b> of CO2 emissions";
          if (memberImpact.cashSavings > 0) {
            objResults.innerHTML += " and up to <b>$" + memberImpact.cashSavings + "</b>";
          }
        }

        //$("#calcResultsWrapper").css("visibility", "visible");
        $("#calcResultsWrapper").fadeIn(1000);

        return memberImpact;
    } else {
        return null;
    }
}

function getSolution(id) {
    // inefficient loop
    for (var i = 0; i < solutions.length; i++) {
	if (solutions[i].id == id) {
	    return solutions[i];
	}
    }
    return null;
}

function renderYourImpact() {
  var listHtml = "";

  var totalCash = 0.0;
  var totalCO2 = 0.0;
  for (var i = 0; i < memberImpacts.length; i++) {
    var cash = memberImpacts[i].cashSavings;
    var co2 = memberImpacts[i].co2Savings;
    totalCash += parseFloat(cash);
    totalCO2 += parseFloat(co2);

    listHtml += "<div class='impactItem'><img src='" + websiteRoot + "/img/icon_tick.gif'/><div class='impactItemName'>" + memberImpacts[i].name + "</div></div>";
  }

  var totalHtml = "";
  if (memberImpacts.length == 0) {
    totalHtml += "<p>Nothing saved to your impact profile yet.</p>";
  } else {
    totalHtml += "<p>Each year you will save up to <b>" + totalCO2 + "kg</b> CO2 and <b>$" + totalCash + "</b> from all your ongoing actions.</p>";
  }

  $("#yourImpactTotal").html(totalHtml);
  $("#yourImpactList").html(listHtml);
}

function showCalculator(solutionId) { 
    selectedSolutionId = solutionId;
    var solution = getSolution(solutionId);

    // UI elements to fill in
    var calcTitle = document.getElementById("calcTitle");
    var calcDesc = document.getElementById("calcDescription");
    var calcSolutionLink = document.getElementById("calcSolutionLink");
    var calcImage = document.getElementById("calcImage");
    var calcInputs = document.getElementById("calcInputs");
    
    calcTitle.innerHTML = solution.name;
    calcImage.innerHTML = "<img src=\"" + solution.image + "\" height=\"150\" width=\"150\" border=\"0\"/>";

    var calculator = getImpactCalculator(solution);
    if (calculator != null) {
        calcDesc.innerHTML = calculator.description;
        calcSolutionLink.innerHTML = "See the <a href='" + solution.url + "'>Full details</a> of this sustainable action.";
        
	var sInputs = "";
	for (var i = 0; i < calculator.inputs.length; i++) {
	    var input = calculator.inputs[i];
            if (input.options == null) {
                var size = 8;
                if (input.units == "name") {
                    size = 20;
                }
                sInputs += "<div class=\"calcInputRow\">" + input.name + " <input type=\"text\" name=\"calcInput" + i + "\" id=\"calcInput" + i + "\" size=\"" + size + "\"";
                if (input.defaultVal != null && input.defaultVal != "") {
                    sInputs += " value=\"" + input.defaultVal + "\"";
                }
                sInputs += "/></div>";
            } else {
                sInputs += "<div class=\"calcInputRow\">" + input.name + " <select name=\"calcInput" + i + "\" id=\"calcInput" + i + "\">";
                var opts = input.options;
                for (var j = 0; j < opts.length; j++) {
                    sInputs += "<option value=\"" + opts[j] + "\">" + opts[j] + "</option>";
                }
                sInputs += "</select></div>";            
            }
	}
	calcInputs.innerHTML = sInputs;
        $("#calcActions").show();
    } else {
	calcDesc.innerHTML = "This calculator is not yet finished.  We are collecting data to make it as accurate as possible.";
        calcSolutionLink.innerHTML = "See the <a href='" + websiteRoot + "/solutions?id=" + solution.id + "'>Full details</a> of this sustainable action.";
	calcInputs.innerHTML = "";
        $("#calcActions").hide();
    }

    $("#calcResultsWrapper").hide();
    $("#calcBottomMessage").hide();
    var coords = getElementPosition("calcList-" + solutionId);
    coords.y -= 20;
    coords.x += 75;
    if ($('#impactCalculator').is (':visible') && $('#impactCalculator').parents (':hidden').length == 0) {
        $("#impactCalculator").animate({
                top: coords.y + "px",
                left: coords.x + "px"}, 1000);
    } else {
        $("#impactCalculator").css("top", coords.y + "px");
        $("#impactCalculator").css("left", coords.x + "px"); 
        $("#impactCalculator").fadeIn("slow");
    }
}

// Can set a function for a callback after an add
var postAddCallback = null;
var pendingChallengeId = null;

/**
 * Add a member impact.
 */
function addMemberImpact(memberImpact) {
  if (memberImpact == null) {
    showStatusError("Nothing to add."); 
    return;
  }
  
  if (memberImpact.co2Savings < 0) {
    showStatusError("Can't add a negative CO2 savings."); 
    return;
  }

  showStatusWorking("Adding impact...");

  var sUrl = websiteRoot + "/ajax/add_impact.php?name=" + memberImpact.name + "&co2_savings=" + memberImpact.co2Savings + "&cash_savings=" + memberImpact.cashSavings + "&solution_id=" + memberImpact.solutionId;
  if (pendingChallengeId != null) {
      sUrl += "&pending_challenge_id=" + pendingChallengeId;
  }
  $.ajax({
      url: sUrl,
      type: 'GET',
      dataType: 'html',
      timeout: 10000,
      error: function(request, errMsg, errObj) {
	 showStatusError("Error adding impact."); 
      },
      success: function(html){
	  showStatusComplete("Impact added.");
	  memberImpacts[memberImpacts.length] = memberImpact;
	  renderYourImpact();
          if (postAddCallback != null) {
              postAddCallback();
          }
      }
  });
}

/**
 * Delete a member impact.
 */
function deleteMemberImpact(memberImpactId) {
  if (memberImpactId == null) {
    alert("Error");
    return;
  }

  showStatusWorking("Deleting impact...");

  var sUrl = websiteRoot + "/ajax/delete_impact.php?member_impact_id=" + memberImpactId;
  $.ajax({
      url: sUrl,
      type: 'GET',
      dataType: 'html',
      timeout: 10000,
      error: function(request, errMsg, errObj){
	 showStatusError("Error deleting impact: " + errMsg); 
      },
      success: function(html){
	  showStatusComplete("Impact deleted.");
	  $("#memberImpactId" + memberImpactId).remove();
          // TODO update totals
      }
  });
}


/**
 * Constants for calculations
 */
var PRICE_LITER_GAS = 1.00;
var PRICE_KWH = 0.07;
var KG_CO2_PER_KWH = 0.7;
var MILES_TO_KM = 1.61;
var AVG_MPG = 21;
var AVG_KM_PER_L = 11.2;
var KG_CO2_PER_L = 2.3;
var CALORIES_PER_KM_BIKED = 21.875;

/**
 * Calculate functions for the solutions.
 */
function bikeToWorkCalculate(arrParams) {
    // arrParams[0] == distance
    // arrParams[1] == km/miles
    // arrParams[2] == months
    var kmweekly = parseInt(arrParams[0]);
    var distanceUnit = arrParams[1];
    if (distanceUnit == "miles") {
        kmweekly = kmweekly * MILES_TO_KM;
    }
    var months = parseInt(arrParams[2]);

    if (kmweekly > 1000) {
        alert("Weekly distance is too high");
        return null;
    }

    if (months > 12 || months < 1) {
        alert("Enter a number of months between 1 and 12");
        return null;
    }

    var totalKM = kmweekly * 4 * months;
    var savedLiters = totalKM / AVG_KM_PER_L;;
    var kgCO2Saved = savedLiters * KG_CO2_PER_L;
    var moneySaved = PRICE_LITER_GAS * savedLiters;    

    return new MemberImpact("Manual transportation to work (" + arrParams[0] + " " + distanceUnit + "/week for " + months + " months/year)", kgCO2Saved.toFixed(0), moneySaved.toFixed(0), 4);
}

function sustainableTransportationCalculate(arrParams) {
    // arrParams[0] == distance/month
    // arrParams[1] == km/miles
    // arrParams[2] == monthly cost
    var kmmonthly = parseInt(arrParams[0]);
    var distanceUnit = arrParams[1];
    if (distanceUnit == "miles") {
        kmmonthly = kmmonthly * MILES_TO_KM;
    }
    var monthlyCost = parseFloat(arrParams[2]);

    if (kmmonthly > 5000) {
        alert("Monthly distance is too high");
        return null;
    }

    var totalKM = kmmonthly * 12;
    var savedLiters = totalKM / AVG_KM_PER_L;;
    var kgCO2Saved = savedLiters * KG_CO2_PER_L;
    var moneySaved = (PRICE_LITER_GAS * savedLiters) - (monthlyCost * 12);    

    return new MemberImpact("Exclusive sustainable transportation (" + arrParams[0] + " " + distanceUnit + "/month with cost of $" + monthlyCost + "/month)", kgCO2Saved.toFixed(0), moneySaved.toFixed(0), 3);
}

function cfBulbCalculate(arrParams) {
    // 125kg of CO2 saved per year by switching one CF bulb
    // Calculations here: http://hybridblog.typepad.com/my_weblog/2006/04/equating_prius_.html

    var numBulbs = parseInt(arrParams[0]);

    if (numBulbs < 1) {
        alert("Number of bulbs needs to be at least 1");
        return null;
    }

    if (numBulbs  > 100) {
        alert("Number of bulbs is too high for one house");
        return null;
    }
    
    var co2Savings = numBulbs * 70;
    var moneySaved = numBulbs * 100 * PRICE_KWH; // 100kWh and $0.10/kWh
    
    return new MemberImpact("Installing " + numBulbs + " CF Bulbs", co2Savings.toFixed(0), moneySaved.toFixed(0), 8);
}

function hybridVehicleCalculate(arrParams) {
    return allVehicleCalculate(arrParams, "Hybrid vehicle", 1);
}

function conventionalVehicleCalculate(arrParams) {
    return allVehicleCalculate(arrParams, "Conventional fuel-efficient vehicle", 15);
}

function allVehicleCalculate(arrParams, sName, iSolutionId) {
    // arrParams[0] == distance/year
    // arrParams[1] == km/miles
    // arrParams[2] == l/100km or MPG
    // arrParams[3] == units (L/100km or MPG)

    var kmyearly = parseInt(arrParams[0]);
    var distanceUnit = arrParams[1];
    if (distanceUnit == "miles") {
        kmyearly = kmyearly * MILES_TO_KM;
    }
    var inputFuelEcon = parseFloat(arrParams[2]); // in l/100km or MPG
    var units = arrParams[3]; 

    if (kmyearly > 250000) {
        alert("Distance driven per year is too high.");
        return null;
    }

    var avgFuelEcon = 11.2;

    // Convert input fuel econ to L/100km
    var fuelEcon = inputFuelEcon;
    if (units == "MPG") {
        fuelEcon = (235.21 / inputFuelEcon).toFixed(0);
        if (fuelEcon > 100) {
            alert("MPG value is too high");
            return null;
        }
    } else {
        if (fuelEcon < 3) {
            alert("L/100km value is too low");
            return null;
        }
        if (fuelEcon > 50) {
            alert("L/100km value is too high");
            return null;
        }
    }

    var avgLused = (kmyearly / 100) * avgFuelEcon;
    var hybridLused = (kmyearly / 100) * fuelEcon;

    var kgCO2PerLiter = 2.3;

    var savedLiters = avgLused - hybridLused;
    var kgCO2Saved = savedLiters * kgCO2PerLiter;
    var moneySaved = PRICE_LITER_GAS * savedLiters;    

    return new MemberImpact(sName + " (" + arrParams[0] + " " + distanceUnit + "/year at " + inputFuelEcon + " " + units + ")", kgCO2Saved.toFixed(0), moneySaved.toFixed(0), iSolutionId);
}

function hangDryCalculate(arrParams) {
    // arrParams[0] == loads/week
    // arrParams[1] == months
    var loads = parseInt(arrParams[0]);
    var months = parseInt(arrParams[1]);

    if (loads < 1 || loads > 50) {
        alert("Enter a reasonable number of weekly loads");
        return null;
    }

    if (months > 12 || months < 1) {
        alert("Enter a number of months between 1 and 12");
        return null;
    }

    // 1 load == 1 hour dryer operation == 5 kWh
    var totalLoads = loads * 4 * months;
    var totalkWh = totalLoads * 5;
    var totalCO2 = totalkWh * KG_CO2_PER_KWH;

    // Use $0.07/kWh
    var moneySaved = totalkWh * PRICE_KWH;

    return new MemberImpact("Hang-drying clothes (" + loads + " loads/week for " + months + " months/year)", totalCO2.toFixed(0), moneySaved.toFixed(0), 9);
}

function cleanEnergyCalculate(arrParams) {
    var kwh = parseInt(arrParams[0]);
    var extraCost = parseFloat(arrParams[1]);

    if (kwh < 1 || kwh > 50000) {
        alert("Enter a reasonable value for KWH");
        return null;
    }

    if (extraCost < 0 || extraCost > 5) {
        alert("Enter a reasonable extra cost");
        return null;
    }
    
    var co2Savings = kwh * KG_CO2_PER_KWH;
    var totalCost = kwh * extraCost;
    
    return new MemberImpact("Switching to a clean energy provider (" + kwh + "kWh/year costing an extra $" + totalCost + "/year)", co2Savings.toFixed(0), 0, 12);
}

function lowFlowShowerCalculate(arrParams) {
    var showerheads = parseInt(arrParams[0]);
    
    if (showerheads < 1 || showerheads > 10) {
        alert("Enter a reasonable number of showerheads.");
        return null;
    }

    var co2Savings = showerheads * 135;
    var moneySaved = showerheads * 150;
    
    return new MemberImpact("Installing " + showerheads + " low-flow showerheads", co2Savings.toFixed(0), moneySaved.toFixed(0), 13);
}

function coldWaterWashCalculate(arrParams) {
    // arrParams[0] == loads/week
    var loads = parseInt(arrParams[0]);

    if (loads < 1 || loads > 50) {
        alert("Enter a reasonable number of loads.");
        return null;
    }

    var totalLoads = loads * 52;
    var totalkWh = totalLoads * 1.85;
    var totalCO2 = totalkWh * KG_CO2_PER_KWH;

    // Use $0.07/kWh
    var moneySaved = totalkWh * PRICE_KWH;

    return new MemberImpact("Wash clothes with cold water (" + loads + " loads/week)", totalCO2.toFixed(0), moneySaved.toFixed(0), 11);
}

function programmableThermostatCalculate(arrParams) {
    // no args
    return new MemberImpact("Use a programmable thermostat", 800, 150, 10);
}

function lowerWaterHeaterCalculate(arrParams) {
    // no args
    return new MemberImpact("Lower water-heater temperature", 225, 30, 14);
}

function recycleCalculate(arrParams) {
    // arrParams[0] == All, Most, Some
    var amount = arrParams[0];
    var people = arrParams[1];
    
    if (people < 1 || people > 10) {
        alert("Enter a reasonable number of people in your household.");
        return null;
    }

    // Base CO2 savings per year is 1090kg for All
    var totalCO2 = 1090;

    if (amount == "Most") {
        totalCO2 = totalCO2 * 0.75;
    } else if (amount == "Some") {
        totalCO2 = totalCO2 * 0.5;
    }

    // Assume 1090kg is for the average household, say 2 people
    totalCO2 = totalCO2 * (people / 2);

    return new MemberImpact("Recycling (" + amount + " eligible materials, " + people + " people)", totalCO2.toFixed(0), 0, 16);
}

function solarWaterCalculate(arrParams) {
    // arrParams[0] == 1, 2, 3, 4, 5+
    var people = arrParams[0];

    // Base CO2 savings per year is 1090kg for All
    var totalCO2 = 0;
    var totalCash = 0;

    if (people == "1") {
        totalCO2 = 446;
        totalCash = 191;
    } else if (people == "2") {
        totalCO2 = 650;
        totalCash = 278;
    } else if (people == "3") {
        totalCO2 = 763;
        totalCash = 327;
    } else if (people == "4") {
        totalCO2 = 827;
        totalCash = 354;
    } else if (people == "5+") {
        totalCO2 = 880;
        totalCash = 377;
    } else {
        alert("Please select the number of people in your household");
        return null;
    }

    return new MemberImpact("Solar Water Heater (" + people + " person household)", totalCO2.toFixed(0), totalCash.toFixed(0), 2);
}

function offsetsCalculate(arrParams) {
    // arrParams[0] == tons
    // arrParams[1] == cost
    var tons = parseFloat(arrParams[0]);
    var cost = parseFloat(arrParams[1]);
    
    if (tons < 1 || cost < 0) {
        alert("Please enter numbers greater than zero for the tons and cost");
        return null;
    }

    if (tons > 1000) {
        alert("Please enter a value for tons less than 1,000.");
        return null;
    }

    // Assume metric tons
    var totalCO2 = tons * 1000;

    return new MemberImpact("Neutralizing with carbon offsets (" + tons + " tons of CO2 for $" + cost + ")", totalCO2.toFixed(0), 0, 17);
}

function oldApplianceCalculate(arrParams) {
    // arrParams[0] == appliance name, or "Custom"
    // arrParams[1] == Custom kWh
    var appliance = arrParams[0];
    var customkWh = arrParams[1];
    
    // Base CO2 savings per year is 1090kg for All
    var totalCO2 = 0;
    var totalCash = 0;

    if (appliance == "Fridge") {
        totalCO2 = 350;
        totalCash = 35;
    } else if (appliance == "Freezer") {
        totalCO2 = 230;
        totalCash = 23;
    } else if (appliance == "Clothes Washer") {
        totalCO2 = 350;
        totalCash = 35;
    } else if (appliance == "Clothes Dryer") {
        totalCO2 = 110;
        totalCash = 11;
    } else if (appliance == "Dish Washer") {
        totalCO2 = 350;
        totalCash = 35;
    } else if (appliance == "Television") {
        totalCO2 = 190;
        totalCash = 19;
    } else {
	// Custom
	if (customkWh == "" || isNaN(customkWh)) {
	    alert("Please enter a valid number in the Custom kWh/year field");
	    return null;
	} else {
            var kwh = parseInt(customkWh);
            if (kwh < 0 || kwh > 1000) {
                alert("Please enter a reasonable custom kWh value.");
                return null;
            }
	    totalCO2 = kwh * KG_CO2_PER_KWH;
	    totalCash = kwh * PRICE_KWH;
	}
    }

    return new MemberImpact("Replace an old appliance (" + appliance + ")", totalCO2.toFixed(0), totalCash.toFixed(0), 18);
}

function lessMeatCalculate(arrParams) {
    // arrParams[0] == % less than developed country average
    var percentLess = parseInt(arrParams[0]);
    
    if (percentLess < 0 || percentLess > 100) {
        alert("Please select a percentage between 0 and 100");
        return null;
    }

    // 1485 is from the Univ. of Chicago study
    var totalCO2 = (percentLess/100) * 1485;

    return new MemberImpact("Eat less meat (" + percentLess + " percent less than average person)", totalCO2.toFixed(0), 0, 19);
}

function waterHeaterBlanketCalculate(arrParams) {
    // no args
    return new MemberImpact("Install a Water Heater Blanket", 1000, 40, 20);
}

function compostingCalculate(arrParams) {
    // arrParams[0] == # people
    var people = parseInt(arrParams[0]);
    // arrParams[1] == cash savings
    var cash = parseInt(arrParams[1]);
    
    if (people < 1 || people > 10) {
        alert("Please enter at least 1 and at most 10 for the number of people in your household");
        return null;
    }

    // Base CO2 per person is 105kg/year from http://www.cat.org.uk/information/catinfo.tmpl?command=search&db=catinfo.db&eqSKUdatarq=InfoSheet_CompostingForClimate
    var co2PerPerson = 105;

    // Assume 1090kg is for the average household, say 2 people
    var totalCO2 = co2PerPerson * people;

    return new MemberImpact("Composting (" + people + " person household)", totalCO2.toFixed(0), cash.toFixed(0), 21);
}

function tanklessWaterCalculate(arrParams) {
    // arrParams[0] == # people
    var people = parseInt(arrParams[0]);
    
    if (people < 1 || people > 10) {
        alert("Please enter at least 1 and at most 10 for the number of people in your household");
        return null;
    }

    // Base CO2 per person is 90kg/year from http://www.thehcf.org/twhprimer.html
    var totalCO2 = 90 * people;

    // Base cash is $28 per person, same site
    var totalCash = 28 * people;

    return new MemberImpact("Tankless Water Heater (" + people + " person household)", totalCO2.toFixed(0), totalCash.toFixed(0), 22);
}

function reusableBagsCalculate(arrParams) {
    // arrParams[0] == # bags
    var bags = parseInt(arrParams[0]);
    
    if (bags < 1 || bags > 20) {
        alert("Please enter at least 1 and at most 20 for the number of bags used per week");
        return null;
    }

    // Assume 3/4 of the bags are plastic, 1/4 paper.  0.1lbs/week/plastic and 0.3lbs/week/paper
    var totalCO2 = (((bags * 0.75) * 0.1) + ((bags * 0.25) * 0.3)) * 52 / 2.2;

    return new MemberImpact("Reusable Bags (" + bags + " bags/week)", totalCO2.toFixed(0), 0, 23);
}

function customOngoingCalculate(arrParams) {
    // arrParams[0] == Name
    // arrParams[1] == tons co2 savings
    // arrParams[2] == cash savings
    var name = arrParams[0];
    var tons = parseFloat(arrParams[1]);
    var cash = parseFloat(arrParams[2]);

    if (tons < 0 || tons > 100) {
        alert("Please enter at least 0 and at most 100 for the number of tons CO2 saved per year");
        return null;
    }

    if (cash < 0 || cash > 10000) {
        alert("Please enter at least 0 and at most 10,000 for the amount of money saved per year");
        return null;
    }

    if (name == "") {
        alert("Please enter a name");
        return null;
    }

    return new MemberImpact(name + " (Custom)", tons * 1000, cash, 24);
}

function customOnetimeCalculate(arrParams) {
    // arrParams[0] == Name
    // arrParams[1] == tons co2 savings
    // arrParams[2] == cash savings
    var name = arrParams[0];
    var tons = parseFloat(arrParams[1]);
    var cash = parseFloat(arrParams[2]);

    if (tons < 0 || tons > 100) {
        alert("Please enter at least 0 and at most 100 for the number of tons CO2 saved per year");
        return null;
    }

    if (cash < 0 || cash > 10000) {
        alert("Please enter at least 0 and at most 10,000 for the amount of money saved per year");
        return null;
    }

    if (name == "") {
        alert("Please enter a name");
        return null;
    }

    return new MemberImpact(name + " (Custom)", tons * 1000, cash, 25);
}

function gasMowerCalculate(arrParams) {
    // arrParams[0] == Size of mower
    // arrParams[1] == Size of yard
    var mower = arrParams[0];
    var yard = arrParams[1];

    var baseCO2 = 40;
    var baseCash = 60;

    var co2 = baseCO2;
    var cash = baseCash;

    if (mower == "Small") {
	co2 = co2 * 0.75;
	cash = cash * 0.75;
    } else if (mower == "Large") {
	co2 = co2 * 1.5; 
	cash = cash * 1.5;
    }

   if (yard == "Small") {
	co2 = co2 * 0.75;
	cash = cash * 0.75;
    } else if (yard == "Large") {
	co2 = co2 * 1.5; 
	cash = cash * 1.5;
    }

    return new MemberImpact("Ditch the gas mower (" + mower + " mower, " + yard + " yard)", co2, cash, 26);
}

