// JavaScript Document

function trim(texto)
{
	var longitud=texto.length;
	var i;
	var j;
	
	if (texto=="undefined")
	{
		return "";
	}
	for (i=0; i<longitud; i++){
		if (texto.substring(i,i+1)!==" "){
			break;
		}
	}
	for (j=longitud; j>0; j--){
		if (texto.substring(j-1,j)!==" "){
			break;
		}
	}
	if (j==0) {
		texto = "";
	}else{
		texto = texto.substring(i,j);
	}
	return texto;
}

function check_email (email) 
{
	// Por defecto, se entiende que la dirección de e-mail es correcta

	// 1 - Que la dirección contenga únicamente caracteres válidos
	allowed_chars = new Array ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "@", "_", "-");
	for (i = 0; i < email.length; i++) 
	{
		comparations = 0;
		for (j = 0; j < allowed_chars.length; j++) 
		{
			if ((email.charAt (i) != allowed_chars [j]) && (email.charAt (i) != allowed_chars [j].toUpperCase()))
			{
				comparations++;
			} 
			else 
			{
				break;
			}
		}
		if (comparations == allowed_chars.length) 
		{
			return (false);
		}
	}
	delete allowed_chars;

	
	// 2 - Comprobación de uso de una única arroba
	count_arrobas = 0;
	for (i = 0; i < email.length; i++) 
	{
		if (email.charAt (i) == '@') 
		{
			count_arrobas++;
		}
	}
	if (count_arrobas != 1) 
	{
		return (false);
	}
	

	// 3 - Comprobación de dominios
	haypunto=false
	for (i = email.length-5; i < email.length-2; i++) 
	{
		if (email.charAt (i) == '.') 
		{
			haypunto=true;
		}
	}
	if (haypunto)
	{
		return (true);
	}
	else
	{
		return(false);
	}
}

function enviar()
{
	if (trim(document.getElementById("txtNombre").value)=="")
	{
		alert ("Introduzca el nombre");
		document.getElementById("txtNombre").focus();
		return;
	}
	
	if (trim(document.getElementById("txtTlf").value)=="")
	{
		alert ("Introduzca un teléfono de contacto");
		document.getElementById("txtTlf").focus();
		return;
	}
	
	if (! check_email(document.getElementById("txtEmail").value))
	{
		alert ("Dirección de e-mail no válida");
		document.getElementById("txtEmail").focus();
		return;
	}
	
	if (trim(document.getElementById("txtDireccion").value)=="")
	{
		alert ("Introduzca la dirección");
		document.getElementById("txtDireccion").focus();
		return;
	}
	
	if (trim(document.getElementById("txtPedido").value)=="")
	{
		alert ("Introduzca un texto para la consulta");
		document.getElementById("txtPedido").focus();
		return;
	}
	document.getElementById("formulario").submit();
}
