/*
FUNCTION to handle Ajax form submissions...

parses the named form, and generates URL pairs to submit to the server. based on the response from the server it can then display various messages/highlight missing text fields...

for now mny of the variables are hardccded in but eventually it'd be nice to have this data set in an external values files

*/

formID='mainContactForm';
submitURL='submit_form.php';

$(function() {
	$('#'+formID).submit(function() {
	  var inputs = [];
	  var allVariables;
	  $(':input', this).each(function() {
		inputs.push(this.name+'='+escape(this.value));
	  })

	  jQuery.ajax({
		data: inputs.join('&'),
		url: submitURL,
		error: function() {
		  serverError();
		},
		success: function(responseString) {
		  handleResponse(responseString);
		}
	  })
	  return false;
	})
})

function serverError() {
	//this function should be run if we are unable to contact the server/find the submitURL
  	alert("Unable to communicate with the server.\nPlease try again later.\n");
}

function handleResponse(responseString) {

	//clear the old highlighted fields...
	$('#formName').removeClass("formHighlight");
	$('#formEmail').removeClass("formHighlight");
	$('#formMessage').removeClass("formHighlight");
	
	//send goal conversion to analytics script...
	pageTracker._trackPageview('/contactFormSubmitted.html');

	//split the response string - currently delimited by a double pipe ||
	responseDetails=responseString.split('||');
	numberOfDetails=responseDetails.length;
	actionCode=responseDetails[0];
	for (x=1; x<=numberOfDetails; x++) {
		//set highlights where needed
		formElement=responseDetails[x]
		$('#'+formElement).addClass("formHighlight");
		if (x==1) {
			$('#'+formElement).focus();
		}
	}
	if (actionCode==194) {
		//success!
		$('#success').html("Your message has been sent. Thanks!");
		$('#failure').css("display", "none");
		$('#success').css("display", "block");
		clearForm(formID);
	}
	else if (actionCode==195) {
		//failure!
		$('#failure').html("Please ensure ALL required fields are completed.");
		$('#success').css("display", "none");
		$('#failure').css("display", "block");
	}
	else if (actionCode==196) {
		//failure!
		$('#failure').html("Please ensure you enter a valid email address.");
		$('#success').css("display", "none");
		$('#failure').css("display", "block");
	}

}

function clearForm(formID) {
	$('#'+formID+' :input').val("");
 }