$(document).ready(function() { 
	accessControlWidget.init();
	headerProfileClickable.init();
	toggleRules.init();
	//newsPanelLoadCheck.init(); // put before normaliser, checks if images loaded yet, if not fire normaliser again when they do
	normaliser.init(['div.collation div.newsLead div.txt div.container', 'div.collation div.newsPanel div.top']);
	createFaqsDrop.init();
	homeSplash.init();
	homeProfileScroller.init();
	lightBoxEnable.init();
	jobApp.init();
	bookmarks.init();
	if($("#registration").length > 0)
		$("#registration").submit( function() { return validateSignupForm.init(); });
		
	//survey.init();
});


var newsPanelLoadCheck = {
	init:function() {
		if($('div.collation div.newsPanel').length < 1) { return; }
		$('div.collation div.newsPanel img').each(function(){
			if(!this.complete) {
				this.load(function() {
					normaliser.init(['div.collation div.newsPanel div.top']);
				});
			}
		});
	}
}



var bookmarks = {
	
	// add bookmarks here and also create an entry in main.css if a non-default image is to be used
	items: {
		favourites : { 
			name: 'Bookmark', 
			url: location.href, 
			className: 'bmFavourites' 
		},
		facebook : { 
			name: 'Facebook', 
			url: 'http://www.facebook.com/share.php?u=' + escape(location.href), 
			className: 'bmFacebook' 
		},
		twitter : { 
			name: 'Twitter', 
			url: 'http://twitter.com/home?status=' + escape(location.href), 
			className: 'bmTwitter' 
		},
		google : { 
			name: 'Google', 
			url: 'http://www.google.com/bookmarks/mark?op=add&bkmk=' + escape(location.href) + '&title=' + escape(document.title) + '&annotation=', 
			className: 'bmGoogle' 
		},
		live : { 
			name: 'Live', 
			url: 'http://favorites.live.com/quickAdd.aspx?url=' + escape(location.href) + '&title=' + escape(document.title) + '&text=', 
			className: 'bmLive' 
		},
		myspace : { 
			name: 'MySpace', 
			url: 'http://www.myspace.com/Modules/PostTo/Pages/?c=' + escape(location.href) + '&t=' + escape(document.title), 
			className: 'bmMySpace' 
		},
		digg : { 
			name: 'Digg', 
			url: 'http://digg.com/submit?phase=2&url=' + escape(location.href) + '&title=' + escape(document.title), 
			className: 'bmDigg' 
		},
		delicious : { 
			name: 'Delicious', 
			url: 'http://del.icio.us/post?url=' + escape(location.href) + '&title=' + escape(document.title), 
			className: 'bmDelicious' 
		},
		stumbleUpon : { 
			name: 'Stumbleupon', 
			url: 'http://www.stumbleupon.com/submit?url=' + escape(location.href) + '&title=' + escape(document.title), 
			className: 'bmStumble' 
		}
	},

	init:function() {
		if($('#footerTop div.newsletter').length < 1 || $('#footerTop div.bookmark').length > 0) { return; }
		var obj = this;
		obj.buildHTML();
		obj.attachEvents();
		
	},
	
	buildHTML:function() {
		var obj = this;
		var listLeft = '', listRight = '', inc = 0, favSupport = false;
		
		if(window.sidebar || window.external || window.opera) { favSupport = true; }
		
		for(var i in obj.items) {
			if(favSupport == true || i != 'favourites') {
				var listItem = '<li class="' + obj.items[i].className + '"><a href="' + obj.items[i].url + '" target="_blank">' + obj.items[i].name + '</a></li>';
				if(inc % 2 == 0) { listLeft += listItem; }
				else { listRight += listItem; }
				inc++;
			}
		}

		var outputHTML = '';
		outputHTML += '<div class="bookmark">';
		outputHTML += '    <h2>Social Bookmarks</h2>';
		outputHTML += '    <div class="panelAnchor">';
		outputHTML += '        <p><a href="#"><strong>Bookmark this page</strong></a></p>';
		outputHTML += '        <div class="anchorElem">';
		outputHTML += '            <div class="panel">';
		outputHTML += '                <div class="inner">';
		
		if(listLeft != '') {
			outputHTML += '                <ul>';
			outputHTML += listLeft;
			outputHTML += '                </ul>';
		}
		
		if(listRight != '') {
			outputHTML += '                <ul>';
			outputHTML += listRight;
			outputHTML += '                </ul>';
		}
		
		outputHTML += '                </div>';
		outputHTML += '            </div>';
		outputHTML += '        </div>';
		outputHTML += '    </div>';
		outputHTML += '</div>';
		
		$('#footerTop div.newsletter').after(outputHTML);
		
		// this is required later in our attach events method for opera to set a bookmark for the "favourites" option
		if(window.opera) { if ($('#footerTop div.bookmark li.bmFavourites a').attr('rel') != ''){  $('#footerTop div.bookmark li.bmFavourites a').attr('rel','sidebar'); } }
		
	},
	
	attachEvents:function(){
		var obj = this;
		$('#footerTop div.bookmark div.panelAnchor').mouseenter(function(ev) {
			$('#footerTop div.bookmark div.panel').show();
		});
		$('#footerTop div.bookmark div.panelAnchor').mouseleave(function(ev) {
			$('#footerTop div.bookmark div.panel').hide();
		});	
	
		// add special rule to handle the add to favourites/bookmarks link
		if($('#footerTop div.bookmark li.bmFavourites a').length > 0) {
			$('#footerTop div.bookmark li.bmFavourites a').click(function(ev) {
				ev.preventDefault();
				if (window.sidebar) {  window.sidebar.addPanel(document.title, location.href,''); }
				else if( window.external ) { window.external.AddFavorite( location.href, document.title); }
			});
		}
	}
}



var jobApp = {

	formID:'emailJobApplicationForm',

	init:function() {
		if($('#'+this.formID).length < 1) return;
		this.doVadlidate();
	},
	
	doVadlidate:function(){
		$('#'+this.formID).validate({
			rules: {
				forename: {
					required: true, 
					maxlength: 100
				},
				surname: {
					required: true,
					maxlength: 100
				},
				town: {
					required: true,
					maxlength: 100
				},
				county: {
					required: true,
					maxlength: 100
				},
				postcode: {
					required: true,
					maxlength: 100
				},
				primary_telephone_number: {
					required: true,
					maxlength: 100
				},
				email: {
					email: true,
					maxlength: 100
				},
				userCv: {
					required: true
				}
			},
			messages: 
			{
				forename: 
				{ 
					required: "Please enter your forename",
					maxlength: "Your forename must be less than 100 characters"
				},
				surname: 
				{ 
					required: "Please enter your surname",
					maxlength: "Your surname must be less than 100 characters"
				},				
				town: 
				{ 
					required: "Please enter your town",
					maxlength: "Your town must be less than 100 characters"
				},	
				county: 
				{ 
					required: "Please enter your county",
					maxlength: "Your county must be less than 100 characters"
				},	
				postcode: 
				{ 
					required: "Please enter your postcode",
					maxlength: "Your postcode must be less than 100 characters"
				},		
				primary_telephone_number: 
				{ 
					required: "Please enter your telephone number",
					maxlength: "Your telephone number must be less than 100 characters"
				},				
				email: 
				{ 
					email: "Please enter a valid email address",
					maxlength: "Your email address must be less than 100 characters"
				},	
				userCv: {
					required: "You must upload a copy of your CV with your application"
				}				
			},			

			errorPlacement: function(error, element) {
				element.parents('fieldset').append(error);
			}			
		
		});
	}

}



var lightBoxEnable = {
	grouping:'.lbox',
	item:'a[rel="imageshow"]',
	initCheck:false, // set to true after initial page load url check
	
	qsParam: 'dimg',
	itemPos:null, // if there is a default image to open, this is the position
	panelWidth:636,
	scrolling: false,	// is the object currently scrolling
	scrollSpeed: 1000,  // speed of scroll
	scrollInt: 3500,	// interval between auto scroll
	scrollSelf: true,	// set auto scroll on or off
	twoPanelEndlessScroll: true, // set to false when only two panels and the scroll effect goes left, right, left instead of forever left	
	elems: Array('#galleryImages','#galleryVideo'),

	init:function() {
		var obj = this;
		var qStr = ''+location.search; // turn querystring into a text string
		$('a[rel="imageshow"]').each(function(s, e) {
			if(qStr.indexOf(obj.qsParam + "=" + $(this).find('img').eq(0).attr('src')) > -1 && obj.itemPos == null) { obj.itemPos = s; }
			$(e).colorbox({ transition:'elastic',  speed:500,  current:'' });
		});
		if(obj.itemPos != null) {  $('a[rel="imageshow"]').eq(obj.itemPos).trigger('click'); }
		
		if($('#colorbox_target').length < 1) {
			$('body').append('<div style="display: none"><div id="colorbox_target" style="width: 640px; padding-top: 5px; padding-left: 6px; padding-right: 6px;height: 386px;"><div id="colorbox_target_video"></div></div></div>'); // originally "580", "400"
		}
		
		$('a[rel="videoshow"]').colorbox({
			current:'',
			inline:true, 
			href: "#colorbox_target",
			onComplete:function(){ 
				var flashvars = { 
					file:$(this).attr('href'), 
					autostart:true, 
					'plugins':'googlytics-1'
//					skin: '/flash/vpstyle/vpstyle.xml'
				}
				var params = { wmode:'transparent', allowfullscreen:'true', allowscriptaccess:'always' }, attributes = {};
				swfobject.embedSWF("/javascript/player.swf", 'colorbox_target_video', "640", "386", "9.0.0", false, flashvars, params, attributes);	
			}
		});
		
		// for normal pages, return now, gallery requires more controls, below:
		if($('#galleryImages').length < 1) { return; }
		
		// set up scrolling
		$.each(obj.elems, function(index, elem) {
			if($(elem + ' div.galleryBody ul').length > 1) { // check there are multiple panels required to scroll
				
				// create next/previous links
				var html = '<ul><li class="next"><a href="#">Next</a></li><li class="prev"><a href="#">Previous</a></li></ul>';
				$(elem + ' div.bodyPanelFooterTop').append(html);
				
				// set width of slider
				$(elem).data("panelNum", $(elem + ' div.slider ul').length); // assign number of panels as data to the container element
				$(elem + ' div.slider').css({'width':parseInt(obj.panelWidth, 10) * parseInt($(elem).data("panelNum"), 10)});
				$(elem + ' li.next').click(function(ev) {
					ev.preventDefault();
					obj.scroll(obj.returnNext(elem), ev, elem, 'next');
				});
				$(elem + ' li.prev').click(function(ev) {
					ev.preventDefault();
					obj.scroll(obj.returnPrev(elem), ev, elem, 'prev');
				});
				
				$(elem).data("visibleSet", 0); // set initial visible set to 0
				$(elem).data("scrolling", false);
			}
		});
	},

	// find the next/previous item in the set and return the number indicator for that item
	returnNext:function(elem) {
		return (parseInt($(elem).data("visibleSet"), 10)+1) > (parseInt($(elem).data("panelNum"), 10)-1) ? 0 : parseInt($(elem).data("visibleSet"), 10)+1; // +1 to account for zero indexing, +1 to get the next increment
	},	
	returnPrev:function(elem) {
		return (parseInt($(elem).data("visibleSet"), 10)-1) < 0 ? (parseInt($(elem).data("panelNum"), 10)-1) : (parseInt($(elem).data("visibleSet"), 10)-1);
	},
	
	scroll:function(set, event, elem, action) {
		var obj = this;
		
		
		event = (!event ? null : event);
		elem = (!elem ? null : elem);
		if(event != null) { event.preventDefault(); }
		
		if(set == $(elem).data("visibleSet")) { return; }

		if($(elem).data("scrolling") == false) {
			// handles special scroll scenarios, i.e. going from first to last or last to first
			if((parseInt($(elem).data("visibleSet"), 10)+1 == parseInt($(elem).data("panelNum"), 10) && set == 0 && action == 'next') || (parseInt($(elem).data("visibleSet"), 10) == 0 && set+1 == parseInt($(elem).data("panelNum"), 10)) || (parseInt($(elem).data("visibleSet"), 10) === 0 && action == 'prev')) {
				if((parseInt($(elem).data("visibleSet"), 10) == 1 && $(elem).data("panelNum") == 2 && obj.twoPanelEndlessScroll == true) || ($(elem).data("panelNum") > 2) ) {
					obj.specialScroll(set, event, elem);
					return;
				}
			}
			
			// handles special scroll of going from item zero to item 1 in a 2 panel scenario
			if(parseInt($(elem).data("visibleSet"), 10) === 0 && action == 'prev') { 
				obj.specialScroll(set, event, elem);
				return;
			}
			
			var obj = obj;
			var s = $(elem + ' div.slider').eq(0);
			var newPos = ( 0 - (parseInt(set, 10) * obj.panelWidth) );
			
			$(elem).data("visibleSet", set);
			$(elem).data("scrolling", true);
			s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem); });
		}
	},

	specialScroll:function(set, event, elem) {
		var obj = this;
		var s = $(elem + ' div.slider').eq(0);
		var start = 'last'; // default is going from last to first as this occurs naturally in the auto-scrolling action

		if(parseInt($(elem).data("visibleSet"), 10)+1 == 1) { start = 'first'; }

		// clone the last item before the first or the first item after the last depending on start
		if(start == 'last') {
			$(elem + ' div.slider').append($(elem + ' div.slider ul').eq(set).clone());
		} else {
			s.css({'left': (0-parseInt(obj.panelWidth, 10)) });
			$(elem + ' div.slider').prepend($(elem + ' div.slider ul').eq(set).clone());
		}
		$(elem + ' div.slider').eq(0).css({'width': parseInt($(elem + ' div.slider').eq(0).css('width'), 10) + parseInt(obj.panelWidth, 10)});
		
		var newPos = ( start == 'first' ? 0 : 0 - ((parseInt($(elem).data("visibleSet"), 10) * obj.panelWidth) + obj.panelWidth) );
		$(elem).data("visibleSet", set);
		$(elem).data("scrolling", true);
		s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem, start); });	
	},	
	
	stopScroll:function(elem, special){ 
		
		if(typeof(special) != 'undefined') {
			
			var obj = this;
			var s = $(elem + ' div.slider').eq(0);
			
			if(special == 'last') {
				s.css({'left':0});
				$(elem + ' div.slider ul').eq($(elem + ' div.slider ul').length-1).remove();
			} else if(special == 'first') {
				s.css({'left': (0 - (parseInt($(elem + ' div.slider ul').length, 10)-1) * this.panelWidth) + this.panelWidth  });
				$(elem + ' div.slider ul').eq(0).remove();
			}
			$(elem + ' div.slider').eq(0).css({'width': parseInt($(elem + ' div.slider').eq(0).css('width'), 10) - parseInt(this.panelWidth, 10)});
		}
		$(elem).data("scrolling", false); 
	}
	
}


var homeProfileScroller = {
	
	elemID: '#homeProfileScroller',
	selected: 0,
	num: 0,
	
	init:function() {
		var obj = this;
		if($(obj.elemID).length < 1) return;
		
		// set heights
		var height = 0;
		$(obj.elemID).find('div.container').each(function(s, e) {
			if(parseInt($(e).height(), 10) > height) { height = parseInt($(e).height(), 10); }
		});
		$(obj.elemID).find('div.container').css({'height':height});
		
		$(obj.elemID).find('div.container').hide();
		$(obj.elemID).find('div.container').eq(obj.selected).show();
		
		// set the height of the three panels to be equal
		obj.normalise();

		var outputHTML = '<p class="more">';
		if(!$(obj.elemID).hasClass('nomorelink')) {
			outputHTML += '<a href="#"><span>Read more</span></a>';
		}
		outputHTML += '</p><a href="#" class="prev">Previous</a><a href="#" class="next">Next</a>';
		
		$(obj.elemID).append(outputHTML);
		obj.setMoreLink();
		obj.nav();
	},

	normalise:function(){
		var obj = this;
		var height = 0;
		
		if($('div.collegeContent').length < 1) {

			var arr = ['div.homeBottom div.paths div.left', 'div.homeBottom div.paths div.right', 'div.homeBottom div.news div.items'];
			$.each(arr, function(inc, selector) {
				if(parseInt($(selector).height(), 10) > height) { height = parseInt($(selector).height(), 10); }
			});
			$.each(arr, function(inc, selector) { $(selector).css({'height':height}); });
		
		} else {

			// do some different normalisation if we're on the college page
			var height = 0;
			var arr = ['div.collegeContent div.profile div.profilePanel div.inner', 'div.profile div.map div.inner'];
			$.each(arr, function(inc, selector) {
				if(parseInt($(selector).height(), 10) > height) { height = parseInt($(selector).height(), 10); }
			});
			$.each(arr, function(inc, selector) { $(selector).css({'height':height}); });	
			
		}
	},
	
	setMoreLink:function(){
		var obj = this;
		$(obj.elemID).find('p.more a').eq(0).attr({'href': $(obj.elemID + ' div.container').eq(obj.selected).find('a').eq(0).attr('href') });
	},
	
	nav:function() {
		var obj = this;
		$(obj.elemID).find('a.next').eq(0).click(function(ev) {
			ev.preventDefault();
			$(this).blur();
			var profNum = parseInt(obj.selected, 10)+1 > $(obj.elemID).find('div.container').length-1 ? 0 : parseInt(obj.selected, 10)+1;
			obj.switchProf(profNum);
		});
		
		$(obj.elemID).find('a.prev').eq(0).click(function(ev) {
			ev.preventDefault();
			$(this).blur();
			var profNum = parseInt(obj.selected, 10)-1 < 0 ?  parseInt($(obj.elemID).find('div.container').length, 10)-1 : parseInt(obj.selected, 10)-1;
			obj.switchProf(profNum);
		});		
		
	},
	
	switchProf:function(num) {
		var obj = this;
		$(obj.elemID).find('div.container').hide();
		$(obj.elemID).find('div.container').eq(num).show();
		obj.selected = num;
		obj.setMoreLink();
	}
}


var homeSplash = {
	
	elemID: '#homeScroller',
	timeout: null,
	timeoutInt: 5000,
	selected: 0,
	num: 0,
	fading: false, // prevent queueing of multiple fades or fast button switching
	
	init:function(){
		var obj = this;
		if($(obj.elemID).length < 1) return;
		
		// set initial view state
		$(obj.elemID).find('div.container').each(function(s, e) {
			if(s > 0) { $(e).hide(); }
		});
		
		$(obj.elemID).find('li').each(function(s, e) {
			$(e).mouseenter(function(ev) {
		
				$(obj.elemID).find('div.container').eq(s).fadeIn('normal');
				$(obj.elemID).find('div.container').each(function(x, y) {
					if(s != x) { $(y).fadeOut('normal'); }
				});
				
				$(obj.elemID).find('li').removeClass('selected');
				$(e).addClass('selected');				
				
				obj.selected = s;
				clearInterval(obj.timeout);
				obj.timeout = null;	
				obj.resetInterval();
			});
		});		
		
		obj.num = parseInt($(obj.elemID).find('li').length, 10);
		$(obj.elemID).find('li').eq(obj.selected).addClass('selected');
		obj.resetInterval();
	},
	
	resetInterval:function(){
		var obj = this;
		obj.timeout = setInterval( function(){
			if(parseInt(obj.selected, 10)+1 <= (obj.num-1)) { obj.selected++; } 
			else { obj.selected = 0; }
			
			$(obj.elemID).find('div.container').eq(obj.selected).fadeIn(1000);
			$(obj.elemID).find('div.container').each(function(x, y) {
				if(obj.selected != x) { $(y).fadeOut(1000); }
			});
			
			$(obj.elemID).find('li').removeClass('selected');
			$(obj.elemID).find('li').eq(obj.selected).addClass('selected');
			
		}, obj.timeoutInt);		
	}

}



// convert anchor links on faqs page into a jump menu
var createFaqsDrop = {
	liParent: 'div.contentWrapper div.main div.pathFaqs ul',
	elemID: 'faqsJumpMenu',
	init:function() {
		if($(this.liParent).length < 1) return;
		var outputHTML = '';
		var obj = this;
		outputHTML += '<select id="' + this.elemID + '">';
		$(this.liParent).find('li a').each(function(s, e) {
			outputHTML += '<option value="' + $(e).attr('href') + '">' + $(e).text() + '</option>';
		});
		outputHTML += '</select>';
		$(this.liParent).after(outputHTML);
		$('#'+this.elemID).change(function(ev) { location.href = $(this).attr('value'); });
	}
}


// various toggle styles
var toggleRules = {

	init:function(){
		if($('#breadcrumb #siteSearchSubmit').length > 0) {
			$('#breadcrumb #siteSearchSubmit').mouseenter(function(ev) {
				$(this).parents('form').addClass('selected');
			});
			$('#breadcrumb #siteSearchSubmit').mouseleave(function(ev) {
				$(this).parents('form').removeClass('selected');
			});
		}
		if($('#footerTop #signUpSubmit').length > 0) {
			$('#footerTop #signUpSubmit').mouseenter(function(ev) {
				$(this).parents('form').addClass('selected');
			});
			$('#footerTop #signUpSubmit').mouseleave(function(ev) {
				$(this).parents('form').removeClass('selected');
			});
		}			
		if($('form#registration #signupBtn').length > 0){
			$('form#registration #signupBtn').mouseenter(function(ev) {
				$(this).parents('form').addClass('selected');
			});
			$('form#registration #signupBtn').mouseleave(function(ev) {
				$(this).parents('form').removeClass('selected');
			});			
		}
	}
}



var normaliser = {

	// pass in an [array] of html element selectors and normaliser will normalise the height based on the tallest element
	// NOTE: when normalising elements containing images, the image must be loaded or have a fixed, set height (in the css or html)
	// otherwise their height is discounted in webkit-based browsers
	init:function(arr) {
		if(!arr) return;
		$.each(arr, function(inc, selector) {
			var heightInc = 0;
			if($(selector).length > 0) {
				$(selector).each(function(s, e){
					var tmpHeightInc = $(e).height();
					if(heightInc < tmpHeightInc) { heightInc = tmpHeightInc; }
				});
			if(heightInc > 0) { $(selector).css({'height':heightInc}); }
			}
		});
	}
}



// create and manage the access helper widget to allow text size and contrast changing
var accessControlWidget = {

	sizes:{'accTxtSm':63, 'accTxtMd':75, 'accTxtLg':88},	// define sizes as percentages
	sizeSelected:'accTxtSm', 								// default selected
	
	contrast:['accCntLo', 'accCntHi'],
	contrastSelected:'accCntLo',

	sizeCookie: 'sizes',
	contrastCookie: 'contrast',

	init:function(){
		
		if($('#header div.utils').length < 1) {
			$('#header h2#logo').after('<div class="utils">&nbsp;</div>'); // if the utils area is not present, add it dynamically to give a hook for the access controls
		}
		
		if($.cookie(this.sizeCookie) != null && $.trim($.cookie(this.sizeCookie)) != '') { this.sizeSelected = $.trim($.cookie(this.sizeCookie)); }
		if($.cookie(this.contrastCookie) != null && $.trim($.cookie(this.contrastCookie)) != '') { this.contrastSelected = $.trim($.cookie(this.contrastCookie)); }
		this.attachHTML();
		this.attachEvents();
	},
	
	attachHTML:function(){
		var output = '';

		output +=	'		<ul class="access">';
		output +=	'			<li><strong>Text size:</strong></li>';
		output +=	'			<li class="size" id="accTxtSm"><a href="#" title="Small text">Small</a></li>';
		output +=	'			<li class="size" id="accTxtMd"><a href="#" title="Medium text">Medium</a></li>';
		output +=	'			<li class="size" id="accTxtLg"><a href="#" title="Large text">Large</a></li>';
		output +=	'			<li><strong>Contrast:</strong></li>';
		output +=	'			<li class="contrast" id="accCntLo"><a href="#" title="Normal contrast">Normal</a></li>';
		output +=	'			<li class="contrast" id="accCntHi"><a href="#" title="High contrast">High</a></li>';
		output +=	'		</ul>';
		
		$('#header div.utils').prepend(output);
		output = null;

		$('#header ul.access #'+this.sizeSelected).addClass('selected');
		$('body').css({'font-size':this.sizes[this.sizeSelected]+'%'});
		
		$('#header ul.access #'+this.contrastSelected).addClass('selected');
		$('body').addClass(this.contrastSelected);
	},

	attachEvents:function(){
		var obj = this;
		$('#header ul li.size').click(function(ev) {
			ev.preventDefault();
			$(this).find('a').blur();
			for(var i in obj.sizes) {
				if($(this).attr('id') == i) {
					$('#header ul li.size').removeClass('selected');
					$(this).addClass('selected');
					$('body').css({'font-size':obj.sizes[i]+'%'});
					obj.sizeSelected = i;
				}
			}
			obj.storeValue(obj.sizeCookie, obj.sizeSelected);
			location.href = location.href;
		});

		$('#header ul li.contrast').click(function(ev) {
			ev.preventDefault();
			$(this).find('a').blur();
			if(!$(this).hasClass('selected')) {
				$('#header ul li.contrast').removeClass('selected');
				$(this).addClass('selected');
				obj.contrastSelected = $(this).attr('id');
				for(var i in obj.contrast) { $('body').removeClass(obj.contrast[i]); }
				$('body').addClass(obj.contrastSelected);
			}
			obj.storeValue(obj.contrastCookie, obj.contrastSelected);
		});
	},
	storeValue:function(cookName, cookValue){ 
		cookName = $.trim(cookName);
		cookValue = $.trim(cookValue);

		$.cookie(cookName, null);
		$.cookie(cookName, cookValue, { path: '/' });
	}
}



// make the whole profile clickable if javascript is enabled
var headerProfileClickable = {
	init:function() {
		if($('#header div.profile').length < 1) return;
		$('#header div.profile').click(function(ev) {
			location.href = $('#header div.profile a').eq(0).attr('href');
		});
		
	}
}

var validateSignupForm = {
	
	init:function() {

		var validData = true;	
		
		//first clear all error msg div's
		$('#formMsgFirstName').html('');
		$('#formMsgLastName').html('');
		$('#formMsgEmail').html('');
		$('#formMsgProfession').html('');
		$('#formMsgInterest').html('');
		$('#formMsgTerms').html('');

		//first trim raw data and then store in variables
		var firstName 		= $.trim($('#forename').val());
		var lastName  		= $.trim($('#surname').val());	
		var email			= $.trim($('#username').val());
		
		//check that user entered a forename
		if(firstName.length < 1) {
			validData = false;
			$('#formMsgFirstName').html('Enter your first name');
		}

		//check that user entered a last name
		if(lastName.length < 1) {
			validData = false;
			$('#formMsgLastName').html('Enter your last name');
		}
		
		//check that user entered a valid email
		if(!this.validEmail(email)) {
			validData = false;
			$('#formMsgEmail').html('Enter a valid email address');
		}
		
		//check that select box option has been picked
		if(! $('#profession').val()) {
			validData = false;
			$('#formMsgProfession').html('Choose an option from the list');
		}
		
		//check that at least one radio button has been checked
		if( !$("input[name='crmid_7']").is(':checked') && !$("input[name='crmid_8']").is(':checked') &&
			!$("input[name='crmid_9']").is(':checked') && !$("input[name='crmid_10']").is(':checked')) {
			
				validData = false;
				$('#formMsgInterest').html('Please choose at least one interest');
			
		}

		//check that user agrees to terms
		if(!$("input[name='interests1']").is(':checked')) {
			validData = false;
			$('#formMsgTerms').html('You must agree to our Terms &amp; Privacy Policy to signup');
		}
		
		return validData;
	
	},
	
	validEmail:function(email) {
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		return emailPattern.test(email);
	}
		
}

sfHover = function() {     

	var sfEls = document.getElementById("nav").getElementsByTagName("li");     
	for (var i=0; i<sfEls.length; i++) {         
		sfEls[i].onmouseover=function() {            
			this.className+=" sfhover";         
		}        
		sfEls[i].onmouseout=function() {             
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");         
		}     
	} 
}

var survey = {

	surveyName:	'#survey',
	sliderPos:	0,
	animSpeed:  800,
	panels: 	0,
	panelWidth:	680,
	controlsHeight: 28,
	highest: 0,
	a: 0,
	b: 0,
	c: 0,

	init:function() {
	
		var obj = this;
	
		this.panels = $(this.surveyName + ' .surveyPanel').length;

		if(!this.panels)	return;

		// figure out heigest panel value
		$(this.surveyName + ' .survey').each(function(s,e){
			if(obj.highest < $(this).height()) {
				obj.highest = $(this).height();
			}			
		});
		
		// now add the controls height to the heighest panel value
		this.highest += this.controlsHeight;
		this.setStyles();
		this.addEvents();

	},
	setStyles:function() {
	
		$(this.surveyName + ' .hider').css({ 'overflow' : 'hidden', 'position' : 'relative', 'height' : (this.highest + 10) + 'px' });
		$(this.surveyName + ' .slider').css({ 'width' : (this.panels * this.panelWidth ) + 'px', 'position' : 'absolute' });
		$(this.surveyName + ' .surveyPanel').css({ 'float' : 'left' });
		$(this.surveyName + ' .surveyPanelTop').css({ 'height' : this.highest + 'px' });
		$(this.surveyName + ' .controls').css({ 'display' : 'block' });
		
	},
	addEvents:function() {
		
		var obj = this;
		
		$(this.surveyName + ' .controls .next').each(function(s,e) {

			$(this).click(function() {
				obj.sliderPos = obj.panelWidth * (s + 1);
				$(obj.surveyName + ' .slider').animate({ 'left' : '-' + obj.sliderPos +'px' }, obj.animSpeed);
				
				if(s == obj.panels - 2) {
					obj.showResults();
				}
				return false;
			});

		});
		
		$(this.surveyName + ' .controls .prev').each(function(s,e) {

			$(this).click(function() {
				obj.sliderPos = obj.panelWidth * s;
				$(obj.surveyName + ' .slider').animate({ 'left' : '-' + obj.sliderPos + 'px' }, obj.animSpeed);
				return false;
			});

		});
		
		$(this.surveyName + ' .surveyPanel').each(function(s,e) {
		
			$("input[name='q" + (s+1) + "']").click(function(){
				$(obj.surveyName + ' a.next').eq(s).css({ 'display' : 'block' });
				$(this).blur();
			});
		
		});

	},
	showResults:function() {
	
		var obj = this, response;

		// calculate number of a, b and c answers
		$(this.surveyName + ' input').each(function(s,e){
		
			if ($("input[name='q" + (s+1) + "']:checked").val() == 'q' + (s+1) + 'a') {
				obj.a++;
			}
			else if ($("input[name='q" + (s+1) + "']:checked").val() == 'q' + (s+1) + 'b') {
				obj.b++;
			}
			else if ($("input[name='q" + (s+1) + "']:checked").val() == 'q' + (s+1) + 'c') {
				obj.c++;
			}
		
		});

		// generate response based on answers
		if(obj.a > obj.b && obj.a > obj.c) {
			response = 'A';
		}
		else if (obj.b > obj.a && obj.b > obj.c) {
			response = 'B';
		}
		else if (obj.c > obj.a && obj.c > obj.b) {
			response = 'C';
		}
		else {
			
			if(obj.a == obj.b) {
				response = 'A';
			}
			else if (obj.b == obj.c) {
				response = 'B';
			}
			else if (obj.a == obj.c) {
				response = 'B';
			}
			
		}

		// set display block to correct response
		$(this.surveyName + ' .results div#response' + response).css({ 'display' : 'block' });

	}
	
}
