﻿function rdoDestino_onClick(obj)
{

	var cboEntidade = document.form.getElementById("sel_Entidade");

	if (obj.value == "fundo")
	{
		cboEntidade.disabled = true;
	}
	else
	{
		cboEntidade.disabled = false;
	}
	
	return true;
}
function Somente_Numeros() {
 if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
}

function AlteraDisp(Tipo,Controle1,Controle2,Controle3){
    if (Tipo == 1){
        document.getElementById(Controle1).style.display = 'none';
        document.getElementById(Controle2).style.display = 'none';
        document.getElementById(Controle3).style.display = 'none';
    }
    else{
        document.getElementById(Controle1).style.display = 'block';
        document.getElementById(Controle2).style.display = 'block';
        document.getElementById(Controle3).style.display = 'block';
    }
}

// JavaScript Document

function soNumeroDecimal(objeto){
	var keypress=event.keyCode;
	if(event.keyCode==17){ 
		event.keyCode=0;
	}
	if(event.keyCode==46 &&(objeto.value.indexOf(String.fromCharCode(46))!=-1))	{
		event.keyCode=0;
	}
	var campo=eval(objeto);
	var caracteres='01234567890.';
	if((caracteres.indexOf(String.fromCharCode(keypress))!=-1))	{
		event.returnValue=true;
	}
	else 
		event.returnValue=false;
}

function validaCasasDecimal(objeto,maxlength,casas,valor){
	if((objeto.value.indexOf('.')!=-1))
	{
	if((objeto.value.length-objeto.value.indexOf('.'))>casas+1)
		objeto.value=objeto.value.substr(0,objeto.value.length-1);
	}
	else{
		if((objeto.value.length)>=maxlength-(casas+valor))
			objeto.value=objeto.value.substr(0,(maxlength-(casas+valor)));
	}
}

function tiposcaracteristicas(descricao){
	if (descricao=="Checkbox")
	return 1;
	else if (descricao=="Quantitativa")
	return 2;
	else if (descricao=="Valor")	
	return 3;	
	else if (descricao=="Filtro")	
	return 4;	
}

function tratarcampo(param,tratar){
	if (tratar==true)	
	var tipocaract = parseInt(tiposcaracteristicas(param));	
	else
	var tipocaract = param;	
	if (tipocaract==1){ //checkbox
	document.form1.valorcaract.onkeypress=function(){};
	document.form1.valorcaract.onKeyUp=function(){};	
	document.form1.valorcaract.value="1"
	document.getElementById("linhacaract").style.visibility="hidden";
	}
	else if (tipocaract==2){ //quantitativa
	document.form1.valorcaract.onkeypress=function(){ mascara(this,soNumeros) };
	document.form1.valorcaract.onKeyUp=function(){};	
	document.form1.valorcaract.value="";
	document.getElementById("linhacaract").style.visibility="visible";
	}
	else if (tipocaract==3){ //valor 	
	document.form1.valorcaract.onkeypress=function(){return(formatarvalor(this,'.',',',event));};	
	document.form1.valorcaract.value="";
	document.getElementById("linhacaract").style.visibility="visible";
	}
}

function selecionarnocombo(obj,valor)
{
	for (var i=0;i<obj.options.length;i++)
	{
	 	if (obj.options[i].text==valor)
		obj.options[i].selected=true;
	}
}

function TextInner(obj){
	if (document.all) 
		return obj.innerText;  // pra IE
	else
		return obj.textContent; // pra Firefox
}

function atualizatamanhoIF(param)
{	
	//alert(param+" "+document.form1.offsetHeight)
	if(parent.document.getElementById(param)){
	parent.document.getElementById(param).height = document.form1.offsetHeight;
	parent.document.getElementById(param).width = document.form1.offsetWidth;
	}
}	

function addEvent(node,evtType,func) {
        if(node.addEventListener){
            node.addEventListener(evtType,func,false);
            return true;
        }
        else if(node.attachEvent)
            return node.attachEvent ("on"+evtType,func);
        else
            return false;
}

function emularenter(){
	if (document.all) {
		if(document.getElementById("executar"))	
		addEvent(document,"keypress",function(){ if (event.keyCode==13) document.getElementById("executar").click(); });
		else if(document.form1.executar)
		addEvent(document,"keypress",function(){ if (event.keyCode==13) document.form1.executar.click(); });		
	}
}

function limparcampos(param)
{	
	var campos = param.split(',')
	for (var i =0 ; i<campos.length;i++)
	{
		if (document.getElementById(campos[i]))	
		document.getElementById(campos[i]).value="";	
	}
}


function camposvazios(param)
{	
	var campos = param.split(",")	
	for (var i =0 ; i<campos.length;i++){
		if (document.getElementById(campos[i]).value==""){
		document.getElementById(campos[i]).style.backgroundColor="red"	
		}
	}	
	alert('Preencha os Campos Obrigatórios!!')
	for (var i =0 ; i<campos.length;i++){
	document.getElementById(campos[i]).style.backgroundColor="white"		
	}		
}

function salvar(param,func)
{	
	var campos = param.split(',')
	for (var i =0 ; i<campos.length;i++){
		if (document.getElementById(campos[i]).value==""){
		document.getElementById(campos[i]).focus();
		camposvazios(param)			
		return false;
		break;
		}
	}
	return enviar('operacoes/cadastrar.php','','',''+func+'');
}

function popup(param,largura,altura)
{
window.open(param,'','location=no,scrollbars=yes,width='+largura+',height='+altura+'px')
}

function validardata(f,fld,msg,vazio) { 
  var frm = f 
  var e = document.getElementById(fld)
	dataStr = e.value;
  if (vazio == "sim") {
     return true;
  } else { 
	   if (dataStr == "") {
         return false;
	   }
	 var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; 
     var matchArray = dataStr.match(datePat); // formato da data ok? 
     if (matchArray == null) {
        alert("Data Inválida com formato inválido.");
				e.value="";
				return false;
     } 
     dia= matchArray[1]; 
     mes = matchArray[3]; 
     ano = matchArray[4]; 

     if (dia < 1 || dia > 31) {
   	    alert("Favor digitar um Dia Válido."); 
				e.value="";
				return false;
     } 

     if ((mes==4 || mes==6 || mes==9 || mes==11) && dia==31) {
        alert("O Mês "+mes+" não possue 31 dias!"); 
				e.value="";
				return false;
     } 

     if (mes == 2) {
        // checando Fevereiro para dia 29  
	      var isleap = (ano % 4 == 0 && (ano % 100 != 0 || ano % 400 == 0)); 
	      if (dia>29 || (dia==29 && !isleap)) {
	         alert("Fevereiro de " + ano + " não tem " + dia + " dias!"); 
					 e.value="";
					 e.select(); 
					 return false;
        } 
     } 

     if (mes < 1 || mes > 12) {
        alert("Favor digitar um Mês Válido."); e.value=""; e.select(); 
				return false;
     } 

     return true; // Data válida
		 
  }
} 

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
}


function filtrarnumero(param)
{
	var result = "";
	
	for (var i=0;i<param.length;i++)
	{
	  if (!isNaN(parseInt(param.charAt(i))))
	  result +=(param.charAt(i))  
	}	
	
	return result;
}

//--------------------------------------------------------------

function Verifica_campo_CPF(campo) {
var CPF = filtrarnumero(campo.value); // Recebe o valor digitado no campo

// Aqui começa a checagem do CPF
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) {
      alert('Cpf informado é inválido!');
      campo.value = '';
      campo.focus();
      return false;
   }
}

//---

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    v.value = v.value.replace(/\D/g,"")
    return v
}
//Adicionado por Jhonny
function telefone2(objeto){ 
     if(objeto.value.length == 0)//Coloca parêntese no primeiro numero
     objeto.value = '(' + objeto.value;
     

   if(objeto.value.length == 3)//Coloca parêntese no segundo numero numero
      objeto.value = objeto.value + ')';

 if(objeto.value.length == 8)//Coloca traço no primeiro numero
     objeto.value = objeto.value + '-';
}

function telefone(v){
   v.value = v.value.replace(/\D/g,"");                  //Remove tudo o que não é dígito
    v.value = v.value.replace(/^(\d\d)(\d)/g,"($1)$2"); //Coloca parênteses em volta dos dois primeiros dígitos
    v.value = v.value.replace(/(\d{4})(\d)/,"$1-$2");    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpfcnpj(v){
    if(v.value.length <= 12){
        return(cpf(v));
    }else{
        return(cnpj(v));
    }
}
function cpf(v){

    v.value = v.value.replace(/\D/g,"");                    //Remove tudo o que não é dígito
    v.value = v.value.replace(/(\d{3})(\d)/,"$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
    v.value = v.value.replace(/(\d{3})(\d)/,"$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos

    v.value = v.value.replace(/(\d{3})(\d{1,2})$/,"$1-$2"); //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cep(v){
    v.value = v.value.replace(/\D/g,"");                 //Remove tudo o que não é dígito
    v.value=v.value.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}


function data(v) {
	v.value = v.value.replace(/[a-z]/g,"");
	v.value = v.value.replace(/^(\d+)$/g,"$1");
	v.value = v.value.replace(/^(\d{2})\/?(\d+)$/g, "$1/$2");
	v.value = v.value.replace(/^(\d{2})\/?(\d{2})\/?(\d{1,4})$/g, "$1/$2/$3");	
	return v;
}


function hora(v) {
	v.replace(/[^d]/g, '').replace(/^(\d{2})(\d{2}).*$/, '$1: $2');
	return v;
}



function cnpj(v){
    v.value=v.value.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v.value=v.value.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v.value=v.value.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v.value=v.value.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v.value=v.value.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}
//-->

function formatarpercentual(fld, decSep, 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;
    
    if (whichCode == 13) return true;  // Enter
    
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
    
    len = fld.value.length;
    
    for(i = 0; i < len; i++)
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
   
    aux = '';
    
    for(; i < len; i++)
        if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
    
    aux += key;
    len = aux.length;
    
    if (len == 0) fld.value = '';
    if (len == 1) fld.value = '0' + decSep + '0' + aux; // Alterei coloquei + '0' , decSep = , (vírgula)
    if (len == 2) fld.value = '0' + decSep + aux; // Alterei coloquei + '0'
    if (len > 2) { // Alterei de 2 para 3
    
    aux2 = '';

    for (j = 0, i = len - 3; i >= 0; i--) {
        aux2 += aux.charAt(i);
        j++;
    }

    fld.value = '';
    len2 = aux2.length;

    for (i = len2 - 1; i >= 0; i--) // Alterei de i >= 0 para i > 0
        fld.value += aux2.charAt(i);

    fld.value += decSep + aux.substr(len - 2, len); // O número dois é o valor chave (número de casas que vem depois da vírgula)
    }
    return false;
}

function formatarvalor(fld, milSep, decSep, 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;
if (whichCode == 13)
return true;  // Enter
key = String.fromCharCode(whichCode);  // Get key value from key code
if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
len = fld.value.length;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) fld.value = '';

// Aqui tem que testar: se $Column->{decimals} for 3 coloca + '0' + '0' + senão, apenas + '0' +
if (len == 1) fld.value = '0' + decSep + '0' + aux; // Alterei coloquei + '0' , decSep = , (vírgula)

// Aqui tem que testar: se $Column->{decimals} for 3 coloca + '0' + senão, não coloca
if (len == 2) fld.value = '0' + decSep + aux; // Alterei coloquei + '0'

// Aqui tem que testar: se $Column->{decimals} for 3 coloca essa linha senão não coloca
//if (len == 3) fld.value = '0' + decSep + aux + aux2; // Adicionei esta linha

// Aqui tem que colocar a variável $decimal
if (len > 2) { // Alterei de 2 para 3
 aux2 = '';

 // A cada três caracteres adiciona um milSep (ponto ".")
 for (j = 0, i = len - 3; i >= 0; i--) {
  if (j == 3) {
   aux2 += milSep;
   j = 0;
  }
  aux2 += aux.charAt(i);
  j++;
 }

 fld.value = '';
 len2 = aux2.length;

 // Aqui tem que testar: se $Column->{decimals} for 3 coloca i > 0 senão coloca i >= 0
 for (i = len2 - 1; i >= 0; i--) // Alterei de i >= 0 para i > 0
 fld.value += aux2.charAt(i);

 // Aqui tem que coloca a variável mo lugar do 3
 fld.value += decSep + aux.substr(len - 2, len); // O número dois é o valor chave (número de casas que vem depois da vírgula)
}
return false;
}
//-------------

function formatarcamposdata(param)
{	
	var campos = param.split(',')
	for (var i =0 ; i<campos.length;i++)
	{	
		if(document.getElementById(campos[i]).value=="00/00/0000"){		
		document.getElementById(campos[i]).value=""
		}
	}
}

function formatarcamposvlr(param)
{	
	var campos = param.split(',')
	for (var i =0 ; i<campos.length;i++)
	{	
		if(document.getElementById(campos[i]).value!=""){
		var valor = parseFloat(document.getElementById(campos[i]).value);
		document.getElementById(campos[i]).value=valor.format(2, ",", ".");	
		}else{
        //document.getElementById(campos[i]).value="0,00";
        
		}
	}
}

String.PAD_LEFT  = 0;
String.PAD_RIGHT = 1;
String.PAD_BOTH  = 2;

String.prototype.pad = function(size, pad, side) {
  var str = this, append = "", size = (size - str.length);
  var pad = ((pad != null) ? pad : " ");
  if ((typeof size != "number") || ((typeof pad != "string") || (pad == ""))) {
    throw new Error("Wrong parameters for String.pad() method.");
  }
  if (side == String.PAD_BOTH) {
    str = str.pad((Math.floor(size / 2) + str.length), pad, String.PAD_LEFT);
    return str.pad((Math.ceil(size / 2) + str.length), pad, String.PAD_RIGHT);
  }
  while ((size -= pad.length) > 0) {
    append += pad;
  }
  append += pad.substr(0, (size + pad.length));
  return ((side == String.PAD_LEFT) ? append.concat(str) : str.concat(append));
}

Number.prototype.format = function(d_len, d_pt, t_pt) {
  var d_len = d_len || 0;
  var d_pt = d_pt || ".";
  var t_pt = t_pt || ",";
  if ((typeof d_len != "number")
    || (typeof d_pt != "string")
    || (typeof t_pt != "string")) {
    throw new Error("wrong parameters for method 'String.pad()'.");
  }
  var integer = "", decimal = "";
  var n = new String(this).split(/\./), i_len = n[0].length, i = 0;
  if (d_len > 0) {
    n[1] = (typeof n[1] != "undefined") ? n[1].substr(0, d_len) : "";
    decimal = d_pt.concat(n[1].pad(d_len, "0", String.PAD_RIGHT));
  }
  while (i_len > 0) {
    if ((++i % 3 == 1) && (i_len != n[0].length)) {
      integer = t_pt.concat(integer);
    }
    integer = n[0].substr(--i_len, 1).concat(integer);
  }
  return (integer + decimal);
}

function convertemoedamysql(param){
param = param.replace(".","")
param = param.replace(",",".")
return param;
}


