// prepare the form when the DOM is ready 
$(document).ready(function() {
	//Options array					   
	var options = { 
		target: '#output',
		beforeSubmit:  validate,  // pre-submit callback 
		success: showResponse,    // post-submit callback 
		resetForm: true,         // reset the form after successful submit 
		//-- other available options: 
		//url:       url         // override for form's 'action' attribute 
		//type:      type        // 'get' or 'post', override for form's 'method' attribute 
		dataType:  'script',        // 'xml', 'script', or 'json' (expected server response type) 
		//clearForm: true        // clear all form fields after successful submit 
		//resetForm: true        // reset the form after successful submit
	
		// $.ajax options can be used here too, for example: 
        timeout:   3000
	};
	
	
	
    // bind form using ajaxForm 
    $('#intakeForm').ajaxForm(options);
});
 
//success function				
function showResponse(responseText, statusText){
	$('#success').slideToggle();
	$('#success').animate({ opacity: "show" }, "slow");
	//$('html, body').animate({scrollTop: $("#formEnd").offset().top}, 500);
	//alert('showResponse() Was Called!');
	
}

// pre-submit callback
function validate(formData, jqForm, options) {
	$("p.error").animate({ opacity: "hide" }, "slow");
	//alert('validation just ran');
	//Required Fields
	var nameValue = $('input[name=name]').fieldValue(); 
	var emailValue = $('input[name=email]').fieldValue();
	
	//compare email address to this regex
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	var correct = true;
	
	// formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
    //alert('About to submit: \n\n' + queryString); 
	
	//validate fields
	if (!nameValue[0]) {
		$("p.error.wrong_name").animate({ opacity: "show" }, "slow");
		correct = false;
	}
	//
	if (!emailValue[0]) {
		$("p.error.wrong_email").animate({ opacity: "show" }, "slow");
		correct = false;
	} else if(!emailReg.test(emailValue[0])) {
		$("p.error.wrong_email").animate({ opacity: "show" }, "slow");
		correct = false;
	}
	//alert('Correct Value: ' + correct);
	//
	if (!correct) {
		//if there are errors
		$('html, body').animate({scrollTop: $("#feedback").offset().top}, 1000);
		return false;
	}else{
		return true;	
	}
	//alert('Correct Value: ' + correct);
	
} 	

//Hide the success message when you click it		
$("p#success,p.notice").click( function () { 
	$(this).animate({ opacity: "hide" }, "slow"); 
});	