// Valijax v1.0
// COPYRIGHT JOREN RAPINI 2010
// jorenrapini@gmail.com

// Text outputs
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
checkboxerror = "Please read the terms and conditions.";
//thankyou = "Thank you, your information has been sent.";

$('.validate').submit(function() {
	//Validate required fields
	$(this).find('.required').each(function() {
		var input = $(this);
		if ((input.val() == "") || (input.val() == emptyerror)) {
			input.addClass("needsfilled");
			input.val(emptyerror);
		// Validate the e-mail.
		} else if (input.hasClass('email')) {
			if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(input.val())) {
				input.addClass("needsfilled");
				input.val(emailerror);
			}	
		// validates checkboxes
		} else if ((input.attr('type') == 'checkbox') && (input.is(':checked') == false)) {
			input.before('<span class="checkboxerror">'+checkboxerror+' </span>');
		} else {
			input.removeClass("needsfilled");
			$('.checkboxerror').remove();
		}
	});
	var output = $(this).nextAll('.output');
	var preloader = $(this).nextAll('.preloader');
	var thankyou = $(this).nextAll('.thankyoumessage');
	//if any inputs on the page have the class 'needsfilled' the form will not submit
	if ($(':input').hasClass('needsfilled')) {
		output.html('There were errors on the form,<br />please correct them and try again').slideDown(750);
	} else {
		$(this).add(output).hide();
		
		preloader.fadeIn(400);
		//update path to sendform.php if necessary relative to the html doc
		$.post('../sendform.php',$(this).serialize(), 
			function(data){	
				preloader.hide();			
				if (data) {
					output.html(data).show();
				} else {
					$(thankyou).show();
					output.html(thankyou).fadeIn(700);
				}
			}
		)
	}
	return false;
});

// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){		
   if ($(this).hasClass("needsfilled") ) {
		$(this).val("");
		$(this).removeClass("needsfilled");
   }
});
