function gE(ID) {return document.getElementById(ID)} // O FAMOSO getElementById

/* FUNÇÃO QUE CRIA O XMLHTTP ------------------*/
function contectaXML() {
	var meuXML;
	try {
		meuXML = new XMLHttpRequest();
	} catch(ee) {
		try  {
			meuXML = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try  {
				meuXML = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(E) {
				meuXML = false;
			}
		}
	}
	return meuXML;
}
/* FUNÇÃO QUE CRIA O XMLHTTP ------------------*/

/* FUNÇÃO QUE EXTRAI O SCRIPT ------------------*/
function extraiScript(texto){
//Maravilhosa função feita pelo SkyWalker.TO do imasters/forum
//http://forum.imasters.com.br/index.php?showtopic=165277
    // inicializa o inicio ><
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            // executa o script
            //eval(codigo);
            /**********************
            * Alterado por Micox - micoxjcg@yahoo.com.br
            * Alterei pois com o eval não executava funções.
            ***********************/
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}
/* FUNÇÃO QUE EXTRAI O SCRIPT ------------------*/

/* FUNÇÃO DO COMBO DE CIDADES ------------------*/
function doBusca(tuf){
	xmlhttp = contectaXML()
    //limpa o select
    var c=document.getElementById("recSelect1")
    while(c.options.length>0)c.options[0]=null
    c.options[0]=new Option(" aguarde... "," aguarde... ")

    xmlhttp.open("GET", "cidades_ajax.asp?id="+tuf,true);
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
            //limpa o select
            var c=document.getElementById("recSelect1")
            while(c.options.length>0)c.options[0]=null
            //Transforma a lista de cidades JSON em Javascript
            var aCidades=eval((xmlhttp.responseText))
            //popula o select com a lista de cidades obtida
            for(var i=0;i<aCidades.length-1;i++){
                aCidades[i]=unescape(aCidades[i])
                c.options[c.options.length]=new Option(aCidades[i],aCidades[i])
            }
        }
    }
    xmlhttp.send(null)
}
/* FUNÇÃO DO COMBO DE CIDADES ------------------*/

/* FUNÇÃO DE POST EM AJAX ------------------*/
function ajxpost(formulario,recipiente,limpa) {
	f = document[formulario]
	var meuXML = contectaXML();
	var conteudoSite = gE(recipiente);
	var dados = ""
	var pagina = f.action
	
	tmF = f.length
	//alert(tmF) //quantidade de objetos encontrados
	for (iF=0;iF<tmF;iF++) {
		
		if (f[iF].id != "tag"){
		dados = dados + escape(f[iF].value) +"|"			
			}

	}
	
	meuXML.open("POST", pagina, true);
	meuXML.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	meuXML.setRequestHeader("Content-length", dados.length);
	meuXML.setRequestHeader("Connection", "close");
	
	meuXML.onreadystatechange = function() {
		if(meuXML.readyState == 4 && meuXML.status == 200) {
			var conteudo = meuXML.responseText;
			extraiScript(conteudo);
			conteudoSite.innerHTML = conteudo
			if(conteudoSite.style.display = "none") 
				conteudoSite.style.display = "block"
				if (limpa !=undefined) limpaForm(f.name)
		}
	}
	meuXML.send(dados);
}
/* FUNÇÃO DE POST EM AJAX ------------------*/

/* VALIDACAO DO SUBMIT DO FORMULARIO ------------------*/
function consultaEmail(id,idCadastro,tipoSubmete,foco) {
	pagina = 'ajax_functions.asp?op=consultaEmail&id='+id+'&idCadastro='+idCadastro

	var conteudoSite = parent.gE('erecEmail1');
	conteudoSite.style.display = 'block'

	var meuXML = contectaXML();
	meuXML.open('GET', pagina, true);
	meuXML.onreadystatechange = function() {
		if (meuXML.readyState == 4) {

			var texto = meuXML.responseText;
			if (texto != "0") {
				conteudoSite.innerHTML = texto;
				if (foco !=undefined) gE('recEmail1').focus()
				return false
			} else {
				if (tipoSubmete == "submete") {
					submete = true
					f = document['formCadastro']
					tmF = f.length
					
					for (iF=0;iF<tmF;iF++) {
						strSchr = f[iF].id
						if (strSchr.substring(0,3) == "rec") {
							forme 	= 'formCadastro'
							source	= gE(strSchr)
							valor	= source.value
							obj		= source.id
							texto	= source.title
							nome	= source.name
							
							regras(valor,obj,texto,nome,true,forme)
							if (submete == false) return false
						}
					}
					f.submit()
				}
			}
		} 

	}
	meuXML.send(null);
	return false
}


function validaSubmit(nomeForm,ajaxpost,limpa) {
	submete = true
	f = document[nomeForm]
	tmF = f.length
	
	for (iF=0;iF<tmF;iF++) {
		strSchr = f[iF].id
		if (strSchr.substring(0,3) == "rec") {
			forme 	= nomeForm
			source	= gE(strSchr)
			valor	= source.value
			obj		= source.id
			texto	= source.title
			nome	= source.name
			
			regras(valor,obj,texto,nome,true,forme)
			if (submete == false) return false
		}
	}
	if (ajaxpost == undefined) {
		return true
	} else {
		ajxpost(nomeForm,ajaxpost,limpa)
		return false
	}
}
/* VALIDACAO DO SUBMIT DO FORMULARIO ------------------*/


/* FUNÇÃO QUE VARRE O SITE APLICANDO AS REGRAS DE VALIDACAO ------------------*/
function valida(e) {
		if(typeof(e)=='undefined')var e=window.event
		source=e.target?e.target:e.srcElement
		if(source.nodeType == 3)source = source.parentNode
		
		forme 	= source.parentNode.parentNode.id
		valor	= source.value
		obj		= source.id
		texto	= source.title
		nome	= source.name
		regras(valor,obj,texto,nome,false,forme)

}
/* FUNÇÃO QUE VARRE O SITE APLICANDO AS REGRAS DE VALIDACAO ------------------*/


/* FUNÇÃO QUE ADICIONA EVENDOS A OBJETOS ESPECIFICOS ------------------*/
function addEvent(obj, evType, fn){
		if (obj.addEventListener)
				obj.addEventListener(evType, fn, true)
		if (obj.attachEvent)
				obj.attachEvent("on"+evType, fn)
}
/* FUNÇÃO QUE ADICIONA EVENDOS A OBJETOS ESPECIFICOS ------------------*/


/* FUNÇÃO REGRAS DE VALIDACAO ------------------*/
function regras(valor,obj,texto,nome,foco,forme) {
	var errOBJ = false
	if (obj.substring(0,6) == "recTxt") {
		if (gE("e"+obj)) {
			var contentErro = gE("e"+obj);
			contentErro.style.display = "none";
		} else if (gE(forme+"erro")) {
			var contentErro = gE(forme+"erro");
			contentErro.style.display = "none";
		} else {
			var contentErro = gE(obj);
			errOBJ = true
		}

		if (valor == "" || valor== texto) {
			contentErro.innerHTML = texto;
			contentErro.style.display = "block"
			if (foco==true) {
				gE(obj).focus()
				if(errOBJ == true) contentErro.value = texto;
			}
			submete = false
		}
	} 
	if (obj.substring(0,8) == "recEmail") {
		if (gE("e"+obj)) {
			var contentErro = gE("e"+obj);
			contentErro.style.display = "none";
		} else if (gE(forme+"erro")) {
			var contentErro = gE(forme+"erro");
			contentErro.style.display = "none";
		} else {
			var contentErro = gE(obj);
			errOBJ = true
		}
		

		email = gE(obj).value
		fim = email.indexOf('.')
		ext = email.substring(fim+1,fim+3)
		
		if ( (email.length <= 0 || email.indexOf("@") == -1 || email.indexOf(".") == -1 || ext.length < 2) ) {
			contentErro.innerHTML = texto;
			contentErro.style.display = "block"
			if (foco==true) {
				gE(obj).focus()
				if(errOBJ == true) contentErro.value = texto;
			}
			submete = false
		}
	}
	if (obj.substring(0,7) == "recCtxt") {
		if (gE("e"+obj)) {
			var contentErro = gE("e"+obj);
			contentErro.style.display = "none";
		} else if (gE(forme+"erro")) {
			var contentErro = gE(forme+"erro");
			contentErro.style.display = "none";
		} else {
			var contentErro = gE(obj);
			errOBJ = true
		}

		txt		= gE(obj).value
		txtConf = gE(nome).value
		if (txt != txtConf) {
			contentErro.innerHTML = texto;
			contentErro.style.display = "block"
			if (foco==true) {
				gE(obj).focus()
				if(errOBJ == true) contentErro.value = texto;
			}
			submete = false
		}
	}
	if (obj.substring(0,6) == "recCpf") {
		///alert(gE(obj))
		valor = gE(obj).value
		gE(obj).value = valor.replace(".","")
		
		if (gE("e"+obj)) {
			var contentErro = gE("e"+obj);
			contentErro.style.display = "none";
		} else if (gE(forme+"erro")) {
			var contentErro = gE(forme+"erro");
			contentErro.style.display = "none";
		} else {
			var contentErro = gE(obj);
			errOBJ = true
		}

		if (valor == "" || valor== texto) {
			contentErro.innerHTML = texto;
			contentErro.style.display = "block"
			if (foco==true) {
				gE(obj).focus()
				if(errOBJ == true) contentErro.value = texto;
			}
			submete = false
		}
		if (valor < 9 || valor == "99999999999" || valor == "88888888888" || valor == "77777777777" || valor == "66666666666" || valor == "55555555555" || valor == "44444444444" || valor == "33333333333" || valor == "22222222222" || valor == "11111111111") {
			contentErro.innerHTML = "CPF Inv&aacute;lido";
			contentErro.style.display = "block"
			if (foco==true) {
				gE(obj).focus()
				if(errOBJ == true) contentErro.value = texto;
			}
			submete = false
		}
		
		//*validacao do CPF*//
		//alert(valor)
		cpf = valor
		var posicao, i, soma, dv, dv_informado;
		var digito = new Array(10);
		dv_informado = cpf.substr(9, 2); // retira os dois últimos dígitos do número informado
		
		// desemembra o número do cpf na array digito
		for (i=0; i<=8; i++)
			digito[i] = cpf.substr( i, 1);
		// calcula o valor do 10º dígito da verificação
		posicao = 10;
		soma = 0;
		for (i=0; i<=8; i++) {
			soma = soma + digito[i] * posicao;
			posicao = posicao - 1;
		}
			  
		digito[9] = soma % 11;
		if (digito[9] < 2) {
			digito[9] = 0;
		} else {
			digito[9] = 11 - digito[9];
		}
		
		// calcula o valor do 11º dígito da verificação
		posicao = 11;
		soma = 0;
		for (i=0; i<=9; i++) {
			soma = soma + digito[i] * posicao;
			posicao = posicao - 1;
		}
		digito[10] = soma % 11;
		if (digito[10] < 2) {
			digito[10] = 0;
		} else {
			digito[10] = 11 - digito[10];
		}
		
		// verifica se os valores dos dígitos verificadores conferem
		dv = digito[9] * 10 + digito[10];
		if (dv != dv_informado) {
			contentErro.innerHTML = "CPF Inv&aacute;lido";
			contentErro.style.display = "block"
			if (foco==true) {
				gE(obj).focus()
				if(errOBJ == true) contentErro.value = texto;
			}
			submete = false
		}
	}
	
	
	if (obj.substring(0,9) == "recSelect") {
		if (gE("e"+obj)) {
			var contentErro = gE("e"+obj);
			contentErro.style.display = "none";
		} else if (gE(forme+"erro")) {
			var contentErro = gE(forme+"erro");
			contentErro.style.display = "none";
		} else {
			var contentErro = gE(obj);
			errOBJ = true
		}
		
		txt		= gE(obj).value
		txtConf = nome
		if (txt == txtConf) {
			contentErro.innerHTML = texto;
			contentErro.style.display = "block"
			if (foco==true) {
				gE(obj).focus()
				if(errOBJ == true) contentErro.value = texto;
			}
			submete = false
		}
	}

	if (obj.substring(0,7) == "recSelX") {
		if ("e"+obj.substring(0,7)) {
			var contentErro = gE("e"+obj.substring(0,7));
			contentErro.style.display = "none";
		} else if (gE(forme+"erro")) {
			var contentErro = gE(forme+"erro");
			contentErro.style.display = "none";
		} else {
			var contentErro = gE(obj);
			errOBJ = true
		}
		
		txt		= gE(obj).value
		txtConf = nome
		if (txt == txtConf) {
			contentErro.innerHTML = texto;
			contentErro.style.display = "block"
			if (foco==true) {
				gE(obj).focus()
				if(errOBJ == true) contentErro.value = texto;
			}
			submete = false
		}
	}
	
	
	
	if (obj.substring(0,6) == "recDat") {
		
		if (gE("e"+obj.substring(0,6))) {
			var contentErro = gE("e"+obj.substring(0,6));
			contentErro.style.display = "none";
		} else if (gE(forme+"erro")) {
			var contentErro = gE(forme+"erro");
			contentErro.style.display = "none";
		} else {
			var contentErro = gE(obj.substring(0,6));
			errOBJ = true
		}

		if (obj.substring(0,7) == "recDatD") {
			//alert(valor)
			if (valor > 31 || valor == "") {
				contentErro.innerHTML = texto;
				contentErro.style.display = "block"
				if (foco==true) {
					gE(obj).focus()
					if(errOBJ == true) contentErro.value = texto;
				}
				submete = false
			}
		} 
		if (obj.substring(0,7) == "recDatM") {
			//alert(valor)
			if (valor > 12 || valor == "") {
				contentErro.innerHTML = texto;
				contentErro.style.display = "block"
				if (foco==true) {
					gE(obj).focus()
					if(errOBJ == true) contentErro.value = texto;
				}
				submete = false
			}
		}
		if (obj.substring(0,7) == "recDatA") {
			//alert(valor)
			if (valor < 1900 || valor == "") {
				contentErro.innerHTML = texto;
				contentErro.style.display = "block"
				if (foco==true) {
					gE(obj).focus()
					if(errOBJ == true) contentErro.value = texto;
				}
				submete = false
			}
		}
	} 
	
	
	
	
}
/* FUNÇÃO REGRAS DE VALIDACAO ------------------*/

/* LOOP Q APLICA AS VALIDACOES NOS OBJETOS DO FORMULARIO ------------------*/
arTests = []
function validaForms() {
	for(var i=0;i<document.forms.length;i++) {
		f = document.forms[i]
		//alert(f.id)
		tmF = f.length
		
		for (iF=0;iF<tmF;iF++) {
			strSchr = f[iF].id
			if (strSchr.substring(0,3) == "rec") {
					//alert("achei: " + f.id + " " + strSchr)
					vNome=gE(strSchr)
					addEvent(vNome,"keyup",valida)
					//addEvent(vNome,"blur",valida)
					arTests.push(strSchr)
			}
			if (strSchr.substring(0,6) == "recSel") {
					//alert("achei:" + strSchr)
					vNome=gE(strSchr)
					addEvent(vNome,"change",valida)
					arTests.push(strSchr)
			}
		}
	}
}
/* LOOP Q APLICA AS VALIDACOES NOS OBJETOS DO FORMULARIO ------------------*/

/* LIMPA FORMULARIO */
function limpaForm(formulario) {
	f = document[formulario]
	tmF = f.length
	
	for (iF=0;iF<tmF;iF++) {
		if (f[iF].type != "submit") f[iF].value = ""

	}
}

function limpa(campo) {
	gE(campo).value = ""
}
function limpaTitle(campo) {
	if (gE(campo).value == gE(campo).title) {
		gE(campo).value = ""
	}
}
function sujaTitle() {
	if (gE(campo).value == "") {
		gE(campo).value =gE(campo).title
	}
}

/* ONLOAD NAO OBSTRUTIVO  ------------------*/
function carrega(nomeFuncao) {
	if (window.attachEvent) {
		var r = window.attachEvent("onload", nomeFuncao);
		return r;
	} else if (window.addEventListener) {
		window.addEventListener("load", nomeFuncao, false);
	return true;
	} else {
		return false;
	}
}
carrega(validaForms) // APLICA A VALIDACAO EM TODOS OS FORMS DO SITE

/* ONLOAD NAO OBSTRUTIVO  ------------------*/





//FUNÇAO DE CPF CNPJ ================================================

function validarcpfcnpj(campo) { 
var invalid, s; 
invalid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/; 
var s; 

// inicio de verificacao de cnpj ou cpf 
if (campo.value.length < campo.maxLength || campo.value.length > campo.maxLength) { 
	gE('erecCpf').innerHTML = "N&ordm; inconsistente!"; 
	//campo.focus(); 
	return false; 
} 
s = limpa_string(campo.value); 


// checa se é cpf 
if (s.length == 11) { 
if (valida_CPF(campo.value) == false ) { 
gE('erecCpf').innerHTML = "O CPF n&atilde;o &eacute; v&aacute;lido!";
//alert("O CPF não é válido !"); 
//campo.focus(); 
return false; } 
} 

// checa se é cgc 
else if (s.length == 14) { 
if (valida_CGC(campo.value) == false ) { 
gE('erecCpf').innerHTML = "O CNPJ n&atilde;o &eacute; v&aacute;lido!";
//alert("O CNPJ não é válido !"); 
//campo.focus(); 
return false; } 
} 

else { 
//alert("O CPF/CNPJ não é válido !"); 
//campo.focus(); 
return false; 
} 

// final da verificacao de cnpj ou cpf 
return true; 
} 
// fim da funcao validar() 


function limpa_string(S){ 
// Deixa so' os digitos no numero 
var Digitos = "0123456789"; 
var temp = ""; 
var digito = ""; 

for (var i=0; i<S.length; i++) { 
digito = S.charAt(i); 
if (Digitos.indexOf(digito)>=0) { 
temp=temp+digito } 
} //for 

return temp 
} 
// fim da funcao 


function valida_CPF(s) { 
var i; 
s = limpa_string(s); 
var c = s.substr(0,9); 
var dv = s.substr(9,2); 
var d1 = 0; 
for (i = 0; i < 9; i++) 
{ 
d1 += c.charAt(i)*(10-i); 
} 
if (d1 == 0) return false; 
d1 = 11 - (d1 % 11); 
if (d1 > 9) d1 = 0; 
if (dv.charAt(0) != d1) 
{ 
return false; 
} 

d1 *= 2; 
for (i = 0; i < 9; i++) 
{ 
d1 += c.charAt(i)*(11-i); 
} 
d1 = 11 - (d1 % 11); 
if (d1 > 9) d1 = 0; 
if (dv.charAt(1) != d1) 
{ 
return false; 
} 
return true; 
} 

function valida_CGC(s) 
{ 
var i; 
s = limpa_string(s); 
var c = s.substr(0,12); 
var dv = s.substr(12,2); 
var d1 = 0; 
for (i = 0; i < 12; i++) 
{ 
d1 += c.charAt(11-i)*(2+(i % 8)); 
} 
if (d1 == 0) return false; 
d1 = 11 - (d1 % 11); 
if (d1 > 9) d1 = 0; 
if (dv.charAt(0) != d1) 
{ 
return false; 
} 

d1 *= 2; 
for (i = 0; i < 12; i++) 
{ 
d1 += c.charAt(11-i)*(2+((i+1) % 8)); 
} 
d1 = 11 - (d1 % 11); 
if (d1 > 9) d1 = 0; 
if (dv.charAt(1) != d1) 
{ 
return false; 
} 
return true; 
} 
















