function MM_jumpMenu(targ,selObj,restore){ //v3.0

  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");

  if (restore) selObj.selectedIndex=0;

}

function MM_findObj(n, d) { //v4.01

  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {

    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}

  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];

  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);

  if(!x && d.getElementById) x=d.getElementById(n); return x;

}



function MM_validateForm() { //v4.0

  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;

  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);

    if (val) { nm=val.name; if ((val=val.value)!="") {

      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');

        if (p<1 || p==(val.length-1)) errors+='- '+nm+' deve conter um endereço de e-mail.\n';

      } else if (test!='R') { num = parseFloat(val);

        if (isNaN(val)) errors+='- '+nm+' deve conter um número.\n';

        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');

          min=test.substring(8,p); max=test.substring(p+1);

          if (num<min || max<num) errors+='- '+nm+' deve conter um número entre '+min+' e '+max+'.\n';

    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' é necessário.\n'; }

  } if (errors) alert('Lista de erro(s):\n'+errors);

  document.MM_returnValue = (errors == '');

}

function validaCobranca() {

	if (document.getElementsByName("tipo_cobranca").item(0).value == "") {

		alert("Selecione o Tipo de Cobrança!");		

	}

	else if (document.getElementsByName("vencimento").item(0).value == "") {

		alert("Não deixe o campo Vencimento em branco!");				

	}

	else if (document.getElementsByName("referente").item(0).value == "") {

		alert("Não deixe o campo Referente em branco!");			

	}

	else if (document.getElementsByName("valor").item(0).value == "") {

		alert("Não deixe o campo Valor em branco!");		

	}

	else if (document.getElementsByName("valor").item(0).value.indexOf(",") != document.getElementsByName("valor").item(0).value.lastIndexOf(",") || document.getElementsByName("valor").item(0).value.indexOf(".") != document.getElementsByName("valor").item(0).value.lastIndexOf(".")) {

		alert("Coloque apenas uma vírgula (\",\") ou apenas um ponto (\".\") no número do campo Valor!");		

	}

	else if (document.getElementsByName("tipo_cobranca").item(0).value == "Nota de Débito" && document.getElementsByName("ptax").item(0).value == "") {

		alert("A taxa PTAX é requerida para Nota de Débito!");		

	}

	else if (document.getElementsByName("tipo_cobranca").item(0).value == "Nota de Débito" && (document.getElementsByName("ptax").item(0).value.indexOf(",") != document.getElementsByName("ptax").item(0).value.lastIndexOf(",") || document.getElementsByName("ptax").item(0).value.indexOf(".") != document.getElementsByName("ptax").item(0).value.lastIndexOf("."))) {

		alert("Coloque apenas uma vírgula (\",\") ou apenas um ponto (\".\") no número do campo PTAX!");		

	}

	else if (document.getElementsByName("destinatario").item(0).value == "") {

		alert("Selecione o Destinatário Final!");

	}	

	else {

		document.getElementsByName("form_aviso").item(0).submit()

	}

}

function verifica_associado() {

	campos = new Array ("nome_empresa",

						"razao_social",

						"cnpj",

						"data_associacao",

						"login",

						"senha",

						"confirma_senha",

						"endereco_empresa",

						"numero_end_empresa",

						"bairro_empresa",

						"cidade_empresa",

						"cep_empresa",

						"telefone_empresa",

						"nome_executivo",

						"email",

						"OK")

	

	nomes_campos = new Array ("Nome da Empresa",

						"Razão Social",

						"CNPJ",

						"Data de Associação",

						"Login",

						"Senha",

						"Confirmar Senha",

						"Endereço (Empresa)",

						"Número (Empresa)",

						"Bairro (Empresa)",

						"Cidade (Empresa)",

						"Cep (Empresa)",

						"Telefone (Empresa)",

						"Nome (Executivo)",

						"Email (Executivo)",

						"OK")

	

	for (i = 0; i < campos.length; i++) {

		esse = document.getElementById(campos[i])

		if (esse.id == "cnpj") {

			if (document.getElementById("tipo_associado").value == "Nacional" && esse.value == "") {

				alert("Preencha o campo CNPJ para associados nacionais")

				esse.focus()

				return false

			}

		}

		else if (esse.id == "OK") {

			if (esse.value == "0") {

				alert("Verifique a duplicidade de registros de associados")

				return false

			}

		}

		else if (esse.value == "") {

			alert("Preencha o campo " + nomes_campos[i])

			esse.focus()

			return false

		}

	}

	

	if (!valida_email()) {

		return false;

	}



	return true

}

function tel(esse, event){

	if (event.keyCode != 8 && event.keyCode != 37 && event.keyCode != 39 && event.keyCode != 46) {

		esse.value=esse.value.replace(/\D/g,"")                 //Remove tudo o que não é dígito

		esse.value=esse.value.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos

		esse.value=esse.value.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos

	}

}

function c(esse, event){

	if (event.keyCode != 8 && event.keyCode != 37 && event.keyCode != 39 && event.keyCode != 46) {

		esse.value=esse.value.replace(/\D/g,"") 

		esse.value=esse.value.replace(/^(\d{5})(\d)/,"$1-$2") 

	}

}

function valida_email() {

	mail = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/

	esse = document.getElementById("email")

	if (!mail.test(esse.value)) {

		alert("Digite o email corretamente");

		esse.focus();

		return false; 

	}

	return true;

}

function selecao(valor) {

	if (valor == "Invoice") {

		document.getElementById("etiqueta_ptax").style.visibility = "hidden"

		document.getElementsByName("ptax").item(0).value = "1"

		document.getElementsByName("ptax").item(0).style.visibility = "hidden"				

	}

	else {

		document.getElementById("etiqueta_ptax").style.visibility = "visible"

		document.getElementsByName("ptax").item(0).style.visibility = "visible"				

	}

}



function MascaraCPF(cpf){

if(mascaraInteiro(cpf)==false){

event.returnValue = false;

}

return formataCampo(cpf, '000.000.000-00', event);

}

function ValidarCPF(Objcpf){

if(!Objcpf.value.length<1){

var cpf = Objcpf.value;

exp = /\.|\-/g

cpf = cpf.toString().replace( exp, "" );

var digitoDigitado = eval(cpf.charAt(9)+cpf.charAt(10));

var soma1=0, soma2=0;

var vlr =11;

for(i=0;i<9;i++){

soma1+=eval(cpf.charAt(i)*(vlr-1));

soma2+=eval(cpf.charAt(i)*vlr);

vlr--;

}

soma1 = (((soma1*10)%11)==10 ? 0:((soma1*10)%11));

soma2=(((soma2+(2*soma1))*10)%11);

var digitoGerado=(soma1*10)+soma2;

if(digitoGerado!=digitoDigitado)

alert('CPF Invalido!');

}

}

function MascaraCNPJ(cnpj){

if(mascaraInteiro(cnpj)==false){

event.returnValue = false;

}

return formataCampo(cnpj, '00.000.000/0000-00', event);

}

function ValidarCNPJ(ObjCnpj){

if(!ObjCnpj.value.length<1){

var cnpj = ObjCnpj.value;

var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);

var dig1= new Number;

var dig2= new Number;



exp = /\.|\-|\//g

cnpj = cnpj.toString().replace( exp, "" );

var digito = new Number(eval(cnpj.charAt(12)+cnpj.charAt(13)));



for(i = 0; i<valida.length; i++){

dig1 += (i>0? (cnpj.charAt(i-1)*valida[i]):0);

dig2 += cnpj.charAt(i)*valida[i];

}

dig1 = (((dig1%11)<2)? 0:(11-(dig1%11)));

dig2 = (((dig2%11)<2)? 0:(11-(dig2%11)));



if(((dig1*10)+dig2) != digito)

alert('CNPJ Inválido!');

}

}

function MascaraCep(cep){

if(mascaraInteiro(cep)==false){

event.returnValue = false;

}

return formataCampo(cep, '00.000-000', event);

}

function ValidaCep(cep){

if(!cep.value.length<1){

exp = /\d{2}\.\d{3}\-\d{3}/

if(!exp.test(cep.value))

alert('Número de Cep Inválido!');

}

}

function MascaraData(data){

if(mascaraInteiro(data)==false){

event.returnValue = false;

}

return formataCampo(data, '00/00/0000', event);

}

function ValidaData(data){

if(!data.value.length<1){

exp = /\d{2}\/\d{2}\/\d{4}/

if(!data.value.length<1){

if(!exp.test(data.value)){

alert('Data Inválida!');}

}

}

}

function MascaraTelefone(tel){

if(mascaraInteiro(tel)==false){

event.returnValue = false;

}

return formataCampo(tel, '(00) 0000-0000', event);

}

function ValidaTelefone(tel){

if(!tel.value.length<1){

exp = /\(\d{2}\)\ \d{4}\-\d{4}/

if(!exp.test(tel.value))

alert('Número de Telefone Inválido!');

}

}

function formataCampo(campo, Mascara, evento) {

var boleanoMascara;

var Digitato = evento.keyCode;

exp = /\-|\.|\/|\(|\)| /g

campoSoNumeros = campo.value.toString().replace( exp, "" );

var posicaoCampo = 0;

var NovoValorCampo="";

var TamanhoMascara = campoSoNumeros.length;;

if (Digitato != 8) { // backspace

for(i=0; i<= TamanhoMascara; i++) {

boleanoMascara = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".")

|| (Mascara.charAt(i) == "/"))

boleanoMascara = boleanoMascara || ((Mascara.charAt(i) == "(")

|| (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " "))

if (boleanoMascara) {

NovoValorCampo += Mascara.charAt(i);

TamanhoMascara++;

}else {

NovoValorCampo += campoSoNumeros.charAt(posicaoCampo);

posicaoCampo++;

}

}

campo.value = NovoValorCampo;

return true;

}else {

return true;

}

}

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){

var sep = 0;

var key = '';

var i = j = 0;

var len = len2 = 0;

var strCheck = '0123456789';

var aux = aux2 = '';

var whichCode = (window.Event) ? e.which : e.keyCode;

//alert(whichCode);

if (whichCode == 13||whichCode == 8||whichCode == 0) return true;

key = String.fromCharCode(whichCode); // Valor para o código da Chave

if (strCheck.indexOf(key) == -1) return false; // Chave inválida

len = objTextBox.value.length;

for(i = 0; i < len; i++)

	if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;

aux = '';

for(; i < len; i++)

	if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);

aux += key;

len = aux.length;

if (len == 0) objTextBox.value = '';

if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;

if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;

if (len > 2) {

	aux2 = '';

	for (j = 0, i = len - 3; i >= 0; i--) {

		if (j == 3) {

			aux2 += SeparadorMilesimo;

			j = 0;

		}

		aux2 += aux.charAt(i);

		j++;

	}

	objTextBox.value = '';

	len2 = aux2.length;

	for (i = len2 - 1; i >= 0; i--)

	objTextBox.value += aux2.charAt(i);

	objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);

}

return false;

}

function mascaraInteiro(valor){

if (event.keyCode < 48 || event.keyCode > 57){

event.returnValue = false;

return false;

}

return true;

}

function confirmar_senha(){

	senha = document.getElementById('senha');

	conf_senha = document.getElementById('confirma_senha');

	

if (senha.value!=conf_senha.value){

	alert("Senha está diferente da Confirmação!");

	senha.value="";

	conf_senha.value="";

	senha.focus();

	}else{

	if(senha.value.length < 6){

		alert("Senha deve conter 6 dígitos ou mais!");

		senha.value="";

		conf_senha.value="";

		senha.focus();

		}

	}

}



function comprova_extensao(formulario, arquivo) {

// como usar essa função:

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

//<form method=post action="#" enctype="multipart/form-data">

//<input type=file name="arquivoupload">

//<input type=button name="Submit" value="Enviar" onclick="comprova_extensao(this.form, this.form.arquivoupload)">

//</form> 

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

   extensoes_permitidas = new Array(".gif", ".jpg", ".jpeg", ".doc", ".pdf", ".xls", ".pps", ".ppt", ".rtf", ".docx", ".xlsx", ".ppsx", ".pptx");

   meuerro = "";

   if (!arquivo) {

      //Se não tenho arquivo, é porque não se selecionou um arquivo no formulário.

       meuerro = "Não foi selecionado nenhum arquivo";

   }else{

      //recupero a extensão deste nome de arquivo

      extensao = (arquivo.substring(arquivo.lastIndexOf("."))).toLowerCase();

      //alert (extensao);

      //comprovo se a extensão está entre as permitidas

      permitida = false;

      for (var i = 0; i < extensoes_permitidas.length; i++) {

         if (extensoes_permitidas[i] == extensao) {

         permitida = true;

         break;

         }

      }

      if (!permitida) {

         meuerro = "verifique a extensão do arquivo. \nExtensões permitidas: " + extensoes_permitidas.join();

		 alert (meuerro);

		 document.form_aviso.arquivo.value="";

		 }/*else{

          //submeto!

         alert ("Tudo correto. Vou submeter o formulário.");

         formulario.submit();

         return 1;

       }*/

   }

   //se estou aqui é porque não se pode submeter

   return 0;

} 



////////////////////////////////////////////////////////////////////

	listacorrente=-1;

	//maxdestinatario=10000;

	//sess_destinatario='';

	

	function limpalista() {

		document.form_aviso.destinatario1.options.length=0;

		document.form_aviso.destinatario.value="";

	}



	function checalista(lval) {

		var found=false;

		var k=document.form_aviso.destinatario1;

		for(var j=0; j<k.length; j++) {

			if(k.options[j].value==lval) {

				found=true;

				break;

			}

		}

		return found;

	}

	

	function adicionalista() {

		var l=document.form_aviso.associados;

		var k=document.form_aviso.destinatario1;

		var m=document.form_aviso.destinatario;

		

		for(var j=0; j<l.length; j++) {

			if(l.options[j].selected) {

				if(!checalista(l.options[j].value)) {

					k.options[k.options.length]	= new Option(l.options[j].text, l.options[j].value, l.options[j].selected="selected");

					m.value += l.options[j].value + ";";

					//if(k.length==maxdestinatario) break;

				}

				l.options[j].selected=0;

			}

		}

		//if(k.length==maxdestinatario) alert('Número Máximo de Destinatários selecionados');

	}

	

	function removelista() {

		var k=document.form_aviso.destinatario1;

		for(var j=0; j<k.length; j++) {

			if(k.options[j].selected) {

				k.options[j]=null;

				j--;

			}

		}

	}



////////////////////////////////////////////////////////////////////

	function grava_destinatario(){

		var k=document.form_aviso.destinatario1;

		var m=document.form_aviso.destinatario;

		var n="";

		

		for(var j=0; j<k.length; j++) {

				//alert(k.options[j].value);

				n += k.options[j].value + ";";

				k.options[j].selected=0;

		}

		m.value = n.substr(0,n.length-1);

	}

function ver_checkbox(eu) {

   for (var i=0;i<document.form_excluir.elements.length;i++) {

     var x = document.form_excluir.elements[i];

     if (x.name == 'codigo[]') {

		x.checked = eu.checked;

		}

	}

} 

function tipos(valor) {

	if (valor == "Nacional") {

		document.getElementById("nac").style.visibility = "visible"	

		document.getElementById("estado1").style.visibility = "visible"	
		
		document.getElementById("estado2").style.visibility = "hidden"	

		document.getElementById("estado3").style.visibility = "visible"	
		
		document.getElementById("estado4").style.visibility = "hidden"	

		document.getElementById("pais").value = "Brasil"

	}

	else {

		document.getElementById("nac").style.visibility = "hidden"	

		document.getElementById("estado1").style.visibility = "hidden"	

		document.getElementById("estado2").style.visibility = "visible"	

		document.getElementById("estado3").style.visibility = "hidden"	

		document.getElementById("estado4").style.visibility = "visible"	

		document.getElementById("cnpj").value = ""
		

	}

}

function abre() {

	document.getElementById("tipo").value = document.getElementById("tipo_associado").value

	document.getElementById("user").value = document.getElementById("login").value

	

	if (document.getElementById("tipo").value == "Nacional") {

		document.getElementById("num").value = document.getElementById("cnpj").value

		if (document.getElementById("num").value == "") {

			alert("Preencha o campo CNPJ para a verificação.")

			document.getElementById("cnpj").focus()

			return 0

		}

	}

	else {

		document.getElementById("nome").value = document.getElementById("nome_empresa").value

		document.getElementById("razao").value = document.getElementById("razao_social").value

		

		if (document.getElementById("nome").value == "") {

			alert("Preencha o campo Nome da Empresa para a verificação.")

			document.getElementById("nome_empresa").focus()

			return 0

		}

		if (document.getElementById("razao").value == "") {

			alert("Preencha o campo Razão Social para a verificação.")

			document.getElementById("razao_social").focus()

			return 0

		}		

	}

	

	

	if (document.getElementById("user").value == "") {

		alert("Preencha o campo Login para a verificação.")

		document.getElementById("login").focus()

		return 0

	}



	

	window.open("","nova","width=400,height=200,menubar=no")

	var intervalo = window.setTimeout("document.getElementById('verificar').submit()",500)

	return 1

}

	