/* Cortesía de http://www.dustindiaz.com/getelementsbyclass/ */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function urlencode(str) 
{
	str = escape(str);
	str = str.replace('+', '%2B');
	str = str.replace('%20', '+');
	str = str.replace('*', '%2A');
	str = str.replace('/', '%2F');
	str = str.replace('@', '%40');
	return str;
}

function obtenerContenidoRemoto(archivo) {
	if(window.XMLHttpRequest)
	{
		pedido = new XMLHttpRequest();
	}
	else // Internet Explorer 5/6
	{
		pedido = new ActiveXObject("Microsoft.XMLHTTP");
	}
	pedido.open("GET", archivo, false);
	pedido.send(null);
	if(pedido.status == 200) 
	{
		return pedido.responseText;
	}
	return false;
}

function sacarId(cadena)
{
	return cadena.substring(2, cadena.length);
}

function obtenerEmail(id, respuesta)
{
	var posicionId = respuesta.indexOf(id);
	var inicio = respuesta.indexOf("'", posicionId);
	var fin = respuesta.indexOf("'", inicio + 1);
	if(inicio && fin)
	{
		return respuesta.substring(inicio + 1, fin);
	}
	else
	{
		return false;
	}
}

function escribirEmails()
{
	//Obtengo los comentarios
		var spans = [];
		spans = getElementsByClass("emails");
	var respuesta = obtenerContenidoRemoto("http://sanjustoenlinea.com/componentes/obtenerEmails.php");
	var email;
	if(respuesta != "")
	{
		for(var z=0; z<spans.length; z++)
		{
			email = obtenerEmail("#" + sacarId(spans[z].id) + ":", respuesta);
			if(email)
			{
				spans[z].innerHTML = email;
			}
		}
	}
}

function esUnEmail(valor) {
	//Cortesía de Jorge Mera
	if (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/.test(valor))
	{
		return (true);
	} 
	else 
	{
		return (false);
	}
}

function validar() {
	var captchaResponse = [];
	captchaResponse = document.getElementsByName("recaptcha_response_field");
	captchaResponse = captchaResponse[0];
	var captchaChallenge = [];
	captchaChallenge = document.getElementsByName("recaptcha_challenge_field");
	captchaChallenge = captchaChallenge[0];
	//Chequeo el nombre
		var errores = 0;
		if(nombre.value == "")
		{
			errores++;
			nombreError.innerHTML = "Debe ingresar un nombre";
			nombre.className = "invalido";
		}
		else
		{
			nombreError.innerHTML = "";
			nombre.className = "valido";
		}
	//Chequeo el e-mail
		if(email.value == "")
		{
			errores++;
			emailError.innerHTML = "Debe ingresar un e-mail";
			email.className = "invalido";
		}
		else
		{
			if(esUnEmail(email.value))
			{
				emailError.innerHTML = "";
				email.className = "valido";
			}
			else
			{
				errores++;
				emailError.innerHTML = "El e-mail es inválido";
				email.className = "invalido";
			}
		}
	//Chequeo el comentario
		if(comentario.value == "")
		{
			errores++;
			comentarioError.innerHTML = "Debe ingresar un comentario";
			comentario.className = "invalido";
		}
		else
		{
			comentarioError.innerHTML = "";
			comentario.className = "valido";
		}
	//Chequeo el captcha
		var captchaValido = obtenerContenidoRemoto("http://sanjustoenlinea.com/componentes/validarCaptcha.php?challenge=" + urlencode(captchaChallenge.value) + "&response=" + urlencode(captchaResponse.value));
		if(captchaValido == "1")
		{
			captchaError.innerHTML = "";
		}
		else
		{
			errores++;
			captchaError.innerHTML = "El código es inválido";
		}
	//Submit
	if(errores === 0)
	{
		this.submit();
	}
	else
	{
		Recaptcha.reload();
		return false;
	}
}

function inicializar() {
	//Asignaciones
		nombre = document.getElementById("formNombre");
		nombreError = document.getElementById("formNombreError");
		email = document.getElementById("formEmail");
		emailError = document.getElementById("formEmailError");
		comentario = document.getElementById("formComentario");
		comentarioError = document.getElementById("formComentarioError");
		captchaError = document.getElementById("formCaptchaError");
		enviar = document.getElementById("btnEnviar");
	//Eventos
		enviar.onclick = validar;
		
	document.getElementById("formulario").action += "&javascript=si";
	escribirEmails();
}

/* Cortesía de http://www.javascriptworld.com/chap9-1.html */

function addOnload(newFunction) {
	var oldOnload = window.onload;
	
	if (typeof oldOnload == "function") {
		window.onload = function() {
			if (oldOnload) {
				oldOnload();
			}
			newFunction();
		};
	}
	else {
		window.onload = newFunction;
	} 
}

addOnload(inicializar);


