// MooTools plugins for Bord Gais Energy



/****************************************************
* Global Vars                                       *
*                                                   *
*****************************************************/

var browser, directory;
var sIFR = false;
var IEPNGFix = false;
var focusLoaded = false;
var fadeFinished = false;
var domReady = false;
var sifrSelectors = false;

var pImages = [];
var fImages = [];

if(document.styleSheets){
	$each(document.styleSheets, function(style, ind){
		var rules = style.rules || style.cssRules;
		if(rules[0]){
			if(rules[0].selectorText == '#wrapper'){
				var bg = false, bg_img;
				if(rules[0].style.background){
					bg = rules[0].style.backgroundImage;
				} else if(rules[0].style['background-image']){
					bg = rules[0].style['background-image'];
				}
				
				if(bg){
					bg_img = bg.substring(bg.indexOf('images/'), bg.indexOf(')'));
					fImages = [root + bg_img, root + bg_img.replace(/.jpg/, '_focus.jpg')];
				}
			}
		}
	});
}

String.prototype.endsWith = function(str){ return (this.match(str+"$")==str); }





/****************************************************
* Browser Detection									*
*													*
*****************************************************/

function Detect() {
	
	agent 	= navigator.userAgent.toLowerCase();
						
	// detect OS
	this.isMac		= (agent.indexOf('mac') != -1);
	this.isWin		= (agent.indexOf('win') != -1);
	this.isWin2k	= (this.isWin && (agent.indexOf('nt 5') != -1));
	this.isWinSP2	= (this.isWin && (agent.indexOf('xp') != -1 || agent.indexOf('sv1') != -1));
	this.isOther	= (agent.indexOf('unix') != -1 || agent.indexOf('sunos') != -1 || agent.indexOf('bsd') != -1 || agent.indexOf('x11') != -1 || agent.indexOf('linux') != -1);
	
	// detect browser
	this.isSafari	= (agent.indexOf('safari') != -1);
	this.isSafari2 = (this.isSafari && (parseFloat(agent.substring(agent.indexOf("applewebkit/")+"applewebkit/".length,agent.length).substring(0,agent.substring(agent.indexOf("applewebkit/")+"applewebkit/".length,agent.length).indexOf(' '))) >=  300));
	this.isOpera	= (agent.indexOf('opera') != -1);
	this.isNN		= (agent.indexOf('netscape') != -1);
	this.isFF		= (agent.indexOf('firefox') != -1);	
	this.isFF2		= (agent.indexOf('firefox/2') != -1);
	this.isFF3		= (agent.indexOf('firefox/3') != -1);	
	this.isIE		= (agent.indexOf('msie') != -1);
	this.isIE8		= (agent.indexOf('msie 8.') != -1);
	this.isIE6		= (agent.indexOf('msie 6.') != -1);
	this.isIE5		= (agent.indexOf('msie 5.') != -1);
	this.isIphone	= (agent.indexOf('iphone') != -1);
}

browser = new Detect();




/****************************************************
* 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];
}




/****************************************************
* Write Out JS Browser Stylesheet					*
*													*
*****************************************************/

function writeJsStyles(w){
	var sSheets = document.getElementsByTagName("link");
	var dir = "";
	
	/* modified 05/03/10 Doug McLean - don't just assume sSheets[0] is a CSS reference - look at them all */
	/* this was the original code
	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;
		}
	}
	*/
	var sSheet = null;
	for (var i = 0; i < sSheets.length; i++) {
		if (sSheets[i].type == "text/css") {
			sSheet = sSheets[i];
			break;
		}
	}
	if(sSheet){
		if(sSheet.href.indexOf("css") != -1){
			dir = sSheet.href.substring(0,sSheet.href.indexOf("css"));
		if(dir == ''){ dir = './'; }
      directory = dir;
		}
	}
	/* end of modification */
	
	if(w==1){ document.write('<link href="' + dir + 'css/js-dependant.css" rel="stylesheet" type="text/css" media="screen" />'); }
	
	if(browser.isIE){
		document.write('<link href="' + dir + 'css/ie.css" rel="stylesheet" type="text/css" media="screen" />');		
	}
	
	if(Browser.Plugins.Flash.version >= 8){
		document.write('<link href="' + dir + 'css/sifr.css" rel="stylesheet" type="text/css" />');
	}
}






/****************************************************
* Rerun PNG Fix										*
*													*
*****************************************************/

function refPng() {
	if(browser.isIE5 || browser.isIE6){
		if(IEPNGFix){
			clearTimeout(IEPNGFix.update.timer);
			IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
		}
	}
}





/****************************************************
* 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){
				var oldSrc = input.src;
				//if (DEBUG) alert(oldSrc);
				input.addEvents({
					'mouseenter': function(){
						if(browser.isIE5 || browser.isIE6){
							if(input.currentStyle.filter){
								input.style.filter = input.currentStyle.filter.replace(/.png/,'_over.png');
							} else {
								input.src = input.src.replace(/.gif/,'_over.gif').replace(/.jpg/,'_over.jpg');
							}
						} else {
							var newSrc = oldSrc.replace(/.png/,'_over.png').replace(/.gif/,'_over.gif').replace(/.jpg/,'_over.jpg');
							//if (DEBUG) alert(newSrc);
							input.src = newSrc;
						}
					},
					
					'mouseleave': function(){
						if(browser.isIE5 || browser.isIE6){
							if(input.currentStyle.filter){
								input.style.filter = input.currentStyle.filter.replace(/_over.png/,'.png');
							} else {
								input.src = input.src.replace(/_over.gif/,'.gif').replace(/_over.jpg/,'.jpg');
							}
						} else {
							input.src = input.src.replace(/_over.png/,'.png').replace(/_over.gif/,'.gif').replace(/_over.jpg/,'.jpg');
						}
					}
				});
			}
		});
	}
}






/****************************************************
* Initialise Rollovers for links with PNG			*
* backgrounds for IE6-								*
*													*
*****************************************************/

function aSpansPngHover(a, over){
	var spans = a.getElements('span');
	$each(spans, function(span, j){
		if(span.getAttribute('orig')){
			if(over){
				span.setStyle('background-image', span.getAttribute('orig').replace(/.png/,'_over.png'));
			} else {
				span.setStyle('background-image', span.getAttribute('orig').replace(/_over.png/,'.png'));
			}
		}
	});	
}

function initPngHovers(){
	var rules, ruleStyle, list = '', bg;
	if(document.styleSheets){
		$each(document.styleSheets, function(style){
			rules = style.rules || style.cssRules;
			$each(rules, function(rule, ind){
				if(rule.selectorText){					
					if(rule.selectorText.indexOf(':hover') >= 0){
						bg = false;
						if(rule.style.background){
							bg = rule.style.backgroundImage;
						} else if(rule.style['background-image']){
							bg = rule.style['background-image'];
						}
						
						if(bg){
							bg = bg.toString();
							if(bg.indexOf('.png') >= 0){
								if(list.length > 0){ list += ', '; }
								list += rule.selectorText.toString().substring(0,rule.selectorText.indexOf(':hover'));
							}
						}
					}
				}
			});
		});
	}
	
	if($('wrapper') && list.length > 0){
		if(browser.isIE5 || browser.isIE6){
			var j, as = $('wrapper').getElements(list);
			$each(as, function(a, i){	
				a.addEvents({
					'mouseenter': function(){
						if(a.getAttribute('orig')){
							a.setStyle('background-image', a.getAttribute('orig').replace(/.png/,'_over.png'));
							aSpansPngHover(a, true);														
						} else {
							if(a.getStyle('background-image')){
								a.setStyle('background-image', a.getStyle('background-image').replace(/.gif/,'_over.gif').replace(/.jpg/,'_over.jpg'));
							}
						}
						
						if(a.getParent().getParent()){
							if(a.getParent().getParent().hasClass('blue-button')){
								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')){
								aSpansPngHover(a);
							}
						}
						
						if(IEPNGFix){
							clearTimeout(IEPNGFix.update.timer);
							IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
						}
					}
				});					
			});
		}
	}
}






/****************************************************
* Position the Loading Indicator Correctly			*
*													*
*****************************************************/

function clearLoading(color){
	if($('wrapper')){		
		var lEffect = new Fx.Morph($('wrapper'), {
			duration: 200, 
			transition: Fx.Transitions.Linear,
			onComplete: function(){}
		});
		
		if(!browser.isIE){
			lEffect.start({opacity: [0, 1]});
		} else {
			$('wrapper').setStyle('opacity',1);
		}
	}
}








/****************************************************
* Position Footer so that it will appear of base of	*
* page every time									*
*													*
*****************************************************/

function getSizeY(){
	var h = 0;
	if(!window.innerWidth){
		if(!(document.documentElement.clientWidth === 0)){
			h = document.documentElement.clientHeight;
		} else {
			h = document.body.clientHeight;
		}
	} else {
		h = window.innerHeight;
	}
	
	return h;
}

function positionFooter(){
	if($('wrapper') && $('page-contents')){
		if(getSizeY() > $('wrapper').getSize().y){
			var diff = getSizeY() - $('wrapper').getSize().y;
			$('page-contents').setStyles({
				'height': 'auto !important',
				'height': $('page-contents').getSize().y + diff,
				'min-height': $('page-contents').getSize().y + diff
			});
		}
	}
}
	

	




/****************************************************
* Make the Focusing Effect on Homepage				*
*													*
*****************************************************/

function mafeFocusDiv(){
	if($('page-contents')){
		var newDiv = new Element('div', {
			'id': 'in-focus-bg',
			'styles': {
				'height': $('page-contents').getSize().y
			}
		});
		var inFocus = newDiv.inject($('page-contents'));
	}
}


function showPreHiddenElements(){
	if($('wrapper')){
		var pHiddens = $('wrapper').getElements('.pre-hidden');
		var fEffect, fx = [];
		var duration = 250;
		
		if(browser.isIE){ duration = 0; }
		
		$each(pHiddens, function(hid, index){
			fEffect = new Fx.Morph(hid, {
				duration: duration,
				transition: Fx.Transitions.Linear,
				onComplete: function(){
					if(index == pHiddens.length - 1){
						fadeFinished = true;
					}
				}
			});
			
			fx[index] = fEffect;
		});
		
		$each(fx, function(eff, index){
			eff.start.delay(index * 250, eff, {'opacity': [0, 1]}); 
		});
		
		if(pHiddens.length <= 0){
			fadeFinished = true;
		}
	}
}


function startFocusEffect(){
	if($('in-focus-bg')){
		var fEffect = new Fx.Morph($('in-focus-bg'), {
			duration:250, 
			transition: Fx.Transitions.Linear,
			onComplete: function(){
				$('in-focus-bg').dispose();
			}
		});
		
		fEffect.start({ 'opacity': 0 });
		showPreHiddenElements.delay(100);
	}
}






/****************************************************
* Setup Tabbed Content plus events					*
*													*
*****************************************************/

var TabbedContent = new Class({

	Implements: [Events, Options],

	options: {
	},

	initialize: function(holder, options){
		this.setOptions(options);
		this.holder = holder;
		this.contents = this.holder.getElements('.content');
		this.h4s = [];
		$each(this.contents, function(cont, i){
			if(cont.getElements('h4').length > 0){
				this.h4s.push(cont.getElements('h4')[0]);
			}
		}.bind(this));
		
		if(this.h4s.length > 0){
			this.tabs = new Element('div', { 'class': 'tabs' });
			this.ul = new Element('ul', {});
			this.lis = [];
			$each(this.h4s, function(h4, i){
				if(i === 0){ this.className = 'active'; }
				else { this.className = ''; }
				this.lis[i] = new Element('li', {
					'html': '<div>' + h4.innerHTML.toUpperCase() + '</div>',
					'class': this.className,
					'events': {
						'click': function(){ this.changeTab(i); }.bind(this),
						'mouseenter': function(){}.bind(this),
						'mouseleave': function(){}.bind(this)
					}
				}).inject(this.ul);
			}.bind(this));
			
			this.ul.inject(this.tabs);
			this.tabs.inject(this.holder);
		}
	},
	
	changeTab: function(index){
		$each(this.contents, function(content, ind){
			if(!content.hasClass('tab-hidden')){ content.addClass('tab-hidden'); }
		}.bind(this));
		
		$each(this.lis, function(li, ind){
			li.removeClass('active');
		}.bind(this));
		
		this.contents[index].removeClass('tab-hidden');
		this.lis[index].addClass('active');
	}
});

function makeTabbedContent(){
	var hObj = [], holders = $$('.tabbed-content');
	$each(holders, function(holder, i){
		hObj[i] = new TabbedContent(holder, {});
	});	
}






/****************************************************
* Initialise Help Popups							*
*													*
*****************************************************/

function initHelpPopups(){
	var name, icons = $$('.help-icon');
	$each(icons, function(icon, ind){
		if(icon.get('name')){
			name = icon.get('name');
			if($(name + '-pop')){
				icon.addEvents({
					'mouseenter': function(){ $(name + '-pop').setStyle('visibility', 'visible'); refPng(); },
					'mouseleave': function(){ $(name + '-pop').setStyle('visibility', 'hidden'); }
				});
			}
		}
	});
}






/****************************************************
* Initialise Accordions								*
*													*
*****************************************************/

function initAccordions(){
	var show = -1, display = -1;	
	var questions = $$('#accordion-content .question');
	var answers = $$('#accordion-content .answer');
	var active = -1;
	
	var accordion = new Fx.Accordion(questions, answers, {
		opacity: 0,
		alwaysHide: true,
		display: display,
		show: show,
		onActive: function(toggler){
			if(!browser.isIE6 && !browser.isIE5){
				toggler.setStyle('background-image', toggler.getStyle('background-image').replace(/_plus.png/,'_minus.png').replace(/_plus_over.png/,'_minus.png'));
			}
			
			$each(questions, function(quest, ind){
				if(toggler == quest){ active = ind; }
			});
		},
		onBackground: function(toggler) {
			if(!browser.isIE6 && !browser.isIE5){
				toggler.setStyle('background-image', toggler.getStyle('background-image').replace(/_minus.png/,'_plus.png'));
			}
		},
		onComplete: function(){
		}
	});

	questions.addEvent('mouseenter', function(){
		if(!browser.isIE6 && !browser.isIE5){
			this.setStyle('background-image', this.getStyle('background-image').replace(/_plus.png/,'_plus_over.png'));
		}
	});
	
	questions.addEvent('mouseleave', function(){
		if(!browser.isIE6 && !browser.isIE5){
			this.setStyle('background-image', this.getStyle('background-image').replace(/_plus_over.png/,'_plus.png'));
		}
	});
	
	answers.setStyle('display', 'block');

}





/****************************************************
* On Page Load Functions							*
*													*
*****************************************************/

function init(){
	domReady = true; // this is required in order to make the page appear
	positionFooter();
	mafeFocusDiv(); // this is required in order to make the page appear
	initInputs();
	makeTabbedContent();
	initHelpPopups();
	initAccordions();
	initLightbox();
	if(browser.isIE5 || browser.isIE6){ initPngHovers(); }
}


function fadeFinishedFuncs(){
	if(fadeFinished){
		fixPageTitle();
		var img_timer = imgsLoad.delay(4000);
		if(browser.isIE5 || browser.isIE6){
			$$('select').setStyle('visibility', 'visible');
		}
	} else {
		var rTimer = fadeFinishedFuncs.delay(500);
	}
}


function initLoad(){
	checkPageLoad(); // this is required in order to make the page appear
	fadeFinishedFuncs();
	if(browser.isIE5 || browser.isIE6){
		var ie6_css = new Asset.css(root + 'css/old-ie.css');
		var ie6_js = new Asset.javascript(root + 'js/iepngfix_tilebg.js', {
			onload: function(){
				if(IEPNGFix){
					clearTimeout(IEPNGFix.update.timer);
					IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
				}
			}
		});
	}
}

function fixPageTitle() {
	document.getElementById("page-title").style.backgroundColor = "transparent";
}


function checkPageLoad(){
	if(focusLoaded && domReady){
		if($('in-focus-bg')){
			if(fImages.length == 2){
				$('in-focus-bg').setStyles({
					'background': 'url(' + fImages[1] + ') no-repeat center top',
					'-webkit-background-size': '2000px 2500px'
				});
				$('wrapper').setStyles({
					'background': 'url(' + fImages[0] + ') no-repeat center top',
					'-webkit-background-size': '2000px 2500px'
				});
			}
			clearLoading('#FFFFFE');
			startFocusEffect.delay(1000);
		} else {
			checkPageLoad.delay(100);
		}
	} else {
		checkPageLoad.delay(100);
	}
}


function imgsLoad(){
	var rules, ruleStyle, bg=false, bg_img;
	if(document.styleSheets){
		$each(document.styleSheets, function(style){
			if(style.href){
				if(style.href.indexOf('addthis.com') < 0){
					try {
						rules = style.rules || style.cssRules;
						$each(rules, function(rule, ind){
							if(rule.selectorText){
								if(rule.selectorText.indexOf(':hover') >= 0){
									bg = false;
									if(rule.style.background){
										bg = rule.style.backgroundImage;
									} else if(rule.style['background-image']){
										bg = rule.style['background-image'];
									}
									if(bg){
										var firstChar = bg.indexOf("images/");
										var lastChar = bg.indexOf(")");
										if ((bg.indexOf('"') >= 0) || (bg.indexOf("'") >= 0)) lastChar--;
										bg_img = bg.substring(firstChar, lastChar);
										//if (DEBUG) alert(bg + "\n" + bg_img);
										pImages.push(root + bg_img);
									}
								}
							}
						});
					} catch (err){}
				}
			}
		});
	}
	
	var loader = new Asset.images(pImages, {
		onProgress: function(counter, index){
		},
		onComplete: function(){
		}
	});
}




/****************************************************
* On Page UnLoad Functions							*
*													*
*****************************************************/

function memoryClean(e){
}





/****************************************************
* Load In Focus Image								*
*													*
*****************************************************/

function loadInFocusImg(){
	var loader = new Asset.images(fImages, {
		onProgress: function(counter, index){
		},
		onComplete: function(){			
			focusLoaded = true;
		}
	});
}




writeJsStyles(1);
loadInFocusImg();
window.addEvent('domready', function() { init(); });
window.addEvent('load', function() { initLoad(); });
window.addEvent('unload', function() { memoryClean(); });
