try { // Wrap this all so that we can catch and display errors appropriately.
	var _ie6 = (jQuery.browser.msie && jQuery.browser.version.substr(0,1)<7);
	
	jQuery(function() {
		// Nav menu
		jQuery('nav#top > ul > li:first').addClass('first');
		jQuery('nav#top > ul > li:last').addClass('last');
		
		jQuery('nav#top > ul > li').hoverIntent({
			over: function() {
				// If there is another submenu visible. Hide it straight away.
				jQuery('nav#top > ul > li > ul:visible').slideUp();
				
				jQuery('> a', this).addClass('hover');
				jQuery('> ul', this).slideDown();
			},
			out: function() {
				jQuery('> a', this).removeClass('hover');
				jQuery('> ul', this).slideUp();
			},
			timeout:500
		});
		
		// Popup for a new window.
		jQuery('a.popup').click(function(e) {
			window.open(jQuery(this).attr('href'));
			e.preventDefault();
		});
		// Generic Fancybox Popup
		jQuery('a.fancybox').fancybox({ autoScale:false });
		// Generic Terms Fancybox Popup
		jQuery('a.fancybox-terms').fancybox({
			autoDimensions:false,
			autoScale:false,
			height:600,
			title:false,
			width:450
		});
		// Instant Win Fancybox Popup
		jQuery('a.iw-fancybox').fancybox({
			autoScale:false,
			height:542,
			title:false,
			padding:0,
			type:'iframe',
			width:865
		});
		var _iwKeys = ['?instant-win-url=', '#instant-win-url='];
		for (i=0; i < _iwKeys.length; i++) {
			var _iwKey = _iwKeys[i];
			if (location.href.indexOf(_iwKey) != -1) { // Automagically pop up the game
				var _href = jQuery('a.iw-fancybox').attr('href');
				jQuery('a.iw-fancybox').attr('href', location.href.substring(location.href.indexOf(_iwKey)+_iwKey.length)).trigger('click');
				jQuery('a.iw-fancybox').attr('href', _href);
			}
		}
		
		// Apply Fancy Labels
		jQuery('body.blog.home input[type=text], body.blog.home textarea, .account-login form input:not(.checkbox input, [type=submit]), .customer-account-create form input:not(.checkbox input, .button), .customer-account-forgotpassword form input, .customer-account-edit form input:not(.checkbox input)').each(function() {
			var _label = jQuery(this).siblings('label');
			if (_label.length == 0) {
				_label = jQuery(this).parent().siblings('label')
			}
			// Apply the css here so that people without js enabled can still use the form properly.
			_label.css({
				'cursor':'text',
				'left':'3px',
				'position':'absolute',
				'top':'0px'
			});
			_label.parents('li').addClass('fancy-label');
		}).fancyLabels({fade:0.5,slide:true});
		
		// Figure out which fields are required and apply validation.
		jQuery('label .gfield_required').each(function() {
			try {
				var _for = jQuery(this).parent('label').attr('for');
				if (_for == '') {
					_for = jQuery(this).parents('.gfield').find('.ginput_container input[type=checkbox]:first').attr('id');
				}
				if (jQuery('#'+_for).is('input, textarea, select')) {
					jQuery('#'+_for).addClass('required');
				} else {
					jQuery('#'+_for+' input').addClass('required');
				}
			} catch(e) {
				if(window.console&&window.console.log)console.log(e);
			}
		});
		
		// Don't apply validation to magento or the select form.
		jQuery('body:not(.magento) form:not(#form-select)').each(function() {
			jQuery(this).validate({
				errorElement:'em',
				messages: {
					input_7: {
						maxlength: jQuery.format("Maximum {0} characters (including spaces).")
					}
				},
				onkeyup:false,
				onfocusout:false,
				rules: {
					input_7: {
						maxlength:110
					}
				},
				showErrors: function(errorMap, errorList) {
					jQuery('.error').removeClass('error');
					for(i=0; i < errorList.length; i++) {
						var el = errorList[i].element;
						jQuery('#'+jQuery(el).attr('id')+', label[for='+jQuery(el).attr('id')+']').addClass('error');
					
						// If this is a gravity forms checkbox, then give the description field an error class too.
						if (jQuery(el).parents('.gfield_checkbox').length != 0) {
							jQuery(el).parents('.ginput_container').siblings('.gfield_description').addClass('error');
						}
					}
				}
			});
		});
		jQuery('.gfield_checkbox').parents('li').addClass('checkbox');
		
		// Homepage slideshow.
		if (jQuery('body.blog.home #showcase #slideshow .slides').cycle) {
			jQuery('body.blog.home #showcase #slideshow .slides').cycle({
				pager:'#slideshow #pager'
			});
		}
	
		// Send to friend form
		var _send_after = '<input type="button" name="print" value="print" class="button" id="print" /><div class="preview_links"><a href="#preview_send">preview this</a><a href="#preview_print">preview this</a></div>';
		if (_ie6) { // trying to print in ie6 crashes it (surprise, surprise)
			_send_after = '<div class="preview_links"><a href="#preview_send">preview this</a>';
		}
		jQuery('body.send-card-to-friends .gform_footer.top_label .button') // Append the print button, and preview links.
			.after(_send_after);
		// Print button click event.
		jQuery('body.send-card-to-friends input#print').click(function() {
			if (jQuery('#gform_5').valid()) {
				jQuery('#full_print img').remove(); // Remove any existing images so that we can replace them here.
				jQuery('#full_print').prepend(
					'<img src="/wp-content/themes/belvoir/images/card_print_full-'+jQuery('#preview-container').attr('class')+'.jpg" />'+
					'<img src="/wp-content/themes/belvoir/images/card_print_full-tr.jpg" /><br />'+
					'<img src="/wp-content/themes/belvoir/images/card_print_full-bl.jpg" />'
				);
				// We need to move this to be a child of the body tag so that everything else can be hidden for printing.
				if (jQuery('body > #full_print').length == 0) {
					jQuery('body').append(jQuery('#full_print'));
				}
				window.print();
				return false;
			}
		});
		// Preview links.
		jQuery('body.send-card-to-friends .preview_links a').fancybox({
			autoScale: false,
			onStart:function() {
				// move the class to the face so the preview shows the correct card.
				jQuery('.preview .face').addClass(jQuery('#preview-container').attr('class'));
			},
			onClosed:function() {
				// reset it so that next time round it won't have both classes.
				jQuery('.preview .face').removeClass(jQuery('#preview-container').attr('class'));
			}
		});
		// Update the class used for the preview, and print functionalities.
		jQuery('body.send-card-to-friends .gfield_select').change(function() {
			jQuery('#preview-container, #full_print').removeAttr('class').addClass(jQuery(this).val());
		});
		// Update the your name, friends name, & message fields for the preview, and print functionalities.
		var send_card_preview = ["your_fname", "friend_name", "message"];
		for (i=0; i < send_card_preview.length; i++) {
			jQuery('body.send-card-to-friends .'+send_card_preview[i]+' input, body.send-card-to-friends .'+send_card_preview[i]+' textarea')
				.attr('rel',send_card_preview[i])
				.change(updateField).blur(updateField);
		}
		function updateField(e) {
			var field = e.currentTarget;
			jQuery('#preview-container .'+jQuery(field).attr('rel')).html(jQuery(field).val());
		}
		// Make sure no more than 110 characters are entered into the message field.
		jQuery('#input_5_7').keyup(restrictMessage);
		function restrictMessage(e) {
			var el = e.currentTarget;
			if (jQuery(el).val().length >= 110) {
				jQuery(el).val(jQuery(el).val().substring(0, 110));
			}
		}
	
		// Our friends page
		jQuery('#friend-category select').change(function() { location.href = jQuery(this).val(); });
	
		// Contact page
		if (jQuery('body.contact').length > 0) {
			var _index = location.href.indexOf('#');
			var preload = (_index != -1) ? location.href.substring(_index+1) : "send-us-a-note"; // default to send us a note form
		
			jQuery('select#type').val(preload);
			jQuery('#'+preload).show();
		
			jQuery('select#type').change(function() {
				var _this = this;
				jQuery('.form-container:visible').slideUp(function() {
					jQuery('#'+jQuery(_this).val()).slideDown();
					location.href = '#'+jQuery(_this).val();
				});
			});
			
			jQuery('option[value="disabled"]').attr('disabled', 'disabled');
			
			if ( jQuery('#input_6_10').val() == 'other' ) {
				jQuery('#gform_6 #field_6_11').slideDown();
			}
			
			jQuery('#input_6_10').change(function() {
				if ( jQuery(this).val() == 'other' ) {
					jQuery('#gform_6 #field_6_11').slideDown();
				} else {
					jQuery('#gform_6 #field_6_11').slideUp();
				}
			});
		
			jQuery('form').validate();
			
			// The current page item will be the contact page.
			jQuery('nav li.current_page_item .children a').click(function(e) {
				var _index = jQuery(this).attr('href').indexOf('#');
				if (_index != -1) { // has a hash
					var _this = this;
					jQuery('.form-container:visible').slideUp(function() {
						jQuery(jQuery(_this).attr('href').substring(_index)).slideDown();
					});
				}
			});
		}
	
		// Blog page
		jQuery('.blog-sidebar .search form').submit(function(e) {
			var option = jQuery('[name=cat] option', this).get(jQuery('[name=cat]', this).attr("selectedIndex"));
			if (jQuery(option).attr('rel') != undefined && jQuery(option).attr('rel') != "") {
				jQuery('[name=cat]', this).attr('name', 'post_type');
			}
		});
	
		// Accordions
		if (jQuery('.accordion').length > 0) {
			jQuery('.accordion section .display_item').hide()
				.siblings('header')
				.css('cursor', 'pointer')
				.hover(function() {
					jQuery(this).addClass('hover');
				},function() {
					jQuery(this).removeClass('hover');
				})
				.click(function() {
					jQuery('.accordion section header.active').removeClass('active');
					jQuery(this).addClass('active');
					// Only do something if this isn't the currently active item
					if (jQuery('.display_item:visible')[0] != jQuery(this).siblings('.display_item')[0]) {
						jQuery('.display_item:visible').slideUp();
						jQuery(this).siblings('.display_item').slideDown();
					}
				});
			// Make this happen a little after the page loads so that the user gets a preview of how it works.
			setTimeout(function() {
				jQuery('section:first .display_item').slideDown().prev('header').addClass('active');
			}, 500);
		}
	
		// Stockists Page
		jQuery('#stockists .filter').change(function() {
			if (jQuery(this).val() != "") {
				jQuery(this).siblings('.filter-item:visible').slideUp();
				jQuery('#'+jQuery(this).attr('name')+'-'+jQuery(this).val()).slideDown();
			}
		}).siblings('.filter-item').hide();
	
		// Shop Sidebar
		jQuery('dl.help dt').css('cursor', 'pointer').click(function() {
			var _slideDown = jQuery('dl.help dd:visible')[0] != jQuery(this).next('dd')[0];
			jQuery('dl.help dd:visible').slideUp();
			// Only slide back down if the current one isn't visible.
			if (_slideDown) {
				jQuery(this).next('dd').slideDown();
			}
		});
		
		// Popup link
		var _popupLabelLinks = jQuery('.shelf-links a[rel]');
		if (!_ie6 && _popupLabelLinks.length > 0) {
			_popupLabelLinks.hoverIntent({
				interval:250,
				over: function() {
					jQuery(this).css('position', 'relative');
					
					jQuery('<div class="popup2"><img /></div>').appendTo(jQuery(this)).attr('href', jQuery(this).attr('href'))
						// get the link to the image out of the rel.
						.find('img').attr('src', jQuery(this).attr('rel'));
					
					var _left = ( jQuery(this).width() / 2 ) - ( jQuery('.popup2', this).width() / 2 ) - 12;
					var _bottom = - 10 - jQuery('.popup2', this).height();
					
					// Do the animation bit here
					jQuery('.popup2', this).css({display:'block', left:_left, opacity:0, bottom:_bottom + 10}).animate({opacity:1,bottom:_bottom});
				},
				out: function() {
					var _bottom = - jQuery('.popup2').height() - 20;
					jQuery('.popup2', this).animate({opacity:0,bottom:_bottom}, function() { jQuery(this).remove(); });
				},
				timeout:250
			});
		}
		
		// Checkout
		jQuery('#shopping-cart-totals-table td:nth-child(2)').addClass('amount');
		// Disable the checkout button if there's a notice message.
		if (jQuery('.checkout-cart-index .notice-message').length > 0) {
			//jQuery('.totals input.button').attr('disabled', 'disabled').addClass('disabled');
			jQuery('.totals input.button').attr('disabled', 'disabled').addClass('hidebutton');
		}
		
		// _blank targets for menu
		jQuery('nav#top a').each(
			function(index) {
				if ( jQuery(this).attr('href').indexOf('http://belvoir.webdev.bigfish.co.uk') < 0 && jQuery(this).attr('href').indexOf('http://www.belvoirfruitfarms.co.uk') < 0 && jQuery(this).attr('href').indexOf('/') != 0 ) {
					jQuery(this).attr('target', '_blank');
				}
			}
		);
		
		jQuery('.prize-winners .entry h3 ~ ul').hide().siblings('h3').each(function() {
			jQuery(this).wrap('<a href="#" />').parents('a').click(function() {
				if (jQuery('.prize-winners .entry ul:visible')[0] == jQuery(this).next('ul')[0]) {
					jQuery(this).next('ul').slideUp();
				} else {
					jQuery('.prize-winners .entry ul:visible').slideUp();
					jQuery(this).next('ul').slideDown();
				}
			});
		});
		setTimeout(function() { jQuery('.prize-winners .entry h3:first').parent('a').next('ul').slideDown(); }, 2000); // slide down the first item after x seconds
		
		if (!(_ie6)) {
			// Facebook code
			window.fbAsyncInit = function() {
				FB.init({appId:(location.href.indexOf('webdev') != -1 ? "189666401061875" : "185970304757443"), status: true, cookie: true, xfbml: true});
			};
			(function() {
				var e = document.createElement('script'); e.async = true;
				e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
				document.getElementById('fb-root').appendChild(e);
			}());
		}

		// Track all mega-nav/sub-menu clicks - Started 2011-06-29 11:30, Stopped 2011-07-04 10:00
		// jQuery('nav#top .children a').click(function() {
		// 	jQuery.post('/wp-content/dropdowns.php?url='+jQuery(this).attr('href'));
		// });
		
		jQuery('.lovely_bunch .privacy-policy').click(function() {
			window.open(jQuery(this).attr('href'), 'privacyPolicy', 'menubar=no,location=no,resizable=no,scrollbars=yes,status=no,width=968,height=700');
			return false;
		});

		jQuery('.gform_validation_container').css('display', 'none');
	});
} catch (e) {
	// If we're on webdev, show the errors.
	if (location.href.indexOf('webdev') != -1) {
		if (jQuery.browser.msie) { alert(e.message); }
		else { if(console&&console.log)console.log(e); }
	}
}

