
//---------------------------
function validaform(esteNome) {
	var campo = "";
	var i = 0;
	var valido = 1;
	var style_0 = "solid 1px red";
	var style_1 = "solid 1px #0099CC";
	document.principal.nomeSubmit.value = esteNome;
	if (esteNome == "incluir" || esteNome == "alterar" || esteNome == "excluir") {
		for (i=0; i<=campoReq.length-1; i++) {
			campo = eval("document.principal."+campoReq[i]);
			switch (tipoValida[i]) {
				case "1":
						(campo.value == '') ? valido=0 : valido=1;
				break;

				case "2":
						(validaData(campo.value)) ? valido=1 : valido=0;
				break;

				case "3":
						(validaEmail(campo.value)) ? valido=1 : valido=0;
				break;

				case "4":
						if (!campo.disabled)
							(validaCPF(campo.value)) ? valido=1 : valido=0;
						else
							valido=1;
				break;

				case "5":
						if (!campo.disabled)
							(validaCNPJ(campo.value)) ? valido=1 : valido=0;
						else
							valido=1;
				break;

				case "6":
						(validaPis(campo.value)) ? valido=1 : valido=0;
				break;
			}
			if (!valido) {
					campo.style.border = style_0;
					document.principal.mensagem.value = "Formulário indevidamente preenchido.\n"+document.principal.mensagem.value;
					break;
			}
			else {
					campo.style.border = style_1;
			}
		}
	}
	if (esteNome == "excluir" && valido) {
		if (!confirm("Deseja Realmente Excluir?")) {
			valido = 0;
		}
	}
	if (valido) {
		document.principal.submit();
	}
}

//---------------------------
function mudaTipoValida() {
	for (i=0; i<document.principal.frmTipoPessoa.length; i++) {
		if (document.principal.frmTipoPessoa[i].selected) {
			if (document.principal.frmTipoPessoa[i].value == "j") {
				document.principal.frmCNPJCPF1.disabled = false;
				document.principal.frmCNPJCPF2.disabled = true;
				document.principal.frmCNPJCPF2.value = "";
			}
			else if (document.principal.frmTipoPessoa[i].value == "f") {
				document.principal.frmCNPJCPF1.disabled = true;
				document.principal.frmCNPJCPF2.disabled = false;
				document.principal.frmCNPJCPF1.value = "";
			}
			else {
				document.principal.frmCNPJCPF1.disabled = true;
				document.principal.frmCNPJCPF2.disabled = true;
				document.principal.frmCNPJCPF2.value = "";
				document.principal.frmCNPJCPF1.value = "";
			}
		}
	}
}
//---------------------------
function trocaVirgula(str) {
	return(str.replace(",","."));
}
//---------------------------
function validaPis(txtPis) {
/*
	Função usada para validar o PIS/PASEP
*/
	var MSG_FGTS_001 = "Número PIS/PASEP inválido.";
	if (txtPis == "") {
		alert(MSG_FGTS_001);
		return(false);
	}
	if (parseInt(txtPis) == 0) {
		alert(MSG_FGTS_001);
		return(false);
	}
	if (txtPis.length != 11) {
		alert(MSG_FGTS_001);
		return(false);
	}
	if(fTiraTracoPontoBarra(txtPis) != fTiraNaoNumericos(txtPis)) {
		alert(MSG_FGTS_001);
		return(false);
	}
	var sString = fTiraNaoNumericos(txtPis);
	var sAux = sString.substring(0, sString.length-1);
	var sDigito = sString.substring(sString.length-1, sString.length);
	if(sCalculaDigitoMod11(sAux, 1, 2) != sDigito) {
		alert(MSG_FGTS_001);
		return(false);
	}
	return(true);
}
//---------------------------
/*
	Função usada para tirar PONTOS, TRAÇOS e BARRAS de uma string
*/
function fTiraTracoPontoBarra(sNum) {
	var sAux = "";
	for (i=0; i<sNum.length; i++) {
		if (sNum.charAt(i)!='.' && sNum.charAt(i)!='-' && sNum.charAt(i) != '/') {
			sAux = sAux + sNum.charAt(i);
		}
	}
	return(sAux);
}
//---------------------------
/*
	Função usada para tirar caracteres não numéricos da string passada como parâmetro
*/
function fTiraNaoNumericos(sStr) {
	var sAux = "";
	for (i=0; i<sStr.length; i++) {
		if (sStr.charAt(i)>='0' && sStr.charAt(i)<='9') {
			sAux = sAux + sStr.charAt(i);
		}
	}
	return(sAux);
}
//---------------------------
/*
	Cálculo MÓDULO11
*/
function sCalculaDigitoMod11(sValor, iDigSaida, sTipoValidacao) {
	if (sTipoValidacao == 1) iCod = 12;
	if (sTipoValidacao == 2) iCod = 9;
	if (sTipoValidacao == 3) iCod = 10;
	for (t=1; t<=iDigSaida; t++) {
		soma = 0; mult = 2;
		for (j=sValor.length; j>0; j--) {
			soma = soma + (mult * parseInt(sValor.substring(j, j-1), 10));
			mult++;
			if (mult > iCod) mult = 2;
		}
		soma = (soma * 10) % 11;
		(soma == 10) ? sValor = sValor + "0" : sValor = sValor + soma;
	}
	return(sValor.substring(sValor.length-iDigSaida, sValor.length));
}
//---------------------------
/*
	Função para validar número de CNPJ
*/
function validaCNPJ(numero) {
	var soma = resultado1 = resultado2 = 0;
	numero = numero.replace("-", "");
	soma = 5 * parseInt(numero.substr(0,1)) + 4 * parseInt(numero.substr(1,1)) + 3 * parseInt(numero.substr(2,1)) + 2 * parseInt(numero.substr(3,1)) + 9 * parseInt(numero.substr(4,1)) + 8 * parseInt(numero.substr(5,1)) + 7 * parseInt(numero.substr(6,1)) + 6 * parseInt(numero.substr(7,1)) + 5 * parseInt(numero.substr(8,1)) + 4 * parseInt(numero.substr(9,1))+ 3 * parseInt(numero.substr(10,1))+ 2 * parseInt(numero.substr(11,1));
	soma = soma - (11 * parseInt(soma / 11));
	(soma == 0 || soma == 1) ?	resultado1 = 0 : resultado1 = 11 - soma;
	if (resultado1 == parseInt(numero.substr(12,1))) {
		soma = parseInt(numero.substr(0,1)) * 6 + parseInt(numero.substr(1,1)) * 5 + parseInt(numero.substr(2,1)) * 4 + parseInt(numero.substr(3,1)) * 3 + parseInt(numero.substr(4,1)) * 2 + parseInt(numero.substr(5,1)) * 9 + parseInt(numero.substr(6,1)) * 8 + parseInt(numero.substr(7,1)) * 7 + parseInt(numero.substr(8,1)) * 6 + parseInt(numero.substr(9,1)) * 5 + parseInt(numero.substr(10,1)) * 4 + parseInt(numero.substr(11,1)) * 3 + parseInt(numero.substr(12,1)) * 2;
		soma = soma - (11 * parseInt(soma / 11));
		(soma == 0 || soma == 1) ? resultado2 = 0 : resultado2 = 11 - soma;
		if (resultado2 == parseInt(numero.substr(13,1))) {
			return(1);
		}
		else {
			alert("CNPJ Inválido");
			return(0);
		}
	}
	else  {
		alert("CNPJ Inválido");
		return(0);
	}
}
//---------------------------
/*
	Função de validação de CPF
*/
function validaCPF(numero) {
	var soma = resultado1 = resultado2 = 0;
	numero = numero.replace("-", "");
	soma = 10 * parseInt(numero.substr(0,1)) + 9 * parseInt(numero.substr(1,1)) + 8 * parseInt(numero.substr(2,1)) + 7 * parseInt(numero.substr(3,1)) + 6 * parseInt(numero.substr(4,1)) + 5 * parseInt(numero.substr(5,1)) + 4 * parseInt(numero.substr(6,1)) + 3 * parseInt(numero.substr(7,1)) + 2 * parseInt(numero.substr(8,1));
	soma = soma - (11 * parseInt(soma / 11));
		(soma == 0 || soma == 1) ? resultado1 = 0 : resultado1 = 11 - soma;
	if (resultado1 == parseInt(numero.substr(9,1))) {
		soma = parseInt(numero.substr(0,1)) * 11 + parseInt(numero.substr(1,1)) * 10 + parseInt(numero.substr(2,1)) * 9 + parseInt(numero.substr(3,1)) * 8 + parseInt(numero.substr(4,1)) * 7 + parseInt(numero.substr(5,1)) * 6 + parseInt(numero.substr(6,1)) * 5 + parseInt(numero.substr(7,1)) * 4 + parseInt(numero.substr(8,1)) * 3 + parseInt(numero.substr(9,1)) * 2;
		soma = soma -(11 * parseInt(soma / 11));
		(soma == 0 || soma == 1) ? resultado2 = 0 : resultado2 = 11 - soma;
		if (resultado2 == parseInt(numero.substr(10,1))) {
			return(1);
		}
		else {
			alert("CPF Inválido");
			return(0);
		}
	}
	else {
		alert("CPF Inválido");
		return(0);
	}
}
//---------------------------
/*
	Função para validação de data
*/
function validaData(Data) {
	if (Data.length == 10) {
		if (Data.charAt(2)=="/" && Data.charAt(5)=="/") {
			var sDia = Data.substring(0, 2);
			var sMes = Data.substring(3, 5);
			var sAno = Data.substring(6, 10);
			if (IsNumber(sDia) && IsNumber(sMes) && IsNumber(sAno)) {
				if (sDia>0 && sDia<32 && sMes>0 && sMes<13) {
					if (AnoBissexto(sAno)) {
						if (sMes == "02") {
							if (sDia > 29) return(false); else return(true);
						}
						else if (sMes == "04" || sMes == "06" || sMes == "09" || sMes == "11") {
							if (sDia > 30) return(false); else return(true);
						}
						else {
							return(true);
						}
					}
					else {
						if (sMes == "02") {
							if (sDia > 28) return(false); else return(true);
						}
						else if (sMes == "04" || sMes == "06" || sMes == "09" || sMes == "11") {
							if (sDia > 30) return(false); else return(true);
						}
						else {
							return(true);
						}
					}
				}
				else {
					return(false);
				}
			}
			else {
				return(false);
			}
		}
	}
}
//---------------------------
/*
	Função para verificação de ano bissexto
*/
function AnoBissexto(Ano) {
	if (Ano.substring(Ano.length-2,Ano.length) == "00") {
		if (Ano.substring(0,Ano.length-2) % 4 == 0) return(true); else return(false);
	}
	else {
		if (Ano % 4 == 0) return(true); else return(false);
	}
}
//---------------------------
/*
	Função para verificar se uma string contém somente números
*/
function IsNumber(Numero) {
   var iIndice;
   for (iIndice=0; iIndice<Numero.length; iIndice++) {
      if (Numero.charAt(iIndice) < "0" || Numero.charAt(iIndice) > "9") {
	      return(false);
      }
   }
   return(true);
}
//---------------------------
/*
	Função para arredondamento de números
*/
function javaRound(numero, decimais) {
	var factor = 10;
	var temp = 0.00;
	if (numero<0)
		marca = "-";
	else
		marca = "+";
	for (i=1 ; i<=decimais-1; i++) {
		factor = factor * factor;
	}
	temp = eval("parseFloat(numero)* factor "+marca+" 0.5;");
	return(parseInt(temp)/factor);
}
//---------------------------
/*
	Função para retirar acentos de uma string
*/
function tiraAcentos(texto) {
	var resultado = "", letra = "", cont = 0;
	for (cont=0; cont<texto.length; cont++) {
		letra = texto.substr(cont, 1);
		if (letra=="á" || letra=="à" || letra=="ã" || letra=="â") letra = "a";
		if (letra=="Á" || letra=="À" || letra=="Ã" || letra=="Â") letra = "A";
		if (letra=="é" || letra=="è" || letra=="ê") letra = "e";
		if (letra=="É" || letra=="È" || letra=="Ê") letra = "E";
		if (letra=="í" || letra=="ì" || letra=="î") letra = "i";
		if (letra=="Í" || letra=="Ì" || letra=="Î") letra = "I";
		if (letra=="ó" || letra=="ò" || letra=="õ" || letra=="ô") letra = "o";
		if (letra=="Ó" || letra=="Ò" || letra=="Õ" || letra=="Ô") letra = "O";
		if (letra=="ú" || letra=="ù" || letra=="û") letra = "u";
		if (letra=="Ú" || letra=="Ù" || letra=="Û") letra = "U";
		if (letra=="ç") letra = "c";
		if (letra=="Ç") letra = "C";
		resultado = resultado + letra;
	}
	return(resultado);
}
//---------------------------
/*
	Função para formatar valores com R$ e %
*/
function frmtValores(str, tipo) {
	var pos = 0;
	var cont = 0;
	str = javaRound(str, 2);
	str = String(str);
	str = str.replace(",",".");
	str = str.replace("R$ ","");
	str = str.replace(" %","");
	if ((str == '') || (isNaN(str))) str = '0';
	for (i=0; i<=str.length; i++) {
		if (str.charAt(i) == '.') {
			pos = i;
		}
	}
	cont = (str.length - pos) - 1;
	if (!pos) {
		str = str + ".00";
	}
	else {
		for (i=0; i<(2-cont); i++) {
			str += "0";
		}
	}
	str = str.replace(".",",");
	switch (tipo) {
		case 1:
			return(str);
		break;

		case 2:
			str = 'R$ '+str;
		break;

		case 3:
			str = str+' %';
		break;

		case 4:
			str = str.replace(",",".");
		break;
	}
	return(str);
}
//---------------------------
/*
	Função para colocar a primeira letra das palavras de uma string em maiúsculo
*/
function varInicial(texto) {
	var palavra = "";
	var posini = 0;
	var posfim = 0;
	var resultado = "";
	var resto = texto + " ";
	texto = resto;
	while (resto.search(" ") !=- 1) {
		posfim = resto.search(" ");
		palavra = resto.substr(0, posfim);
		posini = posini + posfim + 1;
		resto = texto.substr(posini,(parseInt(texto.length)-posini)+1);
		(palavra == "e" || palavra == "de" || palavra == "da" || palavra == "das" || palavra == "do" || palavra == "dos") ? palavra.toLowerCase(palavra) : (palavra.toLowerCase() == "ii" || palavra.toLowerCase() == "iii" || palavra.toLowerCase() == "iv" || palavra.toLowerCase() == "vi") ? palavra = palavra.toUpperCase() : palavra = palavra.substr(0,1).toUpperCase() + palavra.substr(1,parseInt(texto.length)-1).toLowerCase();
		resultado = resultado + palavra + " ";
	}
	return(resultado.substr(0,parseInt(resultado.length)-1));
}
//---------------------------
/*
	Função de validação de email
*/
function validaEmail(campo) {
	((campo.search(/\S+@+\S+\.\S+/) == -1) || (campo.value == "")) ? ret = false : ret = true;
	return(ret);
}
//---------------------------
/*
	Função para retirar os caracteres não ASCII de uma string, espaços em branco duplicados, e espaços em branco no final
*/
function tiraNaoASCII(texto) {
	var chars = new Array("[","\\","/","]","[",",",".",
						  ";","@","ª","º","}","°","?",
						  "_","-","=","§","£","^","~",
						  "´","`","!","+","{",":","*",
						  "?","#","$","%","¨","&","*",
						  "(",")","'","<",">","|","]","\"");
	var retorno = "";
	var grava = "";
	for (i=0; i<texto.length; i++) {
		var controle = 1;
		for (k=0; k<chars.length; k++) {
			//if (!(texto.charAt(i).match(/[\\/\]\[,.;@ªº\}\°?_\-\=§\£^~´`!\+\{:*?"#$%¨&*\(\)'<>|]/))) {
			if (texto.charAt(i) == chars[k]) {
				controle = 0;
			}
		}
		if (controle) {
			j=i-1;
			(texto.charAt(i) == " " && texto.charAt(j) == " ") ? grava = "" : grava = texto.charAt(i);
			if ((i == texto.length) && (grava == " ") && (texto.charAt(j) == " ")) {
				grava = "";
			}
			retorno += grava;
		}
	}
	if (retorno.substr(retorno.length-1, retorno.length) == " ") {
		retorno = retorno.substr(0, retorno.length-1);
	}
	return(retorno);
}
//---------------------------
/*
	Função para formatação de data
*/
function varAcertaData(data) {
	if (data == '') return(data);
	dia = data.substr(0, 2);
	(data.substr(2, 1) == "/") ? ini=3 : ini=2;
	mes = data.substr(ini, 2);
	(data.substr(ini+2, 1) == "/") ? ini=6 : ini=4;
	ano = data.substr(ini, 4);
	if (ano.length < 4) ano = "20" + ano;
	data = dia + "/" + mes + "/" + ano;
	return(data);
}
//---------------------------
/*
	Função usada para dar select em checkboxes
*/
function checaCmps(este) {
	var nome_campo = este.name;
	var nome_form  = este.form.name;
	var tmp		   = eval("document."+nome_form+"."+nome_campo);
	var checados   = tmp[0].checked;
	for (i=0; i<=tmp.length-1; i++) {
		if (checados) {
			if (tmp[i].checked == false) {
				tmp[i].checked = true;
			}
		}
		else {
			if (tmp[i].checked == true) {
				tmp[i].checked = false;
			}
		}
	}
}
//---------------------------
/*
	Função usada para os formulários de backup
*/
function guardaDados(este) {
	var nome_campo = este.name;
	var nome_form  = este.form.name;
	var tmp		   = eval("document."+nome_form+"."+nome_campo);
	var tmp2	   = eval("document."+nome_form+"."+nome_campo+"B");
	tmp2.value = "";
	for (i=1; i<=tmp.length-1; i++) {
		if (tmp[i].checked == true) {
			tmp2.value += tmp[i].value+"|";
		}
	}
	tmp2.value = tmp2.value.substr(0, tmp2.value.length-1);
}
//---------------------------
/*
	Check/Uncheck em todos os checkboxes de um formulário
*/
function selectCheckBoxes(este) {
	var nome_form = este.form.name;
	var nome_elem = este.name;
	var tmp_nroel = eval("document."+nome_form+".elements.length");
	var tmp = eval("document."+nome_form+"."+nome_elem);
	var tmp2 = eval("document."+nome_form);
	var checar = tmp.checked;
	for (i=0; i<=tmp_nroel-1; i++) {
		if (tmp2.elements[i].type == "checkbox") {
			if (checar) {
				if (tmp2.elements[i].checked == false) {
					tmp2.elements[i].checked = true;
				}
			}
			else {
				if (tmp2.elements[i].checked == true) {
					tmp2.elements[i].checked = false;
				}
			}
		}
	}
}
//---------------------------
function vaiMenu(este) {
	var nomeCampo = este.name;
	var nomeForm  = este.form.name;
	for (i=0; i<=(eval("document."+nomeForm+"."+nomeCampo+".length")-1); i++) {
		if ((eval("document."+nomeForm+"."+nomeCampo+"["+i+"].selected")) && (eval("document."+nomeForm+"."+nomeCampo+"["+i+"].value") != "")) {
			self.location.href = (eval("document."+nomeForm+"."+nomeCampo+"["+i+"].value"));
		}
	}
}
//---------------------------
function visibilidade(div,acao) { // visibilidade
	var get = document.getElementById;
	if (get) {
		(acao == 'visible') ? document.getElementById(div).style.visibility = 'visible' : document.getElementById(div).style.visibility = 'hidden';
	}
	else {
		if (document.layers) {
			(acao == 'visible') ? document.layers[div].visibility = 'visible' : document.layers[div].visibility = 'hidden';
		}
		else if (document.all) {
			(acao == 'visible') ? document.all[div].style.visibility = 'visible' : document.all[div].style.visibility = 'hidden';
		}
		else {
			(acao == 'visible') ? div.style.visibility = 'visible' : div.style.visibility = 'hidden';
		}
	}
}
//---------------------------
function fundo_e_cor(div,fundo,cor) { // cor da fonte e background
	var get = document.getElementById;
	if (get) {
		document.getElementById(div).style.background = fundo;
		document.getElementById(div).style.color = cor;
	}
	else {
		if (document.layers) {
			document.layers[div].background = fundo;
			document.layers[div].color = cor;
		}
		else if (document.all) {
			document.all[div].style.background = fundo;
			document.all[div].style.color = cor;
		}
		else {
			div.style.background = fundo;
			div.style.color = cor;
		}
	}
}
//---------------------------
function posicao(div,x,y) { // posicionamento
	var get = document.getElementById;
	if (get) {
		document.getElementById(div).style.position = 'absolute';
		if (y!='') document.getElementById(div).style.top = y;
		if (x!='') document.getElementById(div).style.left = x;
	}
	else {
		if (document.layers) {
			document.layers[div].position = 'absolute';
			if (y!='') document.layers[div].top = y;
			if (x!='') document.layers[div].left = x;
		}
		else if (document.all) {
			document.all[div].style.position = 'absolute';
			if (y!='') document.all[div].style.top = y;
			if (x!='') document.all[div].style.left = x;
		}
		else {
			div.style.position = 'absolute';
			if (y!='') div.style.pixelTop = y;
			if (x!='') div.style.pixelLeft = x;
		}
	}
}
//---------------------------
function cria_divs(div,acao) {
	if (acao == 'cima') {
		(document.layers) ? document.write('<layer id="'+div+'">') : document.write('<div id="'+div+'">');
	}
	else if (acao == 'baixo') {
		(document.layers) ? document.write('</layer>') : document.write('</div>');
	}
	else {
		alert('ERRO NA PASSAGEM DE PARÂMETROS PARA A FUNÇÃO cria_divs()');
	}
}
//---------------------------
function move(div, topo) {
	var get = document.getElementById;
	var yy;
	if (get) {
		if (navigator.appName == "Microsoft Internet Explorer") {
			yy = document.body.scrollTop + 5;
			if (yy <= topo) {
				yy = topo;
			}
			if (navigator.appVersion.substring(0,1) >= "4") {
				document.getElementById(div).style.top = yy;
				document.getElementById(div).style.left = (screen.Width - 220);
			}
			else {
				document.div.style.top = yy;
			}
		}
		else {
			yy = pageYOffset + 5;
			if (yy <= topo) {
				yy = topo;
			}
			document.getElementById(div).style.top = yy;
			document.getElementById(div).style.left = (screen.Width - 220);
		}
	}
}
//---------------------------
function horas() {
	ct = new Date();
	h = "0" + ct.getHours();
	m = "0" + ct.getMinutes();
	s = "0" + ct.getSeconds();
	h = h.substring(h.length-2,h.length+1);
	m = m.substring(m.length-2,m.length+1);
	s = s.substring(s.length-2,s.length+1);
	cl = h+":"+m+":"+s;
	document.getElementById('relogio').innerHTML = cl+"&nbsp;";
	timer = setTimeout("horas()",100);
}
//---------------------------
function cria_data() {
	var dias_semana = new Array();
		dias_semana[0] = "Domingo";
		dias_semana[1] = "Segunda-feira";
		dias_semana[2] = "Terça-feira";
		dias_semana[3] = "Quarta-feira";
		dias_semana[4] = "Quinta-feira";
		dias_semana[5] = "Sexta-feira";
		dias_semana[6] = "Sábado";
	var mes_ano = new Array();
		mes_ano[0]  = "Janeiro";
		mes_ano[1]  = "Fevereiro";
		mes_ano[2]  = "Março";
		mes_ano[3]  = "Abril";
		mes_ano[4]  = "Maio";
		mes_ano[5]  = "Junho";
		mes_ano[6]  = "Julho";
		mes_ano[7]  = "Agosto";
		mes_ano[8]  = "Setembro";
		mes_ano[9]  = "Outubro";
		mes_ano[10] = "Novembro";
		mes_ano[11] = "Dezembro";
	var data = new Date();
	var hora = data.getHours();
	var minu = data.getMinutes();
	var segu = data.getSeconds();
	var sema = data.getDay();
	var mano = data.getMonth();
	var dmes = data.getDate();
	var ano_ = data.getYear();
	if (navigator.appName == "Opera" || navigator.appName == "undefined" || navigator.appName == "Netscape") ano_+=1900;
	return(dias_semana[sema]+", "+dmes+" de "+mes_ano[mano]+" de "+ano_);
}
//---------------------------
function updCheck() {
	/*
		SQLx -> x = numero
		numero total = contaCheckboxes
	*/
	var tmp = "";
	for (i=0; i<=contaCheckboxes; i++) {
		tmp = eval('document.principal.SQL'+i);
		if (document.principal.checaTodos.checked) {
			if (eval("document.principal.SQL"+i+".checked") == false) {
				tmp.checked = true;
			}
		}
		else {
			if (eval("document.principal.SQL"+i+".checked") == true) {
				tmp.checked = false;
			}
		}
	}
}
//---------------------------
/*
	Parametros
		-> destino = nome do arquivo
		-> texto = texto para gravar
*/
function GravaArqLocal(destino, texto, tipo) {
	var objArq;
	var arquivo;
	objArq = new ActiveXObject("Scripting.FileSystemObject");
	switch (tipo)
	{
	case 0: // append
		arquivo = objArq.OpenTextFile(destino, 8, 0)
	break;
	case 1: // grava em cima
		arquivo = objArq.CreateTextFile(destino, true)
	break;
	}
	arquivo.Write(texto);
	arquivo.close();
}
//---------------------------
function cryptV(string) {
	var num = 0;
	var tmp = 0;
	var saida = '';
	var chave = "1925348671953285713";
	var chars1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z','w','ç','0','1','2','3','4','5','6','7','8','9',' '];
	for (i=0; i<string.length; i++) {
		tmp = 0;
		for (j=0; j<chave.length; j++) {
			num = parseInt(chave.charAt(j));
			for (k=0; k<chars1.length; k++) {
				if (string.charAt(i).toLowerCase() == chars1[k]) {
					num = num*k;
				}
			}
			if (!num) num++;
			tmp += num;
		}
		saida += tmp;
	}
	return(saida);
}
//---------------------------
function le_cookie(Name) {
	var search = Name + "=";
	var returnvalue = "";
	if (document.cookie.length > 0) {
		offset = document.cookie.indexOf(search);
		if (offset != -1) {			offset += search.length;
			end = document.cookie.indexOf(";", offset);
			if (end == -1) {end = document.cookie.length;}
			returnvalue = unescape(document.cookie.substring(offset, end));}}
	return(returnvalue);
}
function grava_cookie(name, value) {var argv = grava_cookie.arguments;
	var argc = grava_cookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 4) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain));
}
function apaga_cookie(name) {exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = le_ookie(name);
	document.cookie = name + "=" + cval +"; expires=" + exp.toGMTString();
}
function varLayer(n, d) {
var p,i,x;
for(i=0;!x&&document.layers&&i<document.layers.length;i++)
	x=varLayer(n,document.layers[i].document);
if(!x && document.getElementById) x=document.getElementById(n);
return x;
}

// funções para tela de venda
function vndCalculaItem() {
	document.lista.frmQuantidade.value = parseFloat(((document.lista.frmQuantidade.value == '' || isNaN(document.lista.frmQuantidade.value.replace(",","."))) ? '1' : (document.lista.frmQuantidade.value)).replace(",","."));
	document.lista.frmDesc.value = frmtValores(parseFloat(((document.lista.frmDesc.value == '') ? '0.00' : (document.lista.frmDesc.value)).replace(",",".")),4);
	document.lista.frmAcresc.value = frmtValores(parseFloat(((document.lista.frmAcresc.value == '') ? '0.00' : (document.lista.frmAcresc.value)).replace(",",".")),4);
	document.lista.frmTotal.value = frmtValores(((parseFloat(document.lista.frmValorVenda.value) * parseFloat(document.lista.frmQuantidade.value)) - parseFloat(document.lista.frmDesc.value) + parseFloat(document.lista.frmAcresc.value)),4);
	document.lista.frmIcms.value = ((parseFloat(document.lista.frmQuantidade.value)*parseFloat(document.lista.frmValorVenda.value)*parseFloat(document.lista.frmIcmsProduto.value))/100);
}

function vndCalculaTotal() {
	parent.document.geral.frmSubTotal.value = frmtValores(parseFloat(((parent.document.geral.frmSubTotal.value == '') ? '0.00' : (parent.document.geral.frmSubTotal.value)).replace(",",".")),4);
	parent.document.geral.frmValorAcreDesc.value = frmtValores(parseFloat(((parent.document.geral.frmValorAcreDesc.value == '') ? '0.00' : (parent.document.geral.frmValorAcreDesc.value)).replace(",",".")),4);
	switch (parent.document.geral.frmTipoAcreDesc.value){
		case "a":
			varValorAcreDesc = parent.document.geral.frmValorAcreDesc.value;
		break;
		case "d":
			varValorAcreDesc = (Math.abs(parent.document.geral.frmValorAcreDesc.value))*-1;
		break;
		default:
			parent.document.geral.frmValorAcreDesc.value="0.00";
			varValorAcreDesc=0;
		break;
	}
	parent.document.geral.frmTotalVenda.value = frmtValores(parseFloat(parent.document.geral.frmSubTotal.value)+parseFloat(varValorAcreDesc),4);
	parent.document.geral.frmTotalPago.value =frmtValores(parseFloat(((parent.document.geral.frmTotalPago.value == '') ? "0.00" : (parent.document.geral.frmTotalPago.value)).replace(",",".")),4);
	parent.document.geral.frmTroco.value = frmtValores(parseFloat(parseFloat(parent.document.geral.frmTotalPago.value) - parseFloat(parent.document.geral.frmTotalVenda.value)),4);
}

function selectFuncionario(novo, marcado) {
	var varAchou=0;
	for (i=0; i<document.geral.frmCodFuncionario.length; i++) {
		if (document.geral.frmCodFuncionario[i].value == document.geral.frmCodFuncionarioNum.value){
			document.geral.frmCodFuncionario[i].selected = true;
			varAchou=1;
		}
		else document.geral.frmCodFuncionario[i].selected = false;
	}
	if (varAchou==0){
		document.geral.frmCodFuncionario[marcado].selected = true;
		parent.document.geral.varMensagem.value="Operador "+novo+" não existente.\n"+parent.document.geral.varMensagem.value;
		document.geral.frmCodFuncionarioNum.value="";
	}
	else
		document.geral.frmCodFuncionarioNum.value="";
}
function selectProduto(linha, valores,campoorigem,campodestino, campovalor) {
	var origem = eval("document.principal.frmSub" + linha + campoorigem);
	var destino = eval("document.principal.frmSub" + linha + campodestino);
	var valor = eval("document.principal.frmSub" + linha + campovalor);
	for (i=0; i<destino.length; i++) {
		if (destino[i].value == origem.value){
			destino[i].selected = true;
			if (i>0)
				valor.value =frmtValores(valores.substr((i*10)-10,10),2);
			else
				valor.value ="";
		}
		else {
			destino[i].selected = false;
			valor.value ="";
		}
	}
}

/*function selectProdutoCompra(linha, valores) {
	var origem = eval("document.principal.frmSub" + linha + "8");
	var destino = eval("document.principal.frmSub" + linha + "2");
	var valor = eval("document.principal.frmSub" + linha + "4");
	for (i=0; i<destino.length; i++) {
		if (destino[i].value == origem.value){
			destino[i].selected = true;
			if (i>0)
				valor.value ="R$ " + valores.substr((i*10)-10,10);
			else
				valor.value ="";
		}
		else
			destino[i].selected = false;
	}
}*/

function Tecla(e)
{
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
		var tecla = e.which;
		if (tecla > 47 && tecla < 58) // numeros de 0 a 9
			return true;
		else
			{
				if (tecla != 8) // backspace
					event.keyCode = 0;
					//return false;
				else
					return true;
			}
}

function Tecla2(e)
{
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
		var tecla = e.which;
		if ((tecla > 47 && tecla < 58) || tecla == 47 ) // numeros de 0 a 9
			return true;
		else
			{
				if (tecla != 8) // backspace
					event.keyCode = 0;
					//return false;
				else
					return true;
			}
}

// teste de CNPJ
function validaCNPJ(numero) {
	var soma = resultado1 = resultado2 = 0;
	numero = numero.replace("-", "");
	soma = 5 * parseInt(numero.substr(0,1)) + 4 * parseInt(numero.substr(1,1)) + 3 * parseInt(numero.substr(2,1)) + 2 * parseInt(numero.substr(3,1)) + 9 * parseInt(numero.substr(4,1)) + 8 * parseInt(numero.substr(5,1)) + 7 * parseInt(numero.substr(6,1)) + 6 * parseInt(numero.substr(7,1)) + 5 * parseInt(numero.substr(8,1)) + 4 * parseInt(numero.substr(9,1))+ 3 * parseInt(numero.substr(10,1))+ 2 * parseInt(numero.substr(11,1));
	soma = soma - (11 * parseInt(soma / 11));
	(soma == 0 || soma == 1) ?	resultado1 = 0 : resultado1 = 11 - soma;
	if (resultado1 == parseInt(numero.substr(12,1))) {
		soma = parseInt(numero.substr(0,1)) * 6 + parseInt(numero.substr(1,1)) * 5 + parseInt(numero.substr(2,1)) * 4 + parseInt(numero.substr(3,1)) * 3 + parseInt(numero.substr(4,1)) * 2 + parseInt(numero.substr(5,1)) * 9 + parseInt(numero.substr(6,1)) * 8 + parseInt(numero.substr(7,1)) * 7 + parseInt(numero.substr(8,1)) * 6 + parseInt(numero.substr(9,1)) * 5 + parseInt(numero.substr(10,1)) * 4 + parseInt(numero.substr(11,1)) * 3 + parseInt(numero.substr(12,1)) * 2;
		soma = soma - (11 * parseInt(soma / 11));
		(soma == 0 || soma == 1) ? resultado2 = 0 : resultado2 = 11 - soma;
		if (resultado2 == parseInt(numero.substr(13,1))) { return (0); }
		else { return (1); }
	}
	else  { return (1); }
}

// teste de CPF
function validaCPF(numero) {
	var soma = resultado1 = resultado2 = 0;
	numero = numero.replace("-", "");
	soma = 10 * parseInt(numero.substr(0,1)) + 9 * parseInt(numero.substr(1,1)) + 8 * parseInt(numero.substr(2,1)) + 7 * parseInt(numero.substr(3,1)) + 6 * parseInt(numero.substr(4,1)) + 5 * parseInt(numero.substr(5,1)) + 4 * parseInt(numero.substr(6,1)) + 3 * parseInt(numero.substr(7,1)) + 2 * parseInt(numero.substr(8,1));
	soma = soma - (11 * parseInt(soma / 11));
		(soma == 0 || soma == 1) ? resultado1 = 0 : resultado1 = 11 - soma;
	if (resultado1 == parseInt(numero.substr(9,1))) {
		soma = parseInt(numero.substr(0,1)) * 11 + parseInt(numero.substr(1,1)) * 10 + parseInt(numero.substr(2,1)) * 9 + parseInt(numero.substr(3,1)) * 8 + parseInt(numero.substr(4,1)) * 7 + parseInt(numero.substr(5,1)) * 6 + parseInt(numero.substr(6,1)) * 5 + parseInt(numero.substr(7,1)) * 4 + parseInt(numero.substr(8,1)) * 3 + parseInt(numero.substr(9,1)) * 2;
		soma = soma -(11 * parseInt(soma / 11));
		(soma == 0 || soma == 1) ? resultado2 = 0 : resultado2 = 11 - soma;
		if (resultado2 == parseInt(numero.substr(10,1))) {return (0);}
		else {return (1);}
	}
	else {return (1);}
}

function isWhitespace(s)
{
    var whitespace = " \t\n\r";

    if (s.length == 0) {
        // empty field!
        return true;
    } else {
        // check for whitespace now!
        for (var z = 0; z < s.length; z++) {
            // Check that current character isn't whitespace.
            var c = s.charAt(z);
            if (whitespace.indexOf(c) == -1) return false;
        }
        return true;
    }
}

function isEmail(s)
{
    // email text field.
    var sLength = s.length;
    var denied_chars = new Array(" ", "\n", "\t", "\r", "%", "$", "#", "!", "~", "`", "^", "&", "*", "(", ")", "=", "+", "{", "}", "[", "]", ",", ";", ":", "'", "\"", "?", "<", ">", "/", "\\", "|");

    // look for @
    if (s.indexOf("@") == -1) return false;

    // look for more than one @ sign
    if (s.indexOf("@") != s.lastIndexOf("@")) return false;

    // look for any special character
    for (var z = 0; z < denied_chars.length; z++) {
        if (s.indexOf(denied_chars[z]) != -1) return false;
    }

    // look for .
    if (s.indexOf(".") == -1) return false;

    // no two dots alongside each other
    if (s.indexOf("..") != -1) return false;

    // the last character cannot be a .
    if ((s.charAt(sLength-1) == ".") || (s.charAt(sLength-1) == "_")) return false;

    return true;
}

function hasDeniedChars(s)
{
    var denied_chars = new Array(" ", "\n", "\t", "\r", "%", "$", "#", "!", "~", "`", "^", "&", "*", "(", ")", "=", "+", "{", "}", "[", "]", ",", ";", ":", "'", "\"", "?", "<", ">", "/", "\\", "|");

    for (var z = 0; z < denied_chars.length; z++) {
        if (s.indexOf(denied_chars[z]) != -1) return true;
        // checking for any non-ascii character
        if (s.charCodeAt(z) > 128) return true;
    }

    return false;
}


function soNumeros(s)
{
    var denied_chars = new Array(" ", "\n", "\t", "\r", "%", "$", "#", "!", "~", "`", "^", "&", "*", "(", ")", "=", "+", "{", "}", "[", "]", ",", ";", ":", "'", "\"", "?", "<", ">", "/", "\\", "|", "-");

    for (var z = 0; z < denied_chars.length; z++) {
        if (s.indexOf(denied_chars[z]) != -1) return true;
        // checking for any non-ascii character
        if (s.charCodeAt(z) > 128) { return true; }
    }
     return false;
}

function isNumberOnly(s)
{
    var check = parseFloat(s).toString();
    if ((s.length == check.length) && (check != "NaN")) {
        return true;
    } else { return false;}
}

function isValidPassword(s)
{
    // at least 12 characters on the password
    if (s.length < 12) {
        return false;
    }
    // see if there is at least four lowercase chars and four uppercase chars
    lower = 0;
    upper = 0;
    for (var z = 0; z < s.length; z++) {
        letter = s.charAt(z);
        if (letter == letter.toLowerCase()) {
            lower++;
        }
        if (letter == letter.toUpperCase()) {
            upper++;
        }
    }
    if ((lower < 4) || (upper < 4)) {
        return false;
    }
    // see if there is at least four numbers
    number = 0;
    for (var z = 0; z < s.length; z++) {
        if (parseFloat(s.charAt(z)).toString != "NaN") {
            number++;
        }
    }
    if (number < 4) {
        return false;
    }
    return true;
}

function checa_mural()
{
        checa=this.document.mural;
          if (isWhitespace(checa.de.value) || isWhitespace(checa.para.value) || isWhitespace(checa.mensagem.value)) 
          {
              alert("Simples.NET AVISO: O Mural não pode conter campos em branco ou dados inválidos. O envio foi cancelado. Por favor, digite novamente as informações de forma correta.");
	      checa.de.focus();
              return false;
	      //esse return false naum deixa enviar nada em php
          }

 	  checa.submit();
}

function checa_cadastro()
{
    checa=this.document.cadastro;

    if ( validaCNPJ(checa.cnpj.value)==1)
    {
       alert ("O CNPJ digitado é inválido! Digite novamente.");	      
       checa.cnpj.focus();
       return false;
    }

    checa.submit();
}

function checa_cadastro2()
{
    checa=this.document.cadastro;

    if ( validaCPF(checa.cpf.value)==1)
    {
       alert ("O CPF digitado é inválido! Digite novamente.");	      
       checa.cpf.focus();
       return false;
    }

    checa.submit();
}

function checa_boleto()
{
    aviso=0;
    checa=this.document.boleto;

    if ( validaCNPJ(checa.CNPJCPFSacado.value)==1 &&  validaCPF(checa.CNPJCPFSacado.value)==1)   aviso=1;
    
    if ( aviso==1) 
    {
       alert ("CNPJ ou CPF digitado é inválido! Verifique e digite novamente.");	      
       checa.CNPJCPFSacado.focus();
       return false;
    }

    checa.submit();
}

function checa_pedido()
{
    var aviso=0;
    
    checa=this.document.pedido;

        if (isWhitespace(checa.cnpj.value) || 
        isWhitespace(checa.responsavel.value) || 
        isWhitespace(checa.insce.value) || 
        isWhitespace(checa.razaosocial.value) || 
        isWhitespace(checa.endereco.value) || 
        isWhitespace(checa.bairro.value) || 
        isWhitespace(checa.uf.value) || 
        isWhitespace(checa.cidade.value) || 
        isWhitespace(checa.fone.value) ||
        isWhitespace(checa.representante.value))
    {
       alert ("Você deixou algum campo obrigatório em branco. Por favor, verifique.");	      
       checa.cnpj.focus();
       return false;
    }


  if ( validaCNPJ(checa.cnpj.value)==1 && validaCPF(checa.cnpj.value)==1)   aviso=1;
    
    if ( aviso==1) 
    {
       alert ("CNPJ ou CPF digitado é inválido! Verifique e digite novamente.");	      
       checa.cnpj.focus();
       return false;
    }

    checa.submit();
}

function calculapedido()
{
   dados=this.document.pedido;
   
   dados.valor1.value = dados.qprod1.value * dados.vunit1.value;
   dados.valor2.value = dados.qprod2.value * dados.vunit2.value;
   dados.valor3.value = dados.qprod3.value * dados.vunit3.value;
   dados.valor4.value = dados.qprod4.value * dados.vunit4.value;
   dados.valor5.value = dados.qprod5.value * dados.vunit5.value;

   dados.total.value = dados.valor1.value - (-dados.valor2.value) - (-dados.valor3.value) - (-dados.valor4.value) - (-dados.valor5.value);
}


//---------------------------
function formata(campo, tipo) {
	var nome_campo = campo.name;
	var valor_campo = campo.value;
	/*
		0  - retirar caracteres não ASCII e espaço
		1  - colcar as iniciais em maiusculo
		2  - tirar acentos das letras
		3  - formatar o campo com R$
		4  - formatar o campo com %
		5  - formatar o campo valor padrao brasileiro
		6  - formatar o campo padrao americano
		7  - formata data digitada
		9 - 0 + 1 + 2
		10 - 1 + 2
		11 - tira caracteres nao numericos
		12 - todos caracteres em maísculo + 0 + 2
	*/
	switch (tipo) {

		case 0:
			valor_campo = tiraNaoASCII(valor_campo);
			campo.value = valor_campo;
		break;

		case 1:
			valor_campo = varInicial(valor_campo);
			campo.value = valor_campo;
		break;

		case 2:
			valor_campo = tiraAcentos(valor_campo);
			campo.value = valor_campo;
		break;


		case 3:
			valor_campo = trocaVirgula(valor_campo);
			valor_campo = frmtValores(valor_campo, 2);
			campo.value = valor_campo;
		break;

		case 4:
			valor_campo = trocaVirgula(valor_campo);
			valor_campo = frmtValores(valor_campo, 3);
			campo.value = valor_campo;
		break;

		case 5:
			valor_campo = frmtValores(valor_campo, 1);
			campo.value = valor_campo;
		break;

		case 6:
			valor_campo = frmtValores(valor_campo, 4);
			campo.value = valor_campo;
		break;

		case 7:
			valor_campo = varAcertaData(valor_campo);
			campo.value = valor_campo;
		break;

		case 9:
			valor_campo = tiraAcentos(valor_campo);
			valor_campo = tiraNaoASCII(valor_campo);
			valor_campo = varInicial(valor_campo);
			campo.value = valor_campo;
		break;

		case 10:
			valor_campo = tiraAcentos(valor_campo);
			valor_campo = varInicial(valor_campo);
			campo.value = valor_campo;
		break;

		case 11:
			valor_campo = fTiraNaoNumericos(valor_campo);
			campo.value = valor_campo;
		break;
		case 12:
			valor_campo = tiraNaoASCII(valor_campo);
			valor_campo = tiraAcentos(valor_campo);
			valor_campo = valor_campo.toUpperCase();
			campo.value = valor_campo;
		break;
	}
}


function calculapedido2()
{
   dados=this.document.pedido;
  
    if(dados.qprod1.value!='' && dados.vunit1.value!='') dados.valor1.value = dados.qprod1.value * dados.vunit1.value;
    if(dados.qprod2.value!='' && dados.vunit2.value!='') dados.valor2.value = dados.qprod2.value * dados.vunit2.value;
    if(dados.qprod3.value!='' && dados.vunit3.value!='') dados.valor3.value = dados.qprod3.value * dados.vunit3.value;
    if(dados.qprod4.value!='' && dados.vunit4.value!='') dados.valor4.value = dados.qprod4.value * dados.vunit4.value;
    if(dados.qprod5.value!='' && dados.vunit5.value!='') dados.valor5.value = dados.qprod5.value * dados.vunit5.value;

   dados.total.value = dados.valor1.value - (-dados.valor2.value) - (-dados.valor3.value) - (-dados.valor4.value) - (-dados.valor5.value);

   if(dados.qprod1.value!='' && dados.vunit1.value!='') { formata(dados.vunit1,3);   formata(dados.valor1,3);}
   if(dados.qprod2.value!='' && dados.vunit2.value!='') { formata(dados.vunit2,3);   formata(dados.valor2,3);}
   if(dados.qprod3.value!='' && dados.vunit3.value!='') { formata(dados.vunit3,3);   formata(dados.valor3,3);}
   if(dados.qprod4.value!='' && dados.vunit4.value!='') { formata(dados.vunit4,3);   formata(dados.valor4,3);}
   if(dados.qprod5.value!='' && dados.vunit5.value!='') { formata(dados.vunit5,3);   formata(dados.valor5,3);}

   if(dados.total.value!='') { formata(dados.total,3) };
}

function limpaprodutos()
{
   dados=this.document.pedido;
   
   dados.valor1.value = "";
   dados.qprod1.value = "";
   dados.vunit1.value = "";
   dados.valor2.value = "";
   dados.qprod2.value = "";
   dados.vunit2.value = "";
   dados.valor3.value = "";
   dados.qprod3.value = "";
   dados.vunit3.value = "";
   dados.valor4.value = "";
   dados.qprod4.value = "";
   dados.vunit4.value = "";
   dados.valor5.value = "";
   dados.qprod5.value = "";
   dados.vunit5.value = "";
   dados.total.value  = "";
}

