(function($) {

	var popupMode = function() { return typeof(errors) != "undefined" && errors == 'popup'; };

	$.fn.validateInputs = function(invokeOnInvalid, lockIfValid) {

		var valid = true;

		this.each(function() {
			var fields = $(this)
                .find("input[type='checkbox'], input[type='text'], input[type='password'], select, textarea")
	            .filter(":enabled");

			var fieldChecker = function() {

				if (valid == false && popupMode())
					return;

				if (!validateField(this)) {
					valid = false;
					if (invokeOnInvalid != null && typeof (invokeOnInvalid) == "function")
						invokeOnInvalid(this);
				}
			};

			fields.each(fieldChecker);
		});

		if (!validateRadioButtonGroups(this))
			valid = false;

		return valid;
	};

	$.fn.autoValidate = function() {
		return this.each(function() {
			$(this)
                .find("input[type='checkbox'], input[type='text'], input[type='password'], select, textarea")
	            .filter(".Required:enabled, .Regex:enabled, .ValidationExpression:enabled")
	            .blur(function() { validateField(this); })
	            .change(function() { validateField(this); });
		});
	};

	var validateField = function(sender) {

		var element = $(sender);
		var errorid = 'error_' + element.attr('name').replace(/\./gi, '_');

		if (
            (element.is('.Required') && (element.val() == '' || element.val() == "0" || element.is('input[type=checkbox]:not(:checked)'))) ||
            (element.is('.Regex') && !new RegExp(element.attr("regex"), "gi").test(element.val()) && element.val() != "") ||
            (element.is('.ValidationExpression') && !eval(element.attr("validationExpression")))
       ) {
			element.addClass('Invalid');
			var error = element.attr('error');
			if (typeof (error) != "undefined" && error != null) {

				if (popupMode()) {
					setTimeout(function() { showError({ id: errorid, text: error, element : element }); }, 200);
					return false;
				}

				if ($('#' + errorid).length == 0)
					$("<div id='" + errorid + "' class='error'>" + error + "</div>")
					.show()
					.insertAfter(element);
			}
			return false;
		}
		else {
			element.removeClass('Invalid');
			$('#' + errorid).remove();
			return true;
		}
	};

	var validateRadioButtonGroups = function(container) {
		var valid = true;

		container.find('input.Required[type=radio]')
			.each(function() {
				var group = container.find('input[type=radio][name=' + $(this).attr('name') + ']');
				if (group.filter(':checked').length == 0) {
					valid = false;
					group.parent().find('.error').show();
				}
				else {
					group.parent().find('.error').hide();
				}
			});

		return valid;
	};

})(jQuery);