jQuery.fn.validator = function() {
	var fields = this;

	$(this).focus(function() {
		$(this).parent().addClass('removeLabel');
	});
	
	$(this).blur(function() {
		if (!$(this).val())
			$(this).parent().removeClass('removeLabel');
	});
	
	$(this).keydown(function() {
		$(this).parent().find('.validateError').remove();
	});
	
	var zIndex = 3000;
	
	$(this).each(function() {
		if ($(this).val())
			$(this).parent().addClass('removeLabel');
			
		$(this).parent().css('zIndex', zIndex);
		
		zIndex -= 1000;
	});
	
	$(this).closest('form').submit(function() {
		$('.validateError').remove();
		
		var error = false;
		
		$(fields).each(function() {
			if ($(this).hasClass('required')) {
				var regexp = new RegExp($(this).attr('regexp'));
				var val = $(this).val();
				
				if (!regexp.test(val)) {
					$(this).focus();
					$(this).parent().append('<div class="validateError">' + $(this).attr('message') + '</div>');
					
					error = true;
					return false;
				}
			}
		});
		
		if (!error) {
			var data = {};
			
			$(fields).each(function() {
				data[$(this).attr('name')] = $(this).val();
				$(this).val('');
				$(this).parent().removeClass('removeLabel');
			});
			
			$.ajax({
				type: 'POST',
				url: 'sendmail.php',
				data: data,
				success: function() {
					$('.messageSuccess').fadeIn(500);
					setTimeout(function() {
						$('.messageSuccess').fadeOut(1000);
					}, 5000);
				}
			});
		}

		return false;
	});
}
