
	$(document).ready(function(){

		function comprobar(campo,campo2,tipo,tipo_valor) {
			i=i+1;
			var error = document.getElementById(campo2);
			if(tipo==1) {
					if(campo.value.indexOf('@', 0) == -1 || campo.value.indexOf('.', 0) == -1) {
						campo.style.background = "#fdb2b2";
						error.innerHTML = "<img src='img/exclamation.png' width='16' height='16'>";
					} else {
						a=a+1;
						campo.style.background = "#e0e0e0";
						error.innerHTML = "";
						error.style.height = "0px";
					}
			} else if(tipo==2) {
				if(campo.value.length < 3) {
					campo.style.background = "#fdb2b2";
					error.innerHTML = "<img src='img/exclamation.png' width='16' height='16'>";
				} else {
					a=a+1;
					campo.style.background = "#e0e0e0";
					error.innerHTML = "";
					error.style.height = "0px";
				}
			} else if(tipo==3) {
				if(campo.value != tipo_valor) {
					campo.style.background = "#fdb2b2";
					error.innerHTML = "<img src='img/exclamation.png' width='16' height='16'>";
				} else {
					a=a+1;
					campo.style.background = "#e0e0e0";
					error.innerHTML = "";
					error.style.height = "0px";
				}
			}
		}

		$("#boton_contactar").click(function() {

			var f = document.getElementById("formulario");

			i=0;
			a=0;
			comprobar(f.nombre,"span_nombre",2);
			comprobar(f.apellidos,"span_apellidos",2);
			comprobar(f.comentarios,"span_comentarios",2);
			comprobar(f.email,"span_email",1);
			comprobar(f.captcha,"span_captcha",3,codigo_captcha);
			comprobar(f.referencia,"span_referencia",2);
		
			if(a!=i) {
				return false;
			}

			var ajax = xmlhttp();

			ajax.onreadystatechange=function(){
				if(ajax.readyState==1) {
					$("#formulario_cargando").fadeIn("fast");
				}
				if(ajax.readyState==4) {
					
					setTimeout(function(){ 
						$("#formulario_cargando").fadeOut("fast");
					}, 500);
					
					setTimeout(function(){ 
						$("#formulario_contactar").hide("slow");
						$("#formulario_boton").hide("slow");
					}, 1000);
					
					setTimeout(function(){ 
						$("#formulario_enviado").show("slow");
					}, 1400);
					
				}
			}
			
			ajax.open("POST","contacto.php?enviar=1",true);
			ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			ajax.send("nombre="+f.nombre.value+"&apellidos="+f.apellidos.value+"&email="+f.email.value+"&telefono="+f.telefono.value+"&referencia="+f.referencia.value+"&comentarios="+f.comentarios.value);
			

		})

	});
