google.setOnLoadCallback(function() {
	navigation();
	highlightForms();
	formError();
	clickEvents();
	emailAFriendFocus();
	tableRows();
	searchAgain();
	showLogin();
	loadEventsCalendar();
	validateMembershipForm();
	testimonials();
	searchText();
});

function navigation() {
	var timer = null;
	var navigation = $('navigation');
	var subNavigation = $$('#main-navigation ul');
	
	// if statement needed when fb is launched else it throws a js error, /shrug
	if (navigation) {
		navigation.observe('mouseover',
			function(event) {
				var element = Event.findElement(event, 'a');
	
				// if anchor is in main navigation show relevant sub nav on tab mouseover
				if (element && element.up(1).readAttribute('id') == 'main-navigation') {
					subNavigation.invoke('hide').invoke('setOpacity',0);
					
					var elementSubNavigation = element.next();
					if (elementSubNavigation != null) {
						elementSubNavigation.setStyle({ display : 'block' }).setOpacity(1);
					}
				}
				
				clearTimeout(timer);
				
				// stop any fade/appear effects	(e.g. while the sub nav is crossfading back to the original and you hover over a new tab)
				var queue = Effect.Queues.get('crossfader');
				queue.each(
					function(effect) {
						effect.cancel();
					}
				);
				
			}
		).observe('mouseout',
			function(event) {
				var element = Event.findElement(event);
				// only run if element you mouseout from isn't an anchor
				if (element.tagName.toLowerCase() !== 'a') {
					timer = setTimeout(showOriginalSubNav, 1500);
				}
			}
		);
	}
	
	// show the original sub nav when mouseout event occurs
	function showOriginalSubNav() {
		subNavigation.each(
			function(subNav) {
				if (subNav.up().className == 'on') {
					subNav.appear({
						queue: {
							scope: 'crossfader'
						}
					});
				} else {
					subNav.fade({
						queue: {
							scope: 'crossfader'
						}
					});
				}
			}
		);		
	}
}



// Highlight form fields on focus
function highlightForms() {
	var highlightForm = $$('textarea, input[type=text], input[type=password]');
		highlightForm.invoke('observe', 'focus',
			function(event) {
				event.element().addClassName('highlight');
			}
		).invoke('observe', 'blur',
			function(event) {
				event.element().removeClassName('highlight').removeClassName('highlight-error');
			}
		);
}

// Highlight form fields with errors
function formError() {
	var formError = $$('.form li .error, div#comments span.error');
		formError.each (
			function(formErrorHighlight) {
				var error = formErrorHighlight.innerHTML;
				var errorHTML = error.substring(0,4);
				if (! (errorHTML == '<!--')) {
					var formErrorHighlightInput = formErrorHighlight.previous('input[type=text], input[type=password], textarea');
					if (typeof formErrorHighlightInput !== 'undefined') {
						formErrorHighlightInput.addClassName('highlight-error');
					}
				}
			}
		);
}

function clickEvents() {
	var page = $('page');
	if (page) {
		page.observe('click',
			function(event) {
				var element = event.findElement();

				if (element.tagName == 'A') {
					
					var fileExtension = element.href.substring(element.href.length-4);
					
					// Open external links & print button in new window/tab
					if ((
						element.hostname !== window.location.hostname &&
						element.up(1).className !== 'toolbox' &&
						element.href.substring(0,6) !== 'mailto') ||
						element.className == 'toolbox-print' ||
						fileExtension == '.pdf'
					) {						
						event.stop();
						window.open(element.href);
						
					// Increase/decrease text size in article
					} else if (element.className == 'toolbox-increase-text') {
						textSize('up');
						event.stop();
						
					} else if (element.className == 'toolbox-decrease-text') {
						textSize('down');
						event.stop();
					// show content in company profile page
					} else if (element.hasClassName('company-profile-link')) {
						event.stop();
						var companyID = element.readAttribute('rel');						
						Effect.toggle(companyID, 'slide', { duration: 0.5 });
					} 
					
					
				// Let users click anywhere in the story div to go to url	
				} else if (element.up('div.story') && (element.up('div.story').hasClassName('no-hover') != true) ) {
					var link = element.up('div.story').down('a');

					if (
						typeof link !== 'undefined' &&
						link.className !== 'newsround' &&
						link.className !== 'signup' &&
						link.className !== 'join-forum' &&
						link.className !== 'events-calendar-link' &&
						link.className !== 'event-login'
					) {
						document.location = link.href;
					}
					else if (typeof link !== 'undefined' && link.className == 'signup') {
						parent.fb.loadAnchor('/newsletter-signup/', 'width:530 height:350, showCaption:false');
					}
					else if (typeof link !== 'undefined' && link.className == 'join-forum') {
						parent.fb.loadAnchor(link.href, 'width:510 height:280, showCaption:false');
					}
					else if (typeof link !== 'undefined' && link.className == 'events-calendar-link') {
						parent.fb.loadPageOnClose=link.href;
						parent.fb.end();
					}
					else if (typeof link !== 'undefined' && link.className == 'event-login') {
						parent.fb.loadAnchor('/membership/login.php', 'width:510 height:278, showCaption:false');
					}
					
				} else if (element.hasClassName('story') && element.hasClassName('no-hover') != true) {
					var link = element.down('a');
					
					if (
						typeof link !== 'undefined' &&
						link.className !== 'newsround' &&
						link.className !== 'signup' &&
						link.className !== 'join-forum' &&
						link.className !== 'events-calendar-link' &&
						link.className !== 'event-login'
					) {
						document.location = link.href;
					}
					else if (typeof link !== 'undefined' && link.className == 'signup') {
						parent.fb.loadAnchor('/newsletter-signup/', 'width:530 height:350, showCaption:false');
					}
					else if (typeof link !== 'undefined' && link.className == 'join-forum') {
						parent.fb.loadAnchor(link.href, 'width:510 height:280, showCaption:false');
					}
					else if (typeof link !== 'undefined' && link.className == 'events-calendar-link') {
						parent.fb.loadPageOnClose=link.href;
						parent.fb.end();
					}
					else if (typeof link !== 'undefined' && link.className == 'event-login') {
						parent.fb.loadAnchor('/membership/login.php', 'width:510 height:278, showCaption:false');
					}
				}
				
				// Committees/events toggle
				var button = Event.findElement(event, '.toggleheader button');
				if (button) {
					var divToToggle = button.next('div.togglecontent');
					new Effect.toggle(divToToggle,'slide');
					
					if (button.className == 'minus') {
						button.removeClassName('minus').addClassName('plus');
					} else {
						button.removeClassName('plus').addClassName('minus');
					}
					
				}
	
			}
		);
	}
}

// Set alternate table row colour
function tableRows() {
	var tableRow = $$('div.article tbody tr:nth-child(odd)');
	tableRow.invoke('addClassName','stripe');
}

// Increase/decrease text size in article
function setDefaultFontSize() {
	textToResize = $$('div.article')[0];
	var fs = textToResize.getStyle('fontSize');

	if (fs.endsWith("px")) {
		myFontSize = parseFloat(fs);
		myFontSizeIncrement = 2;
		myFontSizeType = 'px';
	} else if (fs.endsWith("%")) {
		myFontSize = 100;
		myFontSizeIncrement = 10;
		myFontSizeType = '%';
	} else if (fs.endsWith("em")) {
		myFontSize = parseFloat(fs);
		myFontSizeIncrement = 0.1;
		myFontSizeType = 'em';
	} else {
		myFontSize = parseFloat(fs);
		myFontSizeIncrement = 2;
		myFontSizeType = 'px';
	}
}

function textSize(dir) {
	if (typeof myFontSize == 'undefined') {
		setDefaultFontSize();
		myNewFontSize = myFontSize;
	}

	if (dir == 'up') {
		myNewFontSize += myFontSizeIncrement;
	} else {
		myNewFontSize -= myFontSizeIncrement;
	}

	myNewFontSizeString = myNewFontSize + myFontSizeType;
	textToResize.setStyle({ fontSize: myNewFontSizeString });

	return;
}

function emailAFriendFocus() {
	var email = $('your-email');
	if (email) {
		email.focus();
	}
}

function searchAgain() {
	var searchAgain = $('search-again-input');
	if (searchAgain) {
		searchAgain.observe('focus',
			function() {
				if ($F(this) == 'Search again...') {
					this.value = '';
				}
			}
		).observe('blur',
			function() {
				if ($F(this) == '') {
					this.value = 'Search again...';
				}
			}
		);
	}
}

// Show/hide content based on user status
function showLogin() {
	var login_cookie = readCookie('qca_login_id');
	var loggedInDiv = $$('.reg-loggedin');
	var loggedOutDiv = $$('.reg-notloggedin');
	
	if (login_cookie == null) {	
		loggedOutDiv.invoke('show');
		loggedInDiv.invoke('hide');
	} else {
		loggedOutDiv.invoke('hide');
		loggedInDiv.invoke('show');
	}
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


fbPageOptions = {
	outsideClickCloses: false,
	overlayOpacity: 80
};

// Load event calendar in floatbox when you come from link in newsletter
function loadEventsCalendar() {
	var queryString = window.location.search.substring(1);
	if (queryString == 'eventscalendar') {
		parent.fb.loadAnchor('/events/calendar/', 'width:800 height:550, showCaption:false');
	}
}


// validates membership form
function validateMembershipForm() {
	var form = $('membership-form');
	if (form) {
		form.observe('submit',
			function(event) {				
				var requiredMarks = $$('#membership-form em');
				requiredMarks.each(
					function(requiredMark) {
						var actualRequiredMark = requiredMark.innerHTML;
						if (actualRequiredMark == '*') {
							var input = requiredMark.up().next('input[type=text]');
							if (typeof input !== 'undefined') {
								var inputName = input.readAttribute('name');
								var inputValue = input.value;		
								
								// if normal text input		
								if (inputValue == '' && inputName !== 'item[options][5]') {
									event.stop();
									input.next('span.error').update('Please enter a correct value');
									new Effect.ScrollTo(form);
								// if email text input
								} else if (inputName == 'item[options][5]') {
									if (inputValue == '') {
										event.stop();
										input.next('span.error').update('Please enter an email address');
										new Effect.ScrollTo(form);
									} else {
										var regexp = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;
										if (inputValue.match(regexp) == null) {
											event.stop();
											input.next('span.error').update('Please enter a correct email address');
											new Effect.ScrollTo(form);
										} else {
											input.next('span.error').update('');
										}
									}
								} else {
									input.next('span.error').update('');
								}
							}
						}
					}
						
				);
			}
		);
	}
}

function testimonials() {
	var testimonials = $$('#testimonials .column-right'),
		testimonialsArraySize = testimonials.size(),
		randomNumber = Math.round((Math.random()*testimonialsArraySize)),
		randomTestimonialElement = testimonials[randomNumber];
		
	
	// sometimes it doesn't seem to fire, left with the error: TypeError: Unable to get value of the property 'show': object is null or undefined 	 
	if (testimonials) {
		try {  
			randomTestimonialElement.show().previous().show();
		} catch (error) {
			if (typeof testimonials[0] !== 'undefined') {
				testimonials[0].show();
				testimonials[1].show();
			}
		   
		}
	}
	
}


function searchText() {
	var search = $('search-text');
	if (search) {
		search.observe('focus',
			function(event) {
				var element = event.element();
				if ($F(element) === 'Search...') {
					element.value = '';
				}
			}
		).observe('blur',
			function(event) {
				var element = event.element();
				if ($F(element) === '') {
					element.value = 'Search...';
				}
			}
		);
	}
}
