$(document).ready(function(){

	// ----- GLOBALS -----

	var fromValue;
	var emailValue;
	var messageValue;
	var antispamValue;
	var firstSubmitAttempted = false;


	// ----- FUNCTIONS -----

	function showSection(section) {
		var doShow = function() {
			$(section).slideDown(300, function() {
				$('#footer').removeClass('long');
			});
		}

		// Clear the form
		resetForm(true);

		// If we haven't specified a section or the specified section doesn't exist,
		// default to the first one
		if (!section || $(section).length == 0) {
			section = $('#nav a:first').attr('href');
		}
		else {
			// Prepend a hash if not already present
			section = section.replace(/^[^#]/, '#$&');
		}

		clearUrlHash();

		// Highlight the menu item
		$('#nav a').removeClass('sticky');
		$('#nav a[href="' + section + '"]').addClass('sticky');

		$('#footer').addClass('long');
		if ($('body>.section:visible').length) {
			$('body>.section:visible').slideUp('fast', doShow);
		}
		else {
			doShow();
		}
	}

	function trim(s) {
		// because native .trim() is only from JS 1.8.1
		return s.replace(/^\s*(.+?)\s*$/, '$1');
	}

	function submitForm() {
		firstSubmitAttempted = true;

		validateFrom();
		validateEmail();
		validateMessage();
		validateAntispam();

		// If there were no errors, send the form
		if (!$('.errorField').length) {
			$('form *').attr('disabled', true);
			$('input.submitButton')
			.before('<span class="submitButton sending">Sending...</span>')
			.hide();

			$.ajax({
				type: 'POST',
				url: '/include/contact.php',
				data: {
					ajax: true,
					from: fromValue,
					email: emailValue,
					message: messageValue,
					antispam: antispamValue
				},
				success: function(){
					$('span.submitButton')
					.replaceWith(
						$('<span class="submitButton success">Message sent! Click here to send another</span>')
						.click(function(){
							resetForm(true);
						})
					);
				},
				error: function(jqXHR, textStatus, errorThrown) {
					$('span.submitButton')
					.replaceWith(
						$('<span class="submitButton error">Message sending failed. Click here to edit and try again</span>')
						.click(function(){
							resetForm(false);
						})
					);
				}
			});
		}
	}

	function validateFrom() {
		fromValue = trim($('#formFrom').val());
		if (!fromValue.length) {
			showFieldError('#formFrom', 'Please enter your name');
		}
		else {
			hideFieldError('#formFrom');
		}
	}

	function validateEmail() {
		emailValue = trim($('#formEmail').val());
		if (!emailValue.length) {
			showFieldError('#formEmail', 'Please enter your e-mail address');
		}
		else if (!/\S+@\S+\.\S+/.test(emailValue)) {
			showFieldError('#formEmail', 'Please enter a valid e-mail address');
		}
		else {
			hideFieldError('#formEmail');
		}
	}

	function validateMessage() {
		messageValue = trim($('#formMessage').val());
		if (!messageValue.length) {
			showFieldError('#formMessage', 'Please enter a message');
		}
		else {
			hideFieldError('#formMessage');
		}
	}

	function validateAntispam() {
		antispamValue = trim($('#formAntispam').val()).toUpperCase();
		if (!emailValue.length) {
			showFieldError('#formAntispam', 'Fill this in once you enter your e-mail address');
		}
		else if (antispamValue !== emailValue[0].toUpperCase()) {
			showFieldError('#formAntispam', 'This isn\'t the first letter of your e-mail address');
		}
		else {
			hideFieldError('#formAntispam');
		}
	}

	function showFieldError(fieldID, errorMessage) {
		if ($(fieldID).siblings('.errorPrompt').length) {
			$(fieldID).siblings('.errorPrompt').text(errorMessage);
		}
		else {
			var fieldPos = $(fieldID).offset();
			var fieldWidth = $(fieldID).outerWidth();
			$(fieldID)
			.addClass('errorField')
			.before(
				$('<p class="errorPrompt">' + errorMessage + '</p>')
				.css({
					top: fieldPos.top + 6,
					left: fieldPos.left + fieldWidth + 10
				})
				.fadeIn('slow')
			);
		}
	}

	function hideFieldError(fieldID) {
		$(fieldID)
		.removeClass('errorField')
		.siblings('.errorPrompt')
			.fadeOut('fast', function(){
				$(this).remove();
			});
	}

	function resetForm(emptyValues) {
		firstSubmitAttempted = false;
		$('form *').removeAttr('disabled');
		$('.errorField').removeClass('errorField');
		$('.errorPrompt').remove();
		$('span.submitButton').remove();
		$('input.submitButton').show();
		if (emptyValues) {
			$(':input:not(input[type=submit])').val('');
		}
	}

	function clearUrlHash() {
		var newUrl = window.location.href.replace(window.location.hash, '');
		if (newUrl != window.location.href && 'replaceState' in window.history) {
			window.history.replaceState(null, null, newUrl);
		}
	}


	// ----- EVENT HANDLERS -----

	// Intercept nav a clicks
	$('#nav a, a.local')
	.click(function(event){
		showSection($(this).attr('href'), true);
		event.preventDefault();
	});

	// Intercept form submission
	$('form').submit(function(event){
		submitForm();
		event.preventDefault();
		return false;
	});

	$(':input').blur(function(){
		if (firstSubmitAttempted) {
			switch ($(this).attr('id')) {
				case 'formFrom':
					validateFrom();
					break;
				case 'formEmail':
					validateEmail();
					validateAntispam();
					break;
				case 'formMessage':
					validateMessage();
					break;
				case 'formAntispam':
					validateAntispam();
					break;
			}
		}
	});

	// Galleries
	$('#bookReaderGallery').click(function(){
		$.slimbox([
			['/images/bookreader/01.png','Bookshelf view'],
			['/images/bookreader/02.png','Table of contents in portrait orientation'],
			['/images/bookreader/03.png','Search results view'],
			['/images/bookreader/04.png','Adding a bookmark'],
			['/images/bookreader/05.png','Bookmarks view'],
			['/images/bookreader/06.png','Sticky note shown in default "collapsed" mode'],
			['/images/bookreader/07.png','Sticky note shown in detail mode'],
			['/images/bookreader/08.png','Adding a weblink'],
			['/images/bookreader/09.png','Weblink shown in detail mode'],
			['/images/bookreader/10.png','Multi-colour highlights, both single-line and rectangle'],
			['/images/bookreader/11.png','Deleting a highlight']
		],
		0,
		{loop: false});
	});


	// ----- STARTUP PROCESSING -----

	if (!Modernizr.boxshadow) {
		$('body').addClass('noBoxShadow');
	}
	if (!Modernizr.rgba) {
		$('body').addClass('noRgba');
	}

	$('body').removeClass('nojs').addClass('js');   // NOJS/JS
	$(':input').removeAttr('required');             // Do JS validation instead
	$('body>.section').hide();                      // Hide all body sections
	$('.backtotop').hide();                         // Hide all "back to top" links
	// Remove input labels, replace with placeholders
	if ('placeholder' in document.createElement('input')) {
		$('label.hide').hide();
		$(':input').each(function() {
			$(this).attr('placeholder', $(this).attr('title'));
		});
	}

	// Insert section permalinks
	var urlBase = window.location.href
					.replace(window.location.hash, '')
					.replace(/^https?:\/\//, '')
					.replace(/^www./, '');
	$('body>.section h2:first-child').each(function(){
		var $h2 = $(this);
		var hash = '#' + $h2.parents('.section').attr('id');
		$('<a>')
		.attr({
			'href': hash,
			'title': 'Drag to bookmark / right-click to copy link'
		})
		.text(urlBase + hash)
		.addClass('permalink')
		.click(function(event){
			event.preventDefault();
		})
		.prepend('<span class="hidden">Mainwave | ' + $h2.text() + ' (</span>')
		.append('<span class="hidden">)</span>')
		.insertBefore($h2);
	});

	showSection(window.location.hash);
});

