$(document).ready(function(){
	errors = new Array();

	$("#qfields").css({display:'none'});
	$("#send").attr('disabled', true);
	
	$(".switch").click(function(){
		$("#qfields").css({display:'block'});
		$("#send").attr('disabled', false);
	});
	$("input.text, input.numeric, textarea").click(function(){$(this).removeClass("error");$(this).addClass("normal");});
	
	//Подготовка к отправке
	$("#qform").submit(function(){
		$("#qform p.errormsg").remove();
		$("input, textarea").each(function(){validate($(this));});
		if (errors.length > 0) {
			higlightErrors();
			$('<p class="errormsg">Заполните выделенные поля</p>').insertBefore($("#qfields"));
			$("#qform p.errormsg").fadeIn("slow");
			errors = new Array();
			return false;
		}
	});
	
	$("#reset").click(function(){
		$("#qform p.errormsg").remove();
		$("input.text, input.numeric, textarea").removeClass("error");
		$("input.text, input.numeric, textarea").addClass("normal");
	});

	function validate(ob) {
		if (ob.hasClass('required') && !ob.val()) {
			errors.push(ob);
			return false;
		}
		if (ob.hasClass('numeric') && ob.val()) {
			checkNumeric(ob);
		}
		if (ob.hasClass('email') && ob.val()) {
			checkEmail(ob);
		}
	}
	
	/**
	 *
	 *
	 */
	 function higlightErrors() {
	 	for (i in errors) {
			errors[i].addClass("error");
		}
	 }
	
	/**
	 * Check if input has numeric values only
	 * @param object Object to validate
	 */
	function checkNumeric(ob) {
		var reg = /^[0-9]+$/gi
		var str = ob.val();
		if (!str.match(reg)) {
			errors.push(ob);
			return false;
		}
		return true;
	}
	/**
	 * Check email address
	 * @param object Object to validate
	 */
	 function checkEmail(ob) {
		var reg = /^[0-9a-z._-]+@[0-9a-z._-]+\.[a-z]{2,4}$/gi
		var str = ob.val();
		if (!str.match(reg)) {
			errors.push(ob);
			return false;
		}
		return true;
	}
});