jQuery(function() {
	
	jQuery(document).ready(function() {
		if( jQuery("form.validate").find("input#complete").length == 0 ) {
			jQuery("form.validate").append("<input type='hidden' name='complete' id='complete' value='0' />");
		}
	});	
	
	function clearError(f, id) {
		jQuery(f).find("label[for='" + id + "'] em.error").html('');
	}
	
	function throwError(id, msg, f) {
		jQuery(f).find("label[for='" + id + "'] em.error").html(msg);
		
		jQuery(f).find("input#" + id).one('change', function() {
			clearError(f, id);
		});
		
		jQuery(f).find("input#" + id).one('focus', function() {
			clearError(f, id);
		});		
	
		error = true;
		return error;
	}
				
	jQuery("form.validate").submit(function(evt) {
		evt.preventDefault();
		var error = false;
		var msg = '';
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		var userEmail = '';
		var username = '';
		var formObject = this;
		var inputs = [];
					
		jQuery(this).find(".required").each(function(){
			if( jQuery(this).val() == '') {
				id = jQuery(this).attr('id');
				msg = 'This field is required.'
				error = throwError(id, msg, formObject);
			}
			
			if( jQuery(this).hasClass('email') ) {
				if( !emailReg.test( jQuery(this).val() ) ) {
					id = jQuery(this).attr('id');
					msg = 'Please enter a valid email.';
					error = throwError(id, msg, formObject);
				}
			}
		});
			
		if( jQuery(this).find("input#complete").val() == '0' ) {
			
			if( jQuery(this).hasClass('ajax') && error == false) {
				
				jQuery(':input', this).each(function() {
					if(this.value != '') {
						inputs.push(this.name + '=' + escape(this.value));
					}
				});
				
				jQuery.ajax({
					data: inputs.join('&'),
					url: this.action,
					timeout: 2000,
					error: function() {
						console.log("Failed to submit");
					},
					success: function(r) { 
						//alert(r);
					}
				});
				
				jQuery(this).remove();
				jQuery("#intro").remove();
				jQuery(".message").html("Thank You<br /> We'll get back to you shortly!")
			
			return false;
			}
		}
		if( error == true ) {
			return false;
		}
		
	});
});