var formBooking = $('bookingForm');
var formList = $('maillistForm');
var formQuestion = $('questionForm');

stdBorder = formBooking['name'].style.border;
errBorder = "2px solid #A0422D";

formBooking.observe('submit', function(event) {
	
	//stop the actual submit event
	event.stop();
	formBooking['submit'].disable();
	$('error_msg_booking').hide();
	clearErrors(formBooking);
	
	//ajax post to the form's action
	new Ajax.Request(formBooking.action, {
		method:     'post',
		parameters: formBooking.serialize(true),
		onSuccess:  function(transport, json)
		{
			formBooking['submit'].enable();
			if(json.success)
			{
				new Effect.toggle(formBooking, 'slide', { queue: 'front' });
				new Effect.toggle('success_msg_booking', 'appear', { queue: 'end' });
			}
			else
			{
				msg = indicateErrors(json);
				$("error_msg_booking_p").update(msg);
				new Effect.toggle('error_msg_booking', 'appear');
			}
		}
	});
});

formList.observe('submit', function(event) {
	
	//stop the actual submit event
	event.stop();
	formList['submit'].disable();
	$('error_msg_list').hide();
	clearErrors(formList);
	
	//ajax post to the form's action
	new Ajax.Request(formList.action, {
		method:     'post',
		parameters: formList.serialize(true),
		onSuccess:  function(transport, json)
		{
			formList['submit'].enable();
			if(json.success)
			{
				new Effect.toggle(formList, 'slide', { queue: 'front' });
				new Effect.toggle('success_msg_list', 'appear', { queue: 'end' });
			}
			else
			{
				msg = indicateErrors(json);
				$("error_msg_list_p").update(msg);
				new Effect.toggle('error_msg_list', 'appear');
			}
		}
	});
});

formQuestion.observe('submit', function(event) {
	
	//stop the actual submit event
	event.stop();
	formQuestion['submit'].disable();
	$('error_msg_question').hide();
	clearErrors(formQuestion);
	
	//ajax post to the form's action
	new Ajax.Request(formQuestion.action, {
		method:     'post',
		parameters: formQuestion.serialize(true),
		onSuccess:  function(transport, json)
		{
			formQuestion['submit'].enable();
			if(json.success)
			{
				new Effect.toggle(formQuestion, 'slide', { queue: 'front' });
				new Effect.toggle('success_msg_question', 'appear', { queue: 'end' });
			}
			else
			{
				msg = indicateErrors(json);
				$("error_msg_question_p").update(msg);
				new Effect.toggle('error_msg_question', 'appear');
			}
		}
	});
});

function clearErrors(form)
{
	for(var i = 0; i < form.length; i++)
	{
		var field = form[i];
		if(field.type == "textarea" || field.type == "text")
			field.style.border = stdBorder;
	}
}
	
function indicateErrors(json)
{
	var form = $(json.form);
	
	json.fields.each(
		function(fieldName)
		{
			var field = form[fieldName];
			field.style.border = errBorder;
		}
	);
	
	counter = 0;
	msg = "";
	json.errors.each(
		function(errorString)
		{
			if(counter != 0)
				msg += "<br />";
			msg += errorString;
			counter++;
		}
	);
	
	return msg;
}
