// JavaScript Document

$(document).ready(function() {
	textEnlarger();
	checkCookie();
	tabbedMenu();
	footerWidthCalculator();
	lastPaddingRemover();
	topStoryBackground();
	rateThisPageOver();
	rightModuleBorder();
	mpgCalculatorFixer();
	//heightSetter();
	leftNavInserter();
	//siteMapScotland();
	uploadCaseStudy();
	showHideFilters();
	createCaseStudy();
	postSerialize();
	printCase();
	//newLayoutSwitcher();
	casestudydetailForm();
	subfilterSelection();
	pleaseSelectRemove();
	requestAccessForm();
});
$(document).ready(function() {
	var firstName = $("#firstName");
	var lastName = $("#lastName");
	var organisation = $("#organisation");
	var emailAddress = $("#emailAddress");
	var contactPhoneNumber = $("#contactPhoneNumber");
	var postCode = $("#postCode");
	var nameNumber = $("#nameNumber");
	var townCity = $("#townCity");
	var country = $("#country");
	var agreeTerms = $("#termsConditions");
	
	//On blur
	firstName.blur(validateFirstName);
	lastName.blur(validateLastName);
	emailAddress.blur(validateEmail);
	postCode.blur(validatePostCode);
	nameNumber.blur(validateNameNumber);
	organisation.blur(valOrganisation);
	townCity.blur(validateTownCity);
	country.blur(validateCountry);
	agreeTerms.blur(validateTermsCondition);
	
	function validateFirstName(){
		//if it's NOT valid
		if(firstName.val().length < 1){
			if(firstName.parents("li").children("span.gidError").length < 1){
				firstName.parents("li").append("<span class='gidError'>Please enter first name.</span>");
			}
			return false;
		}
		//if it's valid
		else{
			firstName.parents("li").children("span.gidError").remove();
			return true;
		}
	}

	function validateLastName(){
		//if it's NOT valid
		if(lastName.val().length < 1){
			if(lastName.parents("li").children("span.gidError").length < 1){
				lastName.parents("li").append("<span class='gidError'>Please enter last name.</span>");
			}
			return false;
		}
		//if it's valid
		else{
			lastName.parents("li").children("span.gidError").remove();
			return true;
		}
	}
	
	function validateEmail(){
		//if it's NOT valid
		if (!emailAddress.val().match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
			if(emailAddress.parents("li").children("span.gidError").length < 1){
				emailAddress.parents("li").append("<span class='gidError'>Please enter valid email address.</span>");
			}
			return false;
		}
		//if it's valid
		else{
			emailAddress.parents("li").children("span.gidError").remove();
			return true;
		}
	}

	function validatePostCode(){
		//if it's NOT valid
		if(postCode.val().length < 1){
			if(postCode.parents("li").children("span.gidError").length < 1){
				postCode.parents("li").append("<span class='gidError'>Please enter valid post code.</span>");
			}
			return false;
		}
		//if it's valid
		else{
			postCode.parents("li").children("span.gidError").remove();
			return true;
		}
	}

	function validateNameNumber(){
		//if it's NOT valid
		if(nameNumber.val().length < 1){
			if(nameNumber.parents("li").children("span.gidError").length < 1){
				nameNumber.parents("li").append("<span class='gidError'>Please enter an address name or number.</span>");
			}
			return false;
		}
		//if it's valid
		else{
			nameNumber.parents("li").children("span.gidError").remove();
			return true;
		}
	}

	function valOrganisation(){
		//if it's NOT valid
		if(organisation.val().length < 1){
			if(organisation.parents("li").children("span.gidError").length < 1){
				organisation.parents("li").append("<span class='gidError'>Please enter organisation.</span>");
			}
			return false;
		}
		//if it's valid
		else{
			organisation.parents("li").children("span.gidError").remove();
			return true;
		}
	}

	function validateTownCity(){
		//if it's NOT valid
		if(townCity.val().length < 1){
			if(townCity.parents("li").children("span.gidError").length < 1){
				townCity.parents("li").append("<span class='gidError'>Please enter town or city.</span>");
			}
			return false;
		}
		//if it's valid
		else{
			townCity.parents("li").children("span.gidError").remove();
			return true;
		}
	}

	function validateCountry(){
		//if it's NOT valid
		if(country.val().length < 1){
			if(country.parents("li").children("span.gidError").length < 1){
				country.parents("li").append("<span class='gidError'>Please enter a country.</span>");
			}
			return false;
		}
		//if it's valid
		else{
			country.parents("li").children("span.gidError").remove();
			return true;
		}
	}

	function validateTermsCondition(){
		if (document.requestForm.termsConditions.checked == false){
			if(agreeTerms.parent("li").children("span.gidError").length < 1){
				agreeTerms.parent("li").append("<span class='gidError'>Please accept terms and conditions.</span>");
			}
			return false;
		}
		else
		{
			agreeTerms.parent("li").children("span.gidError").remove();
			return true;
		}
	}

	$("#submitRequestForm").click(function(){
		if(validateFirstName() & validateLastName() & validateEmail() & validatePostCode() & validateNameNumber() & valOrganisation() & validateTownCity() & validateCountry() & validateTermsCondition()){
			var strRequestForm = $("#requestForm").serialize();
			$("#responseRequestForm").fadeIn("slow");
			$("#responseRequestForm").html("Sending data...");
			$.ajax({	
				type: "POST",
				url: "/calculator/share_mail",
				data: strRequestForm,
				cache: false,
				success: function(html){
					$("#responseRequestForm").html(html);
					setTimeout('$("#responseRequestForm").fadeOut("slow")',4000);
					setTimeout('$(".request_form").fadeOut("slow")',4000);
					setTimeout('$("#backgroundPopup").fadeOut("slow")',4000);
					$("#firstName").val("");
					$("#lastName").val("");
					$("#organisation").val("");
					$("#emailAddress").val("");
					$("#contactPhoneNumber").val("");
					$("#nameNumber").val("");
					$("#address2").val("");
					$("#townCity").val("");
					$("#country").val("");
					$("#postCode").val("");
					$("#termsConditions").val("");

				}
			});
			return false;
		}
		else{
			return false;
		}
	});
});

var popupStatus = 0;
function disablePopup(){
	if(popupStatus==1){
		$("#backgroundPopup").fadeOut("slow");
		$(".request_form").fadeOut();
		$("#firstName").val("");
		$("#lastName").val("");
		$("#organisation").val("");
		$("#emailAddress").val("");
		$("#contactPhoneNumber").val("");
		$("#nameNumber").val("");
		$("#address2").val("");
		$("#townCity").val("");
		$("#country").val("");
		$("#postCode").val("");
		$("#termsConditions").val("");


		popupStatus = 0;		
	}
}
function loadPopup(){
	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("slow");
		$("#popupContact").fadeIn("slow");
		popupStatus = 1;
	}
}
function requestAccessForm(){

	var styleCurrent = $(this).attr("style");
	$("div.image").each(function(){
		if($(this).attr("style") != ''){
			$(this).parent("div.block").addClass("appliedImage");
		}
		
		var headingResult = $.trim($(this).parent("div.appliedImage").children("h2").text());
		if(headingResult == "New sustainable refurbishment guide"){
			$(this).parent("div.block").children("div.image").attr("style", "background: transparent url(/extension/redesign_business/design/business/images/redesign/contentPage/sustainableGuide.jpg) no-repeat scroll 0% 0%; cursor: pointer; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;");
		}
		if(headingResult == "Visit us at EcoBuild 2nd to 4th March 2010"){
			$(this).parent("div.block").children("div.image").attr("style", "background: transparent url(/extension/redesign_business/design/business/images/redesign/contentPage/ecoBuild.jpg) no-repeat scroll 0% 0%; cursor: pointer; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;");
		}

		if(headingResult == "Helpful Tools"){
			$(this).parent("div.block").children("div.image").attr("style", "background: transparent url(/extension/redesign_business/design/business/images/redesign/contentPage/helpfulTools.jpg) no-repeat scroll 0% 0%; cursor: pointer; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;");
		}

	});


	//centering popup
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var applicationBenefitHeight = $(".applicationBenefit").height();
	var applicationBenefitWidth = $(".applicationBenefit").width();
	$(".request_form").css({
		"left": windowWidth/2-applicationBenefitWidth/2-300,
		"top": windowHeight/2-applicationBenefitHeight/2-200
	});

	$(".requestAccess a").click(function(){
		$(".request_form").fadeIn();
		loadPopup();
		$(".closeList").click(function(){
			disablePopup();
			return false;
		});
		$("#backgroundPopup").click(function(){
			disablePopup();
			$(".request_form").fadeOut();
		});
		$(document).keypress(function(e){
			if(e.keyCode==27 && popupStatus==1){
				disablePopup();
			}
		});	
		return false;
	});

}

function pleaseSelectRemove(){
	$(".projectType span").each(function(i){
		var projectTypeText =$.trim($(this).text());
		if(projectTypeText == ",Please select"){
			$(this).remove();
		}
	});
}


function subfilterSelection(){
	$("input#domestic").click(function(){
		var statusDomestic = $("input#domestic").attr("checked");
		if(statusDomestic){
			$("ul#DomesticFilters input").attr("checked","checked");
		}
		else{
			$("ul#DomesticFilters input").removeAttr("checked","checked");
		}
	});
	$("input#nondomestic").click(function(){
		var statusNondomestic = $("input#nondomestic").attr("checked");
		if(statusNondomestic){
			$("ul#NonDomesticFilters input").attr("checked","checked");
		}
		else{
			$("ul#NonDomesticFilters input").removeAttr("checked","checked");
		}
	});
	$("input#transport").click(function(){
		var statusTransportFilters = $("input#transport").attr("checked");
		if(statusTransportFilters){
			$("ul#TransportFilters input").attr("checked","checked");
		}
		else{
			$("ul#TransportFilters input").removeAttr("checked","checked");
		}
	});
	$("input#community").click(function(){
		var statusDomestic = $("input#community").attr("checked");
		if(statusDomestic){
			$("ul#CommunityFilters input").attr("checked","checked");
		}
		else{
			$("ul#CommunityFilters input").removeAttr("checked","checked");
		}
	});
	$("input#strategy").click(function(){
		var statusDomestic = $("input#strategy").attr("checked");
		if(statusDomestic){
			$("ul#StrategyFilters input").attr("checked","checked");
		}
		else{
			$("ul#StrategyFilters input").removeAttr("checked","checked");
		}
	});
}

function casestudydetailForm(){
	$(".notSignedIn a").click(function(){
		$(".casestudydetailForm").fadeIn();
		return false;
	});
	var uploadCaseStudyHead = $(".uploadCaseStudyHeading").text();
	if(uploadCaseStudyHead == "Upload your case study"){
		$(".rightSectionLast h2:last").hide();
		$(".rightSectionLast p.callNumber:last").hide();
	}
	var shareHead = $(".caseStudy h1").text();
	if(shareHead == "ShARE (Sharing Action on Reducing Emissions)"){
		$(".rightSectionLast h2:last").hide();
		$(".rightSectionLast p.callNumber:last").hide();
	}
}

function newLayoutSwitcher(){
	$("<div class='introPara'></div>").appendTo(".page-title");
	$("div.introPara").html($('.content-attribute-introduction').html());
}

function printCase(){
	$(".printCase").click(function(){
		window.print();
		return false;
	});
}

function postSerialize(){
	$(".searchfilter input").click(function(){
		window.scroll(400,400);
		$(".loading").ajaxStart(function(){ 
		  $(this).show(); 
			$(this).css({
				"opacity": "0.5"
			});
		});
		$(".loading").ajaxStop(function(){ 
  			$(this).hide(); 
		});
		var strForm11 = $("#sendFilter1").serialize();
		$.ajax({	
			type: "POST",
			url: "/extension/redesign_business/design/business/javascript/search_la.php",
			data: strForm11 ,
			cache: false,
			success: function(html){
				$(".searchResultContainer").html(html);
			}
		});
		

		return false;
	});

}

$(function() {
	$("input[@type=file]").filestyle({
		image: "/extension/redesign_business/design/business/images/redesign/customForm/img_browse.gif",
		imageheight : 23,
		imagewidth : 56,
		width : 290
        });

});

/* -------------------------------------------------------------------------------------------------------------
	Create link starts here 
---------------------------------------------------------------------------------------------------------------*/
function createCaseStudy(){

	$("a[href$='.pdf']").addClass("pdf");
	
}


/* -------------------------------------------------------------------------------------------------------------
	Create link script ends here 
---------------------------------------------------------------------------------------------------------------*/

/* -------------------------------------------------------------------------------------------------------------
	Search form script starts here 
---------------------------------------------------------------------------------------------------------------*/
function serializeCheckbox(){
	var string = '';
	var inputs = document.getElementsByTagName('input');
	for( var x = 0; x < inputs.length; x++ ){
		if(inputs[x].type == "checkbox" && inputs[x].name == 'filter'){
			if(inputs[x].checked == true){
				string += inputs[x].value + ',';
			}
		}
	}
	if (/,$/.test(string)){
		string=string.replace(/,$/,"")
	}
	$(".gsc-input").attr("value", string);
}
		
function showHideFilters(){
	$('.showHideFilter').toggle (
        function(){     
                $(".filterCollection").hide() ;
				$(this).addClass("showFilter");
				$(this).text("Show filters");
				$(".gsc-search-button").hide();
                },
        function(){     
                $(".filterCollection").show() ; 
				$(this).removeClass("showFilter");
				$(this).text("Hide filters");
				$(".gsc-search-button").show();
                }); // End toggle
	
	$('.showHideDescription').toggle (
        	function(){
			$("td.description p").hide();
			$(this).addClass("showFilter");
			$(".gs-snippet").hide();
			$(this).text("Show description");
                },
        function(){     
                	$("td.description p").show();
			$(this).removeClass("showFilter");
			$(".gs-snippet").show();
			$(this).text("Hide description");
                }); // End toggle
		$("div.regionSelectAll span.filtersSelect a.selectALL").click(function(){
			$("div.region input").attr("checked", "checked");
			serializeCheckbox();
			return false;
  		});
		$("div.regionSelectAll span.filtersSelect a.unselectALL").click(function(){
			$("div.region input").removeAttr("checked", "checked");
			serializeCheckbox();
			return false;
  		});
		
		$("div.projectSelectAll span.filtersSelect a.selectALL").click(function(){
			$("div.projectInput input").attr("checked", "checked");
			$("ul.projectTypeTabbed input").attr("checked", "checked");
			serializeCheckbox();
			return false;
  		});
		$("div.projectSelectAll span.filtersSelect a.unselectALL").click(function(){
			$("div.projectInput input").removeAttr("checked", "checked");
			$("ul.projectTypeTabbed input").removeAttr("checked", "checked");
			serializeCheckbox();
			return false;
  		});

		$("div.ruralInput span.filtersSelect a.selectALL").click(function(){
			$("div.urbanRuralSelectAll input").attr("checked", "checked");
			serializeCheckbox();
			return false;
  		});
		$("div.ruralInput span.filtersSelect a.unselectALL").click(function(){
			$("div.urbanRuralSelectAll input").removeAttr("checked", "checked");
			serializeCheckbox();
			return false;
  		});

		$("a#projectTypeSelectAll").click(function(){
			$(".projectTypeTabbed input").attr("checked", "checked");
			$(".projectTypeFilter input").attr("checked", "checked");
			serializeCheckbox();
			return false;
		});
		$("a#projectTypeUnSelectAll").click(function(){
			$(".projectTypeTabbed input").removeAttr("checked", "checked");
			$(".projectTypeFilter input").removeAttr("checked", "checked");
			serializeCheckbox();
			return false;
		});
	 $("div.filterCollection input").click(function(){
			serializeCheckbox();
	});
	$("#England").click(function(){
		$("#London").attr("checked","checked");
		$("#YourshireHumber").attr("checked","checked");
		$("#NorthEast").attr("checked","checked");
		$("#SouthWest").attr("checked","checked");
		$("#WestMidlands").attr("checked","checked");
		$("#EastEngland").attr("checked","checked");
		$("#SouthEast").attr("checked","checked");
		$("#EastMidlands").attr("checked","checked");
		$("#Northwest").attr("checked","checked");
		$("#YorkshireHumber").attr("checked","checked");
	});
	
	/* ----------------- Tabs Search starts here ----------------------- */
		$(".projectTypeTabbed li").removeClass("selected");
		$(".projectTypeTabbed li:first").addClass("selected");
		$("li.domestic").click(function(){
			$(".projectTypeFilter ul").hide();
			$(".projectTypeFilter ul#DomesticFilters").show();
			$(".projectTypeTabbed li").removeClass("selected");
			$(this).addClass("selected");
		});
		$("li.NonDomestic").click(function(){
			$(".projectTypeFilter ul#NonDomesticFilters").show();
			$(".projectTypeTabbed li").removeClass("selected");
			$(this).addClass("selected");
		});
		$("li.transport").click(function(){
			$(".projectTypeFilter ul#TransportFilters").show();
			$(".projectTypeTabbed li").removeClass("selected");
			$(this).addClass("selected");
		});
		$("li.Community").click(function(){
			$(".projectTypeFilter ul#CommunityFilters").show();
			$(".projectTypeTabbed li").removeClass("selected");
			$(this).addClass("selected");
		});
		$("li.Strategy").click(function(){
			$(".projectTypeFilter ul").hide();
			$(".projectTypeFilter ul#StrategyFilters").show();
			$(".projectTypeTabbed li").removeClass("selected");
			$(this).addClass("selected");
		});
	/* ----------------- Tabs Search ends here ----------------------- */
	
	/* All select Domestic starts here */
	var countDomestic = 0;
	var statusDomestic = $("li.domestic input").attr("checked");
	$("li.domestic input").click(function(){
		if(statusDomestic==false)
		{
			$("ul#DomesticFilters input").attr("checked","checked");
		}
		if(statusDomestic==true)
		{
			$("ul#DomesticFilters input").removeAttr("checked","checked");
		}
		if(statusDomestic == false)
		{
			statusDomestic = true;
		}
		else
		{
			statusDomestic = false;
		}
	});
	/* All select Domestic ends here */

	/* All select Non-Domestic starts here */
	var countNonDomestic = 0;
	var statusNonDomestic = $("li.NonDomestic input").attr("checked");
	$("li.NonDomestic input").click(function(){
		if(statusNonDomestic==false)
		{
			$("ul#NonDomesticFilters input").attr("checked","checked");
		}
		if(statusNonDomestic==true)
		{
			$("ul#NonDomesticFilters input").removeAttr("checked","checked");
		}
		if(statusNonDomestic == false)
		{
			statusNonDomestic = true;
		}
		else
		{
			statusNonDomestic = false;
		}
	});
	/* All select Non-Domestic ends here */
	
	/* All select Transport starts here */
	var countTransport = 0;
	var statusTransport = $("li.transport input").attr("checked");
	$("li.transport input").click(function(){
		if(statusTransport==false)
		{
			$("ul#TransportFilters input").attr("checked","checked");
		}
		if(statusTransport==true)
		{
			$("ul#TransportFilters input").removeAttr("checked","checked");
		}
		if(statusTransport == false)
		{
			statusTransport = true;
		}
		else
		{
			statusTransport = false;
		}
	});
	/* All select Transport ends here */
	
	/* All select Community starts here */
	var countCommunity = 0;
	var statusCommunity = $("li.Community input").attr("checked");
	$("li.Community input").click(function(){
		if(statusCommunity==false)
		{
			$("ul#CommunityFilters input").attr("checked","checked");
		}
		if(statusCommunity==true)
		{
			$("ul#CommunityFilters input").removeAttr("checked","checked");
		}
		if(statusCommunity == false)
		{
			statusCommunity = true;
		}
		else
		{
			statusCommunity = false;
		}
	});
	/* All select Community ends here */
	
	/* All select Strategy starts here */
	var countStrategy = 0;
	var statusStrategy = $("li.Strategy input").attr("checked");
	$("li.Strategy input").click(function(){
		if(statusStrategy==true)
		{
			$("ul#StrategyFilters input").attr("checked","checked");
		}
		if(statusStrategy==false)
		{
			$("ul#StrategyFilters input").removeAttr("checked","checked");
		}
		if(statusStrategy == true)
		{
			statusStrategy = false;
		}
		else
		{
			statusStrategy = true;
		}
	});
	/* All select Strategy ends here */

}





/* -------------------------------------------------------------------------------------------------------------
	Search form script ends here 
---------------------------------------------------------------------------------------------------------------*/

/* ----------------------------- Upload case study specific JS starts here ----------------------------- */

function uploadCaseStudy(){

/* To create first box starts here */

	$("div.casestudytitle").wrap("<div class='local-auth-box-bottom1'>");
	$("div.projectregion").appendTo("div.local-auth-box-bottom1");
	$("div.project_type1").appendTo("div.local-auth-box-bottom1");
	$("div.project_type2").appendTo("div.local-auth-box-bottom1");
	$("div.project_type3").appendTo("div.local-auth-box-bottom1");
	$("div.projectbudget").appendTo("div.local-auth-box-bottom1");
	$("div.geographicalscale").appendTo("div.local-auth-box-bottom1");
	$("div.urbanrural").appendTo("div.local-auth-box-bottom1");
	$("div.annualcarbonsavings").appendTo("div.local-auth-box-bottom1");
	$("div.datasource").appendTo("div.local-auth-box-bottom1");
	$("<img src='/extension/redesign_est/design/est/images/redesign/customForm/img_duckIcon.jpg' class='boxImage' alt='' />").appendTo("div.local-auth-box-bottom1");
	$("div.local-auth-box-bottom1").wrap("<div class='local-auth-box-top'>");
	$("div.local-auth-box-top").wrap("<div class='local-auth-box'>");

/* To create first box ends here */

/* To create second box starts here */

	$("div.mainimage").wrap("<div class='local-auth-box-bottom2'>");
	//$("div.summary").appendTo("div.local-auth-box-bottom2");
	//$("div.projectdescription").appendTo("div.local-auth-box-bottom2");
	$("div.local-auth-box-bottom2").wrap("<div class='local-auth-box-top'>");
	$("div.local-auth-box-top").wrap("<div class='local-auth-box local-auth-box-top2'>");

/* To create second box ends here */

/* To create third box starts here */

	$("div.document1").wrap("<div class='local-auth-box-bottom3'>");
	$("div.document2").appendTo("div.local-auth-box-bottom3");
	$("div.document3").appendTo("div.local-auth-box-bottom3");
	$("div.document4").appendTo("div.local-auth-box-bottom3");
	$("div.document5").appendTo("div.local-auth-box-bottom3");
	$("div.name").appendTo("div.local-auth-box-bottom3");
	$("div.email").appendTo("div.local-auth-box-bottom3");
	$("div.orgainsation").appendTo("div.local-auth-box-bottom3");
	$("div.telephone").appendTo("div.local-auth-box-bottom3");
	$("div.show_information").appendTo("div.local-auth-box-bottom3");
	//$("<img src='/extension/redesign_est/design/est/images/redesign/customForm/img_daveIcon.jpg' class='boxImage' alt='' />").appendTo("div.local-auth-box-bottom3");
	$("div.local-auth-box-bottom3").wrap("<div class='local-auth-box-top'>");
	$("div.local-auth-box-top").wrap("<div class='local-auth-box'>");

/* To create third box ends here */

$("div.local-auth-box-top2:last").attr("style", "position:relative; top:10px;")
$("div.summary").addClass("summaryUI");
$("div.projectdescription").addClass("projectdescriptionUI");
$("div.local-auth-box:last").addClass("local-auth-box-last");

/* For Project type starts here */

	for(k=2; k<=3; k++){
		$(".project_type"+k).addClass("hide");
	}

	for(i=0; i<3; i++){
		$(".project_type"+i).append("<a class='document1Link'>Add another project type</a>");
	}
	$(".document1Link").click(function(){
		$(this).hide();
		$(this).parent(".block").next(".block").fadeIn();
	});

	$(".project_type3").append("<p class='maxReached'>You have reached the maximum project types you can add</p>");

/* For Project type ends here*/

/* For main image starts here */
	var blockParagraph = $("div.mainimage div.block p").text();
	if(blockParagraph == "There is no image file."){
		$("div.mainimage div.block:first").hide();
		$("div.mainimage div.block:last").hide();
	}
	$("div.mainimage label").text("Main Image");
	$("div.mainimage label:first").hide();

/* For main image ends here */


/* For document upload starts here */

	for(k=2; k<=5; k++){
		$(".document"+k).addClass("hide");
	}
	$("div.block p").each(function(i){
		if($(this).text() == "There is no file."){
			$(this).parent("div.block").remove();
		}
	});
	for(z=1; z<=5; z++){
		$(".document"+z).children("label:first").hide();
		$(".document"+z+ ".block:first label").text($(".document"+z).children("fieldset").children("legend").text());
		$(".document"+z+" .block:last").append("<p class='maxInformative'>Maximum file size in 10MB. acceptable formats .doc, .pdf, .xls, .jpeg, .gif, .png.</p>");
	}
	for(i=0; i<5; i++){
		$(".document"+i+" .block:last").append("<a class='document1Link'>Add another document</a>");
	}
	$(".document1Link").click(function(){
		$(this).hide();
		$(this).parents(".block").next(".block").fadeIn();
	});

/* For document upload ends here */

/* For informative text starts here */

	$(".project_type1 label:first").append("<span class='selectThree'>Select up to three</span>");
	$(".document5").append("<p class='maxReached'>You have reached the maximum number of files you can upload</p>");
	$("<div class='informativeHeading'><label>Supporting document</label><span>(maximum 5 document)</span></div>").prependTo("div.document1");
	$("<div class='informativeHeading contactInfo'><label>Contact Information</label></div>").prependTo("div.name");
	$("<span class='boxNumber'>1</span>").prependTo("div.casestudytitle");
	$("<span class='boxNumber'>2</span>").prependTo("div.mainimage");
	$("<span class='boxNumber'>3</span>").prependTo("div.document1");
	$(".buttonblock .defaultbutton").attr("value", " ");
	$("<span class='tonnes'>tonnes</span>").appendTo("div.annualcarbonsavings");
	$(".datasource label:first").append("<span class='summaryUIInformative dataSourceInformative'>Please provide a short explanation of the methodology you used to arrive at the carbon savings given above.</span>");
	$("<div class='informativeHeading contactInfo'><label>You must have the rights to the image prior to uploading</label><span>Maximum file size 1MB. Formats: .jpg, .gif, .png</span></div>").appendTo("div.mainimage");
	$(".summaryUI label:first").append("<span class='summaryUIInformative'>The summary is visible by everyone</span>");
	$(".projectdescriptionUI label:first").append("<span class='summaryUIInformative'>Only visible by logged in users</span>");
	$(".tooltiplink img").attr("src", "/extension/redesign_est/design/est/images/redesign/customForm/img_question_tool.jpg");
	$("#uploadCaseStudy div.tooltip:first").addClass("tooltip1");
	$("#uploadCaseStudy div.tooltip:last").addClass("tooltip2");
	$("<h2>About Summary</h2>").prependTo("#uploadCaseStudy div.tooltip:first");
	$("<h2>About Project description</h2>").prependTo("#uploadCaseStudy div.tooltip:last");
	$("<div class='bottomShadow'></div>").appendTo("#uploadCaseStudy div.tooltip");
	$("<span class='close'></span>").appendTo("#uploadCaseStudy div.tooltip h2");
	$("#uploadCaseStudy .required").text("*");
	$(".tooltiplink:first img").mouseover(function(){
		$("div.tooltip1").addClass("showToolTip");
	});
	$(".tooltiplink:last img").mouseover(function(){
		$("div.tooltip2").addClass("showToolTip");
	});

	$(".tooltip h2 span.close").click(function(){
		$(this).parent("h2").parent(".tooltip").removeClass("showToolTip");
	});
	$("<div class='informative'><img class='questionInformative' alt='?' src='/extension/redesign_business/design/business/images/redesign/localAuthority/img_question_tool.jpg'/><div class='toolTipRegistrationMiddle'><div class='toolTipRegistrationTop'><div class='toolTipRegistrationBottom'><h2>About Summary</h2><img class='closeInformative' alt='?' src='/extension/redesign_business/design/business/images/redesign/localAuthority/img_CloseButton.gif'/>" + $("#summary_tool_tip").html() +"</div></div></div></div>").appendTo(".summaryUI label:first");

	$("<div class='informative'><img class='questionInformative' alt='?' src='/extension/redesign_business/design/business/images/redesign/localAuthority/img_question_tool.jpg'/><div class='toolTipRegistrationMiddle'><div class='toolTipRegistrationTop'><div class='toolTipRegistrationBottom'><h2>About Project Description</h2><img class='closeInformative' alt='?' src='/extension/redesign_business/design/business/images/redesign/localAuthority/img_CloseButton.gif'/>" + $("#project_description_tool_tip").html()  +"</div></div></div></div>").appendTo(".projectdescriptionUI label:first");
	
	$(".toolTipRegistrationMiddle").hide();

	$(".questionInformative").mouseover(function(){
		$(this).next(".toolTipRegistrationMiddle").show();
	});
	$(".closeInformative").click(function(){
		$(this).parents(".toolTipRegistrationMiddle").hide();
	});

/* For informative text ends here */


}


/* ----------------------------- Upload case study specific JS ends here ----------------------------- */





function getCookie(c_name)
{
if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{ 
		    c_start=c_start + c_name.length+1 ;
		    c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length
	    return unescape(document.cookie.substring(c_start,c_end));
    	} 
  }
	return ""
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
var cookies = document.cookie.split(";");
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : "; expires="+exdate.toGMTString()) + ";path=/";
}

function checkCookie()
{
fontZoom=getCookie('fontZoom');
if (fontZoom!=null && fontZoom!="")
  {
	if(fontZoom == 110)
	  {
		$("#outerContainer").css("font-size","110%");
		$("a.style11").removeClass("selected");
		$("a.style14").addClass("selected");
		$("a.style17").removeClass("selected");
		$(".leftContent .topStory .topStoryContainer").height(225);
		$(".leftContent .teaserSection li div.teaserContent").attr("style", "top:-3px; height:145px;");
		if($("ul.channels li:first a").attr("class")=="selected"){
			$("ul.topShortcutLinks").attr("style","width:515px; margin-top:0px;");
		}
		else{
			$("ul.topShortcutLinks").removeAttr("style");
		}
	  }
	if(fontZoom == 120)
	  {
		$("#outerContainer").css("font-size","120%");
		$("a.style11").removeClass("selected");
		$("a.style14").removeClass("selected");
		$("a.style17").addClass("selected");
		$(".leftContent .topStory .topStoryContainer").height(285);
		$(".leftContent .teaserSection li div.teaserContent").attr("style", "top:-3px; height:165px;");
		if($("ul.channels li:first a").attr("class")=="selected"){
			$("ul.topShortcutLinks").attr("style","margin-left:-15px; width:545px; margin-top:0px;");
		}
		else{
			$("ul.topShortcutLinks").attr("style","margin-left:-15px;");
		}
	  }

  }
else 
  {
    setCookie('fontZoom',100,365); 
  }
} 

function siteMapScotland(){
	var valueFirstLi = $("ul.breadcrumb li.first").text();
	var valueLastLi = $("ul.breadcrumb li:last").text();
	var trimmedvalueFirstLi = $.trim(valueFirstLi);
	var trimmedvalueLastLi = $.trim(valueLastLi);
	if(trimmedvalueFirstLi == "You are here (Scotland)" && trimmedvalueLastLi == "Sitemap"){
		$("body").attr("class", "estHome Sitemap");
	}

}

function textEnlarger(){
	$("a.style11").addClass("selected");
	$("a.style11").click(function(){
		$("#outerContainer").css("font-size","100%");
		$("a.style11").addClass("selected");
		$("a.style14").removeClass("selected");
		$("a.style17").removeClass("selected");
		$(".leftContent .topStory .topStoryContainer").height(200);
		$(".leftContent .teaserSection li div.teaserContent").attr("style", "top:0; height:127px;");
		$("ul.topShortcutLinks").removeAttr("style");
		setCookie('fontZoom',100,365);
		return false;
	});
	$("a.style14").click(function(){
		$("#outerContainer").css("font-size","110%");
		$("a.style11").removeClass("selected");
		$("a.style14").addClass("selected");
		$("a.style17").removeClass("selected");
		$(".leftContent .topStory .topStoryContainer").height(225);
		$(".leftContent .teaserSection li div.teaserContent").attr("style", "top:-3px; height:145px;");
		if($("ul.channels li:first a").attr("class")=="selected"){
			$("ul.topShortcutLinks").attr("style","width:515px; margin-top:0px;");
		}
		else{
			$("ul.topShortcutLinks").removeAttr("style");
		}
		setCookie('fontZoom',110,365);
		return false;
	});
	$("a.style17").click(function(){
		$("#outerContainer").css("font-size","120%");
		$("a.style11").removeClass("selected");
		$("a.style14").removeClass("selected");
		$("a.style17").addClass("selected");
		$(".leftContent .topStory .topStoryContainer").height(285);
		$(".leftContent .teaserSection li div.teaserContent").attr("style", "top:-3px; height:165px;");
		if($("ul.channels li:first a").attr("class")=="selected"){
			$("ul.topShortcutLinks").attr("style","margin-left:-15px; width:545px; margin-top:0px;");
		}
		else{
			$("ul.topShortcutLinks").attr("style","margin-left:-15px;");
		}
		setCookie('fontZoom',120,365);
		return false;
	});	
}

function mpgCalculatorFixer(){
	var valueFirstLi = $("ul.breadcrumb li.first a").attr("href");
	var valueLastLi = $("ul.breadcrumb li:last").text();
	var trimmedValueLastLi = $.trim(valueLastLi);
	if(valueFirstLi == "/scotland" && trimmedValueLastLi == "MPG Calculator"){
		$("body").attr("id", "landing");
		$("body").attr("class", "estHome mpgCalculatorScotland");
	}
	var registerValueLastLi = $("ul.breadcrumb li:last").text();
	var trimmedregisterValueLastLi = $.trim(registerValueLastLi);
	if(valueFirstLi == "/scotland" && trimmedValueLastLi == "Register"){
		$("body").attr("id", "landing");
		$("body").attr("class", "estHome mpgCalculatorScotland");
	}
}

function tabbedMenu(){ 
	$(".tabbedMenu ul li:first a.tabs").addClass("selected");
	$(".tabbedMenu .tabbedContainerContent").hide();
	$(".tabbedMenu .tabbedContainerContent:first").show();
	$("a#news").click(function(){
		$(".tabbedMenu ul li a.tabs").removeClass("selected");
		$(this).addClass("selected");
		$(".tabbedMenu .tabbedContainerContent").hide();
		$(".tabbedMenu #newsContainer").show();
	});
	$("a#features").click(function(){
		$(".tabbedMenu ul li a.tabs").removeClass("selected");
		$(this).addClass("selected");
		$(".tabbedMenu .tabbedContainerContent").hide();
		$(".tabbedMenu #featureContainer").show();
	});
	$("a#faq").click(function(){
		$(".tabbedMenu ul li a.tabs").removeClass("selected");
		$(this).addClass("selected");
		$(".tabbedMenu .tabbedContainerContent").hide();
		$(".tabbedMenu #faqContainer").show();
	});
}

function footerWidthCalculator(){
	var totalSectionCount = $(".footerSection div").length;
	var widthCounter = (900/totalSectionCount)-20;
	$(".footerSection div").width(widthCounter);
	$(".sectionArticle table.striped:last").attr("style", "border-bottom:none;");
	$("div.topStory div.whatSaving ul:last").attr("style", "border:none");
}

function pageselectCallback(page_index, jq){
	var new_content = $('#hiddenresult table:eq('+page_index+')').clone();
	$('#Searchresult').empty().append(new_content);
	return false; 
}

function lastPaddingRemover(){
	$("ul.teaserSection").children("li:last").addClass("last");
	$("div.relatedArticle ul").children("li:last").addClass("last");
	$(".helpAdvice a:first").attr("style", "padding:0; margin:0;");
	$(".whatSaving a:first").attr("style", "padding:0; margin:0;");
	$(".caseStudies li:first").attr("style", "padding-top:0;");
	$(".caseStudies li:last").attr("style", "padding-bottom:0; border-bottom:none;");
	var lengthLi = $(".leftContent .caseStudies li").length;
	if(lengthLi  > 1){
		if(jQuery.browser.version == "6.0"){
			$(".leftContent .caseStudies li:last img").attr("style", "top:-5px;");
		}
	}
}

function topStoryBackground(){
	if($(".topStory .whatSaving").width() == "211"){
		$("#landing .leftContent .topStory").attr("style", "background:transparent url(../images/redesign/img_greenDotted.gif) repeat-x scroll left bottom;")
	}
}

function leftNavInserter(){
	var ulLeftNavigationValue = $.trim($("ul.leftNavigation").html());
	var currentPageName = $.trim($("ul.breadcrumb li:last").text());
	if(ulLeftNavigationValue == ""){
		$("ul.leftNavigation").html("<li class='selectedNav'><a href='#' onclick='return false;' class='currentSelected'>" + currentPageName + "</a></li>");
	}
	$("ul.leftNavigation li a").click(function(){
		var caluclatorText = $.trim($(this).text());
		if(caluclatorText == "Life time value calculator"){
			$(this).attr("href", "/esr/Energy-Saving-Recommended/Independent-retailers/Life-time-value-calculator/");	
		}
	});
}

function rateThisPageOver(){ 
	$("#fRadio1opt1").mouseover(function(){
		$("div#counter span.textCounter").text("1");
	});
	$("#fRadio1opt2").mouseover(function(){
		$("div#counter span.textCounter").text("2");
	});
	$("#fRadio1opt3").mouseover(function(){
		$("div#counter span.textCounter").text("3");
	});
	$("#fRadio1opt4").mouseover(function(){
		$("div#counter span.textCounter").text("4");
	});
	$("#fRadio1opt5").mouseover(function(){
		$("div#counter span.textCounter").text("5");
	});
}

function heightSetter(){
	var height = new Array();
		height[0]=$(".videoModule").height();
		height[1]=$(".caseStudiesContainer").height();
		checkHeight=height[0];
		for(i=1;i<2;i++)
		{
		  if(height[i]>checkHeight)
		  {
			 checkHeight=height[i];
		  }  
		}  
		$(".videoModule").height(checkHeight);
		$(".caseStudiesContainer").height(checkHeight);
}

function rightModuleBorder(){
	$(".rightContent .rightSection:last").addClass("rightSectionLast");
}


$(document).ready(function(){

	/* GU function calls */
	//setupUserLoggedIn();
	initialisePrintPage();
	initialiseBookmarkPage();
	stripeTables();
	stripes(".search-results table:even");
	stripes(".search-results li:even");
	//toggleForms('#details', 'div.buttons a.button', 'form', '#resultsList');
	toggleElements('#resultsList li a');
	showHideElements('a.helpIconActivator', 'div.help-icon-text');
	externalWindow("a[rel='external']");
	submitNewsForm();
	try {
	document.execCommand("BackgroundImageCache", false, true);
	} catch(err) {} // remove background image flicker in IE6 with caching off.
	hrefTheContainer("#home .block","p.arrow a");
	hrefTheContainer(".top-level .block","p.arrow a");
	/* XROW function calls */
	createRateForm("#fRateX", "#fRateXRadio", "#fRateX fieldset.submit", "fRateXAvg", "#fRadio1opt")
	/* initialiseRate();*/
	initialiseNews();
	initialisePoll();
	initialisePostCode();
	initialisePostCodeMPG();
	initialiseRegister();
	initialiseEmmission();

	$('.expand-section').hide();
	$('.toggle-contents a').click(function () {
		$(this).parent().siblings("div").toggle();
		$(this).parent().siblings("ul").toggle();
		$(this).toggleClass("contract");
		return false;
	});
		/* opens pop up window for checklist page */
$('.helpPopup').bind('click', function(ev) {
	 HelpWindow = window.open(this.href,'help','top=300,left=50,height=250,width=400,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no');
	 HelpWindow.focus();
	 return false;
});

/* checklist page toggle and switching results */


    $(".trigger").each(function() {
           
        if(document.getElementById($(this).attr('id') + "-checker").checked == true)
        {
            var id = $(this).attr('id'); // == insulation
            var willSave  = $('#willSave');
            var willSavekg  = $('#willSavekg');
            var reduction = $('#' + id + '-reduction'); // == #insulation-reduction
            var reductionkg = $('#' + id + '-reductionkg'); // == #insulation-reductionkg
            willSave.html(Number(willSave.text()) + Number(reduction.text()));
			willSavekg.html(Number(willSavekg.text()) + Number(reductionkg.text()));
			$(this).removeClass("tick");
			$(this).addClass("undo");
            $(this).html('Undo this');
        }
        else
        {
            $(this).addClass("tick");
            $(this).removeClass("undo");
            $(this).html('I have done this');
        }
        
        $(this).click(function() 
        {
           var id = $(this).attr('id'); // == insulation
           var willSave  = $('#willSave');
           var willSavekg  = $('#willSavekg');
           var reduction = $('#' + id + '-reduction'); // == #insulation-reduction
           var reductionkg = $('#' + id + '-reductionkg'); // == #insulation-reductionkg
           var checkbox = $('#' + id + '-checker'); // == #insulation-reductionkg
	       if(document.getElementById($(this).attr('id') + "-checker").checked == false)
           {
				document.getElementById($(this).attr('id') + "-checker").checked=true;
                willSave.html(Number($('#willSave').text()) + Number(reduction.text()));
				willSavekg.html(Number(willSavekg.text()) + Number(reductionkg.text()));
				$(this).html('Undo this');
				$(this).removeClass("tick");
				$(this).addClass("undo");
           }
           else
           {
                document.getElementById($(this).attr('id') + "-checker").checked=false;
                willSave.html(Number(willSave.text()) - Number(reduction.text()));
                willSavekg.html(Number(willSavekg.text()) - Number(reductionkg.text()));
                $(this).html('I have done this');
                $(this).removeClass("undo");
				$(this).addClass("tick");
           }
	       
	       return false;
       });
    });
  

	/*
	$('.expand-section').hide();
	$('#your-action-plan').toggle();
	//$('#insulation').toggle();
	$('a.expand').click(function () {
		$(this).parent().siblings("div").toggle();
		$(this).parent().siblings("ul").toggle();
		//$(this).toggleClass("contract");
		//$(this).removeClass("expand").addClass("contract");
		//$(this).attr("class").replace("expand","contract"));
		
		//$(this).addClass("contract");
		//$(this).removeClass("expand");
		
		alert($(this).attr("class"));
		return false;
	});
	$('a.contract').click(function () {
		$(this).parent().siblings("ul").toggle();
		//$(this).toggleClass("expand");
		//$(this).removeClass("contract").addClass("expand");
		//$(this).attr("class").replace("contract","expand"));  
		
		//$(this).addClass("expand");
		//$(this).removeClass("contract");
		
		//if ($(this).hasClass("contract")) {alert("!!");  }
		alert($(this).attr("class"));
		return false;
	});*/
	
	

});

/* GU FUNCTIONS */

/* Initialise Print Page link on RHS nav */
function initialisePrintPage() {
    if( document.getElementById("email-page") )
    {
    	$("li#email-page").after("<li id=\"print-page\"><a>" + "Print this page" + "</a></li>");
    	$("li#print-page").bind("click", function() { window.print(); });
    	/* Hack to make hovers work in IEs */
    	if (document.all) {
    		$("li#print-page a").bind("mouseover", function() { this.style.backgroundImage="url(/extension/est/design/est/images/navigation/tools_page-tools_ul_li_print-page_hover_bg.gif)";this.style.cursor="hand"; });
    		$("li#print-page a").bind("mouseout", function() { this.style.backgroundImage="url(/extension/est/design/est/images/navigation/tools_page-tools_ul_li_print-page_bg.gif)"; });
    	}
    }
}

/* Initialise Print Page link on RHS nav */
function initialiseBookmarkPage() {
		$("#tools li#print-page").after("<li id=\"bookmark-page\"><a>" + "Bookmark this page" + "</a></li>");
		$("li#bookmark-page").bind("click", function() { 
			title = document.title; 
			url = document.URL;
			if (window.sidebar) { // Mozilla Firefox Bookmark
				window.sidebar.addPanel(title, url,"");
			}
			else if( window.external ) { // IE Favorite
				window.external.AddFavorite( url, title); 
			}
			else if(window.opera && window.print) { // Opera Hotlist
				return true; 
			}
		});
		if (document.all) {
			$("li#bookmark-page a").bind("mouseover", function() { this.style.backgroundImage="url(/extension/est/design/est/images/navigation/tools_page-tools_ul_li_bookmark-page_hover_bg.gif)";this.style.cursor="hand"; });
			$("li#bookmark-page a").bind("mouseout", function() { this.style.backgroundImage="url(/extension/est/design/est/images/navigation/tools_page-tools_ul_li_bookmark-page_bg.gif)"; });
		}	
}

/* Zebra rows in tables */
function stripeTables() {
	if (document.getElementById("efficientProductsForm")) return false;
	$(".striped tr").mouseover(function() {
		$(this).addClass("over");}).mouseout(function() {$(this).removeClass("over");
	});
	// $(".striped tr:even").addClass("alt");
}

/* Zebra tables in results */
function stripes(theElement) {
	if (document.getElementById("efficientProductsForm")) return false;
	$(theElement).addClass("odd");	
}

/*
toggleForms: 

A click on an 'activator' element in a 'parentElementType' element (.e.g 'a.button' in a 'div'), reveals another element ('elementHiddenFirst') on the page (which has been hidden when the function is called, e.g. onload) and hides its parent 'parentElementType', and any other element 'hideThis'.
           
 */

function getTheLink(theElement){
	targetElementHref = $(theElement).attr("href");
	targetElement = targetElementHref.substring(targetElementHref.lastIndexOf("#"));
	return targetElement;
}

function toggleForms(elementHiddenFirst, activator, parentElementType, hideThis) {
	if($(activator).is(1)){ // If the activator is on the page
		$(elementHiddenFirst).toggle();
	}
    $(activator).click(function() {
		otherElement = getTheLink(this);
		thisElement = $(this).parents(parentElementType);
		$(otherElement).slideDown("slow");
		$(thisElement).slideUp("slow");
		if (otherElement == elementHiddenFirst) {
            $(hideThis).hide("slow");
         } else {
            $(hideThis).show("slow");
         }
		return false;
    });
}

function toggleElements(theElement){
	$(theElement).click(function() {	
		targetElement = getTheLink(this); 
		theform = $(targetElement).parent();	
		$(targetElement).fadeIn("fast");
		(theform.children('fieldset.search-results').not(targetElement)).fadeOut("fast");	
		return false;
    });
}



function showHideElements(theElement, targetElements){
	$(theElement).each(function(){
		targetElement = getTheLink(this); 
		$(targetElement).hide();
	});

	$(theElement).click(function() {	
		targetElement = getTheLink(this); 
		theParent = $(targetElement).parent();	
		$(targetElement).toggle("slow");
		$(theParent.children(targetElements).not(targetElement)).each(function(){
			if(this.style.display == 'block'){
				$(this).hide("slow");
			}
		});
		return false;
    });
}

/* Take the value from the label preceding the input box and put that value in the input box. 
	When you focus the input box, this text disappears.
	When you lose focus it comes back, if there's been no change.
*/

function labelInput(theSearchBox){
	var labelText = $("label[@for='" + theSearchBox + "']").text()
	document.getElementById(theSearchBox).value = labelText;
	document.getElementById(theSearchBox).onfocus = function(){ this.value = "" };
	document.getElementById(theSearchBox).onblur = function(){ 
		if(this.value == ""){
			this.value = labelText;
		} 
	};
}

/* Apply the href of an anchor in a container to that whole container */

function hrefTheContainer(theContainer, theLink){
	if (document.getElementById("efficientProductsForm")) return false;
	$(theContainer + " " + theLink).each( function(i){
		var destination = $(this).attr("href");
		$(this).parent().parent().click( function(){ document.location.href = destination; } );
		$(this).parent().parent().mouseover( function(){ 
			this.style.cursor="hand";
			this.style.cursor="pointer"; 
			window.status = destination;
		});
	});
}

/* XROW FUNCTIONS */

/* Initialise Xajax submit button for RegisterYourInterest */
function initialiseRegister() {
	
	$("input#registerForUpdates").bind("click", function() { 
		/* call xajax function from ez extension est */
		xajax_performRegister(xajax.getFormValues('fRegisterX'));
		
		return false;
	});
}
/* Initialise Xajax submit button for Addressfinder */
function initialisePostCode(){
	
	$("input#AddressFinder").bind("click", function() { 
		/* call xajax function from ez extension est */
		var post1=(document.getElementById("postoutcode").value).replace(/^\s*|\s*$/g,'');
		var post2=(document.getElementById("postincode").value).replace(/^\s*|\s*$/g,'');
		var postcode=post1 + " " + post2;
		xajax_performPostCode( postcode );
		return false;
	});
}

function initialisePostCodeMPG(){
	$("input#AddressFinder_mpg").bind("click", function() { 
		/* call xajax function from ez extension est */
		var post1=(document.getElementById("postoutcode").value).replace(/^\s*|\s*$/g,'');
		var post2=(document.getElementById("postincode").value).replace(/^\s*|\s*$/g,'');
		var postcode=post1 + " " + post2;
		xajax_performPostCodeMPG( postcode );
		return false;
	});
}


/* Initialise Xajax submit button for Poll */
function initialisePoll() {
	
	$("input#pollSubmit").bind("click", function() { 
		/* call xajax function from ez extension est_xajax_poll */
		xajax_performVote(xajax.getFormValues('fPollX'));
		return false;
	});
}

/* Initialise Xajax submit button for Rate */
function initialiseRate() {
	
    for( var i = 1 ; i <= 5 ; i++){
	$("input#Submitrate" + i ).bind("click", function() { 
		/* call xajax function from ez extension est_xajax_poll */
		document.fRateX.Ratevalue.value=this.value;
		xajax_performRate(xajax.getFormValues('fRateX'));
		return false;
	});
    }
}

/* Initialise Xajax submit button for Poll */
function initialiseEmmission() {
	
	$("input#emmissionSubmit").bind("click", function() { 
		/* call xajax function from ez extension est_xajax_poll */
		xajax_performEmmission(xajax.getFormValues('fEmmissionX'));
		return false;
	});
}

function popup(theElement){
	$(theElement).click(function() {
		var theWidth = 500;
		if(this.className.indexOf('wide') != -1) { theWidth = 1024; } 
		window.open(this.href, "", "top=40,left=40,width=" + theWidth + ",height=625,scrollbars=yes");
		return false;
    });
}

function externalWindow(theElement){
	$(theElement).click(function() {
		window.open(this.href);
		return false;
    });
}

function submitNewsForm(){
	$("#newsForm input.submit").bind("click", function(){
		document.location.href='/resources/daily_news' + '/(fromday)/' + document.forms.newsForm.elements.fromDay.value + '/(frommonth)/' +  document.forms.newsForm.elements.fromMonth.value + '/(fromyear)/' + document.forms.newsForm.elements.fromYear.value + '/(today)/' + document.forms.newsForm.elements.toDay.value + '/(tomonth)/' + document.forms.newsForm.elements.toMonth.value + '/(toyear)/' + document.forms.newsForm.elements.toYear.value + '/';
	});
}

function hideAndReveal( id )
{
	var state = document.getElementById(id).style.display;
	if( state != "none")
	{
		document.getElementById(id).style.display = 'none';
	}
	else
	{
		document.getElementById(id).style.display = 'block';
	}
}


/* 
NEW RATE THIS PAGE FUNCTION
*/


function getPost(formId) {
     return function() {
         switch(formId){
			case "#fPollX":
				for (var i=0; i < document.fPollX.fRadio3opt.length; i++) {
					if (document.fPollX.fRadio3opt[i].checked){
						var radioValue = document.fPollX.fRadio3opt[i].value;
					}
				}
				if(radioValue){	
					$("div#poll").load("poll-results.php?fPollValue=" + radioValue).fadeIn("slow");
				}
				return false;
			break;
			case "#fEmissions":
				var theSelect = document.getElementById("fEmissionsCounty");
				var selectValue = theSelect.options[theSelect.selectedIndex].value;
				if(selectValue > 0){	
					$("div#local-emissions").load("results.php?fEmissionsValue=" + selectValue).fadeIn("slow");
				}
				return false;
			break;
			case "#fRateX":
					$(formId).fadeOut("slow");
					/*$("li#rate-page div#rate-page-tool").load("clicked-state.php?fRateRadio=" + this.value).fadeIn("slow");*/
					document.fRateX.Ratevalue.value=this.value;
	                xajax_performRate(xajax.getFormValues('fRateX'));
	                /*$(formId).fadeIn("slow"); */
					/*$("li#rate-page div#rate-page-tool").load("" + this.value).fadeIn("slow");*/
					this.focus();
				return false;
			break;
			default:
				return false;
			}	
     };
}

function initialiseForm(formId) {
     $(formId).bind('submit', getPost(formId));
}

function createRateForm(formId, radioGroupId, hideThis, avgRating, optionId){
	theRate = new Array();
	theRate[1] = 'Bad';
	theRate[2] = 'Poor';
	theRate[3] = 'OK';
	theRate[4] = 'Good';
	theRate[5] = 'Great';
	
	$(hideThis).hide();
	
	if(document.getElementById(avgRating)){
		var avgRating = document.getElementById(avgRating).firstChild.nodeValue;
	}
	
	$(radioGroupId + " input").each(function(i){
		i=i+1;
		
		var imageStatus;
		i <= avgRating ? imageStatus = "on" : imageStatus = "off";
		
		// create image input elements ('on' up to the average so far)
		var imageButton = document.createElement('input');
		$(imageButton).attr({ 
			type: "image",	
			src: "/extension/redesign_est/design/est/images/redesign/" + i + "_" + imageStatus + ".gif", 
			alt: "Rating: " + i + " - " + theRate[i],
			title: "Rating: " + i + " - " + theRate[i],
			name: this.name,
			id: this.id,
			value: this.value
		});
		
		// bind events to them (click to post, and mouseover image swaps)
		$(imageButton).bind('click', getPost(formId));

		$(imageButton).bind('mouseover', function(){
			for(var k=1; k <= i; k++){
				$(optionId + k).attr("src", "/extension/redesign_est/design/est/images/redesign/" + k + "_over.gif");
			}
		});
		
		$(imageButton).bind('mouseout', function(){
			for(var k=i; k > 0; k--){
				k <= avgRating ? localImageStatus = "on" : localImageStatus = "off";
				$(optionId + k).attr("src", "/extension/redesign_est/design/est/images/redesign/" + k + "_" + localImageStatus + ".gif");
			}
		});
		
		// swap radio buttons for images	
		$(this).after(imageButton);
		$(this).remove();
	});
}
function initialiseNews()
{			
			var animate = true;
			
			function showNextNews(first) {

				if ( animate == true && first != true ) {

					var className = 'visible';
					var items = $('#news').children('li');
					for ( var i = 0; items.length > i; i++ ) {
						var item = $(items[i]);
						if ( item.hasClass(className) ) {
							item.removeClass(className);
							if ( i == (items.length - 1) ) {
								$(items[0]).addClass(className);
							}
							else {
								$(items[i+1]).addClass(className);
							}                
							break;
						}
					}
				}
				setTimeout(showNextNews, 4000);
			}
			
			$('#news').bind('mouseover', function() {
				animate = false;

			});
			$('#news').bind('mouseout', function() {
				animate = true;

			});
			
			showNextNews(true);
}
/*function setupUserLoggedIn()
{ 
    if( YAHOO.util.Cookie.get("USER_NAME") )
    {
       if( YAHOO.util.Cookie.get("USER_ID") != "USER_ID" )
       {
          document.getElementById("login").innerHTML='Hi <a href="/calculator/edit/'+YAHOO.util.Cookie.get("USER_ID")+'">'+YAHOO.util.Cookie.get("USER_NAME")+'</a> / <a href="/calculator/logout">Sign out</a>';
       }
    }
}*/

