$(document).ready(function() {
	$('.required-field').focus(function() { $(this).keyup(); }).blur(function() { $(this).keyup(); }).keyup(function() {
		$('img[rel="' + $(this).attr('id') + '"]').css('visibility', 'visible');
		if (has_content($(this))) $('img[rel="' + $(this).attr('id') + '"]').attr('src', '/images/green-checkmark.png');
		else $('img[rel="' + $(this).attr('id') + '"]').attr('src', '/images/ghosted-checkmark.png');
	});
	
	$('#email-field').focus(function() { $(this).keyup(); }).blur(function() { $(this).keyup(); }).keyup(function() {
		$('img[rel="' + $(this).attr('id') + '"]').css('visibility', 'visible');
		if (validateEmail($(this).val())) $('img[rel="' + $(this).attr('id') + '"]').attr('src', '/images/green-checkmark.png');
		else $('img[rel="' + $(this).attr('id') + '"]').attr('src', '/images/ghosted-checkmark.png');
	});
	
	$('#contact-form').submit(function() {
		if (validate_form()) {
			$('#contact-submit').attr('disabled', 'disabled');
			//return true;
			
			var data = { "name-field": $('#name-field').val(), "email-field": $('#email-field').val(), "comments-field": $('#comments-field').val()};
			$.post('/actions/ajax-form-submit.php', data, function(xml_data) {
				switch($("response", xml_data).text()) {
					case 'Success!': $("#success-overlay").fadeIn("fast");
									 break;
					case 'Email error': $('#email-error').fadeIn("fast");
									 	break;
					case 'Random error': $('#random-error').fadeIn("fast");
										 break;
				}
				reset_form();
			}, "xml");
			return false;
		} else {
			display_errors();
			return false;
		}
	});
	
	$('#return-to-form').click(function() {
		$('#success-overlay').fadeOut("fast");
		return false;
	});
});

function has_content(field_object) {
	return (field_object.val().length > 0);
}

function display_errors() {
	$('.validation-instructions').css('visibility', 'visible');
	$('.required-field, #email-field').each(function() {$(this).keyup();});
}

function validate_form() {
	var error = false;
	$('.required-field').each(function() { if (!has_content($(this))) error = true; });
	if (!validateEmail($('#email-field').val())) error = true;
	return (!error);
}

function reset_form() {
	$('.validation-instructions, .validation').css('visibility', 'hidden');
	$('#name-field, #email-field, #comments-field').val('');
	$('#contact-submit').removeAttr('disabled');
}
