// MooTools plugins for ICON


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

var browser, directory, domIsReady, fixTimer, sifrReplaced = 0;
var cLightGreen = '#2e9894', cDarkGreen = '#006d63', cGrey = '#626469';
var fnQue = [];
var sIFR = false;
var selectClick = false;
var doStyledSelects = true;

var root = '/icon-files/cms-templates/images-volunteers/';

var pImages = ['arrow2.gif', 'radiobutton2.gif', 'btn_add2.png', 'btn_apply2.png', 'btn_findout2.png', 'btn_signup2.png', 'btn_submit2.png', 'dropdown_btm_green.png', 'dropdown_btm_white.png', 'dropdown_long_green.png', 'dropdown_long_green1.png', 'dropdown_long_white.png', 'dropdown_long_white1.png', 'nav_left_dark.png', 'nav_left_green.png', 'nav_left_white.png', 'nav_left_white2.png', 'nav_right_dark.png', 'nav_right_green.png', 'nav_right_white.png', 'btn_applynow2.gif'];

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();





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

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

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





/****************************************************
* Fix Position of Footer in IE6 after sIFR			*
* replacements										*
*													*
*****************************************************/

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 fixIE6Footer(){
	if(browser.isIE6 || browser.isIE5 || browser.isOpera){		
		if(!sIFR){
			if(sIFR.replacements){
				if(sifrReplaced == sIFR.replacements.length && sIFR.replacements.length > 0){
					if($('footer-inner')){
						$('footer-inner').setStyle('bottom', 0);
					}
				} else {
					fixTimer = fixIE6Footer.delay(100);
				}
			}
		} else {
			if($('wrapper') && $('footer-inner') && $('torso-content')){
				if($('wrapper').getScrollSize().y > getSizeY()){
					$('torso-content').setStyle('padding-bottom', '40px');
					$('footer-inner').setStyle('position', 'relative');
				}
			}
			if($('footer-inner')){
				$('footer-inner').setStyle('bottom', 0);
			}						
		}				
	}
}




/****************************************************
* Initialise Lightbox Elements						*
*													*
*****************************************************/

function initLightBoxElements(){
	var initMultiBox = new multiBox({
		mbClass: '.mb',
		container: $(document.body),
		useOverlay: true,
		maxSize: {w:1024, h:768},
		addDownload: false,
		pathToDownloadScript: '/',
		addRollover: true,
		addOverlayIcon: false,
		addChain: false,
		recalcTop: false,
		addTips: false
	});
}





/****************************************************
* 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;
}




/****************************************************
* Initialise Inputs - default values				*
*													*
*****************************************************/

function initInputs(el){
	if($(document.body)){
		var elems, inputs, imgs;
		inputs = $(document.body).getElements('input');
		imgs = $(document.body).getElements('img');
		elems = inputs.concat(imgs);
		$each(elems, function(elm, index){
			if(elm.src){
				elm.addEvents({
					'mouseover': function(e){
						if(elm.src.endsWith('1.gif') || elm.src.endsWith('1.jpg') || elm.src.endsWith('1.png')){							
							elm.src = elm.src.replace(/1.gif/,'2.gif');
							elm.src = elm.src.replace(/1.jpg/,'2.jpg');
							elm.src = elm.src.replace(/1.png/,'2.png');
						}
					},
					
					'mouseout': function(e){
						if(elm.src.endsWith('2.gif') || elm.src.endsWith('2.jpg') || elm.src.endsWith('2.png')){
							elm.src = elm.src.replace(/2.gif/,'1.gif');
							elm.src = elm.src.replace(/2.jpg/,'1.jpg');
							elm.src = elm.src.replace(/2.png/,'1.png');
						}
					}
				});
				
			} else {
				if(elm.id){
					if(elm.id == 'site-query'){
						elm.addEvents({
							'focus': function(e){
								if(elm.value == 'Search'){ elm.value = ''; }
							},
							
							'blur': function(e){								
							}
						});
					}
				}
			}
		});
	}
}





/****************************************************
* Initialise Hover State for Primary Nav			*
*													*
*****************************************************/

function initPriNavHover(){
	if($('primary-nav')){
		var spans, uls, divs = $('primary-nav').getElements('li div');		
		$each(divs, function(div, index){
			div.addEvents({
				'mouseenter': function(e){
					if(!(div.hasClass('nav-on'))){
						div.addClass('hover');
						if(browser.isIE5 || browser.isIE6){
							spans = div.getElements('span');
							if(spans.length > 0){ spans[0].setStyle('background','url(/icon-files/cms-templates/images-volunteers/nav_left_dark.gif) no-repeat left bottom'); }
							uls = div.getElements('ul');
							$each(uls, function(ul, i){ ul.setStyle('visibility','visible'); });
						}
					}
				},
				
				'mouseleave': function(e){
					div.removeClass('hover');
					if(browser.isIE5 || browser.isIE6){
						spans = div.getElements('span');
						if(spans.length > 0){ spans[0].setStyle('background','none'); }
						uls = div.getElements('ul');
						$each(uls, function(ul, i){ ul.setStyle('visibility','hidden'); });
					}
				}
			});
		});
	}
}





/****************************************************
* Setup Vertical Scrollables						*
*													*
*****************************************************/

var ScrollBar = new Class({

	Implements: [Events, Options],

	options: {
		maxThumbSize: 11,
		wheel: 8,
		arrows: true,
		init: true,
		speed: 800,
		isDD: false
	},

	initialize: function(main, content, options){
		this.setOptions(options);
		
		this.main = main;
		this.content = content;
		
		if (this.options.arrows === true){
			if (this.options.isDD === true){
				this.arrowOffset = 42;
			} else {
				this.arrowOffset = 32;
			}
				
		} 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);
		this.vThumb_t = new Element('div', { 'class': 'vThumb-top' }).injectInside(this.vTrack);
		this.vThumb_b = new Element('div', { 'class': 'vThumb-base' }).injectInside(this.vTrack);
		this.fxOn = false;

		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),
			'vThumbOver': this.vThumbOver.bind(this),
			'vThumbOut': this.vThumbOut.bind(this)
		};

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

	update: function(){		
		if(!isNaN(this.content.offsetHeight - this.arrowOffset) && (this.content.offsetHeight - this.arrowOffset) >= 0){
			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');	
			this.content.setStyle('width', this.main.offsetWidth);	
		} else {			
			this.vScrollbar.setStyle('display', 'block');
			if (this.options.isDD === true){
				this.content.setStyle('width', Math.max(this.main.offsetWidth - 16,0));				
			} else {
				this.content.setStyle('width', Math.max(this.main.offsetWidth - 30,0));
			}
		}

		if(!isNaN(this.vTrack.offsetHeight - 10) && (this.vTrack.offsetHeight - 10) >= 0){
			if (this.options.isDD === true){
				this.vTrack.setStyles({'height': this.vTrack.offsetHeight});
			} else {
				this.vTrack.setStyles({'height': this.vTrack.offsetHeight - 10});
			}
		}

		if(!isNaN(this.content.offsetHeight) && (this.content.offsetHeight) >= 0){
			this.content.setStyle('height', this.content.offsetHeight);
		}
		
		this.vContentSize = this.content.offsetHeight;
		this.vContentScrollSize = this.content.scrollHeight;
		
		this.vTrackSize = this.vTrack.offsetHeight;
		this.vContentRatio = this.vContentSize / this.vContentScrollSize;
		this.vThumbSize = (this.vTrackSize * this.vContentRatio).limit(this.options.maxThumbSize, this.vTrackSize);
		if(this.vTrackSize * this.vContentRatio < 11){			
			this.vScrollRatio = this.vContentScrollSize / (this.vTrackSize - 11 + Math.floor(this.vTrackSize * this.vContentRatio));
		} else {
			this.vScrollRatio = this.vContentScrollSize / this.vTrackSize;
		}
		if(!isNaN(this.vThumbSize) && (this.vThumbSize) >= 0){
			this.vThumb.setStyle('height', this.vThumbSize);
		}
		this.vThumb_b.setStyle('top', this.vThumbSize - 1);		
		this.vUpdateThumbFromContentScroll();
		this.vUpdateContentFromThumbPosition();
	},
	
	updateAfterScroll: function(){
		this.limYCoord = -1 * this.limYCoord;
		this.content.scrollTop = this.limYCoord;	
		this.contentClone.destroy();
		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);
		this.vThumb_t.setStyle('top', this.vPosition.now - 6);
		this.vThumb_b.setStyle('top', this.vPosition.now + this.vThumbSize - 1);
	},		

	attach: function(){
		this.vThumb.addEvent('mousedown', this.bound.vStart);		
		this.vThumb_t.addEvent('mousedown', this.bound.vStart);		
		this.vThumb_b.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){
				if(!this.fxOn){
					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);
				selectClick = true;
			}.bind(this));						
					
			this.arrowDown.addEvent('mousedown', function(event){
				if(!this.fxOn){
					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);
				selectClick = true;
			}.bind(this));

		}			
					
	},
	
	wheel: function(event){
		if(!this.fxOn){
			this.content.scrollTop -= event.wheel * this.options.wheel;
			this.vUpdateThumbFromContentScroll();
		}
		
		event.stop();
	},

	vPage: function(event){
		if(!this.fxOn){
			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);
		this.vThumb_t.addEvent('mouseup', this.bound.end);
		this.vThumb_b.addEvent('mouseup', this.bound.end);
		this.vThumbOver();
		selectClick = true;
		event.stop();
	},

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

	vDrag: function(event){
		if(!this.fxOn){
			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();
	},
	
	vThumbOver: function(event){	
	},
	
	vThumbOut: function(event){
	}
});






/****************************************************
* Style Select Form Fields							*
*													*
*****************************************************/

var SelectBox = new Class({

	Implements: [Events, Options],

	options: {		
		maxHeight: 160,
		zIndex: 0
	},

	initialize: function(select, options){
		this.setOptions(options);
		this.select = select;
		this.parent = this.select.getParent();
		this.optionsList = this.select.getElements('option');
		if(this.optionsList.length <= 0 || isNaN(this.optionsList.length)){ return; }
		var float, css, tAlign, width;
		selectClick = true;
		
		if(browser.isIE){ this.selectWidth = 2; }
		else { this.selectWidth = 3; }
		
		if(this.select.style['float'] && this.parent.style['text-align']){
			float = this.select.style['float'];
			tAlign = this.parent.style['text-align'];
		} else if(this.select.currentStyle){
			float = this.select.currentStyle['styleFloat'];
			tAlign =  this.parent.currentStyle['textAlign'];
		} else if(document.defaultView && document.defaultView.getComputedStyle){
			css = getComputedStyle(this.select,'');
			float = css.getPropertyValue('float');
			tAlign = css.getPropertyValue('text-align');
		} else {
			float = 'left';
			tAlign = 'left';
		}
		
		if(!float || float == 'none'){
			if(tAlign == 'right'){ float = 'right'; }
			else { float = 'left'; }
		}
		
		if(!this.select.getAttribute('orig-position')){
			this.select.setAttribute('orig-position', this.select.getStyle('position'));
			this.select.setAttribute('orig-top', this.select.getStyle('top'));
		}
		
		width = this.select.getSize().x - this.selectWidth;
		if(width > 205){
			width = 205;
		}
		
		this.holder = new Element('div', {
			'class': 'styled-select',
			'styles': {
				'width': width,
				'height': this.select.getSize().y - this.selectWidth,
				'top': this.select.getAttribute('orig-top'),
				'left': this.select.getStyle('left'),
				'right': this.select.getStyle('right'),
				'bottom': this.select.getStyle('bottom'),
				'float': float,
				'position': this.select.getAttribute('orig-position'),
				'margin': this.select.getStyle('margin'),
				'padding': '0',
				'display': this.select.getStyle('display')
			}
		}).inject(this.select, 'before');
		
		this.select.setStyles({'position':'absolute', 'top':-1000000});
		if((this.select.getSize().x - this.selectWidth) > 205){
			if(this.select.getParent().nodeName.toLowerCase() == 'td'){
				if(this.select.getParent().getParent().getParent().getParent().getParent().id){
					if(this.select.getParent().getParent().getParent().getParent().getParent().id == 'app-form'){
						var tds = this.select.getParent().getParent().getParent().getParent().getElements('td');
						tds.each(function(td, index){
							if(!td.hasClass('right')){
								td.setStyles({'width':205, 'max-width':205 });
							}
						});
					}
				}
			}
		}
		
		this.container = new Element('div', {
			'class': 'container',
			'styles': {
				'z-index': this.options.zIndex
			}
		}).inject(this.holder);
		
		this.selected = new Element('div', {'class': 'selected' }).inject(this.container);
		this.selected.setStyles({'height': this.holder.getSize().y - 2, 'line-height': this.holder.getSize().y - 2});
		
		this.arrow = new Element('div', {'class': 'arrow' }).inject(this.container);
		this.arrow.setStyles({'height': this.holder.getSize().y - 3});
		
		var top_size = this.holder.getSize().y;
		if(browser.isIE){ top_size -= 2; }
		
		
		//this.holder.getSize().x - 2		
		
		this.optionsHolder = new Element('div', {
			'class': 'options',
			'styles': {
				'width': this.select.getSize().x - this.selectWidth - 2,
				'top': top_size,
				'opacity': 0
			}
		}).inject(this.container);
		this.optionsContent = new Element('div', {'class': 'content'}).inject(this.optionsHolder);
		
		this.ul = new Element('ul', {'styles': {'margin': '0'}}).inject(this.optionsContent);
		var li;
		
		if(!this.select.disabled){		
			this.selected.addEvents({
				'click': function(){
					this.closeAll();
					this.optionsHolder.setStyle('opacity',1);
					selectClick=true;
					if(browser.isIE5 || browser.isIE6){
						if(IEPNGFix){
							clearTimeout(IEPNGFix.update.timer);
							IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
						}
					}
				}.bind(this),
				'mouseenter': function(){ this.arrow.setStyle('background-image', this.arrow.getStyle('background-image').replace(/1.gif/, '2.gif')); }.bind(this),
				'mouseleave': function(){ this.arrow.setStyle('background-image', this.arrow.getStyle('background-image').replace(/2.gif/, '1.gif')); }.bind(this)
			});
			
			this.arrow.addEvents({
				'click': function(){
					this.closeAll();
					this.optionsHolder.setStyle('opacity',1);
					selectClick=true;
					if(browser.isIE5 || browser.isIE6){
						if(IEPNGFix){
							clearTimeout(IEPNGFix.update.timer);
							IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
						}
					}
				}.bind(this),
				'mouseenter': function(){ this.arrow.setStyle('background-image', this.arrow.getStyle('background-image').replace(/1.gif/, '2.gif')); }.bind(this),
				'mouseleave': function(){ this.arrow.setStyle('background-image', this.arrow.getStyle('background-image').replace(/2.gif/, '1.gif')); }.bind(this)
			});
		}
		
		$each(this.optionsList, function(option, index){
			if(option.text){
				if(index === 0){ this.selected.innerHTML = option.text; }
				if(option.selected){ this.selected.innerHTML = option.text; }
				
				li = new Element('li', {
					'html': option.text,
					'styles': {
						'background': 'none',
						'padding': '1px 3px'
					},
					'events': {
						'click': function(){ this.choose(index, option.text); selectClick=true; }.bind(this)
					}
				}).inject(this.ul);
			}
		}.bind(this));
		
		this.lis = this.ul.getElements('li');
		$each(this.lis, function(li, index){
			li.addEvent('mouseenter', function(){ this.highlight(li); }.bind(this));
		}.bind(this));
		
		if(this.optionsHolder.getSize().y > this.options.maxHeight){
			this.optionsHolder.setStyle('height', this.options.maxHeight);
			this.optionsContent.setStyle('height', this.options.maxHeight);
			this.scrollBar = new ScrollBar(this.optionsHolder, this.optionsContent, {isDD:true});
		}
		
		if(this.select.disabled){
			this.disabledLayer = new Element('div', {
				'class': 'disabled-layer',
				'styles': {
					'width': this.holder.getSize().x,
					'height': this.holder.getSize().y
				}
			}).inject(this.container);
			this.holder.addClass('disabled-select');
		}		
		
		this.clear = new Element('div', {
			'styles': {
				'clear':'both',
				'width': '100%',
				'height': '0',
				'line-height': '0',
				'font-size': '0px'
			}
		}).inject(this.parent);
	},
	
	choose: function(index,text){
		if(text){ this.selected.innerHTML = text; }
		this.select.options[index].selected = 'selected';
		this.select.selectedIndex = index;
		this.optionsHolder.setStyle('opacity',0);
		if(this.select.getAttribute('onchange')){
			if(this.select.fireEvent){
				this.select.onchange();
			}
			
			if(document.createEvent){
				var evt = document.createEvent('HTMLEvents');
				if(evt.initEvent){ evt.initEvent('change', true, true); }
				if(this.select.dispatchEvent){ this.select.dispatchEvent(evt); }
			}
		}
	},
	
	highlight: function(li){
		$each(this.lis, function(li, index){
			li.setStyles({'background':'none', 'color':'#626469'});
		}.bind(this));
		
		li.setStyles({'background':'#8DC3C0', 'color':'#FFF'});
	},
	
	closeAll: function(){
		if(document.body){
			this.dds = document.body.getElements('.styled-select .options');
			this.dds.each(function(dd, index){
				dd.setStyle('opacity',0);
			});
		}
	}
});



function initSelects(ref){
	var selects, sel, dds;
	if(document.body && doStyledSelects){
		selects = document.body.getElements('select');
		if(selects.length > 0){
			dds = document.body.getElements('.styled-select');
			for(var i=dds.length-1; i >= 0; i--){
				dds[i].dispose();
			}
			
			selects.each(function(select, index){
				sel = new SelectBox(select, {zIndex: selects.length-index});
			});
			
			if(!ref){
				$(document.body).addEvent('click', function(){
					if(selectClick){ selectClick = false; }
					else {
						dds = document.body.getElements('.styled-select .options');
						dds.each(function(dd, index){
							dd.setStyle('opacity',0);
						});
					}
				});
			}
		}
	}
}





/****************************************************
* BMI Calculator		  							*
*					 								*
*****************************************************/

function cal_bmi(lbs, ins)
{
   h2 = ins * ins;
   bmi = lbs/h2 * 703
   f_bmi = Math.floor(bmi);
   diff  = bmi - f_bmi;
   diff = diff * 10;
   diff = Math.round(diff);



   if (diff == 10)    // Need to bump up the whole thing instead
   {
      f_bmi += 1;
      diff   = 0;
   }
   bmi = f_bmi + "." + diff;
   return bmi;
}
function compute(){
   var f = self.document.forms["bmi_input"];

   w = f.wt.value;
   v = f.htf.value;
   u = f.hti.value;

   // Format values for the BMI calculation

   if (!chkw(u))
   {
     var ii = 0;
     f.hti.value = 0;
   } else
   {
     var it = f.hti.value*1;
     var ii = parseInt(it);
    }

   var fi = parseInt(f.htf.value * 12);
   var i =  parseInt(f.htf.value * 12) + f.hti.value*1.0;  // var i = fi + ii; aeisenberg@air.org: now the height in inches is correctly summed

  // Do validation of remaining fields to check for existence of values

   if (!chkw(v))
   {
     alert("Please enter a number for your height.");
     f.htf.focus();
     return;
   }
   if (!chkw(w))
   {
     alert("Please enter a number for your weight.");
     f.wt.focus();
     return;
   }

   // Perform the calculation

   f.bmi.value = cal_bmi(w, i);
   f.bmi.focus();
}

function chkw(w){
   if (isNaN(parseInt(w))){
      return false;
   } else if (w < 0){
  return false;
  }
  else{
  return true;
  }
}




/****************************************************
* Study Finder							*
*													*
*****************************************************/

function checkFieldWasEntered (field, errorMsg)
{
	if (field.type == "text" && field.value.length == 0)
	{
		alert(errorMsg);
		field.focus();
		return false;
	}
	else if (field.type.indexOf("select") != -1 && field.options[field.selectedIndex].value.length == 0)
	{
		alert(errorMsg);
		field.focus();
		return false;
	}
	return true;
}


function checkEmail (field, errorMsg)
{
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(field.value) == false) {
		alert(errorMsg);
		field.focus();
		return false;
	}
	return true;
}



function initStudyCalendar() {
   if ($('finder_date')) {
      myCal = new Calendar({ finder_date: 'd/m/Y' }, { direction: .5 });
   }
   if ($('report_from') && $('report_to')) {
      cal = new Calendar({ report_from: 'd/m/Y', report_to: 'd/m/Y' }, { pad: 1});
   }
}


function checkStudyGroup (f) {
   if (f.group.value.length == 0) {
      alert("Please select a study group.");
      return false;
   }
   return true;
}


function setStudyGroup (group) {
   if ($('study-form')) {
      $('study-form').group.value = group;
   }
}


function checkBasketForm (f) {
   if (f) {
      if (!checkFieldWasEntered(f.firstname, "Please enter your first name.")) return false;
      if (!checkFieldWasEntered(f.lastname, "Please enter your last name.")) return false;
      if (!checkEmail(f.email, "Please enter your email.")) return false;
   }
   return true;
}


function showStudyGroups(groups, li, ind){
	$each(li.getParent().getElements('li'), function(ali, i){
		ali.removeClass('nav-on');								
	});
	li.addClass('nav-on');
	
	$each(groups, function(group, i){
		if(!group.hasClass('sd-hidden')){ group.addClass('sd-hidden'); }
	});
	groups[ind].removeClass('sd-hidden');
}


function initStudyGroups(){
	if($('wrapper')){
		var groups = $('wrapper').getElements('.study-details');
		var groups_nav = $('wrapper').getElements('.study-details-nav');
		var ul, li, as, spans;
		
		if(groups.length == groups_nav.length && groups_nav.length > 1){
			ul = new Element('ul', {});
			$each(groups_nav, function(nav, index){
				li = new Element('li', { 'html': nav.innerHTML }).inject(ul);
				if(index == 0){ li.addClass('nav-on'); li.addClass('first'); }
				nav.innerHTML = '';
			});
			
			ul.inject(groups_nav[0]);
			as = ul.getElements('a');
			$each(as, function(a, index){
				if(index == 0){
					spans = a.getElements('span');
					if(spans.length > 0){ setStudyGroup(spans[0].innerHTML); }
				}
				a.addEvent('click', function(){ showStudyGroups(groups, a.getParent().getParent(), index); });
			});
		}
	}
}





/****************************************************
* Initialise Study Alert Sliders					*
*													*
*****************************************************/

function initRSSSlider(){
	if($('rss-update') && $('rss-dropdown') && $('torso') && $('torso-left') && $('torso-right')){
		var opened = false, sTorso = false;
		var effect = new Fx.Morph($('rss-dropdown'), {duration:500, transition: Fx.Transitions.Cubic.easeOut, onComplete: function(){ $('rss-dropdown').setAttribute('busy',0); if(opened){ $('rss-dropdown').setStyle('overflow','visible'); } } });
		var effect2 = new Fx.Morph($('torso'), {duration:500, transition: Fx.Transitions.Cubic.easeOut });
		var content = $('rss-dropdown').getElements('.content');		
		$('rss-dropdown').setAttribute('busy',0);
		$('rss-update').hideFocus = true;
		
		if(content.length >= 1){
			if(parseInt($('torso-right').getSize().y + content[0].getSize().y,10) > $('torso-left').getSize().y){
				sTorso = true;
			}
		}

		if($('rss-update').href.endsWith('#')){
			$('rss-update').addEvent('click',function(event){
				event.stop();
				if(content.length >= 1){
					if($('rss-dropdown').getAttribute('busy') == 0){
						$('rss-dropdown').setAttribute('busy',1);
						if($('rss-dropdown').getSize().y <= 1){
							opened = true;
							effect.start({ 'height': content[0].getSize().y });
							if(sTorso){
								effect2.start({
									'height': 'auto !important',
									'height': parseInt($('torso').getSize().y + content[0].getSize().y,10),
									'min-height': parseInt($('torso').getSize().y + content[0].getSize().y,10)									
								});
							}
						} else {
							opened = false;
							$('rss-dropdown').setStyle('overflow','hidden');
							effect.start({ 'height': 0 });
							if(sTorso){
								effect2.start({
									'height': 'auto !important',
									'height': parseInt($('torso').getSize().y - content[0].getSize().y,10),
									'min-height': parseInt($('torso').getSize().y - content[0].getSize().y,10)									
								});
							}
						}
					}
				}
			});
		}
	}
}


function initEmailAlert(){
	if($('email-update') && $('email-update-signup') && $('torso') && $('torso-left') && $('torso-right')){
		var opened = false, sTorso = false;
		var effect = new Fx.Morph($('email-update-signup'), {duration:500, transition: Fx.Transitions.Cubic.easeOut, onComplete: function(){ $('email-update-signup').setAttribute('busy',0); if(opened){ $('email-update-signup').setStyle('overflow','visible'); } } });
		var effect2 = new Fx.Morph($('torso'), {duration:500, transition: Fx.Transitions.Cubic.easeOut });
		var content = $('email-update-signup').getElements('.content');		
		$('email-update-signup').setAttribute('busy',0);
		$('email-update').hideFocus = true;		
		
		if(content.length >= 1){
			if(parseInt($('torso-right').getSize().y + content[0].getSize().y,10) > $('torso-left').getSize().y){
				sTorso = true;
			}
		}

		$('email-update').addEvent('click',function(event){
			event.stop();
			if(content.length >= 1){
				if($('email-update-signup').getAttribute('busy') == 0){
					$('email-update-signup').setAttribute('busy',1);
					if($('email-update-signup').getSize().y <= 1){
						opened = true;
						effect.start({ 'height': content[0].getSize().y });
						if(sTorso){
							effect2.start({
								'height': 'auto !important',
								'height': parseInt($('torso').getSize().y + content[0].getSize().y,10),
								'min-height': parseInt($('torso').getSize().y + content[0].getSize().y,10)									
							});
						}
					} else {
						opened = false;
						$('email-update-signup').setStyle('overflow','hidden');
						effect.start({ 'height': 0 });
						if(sTorso){
							effect2.start({
								'height': 'auto !important',
								'height': parseInt($('torso').getSize().y - content[0].getSize().y,10),
								'min-height': parseInt($('torso').getSize().y - content[0].getSize().y,10)									
							});
						}
					}
				}
			}
		});
	}
}






/****************************************************
* Shown hidden form layers if previously used and 	*
* error	occurs on form submission					*
*													*
*****************************************************/

function initHiddenFormLayers(){
	if($('gender-male')){ if($('gender-male').checked){ showGender($('gender-male')); } }
	if($('gender-female')){ if($('gender-female').checked){ showGender($('gender-female')); } }
	if($('cocaine')){ if($('cocaine').checked){ showDrug($('cocaine')); } }
	if($('heroin')){ if($('heroin').checked){ showDrug($('heroin')); } }
	if($('amphetamine')){ if($('amphetamine').checked){ showDrug($('amphetamine')); } }
	if($('cannabis')){ if($('cannabis').checked){ showDrug($('cannabis')); } }
	if ($('bmi-cell')) { runBMI(); }
	if ($('age-cell')) { calcAge($('dob')); }
	if ($('insurance-no-div') && $('passport-div') ) { showPassport($('nationality')); }
        if ($('hw-type') && $('app-form')) { showHeightWeight($('hw-type')); }
}






/****************************************************
* Clear Default value from Last used Fields in UK	*
* Application Form									*
*													*
*****************************************************/

function clearAppFormLastUsed(){
	if($('cocaine_last') && $('heroin_last') && $('amphetamine_last') && $('cannabis_last')){
		$('cocaine_last').addEvent('focus',function(){
			if($('cocaine_last').value == 'Last used'){ $('cocaine_last').value = ''; }
		});
		$('heroin_last').addEvent('focus',function(){
			if($('heroin_last').value == 'Last used'){ $('heroin_last').value = ''; }
		});
		$('amphetamine_last').addEvent('focus',function(){
			if($('amphetamine_last').value == 'Last used'){ $('amphetamine_last').value = ''; }
		});
		$('cannabis_last').addEvent('focus',function(){
			if($('cannabis_last').value == 'Last used'){ $('cannabis_last').value = ''; }
		});
	}
}






/****************************************************
* Format Volunteers Nav in accordance with design	*
*													*
*****************************************************/

function formatVolNav(){
	if($('pnav-1') && $('pnav-3')){
		var as_app = [], as_ext = [], all_as1 = $('pnav-1').getElements('a');
		var as_fac = [], as_lead = [], all_as3 = $('pnav-3').getElements('a');
		var li;
		
		$each(all_as1, function(a,ind){
			if(a.get('text').length > 0){
				if(a.get('text').indexOf('Application Form - ') >= 0){
					if(as_app.length == 0){
						li = new Element('li', { 'html':'Application Form', 'class':'alt-nav-title' }).inject(a.getParent(), 'before');
					}
	
					as_app.push(a);
					
				} else if(a.get('text').indexOf('Existing Volunteers - ') >= 0){
					if(as_ext.length == 0){
						li = new Element('li', { 'html':'Existing Volunteers', 'class':'alt-nav-title' }).inject(a.getParent(), 'before');
					}
					
					as_ext.push(a);
				}
			}
		});
		
		$each(all_as3, function(a,ind){
			if(a.get('text').length > 0){
				if(a.get('text').indexOf('Facilities - ') >= 0){
					if(as_fac.length == 0){
						li = new Element('li', { 'html':'Facilities', 'class':'alt-nav-title' }).inject(a.getParent(), 'before');
					}
	
					as_fac.push(a);
					
				} else if(a.get('text').indexOf('Leadership - ') >= 0){
					if(as_lead.length == 0){
						li = new Element('li', { 'html':'Leadership', 'class':'alt-nav-title' }).inject(a.getParent(), 'before');
					}
					
					as_lead.push(a);
				}
			}
		});
		
		$each(as_app, function(a,ind){
			a.set('text', a.get('text').replace(/Application Form - /, ''));
			a.addClass('alt-nav-style');
		});
		
		$each(as_ext, function(a,ind){
			a.set('text', a.get('text').replace(/Existing Volunteers - /, ''));
			a.addClass('alt-nav-style');
		});
		
		$each(as_fac, function(a,ind){
			a.set('text', a.get('text').replace(/Facilities - /, ''));
			a.addClass('alt-nav-style');
		});
		
		$each(as_lead, function(a,ind){
			a.set('text', a.get('text').replace(/Leadership - /, ''));
			a.addClass('alt-nav-style');
		});
	}	
}







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

function init(){
	fixIE6Footer();
	initInputs();
	if (!browser.isIE6) initSelects();
	initLightBoxElements();
	initPriNavHover();
	initStudyCalendar();
	initStudyGroups();
	initRSSSlider();
	initEmailAlert();
	initHiddenFormLayers();
	clearAppFormLastUsed();
	formatVolNav();
}


function initLoad(){	
	for(var i=0; i<pImages.length; i++){
		pImages[i] = root + pImages[i];
	}
	
	var loader = new Asset.images(pImages, {
		onProgress: function(counter, index){
		},
		onComplete: function(){
		}
	});
}




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

function memoryClean(e){
}





writeJsStyles(1);
window.addEvent('domready', function() { init(); });
window.addEvent('load', function() { var timer = initLoad.delay(7000); });
window.addEvent('unload', function() { memoryClean(); });