var slider, action=0, mT, toPay, orderRef, signDefault = new Array(), title1, title2, thisPage2,menuMoving=0,menuOver,mt1;;

// GENERAL

function messageBox(message,secondsOut) {
	i='messageBox';
	if (mT) clearTimeout(mT);
	mT=null;
	if ($(i) != null) {
		$(i).update(message);
		centreElement (i,1);
		$(i).show();
		mT = setTimeout(function () { $(i).hide(); }, (secondsOut*1000));
	}
	else {
		alert('Message box doesn\'t exist');	
	}
}

function centreElement (e, vert) {
	var theScrolls = document.viewport.getScrollOffsets();
	theLeft = Math.floor(((document.viewport.getWidth())-($(e).getWidth()))/2) + theScrolls[0];
	theTop = Math.floor(((document.viewport.getHeight())-($(e).getHeight()))/2) + theScrolls[1];
	if (theTop < 0) theTop = 0;
	if (vert==1)  {
		$(e).setStyle({ top: '0px' });
		$(e).setStyle({ top: theTop+'px' });
	}
	$(e).setStyle({ left: theLeft+'px' });
	
}

function pageOverlay() {
	var theScrolls = document.viewport.getScrollOffsets();
	pageWidth = document.viewport.getWidth() + theScrolls[0]; pageHeight = document.viewport.getHeight() + theScrolls[1];
	if (pageWidth < $('mainContainer').getWidth()) pageWidth = $('mainContainer').getWidth();
	if (pageHeight < ($('mainContainer').getHeight()+127)) pageHeight = ($('mainContainer').getHeight()+127);
	$('pageOverlay').setStyle({ opacity: '0.7', display: 'block', width:pageWidth+'px', height:pageHeight+'px' });
	$('pageOverlay').show();
}

function closeBox(id) {
	if (id=='videoBox') $('theVid2').update('');
	$('pageOverlay').hide();
	$(id).hide();
}

function showBox(id) {
	pageOverlay();
	centreElement (id,1);
	$(id).show();
}

function buttonMouseOver (buttonID,over,cOn,cOff) {
	var buttonWidth = $(buttonID).getWidth();
	linkID = $(buttonID).firstDescendant();
	if (over==1) {
		$(buttonID).setStyle({ backgroundPosition: '-'+buttonWidth+'px 0' });
		$(linkID.id).setStyle({ color:cOn });
	}
	else {
		$(buttonID).setStyle({ backgroundPosition: '0 0' });
		$(linkID.id).setStyle({ color:cOff });
	}
}

function sortButtons (p) {
	var a=$$('div.'+p+'Button');
	a.each(function(n){
		$(n.id).observe('mouseover', function () { buttonMouseOver (n.id,1,'#001d28','#b0b0b0'); });
		$(n.id).observe('mouseout', function () { buttonMouseOver (n.id,0,'#001d28','#b0b0b0'); });
   	});
	var a2=$$('div.'+p+'Button2');
	a2.each(function(n){
		$(n.id).observe('mouseover', function () { buttonMouseOver (n.id,1,'#2c2c2c','#00202d'); });
		$(n.id).observe('mouseout', function () { buttonMouseOver (n.id,0,'#2c2c2c','#00202d'); });
   	});
}

function careerNewsLinkMouseOver (divID,over) {
	var linkID = $(divID).firstDescendant();
	if (over==1) {
		$(divID).setStyle({ backgroundColor: '#002433' });
		$(linkID.id).setStyle({ color:'#FFF' });
	}
	else {
		$(divID).setStyle({ backgroundColor: '' });
		$(linkID.id).setStyle({ color:'#002433' });
	}
}

function clearInputBox(i,t,o,c) {
	if (o==1) {
		if ($F(i) == t) $(i).value='';
	}
	else if (o==2) {
		$(i).observe('focus', function () { clearInputBox(i,t,1,c); });
		$(i).observe('blur', function () { clearInputBox(i,t,0,c); });
	}
	else {
		if ($F(i) == '') $(i).value=t;	
	}
	if (c) { $(i).setStyle({ color: c }); }
}

function isValidEmail2(s) {
	return (s.indexOf(".") > 2) && (s.indexOf("@") > 0);
}

function isValidEmail(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1) return false;
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
	if (str.indexOf(at,(lat+1))!=-1) return false;
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
	if (str.indexOf(dot,(lat+2))==-1) return false;
	if (str.indexOf(" ")!=-1) return false;
	return true;			
}

function handle(e) { // MOUSE WHEEL FOR SCROLLER
	var wheelVal = Event.wheel(e);
	wheelVal = wheelVal/100;
	slider.setValueBy(-wheelVal);
}

function openCloseMenu (t,i,d) {
	if (menuMoving<1) {
		if (t==1 && $(i).visible()==false) {
			menuMoving=1;
			Effect.BlindDown(i, { duration:d,afterFinish:function () {
				menuMoving=0
			}});
		}
		else if (i != 'dropCourseMenu') {
			var s = i.replace("coursesList","");
			window.location.href = $('courseType'+s).href;
		}
		else if (t==2) {
			menuOver=0;
			clearTimeout(mt1);
			mt1='';
			mt1 = setTimeout(function() {
				if (menuOver<1) {
					menuMoving=1;
					Effect.BlindUp(i, { duration:d,afterFinish:function () {
						menuMoving=0;
						var a = $$('ul[id^="coursesList"]');
						a.each(function(n){
							$(n.id).hide();
						});
					}});
				}
			},500);
		}
	}
}

// CAREERS PAGES

function setUpCareers () {
	openCloseCareer();
}

function openCloseCareer (n) {
	if (n != null) {
		var h = 52 + $('career_title_'+n).getHeight();
		if (h < ($('career_'+n).getHeight()-20)) {
			$('career_'+n).setStyle({ height:h+'px' });
			$('career_'+n+'_text').setStyle({ height:h+'px' });
			$('buttonLink_'+n+'_1').update('More');
			$('buttonLink_'+n+'_2').hide();
		}
		else {
			$('buttonLink_'+n+'_1').update('Close');
			$('career_'+n).setStyle({ height:'auto' });
			$('career_'+n+'_text').setStyle({ height:'auto' });
			$('buttonLink_'+n+'_2').show();
		}
	}
	else {
		var a = $$("a[id^='buttonLink']");
		a.each(function(n){
			y=n.id.replace('buttonLink_','');
			y=y.substr(0,1);
			y3 = n.id.length;
			y2=n.id.substr((y3-1),1);
			if (y2==1) {
				var m = y;
				$(n.id).observe('click', function () { openCloseCareer (m); });
				openCloseCareer (y);
			}
   		});
	}
}



// FAQS PAGES

function setUpFaqs (id) {
	openFaqs = new Array('0','1');
	var a = $$("[id^='l']"),y;
	a.each(function(n){
		$(n.id).observe('click', function () { openCloseFaq (n.id); });
		y=n.id.replace('l','');
		if (y>1) $('t'+y).hide();
   	});
}

function openCloseFaq (id) {
	var y=id.replace('l','');
	if (openFaqs[y] == 1 && action==0) {
		action=1;
		$('hl'+y).setStyle({ backgroundImage: 'url('+pageURL+'images/backgrounds/faqs_title_dark_left.png)' });
		$('hr'+y).setStyle({ backgroundImage: 'url('+pageURL+'images/backgrounds/faqs_title_dark_gradient.png)' });
		Effect.BlindUp('t'+y, { duration: 0.5, afterFinish: function () { action=0; } });
		openFaqs[y]=0;
	}
	else if (action==0) {
		action=1;
		Effect.BlindDown('t'+y, { duration: 0.5, afterFinish: function () { action=0; } });
		$('hl'+y).setStyle({ backgroundImage: 'url('+pageURL+'images/backgrounds/faqs_title_light_left.png)' });
		$('hr'+y).setStyle({ backgroundImage: 'url('+pageURL+'images/backgrounds/faqs_title_light_gradient.png)' });
		openFaqs[y]=1;
	}
}



// HOME PAGE

function setUpHome () {
	slider = new Control.Slider('handle2', 'track2', {
		axis: 'vertical',
		onSlide: function(v) { scrollVertical(v, $('homeTextScrollBox2'), slider);  },
		onChange: function(v) { scrollVertical(v, $('homeTextScrollBox2'), slider); }
	});
	if ($('homeTextScrollBox2').scrollHeight <= $('homeTextScrollBox2').offsetHeight) {
		slider.setDisabled();
		$('track2').hide();
	}
	var a=$$('.homeInfoBox');
		a.each(function(n){
			var b = $(n.id).descendants();
			var id = n.id;
			$(id).observe('click', function () { window.location = $(id+'L').href; });
			b.each(function(n){
				$(n.id).observe('mouseover', function () { doHomeBox (id,'on') });
				$(n.id).observe('mouseout', function () { doHomeBox (id,'off') });
			});
		});
	Event.observe($('homeTextScrollBox2'), "mousewheel", handle, false);
	Event.observe($('homeTextScrollBox2'), "DOMMouseScroll", handle, false);
	function scrollVertical(value, element, slider) {
		element.scrollTop = Math.round(value/slider.maximum*(element.scrollHeight-element.offsetHeight));
	}
	Object.extend(Event, {
		wheel:function (event) {
			var delta = 0;
			if (!event) event = window.event;
			if (event.wheelDelta) {
				delta = event.wheelDelta/120; 
				if (window.opera) delta = -delta;
			} else if (event.detail) { delta = -event.detail/3;	}
			if (event.preventDefault)
			event.preventDefault();
			event.returnValue = false;
			return Math.round(delta); //Safari Round
		}
	});
	Event.observe('sampleCourses', 'click',function () {
		$('theVid2').update('<div id="theVid"></div>');
		showBox('videoBox')
		var flashvars = {};
		var params = {};
		params.allowscriptaccess = "always";
		var attributes = {};
		swfobject.embedSWF(pageURL+"video/presentation2.swf", "theVid", "800", "540", "10","video/expressInstall.swf", flashvars, params, attributes);
	});
}

function doHomeBox (i,onOff) {
	if (onOff=='on') {
		$(i).setStyle({ backgroundPosition:'-303px 0' });
		$(i+'H').setStyle({ color:'#002534' });
		$(i+'T2').setStyle({ color:'#ffffff' });
		$(i+'L').setStyle({ color:'#ffffff' });
		$(i+'L2').setStyle({ color:'#002534' });
	}
	else {
		$(i).setStyle({ backgroundPosition:'0 0' });
		$(i+'H').setStyle({ color:'#ffffff' });	
		$(i+'T2').setStyle({ color:'#002534' });
		$(i+'L').setStyle({ color:'#002534' });
		$(i+'L2').setStyle({ color:'#ffffff' });
	}
}


// CART FUNCTIONS

function setUpCart () {
	slider = null;
	if ($('handle') != null) {
		slider = new Control.Slider('handle', 'track', {
			range:$R(100, cartMaxCost),
			sliderValue: 100,
			onSlide: function(v) { $('toPay').update('Pay now - &pound;'+Math.ceil(v)+'.00'); },
			onChange: function(v) { $('toPay').update('Pay now - &pound;'+Math.ceil(v)+'.00'); setCartPayment (v); }
		});
	}
	if (orderRef == null) {
		var a=$$('#cartForm input');
		a.each(function(n){
			id=n.id.replace('i','');
			$(n.id).observe('click', function () { deleteFromCart (id); });
		});
	}
	if ($('checkOutButton') != null) $('checkOutButton').observe('click',cartRedirect);
}

function cartRedirect () {
	
	if (orderRef != null) {
		var allNodes = Form.serialize("cartForm");
		var aj = new Ajax.Request(pageURL+'ajaxStuff.php', {method: 'post', parameters: 'orderDetails=1&'+allNodes,onComplete: function(response) {
				var response = response.responseText;
				var reply = response.split("||message||");
				if (reply[0]=='ok') {
					$('crypt').value = reply[1];
					$('signUpForm2').submit();
				}
			}});
	}
	else {
		window.location = pageURL+'Sign-up';
	}
}

function setCartPayment (a) {
	action=1;
	var aj = new Ajax.Request(pageURL+'/ajaxStuff.php', {method: 'post', parameters: 'setCartPayment='+a,onComplete: function() { action=0; }});
	
}

function deleteFromCart (id) {
	var aj = new Ajax.Request(pageURL+'/ajaxStuff.php', {method: 'post', parameters: 'deleteFromCart='+id,onComplete: function(response) {
		var response = response.responseText;
		messageBox(response,3);
		showCart();
		setUpCart();
	}});
}

function showCart() {
	var aj = new Ajax.Request(pageURL+'/ajaxStuff.php', {method: 'post', parameters: 'getCart=1',onComplete: function(response) {
		var response = response.responseText;
		var reply = response.split("||message||");
		$('cartTotal').update('Total - &pound;'+reply[1]);
		$('cartContents').update(reply[0]);
		if (reply[1]<1) {
			$('paymentSelectContainer').hide();	
		}
		else {
			cartMaxCost = parseInt(reply[1])*0.9;
			$('toPay').update('Pay now - &pound;100');
			setUpCart();
		}
		messageBox('Item deleted',3);
	}});
}

function sortMiniCart () {
	if ($('miniCart') != null) {
		var aj = new Ajax.Request(pageURL+'/ajaxStuff.php', {method: 'post', parameters: 'miniCart=1',onComplete: function(response) {
			var response = response.responseText;
			var reply = response.split("||message||");
			if (reply[0]>0) {
				var w = document.viewport.getWidth();
				t = Math.ceil((w-996)/2)+30;
				if (t<0)t=0;
				$('miniCart').setStyle({ right:t+'px' });
				if (reply[0]>1) a='s'; else a='';
				$('miniCartTop').update('Your cart - '+reply[0]+' item'+a+' - &pound;'+reply[1]);
				$('miniCart').show();
			}
			else {
				$('miniCart').hide();
			}
		}});
	}
}

function addToCart () {
	var allNodes = Form.serialize("courseSelectForm");
	var aj = new Ajax.Request(pageURL+'/ajaxStuff.php', {method: 'post', parameters: 'addToCart=1&'+allNodes,onComplete: function () {
		sortMiniCart();
		messageBox('Item added to cart',3)
	}});
}



// COURSE PAGES

function setUpCourses () {
	if ($('company_bookings') != null && $('b1') != null) {
		
		$('company_bookings').hide();
		$('a1').observe('click', swapCourseTab );
		$('b1').observe('click', swapCourseTab );
		
	}
	
	if ($('courseInfoBoxes') != null && $('b1') != null) {
		var a = $$('a[id^="cbl"]');
		a.each(function(n){
			var id = n.id;
			var y=id.replace('cbl','');
			$(n.id).observe('click', function () { courseInfo (y); });
		});
		$('company_bookings').hide();
		$('a1').observe('click', swapCourseTab );
		$('b1').observe('click', swapCourseTab );
		
	}
	
	if ($('courseSelectForm') != null) {
		$('buyCourse').observe('click', addToCart);
	}
	
	if ($('courseTitleContainer') != null) {
		$('courseTitleContainer').update('<div><div id="courseTitle1"><h1>'+title1+'</h1></div></div><div><div id="courseTitle2"><h1>'+title2+'</h1></div></div>');
	}
	if (thisPage2 == 'coursef1') {
		var a=$$('.courseInfoBox3');
		a.each(function(n){
			var id = n.id;
			var b = $(id).descendants();
			$(id).observe('mouseover', function () { doCourseBox (id,'on') });
			$(id).observe('mouseout', function () { doCourseBox (id,'off') });
			$(id).observe('click', function () { window.location = $(id+'L2').href; });
			b.each(function(n){
				$(n.id).observe('mouseover', function () { doCourseBox (id,'on') });
				$(n.id).observe('mouseout', function () { doCourseBox (id,'off') });
			});
		});
	}
}

function doCourseBox (t,onOff) {
	if (onOff=='on') {
		$(t).setStyle({ backgroundPosition:'-346px 0' });
		$(t+'T').setStyle({ color:'#002534' });
		$(t+'L2').setStyle({ color:'#ffffff' });
		$(t+'L').setStyle({ color:'#ffffff' });
		$(t+'L3').setStyle({ color:'#002534' });
	}
	else {
		$(t).setStyle({ backgroundPosition:'0 0' });
		$(t+'T').setStyle({ color:'#ffffff' });
		$(t+'L2').setStyle({ color:'#002534' });
		$(t+'L').setStyle({ color:'#002534' });
		$(t+'L3').setStyle({ color:'#ffffff' });
	}
}

function courseInfo (n) {
	var k,o;
	if (action<1) {
		action=1;
		if ($('cbtl'+n).hasClassName('courseBoxOffTopL')) {
			k='On'; o='Off';
			$('cbl'+n).update('Less info');
			Effect.BlindDown('cbmt'+n, { duration: 0.5, afterFinish: function () { courseInfoClasses (n,k,o); } });
		} else {
			k='Off'; o='On';
			$('cbl'+n).update('More info...');
			Effect.BlindUp('cbmt'+n, { duration: 0.5, afterFinish: function () { courseInfoClasses (n,k,o); } });
		}
	}
}

function courseInfoClasses (n,k,o) {
	action=0;
	$('cbtl'+n).addClassName('courseBox'+k+'TopL');
	$('cbtl'+n).removeClassName('courseBox'+o+'TopL');
	$('cbtr'+n).addClassName('courseBox'+k+'TopR');
	$('cbtr'+n).removeClassName('courseBox'+o+'TopR');
	$('cbm'+n).addClassName('courseBox'+k+'Middle');
	$('cbm'+n).removeClassName('courseBox'+o+'Middle');
	$('cbbr'+n).addClassName('courseBox'+k+'BaseR');
	$('cbbr'+n).removeClassName('courseBox'+o+'BaseR');
	$('cbbl'+n).addClassName('courseBox'+k+'BaseL');
	$('cbbl'+n).removeClassName('courseBox'+o+'BaseL');
}

function swapCourseTab () {
	var t;
	if ($('availabilty') != null) {
		if ($('a1').hasClassName('tabContainer')) {
			on='b'; off='a';
			$('availabilty').hide();
			$('company_bookings').show();
		}
		else {
			on='a'; off='b';
			$('availabilty').show();
			$('company_bookings').hide();
		}
	}
	$(on+'1').addClassName('tabContainer');
	$(on+'1').removeClassName('tabContainerLight');
	$(off+'1').addClassName('tabContainerLight');
	$(off+'1').removeClassName('tabContainer');
	
	$(on+'2').addClassName('tabLeft');
	$(on+'2').removeClassName('tabLeftLight');
	$(off+'2').addClassName('tabLeftLight');
	$(off+'2').removeClassName('tabLeft');
	
	$(on+'3').addClassName('tabContent');
	$(on+'3').removeClassName('tabContentLight');
	$(off+'3').addClassName('tabContentLight');
	$(off+'3').removeClassName('tabContent');
	
	$(on+'4').addClassName('tabRight');
	$(on+'4').removeClassName('tabRightLightTrans');
	$(off+'4').addClassName('tabRightLightTrans');
	$(off+'4').removeClassName('tabRight');
}



// CONTACT PAGE

function setUpContact () {
	$('submitButton').observe('click', submitContact);
}

function submitContact () {
	var allNodes = Form.serialize("contactForm");
	var aj = new Ajax.Request(pageURL+'/ajaxStuff.php', {method: 'post', parameters: 'contact=1&'+allNodes,onComplete: function(response) {
		var response = response.responseText;
		if (response != null && response != '' ) {
			messageBox(response,3);
		}
		if (response == 'Your message has been sent.' ) {
			$('contactForm').reset();
		}
	}});
}



// SIGN UP PAGE

function setUpSignUp () {
	$('signUpForm').reset();
	var a=$$('#signUpForm input');
	a.each(function(n){
		if ($F(n.id) != null && n.id != null) {
			clearInputBox($(n.id),$F(n.id),2,'#002534');
			signDefault[n.id]=$F(n.id);
		}
   	});
	$('submitSignup').observe('click',processSignUp);
}


function processSignUp () {
	allOK=1;
	var reqFields = new Array ('firstname','dob','surname','address','city','county','postcode','email','email2','phone','employment_status');
	i=0;
	while (reqFields[i]) {
		if ($F(reqFields[i]) == '' || $F(reqFields[i])==signDefault[reqFields[i]]) {
			$(reqFields[i]).setStyle({ color:'#f00' });
			allOK=0;
		}
		++i;
	}
	if (allOK==1) {
		if ($('tc').checked==true) {
			if (isValidEmail($F('email')) && isValidEmail($F('email2')) && $F('email') == $F('email2')) {
				var a=$$('#signUpForm input');
				a.each(function(n){
					if (signDefault[n.id] != null && signDefault[n.id] != '' && $F(n.id) == signDefault[n.id]) {
						clearInputBox(n.id,'',2);
						$(n.id).value='';
					}
				});
				var allNodes = Form.serialize("signUpForm");
				if (payType=='dd') {
					var aj = new Ajax.Request(pageURL+'/ajaxStuff.php', {method: 'post', parameters: 'orderDetailsDD=1&'+allNodes,onComplete: function(response) {
						var response = response.responseText;
						var reply = response.split("||message||");
						if (reply[0]=='ok') {
							window.location='https://www.fastdd.co.uk/start.php?c=8d442af3e10f70fc767ac1d1b43283fb';
						}
						else {
							messageBox(reply[0]+' '+reply[1]+'matt',3);
						}
					}});
				}
				else {
					var aj = new Ajax.Request(pageURL+'/ajaxStuff.php', {method: 'post', parameters: 'orderDetails=1&'+allNodes,onComplete: function(response) {
						var response = response.responseText;
						var reply = response.split("||message||");
						if (reply[0]=='ok') {
							$('crypt').value = reply[1];
							$('signUpForm2').submit();
						}
						else {
							messageBox(reply[0]+' '+reply[1]+'matt',3);
						}
					}});
				}
			}
			else { 
				$('email').value = 'E-mail*';
				$('email2').value = 'Confirm your e-mail*';
				$('email').setStyle({ color: '#f00' });
				$('email2').setStyle({ color: '#f00' });
				messageBox('One of your emails seems to be incorrect?',3);
			}
		}
		else messageBox('Please confirm you have read our Terms and Conditions',3);
	}
	else {
		messageBox('Please fill the fields in red to proceed.',3);
	}
}


// ALL PAGES

function setUpAllPages () {
	if ($('postCodeSearch') != null) {
		clearInputBox('postCodeSearch','Type your postcode',2)
	}
	if ($('loginBox') != null) {
		$('loginBox').setStyle({ cursor:'pointer' });
		$('loginBox').observe('click', function () {
			window.location=pageURL+'login.php';
		});
	}
	sortMiniCart ();
	
	if ($('link_AllCourses') != null) {
		Event.observe('link_AllCourses', 'mouseover',function () {
			menuOver=1;
			openCloseMenu (1,'dropCourseMenu',0.6)
		});
		Event.observe('dropCourseMenu', 'mouseover',function () {
			menuOver=1;
		});
		Event.observe('dropCourseMenu', 'mouseout',function () {
			openCloseMenu (2,'dropCourseMenu',0.6)
		});
		Event.observe('link_AllCourses', 'mouseout',function () {
			openCloseMenu (2,'dropCourseMenu',0.6)
		});
		var a = $$('a[id^="courseType"]');
		a.each(function(n){
			var t = n.id.replace("courseType","");
			Event.observe(n.id, 'click',function () {
				openCloseMenu (1,'coursesList'+t,0.6)
			});
		});
	}
}


// RESIT PAGE

var daySelected, monNames = new Array("","January","February","March","April","May"," June","July","August","September","October","November","December");
function getCalendar (action) {
	$('calenderMonth').update('<img src="'+pageURL+'images/x.gif" />');
	$('calendarDates').update('');
	var aj1 = new Ajax.Request(pageURL+'/ajaxStuff.php', {method: 'post', parameters: 'getCalendar=1&action='+action,onComplete: function(response) {
		var response = response.responseText;
		var reply = response.split("||message||");
		$('calenderMonth').update(reply[1]);
		$('calendarDates').update(reply[0]);
		if ($(daySelected) != null) $(daySelected).setStyle({ borderColor: '#000' });
	}});
}

function selectDate(i) {
	var dates = i.split("-");
	daySelected = i;
	$('calDate').update('date to change');
	$('calendarButton').update(ord(dates[1])+' '+monNames[dates[2]]+' '+dates[3]);
	$('calendarCont2').hide();
}

function ord(n) {
	var sfx = ["th","st","nd","rd"];
	var val = n%100;
	return n + (sfx[(val-20)%10] || sfx[val] || sfx[0]);
}

function setUpResit() {
	$('calendarButton').observe('click', function () { $('calendarCont2').show(); });
	$('submitButton').observe('click', submitResit);
}

function submitResit () {
	if (daySelected == null) {
		messageBox('Please select a date.',3);
	}
	else {
		var allNodes = Form.serialize("resitForm");
		var dates2 = daySelected.split("-");
		var aj = new Ajax.Request(pageURL+'/ajaxStuff.php', {method: 'post', parameters: 'resitSubmit=1&date='+ord(dates2[1])+' '+monNames[dates2[2]]+' '+dates2[3]+'&'+allNodes,onComplete: function(response) {
			var response = response.responseText;
			if (response != null && response != '' ) {
				messageBox(response,3);
			}
			if (response == 'Your message has been sent.' ) {
				$('resitForm').reset();
				$('calendarButton').update('<img src="images/calendar_button.png" alt="date of resit" />');
				daySelected=null;
				$('calDate').update('calendar to select');
			}
		}});
	}
}

// ALL COURSES

function setUpAllCourses () {
	openCourses = new Array('0','1');
	var a = $$("a[id^='courseHeader']"),y;
	a.each(function(n){
		var y=n.id.replace('courseHeader_','');
		$(n.id).observe('click', function () { openCloseAllCourses (y); });
		if (y>1) {
			$('courseContent_'+y).hide();
			openCourses[y]=0;
		}
   	});
}

function openCloseAllCourses (t) {
	if (openCourses[t] == 1 && action==0) {
		action=1;
		Effect.BlindUp('courseContent_'+t, { duration: 0.5, afterFinish: function () { action=0; } });
		openCourses[t]=0;
	}
	else if (action==0) {
		action=1;
		Effect.BlindDown('courseContent_'+t, { duration: 0.5, afterFinish: function () { action=0; } });
		openCourses[t]=1;
	}
}

// LOGIN PAGE

function setUpLogin () {
	$('loginForm').reset();
	var a=$$('#loginForm input');
	a.each(function(n){
		if ($F(n.id) != null && n.id != null) {
			clearInputBox($(n.id),$F(n.id),2);
			signDefault[n.id]=$F(n.id);
		}
   	});
	$('submitSignup').observe('click',loginSubmit);
}

function loginSubmit () {
	var allNodes = Form.serialize("loginForm");
	var aj = new Ajax.Request(pageURL+'ajaxStuff.php', {method: 'post', parameters: 'loginSubmit=1&'+allNodes,onComplete: function(response) {
			var response = response.responseText;
			if (response != null && response != '' ) {
				messageBox(response,3);
			}
			if (response == 'You have been logged in.' ) {
				setTimeout(window.location=pageURL+'admin.php',2000);
			}
		}});
}

function adminLogout () {
	new Ajax.Request(pageURL+'ajaxStuff.php', { method: 'post', parameters: 'adminLogout=1',onComplete: function(response) {
		var response = response.responseText;
		setTimeout(window.location=pageURL+'login.php',2000);
	}});
}

// VENUES PAGE
function showVenue (p,b) {
	var m = $(b).cumulativeOffset();
	$('venueOverlay').setStyle ({top:(m[1]-380)+'px'});
	new Ajax.Request(pageURL+'ajaxStuff.php', { method: 'post', parameters: 'showVenue='+p,onComplete: function(response) {
		var response = response.responseText;
		$('venueOverlay').update(response);
		$('venueOverlay').show();
	}});
}

function closeVenue () {
	$('venueOverlay').update('');
	$('venueOverlay').hide();
}

function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

function setUpPaymentOptions () {
	$('submitSignup').observe('click', function () {
		var f = $RF('paySubmitForm','payOption');
		if (f=='cc') {
			window.location=pageURL+'Cart';
		}
		else if (f=='dd') {
			window.location=pageURL+'Sign-up/Direct-Debit';
		}
		else messageBox('Please select a payment option',3);
	});
}


if (thisPage == 'careers') Event.observe(window, 'load', setUpCareers);
if (thisPage == 'faqs') Event.observe(window, 'load', setUpFaqs);
if (thisPage == 'home') Event.observe(window, 'load', setUpHome);
if (thisPage == 'signup') Event.observe(window, 'load', setUpSignUp);
if (thisPage == 'courses') Event.observe(window, 'load', setUpCourses);
if (thisPage == 'contact') Event.observe(window, 'load', setUpContact);
if (thisPage == 'cart') Event.observe(window, 'load', setUpCart);
if (thisPage == 'resit') Event.observe(window, 'load', setUpResit);
if (thisPage == 'login') Event.observe(window, 'load', setUpLogin);
if (thisPage == 'all_courses') Event.observe(window, 'load', setUpAllCourses);
if (thisPage == 'payment_options') Event.observe(window, 'load', setUpPaymentOptions);
Event.observe(window, 'load', setUpAllPages);