
Object.extend(Number.prototype, {
	toCommaString: function() {
		// Only insert commas in numbers greater than 1000
		// or less than -1000
		var string = this.toString();
		if (this >= 1000 || this <= -1000) {
			var negative = "", decimal = "";
			if(this < 0) {
				negative = "-";
				string = string.substring(1);
			}
			
			if(string.include(".")) {
				var parts = string.split(".");
				string = parts[0];
				decimal = "." + parts[1];
			}
			
			return negative + string.toArray().reverse().inGroupsOf(3).invoke('reverse').reverse().invoke('join', '').join(',') + decimal;
		} else {
			return string;
		}
	}
});

Object.extend(String.prototype, {
	makeDigits: function() {
		return this.replace(/[^\d]/g, "");
	}
});
	
(function() {
	var loader = new YAHOO.util.YUILoader({
		base: "",
		require: ["history","tabview"],
		loadOptional: false,
		combine: true,
		filter: "MIN",
		allowRollup: true,
		onSuccess: function() {
			var bookmarkedCalcTabsState = YAHOO.util.History.getBookmarkedState("calc");
			var initialCalcTabsState = bookmarkedCalcTabsState || "instructions";

			var calcTabs;
			
			function updateApplicationState() {
				var hist = YAHOO.util.History;
				
				var calcTabsState = hist.getCurrentState('calc');
				switch(calcTabsState) {
					case "instructions": 
						$('prev_section_link').hide();
						break;
					case "summary":
						$('next_section_link').hide();
						break;
					default:
						$('next_section_link').show();
						$('prev_section_link').show();
						break;
				}
				
				$('header').scrollTo();
			}
			
			function updateCalcTabsState(state) {
				switch(state) {
					case "instructions":
						calcTabs.set("activeIndex", 0);
						break;
					case "faucets":
						calcTabs.set("activeIndex", 1);
						break;
					case "lights":
						calcTabs.set("activeIndex", 2);
						break;
					case "bike":
						calcTabs.set("activeIndex", 3);
						break;
					case "bus":
						calcTabs.set("activeIndex", 4);
						break;
					case "magazines":
						calcTabs.set("activeIndex", 5);
						break;
					case "tv":
						calcTabs.set("activeIndex", 6);
						break;
					case "summary":
						calcTabs.set("activeIndex", 7);
						break;
					default:
						break;
				}
			}

			YAHOO.util.History.register("calc", initialCalcTabsState, function (state) {
				updateApplicationState();
				updateCalcTabsState(state);
			});
			
			function handleCalcTabsActiveTabChange(e) {
				var newState, currentState;
				newState = e.newValue.get('href');
				newState = newState.substr(newState.search(/#/) + 1);
				try {
					currentState = YAHOO.util.History.getCurrentState("calc");
					if (newState != currentState) {
						YAHOO.util.History.navigate("calc", newState);
					}
				} catch (e) {
					var newIndex = calcTabs.getTabIndex(e.newValue);
					calcTabs.set("activeIndex", newIndex);
				}
			}
		
			function initCalcTabs() {
				calcTabs = new YAHOO.widget.TabView("calc");
				calcTabs.addListener("activeTabChange", handleCalcTabsActiveTabChange);
			}
			
			YAHOO.util.History.onReady(function () {
				initCalcTabs();
				updateCalcTabsState(YAHOO.util.History.getCurrentState("calc"));
				updateApplicationState();
			});
		
			try {
				YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
			} catch (e) {
				initCalcTabs();
			}

		}
	});

	// Load the files using the insert() method.
	loader.insert();
})();




var KidsCalcConstants = {
	daysInYear: 365, //days per year
	weeksPerYear: 52, // weeks per year
	schoolWeeksPerYear: 35, // school weeks per year
	totalStudentsInUS: 55966000, // students in United States
	eFactor: 1.72, //pounds CO2 per kWh
	savedEmissionsFromTurningFaucetOff: 528, // efactor of 1.72 times annual energy use of faucet of 307 kWh per year
	householdLightAnnualEnergyUse: 117, //kWh per year
	assumedAverageLightUsePerDay: 8, //hours per day
	energySavingsOfEnergyStarLight: 80, //kWh per year
	assumedMileageBikedOrWalked: 1, //mile
	assumedMileageAlternativeTrans: 3, //miles
	averageVehicleEfficiency: 20.4, //miles per gallon
	CO2EmissionsPerGallonOfGas: 19.4, //pounds per gallon
	otherEmissionsPerGallonOfGas: 1.05, //NA
	assumedAnnualAverageMileage: 12000, //miles per year
	savedEmissionsFromRecyclingMagazines: 51.91, //pounds CO2 equivalent per year
	savedEmissionsFromRecyclingNewspaper: 172.38, //pounds CO2 equivalent per year
	savedEmissionsFromRecyclingGlass: 29.95, //pounds CO2 equivalent per year
	savedEmissionsFromRecyclingPlastic: 46.93, //pounds CO2 equivalent per year
	savedEmissionsFromRecyclingMetal: 145.58, //pounds CO2 equivalent per year
	televisionAnnualEnergyUse: 184, //kWh per year
	assumedAverageTelevisionUsagePerDay: 6, //hours per day
	electronicDeviceAnnualEnergyUse: 15, //kWh per year
	assumedAverageElectronicDeviceUsagePerDay: 3, //hours per day
	chargerAnnualEnergyUse: 0.4, //kWh
	assumedAverageChargerUsagePerDay: 5.5, //hours per day
	energySavingsOfComputerSleep: 98 //kWh per year
};

var KidsAction = Class.create({
	initialize: function (form, name) {
		this.form = form;
		this.name = name;
		
		this.radios = this.form.getInputs('radio', this.name);
		this.savingsField = $(this.name + "_savings");
		this.el = this.savingsField.up('div.action');
		this.radios.invoke('observe', 'click', this.calculate.bindAsEventListener(this));
		this.el.select('input[type="text"]').invoke('observe', 'blur', this.calculate.bindAsEventListener(this));
	},
	
	getAnswer: function () {
		var checked = this.radios.find(function(radio) {
			return radio.checked;
		});
		return checked ? checked.value : 0;
	},
	
	getTotalSavings: function() {
		this.calculate();
		return parseFloat(this.savingsField.innerHTML.makeDigits());
	},
	
	getAlreadyDoSavings: function() {
		if(this.getAnswer() == "alreadydo") {
			this.calculate();
			return parseFloat(this.savingsField.innerHTML.makeDigits());
		} else {
			return 0;
		}
	},
	
	getNewSavings: function() {
		if(this.getAnswer() == "yes") {
			this.calculate();
			return parseFloat(this.savingsField.innerHTML.makeDigits());
		} else {
			return 0;
		}
	},
	
	calculate: function() {
		var answer = this.getAnswer();
		this.handleAlreadyDo(answer);
		if(answer == "yes" || answer == "alreadydo") {
			switch(this.name) {
				case "faucets":
					this.savingsField.update(KidsCalcConstants.savedEmissionsFromTurningFaucetOff + " lbs");
					break;
				case "lights":
					var hours = parseFloat($F(this.form[this.name + "_amount"])) || 0;
					this.savingsField.update(Math.round(KidsCalcConstants.householdLightAnnualEnergyUse * (hours / KidsCalcConstants.assumedAverageLightUsePerDay) * KidsCalcConstants.eFactor).toCommaString() + " lbs");
					break;
				case "bulbs":
					var numBulbs = parseFloat($F(this.form[this.name + "_amount"])) || 0;
					this.savingsField.update(Math.round(numBulbs * KidsCalcConstants.energySavingsOfEnergyStarLight * KidsCalcConstants.eFactor).toCommaString() + " lbs");
					break;
				case "bike":
					var daysPerWeek = parseFloat($F(this.form[this.name + "_amount"])) || 0;
					this.savingsField.update(Math.round(((KidsCalcConstants.assumedMileageBikedOrWalked * daysPerWeek * KidsCalcConstants.schoolWeeksPerYear) / KidsCalcConstants.averageVehicleEfficiency) * KidsCalcConstants.CO2EmissionsPerGallonOfGas * KidsCalcConstants.otherEmissionsPerGallonOfGas * 2).toCommaString() + " lbs");
					break;
				case "bus":
					var daysPerWeek = parseFloat($F(this.form[this.name + "_amount"])) || 0;
					this.savingsField.update(Math.round(((KidsCalcConstants.assumedMileageAlternativeTrans * daysPerWeek * KidsCalcConstants.schoolWeeksPerYear) / KidsCalcConstants.averageVehicleEfficiency) * KidsCalcConstants.CO2EmissionsPerGallonOfGas * KidsCalcConstants.otherEmissionsPerGallonOfGas * 2).toCommaString() + " lbs");
					break;
				case "carpool":
					var daysPerWeek = parseFloat($F(this.form[this.name + "_amount"])) || 0;
					var otherPeople = parseFloat($F(this.form[this.name + "_num_people"])) || 0;
					this.savingsField.update(Math.round(((KidsCalcConstants.assumedMileageAlternativeTrans * daysPerWeek * KidsCalcConstants.schoolWeeksPerYear) / KidsCalcConstants.averageVehicleEfficiency) * KidsCalcConstants.CO2EmissionsPerGallonOfGas * KidsCalcConstants.otherEmissionsPerGallonOfGas * (otherPeople / (otherPeople + 1)) * 2).toCommaString() + " lbs");
					break;
				case "reduce_car":
					var usualNumTrips = parseFloat($F(this.form[this.name + "_trips"])) || 1; // to prevent divide-by-zero errors
					var numTripsBiked = parseFloat($F(this.form[this.name + "_amount"])) || 0;
					this.savingsField.update(Math.round(((KidsCalcConstants.assumedMileageBikedOrWalked * (numTripsBiked / usualNumTrips) * KidsCalcConstants.weeksPerYear) / KidsCalcConstants.averageVehicleEfficiency) * KidsCalcConstants.CO2EmissionsPerGallonOfGas * KidsCalcConstants.otherEmissionsPerGallonOfGas * 2).toCommaString() + " lbs");				
					break;
				case "magazines":
					this.savingsField.update(Math.round(KidsCalcConstants.savedEmissionsFromRecyclingMagazines) + " lbs");
					break;
				case "newspaper":
					this.savingsField.update(Math.round(KidsCalcConstants.savedEmissionsFromRecyclingNewspaper) + " lbs");
					break;
				case "glass":
					this.savingsField.update(Math.round(KidsCalcConstants.savedEmissionsFromRecyclingGlass) + " lbs");
					break;
				case "plastic":
					this.savingsField.update(Math.round(KidsCalcConstants.savedEmissionsFromRecyclingPlastic) + " lbs");
					break;
				case "metal":
					this.savingsField.update(Math.round(KidsCalcConstants.savedEmissionsFromRecyclingMetal) + " lbs");
					break;
				case "tv":
					var hours = parseFloat($F(this.form[this.name + "_amount"])) || 0;
					this.savingsField.update(Math.round(KidsCalcConstants.televisionAnnualEnergyUse * (hours / KidsCalcConstants.assumedAverageTelevisionUsagePerDay) * KidsCalcConstants.eFactor).toCommaString() + " lbs");
					break;
				case "dvd":
					var numDevices = parseFloat($F(this.form[this.name + "_devices"])) || 0;
					var hoursOff = parseFloat($F(this.form[this.name + "_amount"])) || 0;
					this.savingsField.update(Math.round(KidsCalcConstants.electronicDeviceAnnualEnergyUse * numDevices * (hoursOff / KidsCalcConstants.assumedAverageElectronicDeviceUsagePerDay) * KidsCalcConstants.eFactor).toCommaString() + " lbs");
					break;
				case "powerstrip":
					var numChargers = parseFloat($F(this.form[this.name + "_chargers"])) || 0;
					var hoursOff = parseFloat($F(this.form[this.name + "_amount"])) || 0;
					this.savingsField.update(Math.round(KidsCalcConstants.chargerAnnualEnergyUse * numChargers * (hoursOff / KidsCalcConstants.assumedAverageChargerUsagePerDay) * KidsCalcConstants.eFactor).toCommaString() + " lbs");
					break;
				case "sleep":
					var numComputers = parseFloat($F(this.form[this.name + "_amount"])) || 0;
					this.savingsField.update(Math.round(KidsCalcConstants.energySavingsOfComputerSleep * numComputers * KidsCalcConstants.eFactor).toCommaString() + " lbs");
					break;
				default:
					break;
			}
		} else {
			this.savingsField.update("0 lbs");
		}
	},
	
	handleAlreadyDo: function(answer) {
		if(answer == "alreadydo") {
			switch(this.name) {
				case "lights":
					this.el.select('.tense').reduce().update('do you leave the lights');
					break;
				case "bulbs":
					this.el.select('.tense').first().update('have');
					this.el.select('.tense')[1].update('d');
					break;
				case "bike":
				case "bus":
				case "powerstrip":
					this.el.select('.tense').reduce().update('do');
					break;
				case "carpool":
					this.el.select('.tense').first().update('do');
					this.el.select('.tense')[1].update('When');
					break;
				case "reduce_car":
					this.el.select('.tense').first().update('would you normally');
					this.el.select('.tense')[1].update('do');
					break;
				case "tv":
					this.el.select('.tense').reduce().update('do you leave the TV');
					break;
				case "dvd":
					this.el.select('.tense').reduce().update('do you leave these devices');
					break;
				default:
					break;
			}
		} else {
			switch(this.name) {
				case "faucets":
					break;
				case "lights":
					this.el.select('.tense').reduce().update('will the lights be');
					break;
				case "bulbs":
					this.el.select('.tense').first().update('will');
					this.el.select('.tense')[1].update();
					break;
				case "bike":
				case "bus":
				case "powerstrip":
					this.el.select('.tense').reduce().update('will');
					break;
				case "carpool":
					this.el.select('.tense').first().update('will');
					this.el.select('.tense')[1].update('If');
					break;
				case "reduce_car":
					this.el.select('.tense').first().update('do you currently');
					this.el.select('.tense')[1].update('will');
					break;
				case "tv":
					this.el.select('.tense').reduce().update('will the TV be');
					break;
				case "dvd":
					this.el.select('.tense').reduce().update('will these devicees be');
					break;
				default:
					break;
			}
		}
	}
});


var KidsCalc = Class.create({
	initialize: function (form) {
		this.form = form;
		this.actions = [];
		$$('.action').each(function(action) {
			this.actions.push(new KidsAction(this.form, action.select('input').first().name));
		}, this);
		
		this.form.getInputs('radio').invoke('observe', 'click', this.calculateTotals.bindAsEventListener(this));
		this.form.getInputs('text').invoke('observe', 'blur', this.calculateTotals.bindAsEventListener(this));
	},
	
	calculateTotals: function () {
		var kidsInClass = $F(this.form.classroom_amount);
		var kidsInSchool = $F(this.form.school_amount);
		
		var totalSavings = this.actions.invoke('getTotalSavings').inject(0, function (acc, n) { return acc + n; });
		var alreadydoSavings = this.actions.invoke('getAlreadyDoSavings').inject(0, function (acc, n) { return acc + n; });
		var newSavings = this.actions.invoke('getNewSavings').inject(0, function (acc, n) { return acc + n; });

		$('total_savings').update(totalSavings.toCommaString());
		$('total_equiv').update(Math.round(totalSavings / KidsCalcConstants.CO2EmissionsPerGallonOfGas * KidsCalcConstants.averageVehicleEfficiency).toCommaString());
		
		$('alreadydo_savings').update(alreadydoSavings.toCommaString());
		$('alreadydo_equiv').update(Math.round(alreadydoSavings / KidsCalcConstants.CO2EmissionsPerGallonOfGas * KidsCalcConstants.averageVehicleEfficiency).toCommaString());
		$('new_savings').update(newSavings.toCommaString());
		$('new_equiv').update(Math.round(newSavings / KidsCalcConstants.otherEmissionsPerGallonOfGas / KidsCalcConstants.CO2EmissionsPerGallonOfGas * KidsCalcConstants.averageVehicleEfficiency).toCommaString());
		
		var classTotal = totalSavings * kidsInClass;
		$('class_lbs').update(classTotal.toCommaString());
		$('class_miles').update((Math.round(classTotal / KidsCalcConstants.otherEmissionsPerGallonOfGas / KidsCalcConstants.CO2EmissionsPerGallonOfGas * KidsCalcConstants.averageVehicleEfficiency)).toCommaString());
		
		var schoolTotal = totalSavings * kidsInSchool;
		$('school_lbs').update(schoolTotal.toCommaString());
		$('school_miles').update((Math.round(schoolTotal / KidsCalcConstants.otherEmissionsPerGallonOfGas / KidsCalcConstants.CO2EmissionsPerGallonOfGas * KidsCalcConstants.averageVehicleEfficiency)).toCommaString());
		
		var usTotal = totalSavings * KidsCalcConstants.totalStudentsInUS;
		$('us_lbs').update(usTotal.toCommaString());
		$('us_miles').update((Math.round(usTotal / KidsCalcConstants.otherEmissionsPerGallonOfGas / KidsCalcConstants.CO2EmissionsPerGallonOfGas * KidsCalcConstants.averageVehicleEfficiency)).toCommaString());
		$('us_cars').update((Math.round(usTotal / KidsCalcConstants.otherEmissionsPerGallonOfGas / KidsCalcConstants.CO2EmissionsPerGallonOfGas * KidsCalcConstants.averageVehicleEfficiency / KidsCalcConstants.assumedAnnualAverageMileage)).toCommaString());
	}
});

document.observe('dom:loaded', function (e) {
	$$('.yui-content').reduce().insert({after: '<div class="cap"><div></div></div>'});
	var kidsCalc = new KidsCalc($('calculator'));
	kidsCalc.calculateTotals();
	$('next_section_link').observe('click', function(e) {
        e.stop();
		var hist = YAHOO.util.History;
        var calcTabsState = hist.getCurrentState('calc');
        switch(calcTabsState) {
			case "instructions":
	            hist.navigate('calc', 'faucets');
				break;
			case "faucets":
				hist.navigate('calc', 'lights');
				break;
			case "lights":
				hist.navigate('calc', 'bike');
				break;
			case "bike":
				hist.navigate('calc', 'bus');
				break;
			case "bus":
				hist.navigate('calc', 'magazines');
				break;
			case "magazines":
				hist.navigate('calc', 'tv');
				break;
			case "tv":
				hist.navigate('calc', 'summary');
				break;
			default:
				break;
		}		
    });
    
    $('prev_section_link').observe('click', function(e) {
        e.stop();
		var hist = YAHOO.util.History;
        var calcTabsState = hist.getCurrentState('calc');
        switch(calcTabsState) {
			case "faucets":
	            hist.navigate('calc', 'instructions');
				break;
			case "lights":
				hist.navigate('calc', 'faucets');
				break;
			case "bike":
				hist.navigate('calc', 'lights');
				break;
			case "bus":
				hist.navigate('calc', 'bike');
				break;
			case "magazines":
				hist.navigate('calc', 'bus');
				break;
			case "tv":
				hist.navigate('calc', 'magazines');
				break;
			case "summary":
				hist.navigate('calc', 'tv');
				break;
			default:
				break;
		}	
    });
});