// MooTools plugins for Bord Gais Energy



/****************************************************
* Global Vars										*
*													*
*****************************************************/

var root = '/';

var browser, directory, sifrReplaced = 0;
var sIFR = false;
var IEPNGFix = false;
var selectClick = false;
var cardClick = false;
var focusLoaded = false;
var fadeFinished = false;
var domReady = false;
var lbFormsJS = false;
var formCheckLoaded = false;
var stSheets;
var sifrSelectors = false;
var formSubmitting = false;
var sifrElements = 0;
var sifrReplaced = 0;
var defaultInputs = ['Search', 'Home', 'Work', 'Mobile', 'on existing account at address', 'of outgoing customer', 'Give us your feedback...'];
var carouselHolders = ['.homepage #featured', '.carousel', '.recipe-carousel', '#image-carousel'];
var currentLocation = 'homepage';
var hoverTimer, csTimer1, csTimer2, oTimer;

var pImages = [];
var fImages = [];
var popularQuestions = [];
var formValidators = [];

if(document.styleSheets){
	$each(document.styleSheets, function(style, ind){
		var rules = style.rules || style.cssRules;
		if(rules[0]){
			if(rules[0].selectorText == '#wrapper'){
				var bg = false, bg_img;
				if(rules[0].style.background){
					bg = rules[0].style.backgroundImage;
				} else if(rules[0].style['background-image']){
					bg = rules[0].style['background-image'];
				}
				
				if(bg){
					bg_img = bg.substring(bg.indexOf('images/'), bg.indexOf(')'));
					fImages = [root + bg_img, root + bg_img.replace(/.jpg/, '_focus.jpg')];
				}
			}
		}
	});
}

String.prototype.endsWith = function(str){ return (this.match(str+"$")==str); }




/****************************************************
* Get Current Site Location							*
*													*
*****************************************************/

function getCurrentLocation(){
	var url = window.location || document.URL;
	if(url){
		url = url.toString();
		if(url.indexOf('/home/') >= 0){
			if(url.indexOf('/home/services/') >= 0){ currentLocation = 'home services'; }
			else { currentLocation = 'home'; }
		} else if(url.indexOf('/business/') >= 0){ currentLocation = 'business'; }
	}
}

getCurrentLocation();






/****************************************************
* Toggle Display of a Certain Element				*
*													*
*****************************************************/

function toggle(el){
	if($(el)){
		if($(el).getStyle('display') == 'none'){
			$(el).setStyle('display','inline');
		} else {
			$(el).setStyle('display','none');
		}
	}
}




/****************************************************
* Get Flash Object									*
*													*
*****************************************************/

function getFlashMovieObject(movieName){
	if (window.document[movieName]){
		return window.document[movieName];
	}
	
	if (navigator.appName.indexOf("Microsoft Internet")==-1){
		if (document.embeds && document.embeds[movieName]){
			return document.embeds[movieName];
		}
	} else {
		return document.getElementById(movieName);
	}
}

function getFlashMovie(movieName){
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}



/****************************************************
* Browser Detection									*
*													*
*****************************************************/

function Detect() {
	
	agent 	= navigator.userAgent.toLowerCase();
						
	// detect OS
	this.isMac		= (agent.indexOf('mac') != -1);
	this.isWin		= (agent.indexOf('win') != -1);
	this.isWin2k	= (this.isWin && (agent.indexOf('nt 5') != -1));
	this.isWinSP2	= (this.isWin && (agent.indexOf('xp') != -1 || agent.indexOf('sv1') != -1));
	this.isOther	= (agent.indexOf('unix') != -1 || agent.indexOf('sunos') != -1 || agent.indexOf('bsd') != -1 || agent.indexOf('x11') != -1 || agent.indexOf('linux') != -1);
	
	// detect browser
	this.isSafari	= (agent.indexOf('safari') != -1);
	this.isSafari2 = (this.isSafari && (parseFloat(agent.substring(agent.indexOf("applewebkit/")+"applewebkit/".length,agent.length).substring(0,agent.substring(agent.indexOf("applewebkit/")+"applewebkit/".length,agent.length).indexOf(' '))) >=  300));
	this.isOpera	= (agent.indexOf('opera') != -1);
	this.isNN		= (agent.indexOf('netscape') != -1);
	this.isFF		= (agent.indexOf('firefox') != -1);	
	this.isFF2		= (agent.indexOf('firefox/2') != -1);
	this.isFF3		= (agent.indexOf('firefox/3') != -1);	
	this.isIE		= (agent.indexOf('msie') != -1);
	this.isIE8		= (agent.indexOf('msie 8.') != -1);
	this.isIE6		= (agent.indexOf('msie 6.') != -1);
	this.isIE5		= (agent.indexOf('msie 5.') != -1);
	this.isIphone	= (agent.indexOf('iphone') != -1);
}

browser = new Detect();




/****************************************************
* Write Out JS Browser Stylesheet					*
*													*
*****************************************************/

function writeJsStyles(w){
	var sSheets = document.getElementsByTagName("link");
	var dir = "";

	if(sSheets[0]){
		if(sSheets[0].href.indexOf("css") != -1){
			dir = sSheets[0].href.substring(0,sSheets[0].href.indexOf("css"));
			if(dir == ''){ dir = './'; }
			directory = dir;
		}
	}
	
	if(w==1){ document.write('<link href="' + dir + 'css/js-dependant.css" rel="stylesheet" type="text/css" media="screen" />'); }
	
	if(browser.isIE){
		document.write('<link href="' + dir + 'css/ie.css" rel="stylesheet" type="text/css" media="screen" />');		
	}
		
	if(browser.isSafari){
		document.write('<link href="' + dir + 'css/safari.css" rel="stylesheet" type="text/css" media="screen" />');
	}
	
	if(browser.isIphone){
		document.write('<link href="' + dir + 'css/iphone.css" rel="stylesheet" type="text/css" media="screen" />');
	}
	
	if(browser.isOpera){
		document.write('<link href="' + dir + 'css/opera.css" rel="stylesheet" type="text/css" media="screen" />');
	}
	
	if(browser.isFF && !browser.isFF3){
		document.write('<link href="' + dir + 'css/old-ff.css" rel="stylesheet" type="text/css" media="screen" />');
	}
	
	if(Browser.Plugins.Flash.version >= 8){
		document.write('<link href="' + dir + 'css/sifr.css" rel="stylesheet" type="text/css" />');
	}
}






/****************************************************
* Split URL in various parts						*
*													*
*****************************************************/

function splitURL(url){
    var elements = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
    var parts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(url);
    var sURL = {};
    
    for(var i = 0; i < 10; i++){
        sURL[elements[i]] = (parts[i] ? parts[i] : "");
    }
	
    if(sURL.directoryPath.length > 0){
        sURL.directoryPath = sURL.directoryPath.replace(/\/?$/, "/");
    }
    
    return sURL;
}

function gup(name){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null ){ return ""; }
	else { return results[1]; }
}






/****************************************************
* Build lightbox dynamically on each page			*
*													*
*****************************************************/

function fadeErrorMsgs(){
	var errors = $$(".fc-tbx");
	var duration = 300;
	if(browser.isIE){ duration = 0; }
	
	var fx = new Fx.Elements(errors, {
		duration: duration
	});
	
	var o = {};
	errors.each(function(error, i) {
		o[i] = {opacity: 0};
	});
	
	fx.start(o);
}

function fadeLightBox(){
	var duration = 300;
	if(browser.isIE){ duration = 0; }
	
	var oDivs = $('lightbox-content-inner').getElements('div');
	var blendFX = new Fx.Morph($('lightbox-content-inner'), {
		duration: duration,
		onComplete: function(){
			$each(oDivs, function(div,ind){
				if(div.getStyle('overflow') == 'auto'){
					div.setStyle('overflow', 'hidden');
				}
			});
		}
	});	
	
	fadeErrorMsgs();
	blendFX.start({ 'opacity':0 });
	if(browser.isIE){ $$('#lightbox-content-inner .sIFR-replaced').setStyle('opacity', 0); }		
	
}

function resizeLightBox(){
	var diff = $('lightbox-content-inner').getSize().y - $('lb-body').getSize().y;
	
	if(diff < 0){ diff = -1 * diff; }
	
	if(diff > 15){
		$('lightbox-content-inner').setStyle('height', $('lb-body').getSize().y - 2);
		if($('lightbox-overlay')){
			if($('lightbox-overlay').getStyle('height').toInt() > 0){
				$('lightbox-overlay').setStyle('height', Math.max($('wrapper').getSize().y, $('lightbox').getSize().y));
			}
		}
	}
}

function attachLbEvents(){
	if($('lightbox-content-inner')){
		var target, as = $('lightbox-content-inner').getElements('a');
		$each(as, function(a,i){
			if(a.get('target')){ target = a.get('target'); }
			else { target = '_self'; }
			
			if(!a.hasClass('no-lb') && target != '_blank' && a.get('href').indexOf('mailto:') < 0 && a.get('href') != '#'){
				a.addEvents({
					'keypress': function(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ event.stop(); fadeLightBox(); openLbPage.delay(300, this, [a]); } } },
					'click': function(event){ event.stop(); fadeLightBox(); openLbPage.delay(300, this, [a]); a.blur(); }
				});
			}
		});
	}
	
	if($('lb-body')){
		$('lb-body').addEvents({
			'keypress': function(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ resizeLightBox(); } } },
			'click': function(event){ resizeLightBox(); }
		});
	}
}

function openLightBox(el, url, x, y, width, height){
	if($('wrapper') && $('header')){
		var coords= {}, hCoords, flash;
		var opened = true;
		var duration = 300;
		var openWidth = 940, openLeft;
		if(browser.isIE){ duration = 0; }
		
		var href;
		if(el){
			if(el.get('href')){ href = el.get('href'); }
			else if(url){ href = url; }
		} else if(url){
			href = url;
		}
		
		if(!$('lightbox').get('open') || $('lightbox').get('open') == 0){
			opened = false;
			$('lightbox').set('open', 1);
			if(url){
				flash = $('t1Flash') || $('flash-banner');
				coords.left = flash.getPosition($('wrapper')).x.toInt() + x.toInt();
				coords.top = flash.getPosition($('wrapper')).y.toInt() + y.toInt();
				coords.width = width.toInt();
				coords.height = height.toInt();
			} else {
				coords = el.getCoordinates($('wrapper'));
				if(coords.left < 0){
					if(9999 + coords.left > 0 && 9999 + coords.left < 960){
						coords.left = 9999 + coords.left;
					} else if(99999 + coords.left > 0 && 99999 + coords.left < 960){
						coords.left = 99999 + coords.left;
					} else if(999999 + coords.left > 0 && 999999 + coords.left < 960){
						coords.left = 999999 + coords.left;
					} else if(9999999 + coords.left > 0 && 9999999 + coords.left < 960){
						coords.left = 9999999 + coords.left;
					}
				}
			}
			
			hCoords = $('header').getCoordinates($('wrapper'));
		}				
		
		var elements = [$('lightbox'), $('lightbox-content-inner'), $('lightbox-close-but')];
		var o1 = {}, o2 = {};
		var blendFX = new Fx.Elements([elements[1], elements[2]], {
			duration: duration,
			onComplete: function(){ $('lightbox').set('busy', 0); }
		});
		
		var growFX = new Fx.Elements([elements[0], elements[1]], {
			duration: 600,
			transition: Fx.Transitions.Cubic.easeOut,
			onComplete: function(){
				$('lightbox-content-inner').innerHTML = $('lightbox-tmp').innerHTML;
				$('lightbox-tmp').innerHTML = '';
				if(el){
					if(el.hasClass('upload')){
						try {
							createUploadObject();
						} catch(error){}
					}
				}
				
				if($('lightbox-overlay')){
					$('lightbox-overlay').addEvents({
						'click': function(){ /*closeLightBox();*/ }
					});
				}
				
				$('lightbox-overlay').setStyle('height', Math.max($('wrapper').getSize().y, $('lightbox').getSize().y));
				
				attachLbEvents();
				initLbForms();			
				blendFX.start(o2);
			}
		});						
		
		if(!opened){
			$('lightbox').setStyles({ 'left': coords.left - 8, 'top': coords.top - 8 });
			$('lightbox-content-inner').setStyles({ 'width': coords.width, 'height': coords.height });		
			$('lightbox').set('oLeft', coords.left - 8);
			$('lightbox').set('oTop', coords.top - 8);
			$('lightbox').set('oWidth', coords.width);
			$('lightbox').set('oHeight', coords.height);
			
			openLeft = hCoords.left + 3;
			if(href.endsWith('.jpg') || href.endsWith('.gif') || href.endsWith('.png')){
				openLeft = hCoords.left + 3 + ((960 - $('lightbox-tmp').getElements('img')[0].width) / 2).toInt()
			}			
		
			o1[0] = {left: openLeft, top: 0};
			if(el){
				if(el.hasClass('to-center')){
					o1[0] = {left: openLeft, top: Math.max(0, parseInt(getSizeY()/2,10) - parseInt($('lightbox-tmp').getSize().y/2,10) + window.getScroll().y - 8)};
				}
			}
		}				
		
		if(href.endsWith('.jpg') || href.endsWith('.gif') || href.endsWith('.png')){
			openWidth = $('lightbox-tmp').getElements('img')[0].width;		
		}
			
		o1[1] = {width: openWidth, height: $('lightbox-tmp').getSize().y};
		
		o2[0] = {opacity: 1};
		o2[1] = {opacity: 1};
		growFX.start(o1);
	}
}

function closeLightBox(){
	if($('lightbox').get('busy') == 1){ return; }
	var coords = {};
	var elements = [$('lightbox'), $('lightbox-content-inner'), $('lightbox-close-but')];
	var o1 = {}, o2 = {};
	var duration = 300;
	if(browser.isIE){ duration = 0; }
	
	var growFX = new Fx.Elements([elements[0], elements[1]], {
		duration:600,
		transition: Fx.Transitions.Cubic.easeIn,
		onComplete: function(){
			$('lightbox-overlay').setStyle('height', 0);			
			$('lightbox').set('open', 0);
			$('lightbox').setStyles({
				'left': -99999,
				'top': -99999
			});
			
			$('lightbox').set('busy', 0);
		}
	});
	
	var blendFX = new Fx.Elements([elements[1], elements[2]], {
		duration: duration,
		onComplete: function(){
			$('lightbox-content-inner').innerHTML = '';
			growFX.start(o1);
		}
	});
	
	$('lightbox').set('busy', 1);
	
	$('lightbox-overlay').removeEvents('click');
	if($('lb-body')){
		$('lb-body').removeEvents('keypress');
		$('lb-body').removeEvents('click');
	}
	
	coords.left = $('lightbox').get('oLeft');
	coords.top = $('lightbox').get('oTop');
	coords.width = $('lightbox').get('oWidth');
	coords.height = $('lightbox').get('oHeight');
	
	o1[0] = {left: coords.left, top: coords.top};
	o1[1] = {width: coords.width, height: coords.height};
	o2[0] = {opacity: 0};
	o2[1] = {opacity: 0};
	
	fadeErrorMsgs();
	blendFX.start(o2);
}

function readLbHtml(el, url, x, y, width, height){
	var href;
	if(el){
		if(el.get('href')){ href = el.get('href'); }
		else if(url){ href = url; }
	} else if(url){
		href = url;
	}
	
	if(href.endsWith('.jpg') || href.endsWith('.gif') || href.endsWith('.png')){
		var aImage = new Asset.image(href, {
			onload: function(){
				$('lightbox-tmp').innerHTML = '<img src="' + href + '" alt="" width="' + aImage.width + '" height="' + aImage.height + '" />';
				openLightBox(el, url, x, y, width, height);
			}
		});		
		
	} else {
		var html = new Request.HTML({
			method: 'get',
			url: href,
			noCache: true,
			evalScripts: false,
			onRequest: function(){},
			onComplete: function(){},
			onSuccess: function(tree, elements, html, js){
				var ajaxContent = elements.filter(function(elm) {
					return elm.id.test(/^ajax-content/i);
				});
				
				if(ajaxContent.length > 0){
					$('lightbox-tmp').innerHTML = ajaxContent[0].innerHTML;
					openLightBox(el, url, x, y, width, height);
				}
			},
			onFailure: function(xhr){ $('lightbox').set('busy', 0); }
		}).send();
	}
}

function openLbPage(el, url, x, y, width, height){	
	if(!lbFormsJS || $('lightbox').get('busy') == 1){ return; }
	var duration = 0;
	
	if(window.getScroll().y > 0){
		duration = parseInt(300 + window.getScroll().y/4, 10);
	}
	
	if($('lightbox-overlay')){
		$('lightbox-overlay').setStyle('height', $('wrapper').getSize().y);
	}
	
	if(el){
		if(!el.get('href')){ return; }
	} else {
		if(!url){ return; }
	}
	
	var bodyFx = new Fx.Scroll(window, {
		duration: duration,
		wheelStops: false,
		onComplete: function(){
			readLbHtml(el, url, x, y, width, height);
		}
	});
	
	$('lightbox').set('busy', 1);
	
	if(el){
		if(el.hasClass('to-center')){
			readLbHtml(el, url, x, y, width, height);
		} else {
			bodyFx.start(0, 0);
		}
	} else {
		bodyFx.start(0, 0);
	}
}

function initLightbox(){
	if($('wrapper')){
		var lightbox = new Element('div', { 'id': 'lightbox' }).inject($('wrapper'), 'top');
		lightbox.innerHTML = '<div id="lb-br"><div id="lb-tr"><div id="lb-tl"><div id="lb-top"><div id="lb-base"><div id="lb-right"><div id="lb-left"><div id="lightbox-content"><div id="lightbox-content-inner"></div></div></div></div></div></div></div></div></div>';
		lightbox.set('busy',0);
		
		var lightbox_tmp = new Element('div', { 'id': 'lightbox-tmp' }).inject($('wrapper'), 'bottom');
		var lightbox_overlay = new Element('div', {
			'id': 'lightbox-overlay'
		}).inject($('wrapper'), 'bottom');
		
		var lightbox_close = new Element('div', {
			'id': 'lightbox-close-but',
			'class': 'lightbox-close',
			'styles': {'opacity': 0},
			'events': {
				'click': function(){ closeLightBox(); },
				'mouseenter': function(){ this.addClass('lightbox-close-over'); },
				'mouseleave': function(){ this.removeClass('lightbox-close-over'); }
			}
		}).inject($('lightbox-content'));
		
		if(document.URL.indexOf('/generic/') < 0){
			var lightbox_forms_js = new Asset.javascript(root + 'js/lightbox-forms.js', {
				onload: function(){ lbFormsJS = true; initLbForms(); }
			});
			
			var lightbox_forms_css = new Asset.css(root + 'css/lightbox-forms.css');		
		}
		
		$('lightbox-content-inner').setStyle('opacity', 0);
		
		if($(document.body) && document.URL.indexOf('/generic/') < 0){
			var as = $(document.body).getElements('a.lb');
			$each(as, function(a,i){
				a.addEvents({
					'keypress': function(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ event.stop(); openLbPage(a); } } },
					'click': function(event){ event.stop(); openLbPage(a); a.blur(); }
				});
			});
		}
		
		window.addEvents({
			'keypress': function(event){ if(event.key){ if(event.key == 'esc'){ closeLightBox(); closeCustomerSatisfaction(); } } },
			'resize': function(event){ }
		});	
	}
}






/****************************************************
* Rerun PNG Fix										*
*													*
*****************************************************/

function refPng() {
	if(browser.isIE5 || browser.isIE6){
		if(IEPNGFix){
			clearTimeout(IEPNGFix.update.timer);
			IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
		}
	}
}





/****************************************************
* Update sIFR CSS									*
*													*
*****************************************************/

function redrawTabSifr(el,css){
	var objs = el.getElements('object');
	
	if(sIFR){
		if(objs.length > 0 && sIFR.replacements){		
			for(var k=0, l=sIFR.replacements.length; k<l; k++){
				if(sIFR.replacements[k].id == objs[0].id){
					sIFR.replacements[k].changeCSS(css);
				}
			}
		}
	}
}





/****************************************************
* Initialise Input Fields - Rollovers/Default Text	*
*													*
*****************************************************/

function initInputs(el){
	if(!el){ el = $('wrapper'); }
	if(el){
		var inputs = el.getElements('input');
		$each(inputs, function(input, i){
			if(input.src){
				input.addEvents({
					'mouseenter': function(){
						if(browser.isIE5 || browser.isIE6){
							if(input.currentStyle.filter){
								input.style.filter = input.currentStyle.filter.replace(/_on.png/,'_over.png');
							} else {
								input.src = input.src.replace(/_on.gif/,'_over.gif').replace(/_on.jpg/,'_over.jpg');
							}
						} else {
							input.src = input.src.replace(/_on.png/,'_over.png').replace(/_on.gif/,'_over.gif').replace(/_on.jpg/,'_over.jpg');
						}
					},
					
					'mouseleave': function(){
						if(browser.isIE5 || browser.isIE6){
							if(input.currentStyle.filter){
								input.style.filter = input.currentStyle.filter.replace(/_over.png/,'_on.png');
							} else {
								input.src = input.src.replace(/_over.gif/,'_on.gif').replace(/_over.jpg/,'_on.jpg');
							}
						} else {
							input.src = input.src.replace(/_over.png/,'_on.png').replace(/_over.gif/,'_on.gif').replace(/_over.jpg/,'_on.jpg');
						}
					}
				});
			}
			
			if(input.value && input.get('type')){
				if(input.value.length > 0 && input.get('type') == 'text'){				
					$each(defaultInputs, function(dInput, j){
						if(dInput == input.value){
							input.set('def_value', dInput.toString());
							input.addEvents({
								'focus': function(){ input.value = ''; input.erase('def_value'); }
							});
						}
					});
					
					if(input.getParent().getParent().getParent()){
						if(input.getParent().getParent().getParent().id){
							if(input.getParent().getParent().getParent().id == 'site-search'){
								input.addEvents({
									'blur': function(){ if(input.value == ''){ input.value = 'Search'; } }
								});
							}
						}
					}										
				}
			}						
		});
		
		var textareas = el.getElements('textarea');
		$each(textareas, function(textarea, i){
			if(textarea.innerHTML.length > 0){
				textarea.addEvents({
					'focus': function(){
						$each(defaultInputs, function(dInput, j){
							if(dInput == textarea.innerHTML){ textarea.innerHTML = ''; }
						});
					}
				});										
			}									
		});
	}
}






/****************************************************
* Initialise Rollovers for links with PNG			*
* backgrounds for IE6-								*
*													*
*****************************************************/

function aSpansPngHover(a, over){
	var spans = a.getElements('span');
	$each(spans, function(span, j){
		if(span.getAttribute('orig')){
			if(over){
				span.setStyle('background-image', span.getAttribute('orig').replace(/.png/,'_over.png'));
			} else {
				span.setStyle('background-image', span.getAttribute('orig').replace(/_over.png/,'.png'));
			}
		}
	});	
}

function initPngHovers(){
	var rules, ruleStyle, list = '', bg;
	if(document.styleSheets){
		$each(document.styleSheets, function(style){
			rules = style.rules || style.cssRules;
			$each(rules, function(rule, ind){
				if(rule.selectorText){					
					if(rule.selectorText.indexOf(':hover') >= 0){
						bg = false;
						if(rule.style.background){
							bg = rule.style.backgroundImage;
						} else if(rule.style['background-image']){
							bg = rule.style['background-image'];
						}
						
						if(bg){
							bg = bg.toString();
							if(bg.indexOf('.png') >= 0){
								if(list.length > 0){ list += ', '; }
								list += rule.selectorText.toString().substring(0,rule.selectorText.indexOf(':hover'));
							}
						}
					}
				}
			});
		});
	}
	
	if($('wrapper') && list.length > 0){
		if(browser.isIE5 || browser.isIE6){
			var j, as = $('wrapper').getElements(list);
			$each(as, function(a, i){
				a.addEvents({
					'mouseenter': function(){
						if(a.getAttribute('orig')){
							a.setStyle('background-image', a.getAttribute('orig').replace(/.png/,'_over.png'));
							aSpansPngHover(a, true);														
						} else {
							if(a.getStyle('background-image')){
								a.setStyle('background-image', a.getStyle('background-image').replace(/.gif/,'_over.gif').replace(/.jpg/,'_over.jpg'));
							}
						}
						
						if(a.getParent().getParent()){
							if(a.getParent().getParent().hasClass('blue-button') || a.getParent().hasClass('submit-entry')){
								aSpansPngHover(a, true);
							}
						}
						
						if(IEPNGFix){
							clearTimeout(IEPNGFix.update.timer);
							IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
						}
					},
					
					'mouseleave': function(){
						if(a.getAttribute('orig')){
							a.setStyle('background-image', a.getAttribute('orig').replace(/_over.png/,'.png'));
							aSpansPngHover(a);														
						} else {
							if(a.getStyle('background-image')){
								a.setStyle('background-image', a.getStyle('background-image').replace(/_over.gif/,'.gif').replace(/_over.jpg/,'.jpg'));
							}
						}
						
						if(a.getParent().getParent()){
							if(a.getParent().getParent().hasClass('blue-button') || a.getParent().hasClass('submit-entry')){
								aSpansPngHover(a);
							}
						}
						
						if(IEPNGFix){
							clearTimeout(IEPNGFix.update.timer);
							IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
						}
					}
				});					
			});
		}
	}
}






/****************************************************
* Position the Loading Indicator Correctly			*
*													*
*****************************************************/

function clearLoading(color){
	if($('wrapper')){		
		var lEffect = new Fx.Morph($('wrapper'), {
			duration: 200, 
			transition: Fx.Transitions.Linear,
			onComplete: function(){}
		});
		
		if(!browser.isIE){
			lEffect.start({opacity: [0, 1]});
		} else {
			$('wrapper').setStyle('opacity',1);
		}
	}
}








/****************************************************
* Position Footer so that it will appear of base of	*
* page every time									*
*													*
*****************************************************/

function getSizeY(){
	var h = 0;
	if(!window.innerWidth){
		if(!(document.documentElement.clientWidth === 0)){
			h = document.documentElement.clientHeight;
		} else {
			h = document.body.clientHeight;
		}
	} else {
		h = window.innerHeight;
	}
	
	return h;
}

function positionFooter(){
	if($('wrapper') && $('page-contents')){
		if(getSizeY() > $('wrapper').getSize().y){
			var diff = getSizeY() - $('wrapper').getSize().y;
			$('page-contents').setStyles({
				'height': 'auto !important',
				'height': $('page-contents').getSize().y + diff,
				'min-height': $('page-contents').getSize().y + diff
			});
		}
	}
}
	

	




/****************************************************
* Make the Focusing Effect on Homepage				*
*													*
*****************************************************/

function mafeFocusDiv(){
	if($('page-contents')){
		var inFocus = new Element('div', {			
			'id': 'in-focus-bg',
			'styles': {
				'height': $('page-contents').getSize().y
			}
		}).inject($('page-contents'));
	}
}


function showPreHiddenElements(){
	if($('wrapper')){
		var pHiddens = $('wrapper').getElements('.pre-hidden');
		var fEffect, fx = [];
		var duration = 250;
		
		if(browser.isIE){ duration = 0; }
		
		$each(pHiddens, function(hid, index){
			fEffect = new Fx.Morph(hid, {
				duration: duration,
				transition: Fx.Transitions.Linear,
				onComplete: function(){
					if(index == pHiddens.length - 1){
						fadeFinished = true;
					}
				}
			});
			
			fx[index] = fEffect;
		});
		
		$each(fx, function(eff, index){						   
			eff.start.delay(index * 250, eff, {'opacity': [0, 1]}); 
		});
		
		if(pHiddens.length <= 0){
			fadeFinished = true;
		}
	}
}


function startFocusEffect(){
	if($('in-focus-bg')){
		var fEffect = new Fx.Morph($('in-focus-bg'), {
			duration:250, 
			transition: Fx.Transitions.Linear,
			onComplete: function(){				
				$('in-focus-bg').dispose();
			}
		});
		
		fEffect.start({ 'opacity': 0 });
		showPreHiddenElements.delay(100);
	}
}





/****************************************************
* Return number of sIFR Elements					*
*													*
*****************************************************/

function getSifrElements(){
	var sifrStr = '';
	if($('wrapper') && sifrSelectors){
		if(sifrSelectors.length > 0){
			$each(sifrSelectors, function(sifrSel, ind){
				sifrStr += sifrSel.toString();
				if(ind != sifrSelectors.length - 1){
					sifrStr += ', ';
				}
			});		
			
			sifrElements = $$(sifrStr).length;
		}		
	}
}






/****************************************************
* Initialise Customer Satidfaction Slider			*
*													*
*****************************************************/

function showCustomerSatisfaction(el, show){
	if(el){
		if(show){
			$('customer-satisfaction').setStyle('z-index', 7);
			el.setStyles({
				'left': 0,
				'top': -1*el.getSize().y + 2
			});
		} else {
			$('customer-satisfaction').setStyle('z-index', 4);
			el.setStyles({
				'left': -999999,
				'top': -999999
			});
		}
	}
}


function slideCustomerSatisfaction(a, el, action, quick){
	if(el){
		if($('customer-satisfaction').get('busy') == 1){ return; }
		var elements = [$('customer-satisfaction'), el];
		var duration = 600;
		
		if(quick){ duration = 0; }
		
		var fx = new Fx.Elements(elements, {
			duration: duration,
			onComplete: function(){
				if(action == 'open'){
					if($('cs-card-start')){ $('cs-card-start').focus(); $('cs-card-start').focus(); }
				} else {
					showCustomerSatisfaction(el, false);					
				}

				$('customer-satisfaction').set('busy',0);
				$('cs-ajax-ind').setStyles({ 'opacity': 0 });
			}
		});				
		
		$('customer-satisfaction').set('busy',1);
		if(action == 'open'){
			$('customer-satisfaction').set('open',1);
			showCustomerSatisfaction(el, true);
			if(quick){
				fx.start({
					'0': { 'margin-top': -1*el.getSize().y, 'padding-top': el.getSize().y + 2 },
					'1': { 'top': 2 }
				});
			} else {
				fx.start.delay(100, fx, [{
					'0': { 'margin-top': -1*el.getSize().y, 'padding-top': el.getSize().y + 2 },
					'1': { 'top': 2 }
				}]);
			}
			
		} else {
			$('customer-satisfaction').set('open',0);
			if(quick){
				fx.start({
					'0': { 'margin-top': 0, 'padding-top': 2 },
					'1': { 'top': -1*el.getSize().y + 2 }
				});
			} else {
				fx.start.delay(100, fx, [{
					'0': { 'margin-top': 0, 'padding-top': 2 },
					'1': { 'top': -1*el.getSize().y + 2 }
				}]);
			}
		}
	}

}


function getCustomerSatisfaction(a, form){
	if(!lbFormsJS){ csTimer1 = getCustomerSatisfaction.delay(100, this, [a, form]); }
	else {
		$clear(csTimer1);

		if($('customer-satisfaction').get('loading') == 1){ return; }
		$('customer-satisfaction').set('loading',1);			

		var html = new Request.HTML({
			method: 'get',
			url: a.get('href'),
			evalScripts: false,
			onRequest: function(){},
			onComplete: function(){},
			onSuccess: function(tree, elements, html, js){
				$('customer-satisfaction').set('loaded',1);
				$('customer-satisfaction').set('loading',0);
				
				var ajaxContent = elements.filter(function(el) {
					return el.id.test(/^ajax-content/i);
				});

				if(ajaxContent.length > 0){
					form.innerHTML = ajaxContent[0].innerHTML;
					var containers = $$('#cs-form-header .container');
					if(containers.length > 0){
						var cus_sat_close = new Element('div', {
							'id': 'cs-close-but',
							'class': 'lightbox-close',
							'events': {
								'click': function(){ slideCustomerSatisfaction(a, form, 'close'); },
								'mouseenter': function(){ this.addClass('lightbox-close-over'); },
								'mouseleave': function(){ this.removeClass('lightbox-close-over'); }
							}
						}).inject(containers[0]);
					}
					

					initLbForms();					
					slideCustomerSatisfaction(a, form, 'open');
				}
			},
			onFailure: function(xhr){}
		}).send();
		
		if($('cs-ajax-ind-img')){ $('cs-ajax-ind-img').src = root + 'images/homepage/ajax-loader-small.gif'; }
	}
}


function closeCustomerSatisfaction(){
	if($('customer-satisfaction')){
		var main_link = $('customer-satisfaction').getElements('a.button');
		var form_holder = $('customer-satisfaction-form');
		if($('customer-satisfaction').get('open') != 0 && main_link.length > 0 && form_holder){
			slideCustomerSatisfaction(main_link[0], form_holder, 'close'); // add true as 4th param to close instantly
		}
	}
}


function initCustomerSatisfaction(){
	if($('customer-satisfaction') && document.URL.indexOf('/generic/') < 0){
		var main_link = $('customer-satisfaction').getElements('a.button');
		var form_holder = $('customer-satisfaction-form');
		$('customer-satisfaction').set('open',0);
		$('customer-satisfaction').set('busy',0);
		$('customer-satisfaction').set('loaded',0);
		$('customer-satisfaction').set('loading',0);

		if(main_link.length > 0 && form_holder){
			main_link[0].addEvents({
				'click': function(event){
					event.stop();			
					cardClick = true;
					if($('customer-satisfaction').get('loaded') == 0){
						$('cs-ajax-ind').setStyles({ 'visibility': 'visible', 'opacity': 1 });
						getCustomerSatisfaction.delay(100, this, [main_link[0], form_holder]);						
					} else {
						if($('customer-satisfaction').get('open') == 0){						
							slideCustomerSatisfaction(main_link[0], form_holder, 'open');
						} else {
							slideCustomerSatisfaction(main_link[0], form_holder, 'close');
						}
					}
				},
				
				'focus': function(event){
					if($('customer-satisfaction').get('loaded') == 0){
						$('cs-ajax-ind').setStyles({ 'visibility': 'visible', 'opacity': 1 });
						getCustomerSatisfaction.delay(100, this, [main_link[0], form_holder]);
					} else {
						if($('customer-satisfaction').get('open') == 0){						
							slideCustomerSatisfaction(main_link[0], form_holder, 'open');
						} else {
							slideCustomerSatisfaction(main_link[0], form_holder, 'close');
						}
					}
				},
				
				'keypress': function(event){ event.stop(); return false; },
				'keydown': function(event){ event.stop(); return false; }
			});
			
			//getCustomerSatisfaction(main_link[0], form_holder, true);
		}
	
	} else {
		//if(!lbFormsJS){ initCustomerSatisfaction.delay(100, this, []); }
		//initLbForms();
	}

	if($('page-contents') && $('footer')){
		$$('#page-contents, #footer').addEvents({
			'keydown': function(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter' || event.key == 'tab'){ closeCustomerSatisfaction(); } } },
			'mousedown': function(event){ closeCustomerSatisfaction(); }
		});
	}
}
	
	






/****************************************************
* Add Hover Events to Li's rather than a's in the	*
* main nav(overviews) for IE6						*
*													*
*****************************************************/

function doLiMainNavHovers(){
	if($('overviews')){
		var as, spans, lis = $('overviews').getElements('li');
		$each(lis, function(li, ind){
			if(li.id){
				if(li.id.indexOf('overview-') >= 0){
					li.addEvents({
						'mouseenter': function(){
							as = li.getElements('a.main');
							spans = li.getElements('a.main span.tab');
							if(as.length > 0 && spans.length > 0){
								if(!as[0].hasClass('hover')){
									as[0].addClass('hover');
								}
								
								if(!spans[0].get('bPos')){ spans[0].set('bPos', spans[0].currentStyle.backgroundPositionX + " " + spans[0].currentStyle.backgroundPositionY); }
								spans[0].setStyles({
									'background-image': spans[0].getStyle('background-image').replace(/\/homepage\//, '/homepage/tabs/').replace(/_on.gif/, '_over.gif'),
									'background-position': 'left top'
								});
							}
						},
						'mouseleave': function(){							
							as = li.getElements('a.main');
							spans = li.getElements('a.main span.tab');
							if(as.length > 0 && spans.length > 0){
								as[0].removeClass('hover');
								spans[0].setStyles({
									'background-image': spans[0].getStyle('background-image').replace(/\/homepage\/tabs\//, '/homepage/').replace(/_over.gif/, '_on.gif'),
									'background-position': spans[0].get('bPos')
								});
							}
						}
					});
				}
			}
		});
	}
}





/****************************************************
* Init SmoothScroll									*
*													*
*****************************************************/

function initSmoothScroll(){
	if($('wrapper')){
		var links = $('wrapper').getElements('a[href$=top]');
		var bodyFx = new Fx.Scroll(window, {
			duration: 600,
			wheelStops: false
		});
		
		$each(links, function(a, ind){
			if(a.get('href').endsWith('#top')){
				a.addEvents({
					'click': function(event){ 
						event.stop();
						bodyFx.start(0, 0);
					},
					'focus': function(event){
						closeCustomerSatisfaction();
					}
				});
			}
		});
	}
}




/****************************************************
* Initialise Accordions								*
*													*
*****************************************************/

function scrollToElement(el, offset){
	if(fadeFinished){
		if(el){
			var yPos = -25;
			if(!isNaN(offset)){
				yPos = offset;
			}
			
			var bodyFx = new Fx.Scroll(window, {
				duration: 800,
				wheelStops: false,
				offset: {
					'x': 0,
					'y': yPos
				}
			});
			
			bodyFx.toElement(el);
		}
	
	} else {
		scrollToElement.delay(100, this, [el, offset]);
	}
}

function initHqAccordion(){
	if($('help-and-questions-content')){
		var script = new Asset.javascript(root+ 'js/accordion-help-questions.js', {
			onload: function(){
				setupHqAccordion();
			}
		});
	}
}

function initTermsPrivacyAccordion(){
	if($('terms-privacy-content')){		
		var script = new Asset.javascript(root+ 'js/accordion-terms-privacy.js', {
			onload: function(){
				setupTermsPrivacyAccordion();
			}
		});
	}
}

function initTCsSupplyAccordion(){
	if($('terms-conditions-supply-content')){		
		var script = new Asset.javascript(root+ 'js/accordion-tcs-supply.js', {
			onload: function(){
				setupTCsSupplyAccordion();
			}
		});
	}
}

function initLanguagesAccordion(){
	if($('languages-content')){		
		var script = new Asset.javascript(root+ 'js/accordion-languages.js', {
			onload: function(){
				setupLanguagesAccordion();
			}
		});
	}
}

function initSponsorshipAccordion(){
	if($('sponsorship-accordion')){		
		var script = new Asset.javascript(root+ 'js/accordion-sponsorship.js', {
			onload: function(){
				setupSponsorshipAccordion();
			}
		});
	}
}




/****************************************************
* Fix Safari Cursor Bug on Links					*
*													*
*****************************************************/

function setCursor(el){
	el.setStyle('cursor', 'pointer');
}

function fixSafariHoverBug(){		
	if($('wrapper')){
		$$('#wrapper a, #wrapper a span, #wrapper a img').addEvent('mouseenter', function(){
			hoverTimer = setCursor.periodical(50, this, [this]);
			this.setStyle('cursor', 'pointer');		
		});
		
		$$('#wrapper a, #wrapper a span, #wrapper a img').addEvent('mouseleave', function(){
			$clear(hoverTimer);
			this.setStyle('cursor', 'default');		
		});
	}
	
	if($('overviews')){
		var as, lis = $('overviews').getElements('li');
		var pops = $$('#overviews ul #overview-1 .pop');
		
		$each(lis, function(li, i){
			if(li.id){
				if(li.id.indexOf('overview-') >= 0 && !li.hasClass('first')){
					as = li.getElements('a');
					$each(as, function(a, j){
						a.addEvents({
							'mouseenter': function(){ if(pops.length > 0){ pops[0].setStyles({ left:-99999 }); } },
							'mouseleave': function(){ if($(document.body).hasClass('homepage')){ pops[0].setStyles({ left:0 }); } }
						});
					});
				}
			}
		});
	}
}






/****************************************************
* Initialise Opacity Roolovers on Energy Efficiency	*
* Tabs Images										*
*													*
*****************************************************/

var EnergyEffiencyOpacity = new Class({

	Implements: [Events, Options],

	options: {},

	initialize: function(imgs, options){
		this.setOptions(options);
		this.ob = {};
		this.imgs = imgs;
		this.fx = new Fx.Elements(this.imgs, {
			duration:300,
			'link': 'cancel',
			onComplete: function(){}
		});
		
		$each(this.imgs, function(img, i){
			img.addEvents({
				'mouseenter': function(){ this.fade(i, true); }.bind(this),
				'mouseleave': function(){ this.fade(i); }.bind(this)
			});
		}.bind(this));
	},
	
	fade: function(ind, over){
		if(over){
			$each(this.imgs, function(img, i){ this.ob[i] = {opacity: 0.5}; }.bind(this));
			this.ob[ind] = {opacity: 1};
		} else {
			$each(this.imgs, function(img, i){ this.ob[i] = {opacity: 1}; }.bind(this));
		}
		
		this.fx.start(this.ob);
	}
});

function initEnEfficOpac(){
	if($('overview-4')){
		var eff = new EnergyEffiencyOpacity($$('#overview-4 .col1 img, #overview-4 .col2 img, #overview-4 .col3 img'), {});
	}
}






/****************************************************
* Initialise AJAX Menu Building in Help and			*
* Questions and tab									*
*													*
*****************************************************/

function loadHqTopicMenuAjax(section, list, bg){
	var i, j, topics, divs, oHTML = '<ul>';
	var menuReq = new Request({
		method: 'post',
		url: root + 'help-and-questions/getQuestions.php',
		noCache: true,
		data: 'files=' + list,
		onSuccess: function(text, xml){
			topics = xml.getElementsByTagName('topic');			
			for(i=0; i<topics.length; i++){				
				divs = topics[i].getElementsByTagName('div');
				for(j=0; j<divs.length; j++){
					if(topics[i].attributes[0].firstChild.nodeValue && divs[j].attributes[0].firstChild.nodeValue){
						if(divs[j].attributes[0].firstChild.nodeValue.toString().indexOf('popularPage') >= 0){
							oHTML += '<li><a href="' + topics[i].attributes[0].firstChild.nodeValue.toString() + '"><span>' + divs[j].firstChild.nodeValue.toString() + '</span></a></li>';
						} else if(divs[j].attributes[0].firstChild.nodeValue.toString().indexOf('popular') >= 0){
							oHTML += '<li><a href="' + topics[i].attributes[0].firstChild.nodeValue.toString() + '?q=' + j + '"><span>' + divs[j].firstChild.nodeValue.toString() + '</span></a></li>';
						}
					}
				}
			}
			
			oHTML += '</ul>';
			popularQuestions[section] = oHTML;
			if(!bg){
				$('help-and-questions-popular').innerHTML = popularQuestions[section];
				addMainTabEvents($$('#help-and-questions-popular a'));
			}
		}
	}).send();
}

function loadHqTopicMenu(section, list, bg){
	if(popularQuestions[section]){
		if(popularQuestions[section].indexOf('</ul>') >= 0){
			$('help-and-questions-popular').innerHTML = popularQuestions[section];
		} else {
			loadHqTopicMenuAjax(section, list, bg);
		}
		
	} else {
		loadHqTopicMenuAjax(section, list, bg);
	}
}

function loadHqSectionMenu(section, bg){	
	var menuReq = new Request.HTML({
		method: 'get',
		url: root + 'help-and-questions/getHelpQuestionsMenu.php',
		noCache: true,
		evalScripts: false,
		onSuccess: function(tree, elements, html, js){
			if(!bg){
				$('help-and-questions-topics').innerHTML = html;
				$('help-and-questions-popular').innerHTML = '';
				addMainTabEvents($$('#help-and-questions-topics a'));
				if(browser.isIE5 || browser.isIE6){
					if(IEPNGFix){
						clearTimeout(IEPNGFix.update.timer);
						IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
					}
				}
			}
			
			var links = elements.filter(function(el) {
				return el.nodeName.test(/^a$/i);
			});
			
			if(links.length > 0){
				loadHqTopicMenu(section, links, bg);
			}
		}
	}).send('s='+section);
}

function changeHqTitles(title){
	if($('hq-col1-img') && $('hq-col2-img') && $('customer-options')){
		var img1, img2;
		if(title.indexOf('_gas') >= 0){
			$('hq-col1-img').set('title', 'Browse gas help topics');
			$('hq-col2-img').set('title', 'Popular gas questions');			
			img1 = 'gas_topics.gif';
			img2 = 'gas_questions.gif';
			//$('customer-options').setStyle('display', 'block');
		} else if(title.indexOf('_electricity') >= 0){
			$('hq-col1-img').set('title', 'Browse electricity help topics');
			$('hq-col2-img').set('title', 'Popular electricity questions');
			img1 = 'electricit_topics.gif';
			img2 = 'electricity_questions.gif';
			//$('customer-options').setStyle('display', 'block');
		} else if(title.indexOf('_services') >= 0){
			$('hq-col1-img').set('title', 'Browse services help topics');
			$('hq-col2-img').set('title', 'Popular services questions');
			img1 = 'services_topics.gif';
			img2 = 'services_questions.gif';
			//$('customer-options').setStyle('display', 'none');
		}
		
		$('hq-col1-img').set('src', $('hq-col1-img').get('src').substring(0,$('hq-col1-img').get('src').lastIndexOf('new/')+4) + img1);
		$('hq-col2-img').set('src', $('hq-col2-img').get('src').substring(0,$('hq-col2-img').get('src').lastIndexOf('new/')+4) + img2);
	}
}

function initHelpQuestionsTab(){
	var as, lis, title;
	if($('help-and-questions-nav') && $('help-and-questions-topics') && $('help-and-questions-popular')){
		$each($$('#help-and-questions-nav a'), function(a, ind){
			title = a.get('title') || a.get('tmpTitle');
			if(ind > 0){
				loadHqSectionMenu(title.toLowerCase().replace(/ /, '_'), true);				
			} else {
				loadHqSectionMenu(title.toLowerCase().replace(/ /, '_'), false);
			}
			
			a.addEvent('click', function(event){
				event.stop();
				title = a.get('title') || a.get('tmpTitle');
				if(title){
					lis = a.getParent('ul').getElements('li');
					$each(lis, function(li, ind){ li.removeClass('active'); });
					a.getParent('li').addClass('active');
					loadHqSectionMenu(title.toLowerCase().replace(/ /, '_'), false);					
					changeHqTitles(title.toLowerCase().replace(/ /, '_'));
				}
			});
		});
	}
}




/****************************************************
* Add Events to Main Tabs at Page Top				*
*													*
*****************************************************/

function getParentTabMain(el){
	var parent = el;
	var mains, limit = 20;
	
	while(limit > 0){
		parent = parent.getParent();
		if(parent.get('id')){
			if(parent.get('id').indexOf('overview-') >= 0 || parent.get('id') == 'wrapper'){
				limit = -10;
			}
		}
		
		limit--;
	}
	
	if(parent.get('id')){
		if(parent.get('id').indexOf('overview-') >= 0){
			mains = parent.getElements('a.main');
			if(mains.length > 0){
				return mains[0];
			} else {
				return false;
			}
		} else {
			return false;
		}
		
	} else {
		return false;
	}
}


function addDelayClass(add, lis){
	var pops, as = [];
	if(lis.length > 0){
		as = lis[0].getParent('ul').getElements('a.main');
	} else {
		return;
	}
	
	if(add){
		$each(as, function(a, ind){
			if(ind > 0){
				if(!a.hasClass('delay') && !a.getParent().hasClass('delay')){
					a.getParent().addClass('delay');
					a.addClass('delay');					
				}
			} else {
				if($(document.body).hasClass('homepage')){
					pops = a.getParent().getElements('.pop');
					if(pops.length > 0){ pops[0].setStyle('left',0); }
				}
			}
		});
	} else {
		$each(as, function(a, ind){
			a.getParent().removeClass('delay');
			a.removeClass('delay');
		});
	}
}


function manageActiveOverviews(pli, init){
	var oLis = [], allLis = $('overviews').getElements('li');
	var oMains = [], foundAt = -1, count = 0;
	var objects, cover, covers;
	
	$each(allLis, function(li, ind){
		if(li.id){
			if(li.get('id').indexOf('overview-') >= 0){
				oLis[count] = li;
				oMains[count] = li.getElements('a.main');
				if(li == pli){ foundAt = count; }
				count++;
			}
		}
	});		
	
	if(pli){
		if(oLis.length == oMains.length && foundAt >= 0){
			if(oLis[foundAt] && oMains[foundAt]){
				$each(oLis, function(li, ind){ li.removeClass('active'); });
				$each(oMains, function(main, ind){ main.removeClass('active'); });
				oLis[foundAt].addClass('active');
				oMains[foundAt].addClass('active');
				addDelayClass(false, oLis);
			}
			
			if(foundAt > 0 && browser.isSafariTest){
				objects = $(document.body).getElements('object');
				$each(objects, function(obj, ind){
					if(obj.getParent()){
						if(obj.getParent().getElements('.flash-cover').length > 0){}
						else {
							if(obj.getParent().getStyle('position') != 'absolute'){
								obj.getParent().setStyle('position', 'relative');
							}
							
							cover = new Element('div', {
								'class': 'flash-cover',
								'styles': {
									'width': obj.getParent().getSize().x,
									'height': obj.getParent().getSize().y,
									'position': 'absolute',
									'left': 0,
									'top': 0,
									'z-index': 10,
									'background': 'url(' + root + 'css/blank.gif) repeat'
								}
							}).inject(obj.getParent());
						}
					}
				});
			}
		}				
	} else {
		$each(oLis, function(li, ind){ li.removeClass('active'); });
		$each(oMains, function(main, ind){ main.removeClass('active'); });
		addDelayClass(false, oLis);
		if(browser.isSafariTest){
			covers = $(document.body).getElements('.flash-cover');
			for(count=covers.length-1; count>=0; count--){
				covers[count].dispose();
			}
		}
	}
}


function addMainTabEvents(as){
	if($('overviews')){
		var all_as = $$('#overviews a');
		var mains = $$('#overviews a.main');
		var main, hasActive = false, lis = [];				
		
		if(as){
			all_as = as;
			all_as.removeEvents('focus');
			all_as.removeEvents('blur');		
			
		} else { all_as = $$('#overviews a'); }
		
		all_as.addEvents({
			'focus': function(){
				$each(mains, function(a, i){ a.removeClass('active'); a.getParent().removeClass('active'); });
				main = getParentTabMain(this);
				if(main){
					if(!main.hasClass('active')){ main.addClass('active'); }
					if(!main.getParent().hasClass('active')){ main.getParent().addClass('active'); }
				}
			},
			'blur': function(){
				$each(mains, function(a, i){ a.removeClass('active'); a.getParent().removeClass('active'); });
			},
			'mouseenter': function(){
				if(this.get('title') && !this.get('tnpTitle')){
					this.set('tmpTitle', this.get('title'));
					this.set('title', '');
				}
			},
			'mouseleave': function(){
				if(this.get('tmpTitle') && this.get('title')){
					this.set('title', this.get('tmpTitle'));
					this.erase('tmpTitle');
				}
			}
		});
		
		if(!as){
			if(!browser.isIE6 && !browser.isIE5){
				mains.addEvents({
					'keypress': function(event){ if(event.key){ if(!this.getParent().hasClass('first')){ if(event.key == 'space' || event.key == 'enter'){ event.stop(); } } } },
					'click': function(event){ if(!this.getParent().hasClass('first')){ event.stop(); } }
				});
			
			
				$each(mains, function(a, ind){
					lis[ind] = a.getParent('li');
				});
				
				$each(lis, function(li, ind){
					li.addEvents({
						'mouseenter': function(){									
							$clear(oTimer);
							hasActive = false;
							
							$each(lis, function(pli, i){
								$each(pli.getElements('a.main'), function(a, j){
									if(a.hasClass('active')){
										hasActive = true;
									}
								});
							});
							
							if(hasActive){
								manageActiveOverviews(li);
							} else {
								addDelayClass(true, lis);
								oTimer = manageActiveOverviews.delay(500, this, [li]);
							}
						}
					});								
				});
				
				$('overviews').addEvents({
					'mouseleave': function(){
						$clear(oTimer);
						addDelayClass(false, lis);
						oTimer = manageActiveOverviews.delay(500, this, []);
					}
				});
				
			} else {
				mains.addEvents({
					'mouseenter': function(){
						if(IEPNGFix){
							clearTimeout(IEPNGFix.update.timer);
							IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
						}
					}
				});
			}
		}
	}
}




/****************************************************
* Add Covering div over Links containing sifrs so	*
* we can click on them								*
*													*
*****************************************************/

function getCoverParentA(cover){
	var retA = false;
	var parent = cover.getParent();
	var others = parent.getElements('.sifrCover');
	var sifrs = parent.getElements('.sIFR-replaced');
	
	for(var i=0; i<others.length; i++){
		if(others[i] == cover){
			if(sifrs[i].nodeName.toLowerCase() == 'a'){ retA = sifrs[i]; }
			else { retA = sifrs[i].getParent('a'); }
		}
	}
	
	return retA;
}

function addSifrCovers(){
	var par_a, cover, left, top, highs, arr = [], eCovers;
	if(sifrSelectors){
		if(sifrSelectors.length > 0){
			$each(sifrSelectors, function(sifrSel, ind){
				arr = sifrSel.split(',');
				$each(arr, function(ar, ind2){
					if(ar.toString().indexOf(' a ') >= 0 || ar.toString().indexOf(' a.') >= 0 || ar.toString().endsWith(' a')){
						$$(ar.toString()).each(function(arg, ind3){
							par_a = arg.getParent('a');
							if(par_a){
								if(par_a.getParent()){
									eCovers = par_a.getParent().getElements('.sifrCover');
									if(eCovers.length == 0){									
										if(par_a.getStyle('position') == 'absolute'){
											left = par_a.getStyle('left').toInt();
											top = par_a.getStyle('top').toInt();
										} else {
											left = 0;
											top = 0;
										}
										
										if(par_a.getParent().getStyle('position') != 'absolute'){
											par_a.getParent().setStyle('position', 'relative');
										}										
										
										cover = new Element('div', {
											'class': 'sifrCover',
											'styles': {
												'width': par_a.getSize().x,
												'height': par_a.getSize().y,
												'position': 'absolute',
												'clear': 'both',
												'left': left,
												'top': top,
												'z-index': 5,
												'cursor': 'pointer',
												'background': 'url(' + root + 'css/blank.gif) repeat'
											},
											'events': {
												'click': function(){
													if(getCoverParentA(this)){
														if(getCoverParentA(this).hasClass('ajax')){
															getCoverParentA(this).fireEvent('click');
														} else {
															document.location.href = getCoverParentA(this).get('href');
														}
													}
												},
												'mouseenter': function(){
													if(getCoverParentA(this)){
														if(!getCoverParentA(this).hasClass('covered') && !getCoverParentA(this).hasClass('active')){
															getCoverParentA(this).addClass('covered');
														}
													}
												},
												'mouseleave': function(){
													if(getCoverParentA(this)){
														getCoverParentA(this).removeClass('covered');
														
													}
												}
											}
										}).inject(par_a.getParent());
									}
								}
							}
						});
					}
				});
			});
		}		
	}
}







/****************************************************
* Initialise Carousels								*
*													*
*****************************************************/

function initCarousels(){
	var leftBut, rightBut, carouselArr = [], numCarousels = 0;
	if(carouselHolders.length > 0){
		$each(carouselHolders, function(car,ind){
			numCarousels += $$(car.toString()).length;
		});
	}
	
	if(numCarousels > 0){	
		var carScript = new Asset.javascript(root + 'js/carousel.js', {
			onload: function(){
				$each(carouselHolders, function(car,ind){
					$$(car.toString()).each(function(sel, ind2){
						leftBut = sel.getElements('.left-button');
						rightBut = sel.getElements('.right-button');
						if(leftBut.length > 0 && rightBut.length > 0){
							if(car == '#image-carousel' || car == '.recipe-carousel'){
								carouselArr[ind2] = new Carousel(sel, {leftButton:leftBut[0], rightButton:rightBut[0], viewable:5});
							} else {
								carouselArr[ind2] = new Carousel(sel, {leftButton:leftBut[0], rightButton:rightBut[0]});
							}
						} else {
							carouselArr[ind2] = new Carousel(sel, {paginate:true});
						}
					});				
				});
				
				initSponCarouselNav();
			}
		});
	}
}





/****************************************************
* Hide Empty Span Tags in Features					*
*													*
*****************************************************/

function hideFeaturesSpans(){
	var spans = $$('#featured span.image');
	$each(spans, function(span, ind){
		if(span.innerHTML == '' || span.innerHTML == '&nbsp;' || span.innerHTML == '&#160;'){
			span.setStyle('display','none');
		}
	});
}





/****************************************************
* Handle Flash Functions							*
* open_lightbox - to open a page in lBox from flash	*
* jump_target - to scroll to an element on the page	*
*													*
*****************************************************/

function open_lightbox(info){
	var fInfo = info.split(',');
	if(fInfo.length == 5){
		openLbPage(false, fInfo[0], fInfo[1], fInfo[2], fInfo[3], fInfo[4]);
	}
}


function jump_target(tgt){
	if($(tgt)){
		scrollToElement(tgt, 0);
	}
}





/****************************************************
* Initialise Site Search							*
*													*
*****************************************************/

function initSiteSearch(){
	if($('site-search')){
		var forms = $('site-search').getElements('form');
		var inputs = $('site-search').getElements('input[name=q]');
		if(forms.length > 0 && inputs.length > 0){
			forms[0].addEvent('submit', function(event){
				event.stop();
				if(inputs[0].value.length > 0){
					window.location.href = root + 'search.php?q=' + inputs[0].value;
				}
			});
		}
	}
}





/****************************************************
* On Page Load Functions							*
*													*
*****************************************************/

function init(){
	domReady = true;
	positionFooter();
	mafeFocusDiv();
	addMainTabEvents();
	initInputs();
	if(browser.isIE5 || browser.isIE6){ initPngHovers(); }
	getSifrElements();	
	initSmoothScroll();
	initHqAccordion();
	initTermsPrivacyAccordion();
	initTCsSupplyAccordion();
	initLanguagesAccordion();
	initSponsorshipAccordion();
	initEnEfficOpac();
	addSifrCovers();
	initSiteSearch();
	hideFeaturesSpans();
	if(browser.isIE5 || browser.isIE6){ doLiMainNavHovers(); }
	if(browser.isSafari){ fixSafariHoverBug(); }
	if(document.URL.indexOf('/admin/') >= 0){
		initLightbox();
	}
}


function fadeFinishedFuncs(){
	if(fadeFinished){
		initHelpQuestionsTab();
		initLightbox();
		initCarousels();
		initCustomerSatisfaction();
		var img_timer = imgsLoad.delay(4000);
	} else {
		var rTimer = fadeFinishedFuncs.delay(500);
	}
}


function initLoad(){
	checkPageLoad();
	fadeFinishedFuncs();
	if(browser.isIE5 || browser.isIE6){
		var ie6_css = new Asset.css(root + 'css/old-ie.css');		
		var ie6_js = new Asset.javascript(root + 'js/iepngfix_tilebg.js', {
			onload: function(){
				if(IEPNGFix){
					clearTimeout(IEPNGFix.update.timer);
					IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
				}
			}
		});
	}
}


function checkPageLoad(){
	if(focusLoaded && domReady){
		if($('in-focus-bg')){
			if(fImages.length == 2){
				$('in-focus-bg').setStyles({
					'background': 'url(' + fImages[1] + ') no-repeat center top',
					'-webkit-background-size': '2000px 2500px'
				});
				$('wrapper').setStyles({
					'background': 'url(' + fImages[0] + ') no-repeat center top',
					'-webkit-background-size': '2000px 2500px'
				});
			}
			clearLoading('#FFFFFE');
			startFocusEffect.delay(1000);
		} else {
			checkPageLoad.delay(100);
		}
	} else {
		checkPageLoad.delay(100);
	}
}


function imgsLoad(){
	var rules, ruleStyle, bg=false, bg_img;
	if(document.styleSheets){
		$each(document.styleSheets, function(style){
			if(style.href){
				if(style.href.indexOf('addthis.com') < 0){
					try {
						rules = style.rules || style.cssRules;
						$each(rules, function(rule, ind){
							if(rule.selectorText){					
								if(rule.selectorText.indexOf(':hover') >= 0){
									bg = false;
									if(rule.style.background){
										bg = rule.style.backgroundImage;
									} else if(rule.style['background-image']){
										bg = rule.style['background-image'];
									}
									
									if(bg){
										bg_img = bg.substring(bg.indexOf('images/'), bg.indexOf(')'));
										pImages.push(root + bg_img);
									}
								}
							}
						});
					} catch (err){}
				}
			}
		});
	}
	
	var loader = new Asset.images(pImages, {
		onProgress: function(counter, index){
		},
		onComplete: function(){
		}
	});
}




/****************************************************
* On Page UnLoad Functions							*
*													*
*****************************************************/

function memoryClean(e){
}





/****************************************************
* Load In Focus Image								*
*													*
*****************************************************/

function loadInFocusImg(){
	var loader = new Asset.images(fImages, {
		onProgress: function(counter, index){
		},
		onComplete: function(){			
			focusLoaded = true;
		}
	});
}




writeJsStyles(1);
loadInFocusImg();
window.addEvent('domready', function() { init(); });
window.addEvent('load', function() { initLoad(); });
window.addEvent('unload', function() { memoryClean(); });