// this will handle form submission

// check to make sure we have a form
$(document).ready(function(){
	if (document.getElementById('join_form'))
	{
		// watch for submit clicks
		$('#join_submit').bind('click', function(){
			// validate me!
			var validated = true;
			// clear any error classes
			$('input').each(function(){
				$(this).removeClass('error');
			});
			$('#join_form_error').html('');
			// first, check for required fields
			$('input.required').each(function(){
				if (this.value == '')
				{
					validated = false;
					$(this).addClass('error');
				}
			});
			// quick check and error message display if necessary
			if (!validated)
			{
				$('#join_form_error').append('Some required info was missing<br />');
			}
			// check for good email address format
			var email = $('input.email')[0].value;
			apos=email.indexOf("@");
			dotpos=email.lastIndexOf(".");
			if (apos<1||dotpos-apos<2)
			{
				validated = false;
				$('input.email').addClass('error');
				$('#join_form_error').append('Invalid email address<br />');
			}
			// and for phone number format
			if ($('input.phone')[0].value.replace(/\D/g, '').length != 10)
			{
				validated = false;
				$('input.phone').addClass('error');
				$('#join_form_error').append('Invalid phone number<br />');
			}

			// if validation succeeded, continue with submission
			if (validated)
			{
				$.post("join_form_ajax.php", $('#join_form').serialize(), function(data){
					if ($.trim(data) == '1')
					{
						// forward to thank you page
						window.location.href = 'apply_thanks.php';
					}
					else
					{
						alert('There was a problem submitting the form.  Please try again.');
					}
				});

			}
		});
	}
});
