$(document).ready(function(){
	/* GU function calls */
	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();*/
	initialisePoll();
	initialisePostCode();
	initialiseRegister();
	initialiseEmmission();
	labelInput("fSearch");

	$('.expand-section').hide();
	$('.toggle-contents a').click(function () {
		$(this).parent().siblings("div").toggle();
		$(this).parent().siblings("ul").toggle();
		$(this).toggleClass("contract");

		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;
	});
}


/* 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='http://collections.europarchive.org/tna/20080530153425/http://energysavingtrust.org.uk/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 + '/';
	});
}


/* 
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: "http://collections.europarchive.org/tna/20080530153425/http://energysavingtrust.org.uk/extension/est/design/est/images/temp/"  + 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", "http://collections.europarchive.org/tna/20080530153425/http://energysavingtrust.org.uk/extension/est/design/est/images/temp/"  + k + "_over.gif");
			}
		});
		
		$(imageButton).bind('mouseout', function(){
			for(var k=i; k > 0; k--){
				k <= avgRating ? localImageStatus = "on" : localImageStatus = "off";
				$(optionId + k).attr("src", "http://collections.europarchive.org/tna/20080530153425/http://energysavingtrust.org.uk/extension/est/design/est/images/temp/"  + k + "_" + localImageStatus + ".gif");
			}
		});
		
		// swap radio buttons for images	
		$(this).after(imageButton);
		$(this).remove();
	});
}


