/*
  Função que retorna somente numeros:
  -fld = id do campo - ex: this
  -decSep = Separador decimal
  -e = evento do campo - ex: event
  -milSize = tamanho do numero - ex: (123,00) = 3
  -decSize = tamanho do digito apos o separador - ex: (123,00) = 2
  
  Modo de uso:
    onKeyPress="return formatNumber(this,',',event,3,2);"
*/
function formatNumber(fld, decSep, e, milSize, decSize) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	
	if(decSize>0) strCheck= '0123456789'+ decSep;
	
	var aux = aux2= '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	
	if (whichCode == 13) {
    event.returnValue=true;
    return true;  // Enter
  }
	
	key = String.fromCharCode(whichCode);  // Get key value from key code
  
	if (strCheck.indexOf(key) == -1){
    event.returnValue= false;
    return false;  // Not a valid key
    
  }
	len = fld.value.length;
	
	var sepPosition;
	if(decSize>0) sepPosition=fld.value.indexOf(decSep);
	else sepPosition=-1;
	
  
	if(sepPosition>-1){  //já setou separador;
		if(key==decSep){
      event.returnValue=false;
      return false;
      
    }
    if(fld.value.substr(sepPosition+1).length==decSize){
      event.returnValue=false;
      return false;
    }
	}else{
		if(key!=decSep && fld.value.length==milSize){
      event.returnValue=false;
      return false;
      }
	}
	fld.value=fld.value+key;
	
  event.returnValue=false;
	return false;
}

/* 
	Funcao que formata os campos necessitando apenas passar o proprio objeto
	e a mascara exemplo: onKeyPress="formatar(this,"##/##/####");" 

 */
function formatar(src, mask, e) {
	
	var whichCode = (window.Event) ? e.which : e.keyCode;
	var key = '';
  if (whichCode == 13) {
    event.returnValue=true;
    return true;  // Enter
  }
	key = String.fromCharCode(whichCode);  // Get key value from key code
  
  var sepPosition=src.value.indexOf(',');
//  alert('sepPosition '+sepPosition);
	if(sepPosition>-1){  //já setou separador;
//		if(key!=','){
      event.returnValue=false;
//      alert('42');
      return false;
//    }else(key);
    
//    if(fld.value.substr(sepPosition+1).length==decSize){
//      event.returnValue=false;
////      alert('22');
//      return false;
//    }
  }
  
  var i = src.value.length;
	var a = [];
	var saida = mask.substring(0,1);
	var texto = mask.substring(i);
	
  
	if (texto.substring(0,1) != saida) {
		src.value += texto.substring(0,1);
	}
}

/* 
	Funcao que formata com zeros as posições decimais do campo
	e a mascara exemplo: onBlur="zerarDecimal(this,2);" 
 */
function zerarDecimal(src, decSize) {
  if(src.value=='') return true;
	if(src.value.indexOf(',')<0)  //não setou separador;
    src.value= src.value + ',';

  if(src.value.indexOf(',')==0)  //separador é o primeiro caracter;
    src.value='0'+src.value;

  while( (src.value.length-src.value.indexOf(','))<=decSize )
    src.value=src.value+'0';
}
  

//Variavel responsavel para controle do estilo da moeda
var pControleMoeda = '';


function getKeyCode(evnt) {
    if(window.event) { 
        return window.event.keyCode;
    } else if(e) {
        return e.which;
    }
    return 0;
}

function setKeyCode(evnt, keyCode) {
    if(window.event) {
        window.event.keyCode=keyCode;
    } else if(e.which) {
        e.which=keyCode;
    }
    return true;
}

function textoMaiusculo(e){
    return setKeyCode(e, (String.fromCharCode(getKeyCode(e))).toUpperCase().charCodeAt(0));
}

function textoMinusculo(e){
    return setKeyCode(e, (String.fromCharCode(getKeyCode(e))).toLowerCase().charCodeAt(0));
}

function fctAbrirPopupArtigo(adArtigo, scrollBars) {
    window.open("/ste/jsp/default.jhtml?adPagina=460&adArtigo="+adArtigo,'','status=0,resizable=1,center=1,scrollbars='+scrollBars);
}

function openPopup(url,n,w,h,other,c){
    // Compatibilidade com a versão 1.0 (STE)
	l=18;t=18
	if(c){l=(screen.availWidth-w)/2;t=(screen.availHeight-h)/2}
	url=url.replace(/[ ]/g,'%20')
	popup=window.open(url,'pop_'+n,'left='+l+',top='+t+',width='+w+',height='+h+',scrollbars=1'+((other)?','+other:''))
	other=other||''
	if(is.ie&&other.indexOf('fullscreen')!=-1){popup.moveTo(0,0);popup.resizeTo(screen.width,screen.height)}
	popup.focus()
}

function submeter(acao){
    document.forms[0].acao.value=acao;
    document.forms[0].submit();
}

function abrirPopupSeguranca(){
    window.open('/ste/jsp/imagemSeguranca.jsp','','scrollbars=0,status=0,resizable=no,left=230,top=220,width=380,height=180');
}

function submeterSeguranca(){
    if(document.forms[0].txtCodigoSeguranca.value.length < 4){
        alert("Favor informar o número da imagem com 4 dígitos!");
        document.forms[0].txtCodigoSeguranca.focus();
        return false;
    } else {
        opener.document.forms[0].cdImgSeguranca.value= document.forms[0].cdImgSeguranca.value+";"+document.forms[0].txtCodigoSeguranca.value;
        opener.document.forms[0].acao.value= "inserirSeguranca";
        opener.document.forms[0].submit();
        window.close();
    }
}

function insereZero(value, tam){
    var length = value.length;
    for (i = 0 ; i < tam - length ; i++){
        value = "0" + value;
    }
    return value;
}

function mudaFoco(campo){
    if(campo.value.length == campo.maxLength){
        for(var i = 0 ; i < campo.form.length ; i++){
            if(campo.form[i] == campo && campo.form[i+1] && !campo.form[i+1].disabled){
                campo.form[i+1].focus();
                break
            }
        }
    }
}

function tamanhoMaximo(campo){
    if(campo.value.length == campo.maxLength){
        return true;
    }
    return false;
}

function digite(numeros, letras, valores, outros, e){
    if(window.event)key=window.event.keyCode
    else if(e)key=e.which
    else return true
    S=(outros)?outros:''
    if(valores)S+='0123456789,.'
    if(numeros)S+='0123456789'
    if(letras)S+='abcdefghijklmnopqrstuvwxyzçABCDEFGHIJKLMNOPQRSTUVWXYZÇ'
    if(key==null || key==0 || key==8 || key==9 || key==27 || key==13)return true
    else if(S.indexOf(String.fromCharCode(key))!=-1)return true
    else return false
}

function validarStrings(comEspacos, somenteMaiuscula){
    if(window.event)key=window.event.keyCode;
    if(key==null || key==0 || key==8 || key==9 || key==27 || key==13 || comEspacos && key == 32)return;
    if(!isNaN(String.fromCharCode(key))){event.returnValue = false;return}
	if(somenteMaiuscula)event.keyCode=String.fromCharCode(key).toUpperCase().charCodeAt(0);
}

function digitarData(campo){
    var texto = campo.value;
    if(window.event)key=window.event.keyCode;
    else return true;
    if(texto.length==10||key==47&&texto.length==0||texto.length>0&&key==47&&texto.lastIndexOf('/')==(texto.length-1)) return false;
    if(key==null||key==0||key==8||key==9||key==13||key==27||"0123456789/".indexOf(String.fromCharCode(key))!=-1) return true;
    return false;
}

function validarDataDetalhe(campo) {
    var fld = campo.value;
    //verificando se o campo está vazio
    if (fld.length == 0) return 0;
    //separa a data em partes
    var vDia = -1, vMes = -1, vAno = -1, vBarra = 0;
    for (i = 0; i < fld.length; i++) {
        if (fld.substr(i, 1) == "/") {
            if (vDia == -1) {
                vDia = parseInt(fld.substring(vBarra, i), 10);
            } else if (vMes == -1) {
                vMes = parseInt(fld.substring(vBarra, i), 10);
            }
            vBarra = i + 1;
        }
    }
    if (vDia == -1) {
        vDia = parseInt(fld.substring(0), 10);
        objData = new Date();
        vMes = objData.getMonth()+1;
        vAno = objData.getFullYear();
    } else if (vMes == -1) {
        vMes = parseInt(fld.substring(vBarra, i), 10);
        objData = new Date();
        vAno = objData.getFullYear();
    } else {
        vAno = parseInt(fld.substring(vBarra), 10);
    }
    vAno += (vAno < 50 ? 2000 : (vAno <= 99 ? 1900 : 0));
    if (vDia < 1 || vDia > 31) return 1;
    if (vMes < 1 || vMes > 12) return 2;
    if (vAno < 1900 || vAno > 2099) return 3;
    switch (vMes) {
        case 2:
            if (vAno % 4 == 0 && vDia > 29 || vAno % 4 != 0 && vDia > 28) return 4; // Dia inválido para este mês
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            if (vDia == 31) return  4; // Dia inválido para este mês
    }
    campo.value = (vDia > 9 ? "" : "0") + vDia + "/" + (vMes > 9 ? "" : "0") + vMes + "/" + vAno;
    return 0;
}

/**
 * Validar o Campo data
 */
function validarData(campo, nome) {
    // constantes
    /*
    arrayErros = [
        '', // 0
        'O campo ' + nome + ' deve seguir o formato \"dd/mm/aaaa\" .',
        'Mês deve ser maior ou igual a 1 e menor ou igual a 12.',
        'Mês deve ser numérico.',
        'Dia deve ser maior ou igual a 1 e menor ou igual a 31.',
        'Dia deve ser numérico.',
        'Ano deve ser maior ou igual a 1900 e menor ou igual a 2099.',
        'Ano deve ser numérico.',
        'Este mês só possui 30 dias.',
        'O mês de fevereiro possui menos de 30 dias.',
        'Data inválida.\nNão é ano bissexto.'];
    */
    arrayErros = [
        '', // 0
        'Dia Inválido!!',
        'Mês Inválido!!',
        'Ano Inválido!!',
        'Dia Inválido para este mês!!'];
    var ret = validarDataDetalhe(campo);
    if (ret != 0) {
        alert(nome + '\n\n' + arrayErros[ret]);
        campo.focus();
        return false;
    }
    return true;
}

function validarNrDecimal(texto){
    if(window.event)key=window.event.keyCode
    else return true;
    if(key==null||key==0||key==8||key==9||key==13||key==27) return true
    else if(texto.indexOf(",")>=0 && key==44) {
    	alert("Vírgula já foi informada!!");
    	return false;
    } else if(texto.indexOf(".")>=0 && key==46) {
    	alert("Ponto já foi informado!!");
    	return false;
    } else if((texto.indexOf(".") >= 0 || texto.lastIndexOf(",") >= 0) && (key==44 || key==46)) {
    	alert("Ponto e Vírgula não podem ser utilizados em conjunto!!");
    	return false;
    }else if("0123456789,.".indexOf(String.fromCharCode(key))!=-1) return true
    return false;
}

function validaEmail(email) {

    var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    
    if (filter.test(email)) {
        return true;
    } else{
        return false;
    }
}

function checarValor(campo){
    valor = campo.value;
    if((valor.indexOf(",") > -1 || valor.indexOf(".") > -1) && valor.length < 2){
        campo.value = "";
    }
}

function validaCpf(v){
  var s=null
  var r=null
  if(v.length!=11||
    v=='00000000000'||v=='11111111111'||v=='22222222222'||v=='33333333333'||v=='44444444444'||
    v=='55555555555'||v=='66666666666'||v=='77777777777'||v=='88888888888'||v=='99999999999')return false
  s=0
  for(var i=0;i<9;i++)s+=parseInt(v.charAt(i))*(10-i)
  r=11-(s%11)
  if(r==10||r==11)r=0
  if(r!=parseInt(v.charAt(9)))return false
  s=0
  for(var i=0;i<10;i++)s+=parseInt(v.charAt(i))*(11-i)
  r=11-(s%11)
  if(r==10||r==11)r=0
  if(r!=parseInt(v.charAt(10)))return false
  return true
}

// Validacao de CNPJ
function cgc(pcgc) {
    // verifica o tamanho
    if (pcgc.length != 14) {
        sim=false
    }else {
        sim=true
    }
    // verifica se e numero
    if(sim) {
        for (i=0;((i<=(pcgc.length-1))&& sim); i++) {
            val = pcgc.charAt(i)
            //alert(val);
            if((val!="9")&&(val!="0")&&(val!="1")&&(val!="2")&&(val!="3")&&(val!="4") &&
               (val!="5")&&(val!="6")&&(val!="7")&&(val!="8")) {
                sim=false
            }
        }
        // se for numero continua
        if(sim) {
            m2 = 2
            soma1 = 0
            soma2 = 0
            for (i=11;i>=0;i--) {
                val = eval(pcgc.charAt(i))
                //alert("Valor do Val: "+val);
                m1 = m2
                if (m2<9) {
                    m2 = m2+1
                } else {
                    m2 = 2
                }
                soma1 = soma1 + (val * m1)
                soma2 = soma2 + (val * m2)
            }// fim do for de soma
            soma1 = soma1 % 11
            if (soma1 < 2) {
                d1 = 0
            }else {
                d1 = 11- soma1
            }
            soma2 = (soma2 + (2 * d1)) % 11
            if (soma2 < 2) {
                d2 = 0
            }else { 
                d2 = 11- soma2
            }
            //alert(d1);
            //alert(d2);
            if ((d1==pcgc.charAt(12)) && (d2==pcgc.charAt(13))){
                sim=true;
                return true;
            }else {
                //break;
                sim=false;
                return false;
            }
        }
    }
}

function checkBrowser(){
	T=this
	b=navigator.appName
	v=navigator.appVersion
	u=navigator.userAgent
	if(b=='Netscape')T.b='ns'
	else if(b=='Microsoft Internet Explorer')T.b='ie'
	else T.b=b
	T.v=parseInt(v)
	T.ns=(T.b=='ns'&&T.v>=4)
	T.ns4=(T.b=='ns'&&T.v==4)
	T.ns5=(T.b=='ns'&&T.v==5)
	T.ns6=(T.b=='ns'&&T.v==5)
	T.ie=(T.b=='ie'&&T.v>=4)
	T.ie4=(u.indexOf('MSIE 4')>0)
	T.ie5=(u.indexOf('MSIE 5.0')>0)
	T.ie55=(u.indexOf('MSIE 5.5')>0)
	T.ie6=(u.indexOf('MSIE 6.0')>0)
	if(T.ie5)T.v=5
	if(T.ie55)T.v=5.5
	if(T.ie6)T.v=6
	T.min=(T.ns||T.ie)
	T.dom=(T.v>=5)
	T.win=(u.indexOf('Win')>0)
	T.mac=(u.indexOf('Mac')>0)
}

/**
 * Não permite utilizar caracteres inválidos (Por Exemplo: Pontuações)
 */
function verificaCaracteres(obj) {
    var termo = document.getElementById(obj).value;
    var key = window.event.keyCode;
    if ( key==43 || key==45 || key==42 || key==47 || key==36 || key==63 || key==40 || key==41 || key==64 ||
         key==33 || key==38 || key==124 || key==60 || key==62 || key==46 || key==44 || key==59 || key==58 ||
         key==39 || key==92 || key==126 || key==96 || key==37 || key==34 || key==35 || key==94 || key==61 ||
         key==95 || key==91 || key==93 || key==123 || key==125 ) {
         
         event.returnValue = false;
    }
}

is=new checkBrowser()

// Retira caracteres invalidos da string
function Limpar(valor, validos) {
    var result = "";
    var aux;
    for (var i=0; i < valor.length; i++) {
        aux = validos.indexOf(valor.substring(i, i+1));
        if (aux>=0) {
            result += aux;
        }
    }
    return result;
}

//Formata número tipo moeda usando o evento onKeyDown
function Formata(campo,tammax,teclapres,decimal) {
    var objCampo = document.getElementById(campo);
    var tecla = teclapres.keyCode;
    vr = Limpar(objCampo.value,"0123456789");
    tam = vr.length;
    dec=decimal
    
    if(tam > 10){
        event.returnValue=false;
        return false;
    }
    
    if (tam < tammax && tecla != 8){ 
        tam = vr.length + 1 ; 
    }

    if (tecla == 8 ){ 
        tam = tam - 1 ; 
    }

    if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
        if ( tam <= dec ){ 
            objCampo.value = vr ; 
        }

        if ( (tam > dec) && (tam <= 5) ){
            objCampo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; 
        }
        
        if ( (tam >= 6) && (tam <= 8) ){
            objCampo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
        }
        
        if ( (tam >= 9) && (tam <= 11) ){
            objCampo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
        }
        
        if ( (tam >= 12) && (tam <= 14) ){
            objCampo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
        }
        
        if ( (tam >= 15) && (tam <= 17) ){
            objCampo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;
        }
    }
}

//------------------------------------------------------------------------
// Formata o valor do campo numérico para estilo de moeda (999.999.999,00)
// Parâmetro Entrada: Valor do campo no formulário a ser formatado.
//------------------------------------------------------------------------
function formatadaEstiloMoeda() {
    if(arguments[0]){
        var valor = arguments[0];
        valor = valor.replace(".","");
        valor = valor.replace(".","");
        valor = valor.replace(",",".");
        
        if ( isNaN(parseFloat(valor)) ) {
            return "";
        }
        
        if(pControleMoeda == 'MOEDA'){
            valor = (parseFloat(valor) ).toFixed(2);
        }else{
            valor = (parseFloat(valor) ).toFixed(3);
        }
        
        valor = valor.replace(".",",");
        if ( valor.length > 6 ) {
            valor = valor.substr(0,valor.length - 6) + "." +  valor.substr(valor.length - 6); 
        }
        if ( valor.length > 10 ) {
            valor = valor.substr(0,valor.length - 10) + "." +  valor.substr(valor.length - 10);
        }
        
        return valor;
    }
    return "";
}

//------------------------------------------------------------------------
// Formata o valor do campo numérico para estilo de volume (99999,000)
// Parâmetro Entrada: Valor do campo no formulário a ser formatado.
//------------------------------------------------------------------------
function formatadaEstiloVolume() {
    if(arguments[0]){
        var valor = arguments[0];
        valor = valor.replace(".","");
        valor = valor.replace(".","");
        valor = valor.replace(",",".");
        
        if ( isNaN(parseFloat(valor)) ) {
            return "";
        }
        
        valor = (parseFloat(valor) ).toFixed(3);
        valor = valor.replace(".",",");
        
        return valor;
    }
    return "";
}
function Trim(str){
    return str.replace(/^\s+|\s+$/g,"");
}

function formatar_mascara(obj, mascara) {

	var campo = obj.value.length;
	var saida = arguments[1].substring(0,1);
	var texto = arguments[1].substring(campo);
    
    if(texto.substring(0,1) != saida) {
        obj.value += texto.substring(0,1);
    }  
}

//********************************************************************//
// Formata o objeto CNPJ para retirar a  máscara 00.000.000/0000-00 **//
//********************************************************************//
function cnpjSemMascara(cnpj){
    if( (cnpj != "") && (cnpj.length == 18) ){
         var cnpj =  cnpj.replace(/[\.\/-]/g,"");
    }
    return cnpj;
}

//*******************************************************************//
// Formata o objeto CPF para retirar a máscara 000.000.000-00     **//
//*******************************************************************//
function cpfSemMascara(cpf){
    if( (cpf != "") && (cpf.length == 14) ){
         var cpf =  cpf.replace(/[\.\/-]/g,"");
    }
    return cpf;
}

//*******************************************************************//
// Valida CEP                                                      **//
//*******************************************************************//
function validaCep(strCEP)
{
  // Caso o CEP não esteja nesse formato ele é inválido!
  var objER = /^[0-9]{5}-[0-9]{3}$/;

  if(objER.test(strCEP)) {
    return true;
  } else {
    return false;
  }
}

//*******************************************************************//
// FORMATA VALORES COM 3 CASAS APÓS A VIRGULA                                                    **//
//*******************************************************************//
function formataValor(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) {
         event.returnValue=true;  // Enter
         return true;
      }

      if (whichCode == 27) {
         event.returnValue=false;  // Enter
         return false;
      }

      key = String.fromCharCode(whichCode);  // Get key value from key code

      if (strCheck.indexOf(key) == -1) {
         event.returnValue=false;  // Not a valid key
         return false;
      }
      
      len = fld.value.length;
      if(len > 6){
         event.returnValue=false;  
         return false;
      }
      
      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 + '00' + aux;
      if (len == 2) 
         fld.value = '0'+ decSep + '0' + aux;
      if (len == 3) 
         fld.value = '0' + decSep + aux;                           
      if (len > 3) {
          aux2 = '';
          for (j = 0, i = len - 4; i >= 0; i--) {
              if (j == 3) {
                  aux2 += milSep;
                  j = 0;
              }
              aux2 += aux.charAt(i);
              j++;
          }
          fld.value = '';
          len2 = aux2.length;
          for (i = len2 - 1; i >= 0; i--)
              fld.value += aux2.charAt(i);

          fld.value += decSep + aux.substr(len - 3, len);
      }
      event.returnValue=false;
      return false;
}
