/**
* Function to validate forms using AJAX requests
* 12 sept 07
*/
function validateForm (template, form, bPrefixFieldInErrorMessages, bDebug, sErrorClassName)
{

	// Set default params
	if (sErrorClassName == null || sErrorClassName == '')
	{
		sErrorClassName = 'error';
	}

	if (bDebug == null || bDebug == false)
	{
		bDebug = false;
	}

	if (bPrefixFieldInErrorMessages == null || bPrefixFieldInErrorMessages == false)
	{
		bPrefixFieldInErrorMessages = false;
	}


	window.iserror = 0;
	var sId = '#frm'+form.substr(0,1).toUpperCase() + form.substr(1);
	var oForm = $(sId);
	sCheck = unescape(oForm.serialize());


	var bError = false;
	var sDebugging = '';
	var sAjaxWrapperURL = '/formvalidate/validate/?actiontype=ajax&template=' + template + '&form=' + form + '&validate=';

	if (bDebug)
	{
		console.debug ('Ready to make a request to "' + sAjaxWrapperURL + '" with the following data: "' + sCheck + '"');
	}

	jQuery.getJSON (sAjaxWrapperURL  + jQuery.base64Encode (sCheck), function(aResponse)
	{

		if (bDebug)
		{
			console.debug("Success! Received response:\n\n" + aResponse);
		}
		window.iserror = 0;

		var aErrors = aResponse['errors'];
		var sMessage = aResponse['message'];

		for  (sKey in aErrors)
		{
			//debugger;
			if (bDebug)
			{
				console.debug ('Key: ' + sKey + ' with value ' + aErrors [sKey]);
			}

			$('#'+sKey + ' span.error').remove();
			if (aErrors [sKey] != '')
			{
				// There is an error in the response for this field.
				window.iserror = 1;

				if ($('#' + sKey).length > 0)
				{
					$('#'+sKey).addClass(sErrorClassName);
				}
				else
				{
					sDebugging = sDebugging + 'ERR - Input holder (div) with id "' + sKey + '" is not found!' + "\n";
				}


				$('#'+sKey).append('<span class="error">' + aErrors [sKey] + '</span>');



			}
			else
			{
				// This field has no error!


				if ($('#' + sKey))
				{
					$('#' + sKey).removeClass(sErrorClassName);
				}

				if ($('#'+'error_message_' + sKey))
				{
					$('#'+'error_message_' + sKey).html('');
				}

			}


		}
		if (bDebug)
		{
			console.debug ('Done.. ' + "\n" + sDebugging);
		}

		$('.formErrorMessage').remove();

		if (window.iserror != 1)
		{
			window.submitCheck = true;
			
			
			oForm.submit();
			return true;
		}
		else
		{
			$(sId + ' .submit').before ('<div class="formErrorMessage">' + sMessage + '</div>');

			return false;
		}


	});





}

function checkForEnterSubmit ()
{
	// Google chrome submits a form when hitting enter
	// Stop this behaviour because it messes up the validator.
	return (window.submitCheck != undefined);
}
