var mc, sdata = [], newsTick, lbl,frm,eventG, errTxt,scrl, jax=false, cbPeriod, cbLbl, curSel, lastPos, fx, fx2, fxState=0, page, tmr, tmr2; // Used in callback stuffs.

errTxt = 'some error occured';


window.addEvent('domready', function() {

	// Toggle in JS Specific Functionality.
	$$('div.noJava').setStyles({display: 'none'}); $$('.javaContent').setStyles({display: 'block'});
	$$('div.noJava').removeClass('noJava'); // Remove all on tabs



	/************************************************************
	 Join Imagine golf Pane
	******/
	var regTabs = $$('div.tab ul li a');
	var parD, curClass;

	regTabs.addEvent('click', function(e) {

		curClass = this.getParent('li').get('class');
		parD = this.getParent('div').getParent('div').get('id')


		if ($$('div#' + parD + ' div.forms div.' + curClass).length > 0) { // Only do if the Div exists
			e.stop();

			$$('div#' + parD + ' div.forms div.' + curClass).addClass('active'); 	// add active class to the div
			//$$('div#' + parD + ' div.overlay').addClass('active');
			$$('div.overlay').addClass('active');


			// Get rid on ESC
			window.addEvent('keydown', function(e) {
				if (e.key == 'esc') {
					removeActiveTab();
				}
			});
		}

	});


	function removeActiveTab() {
		$$('div.overlay').removeClass('active');
		$$('div.forms div').removeClass('active');

		if ($('popupform')) {
			$('popupform').setStyle('display', 'none');
		}
		window.removeEvents('keydown');
	}


	$$('div.forms a.close').addEvent('click', function(e) {
		e.stop();
		removeActiveTab();
	});

	$$('div.overlay').addEvent('click', function() {
		removeActiveTab();
	});


	/******
	 End
	************************************************************/




	/************************************************************
	 News Pane
	******/
	if ($$('div#latestnews').length == 1) {
		if ($$('div#latestnews div#sectionWrap div').length > 0) {
			var newsItems = 5; // How many news items are there.

			var pag = $$('ul.pag li:not(.nav)');
			var cur = window.location.hash;

			// Check if a hash value has been passed thru the URL.. if so.. set this as the default one to start on...
			pattern = /\#news([0-9])/;
			if (matches = cur.match(pattern)) {
				// We've got a hash passed in.. that is a news one..
				pag.removeClass('active');
				pag[matches[1]-1].addClass('active');
			}

			//var section = $$('section')[0];
			scrl = new Fx.Scroll2('sectionOuter', {
				wait: false,
				duration: 500,
				transition: Fx.Transitions.Quad.easeInOut,
				wheelStops: false,
				offset: {
					'x':-1,
					'y':0
				}
			});



			pag.addEvent('click', function(e) {
				e.stop();
				$clear(newsTick); // clear the tick

				var el = this.getElement('a').get('href').replace('#','');

				pag.removeClass('active');

				this.addClass('active');
				scrl.toElement(el);
				startNewsTick();
			});


			$$('ul.pag li.prev').addEvent('click', function(e) {
				$clear(newsTick); // clear the tick
				newsNav('prev');
				startNewsTick();
			});

			$$('ul.pag li.next').addEvent('click', function(e) {
				$clear(newsTick); // clear the tick
				newsNav('next');
				startNewsTick();
			});




			function newsNav(d) {

				// get the current position

				var el = $$('ul.pag li.active')[0].getElement('a').get('href');

				var thisMatch;
				pattern = /\#news([0-9])/;

				if (thisMatch = el.match(pattern)) {
					pag.removeClass('active');

					if (d == 'prev') {
						if (thisMatch[1] == 1) {
							pag[newsItems-1].addClass('active');
							scrl.toElement($('news' + newsItems)); // Goto the last element
						} else {
							var num = parseInt(thisMatch[1])-1;
							pag[num-1].addClass('active');
							scrl.toElement($('news' + num)); // goto minus 1
						}
					} else {
						// We're goign next
						if (thisMatch[1] == newsItems) {
							pag[0].addClass('active');
							scrl.toElement($('news1')); // Goto the first element
						} else {
							var num = parseInt(thisMatch[1])+1;
							pag[num-1].addClass('active');
							scrl.toElement($('news' + num));
						}
					}
				}


			}


			function startNewsTick() {
				newsTick = (function() {
					newsNav('next');
				}).periodical('6000'); // change news every 6 seconds..
			}

			startNewsTick();

		}


	}


	/************************************************************
	 Advice Center
	******/

	if ($$('div#howto div#tabs h3 a')) {

		$$('div#howto div#tabs h3 a').addEvent('click', function(e) {
			e.stop();
			$$('div#howto div#tabs h3').removeClass('active');

			var tb = this.getParent('h3');


			$$('div#howto div#tabs div').setStyle('display', 'none');

			// display the current tab.
			$(tb.get('class').trim()).setStyle('display', 'block')

			// Show the active state
			tb.addClass('active');


		});

	}


	/************************************************************
	 Settings (Account)
	******/

	if ($$('body#account div#settings').length == 1) {
		$$('div.settingFrm').setStyle('display', 'none');

		$$('body#account div#settings div.h3 p.right a').addEvent('click', function(e) {
			e.stop();

			var descDiv = this.getParent('div').getNext('div');
			var frmDiv  = descDiv.getNext('div');


			if (this.get('html') == 'hide') {
				descDiv.setStyle('display', 'block');
				frmDiv.setStyle('display', 'none');
				this.set('html', 'change');


				if ($('flasher')) {
					$('flasher').setStyle('display', 'none');
				}


			} else {
				// we're showing
				descDiv.setStyle('display', 'none');
				frmDiv.setStyle('display', 'block');
				this.set('html', 'hide');


				if ($('flasher')) {
					// The funkmaster-flex image uploader thinggy
					$('flasher').setStyles(($('browse-images').getCoordinates()));
					$('flasher').setStyle('display', 'block');
				}



				if (frmDiv.get('id') == 'frmAddress') {
					// if we've got a map.. resize it..
					if ($('map')) {
						map.checkResize();
						map.setCenter(addrpnt.getPoint()) ;
					}
				}
			}


		});
	}


	/************************************************************
	 My Messages
	******/

	if ($$('#social div#messages')) {
		$$('#social div#messages td.del a').addEvent('click', function(e) {
			e.stop();

			var thisEl = this;
			var myRequest = new Request({
				'method': 'post',
				'url': thisEl.href,
				'data': {
					'fromJs' : '1'
				},
				'onSuccess': function() {
					thisEl.getParent('tr').destroy();
				},
				'onFailure': function() {
					window.location.href = thisEl.href;
				}
			}).send();

		});
	}


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


	$$('form button[class^=frmValidate]').addEvent('click', function(e) {


		frm = this.getParent('form');
		var toValidate = frm.getElements('[class*=validate]');
		var pattern, matches;
		var hasErr = false;
		var btn = this;


		// We validate each of the fields on their own..
		toValidate.each(function(item) {
			validateField(item);
		});



		//  there may be a number of callback functions here....
		// we may need to wait..

		var waitFor = function() {
			waitForCallback(frm, btn, e);
		};





		cbPeriod = waitFor.periodical(500); // Check if the Callback (if any) is successful every half second.
		e.stop();


	});


	function waitForCallback(frm, el, e) {
		if (jax != false) {
			return false;

		} else {
			$clear(cbPeriod);
			checkFrm(frm, el, e);
			return true;
		}
	}

	function checkFrm(frm, el, e) {

		if (frm.getElements('[class*=err]').length != 0) {
			// we've got some errors.. lets stop this right here.
			validationErr(frm);
		} else {
			// We've passed initial validation... is there another function to call?
			pattern = /frmValidate\[(.*?)\]/;

			if (matches = el.get('class').match(pattern)) {
				//matches[0] = full match (ignore)
				//matches[1] = func name
				//eventG = e;
				//e.stop();
				// Call the function passed through in matches[1]
				$exec(matches[1] + "()")
			} else {
				frm.submit();
			}
		}


	}


	function validateField(item) {
		var cls = item.get('class');
		var val = item.get('value');

		errTxt = 'One or more required fields were not entered or do not contain valid data. Please check the highlighted fields below and try again.';


		lbl = item.getParent('label');

		lbl.removeClass('err');
		lbl.removeClass('ok');



		//------------------------------------------------------------
		// Check to see if validate-callback[func] is present.

		pattern = /validate\-callback\[(.*?)\]/;

		if (matches = cls.match(pattern)) {
			cbLbl = lbl;
			//matches[0] = full match (ignore)
			//matches[1] = func name

			// Call the function passed through in matches[1]
			$exec(matches[1] + "('" + val + "')")
		}

		//------------------------------------------------------------




		//------------------------------------------------------------
		// Check to see if validate-length[min, max(opt)] is present.

		pattern = /validate\-length\[([0-9]{1,24})(\,([0-9]{1,24}))?\]/;
		if (matches = cls.match(pattern)) {

			//matches[0] = full match (ignore)
			//matches[1] = min limit
			//matches[2] = comma optional (ignore)
			//matches[3] = max limit

			if (typeof matches[3] == 'undefined') {
				matches[3] = '999999'; // Give it a ridiculous upper limit.
			} else {
				if (matches[3].length == 0) {
					matches[3] = '999999'; // Give it a ridiculous upper limit.
				}
			}


			if (val.length < matches[1] || val.length > matches[3]) {
				lbl.addClass('err');
			} else {
				lbl.addClass('ok');
			}
		}
		//------------------------------------------------------------


		//------------------------------------------------------------
		// Check to see if validate-match[fld] is present.

		pattern = /validate\-match\[(.*?)\]/;

		if (matches = cls.match(pattern)) {
			//matches[0] = full match (ignore)
			//matches[1] = fld name

			if (val != $(matches[1]).get('value') || val.length < 1) {
				lbl.addClass('err');
			} else {
				lbl.addClass('ok');
			}
		}

		//------------------------------------------------------------




		//------------------------------------------------------------
		// Check to see if validate-email

		if (cls == 'validate-email') {
			pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

			if (matches = val.match(pattern)) {
				lbl.addClass('ok');
			} else {
				lbl.addClass('err');
			}
		}

		//------------------------------------------------------------



		//------------------------------------------------------------
		// Check to see if validate-on (checkbox = 1)

		if (cls == 'validate-on') {

			if (item.checked === true) {
				lbl.addClass('ok');
			} else {
				lbl.addClass('err');
			}
		}

		//------------------------------------------------------------


		//------------------------------------------------------------
		// Check to see if validate-one

		pattern = /validate\-one\[(.*?)\]/;
		if (matches = cls.match(pattern)) {


			var radErr = 1; // Lets default an error
			$$('input[name=' + matches[1] + ']').each(function(radio) {
				if (radio.checked === true) {
					radErr = 0;
				}
			});


			if (radErr == 1) {
				//lbl.addClass('err');

				$$('input[name=' + matches[1] + ']').getParent('label').addClass('err');
			} else {
				$$('input[name=' + matches[1] + ']').getParent('label').removeClass('err');
				$$('input[name=' + matches[1] + ']').getParent('label').addClass('ok');
			}

		}

		//------------------------------------------------------------

	}


	/******
	 End
	************************************************************/




	/************************************************************
	 Tabs
	******/

	$$('ul.tabs li a').addEvent('click', function(e) {
		e.stop();


		$$('ul.tabs li').removeClass('on'); // Remove all on tabs
		this.getParent('li').addClass('on'); // Add the on class onto the selected tab


		this.getParent('ul').getNext('div').getChildren('div').setStyle('display', 'none'); // Hide all the divs..

		var toShow = this.get('class'); // Decide which div to show now..
		$(toShow).setStyle('display', 'block'); // Show it
	});



	/******
	 End
	************************************************************/



	/************************************************************
	 Display Name
	******/

	if ($('display_name'))  {
		$('display_name').addEvent('blur', function() {
			checkDisplayName('');
		});
	}


	/******
	 End
	************************************************************/





	/************************************************************
	 Image Cycler
	******/



	if ($$('ul.cycleControls').length > 0) {
		var cels = $$('ul.cycleControls li a');

		cels.addEvent('click', function(e) {
			$clear(newsTick); // clear the tick
			cels.removeClass('active');
			this.addClass('active');

			var i = 1;
			cels.each(function(item) {

				if(item.hasClass('active')) {
					$$('div.cycleImages img.mainImg')[0].set('src', $$('div.cycleImages img')[(i)].get('src') );
				}

				i++;

			});

			startCycleTick();

		});

		function startCycleTick() {
			newsTick = (function() {
				var i = 0;
				var nextI;
				cels.each(function(item) {

					if (item.hasClass('active')) {
						nextI = i+1;
					}
					i++;
				});


				if (nextI >= 0 ) {
					if (nextI >= cels.length) {
						cels[nextI-1].removeClass('active');
						nextI = 0;
					} else {
						cels[nextI-1].removeClass('active');
					}


					cels[nextI].addClass('active');
					$$('div.cycleImages img.mainImg')[0].set('src', $$('div.cycleImages img')[(nextI+1)].get('src') );
				}
			}).periodical('6000'); // change news every 6 seconds..
		}

		startCycleTick();


	}









	// The time between switches of images...
	var switchTime = 4000;


	var curImg = 1;
	var nextImg;
	var timer;


	if ($('proWrap')) {

		// we've got a pro wrap div.. which is a nice start.

		var wrap = $('proWrap');

		/*
		wrap.setStyles({
			'height':'377px',
			'overflow':'hidden',
			'position': 'relative'
		});*/


		wrap.setStyles({

			'overflow'	: 'hidden',
			'position'	: 'relative'
		});





		// Check through the images.. and hide all but the first...
		// and also set them to absolute...

		var i = 0;
		$$('div#proWrap div.proClass').each(function(item) {
			item.setStyles({
				'position':'absolute',
				'top':'0px',
				'z-index':'1'
			});


			if (i != 0) {
				item.setStyle('display', 'none');
			}

			i = 1;
		});

		if ($$('div#proWrap div.proClass').length > 1) {
			// activate the timer by default
			timer = changeImg.periodical(switchTime);


			wrap.addEvents({
				'mouseenter': function() {
					$clear(timer);
				},
				'mouseleave': function() {
					timer = changeImg.periodical(switchTime);
				}
			});
		}

	}


	if ($$('div.scroll').length > 0) {
 		var myScrollArea = new MooScroll({
				'handleActiveOpacity' : 1
			});
	}


	function changeImg() {
		if (curImg) {
			// we've got an image number..
			// so we can work out what will be the next image..
			if ($('pro' + (parseInt(curImg)+1))) {
				nextImg = curImg + 1;
			} else {
				nextImg = 1;
			}



			// Get the current and next elements..
			var nextEl = $('pro' + nextImg);
			var curEl = $('pro' + curImg);

			// Give th3e next element a higher z-index for the duration of the transition
			// and set its opacity to 0 ready for fade it...
			nextEl.setStyles({
				'opacity':0,
				'display':'block',
				'z-index': '2'
			});



			var myEffect2 = new Fx.Morph(curEl).start({'opacity':'0'});

			var myEffect = new Fx.Morph(nextEl, {
				onComplete: function() {
					// We';ve completed the transition.
					// so we'll set the previous (still technically current)
					// element to display none
					curEl.setStyle('display','none');

					// reset the z-index back to one on the next(technically current) el..
					nextEl.setStyle('z-index','1');


					// prepare for the next one..
					curImg = nextImg;
				}
			});



			// Fade the element in..
			myEffect.start({
			    'opacity': '1'
			});

		} else {
			return;
		}
	}


	/***
	* Bind events to maps search shared box
	*/
	if($('radMapsLocation')) {

		if($('boxCountry')) {
			$('boxCountry').addEvent('change', function() {
				fetchCounties('boxCounty');
			});
		}
		$('radMapsLocation').addEvent('click', function() {
			$('mapsBoxSpanA').set('text', 'Location');
			$('mapsBoxSpanB').set('text', '(e.g. Birmingham or B13)');
                        fetchCounties('boxCounty');
		});
		$('radMapsName').addEvent('click', function() {
			$('mapsBoxSpanA').set('text', 'Name');
			$('mapsBoxSpanB').set('text', '');
                        fetchCounties('boxCounty');
		});
		var els = $$('#findasearch .checkboxes label:not(.sall)');
		els.each(function(item) {
			$$(item).getElement('input')[0].addEvent('click', function() {
				mapsSearchBindAll();
			});
		});
		var el = $$('#findasearch .checkboxes .sall').getElement('input')[0];
		$$(el).addEvent('click', function() {
			var els = $$('#findasearch .checkboxes label');
			if($$(el)[0].get('checked') == true) {
				els.each(function(item) {
					$$(item).getElement('input').set('checked','checked');
				});
			} else {
				els.each(function(item) {
					$$(item).getElement('input').set('checked','');
				});
			}
		});
		function mapsSearchBindAll() {
			var allChecked = true;
			var el;
			el = $('spro');
			if(el.checked==false) {
				allChecked = false;
			}
			el = $('sclub');
			if(el.checked==false) {
				allChecked = false;
			}
			el = $('ssociety');
			if(el.checked==false) {
				allChecked = false;
			}
			el = $('sresort');
			if(el.checked==false) {
				allChecked = false;
			}
			el = $('sdriving');
			if(el.checked==false) {
				allChecked = false;
			}
			el = $('sall');
			if(allChecked == true) {
				$$(el)[0].set('checked','checked');
			} else {
				$$(el)[0].set('checked','');
			}
		}

	}







	/******
	 End
	************************************************************/





	/************************************************************
	 Image Cycler
	******/



	var serv_scrl = new Fx.Scroll2(document.body, {
		wait: false,
		duration: 500,
		transition: Fx.Transitions.Quad.easeInOut,
		wheelStops: false,
		offset: {
			'x':-1,
			'y':0
		}
	});






	$$('a.serviceLink').addEvent('click', function(e) {


		var el = this;
		el.addClass('loading');

		var req = new Request.HTML({
			'url'	:	'/call/service',
			'data'	: {
				'service_id'	: this.get('id').replace('service',''),
				'name'		: $('sProName').get('value'),
				'uid'		: $('sProUid').get('value')
			},
			'onSuccess' : function(responseTree, responseElements, responseHTML, responseJavaScript) {
				//responseHTML.inject($('servicetitle'), 'after');


				new Element('div', {
					'html': responseHTML
				}).inject($('servicetitle'), 'after');

				$$('div#moreinfo .close').addEvent('click', function(e) {
					e.stop();
					$('moreinfo').getParent('div').destroy();
				});


				serv_scrl.toElement('myservices');


				el.removeClass('loading');
			}
		}).send();

		e.stop();
	});









	/************************************************************
	 Default Value hide / restore
	******/


	$(document.body).getElements('input[type=text].def,textarea.def').addEvents({
		'focus' : function(){
			if (this.get('value') == this.defaultValue) {
				this.set('value', '');
			}
		},
		'blur' : function(){
			if (this.get('value') == '') {
				this.set('value', (this.defaultValue));
			}
		}
	});







	/************************************************************
	 Add/Remove Notices.
	******/
	if ($('noticeboardSetting')) {
		$('noticeAdd').addEvent('click', function(e) {
			e.stop();


			var lbl = new Element('label', {
				'html'	: 'Noticeboard Content',
				'class'	: 'textarea'
			}).adopt(
				new Element('textarea', {
					'name'	: 'notice[]'
				}),
				new Element('a', {
					'html'	: 'Delete',
					'events':{
						'click'	: function(e) {
							e.stop();
							this.getParent('label').destroy();

						}
					},
					'href'	: 'javascript:;'
				})
			).inject(this, 'before');

		});

		$$('form#noticeboardSetting label a').addEvent('click', function(e) {
			e.stop();
			this.getParent('label').destroy();

		});


	}


	/************************************************************
	 Add 'filter' js event onchange.
	******/

	if ($('filter')) {
		$('filter').addEvent('change', function(e) {
			this.form.submit();
		});
	}



	/************************************************************
	 Equipment Image Switcher
	******/

	 if ($('equipment')) {

		if ($('imgswitcher')) {
			var imgs = $$('div#imgswitcher img');
			imgs[0].setStyle('border-color', '#888888');


			//$$('div#mainimgContainer');
			$$('div#imgswitcher a').addEvent('click', function(e) {
				var thisImg = this.getChildren('img');
				imgs.setStyle('border-color', '#CDCDCD');
				thisImg.setStyle('border-color', '#888888');

				$$('div.mainimg').setStyle('display', 'none');
				$('img' + this.get('id').replace('link', '')).setStyle('display', 'block');
			});
		}


		if ($('brandSel')) {
			$('brandSel').addEvent('change', function(e) {
				brandChange(this);
			});

			brandChange($('brandSel'));
		}

	 }

	function brandChange(el) {


		var req = new Request.JSON({
			'url': '/call/brand-categories',
			'data': {
				'brand': el.get('value')
			},
			'onSuccess' : function(response) {


				var catSel = $('catSel');

				// Get the selected element if any?
				var selectedEl = catSel.getSelected()[0].get('value');

				catSel.empty();

				new Element('option', {
					'value'	: 'all',
					'html'	: 'All Categories'
				}).inject(catSel);

				response.each(function(item) {

					if (selectedEl == item.safe) {
						new Element('option', {
							'value'		: item.safe,
							'html'		: item.name,
							'selected'	: 'selected'
						}).inject(catSel);
					} else {
						new Element('option', {
							'value'	: item.safe,
							'html'	: item.name
						}).inject(catSel);
					}
				});
			}
		}).send();
	}




	if (typeof ZeroClipboard != 'undefined') {

		ZeroClipboard.setMoviePath( '/flash/ZeroClipboard.swf');

		clip = new ZeroClipboard.Client();
		clip.setHandCursor( true );
		clip.addEventListener('onMouseDown', mousedownEmbed);
		clip.glue('copyEmbed', 'embedContain');


		link = new ZeroClipboard.Client();
		link.setHandCursor( true );
		link.addEventListener('onMouseDown', mousedownLink);
		link.glue('copyLink', 'linkContain');


	}

	if ($$('#photogallery div#section div.featured div.pag ul li').length > 0) {

		var itemsPP = 19; // 21 Items per page.
		page = 0;

		/*********
		/ Gallery Setup
		**/
		var items 	= $$('#photogallery div#section div.featured div.item');

		var i = 0;
		items.each(function(item) {
			item.setStyles({
				'position'	: 'absolute',
				'zIndex'	: '1',
				'display'	: 'block'
			});

			if (i != 0) {
				item.setStyles({
					'display': 'none',
					'zIndex' : '0'
				});
			}
			i++;
		});




		/*********
		/ Click Events
		**/
		var els = $$('#photogallery div#section div.featured div.pag ul li a');
		lastPos = $$('div#pagwrap ul li:nth-child(last)')[0].getPosition().x;
		var amnt = '';
		var total = $$('div#pagwrap ul li a').length;
		var imgTime = 11000; // how longto display image for
		$('galleryContainer').setStyle('overflow', 'hidden');
		els.addEvent('click', function(e) {
			e.stop();
			gal_changeEl(this);
		});


		/*********
		/ Hover Events (for sliding)
		**/

		//fx = new Fx.Scroll2($('pagwrap'));

		fx = new Fx.Scroll2($('pagwrap'), {
			wait: false,
			duration: 500,
			transition: Fx.Transitions.Quad.easeInOut,
			wheelStops: false,
			offset: {
				'x': -2,
				'y': -1
			}
		});



		$('pagLeft').addEvents({
			'click': function(e) {
				curSel = $$('div.pages div.pag ul li.active a')[0].get('html');
				var gotoId = parseInt(curSel)-itemsPP;


				if (gotoId < 0) {
					gotoId = 0;
				}

				gal_changeEl($$('div#pagwrap ul li a')[gotoId]);
			}
		});

		$('pagRight').addEvents({
			'click': function(e) {
				curSel = $$('div.pages div.pag ul li.active a')[0].get('html');
				var gotoId = parseInt(curSel)+itemsPP;


				if (gotoId > total) {
					if (gotoId < itemsPP) {
						gotoId = total-1;
					} else {
						gotoId = ($$('div#pagwrap ul li').length - 1);
					}
				}

				if ($('item' + gotoId)) {
					gal_changeEl($$('div#pagwrap ul li a')[gotoId]);
				}
			}
		});


		/*********
		/ Previous / Next
		**/

		$('next').addEvent('click', function(e) {
			gal_next();
		});

		$('prev').addEvent('click', function(e) {
			gal_prev();
		});



		/*********
		/ Action Event
		**/

		function gal_changeEl(item) {
			if (fxState == 0) {

				$clear(cbPeriod);

				curSel = $$('div.pages div.pag ul li.active a')[0].get('html');


				// First we rmove the active class from all pages
				$$('#photogallery div#section div.featured div.pag ul li').removeClass('active');

				// Now we add the active class to the current one..
				item.getParent('li').addClass('active');




				// Change Images
				var thisId = item.get('html');
				thisId = parseInt(thisId) - 1


				var curId = parseInt(curSel) - 1;


				// Set the image number
				$('imgNum').set('html', thisId+1);


				// Do any transitioning required!

				// the 9s below are floor(itemsPP/2)
				// and the 10s are the above + 1 :-)

				if ($$('div#pagwrap ul li').length > itemsPP) {
					if ((thisId > 9 && total) > itemsPP && (thisId < total-9)) {
						// we're moving one by one dawg.
						fx.toElement($$('div#pagwrap ul li a')[thisId-9]);
					} else if (thisId < 10 ) {
						fx.toElement($$('div#pagwrap ul li a')[0]);
					} else if (thisId > total-10) {
						fx.toElement($$('div#pagwrap ul li a')[total-itemsPP]);
					}
				}


				// If we're on the same image... dont do anything now..
				if (thisId != curId) {

					//var infoDiv = $('item' + thisId).getElements('div.info')[0];

					$('item' + curId).setStyle('zIndex', '0');
					//infoDiv.setStyle('opacity', 1);
					//infoDiv.setStyle('background-color', 'red');



					var newItem = $('item' + thisId);

					newItem.setStyles({
						'opacity' : '0',
						'display' : 'block',
						'zIndex'  : '1'
					});

					newItem.getElements('div.info')[0].setStyle('opacity', 1);

					fxState = 1;

					fx2 = new Fx.Morph(newItem, {
						'duration': '300',
						'link'	: 'chain',
						'transition': Fx.Transitions.Sine.easeOut,
						'onComplete': function() {
							$('item' + curId).setStyles({
								'display': 'none',
								'zIndex' : '0'
							});

							fxState = 0;

							/*
							newItem.removeEvent('mouseenter');
							newItem.removeEvent('mouseleave');
							newItem.addEvent('mouseenter', function(e) {
								console.log('in');
							});
							*/

							showDesc(newItem);
						}
					});

					fx2.start({
					    'opacity': 1
					});
				}

				cbPeriod = gal_next.periodical(imgTime);
			}
		}


		function gal_next() {
			curSel = $$('div.pages div.pag ul li.active a')[0].get('html');
			var gotoId = parseInt(curSel);


			if (gotoId >= $$('div#pagwrap ul li a').length) {
				gotoId = 0;
			}

			gal_changeEl($$('div#pagwrap ul li a')[gotoId]);

		}

		function gal_prev() {
			curSel = $$('div.pages div.pag ul li.active a')[0].get('html');
			var gotoId = parseInt(curSel) - 2;

			if (gotoId < 0) {
				gotoId = parseInt($$('div#pagwrap ul li a').length)-1;
			}

			gal_changeEl($$('div#pagwrap ul li a')[gotoId]);
		}


		$clear(cbPeriod);
		cbPeriod = gal_next.periodical(imgTime);


		$clear(tmr);
		tmr = hidePage.delay(5000);



		$('galleryContainer').addEvent('mouseenter', function(e) {
			showPage();
			$clear(tmr);
		});

		$('galleryContainer').addEvent('mouseleave', function(e) {
			$clear(tmr);
			tmr = hidePage.delay(1000);
		});


		// Start the first one as we mean to go on..
		showDesc($('item0'));

	}





	if ($('shop')) {

		sdata = [
			{image: 'images/misc/shop/adamsgolf.jpg', title: 'Adams Golf'},
			{image: 'images/misc/shop/adidas.jpg', title: 'Adidas'},
			{image: 'images/misc/shop/ashworth.jpg', title: 'Ashworth'},
			{image: 'images/misc/shop/callaway.jpg', title: 'Callaway'},
			{image: 'images/misc/shop/cleveland.jpg', title: 'Cleveland Golf'},
			{image: 'images/misc/shop/cobra.jpg', title: 'Cobra'},
			{image: 'images/misc/shop/hotblade.jpg', title: 'Hot Blade'},
			{image: 'images/misc/shop/john-letters.jpg', title: 'John Letters'},
			{image: 'images/misc/shop/mizuno.jpg', title: 'Mizuno'},
			{image: 'images/misc/shop/motocaddy.jpg', title: 'Motocaddy'},
			{image: 'images/misc/shop/nike.jpg', title: 'Nike Golf'},
			{image: 'images/misc/shop/odyssey.jpg', title: 'Odyssey'},
			{image: 'images/misc/shop/powakaddy.jpg', title: 'Powakaddy'},
			{image: 'images/misc/shop/rossa.jpg', title: 'Rossa'},
			{image: 'images/misc/shop/sunderland.jpg', title: 'Sunderland of Scotland'},
			{image: 'images/misc/shop/taylor-made.jpg', title: 'TaylorMade'},
			{image: 'images/misc/shop/titleist.jpg', title: 'Titleist'},
			{image: 'images/misc/shop/wilson.jpg', title: 'Wilson'}
		];




		// http://fragged.org/dev/scroller.php
		mc = new ImageScrOOler(sdata, {
			imagePath	: "/",
			imageHeight	: 195,
			targetElement	: $('brandCont'),
			showProgress	: false,
			carousel	: true,
        		imageSpacing	: 10,
        		imageOpacity	: 1
		});

		$('lftLink').addEvents({
			'mouseenter': function(e) {
				mc.moveDirection = 'left';
				mc.options.moveSteps = 3;
			},
			'mouseleave': function(e) {
				mc.options.moveSteps = 1;
			},
			'mousedown': function(e) {
				mc.options.moveSteps = 5;
			},
			'mouseup': function(e) {
				mc.options.moveSteps = 1;
			}
		});

		$('rgtLink').addEvents({
			'mouseenter': function(e) {
				mc.moveDirection = 'right';
				mc.options.moveSteps = 3;
			},
			'mouseleave': function(e) {
				mc.options.moveSteps = 1;
			},
			'mousedown': function(e) {
				mc.options.moveSteps = 5;
			},
			'mouseup': function(e) {
				mc.options.moveSteps = 1;
			}
		});
	}


	if ($$('div#competitions div.youwin form div.question').length > 0) {

		$('nopopupform').set('id', 'popupform');
		$('popupform').setStyle('display','none');


		var sp = new Fx.Scroll2(document.body, {
			wait: false,
			duration: 500,
			transition: Fx.Transitions.Quad.easeInOut,
			wheelStops: true,
			offset: {
				'x': 0,
				'y': -20
			}
		});


		$('subbtn').removeEvents();

		$('subbtn').addEvent('click', function(e) {
			e.stop();

			var frm = $$('div.valsec')[0];
			var toValidate = frm.getElements('[class*=validate]');
			var pattern, matches;
			var hasErr = false;
			var btn = this;


			// We validate each of the fields on their own..
			toValidate.each(function(item) {
				validateField(item);
			});



			if (frm.getElements('[class*=err]').length == 0) {


				$$('div.overlay').addClass('active');


				// Get rid on ESC
				window.addEvent('keydown', function(e) {
					if (e.key == 'esc') {
						removeActiveTab();
						$('popupform').setStyle('display','none');
					}
				});


				$('popupform').setStyle('display','block');
				sp.toElement($('popupform'));

				frm.getElements('[class=txtErr]').destroy();
			} else {
				validationErr(frm);
			}
		});

		$$('div#popupform a.close').addEvent('click', function(e) {
			e.stop();
			removeActiveTab();
			//this.getParent('div').setStyle('display', 'none');

		});

		$('subbtn2').addEvent('click', function(e) {
			e.stop();

			var frm = $$('div.valsec')[1];
			var toValidate = frm.getElements('[class*=validate]');
			var pattern, matches;
			var hasErr = false;
			var btn = this;


			// We validate each of the fields on their own..
			toValidate.each(function(item) {
				validateField(item);
			});



			if (frm.getElements('[class*=err]').length == 0) {
				this.form.submit();
			} else {
				validationErr(frm);
			}


		});
	}

	if ($('podcastItem')) {
		AudioPlayer.setup("/flash/audio.swf", {
			width: 290,
			transparentpagebg:'yes'
		});

		$$('.pclisten').each(function(item) {

			AudioPlayer.embed(item.get('id'), {
				soundFile: item.get('href'),
				titles:item.get('title'),
				artists:'Imagine Golf Podcast'

			});
		});
	}

});

function showDesc(item) {
	var infoDiv = $(item).getElements('div.info')[0];
	var infoTime = 4000; // Time to display info pane for.

	item.removeEvent('mouseenter');
	item.removeEvent('mouseleave');



	var meh = function() {
		infoDiv.fade();
	}

	$clear(tmr2);
	tmr2 = meh.delay(infoTime); // default of 3 secs.


	item.addEvent('mouseenter', function(e) {
		$clear(tmr2);
		infoDiv.fade('in');
	});


	item.addEvent('mouseleave', function(e) {
		$clear(tmr2);
		tmr2 = meh.delay(1000) // only a second once you've gone in and out
	});
}




function hidePage() {
	var pl = $('pageList');
	var curT = pl.getStyle('top');
	var myFx = new Fx.Tween(pl);

	myFx.start('top', '338px', '364px');

}

function showPage() {
	var pl = $('pageList');
	var curT = pl.getStyle('top');

	if (curT != '338px') {
		var myFx = new Fx.Tween(pl);

		myFx.start('top', '364px', '338px');
	}
}



function scrollEl(i, x) {

	var pos = 0;

	if ($$('div#pagwrap ul li:nth-child(last)')[0].getPosition('pagCont').x >= 565 || i == 1) {

		//console.log(lastPos);
		// 1128

		if (i == 1) {
			// Left
			pos = parseInt($('pagwrap').getScroll().x) - x;

		} else {
			// Right
			pos = parseInt($('pagwrap').getScroll().x) + x;
		}


		//if (pos < 565) {
			//console.log('Going to'  + pos);
			fx.set(pos);
		//}
	}
}

function mousedownEmbed(client) {
	// we can cheat a little here -- update the text on mouse over
	clip.setText($('embedCode').get('value'));
}


function mousedownLink(client) {
	// we can cheat a little here -- update the text on mouse over
	link.setText($('linkCode').get('value'));
}


//====================================================================================
// Non Mootools controlled functions
//








// Validation
function validationErr(frm) {

	var p;

	if(frm.getElement('p.txtErr') == null) {
		p = new Element('p', {
			'class':'txtErr',
			'id':'txtErr'
		}).inject(frm,'top');
	} else {
		p = frm.getElement('p.txtErr');
	}

	p.set('html', errTxt);

	var s = new Fx.Scroll2(document.body, {
		wait: false,
		duration: 500,
		transition: Fx.Transitions.Quad.easeInOut,
		wheelStops: true,
		offset: {
			'x': 0,
			'y': -20
		}
	});

	s.toElement('txtErr');

}


function verifyCheckUser(val) {
	verifyCheck(val, 'user');
}

function verifyCheckPro(val) {
	verifyCheck(val, 'pro');
}

function verifyCheck(val, vtype) {

	// we need to check the verify image now...

	var req = new Request.HTML({
		'url'	: '/call/verify-check',
		'data':{
			'verify' : val,
			'vtype'	 : vtype
		},
		'onSuccess': function(responseTree, responseElements, responseHTML, responseJavaScript) {
			if (responseHTML == 0){
				cbLbl.addClass('err');
			} else {
				cbLbl.addClass('ok');
			}

			jax = false;
		},
		'onRequest': function() {
			jax = true; // make sure the lord knows we're jaxing
		}
	}).send();
}



function checkLogin() {
	var req = new Request.HTML({
		'url'	: '/call/check-login',
		'data':{
			'email_a' 	: frm.getElement('input[name=email_a]').get('value'),
			'password_a' 	: frm.getElement('input[name=password_a]').get('value')
		},
		'onSuccess': function(responseTree, responseElements, responseHTML, responseJavaScript) {
			if (responseHTML == 0){
				errTxt = 'Your username or password were not recognised.';
				validationErr(frm);

			} else {
				frm.submit();
			}

			jax = false;
		},
		'onFailure': function() {
			frm.submit();

		},
		'onRequest': function() {
			jax = true; // make sure the lord knows we're jaxing
		}
	}).send();
}



function validateDisplayNamePost() {
	checkDisplayName('post')
}

function validateDisplayName() {
	checkDisplayName('')
}



function checkDisplayName(a) {
	var username = $('display_name').value;


	var req = new Request({
		url:'/account/nick_lookup.htm',
		data: {
			'n' : username
		},
		onComplete: function(html) {
			if (html) {
				$('availField').empty();

				var tclass 	= '';
				var result 	= html.substring(0,1);
				var txt 	= html.substring(2);


				if (result == 0) {
					// The username is available...
					tclass = 'good'

					if (a == 'post') {
						frm.submit();
					}

					if (lbl) {
						lbl.addClass('ok');
					}
				} else {
					// The username is taken...
					tclass = 'bad'

					if (a == 'post') {
						errTxt = 'The display name entered has already been taken or is in the wrong format - Please try another display name.';
						validationErr(frm);
					}

					if (lbl) {
						lbl.addClass('err');
					}
				}

				new Element('span', {
					'class':'userLookup ' + tclass,
					'html':txt
				}).inject($('availField'));
			}

			jax = false;
		},
		'onRequest': function() {
			jax = true; // make sure the lord knows we're jaxing
		}
	}).send();
}

function launchGameWindow(fl, scrn){

	var windowHeight = 600;
	var windowWidth = 800;
	var windowName = 'golfgame';
	var windowUri = '/games/' + fl + '.htm?scrn=' + scrn;
	//var windowUri = '/games/powerchip.htm';


	var centerWidth = (window.screen.width - windowWidth) / 2;
	var centerHeight = (window.screen.height - windowHeight) / 2;

	newWindow = window.open(windowUri, windowName, 'resizable=0,width=' + windowWidth +
	',height=' + windowHeight +
	',left=' + centerWidth +
	',top=' + centerHeight);

	newWindow.focus();
	return newWindow.name;

}

/***
 * Reset County select input element
 */
function resetCountySelect(countyElm) {
    $(countyElm).set('html','<option value="0">All</option>');
    if(countyElm=='boxCounty'){
        $('lblBoxCounty').setStyle('display','none');
        if($('findasearch')) {
            $('findasearch').setStyle('height', '293px');
            $$('#findasearch .content')[0].setStyle('height', '282px');
        }
    } else {
        $('lblCounty').setStyle('display','none');
    }
}

/***
* Equivalent of PHPs ;)
*/
function in_array(str, arr){
        var x=false;
        for(var i=0;i<arr.length;i++){
                if(str == arr[i]) {
                        x=true;
                        break;
                }
        }
        return x;
}

/***
* Fetch counties on AJAX call and load into memory
*/
function fetchCounties(source) {

    var thisCountry,thisCounty;
    if(source == 'boxCounty') {
        thisCounty = $('boxCounty').options[$("boxCounty").selectedIndex].value;
        thisCountry = $('boxCountry').options[$("boxCountry").selectedIndex].value;
    } else {
        thisCounty = $('county').options[$("county").selectedIndex].value;
        thisCountry = $('country').options[$("country").selectedIndex].value;
    }

    var countries = new Array("Australia", "Canada", "United Kingdom", "Ireland", "Netherlands", "United States");

    var optg = 'radMapsLocation';
    if ($('frmSearchMap')) {
        optg = 'radLocation';
    }

    if(in_array(thisCountry,countries) && $(optg).checked === true) {

        $(source).set('html','<option>Loading...</option>');

        if(source == 'boxCounty') {
            $('lblBoxCounty').setStyle('display','block');
            if($('findasearch')) {
                $('findasearch').setStyle('height', '333px');
                $$('#findasearch .content')[0].setStyle('height', '323px');
            }
        } else {
            $('lblCounty').setStyle('display','block');
        }

        var req = new Request({
                'url': '/call/maps.search.xml',
                'data': {
                        'country':thisCountry,
                        'method':'fetchCounties',
                        'format':'html'
                },
                'onSuccess': function(responseText, responseXML) {
                       var html = '<option value="0">All</option>';
                       if(responseText) {
                            html += responseText;
                            $(source).set('html',html);
                       }
                },
                'method':'post'
        }).send();

    } else {
        resetCountySelect(source);
    }

}