function verificaMailValido(campo){
	var c = document.getElementById(campo);
	if(c.value != ""){
		//verifica se é um e-mail válido
		var arroba = c.value.indexOf("@");
		if(arroba == -1){
			alert("E-MAIL inválido");
			c.focus();
			c.select();
			return false;
		}else{
			var v = c.value.substr(arroba+1, c.value.length);
			var ponto = v.indexOf(".com");
			if(ponto == -1){
				ponto = v.indexOf(".net");
				if(ponto == -1){
					ponto = v.indexOf(".br");
					if(ponto == -1){
						alert("E-MAIL inválido");
						c.focus();
						c.select();
						return false;
					}
				}
			}
			if(ponto != -1){
				var meio = v.substr(0,ponto);
				if(meio.length < 2){
					alert("E-MAIL inválido");
					c.focus();
					return false;
				}
			}
		}
	}
}

function verificaTelefoneValido(campo){
	c = document.getElementById(campo);
	if(c.value != ""){
		//verifica se o telefone tem somente dígitos
		abre = c.value.indexOf("(");
		fecha = c.value.indexOf(")");
		ddd = v = c.value.substr(abre+1,fecha-1);
		if(isNaN(v)){
			alert("TELEFONE inválido");
			c.focus();
			return false;
		}else{
			//verifica os próximo caracteres
			v = c.value.substr(fecha+2,c.value.length);
			if(isNaN(v)){
				alert("TELEFONE inválido");
				c.focus();
				return false;
			}
			if(v.length < 8){
				alert("TELEFONE inválido");
				c.focus();
				return false;
			}
		}
		//------------------------------------------

		//Verifica se o DDD tem dois dígitos
		if(ddd.length != 2){
			alert("DDD inválido");
			c.focus();
			return false;
		}
		espaco = ddd.indexOf(" ");
		if(espaco != -1){
			alert("DDD inválido");
			c.focus();
			return false;
		}
		//------------------------------------------
	}
}

function verificaSiteValido(campo){
	c = document.getElementById(campo);
	if(c.value != ""){
		w = c.value.indexOf("www");
		if(w == -1){
			alert("ENDEREÇO inválido");
			c.focus();
			return false;
		}
		ponto = c.value.indexOf(".com");
		if(ponto == -1){
			ponto = c.value.indexOf(".net");
			if(ponto == -1){
				ponto = c.value.indexOf(".br");
				if(ponto == -1){
					alert("ENDEREÇO inválido");
					c.focus();
					return false;
				}
			}
		}
	}
}

function verificaCEPValido(campo){
	c = document.getElementById(campo);
	if(c.value != ""){
		if(c.value.length < 9){
			alert("CEP inválido");
			c.focus();
			return false;
		}else{
			//verifica se tem apenas dígitos
			hifem = c.value.indexOf("-");
			v = c.value.substr(0,hifem);
			if(isNaN(v)){
				alert("CEP inválido");
				c.focus();
				return false;
			}
			v = c.value.substr(hifem+1,c.value.length);
			if(isNaN(v)){
				alert("CEP inválido");
				c.focus();
				return false;
			}
		}
	}
}

function verificaCPFValido(campo, indice){
	c = document.getElementById(campo);
	cpf = c.value;
	var caminho = String();
	if(indice == 1)
		caminho = "xml/verificaCPF.php";
	else if(indice == 2)
		caminho = "../xml/verificaCPF.php";

	if(cpf != ""){
		var ajax = suporteAjax();
		if(ajax){
			ajax.open("POST", caminho, true);
			ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			ajax.onreadystatechange = function(){
				if(ajax.readyState == 1){
					c.value = "Verificando CPF...";
				}else if(ajax.readyState == 4){
					if(ajax.responseText){
						var resultado = ajax.responseText;
						if(resultado == 0){
							alert("CPF inválido");
							c.value = cpf;
							c.focus();
							return false;
						}else{
							c.value = cpf;
							return true;
						}
					}else{
						alert("CPF inválido");
						c.value = cpf;
						c.focus();
						return false;
					}
				}
			}
			var parametro = "cpf="+cpf;
			ajax.send(parametro);
		}
	}
}

function verificaCNPJValido(campo, indice){
	d = document.getElementById(campo);
	cnpj = d.value;
	var caminho = String();
	if(indice == 1)
		caminho = "xml/verificaCNPJ.php";
	else if(indice == 2)
		caminho = "../xml/verificaCNPJ.php";
	if(cnpj != ""){
		var ajax = suporteAjax();
		if(ajax){
			ajax.open("POST", caminho, true);
			ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			ajax.onreadystatechange = function(){
				d.value = "Verificando CNPJ...";
				if(ajax.readyState == 4){
					if(ajax.responseText == 1){
						d.value = cnpj;
						return true;
					}else if(ajax.responseText == 0){
						alert("CNPJ inválido");
						d.focus();
						d.value = cnpj;
						return false;
					}
				}
			}
			var parametros = "cnpj="+cnpj;
			ajax.send(parametros);
		}
	}
}

function verificaUsuarioDisponivel(campo, tabela, indice){
	d = document.getElementById(campo);
	var caminho = String();
	if(indice == 1)
		caminho = "xml/verificaUsuarioDisponivel.php";
	else if(indice == 2)
		caminho = "../xml/verificaUsuarioDisponivel.php";

	usuario = d.value;
	if(usuario != ""){
		var ajax = suporteAjax();
		if(ajax){
			ajax.open("POST", caminho, true);
			ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			ajax.onreadystatechange = function(){
				d.value = "Verificando disponibilidade de usuário";
				if(ajax.readyState == 4){
					if(ajax.responseText == 0){
						alert("Usuário já cadastrado, escolha outro");
						d.focus();
						d.value = usuario;
						return false;
					}else if(ajax.responseText == 1){
						d.value = usuario;
						return true;
					}
				}
			}
			var parametros = "tabela="+tabela+"&usuario="+usuario;
			ajax.send(parametros);
		}
	}
}

function verificaDataValida(campo){
	var data = document.getElementById(campo);
	if(data){
		if(data.value != ""){
			//sepera os valores
			if(isNaN(data.value.substr(0,2)) || isNaN(data.value.substr(3,2)) || isNaN(data.value.substr(6,4))){
				alert("Data inválida");
				data.focus();
				return false;
			}else{
				var dia = Number(data.value.substr(0,2));
				var mes = Number(data.value.substr(3,2));
				var ano = data.value.substr(6,4);
				//verifica se o dia, o mês e o ano tem o número de caracteres necessários
				if((dia < 1 || dia > 31) || (mes < 1 || mes > 12) || ano.length != 4){
					alert("Data inválida");
					data.focus();
					return false;
				}
			}
		}
	}
}

function verificaHoraValida(campo){
	var tempo = document.getElementById(campo);
	if(tempo){
		if(tempo.value != ""){
			//sepera os valores
			if(isNaN(tempo.value.substr(0,2)) || isNaN(tempo.value.substr(3,2))){
				alert("Hora inválida");
				tempo.focus();
				return false;
			}else{
				var hora = Number(tempo.value.substr(0,2));
				var minutos = Number(tempo.value.substr(3,2));
				//verifica se a hora e os minutos tem o número de caracteres necessários
				if((hora < 0 || hora > 23) || (minutos < 0 || minutos > 59)){
					alert("Hora inválida");
					tempo.focus();
					return false;
				}
			}
		}
	}
}

function verificaTamanhoTotal(campo, indice, tamanho){
	//cada vez que o usuário digita em um campo, é verificado se o tamanho do texto atingiu o tamanho limite
	var texto = document.getElementsByName(campo);
	if(texto){
		//pega o caractere digitado
		var digitado = event.keyCode;
		if(texto[indice].value.length >= tamanho){
			if(!codigoCaractere02(digitado)){
				//não faz nada
				event.returnValue = false;
			}
		}
	}
}

function suporteAjax(){
	try{
		ajax = new ActiveXObject("Microsoft.XMLHTTP");
	}catch(e){
		try{
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(ex){
			try{
				ajax = new XMLHttpRequest();
			}catch(exc){
				alert("Esse browser não tem suporte para uso de AJAX");
				ajax = null;
			}
		}
	}

	return ajax;
}

function buscaCidades(valor, indice){
	cidade = document.getElementById("cidade");
	var ok = 0;
	var caminho = String();
	if(indice == 1)
		caminho = "xml/cidades.php";
	else if(indice == 2)
		caminho = "../xml/cidades.php";

	//verifica se o navegador tem suporte à AJAX
	var ajax = suporteAjax();

	if(ajax){
		cidade.length = 1;
		idOpcao = document.getElementById("opcoes");
		ajax.open("POST", caminho, true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.onreadystatechange = function(){
			if(ajax.readyState == 1){
				idOpcao.innerHTML = "Carregando";
			}
			if(ajax.readyState == 4){
				if(ajax.responseXML){
					busca(ajax.responseXML);
				}else{
					idOpcao.innerHTML = "Primeiro selecione o Estado";
				}
			}
		}

		var params = "estado=" + valor;
		ajax.send(params);
		ok = 1;
	}

	return (ok);
}

function busca(obj){
	var dataArray = obj.getElementsByTagName("cidade");
	if(dataArray.length > 0){
		for(i=0;i<dataArray.length;i++){
			var itens = dataArray[i];
			var codigo = itens.getElementsByTagName("codigo")[0].firstChild.nodeValue;
			var descricao = itens.getElementsByTagName("descricao")[0].firstChild.nodeValue;

			idOpcao.innerHTML = "Selecione uma Cidade";

			var novo = document.createElement("option");
			novo.setAttribute("id","opcoes");
			novo.value = codigo;
			novo.text = descricao;
			cidade.options.add(novo);
		}
	}else{
		idOpcao.innerHTML = "Primeiro selecione o Estado";
	}
}

function incrementaCampo(caractere, campo, local){
	valor = campo.value;
	if(local == "inicio"){
		valor = caractere + valor;
	}else{
		valor = valor + caractere;
	}
	campo.value = valor;
}

function incrementaTelefone(campo){
	var fone = document.getElementById(campo);
	if(fone){
		//verifica qual tecla o código da tecla que o usuário digitou
		var digitado = event.keyCode;
		if(fone.value.length < 13){
			//verifica se o valor digitado é o código de um número
			if(codigoCaractere(digitado)){
				if(fone.value.length == 0)
					fone.value = "(" + fone.value;
				else if(fone.value.length == 3)
					fone.value = fone.value + ") ";
			}else{
				//verifica se o valor digitado é um backspace, delete, etc
				if(!codigoCaractere02(digitado)){
					//não faz nada
					event.returnValue = false;
				}
			}
		}else{
			//verifica se o valor digitado é um backspace, delete, etc
			if(!codigoCaractere02(digitado)){
				//não faz nada
				event.returnValue = false;
			}
		}
	}
}

function incrementaCEP(campo){
	var cep = document.getElementById(campo);
	if(cep){
		//pega o caractere digitado
		var digitado = event.keyCode;
		if(cep.value.length < 9){
			//verifica se o valor digitado é um número
			if(codigoCaractere(digitado)){
				if(cep.value.length == 5)
					cep.value = cep.value + "-";
			}else{
				if(!codigoCaractere02(digitado)){
					//não faz nada
					event.returnValue = false;
				}
			}
		}else{
			if(!codigoCaractere02(digitado)){
				//não faz nada
				event.returnValue = false;
			}
		}
	}
}

function incrementaCNPJ(campo){
	var cnpj = document.getElementById(campo);
	if(cnpj){
		//verifica qual tecla o código da tecla que o usuário digitou
		var digitado = event.keyCode;
		if(cnpj.value.length < 18){
			//verifica se o valor digitado é o código de um número
			if(codigoCaractere(digitado)){
				if(cnpj.value.length == 2 || cnpj.value.length == 6)
					cnpj.value = cnpj.value + ".";
				else if(cnpj.value.length == 10)
					cnpj.value = cnpj.value + "/";
				else if(cnpj.value.length == 15)
					cnpj.value = cnpj.value + "-";
			}else{
				//verifica se o valor digitado é um backspace, delete, etc
				if(!codigoCaractere02(digitado)){
					//não faz nada
					event.returnValue = false;
				}
			}
		}else{
			//verifica se o valor digitado é um backspace, delete, etc
			if(!codigoCaractere02(digitado)){
				//não faz nada
				event.returnValue = false;
			}
		}
	}
}

function incrementaCPF(campo){
	var cpf = document.getElementById(campo);
	if(cpf){
		//verifica qual tecla o código da tecla que o usuário digitou
		var digitado = event.keyCode;
		if(cpf.value.length < 14){
			//verifica se o valor digitado é o código de um número
			if(codigoCaractere(digitado)){
				if(cpf.value.length == 3 || cpf.value.length == 7)
					cpf.value = cpf.value + ".";
				else if(cpf.value.length == 11)
					cpf.value = cpf.value + "-";
			}else{
				//verifica se o valor digitado é um backspace, delete, etc
				if(!codigoCaractere02(digitado)){
					//não faz nada
					event.returnValue = false;
				}
			}
		}else{
			//verifica se o valor digitado é um backspace, delete, etc
			if(!codigoCaractere02(digitado)){
				//não faz nada
				event.returnValue = false;
			}
		}
	}
}

function incrementaData(campo){
	var data = document.getElementById(campo);
	if(data){
		//pega o caractere digitado
		var digitado = event.keyCode;
		if(data.value.length < 10){
			//verifica se o caractere digitado é um número
			if(codigoCaractere(digitado)){
				if(data.value.length == 2 || data.value.length == 5)
					data.value = data.value + "/";
			}else{
				//verifica se não é um caractere especial
				if(!codigoCaractere02(digitado)){
					//não faz nada
					event.returnValue = false;
				}
			}
		}else{
			//verifica se não é um caractere especial
			if(!codigoCaractere02(digitado)){
				//não faz nada
				event.returnValue = false;
			}
		}
	}
}

function incrementaHora(campo){
	var hora = document.getElementById(campo);
	if(hora){
		//pega o caractere digitado
		var digitado = event.keyCode;
		if(hora.value.length < 5){
			//verifica se o caractere digitado é um número
			if(codigoCaractere(digitado)){
				if(hora.value.length == 2)
					hora.value = hora.value + ":";
			}else{
				//verifica se não é um caractere especial
				if(!codigoCaractere02(digitado)){
					//não faz nada
					event.returnValue = false;
				}
			}
		}else{
			//verifica se não é um caractere especial
			if(!codigoCaractere02(digitado)){
				//não faz nada
				event.returnValue = false;
			}
		}
	}
}

function calculaIdade(campo, campoMostragem){
	var data = document.getElementById(campo);
	var display = document.getElementById(campoMostragem);
	if(data && display){
		var dt = new Date();
		var diaAtual = new Number(dt.getDate());
		var mesAtual = new Number(dt.getMonth() + 1);
		var anoAtual = new String(dt.getYear());
		if(isNaN(data.value.substr(0,2)) || isNaN(data.value.substr(3,2)) || isNaN(data.value.substr(6,4))){
			display.value = "";
		}else{
			//separa os valores
			var dia = new Number(data.value.substr(0,2));
			var mes = new Number(data.value.substr(3,2));
			var ano = new String(data.value.substr(6,4));
			if(Number(ano) >= Number(anoAtual)){
				display.value = "";
			}else{
				//verifica se o dia, o mês e o ano tem o número de caracteres necessários
				if((dia >= 1 && dia <= 31) && (mes >= 1 && mes <= 12) && ano.length == 4){
					var valor = anoAtual - ano;
					//verificação do mês
					if(mes > mesAtual){
						valor--;
					}else if(mes == mesAtual){
						//verificação da data
						if(dia > diaAtual){
							valor--;
						}
					}
					display.value = valor + " anos";
				}else{
					display.value = "";
				}
			}
		}
	}
}

function codigoCaractere(codigo){
	//código das teclas de números, retorna o número digitado
	var codigosNumeros = new Array();
	var numeros = new Array();
	codigosNumeros.push(48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105);
	numeros.push("0","1","2","3","4","5","6","7","8","9","0","1","2","3","4","5","6","7","8","9");
	for(var i=0;i<codigosNumeros.length;i++){
		if(codigosNumeros[i] == codigo)
			return numeros[i];
	}
	return false;
}

function codigoCaractere02(codigo){
	//código das teclas de BACKSPACE, DELETE, setas para esquerda e direita, TAB, SHIFT, END, HOME, ESC
	var codigos = new Array();
	var caracteres = new Array();
	codigos.push(8,46,37,39, 9, 16, 35, 36, 27);
	caracteres.push("BACKSPACE", "DELETE", "ESQUERDA", "DIREITA", "TAB", "SHIFT", "END", "HOME", "ESC");
	for(var i=0;i<codigos.length;i++){
		if(codigos[i] == codigo)
			return caracteres[i];
	}
	return false;
}

function codigoCaractereLetras(codigo){
	//código das teclas de letras, retorna a letra digitada
	var codigosLetras = new Array(65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,186);
	var letras = 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","ç");
	codigosLetras.push();
	letras.push();
	for(var i=0;i<codigosLetras.length;i++){
		if(codigosLetras[i] == codigo)
			return letras[i];
	}
	return false;
}