/******************************************************************************************************************
 * Arquivo criado em:		2003-01-11
 * Arquivo atualizado em:	2011-03-24
 * Autor:					Francisco L. de Matos
 * Descricao:				Funcoes de validacao, tratamento e recursos em geral de e-mails
 ******************************************************************************************************************/

	// 01 - Validar e-mail a partir de uma string - is_email
	/*
		Atributos:  1º e-mail (Ex.: fulano@empresa.com.br, ...)
		Uso com: 	funções em gerais
		Exemplo: 	boolean = is_email('fulano@empresa.com.br');
		Descricao: 	Esta função é utilizada exclusivamente para validar conteúdos de e-mail de variáveis string.
	*/
	function is_email(){
		// 1. Coleta de parâmetros
		var em = ""; var ce = 0;
		for (i = 0; i < arguments.length; i++) {
			if (i == 0) {em = arguments[i];}
		}
		// 2. Tratamentos/críticas
		// 2.1. ERRO: conteudo nulo
		if (em == '') {return false;}
		// 2.2. ERRO: conteudo pequeno
		if (em.length < 8) {return false;}
		// 2.3. ERRO: verificar caracteres especiais
		em = em.toLowerCase();
		var carac_ = new Array("!","#","$","%","&","*","(",")","+","=",
							   "/","\\","|","?","'","\"","{","}","[","]",
							   "ª","º",":",",",";","§","°","<",">");
		for(i=0; i<carac_.length; i++) {
			if (em.indexOf(carac_[i],0) != -1) {ce++;}
		}
		if (ce != 0) {return false;}
		// 2.4. ERRO: verifica o arroba
		var email_ = em.split('@');
		if (email_.length < 2) {return false;}
		// 2.5. ERRO: verifica o comprimento da conta e do domínio
		var conta = "", dominio = "";
		conta = email_[0]; dominio = email_[1];
		if (conta.length < 2) {return false;}
		if (dominio.length < 4) {return false;}
		// 2.6. ERRO: verifica o ponto
		var dominio_ = dominio.split('.');
		//if (dominio_.length < 2 || dominio_.length > 4) {return false;}
		if (dominio_.length < 2) {return false;}
		// 2.7. ERRO: tratamento da instituição, extensão e país
		var inst = '', ext = '', pais = '', qa = (dominio_.length - 1);
		var eh_pais = 0, eh_ext = 0;
		string = dominio_[qa];
		for (i = 0; i < dominio_.length; i++) {
			if (dominio_[i].length < 2) {return false;}
		}
		if (is_pais(string)) {
			pais = string;
			eh_pais = 1; qa--;
			string = dominio_[qa];
		}
		if (is_extensao(string)) {
			ext = string;
			eh_ext = 1; qa--;
		} else {
			if (eh_pais == 0) {
				return false;
			}
		}
		for (i = 0; i <= qa; i++) {
			inst += dominio_[i]+'.';
		}
		inst = inst.substr(0,(inst.length-1));
		if (inst.length < 2) {return false;}
		// 2.8. NOTA: se o script chegou até aqui então tá tudo certo
		return true;
	}
	
	// 02 - Validar e-mail a partir da string de um campo - validar_email
	/*
		Atributos:  1º campo (Ex.: this)
					2º formulário (Ex.: this.form. É usado para identificar campos que são repetidos na página, porém em formulários diferentes)
		Uso com: 	onBlur (geralmente)
		Exemplo: 	onBlur="validar_hora(this,this.form)"
		Descricao: 	Esta função é utilizada para validação de strings de e-mail em campos de formulario.
	*/
	function validar_email(){
		// 1. Coleta de parâmetros
		var campo = "", form = "";
		for (i = 0; i < arguments.length; i++) {
			if (i == 0) {campo = arguments[i];}
			if (i == 1) {form = arguments[i];}
		}
		// 2. tratamento de parametros padroes
		var temp_ = localizar_formulario_campo(campo,form);
		vI = temp_[0]; vJ = temp_[1];
		if (vI == -1 || vJ == -1) {return false;}
		// d) validação e mensagem de erro
		var em = document.forms[vI].elements[vJ].value;
		if (em != "") {
			if (!is_email(em)) {
				// 2. Resposta
				alert(em+"\n\r\n\r ERRO: E-mail inválido!");
				//document.forms[vI].elements[vJ].value = "";
				window.setTimeout("document.forms["+vI+"].elements["+vJ+"].focus()",20);
				//window.setTimeout("document.forms["+vI+"].elements["+vJ+"].select()",20);
			}
		}
	}
	
	// 03 - Extrai dados de uma string e-mail - extrair_dados_email
	/*
		Atributos:  1º string do e-mail (Ex.: fulando@empresa.com.br)
		Uso com: 	chamada normal de funcoes
		Exemplo: 	var eh_pais = extrair_dados_email('fulando@empresa.com.br','dominio'); ---> empresa.com.br
		Descricao: 	Esta função é utilizada para extrar dados de uma string de e-mail
	*/
	function extrair_dados_email(){
		// 1. Coleta de parâmetros
		var email = '', type = '', path = '', ce = 0;
		for (i = 0; i < arguments.length; i++) {
			if (i == 0) {email = arguments[i];}
			if (i == 1) {type = arguments[i];}
		}
		// 2. Tratamentos/críticas
		if (!is_email(email)){return '';}
		// 3. Capturar o nome do arquivo com a extensão
		x_ = email.split('@');
		// 4. Retorno
		if (type == 'conta'){return x_[0];}
		if (type == 'dominio'){return x_[1];}
		return '';
	}
	
	// 04 - Verificar se o caracter digitado em um campo pertence aos padrões do e-mail - apenas_email
	/*
		Atributos:  1º evento (Ex.: event)
					2º array - opcional - (permite a escolha do algorítimo que será utilizado)
		Uso com: 	campos
		Exemplo: 	onkeypress="return apenas_email(event,1)"
		Descricao: 	Esta função é utilizada exclusivamente para validar conteúdos de campos, ou seja, permitir
					a digitação apenas de caracteres característicos de e-mail.
	*/
	function apenas_email(){
		// 1. Coleta de parâmetros
		var evento = 0, achou = 0, array = 1;
		for (i = 0; i < arguments.length; i++) {
			if (i == 0) {evento = arguments[i];}
			if (i == 1) {array = arguments[i];}
		}
		// 2. Tratamento do evento
		// 2.1. Captura do evento
		if(typeof(evento) != 'object') {
			tecla = evento;
		}else {
			if(document.all) { // Internet Explorer
				tecla = evento.keyCode;
			} else { // Nestcape, Firefox
				var tecla = evento.which    ? evento.which    :
						    evento.keyCode  ? evento.keyCode  :
							evento.charCode ? evento.charCode : void 0;
			}
		}
		// 2.2. Habilitar teclas <UNDEFINED>, <DEL>, <TAB>, <ENTER>, <ESC>, <BACKSPACE> e <???>
		if (tecla == 0 || tecla == 8 || tecla == 9 || tecla == 13 || tecla == 16 || tecla == 27 || tecla == 46) {
			if(document.all) {evento.returnValue = true; return true;} else {return true;}
		}
		// 3. Tratamento usando array
		if (array == 1) {
			var achou = 0;
			var c_ = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','w','z','@','.','_','-','1','2','3','4','5','6','7','8','9','0');
			var c = String.fromCharCode(tecla)
			for(i=0; i<c_.length; i++) {if (c == c_[i]) {achou = 1;}}
			if (achou == 1) {
				if(document.all) {evento.returnValue = true; return true;} else {return true;}
			}
		} else {
			// 3.2. Habilitar numeros
			if ((tecla >= 48)  &&  (tecla <= 57)){if(document.all) {evento.returnValue = true; return true;} else {return true;}}
			// 3.3. Habilitar letras minúsculas
			else if ((tecla >= 97)  &&  (tecla <= 122)){if(document.all) {evento.returnValue = true; return true;} else {return true;}}
			// 3.4. Habilitar @ _ - .
			else if (tecla == 64 || tecla == 95 || tecla == 45 || tecla == 46){if(document.all) {evento.returnValue = true; return true;} else {return true;}}
		}
		// 4. Se a funcao chegar ate aqui eh porque o evento nao eh valido
		if(document.all) {evento.returnValue = false; return false;} else {return false;}
	}


