function FieldValidation() {
	var $this = this;

	var $init = function () {

		// Add a validation
		$(document).on('click', '.field-validation-add', function () {

			// Add the rule
			$wrapper = $(this).parents().closest('.field-validation');
			var $template = $wrapper.find('.templates li.template').clone().removeClass('template');

			// Handle the change of the type of the validation
			$attachRuleChangeListener($template.find('.field-validation-type select'));
			$wrapper.find('.field-validation-list').append($template);
			$populateRuleIndex($wrapper)

		});

		// Remove validation rule
		$(document).on('click', '.field-validation-remove', function () {
			$(this).closest('li').remove();
		});
	};

	var $populateRuleIndex = function ($wrapper) {
		var $validationRules = $wrapper.find('ul li').not('.template');
		$validationRules.each(function (index, value) {
			$(this).attr('data-rule-index', index);
			$(this).find('input,select').each(function () {
				var $input = $(this);
				$input.attr('name', $input.attr('data-name').replace('!*!', index));
			});
		});
	};

	var $removeValidationRule = function ($rule) {
		var $wrapper = $rule.parents().closest('.validation-rules-list');
		$rule.remove();
		$populateRuleIndex($wrapper);
	};


	var $attachRuleChangeListener = function ($selects) {
		$selects.each(function (index, select) {
			var $select = $(select);
			$getValidationParams($select);
			$select.change(function () {
				$getValidationParams($(this));
			});
		});
	};


	var $getValidationParams = function ($select) {
		var currentRule = $select.val();
		var $validationRule = $select.closest('li');

		if ($validationRule.hasClass('skip-initial')) {
			$validationRule.removeClass('skip-initial');
			return;
		}

		// Get the rules by AJAX
		$.ajax({
			url: '/modules/validation_params',
			data: {
				'rule_id': currentRule,
				'field_index': $validationRule.attr('data-field-index'),
				'rule_index': $validationRule.attr('data-rule-index')
			},
			type: 'post',
			dataType: 'html',
			success: function (data) {
				$validationRule.find('.field-validation-params').empty().append(data);
			}
		});
	};

	// Load
	$(document).ready(function () {
		$init();
	});
}

window.fieldValidation = new FieldValidation();
