//Não utilizar
function Selecionar(campoId,id,campoDesc,desc,submit)
	{
		var wo = eval('window.opener');

		if (wo == null)
		{
			alert("window.opener não é um objeto!");
			top.close();
		}

		ObjId = eval('window.opener.document.forms[0].' + campoId);
		if (ObjId != null) 
		{
			ObjId.value = id;
			
		}
		else
		{
			alert('Erro ao selecionar Objeto para ID!');
		}
		
		ObjDesc = eval('window.opener.document.forms[0].' + campoDesc);
		if (ObjDesc != null) 
		{
			ObjDesc.value = desc;
		}
		

		top.close();
	}


//Não utilizar
function ParseNumb(c)
{
  c=ClearStr(c,"-");
  c=ClearStr(c,"/");
  c=ClearStr(c,",");
  c=ClearStr(c,".");
  c=ClearStr(c,"(");
  c=ClearStr(c,")");
  c=ClearStr(c," ");
  if((parseFloat(c) / c != 1))
  {
    if(parseFloat(c) * c == 0)
    {
      return(c);
    }
    else
    {
      return(0);
    }
  }
  else
  {
    return(c);
  }
  return(c);
}
//Não utilizar
function Verify(CNUMB,CTYPE)
{
  CNUMB=ParseNumb(CNUMB)
  if(CNUMB == 0)
  {
    return(false);
  }
  else
  {
    g=CNUMB.length-2;
    if(TestDigit(CNUMB,CTYPE,g))
    {
      g=CNUMB.length-1;
      if(TestDigit(CNUMB,CTYPE,g))
      {	
        return(true);
      }
      else
      {
        return(false);
      }
    }
    else
    {
      return(false);
    }
  }
}
//Não utilizar
function TestDigit(CNUMB,CTYPE,g)
{
  var dig=0;
  var ind=2;
  for(f=g;f>0;f--)
  {
    dig+=parseInt(CNUMB.charAt(f-1))*ind;
    if (CTYPE=='CNPJ')
    { if(ind>8) {ind=2} else {ind++} }
    else
    { ind++ }
  }
  dig%=11;
  if(dig<2)
  {
    dig=0;
  }
  else
  {
    dig=11-dig;
  }
  if(dig!=parseInt(CNUMB.charAt(g)))
  {
    return(false);
  }
  else
  {
    return(true);
  }
}
//Não utilizar
function Validar(comp, CNUMB, CTYPE)
{
  if(!Verify(CNUMB, CTYPE))
  {
    if(comp.value.length > 0)
    {
    alert(CTYPE+" invalido!");
    comp.focus();
    comp.select();
     }
    return;
  }
  return;
}
//Não utilizar
function Selecionar2(campoId,id,campoDesc,desc,campoValor,valor,submit)
{
		var wo = eval('window.opener');

		if (wo == null)
		{
			alert("window.opener não é um objeto!");
			top.close();
		}

		ObjId = eval('window.opener.document.forms[0].' + campoId);
		if (ObjId != null) 
		{
			ObjId.value = id;
			
		}
		else
		{
			alert('Erro ao selecionar Objeto para ID!');
		}
		
		ObjDesc = eval('window.opener.document.forms[0].' + campoDesc);
		if (ObjDesc != null) 
		{
			ObjDesc.value = desc;
		}
		
		ObjValor = eval('window.opener.document.forms[0].' + campoValor);
		if (ObjValor != null) 
		{
			ObjValor.value = valor;
		}
		
		top.close();
}

function ClearStr(str, char)
{
  while((cx=str.indexOf(char))!=-1)
  {		
    str = str.substring(0,cx)+str.substring(cx+1);
  }
  return(str);
}

//Compativel Firefox e IE
function formatar(campo, mask,event) 
{
	var keyCode = RetornaKeyCod(event);
	
	if(campo.value.length == mask.length &&
		!Padrao(keyCode,event))
	{
		return false;
	}
	
	//alert(keyCode);
	if((keyCode < 48 || keyCode > 57) && !Padrao(keyCode,event)) 
	{		
		keyCode = 0;
	}

	var tam = campo.value.length;
	var saida = mask.substring(0,1);
	var texto = mask.substring(tam);
	
	//Tá na posição
	if(texto.substring(0,1) != saida && !Padrao(keyCode,event))
	{
		if(keyCode == 0)
		{
			campo.value += texto.substring(0,1);
		}
		else
		{
			campo.value += texto.substring(0,1)+String.fromCharCode(keyCode);
		}
		return false;
	}
	else if (keyCode == 0)
	{
		return false;
	}
}

//Compativel Firefox e IE
function formatarValoresInteiro(campo,event)
{
	var keyCode = RetornaKeyCod(event);	
	//var caract = new RegExp(/^[0-9 ]+$/i);
    //var caract = caract.test(String.fromCharCode(keyCode));
    //------------------------
    //alert(keyCode);
    if(! ((keyCode > 47 && keyCode < 58) || Padrao(keyCode,event)) )
    {          
        keyCode=0;
        return false;
    }
    
    if(campo.value.length >  8)
	{
		keyCode = 0;
		return false;
	}
}

//Compativel Firefox e IE
function formatarBanco(event)
{
	var keyCode = RetornaKeyCod(event);		
    //alert(keyCode);
    
    if(!Padrao(keyCode,event) && ((keyCode != 45 && keyCode < 48) || keyCode > 57) )    
    {          
        keyCode=0;
        return false;
    }
}


//Compativel Firefox e IE
function formatarValoresFone(event)
{
	var keyCode = RetornaKeyCod(event);
	//alert(keyCode);	
	if ((keyCode != 45 && keyCode != 41 && keyCode != 40) && 
		(keyCode < 48 || keyCode > 57) && !Padrao(keyCode,event))
	{
		//alert('er');	
		keyCode = 0;
		return false;
	}
}

///Compativel Firefox e IE
function formatarValoresRG(event)
{
	var keyCode = RetornaKeyCod(event);
	//alert(keyCode);	
	if (keyCode == 45 || keyCode == 46)
	{
		//alert('er');	
		keyCode = 0;
		return false;
	}
}

//Compativel Firefox e IE
//Retorna o caracter digitado
function RetornaKeyCod(event)
{
	//keyCode no IE
	//which no Netscape
	//charCode no Firefox		
	return event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
}

//Teclas padrões que sempre devem ser permitidas como delete ou tab
function Padrao(key,event)
{	
	//É IE
	var isIE = (navigator.appVersion.indexOf("MSIE") > -1);
		
	if(key == 8 || key == 9 || key == 13 ||
		event.keyCode && (key >= 36 && key <= 40) && !isIE)
	{
		return true;
	}
	else
	{
		return false;
	}
}

//Compativel Firefox e IE
function formatarValoresDecimal(campo,event)
{		
	var keyCode = RetornaKeyCod(event);	
	//Tab ou enter
	if(Padrao(keyCode,event))
	{		
		return true;
	}		
	
	//Troca ponto por virgula
	if(keyCode == 46)
	{
		keyCode = 44;
	}
	
	//Não é numérico
	if (keyCode != 44 && (keyCode < 48 || keyCode > 57)) 
	{		
		return false;
	}	
	var a = 0;	
	if(keyCode == 44)
	{		
		while(a < campo.value.length)
		{			
			//Digitou 2 virgulas
			if(campo.value.substring(a,a+1) == ",")
			{				
				return false;
			}
			a = a + 1; 
		}
	}
	
	var texto = campo.value.split(",");
	if((texto[0].length > 6) && (keyCode != 44))
	{
		if(texto[0].length == campo.value.length)
		{				
			return false;
		}
		else
		{	if(texto[1] != null)
			{
				if(texto[1].length > 1)
				{	
					return false;
				}
			}
		}
	}
	else
	{
		if(texto[1] != null)
		{
			if((texto[0].length > 6)&&(texto[1].length > 1))
			{	
				return false;
			}
		}
	}
}

//Compativel Firefox e IE
function formatarValoresMoney(scr,event)
{
	scr.value = scr.value.replace(".",",");
	var keyCode = RetornaKeyCod(event);
	var control = 1;
	if(keyCode == 9)
	{	
		if(scr.value=="0" ||scr.value.length == 0)
		{
			scr.value = "0,00";
			scr.select();
			return;
		}
		scr.select();
		return;
	}
	if(scr.value == "0,00")
	{	
		return;
	}

	var teste = scr.value.split(",");
	if(teste[1] == null)
	{
		return;
	}
	if(teste[1].length == 2)
	{
		control = 0;
	}
	if(control == 1)
	{
		if(teste[1].length > 2)
		{
			scr.value = teste[0] + teste[1].substring(0,1) + "," + teste[1].substring(1,3);
		}
		else
		{
			scr.value = teste[0] + "," + teste[1].substring(0,2);
		}
	}
	var cont;
	teste = scr.value.split(",");
	cont = 0;
	control = 1;
	var result = "a";
	var caract;
	while(cont < teste[0].length)
	{
		caract = teste[0].substring(cont,cont+1);
		if(control == 1)
		{
			if(caract == "0")
			{
				result = teste[0].substring(cont+1,teste[0].length);
			}
			else
			{
				control = 0;
				break;				
			}
		}	

		cont = cont + 1;
	}
	if(result != "a")
	{
		scr.value = result + "," + teste[1];
	}
	if(scr.value.length == 3)
	{
		teste = scr.value.split(",");
		if(teste[0].length < 1)
		{
			scr.value = "0" + scr.value;
		}
	}			
}

//Compativel Firefox e IE
function SelecionarValor(scr)
{
	scr.select();
}

//Compativel Firefox e IE
function semNumero(event)
{
	if (soNums(event))
	{
		return false;
	}
	else
	{
		return true;
	}
}

//Compativel Firefox e IE
function formataAno(scr)
{
	if(scr.value.length == 2)
	{
		if(scr.value < 51)
		{
			scr.value = "20" + scr.value;
		}
		else
		{
			scr.value = "19" + scr.value;
		}
		return;
	}
	if(scr.value.length == 1)	
	{
		scr.value = "200" + scr.value;
		return;
	}		
}

//Compativel Firefox e IE
function formatarValoresForm(scr,event)
{
	var keyCode = RetornaKeyCod(event);		
	if(Padrao(keyCode,event))
	{
		return true;
	}
	if((keyCode != 35 && keyCode != 46) || (keyCode == 46 && 
			(scr.value.substring(scr.value.length-1,scr.value.length) == ".")))
	{	
		scr.value += '#';
		return false;
	}	
}

//Compativel Firefox e IE
function formatarValoresRetiraPontoFinal(scr)
{
	if(scr.value.substring(scr.value.length-1,scr.value.length) == ".")
	{
		var teste = scr.value.substring(0,scr.value.length-1);
		scr.value = teste;
	}
}

//Compativel Firefox e IE / incompleto
function ValidarCampoTexto(scr,Nlinhas,TLinha,event)
{
	var keyCode = RetornaKeyCod(event);
	
	if(Padrao(keyCode,event))
	{
		return true;
	}
	
	var texto = scr.value.split("\n");
	if(texto.length > Nlinhas)
	{		
		return false;
	}
	
	if(texto[texto.length -1].length > TLinha)
	{
		scr.value += "\n";
		if(texto.length > Nlinhas)
		{
			return false;
		}
	}	
}

//Compativel Firefox e IE / incompleto
function CompletaStringKeyUp(scr,valor,valor1)
{
	if((scr.value == valor)||(scr.value == valor1))
	{
		return;
	}
	if(scr.value.toUpperCase().substring(0,1) == valor.toUpperCase().substring(0,1))
	{
		scr.value = valor;
		scr.select();
		return;
	}
	if(scr.value .toUpperCase().substring(0,1) == valor1.toUpperCase().substring(0,1))
	{
		scr.value = valor1;
		scr.select();
		return
	}
}


//Compativel Firefox e IE / incompleto
function CompletaStringKeyPress(scr,valor,valor1,event)
{
	var keyCode = RetornaKeyCod(event);
	if(Padrao(keyCode,event))
	{
		return true;
	}	
	if(scr.value.length > 1)
	{		
		return false;
	}
	if(String.fromCharCode(keyCode).toUpperCase() == valor.toUpperCase().substring(0,1))
	{
		return true;
	}
	if(String.fromCharCode(keyCode).toUpperCase() == valor1.toUpperCase().substring(0,1))
	{
		return true;
	}
	window.alert("Valores permitidos: \n"+valor.substring(0,1) + "-"+ valor + " / " + valor1.substring(0,1) + "-" + valor1);
	return false;
}

//////////////////////////////////////////////////////////////////////


//Compativel Firefox e IE
// JavaScript Document 
/*    ********************************************************************     
    #################################################################### 
    Funcionamento = O script recebe como parâmetro um objeto por isso  
    deve ser chamado da seguinte forma: 
    E.: no evento onBlur de um campo texto 
    <input name="cpf_cnpj" type="text" size="40" maxlength="18"  
    onBlur="validar(this);"> 
    Ao deixar o campo o evento é disparado e chama validar() com o  
    argumento "this" que representa o próprio objeto com todas as  
    propriedades. 
    A partir daí a função validar() trata a entrada removendo tudo que 
    não for caracter numérico e deixando apenas números, portanto 
    valores escritos só com números ou com separadores como '.' ou mesmo 
    espaços são aceitos 
    ex.: 111222333/44, 111.222.333-44, 111 222 333 44 serão tratadoc como 
    11122233344 (para CPFs) 
    De certa forma até mesmo valores como 111A222B333C44 será aceito mas 
    aconselho a usar a função soNums() que encotra-se aqui mesmo para 
    que o campo só aceite caracteres numéricos. 
    Para usar a função soNums() chame-a no evento onKeyPress desta forma 
    onKeyPress="return soNums(event);" 
    Após limpar o valor verificamos seu tamanho que deve ser ou 11 ou 14 
    Se o tamanho não for aceito a função retorna false e [opcional]  
    mostra uma mensagem de erro. 
    Sugestões e comentários marcos_regis@hotmail.com 
    #################################################################### 
    ********************************************************************    */ 

// a função principal de validação 
function validarCPFCNPJ(obj) { // recebe um objeto     
    obj.value = (obj.value).replace(/\D/g,'');

    var tam=obj.value.length; // removendo os caracteres não numéricos 	
    
    if(tam==0)
    {
	return false;
    }	    

    if (!(tam==11 || tam==14)){ // validando o tamanho 
        alert("CPF ou um CNPJ invalido!" ); // tamanho inválido 
	obj.select();
        return false; 
    } 
     
	// se for CPF 
    if (tam==11 ){ 		
        return validaCPF(obj);
    } 
     
	// se for CNPJ             
    if (tam==14){ 
        return validaCNPJ(obj);             
    }      
} 
// fim da funcao validar() 

// função que valida CPF 
// O algorítimo de validação de CPF é baseado em cálculos 
// para o dígito verificador (os dois últimos) 
// Não entrarei em detalhes de como funciona 
function validaCPF(obj) { 
    obj.value = (obj.value).replace(/\D/g,'');
    
    var s = obj.value;

    var tam  = s.length;
	
    if(tam==0)
    {
	return false;
    }
	
    if(tam!=11)
    {
	alert("CPF invalido!" ); // se quiser mostrar o erro 
        obj.select();  // se quiser selecionar o campo em questão 
        return false;
    }	
    	
    var c = s.substr(0,9); 
    var dv = s.substr(9,2); 
    var d1 = 0; 

    for (var 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){ 
	alert("CPF invalido!" ); // se quiser mostrar o erro 
        obj.select();  // se quiser selecionar o campo em questão 
        return false;         
    } 
    d1 *= 2; 
    for (var 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){ 
	alert("CPF invalido!" ); // se quiser mostrar o erro 
        obj.select();  // se quiser selecionar o campo em questão 
        return false;
    } 
    obj.value=maskCPF(s);    // se validou o CPF mascaramos corretamente 
    return true;
} 

// Função que valida CNPJ 
// O algorítimo de validação de CNPJ é baseado em cálculos 
// para o dígito verificador (os dois últimos) 
// Não entrarei em detalhes de como funciona 
function validaCNPJ(obj) { 
    obj.value = (obj.value).replace(/\D/g,'');

    var CNPJ = obj.value;

    var tam  = obj.value.length;
	
    if(tam==0)
    {
	return false;
    }
	
    if(tam!=14)
    {
	alert("CNPJ invalido!" ); // se quiser mostrar o erro 
        obj.select();  // se quiser selecionar o campo em questão 
        return false;
    }
	
    var a = new Array(); 
    var b = new Number; 
    var c = [6,5,4,3,2,9,8,7,6,5,4,3,2]; 
    for (i=0; i<12; i++){ 
        a[i] = CNPJ.charAt(i); 
        b += a[i] * c[i+1]; 
    } 
    if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x } 
    b = 0; 
    for (y=0; y<13; y++) { 
        b += (a[y] * c[y]); 
    } 
    if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; } 
    if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){ 
	alert("CNPJ invalido!" ); // se quiser mostrar o erro 
        obj.select();  // se quiser selecionar o campo em questão 
        return false;
    } 
    obj.value=maskCNPJ(CNPJ);    // se validou o CNPJ mascaramos corretamente 
    return true; 
} 


    // Função que permite apenas teclas numéricas 
    // Deve ser chamada no evento onKeyPress desta forma 
    // return (soNums(event)); 
function soNums(e) 
{ 
    if (document.all){var evt=event.keyCode;} 
    else{var evt = e.charCode;} 
    if (evt <20 || (evt >47 && evt<58)){return true;} 
    return false; 
} 

//    função que mascara o CPF 
function maskCPF(CPF){ 
    return CPF.substring(0,3)+"."+CPF.substring(3,6)+"."+CPF.substring(6,9)+"-"+CPF.substring(9,11); 
} 

//    função que mascara o CNPJ 
function maskCNPJ(CNPJ){ 
    return CNPJ.substring(0,2)+"."+CNPJ.substring(2,5)+"."+CNPJ.substring(5,8)+"/"+CNPJ.substring(8,12)+"-"+CNPJ.substring(12,14);     
} 

//Compativel só com IE
function formatarValoresDecimalAntesVirgula(scr, antesVirgula)
{
	var teste = scr.value.split(',');
	if(teste[0]!= null)
	{
		if(teste[0].length >= antesVirgula)
		{
			if(teste[1] == null)
			{
				scr.value = teste[0];
			}
		}
	}
	scr.value = scr.value;
}

//Compativel só com IE
function formatarValoresDecimalAposVirgula(scr, aposVirgula)
{
	if(event.keyCode == 46)
	{
		event.keyCode = 44;
	}
	if ((event.keyCode != 44 && event.keyCode < 48) || event.keyCode > 57) 
	{
		event.keyCode = 0;
		return;
	}
	
	var a = 0;
	var result = 1;
	if(event.keyCode == 44)
	{
		while(a < scr.value.length)
		{
			if(scr.value.substring(a,a+1) == ",")
			{
				result	= 0;
				a = scr.value.length;
			}
			a = a + 1; 
		}
		if(result == 0)
		{
			event.keyCode = 0;
			return;
		}		
	}	
	var teste = scr.value.split(',');
	if(scr.value.length > aposVirgula) 
	{
		if(teste[1] == null)
		{
			scr.value = scr.value + ",";
			event.keyCode = 0;
			return;
		}		
	}
	if(teste[1] != null)
	{	
		if(teste[1].length >= aposVirgula)
		{
			event.keyCode = 0;
			return;
		}
	}
}

function ValidaPis(CampoPis)
{
	pis=CampoPis.value;
	
	if (!ChecaPIS(pis))
	{
		CampoPis.value = "";
		alert("PIS INVALIDO");		
	}
}

function ChecaPIS(pis)
{

var ftap="3298765432";
var total=0;
var i;
var resto=0;
var numPIS=0;
var strResto="";

	numPIS=pis;
			
	if (numPIS=="" || numPIS==null)
	{
		return false;
	}
	
	for(i=0;i<=9;i++)
	{
		resultado = (numPIS.slice(i,i+1))*(ftap.slice(i,i+1));
		total=total+resultado;
	}
	
	resto = (total % 11)
	
	if (resto != 0)
	{
		resto=11-resto;
	}
	
	if (resto==10 || resto==11)
	{
		strResto=resto+"";
		resto = strResto.slice(1,2);
	}
	
	if (resto!=(numPIS.slice(10,11)))
	{
		return false;
	}
	
	return true;
}

function CopiarValor(Origem, Destino)
{ 
	
	var objDestino = document.getElementById(Destino);
	if(objDestino != null)
	{
		if(objDestino.value.length == 0)
		{
			objDestino.value = Origem.value;
		}
	}
}
////////////////////// Não utilizados ///////////////////////////////////
/* 
function cpfcnpj(){ 
    if(document.a.b.value.length == 3){ 
        document.a.b.value = document.a.b.value + '.'; 
        return false; 
    } 
    if(document.a.b.value.length == 7){ 
        document.a.b.value = document.a.b.value + '.'; 
        return false; 
    } 
    if(document.a.b.value.length == 11){ 
        document.a.b.value = document.a.b.value + '-'; 
        return false; 
    } 
    if(document.a.b.value.length == 15){ 
        p0=document.a.b.value.charAt(0); 
        p1=document.a.b.value.charAt(1); 
        p2=document.a.b.value.charAt(2); 
        p3=document.a.b.value.charAt(4); 
        p4=document.a.b.value.charAt(5); 
        p5=document.a.b.value.charAt(6); 
        p6=document.a.b.value.charAt(8); 
        p7=document.a.b.value.charAt(9); 
        p8=document.a.b.value.charAt(10); 
        p9=document.a.b.value.charAt(12); 
        p10=document.a.b.value.charAt(13); 
        p11=document.a.b.value.charAt(14); 
        document.a.b.value = ''; 
        document.a.b.value = p0 + p1 + '.' + p2 + p3 + p4 + '.' + p5 + p6 + p7 + '/' + p8 + p9 + p10 + p11 + '-'; 
        p0=''; 
        p1=''; 
        p2=''; 
        p3=''; 
        p4=''; 
        p5=''; 
        p6=''; 
        p7=''; 
        p8=''; 
        p9=''; 
        p10=''; 
        p11=''; 
        return false; 
    } 
}
//Sem utilidade pois a formtação já retringe inteiros
function formatarValoresInteiroComPonto(scr) 
{
	if(event.keyCode == 46)
	{
		if(scr.value.substring(scr.value.length-1,scr.value.length) == ".")
		{
			event.keyCode = 0;
		}
		return;
	}
	if ((event.keyCode < 48) || event.keyCode > 57) {event.keyCode = 0;}
}


//Igual a formatar 
function formatarValoresComPonto(src, mask) 
{
	if ((event.keyCode < 48) || event.keyCode > 57) {event.keyCode = 0;}
	

	var i = src.value.length;
	var saida = mask.substring(0,1);
	var texto = mask.substring(i)
	if (texto.substring(0,1) != saida) 
	{
			src.value += texto.substring(0,1);
	}
}
*/
////////////////////// Fim - Não utilizados ///////////////////////////////////