/****************************************
 * Biblioteca javascript pbSistemas     *
 * versão 1.0                           *
 * site: www.pbsistemas.com.br			*
 * e-mail: pbsistemas@pbsistemas.com.br *
 ****************************************/

/*---------------------------------------------------------------------------------------------------------- */

var tam_popup = 0;

//detecta firefox
var isNS4 = (navigator.appName=="Netscape")?1:0;
//detecta internet explorer
var isIE  = (navigator.appName=="Netscape")?0:1; 
//detecta opera
function isOpera(){if((navigator.product == null)&&(navigator.userAgent.indexOf('Opera')>-1))return true;}

//Função para detectar a resolução do visitante e selecionar o arquivo CSS a ser executado
function detectaResolucao(id, css1, css2) {		
	if (screen.width == 800 && screen.height == 600) {
		document.getElementById(id).href = css2;
	} else if (screen.width == 1024 && screen.height == 768) {
		document.getElementById(id).href = css2;
	} else {
		document.getElementById(id).href = css2;
	}
}

/* --------------------------------------------------------------------------------------------------------- */

//Função para filtrar campos apenas númericos
function FiltraCampo(codigo) {
    var s = "";
	tam = codigo.length;
	for (i = 0; i < tam ; i++) {
		if (codigo.substring(i,i + 1) == "0" ||
           	codigo.substring(i,i + 1) == "1" ||
            codigo.substring(i,i + 1) == "2" ||
            codigo.substring(i,i + 1) == "3" ||
            codigo.substring(i,i + 1) == "4" ||
            codigo.substring(i,i + 1) == "5" ||
            codigo.substring(i,i + 1) == "6" ||
            codigo.substring(i,i + 1) == "7" ||
            codigo.substring(i,i + 1) == "8" ||
            codigo.substring(i,i + 1) == "9"  )
		 	s = s + codigo.substring(i,i + 1);
	}
	return s;
}

//Função para colocar o foco em um determinado elemento
function setFocus( destino ){
  obj = document.getElementById(destino);
  if ( obj )
  	try {
     obj.focus();
  	} catch(e){}
}

//Função para colocar o foco em um determinado elemento ao carregar a página
function focoInicial(id) {
	window.onload = function() {
		document.getElementById(id).focus();
	} 
}

//Função para modificar a barra de status
function setStatus(msg) {
    window.status = msg;
    return true;
}

//Função para validar campos númericos
function numero(evtKeyDown) {
    var nTecla = 0;
    if (document.all) {
        nTecla = evtKeyDown.keyCode;
    } else {
        nTecla = evtKeyDown.which;
    }
    if ( (nTecla> 47 && nTecla <58)
    || nTecla == 8 || nTecla == 127
    || nTecla == 0 || nTecla == 9  // 0 == Tab
    || nTecla == 13) { // 13 == Enter
        return true;
    } else {
        return false;
    }
} 

//Função para validar campos quantitativos (inteiros ou decimais)
function numero2(evtKeyDown) {
    var nTecla = 0;
    if (document.all) {
        nTecla = evtKeyDown.keyCode;
    } else {
        nTecla = evtKeyDown.which;
    }
    if ( (nTecla> 47 && nTecla <58)
    || nTecla == 8 || nTecla == 127
    || nTecla == 0 || nTecla == 9  // 0 == Tab
    || nTecla == 13 || nTecla == 46) { // 13 == Enter
        return true;
    } else {
        return false;
    }
}

//Função para mudar a cor de fundo dos campos
function mudaCor(e, cor) {
  e.style.background = cor;
}

//Função para formatar números decimais
function FormataDecimal(e) {
   s = e.value;
    if ( s == '0,00-'){
      s = '- ';
      }
    negativo = ( s.substring(0,1) == '-');

    // retirar os caractes inválidos
    s = FiltraCampo(e.value);
    // completar com zeros quando o valor for menor que  1,00
	
   
    if (s.length == 1) s = "000" + s
     // else if (s.length == 1) s = "00" + s
         else if (s.length == 2) s = "0" + s;
    // numero de caracteres digitados
	tam =  s.length;
	if ( tam > 2 ) {
        // a posição da vírgula será sempre o tamanho menos 2
        posvirg = tam - 2;
        // retirar os zeros da esquerda da parte inteira e colocar a virgula na parte decimal
        s = eval(s.substring(0,posvirg)) + "," + s.substring(posvirg);
        
        // colocar pontos de 3 em 3 digitos se a parte inteira ja tiver tamanho > 3
        parteInteira = s.substring(0,posvirg);
        if ( parteInteira.length > 3 )  {
           j = 0;
           r = '';
           // ler a parte inteira de traz para frente colocando os pontos e guardando em r
           for( i = parteInteira.length; i > 0 ; i-- ) {
              j++;
              if (j == 4) {
                 j = 1;
                 r = '.' + r;
                }
              r = parteInteira.substring(i-1,i) + r;
              }
           // devolver para o resultado a parte inteira formatada concatenada com a parte decimal
           s = r + s.substring(posvirg);
         }
        }
    if ( negativo ) {
         e.value = '-'+e.value+'';
         s = '-'+s+'';
         }
    e.value = s;
    return s;
}

/**** Funções para formatar datas ****/
function DataOk(e,mascara) {
var strDia="";
var strMes="";
var strAno="";
var Dia=0;
var Mes=0;
var Ano=0;
var Texto=""; //VALOR A SER TESTADO
var Msg=""; // MENSAGEM A SER EXIBIDA NA TELA SE HOUVER ERRO
var Erro = false;

Texto = FormataData(e,mascara); // COLOCAR AS BARRAS

if (Texto!="") {
   //EXISTE VALOR

   switch (mascara) {
    case 'dm':
    	Texto +='/2000';
    break;
    case 'my':
    	Texto ='01/' + Texto;
    break;
   }
   
   //window.status = Texto;
   // DATA ESTÁ DIGITADA INCOMPLETA
   if ( Texto.length < 10 && Texto.length != 8 ) {
      e.value = '';
      return true;
      }

   strDia = Texto.substring(0,2);
   strMes = Texto.substring(3,5);
   strAno = Texto.substring(6);


   Dia=parseInt(strDia,10);
   Mes=parseInt(strMes,10);
   Ano=parseInt(strAno,10);

   // colocar o ano com 4 digitos se o usuario informar com 2
   if ( Ano < 100 ) {
      if (Ano > 40 )
          Ano += 1900
      else
         Ano += 2000;
   }
   
   switch (mascara) {
    case 'dm':
    	e.value = strDia+'/'+strMes;
    	exemplo = 'Informe o dia e o mês. Ex. 01/10 01/08 20/05...';
    break;
    case 'my':
	   e.value = strMes+'/'+Ano;
    	exemplo = 'Informe o mês e ano. Ex. 10/2004 05/2002 01/2004...';
    break;
    default:
    	exemplo = '';
	   e.value = strDia+'/'+strMes+'/'+Ano;
   }

   if ((Dia<1) || (Dia>31) || isNaN(Dia)) {
      Msg = Msg + 'Dia '+Dia+' inválido\n';
      Erro = true;
      }
   if ((Mes<1) || (Mes>12) || isNaN(Mes)) {
      Msg = Msg + 'Mês '+Mes+' inválido\n';
      Erro = true;
      }
   if (isNaN(Ano)) {
      Msg = Msg + 'Ano '+Ano+' inválido\n';
      Erro = true;
      }
   if ((Dia>=31) && ((Mes==4) || (Mes==6) || (Mes==9) || (Mes==11))) {
      Msg = Msg + 'Dia inválido para este mês\n';
      Erro = true;
      }
   if (Mes==2) {
      //MES DE FEVEREIRO
      if (Dia>=30) {
         Msg = Msg + 'Dia inválido para fevereiro\n';
         Erro = true;
        }
      if ((Dia==29) && (((Ano % 4) != 0) || (((Ano % 100) == 0) && ((Ano % 400) != 0)))) {           Msg = Msg + 'Dia inválido para fevereiro. '+ Ano +' não é bisexto\n';
         Erro = true;
         }
      }
   }
  if ( Erro ) {
    alert(Msg + exemplo);
    e.focus();
    }
  return true;
}

function colocarMascara(field, _mascara, event) {
	var key ='';
	var aux='';
	var len=0;
	var i=0;
	var strCheck = '0123456789';
	var rcode = (window.Event) ? event.which : event.keyCode;
	// se trocar o evento onKeypress por onKeyUp, tem que diminuir 48 para achar o codigo certo.
	rcode-=48;
	aux=field.value;
	aux=retirarMascara(aux); 
	aux=mascara(_mascara,aux);
	if( (rcode < 1 ) || ( field.value.length >= _mascara.length )  ) {
		if( rcode < 0 ) {
			return false;
		}
	}
	key=String.fromCharCode(rcode);
	if(strCheck.indexOf(key)==-1) {
		key=String.fromCharCode(rcode+48);
		if(strCheck.indexOf(key)==-1) {
			i = field.value.toUpperCase().indexOf(key);
			aux = field.value.substr(0,i) + field.value.substr(i+1,1000);
			aux=mascara(_mascara,aux);
			field.value=aux;
			return false;
		}
	}
	field.value=aux;	
	field.value = aux.substr(0,_mascara.length);
	return false;
}

function FormataData(e,mascara) {
    var s = "";

    s = FiltraCampo(e.value);
    tam =  s.length;

    r = s.substring(0,2) + "/" + s.substring(2,4) + "/"+s.substring(4,8);
    if ( tam < 3 )
        s = r.substring(0,tam);
    else if ( tam < 5 )
        s = r.substring(0,tam+1);
    else
        s = r.substring(0,tam+2);
    e.value = s;
    return s;
}

function retirarMascara(val) {
	var strCheck = "'[](){}<>=+-*/_|\~`!?@#$%^&:;,.";
	var aux="";
	var i;
	
	for(i=0; i<val.length; i++) {
		if(strCheck.indexOf(val.charAt(i))==-1) {
			aux+=val.charAt(i);
		}
	}
	return aux;
}

function mascara(_mascara, val) {
	var i, mki;
	var aux="";
	
	for(i=mki=0; i<val.length; i++, mki++) {
		if(_mascara.charAt(mki)=='' || _mascara.charAt(mki)=='#' || _mascara.charAt(i)==val.charAt(i)) {
			aux+=val.charAt(i);
		} else {
			aux+=_mascara.charAt(mki)+val.charAt(i);
			mki++;
		}
	}
	return aux;
}

/**** Fim das funções para formatar datas ****/

/**** Funçoes para formatar CPF ****/

//Checa se o CPF é válido
function DvCpfOk(e,evento ) {
    var dv = false;
	if(e.value=='000.000.000-00'
	   || e.value=='111.111.111-11'
	   || e.value=='222.222.222-22'
	   || e.value=='333.333.333-33'
	   || e.value=='444.444.444-44'
	   || e.value=='555.555.555-55'
	   || e.value=='666.555.555-55'
	   || e.value=='777.777.777-77'
	   || e.value=='888.888.888-88'
	   || e.value=='999.999.999-99'
	   || e.value=='123.456.789-09'){
		alert(" O CPF " + e.value + " é inválido!\n");
		e.value='';
		e.focus();
		return;
	}
		
    controle = "";
    s = FiltraCampo(e.value);
    tam = s.length;
    if ( tam == 11 ) {
        dv_cpf = s.substring(tam-2,tam);
        for ( i = 0; i < 2; i++ ) {
            soma = 0;
            for ( j = 0; j < 9; j++ )
                soma += s.substring(j,j+1)*(10+i-j);
            if ( i == 1 ) soma += digito * 2;
            digito = (soma * 10) % 11;
            if ( digito == 10 ) digito = 0;
            controle += digito;
        }
        if ( controle == dv_cpf )
            dv = true;

        if ( ! dv && tam > 0) {
            mensagem = "";
            mensagem+= " O CPF " + e.value + " é inválido!\n";
            alert(mensagem);
			e.value='';
			e.focus(); 
        }
     } else  {
         e.value = '';
        }
    return dv;
}

//Coloca a máscara para CPF
function FormataCpf(e,cpf) {
    var s = "";
    if(e) 
       s = FiltraCampo(e.value);
    else
      s = FiltraCampo(cpf );
      
    tam =  s.length;
    r = s.substring(0,3) + "." + s.substring(3,6) + "." + s.substring(6,9)
    r += "-" + s.substring(9,11);
    if ( tam < 4 )
        s = r.substring(0,tam);
    else if ( tam < 7 )
        s = r.substring(0,tam+1);
    else if ( tam < 10 )
        s = r.substring(0,tam+2);
    else
        s = r.substring(0,tam+3);
    if( e ) {
    	e.value = s;
    }
    return s;
}
/**** Fim das funçoes para formatar CPF ****/

/**** Funçoes para formatar CNPJ ****/

//Verifica se o CNPJ é válido
function DvCnpjOk(e) {
    var dv = false;
	if(e.value=='00.000.000/0000-00'
	   || e.value=='11.111.111/1111-11'
	   || e.value=='22.222.222/2222-22'
	   || e.value=='33.333.333/3333-33'
	   || e.value=='44.444.444/4444-44'
	   || e.value=='55.555.555/5555-55'
	   || e.value=='66.666.666/6666-66'
	   || e.value=='77.777.777/7777-77'
	   || e.value=='88.888.888/8888-88'
	   || e.value=='99.999.999/9999-99'){
		alert(" O CNPJ " + e.value + " é inválido!\n");
		e.value='';
		e.focus();
		return;
	}
    
    controle = "";
    s = FiltraCampo(e.value);
    tam = s.length
    if ( tam  == 14 ) {
        dv_cnpj = s.substring(tam-2,tam);
        for ( i = 0; i < 2; i++ ) {
            soma = 0;
            for ( j = 0; j < 12; j++ )
                soma += s.substring(j,j+1)*((11+i-j)%8+2);
            if ( i == 1 ) soma += digito * 2;
            digito = 11 - soma  % 11;
            if ( digito > 9 ) digito = 0;
            controle += digito;
        }
        if ( controle == dv_cnpj )
            dv = true;

        if ( ! dv && tam > 0) {
            mensagem = "O CNPJ " + e.value + " é inválido!\n";
            alert(mensagem);
            e.value='';
            e.focus();
        }
     } else  {
         e.value = '';
         }
     return dv;
}

//Coloca máscara para CNPJ
function FormataCnpj(e) {
    var s = "";
    var r = "";

    s = FiltraCampo(e.value);
    tam =  s.length;
    r = s.substring(0,2) + "." + s.substring(2,5) + "." + s.substring(5,8)
    r += "/" + s.substring(8,12) + "-" + s.substring(12,14);
    if ( tam < 3 )
        s = r.substring(0,tam);
    else if ( tam < 6 )
        s = r.substring(0,tam+1);
    else if ( tam < 9 )
        s = r.substring(0,tam+2);
    else if ( tam < 13 )
        s = r.substring(0,tam+3);
    else
        s = r.substring(0,tam+4);
    e.value = s;
    return s;
}

/**** Fim das funçoes para formatar CNPJ ****/

/**** Funçoes para formatar CEP ****/

//Verifica se o CEP é válido
function formDinCepOk(e){
    var s = "";
    s = FiltraCampo(e.value);
    tam =  s.length;
	if(tam!=8 ) {
		e.value=''
	}
	return true;
}

//Coloca máscara pra o CEP
function formataCep(e) {
    var s = "";
    s = FiltraCampo(e.value);
    tam =  s.length;
	if(tam>2 && tam<6 ) {
		s = s.substring(0,2)+'.'+s.substring(2,5);
	} else if ( tam > 5 ) {
		s = s.substring(0,2)+'.'+s.substring(2,5)+'-'+s.substring(5,8);
	}
    e.value = s;
    return s;
}

/**** Fim das funçoes para formatar CEP ****/

/**** Funções para formatar telefones ****/

//Checa se o telefone é válido
function checaFone(e) {
  var s = "";
    s = FiltraCampo(e.value);
    tam =  s.length;
	if(tam!=8 ) {
		e.value=''
	}
	return true;
}

//Coloca máscara para telefone
function formDinFormataFoneFax(e) {
    var s = "";
    var res = "";

    s = FiltraCampo(e.value);
    while ( s.substring(0,1) == "0" ) {
        s1 = s.substring(1,s.length);
        s = s1;
    }
    if ( s.length == 14 || s.length == 12 )
        s = s.substring(s.length-10,s.length);
    if ( s.length == 13 || s.length == 11 )
        s = s.substring(s.length-9,s.length);

    res = s.substring(s.length-4,s.length);
    if ( s.length > 4  && s.length < 9 )
        res = s.substring(0,s.length-4)+"-"+res;
    if ( s.length > 8  ) //res = "(0XX" + s.substring(0,2) + ") " +
        res = s.substring(2,s.length-4) + "-" + res;
    e.value = res;
    return res;
}

/**** Fim das funções para formatar telefones ****/

//Função para formatar e-mail
function emailOk(obj) {
  // verificar se existe suporte para expressao regular;
  var supported = 0;
  var str=obj.value;
  if (str=='')
     return true;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }
  if (!supported) {
  	alert('E-mail não suportado, tente novamente.');
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
    
  }
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  var r = !r1.test(str) && r2.test(str);
  if (!r) {
   	alert('O e-mail '+ str +' é inválido!');
   	//obj.value = '';
   	obj.focus();
  }
  return r;
}

//Função para limitar digitação em textareas
function formDinLimitaTamanho(maximo,campo,contador) {
	var dif, valor;
	total 	= eval(maximo)
	if( campo.type == undefined )
		campo = document.getElementById(campo);
	tamanho = eval(campo.value.length)
	faltam  = eval(total - tamanho)
	if (faltam <= "-1") {
		valor = campo.value.substr(0,maximo);
		campo.value = valor;
		faltam='0';
		}
	if(isNS4)
		contador = document.getElementById(contador);
	else
		contador = document.all[contador];
	 
	if( contador ){
		contador.innerHTML=faltam+' / '+maximo;
//		if (faltam != maximo )
//			contador.innerHTML=faltam+'/'+maximo;
//		else
//			contador.innerHTML=faltam;
	}
}

//Função para validar campos obrigatorios e enviar dados ao servidor
function EnviaForm(dados, modulo, acao) {
    aCamposNomes=dados.split('#');
	for(id in aCamposNomes) {
		campo=aCamposNomes[id].split('|');
		valor=aCamposNomes[id].split('|');
		if (!document.getElementById(campo[0]).value)		{
			window.alert('Você precisa preencher o campo "'+valor[1]+'"');
			document.getElementById(campo[0]).focus();
			document.getElementById(campo[0]).style.border= "1px solid #FF0000";
			return false;
		}
	}
	frmFazer(modulo,acao);
}

//Função para montar templates
function frmFazer(include, acao){
	//if (formulario==null || foemulario=='undefined')
	  var  formulario = document.frm;
	    
	try{
		document.getElementById('include').value=include;
		if(acao){
			document.getElementById('acao').value=acao;
		}
		formulario.submit();
	} catch(e){
		window.alert('Erro ao postar informações a:'+acao+' f:'+formulario+' c:'+classePostada);
	}
}

//Função para limpar as bordas dos campos do formulário
function LimpaForm(dados) {
	camponome = new Array();
    camponome = dados.split('#');		
    x = camponome.length;
	
 	for(i = 0; i < x; i++) {
		document.getElementById(camponome[i]).style.border = "#CCC 1px solid";
	} 
	
	document.getElementById('pgf_area_mensagem1').style.display = 'none';
	location.href = "#topo";
}

//Função para limpar os campos e as bordas do formulário
function LimpaCampos(dados) {
	camponome = new Array();
    camponome = dados.split('#');		
    x = camponome.length;
	
 	for(i = 0; i < x; i++) {
 		document.getElementById(camponome[i]).value = "";
 		document.getElementById(camponome[i]).style.border = "#CCC 1px solid";		
	} 	
}

//Função para exibir a data e hora atual
function exibeDataHora() { 
 var hoje = new Date()

 data = ((hoje.getDate() < 10) ? "0" : "") + hoje.getDate() + '/';
 data += (((hoje.getMonth()+1) < 10) ? "0" : "") + (hoje.getMonth()+1) + '/';
 data += hoje.getFullYear();
 
 var hora = hoje.getHours()   
 var minuto = hoje.getMinutes()  
 var segundo = hoje.getSeconds()   

 var temp = "" + ((hora < 10) ? "0" : "") + hora;
  temp += ((minuto < 10) ? ":0" : ":") + minuto;
  temp += ((segundo < 10) ? ":0" : ":") + segundo;

 str = data+" - "+temp;
 document.getElementById('span_msg_data_hora').innerHTML = str;
 
  timerID = setTimeout("exibeDataHora()",1000);
//  timerRunning = true;
}

//Função para exibir mensagens ao usuário
function exibeMensagem(id, msg, cor) {
		if (cor == ""){
			cor = 'red';
		}
		document.getElementById(id).style.color = cor;
		document.getElementById(id).innerHTML = msg;		
		document.getElementById(id).style.display = 'block';
	
}

//Função para mostrar ou esconder o formulário
function minimizarMaximizar(tipo, id){
	if(tipo == 0) {
		document.getElementById(id).style.display = 'none';
	} else{
		document.getElementById(id).style.display = 'inline';
	}
}

/*********** Inicio da div de ajuda dinâmica ********************/
var initHeight = 0;
var slidedown_direction = 1;
var slidedownContentBox = false;
var slidedownContent = false;
var slidedownActive = false;
var contentHeight = false;
if (isNS4) {
	var slidedownSpeed = 13; 	// Higher value = faster script
	var slidedownTimer = 9;	// Lower value = faster script
} else {
	var slidedownSpeed = 10; 	// Higher value = faster script
	var slidedownTimer = 16;	// Lower value = faster script
}
	
	function mostraAjuda() {
		
		document.getElementById('dhtmlgoodies_contentBox').style.display = 'block';	
		document.getElementById('dhtmlgoodies_contentBox').style.padding = '10px 10px 10px 10px'; 
        document.getElementById('dhtmlgoodies_contentBox').style.border = '1px solid #FFDF84';
	
		if(initHeight==0)slidedown_direction=slidedownSpeed; else slidedown_direction = slidedownSpeed*-1;
		
		if(!slidedownContentBox){
			slidedownContentBox = document.getElementById('dhtmlgoodies_contentBox');
			
			slidedownContent = document.getElementById('dhtmlgoodies_content');
		
			slidedownContentBox.style.display= 'block';
			
			contentHeight = document.getElementById('dhtmlgoodies_content').offsetHeight;
			
		}  
		slidedownContentBox.style.visibility='visible';
		slidedownActive = true;
        slidedown_showHide_start();
	}
	
	function slidedown_showHide_start() {
	if(!slidedownActive){
					return};
		
		initHeight = initHeight/1 + slidedown_direction;
		
		if(initHeight <= 0){
			slidedownActive = false;
				slidedownContentBox.style.visibility='hidden';
	
			initHeight = 0;
			document.getElementById('dhtmlgoodies_contentBox').style.padding = '0px 0px 0px 0px';	
			document.getElementById('dhtmlgoodies_contentBox').style.border = '0px';	
			document.getElementById('dhtmlgoodies_contentBox').style.display = 'none';	
		}
		
		if(initHeight>contentHeight){
				slidedownActive = false;	
			}
		
		slidedownContentBox.style.height = initHeight + 'px';
		slidedownContent.style.top = initHeight - contentHeight + 'px';
		setTimeout('slidedown_showHide_start()',slidedownTimer);	// Choose a lower value than 10 to make the script move faster
	}
	
	function setslidedownWidth(newWidth) {
		document.getElementById('dhtmlgoodies_slidedown').style.width = newWidth + 'px';
		document.getElementById('dhtmlgoodies_contentBox').style.width = newWidth + 'px';
	}
	
	function setSlideDownSpeed(newSpeed){
		slidedownSpeed = newSpeed;
	}
	
/***** Fim da div de ajuda dinâmica *****/

/***** 
Função responsável por resolver os problemas de alinhamento
entre os browsers em diferentes resoluções. 
*****/
function checkSize() {
	 var resolucao;

	 if ((screen.width == 800 && screen.height == 600)) {//detecta 800x600
     	resolucao = '800x600';
     } else if ((screen.width == 1024 && screen.height == 768)){//detecta 1024x768
     	resolucao = '1024x768';
     } else if ((screen.width == 1280 && screen.height == 720)){//detecta 1280x720
     	resolucao = '1280x720';
     }
    
    var ie = /msie/i.test(navigator.userAgent);
    var ieBox = ie && (document.compatMode == null || document.compatMode == "BackCompat");
    var canvasEl = ieBox ? document.body : document.documentElement;
    var w = window.innerWidth || canvasEl.clientWidth;
    var h = window.innerHeight || canvasEl.clientHeight;

    document.getElementById("item1").style.width = Math.max(0, w + 100) + "%";
    document.getElementById("item2").style.width = Math.max(0, w + 100) + "%";
        
    if (isOpera()){//alinha o sub-menu no opera
    	document.getElementById("sub_menu1").style.left = "100%";
    	document.getElementById("sub_menu2").style.left = "100%";
    } else {//alinha o sub-menu nos outros browsers
    	document.getElementById("sub_menu1").style.left = "15%";
    	document.getElementById("sub_menu2").style.left = "15%";
    }
    
	   switch (resolucao){//realiza modificaçãoes de alinhamento e posicionamento de acordo com a resolução detectada
	   	
	   		case '800x600':	   	

	   		   if (isOpera()){//alinha os botões de minimizar / maximizar no opera
    			 	document.getElementById("span_max_min").style.top = '33.5%';
       	  	        document.getElementById("span_max_min").style.left = '87.4%';
       	  	        
       	  	        document.getElementById("btn_ajuda").style.width = '10px';
       	  	        document.getElementById("btn_min").style.width = '10px';
       	  	        document.getElementById("btn_max").style.width = '7px';
       	  	        document.getElementById("btn_ajuda").style.height = '15px';
       	  	        document.getElementById("btn_min").style.height = '15px';
       	  	        document.getElementById("btn_max").style.height = '15px';
       	  	        
       	  	   } else {//alinha os botões de minimizar / maximizar nos outros browsers
       	  		    document.getElementById("span_max_min").style.top = '30.6%';
       	  	    	document.getElementById("span_max_min").style.left = '89.6%';
       	  	   }	
	   	  	  
       	  	   //alinha a data e hora
       	  	   document.getElementById("span_msg_data_hora").style.margin = '0% 0% 0% 47%';	
       	  	   //alinha a div com os icones de documentos
       	  	   document.getElementById("div_btn_docs").style.margin = '-0.2% 0% 0% 92.2%';
       	  	   
       	  	   tam_popup = 10;
	   	  	
       	  	break;

	   	  	case '1024x768':
       	  	
  				 if (isOpera()){//alinha os botões de ajuda / minimizar / maximizar no opera
    			    document.getElementById("span_max_min").style.top = '24.2%';
       	  	        document.getElementById("span_max_min").style.left = '89.4%';
    			    document.getElementById("btn_ajuda").style.width = '11px';
       	  	        document.getElementById("btn_min").style.width = '11px';
       	  	        document.getElementById("btn_max").style.width = '7px';
       	  	        document.getElementById("btn_ajuda").style.height = '15px';
       	  	        document.getElementById("btn_min").style.height = '15px';
       	  	        document.getElementById("btn_max").style.height = '15px';
       	  	     } else if (isIE) {//alinha os botões de ajuda / minimizar / maximizar no IE
       	  	        document.getElementById("span_max_min").style.top = '22.7%';
       	  	    	document.getElementById("span_max_min").style.left = '90.7%';
       	  	     } else if (isNS4){//alinha os botões de ajuda / minimizar / maximizar no firefox
       	  	     	document.getElementById("span_max_min").style.top = '22.6%';
       	  	    	document.getElementById("span_max_min").style.left = '91.3%';
       	  	    	document.getElementById("btn_min").style.width = '25px';
       	  	        document.getElementById("btn_max").style.width = '25px';
       	  	     }
       	  	 
       	  		  //alinha a data e hora
       	  		  document.getElementById("span_msg_data_hora").style.margin = '0% 0% 0% 57.8%';
       	  		  //alinha a div com os icones de documentos
       	  		  document.getElementById("div_btn_docs").style.margin = '-0.2% 0% 0% 93.7%';
       	  		  
       	  		  tam_popup = 90;
       	        	  		  
       	  	break;
       	  	
       	  	case '1280x720':
       	  		
       	  	 if (isOpera()){
    			  	document.getElementById("span_max_min").style.top = '26.6%';
       	  	        document.getElementById("span_max_min").style.left = '91%';
       	  	        
       	  	        document.getElementById("btn_ajuda").style.width = '11px';
       	  	        document.getElementById("btn_min").style.width = '11px';
       	  	        document.getElementById("btn_max").style.width = '7px';
       	  	        document.getElementById("btn_ajuda").style.height = '15px';
       	  	        document.getElementById("btn_min").style.height = '15px';
       	  	        document.getElementById("btn_max").style.height = '15px';
       	  	       
       	  	 } else {//alinha os botões de minimizar / maximizar nos outros browsers
       	  		   		document.getElementById("span_max_min").style.top = '25.2%';
       	  	 			if (isNS4){
       	  	 				document.getElementById("btn_ajuda").style.width = '25px';
       	  	        		document.getElementById("btn_min").style.width = '25px';
       	  	        		document.getElementById("btn_max").style.width = '25px';
       	  	    			document.getElementById("span_max_min").style.left = '92.7%';
       	  	 			} else if (isIE){
       	  	    			document.getElementById("span_max_min").style.left = '91.5%';
       	  	 			}
       	  	 }
       	  	 
       	  		//alinha a data e hora
       	  		if (isOpera() || isNS4) {
       	  			document.getElementById("span_msg_data_hora").style.margin = '0% 0% 0% 65.6%';
       	  		} else {
       	  			document.getElementById("span_msg_data_hora").style.margin = '0% 0% 0% 66.6%';
       	  		}
       	  		//alinha a div com os icones de documentos
       	  		document.getElementById("div_btn_docs").style.margin = '1.3% 0% 0% 94.5%';
       	  		
       	  		tam_popup = 220;
     	  		
       	  	break;
	   }
}
/***************************/

//Função para esconder e exibir campos de um formulário
function showHideForm (idMostrar, idEsconder) {
	camponome1 = new Array();
	camponome2 = new Array();
	
    camponome1 = idMostrar.split('#');		
    tam1 = camponome1.length;
    
    for(i = 0; i < tam1; i++) {
		if (isOpera()){
 			document.getElementById(camponome1[i]).style.display = "table-row";
		} else if (isNS4) {
		    document.getElementById(camponome1[i]).style.display = "table-row";
 		} else if (isIE) {
			document.getElementById(camponome1[i]).style.display = "inline";
		}
	} 	
    
    if (idEsconder != null) {
    	camponome2 = idEsconder.split('#');		
    	tam2 = camponome2.length;
    	for(j = 0; j < tam2; j++) {
			document.getElementById(camponome2[j]).style.display = "none";
		}
	}
}

//Função para esconder e exibir campos de um sub-relatório
function showHideSubReport (id) {
	camponome = new Array();
	
	camponome = id.split('#');		
    tam = camponome.length;
    
    for(i = 0; i < tam; i++) {
		
    	if (document.getElementById(camponome[0]).style.display == 'none'){
    		if (isOpera()){
 				document.getElementById(camponome[i]).style.display = "table-row-group";
			} else if (isNS4) {
		   		document.getElementById(camponome[i]).style.display = "table-row-group";
 			} else if (isIE) {
				document.getElementById(camponome[i]).style.display = "inline";	
			}
			document.getElementById('img_mostrar_prod1').src = 'base/imagem/menos.png'
		} else {
			document.getElementById(camponome[i]).style.display = "none";
			document.getElementById('img_mostrar_prod1').src = 'base/imagem/mais.png'
		}

	}     
}

/*** Alias para função document.getElementById('e').value ***/
function gV(elem){
	try{
		if(elem) return document.getElementById(elem).value;
	}catch(e){
		alert('Elemento "'+elem+'" não encontrado!"');	
		return false;
	}
}

/*** Alias para função document.getElementById('e') ***/
function gE(elem){
	try{
		if(elem) return document.getElementById(elem);
	}catch(e){
		alert('Elemento "'+elem+'" não encontrado!"');	
		return false;
	}
}

/*** Alias para função setar um valor a um elemento ***/
function sV(elem,valor){
	try{
		if(elem && valor) document.getElementById(elem).value=valor;
	}catch(e){
		alert('Elemento ou valor não informado!"');	
		return false;
	}
}

/***** INICIO DAS FUNÇÕES RESPONSAVEIS PELOS POPUPS ****/
var horizontal_offset = "9px";
var vertical_offset = "0"; 
var ie = document.all;
var ns6 = document.getElementById&&!document.all;

function getposOffset(what, offsettype){
	var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
	var parentEl=what.offsetParent;

	while (parentEl!=null){
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
return totaloffset;
}

function iecompattest(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function clearbrowseredge(obj, whichedge){
	var edgeoffset = (whichedge=="rightedge") ? parseInt(horizontal_offset)*-1 : parseInt(vertical_offset)*-1;
		if (whichedge == "rightedge"){
			var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-30 : window.pageXOffset+window.innerWidth-40;
			dropmenuobj.contentmeasure = dropmenuobj.offsetWidth;
				if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure){
					edgeoffset = dropmenuobj.contentmeasure+obj.offsetWidth+parseInt(horizontal_offset);
				}
		} else {
			var windowedge = ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18;
			dropmenuobj.contentmeasure = dropmenuobj.offsetHeight;
				if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure){
					edgeoffset = dropmenuobj.contentmeasure-obj.offsetHeight;
				}
		}
	return edgeoffset
}

function showPopUp(obj, e){
	if ((ie||ns6) && document.getElementById("div_popup")){
		
		dropmenuobj = document.getElementById("div_popup");
		dropmenuobj.style.display="block";
		dropmenuobj.style.left=dropmenuobj.style.top = -500;
		dropmenuobj.x = getposOffset(obj, "left");
		dropmenuobj.y = getposOffset(obj, "top");
		dropmenuobj.style.left = dropmenuobj.x-clearbrowseredge(obj, "rightedge")-tam_popup+obj.offsetWidth+"px";
		dropmenuobj.style.top = dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+"px";
		
		if (!isOpera() && !isNS4){
		dropmenuobj2 = gE('iframe_hack');
		
		dropmenuobj2.style.display="block";
		
		dropmenuobj2.style.left=dropmenuobj2.style.top = -500;
		dropmenuobj2.x = getposOffset(obj, "left");
		dropmenuobj2.y = getposOffset(obj, "top");
		dropmenuobj2.style.left = dropmenuobj2.x-clearbrowseredge(obj, "rightedge")-tam_popup+obj.offsetWidth+"px";
		dropmenuobj2.style.top = dropmenuobj2.y-clearbrowseredge(obj, "bottomedge")+"px";
		}
	}
}
/**** FIM DAS FUNÇÕES RESPONSÁVEIS PELOS POPUPS ****/

//Função para gerar numero aleatorio
function gerador() {
	var numAleatorio = Math.random()+"";
	gE('text_senha').value = "bstoreuser"+numAleatorio.substring(2, 7);
}

/** Funçao AJAX **/
/*
EX: 
 aj = new ajax();
 aj.send(CADASTRAR&nome=chico&fone=123456)

*/
function ajax(src, metodo, tipoResposta) { 
	this.src 			= src || 'base/include/ajax.php';
	this.metodo 		= metodo || 'POST';
	this.tipoResposta 	= tipoResposta || 'TXT';
	req = false;
	
	/** Metodo que realiza a requisição ao servidor **/
	this.send = function(dados){
		//showDivCarregando();
		try{
		    req = new XMLHttpRequest(); // XMLHttpRequest para browsers decentes, como: Firefox, Safari, dentre outros.
		} catch(ee) {
		    try{
		        req = new ActiveXObject("Msxml2.XMLHTTP"); // Para o IE da MerdaSoft
		    } catch(e) {
		        try{
		            req = new ActiveXObject("Microsoft.XMLHTTP"); // Para o IE 5+ da MerdaSoft
		        } catch(E) {
		            req = false;
		        }
		    }
		}
		
		if(req){
			req.onreadystatechange = function(){
				if (req.readyState == 4) { 
					if (req.status == 200) {
						//alert(req.getAllResponseHeaders());
						//hidden('div_carregando');
						if(this.tipoResposta == 'XML')
							result(req.responseXML);
						else{
							var texto = req.responseText; 
							texto = texto.replace(/\+/g," "); // problema com os acentos"
         					result(unescape(texto)); 
						}
					}else 
						alert("Houve um problema ao obter os dados:\n" + req.statusText); 
				}
			};
			
			if(this.metodo=='POST'){
				req.open(this.metodo, this.src, true); 
				req.setRequestHeader("Connection", "close");
        		req.setRequestHeader("Method", "POST " + this.src + "HTTP/1.1");
				req.setRequestHeader('encoding','ISO-8859-1');
				if(this.tipoResposta=='XML')
	        		req.setRequestHeader('Content-Type','text/xml');
				else
					req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				req.send('op='+dados); 
			}else{
				req.open(this.metodo, this.src+'?'+dados, true); 
				req.send(null); 
			}
		}else
			alert("Seu Browser não oferece suporte ao objeto XMLHttpRequest!"); 
	};	
}