(function($) {

	// Fields
	var startingTop = 20;
	var instantAnimation = false;
	var isShowing = true;

	// jQuery onload: Add the event handler in, and
	// test for the cookie. Hide the box if the cookie
	// tells us to.
	$(document).ready(function() {
		
		$('div#previewBoxContainer div#previewBox').height(120);
		
		if ($.cookie('previewBoxHidden') == 'true') {
			// The box should be hidden
			instantAnimation = true;
			toggleBox();
			instantAnimation = false;
		}
		
		$('div#previewBoxContainer div#previewBoxToggle a').click(
			toggleBox
		);
	});

	// We can't use a "true" jQuery toggle, since that would require the box
	// to be either hidden or shown at the start, but this is down to user preference
	// - via a cookie. So instead we have to write our own toggle.
	function toggleBox() {
		if(isShowing) {
			// Hide the box
			$('div#previewBoxContainer div#previewBoxToggle a').text('show');
			var contentHeight = $('div#previewBoxContainer div#previewBox').height();

			var slideHeight = contentHeight + 8;
			
			$('div#previewBoxContainer').animate({top: '-' + slideHeight + 'px'}, instantAnimation ? 0 : 800);
			
			$.cookie('previewBoxHidden', 'true', { expires: 7, path: '/'});
			
			isShowing = false;
			
			
		} else {
			// Show the box
			$('div#previewBoxContainer div#previewBoxToggle a').text('hide');
			var contentHeight = $('div#previewBoxContainer div#previewBox').height();
			var slideHeight = contentHeight + 28;
			
			$('div#previewBoxContainer').animate({top: startingTop + 'px'}, 800);
			
			$.cookie('previewBoxHidden', 'false', { expires: 7, path: '/'});
			
			isShowing = true;
		}
	}
}
)(jQuery);