(function($){
	
	var acore_validate_is_processing = false;
	
	function acore_validate_remove_errors()
	{
		$('.form-element-error').each(function(i){ acore_validate_remove_error($(this)); });
	}
	
	function acore_validate_remove_error(elem)
	{
		elem.removeClass('form-element-error');
		elem.siblings('.error-info').remove();
	}
	
	function acore_validate_update_errors(elem, prefix, err, force)
	{
		$.each(err, function(i){
			var obj_id = prefix + ((prefix.length > 0) ? '_' : '') + i;
			$obj = $('#' + obj_id, elem);
			var errdata = err[i];
			if ($obj.length == 0)
				$obj = elem;
			if (typeof(errdata) == 'object')
			{
				acore_validate_update_errors($obj, obj_id, errdata, force);
			}
			else
			{
				if ($obj.length > 0)
				{
					if (force)
					{
						$obj.get(0).isValidatable = true;
					}
					if ($obj.get(0).isValidatable)
					{
						$obj.siblings('.error-info').remove();
						$obj.after('<span class="error-info">'+errdata+'</span>');
						$obj.addClass('form-element-error');
					}
				}
			}
		});
	}
	
	$(document).ready(function(){
		$('.zend_form form').each(function(){
			var $form = $(this);
			$('input.validate, select.validate', this).each(function(){
				if ($(this).hasClass('instant-validate'))
					this.isValidatable = true;
				else
					this.isValidatable = false;
				
				$(this).focus(function(){
					acore_validate_remove_error($(this));
					$(this).addClass('active-form-element');
				});
				
				$(this).blur(function(){
					this.isValidatable = true;
					if (!acore_validate_is_processing)
					{
						acore_validate_is_processing = true;
						acore_validate_remove_errors();
						$(this).removeClass('active-form-element');
						$form.ajaxSubmit({
							type: 'POST',
							success: function(responseText, statusText){
								var errors = eval('('+responseText+');');
								acore_validate_update_errors($form, '', errors, 0);
								acore_validate_is_processing = false;
							}
						});
					}
				});
			});
			
			$form.submit(function(){
				if (this.isSubmittable)
					return true;
				var form = this;
				$form.ajaxSubmit({
					type: 'POST',
					success: function(responseText, statusText){
						var errors = eval('('+responseText+');');
						if ($(errors).length > 0)
						{
							acore_validate_remove_errors();
							acore_validate_update_errors($form, '', errors, 1);
							$.scrollTo($('.error-info:first', form).get(0), 500, { onAfter: function(){
								$.scrollTo('-=100', 100, { onAfter: function(){
									alert('Kérjük, javítsa ki a hibákat az űrlap elküldése előtt!');
								}});
							}});
						}
						else
						{
							form.isSubmittable = true;
							$form.submit();
						}	
					}
				});
				return false;
			});
		});
		
	});
	
})(jQuery);
