/* Javascript document for Forms within the Lightbox */

/****************************************************
* Check specific info on elements					*
*													*
*****************************************************/

function checkSpecificParent(el, type, name){
	var parent = el;
	var nodeName;
	while(parent != $(document.body)){
		if(type == 'id'){
			if(parent.id){
				if(parent.get('id') == name){
					return true;
				}
			}
		} else if(type == 'class'){
			if(parent.hasClass(name)){
				return parent;
			}
		} else if(type == 'hidden'){
			nodeName = parent.nodeName.toLowerCase();
			if(nodeName != 'input' && nodeName != 'select' && nodeName != 'textarea'){
				if(parent.getStyle('display') == 'none'){ return true; }			
			}
		}
		
		parent = parent.getParent();
	}
	
	return false;
}


/****************************************************
* Initialise Join Applications Dropdown				*
*													*
*****************************************************/

function showJointApplication(init){
	var form = $('joint-application').getParent('form');
	if($('joint-applicants-no').checked){ $('joint-application').setStyle('display', 'none'); if(!init){ disableHiddenInputs(form); } }
	else if($('joint-applicants-yes').checked){ $('joint-application').setStyle('display', 'block'); if(!init){ enableHiddenInputs('joint-application'); } }
}

function initJointApplication(){
	if($('joint-applicants-no') && $('joint-applicants-yes') && $('joint-application')){
		$('joint-applicants-no').addEvent('click', function() { showJointApplication(); });
		$('joint-applicants-no').addEvent('keypress', function(event) { if(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ showJointApplication(); } } } });
		$('joint-applicants-yes').addEvent('click', function() { showJointApplication(); });
		$('joint-applicants-yes').addEvent('keypress', function(event) { if(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ showJointApplication(); } } } });
		showJointApplication(true);
	}
}



/****************************************************
* Initialise Other Address Dropdown					*
*													*
*****************************************************/

function showOtherAddress(init){
	var form = $('other-address').getParent('form');
	if($('where-bill-sent-new').checked){ $('other-address').setStyle('display', 'none'); if(!init){ disableHiddenInputs(form); } }
	else if($('where-bill-sent-other').checked){ $('other-address').setStyle('display', 'block'); if(!init){ enableHiddenInputs('other-address'); } }
}

function initOtherAddress(){
	if($('where-bill-sent-new') && $('where-bill-sent-other') && $('other-address')){
		$('where-bill-sent-new').addEvent('click', function() { showOtherAddress(); });
		$('where-bill-sent-new').addEvent('keypress', function(event) { if(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ showOtherAddress(); } } } });
		$('where-bill-sent-other').addEvent('click', function() { showOtherAddress(); });
		$('where-bill-sent-other').addEvent('keypress', function(event) { if(event){ if(event.key){ if(event.key == 'space' || event.key == 'enter'){ showOtherAddress(); } } } });
		showOtherAddress(true);
	}
}






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

var SelectBox = new Class({

	Implements: [Events, Options],

	options: {		
		maxHeight: 16000,
		zIndex: 0,
		ref: false
	},

	initialize: function(select, options){
		this.setOptions(options);
		this.select = select;
		
		this.isHomePrefix = false;
		if(this.select.get('name')){
			if(this.select.get('name') == 'home_prefix'){
				this.isHomePrefix = true;
				this.optionsList = this.select.getElements('option');
				this.reorderedOptions = [];
				this.selectedIndex = this.select.selectedIndex;

				for(var i=0; i<13; i++){
					this.reorderedOptions[4*i] = this.optionsList[i];					
					this.reorderedOptions[4*i + 1] = this.optionsList[i+13];
					this.reorderedOptions[4*i + 2] = this.optionsList[i+26];
					this.reorderedOptions[4*i + 3] = this.optionsList[i+39];
				}
				
				this.select.empty();
				$each(this.reorderedOptions, function(option, ind){
					if(ind === 0){
						this.select.options[ind] = new Option(option.get('value'), option.get('value'), false, true);
					} else {
						this.select.options[ind] = new Option(option.get('value'), option.get('value'));
					}
					
				}.bind(this));
			}
		}
		
		if(this.select.getSize().x <= 0 || this.select.getSize().y <= 0){ return; }
		
		if(this.select.hasClass('styled') && !this.options.ref){
			return;
		}
		
		this.select.addClass('styled');
		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;
		selectClick = true;
		
		if(browser.isIE){ this.selectWidth = 2; }
		else { this.selectWidth = 3; }
		
		if(!this.select.get('oWidth')){
			this.select.set('oWidth', this.select.getSize().x);
			this.select.set('oHeight', this.select.getSize().y);
			this.select.set('oLeft', this.select.getPosition(this.parent).x);
			this.select.set('oTop', this.select.getPosition(this.parent).y);
		}
		
		this.holder = new Element('div', {
			'class': 'styled-select',
			'styles': {
				'width': this.select.get('oWidth').toInt() - this.selectWidth,
				'height': 30,	
				'z-index': this.options.zIndex
			}
		}).inject(this.select, 'before');
		
		this.parent.setStyles({'height':30, 'position':'relative', 'z-index': this.options.zIndex, 'overflow': 'hidden'});
		
		this.selHolder = new Element('div', {
			'styles': {
				'position': 'absolute',
				'left': this.select.get('oLeft').toInt() - 4,
				'top': this.select.get('oTop').toInt() - 5,
				'visibility': 'visible',/*
				'width': 0,*/
				'height': 0,
				'padding': '0',
				'overflow': 'hidden',
				'font-size': '0px',
				'border': 'none',
				'outline': 'none',
				'line-height': '0'
			}
		}).inject(this.parent);
		
		this.select.setStyles({
			'visibility': 'visible'
		});			
		
		this.selHolder.adopt(this.select);
		
		this.container = new Element('div', {
			'class': 'select-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.ddWidth = this.holder.getSize().x - 2;
		if(this.isHomePrefix){
			this.ddWidth = 217;
		}
		
		this.optionsHolder = new Element('div', {
			'class': 'styled-select-options',
			'styles': {
				'width': this.ddWidth,				
				'opacity': 0
			}
		}).inject($('wrapper'));
		
		this.optionsContent = new Element('div', {'class': 'content'}).inject(this.optionsHolder);				
		
		this.ul = new Element('ul', {'styles': {'margin': '0'}}).inject(this.optionsContent);
		var li, html, even_row = true;
		var li_styles = { 'background': 'none', 'padding': '1px 6px' }
		
		if(this.isHomePrefix){
			li_styles = { 'width': Math.floor((this.ul.getSize().x / 4) - 12), 'padding': '1px 6px', 'float': 'left', 'font-size': '95%' }
		}
		
		$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; }
				html = option.text;
			} else {
				html = '&nbsp;';
			}
				
			li = new Element('li', {
				'html': html,
				'styles': li_styles,
				'events': {
					'click': function(){ this.choose(index, option.text); selectClick=true; }.bind(this),
					'mousedown': function(){ this.choose(index, option.text); selectClick=true; }.bind(this)
				}
			}).inject(this.ul);
			
			if(this.isHomePrefix){
				if(even_row){
					li.setStyle('background', '#F9FBFF');
				} else {
					li.setStyle('background', '#FFF');
				}
				
				li.set('orig_bg', li.getStyle('background-color'));
				
				if((index+1) % 4 === 0 && index > 0){
					li.setStyle('width', li.getStyle('width').toInt() + 1);
					if(even_row){
						even_row = false;
					} else {
						even_row = true;
					}
				}
			}
			
		}.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.select.disabled){
			this.select.addEvents({
				'focus': function(){ this.openOptions(); }.bind(this),
				'blur': function(){ this.closeOptions(); }.bind(this),
				'keyup': function(event){
					if(event){
						if(event.key){
							if(event.key == 'space' || event.key == 'enter'){
								this.choose(this.select.selectedIndex, this.lis[this.select.selectedIndex].innerHTML);
							} else {
								this.highlight(this.lis[this.select.selectedIndex]);
							}														
						}
					}					
				}.bind(this)
			});
			
			this.selected.addEvents({
				'click': function(){ this.closeAll(); this.openOptions(); selectClick=true; }.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.openOptions(); selectClick=true; }.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)
			});
			
		//}
		
		/*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);
	},
	
	openOptions: function(){
		this.optionsHolder.setStyles({
			'opacity': 1,
			'left': this.holder.getPosition($(document.body)).x,
			'top': this.holder.getPosition($(document.body)).y + this.holder.getSize().y
		});		
	},
	
	closeOptions: function(){
		this.optionsHolder.setStyles({
			'opacity': 0,
			'left': -99999,
			'top': -99999
		});		
	},
	
	choose: function(index,text){
		var evt;
		if(text){ this.selected.innerHTML = text; }
		this.select.options[index].selected = 'selected';
		this.select.selectedIndex = index;
		this.optionsHolder.setStyles({ 'opacity':0, 'left': -99999, 'top': -99999 })

		if(this.select.getAttribute('onchange')){
			if(this.select.fireEvent){
				this.select.onchange();
			}
			
			if(document.createEvent){
				evt = document.createEvent('HTMLEvents');
				if(evt.initEvent){ evt.initEvent('change', true, true); }
				if(this.select.dispatchEvent){ this.select.dispatchEvent(evt); }
			}
		}
		
		this.select.fireEvent('keypress');
	},
	
	highlight: function(li){
		$each(this.lis, function(li, index){
			if(li.get('orig_bg')){
				li.setStyles({'background':li.get('orig_bg')});
			} else {
				li.setStyles({'background':'none'});
			}
		}.bind(this));
		
		li.setStyles({'background':'#D1D8E0'});
	},
	
	closeAll: function(){
		if($(document.body)){
			this.dds = $(document.body).getElements('.styled-select-options');
			this.dds.each(function(dd, index){
				dd.setStyles({ 'opacity': 0, 'left': -99999, 'top': -99999 });
			});
		}
	}
});



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








/****************************************************
* Initialise Styled Radio Buttons					*
*													*
*****************************************************/

var RadioButton = new Class({

	Implements: [Events, Options],

	options: {
		checkbox: false,
		cls: 'styled-radio'
	},

	initialize: function(radio, options){
		this.setOptions(options);
		this.radio = radio;
		this.parent = radio.getParent();
		this.name = this.radio.get('name');
		this.others = [];
		this.cls = this.options.cls;
		this.tmpCls = '';
		this.chrAt = false;
		
		if(this.radio.getParent('form')){
			this.others = this.radio.getParent('form').getElements('input[name=' + this.name + ']');
		}
		
		if(this.radio.checked){ this.cls = this.options.cls + ' ' + this.options.cls + '-active'; }
		
		this.parent.setStyle('position', 'relative');
		this.radio.setStyles({
			'left': this.radio.getPosition(this.parent).x + 4,
			'top': this.radio.getPosition(this.parent).y - 10,
			'position': 'absolute'
		});
		
		this.sRadio = new Element('div', {
			'class': this.cls + ' sRadio',			
			'events': {
				'click': function(){ this.check(); }.bind(this),
				'mouseenter': function(){ this.enter(); }.bind(this),
				'mouseleave': function(){ this.leave(); }.bind(this)
			}
		}).inject(this.radio, 'after');
		
		if(this.radio.get('title')){
			this.sRadio.set('title', this.radio.get('title'));
		}
		
		if(browser.isIE6 || browser.isIE5){
			if(checkSpecificParent(this.sRadio, 'id', 'ajax-content')){
				if(!$('ajax-content').hasClass('auto-adjusted')){
					$('ajax-content').setStyles({
						'height': $('ajax-content').getSize().y,
						'overflow': 'hidden',
						'position': 'relative'
					});
					$('ajax-content').addClass('auto-adjusted')
				}
			}
		}
	},
	
	check: function(){
		if(this.others.length > 1){
			$each(this.others, function(rad, i){
				$each(rad.getParent().getElements('.sRadio'), function(styRad, j){
					this.tmpCls = '';
					this.chrAt = Math.max(styRad.className.indexOf('-over'), styRad.className.indexOf('-active'));
					if(this.chrAt > 0){
						this.chrAt--;
						while(styRad.className.charAt(this.chrAt) != ' ' && this.chrAt > -1){
							this.tmpCls = styRad.className.charAt(this.chrAt) + this.tmpCls;
							this.chrAt--;
						}
						
						styRad.removeClass(this.tmpCls + '-over');
						styRad.removeClass(this.tmpCls + '-active');
					}										
				}.bind(this));
			}.bind(this));
		}
		
		if(!this.options.checkbox){
			this.sRadio.removeClass(this.options.cls + '-over');			
			this.sRadio.addClass(this.options.cls + '-active');
			this.radio.checked = 'checked';
		
		} else {
			if(this.sRadio.hasClass(this.options.cls + '-active')){
				this.sRadio.removeClass(this.options.cls + '-active');
				this.radio.checked = false;
			} else {
				this.sRadio.removeClass(this.options.cls + '-over');
				this.sRadio.addClass(this.options.cls + '-active');
				this.radio.checked = 'checked';
			}
		}
		
		this.radio.fireEvent('click');
		this.radio.fireEvent('keypress');
	},
	
	enter: function(){
		if(!this.sRadio.hasClass(this.options.cls + '-active')){			
			this.sRadio.addClass(this.options.cls + '-over');
		}
	},
	
	leave: function(){
		this.sRadio.removeClass(this.options.cls + '-over');
	}
});


function initRadioButtons(){		
	var rad, radios, checks;
	if($('lb-body')){
		radios = $('lb-body').getElements('.radio-button');
		radios.each(function(radio, index){
			rad = new RadioButton(radio, {});
		});
		
		checks = $('lb-body').getElements('.checkbox');
		checks.each(function(check, index){
			rad = new RadioButton(check, {checkbox: true});
		});
	}
	
	if($('cs-form-torso')){
		radios = $('cs-form-torso').getElements('.radio-button');
		sRadios = $('cs-form-torso').getElements('.sRadio');
		if(sRadios.length < 1){
			radios.each(function(radio, index){
				if(radio.hasClass('bad')){ rad = new RadioButton(radio, {cls: 'bad'}); }
				if(radio.hasClass('poor')){ rad = new RadioButton(radio, {cls: 'poor'}); }
				if(radio.hasClass('average')){ rad = new RadioButton(radio, {cls: 'average'}); }
				if(radio.hasClass('good')){ rad = new RadioButton(radio, {cls: 'good'}); }
				if(radio.hasClass('excellent')){ rad = new RadioButton(radio, {cls: 'excellent'}); }
			});
		}
	}
	
	if($('cu-get-in-touch') && $('questionnaire')){
		radios = $('questionnaire').getElements('.radio-button');
		sRadios = $('questionnaire').getElements('.sRadio');
		if(sRadios.length < 1){
			radios.each(function(radio, index){
				if(radio.hasClass('bad')){ rad = new RadioButton(radio, {cls: 'bad'}); }
				if(radio.hasClass('poor')){ rad = new RadioButton(radio, {cls: 'poor'}); }
				if(radio.hasClass('average')){ rad = new RadioButton(radio, {cls: 'average'}); }
				if(radio.hasClass('good')){ rad = new RadioButton(radio, {cls: 'good'}); }
				if(radio.hasClass('excellent')){ rad = new RadioButton(radio, {cls: 'excellent'}); }
			});
		}
	}		
}



function redrawFormSifrs(){
	if(sIFR && !browser.isIE5 && !browser.isIE6){
		sIFR.replace(gotham_book, {
			selector: sifrSelectors[6],
			ratios: [6, 1.24, 11, 1.13, 12, 1.12, 21, 1.07, 29, 1.04, 30, 1.05, 49, 1.03, 53, 1.02, 54, 1.03, 74, 1.02, 77, 1.01, 78, 1.02, 83, 1.01, 84, 1.02, 89, 1.01, 90, 1.02, 95, 1.01, 96, 1.02, 1.01],
			css: {
				'.sIFR-root': { 'color':'#003366', 'font-size':'21px'},
				'.pink': { 'color':'#EE0090', 'font-weight':'bold' }
			},
			wmode: 'transparent',
			onReplacement: function(){ }
		});
		
		sIFR.replace(gotham_book, {
			selector: sifrSelectors[2],
			ratios: [6, 1.24, 11, 1.13, 12, 1.12, 21, 1.07, 29, 1.04, 30, 1.05, 49, 1.03, 53, 1.02, 54, 1.03, 74, 1.02, 77, 1.01, 78, 1.02, 83, 1.01, 84, 1.02, 89, 1.01, 90, 1.02, 95, 1.01, 96, 1.02, 1.01],
			css: {
				'.sIFR-root': { 'color':'#003366', 'font-size':'21px'},
				'.center': { 'display':'block', 'text-align':'center' },
				'.white': { 'color':'#FFFFFF', 'font-size':'25px' },
				'.dark-blue': { 'color':'#48133D' }
			},
			wmode: 'transparent',
			fitExactly: false,
			forceWidth: false,
			preventWrap: false,
			forceSingleLine: false,
			onReplacement: function(){ }
		});
	}
}






/****************************************************
* Initialise Terms and Conditions Popups			*
*													*
*****************************************************/

function getTermsAndConditions(a,manual,show){
	if(a.id){
		if(a.get('id').indexOf('view-') === 0){
			var id = a.get('id').substring(5,a.get('id').length);
			
			if($(id)){
				if($(id).get('busy')){
					if($(id).get('busy') == 1){ return; }
				}
				
				$(id).set('busy', 1);
				a.blur();
				
				if($(id).innerHTML.length > 0){
					if(manual){
						if(show){
							$(id).setStyle('display', 'block');
						} else {							
							$(id).setStyle('display', 'none');
						}
					
					} else {					
						if($(id).getStyle('display') != 'none'){
							$(id).setStyle('display', 'none');
						} else {
							$(id).setStyle('display', 'block');
						}
					}
					
					if(browser.isIE6 || browser.isIE5){
						if($('ajax-content') && $('lb-body')){
							$('ajax-content').setStyle('height', $('lb-body').getSize().y);
						}
					}
						
					$(id).set('busy', 0);
					resizeLightBox();
					
				} else {
					var inner;
					var html = new Request.HTML({
						method: 'get',
						url: a.get('href'),
						noCache: true,
						evalScripts: false,
						onRequest: function(){},
						onComplete: function(){},
						onSuccess: function(tree, elements, html, js){
							var ajaxContent = elements.filter(function(el) {
								if(el.id){
									if(el.id == id){ return el; }
								}
							});
							
							if(ajaxContent.length > 0){
								var inner = new Element('div', {
									'html': ajaxContent[0].innerHTML,
									'styles': {
										'width': '100%',
										'float': 'left'
									}
								}).inject($(id));

								$(id).setStyles({
									'width': $(id).getParent().getSize().x - 40 - $(id).getParent().getStyle('padding-left').toInt() - $(id).getParent().getStyle('padding-right').toInt(),
									'height': 300,
									'max-height': 300,
									'margin': '0 0 20px 0',
									'padding': '20px',
									'float': 'left',
									'overflow': 'hidden',
									'overflow-y': 'auto',
									'background': '#FCFCFC',
									'position': 'relative',
									'display': 'block'
								});
								
								if(browser.isIE6 || browser.isIE5){
									if($('ajax-content') && $('lb-body')){
										$('ajax-content').setStyle('height', $('lb-body').getSize().y);
									}
								}
							}
							
							$(id).set('busy', 0);
							resizeLightBox();
						},
						onFailure: function(xhr){ }
					}).send();
				}
			}
		}
	}
}


function initTermsAndConditions(){
	if($('lb-body')){
		var as = $('lb-body').getElements('a.tcs');
		as.addEvents({
			'click': function(event){
				event.stop();
				getTermsAndConditions(this);
			},
			'keypress': function(event){
				if(event.key){
					if(event.key == 'space' || event.key == 'enter'){
						event.stop();
						getTermsAndConditions(this);
					}
				}
			}
		});
		
		if($('view-terms-conditions') && $('view-data-protection' && 'view-travel-voucher-terms')){
			if(!($('view-terms-conditions').hasClass('tcs')) && !($('view-data-protection').hasClass('tcs')) && !($('view-travel-voucher-terms').hasClass('tcs')) && $('view-terms-conditions').get('href') && $('view-data-protection').get('href') && $('view-travel-voucher-terms').get('href')){				
				$('view-terms-conditions').addEvents({
					'click': function(event){
						event.stop();
						getTermsAndConditions(this);
						getTermsAndConditions($('view-data-protection'), true, false);
					},
					'keypress': function(event){
						if(event.key){
							if(event.key == 'space' || event.key == 'enter'){
								event.stop();
								getTermsAndConditions(this);
								getTermsAndConditions($('view-data-protection'), true, false);
							}
						}
					}
				});
				
				$('view-data-protection').addEvents({
					'click': function(event){
						event.stop();
						getTermsAndConditions(this);
						getTermsAndConditions($('view-terms-conditions'), true, false);
					},
					'keypress': function(event){
						if(event.key){
							if(event.key == 'space' || event.key == 'enter'){
								event.stop();
								getTermsAndConditions(this);
								getTermsAndConditions($('view-terms-conditions'), true, false);
							}
						}
					}
				});

				$('view-travel-voucher-terms').addEvents({
					'click': function(event){
						event.stop();
						getTermsAndConditions(this);
						getTermsAndConditions($('view-terms-conditions'), true, false);
					},
					'keypress': function(event){
						if(event.key){
							if(event.key == 'space' || event.key == 'enter'){
								event.stop();
								getTermsAndConditions(this);
								getTermsAndConditions($('view-terms-conditions'), true, false);
							}
						}
					}
				});
			}
		}
	}
}








/****************************************************
* Form Validation									*
*													*
*****************************************************/

function disableHiddenInputs(form){
	var formEls = form.getElements('input, textarea, select');
	$each(formEls, function(el, i){
		if(checkSpecificParent(el, 'hidden')){
			el.set('disabled', 'disabled');
		}
	});
	
	$each(formValidators, function(form,i){
		form.reinitialize('forced');
	});
}


function enableHiddenInputs(id){
	if($(id)){
		var formEls = $(id).getElements('input, textarea, select');
		$each(formEls, function(el, i){
			el.erase('disabled');
		});
		
		$each(formValidators, function(form,i){
			form.reinitialize('forced');
		});
	}
}


function validateDefaults(el){	
	if(el.get('def_value')){
		el.errors.push('This field is required.');
		return false;						
	} else {
		return true;
	}
}


function validateTelephone(el){	
	if (!el.value.test(/[0-9]{3} [0-9]{7}/)){
		el.errors.push('Telephone number must have a 3-digit<br />area code followed by a space followed<br />by the 7-digit local number.<br />e.g. 087 1234567');
		return false;						
	} else {
		return true;
	}
}


function validateLocalNum(el){	
	if (!el.value.test(/[0-9]{7}/)){
		el.errors.push('Please enter a valid 7-digit local number.');
		return false;						
	} else {
		return true;
	}
}


function validateAccNum(el){	
	if (!el.value.test(/[0-9]{10}/)){
		el.errors.push('Please enter a valid 10-digit account number.');
		return false;						
	} else {
		return true;
	}
}


function validateForms(){
	var fx = [], ids = [];
	var forms = $$('form.validate');
	var fx_el = [], resp_el = [], resp_fx_el = [], req, name, error = '';
	var hasUpdateable = [];
	var growDuration = [];
	var inputs;
	
	$each(forms, function(vForm, ind){
		if(!vForm.hasClass('validated')){
			vForm.addEvent('submit', function(e){
				e.stop();
				error = '';
			});
		}
		
		hasUpdateable[ind] = checkSpecificParent(vForm, 'class', 'ajax-updateable');
		if(hasUpdateable[ind]){ fx_el[ind] = hasUpdateable[ind]; }
		else { fx_el[ind] = vForm; }
		
		if(vForm.hasClass('no-growing')){ growDuration[ind] = 600; }
		else { growDuration[ind] = 0; }
		
		if(vForm.hasClass('validated')){ fx[ind] = null; }
		else {
			
			disableHiddenInputs(vForm);
			
			fx[ind] = new Fx.Morph(fx_el[ind], {
				duration: 300,
				onComplete: function(){
					var sDuration = 0;
					
					if(window.getScroll().y > 0){
						if(checkSpecificParent(vForm, 'id', 'customer-satisfaction-popup') || checkSpecificParent(vForm, 'id', 'opt-out-div')){ sDuration = 0; }
						else { sDuration = parseInt(300 + window.getScroll().y/4, 10); }
					}
					
					var bodyFx = new Fx.Scroll(window, {
						duration: sDuration,
						wheelStops: false,
						onComplete: function(){							
					
							if(vForm.get('action')){
								req = new Request.HTML({
									url: vForm.get('action'),
									data: vForm,
									evalScripts: false,
									onRequest: function(){ },
									onSuccess: function(tree, elements, html, js){
										var ajaxResponse = elements.filter(function(el) {
											if(el.hasClass('ajax-response')){
												return el;
											}
										});
										
										if(ajaxResponse.length > 0){									
											var resp = new Element('div', {
												'id': 'ajax-response-' + ind,
												'class': 'ajax-response',
												'html': ajaxResponse[0].innerHTML,
												'styles': {										
													'opacity': 0,
													'position': 'absolute',
													'left': 0,
													'top': 0
												}
											});
											
											if(hasUpdateable[ind]){ resp_el[ind] = hasUpdateable[ind]; }
											else { resp_el[ind] = vForm; }
											
											resp.inject(resp_el[ind], 'before');
											
											var diff = -1 * (resp_el[ind].getSize().y - resp.getSize().y);
											
											if(hasUpdateable[ind]){ resp_fx_el[ind] = hasUpdateable[ind]; }
											else { resp_fx_el[ind] = $('ajax-response-' + ind); }
											
											var respEffect = new Fx.Morph(resp_fx_el[ind], {
												duration: 300,
												onComplete: function(){ $('lightbox').set('busy', 0); }
											});
											
											var growFX = new Fx.Morph($('lightbox-content-inner'), {
												duration: growDuration[ind],
												transition: Fx.Transitions.Cubic.easeOut,
												onComplete: function(){
													if(hasUpdateable[ind]){
														if(vForm.hasClass('no-growing')){
															hasUpdateable[ind].setStyles({
																'height': hasUpdateable[ind].getSize().y.toInt() - hasUpdateable[ind].getStyle('margin-top').toInt() - hasUpdateable[ind].getStyle('margin-bottom').toInt() - hasUpdateable[ind].getStyle('padding-top').toInt() - hasUpdateable[ind].getStyle('padding-bottom').toInt(),
																'min-height': hasUpdateable[ind].getSize().y.toInt() - hasUpdateable[ind].getStyle('margin-top').toInt() - hasUpdateable[ind].getStyle('margin-bottom').toInt() - hasUpdateable[ind].getStyle('padding-top').toInt() - hasUpdateable[ind].getStyle('padding-bottom').toInt()
															});
														}
														
														hasUpdateable[ind].innerHTML = '';
														hasUpdateable[ind].adopt($('ajax-response-' + ind));
														$('ajax-response-' + ind).setStyle('opacity',1);
													}
													
													if(vForm.get('action').indexOf('customer-satisfaction-card.php') >= 0){
														if($('cs-form-header')){
															 resp.setStyle('top', $('cs-form-header').getSize().y);
														}
														
														//closeCustomerSatisfaction.delay(2000);
													
													} else { resp.setStyle('position','relative'); }
													
													$('ajax-response-' + ind).erase('id');													
													attachLbEvents();
													initLbForms();
													respEffect.start({ 'opacity': 1 });
													formSubmitting = false;													
												}
											});
											
											if(vForm.hasClass('no-growing')){
												growFX.start({ 'left': $('lightbox-content-inner').getStyle('left').toInt() });
											} else {
												growFX.start({ 'height': [Math.max(0, $('lightbox-content-inner').getSize().y.toInt()), Math.max(0, $('lightbox-content-inner').getSize().y.toInt() + diff)] });
											}																	
										}														
									}
								}).send();
							}
						}
					});		// end bodyFx
					
					
					if(checkSpecificParent(vForm, 'id', 'customer-satisfaction-popup') || checkSpecificParent(vForm, 'id', 'opt-out-div')){
						bodyFx.start(0, window.getScroll().y);
					} else if(checkSpecificParent(vForm, 'class', 'cu-form')){
						if($('cu-get-in-touch')){
							bodyFx.toElement($('cu-get-in-touch'));
						} else {
							bodyFx.start(0, 0);
						}
					} else {
						bodyFx.start(0, 0);
					}					
					
				}
			});		// end fx[ind]
		}
		
		
		
		if(vForm.hasClass('validated')){ fx[ind] = null; }
		else {
			if(!vForm.id){ vForm.set('id','vForm-'+ind); }			
			ids[ind] = vForm.get('id');
			
			formValidators[ind] = new FormCheck(ids[ind], {
				regexp : {
					date: /^((0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)\d\d)$/,
					trim: /^\s+|\s+$/g
				},
				alerts : {
					date: 'This must be a valid date - dd/mm/yyyy',
					trim: 'Please remove whitespaces from the<br />beginning and end of this value'
				},
				display : {
					showErrors : 0,	
					flashTips : 1,
					scrollToFirst: vForm.hasClass('no-scroll')? false:true
				},				
				submit: false,
				onValidateSuccess: function(){
					if(!vForm.hasClass('passedValidation')){
						vForm.addClass('passedValidation');
					}
					
					inputs = vForm.getElements('input');
					$each(inputs, function(input, count){
						if(input.className){
							if(input.className.indexOf('validate') >= 0 && input.className.indexOf('email') >= 0){
								if(input.get('value')){
									input.set('value', input.get('value').replace(/^\s\s*/, '').replace(/\s\s*$/, ''));
								}																										
							}
						}
					});
					
					if(vForm.hasClass('no-response')){
						vForm.submit();
					} else if(vForm.hasClass('no-submit')){
						if(vForm.getElement('input[name=next_action]')){
							eval(vForm.getElement('input[name=next_action]').get('value'));
						}
					} else if(vForm.hasClass('upload')){
						try {
							uploadFormSubmit();
						} catch(err){}
					} else {
						if(checkSpecificParent(vForm, 'id', 'lightbox-content-inner') || checkSpecificParent(vForm, 'id', 'customer-satisfaction-popup') || checkSpecificParent(vForm, 'id', 'opt-out-div') || checkSpecificParent(vForm, 'class', 'cu-form')){
							formSubmitting = true;
							fx[ind].start({ 'opacity': 0 });
							$('lightbox').set('busy', 1);
						} else {
							vForm.submit();
						}
					}					
				},
				onValidateFailure: function(){}
			});
		}
		
		
		if(!vForm.hasClass('validated')){
			vForm.addClass('validated');	// only apply validation once
		}				
		
	});
}











/****************************************************
* Initialise Contact Us Form Navigation				*
*													*
*****************************************************/

function openContactUsForm(id){
	if($(id)){
		$('cu-forms-intro').setStyle('display', 'none');
		$(id).setStyles({
			'left': 0,
			'top': 0,
			'position': 'relative'
		});
	}
}

function initContactUsNav(){
	if($('cu-forms-intro') && $('cu-forms-nav')){
		var others, parent, id;
		$$('#cu-forms-nav div').addEvents({
			'click': function(){
				parent = this.getParent('li');
				if(parent.id){
					if(parent.get('id').indexOf('-but') >= 0){
						id = parent.get('id').substring(0, parent.get('id').indexOf('-but'));
						openContactUsForm(id);
					}
				}
			},
			'mouseenter': function(){
				parent = this.getParent('ul');
				others = parent.getElements('div');
				others.removeClass('over');
				this.addClass('over');
			},
			'mouseleave': function(){
				this.removeClass('over');
			}
		});
		
		if(document.URL.indexOf('form=submit-a-query') >= 0){
			if($('submit-a-query')){
				 openContactUsForm('submit-a-query');
				 scrollToElement('submit-a-query');
			}
		} else if(document.URL.indexOf('form=call-me-back') >= 0){
			if($('call-me-back')){
				openContactUsForm('call-me-back');
				 scrollToElement('call-me-back');
			}
		} else if(document.URL.indexOf('form=questionnaire') >= 0){
			if($('questionnaire')){
				openContactUsForm('questionnaire');
				 scrollToElement('questionnaire');
			}
		}				
	}
	
	if($('cu-get-in-touch') && $('cu-forms-intro')){
		$$('#cu-get-in-touch .cu-form-close').addEvents({
			'click': function(){
				if(this.getParent().hasClass('cu-form')){
					$('cu-forms-intro').setStyle('display', 'inline');
					this.getParent().setStyles({
						'left': -9999999,
						'top': -9999999,
						'position': 'absolute'
					});
				}
			},
			'mouseenter': function(){
				this.addClass('cu-form-close-over');
			},
			'mouseleave': function(){
				this.removeClass('cu-form-close-over');
			}
		});
	}
}




/****************************************************
* Initialise Popups on Help Icons					*
*													*
*****************************************************/

function initHelpPopups(){
	var icons = $$('.help-icon');
	if(icons.length > 0){
		var help_popup = new Element('div', {
			'id': 'help-explanation-popup',
			'class': 'fc-tbx',
			'html': '<table cellspacing="0" cellpadding="0" border="0"><tbody><tr><td class="tl"></td><td class="t"></td><td class="tr"></td></tr><tr><td class="l"></td><td class="c"><div class="err"></div></td><td class="r"></td></tr><tr><td class="bl"></td><td class="b"></td><td class="br"></td></tr></tbody></table>',
			'styles': {
				'opacity': 0
			}
		}).inject($(document.body));
		
		var inner = $('help-explanation-popup').getElement('div.err');
		var duration = browser.isIE ? 0 : 200;
		var fx = new Fx.Morph($('help-explanation-popup'), {
			duration: duration,
			link: 'cancel'
		});
		
		$each(icons, function(icon, ind){
			icon.addEvents({
				'mouseenter': function(){
					if(this.getNext('.help-text')){
						fx.set({ 'opacity': 0 });
						inner.innerHTML = this.getNext('.help-text').innerHTML;
						$('help-explanation-popup').setStyles({
							'left': this.getPosition($('wrapper')).x - 30,
							'top': this.getPosition($('wrapper')).y - $('help-explanation-popup').getSize().y
						});
						fx.start({ 'opacity': 1 });
					}
				},
				'mouseleave': function(){
					fx.start({ 'opacity': 0 });
				}
			});
		});
	}
}






/****************************************************
* On DOM Ready Functions							*
*													*
*****************************************************/

function initLbForms(){	
	initJointApplication();
	initOtherAddress();	
	initRadioButtons();
	initTermsAndConditions();
	initContactUsNav();	
	initHelpPopups();
	
	if(document.URL.indexOf('/admin/') < 0){
		initSelects();	
	}
	
	if(document.URL.indexOf('/generic/') < 0){
		redrawFormSifrs();
		initInputs($('lightbox'));
		initInputs($('customer-satisfaction'));
	}		
	
	if(!formCheckLoaded){
		var formcheck_css = new Asset.css(root + 'css/formcheck.css');
		var formcheck_js = new Asset.javascript(root + 'js/formcheck.js', {
			onload: function(){
				formCheckLoaded = true;
				validateForms();
			}
		});
	} else {
		validateForms();
	}		
}

if(document.URL.indexOf('/generic/') >= 0){
	window.addEvent('domready', function() { initLbForms(); });
}
