//RuFox (C)
//Универсальный валидатор форм

jQuery.fn.validator = function()
{
	$("*[pattern!='']").each(function()
	{
		$(this).attr('regex',$(this).attr('pattern'));
	});
	
	$('form').each(function() {
		if ($(this).find("input[regex],select[regex],textarea[regex]").length>0)
		{
			$(this).submit(jQuery.fn.validator.handler);
		}
	});
}

jQuery.fn.validator.checker = function(patt, value, errormsg, formname, callback)
{
		var reg = new RegExp(patt);
		if (!reg.test(value)) 
		{
			fielderr = errormsg;
			if (typeof fielderr == 'undefined')
				fielderr = 'Ошибка в поле "' + formname + '"';
			return fielderr + '\n';
		}
		if (typeof callback !='undefined') 
			return eval(callback+"('"+value+"','"+errormsg+"')");
		else 
			return '';
}

jQuery.fn.validator.handler = function (e) 
{
	var err='';
	var fielderr='';
	$("input[regex]:not(:checkbox)", e.target).each (function()
	{
		err=err + jQuery.fn.validator.checker ($(this).attr('regex'), 
											   $(this).val(), 
											   $(this).attr('errormsg'), 
											   $(this).attr('name'),
											   $(this).attr('callback'));
	});
	
	$("select[regex] option:selected", e.target).each(function() {
		err=err + jQuery.fn.validator.checker ($(this).parents('select:first').attr('regex'), 
											   $(this).val(), 
											   $(this).parents('select:first').attr('errormsg'),  
											   $(this).parents('select:first').attr('name'),
											   $(this).parents('select:first').attr('callback'));
	});
	
	$("input[regex]:checkbox:not(:checked)", e.target).each(function() {
		err=err + $(this).attr('errormsg') + "\n";
	});
	

	$("textarea[regex]", e.target).each(function() {
		err=err + jQuery.fn.validator.checker ($(this).attr('regex'), 
											   $(this).val(), 
											   $(this).attr('errormsg'),  
											   $(this).attr('name'),
											   $(this).attr('callback'));
	});
	
	$("input[regex]:radio", e.target).each(function() {
		
		var chb = $("input[name='" + $(this).attr('name')+ "']:radio:checked", e.target).val();
		if (typeof chb == 'undefined') chb='';
		err=err + jQuery.fn.validator.checker ($(this).attr('regex'), 
											   chb, 
											   $(this).attr('errormsg'),  
											   $(this).attr('name'),
											   $(this).attr('callback'));
	});
	
	if (err!='') 
	{
		jQuery.fn.validator.showalert(err);
		return false;	
	} else {
		$("input[type='submit']", e.target).each(function()
			{ 
				$(this).attr('disabled','disabled'); 
			});
		return true;
	}
		
}

jQuery.fn.validator.showalert = function (message)
{
	alert(message);
}

$(document).ready (function () {

	$().validator();

});