/*
 Functions related to Ajax requests going to the server, e.g. registration etc
 */

var root = "/";
//var root = "/Oxigen/development/";
var browser, directory, sifrReplaced = 0;
var lbFormsJS = false;



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



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

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

function resizeLightBox(){
	var forms, height = 0;
	if($('tabs-wrapper')){		
		forms = $('tabs-wrapper').getElements('form');
		$each(forms, function(form, ind){
			if(form.getParent().getStyle('display') != 'none'){
				height += form.getSize().y;
			}
		});
		
		height += 60;
		
		//$('tabs-wrapper').setStyles({'height': Math.max(325, height), 'min-height': Math.max(325, height)});
		//$('lightbox-content-inner').setStyle('height', Math.max($('tabs-wrapper').getSize().y, height));
	}
	if($('lightbox-overlay')){
		if($('lightbox-overlay').getStyle('height').toInt() > 0){
			$('lightbox-overlay').setStyle('height', Math.max($('wrapper').getSize().y, $('lightbox').getSize().y));
		}
	}
}

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

function openLightBox(el, url, x, y, width, height){

	if($('wrapper') && $('header')){
		var coords= {}, hCoords, flash;
		var opened = true;
		var duration = 300;
		if(browser.isIE){ duration = 0; }
		
		var href;
		if(el){
			if(el.get('href')){ href = el.get('href'); }
			else if(url){ href = url; }
		} else if(url){
			href = url;
		}
		
		if(!$('lightbox').get('open') || $('lightbox').get('open') == 0){
			opened = false;
			$('lightbox').set('open', 1);
			if(url){
				flash = $('flashcontent-homepage');
				coords.left = flash.getPosition($('wrapper')).x.toInt() + x.toInt();
				coords.top = flash.getPosition($('wrapper')).y.toInt() + y.toInt();
				coords.width = width.toInt();
				coords.height = height.toInt();
			} else {
				coords = el.getCoordinates($('wrapper'));
			}
			
			hCoords = $('header').getCoordinates($('wrapper'));
		}				
		
		var elements = [$('lightbox'), $('lightbox-content-inner'), $('lightbox-close-but')];
		var o1 = {}, o2 = {};
		var blendFX = new Fx.Elements([elements[1], elements[2]], {
			duration: duration,
			onComplete: function(){ $('lightbox').set('busy', 0); }
		});
		
		var growFX = new Fx.Elements([elements[0], elements[1]], {
			duration: 600,
			transition: Fx.Transitions.Cubic.easeOut,
			onComplete: function(){
				$('lightbox-content-inner').innerHTML = $('lightbox-tmp').innerHTML;
				if(el){
					if(el.get('href').indexOf('?tab=') >= 0){ initTabs(1); }
					else { initTabs(); }
				} else if(url) {
					if(url.indexOf('?tab=') >= 0){ initTabs(1); }
					else { initTabs(); }
				}
				
				//initTabs();
				$('lightbox-tmp').innerHTML = '';
				
				if($('lightbox-overlay')){
					$('lightbox-overlay').addEvents({
						'click': function(){ closeLightBox(); }
					});
				}
				
				$('lightbox-overlay').setStyle('height', Math.max($('wrapper').getSize().y, $('lightbox').getSize().y));
				
				attachLbEvents();
				//initLbForms();
				blendFX.start(o2);
			}
		});						
		
		if(!opened){
			$('lightbox').setStyles({ 'left': coords.left - 8, 'top': coords.top - 8 });
			$('lightbox-content-inner').setStyles({ 'width': coords.width, 'height': coords.height });		
			$('lightbox').set('oLeft', coords.left - 8);
			$('lightbox').set('oTop', coords.top - 8);
			$('lightbox').set('oWidth', coords.width);
			$('lightbox').set('oHeight', coords.height);
		
			//l = parseInt(hCoords.width/2) - parseInt(coords.width/2);
			
		
			l = hCoords.left + 325;
			
			o1[0] = {left: l, top: 0};
			if(el){
				if(el.hasClass('to-center')){
					o1[0] = {left: hCoords.left + 3, top: Math.max(0, parseInt(getSizeY()/2,10) - parseInt($('lightbox-tmp').getSize().y/2,10) + window.getScroll().y - 8)};
				}
			}
		}				
		
		o1[1] = {width: 330, height: $('lightbox-tmp').getSize().y};
		o2[0] = {opacity: 1};
		o2[1] = {opacity: 1};
		growFX.start(o1);
	}

}

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

function readLbHtml(el, url, x, y, width, height){
	
	var href;
	if(el){
		if(el.get('href')){ href = el.get('href'); }
		else if(url){ href = url; }
	} else if(url){
		href = url;
	}
	
	var html = new Request.HTML({
		method: 'get',
		url: href,
		noCache: true,
		evalScripts: false,
		onRequest: function(){},
		onComplete: function(){},
		onSuccess: function(tree, elements, html, js){
			var ajaxContent = elements.filter(function(el) {
				return el.id.test(/^ajax-content/i);
			});

			if(ajaxContent.length > 0){
				$('lightbox-tmp').innerHTML = ajaxContent[0].innerHTML;
				openLightBox(el, url, x, y, width, height);
			}
		},
		onFailure: function(xhr){ $('lightbox').set('busy', 0); }
	}).send();
}

function openLbPage(el, url, x, y, width, height){

	if(!lbFormsJS || $('lightbox').get('busy') == 1){ return; }
	var duration = 0;
	
	if(window.getScroll().y > 0){
		duration = parseInt(300 + window.getScroll().y/4, 10);
	}

	if($('lightbox-overlay')){
		$('lightbox-overlay').setStyle('height', $('wrapper').getSize().y);
	}

	if(el){
		if(!el.get('href')){ return; }
	} else {
		if(!url){ return; }
	}
	
	var bodyFx = new Fx.Scroll(window, {
		duration: duration,
		wheelStops: false,
		onComplete: function(){
			readLbHtml(el, url, x, y, width, height);
		}
	});
	
	$('lightbox').set('busy', 1);
	
	if(el){
		if(el.hasClass('to-center')){
			readLbHtml(el, url, x, y, width, height);
		} else {
			bodyFx.start(0, 0);
		}
	} else {
		bodyFx.start(0, 0);
	}
}

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


function clickTest() {
	var as = $(document.body).getElements('a');
	$each(as, function(a,i){
		a.addEvents({
			'click': function(event){ /*a;ert('click');*/ }
		});
	});
}


/****************************************************
* Switch form										*
*													*
*****************************************************/
var switchLocationsXML = null;
var currentSwitchStep = 1;


function initSwitchForm() {
	if ($('switch-form')) {
		// only show the first tab
		$('step2-wrapper').setStyles({display: 'none', opacity: 0});
		$('step3-wrapper').setStyles({display: 'none', opacity: 0});
		$('step4-wrapper').setStyles({display: 'none', opacity: 0});
		$('dd-thank-you').setStyles({display: 'none', opacity: 0});
		
		// populate the counties dropdown
		var countyRequest = new Request({
					method: 'get', 
					url: root + 'php/ajax/switch/counties.php',
					onSuccess: function(responseText, responseXML) {
						switchLocationsXML = responseXML;
						var counties_a = responseXML.getElementsByTagName("county");
						$('county-select').options.length = counties_a.length + 1;
						for (i=0;i<counties_a.length;i++) {
							opt = i + 1;
							county = counties_a[i].getAttribute("name");
							$('county-select').options[opt] = new Option(county, county);
							
						}
					}
		});
		countyRequest.send();
		
		
		// Form Validators 
		var step1Validator = new FormValidator.Inline($('switch-form'), {
			scrollToErrorsOnSubmit: false,
			onFormValidate: function(passed, form, event) {
				if (passed) {
					event.preventDefault(); //stop the normal behavior of submitting the form.
					var bSubmitForm = false;
					nextSwitchStep = currentSwitchStep + 1;
					window.scrollTo(0,0);
					
					if (nextSwitchStep == 5) {
						bSubmitForm = true;
						form.set('send', {onComplete: function(response) { 
							if (response == "Success") {
								var myEffect = new Fx.Morph('step' + currentSwitchStep + '-wrapper', {
									duration: browser.isIE ? 0 : 'long',
									transition: Fx.Transitions.Sine.easeOut,
									onComplete: function () {
										$('step' + currentSwitchStep +'-wrapper').setStyles({display: 'none'});
										$('dd-thank-you').setStyles({display: 'block'});
										$('dd-thank-you').fade("in");
									}
								});
								myEffect.start({
						   		 'opacity': [1, 0] 
								});
							}
							else {
								alert(response);
							}		
						}});
						form.send();	
					}
					else if (nextSwitchStep == 4 && $('payment-method').options[$('payment-method').selectedIndex].value == "cc") {
						bSubmitForm = true;
						form.set('send', {onComplete: function(response) { 
							if (response.indexOf("MERCHANT_ID") != -1) {
								// Success
								if ($('realex-fields')) $('realex-fields').dispose();
								var realexDiv = new Element("div");
								realexDiv.set("html", response);
								realexDiv.inject($('switch-form'));
								form.set("action", "https://epage.payandshop.com/epage.cgi");
								form.submit();
							}
						}});
						form.send();
					}
					else {
						var myEffect = new Fx.Morph('step' + currentSwitchStep + '-wrapper', {
							duration: browser.isIE ? 0 : 'long',
							transition: Fx.Transitions.Sine.easeOut,
							onComplete: function () {
								
								if (nextSwitchStep == 3) prefillSwitchSummary();
								else if (nextSwitchStep == 4) {
									prefillDirectDebitDetails();
									if ($('payment-method').options[$('payment-method').selectedIndex].value == "dd") {
										
									}
								}
								
								
								if (!bSubmitForm) {
									$('step' + currentSwitchStep +'-wrapper').setStyles({display: 'none'});
									$('step' + nextSwitchStep + '-wrapper').setStyles({display: 'block'});
									
									for (tab = 1;tab<currentSwitchStep;tab++) {
										$('step' + tab + "-tab").set("src", $('step' + tab + "-tab").get("src").replace("2.gif", "1.gif"));
									}
									
									$('step' + nextSwitchStep + "-tab").set("src", $('step' + nextSwitchStep + "-tab").get("src").replace("1.gif", "_a.gif"));
									$('step' + currentSwitchStep + "-tab").set("src", $('step' + currentSwitchStep + "-tab").get("src").replace("_a.gif", "2.gif"));
									$('step' + nextSwitchStep + '-wrapper').fade("in");
									currentSwitchStep = nextSwitchStep;
								}
							}
						});
					
						myEffect.start({
						    'opacity': [1, 0] 
						});
					}
					
				}
			}
		});
	}
}



function switchGotoStep (num) {
	if (num > 0 && num < currentSwitchStep) {
		var myEffect = new Fx.Morph('step' + currentSwitchStep + '-wrapper', {
							duration: browser.isIE ? 0 : 'long',
							transition: Fx.Transitions.Sine.easeOut,
							onComplete: function () {
								$('step' + currentSwitchStep +'-wrapper').setStyles({display: 'none'});
								$('step' + num + '-wrapper').setStyles({display: 'block'});
								$('step' + num + "-tab").set("src", $('step' + num + "-tab").get("src").replace("1.gif", "_a.gif"));
								$('step' + currentSwitchStep + "-tab").set("src", $('step' + currentSwitchStep + "-tab").get("src").replace("_a.gif", "1.gif"));
								$('step' + num + '-wrapper').fade("in");
								currentSwitchStep = num;
							}
						});
					
						myEffect.start({
						    'opacity': [1, 0] 
						});
	}
}

function prefillSwitchSummary ()
{
	if ($('step3-wrapper')) {
		$('summary-name').set("text", $('switch-form').elements['name'].value);
		$('summary-address1').set("text", $('switch-form').elements['address1'].value);
		$('summary-address2').set("text", $('switch-form').elements['address2'].value);
		$('summary-address3').set("text", $('switch-form').elements['address3'].value);
		$('summary-phone').set("text", $('switch-form').elements['phone'].value);
		$('summary-email').set("text", $('switch-form').elements['email'].value);
		$('summary-area').set("text", $('location-select').options[$('location-select').selectedIndex].text);
		
		$('summary-services').set("html", $('services-list').get("html"));
		
		var price = $('price').get("text").replace("*", "");
		$('summary-price').set("text", price);
	}
}

function prefillDirectDebitDetails() {
	if ($('step4-wrapper'))
		var price = $('price').get("text").replace("*", "");
		$('dd-price').set("text", price);

		$($('services-list').getElementsByTagName("ul")[0]).inject($('dd-text'));
}


function prefillBankDetails (formField) {
	f = $(formField.form);
	if (f) {
		var accountNo = f.elements['dd_account_number'].value;
		var accountSortCode = f.elements['dd_account_sort_code'].value;
		
		var bankRequest = new Request({
					method: 'post', 
					url: root + 'php/ajax/switch/get_bank_details.php',
					onSuccess: function(responseText, responseXML) {
						result = responseXML.getElementsByTagName("result")[0].firstChild.nodeValue;
						if (result == "00") {
							var bankName = responseXML.getElementsByTagName("bank")[0].firstChild.nodeValue;
							var bankBranch = responseXML.getElementsByTagName("branch")[0].firstChild.nodeValue;
							var bankAddress = responseXML.getElementsByTagName("address")[0].firstChild.nodeValue;
							selectObj = f.elements['dd_account_bank_name'];
							for (var i=0; i<selectObj.options.length;i++) {
								if (selectObj.options[i].text == bankName) selectObj.selectedIndex = i;
							}
							//f.elements['dd_account_bank_name'].value = bankName;
							//$('switch-form').elements['dd_account_bank_address1'].value = bankBranch;
							f.elements['dd_account_bank_address1'].value = bankAddress;
						}
					}
		});
		bankRequest.send("account_number="+accountNo+"&sort_code="+accountSortCode);
	}
}


function switchLocation (selectObj) {
	county = selectObj.options[selectObj.selectedIndex].value;
	if (county.length == 0) $('county-select').options.length = counties_a.length = 1;
	else {
		var counties_a = switchLocationsXML.getElementsByTagName("county");
		var locations_a = new Array();
		for (i=0;i<counties_a.length;i++) {
			if (counties_a[i].attributes[0].firstChild.nodeValue == county) {
				locations_a = counties_a[i].getElementsByTagName("location");
				break;
			}
		}
	
		
		if (locations_a.length > 0) {
			$('location-select').selectedIndex = 0;
			$('location-select').options.length = locations_a.length + 1;
			for (i=0;i<locations_a.length;i++) {
				opt = i + 1;
				loc = locations_a[i].firstChild.nodeValue;
				$('location-select').options[opt] = new Option(loc, loc);
			}
		}
		
	}
}


function getPrice (selectObj) {
	loc = selectObj.options[selectObj.selectedIndex].value;
	county = $('county-select').options[$('county-select').selectedIndex].value;
	if (county.length > 0 && loc.length > 0) {
		var priceRequest = new Request({
					method: 'get', 
					url: root + 'php/ajax/switch/get_price.php',
					onSuccess: function(responseText, responseXML) {
						var price = responseXML.getElementsByTagName("price")[0].firstChild.nodeValue;
						var collections_pa_black = responseXML.getElementsByTagName("collections_pa_black")[0].firstChild.nodeValue;
						var collections_pa_green = responseXML.getElementsByTagName("collections_pa_green")[0].firstChild.nodeValue;
						var collections_pa_brown = responseXML.getElementsByTagName("collections_pa_brown")[0].firstChild.nodeValue;
						
						var services = "";
						if (collections_pa_black > 0) services += "<li>Residual Waste Collection</li>";
						if (collections_pa_green > 0) services += "<li>Recyclables Collection</li>";
						if (collections_pa_brown > 0) services += "<li>Organic Waste Collection</li>";
						if (services.length > 0) services = "<ul>" + services + "</ul>";
						
						$('services-list').set("html", services);
						$("price").set("html", "&euro;" + price + "*");
					}
		});
		priceRequest.send("county=" + county + "&location="+loc);
	}
}



/****************************************************
* Sign up for Direct Debit							*
*													*
*****************************************************/

function initDDForm() {
	if ($('dd-form')) {
		$('dd-thank-you').setStyles({display: 'none', opacity: 0});
		// Form Validators 
		var ddValidator = new FormValidator.Inline($('dd-form'), {
			scrollToErrorsOnSubmit: false,
			onFormValidate: function(passed, form, event) {
				if (passed) {
					event.preventDefault(); //stop the normal behavior of submitting the form.
					form.set('send', {onComplete: function(response) { 
						if (response == "Success") {
							var myEffect = new Fx.Morph('setup-dd-div', {
								duration: browser.isIE ? 0 : 'long',
								transition: Fx.Transitions.Sine.easeOut,
								onComplete: function () {
									$('setup-dd-div').setStyles({display: 'none'});
									$('dd-thank-you').setStyles({display: 'block'});
									$('dd-thank-you').fade("in");
									$('confirm-btn').setStyles({display: 'none'});
									if ($('dd-loader')) $('dd-loader').setStyles({display: "none"});
								}
							});
							myEffect.start({
					   		 'opacity': [1, 0] 
							});
						}
						else {
							alert(response);
							$('confirm-btn').enabled = true;
							if ($('dd-loader')) $('dd-loader').setStyles({display: "none"});
						}		
					}});
					if ($('dd-loader')) $('dd-loader').setStyles({display: "block"});
					$('confirm-btn').enabled = false;
					form.send();
				}
			}
		});
	}
}


/****************************************************
* Pay Bills											*
*													*
*****************************************************/
function initPayBillForm() {
	if ($('bills-form')) {
		
		// Form Validators 
		var myValidator = new FormValidator.Inline($('bills-form'), {
			scrollToErrorsOnSubmit: false,
			onFormValidate: function(passed, form, event) {
				if (passed) {
					
				}
			}
		});
	}
}


/****************************************************
* Nav links											*
*													*
*****************************************************/

function initNavLinks() {
	var loginRequest = new Request({
			method: 'get', 
			url: root + 'php/ajax/is_logged_in.php',
			onFailure: function(){ },
			onSuccess: function(responseText, responseXML) {
				if (responseText == "No") {
					var as = $$("a");
					$each(as, function (a, ind) {
						if (a.get("href").indexOf("online-account") != -1) {
							a.addClass("lb");
							a.set("href", root + "dialog/register.php");
							a.addEvents({
								'keypress': function(event){ if(event.key == 'space' || event.key == 'enter'){ openLbPage(a); } },
								'click': function(event){ event.stop(); openLbPage(a); a.blur(); }
							});
						}
					});
				}
			}
		});
		loginRequest.send();
}


/****************************************************
* Calendar Functions								*
*													*
*****************************************************/
function initCalendar() {
	if ($('start-date')) {
		myCal1 = new Calendar({ 'start-date': 'd/m/Y', 'end-date': 'd/m/Y' }, { direction: -1, tweak: { x: 6, y: 0 }});
	}
}



function initCheckboxes () {
	// change checkboxes to use images instead
	var inputs_a = $$("input").each(function (item) {							 
		if(item.type){					
			if (item.type == "checkbox") {
				var checkboxSrc = "";
				//item.set('type', 'hidden');
				item.setStyle('visibility', 'hidden');
				item.set("id", item.name);
				if (item.checked) {
					item.value = 1;
					checkboxSrc = root + "images/account_system/tickbox2.gif";
				}
				else {
					item.value = 0;
					checkboxSrc = root + "images/account_system/tickbox1.gif";
				}
				
				checkboxImg = new Element("img", {
					'id': item.name + "_img",
					'src': checkboxSrc,
					'styles': { 'float': 'left', 'padding-right': '5px' },
					'events': {
						'click': function () {
							// switch the value of the associated (now) hidden form field
							fieldId = this.getAttribute("id").replace("_img", "");
							if ($(fieldId)) {
								if ($(fieldId).value == 0) {
									$(fieldId).value = 1;
									$(fieldId).checked = true;
									this.src = root + "images/account_system/tickbox2.gif";
								}
								else {
									$(fieldId).value = 0;
									$(fieldId).checked = false;
									this.src = root + "images/account_system/tickbox1.gif";
									
								}
							}
						}
					}
				});

				checkboxImg.inject(item, "before");
			}
		}
	});
}




/****************************************************
* yacine Skip Hire									*
*													*
*****************************************************/
var switchLocationsXML = null;
var bGotPrice = false;

function initSkipForm() {
	if ($('skip-form')) {
		
		// only show the first tab
		$('step2-wrapper').setStyles({display: 'none', opacity: 0});
		$('step3-wrapper').setStyles({display: 'none', opacity: 0});
		
		// populate the counties dropdown
	
		/*
		var countyRequest = new Request({
					method: 'get', 
					url: root + 'php/ajax/skip/skip.php',
					onSuccess: function(responseText, responseXML) {
						switchLocationsXML = responseXML;
						//alert(responseText)
						var counties_a = responseXML.getElementsByTagName("county");
						$('county-select').options.length = counties_a.length + 1;
						for (i=0;i<counties_a.length;i++) {
							opt = i + 1;
							county = counties_a[i].getAttribute("name");
							$('county-select').options[opt] = new Option(county, county);
						}
					}
		});
		countyRequest.send("skipselected=" + $('skip-select').options[$('skip-select').selectedIndex].value);
		//countyRequest.send("skipselected=" + skipselected);
		*/
	
		// Form Validators 
		var step1Validator = new FormValidator.Inline($('skip-form'), {
			scrollToErrorsOnSubmit: false,
			evaluateFieldsOnChange: false,
			evaluateFieldsOnBlur: false,
			onFormValidate: function(passed, form, event) {
				if (passed) {
					
					event.preventDefault(); //stop the normal behavior of submitting the form.
					var bSubmitForm = false;
					nextSwitchStep = currentSwitchStep + 1;
					//alert(nextSwitchStep);
					
					window.scrollTo(0,0);
					
                      if (nextSwitchStep == 3) {
	                    bSubmitForm = true;
						var saveRequest = new Request({
							method: 'post', 
							url: root + 'php/ajax/skip/skip-hire.php',
							onSuccess: function(responseText, responseXML) {
								//alert(responseText);
								//alert(responseXML.getElementsByTagName("hash")[0].firstChild.nodeValue);
			$('sha1').value = responseXML.getElementsByTagName("hash")[0].firstChild.nodeValue;
			$('orderid').value = responseXML.getElementsByTagName("orderid")[0].firstChild.nodeValue;	
			$('timestamp').value = responseXML.getElementsByTagName("timestamp")[0].firstChild.nodeValue;
			$('officenumber').value = responseXML.getElementsByTagName("officenumber")[0].firstChild.nodeValue;
							form.submit();
								//$('sha1').value=responseText;
								
								
								if (responseText == "Success") {
									//form.submit();
								}
							}
						});
						str = "";
						for (i=0;i<form.elements.length;i++) {
							el = form.elements[i];
							if (str.length > 0) str += "&";
							str += el.name + "=" + el.value;
						}
						saveRequest.send(str);
					}
					else {
						var myEffect = new Fx.Morph('step' + currentSwitchStep + '-wrapper', {
							duration: browser.isIE ? 0 : 'long',
							transition: Fx.Transitions.Sine.easeOut,
							onComplete: function () {
								
								//alert(nextSwitchStep)
								if (nextSwitchStep == 2) {getPrice1(); prefillSwitchSummary1();}
								//else if (nextSwitchStep == 3) {
									//prefillDirectDebitDetails();
									//if ($('payment-method').options[$('payment-method').selectedIndex].value == "dd") {
										
									//}
								//}
								document.getElementById('step1-tab').src="../images/skip-hire/step_bookingdetails2.gif";
								
								
								if (!bSubmitForm) {
                                      $('step' + nextSwitchStep + "-tab").set("src", $('step' + nextSwitchStep + "-tab").get("src").replace("1.gif", "_a.gif"));
									$('step' + currentSwitchStep + "-tab").set("src", $('step' + currentSwitchStep + "-tab").get("src").replace("_a.gif", "1.gif"));
									$('step' + currentSwitchStep +'-wrapper').setStyles({display: 'none'});
									$('step' + nextSwitchStep + '-wrapper').setStyles({display: 'block'});
									$('step' + nextSwitchStep + '-wrapper').fade("in");
									currentSwitchStep = nextSwitchStep;
									
									
								}
							}
						});
					
						myEffect.start({
						    'opacity': [1, 0] 
						});
					}
					
				}
			}
		});
		
		step1Validator.add('isChecked', {
			errorMsg: "This item is required",
			test: function (field) {
				return field.checked;
			}
		});
	}
}



function prefillSwitchSummary1 ()
{
	var description;
	
	if ($('step2-wrapper')) {
		$('summary-name').set("text", $('skip-form').elements['name'].value);
		$('summary-address1').set("text", $('skip-form').elements['address1'].value);
		$('summary-address2').set("text", $('skip-form').elements['address2'].value);
		$('summary-address3').set("text", $('skip-form').elements['address3'].value);
		$('summary-phone').set("text", $('skip-form').elements['phone'].value);
		$('summary-mobile').set("text", $('skip-form').elements['mobile'].value);
		$('summary-email').set("text", $('skip-form').elements['email'].value);
		$('summary-date').set("text", $('skip-form').elements['delivery_date'].value);
        $('summary-skip').set("text", $('skip-form').elements['skip'].value);
		//alert($('skip-form').elements['read_tcs'].value);
		//description=$('skip-form').elements['skip'];
		//displayText(description);
		
		
		$('summary-location').set("text", $('location-select').options[$('location-select').selectedIndex].text);
		$('summary-county').set("text", $('county-select').options[$('county-select').selectedIndex].text);
		
        $('summary-deliverytime').set("text", $('deliverytime').options[$('deliverytime').selectedIndex].text);
		
		
		$('summary-textskip').set("text", $('skip-form').elements['textskip'].value);
		
		//var price = $('price').get("text").replace("*", "");
		//$('summary-price').set("text", price);
	
		
		$('summary-instructions').set("text", $('skip-form').elements['instructions'].value);
		$('summary-comments').set("text", $('skip-form').elements['comments'].value);
        //$('timestamp').value = ;
		//var test=$('timestamp').value;
		//alert( test)
		
       }
}



function displaycounty(variab) {
var count = $('county-select').options[$('county-select').selectedIndex].value;

var skipselected=variab.value;	


	if (skipselected.length > 0) 
	{
		var countyRequest = new Request({
					method: 'get', 
					url: root + 'php/ajax/skip/skip.php',
					onSuccess: function(responseText, responseXML) 
					{
						switchLocationsXML = responseXML;
						var counties_a = responseXML.getElementsByTagName("county");
						$('county-select').options.length = counties_a.length + 1;
						for (var i=0;i<counties_a.length;i++) {
							opt = i + 1;
							county = counties_a[i].getAttribute("name");
							$('county-select').options[opt] = new Option(county, county);
							if ($('countypreselect') && $('countypreselect').value == county) {
								$('county-select').options[opt].selected = "selected";
								switchLocationskip($('county-select'));
							}
							bGotPrice = true;
						}
					} 
		});
		countyRequest.send("skipselected=" + skipselected);
		
		/*
		if(bGotPrice== false)
		{
			$("price").set("html", "&euro;0.00*");
			//alert($('county-select').options.length)
			$('realex-price').value = 0;
			$('location-select').value="";
		}
		*/
	}



	
	
}







function switchGotoStep1 (num) {
	
	if (num > 0 && num < currentSwitchStep) {
		
		if(num==1)
		{document.getElementById('step1-tab').src="../images/skip-hire/step_bookingdetails_a.gif";}
		
		var myEffect = new Fx.Morph('step' + currentSwitchStep + '-wrapper', {
							duration: browser.isIE ? 0 : 'long',
							transition: Fx.Transitions.Sine.easeOut,
							onComplete: function () {
								$('step' + currentSwitchStep +'-wrapper').setStyles({display: 'none'});
								$('step' + num + '-wrapper').setStyles({display: 'block'});
								$('step' + num + "-tab").set("src", $('step' + num + "-tab").get("src").replace("1.gif", "_a.gif"));
								$('step' + currentSwitchStep + "-tab").set("src", $('step' + currentSwitchStep + "-tab").get("src").replace("_a.gif", "1.gif"));
								$('step' + num + '-wrapper').fade("in");
								currentSwitchStep = num;
							}
						});
					
						myEffect.start({
						    'opacity': [1, 0] 
						});
	}
}








function getPrice1() {
   var loc = $('location-select').options[$('location-select').selectedIndex].value;
   //alert(loc)
   var skip = $('skip-select').options[$('skip-select').selectedIndex].value;
   var promotionCode = $('promotion-code').value;
  // alert(skip)
   
  // $('areapreselect').value = loc;
  // var bGotPrice = false;
	if (skip.length > 0 && loc.length > 0) {
		if ($('areapreselect')) $('areapreselect').value = loc;
		var priceRequest = new Request({
					method: 'get', 
					url: root + 'php/ajax/skip/get_price.php',
					onSuccess: function(responseText, responseXML) 
					{
						//alert(responseText)
						myResult = responseXML.getElementsByTagName("result")[0];
						myPrice = myResult.getElementsByTagName("price")[0].firstChild.nodeValue;
						myDiscountPrice = myResult.getElementsByTagName("discountPrice")[0].firstChild.nodeValue;
						myDiscountAmount = myResult.getElementsByTagName("discountAmount")[0].firstChild.nodeValue;
						myPromotionMessage = "";
						if (myResult.getElementsByTagName("promotionMessage")[0].firstChild) 
							myPromotionMessage = myResult.getElementsByTagName("promotionMessage")[0].firstChild.nodeValue;
						
						//alert(responseText);
						//vsr tmp = "blah";
						//var price = tmp.getElementsByTagName("price")[0];
						//var discountPrice = tmp.getElementsByTagName("discountPrice")[0];
						//alert(discountPrice);
						
						if (myDiscountPrice > 0) {
							$("price").set("html", "&euro;" + myDiscountPrice + "*");
							$('summary-price').set("html", "&euro;" + myDiscountPrice + "<span style='font-size: 80%;font-weight:normal;'> (&euro;" + myPrice + " - &euro;" + myDiscountAmount +")</span>");
							//$('summary-discount').set("html", "&euro;" + myDiscountAmount);
							//$('summary-total').set("html", "&euro;" + myDiscountPrice);
							$('realex-price').value = myDiscountPrice * 100;
							$('summary-promotion').set("text", $('skip-form').elements['promotion_code'].value);
							$('original-price').value = myPrice;
							
						}
						else if (myPromotionMessage.length > 0) {
							$('summary-promotion').set("text", $('skip-form').elements['promotion_code'].value + " (" + myPromotionMessage + ")");
							$('original-price').value = myPrice;
						}
						else {
							$("price").set("html", "&euro;" + myPrice + "*");
							$('summary-price').set("html", "&euro;" + myPrice);
							$('realex-price').value = myPrice * 100;
							$('summary-promotion').set("text", $('skip-form').elements['promotion_code'].value);
							$('original-price').value = myPrice;
						}
						
						
					
					bGotPrice = true;
					}
		});
		//alert("skip=" + skip + "&area="+loc+"&promotion="+promotionCode);
		priceRequest.send("skip=" + skip + "&area="+loc+"&promotion="+promotionCode);
	}
	else {
		$("price").set("html", "&euro;0.00*");
		$('realex-price').value = 0;
	}
}


function getPrice2(varskip) {
	
 var loc = $('location-select').options[$('location-select').selectedIndex].value;
 var promotionCode = $('promotion-code').value;
 
  var skip = varskip;

	if (skip.length > 0 && loc.length > 0) {
		var priceRequest = new Request({
					method: 'get', 
					url: root + 'php/ajax/skip/get_price.php',
					onSuccess: function(responseText, responseXML) {

myResult = responseXML.getElementsByTagName("result")[0];
myPrice = myResult.getElementsByTagName("price")[0].firstChild.nodeValue;				
						
						
						$("price").set("html", "&euro;" + myPrice + "*");
						
					}
		});
			
		priceRequest.send("skip=" + skip + "&area="+loc+"&promotion="+promotionCode);
		
	}
}




function switchLocationskip (selectObj) {
	
	county = selectObj.options[selectObj.selectedIndex].value;
	
	if (county.length == 0) $('county-select').options.length = counties_a.length = 1;
	else {
		if ($('countypreselect')) $('countypreselect').value = county;
		var counties_a = switchLocationsXML.getElementsByTagName("county");
		var locations_a = new Array();
		for (i=0;i<counties_a.length;i++) {
			if (counties_a[i].attributes[0].firstChild.nodeValue == county) {
				locations_a = counties_a[i].getElementsByTagName("location");
				break;
			}
		}
	
		
		if (locations_a.length > 0) {
			$('location-select').selectedIndex = 0;
			$('location-select').options.length = locations_a.length + 1;
			for (i=0;i<locations_a.length;i++) {
				opt = i + 1;
				loc = locations_a[i].firstChild.nodeValue;
				$('location-select').options[opt] = new Option(loc, loc);
				if ($('areapreselect') && $('areapreselect').value == loc) {
					$('location-select').options[opt].selected = "selected";
					getPrice1();
				}
			}
		}
		
		// Nial l - need to also update the realex account value depending on the county value
		if (county.toLowerCase() == "cavan") {
			selectObj.form.ACCOUNT.value = REALEX_CAVAN;
		}
		else {
			selectObj.form.ACCOUNT.value = REALEX_OXIGEN;
		}
	}
	
	
	
	
}





function displaycountyexternal(variab) {

var skipselected=variab;	


	if (skipselected.length > 0) 
	{
		var countyRequest = new Request({
					method: 'get', 
					url: root + 'php/ajax/skip/skip.php',
					onSuccess: function(responseText, responseXML) 
					{
						switchLocationsXML = responseXML;
						var counties_a = responseXML.getElementsByTagName("county");
						$('county-select').options.length = counties_a.length + 1;
						for (i=0;i<counties_a.length;i++) {
							opt = i + 1;
							county = counties_a[i].getAttribute("name");
							$('county-select').options[opt] = new Option(county, county);

						}
					} 
		});
		countyRequest.send("skipselected=" + skipselected);
	
	}
}




function switchLocationskip1 (selectObj) {
	
	county = selectObj;
	//alert(county);
	if (county.length == 0) $('county-select').options.length = counties_a.length = 1;
	else {
		var counties_a = switchLocationsXML.getElementsByTagName("county");
		var locations_a = new Array();
		for (i=0;i<counties_a.length;i++) {
			if (counties_a[i].attributes[0].firstChild.nodeValue == county) {
				locations_a = counties_a[i].getElementsByTagName("location");
				break;
			}
		}
	
		
		if (locations_a.length > 0) {
			$('location-select').selectedIndex = 0;
			$('location-select').options.length = locations_a.length + 1;
			for (i=0;i<locations_a.length;i++) {
				opt = i + 1;
				loc = locations_a[i].firstChild.nodeValue;
				$('location-select').options[opt] = new Option(loc, loc);
			}
		}
		
	}
	
	
	
	
}




function open_lightbox(ps){
	

	var params = ps.split(',');
	if(params.length == 5){
		openLbPage(null, params[0], params[1], params[2], params[3], params[4]);
	}	
}


/****************************************************
* Pay bill page										*
*													*
*****************************************************/

function initPayBillForm () {
	if ($('bills-form')) {
		var validator = new FormValidator.Inline($('bills-form'), {
			scrollToErrorsOnSubmit: false,
			evaluateFieldsOnChange: false,
			evaluateFieldsOnBlur: false,
			onFormValidate: function(passed, form, event) {
				
			}
		});
		validator.add('isChecked', {
			errorMsg: "This item is required",
			test: function (field) {
				return field.checked;
			}
		});
	}
}


/****************************************************
* Brown Bins Check Eligible Form					*
*													*
*****************************************************/

function initBrownBinEligibleForm () {

	if ($('brown-bin-eligible-form')) {
		var validator = new FormValidator.Inline($('brown-bin-eligible-form'), {
			scrollToErrorsOnSubmit: false,
			evaluateFieldsOnChange: false,
			evaluateFieldsOnBlur: false,
			onFormValidate: function(passed, form, event) {

				
			}
		});
		validator.add('isChecked', {
			errorMsg: "This item is required",
			test: function (field) {
				return field.checked;
			}
		});
	}
}

/****************************************************
* Brown Bins Check Eligible Form					*
*													*
*****************************************************/

function initBrownBinSubmitForm () {

	if ($('brown-bin-submit-form')) {	    
		var validator = new FormValidator.Inline($('brown-bin-submit-form'), {
			scrollToErrorsOnSubmit: false,
			evaluateFieldsOnChange: false,
			evaluateFieldsOnBlur: false,
			onFormValidate: function(passed, form, event) {
				
			}
		});
		validator.add('isChecked', {
			errorMsg: "This item is required",
			test: function (field) {
				return field.checked;
			}
		});
	}
}


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

function memoryClean(e){
}




function init() {
	
	initRollovers();
	initNavLinks();
	initSwitchForm();
	initSkipForm();
	
	initCheckboxes();
	initDDForm();
	initPayBillForm();
	initCalendar();
	initPayBillForm();
	
	initBrownBinEligibleForm();
	initBrownBinSubmitForm();

	
	var lbTabs = new Asset.javascript(root + 'js/tabs/SimpleTabs.js', {});
	var loginRegTabCss = new Asset.css(root + 'css/SimpleTabs.css', {});
}


function initLoad(){
	initLightbox();
}

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

