/*
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 many of the variables are hardccded in but eventually it'd be nice to have this data set in an external values files

*/

formID='maincolContactForm';
submitURL='_fixed/submitContactForm.php';

$(function() {
	$('#'+formID).submit(function() {

	  var inputs = [];
	  var allVariables;
	  $(':input', this).each(function() {
		if (this.type=='checkbox') {
			if ($('#contactAgro').attr('checked')) {
				inputs.push('contactAgro=true');
			}
			if ($('#contactBiocides').attr('checked')) {
				inputs.push('contactBiocides=true');
			}
			if ($('#contactReach').attr('checked')) {
				inputs.push('contactReach=true');
			}
		}
		else {
			inputs.push(this.name+'='+escape(this.value));
		}
	  
		//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("An error has occurred!\nUnable to communicate with the server.\nPlease try again later.\n");
}

function handleResponse(responseString) {

	//clear the old highlighted fields...
	removeHighlights(formID);

	//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("formInputError");
		if (x==1) {
			$('#'+formElement).focus();
		}
	}

	if (actionCode==194) {
		//success!
		$('#contactFormDisplay').hide();
		$('#contactFormThanks').show();			
		removeHighlights(formID);
		clearForm(formID);
	}
	else if (actionCode==195) {
		//failure!
		$('#failure').html("Please ensure ALL required fields are completed.");
		$('#failure').show();
	}
	else if (actionCode==196) {
		//failure!
		$('#failure').html("Please ensure you enter a valid email address.");
		$('#failure').show();
	}

}

function clearForm(formID) {
	$('#'+formID+' :input').val("");
}
function removeHighlights(formID) {
	$('#'+formID+' :input').removeClass("formInputError");
}

function displayContactForm() {
		$('#contactFormThanks').hide();	
		$('#contactFormDisplay').show();
}