$.fn.clearForm = function() {
  return this.each(function() {
	var type = this.type, tag = this.tagName.toLowerCase();
	if (tag == 'form')
	  return $(':input',this).clearForm();
	if (type == 'text' || type == 'password' || tag == 'textarea')
	  this.value = '';
	else if (type == 'checkbox' || type == 'radio')
	  this.checked = false;
	else if (tag == 'select')
	  this.selectedIndex = -1;
  });
};

function afterAjaxSubmit(data) {
	// alert(data.response);
	// alert(data.errors);
	var contact_form_response = $('#contact_form_response');
	var divResponseText;
	if(data.response == 'failure') {
		divResponseText = 'Please correct the following errors: <ul>';
		$.each(data.errors, function(i, item) {
			 divResponseText += '<li>'+item.error+'</li>'; 
		 	// bring back default text on these if empty
			// elementId = ;
			var elementVal = $('#'+item.element).val();
			if( elementVal == '') {
				$('#'+item.element).val(item.replaceValueText);
			}
		 });
									 
		divResponseText += '</ul>';
		$('#contact_form_response').html(divResponseText);
		
		contact_form_response.addClass("submissionFail");
		// contact_form_response.removeClass("submissionSuccess");
	} 
	if(data.response == 'success') {
		divResponseText = 'Thank you for your interest! You will be added to our newsletter.';
		$('#contact_form_response').html(divResponseText);
		contact_form_response.addClass("submissionSuccess");
		// contact_form_response.removeClass("submissionFail");
		$('#contact_form').hide();
		$('#contact_form').clearForm();
	}
	contact_form_response.show();
}

function beforeAjaxSubmit() {
}

var todoAddOptions = { 
	beforeSubmit:  beforeAjaxSubmit,  // pre-submit callback 
	success:       afterAjaxSubmit,  // post-submit callback 
	// clearForm: true        // clear all form fields after successful submit 
	dataType:  'json', 
};

$(document).ready(function() {
	$('#contact_form').ajaxForm(todoAddOptions);
	$.get("_includes/form_security/token.php",function(txt){
		$(".secure").append('<input type="hidden" name="ts" value="'+txt+'" />');
	});
});