jQuery(document).ready(function()
{
	/**
	 * Load main question
	 */
	function getMainQuestion()
	{
		// reset system
		resetApplication(); // resets to main
		// display the question
		showQuestion();
	}
	
	/**
	 *  Generate energy selector field 
	 */
	function getEnergySelector()
	{
		currentSection = "Energy Selector";
		showEnergySelectorLocation();
		
		jQuery("#user-options").hide();
		jQuery("#energyquestions").html("What type of property do you have?");
		jQuery("#property-select-buttons").show();
		jQuery("#instructions").html("Please select the following");
		jQuery("#property-selection").html("<div id=\"energyselectorproperty\">"+
			"<table>"+
				"<tr>"+
				"<td>Property Type:</td><td><select id=\"propertType\">"+generatePropertyTypes()+"</select></td><td colspan=\"2\" align=\"right\"><a href='#' id=\"specificenergyPrevious\"><div id='specificenergyPreviousbutton'></div></a></td>"+
				"</tr>"+
				"<tr>"+
				"<td>Fuel Type:</td><td><select id=\"fuelType\">"+generateFuelTypes()+"</select></td><td><a href='#' id=\"select_page1\"><div id='specificenergyNextbutton'></div></a></td>"+
				"</tr>"+
			"</table>"+ 
			"<!-- Mask to cover the whole screen -->"+
			  "<div id=\"mask\"></div>"+
			  "<br/><div id=\"applicable\"></div>"+
			"</div>" +
			"<div id=\"energyquestions\"></div><div style=\"display:none\" id=\"specificenergyselector\">" +
			"<input type=\"radio\" name=\"energyTypeChoice\" id=\"yesSelect\" value=\"yes\"> Yes <br>" +
			"<input type=\"radio\" name=\"energyTypeChoice\" id=\"noSelect\" value=\"no\"> No <br>" +
					"<input id=\"specificenergyPrevious\" type=\"button\" value=\"Previous\"><input id=\"specificenergyNext\" type=\"button\" value=\"Next\">" +
					"" +
					"" +
					"</div>");

	}
	
	/**
	 *  Generate energy selector field 
	 */
	function getEnergySelector2()
	{
		currentSection = "Energy Selector";
		showEnergySelectorLocation();
		
		jQuery("#user-options").hide();
		
		jQuery("#instructions").html("Please select the following");
		jQuery("#property-selection").html("<div id=\"energyselectorproperty\">"+
			"<table border='1'>"+
				"<tr>"+
				"<td>Property Type:</td><td><select id=\"propertType\">"+generatePropertyTypes()+"</select></td><td align=\"right\"><input id=\"specificenergyPrevious\" type=\"button\" value=\"Previous\">"+
				"</tr>"+
				"<tr>"+
				"<td>Fuel Type:</td><td><select id=\"fuelType\">"+generateFuelTypes()+"</select></td><td><input type=\"button\" id=\"select_page1\" value=\"Next\"></td>"+
				"</tr>"+
			"</table>"+ 
			"<!-- Mask to cover the whole screen -->"+
			  "<div id=\"mask\"></div>"+
			  "<br/><div id=\"applicable\"></div>"+
			"</div>" +
			"<div id=\"energyquestions\"></div><div style=\"display:none\" id=\"specificenergyselector\">" +
			"<input type=\"radio\" name=\"energyTypeChoice\" id=\"yesSelect\" value=\"yes\"> Yes <br>" +
			"<input type=\"radio\" name=\"energyTypeChoice\" id=\"noSelect\" value=\"no\"> No <br>" +
					"<input id=\"specificenergyPrevious\" type=\"button\" value=\"Previous\"><input id=\"specificenergyNext\" type=\"button\" value=\"Next\"></div>");

	}
	
	

	/** 
	 * Show applicable fields 
	 */
	function showApplicableFields(propertyType,fuelType)
	{
		linkPropertFuel();
		
		var applicableEnergies = "";
		var energySelections = "";
		switch(propertyType)
		{
			case "bungalow":
				energySelections = bungalow[fuelType];
				break;
			case "flat_ground_floor":
				energySelections = flatgroundfloor[fuelType];
				break;
			case "flat_middle_floor":
				energySelections = flatmiddlefloor[fuelType];
				break;
			case "flat_top_floor":
				energySelections = flattopfloor[fuelType];
				break;
			case "house_detached":
				energySelections = housedetached[fuelType];
				break;
				
			case "house_semidetached":
				energySelections = housesemidetached[fuelType];
				break;
			case "house_terraced":
				energySelections = houseterraced[fuelType];
				break;
			case "maisonette":
				energySelections = maisonette[fuelType];
				break;
		}

		var energySelections = energySelections.split(",");
		
		
		
		// Loop over the energy types and see what is available to the selected property and fuel type
		var len = energySelections.length;
		for (var i = 0; i < len; i++)
		{
			if (energySelections[i] == "1")
			{
				if (applicableEnergies == "")
					applicableEnergies += energyList[i];
				else
					applicableEnergies += ","+energyList[i];
			}
		}

		jQuery('#applicable').html(applicableEnergies);
		sectionNo = 0;
		applicableEnergy = applicableEnergies.split(","); // get all the applicable energy types
		
		currentQuestionNo = 0;
		currentSection = applicableEnergy[0];
		applicableEnergySize = applicableEnergy.length;
		showQuestion();
	}
		
	/**
	 * Set the appropriate questions for each Property Type and Fuel Type
	 */
	function linkPropertFuel()
	{	
		// Bungalow
		bungalow["gas"] = "1,1,1,1,1,1,1";
		bungalow["oil"] = "1,1,1,1,1,0,1";
		bungalow["lpg"] = "1,1,1,1,1,0,1";
		bungalow["electric"] = "1,1,1,1,0,1";
		bungalow["coal"] = "1,1,1,1,1,0,1";
		
		// Flat Ground Floor
		flatgroundfloor["gas"] = "0,0,1,1,1,1,0";
		flatgroundfloor["oil"] = "0,0,1,1,1,0,0";
		flatgroundfloor["lpg"] = "0,0,1,1,1,0,0";
		flatgroundfloor["electric"] = "0,0,1,1,1,0,0";
		flatgroundfloor["coal"] = "0,0,1,1,1,0,0";   
		
		
		// Flat Middle Floor
		flatmiddlefloor["gas"] = "0,0,0,1,1,1,0";
		flatmiddlefloor["oil"] = "0,0,0,1,1,0,0";
		flatmiddlefloor["lpg"] = "0,0,0,1,1,0,0";
		flatmiddlefloor["electric"] = "0,0,0,1,1,0,0";
		flatmiddlefloor["coal"] = "0,0,0,1,1,0,0";  
		
		// Flat Top Floor
		flattopfloor["gas"] = "1,1,0,1,1,1,1";
		flattopfloor["oil"] = "1,1,0,1,1,0,1";
		flattopfloor["lpg"] = "1,1,0,1,1,0,1";
		flattopfloor["electric"] = "1,1,0,1,1,0,1";
		flattopfloor["coal"] = "1,1,0,1,1,0,1";  
		
		// House Detached
		housedetached["gas"] = "1,1,1,1,1,1,1";
		housedetached["oil"] = "1,1,1,1,1,0,1";
		housedetached["lpg"] = "1,1,1,1,1,0,1";
		housedetached["electric"] = "1,1,1,1,1,0,1";
		housedetached["coal"] = "1,1,1,1,1,0,1";  
		
		// House Semi Detached
		housesemidetached["gas"] = "1,1,1,1,1,1,1";
		housesemidetached["oil"] = "1,1,1,1,1,0,1";
		housesemidetached["lpg"] = "1,1,1,1,1,0,1";
		housesemidetached["electric"] = "1,1,1,1,1,0,1";
		housesemidetached["coal"] = "1,1,1,1,1,0,1";  

		// House Terraced
		houseterraced["gas"] = "1,1,1,1,0,1,1";
		houseterraced["oil"] = "1,1,1,1,0,0,1";
		houseterraced["lpg"] = "1,1,1,1,0,0,1";
		houseterraced["electric"] = "1,1,1,1,0,0,1";
		houseterraced["coal"] = "1,1,1,1,0,0,1"; 
		
		// House Maisonette
		maisonette["gas"] = "0,0,1,1,1,1,0";
		maisonette["oil"] = "0,0,1,1,1,0,0";
		maisonette["lpg"] = "0,0,1,1,1,0,0";
		maisonette["electric"] = "0,0,1,1,1,0,0";
		maisonette["coal"] = "0,0,1,1,1,0,0";  
	}
	
	
/*** BENEFITS MATRIX SECTIOM **********************/
	var benefitsMatrix = new Array();
	
	function generateBenefitsMatrix()
	{
		var Solar_Electricity = "41.3 pence|£900-£1100|£1,200.00|8.3|25";
		var Combined_Heat_and_Power = "10 pence|Around £200|£290.00|8.6|15";
		var Mini_Wind_Turbine = "26.7 pence|£900-£1100|£1,300.00|15.4|20";
		var Solar_Heating = "18 pence|Around £200|£270.00|11.1|25";
		var Air_Source_Heat_Pumps = "7.5 pence|Around £750|£750.00|10.7|20";
		var Ground_Source_Heat_Pumps = "7 pence|Around £700|£700.00|14.3|25";
		var Wood_Fuel_Boiler = "9 pence|Around £900|£600.00|16.7|20";

		benefitsMatrix["solarpv"] =  Solar_Electricity;
		benefitsMatrix["microchp"] =  Combined_Heat_and_Power;
		benefitsMatrix["wind"] =  Mini_Wind_Turbine;
		benefitsMatrix["solarthermal"] =  Solar_Heating;
		benefitsMatrix["ashp"] =  Air_Source_Heat_Pumps;
		benefitsMatrix["gshp"] =  Ground_Source_Heat_Pumps;
		benefitsMatrix["wood"] =  Wood_Fuel_Boiler;
	}
	
	// generates benefits table
	function generateBenefitsMatrixView()
	{
		var Solar_Electricity = "<tr><td>41.3 pence</td><td>&pound;900-&pound;1100</td><td>&pound;1,200.00</td><td>8.3</td><td>25</td></tr></table>";
		var Combined_Heat_and_Power = "<tr><td>10 pence</td><td>Around &pound;200</td><td>&pound;290.00</td><td>8.6|15</td>";
		var Mini_Wind_Turbine = "<tr><td>26.7 pence</td><td>&pound;900-&pound;1100</td><td>&pound;1,300.00</td><td>15.4</td><td>20</td>";
		var Solar_Heating = "<tr><td>18 pence</td><td>Around &pound;200</td><td>&pound;270.00</td><td>11.1</td><td>25</td>";
		var Air_Source_Heat_Pumps = "<tr><td>7.5 pence</td><td>Around &pound;750</td><td>&pound;750.00</td><td>10.7</td><td>20</td>";
		var Ground_Source_Heat_Pumps = "<tr><td>7 pence</td><td>Around &pound;700</td><td>&pound;700.00</td><td>14.3</td><td>25</td>";
		var Wood_Fuel_Boiler = "<tr><td>9 pence</td><td>Around &pound;900</td><td>&pound;600.00</td><td>16.7</td><td>20</td>";

		benefitsMatrix["solarpv"] =  Solar_Electricity;
		benefitsMatrix["microchp"] =  Combined_Heat_and_Power;
		benefitsMatrix["wind"] =  Mini_Wind_Turbine;
		benefitsMatrix["solarthermal"] =  Solar_Heating;
		benefitsMatrix["ashp"] =  Air_Source_Heat_Pumps;
		benefitsMatrix["gshp"] =  Ground_Source_Heat_Pumps;
		benefitsMatrix["wood"] =  Wood_Fuel_Boiler;
	}
	
	var energy_cost="";
	function getBenefitsMatrix(technology)
	{
		var arr = benefitsMatrix[technology];
		return arr;
	}
	
	// Get price difference
	jQuery('.selected-energy').livequery('mouseover', function(event) 
	{
		generateBenefitsMatrix();
		var id = jQuery(this).attr("id");
		var save = getBenefitsMatrix(id).split("|");
	
		energy_cost = jQuery("#your_energy_cost").val();
		energy_cost = energy_cost.replace("<","");
		energy_cost = energy_cost.replace(">","");

		// your min and max costs
		var ecost = energy_cost.split("-");
		//alert(energy_cost);
		var ymin = parseFloat(ecost[0]);

		// actual min and max costs	
		var save1 = save[2].replace("&pound;","");
		var save1 = save1.replace("£","");
		var totalben = parseFloat(save1.replace(",",""));
		
		var oymin = ymin;
		ymin = ymin - totalben;

		var imgurl = jQuery("#currurl").val()+"/images/energy-selector/how-icon.png";
		if (ymin < 0)
		{
			ymin = ""+ymin;
			ymin = ymin.replace("-","");
			jQuery('#savings_field').html("You could earn upto <strong>&pound;"+ymin+ "</strong> next year if you install "+technologyNames[id] + ". Click on (more info) <span class='txtafterimg'>to view how we worked this out.</span>");
		}else if (ymin == 0)
		{
			jQuery('#savings_field').html("Your energy bill next year could be <strong>&pound;"+oymin+ "</strong>  if you install "+technologyNames[id]+". Click on (more info) <span class='txtafterimg'>to view how we worked this out.</span>");
		}else {
			jQuery('#savings_field').html("Your energy bill next year could be <strong>&pound;"+ymin+ "</strong>  if you install "+technologyNames[id]+". Click on (more info) <span class='txtafterimg'>to view how we worked this out.</span>");
		}
	
	});
		
	jQuery(".selected-energy").hover(function() {
		jQuery("#savings_field").slideDown(1);
		return;
	}, function() {
		jQuery("#savings_field").slideUp(1);
	});
	

	
	var technologyNames;
	generateTechnologyNames();
	function generateTechnologyNames()
	{
		technologyNames = new Array(); 
		technologyNames["solarpv"] =  "Solar Electricity";
		technologyNames["microchp"] =  "Combined Heat and Power";
		technologyNames["wind"] =  "Mini Wind Turbine";
		technologyNames["solarthermal"] =  "Solar Heating";
		technologyNames["ashp"] =  "Air Source Heat Pumps";
		technologyNames["gshp"] =  "Ground Source Heat Pumps";
		technologyNames["wood"] =  "Wood Fuel Boiler";
	}
	
	
	// Get table of how calculations where done
	jQuery('.selected-energy_help').livequery('click', function(event) 
	{
		generateBenefitsMatrixView();
		var id = jQuery(this).attr("id");
		jQuery.facebox("<h2>"+technologyNames[id]+"</h2><table border=1 class=energy_selector_table><tr><td class=heading>Cashback per unit (kWh) of energy generated</td>" +
				"<td class=heading>Potential Clean Energy Cashback per year</td>"+
				"<td class=heading>Total Annual Benefits including bill savings</td>"+
				"<td class=heading>Payback on cost of typical system (Years)</td>"+
				"<td class=heading>Ongoing Benefits (Years)</td>"+
				"</tr>"+getBenefitsMatrix(id)+"</table>");
	});
			
	
/******* END OF BENEFITS MATRIX SECTION ***********************/
	
	
	

	/**
	 *  Generate Property Types 
	 */
	function generatePropertyTypes()
	{
		// holds ids of properties for referring to them, much safer than using the titles to allow these to be changed without effect
		propertyID = new Array("bungalow","flat_ground_floor","flat_middle_floor","flat_top_floor","house_detached","house_semidetached","house_terraced","maisonette");
		// creates the property titles, where locations are linked to the propertyID above
		return createOptions("Bungalow,Flat - Ground Floor,Flat - Middle Floor, Flat - Top Floor,House - Detached,House - Semi-Detached, House - Terrace,Maisonette",true);
	}
	

	
	/**
	 *  Generate Fuel Types 
	 */
	function generateFuelTypes()
	{
		return createOptions("Gas,Oil,LPG,Electric,Coal",false);
	}
	
	/**
	 *  Create the options that go into the select field 
	 */
	function createOptions(data,property)
	{
		var options = "";
		var list = data.split(",");
		
		for (var i=0;   i<list.length;   i++)
		{
			if (property)
				options+="<option value="+propertyID[i]+">"+list[i]+"</option>"; // add to <options> tag for simple inserting into <select> tag
			else
					options+="<option value="+list[i].toLowerCase()+">"+list[i]+"</option>"; // add to <options> tag for simple inserting into <select> tag
		}
		
		return options;
	}

	var locations;
	function traceLocation()
	{
		if ((applicableEnergy !=  null) && (applicableEnergy !=  ""))
		{
			locations = "Start Page > Property & Fuel Type Selecion > "
			for (var i = 0; i < applicableEnergy.length;i++)
			{
				if (applicableEnergy[i] != "MicroCHP")
				{
					if (currentSection == applicableEnergy[i])
					{
						locations +="<b>" + applicableEnergy[i] + "</b> > " ;
					}else
					{
						locations += applicableEnergy[i] + " > ";
					}
				}
					
			}
		}else
		{
			if (currentSection = "main")
			{
				locations="<b>Start Page </b> > Property & Fuel Type Selection > ";
			}
		}
		
		jQuery("#locationTrace").html(locations);	
	}
	
	function showEnergySelectorLocation()
	{
		jQuery("#locationTrace").html("Start Page > <b>Property & Fuel Type Selection</b> > ");	
	}

	/**
	 * Store the user information and technologies in the basket in the database
	 */
	function getQuestion(section,questionno)
	{
		if (section == 'end' && questionno == 0) {
			questionno++;
			currentQuestionNo = questionno;
		}
		
		var desturl = jQuery("#desturl").val(); // destination url		
		// load the page concatenating currentSection with currentQuestionNo
		var page = section+"/"+""+questionno+".php";
		jQuery("#technology").load(desturl+energyselectorfolder+"/"+page,function()
		{
			if ((section == "main") && (questionno == 1))
			{
				var properties = generatePropertyTypes();
				var fueltypes = generateFuelTypes();
				jQuery("#propertType").html(properties);
				jQuery("#fuelType").html(fueltypes);
			}	
			
		});
	
	}
	
	/**
	 * Store the user information and technologies in the basket in the database
	 */
	function getCustomPage(section,pagename)
	{
		var desturl = jQuery("#desturl").val(); // destination url		
		// load the page concatenating currentSection with currentQuestionNo
		var page = section+"/"+""+pagename+".php";
		jQuery("#technology").load(desturl+energyselectorfolder+"/"+page,function()
		{
			if (pagename == 'maps_page') {
				if(energyselectorfolder == 'energyselector_external') {
					mapLoad(personalInfo["postcode"]); // pass postcode to google maps
				} else {
					mapLoadCustom(personalInfo["postcode"],500,175); // pass postcode to google maps with custom size
				}
			}
		});
	}
	
	/**
	 * Populate the question depending on the section and the question number
	 */ 
	function showQuestion()
	{
		getQuestion(currentSection,currentQuestionNo);
	}
	
	function showAdvice()
	{

			extraBefore = "<b><font color='green'>"+mainQuestionsAdvice[currentQuestionNo]+"</font></b><br/><br/>";
			jQuery("#energyadvice").html(extraBefore);
			currentQuestionNo++;
			showQuestion();
			
	}
	
	/**
	 * Hide all text,advice etc not related to questions
	 */
	function hidePreEnergyData()
	{
		jQuery("#energyadvice").html("");
		jQuery("#instructions").html("");
	}
	


	/**
	 * Load the next energy type questions
	 */
	function goToNextSection()
	{
		var techUrl = jQuery("#siteUrl").val();
		
		// wind is the last section so just go straight to the end
		if (currentSection != "wind")
		{
			sectionNo++;//increment section so that we can move on
			currentSection = applicableEnergy[sectionNo];
			currentQuestionNo = 0;
		}

		// no questions for MicroCHP so just add it to basket and move to next question
		if (currentSection == "microchp")
		{
			currentQuestionNo = 0;
			if (choice == "yes")
			{
				addToBasket("<li class=selected-energy id=microchp>" +
						"<a href="+techUrl+"your-options/micro-chp>Micro<br />CHP</a>"+
						"<div class=helpbox><a href=javascript:void(0) id=microchp class=selected-energy_help><p id=help-icon>(more info)</p></a></div>" +
						"</li>");
				addShortCode("MicroCHP");
			}
			
			if (isLastItem())
			{	
				if (currentQuestionNo > 1 && currentSection == 'section') {
					showBasketContents();
				}
			}else
			{
				sectionNo++;
				currentSection = applicableEnergy[sectionNo];
				showQuestion();
			}
			return;
		}
		
		showQuestion();
	}
	
	/**
	 * Load the next question
	 */
	function goToNextQuestion()
	{
		currentQuestionNo++;
		showQuestion();
	}
	
	var lastAnswer = '';
	function isLastItem()
	{

		if (((currentSection == applicableEnergy[applicableEnergy.length-1]) || (currentSection == "end")) && (currentSection != "wind"))
		{
			addAnswer(lastAnswer);
			showEndingQuestions();
			return true;
		}
		
		return false;
	}
	
	
	/**
	 * Store the user information and technologies in the basket in the database
	 */
	function addAnswer(answer)
	{
		var desturl = jQuery("#desturl").val(); // destination url
		
		// pass the data to the correct model to store the data
		jQuery.ajax({
				type:			"POST",
				url:			desturl+"energyselector/addAnswer.php",
				dataType:		"html",
				cache:			false,
				async: 			false,
				data:			"answertext="+answer,					
				success:		function(html){}
		});
		return true;
	}
	
	/**
	 * Store the selected property type 
	 */
	function storeSelectedProperty(propertyType)
	{
		var desturl = jQuery("#desturl").val(); // destination url
		
		// pass the data to the correct model to store the data
		jQuery.ajax({
				type:			"POST",
				url:			desturl+"energyselector/addAnswer-property.php",
				dataType:		"html",
				cache:			false,
				data:			"answertext="+propertyType,					
				success:		function(html){}
		});
		return true;
	}
	
	
	jQuery("#help-img").livequery('click', function(e) 
	{
		jQuery.facebox(jQuery('#help-text-contents').show());
	});
	

	function showEndingQuestions()
	{
		if ((currentSection == "end") && (currentQuestionNo > 2))
		{
			showBasketContents();
			resetApplication();
		}else
		{
			currentSection = "end";
			showQuestion();
			currentQuestionNo++;
		}
	}
	
	
	/**
	 * Takes action depending on the current section and the fact that yes is clicked. Remember that since we are using an array question 0 = question 1
	 */
	function takeYesAction()
	{

		extraBefore = "";
		extraAfter = "";
		lastAnswer = 'yes'; // due to the logic written before this modification this is used ONLY for the END section
		
		// last item is always wind if its applicable then deal with it, if its not applicable this is ignored
		if ((currentSection == "wind") && (currentQuestionNo == 0))
		{
			var siteUrl = jQuery("#enquiryFormUrl").val();
			addToBasket("<li class=selected-energy id=wind>" +
					"<a href="+siteUrl+"your-options/mini-wind>Wind</a>"+
					"<div class=helpbox><a href=javascript:void(0) id=wind class=selected-energy_help><p id=help-icon>(more info)</p></a></div>" +
					"</li>");
			addShortCode("Wind");
		}
		else
		if (isLastItem())
		{
			currentSection = "end";
			return;
		}
		
		var techUrl = jQuery("#siteUrl").val();
		switch (currentSection)
		{
			case "end":
				addAnswer("yes");
				break;
			case "solarpv":
				addAnswer("yes");
				addToBasket("<li class=selected-energy id=solarpv>" +
						"<a href="+techUrl+"your-options/solar-electricity>Solar<br />Electricity</a>" +
						"<div class=helpbox><a href=javascript:void(0) id=solarpv class=selected-energy_help><p id=help-icon>(more info)</p></a></div>" +
						"</li>");
				addShortCode("Solar PV");
				goToNextSection();
				break;
			case "solarthermal":
				addAnswer("yes");
				addToBasket("<li class=selected-energy id=solarthermal>" +
						"<a href="+techUrl+"your-options/solar-heating> Solar<br />Heating</a>" +
						"<div class=helpbox><a href=javascript:void(0) id=solarthermal class=selected-energy_help><p id=help-icon>(more info)</p></a></div>" +
						"</li>");
				addShortCode("Solar Thermal");
				goToNextSection();
				break;
			case "ashp":
				addAnswer("yes");
				addToBasket("<li class=selected-energy id=ashp>" +
						"<a href="+techUrl+"your-options/air-source-heat-pumps>Air Source<br />Heat Pump</a>" +
						"<div class=helpbox><a href=javascript:void(0) id=ashp class=selected-energy_help><p id=help-icon>(more info)</p></a></div>" +
						"</li>");
				addShortCode("ASHP");
				goToNextSection();
				
				break;
			case "microchp":
				addAnswer("yes");
				goToNextSection();	
				break;
			case "main":
				addAnswer("yes");
				currentSection="main";
				currentQuestionNo++;
				showQuestion();
				break;
			case "gshp":
				addAnswer("yes");
				if (currentQuestionNo == 1)
				{
					addToBasket("<li class=selected-energy id=gshp>" +
							"<a href="+techUrl+"your-options/ground-source-heat-pump>Ground Source<br />Heat Pump</a>" +
							"<div class=helpbox><a href=javascript:void(0) id=gshp class=selected-energy_help><p id=help-icon>(more info)</p></a></div>" +
							"</li>");
					addShortCode("GSHP");
					goToNextSection();	
				}else
				{
					goToNextQuestion();
				}
				break;
			case "biomass":
				addAnswer("yes");
				if (currentQuestionNo == 1)
				{
					addToBasket("<li class=selected-energy id=wood>" +
							"<a href="+techUrl+"your-options/wood-fuelled-heating>Wood Fuel<br />Heating</a>" +
					"<div class=helpbox><a href=javascript:void(0) id=wood class=selected-energy_help><p id=help-icon>(more info)</p></a></div>" +
					"</li>");
					addShortCode("Biomass");
					goToNextSection();	
				}else
				{
					goToNextQuestion();
				}
				break;
			case "wind": // This is the last energy type so reset all variables for reuse of the application and show the contents of the basket
				addAnswer("yes");
				
				if (currentQuestionNo == 1)
				{
					addToBasket("<li class=selected-energy id=wind>" +
							"<a href="+techUrl+"your-options/mini-wind>Mini<br />Wind</a>"+
					"<div class=helpbox><a href=javascript:void(0) id=wind class=selected-energy_help><p id=help-icon>(more info)</p></a></div>" +
					"</li>");
					addShortCode("Wind");
					showEndingQuestions();
				}else
				{
					goToNextQuestion();
				}
				break;
		}
	}
	
	
	
	/*
	 * Takes action depending on the current section and the fact that yes is clicked. Remember that since we are using an array question 0 = question 1
	 */
	function takeNoAction()
	{

		extraBefore = "";
		extraAfter = "";
		lastAnswer = 'no'; // due to the logic written before this modification this is used ONLY for the END section
		
		if (isLastItem())
		{
			lastAnswer = 'no';
			currentSection = "end";
			return;
		}
		
		removeFromBasket(); // if its in the basket then remove from it

		switch (currentSection)
		{
			case "end":
				addAnswer("no");
				break;
			case "main":
				addAnswer("no");
				currentSection="main";
				currentQuestionNo++;
				showQuestion();
				break;
			case "solarpv":
				addAnswer("no");
				goToNextSection();
				break;
			case "solarthermal":
				addAnswer("no");
				goToNextSection();
				break;
			case "ashp":
				addAnswer("no");
				goToNextSection();
				break;
			case "gshp":
				addAnswer("no");
				goToNextSection();
				break;
			case "biomass":
				addAnswer("no");
				goToNextSection();
				break;
			case "wind": // This is the last energy type so reset all variables for reuse of the application and show the contents of the basket
				addAnswer("no");
				currentQuestionNo=1;
				showEndingQuestions();
				break;
		}
	}
	

	
	/**
	 * Reset the application for reuse
	 */
	function resetApplication()
	{
		currentQuestionNo = 0; // reset questions
		currentSection = "main"; // reset section to main
		sectionNo = 0; // reset section no
		applicableEnergy = ""; // reset applicable energies
		basket = ""; // clear basket contents
		basket2 = ""; // clear basket contents
		basket = new Array();
		basket2 = new Array();
	}
	
	function removeShortCodeFromBasket()
	{
		if(basket2[sectionNo]!=null)
		{
			basket2[sectionNo] = null;
		}
	}
	
	function removeFromBasket()
	{
		if(basket[sectionNo]!=null)
		{
			basket[sectionNo] = null;
			//ensure focus is set back
		}
	}
	
	/**
	 * Store the user information and technologies in the basket in the database
	 */
	function getBasketPage(basketContents)
	{
		jQuery.facebox('<p class="please-wait-message">Please wait...</p>');
		window.location.href="energy-selector?completed=true";
	}
	
	/**
	 * Store the user information and technologies in the basket in the database
	 */
	function storeResultsSession()
	{
		var desturl = jQuery("#desturl").val(); // destination url
		
		// pass the data to the correct model to store the data
		jQuery.ajax({
				type:			"POST",
				url:			desturl+energyselectorfolder+"/storeResultsSession.php",
				dataType:		"html",
				cache:			false,
				data:			"selected-technologies="+basketContents,					
				success:		function(html)
				{
					getBasketPage("");
				}
		});
	}
	
	var basketContents;
	/**
	 * Print the contents of the basket
	 */
	function showBasketContents()
	{
		if (basket != "")
		{
			basketContents = "";
			for (var i = 0; i < basket.length; i++)
			{
				if (basket[i] != null)
				{
					basketContents +=  basket[i];// + " - ";
				}
			}
			// store user information
			storeDetails();
			storeResultsSession();
		}
		else {
			getBasketPage("No results");
		}
	}
	
	/**
	 * Store the user information and technologies in the basket in the database
	 */
	function storeDetails()
	{
		var technologies = basket2;
		var desturl = jQuery("#desturl").val(); // destination url
		if (typeof personalInfo["phone"]  == "undefined" || personalInfo["phone"] == null || personalInfo["phone"] == '')  { personalInfo["phone"] = ""; } 
		
		// If initial entered postcode was wrong and Google Maps prompted for a re-enter we need to grab the correct postcode
		if (stored_postcode != '') {
			personalInfo["postcode"] = stored_postcode;
		}
				
		// pass the data to the correct model to store the data
		jQuery.ajax({
				type:			"POST",
				url:			desturl+"energyselector.php",
				dataType:		"html",
				cache:			false,
				data:			"firstname="+personalInfo["firstname"]
								+"&surname="+personalInfo["surname"]
								+"&email="+personalInfo["email"]
								+"&postcode="+personalInfo["postcode"]
								+"&energycost="+personalInfo["energycost"]
								+"&phone="+personalInfo["phone"]
								+"&latitude="+stored_latitude
								+"&longitude="+stored_longitude
								+"&technologies="+technologies,					
				success:		function(html){}
		});
	}
	
	/**
	 * Add energy type to basket
	 */
	function addToBasket(energyType)
	{
		basket[sectionNo] = energyType;
	}
	
	function addShortCode(energyType)
	{
		basket2[sectionNo] = energyType;
	}


//----------------- ALL GLOBAL VARIABLES-----------------------------------------------------------
	
	// Energy Selector folder (at this moment its energyselector and energyselector_external
	var energyselectorfolder = 'energyselector'; // default
	
	// holds basket contents
	var basket = "";
	
	var extraAfter=""; // any data you want to display before the question
	var extraBefore=""; // any data you want to display after the question
	
	// List of energy types
	var energyList = new Array("solarpv", "solarthermal","gshp","ashp","biomass","microchp","wind"); //microchp
	
	// Questions for energy types
	var mainQuestions = new Array("Are you the homeowner or property manager?","Do you have loft and cavity wall insulation","What type of property do you have?","What is your heating fuel type?","How much is your annual heating and electricity bill?");
	var mainQuestionsAdvice = new Array("Green Energy Providers can help you cut CO2","Insulation is a very c/e way of saving energy");
	var solarPVQuestions = new Array("Do you have an unshaded roof space facing between east and west through south?");
	var solarThermalQuestions = new Array("Do you have space for a hot water tank?");
	var gshpQuestions = new Array("Do you own an area of open ground large enough to accommodate groundwork required for a Ground Source Heat Pump?","Do you have space to install a GSHP unit?");
	var ashpQuestions = new Array("Do you have space on an external wall to place and ASHP unit?");
	var bioMassQuestions = new Array("Do you have enough space to store fuel between deliveries","Do you have space for a wood fuel boiler?");
	var windQuestions = new Array("Do you live in a rural, coastal or suburban area?","Do you have an area of unrestricted open ground with good wind flows?");
	
	// holds property types and fuel types
	var bungalow = new Array();
	var flatgroundfloor = new Array();
	var flatmiddlefloor = new Array();
	var flattopfloor = new Array();
	var housedetached = new Array();
	var housesemidetached = new Array();
	var houseterraced = new Array();
	var maisonette = new Array();
	
	var propertyID;
	var currentSection = ""; //the current energy section we are on
	var currentQuestionNo; // the current question number
	var sectionNo; // the current section
	var applicableEnergy;	// will hold array of all energy types for which we want to populate questions
	// holds the size for the number of applicable energies
	var applicableEnergySize;
	var locationTrace; // traces where you are 
	
//----------------- USER EVENTS------------------------------------------------------------------------
	
	// energy selector is click the main question is loaded
	jQuery('#energyselector').livequery('click', function(event) 
	{
		// load main question
		getMainQuestion();
	});
	
	// Clicking the Next button on the first energy selector page
	jQuery('#select_page1').livequery('click', function(event) 
	{
		jQuery("#property-selection").hide();
		jQuery("#question-section").show();
		hidePreEnergyData(); // hide the advice and instructions text as questions will follow
		var propertyType = jQuery("#propertType option:selected").val();
		var fuelType = jQuery("#fuelType option:selected").val();
		
		if ((propertyType == "") || (fuelType == ""))
		{
			// error message if nothing is selected
			jQuery("#energyadvice").html("Please select Yes or No!");
			jQuery("#energyadvice").addClass("errorMessage");
		}else
		{			
			jQuery("#energyquestions").html("");
			jQuery("#specificenergyselector").css("display", "none"); 
			if (storeSelectedProperty(propertyType))
			{
				showApplicableFields(propertyType,fuelType);
			}
		}
	});
	
	var choice;
	// User clicked Next on a question
	jQuery('.specificenergyNext').livequery('click', function(event) 
	{
		jQuery("#energyadvice").html("");
		//choice = jQuery("input[name='energyTypeChoice']:checked").val(); 
		choice = jQuery(this).attr('id');
		

		if (choice == null) 
		{
			// error message if nothing is selected
			jQuery("#energyadvice").html("Please select Yes or No!");
			jQuery("#energyadvice").addClass("errorMessage");
		}else
		{	
			// show previous button if we press next on the main page
			if (currentSection == "main")
				jQuery("#specificenergyPrevious").show();// show previous button
	
			if (choice == "yes")
			{
				takeYesAction();
			}else if (choice == "no")
			{
				takeNoAction();
			}		
		}	
	});
	
	var personalInfo = new Array();; // holds personal information
	// User clicked Next on a question
	jQuery('#specificenergyNextStart').livequery('click', function(event) 
	{
		var firstname = jQuery('#energyselector_firstname').val(); // store firstname
		var surname = jQuery('#energyselector_surname').val(); // store firstname
		var email = jQuery('#energyselector_email').val(); // store email
		var postcode = jQuery('#energyselector_postcode').val(); // store postcode
		var telephone = jQuery('#energyselector_phone').val(); // store telephone
	
		if (typeof telephone  == "undefined")  { telephone = ""; } // if undefined set to empty value
		
		// validation
		var validatedetails = Array();
		validatedetails['firstname'] = firstname;
		validatedetails['surname'] = surname;
		validatedetails['email'] = email;
		validatedetails['postcode'] = postcode;
		
		var error = validatePersonalDetails(validatedetails);
		
		if (error)
		{
			jQuery('#incomplete-field-error').show();
			return;
		}else
		{
			jQuery('#incomplete-field-error').hide();
		}
		
		
		personalInfo["firstname"] = firstname;
		personalInfo["surname"] = surname;
		personalInfo["email"] = email;
		personalInfo['phone'] = telephone;
		personalInfo["postcode"] = jQuery('#energyselector_postcode').val(); // store postcode
		personalInfo["energycost"] = jQuery('#energyselector_energycost').val(); // store energy costs
		energy_cost = jQuery('#energyselector_energycost').val();
		
		getCustomPage('main','maps_page'); // get custom page
		
	});
	
	// User clicked Next on a question
	jQuery('#getCustomPage').livequery('click', function(event) 
	{
		// set to use external folder
		energyselectorfolder = 'energyselector_external';
		
		var firstname = jQuery('#energyselector_firstname').val(); // store firstname
		var surname = jQuery('#energyselector_surname').val(); // store firstname
		var email = jQuery('#energyselector_email').val(); // store email
		var postcode = jQuery('#energyselector_postcode').val(); // store postcode
		var telephone = jQuery('#energyselector_phone').val(); // store telephone
	
		if (typeof telephone  == "undefined")  { telephone = ""; } // if undefined set to empty value
		
		// validation
		var validatedetails = Array();
		validatedetails['firstname'] = firstname;
		validatedetails['surname'] = surname;
		validatedetails['email'] = email;
		validatedetails['postcode'] = postcode;
		
		
		var error = validatePersonalDetails(validatedetails);
		
		if (error)
		{
			jQuery('#incomplete-field-error').show();
			return;
		}else
		{
			jQuery('#incomplete-field-error').hide();
		}
		
		
		personalInfo["firstname"] = firstname;
		personalInfo["surname"] = surname;
		personalInfo["email"] = email;
		personalInfo['phone'] = telephone;
		personalInfo["postcode"] = jQuery('#energyselector_postcode').val(); // store postcode
		personalInfo["energycost"] = jQuery('#energyselector_energycost').val(); // store energy costs
		energy_cost = jQuery('#energyselector_energycost').val();
		jQuery('.next-button').hide();
		getCustomPage('main','maps_page'); // get custom page

	});
	
	function validatePersonalDetails(validatedetails)
	{
		var vfirstname = validatedetails['firstname'];
		var vsurname = validatedetails['surname'];
		var vpostcode = validatedetails['postcode'];
		var vemail = validatedetails['email'];
		
		var error = false;
		jQuery('#incomplete-field-error').html('* Please complete the selected field(s)!');
		// validate firstname, surname and email
		if (vfirstname == "")
		{
			jQuery('#energyselector_firstname').addClass("validate-field");
			error = true;
		}else
		{
			jQuery('#energyselector_firstname').removeClass("validate-field");
		}
		
		if (vsurname == "")
		{
			jQuery('#energyselector_surname').addClass("validate-field");
			error = true;
		}else
		{
			jQuery('#energyselector_surname').removeClass("validate-field");
		}

		if (vpostcode == "")
		{
			jQuery('#energyselector_postcode').addClass("validate-field");
			error = true;
		}else
		{
			jQuery('#energyselector_postcode').removeClass("validate-field");
		}
				
		if (vemail == "")
		{
			jQuery('#energyselector_email').addClass("validate-field");
			error = true;
		}else
		{
			if (!error) 
			{
				var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
				if(reg.test(vemail) == false) {
					jQuery('#energyselector_email').addClass("validate-field");
					jQuery('#incomplete-field-error').html('* Email is invalid!');
					error = true;
				} else {
					jQuery('#energyselector_email').removeClass("validate-field");		      
				}
			}
		}
		
		return error;	
	}
	
	// User clicked Next on a question
	jQuery('#startSurveyBtn').livequery('click', function(event) 
	{
		getMainQuestion();
	});
	
	jQuery("#terms-and-conditions").click(function()
	{
	       
        // If checked
        if (jQuery("#terms-and-conditions").is(":checked"))
        {
            //show the hidden div
        	jQuery('#specificenergyNextStart').css("visibility","");
        }
        else
        {     
            //otherwise, hide it
        	jQuery('#specificenergyNextStart').css("visibility","hidden");
        }
      });
      
	jQuery('#next-button').css("display","none");	// uncheck button if page refreshed
	jQuery("#terms-and-conditions-external").attr("checked",false); // uncheck checkbox if page refreshed
	jQuery("#terms-and-conditions-external").click(function() {
		 // If checked show next button
        if (jQuery("#terms-and-conditions-external").is(":checked")) {
            //show the hidden div
        	jQuery('#next-button').css("display","block");
        } else {     
            //otherwise, hide it
        	jQuery('#next-button').css("display","none");
        }
      });
	
	jQuery('#specificenergyNextStart').css("visibility","hidden");
	
	// User clicked Previous on a question
	jQuery('#specificenergyPrevious').livequery('click', function(event) 
	{
		jQuery("#energyadvice").html("");
		
		// go back to Energy Selector screen
		if ((sectionNo == 0) && (currentQuestionNo == 0))
		{
			currentSection = "Energy Selector";
			getEnergySelector();
		}else 
		if ((currentSection == "main") || (currentSection == "Energy Selector"))
		{
			currentSection = "main";
			// hide previous button
			jQuery("#specificenergyPrevious").hide();
			currentQuestionNo--; // go to previous section;
			showQuestion();
		}else
		{
			// go to previous question if there is more than one question
			if (currentQuestionNo > 0)
			{
				currentQuestionNo--; // go to previous section;
				currentSection = applicableEnergy[sectionNo];
				showQuestion();
			}else
			{
				// go to previous section if this section only has one question
				sectionNo--; // go to previous section;
				currentSection = applicableEnergy[sectionNo];
				showQuestion();
			}
		}
	});
		
});

	// Explanation for why we need your location on Google Maps
	function showMapExplanation()
	{
		jQuery.facebox("<h2>Why do we need this?</h2><br/><div id='help-text-contents'>To help us determine whether a number of technologies might be suitable, for example via orientation of your roof etc</div>");
	}
