/** 
* Delay for a number of milliseconds 
*/ 
function sleep(delay) 
{ 
    var start = new Date().getTime(); 
    while (new Date().getTime() < start + delay); 
} 

//formata campo de Data para nn/nn/nnnn
function formata_data(data) {  
    var nTecla;
	//aceita apenas caracteres num?ricos
    if (document.all) { // Internet Explorer
        nTecla = evtKeyPress.keyCode;
    } else {
        if (document.layers) { // Nestcape		
            nTecla = evtKeyPress.which;
        }
    }
    if (data.value.length == 2 || data.value.length == 5) {
        data.value += "/";
    }
    if (nTecla < 48 || nTecla > 57) {
		//event.returnValue=false;
        return false;
    }
}
function formataMesAno(data, event) {
			    var nTecla;
			    if (window.event) {
			        nTecla = event.keyCode;
			    } else {
			        nTecla = event.which;
			    }
			    if ((nTecla == 8) || (nTecla == 0)) {
			        return true;
			    }
			    if (apenasNumeros(null, event)) {
			        if (data.value.length == 2) {
			            data.value += "/";
			        }
			        if (nTecla < 48 || nTecla > 57) {
			            return false;
			        }
			    } else {
			        return false;
			    }
			}

function validaDataMesAno(campo) {
		    var novoMes = parseInt(campo.value.substr(0, 2));
			    if (novoMes > 12) {
			        campo.value = "";
			        return false;
			    }
		}
		
//formata campo de Data para nn/nn/nnnn correta
function formatador_data(data, event) {
    var nTecla;
	//aceita apenas caracteres num?ricos
    if (window.event) {
        nTecla = event.keyCode;
    } else {
        nTecla = event.which;
    }
    if ((nTecla == 0) || (nTecla == 13) || (nTecla == 8)) {
        return true;
    }
    if (data.value.length == 2 || data.value.length == 5) {
        data.value += "/";
    }
    if (nTecla < 48 || nTecla > 57) {
		//event.returnValue=false;
        return false;
    }
}

// localizar objeto na pagina w3c //
function 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 = findObj(n, d.layers[i].document);
    }
    if (!x && d.getElementById) {
        x = d.getElementById(n);
    }
    return x;
}


// --------- DEL --------- //
function del(url, message, id) {
    if (message != "") {
        if (confirm(message)) {
            url = url + "?id=" + id;
            window.location = (url);
        }
    } else {
        history.go(-1);
    }

//www = link da p?gina que est? querendo abrir
//h = comprimento da p?gina
//w = largura da p?gina
}

// --------- JANELA --------- //
function janela(www, h, w) {
    var obj = window.self;
    var height = h; //(obj.screen.height - 260);
    var width = w; //obj.screen.width;
    var top = (h / 2);
    var left = (w / 2);

//window.open(www,"nova","top=" + top + ",left="+ left +",width="+w+",heigth="+h+",toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,scrolling=yes,resizable=yes")
    window.open(www, "nova", "top=" + top + ",left=" + left + ",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=450,height=420");
}


// --------- APLICA MASCARA --------- //
function aplicaMascara(e, src, mask) {
    var TAB = 39; // 13
    var BACKSPACE = 8;
    var windows = false;
    var continua = false;
    var _TXT = null;
    if (window.event) {
        _TXT = e.keyCode;
        windows = true;
        TAB = 13;
    } else {
        if (e.which) {
            _TXT = e.which;
        }
    }
    var tam = src.value.length;
    if((_TXT == null) || (_TXT == BACKSPACE) || (_TXT == TAB)) {
        return true;
    }
    if (_TXT > 47 && _TXT < 58) {
        continua = true;
    } else {
        if (windows) {
            if (_TXT > 95 && _TXT < 106) {  // onKeyDown considera estes valores como teclado n?mero --> funcAjax.js  		
                continua = true;
            }
        }
    }
    if (continua) {
        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);
        }
        return true;
    } else {
        if (_TXT != 8) {
            return false;
        } else {
            return true;
        }
    }
}


// --------- VALIDA CNPJ --------- //
function validaCNPJ(object) {
    CNPJ = object.value;
    erro = new String;
    
    // Considera como um CPF
    if(CNPJ.length == 11){
    	return true;
    }
    
    if((CNPJ.length != 18) && (CNPJ.length != 14)){
        erro += "E necessario preencher corretamente o numero do CNPJ!";
    }
    if(CNPJ.length == 14){
    	CNPJ = formataCNPJ(CNPJ);
	}
    if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")) {
        if (erro.length == 0) {
            erro += "E necessario preencher corretamente o numero do CNPJ!";
        }
    }
    if (document.layers && parseInt(navigator.appVersion) == 4) {
        x = CNPJ.substring(0, 2);
        x += CNPJ.substring(3, 6);
        x += CNPJ.substring(7, 10);
        x += CNPJ.substring(11, 15);
        x += CNPJ.substring(16, 18);
        CNPJ = x;
    } else {
        CNPJ = CNPJ.replace(".", "");
        CNPJ = CNPJ.replace(".", "");
        CNPJ = CNPJ.replace("-", "");
        CNPJ = CNPJ.replace("/", "");
    }
    var nonNumbers = /\D/;
    if (nonNumbers.test(CNPJ)) {
        erro += "A verificacao de CNPJ suporta apenas numeros!";
    }
    var a = [];
    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])) {
        erro += "Digito verificador com problema!";
    }
    if (erro.length > 0) {
        return false;
    }
    return true;
}

// --------- VALIDA CPF --------- //
 function validaCPF(object) {
        cpf =  object.value;
		cpf =  cpf.replace(".","");
		cpf =  cpf.replace(".","");
		cpf =  cpf.replace("-","");

		valor = true;
		erro = new String;
		if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n"; 
		var nonNumbers = /\D/;
		if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";	
		if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
			  erro += "Numero de CPF invalido!"
		}
		var a = [];
		var b = new Number;
		var c = 11;
		for (i=0; i<11; i++){
			a[i] = cpf.charAt(i);
			if (i < 9) b += (a[i] *  --c);
		}
		if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		b = 0;
		c = 11;
		for (y=0; y<10; y++) b += (a[y] *  c--); 
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
			erro +="Digito verificador com problema!";
		}
		if (erro.length > 0){
			//alert(erro);
			return false;
		}
		return true;
	}


//2 digitos decimais
// --------- VALIDA MOEDA --------- //
function validaMoeda(vlrDecimal) {
    var reMoeda = /^\d{1,3}(\.\d{3})*\,\d{2}$/;
    if (!(vazio(vlrDecimal.value))) {
        if (reMoeda.test(vlrDecimal.value)) {
            return true;
        } else {
            alert("Valor de moeda invalido!\n Utilize o formato : 0,00");
            return reMoeda.test(vlrDecimal);
        }
    }
    return true;
}


// --------- TROCA STRING --------- //
function troca(str, strsai, strentra) {
    while (str.indexOf(strsai) > -1) {
        str = str.replace(strsai, strentra);
    }
    return str;
}


// --------- VAZIO --------- //
function vazio(valor) {
    if (valor.length > 0) {
        return false;
    } else {
        return true;
    }
}

// --------- APENAS NUMEROS --------- //
function apenasNumeros(campo, event) {
    var BACKSPACE = 8;
    var TAB = 0;
    var key;
    var tecla;
    CheckTAB = true;
    if (window.event) {
        tecla = event.keyCode;
    } else {
        tecla = event.which;
    }
    key = String.fromCharCode(tecla);
    if (tecla == TAB) {
        return true;
    }
    if (tecla == 13) {
        return false;
    }
    if (tecla == BACKSPACE) {
        return true;
    }
    if (tecla == 44) {//virgula
        return false;
    }
    var strValidos = "0123456789,";
    if (strValidos.indexOf(key) == -1) {
        return false;
    }
    return true;
}

function apenasNumerosComVirgula(campo, event) {
    var BACKSPACE = 8;
    var TAB = 0;
    var key;
    var tecla;
    CheckTAB = true;
    if (window.event) {
        tecla = event.keyCode;
    } else {
        tecla = event.which;
    }
    key = String.fromCharCode(tecla);
    if (tecla == TAB) {
        return true;
    }
    if (tecla == 13) {
        return false;
    }
    if (tecla == BACKSPACE) {
        return true;
    }
    
    var strValidos = "0123456789,";
    if (strValidos.indexOf(key) == -1) {
        return false;
    }
    
    if(campo.value.length > 0){
    	if(campo.value.substring(campo.value.length - 1, campo.value.length) == ',' && tecla == 44){
    		return false;
    	}
    }
    return true;
}

// --------- APLICA CPF/CNPJ --------- //
function aplicaCPFCNPJ(campo, vlr) {
    if (window.event) {
        nTecla = event.keyCode;
    } else {
        nTecla = event.which;
    }
    if ((nTecla == 0) || (nTecla == 13) || (nTecla == 8)) {
        return true;
    }
    caracter = String.fromCharCode(nTecla);
    if (nTecla < 48 || nTecla > 57) {
		//event.returnValue=false;
        return false;
    }
    if (vlr.length == 3) {
		//	PJ
        vlr = vlr.substr(0, 2) + "." + vlr.substr(2, 1);
    } else {
        if (vlr.length == 5) {
		//	PF	
            vlr = vlr.substr(0, 2) + vlr.substr(3, 1) + "." + vlr.substr(4, 1);
        }
    }
    if (vlr.length == 7) {
		//	PJ
        vlr = vlr.substr(0, 2) + "." + vlr.substr(2, 1) + vlr.substr(4, 2) + "." + vlr.substr(6, 1);
    } else {
        if (vlr.length == 9) {
		//	PF
            vlr = vlr.substr(0, 2) + vlr.substr(3, 1) + "." + vlr.substr(4, 2) + vlr.substr(7, 1) + "." + vlr.substr(8, 1);
        }
    }
    if (vlr.length == 11) {
		//	PJ
        vlr = vlr.substr(0, 2) + "." + vlr.substr(2, 1) + vlr.substr(4, 2) + "." + vlr.substr(6, 1) + vlr.substr(8, 2) + "/" + vlr.substr(10, 1);
    } else {
        if (vlr.length == 13) {
		//	PF
            vlr = vlr.substr(0, 2) + vlr.substr(3, 1) + "." + vlr.substr(4, 2) + vlr.substr(7, 1) + "." + vlr.substr(8, 2) + vlr.substr(11, 1) + "-" + vlr.substr(12, 1);
        }
    }
    if (vlr.length == 16) {
		//	PJ
        vlr = vlr.substr(0, 2) + "." + vlr.substr(2, 1) + vlr.substr(4, 2) + "." + vlr.substr(6, 1) + vlr.substr(8, 2) + "/" + vlr.substr(10, 1) + vlr.substr(12, 3) + "-" + vlr.substr(16, 2);
    }
    campo.value = vlr;
}



// --------- FORMATA CNPJ --------- //
function formataCNPJ(cnpj) {
    var formatted = cnpj.substr(0, 2) + ".";
    formatted = formatted + cnpj.substr(2, 3) + ".";
    formatted = formatted + cnpj.substr(5, 3) + "/";
    formatted = formatted + cnpj.substr(8, 4) + "-";
    formatted = formatted + cnpj.substr(12, 2);
    return formatted;
}

// --------- ADICIONA DECIMAL --------- //
function adicionaDecimal(valor) {
    if ((valor.length == 1) || (valor.length == 2)) {
        valor = valor + ",00";
        return valor;
    } else {
        return valor;
    }
}

//--------- FORMATA MOEDA --------- //
function formataMoedaNegativo(campo, tammax, event) {
    if (window.event) {
        nTecla = event.keyCode;
    } else {
        nTecla = event.which;
    }
    if ((nTecla == 0) || (nTecla == 13) || (nTecla == 8)) {
        return true;
    }
    caracter = String.fromCharCode(nTecla);
    if (caracter == ",") {
        if (campo.value.indexOf(",") == -1) {
			// permite que a virgula seja digitada se houver pelo menos dois espa?os livres
            if ((tammax - campo.value.length) >= 2) {
                return true;
            }
        }
    }
    if(nTecla == 45){
       	// Aceita negativo
    	
    }else if (nTecla < 48 || nTecla > 57) {
		//event.returnValue=false;
        return false;
    }
    return true;
}


// --------- FORMATA MOEDA --------- //
function formataMoeda(campo, tammax, event) {
    if (window.event) {
        nTecla = event.keyCode;
    } else {
        nTecla = event.which;
    }
    if ((nTecla == 0) || (nTecla == 13) || (nTecla == 8)) {
        return true;
    }
    caracter = String.fromCharCode(nTecla);
    if (caracter == ",") {
        if (campo.value.indexOf(",") == -1) {
			// permite que a virgula seja digitada se houver pelo menos dois espa?os livres
            if ((tammax - campo.value.length) >= 2) {
                return true;
            }
        }
    }
    if (nTecla < 48 || nTecla > 57) {
		//event.returnValue=false;
        return false;
    }
    return true;
}

// --------- FORMATA DATA --------- //
function formataData(data, event) {
    var nTecla;
    if (window.event) {
        nTecla = event.keyCode;
    } else {
        nTecla = event.which;
    }
    if ((nTecla == 8) || (nTecla == 0)) {
        return true;
    }
    if (apenasNumeros(null, event)) {
        if (data.value.length == 2 || data.value.length == 5) {
            data.value += "/";
        }
        if (nTecla < 48 || nTecla > 57) {
            return false;
        }
    } else {
        return false;
    }
    
}

// --------- DATA DE HOJE ----------- //
function dataHoje() {
    var hoje;
    with (new Date()) {
    	var dia = new String(getDate());
    	var diaFormatado = dia.length==1?"0"+dia:dia;
    	
    	var mes = new String((getMonth() + 1));
 		var mesFormatado = mes.length==1?"0"+mes:mes;
 		
        hoje = diaFormatado + "/" + mesFormatado + "/" + getFullYear();
    }
    return hoje;
}

function validaData(campo){
	var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
	if (campo.value.match(expReg)){
		var dia = campo.value.substring(0,2);
		var mes = campo.value.substring(3,5);
		var ano = campo.value.substring(6,10);
		
		if((mes==4 || mes==6 || mes==9 || mes==11) && dia > 30){
			campo.value = "";
			return false;
		} else{
			if(ano%4!=0 && mes==2 && dia>28){
				campo.value = "";
				return false;
			} else{
				if(ano%4==0 && mes==2 && dia>29){
					campo.value = "";
					return false;
				} else{ 
					return true;
				}
			}
		}
	} else {
		campo.value = "";
		return false;
	}
}

// --------- COMPARA DATAS --------- //
// Resultado:
//		-1 = data1 menor que data2
//		 0 = data1 data2 sao iguais
//		 1 = data1 maior que data2
//
function comparaDatas(data1, data2, igual) {
    var dia1, dia2;
    var mes1, mes2, mesTemp;
    var ano1, ano2;
    dia1 = parseFloat(data1.substr(0, data1.indexOf("/")));
    mes1 = parseFloat(data1.substr(data1.indexOf("/") + 1, data1.lastIndexOf("/") - data1.indexOf("/") - 1));
    ano1 = parseFloat(data1.substr(data1.lastIndexOf("/") + 1, 4));

    dia2 = parseFloat(data2.substr(0, data2.indexOf("/")));
    mes2 = parseFloat(data2.substr(data2.indexOf("/") + 1, data2.lastIndexOf("/") - data2.indexOf("/") - 1));
    ano2 = parseFloat(data2.substr(data2.lastIndexOf("/") + 1, 4));

	if (ano1 > ano2) return 1;
	else if (ano1 < ano2) return -1;
	else if (mes1 > mes2) return 1;
	else if (mes1 < mes2) return -1;
	else if (dia1 > dia2) return 1;
	else if (dia1 < dia2) return -1;
	else return 0;
}

function validaDiferenteZero(condicao, label, field){
	return validaErro(condicao, label, field, " deve ser maior que zero.");
}

function validaErroObrigatorio(condicao, label, field){
	return validaErro(condicao, label, field, " obrigat&oacute;rio(a).");
}
function validaErroInvalido(condicao, label, field){
	return validaErro(condicao, label, field, " inv&aacute;lido(a).");
}
function validaErro(condicao, label, field, erro){
	var retorno = 1;

	if(document.all[label]){
		if(condicao){
			exibeMsgErro(label, field + erro);
			retorno = -1;
		}else{
			document.all[label].innerHTML = "";
			retorno = 1;
		}
	}
	
	return retorno;
}
function exibeMsgErro(label, msg){
	document.all[label].innerHTML = "<span class='erro'>" + msg + "</span>";
}


function validaPesquisa(condicao,label,quantidade){
	if(quantidade == null){
		quantidade = 3;
	}
	return validaErro(condicao, label, "Mínimo de " + quantidade, " letras ou números para pesquisar");
}

function validaQuantidadeCaracter(condicao,label,quantidade){
	if(quantidade == null){
		quantidade = 3;
	}
	return validaErro(condicao, label, "Mínimo de " + quantidade, " letras ou números para cadastrar");
}

function retornaValorFormatado(valor){
	return retornaValorFormatadoDecimais(valor, 2);
}
function retornaValorFormatado(valor, decimais){
	if(valor != null){	
		try{
			if((decimais == null) || (decimais == '')){
				decimais = 2; // Duas casas decimais 
			}
			valor = valor.toFixed(decimais);
		}catch(e){}		
		
		var novoValor = new String(valor);
		var decimal = valor - parseInt(valor);
		
		novoValor = novoValor.replace(',', '@');
		novoValor = novoValor.replace('.', ',');
		novoValor = novoValor.replace('@', '.');
	}else{
		var novoValor = '0';
		var decimal = 0;
	}	

	if(decimal == 0){		
		novoValor = parseInt(novoValor) + ",00";
	}
	
	return novoValor
}


function validaCadastroBancario(numeroBanco,numeroAgencia,numeroConta,field) {         
        var validaBanco = true; 
       
        if (numeroBanco != '' || numeroAgencia != ''
                || numeroConta != '') {
          var cadastroBancario = 0;

         cadastroBancario += 
                  validaErroInvalido((numeroBanco == ""),"labelCadastroBancario",field);
                  
         if(cadastroBancario > 0){
			cadastroBancario += 
                  validaErroInvalido((numeroAgencia == ""),"labelCadastroBancario",field); 
           
	          if(cadastroBancario > 0){
	          cadastroBancario += 
                  validaErroInvalido((numeroConta == ""),"labelCadastroBancario",field);
                 }
	       } 
     
          validaBanco = false;

          if (cadastroBancario == 3) {
            validaBanco = true;
          }
        }
        return validaBanco;
      }
      
function showAguarde(){
	if(document.getElementById("aguardeSplashScreen")){
		if(document.getElementById("aguardeSplashScreen").style.visibility == "hidden"){
			document.getElementById("aguardeSplashScreen").style.visibility = "visible";	  
		}
	}
}

function hideAguarde(){
	if(document.getElementById("aguardeSplashScreen")){
		if(document.getElementById("aguardeSplashScreen").style.visibility == "visible"){
			document.getElementById("aguardeSplashScreen").style.visibility = "hidden";	  
		}
	}
}      

function retornaFormatoMoeda(valor,tammax ,decimal) {
	var novoValor = new String(valor);

   	for(var i=0; i <= novoValor.length; i++){
   
    	vr = Limpar(novoValor,"0123456789");

    	tam = vr.length;
    	dec=decimal

    	if ( tam <= dec ){ 
    		novoValor = vr ; 
    	}

    	if ( (tam > dec) && (tam <= 5) ){
    		novoValor = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; 
    	}
    	if ( (tam >= 6) && (tam <= 8) ){
    		novoValor = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
    	}
    	if ( (tam >= 9) && (tam <= 11) ){
    		novoValor = 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) ){
    		novoValor = 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) ){
    		novoValor = 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 ) ;
    	}
    }
    
    return novoValor;

} 

function Limpar(valor, validos) {
	// retira caracteres invalidos da string
	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;
}  

function bloqueiaCaracteres(event){
	var tecla = event.which;
	if(tecla==34||tecla==39||tecla==45||tecla==47||tecla==92){
		return false;
	}
	
	return true;
	
}

function bloqueiaAspaSimples(event){
	if(event.which==39){
		return false;
	}
	return true;
}


//**********VALIDA CPF OU CNPJ********************//

/**
 * PROTÓTIPOS:
 * método String.lpad(int pSize, char pCharPad)
 * método String.trim()
 *
 * String removeFormatacao(String pNum)
 * String formatCpfCnpj(String pCpfCnpj, boolean pUseSepar, boolean pIsCnpj)
 * String dvCpfCnpj(String pEfetivo, boolean pIsCnpj)
 * boolean isCpf(String pCpf)
 * boolean isCnpj(String pCnpj)
 * boolean isCpfCnpj(String pCpfCnpj)
 */


NUM_DIGITOS_CPF  = 11;
NUM_DIGITOS_CNPJ = 14;
NUM_DGT_CNPJ_BASE = 8;


/**
 * Adiciona método lpad() à classe String.
 * Preenche a String à esquerda com o caractere fornecido,
 * até que ela atinja o tamanho especificado.
 */
String.prototype.lpad = function(pSize, pCharPad)
{
	var str = this;
	var dif = pSize - str.length;
	var ch = String(pCharPad).charAt(0);
	for (; dif>0; dif--) str = ch + str;
	return (str);
} //String.lpad


/**
 * Adiciona método trim() à classe String.
 * Elimina brancos no início e fim da String.
 */
String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim


/**
 * Formata a string fornecida como CNPJ ou CPF, adicionando zeros
 * à esquerda se necessário e caracteres separadores, conforme solicitado.
 * @param String pCpfCnpj
 * 	String fornecida para ser formatada.
 * @param boolean pUseSepar
 * 	Indica se devem ser usados caracteres separadores (. - /).
 * @param boolean pIsCnpj
 * 	Indica se a string fornecida é um CNPJ.
 * 	Caso contrário, é CPF. Default = false (CPF).
 * @return String de CPF ou CNPJ devidamente formatada.
 */
function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	if (pUseSepar==null) pUseSepar = true;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var numero = removeFormatacao(pCpfCnpj);

	numero = numero.lpad(maxDigitos, '0');
	if (!pUseSepar) return numero;

	if (pIsCnpj)
	{
		reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
	}
	else
	{
		reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		numero = numero.replace(reCpf, "$1.$2.$3-$4");
	}
	return numero;
} //formatCpfCnpj


/**
 * Calcula os 2 dígitos verificadores para o número-efetivo pEfetivo de
 * CNPJ (12 dígitos) ou CPF (9 dígitos) fornecido. pIsCnpj é booleano e
 * informa se o número-efetivo fornecido é CNPJ (default = false).
 * @param String pEfetivo
 * 	String do número-efetivo (SEM dígitos verificadores) de CNPJ ou CPF.
 * @param boolean pIsCnpj
 * 	Indica se a string fornecida é de um CNPJ.
 * 	Caso contrário, é CPF. Default = false (CPF).
 * @return String com os dois dígitos verificadores.
 */
function dvCpfCnpj(pEfetivo, pIsCnpj)
{
	if (pIsCnpj==null){ 
	pIsCnpj = false;
	}
	var i, j, k, soma, dv;
	var cicloPeso = pIsCnpj? NUM_DGT_CNPJ_BASE: NUM_DIGITOS_CPF;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var calculado = formatCpfCnpj(pEfetivo, false, pIsCnpj);
	calculado = calculado.substr(2, maxDigitos);
	var result = "";

	for (j = 1; j <= 2; j++)
	{
		k = 2;
		soma = 0;
		for (i = calculado.length-1; i >= 0; i--)
		{
			soma += (calculado.charAt(i) - '0') * k;
			k = (k-1) % cicloPeso + 2;
		}
		dv = 11 - soma % 11;
		if (dv > 9) {
		dv = 0;
		calculado += dv;
		result += dv
		}
	}

	return result;
} //dvCpfCnpj


/**
 * Testa se a String pCpf fornecida é um CPF válido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCpf
 * 	String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF válido.
 */
function isCpf(pCpf)
{
	var numero = formatCpfCnpj(pCpf, false, false);
	var base = numero.substr(0, numero.length - 2);
	var digitos = dvCpfCnpj(base, false);
	var algUnico, i;

	
	/* Não serão considerados válidos os seguintes CPF:
	 * 000.000.000-00, 111.111.111-11, 222.222.222-22, 333.333.333-33, 444.444.444-44,
	 * 555.555.555-55, 666.666.666-66, 777.777.777-77, 888.888.888-88, 999.999.999-99.
	 */	
	algUnico = true;
	for (i=1; i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}	
	return (!algUnico);
	
	// Valida dígitos verificadores	
	if (numero != base + digitos) {	
	return false;
	}
} //isCpf


/**
 * Testa se a String pCnpj fornecida é um CNPJ válido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCnpj
 * 	String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CNPJ válido.
 */
function isCnpj(pCnpj)
{
	var numero = formatCpfCnpj(pCnpj, false, true);
	var base = numero.substr(0, NUM_DGT_CNPJ_BASE);
	var ordem = numero.substr(NUM_DGT_CNPJ_BASE, 12);
	var digitos = dvCpfCnpj(base + ordem, true);
	var algUnico;

	// Valida dígitos verificadores
	if (numero != base + ordem + digitos){ 
		return false;
	}

	/* Não serão considerados válidos os CNPJ com os seguintes números BÁSICOS:
	 * 11.111.111, 22.222.222, 33.333.333, 44.444.444, 55.555.555,
	 * 66.666.666, 77.777.777, 88.888.888, 99.999.999.
	 */
	algUnico = numero.charAt(0) != '0';
	for (i=1; i<NUM_DGT_CNPJ_BASE; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	if (algUnico){
	 return false;
	 }

	/* Não será considerado válido CNPJ com número de ORDEM igual a 0000.
	 * Não será considerado válido CNPJ com número de ORDEM maior do que 0300
	 * e com as três primeiras posições do número BÁSICO com 000 (zeros).
	 * Esta crítica não será feita quando o no BÁSICO do CNPJ for igual a 00.000.000.
	 */
	if (ordem == "0000"){ 
	return false;
	}
	return (base == "00000000"
		|| parseInt(ordem, 10) <= 300 || base.substr(0, 3) != "000");
} //isCnpj


/**
 * Testa se a String pCpfCnpj fornecida é um CPF ou CNPJ válido.
 * Se a String tiver uma quantidade de dígitos igual ou inferior
 * a 11, valida como CPF. Se for maior que 11, valida como CNPJ.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCpfCnpj
 * 	String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF ou CNPJ válido.
 */
function isCpfCnpj(pCpfCnpj)
{
	var numero = pCpfCnpj.replace(/\D/g, "");
	if (numero.length > NUM_DIGITOS_CPF){
		return isCnpj(pCpfCnpj);
		}
	else{
		return isCpf(pCpfCnpj);
		}
}

/**
 * Verifica o tamanho do campo CPF e CNPJ
 */

function verificaTamanhoCnpj(valor){
	if(valor.length < 18 ){
		return false;
	}
}

function verificaTamanhoCpf(valor){
	if(valor.length < 14){
		return false;
	}
}

//VALIDACAO DE EMAIL
function validaEmail(obj, required) {
	if (required == undefined)required=true; //se não for especificado, assume que é obrigatório
	if (obj == null)return(!required); //se o e-mail for nulo mas não for obrigatório retorna 1
	if (obj.value.length==0)return(!required); //se o campo estiver vazio mas não for obrigatório retorna 1
	return(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,3})+$/.test(obj.value));//retorna true se a regra for obdecida
}


function exibeSplash(){	
	splashIframe(true);	
	document.getElementById("aguardeSplashScreen").style.visibility = "visible";
	if(document.getElementById("frame")){
		document.getElementById('frame').style.visibility = "visible";		
	}
}

function exibeSplashSemFrame(){
	document.all.aguardeSplashScreen.style.visibility = "visible";	
}

function exibeIframeInicial(state) {
   var DivRef = document.getElementById('aguardeSplashScreen');
   var IfrRef = document.getElementById('rodape');	
   if(state){
    DivRef.style.display = "block";
    if(IfrRef){    
	    IfrRef.style.width = "100%";
	    IfrRef.style.height = "100%";	    	    
	    //IfrRef.style.top = DivRef.style.top;
	    //IfrRef.style.left = DivRef.style.left;
	    IfrRef.style.zIndex = DivRef.style.zIndex - 1;
	    IfrRef.style.display = "block";	    
	}
    //IfrRef.style.-moz-opacity: = "0.1";
    //IfrRef.style.position: "absolute";
    //IfrRef.style.visibility = "visible";
   }else{
    if(DivRef){    
	    DivRef.style.display = "none";
	}
	
    if(IfrRef){    
	    IfrRef.style.display = "none";
	}
   }
}

function splashIframe(state){
   var DivRef;
   var IfrRef;
   
   if(document.getElementById('aguardeSplashScreen'))
	   DivRef = document.getElementById('aguardeSplashScreen');
   if(parent.document.getElementById('aguardeSplashScreen'))
	   DivRef = parent.document.getElementById('aguardeSplashScreen');
   
	if(document.getElementById('rodape'))	
		IfrRef = document.getElementById('rodape');	
	if(parent.document.getElementById('rodape'))	
		IfrRef = parent.document.getElementById('rodape');	
   	
   if(state){
    DivRef.style.display = "block";
    if(IfrRef){    
	    IfrRef.style.width = "100%";
	    IfrRef.style.height = "100%";	
	    IfrRef.style.zIndex = DivRef.style.zIndex - 1;
	    IfrRef.style.display = "block";	    
	}
   }else{
    if(DivRef){    
	    DivRef.style.display = "none";
	}
	
    if(IfrRef){    
	    IfrRef.style.display = "none";
	}
   }
}

function executaLink(link){
	exibeSplash();
	window.location = link;
}

function escondeSplash(){
	//clearInterval(intervalo);
	splashIframe(false);
		
	if(document.getElementById("aguardeSplashScreen"))
		document.getElementById("aguardeSplashScreen").style.visibility = "hidden";
	if(parent.document.getElementById("aguardeSplashScreen"))
		parent.document.getElementById("aguardeSplashScreen").style.visibility = "hidden";
	
	if(document.getElementById("frame"))
		document.getElementById('frame').style.visibility = "hidden";		
	if(parent.document.getElementById("frame"))
		parent.document.getElementById('frame').style.visibility = "hidden";		
	
}

function formataValorMoeda(valor) {
	// ================================================================================	=====
	// Para fazer com que o resultado "0000.00" se torne "0.000,00"
	// ================================================================================	=====
	var indPontoDec; // localizacao do ponto decimal
	var valorLimpo = ""; // valor filtrado (apenas numeros e virgula)
	var cont = 0; // contador
	var indPonto = 0; // localizacao do último ponto
	var indVirgula = 0; // localizacao da última virgula
	var numero = "0123456789"; // domínio de dígitos válidos
	var qtPonto = 0; // qtde de pontos de milhar
	var qtResto = 0; // resto de indPontoDec / 3
	var limite = 0; // limite da colocação do ponto de milhar
	
	// ================================================================================	=====
	// descobre qual o último separador que está sendo utilizado
	// ================================================================================	=====
	valor = new String(valor);
	indVirgula = valor.lastIndexOf(',');
	indPonto = valor.lastIndexOf('.');
	if (indVirgula == indPonto)
		indPontoDec = -1;
	else if (indVirgula > indPonto)
		indPontoDec = indVirgula;
	else
		indPontoDec = indPonto;
	
	// ================================================================================	=====
	// limpa dígitos não numéricos do valor
	// ================================================================================	=====
	for (cont=0; cont < valor.length; cont++){
		if (numero.indexOf(valor.charAt(cont)) != -1)
		valorLimpo += valor.charAt(cont);
		// substitui ponto decimal por vírgula
		if (cont+1 == indPontoDec){
			cont++;
			valorLimpo += ',';
		}else if ((cont==0) && (indPontoDec==0))
			valorLimpo += ',';
	}
	
	if (valorLimpo.indexOf(",") == -1)
		valorLimpo += ",00";
	if (valorLimpo.indexOf(",") == valorLimpo.length-1)
		valorLimpo += "00";
	if (valorLimpo.indexOf(",") == valorLimpo.length-2)
		valorLimpo += "0";
	
	// ================================================================================	=====
	// retira zeros à esquerda
	// ================================================================================	=====
	while (valorLimpo.charAt(0)=='0')
		valorLimpo = valorLimpo.substring(1, valorLimpo.length);
	
	// ================================================================================	=====
	// transforma ",xx" em "0,xx"
	// ================================================================================	=====
	if (valorLimpo.charAt(0)==',')
		valorLimpo = '0' + valorLimpo;
	
	// ================================================================================	=====
	// coloca separação de milhar
	// ================================================================================	=====
	indPontoDec = valorLimpo.lastIndexOf(',');
	qtPonto = Math.floor(indPontoDec/3);
	qtResto = indPontoDec%3;
	if (qtResto==0)
		limite=1;
	else
		limite=0;
	if(valor != ""){
		for (cont=qtPonto-1; cont >= limite; cont--)
			valorLimpo = valorLimpo.substring(0, qtResto + cont*3) + valorLimpo.substring(qtResto + cont*3, valorLimpo.length);
	}
	
	// ================================================================================	=====
	// Deixa só duas casas depois da vírgula
	// ================================================================================	=====
	if((valor != "") && (valorLimpo != "")){
		while (valorLimpo.indexOf(",") != valorLimpo.length-3)
			valorLimpo = valorLimpo.substring(0, valorLimpo.length-1);
	}
	
	return valorLimpo;
} 

function exibeJanela(link, altura, largura){
    var top = (screen.height - altura) / 2;
	var left = (screen.width - largura) / 2;

  	window.open(link, "" , 'width='+largura+',height='+altura+',left='+left+',top='+top
  		+",toolbar=no,location=no,directories=0,status=0,menubar=0,scrollbars=1,resizable=1");
}

// --------- APENAS NUMEROS E LETRAS --------- //
function apenasNumerosLetrasSemAcentos(campo, event, tipo) {
    var BACKSPACE = 8;
    var TAB = 0;
    var key;
    var tecla;
    CheckTAB = true;
    if (window.event) {
        tecla = event.keyCode;
    } else {
        tecla = event.which;
    }
    key = String.fromCharCode(tecla);
    if (tecla == TAB) {
        return true;
    }
    if (tecla == 13) {
        return false;
    }
    if (tecla == BACKSPACE) {
        return true;
    }
    var strValidos = "0123456789";
    if(tipo == 0){
       	strValidos = strValidos + "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";

    }else if(tipo == 1){
	   	strValidos = strValidos + "QWERTYUIOPASDFGHJKLZXCVBNM";
	   	
    }else if(tipo == 2){
    	strValidos = strValidos + "qwertyuiopasdfghjklzxcvbnm";
    	
    }
    	
    if (strValidos.indexOf(key) == -1) {
        return false;
    }
    return true;
}

// Desabilita tecla F5
function disableKey(event) {
  if (!event) event = window.event;
  if (!event) return;

  var keyCode = event.keyCode ? event.keyCode : event.charCode;

  //window.status = keyCode;
  //alert(keyCode);
  
  // keyCode for F% on Opera is 57349 ?!
  
  if (keyCode == 116) {
   window.status = "F5 key detected! Attempting to disabling default response.";
   window.setTimeout("window.status='';", 2000);

   // Standard DOM (Mozilla):
   if (event.preventDefault) event.preventDefault();

   //IE (exclude Opera with !event.preventDefault):
   if (document.all && window.event && !event.preventDefault) {
     event.cancelBubble = true;
     event.returnValue = false;
     event.keyCode = 0;
   }

   return false;
  }
}
function setEventListener(eventListener) {	
  if (document.addEventListener) document.addEventListener('keypress', eventListener, true);
  else if (document.attachEvent) document.attachEvent('onkeydown', eventListener);
  else document.onkeydown = eventListener;
  
  if (!document.getElementById) return;
  var el = document.getElementById("Msg");
  if (el) el.innerHTML = "Event handler added.";
}


function unsetEventListener(eventListener) {
  if (document.removeEventListener) document.removeEventListener('keypress', eventListener, true);
  else if (document.detachEvent) document.detachEvent('onkeydown', eventListener);
  else document.onkeydown = null;
  
  if (!document.getElementById) return;
  var el = document.getElementById("Msg");
  if (el) el.innerHTML = "Event handler removed.";
}


//Function travaTeclaF5
//ESSAS SERÃO AS TECLAS DESABILITADAS
//var asciiF2        = 113;
//var asciiF3        = 114;
//var asciiF4        = 115;
var asciiF5        = 116;
//var asciiF6        = 117;
//var asciiF11        = 122;
//var asciiF12        = 123;
//var asciiF11        = 122;

if(document.all){ //ie has to block in the key down
    document.onkeydown = onKeyPress;
}else if (document.layers || document.getElementById){ //NS and mozilla have to block in the key press
    document.onkeypress = onKeyPress;
}

function onKeyPress(evt) {
    window.status = '';
    //get the event object
    var oEvent = (window.event) ? window.event : evt;
  
    //hmmm in mozilla this is jacked, so i have to record these seperate
    //what key was pressed
    var nKeyCode =  oEvent.keyCode ? oEvent.keyCode : oEvent.which ? oEvent.which : void 0;
    var bIsFunctionKey = false;

    //hmmm in mozilla the keycode would contain a function key ONLY IF the charcode IS 0  
    //else key code and charcode read funny, the charcode for 't'
    //returns 116, which is the same as the ascii for F5
    //SOOO,... to check if a the keycode is truly a function key,
    //ONLY check when the charcode is null OR 0, IE returns null, mozilla returns 0
    if(oEvent.charCode == null || oEvent.charCode == 0){
    	//bIsFunctionKey = (nKeyCode >= asciiF2 && nKeyCode <= asciiF12)
        bIsFunctionKey = (nKeyCode == asciiF5)

    }
  
    //convert the key to a character, makes for more readable code
    var sChar = String.fromCharCode(nKeyCode).toUpperCase();

    //get the active tag that has the focus on the page, and its tag type
    var oTarget = (oEvent.target) ? oEvent.target : oEvent.srcElement;
    var sTag = oTarget.tagName.toLowerCase();
    var sTagType = oTarget.getAttribute("type");
  
    var bAltPressed = (oEvent.altKey) ? oEvent.altKey : oEvent.modifiers & 1 > 0;
    var bShiftPressed = (oEvent.shiftKey) ? oEvent.shiftKey : oEvent.modifiers & 4 > 0;
    var bCtrlPressed = (oEvent.ctrlKey) ? oEvent.ctrlKey : oEvent.modifiers & 2 > 0;
    
    var bRet = true; //assume true as that will be the case most times
    
    if(sTagType != null){sTagType = sTagType.toLowerCase();}

    //bloqueia o enter no input
    if  (nKeyCode == 13 && (sTag == "textarea" || (sTag == "input" && (sTagType == "text" || sTagType == "password")))){
    	bRet = false;
    //bloqueia o F5 no input	
    //}else if(nKeyCode == 116 && (sTag == "textarea" || (sTag == "input" && (sTagType == "text" || sTagType == "password")))){	
    	//bRet = false; 	
    //permite digitar no dentro do input
    } else if(sTag == "textarea" || (sTag == "input" && (sTagType == "text" || sTagType == "password"))){	
    	return true;
    // block alt + left or right arrow, atalho para voltar e avançar pagina no browser. **não garanto que esteja funcionando	        
    } else if(bAltPressed && (nKeyCode == 37 || nKeyCode == 39)){ 
        bRet = false;
    // Permite copiar, colar, recortar e selecionar tudo
    }else if(bCtrlPressed && (sChar == 'A' || sChar == 'C' || sChar == 'V' || sChar == 'X')){ 
        bRet = true;
    //bloqueia F5
    }else if(bIsFunctionKey){ 
        bRet = false;
    }
  
    if(!bRet){
        try{
            oEvent.returnValue = false;
            oEvent.cancelBubble = true;

            if(document.all){ //IE
                oEvent.keyCode = 0;
            }else{ //NS
                oEvent.preventDefault();
                oEvent.stopPropagation();
            }
            //window.status = msg;
  
        }catch(ex){
            
        }
    }
    return bRet;
}

function apenasNumerosBarra(campo, event) {
    var BACKSPACE = 8;
    var TAB = 0;
    var key;
    var tecla;
    CheckTAB = true;
    if (window.event) {
        tecla = event.keyCode;
    } else {
        tecla = event.which;
    }
    key = String.fromCharCode(tecla);
    if (tecla == TAB) {
        return true;
    }
    if (tecla == 13) {
        return false;
    }
    if (tecla == BACKSPACE) {
        return true;
    }
    if(tecla == 47){
    	return true;
    }
    var strValidos = "0123456789,";
    if (strValidos.indexOf(key) == -1) {
        return false;
    }
    return true;
}

function converteMinuscula(event){
    if (window.event) {
        key = event.keyCode;
    } else {
        key = event.which;
    }

	tecla = String.fromCharCode(key);
	tecla = tecla.toLowerCase();

	caracteres = "1234567890 abcdefghijklmnopqrstuvwxyz!@#$%&*()_+{}?:><,.;/][=-";
	if (caracteres.toLowerCase().indexOf(tecla) > -1){
	
	}else{
		tecla = "";
	}

    if (window.event) 
		window.event.keyCode = String(tecla).charCodeAt(0);
	else
		return String(tecla).charCodeAt(0);
}

function converteMaiuscula(event){
    if (window.event) {
        key = event.keyCode;
    } else {
        key = event.which;
    }

	tecla = String.fromCharCode(key);
	tecla = tecla.toUpperCase();

	caracteres = "1234567890 abcdefghijklmnopqrstuvwxyz!@#$%&*()_+{}?:><,.;/][=-";
	if (caracteres.toUpperCase().indexOf(tecla) > -1){
	
	}else{
		tecla = "";
	}

    if (window.event) {
		window.event.keyCode = String(tecla).charCodeAt(0);
	}else{
		return String(event.which).toUpperCase();
	}
}

function capsDetect( e ) {
	if(document.all.capsMsg){
		document.all.capsMsg.innerHTML = '';
	}

    if (window.event) {
        keypress = e.keyCode;
    } else {
        keypress = e.which;
    }

   	var strValidos = "qwertyuiopasdfghjklzxcvbnm";
    key = String.fromCharCode(keypress);

    if (strValidos.indexOf(key) > -1) {

		if( !e ) { e = window.event; } if( !e ) { capsMsg( false ); return; }
		//what (case sensitive in good browsers) key was pressed
		var theKey = e.which ? e.which : ( e.keyCode ? e.keyCode : ( e.charCode ? e.charCode : 0 ) );
		//was the shift key was pressed
		var theShift = e.shiftKey || ( e.modifiers && ( e.modifiers & 4 ) ); //bitWise AND
		//if upper case, check if shift is not pressed. if lower case, check if shift is pressed
		capsMsg( ( theKey > 64 && theKey < 91 && !theShift ) || ( theKey > 96 && theKey < 123 && theShift ) );
	}
}

function capsMsg( oC ) {
	if( typeof( capsError ) != 'string' ) { 
		if( !oC ){
			if(document.all.capsMsg){
				document.all.capsMsg.innerHTML = '<font color="BLUE">ATENÇÃO:\n\nCaps Lock está desativado!</font>';
			}
		}
	}
}

function atualizaDiv(id){
	if(id == "combo"){
		document.getElementById("combo").style.display = "inline";
	    document.getElementById("intervalo").style.display = "none";
	    document.all.grupoProdutoDe.value = "";
	    document.all.grupoProdutoAte.value = "";
	    document.getElementById("labelErroGrupoProdutoDe").innerHTML = "";
	    document.getElementById("labelErroGrupoProdutoAte").innerHTML = "";
	}else{
		document.getElementById("combo").style.display = "none";
	    document.getElementById("intervalo").style.display = "inline";
	    document.all.idGrupoProduto.value = "0";
	}
}

function atualizaDivGenerico(tipo, de, ate, labelErroDe, labelErroAte, id){
	if(tipo == "combo"){
		document.getElementById("combo").style.display = "inline";
	    document.getElementById("intervalo").style.display = "none";
	    document.all(de).value = "";
	    document.all(ate).value = "";
	    document.getElementById(labelErroDe).innerHTML = "";
	    document.getElementById(labelErroAte).innerHTML = "";
	}else{
		document.getElementById("combo").style.display = "none";
	    document.getElementById("intervalo").style.display = "inline";
	    document.all(id).value = "0";
	}
}

function validaGrupoIntervalo(){
	var errosGrupoIntervalo = 0;	

	if(document.getElementById("grupoIntervalo").checked){
		errosGrupoIntervalo += validaErroObrigatorio((document.all.grupoProdutoDe.value == ""),
			"labelErroGrupoProdutoDe", "De");

		errosGrupoIntervalo += validaErroObrigatorio((document.all.grupoProdutoAte.value == ""),
			"labelErroGrupoProdutoAte", "Até");
	}else{
		errosGrupoIntervalo += 2;
	}
	
	return errosGrupoIntervalo;

}


function montaMiniAguarde(){
	var aguarde = '<P align="CENTER" STYLE="background-color:transparent">'
			+'	<BR>'
			+'	<TABLE BGCOLOR="RED" BORDER="1" HEIGHT=70 WIDTH=380>'
			+'		<TR>'
			+'			<TD BGCOLOR="#FFF7E3" ALIGN="CENTER" VALIGN="MIDDLE">'
			+'				<FONT FACE="Helvetica,Verdana,Arial" SIZE=3 COLOR="RED">'
			+'					<BLINK>'
			+'						<B>Aguarde, processando...</B>'
			+'                       &nbsp;'
			+'					<img src="/house/jsp/img/progressBar.gif">'
			+'					</BLINK>'
			+'				</FONT>'
			+'			</TD>'
			+'		</TR>'
			+'	</TABLE>'
			+'</P>';
			
	return aguarde;
}

function desativaBotaoTemp(nome){
	if(document.all(nome)){
		document.all(nome).disabled = true;	
		window.setTimeout('ativarBotao("'+nome+'");', 1500);	
	}
}

function ativarBotao(nome){
	document.all(nome).disabled = false
}

function trocaDivAguarde(nomeDiv){
	if(document.getElementById(nomeDiv)){
		document.getElementById(nomeDiv).innerHTML = montaMiniAguarde();
	}
}

//Função que insere zero informando a quantidade e qual o lado a ser inserido
function preencheZero( numero , digitos , esquerda){	

 for (i=1; i<digitos; i++){
	if(esquerda){
  		numero = "0" + numero;
  	}else{
  		numero = numero + "0";  		
  	}	
 }
 
  return numero;
}

function aceitaLetras(campo, event, letras) {
    if (window.event) {
        nTecla = event.keyCode;
    } else {
        nTecla = event.which;
    }
    if ((nTecla == 0) || (nTecla == 13) || (nTecla == 8)) {
        return true;
    }
    caracter = String.fromCharCode(nTecla);
    if(letras.indexOf(caracter) == -1){
        return false;
    }
    return true;
}


function teclaEnter(event){
    if (window.event) {
        tecla = event.keyCode;
    } else {
        tecla = event.which;
    }
    if (tecla == 13) {
        return true;
    }else {
    	return false;
    }
}

function executeOnEnter(campo, event, rotina){
	if(teclaEnter(event)){
		eval(rotina);
	}
}

function tabOnEnter(e){
	var charCode = (e.which) ? e.which : e.keyCode;
	if (charCode == 13){
		if (e.which){
			e.which = 9;
		}else{
			e.keyCode = 9;
		}
	}
}

function validaPeriodoLancamento(periodo){		
	FaixaComissaoAjax.verificaPeriodoLancamento(preencheMensagemPeriodo, periodo);

}

function procuraTextoComboBox(campo, lista) {
	procuraValorComboBox(campo.value, lista);
}
	
function procuraValorComboBox(input, lista) {
  var output=lista.options;
  if(input.length ==1){
	 input = input + " ";
  }else if(input.length ==2){
	 input = input + " ";
  }else if(input.length ==3){
	 input = input + " ";
  }  
  

	if(input.length > 0){
	  for(var i=0;i<output.length;i++) {
	    if(output[i].text.indexOf(input)==0){
	      output[i].selected=true;
		}
	    if(input == ''){
	      output[0].selected=true;
	    }
	  }
	}else{
		output[0].selected=true;
	}
	
  
}

function imprimirTela(){
	document.all("fundo").style.background="#FFFFFF";
	print();
	window.setTimeout("retornaPlanoFundo();", 1000);
}

function retornaPlanoFundo(){
	document.all("fundo").style.background="#06335F";
}

function retornaDecimalPonto(valor){
	if(valor == ''){
		valor = '0';
	}
	if(valor.indexOf(',') > -1){
		valor = valor.replace(',', '@');
		if(valor.indexOf(".") > -1){
			valor = valor.replace(/\./g, "");
		}
		valor = valor.replace('@', '.');
	}
	return parseFloat(valor);
}

function retornaValorComboBox(chave, lista) {
  var output=lista.options;

	if(chave.length > 0){
	  for(var i=0;i<output.length;i++) {
	    if(output[i].text.indexOf(chave+" ")==0){
	      return output[i].text;
		}
	    if(chave == ''){
	      return '';
	    }
	  }
	}else{
      return '';
	}	
}

function retornaValorInteiro(parametro){
	var valor = new String(parametro);
	if(valor.indexOf(".") > -1){
		var posicao = valor.lastIndexOf('.');					
		valor = valor.substring(0, posicao);
	}
	return valor;
}

function arredondaDecimal(valor){
	return (Math.round(valor*100))/100; 
}

function mostrarCombosTela(exibir){
	mostrarComponentesTela(exibir, "select")
}

function mostrarCamposTela(exibir){
	mostrarComponentesTela(exibir, "input")
}

function mostrarBotoesTela(exibir){
	mostrarComponentesTela(exibir, "button")
}

function mostrarControlesTela(exibir){
	mostrarComponentesTela(exibir, "select")
	mostrarComponentesTela(exibir, "input")
	mostrarComponentesTela(exibir, "button")
}

function mostrarComponentesTela(exibir, controle){
	var x = document.getElementsByTagName(controle);
	
	for (i = 0; i < x.length; i++) {
//	   x[i].style.display = "none";
		if(exibir){
			x[i].style.visibility = "visible";
		}else{
			x[i].style.visibility = "hidden";
		}
	}
}

function carregarTelaRelatorios(){
	executaLink("/house/relatoriosList.do");
}

/**
 * Elimina caracteres de formatação e zeros à esquerda da string de um número fornecido.
 * @param String pNum 
 * 		String de número fornecido para ser desformatado.
 * @return 
 * 		String de número desformatado.
 */
function removeFormatacao(pNum){
	return String(pNum).replace(/\D/g, "");
}

function formataMoedaBanco(campo,evento) {
	var tecla;
	if(window.event)
		tecla=event.keyCode;
	else 
		tecla=evento.which;

	vr = campo.value;
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );

	if (vr.length > 0) {
		vr = parseFloat(vr);
	} 
	if (isNaN(vr)) {
		campo.value = "0,00";
		return;
	}
	vr = vr + "";
	tam = vr.length;
	if (tecla != 8){ 
		tam = vr.length + 1 ; 
	}else{
		tam = tam - 1 ;
	}
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){ 
			if (tam == 1) {
				campo.value = '0,0' + vr ;
			} else if (tam == 2) {
			campo.value = '0,' + vr ;
		} else {
			campo.value = vr ; 
		}
		}else if ( (tam > 2) && (tam <= 5) ){
			campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; 
		}else if( (tam >= 6) && (tam <= 8) ){
			campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; 
		}else if ( (tam >= 9) && (tam <= 11) ){
			campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; 
		}else if ( (tam >= 12) && (tam <= 13) ){
			campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 1, tam ) ; 
		}else if ( (tam >= 15) && (tam <= 16) ){
			campo.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 ) ; 
		}
	}
}

function chConstraint(campo,e,tamanho){
	if(window.event)
		key=window.event.keyCode
	else if(e)
		key=e.which
	var tam = campo.value.length;
	if (tam > tamanho) {
		return false;
	}
	if (key == 8) {
		return true;
	}
	if (key <= 47 || key >= 58 ) {
		return false;
	}
	return true;
}

/**
 * Converte um número String (10.000.000,55) para formato double (10000000.55) 
 */
function convertStringToDoubleFormat(number) {
	for (i = 0; i < number.length; i++) {
		if (number.indexOf(".") > -1) {
			number = number.replace(".", "");
		}
	}
	number = number.replace(",", ".");

	return (number - 0); // -0 para converter a string para numero.
}

/**
 * Formata um numero formato double (10000000.55) para formato monetário (10.000.000,55)
 */
function convertDoubleToCurrencyFormat(num) {
	x = 0;

	if(num<0) {
	    num = Math.abs(num);
	    x = 1;
	}

	if(isNaN(num)) {
		num = "0";
	}

	cents = Math.floor((num * 100 + 0.5) % 100);
	num = Math.floor((num * 100 + 0.5) / 100).toString();

	if(cents < 10) {
		cents = "0" + cents;
	}

	for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
		num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
	}

	ret = num + ',' + cents;
	if (x == 1) {
		ret = ' - ' + ret;
	}

	return ret;
}

