$(document).ready(function(){
	/* GU function calls */
	/* New function created by sapient starts here */
	mpgCalculatorFixer();
	footerWidthCalculator();
	/* New function created by sapient ends here */
	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();
	initialisePostCodeRenew();
	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;
	});
}

function initialisePostCodeRenew(){
	$("input#AddressFinderRenewables").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_performPostCodeRenew( 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/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", "/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", "/extension/est/design/est/images/temp/" + 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" )
       {
	  //commented out and copy augmented by joshr 28 Aug 2009 as a temporary measure
          //document.getElementById("login").innerHTML='Hi <a href="/calculator/edit/'+YAHOO.util.Cookie.get("USER_ID")+'/f/eng-GB">'+YAHOO.util.Cookie.get("USER_NAME")+'</a> / <a href="/calculator/logout">Sign out</a>';
          document.getElementById("login").innerHTML='<a href="/calculator/navigation/profile">My profile</a> / <a href="/calculator/logout">Sign out</a>';
       }
    }
}
function onToggleElementModalClick(e) {    
    targetElement = getTheLink(this);
    theform = $(targetElement).parent();    
    $(targetElement).fadeIn("fast");
    (theform.children('fieldset.search-results').not(targetElement)).fadeOut("fast");    
    $('.toggle-on').removeClass('toggle-on');
    $(e.target).addClass( 'toggle-on' );    
    return false;
}

function toggleElementsModal(theElement){
    if( $(theElement).length === 0 ) {
        return false;
    }
    firstElement = $(theElement + ':first');
    $(theElement).click(onToggleElementModalClick);
    $(theElement).not(firstElement).removeClass('toggle-on');
    firstElement.addClass('toggle-on');    
    firstTargetElement = getTheLink(firstElement);
    theform = $(firstTargetElement).parent();
    (theform.children('fieldset.search-results').not(firstTargetElement)).fadeOut("fast");    
    $(firstTargetElement).fadeIn("fast");
}
/* New function created by sapient starts here */
function footerWidthCalculator(){
	var totalSectionCount = $(".footerSection div").length;
	var widthCounter = (900/totalSectionCount)-20;
	$(".footerSection div").width(widthCounter);
}

function mpgCalculatorFixer(){
 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)"){
  $("body").attr("class", "estHome mpgCalculatorScotland");
 }
 var currentPageName = $.trim($("ul.breadcrumb li:last").text());
 if(trimmedvalueFirstLi == "You are here (Scotland)"){
  $(".mpgCalculatorScotland #section-nav").html("<ul><li class=\"selected\"><a onclick=\"return false;\" href=\"#\" class=\"currentSelected\">" + currentPageName + "</a></li></ul>")
 }
 if(trimmedvalueLastLi == "MPG Calculator"){
  $("#tools").hide();
 }
 
}
/* New function created by sapient ends here */
