// JavaScript Document

$(document).ready(function() {
	textEnlarger();
	tabbedMenu();
	footerWidthCalculator();
	lastPaddingRemover();
	topStoryBackground();
	rateThisPageOver();
	rightModuleBorder();
	mpgCalculatorFixer();
	//heightSetter();
	leftNavInserter();
	//siteMapScotland();
	buttonOver();
	discussionListing();
	groupingListing();
	initPagination1();
	initPagination();
	latestMemberImage();
	blogListSocialMediaTab();
	emailPositionSetter();
	formValidSignin();
	editMode();
	captchaLabel();
	imageUploader();
	showHideRadioOptionGid();
	applicationBenefitListing();
	initPaginationPopUp();
	profileHelper();
});
function profileHelper(){
	$("#backgroundPopup").css({
			"opacity": "0.7"
	});
	$("#profileHelper").click(function(){
		$("#backgroundPopup").fadeIn();
		$("body").append('<div class="profilePercentageHelper"><div class="imageUploader"><a id="popupContactClose1" href="#">X</a><div class="block"><p class="completeProfile">Steps to complete your profile:</p><ul><li>10%: - Add a profile picture.</li><li>10%: - Add an interest.</li><li>10%: - Complete your personal information.</li><li>5%: - Use the carbon cutter application.</li><li>5%: - Use the energy check list application.</li><li>5%: - Use the microgen application.</li><li>10%: - Subscribe to another "Where I live" newsletter.</li><li>5%: - Add a comment to a discussion.</li></ul></div></div>');
		 //centering popup
			var windowWidth = document.documentElement.clientWidth;
			var windowHeight = document.documentElement.clientHeight;
			var profilePercentageHeight = $(".profilePercentageHelper").height();
			var profilePercentageWidth = $(".profilePercentageHelper").width();
			$(".profilePercentageHelper").css({
				"left": windowWidth/2-profilePercentageWidth/2-150,
				"top": windowHeight/2-profilePercentageHeight/2-200
			});
		

		$("#popupContactClose1").click(function(){
			$("#backgroundPopup").fadeOut("slow");
			$(".profilePercentageHelper").remove();
			return false;
		});
		return false;	
	});
	$(document).keypress(function(e){
		if(e.keyCode==27 && popupStatus==1){
			$("#backgroundPopup").fadeOut("slow");
			$(".profilePercentageHelper").remove();
		}
	});
	$("#backgroundPopup").click(function(){
		$("#backgroundPopup").fadeOut("slow");
		$(".profilePercentageHelper").remove();
	});
	


}

/* =============================================================================================

				**************** GID SCRIPTS STARTS HERE ****************

=============================================================================================== */

function showHideRadioOptionGid(){
	$("ul.insulation li:first").addClass("wideToolTip");
	$("ul.insulation li:first").next("li").next("li").addClass("wideToolTip thirdLi");

	$("h3 img.informativeIcon").click(function(){
		$(this).next(".toolTipHint").show();
	});
	$(".informativeIcon").click(function(){
		$(".toolTipHint").hide();
		$(this).next(".toolTipHint").show();
	});
	$("li.displayName img").click(function(){
		$(".toolTipHint").hide();
		$(this).parent("label").next(".toolTipHint").show();
	});
	
	$(".btnPrint").click(function(){
		window.print();						   
	});

	$(".option input").click(function(){
		var selectedMeasureHeading = $(this).parents(".showHideContainerGroups").children(".groupRadioOptionGid").children(".selectedOpenOptionRadioBottom").children("a.showHideOption").text();
		if(selectedMeasureHeading == "Insulation"){
			$("#measure_category").val("1");
		}
		if(selectedMeasureHeading == "Heating"){
			$("#measure_category").val("2");
		}
		if(selectedMeasureHeading == "Energy generation"){
			$("#measure_category").val("3");
		}
	});

	if($("#measure_category").val() == "Energy generation"){
		$("#energyGeneration").addClass("showGroups");
		$("#energyGeneration .groupRadioOptionGid").addClass("selectedOpenOptionRadio");
	}
	if($("#measure_category").val() == "Heating"){
		$("#headingGroup").addClass("showGroups");
		$("#headingGroup .groupRadioOptionGid").addClass("selectedOpenOptionRadio");
	}
	if($("#measure_category").val() == "Insulation"){
		$("#insulationGroup").addClass("showGroups");
		$("#insulationGroup .groupRadioOptionGid").addClass("selectedOpenOptionRadio");
	}

	$("#changeMeasure").click(function(){
		$(".popUpChangeEnergySavingMeasure").fadeIn();
		loadPopup();
		$(".closeList").click(function(){
			disablePopup();
			$(".popUpChangeEnergySavingMeasure").fadeOut();
			return false;
		});
		$("#backgroundPopup").click(function(){
			disablePopup();
			$(".popUpChangeEnergySavingMeasure").fadeOut();
		});
		$(document).keypress(function(e){
			if(e.keyCode==27 && popupStatus==1){
				disablePopup();
				$(".popUpChangeEnergySavingMeasure").fadeOut();
			}
		});	
		return false;								
	});
	$(".grantGreen").height(130);
	$(".discountBlue").height(130);
	
	
	$(".showMoreInformation").toggle(function(){
		$(this).next(".moreInformationSearchResult").show();
		$(this).parents("tr").height($(this).next(".moreInformationSearchResult").height()+150);
		$(this).parents(".grantGreen").height($(this).next(".moreInformationSearchResult").height()+135);
		$(this).parents(".discountBlue").height($(this).next(".moreInformationSearchResult").height()+135);
		$(this).addClass("hideMoreInformation");
		$(this).text("Hide information");
	}, function () {
		$(this).next(".moreInformationSearchResult").hide();
		$(this).parents("tr").height(105);
		$(this).parents(".grantGreen").height(135);
		$(this).parents(".discountBlue").height(135);
		$(this).removeClass("hideMoreInformation");
		$(this).text("Show more information");
	});
	
	$(".changeDetail").click(function(){
		$(".gettingRegisteredForm li").removeClass("readOnlyDetails");
		$(".gettingRegisteredForm li").removeClass("editableChange");
		$(".gettingRegisteredForm li.readOnlyDetails").hide();
		$(".gettingRegisteredForm li.addressReadOnlyContainer").hide();
		$(".gettingRegisteredForm li input").removeAttr("readonly");
	});
	
	
	$(".searchResultGrant tr:odd").addClass("blueBackground");
	$("p.grantCount span").text($(".searchResultGrant tr").length-1);
	
/* Show hide or energy measures starts here */
$(".insulationAnchor").click(function(){
	$(".toolTipHint").hide();
	if($("#insulationGroup").attr("class") == "showHideContainerGroups showGroups"){
		$("#insulationGroup").removeClass("showGroups");
		$("#insulationGroup .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#headingGroup").removeClass("showGroups");
		$("#headingGroup .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#energyGeneration").removeClass("showGroups");
		$("#energyGeneration .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#loftInsulationExtra").hide();
		return false;
	}else{
		$("#insulationGroup").addClass("showGroups");
		$("#insulationGroup .groupRadioOptionGid").addClass("selectedOpenOptionRadio");
		$("#headingGroup").removeClass("showGroups");
		$("#headingGroup .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#energyGeneration").removeClass("showGroups");
		$("#energyGeneration .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		if($("#Cavityandloftinsulation").attr("checked") || $("#LoftInsulation").attr("checked")){
			$("#loftInsulationExtra").show();
		}
		return false;
	}
});

$(".heatingAnchor").click(function(){
	$(".toolTipHint").hide();
	if($("#headingGroup").attr("class") == "showHideContainerGroups showGroups"){
		$("#insulationGroup").removeClass("showGroups");
		$("#insulationGroup .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#headingGroup").removeClass("showGroups");
		$("#headingGroup .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#energyGeneration").removeClass("showGroups");
		$("#energyGeneration .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#loftInsulationExtra").hide();
		return false;
	}else{
		$("#headingGroup").addClass("showGroups");
		$("#headingGroup .groupRadioOptionGid").addClass("selectedOpenOptionRadio");
		$("#insulationGroup").removeClass("showGroups");
		$("#insulationGroup .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#energyGeneration").removeClass("showGroups");
		$("#energyGeneration .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#loftInsulationExtra").hide();
		return false;
	}
});

$(".energyGenerationAnchor").click(function(){
	$(".toolTipHint").hide();
	if($("#energyGeneration ").attr("class") == "showHideContainerGroups showGroups"){
		$("#insulationGroup").removeClass("showGroups");
		$("#insulationGroup .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#headingGroup").removeClass("showGroups");
		$("#headingGroup .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#energyGeneration").removeClass("showGroups");
		$("#energyGeneration .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#loftInsulationExtra").hide();
		return false;
	}else{
		$("#energyGeneration").addClass("showGroups");
		$("#energyGeneration .groupRadioOptionGid").addClass("selectedOpenOptionRadio");
		$("#headingGroup").removeClass("showGroups");
		$("#headingGroup .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#insulationGroup").removeClass("showGroups");
		$("#insulationGroup .groupRadioOptionGid").removeClass("selectedOpenOptionRadio");
		$("#loftInsulationExtra").hide();
		return false;
	}
});

/* Show hide or energy measures ends here */

	$(".insulation input").click(function(){
		$(".optionlofInsulation").fadeOut();								   
	});
	$("#LoftInsulation1").click(function(){
		$(".optionlofInsulation").fadeIn();
		$(".optionlofInsulation").show();
	});
	$("#Cavityandloftinsulation1").click(function(){
		$(".optionlofInsulation").fadeIn();
		$(".optionlofInsulation").show();
	});
	
	$("#uploadCaseStudy li label img").click(function(){
		leftCoordinate = this.offsetLeft;
			if($.browser.msie){
				if(jQuery.browser.version == "6.0")
				{
					leftCoordinateCavity = 242;
					topCoordinateCavity = 245;
					leftCoordinate -= 65;
				}
				else
				{
					leftCoordinateCavity = 242;
					topCoordinateCavity = 238;
					leftCoordinate -= 60;
				}
			}
			if($.browser.mozilla || $.browser.safari){
				leftCoordinateCavity = 234;
				topCoordinateCavity = 236;
				leftCoordinate -= 71;
			}
		$("span.toolTipHint").hide();
		$(this).parents("li").children("span.toolTipHint").show();
		var heightHint = $(this).parents("li").children("span.toolTipHint").height();
		$(".toolTipHint").css({
			"top": -heightHint-15,
			"left":leftCoordinate
		});
		$(".cavityWallInsulation").css({
			"top" :topCoordinateCavity,
			"left":leftCoordinateCavity
		});
		return false;																   
	});
	$(document).keypress(function(e){
			if(e.keyCode==27){
			$("span.toolTipHint").hide();
		}
	});	
	$(".closeHint").click(function(){
		$(this).parents(".toolTipHint").hide();
	});
	if($(".Doyouhaveanyoneover60livinginyourhome .radioOption2ndGid input:first").attr("checked")){
		$(".Areanyofthesepeople").show();
	}

	$(".Doyouhaveanyoneover60livinginyourhome .radioOption2ndGid input:first").click(function(){
		$(".Areanyofthesepeople").fadeIn();
		$(".recieveBenefits .toolTipHint").attr("style", "top:93px !important;");
	});
	$(".Doyouhaveanyoneover60livinginyourhome .radioOption2ndGid input:last").click(function(){
		$(".Areanyofthesepeople").fadeOut();
		$(".recieveBenefits .toolTipHint").attr("style", "top:59px !important;");
	});
	//centering popup
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var applicationBenefitHeight = $(".applicationBenefit").height();
	var applicationBenefitWidth = $(".applicationBenefit").width();
	$(".applicationBenefit").css({
		"left": windowWidth/2-applicationBenefitWidth/2,
		"top": windowHeight/2-applicationBenefitHeight/2+250
	});
	//only need force for IE6
	$(".applicationBenefitOpener").click(function(){
		$(".applicationBenefit").fadeIn();
		loadPopup();
		$(".closeList").click(function(){
			disablePopup();
			$(".applicationBenefit").fadeOut();
			return false;
		});
		$("#backgroundPopup").click(function(){
			disablePopup();
			$(".applicationBenefit").fadeOut();
		});
		$(document).keypress(function(e){
			if(e.keyCode==27 && popupStatus==1){
				disablePopup();
				$(".applicationBenefit").fadeOut();
			}
		});	
		return false;
	});
	if($("#pvt_landlordYES").attr("checked")){
		$(".noteText").show();
	}

	$("#pvt_landlordYES").click(function(){
		$(".noteText").fadeIn();
	});
	$("#pvt_landlordNO").click(function(){
		$(".noteText").fadeOut();
	});
	$("#uploadCaseStudy .step2ToolForm li label img").click(function(){
		leftCoordinatequestion = this.offsetLeft;
		TopCoordinatequestion = this.offsetTop;
		totalHeightToolTip = $(this).parent("label").parent("li").children(".toolTipHint").height()+20;
		$(this).parent("label").parent("li").children(".toolTipHint").css({
			"top" :TopCoordinatequestion-totalHeightToolTip,
			"left":leftCoordinatequestion-90
		});
	});
	
	$(".Areanyofthesechildrenunder16inreceiptofdisabilitylivingallowance").hide();
	$(".Areyoualoneparentfamily").hide();
	if($("#Yes80").attr("checked")){
		$(".Areanyofthesechildrenunder16inreceiptofdisabilitylivingallowance").show();
		$(".Areyoualoneparentfamily").show();
	}
	$("#Yes80").click(function(){
		$(".Areanyofthesechildrenunder16inreceiptofdisabilitylivingallowance").fadeIn();
		$(".Areyoualoneparentfamily").fadeIn();
	});
	$("#No81").click(function(){
		$(".Areanyofthesechildrenunder16inreceiptofdisabilitylivingallowance").fadeOut();
		$(".Areyoualoneparentfamily").fadeOut();
		$("#No83").attr("checked", "checked");
		$("#No85").attr("checked", "checked");
	});
	if($("#Cavityandloftinsulation1").attr("checked")){
		$(".optionlofInsulation").show();
		$(".insulation").parents(".showHideContainerGroups").addClass("showGroups");
		$(".insulation").parents(".groupRadioOptionGid").addClass("selectedOpenOptionRadio");
	}
	if($("#LoftInsulation1").attr("checked")){
		$(".optionlofInsulation").show();
		$(".insulation").parents(".showHideContainerGroups").addClass("showGroups");
		$(".insulation").parents(".groupRadioOptionGid").addClass("selectedOpenOptionRadio");

	}
	
	$(".currentSupplier label img").click(function(){
		var toolTipHintCurrentSupplier = $(".currentSupplier span.toolTipHint").height();
		$(".currentSupplier span.toolTipHint").css({
			"margin-top": 136-toolTipHintCurrentSupplier
		});
	});

}


var popupStatus = 0;
function loadPopup(){
	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("slow");
		$("#popupContact").fadeIn("slow");
		popupStatus = 1;
	}
}
function disablePopup(){
	if(popupStatus==1){
		$("#backgroundPopup").fadeOut("slow");
		$("#popupContact").fadeOut("slow");
		popupStatus = 0;		
	}
}
function applicationBenefitListing(){
	jQuery.fn.wrapInChunks = function(html, chunkSize) {
		chunkSize = chunkSize || 1;
		var items = this.get(),
		rows = [],
		cur = rows[0] = $(html);
		while (items[0]) {
			if (rows[rows.length - 1].children().length === chunkSize) {
				cur = rows[rows.length] = $(html);
			}
			cur.append( items.shift() );
		}
		return this.pushStack(rows);
	};
	$(".applicationBenefit .popUpContent ul").each(function(i){
		$(this).children("li").wrapInChunks('<div class="applicationBenefitGroup" />', 11).appendTo(this);
	});
}
function initPaginationPopUp() {
	var num_entries = $("div.applicationBenefitGroup").length-1;
	$("#paginationPopUp").pagination(num_entries, {
		num_edge_entries: 1,
		num_display_entries: 8,
		callback: pageselectCallbackBU,
		items_per_page:1
	});
	if($(".popUpContent div.applicationBenefitGroup").length == 1){
		$("#paginationPopUp").hide();
	}
}
function pageselectCallbackBU(page_index, jq){
	$("div.applicationBenefitGroup").hide();
	var new_content = $("div.popUpContent").children("ul").children('div.applicationBenefitGroup:eq('+page_index+')').attr("style", "display:block");
	return false;
}

/* =============================================================================================

				**************** GID SCRIPTS ENDS HERE ****************

=============================================================================================== */


/* -------------------------------------------------------------------------------------------------------------
	image Uplader for myProfile starts here
---------------------------------------------------------------------------------------------------------------*/

function imageUploader(){
	$(".co2Toolbox a img.floatLeft").parent("a").attr("style","background:none; padding:0;");
	$(".imageUser div.imageUploader").hide();
	$(".imageEdit").click(function(){
		$(".imageUser div.imageUploader").fadeIn();
		loadPopup();
		//CLOSING POPUP
		//Click the x event!
		$("#popupContactClose").click(function(){
			disablePopup();
			$(".imageUser div.imageUploader").fadeOut();
			return false;
		});
		//Click out event!
		$("#backgroundPopup").click(function(){
			disablePopup();
			$(".imageUser div.imageUploader").fadeOut();
		});
		//Press Escape event!
		$(document).keypress(function(e){
			if(e.keyCode==27 && popupStatus==1){
				disablePopup();
				$(".imageUser div.imageUploader").fadeOut();
			}
		});	
		return false;
	});
	$("#tweetbox a").attr("target","_blank");
}

/* -------------------------------------------------------------------------------------------------------------
	image Uplader for myProfile ends here
---------------------------------------------------------------------------------------------------------------*/



/* -------------------------------------------------------------------------------------------------------------
	captcha script starts here 
---------------------------------------------------------------------------------------------------------------*/

function captchaLabel(){
	$("<label for='recaptcha_response_field'>Type the words</label>").prependTo(".recaptcha_input_area");
	$("#tweetbox div:last").hide();
	$("#tweetbox ol li:last").attr("style", "border-bottom:none");
}

/* -------------------------------------------------------------------------------------------------------------
	captcha script ends here 
---------------------------------------------------------------------------------------------------------------*/


/* -------------------------------------------------------------------------------------------------------------
	Accont setting script starts here 
---------------------------------------------------------------------------------------------------------------*/
function editMode(){
	if(jQuery.browser.version == "1.9.0.15"){
		$("a.showHideMyAccount").css("margin-top", "-15px");
	}

	$("a.accountSetting").click(function(){
		$(".accountSettingReadMode").hide();
		$(".accountSettingEditMode").show();
		$(".imageEdit").show();
	});
	if($("ul.interestRead li span:first").text() != ""){
		$("p.introMyInterest").hide();
		$("ul.interestRead").show();
		$(".addInterest strong").text("Change your interests »");
	}
	$(".addInterest").click(function(){
		$(".introMyInterest").hide();
		$(".interestEdit").show();
		$(".interestRead").hide();
		$(".saveChangeInterest").show();
		$(this).hide();
		return false;
	});
	$('.showHideMyAccount').toggle (
        function(){     
                $(this).parents("h2.consumerOverview").next(".atHomeAccount").hide();
				$(this).addClass("showMyAccount");
				$(this).text("Show");
				 },
        function(){     
               $(this).parents("h2.consumerOverview").next(".atHomeAccount").show();
				$(this).removeClass("showMyAccount");
				$(this).text("Hide");
	  }); // End toggle
	$(".readModeMyDetails .changeButton input").click(function(){
		$(".editModeMyDetails").show();
		$(".readModeMyDetails").hide();
		return false;
	});
	/*$(".editModeMyDetails .changeButton input").click(function(){
		$(".editModeMyDetails").hide();
		$(".readModeMyDetails").show();
		return false;
	});*/
	$('.newsSubscription').toggle (
        function(){     
                $(this).parent("li").children(".descriptionSubscription").fadeIn();
				$(this).addClass("hideSubscriptionIcon");
				 },
        function(){     
                $(this).parent("li").children(".descriptionSubscription").fadeOut();
				$(this).removeClass("hideSubscriptionIcon");
	}); // End toggle
	
	$(".YesNo").click(function(){
		var status = $(this).attr("checked");
		if(status == undefined){
			$(this).parent("li").children(".cancelRegistration").show();
		}
		if(status == true){
			$(this).parent("li").children(".cancelRegistration").hide();
		}
	});
	
	$(".yes").click(function(){
		$(this).parents(".cancelRegistration").hide();
		return false;
	});
	
	$(".no").click(function(){
		$(this).parents(".cancelRegistration").hide();
		$(this).parents("li").children("input.YesNo").attr("checked", "checked");
		return false;
	});
}


/* -------------------------------------------------------------------------------------------------------------
	Accont setting script starts here 
---------------------------------------------------------------------------------------------------------------*/





function formValidSignin(){
	$("#AddressFinder").attr("value", " ");
	$("#recaptcha_reload").attr("src","http://api.recaptcha.net/img/clean/refresh.png");
	$("#recaptcha_switch_audio").attr("src","http://api.recaptcha.net/img/clean/audio.png");
	$("#recaptcha_whatsthis").attr("src","http://api.recaptcha.net/img/clean/help.png");
	$("#recaptcha_switch_img").attr("src","http://api.recaptcha.net/img/clean/text.png");

	$(".questionInformative").mouseover(function(){
		$(this).next(".toolTipRegistrationMiddle").show();
	});
	$(".closeInformative").click(function(){
		$(".informative .toolTipRegistrationMiddle").hide();
	});
}

/* -------------------------------------------------------------------------------------------------------------
	Registration form script starts here 
---------------------------------------------------------------------------------------------------------------*/


/* ------------------------------------  Report abuse email sender starts here ------------------------------------  */
var popupStatus = 0;
	//loading popup with jQuery magic!
	function loadPopup(){
		//loads popup only if it is disabled
		if(popupStatus==0){
			$("#backgroundPopup").css({
				"opacity": "0.7"
			});
			$("#backgroundPopup").fadeIn("slow");
			$("#popupContact").fadeIn("slow");
			popupStatus = 1;
		}
	}
	//disabling popup with jQuery magic!
	function disablePopup(){
		//disables popup only if it is enabled
		if(popupStatus==1){
			$("#backgroundPopup").fadeOut("slow");
			$("#popupContact").fadeOut("slow");
			popupStatus = 0;		
		}
	}
	//centering popup
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#popupContact").height();
	var popupWidth = $("#popupContact").width();
	function centerPopup(){
		//request data for centering
		//centering
		$("#popupContact").css({
			"left": windowWidth/2-popupWidth/2-200
		});
		//only need force for IE6
		$("#backgroundPopup").css({
			"height": windowHeight
		});
	}
function emailPositionSetter(){
	$("a.thickbox").click(function(){
		//centering with css
		centerPopup();
		//load popup
		loadPopup();
		var pos = $(this).offset().top+15;  
		$("#popupContact").css({ 
			position : "absolute",
			display : "block",
			top : pos-367 + "px"
			//left : "windowWidth/2-popupWidth/2 + "px" 
		});
		var commentUrl = $(this).parent("li").children(".commentUrl").text().length-1;
		commentUrlNew = $(this).parent("li").children(".commentUrl").text().substring(1 , commentUrl);
		$("#responseEmail").hide();
		$("#formail textarea").val("");
		$("#name").val("http://"+location.host+commentUrlNew);

		if(location.host == "www.energysavingtrust.org.uk"){
			$("#admin_url").val("http://admin.ez.est.org.uk"+commentUrlNew);
		}
		else{
			$("#admin_url").val("http://"+location.host+"/est_admin"+commentUrlNew);
		}
		$("#subject").val($(this).parent("li").children(".commentName").text());

		//CLOSING POPUP
		//Click the x event!
		$("#popupContactClose").click(function(){
			disablePopup();
			return false;
		});
		//Click out event!
		$("#backgroundPopup").click(function(){
			disablePopup();
		});
		//Press Escape event!
		$(document).keypress(function(e){
			if(e.keyCode==27 && popupStatus==1){
				disablePopup();
			}
		});	
		return false;
	});
}


/* ------------------------------------  Report abuse email sender ends here ------------------------------------  */


/* ------------------------------------ Blog list social media tabs starts here ---------------------------------- */

function blogListSocialMediaTab(){
	$(".socialMediaRight ul li:first a").addClass("selected");
	$(".socialMediaRight .socialMediaContent").addClass("hiddenTab");
	$(".socialMediaRight .socialMediaContent:first").removeClass("hiddenTab");
	$("a.twitterTab").click(function(){
		$(".socialMediaRight ul li a.socialTab").removeClass("selected");
		$(this).addClass("selected");
		$(".socialMediaRight .socialMediaContent").addClass("hiddenTab");
		$(".socialMediaRight .tweeterTabBlogList").removeClass("hiddenTab");
		if($.browser.version == "6.0"){
			$(".socialMediaRight").attr("style","margin-bottom:15px;");
		}
		return false;
	});
	$("a.flickrTab").click(function(){
		$(".socialMediaRight ul li a.socialTab").removeClass("selected");
		$(this).addClass("selected");
		$(".socialMediaRight .socialMediaContent").addClass("hiddenTab");
		$(".socialMediaRight #flickrContainer").removeClass("hiddenTab");
		if($.browser.version == "6.0"){
			$(".socialMediaRight").attr("style","margin-bottom:15px;");
		}
	});
	$("a.faceBookTab").click(function(){
		$(".socialMediaRight ul li a.socialTab").removeClass("selected");
		$(this).addClass("selected");
		$(".socialMediaRight .socialMediaContent").addClass("hiddenTab");
		$(".socialMediaRight .faceBookContainer").removeClass("hiddenTab");
		if($.browser.version == "6.0"){
			$(".socialMediaRight").attr("style","margin-bottom:-350px;");
			$(".faceBookContainer").attr("style","margin-top:9px;");
		}
		return false;
	});
	$("a.youtubeTab").click(function(){
		$(".socialMediaRight ul li a.socialTab").removeClass("selected");
		$(this).addClass("selected");
		$(".socialMediaRight .socialMediaContent").addClass("hiddenTab");
		$(".socialMediaRight .youtubeBlogListSocial").removeClass("hiddenTab");
		if($.browser.version == "6.0"){
			$(".socialMediaRight").attr("style","margin-bottom:15px;");
		}
		return false;
	});


}

/* ------------------------------------ Blog list social media tabs starts here ---------------------------------- */

/* ------------------------------------ To find out Member first name starts here ---------------------------------- */

function latestMemberImage(){
	$('.ec_user_list_entry_even').each(function(i) {
		var fullMemberName = $(this).children(".ec_user_list_entry_name").children("a").text();
		var trimfullMemberName = $.trim(fullMemberName);
		var selectedMemberName = trimfullMemberName.indexOf(" ");
		var firstMemberName = trimfullMemberName.substring(0, selectedMemberName);
		$(this).children(".ec_user_list_entry_name").children("a").text(firstMemberName);
		$(this).children(".ec_user_list_entry_name").children("a").attr("href", "");
		$(this).children(".ec_user_list_entry_name").children("a").attr("onclick", "");
		var ImageContainer = $(this).children(".image").html();
		var trimImageContainer = $.trim(ImageContainer);
		if(trimImageContainer == ""){
			$(this).children(".image").html("<img src='/extension/redesign_est/design/est/images/redesign/haveYourProfile/member.png' alt='" + fullMemberName + "'/>");
		}
	});
}

/* ------------------------------------ To find out Member first name ends here ---------------------------------- */

/* ------------------------------------ What we have discussed section BU starts here ---------------------------------- */

function discussionListing(){
	$(".discussionListingServer").hide();
	$(".discussionListingClient").show();
	$('.haveDiscussionListing').prev("a").each(function() {
		$(this).attr("href", "javascript:;");
	});
	$(".haveDiscussionCategory li ul.discussionListingClient").hide();
	$(".haveDiscussionCategory li:first ul.discussionListingClient").show();
	$('.haveDiscussionListing').prev("a").click(function(){
		$(".haveDiscussionCategory li ul.discussionListingClient").hide();
		$(this).next("ul.discussionListingClient").show();
		$(".haveDiscussionCategory li a").removeClass("selected");
		$(this).addClass("selected");
		currentNode = $(this);
		initPaginationClick();
	});
	$(".haveDiscussion .haveDiscussionCategory li").each(function(i){
		if($(this).text() == ""){
			$(this).remove();
		}
	});
}

/* ------------------------------------ What we have discussed section BU ends here ------------------------------------- */

/* ----------------------------------------------------- Pagination BU starts here -------------------------------------- */
var currentNode;

	function pageselectCallbackClick(page_index, jq){
		$(".haveDiscussion ul li ul div.listingGroup").hide();
		var new_content = $(currentNode).next("ul").children('div.listingGroup:eq('+page_index+')').attr("style", "display:block");
		return false;
	}
	function initPaginationClick() {
		var num_entries = $(currentNode).next("ul").children("div.listingGroup").length;
		$("#paginationBU").pagination(num_entries, {
			num_edge_entries: 2,
			num_display_entries: 8,
			callback: pageselectCallbackClick,
			items_per_page:1
		});
	}
	/*function listing(){
		$(".haveDiscussion ul li ul").hide();
		$(".haveDiscussion ul li:first ul").show();
		$(".haveDiscussionCategory li a").click(function(){
			$(".haveDiscussion ul li ul").hide();
			$(this).next("ul").show();
			currentNode = $(this);
			initPagination();
		});
	}*/
	/* To show on load listing starts here */
	function pageselectCallback1(page_index, jq){
		$(".haveDiscussion ul li ul div.listingGroup").hide();
		var new_content1 = $('.haveDiscussion ul li:first ul').children('div.listingGroup:eq('+page_index+')').attr("style", "display:block");
		return false;
	}
	function initPagination1() {
		var num_entries1 = $('.haveDiscussion ul li:first ul').children("div.listingGroup").length;
		$("#paginationBU").pagination(num_entries1, {
			num_edge_entries: 2,
			num_display_entries: 8,
			callback: pageselectCallback1,
			items_per_page:1
		});
		$(".paginationBU").show();
	}

	/* To show on load listing ends here */

	function groupingListing(){
		jQuery.fn.wrapInChunks = function(html, chunkSize) {
			chunkSize = chunkSize || 1;
			var items = this.get(),
			rows = [],
			cur = rows[0] = $(html);
			while (items[0]) {
				if (rows[rows.length - 1].children().length === chunkSize) {
					cur = rows[rows.length] = $(html);
				}
				cur.append( items.shift() );
			}
			return this.pushStack(rows);
		};
		$(".haveDiscussion ul li ul").each(function(i){
			$(this).children("li").wrapInChunks('<div class="listingGroup" />', 12).appendTo(this);
		});
	}


/* ----------------------------------------------------- Pagination BU ends here -------------------------------------- */

$(function() {
	$("input[@type=file]").filestyle({
		image: "/extension/redesign_est/design/est/images/redesign/customForm/img_browse.gif",
		imageheight : 23,
		imagewidth : 56,
		width : 290
        });

});


function buttonOver(){
	$("a.joinNowButton").mouseover(function(){
		$(this).children("img").attr("src", "/extension/redesign_est/design/est/images/redesign/haveYourProfile/btn_joinNow_Over.gif");
	});
	$("a.joinNowButton").mouseout(function(){
		$(this).children("img").attr("src", "/extension/redesign_est/design/est/images/redesign/haveYourProfile/btn_joinNow.gif");
	});
	$("ul.greyTeasers li:first a.teaserGreyButton").mouseover(function(){
		$(this).children("img").attr("src", "/extension/redesign_est/design/est/images/redesign/haveYourProfile/btn_login_Over.gif");
	});
	$("ul.greyTeasers li:first a.teaserGreyButton").mouseout(function(){
		$(this).children("img").attr("src", "/extension/redesign_est/design/est/images/redesign/haveYourProfile/btn_login.gif");
	});
	$("ul.greyTeasers li:last a.teaserGreyButton").mouseover(function(){
		$(this).children("img").attr("src", "/extension/redesign_est/design/est/images/redesign/haveYourProfile/btn_joinNow_Over.gif");
	});
	$("ul.greyTeasers li:last a.teaserGreyButton").mouseout(function(){
		$(this).children("img").attr("src", "/extension/redesign_est/design/est/images/redesign/haveYourProfile/btn_joinNow.gif");
	});

}

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");
		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");
		}
		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;");
		}
		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;
	if($(".plainstyle table").length > 1){
		new_content = $('#hiddenresult table.plainstyle:eq('+page_index+')').clone();
	}
	else{
		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:-10px;");
		}
	}
}

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>")
	}
}

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(){

	$("#AddressFinder").bind("click", function() {
		//alert("hiii");
		$(this).parent("li.postCode").addClass("postCodeSearch");
		$("li.postCodeSearch").show();
		/* 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) {
var newFormId = formId.substring(0 , 7);
	return function() {
	var subitdatalength = formId.length;
	var submitDataFormId = formId.substring(1 , subitdatalength);
		if(formId = newFormId){
			$(formId).fadeOut("slow");
			/*$("li#rate-page div#rate-page-tool").load("clicked-state.php?fRateRadio=" + this.value).fadeIn("slow");*/
			document.getElementById(submitDataFormId).Ratevalue.value=this.value;
	              xajax_performRate(xajax.getFormValues(submitDataFormId));
			/*$(formId).fadeIn("slow"); */
			/*$("li#rate-page div#rate-page-tool").load("" + this.value).fadeIn("slow");*/
			this.focus();
			return false;
		}
		if(formId = "#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;
		}
		if(formId = "#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;
		}
		else{
			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>';
       }
    }
}*/
