var WATER_AJAX_SCRIPT = 'ajax.php';

// Calculuation Constants
var LTR_IN_BUCKET = 9;
var LTR_IN_BATH = 90;
var FLUSH_PER_WEEK = 35;
var FLUSH_PER_DAY = FLUSH_PER_WEEK/7;
var LTR_HAND_WASH_DISHES = 18;
var LTR_IN_OLYMPICPOOL = 2000000;
var POPULATION_AUSTRALIA = 20434176;
var LTR_IN_GLASS = 0.3;

// Constructor
function Water(options)
{
	// Properties
	this.pageDivs = options.pageDivs;
	
	// Data
	this.PageLoaded 			= Array();
	this.data 					= {};
	this.answers 				= {};
	this.sections 				= {};
	this.defaults				= {};
	this.currentUsage 			= 0;
	this.potentialUsage 		= 0;
	this.averageUsage			= 0;
	this.potentialSaving 		= 0;
	this.averageUsage 			= 0;
	this.averageName			= 'City Name';
	this.catchmentName 			= 'Catchment Name';
	this.catchmentTotalSavings 	= 0;
	this.catchmentTotalUsers 	= 0;

	// Flags
	this.UserLoaded = 0;
	this.RenderPotentialPanel = 0;
	
	// Graphs
	this.currentgraph = null;
	this.potentialgraph = null;
	this.averagegraph = null;
	
	// Methods
	this.ValidatePage 				= ValidatePage;	
	this.LoadSaveUser				= LoadSaveUser;
	this.SavePage					= SavePage;	
	this.SaveField					= SaveField;
	this.Completed					= Completed;
	this.UpdatePage     			= UpdatePage;
	this.RenderPanel				= RenderPanel;
	this.CalculateSection 			= CalculateSection;
	this.CalculateAllSections		= CalculateAllSections;
	this.PotentialBarXML 			= PotentialBarXML;
	this.DefaultPotentialValues 	= DefaultPotentialValues;
	this.UsageXML					= UsageXML;
	this.CalculateTotalUsage		= CalculateTotalUsage;
	this.SetMax						= SetMax;
	this.ShowRecommendations		= ShowRecommendations;
	this.PrintRecommendations		= PrintRecommendations;
	this.EnableIntroQuestions		= EnableIntroQuestions;
	this.DisableCompletionCheck		= DisableCompletionCheck;
	this.RenderUserGMap				= RenderUserGMap;
	this.PersonaliseGMap 			= PersonaliseGMap;
}

function debug(txt)
{
	$('debug').update(txt);
}

// This method is attached to all 'non-slider' fields and saves the value
// of the field to our data object so it can be saved to the database
function SaveField(fld)
{
	var id = $(fld).id;
	this.data[id] = $F(fld);
//alert($H(this.data).inspect());
}

// This method saves all the data to the database.  Its called when the pages
// are changed as users navigate through the wizard
function SavePage(id)
{
	$('spinner').update("<img src='./images/ajax-loader.gif'>");
//alert($H(this.data).inspect());
	new Ajax.Request(WATER_AJAX_SCRIPT,
	{
		parameters: {f: 'SaveData', d: $H(this.data).toJSON(), a: $H(this.answers).toJSON()},
		onComplete: function(transport)
		{
			var result = transport.responseText.evalJSON();
			
			if(result.Result == 0)
			{
				//alert(result.Error);
			}
			$('spinner').update('');						
		}
	});	
}

// This function tells the system that the user actually completed the entire process
function Completed()
{
	new Ajax.Request(WATER_AJAX_SCRIPT,
	{
		parameters: {f: 'SaveAsComplete', d: $H({User_ID: water.data.User_ID}).toJSON()},
		onComplete: function() {
			water.data.Completed = 'Y';
			water.DisableCompletionCheck();
		}
	});	
}

function DisableCompletionCheck()
{
	for (var i=0; i<pageDivs.length; i++)
	{
		if(pageDivs[i].id == 'results' && water.data.Completed == 'Y')
		{
			pageDivs[i].confirmOnProgress = null;
			break;
		}
	}
}

// This method saves the initial information the user enters to the 
// database.  If they already exist, it loads their previous responses
// and updates the page
function LoadSaveUser()
{
	if ($F('Email') != '' && $F('Post_Code') != '' && $('Post_Code').value.length == 4) 
	{
		var data = {Email: $F('Email'), Post_Code: $F('Post_Code'), Water_Bill_Type: $F('Water_Bill_Type')};
		if (water.UserLoaded)
		{
			data 					= water.data;
			data.Post_Code 			= $F('Post_Code');
			data.Email 				= $F('Email');
			data.Water_Bill_Type 	= $('Water_Bill_Type');
		}
//alert($H(data).inspect());
		$('spinner').update("<img src='./images/ajax-loader.gif'>");
		
		new Ajax.Request(WATER_AJAX_SCRIPT,
		{
			parameters: {f: 'SaveUser', d: $H(data).toJSON()},
			onComplete: function(transport)
			{
				var result = transport.responseText.evalJSON();
//alert(transport.responseText);
//alert($H(data).inspect());

				if(result.Result == 0)
				{
					alert(result.Error);
				}
				else
				{
					// Allow functions to be called as we change page
					rat.NavPreChangeFnDisabled = 0;
			
					water.data 		= result.Data;
					water.answers 	= result.Answers;
										
//alert($H(water.data).inspect());
				
					water.UpdatePage('intro');	

					// Now that we've loaded the user, render all the panels
					for (var i=0; i<water.pageDivs.length; i++)
					{
						water.RenderPanel(water.pageDivs[i].id);
					}	
					water.UserLoaded = 1;	


					new Effect.Fade('hideIntroQuestions', {delay: 0});	

					$('introHint').update('<b>Hint:</b> Slide water drops left or right to describe household &amp; garden, then click Next.');						
					
					water.DisableCompletionCheck();
					water.PersonaliseGMap();
					//water.EnableIntroQuestions();			
				}

				// EVIL USE OF GLOBALS!!!! - "rat" is a global defined in the wizard.php page
				rat.NavLock(0);
				$('spinner').update('');						
			}
		});
	}
}

function RenderUserGMap()
{
	water.userMap = new GMap2($("introMap"));
	water.userMap.setCenter(new GLatLng(-29.5,134), 1);
}

function PersonaliseGMap()
{
	water.userMap.clearOverlays();
	water.userMap.setCenter(new GLatLng(water.data.Postcode_Longitude, water.data.Postcode_Latitude), 3);

	var mPoint = new GLatLng(water.data.Postcode_Longitude, water.data.Postcode_Latitude);
	var icon = new GIcon();
	icon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
	icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	icon.iconSize = new GSize(12, 20);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	markerOptions = { icon:icon };	
	
	var marker = new GMarker(mPoint, markerOptions);
	water.userMap.addOverlay(marker);
}

function EnableIntroQuestions()
{
	//sliders['Household_Size'].setEnabled();
	//sliders['Garden_Size'].setEnabled();
	//$('Water_Bill_Use').disabled = false;
	//$('Water_Bill_Type').disabled = false;
}

function AddCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function RenderPanel(id)
{
	// We do special things for the 'potential' page as it has graphs
	if (id == 'potential' && water.RenderPotentialPanel)
	{			
		// Calculate the potential sections and total usage
//alert($H(water.sections).inspect());
		water.CalculateAllSections();
		water.CalculateTotalUsage();
//alert($H(water.sections).inspect());
		
		var width = 110;
		var height = 120;		
		
		// Update titles of graphs and values for page
		$('currentUsageChartValue').update(AddCommas(PerDay(this.currentUsage)));
		$('potentialUsageChartValue').update(AddCommas(PerDay(this.potentialUsage)));
		$('averageUsageChartValue').update(AddCommas(PerDay(this.averageUsage)));
		$('averageUsageChartCity').update(this.averageName);
		
		var potentialSavings = PerDay((water.currentUsage - water.potentialUsage));
		var potentialSavingsPC = Math.round(potentialSavings / PerDay(this.currentUsage) * 100);
		$('potentialSavings').update('<br><br><b><span class=big>'+AddCommas(potentialSavings)+"</span><br>litres saved<br>each day<br>("+potentialSavingsPC+"%)</b>");
		
		
		// Generate actual usage graphs
		/*if (this.currentgraph)
		{
			var chartRef = getChartFromId('currentUsageChartSWF');
			chartRef.setData(this.currentUsage);			
		}
		else
		{*/
			var xml = water.UsageXML('current');
			this.currentgraph = new FusionCharts("./ssi/FusionCharts/Charts/Cylinder.swf", "currentUsageChartSWF", width, height, "0", "1");
			this.currentgraph.setDataXML(xml);
			this.currentgraph.render('currentUsageChart');
		/*}
		// Generate potential graph
		if (this.potentialgraph)
		{
			var chartRef = getChartFromId('potentialUsageChartSWF');
			chartRef.setData(this.potentialUsage);
		}
		else
		{*/
			xml = water.UsageXML('potential');
			this.potentialgraph = new FusionCharts("./ssi/FusionCharts/Charts/Cylinder.swf", "potentialUsageChartSWF", width, height, "0", "1");
			this.potentialgraph.setDataXML(xml);
			this.potentialgraph.render('potentialUsageChart');
		//}
		
		// We never update the average graph, so just draw it the once
		xml = water.UsageXML('average');
		this.averagegraph = new FusionCharts("./ssi/FusionCharts/Charts/Cylinder.swf", "averageUsageChartSWF", width, height, "0", "1");
		this.averagegraph.setDataXML(xml);
		this.averagegraph.render('averageUsageChart');
		
		
		// Generate XML for graph and update
		xml = water.PotentialBarXML();
	 	var bargraph = new FusionCharts("./ssi/FusionCharts/Charts/MSColumn2D.swf", "sectionChart", "370", "177", "0", "1");
		bargraph.setDataXML(xml);
		bargraph.render("potentialBarChart");
	}
	else if (id == 'results')
	{		
		$('spinner').update("<img src='./images/ajax-loader.gif'>");
		$('resultsYourCatchmentIntro').update("Finding your water catchment...");
	
		// Save data and get catchement information but only if we have valid calculations
		water.CalculateAllSections();
		water.CalculateTotalUsage();
				
		var results = {Current_Usage: PerDay(this.currentUsage),
					   Potential_Usage: PerDay(this.potentialUsage),
					   Potential_Saving: PerDay(this.potentialSaving),
					   User_ID: water.data.User_ID};
	
	//alert($H(this.data).inspect());
		// Save results to database
		new Ajax.Request(WATER_AJAX_SCRIPT,
		{
			parameters: {f: 'SaveResults', d: $H(results).toJSON(), userData: $H(this.data).toJSON()},
			onComplete: function(transport) {
				// Now get catchement information
				var result = transport.responseText.evalJSON();
				
				water.catchmentName = result.Catchment_Name;
				water.catchmentTotalSavings = result.Total_Savings;
				water.catchmentTotalUsers = result.Total_Users;
				
//debug(transport.responseText+" Debug: "+water.data.User_ID);					
				// Show final page values
				$('resultsCurrentValue').update(AddCommas(PerDay(water.currentUsage)));
				$('resultsPotentialValue').update(AddCommas(PerDay((water.currentUsage - water.potentialUsage))));			
				$('resultsCatchmentTotalLitresValue').update(AddCommas(water.catchmentTotalSavings));
				$('resultsCatchmentSurveycountValue').update(AddCommas(water.catchmentTotalUsers));	
				$('resultsYourCatchment').update(water.catchmentName);     
				$('resultsYourCatchmentIntro').update("Your water catchment is:<br><b><i>"+water.catchmentName+"</i></b>.");                	

				// Show recommendations
				html = water.ShowRecommendations();

				$('recommendations').update(html);				
				$('spinner').update("");				
			}
		});
	}
	else if (id == 'map')
	{
		
	}
	else
	{
		// Show image for panel
		
		var imageType = "";
		//$('sectionImage').update("<img src='./images/ajax-loader.gif'>");
		for(var i=0; i<this.pageDivs.length; i++)
		{
	//alert($H(this.pageDivs[i]).inspect());
			if (this.pageDivs[i].id == id)
			{
				imageType = this.pageDivs[i].img;
				$('sectionImage').update("<img src='./images/section-"+imageType+".jpg'>");
				break;
			}
		}
	
		// Now calculate useage for section
		var usage = self.CalculateSection(id);
		water.sections[id] = usage;
		$('sectionWater').update(Math.round(usage/365));
	
		// Now show txt
		$('sectionTxt').update('your household '+id+' usage');
	
		// Now equivalent txt
		
		var equivText = '';
		if (imageType == 'buckets')
		{
			var bucketsDay = Math.round(usage/LTR_IN_BUCKET/365);
			equivText = "That's an average of <b>"+bucketsDay + "</b> buckets of water a day in "+id+" water usage by your household.";
		}
		if (imageType == 'glasses') 
		{
			var glasses = Math.round(usage/LTR_IN_GLASS/365);
			equivText = "That's about <b>"+glasses + "</b> glasses of water a day in "+id+" water usage by your household.";
		}i
		if (imageType == 'pools')
		{
			var pools = AddCommas(Math.round(usage/365/water.data.Household_Size/LTR_IN_OLYMPICPOOL*POPULATION_AUSTRALIA));
			equivText =  "If all Australians had the same "+id+
						" usage as people in your home, we'd use <b>"+pools+"</b> olympic-sized swimmimg pools of water in the "+id+" each day! ";
		}
		$('sectionHolder').className = "sectionHolder_"+id;
		$('sectionEquivalentText').update(equivText);
	}
}

function PrintRecommendations()
{
	var printWindow = window.open("about:blank", "printWindow", "resizable=yes,scrollbars=yes,menubar=yes,toolbar=yes,width=760,height=500");
	
	var html = "<html><head>";
	html += "<title>Water Calculator Suggestions</title>";
	html += '<link href="global.css" rel="stylesheet" type="text/css">';
	html += '<![if !IE]>';
	html += '<link rel="stylesheet" type="text/css" href="non-ie.css" />';
	html += '<![endif]>';
	html += "</head><body><div id=print>";
	html += "<a href='javascript:window.close()'>Close</a> | <a href=\"javascript:alert('Use the print function of your browser to print this page')\">Print</a>";
	html += water.ShowRecommendations(1);
	html += "<br><br><hr><sup>&copy; 2008 www.HelpUsHelpTheEarth.com.au<br>Powered by WSP Environmental Water Calculator</sup>";
	html += "</div></body></html>";
	
	printWindow.document.write(html);
}

function ShowRecommendations(noPrint)
{
	var html = "";
	
	if (!noPrint)
	{
		html += "<a  style='float: right;' href='javascript:void(0)' onClick='water.PrintRecommendations()'>Print friendly version</a><br>";
	}
	
	html += "<h1>Recommendations</h1>";
	html += "<p class=lightBlue><b>Based on your current water usage here are some suggestions that could help you save water for your catchment:</b></p>";
	html += "<ul>";

	var Loads_Washing 	= water.answers.Loads_Washing;
	var Wash_Rating 	= water.answers.Wash_Rating;
	var Garden_Watering = water.answers.Garden_Watering;
	var Has_Pool 		= water.answers.Has_Pool;
	var Pool_Usage 		= water.answers.Pool_Usage;
	var Rain_Grey 		= water.answers.Rain_Grey;
	var Leaking_Taps 	= water.answers.Leaking_Taps;
	var Other_Measure 	= water.answers.Other_Measure;
	
	var debug = '';
	
	// Shower usage
	debug += "<b>Shower Usage</b><br>";
	debug += "Shower Time: "+water.answers.Shower_Time+"<br>";
	debug += "Shower Heads: "+water.answers.Shower_Heads+"<br>";
	debug += "Shower Time * Shower Heads > 160 ? ";
	debug += water.answers.Shower_Time * water.answers.Shower_Heads +"<br>";
	if ((water.answers.Shower_Time * water.answers.Shower_Heads) > 160)
	{
		html += ResultItem('shower_heads');
	}
	
	// Toilet usage
	debug += "<b>Toilet Usage</b><br>";
	debug += "Dual Flush: "+water.answers.Dual_Flush+"<br>";
	debug += "Flush Per Day: "+FLUSH_PER_DAY+"<br>";
	debug += "Household Size: "+water.data.Household_Size+"<br>";
	debug += "Leaking Toilets (day): "+water.answers.Leaking_Toilets/7+"<br>";
	debug += "(Dual Flush * Flush Per Day * Household Size) + (Leaking Toilets) > 70 ? ";
	debug += (water.answers.Dual_Flush * (FLUSH_PER_DAY/7) * water.data.Household_Size) + (water.answers.Leaking_Toilets/7) +"<br>";	
	if ((water.answers.Dual_Flush * (FLUSH_PER_DAY/7) * water.data.Household_Size) + (water.answers.Leaking_Toilets/7) > 70)
	{
		html += ResultItem('toilets');
	}
	
	// Washing Machine
	debug += "<b>Washing Machine</b><br>";	
	debug += "Wash Rating: "+water.answers.Wash_Rating+"<br>";
	debug += "Loads Washing: "+water.answers.Loads_Washing+"<br>";
	debug += "Wash Rating > 40 (5star) or Loads of washing > 1<br>";
	if (water.answers.Wash_Rating > 40 || water.answers.Loads_Washing > 1)
	{
		html += ResultItem('washing_machine');
	}
	
	// Other
	debug += "<b>Other measures</b><br>";
	debug += "Other Measures: "+water.answers.Other_Measure+"<br>";
	debug += "Other Measures > 670<br>";
	if (water.answers.Other_Measure > 670)
	{
		html += ResultItem('other');
	}
	
	// Pool
	debug += "<b>Pool</b><br>";
	debug += "Has Pool: "+water.answers.Has_Pool+"<br>";
	debug += "Pool Usage: "+water.answers.Pool_Usage+"<br>";	
	debug += "Pool usage > 1 (means no cover)<br>";
	if (water.answers.Has_Pool == 1 && water.answers.Pool_Usage > 1)
	{
		html += ResultItem('pool');
	}	
	
	// Always
	html += ResultItem('always');
	
	html += "</ul>";
	
	//$('debug').update(debug);	
	
	return html;			 
}

function ResultItem(id)
{
	var recommendation_list = 
	{
		shower_heads: 
		{
			text: 			"Install 3 Star rated low-flow showerheads in all showers and reduce shower length to 4 minutes a day per person",
			explanation: 	"A water efficient household of four people can use as little as 160 litres per day",
			source:         "http://www.griffith.nsw.gov.au/Page/Page.asp?Page_Id=381&p=1" 
		},
		toilets: 
		{
			text: 			"Make sure all your toilets do not leak, are dual flush, and only use the full-flush option when you need to",
			explanation: 	"A water efficient household of four people can use 60 litres a day flushing the tiolet if using a dual-flush toilet, compared to 176 litres if not using a dual-flush system",
			source:         "http://www.griffith.nsw.gov.au/Page/Page.asp?Page_Id=381&p=1" 
		},
		washing_machine:
		{
			text: 			"Next time you purchase a washing machine, make sure it is a water efficient one (at least 4 Star rated). In the meantime, make sure you always do full loads of washing to get the most out of the water you use",  
			explanation: 	"A water efficient washing machine (5 Star rated) can use 45% less water than a standard one",
			source: 		"http://www.griffith.nsw.gov.au/Page/Page.asp?Page_Id=381&p=1" 
		},
		other:
		{
			text: 			"Apply water conservation measures around your household. For example: minimise using water when cleaning bathrooms and kitchens, cleaning paths and washing the car; check water efficiency of air conditioners and water heaters",
			explanation: 	"",
			source: 		"" 
		},
		pool:
		{
			text: 			"Install a pool cover on your pool and only top up water lost to evaporation",
			explanation: 	"Installing a pool cover and only topping up your pool can save over 30,000 litres per year compared to filling your pool each year",
			source: 		"http://www.yvw.com.au/yvw/Home/WaterConservation/" 
		},
		always:
		{
			text: 			"Keep up the good work! By taking an active interest in your water usage you are on the way to saving water for your catchment", 
			explanation:    "",
			source:         "" 
		}						
	};
	
	var html = "<li><b>";
	html += recommendation_list[id].text;
	html += "</b>";
	html += recommendation_list[id].explanation;
	if (recommendation_list[id].source != '')
	{
		html += " (<a target='newwindow' href='"+recommendation_list[id].source+"'>source</a>)";
	}
	html += "</li>";
	return html;
}

// This function is used to default the sliders on the 'potential' page to 
// the values selected in the previous pages.  If there is already a value stored 
// in the database, it uses that instead (water.answers)
function DefaultPotentialValues()
{
	var sliderList =['Shower_Time', 'Shower_Heads', 'No_Baths', 'Turn_Tap', 'Dual_Flush', 'Leaking_Toilets', 'Loads_Dishes', 'Dishwash_Method', 'Dishwash_Rating', 
	                 'Other_Kitchen', 'Loads_Washing', 'Wash_Rating', 'Garden_Watering', 'Has_Pool', 'Pool_Usage', 'Rain_Grey', 'Leaking_Taps', 'Other_Measure'];
					
	// Don't redraw the graphs when we are updating the sliders - each time a slider is updated it calls
	// the "RenderPanel" function which redraws the graphs on the 'potential' panel
	water.RenderPotentialPanel = 0;	
	for (var i=0; i<sliderList.length; i++)
	{
		var sliderName = sliderList[i] + "2";
		var previousSliderName = sliderList[i];

		if(water.answers[sliderName] != null)
		{
			sliders[sliderName].setValue(water.answers[sliderName]);
		}
		else
		{
			var value = GetAnswerValue(previousSliderName);
			sliders[sliderName].setValue(value);
			water.answers[sliderName] = value;
		}
	}
	water.RenderPotentialPanel = 1;	
}

function PotentialBarXML()
{
	var xml = "<chart showLabels='1' showLegend='0' rotateLabels='1' slantLabels='1' showValues='0' bgSWF='./images/barbkg.swf' baseFontColor='77685d' showBorder='0' ";
	xml += "bgColor='f5ead8'  bgAlpha='100' 	canvasBgAlpha='0'  canvasBorderAlpha='0' showYAxisValues='0' numberSuffix=' litres' plotBorderColor='929090' ";
	xml += " showBorder='1' borderColor='f5ead8' borderAlpha='100' borderThickness='1' ";
	xml += " numDivLines='4' divLineAlpha='20' divLineIsDashed='0' showAlternateHGridColor='0' ";
	xml += "plotFillAlpha='100' plotFillRatio='100' plotSpacePercent='20'> ";
	
	xml += "<categories>";
	xml += "<category label='Shower'/><category label='Bathroom' /><category label='Toilet' /><category label='Kitchen' /><category label='Laundry' />";
	xml += "<category label='Outdoors' /><category label='Other' />";
	xml += "</categories>";

	xml += "<dataset seriesname='Current usage' color='d19276' >";
	xml += "   <set value='"+PerDay(water.sections.shower)+"'    />";
	xml += "   <set value='"+PerDay(water.sections.bathroom)+"'  />";
	xml += "   <set value='"+PerDay(water.sections.toilet)+"'   />";
	xml += "   <set value='"+PerDay(water.sections.kitchen)+"'  />";	
	xml += "   <set value='"+PerDay(water.sections.laundry)+"'  />";
	xml += "   <set value='"+PerDay(water.sections.outdoor)+"'  />";
	xml += "   <set value='"+PerDay(water.sections.other)+"'   />";
	xml += "</dataset>";	
	
	xml += "<dataset seriesname='Improved Usage' color='75aec2' >";
	xml += "   <set value='"+PerDay(water.sections.shower2)+"' 		  />";
	xml += "   <set value='"+PerDay(water.sections.bathroom2)+"' 	  />";
	xml += "   <set value='"+PerDay(water.sections.toilet2)+"' 		  />";
	xml += "   <set value='"+PerDay(water.sections.kitchen2)+"' 	  />";	
	xml += "   <set value='"+PerDay(water.sections.laundry2)+"' 	  />";
	xml += "   <set value='"+PerDay(water.sections.outdoor2)+"' 	  />";
	xml += "   <set value='"+PerDay(water.sections.other2)+"' 		  />";
	xml += "</dataset>";	

	xml += "</chart>";
//alert(xml);	
	return xml;
}

function PerDay(value)
{
	return Math.round(value/365);
}

function potentialJumpSection(num)
{
	var sections = Array('showerPotential', 'bathroomPotential', 'toiletPotential', 'kitchenPotential', 'laundryPotential', 'outdoorPotential', 'otherPotential');
	document.location = '#'+sections[num-1];
}

function showHelp(txt)
{
	alert(txt);
}

function UsageXML(mode)
{
	var max = this.currentUsage;
	if (this.potentialUsage > max) { max = this.potentialUsage; }
	//if (this.averageUsage > max) { max = this.averageUsage; }
	
	// Now lets make the maximum a nice round number (in 10,000's)
	max = this.SetMax(PerDay(max));

	var startxml = "<chart registerWithJS='1' majorTMNumber='3' upperLimit='"+max+"' bgColor='f5ead8' bgAlpha='100' ticksOnRight='0' lowerLimit='0' ";
	startxml += " showTickMarks='1' showTickValues='0' showLimits='1' numberSuffix=' litres'  decimalPrecision='0' baseFontColor='000000' ";
	startxml += " showBorder='1' borderColor='f5ead8' borderAlpha='100' borderThickness='1' ";
	startxml += "chartLeftMargin='15' chartRightMargin='15' chartTopMargin='15'";
	
	var bodyxml = '';
	if (mode == 'current')
	{
		startxml += "cylFillColor='cc683d'";
		bodyxml += "<value>"+PerDay(this.currentUsage)+"</value>";
	}
	else if (mode == 'potential')
	{
		startxml += "cylFillColor='4ca5c5'";
		bodyxml += "<value>"+PerDay(this.potentialUsage)+"</value>";
	}	
	else if (mode == 'average')
	{
		startxml += "cylFillColor='898783'";
		bodyxml += "<value>"+PerDay(this.averageUsage)+"</value>";
	}
	startxml += ">";
	bodyxml += "</chart>";
	
	var xml = startxml + bodyxml;
	
	return xml;
}

function SetMax(max)
{
	for (var i=1; i<500; i++)
	{
		var newmax = i * 100;
		if (newmax > max)
		{
			return newmax;
		}
	}
	return max;
}

function CalculateAllSections()
{
	// Actual usage - update to 0 if using grey water
	if (water.answers.Rain_Grey == 4)
	{
		water.sections.shower    	= 0;
		water.sections.bathroom		= 0;
		water.sections.toilet		= 0;
		water.sections.kitchen     	= 0;
		water.sections.laundry     	= 0;
		water.sections.outdoor     	= 0;
		water.sections.other        = 0;
	}	
	else
	{
		water.sections.shower    	= water.CalculateSection('shower');
		water.sections.bathroom		= water.CalculateSection('bathroom');
		water.sections.toilet		= water.CalculateSection('toilet');
		water.sections.kitchen      = water.CalculateSection('kitchen');
		water.sections.laundry      = water.CalculateSection('laundry');
		water.sections.outdoor      = water.CalculateSection('outdoor');
		water.sections.other        = water.CalculateSection('other');		
	}
	
	//Potential usage
	if (water.answers.Rain_Grey2 == 4)
	{
		water.sections.shower2    	= 0;
		water.sections.bathroom2	= 0;
		water.sections.toilet2		= 0;
		water.sections.kitchen2     = 0;
		water.sections.laundry2     = 0;
		water.sections.outdoor2     = 0;
		water.sections.other2       = 0;
	}
	else
	{
		water.sections.shower2    	= water.CalculateSection('shower', 'potential');
		water.sections.bathroom2	= water.CalculateSection('bathroom', 'potential');
		water.sections.toilet2		= water.CalculateSection('toilet', 'potential');
		water.sections.kitchen2     = water.CalculateSection('kitchen', 'potential');
		water.sections.laundry2     = water.CalculateSection('laundry', 'potential');
		water.sections.outdoor2     = water.CalculateSection('outdoor', 'potential');
		water.sections.other2       = water.CalculateSection('other', 'potential');
	}
//alert($H(water.sections).inspect());
}

function CalculateTotalUsage()
{
	this.currentUsage = water.sections.shower + water.sections.bathroom + water.sections.toilet + 
					    water.sections.kitchen + water.sections.laundry + water.sections.outdoor + water.sections.other; 
	this.potentialUsage = water.sections.shower2 + water.sections.bathroom2+ water.sections.toilet2 + 
						water.sections.kitchen2 + water.sections.laundry2 + water.sections.outdoor2 + water.sections.other2;
	this.potentialSaving = this.currentUsage - this.potentialUsage;	
	
	// Calculate average usage - this depends on the user's city
	var postcode = Number(water.data.Post_Code);
	var household = water.data.Household_Size;

	if (household > 1)
	{
		household = household * .75;
	}

	if (postcode < 300)
	{
		// ACT
		this.averageUsage = 151000 * household;
		this.averageName = 'Sydney';
	}
	else if (postcode > 300 && postcode < 1000)
	{
		// NT
		this.averageUsage = 151000 * household;
		this.averageName = 'Sydney';
	}
	else if (postcode < 300 || (postcode >= 1000 && postcode < 3000))
	{
		// NSW
		this.averageUsage = 151000 * household;
		this.averageName = 'Sydney';
	}
	else if (postcode >= 3000 && postcode < 4000)
	{
		// VIC
		this.averageUsage = 138000 * household;
		this.averageName = 'Melbourne';
	}	
	else if (postcode >= 4000 && postcode < 5000)
	{
		// QLD
		this.averageUsage = 183000 * household;
		this.averageName = 'Brisbane';
	}
	else if (postcode >= 5000 && postcode < 6000)
	{
		// SA
		this.averageUsage = 166000 * household;
		this.averageName = 'Adelaide';
	}	
	else if (postcode >= 6000 && postcode < 7000)
	{
		// WA
		this.averageUsage = 149000 * household;
		this.averageName = 'Perth';
	}	
	else if (postcode >= 7000 && postcode < 8000)
	{
		// TAS
		this.averageUsage = 143000 * household;
		this.averageName = 'Hobart';
	}
	else if (postcode >= 8000 && postcode < 9000)
	{
		// VIC AGAIN
		this.averageUsage = 138000 * household;
		this.averageName = 'Melbourne';
	}
	else if (postcode >= 9000 && postcode < 9100)
	{
		// QLD AGAIN
		this.averageUsage = 183000 * household;
		this.averageName = 'Brisbane';
	}			
}

function UpdatePage(id)
{	
	var sections = {
		shower: 	['Shower_Time', 'Shower_Heads'],
		bathroom: 	['No_Baths', 'Turn_Tap'],
		toilet: 	['Dual_Flush', 'Leaking_Toilets'],
		kitchen: 	['Loads_Dishes', 'Dishwash_Method', 'Dishwash_Rating', 'Other_Kitchen'],
		laundry: 	['Loads_Washing', 'Wash_Rating'],
		outdoor: 	['Garden_Watering', 'Has_Pool', 'Pool_Usage'],
		other: 		['Rain_Grey', 'Leaking_Taps', 'Other_Measure']
	};

	if (!this.PageLoaded[id] || !this.UserLoaded)
	{
		if (id == 'intro')
		{	
			// Intro data is stored in the "data" hash so deal with it seperately
			if(!water.data.Household_Size)
			{
				water.data.Household_Size = 3;
			}
			if(!water.data.Garden_Size)
			{
				water.data.Garden_Size = 2;
			}
			sliders['Household_Size'].setValue(water.data.Household_Size);
			sliders['Garden_Size'].setValue(water.data.Garden_Size);
			if (this.data.Water_Bill_Use && this.data.Water_Bill_Use != 0)
			{
				$('Water_Bill_Use').value = this.data.Water_Bill_Use;
			}
			if (this.data.Water_Bill_Type)
			{
				var bill_type = $('Water_Bill_Type');
				for (var i=0; i<bill_type.options.length; i++)
				{
					if (bill_type.options[i].value == this.data.Water_Bill_Type)
					{
						bill_type.options[i].selected = true;
						break;
					}
				}
			}
		}
		else if(sections[id])
		{
			var list = sections[id];
			for(var i=0; i<list.length; i++)
			{
				var name = list[i];
				sliders[name].setValue(this.answers[name]);
			}
		}
		this.PageLoaded[id] = 1;
	}	
}

// ------------------------------------------------------------------------------
// Calculation functions!
// ------------------------------------------------------------------------------
function CalculateSection(id, mode)
{
	var total = 0;
	var Shower_Time 	= GetAnswerValue('Shower_Time');
	var Shower_Heads 	= GetAnswerValue('Shower_Heads');
	var No_Baths 		= GetAnswerValue('No_Baths');
	var Turn_Tap 		= GetAnswerValue('Turn_Tap');
	var Household_Size 	= GetAnswerValue('Household_Size');
	var Dual_Flush 		= GetAnswerValue('Dual_Flush');
	var Leaking_Toilets = GetAnswerValue('Leaking_Toilets');
	var Loads_Dishes 	= GetAnswerValue('Loads_Dishes');
	var Dishwash_Method = GetAnswerValue('Dishwash_Method');
	var Dishwash_Rating = GetAnswerValue('Dishwash_Rating');
	var Other_Kitchen 	= GetAnswerValue('Other_Kitchen');
	var Loads_Washing 	= GetAnswerValue('Loads_Washing');
	var Wash_Rating 	= GetAnswerValue('Wash_Rating');
	var Garden_Watering = GetAnswerValue('Garden_Watering');
	var Has_Pool 		= GetAnswerValue('Has_Pool');
	var Pool_Usage 		= GetAnswerValue('Pool_Usage');
	var Rain_Grey 		= GetAnswerValue('Rain_Grey');
	var Leaking_Taps 	= GetAnswerValue('Leaking_Taps');
	var Other_Measure 	= GetAnswerValue('Other_Measure');
	
	if (mode == 'potential')
	{
		Shower_Time 	= GetAnswerValue('Shower_Time','potential');
		Shower_Heads 	= GetAnswerValue('Shower_Heads','potential');
		No_Baths 		= GetAnswerValue('No_Baths','potential');
		Turn_Tap 		= GetAnswerValue('Turn_Tap','potential');
		Household_Size 	= GetAnswerValue('Household_Size','potential');
		Dual_Flush 		= GetAnswerValue('Dual_Flush','potential');
		Leaking_Toilets = GetAnswerValue('Leaking_Toilets','potential');
		Loads_Dishes 	= GetAnswerValue('Loads_Dishes','potential');
		Dishwash_Method = GetAnswerValue('Dishwash_Method','potential');
		Dishwash_Rating = GetAnswerValue('Dishwash_Rating','potential');
		Other_Kitchen 	= GetAnswerValue('Other_Kitchen','potential');
		Loads_Washing 	= GetAnswerValue('Loads_Washing','potential');
		Wash_Rating 	= GetAnswerValue('Wash_Rating','potential');
		Garden_Watering = GetAnswerValue('Garden_Watering','potential');
		Has_Pool 		= GetAnswerValue('Has_Pool','potential');
		Pool_Usage 		= GetAnswerValue('Pool_Usage','potential');
		Rain_Grey 		= GetAnswerValue('Rain_Grey','potential');
		Leaking_Taps 	= GetAnswerValue('Leaking_Taps','potential');
		Other_Measure 	= GetAnswerValue('Other_Measure','potential');		
	}
	
//alert($H(water.answers).inspect());
	if (id == 'shower')
	{
		total = Shower_Time * Shower_Heads * 365;
		//alert("SHOWER: "+total);
	}
	else if (id == 'bathroom')
	{
		total = (No_Baths * LTR_IN_BATH * 52) + (Turn_Tap * 52 * water.data.Household_Size);
		//alert(Turn_Tap*52*water.data.Household_Size);
	}
	else if (id == 'toilet')
	{
		total = (Dual_Flush * FLUSH_PER_WEEK * water.data.Household_Size * 52) + 
		        (Leaking_Toilets * 52);
	}
	else if (id == 'kitchen')
	{
		total = (Loads_Dishes * 52);

		if (Dishwash_Method == 1)
		{
			total = total * LTR_HAND_WASH_DISHES;
			//$('debug').update(total);
		}
		else
		{
			var setting = (Dishwash_Method - 1);
			var hand_ratio = (1 - setting);
			var auto_ratio = setting;
//$('debug').update('hand ratio: '+ hand_ratio+'\nauto_ratio: '+ auto_ratio);
			total = total * ((hand_ratio * LTR_HAND_WASH_DISHES) + (auto_ratio * Dishwash_Rating));
		}
		
		total = total + (Other_Kitchen * 52);
	}
	else if (id == 'laundry')
	{
		total = (Loads_Washing * Wash_Rating * 52);
	}
	else if (id == 'outdoor')
	{
		// Gardens
		total = (Garden_Watering * 52);
		// + Pool
		if (Has_Pool == 1)
		{
//$('debug').update('pool usage: '+ Pool_Usage);
			if (Pool_Usage == 1)
			{
				total += 2700;
			}
			else if (Pool_Usage == 2)
			{
				total += 3000;
			}
			else 
			{
				total += 40000;
			}
		}
	}
	else if (id == 'other')
	{	
		// Rainwater tank
		if (Rain_Grey == 2)
		{
			total = total - 434;
		}
		else if (Rain_Grey == 3)
		{
			total = total - 868;
		}
		
		// Leaking taps
		total = Number(total) + (Number(Leaking_Taps) * 365);
		
		// Other measures
		total = Number(total) + Number(Other_Measure * 52);

		if (Rain_Grey == 4)
		{
			total = 0;
		}
		
//		$('debug').update('Rain_Grey: '+Rain_Grey+'\nLeaking_Taps: '+Leaking_Taps+'\nOther_Measure: '+	Other_Measure+'\nTotal: '+total);	
		
	}
	
	// Zero out if Rain_Grey == 4
	if (Rain_Grey == 4)
	{
		total = 0;
	}

//$('debug').update('Catchment: '+water.data.Catchment_Name);		
	return Math.round(total);
}

function GetAnswerValue(item, potential)
{
	// Deal with normal values (not inpotential section)
	if (!potential)
	{
		if (water.answers[item])
		{
			return water.answers[item];
		}
		else
		{
			return water.defaults[item];
		}
	}
	else
	{
		var responseName = item + "2";
		if (water.answers[responseName] != null)
		{
			return water.answers[responseName];
		}
		else
		{
			// return the value of the slider in the first section
			return GetAnswerValue(item);
		}
	}
}

///////////////////////////////////////////////////////////////////////////////
// Validation routines
///////////////////////////////////////////////////////////////////////////////

function ValidatePage(id)
{
	var errorTxt = 'Please correct the following before continuing:\n\n';
	var errorCnt = 0;
	
	if (id == 'intro')
	{
		var Email = $F('Email');
		if (!Email || !RAT_ValidateEmail(Email))
		{
			if (errorCnt == 0) { $('Email').focus(); }
			errorTxt += "* Please enter a valid Email Address\n";
			errorCnt++;			
		}		
		var Post_Code = $F('Post_Code');
		if (!Post_Code || !Post_Code.match(/^\d+$/) || Post_Code > 9999 || Post_Code < 1000)
		{
			if (errorCnt == 0) { $('Post_Code').focus(); }
			errorTxt += "* Please enter a valid Post Code between 1000-9000\n";
			errorCnt++;
		}
		var Water_Bill_Use = $F('Water_Bill_Use');
		if (Water_Bill_Use.length > 0 && (!Water_Bill_Use.match(/^\d+$/) || Water_Bill_Use < 0))
		{
			if (errorCnt == 0) { $('Water_Bill_Use').focus(); }
			errorTxt += "* Please enter a valid number (litres) for your water use, or leave blank if unknown\n";
			errorCnt++;			
		}
	}
	
	if (errorCnt > 0)
	{
		alert(errorTxt);
		return false;
	}

	return true;
}

