
window.addEvent('domready', function ()
{

	/**
	 * This part handles the forms included by the form component.
	 * When these forms are submitted, the default event is prevented,
	 * and a XHR is send with the data of the form attached, using the POST method.
	 * The receiving script will handle the incoming data and send a JSON message
	 * confirming successful processing or an error message.
	 */

	// First get a list of all the active `auto'-forms on the page.
	var formList = document.id(document.body).getElements('form.autoForm');
	if (formList && formList.length)
	{

		// Attach the event handler to each form
		formList.each(function (form)
		{

			// Get the form's ID
			var formID = form.get('id').replace('form:', '').toInt();
			
			// Prepend an notice/error element
			var noticeElement = new Element('p', {'class': 'formNotice', styles: {display: 'none'}}).inject(form, 'before');

			// The XHR request
			var httpRequest = new Request.JSON(
			{
				url: 'forms.ajax.php?form=' + formID,
				method: 'post',
				onRequest: function ()
				{
					noticeElement.setStyle('display', 'none');
				},
				onSuccess: function (response)
				{
					// Check the status code; 1 means success, 0 means error
					if (response && response.status)
					{
						if (response.redirect)
							window.location = response.redirect;
						else if (response.message)
						{
							noticeElement.set('text', response.message);
							noticeElement.setStyle('display', '');
						}
					}
					else
					{
						noticeElement.set('text', response ? response.error : 'Er is een onbekende fout opgetreden.');
						noticeElement.setStyle('display', '');
					}
				}
			});
			
			// reCAPTCHA
			var reCAPTCHA = form.getElement('div.reCAPTCHA');
			var reCAPTCHA_API_URL = 'http://www.google.com/recaptcha/api/js/recaptcha_ajax.js'
			if (reCAPTCHA)
			{
				var placeholder = reCAPTCHA.getElement('img');
				var publicKey = placeholder.get('id');
				
				if (!publicKey)
					return false;
					
				new Asset.javascript(reCAPTCHA_API_URL, {onload: function ()
				{
					if (!window.Recaptcha)
						return false;
						
					Recaptcha.create
					(
						publicKey,
						reCAPTCHA,
						{
							lang: 'nl',
							theme: 'clean',
							callback: Recaptcha.focus_response_field
						}
					);
				
				}});
			}

			// The submit event handler
			form.addEvent('submit', function (event)
			{
				if (event) event.preventDefault();

				// Gather the data
				var data = {};
				var items = form.getElements('input[type=radio]');
				items.each(function (item)
				{
					alert(item.get('value'));
				});
				
				var items = form.getElements('select').combine(form.getElements('input')).combine(form.getElements('textarea'));
				items.each(function (item)
				{
					if (item.get('type') == 'submit')
						return;
					data[item.get('name')] = item.get('value');
				});

				// Send the request with the data attached.
				httpRequest.send({data: data});
			});

		});

	}

});

