// MooTools plugins for Bord Gais Energy



/****************************************************
* Global Vars and Prototypes						*
*													*
*****************************************************/

var browser, directory, sifrReplaced = 0;
var sIFR = false;
if(typeof(window[IEPNGFix]) == "undefined"){
	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', '.ccm-video-carousel'];
var currentLocation = 'homepage';
var hoverTimer, csTimer1, csTimer2, oTimer;
var pageTracker = false;
var lightBoxGallery = [];
var homepage_carousel = false;
var homepage_carousel_new = false;
var homepage_banner = false;
var isHomepage = false;
var homeTeamRobot = false;

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

var bcExp, modVP, modExp, modCon, brightcove_js;


String.prototype.endsWith = function(str){ return (this.match(str+"$")==str); }
Element.implement({
    toJSON: function(){
        var json = {};
        this.getElements('input, select, textarea', true).each(function(el){
            if (!el.name || el.disabled || el.type == 'submit' || el.type == 'reset' || el.type == 'file') return;
            var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
                return opt.value;
            }) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
            $splat(value).each(function(val){
                if (typeof val != 'undefined') {
                    json[el.name] = val;
                }
            });
        });
        return json;
    }
});

//$('myform').toJSON();


if(document.styleSheets){
	$each(document.styleSheets, function(style, ind){
		var rules = style.rules || style.cssRules;
		$each(rules, function(rule, ind2){
			if(rule.selectorText == '#wrapper'){
				var bg = false, bg_img;

				if(rule.style.backgroundImage){
					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(')'));
					bg_img = bg_img.replace(/"/g, '');
					if(site_url.toString().indexOf('bordgaisenergybookclub.ie') >= 0){
						fImages = ['/wp-content/themes/bookclub/' + bg_img, '/wp-content/themes/bookclub/' + bg_img.replace(/.jpg/, '_focus.jpg')];
					} else {
						fImages = [root + bg_img, root + bg_img.replace(/.jpg/, '_focus.jpg')];
					}
				}
			}
		});
	
		if(style.href){
			if(style.href.endsWith('homepage.css')){
				isHomepage = true;
			}
		}
	});
}




/****************************************************
* 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('/hometeam/') >= 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.isChrome	= (this.isSafari && (agent.indexOf('chrome/') != -1));
	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.isIE9		= (agent.indexOf('msie 9.') != -1);
	this.isIE8		= (agent.indexOf('msie 8.') != -1);
	this.isIE7		= (agent.indexOf('msie 7.') != -1);
	this.isIE6		= (agent.indexOf('msie 6.') != -1);
	this.isIE5		= (agent.indexOf('msie 5.') != -1);
	this.isIphone	= (agent.indexOf('iphone') != -1 || agent.indexOf('ipod') != -1 || agent.indexOf('ipad') != -1);
	this.isMobile	= (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(agent));  
}

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;
		}
	}
	
	isBC = false;
	if(site_url.toString().indexOf('bordgaisenergybookclub.ie') >= 0){
		directory = dir = root;
		isBC = true;
	}
	
	if(w==1){ 
		document.write('<link href="' + dir + 'css/js-dependant.css" rel="stylesheet" type="text/css" media="screen" />'); 
		if(isBC && (browser.isIE6 || browser.isIE7) ) { document.write('<link href="' + dir + 'css/js-dependant-bc-ie6.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.isChrome){
			document.write('<link href="' + dir + 'css/chrome.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]; }
}





/****************************************************
* Brightcove Functionality							*
*													*
*****************************************************/

function onTemplateReady(evt){
}

function onContentLoad(evt){
}

function onVideoLoad(evt){
}

function onVideoBegin(evt){
}

function onMediaComplete(evt){
	closeLightBox();
	/*if(modVP){
		modVP.cueVideo(modVP.getCurrentVideo().id);
	}*/
}
 
function onTemplateLoaded(experienceID){
	bcExp = brightcove.getExperience(experienceID);
	modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
	modExp = bcExp.getModule(APIModules.EXPERIENCE);
	modCon = bcExp.getModule(APIModules.CONTENT);
	
	modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
	modExp.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);
	modCon.addEventListener(BCContentEvent.VIDEO_LOAD, onVideoLoad);
	modVP.addEventListener(BCMediaEvent.BEGIN, onVideoBegin);
	modVP.addEventListener(BCMediaEvent.COMPLETE, onMediaComplete);
}




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

function loadLightboxVideo(flv){
	if(flv.indexOf('/flash/video-player/') >= 0){
		try {
			var root_flv = root + flv.substring(flv.indexOf('flash/video-player/'));
			getFlashMovie('video-player-swf').changeURL(root_flv);
		} catch(er){
			loadLightboxVideo.delay(500, this, [flv]);
		}
	} else {
		alert('Flash Videos must sit in the /flash/video-player/ folder in the root directory');
	}
}

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');
				}
			});
		}
	});
	
	var dds = $(document.body).getElements('.styled-select-options, .lightbox-gallery-move, .help-icon');
	dds.each(function(dd, index){
		dd.setStyles({ 'opacity': 0, 'left': -99999, 'top': -99999 });
	});
	
	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'), href;
		$each(as, function(a,i){
			if(a.get('target')){ target = a.get('target'); }
			else { target = '_self'; }
			if(a.get('href')){
				href = a.get('href').toString();
			} else {
				href = '';
			}
			
			if(!a.hasClass('no-lb') && target != '_blank' && href.indexOf('mailto:') < 0 && href != '#' && !href.endsWith('#')){
				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(a.hasClass('close-lb')){
				a.addEvents({
					'keypress': function(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ event.stop(); $('lightbox-close-but').fireEvent('click'); } } },
					'click': function(event){ event.stop(); $('lightbox-close-but').fireEvent('click'); }
				});
			}
		});
	}
	
	if($('lb-body')){
		$('lb-body').removeEvents('keypress');
		$('lb-body').removeEvents('click');
		$('lb-body').addEvents({
			'keypress': function(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ resizeLightBox(); } } },
			'click': function(event){ resizeLightBox(); }
		});
	}
}

function setLightboxRels(a){
	var optArr, ta, rel = {}
	
	if(a.get('rel')){
		a.set('rel', a.get('rel').replace(/; /g, ';'));
		optArr = a.get('rel').split(';');
		$each(optArr, function(el, i){
			ta = el.split(':');
			rel[ta[0]] = ta[1];
		});
	}
	
	return rel;
}

function openLightBox(el, url, x, y, width, height, growWidth, growHeight){	
	if($('wrapper') && $('header')){
		var coords= {}, hCoords, flash, lbFooterCount, fullLbCount;
		var opened = true;
		var duration = 300;
		var openWidth = 940, openLeft, found_at = -1, heightOffset;
		var isImage = false, isVideo = false, fromGallery = false, isBookClub = false;
		var groupName = '', lUrl = '';
		var lbDivs = $('lightbox-tmp').getElements('div');
		var rels = {
			width: null,
			height: null
		};
		if(browser.isIE){ duration = 0; }
		
		var href;
		if(el){
			if(el.get('href')){ href = el.get('href'); }
			else if(url){ href = url; }
			if(el.hasClass('lightbox-gallery-move')){ fromGallery = true; }
			rels = setLightboxRels(el);
			
		} else if(url){
			href = url;
		}
		
		if(href.endsWith('.jpg') || href.endsWith('.gif') || href.endsWith('.png') || href.indexOf('getImage.php') >= 0){
			isImage = true;
		}
		
		if(href.endsWith('.flv')){
			isVideo = true;
		}
		
		if(el){
			if(el.hasClass('bookclub')){
				isBookClub = true;
			}
		}
		
		if(!$('lightbox').get('open') || $('lightbox').get('open') == 0){
			opened = false;
			$('lightbox').set('open', 1);
			if(url){
				flash = $('flash-banner') ? $('flash-banner') : $('tab-1-flash-holder');
				if(flash){
					coords.left = flash.getPosition($('wrapper')).x.toInt() + x.toInt();
					coords.top = flash.getPosition($('wrapper')).y.toInt() + y.toInt();
				} else {
					coords.left = x.toInt();
					coords.top = 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);
				$(document.body).focus();
			}
		});
		
		var growFX = new Fx.Elements([elements[0], elements[1]], {
			duration: 600,
			transition: Fx.Transitions.Cubic.easeOut,
			onComplete: function(){
				if(!isVideo){
					$('lightbox-content-inner').innerHTML = $('lightbox-tmp').innerHTML;				
				} else {
					var video_player = new Swiff(root + 'flash/video-player/video_player.swf', {
						id: 'video-player-swf',
						width: 504,
						height: 335,
						container: $('lightbox-content-inner'),
						params: {
							play: 'true',			
							loop: 'true',			
							wmode: 'transparent',
							menu: 'true',
							scale: 'showall',
							salign: 'tl',
							bgcolor: '#FFFFFF',
							devicefont: 'false',
							allowfullscreen: 'true',
							allowscriptaccess: 'sameDomain',
							allownetworking: 'all'
						},
						vars: {},
						callBacks: {
							onFlashLoad: function() { }
						}														
					});
					
					loadLightboxVideo(href);
				}	
				
				$('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));
				
				lightBoxGallery.empty();
				
				if(el && isImage){
					if(el.get('href') && el.get('rel')){
						if(el.get('rel').contains('[') && el.get('rel').contains(']')){
							groupName = el.get('rel').substring(el.get('rel').indexOf('['), el.get('rel').indexOf(']')+1);
						
							$each($(document.body).getElements('a.lb'), function(a,i){
								if(a.get('href') && a.get('rel')){
									if(a.get('rel').contains(groupName)){
										lUrl = a.get('href').toLowerCase();
										if(lUrl.endsWith('.gif') || lUrl.endsWith('.jpg') || lUrl.endsWith('.png')){
											if(a.get('href') == el.get('href')){
												found_at = lightBoxGallery.length;
											}
											
											lightBoxGallery.push(a);											
										}
									}
								}
							});
							
							if(lightBoxGallery.length > 1 && found_at >= 0){
								if(found_at > 0){
									var lb_gallery_left = new Element('a', {
										'id': 'lightbox-gallery-move-left',
										'class': 'lightbox-gallery-move',
										'html': '<span></span>',
										'events': {
											'mouseover': function(){
												this.getElement('span').setStyle('visibility', 'visible');
											},
											'mouseout': function(){
												this.getElement('span').setStyle('visibility', 'hidden');
											}
										}
									}).inject($('lightbox-content-inner'));
									
									lb_gallery_left.hideFocus = true;
									
									if(lightBoxGallery[found_at-1].get('href')){
										$('lightbox-gallery-move-left').set('href', lightBoxGallery[found_at-1].get('href'));
									}
									
									if(lightBoxGallery[found_at-1].get('class')){
										$('lightbox-gallery-move-left').addClass(lightBoxGallery[found_at-1].get('class'));
									}
									
									if(lightBoxGallery[found_at-1].get('rel')){
										$('lightbox-gallery-move-left').set('rel', lightBoxGallery[found_at-1].get('rel'));
									}
								}
								
								if(found_at < lightBoxGallery.length - 1){
									var lb_gallery_right = new Element('a', {
										'id': 'lightbox-gallery-move-right',
										'class': 'lightbox-gallery-move',
										'html': '<span></span>',
										'events': {
											'mouseover': function(){
												this.getElement('span').setStyle('visibility', 'visible');
											},
											'mouseout': function(){
												this.getElement('span').setStyle('visibility', 'hidden');
											}
										}
									}).inject($('lightbox-content-inner'));
									
									lb_gallery_right.hideFocus = true;
									
									if(lightBoxGallery[found_at+1].get('href')){
										$('lightbox-gallery-move-right').set('href', lightBoxGallery[found_at+1].get('href'));
									}
									
									if(lightBoxGallery[found_at+1].get('class')){
										$('lightbox-gallery-move-right').addClass(lightBoxGallery[found_at+1].get('class'));
									}
									
									if(lightBoxGallery[found_at+1].get('rel')){
										$('lightbox-gallery-move-right').set('rel', lightBoxGallery[found_at+1].get('rel'));
									}
								}
								
								$$('.lightbox-gallery-move span').setStyle('margin-top', Math.max(0, ($('lightbox-content-inner').getSize().y/2).toInt() - 16));
							}
						}
					}
				}
				
				attachLbEvents();
				initLbForms();			
				blendFX.start(o2);
				if(typeof(window['brightcove']) != "undefined"){
					brightcove.createExperiences();
				}				
			}
		});						
		
		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(isImage){
			openLeft = hCoords.left + 3 + ((960 - $('lightbox-tmp').getElements('img')[0].width) / 2).toInt();
		}
		
		if(isVideo){
			openLeft = hCoords.left + 3 + ((960 - 504) / 2).toInt();
		}
		
		fullLbCount = lbDivs.filter(function(elm) {
			return (elm.id.test(/^lb-body/i) && elm.className.test(/full-lb/i));
		});
		
		if(isBookClub){					
			if(fullLbCount.length > 0){
				openLeft = hCoords.left + 3 + ((960 - 955) / 2).toInt();
			} else {				
				openLeft = hCoords.left + 3 + ((960 - 680) / 2).toInt();
			}				
		}
		
		if(growWidth || rels.width){
			openLeft = hCoords.left + 3 + ((960 - (growWidth ? growWidth : rels.width.toInt())) / 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(isImage){
			openWidth = $('lightbox-tmp').getElements('img')[0].width;		
		}
		
		if(isVideo){
			openWidth = 504;		
		}
		
		if(isBookClub){
			if(fullLbCount.length > 0){
				openWidth = 938; 
			} else {				
				openWidth = 663;
			}			
		}
		
		if(growWidth || rels.width){
			openWidth = (growWidth ? growWidth.toInt() : rels.width.toInt());
		}
			
		$('lightbox-tmp').setStyle('width', openWidth);
		heightOffset = 0;			
		lbFooterCount = lbDivs.filter(function(elm) {
			return elm.id.test(/^lb-footer/i);
		});

		if(lbFooterCount.length > 0){
			heightOffset = 10;
		}
		
		o1[1] = {width: openWidth, height: $('lightbox-tmp').getSize().y - heightOffset};
		
		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, growWidth, growHeight){
	var href, isImage = false, isVideo = false;
	if(el){
		if(el.get('href')){ href = el.get('href'); }
		else if(url){ href = url; }
	} else if(url){
		href = url;
	}
	
	if(pageTracker){
		pageTracker._trackEvent('Lightbox', 'Open', href);
	} else if(typeof(window['_gaq']) != 'undefined'){
		_gaq.push(['_trackEvent', 'Lightbox', 'Open', href]);
	}
	
	if(href.endsWith('.jpg') || href.endsWith('.gif') || href.endsWith('.png') || href.indexOf('getImage.php') >= 0){
		isImage = true;
	}
	
	if(href.endsWith('.flv')){
		isVideo = true;
	}
	
	if(isImage){
		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, growWidth, growHeight);
			}
		});		
		
	} else if(isVideo){
		$('lightbox-tmp').innerHTML = '';
		
		var lightbox_video_holder = new Element('div', {
			'id': 'lightbox-video-holder',
			'styles': {
				'width': 504,
				'height': 335
			}
		}).inject($('lightbox-tmp'));

		openLightBox(el, url, x, y, width, height, growWidth, growHeight);
		
	} 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, growWidth, growHeight);
				}
			},
			onFailure: function(xhr){ $('lightbox').set('busy', 0); }
		}).send();
	}
}

function openLbPage(el, url, x, y, width, height, growWidth, growHeight){	
	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, growWidth, growHeight);
		}
	});
	
	$('lightbox').set('busy', 1);
	
	if(el){
		if(el.hasClass('to-center')){
			readLbHtml(el, url, x, y, width, height, growWidth, growHeight);
		} 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.backgroundImage){
							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().getParent().hasClass('purple-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().getParent().hasClass('purple-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 && !browser.isIE9){
			lEffect.start({opacity: [0, 1]});
		} else {
			$('wrapper').setStyle('opacity',1);
		}
	}
}








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

function getSizeX(){
	var w = 0;
	if(!window.innerWidth){
		if(!(document.documentElement.clientWidth === 0)){ w = document.documentElement.clientWidth; }
		else { w = document.body.clientWidth; }
	} else { w = window.innerWidth; }
	
	return w;
}

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(first){
	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
			});
		}
	}
	
	if(first){
		window.addEvent('resize', function() { positionFooter(); });
	}
}




/****************************************************
* 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'));
		
		if($('overviews')){
			var overviewsCover = new Element('div', {			
				'id': 'overviews-cover'
			}).inject($('overviews'));
		}
	}
}


function showHiddenFlash(obj){
	obj.style.visibility = 'visible';
}


function showPreHiddenElements(){
	if($('wrapper')){
		var pHiddens = $('wrapper').getElements('.pre-hidden');
		var fEffect, fx = [], objs;
		var duration = 250;
		
		if(browser.isIE){ duration = 0; }
		if(browser.isIphone){
			duration = 0;
		}
		
		$each(pHiddens, function(hid, index){
			if($('header') && $('site-search')){
				if(hid == $('header')){
					$('site-search').setStyles({
						'position': 'relative',
						'left': 0,
						'top': 0
					});
				}
			}
			
			if(browser.isIE){
				objs = hid.getElements('object');
				if(objs.length > 0){
					$each(objs, function(obj, ind){
						showHiddenFlash.delay(500, this, [obj]);
					});
				}
			}
								 
			fEffect = new Fx.Morph(hid, {
				duration: duration,
				transition: Fx.Transitions.Linear,
				onComplete: function(){
					if(index == pHiddens.length - 1){
						fadeFinished = true;
						var css = new Asset.css(root + 'css/loading-finished.css', {});
						if($('overviews-cover')){
							$('overviews-cover').destroy();
						}
						
						if($('iphone-app-feedback')){							
							$('iphone-app-feedback').erase('id');
						}
					}
				}
			});
			
			fx[index] = fEffect;
		});
		
		$each(fx, function(eff, index){
			if(browser.isIphone){
				if(index == pHiddens.length - 1){
					fadeFinished = true;
					var css = new Asset.css(root + 'css/loading-finished.css', {});
					if($('overviews-cover')){
						$('overviews-cover').destroy();
					}
					
					if($('iphone-app-feedback')){
						$('iphone-app-feedback').erase('id');
					}
				}
			} else {
				eff.start.delay(index * 250, eff, {'opacity': [0, 1]}); 
			}			
		});
		
		if(pHiddens.length <= 0){
			fadeFinished = true;
		}
	}
}


function startFocusEffect(){
	if(browser.isIphone){
		showPreHiddenElements();
		return false;
	}
	
	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'));
			}
			
			if(root.indexOf('bookclub.ie') >= 0){
				$each($$('#help-and-questions-topics a, #help-and-questions-popular a'), function(a, index){
					if(a.get('href').indexOf('help-and-questions') >= 0){
						a.set('href', 'http://www.bordgaisenergy.ie/' + a.get('href').substring(a.get('href').indexOf('help-and-questions')));
					}
				});
			}
		}
	}).send();
}

function loadHqTopicMenu(section, list, bg){
	if(popularQuestions[section]){
		if(popularQuestions[section].indexOf('</ul>') >= 0){
			$('help-and-questions-popular').innerHTML = popularQuestions[section];
			if(root.indexOf('bookclub.ie') >= 0){
				$each($$('#help-and-questions-topics a, #help-and-questions-popular a'), function(a, index){
					if(a.get('href').indexOf('help-and-questions') >= 0){
						a.set('href', 'http://www.bordgaisenergy.ie/' + a.get('href').substring(a.get('href').indexOf('help-and-questions')));
					}
				});
			}
			
		} 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.replace(/á/g, '&aacute;');
				$('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);
			});
			
			var links_a = [];
			$each(links, function(link, index){
				if(link.attributes[0]){
					if(link.attributes[0].firstChild){
						if(link.attributes[0].firstChild.nodeValue){
							links_a.push(link.attributes[0].firstChild.nodeValue.toString());
						}
					}
				}
			});
			
			if(links_a.length > 0){
				loadHqTopicMenu(section, links_a, bg);
			} else {
				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(event){
													if(getCoverParentA(this)){
														if(getCoverParentA(this).hasClass('ajax')){
															getCoverParentA(this).fireEvent('click');
														} else {
															if(getCoverParentA(this).get('target')){
																if(getCoverParentA(this).get('target').indexOf('blank') >= 0){
																	var newWindow = window.open(getCoverParentA(this).get('href'), '_blank');
																	newWindow.focus();
																	return false;
																} else {
																	document.location.href = getCoverParentA(this).get('href');
																}
															} 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 || $('carousel-wrapper')){	
		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 {	
							if(car == '.ccm-video-carousel'){
								carouselArr[ind2] = new Carousel(sel, {paginate:true, autoAnimate:false, paginateDiv:true, replicate:false});
							} else {
								if(car == '.homepage #featured'){
									if($('homepage-featured-items')){}
									else {
										carouselArr[ind2] = new Carousel(sel, {paginate:true});
									}
								} else {
									carouselArr[ind2] = new Carousel(sel, {paginate:true});
								}
							}
						}
					});				
				});
				
				initSponCarouselNav();
				
				if($('carousel-wrapper')){
					var newSponsorshipCarousel = new SponsorshipCarousel($('carousel-wrapper'), {});
				}
			}
		});
	}
}





/****************************************************
* 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){
		if(fInfo[0].indexOf('hometeam/tv-advertisement.php') >= 0){
			openLbPage(false, fInfo[0], fInfo[1], fInfo[2], fInfo[3], fInfo[4], 640);
		} else {
			openLbPage(false, fInfo[0], fInfo[1], fInfo[2], fInfo[3], fInfo[4]);
		}
	} else if(fInfo.length == 6){
		openLbPage(false, fInfo[0], fInfo[1], fInfo[2], fInfo[3], fInfo[4], fInfo[5]);
	}
}


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





/****************************************************
* Print Specific Elements on a Page					*
*													*
*****************************************************/

function printContent(div){
	if($(div)){
		var windowObj = window.open('', 'printWindow', 'width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes');
		windowObj.document.writeln($(div).innerHTML);
		windowObj.document.close();
		windowObj.focus();
		windowObj.print();
		windowObj.close();
	}
}





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

function initSiteSearch(){
	if($('site-search')){
		var forms = $('site-search').getElements('form');
		var inputs = $('site-search').getElements('input[name=q]');
		//var selects = $('site-search').getElements('select[name=ul]');
		if(forms.length > 0 && inputs.length > 0){
			forms[0].addEvent('submit', function(event){
				event.stop();
				if(inputs[0].value.length > 0){
					if(site_url.toString().indexOf('bordgaisenergybookclub.ie') >= 0){
						//window.location.href = 'http://www.bordgaisenergy.ie/search.php?q=' + inputs[0].value + '&ul=' + selects[0].value;
						window.location.href = 'http://www.bordgaisenergy.ie/search.php?q=' + inputs[0].value;
					} else {
						//window.location.href = root + 'search.php?q=' + inputs[0].value + '&ul=' + selects[0].value;
						window.location.href = root + 'search.php?q=' + inputs[0].value;
					}
				}
			});
		}
	}
}



/****************************************************
* Apply a hover to Your Country Your Call on top	*
* level of the Sponsorship Page						*
*													*
*****************************************************/

function initYourCountryYourCallHover(ref){
	if($('your-country-your-call')){
		$('your-country-your-call').setStyles({
			'height': $('your-country-your-call').getParent().getSize().y - 20,
			'top': 20
		});
		
		if(!ref){
			$('your-country-your-call').addEvents({
				'mouseover': function(){
					this.getParent().setStyle('color', '#000');
				},
				'mouseout': function(){
					this.getParent().setStyle('color', '#666');
				}
			});
			
			window.addEvent('resize', function() { initYourCountryYourCallHover(true); });
		}
	}
}




/****************************************************
* Open Lightbox once element fading aminmation is	*
* complete if 'lb' query set in URL					*
*													*
*****************************************************/

function openLightboxFromUrl(){	
	if(lbFormsJS){
		if($('wrapper') && gup('lb')){
			var last_part, first_a = false, url_lb = gup('lb');
			if(url_lb.indexOf('/') >= 0){
				last_part = url_lb.substring(url_lb.lastIndexOf('/') + 1);
			} else {
				last_part = url_lb;
			}
			
			if(last_part.indexOf('.php') >= 0){
				first_a = $('wrapper').getElement('a[href$=' + last_part + ']');
			} else {
				first_a = $('wrapper').getElement('a[href$=' + last_part + '.php]');
			}
			
			if(first_a){
				openLbPage(first_a);
			}
		}
		
	} else {
		var rTimer = openLightboxFromUrl.delay(250);
	}
}







/****************************************************
* Styled Vertical Scrollbars						*
*													*
*****************************************************/

var ScrollBar = new Class({

	Implements: [Events, Options],

	options: {
		maxThumbSize: 15,
		wheel: 8,
		arrows: true,
		homepage: false
	},

	initialize: function(main, content, options){
		this.setOptions(options);
		
		this.main = $(main);
		this.content = $(content);
		
		if (this.options.arrows == true){
			this.arrowOffset = 30;
		} else {
			this.arrowOffset = 0;
		}				

		this.vScrollbar = new Element('div', {
				'class': 'vScrollbar'
			}).injectAfter(this.content);				

		if (this.options.arrows == true){				
			this.arrowUp = new Element('div', {
					'class': 'arrowUp'
				}).injectInside(this.vScrollbar);
		}	

		this.vTrack = new Element('div', {
				'class': 'vTrack'
			}).injectInside(this.vScrollbar);
			
		this.vThumb = new Element('div', {
				'class': 'vThumb'
			}).injectInside(this.vTrack);

		if (this.options.arrows == true){				
			this.arrowDown = new Element('div', {
					'class': 'arrowDown'
				}).injectInside(this.vScrollbar);
		}
		
		this.bound = {
			'vStart': this.vStart.bind(this),				
			'end': this.end.bind(this),
			'vDrag': this.vDrag.bind(this),			
			'wheel': this.wheel.bind(this),
			'vPage': this.vPage.bind(this)				
		};

		this.vPosition = {};
		this.hPosition = {};			
		this.vMouse = {};
		this.hMouse = {};			
		this.update();
		this.attach();
	},

	update: function(){
		
		this.main.setStyle('height', this.content.offsetHeight);
		this.vTrack.setStyle('height', this.content.offsetHeight - this.arrowOffset);
		
		// Remove and replace vertical scrollbar			
		if (this.content.scrollHeight <= this.main.offsetHeight) {
			this.vScrollbar.setStyle('display', 'none');				
		} else {
			if(!this.options.homepage){
				this.content.setStyle('width', this.content.offsetWidth - 15);
			}
			this.vScrollbar.setStyle('display', 'block');			
		}		

		// Vertical
		this.vContentSize = this.content.offsetHeight;
		this.vContentScrollSize = this.content.scrollHeight;
		this.vTrackSize = this.vTrack.offsetHeight;

		this.vContentRatio = this.vContentSize / this.vContentScrollSize;

		if(this.options.homepage){
			this.vThumbSize = this.vThumb.offsetHeight;
			this.vScrollRatio = (this.vContentScrollSize - this.vContentSize) / (this.vTrackSize - this.vThumbSize);
		} else {
			this.vThumbSize = (this.vTrackSize * this.vContentRatio).limit(this.options.maxThumbSize, this.vTrackSize);
			this.vScrollRatio = this.vContentScrollSize / this.vTrackSize;
		}

		if(!this.options.homepage){
			this.vThumb.setStyle('height', this.vThumbSize);
		}

		this.vUpdateThumbFromContentScroll();
		this.vUpdateContentFromThumbPosition();
		
	},

	vUpdateContentFromThumbPosition: function(){		
		this.content.scrollTop = this.vPosition.now * this.vScrollRatio;
	},

	vUpdateThumbFromContentScroll: function(){
		this.vPosition.now = (this.content.scrollTop / this.vScrollRatio).limit(0, (this.vTrackSize - this.vThumbSize));
		this.vThumb.setStyle('top', this.vPosition.now);
	},

	attach: function(){
		this.vThumb.addEvent('mousedown', this.bound.vStart);
		if (this.options.wheel) this.content.addEvent('mousewheel', this.bound.wheel);
		this.vTrack.addEvent('mouseup', this.bound.vPage);
		
		if (this.options.arrows == true){
			this.arrowUp.addEvent('mousedown', function(event){
					this.interval = (function(event){
					this.content.scrollTop -= this.options.wheel;
					this.vUpdateThumbFromContentScroll();
				}.bind(this).periodical(40))
			}.bind(this));
		
			this.arrowUp.addEvent('mouseup', function(event){
				$clear(this.interval);
			}.bind(this));
		
			this.arrowUp.addEvent('mouseout', function(event){
				$clear(this.interval);
			}.bind(this));
					
			this.arrowDown.addEvent('mousedown', function(event){
					this.interval = (function(event){
					this.content.scrollTop += this.options.wheel;
					this.vUpdateThumbFromContentScroll();
				}.bind(this).periodical(40))
			}.bind(this));
		
			this.arrowDown.addEvent('mouseup', function(event){
				$clear(this.interval);
			}.bind(this));
		
			this.arrowDown.addEvent('mouseout', function(event){
				$clear(this.interval);
			}.bind(this));
		}			
					
	},
	
	wheel: function(event){
		this.content.scrollTop -= event.wheel * this.options.wheel;
		this.vUpdateThumbFromContentScroll();
		event.stop();
	},

	vPage: function(event){
		if (event.page.y > this.vThumb.getPosition().y) this.content.scrollTop += this.content.offsetHeight;
		else this.content.scrollTop -= this.content.offsetHeight;
		this.vUpdateThumbFromContentScroll();
		event.stop();
	},

	vStart: function(event){
		this.vMouse.start = event.page.y;
		this.vPosition.start = this.vThumb.getStyle('top').toInt();
		document.addEvent('mousemove', this.bound.vDrag);
		document.addEvent('mouseup', this.bound.end);
		this.vThumb.addEvent('mouseup', this.bound.end);
		event.stop();
	},

	end: function(event){
		document.removeEvent('mousemove', this.bound.vDrag);
		document.removeEvent('mouseup', this.bound.end);
		this.vThumb.removeEvent('mouseup', this.bound.end);
		event.stop();
	},

	vDrag: function(event){
		this.vMouse.now = event.page.y;
		this.vPosition.now = (this.vPosition.start + (this.vMouse.now - this.vMouse.start)).limit(0, (this.vTrackSize - this.vThumbSize));
		this.vUpdateContentFromThumbPosition();
		this.vUpdateThumbFromContentScroll();
		event.stop();
	}	

});




/****************************************************
* Home Team Robot Functionality						*
*													*
*****************************************************/

function homepage_robots_action(action){
	var flash = getFlashMovieObject('t1Flash'), el = false;
	if(flash && homeTeamRobot){
		el = browser.isIE ? flash.parentNode : flash;		
		if(el){
			switch(action){
				case 'expand':
					el.setStyles({
						'width': 953,
						'height': el.getCoordinates().top + el.getSize().y,
						'margin-top': browser.isIE ? -1 * (el.getCoordinates().top + el.getStyle('padding-top').toInt()) : -1 * el.getCoordinates().top
					});
					
					if(browser.isIE){
						flash.width = 953;
						flash.height = el.getStyle('height').toInt();
						if(browser.isIE5 || browser.isIE6){
							el.getParent('li').setStyles({
								'position': 'relative',
								'z-index': 3						
							});
						}
					}
					
					el.getParent('.pop').setStyle('z-index', 3);
					break;
				case 'collapse':
					el.setStyles({
						'width': 953,
						'height': 266,
						'margin-top': ''
					});
					
					if(browser.isIE){
						flash.width = 953;
						flash.height = 266;
						el.getParent('li').setStyles({
							'position': '',
							'z-index': ''						
						});
					}										
					
					el.getParent('.pop').setStyle('z-index', '');
					break;
				case 'follow':
					homeTeamRobot.setCookie('homepage');
					window.location.href = root + 'hometeam/?flash=1&pbot=hp';
					break;
				case 'exit':
					el.setStyles({
						'width': '',
						'height': 266,
						'margin-top': ''
					});
					
					if(browser.isIE){
						flash.width = 757;
						flash.height = 266;
						el.getParent('li').setStyles({
							'position': '',
							'z-index': ''						
						});
					}
					
					el.getParent('.pop').setStyle('z-index', '');
					break;
			}
		}
	}
}

var HomeTeamRobot = new Class({

	Implements: [Events, Options],

	options: {
		minFlashVersion: 8,
		minWindowWidth: 980,
		jsVersionSlideTime: 3000
	},

	initialize: function(url, options){
		var htr = this;
		this.setOptions(options);
		this.robotHolder = null;
		this.robotHolderWidth = null;
		this.url = url.indexOf('?') >= 0 ? url.substring(0, url.indexOf('?')) : url;
		this.windowSize = $(window).getSize().x;
		this.visible = false;
		this.section = null;
		this.flashVersion = Browser.Plugins.Flash.version >= this.options.minFlashVersion ? true : false;
		this.jsVersionOb = {};
		this.currentDialogue = 0;
		this.stayOnPage = false;
		this.calledClose = false;
		this.timer1 = null;
		this.timer2 = null;
		this.timer3 = null;
		
		if($('page-title')){
			if(fadeFinished){
				this.build();
				if(this.robotHolder){				
					this.fx = new Fx.Morph(this.robotHolder, {
						duration: 1200,
						transition: Fx.Transitions.Sine.easeOut,
						onComplete: function(){
							htr.visible = true;
							htr.startJsVersion();
							htr.initControls();
						}
					});
					
					this.populate();
					
					window.addEvent('resize', function() {
						if(htr.visible){
							htr.windowSize = $(window).getSize().x;
							htr.robotHolder.setStyle('width', Math.min(htr.robotHolderWidth, htr.robotHolderWidth - (htr.options.minWindowWidth - htr.windowSize)));
						}
					});
				}
			} else {
				this.timer1 = this.initialize.delay(1000, this, [url, options]);
			}
				
		} else if(isHomepage){
			if($('homepage-banner-enlarged')){
				$each($('homepage-banner-enlarged').getElements('.link a'), function(a, ind){
					if(a.get('href').indexOf('hometeam/?') >= 0 && a.get('href').indexOf('flash=1') >= 0 && a.get('href').indexOf('js=1') >= 0){
						a.addEvents({
							'click': function(){
								htr.setCookie('homepage');
							}
						});
					}
				});
			}
		}
	},
	
	build: function(){
		this.section = this.getSection(this.url);
		
		if(this.section && $('page-contents')){
			this.robotHolder = new Element('div', {
				'id': 'robotHolder'
			}).inject($('page-contents'));
				
			this.robotHolderContent = new Element('div', {
				'class': 'content'
			}).inject(this.robotHolder);
			
			this.robotHolderWidth = this.robotHolderContent.getSize().x;
		}
	},
	
	setCookie: function(val){
		if(Cookie.read('bordgaisenergybot_position')){ Cookie.dispose('bordgaisenergybot_position', { path:'/' }); }			
		this.cookie = Cookie.write('bordgaisenergybot_position', val ? val : this.section, { path:'/' });
	},
	
	populate: function(){
		var htr = this, robotReq, cookie, action = 'stop', energybot_flash;
		if(Cookie.read('bordgaisenergybot_position')){			
			if((Cookie.read('bordgaisenergybot_position') == 'homepage' || Cookie.read('bordgaisenergybot_position') == 'home-electricity') && this.section == 'home-team'){
				action = 'talk';
			} else if(Cookie.read('bordgaisenergybot_position') == 'home-team' && this.section == 'home-team-hq'){
				action = 'talk';
			} else if(Cookie.read('bordgaisenergybot_position') == 'home-team-hq' && this.section == 'energy-efficiency'){
				action = 'talk';
			} else if(Cookie.read('bordgaisenergybot_position') == 'energy-efficiency' && this.section == 'home-electricity'){
				action = 'talk';
			} else if(Cookie.read('bordgaisenergybot_position') == 'hide'){
				action = 'hide';
			}
			
			if(action == 'talk'){
				Cookie.dispose('bordgaisenergybot_position', { path:'/' });
			}
		} else {
		}
		
		robotReq = new Request.HTML({
			method: 'get',
			url: root + 'energybots/' + htr.section + '.php?action=' + action,
			noCache: true,
			onSuccess: function(tree, elements, html, js){
				var content = elements.filter(function(elm) {
					if(htr.flashVersion){
						return elm.className.test(/^flash-content/i);
					} else {
						return elm.className.test(/^js-content/i);
					}
				});
				
				if(content.length > 0){
					if(htr.flashVersion && typeof(window['energybot_flash_obj']) != 'undefined'){
						energybot_flash = new Swiff(energybot_flash_obj.src, {
							id: 'energybotFlash',
							width: energybot_flash_obj.width,
							height: energybot_flash_obj.height,
							container: htr.robotHolderContent,
							properties: {
								style: energybot_flash_obj.style
							},
							params: {
								play: 'true',			
								loop: 'false',			
								wmode: 'transparent',
								menu: 'false',
								scale: 'showall',
								salign: 'tl',
								allowfullscreen: 'false',
								allowscriptaccess: 'sameDomain',
								allownetworking: 'all'
							},
							vars: energybot_flash_obj.vars,
							callBacks: {
								onFlashLoad: function() { getFlashMovieObject('energybotFlash').Play(); },
								robots_action_hide: function() {
									htr.setCookie('hide');
									htr.close(true);
								},
								robots_action_play: function() { },
								robots_action_follow: function() {
									htr.setCookie();
									window.location.href = energybot_flash_obj.vars.href;
								}								
							}
						});
						
						htr.robotHolder.setStyle('width', Math.min(htr.robotHolderWidth, htr.robotHolderWidth - (htr.options.minWindowWidth - htr.windowSize)));

					} else {
						htr.robotHolderContent.set('html', content[0].innerHTML);
						htr.robotText = htr.robotHolder.getElement('.text');
						htr.robotTextInner = htr.robotHolder.getElement('.text .inner');
						htr.robotTextDialogue = htr.robotHolder.getElement('.text .dialogue');
						htr.robotTextDialogueTrs = htr.robotHolder.getElements('.text .dialogue tr');
						htr.robotTextFinish = htr.robotHolder.getElement('.text .finish');
						htr.robotImage = htr.robotHolder.getElement('.image');
						htr.robotClose = htr.robotHolder.getElement('.close .inner a');
						htr.robotPlay = htr.robotHolder.getElement('.play .inner a');
						htr.fx.start({
							'width': Math.min(htr.robotHolderWidth, htr.robotHolderWidth - (htr.options.minWindowWidth - htr.windowSize))
						});
					}										
				}
			}
		}).send();
	},
	
	getSection: function(url){
		if(url.endsWith('/hometeam/') || url.endsWith('/hometeam/index.php')){
			return 'home-team';
		} else if(url.indexOf('/help-and-questions/home-services/') >= 0 || url.indexOf('/help-and-questions/hometeam/') >= 0){
			return 'home-team-hq';
		} else if(url.endsWith('/energy-efficiency/home/') || url.endsWith('/energy-efficiency/home/index.php')){
			return 'energy-efficiency';
		} else if(url.endsWith('/home/electricity/join/') || url.endsWith('/home/electricity/join/index.php')){
			return 'home-electricity';
		} else if(isHomepage){
			return 'homepage';
		} else {
			return false;
		}
	},		
	
	startJsVersion: function(){
		var htr = this, as;
		if(this.robotText && this.robotTextDialogue && this.robotTextFinish && this.robotTextDialogueTrs.length > 0){
			if(!this.robotText.hasClass('text-visible')){ return; }
			as = this.robotTextFinish.getElements('a');
			this.robotText.setStyles({
				visibility: 'visible',
				opacity: 0
			});
			
			if(this.robotImage.hasClass('hidden')){
				this.robotImage.setStyles({
					visibility: 'visible',
					opacity: 0
				});
				this.robotImage.removeClass('hidden');
			}
			
			this.robotTextDialogue.setStyles({
				'opacity': 0,
				'margin-top': ''
			});
			
			this.currentDialogue = 0;
			
			if(browser.isIE && !this.stayOnPage){
				this.fixIePngFade(this.robotText);
				this.fixIePngFade(this.robotTextFinish);
			}
			
			this.robotTextInnerFx = new Fx.Elements([this.robotTextDialogue, this.robotTextFinish], {
				duration: 600,
				onComplete: function(){
					if(!htr.calledClose){
						if(htr.robotTextDialogue.getStyle('opacity').toInt() === 0 && htr.currentDialogue < htr.robotTextDialogueTrs.length){
							htr.timer1 = htr.runJsVersion.delay(200, htr, [htr.robotTextInnerFx, true]);
							htr.timer2 = htr.runJsVersion.delay(htr.options.jsVersionSlideTime+200, htr, htr.robotTextInnerFx);
						} else if(htr.currentDialogue == htr.robotTextDialogueTrs.length){
							htr.runJsVersion(htr.robotTextInnerFx);
						}
					}
				}
			});						
		
			this.robotTextFx = new Fx.Elements([this.robotText, this.robotImage], {
				duration: 800,
				onComplete: function(){
					if(!htr.calledClose){
						htr.jsVersionOb = {};
						htr.jsVersionOb[0] = {opacity: 1};
						htr.robotTextInnerFx.start(htr.jsVersionOb);
						htr.timer3 = htr.runJsVersion.delay(htr.options.jsVersionSlideTime+600, htr, htr.robotTextInnerFx);
					}
				}
			}).start({
				0: { 'opacity':1 },
				1: { 'opacity':1 }
			});
			
			if(!this.stayOnPage){
				$each(as, function(a, ind){
					a.addEvents({
						mouseenter: function(){
							if(ind === 0){
								htr.rolloverPng(this.getParent('.finish'), '0px -121px');
							} else {
								htr.rolloverPng(this.getParent('.finish'), '0px -242px');
							}
						},
						mouseleave: function(){
							this.fireEvent('blur');
						},
						contextmenu: function(event){
							event.stop();
						},
						focus: function(){
							this.fireEvent('mouseenter');
						},
						blur: function(){
							htr.rolloverPng(this.getParent('.finish'), '0px 0px');
						},
						click: function(event){
							event.stop();
							if(ind == 0){
								htr.setCookie();
								window.location.href = this.get('href');
							} else {
								htr.close(false, true);
							}
						},
						keypress: function(event){
							if(event.key){
								if(event.key == 'enter'){
									event.stop();
									a.fireEvent('click');
								}
							}
						}
					});
					
					if(ind == as.length -1){
						a.set('href', this.url);
					}
				}.bind(this));
			}
		}
		
		if(this.robotImage && browser.isIE && !this.stayOnPage){
			this.fixIePngFade(this.robotImage);
		}
	},
	
	runJsVersion: function(fx, next){
		var htr = this;
		this.jsVersionOb = {};
		if(this.currentDialogue < this.robotTextDialogueTrs.length){
			if(next){
				this.robotTextDialogue.setStyle('margin-top', -1*this.currentDialogue*this.robotTextDialogue.getParent().getSize().y);
				this.jsVersionOb[0] = {opacity: 1};
			} else {
				this.jsVersionOb[0] = {opacity: 0};
				this.currentDialogue++;
			}
		} else {
			this.robotTextDialogue.setStyle('margin-top', -1*this.currentDialogue*this.robotTextDialogue.getParent().getSize().y);
			this.currentDialogue++;
			this.jsVersionOb[1] = {opacity: [0,1]};
		}
		
		fx.start(this.jsVersionOb);
	},
	
	rolloverPng: function(div, pos){
		this.div = div;
		this.ieFilter = this.div.getElement('.ieFilter');
		this.div.setStyle('background-position', pos);
		if(this.ieFilter){
			this.ieFilter.setStyles({
				'width': this.div.getSize().x - this.div.getStyle('background-position-x').toInt(),
				'height': this.div.getSize().y - this.div.getStyle('background-position-y').toInt(),		
				'left': this.div.getStyle('background-position-x').toInt(),
				'top': this.div.getStyle('background-position-y').toInt(),
				'clip': 'rect(' + (-1*this.div.getStyle('background-position-y').toInt()) + 'px ' + (this.div.getSize().x-this.div.getStyle('background-position-x').toInt()) + 'px ' + (this.div.getSize().y-this.div.getStyle('background-position-y').toInt()) + 'px 0px)'
			});			
		}
	},
	
	play: function(){
		if(this.robotText){
			this.robotText.addClass('text-visible');
			this.startJsVersion();
			this.calledClose = false;
			if(this.robotControlsFx){
				this.robotControlsFx.setOptions({
					duration: 800,
					transition: ''
				});

				this.robotControlsFx.start({
					0: { 'opacity':1 },
					1: { 'opacity':0 }
				}); 
			}
		}
	},
	
	close: function(instant, showPlay){
		var htr = this;
		this.calledClose = true;
		if(!showPlay){
			this.setCookie('hide');
		}
		
		$clear(this.timer1);
		$clear(this.timer2);
		$clear(this.timer3);
		
		this.fx.setOptions({
			duration: 1000,
			transition: '',
			onComplete: function(){
				if(!browser.isIE5 && !browser.isIE6){
					htr.robotHolder.dispose();					
				}
			}
		});
		
		if(this.robotTextFx){
			this.robotTextFx.pause();
			this.robotTextFx.setOptions({
				onComplete: function(){}				
			});
		}
		
		if(instant){
			this.fx.set({display:'none'});
		} else if(showPlay){
			this.stayOnPage = true;
			if(this.robotTextInnerFx){
				this.robotTextInnerFx.pause();
				this.robotTextInnerFx.setOptions({
					duration: 10,
					onComplete: function(){
						if(htr.robotTextFx){
							htr.robotTextFx.start({
								0: { 'opacity':0 },
								1: { 'opacity':0 }
							});
						}
						
						if(htr.robotControlsFx){
							htr.robotControlsFx.setOptions({
								duration: 800,
								transition: ''
							});
							
							htr.robotControlsFx.start({
								0: { 'opacity':0 },
								1: { 'opacity':1 }
							});
						}
					}
				});
				
				this.robotTextInnerFx.start({
					0: { 'opacity': 0 },
					1: { 'opacity': 0 }
				});
			}
		} else {
			if(this.robotTextInnerFx){
				this.robotTextInnerFx.setOptions({
					duration: 200,
					onComplete: function(){
						htr.robotTextInner.setStyle('display','none');
						htr.fx.start({opacity:0});
					}
				});
				
				this.robotTextInnerFx.start({
					0: { 'opacity': 0 },
					1: { 'opacity': 0 }
				});
			} else {
				this.fx.start({opacity:0});
			}
		}
	},
	
	initControls: function(){
		var htr = this, els = [], elParents = [], robotControlsFxObj = {};
		$each([this.robotClose, this.robotPlay], function(el, ind){
			if(el){
				els.push(el);
				elParents.push(el.getParent());
				robotControlsFxObj[ind] = { 'margin-right':0 };
				if(el.getParent().getParent().hasClass('hidden')){
					el.getParent().getParent().removeClass('hidden');
					el.getParent().setStyle('opacity', 0);
				}
			}
		});
		
		if(els.length > 0){
			$each(els, function(el, ind){
				el.set('href', htr.url);
				el.addEvents({
					mouseenter: function(){
						htr.rolloverPng(elParents[ind], '0px -33px');
					},
					mouseleave: function(){
						htr.rolloverPng(elParents[ind], '0px 0px');
					},
					contextmenu: function(event){
						event.stop();
					},				
					click: function(event){
						event.stop();
						htr.rolloverPng(elParents[ind], '0px 0px');
						if(el == htr.robotClose){
							htr.close();
						} else if(el == htr.robotPlay){
							htr.play();
						}
					},
					keypress: function(event){
						if(event.key){
							if(event.key == 'enter'){
								event.stop();
								el.fireEvent('click');
							}
						}
					},
					focus: function(){
						el.fireEvent('mouseenter');
					},
					blur: function(){
						el.fireEvent('mouseleave');
					}
				});
				
				if(browser.isIE){
					htr.fixIePngFade(elParents[ind]);
				}
			});
			
			this.robotControlsFx = new Fx.Elements(elParents, {
				duration: 600,
				transition: Fx.Transitions.Cubic.easeOut
			}).start(robotControlsFxObj); 
		}
	},
	
	fixIePngFade: function(div){
		if(Browser.Engine.version >= 5){
			this.ieDiv = div;
			this.ieDiv.setStyle('background-image','');
			this.ieDivBg = this.ieDiv.getStyle('background-image');
			this.ieSrc = this.ieDivBg.substring(this.ieDivBg.indexOf('http'), this.ieDivBg.indexOf('.png')+4);
			this.blank_bg = this.blank_bg ? this.blank_bg : 'url(' + root + 'css/blank.gif)';
			this.ieDiv.setStyles({
				'background-image': this.blank_bg,
				'zoom': 1
			});
			
			if(this.ieDiv.getElements('.ieFilter').length <= 0){
				this.ieFilter = new Element('div', {
					'class': 'ieFilter'
				}).inject(this.ieDiv);
			}
			
			this.ieFilter.setStyles({
				'width': this.ieDiv.getSize().x - this.ieDiv.getStyle('background-position-x').toInt(),
				'height': this.ieDiv.getSize().y - this.ieDiv.getStyle('background-position-y').toInt(),
				'display': 'block',
				'z-index': -999,
				'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + this.ieSrc + '\',sizingMethod=\'crop\')',
				'position': 'absolute',
				'left': this.ieDiv.getStyle('background-position-x').toInt(),
				'top': this.ieDiv.getStyle('background-position-y').toInt(),
				'behavior': 'none',				
				'clip': 'rect(' + (-1*this.ieDiv.getStyle('background-position-y').toInt()) + 'px ' + (this.ieDiv.getSize().x-this.ieDiv.getStyle('background-position-x').toInt()) + 'px ' + (this.ieDiv.getSize().y-this.ieDiv.getStyle('background-position-y').toInt()) + 'px 0px)'				
			});
		}
	}
});

function initHomeTeamRobots(){
	homeTeamRobot = new HomeTeamRobot(window.location.toString());
}




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

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


function fadeFinishedFuncs(){
	if(fadeFinished){
		initHelpQuestionsTab();
		if(document.URL.indexOf('/admin/') < 0){
			initLightbox();
		}
		initCarousels();
		initCustomerSatisfaction();
		openLightboxFromUrl();
		if(homepage_carousel){
			homepage_carousel.autoAnimate();
		}

		//if($('book-club-facebook') && !browser.isIE5 && !browser.isIE6){
		if($('book-club-facebook')){
			var fb_iframe = new Element('iframe', {
				'src': 'http://www.facebook.com/plugins/likebox.php?id=149890191689087&width=292&connections=10&stream=true&header=false&height=555',
				'scrolling': 'no',
				'frameborder': '0',
				'allowTransparency': 'true',
				'styles': {
					'border':'none',
					'overflow':'hidden',
					'width':292,
					'height':555
				}
			}).inject($('book-club-facebook'));			
		}

		var img_timer = imgsLoad.delay(4000);
		
		if($('footer-robot-1')){
			var robotFooterEffect = new Fx.Morph($('footer-robot-1'), {
				duration: 1200, 
				transition: Fx.Transitions.Linear,
				onComplete: function(){}
			}).start({
				top: -147,
				height: 47
			});
		}				
		
	} else {
		var rTimer = fadeFinishedFuncs.delay(500);
	}
}


function initLoad(){
	checkPageLoad();
	initHomeTeamRobots();
	fadeFinishedFuncs();
	if(browser.isIE5 || browser.isIE6){
		var ie6_js, ie6_css = '';
		if(site_url.toString().indexOf('bordgaisenergybookclub.ie') < 0){
			ie6_css = new Asset.css(root + 'css/old-ie.css');
			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);
					}
				}
			});
		} else {
			/*ie6_css = new Asset.css(root + 'css/old-ie.css');
			ie6_js = new Asset.javascript('http://www.bordgaisenergybookclub.ie/wp-content/themes/bookclub/js/iepngfix_tilebg.js', {
				onload: function(){
					if(IEPNGFix){
						clearTimeout(IEPNGFix.update.timer);
						IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
					}
				}

			});*/
		}
	}
}


function checkPageLoad(){
	if(browser.isIphone){
		startFocusEffect();
		return false;
	}
	
	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.backgroundImage){
										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(')'));
										bg_img = bg_img.replace(/"/g, '');
										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(){
	if(browser.isIphone){ focusLoaded = true; return false; }
	
	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(); });

