function HTMLencode(strToCode) {
	strToCode = strToCode.replace(/</g,"&lt;");
	strToCode = strToCode.replace(/>/g,"&gt;");
	strToCode = strToCode.replace(/"/g,"&quot;");
	return strToCode;
}



/*
 	Funcao .....: Sleep(n)
	Descricao ..: Funcao para paralizar o processamento por um periodo determinado
	Parametros .: n ..........: Tempo em segundos

	Uso ........: Sleep(5);
*/
function Sleep(n) {
	var args = Sleep.arguments;
	n = (args.length == 0) ? 5 : n;
	n = (n > 60) ? 60 : n;
	n = Math.ceil(n*1000);
	var newElem = document.createElement('span');
	newElem.id = 'tempo_sleep';
	document.body.appendChild(newElem);
	document.getElementById('tempo_sleep').style.visibility ='hidden';
	for(k=1;k<=n;k++) {	document.getElementById('tempo_sleep').innerHTML = k; }

}
// --- Fim Sleep ---






/*
 	Funcao .....: 
	Descricao ..: 

	Uso ........: 
*/
function Is() {
    agent  = navigator.userAgent.toLowerCase();
    this.major = parseInt(navigator.appVersion);
    this.minor = parseFloat(navigator.appVersion);
    this.ns    = ((agent.indexOf('mozilla')   !=   -1) && 
                 ((agent.indexOf('spoofer')   ==   -1) && 
                 (agent.indexOf('compatible') ==   -1)));
    this.ns4   = (this.ns && (this.major      ==    4));
    this.ns6   = (this.ns && (this.major      >=    5));
    this.ie    = (agent.indexOf("msie")       !=   -1);
    this.ie3   = (this.ie && (this.major      < 4));
    this.ie4   = (this.ie && (this.major      ==    4) && 
                 (agent.indexOf("msie 5.0")   ==   -1) &&
                 (agent.indexOf("msie 6.0")   ==   -1));
    this.ie5   = (this.ie && (this.major      ==    4) && 
                 (agent.indexOf("msie 5.0")   !=   -1));
    this.ie55  = (this.ie && (this.major      ==    4) && 
                 (agent.indexOf("msie 5.5")   !=   -1));
    this.ie6   = (this.ie && (agent.indexOf("msie 6.0")!=-1) );
    this.opera = (agent.indexOf("opera")       !=   -1);

	this.firefox = (agent.indexOf("firefox")  !=   -1);

	if( this.ns )
		this.browser = "Netscape";
	if( this.ie)
		this.browser = "Internet Explorer";
	if( this.opera) {
		this.browser = "Opera";
		this.ie  = false;
		this.ie5 = false;
	}
	if(this.ie4)   this.version = "4.x";
	if(this.ie5)   this.version = "5.0";
	if(this.ie55)  this.version = "5.5";
	if(this.ie6)   this.version = "6.0";
	if(this.opera) this.version = "5.x";

	if(this.ns4)   this.version = "4.x";
	if(this.ns6)   this.version = "6.x";
	if(this.opera) this.version = "5.x"

	if(this.ie5 || this.ie55 || this.ie6 || this.ns6 || this.opera)
		this.dom = true
	else	
		this.dom = false

	this.info = this.browser + " " + this.version + "\r\n" + this.major + "." + this.minor + "   \r\n" + agent + "  \r\n" + navigator.appVersion
}
//var is = new Is();


/*
 	Funcao .....: checkBrowserIE()
	Descricao ..: Verifica se o browse utilizado é o internet explorer apartir da versão 6.0

	Uso ........: checkBrowserIE()
*/

function checkBrowserIE()
{	var is = new Is();
  
  var versao = parseInt(is.version.substring(0,1));

  if ((is.ns6) && (versao < 6))
  { alert("ATENÇÃO : \nSite melhor visualizado com FireFox 6.0 ou superior");
  }
  
  if ((is.ie) && ((versao < 6) && (versao != 4)) )
  {	alert("ATENÇÃO : \nSite melhor visualizado com Internet Explorer 6.0 ou superior");
	}

  if (!(is.ie) && !(is.ns))
  { alert("ATENÇÃO : \nSite melhor visualizado com Internet Explorer 6.0 ou superior e FireFox 6.0 ou superior.");
  }
}




// Controle da duração da sessão do usuário
var running = false
var endTime = null
var timerID = null
function startTimer() {
	running = true
	now = new Date()
	now = now.getTime()
	// change last multiple for the number of minutes
	endTime = now + (1000 * 60 * 0.15)
	
	apos_02_min  = now + (1000 * 60 * 2)
	apos_30_min  = now + (1000 * 60 * (1 * 30) )
	apos_01_hora = now + (1000 * 60 * (1 * 60) )
	msg_apos_02_min  = "Atenção sua sessão será finalizada em 2 minutos...";
	msg_apos_30_min	 = "Atenção sua sessão será finalizada em 30 minutos...";
	msg_apos_01_hora = "Atenção sua sessão será finalizada em 1 hora...";

	showCountDown()
}

function showCountDown() {
	var now = new Date()
	now = now.getTime()
	if (endTime - now <= 0) {
		stopTimer()
		alert('Sua sessão foi finalizada \n\n (Tempo esgotado).')
		window.location.href = 'frmLogOff.php';
	} else {
		var delta = new Date(endTime - now)
		var theMin = delta.getMinutes()
		var theSec = delta.getSeconds()
		var theTime = theMin
		theTime += ((theSec < 10) ? ':0' : ':') + theSec
//		document.forms[0].timerDisplay.value = theTime
		if (running) {
			timerID = setTimeout('showCountDown()',1000)
		}
	}
}
function stopTimer() {
	clearTimeout(timerID)
	running = false
//	document.forms[0].timerDisplay.value = '0:00'
}

// Fim do controle da duração da sessão do usuário-->




// funcao para delimitar a quantidade de casas decimais
function FormataDecimal(vlr, qntDec, decSep) {
	decSep = (decSep == null) ? "," : decSep;
	vlr    = new String(vlr);
	vlr    = vlr.replace(",", ".");
	var str = "" + Math.round (eval(vlr) * Math.pow(10,qntDec));
	while (str.length <= qntDec) { str = "0" + str;	}
	var decpoint = str.length - qntDec;
	return str.substring(0,decpoint) + decSep + str.substring(decpoint,str.length);
}

//

// Funcao para retornar minutos de uma hora 
// RetornaMinutosDeHoras(03:10) --> 190
function RetornaMinutosDeHoras(HoraMin) {
  var HoraMin =  new String(HoraMin);
  HoraMin = HoraMin.split(":");
	if (HoraMin.length < 2) {HoraMin[1] = 0;}
    return (parseFloat(HoraMin[0]) * 60) + parseFloat(HoraMin[1]);
} // fim RetornaMinutosDeHoras

// Funcao para retornar a hora
// RetornaHorasDeMinutos(300) --> 03:10
function RetornaHorasDeMinutos(Minutos) {
	var Horas = parseInt(Minutos.value / 60);
	var Min   = parseInt(Minutos.value % 60);
/*
	var Horas = parseInt(Minutos / 60);
	var Min   = parseInt(Minutos % 60);
*/

	Horas = new String(Horas);	Horas = (Horas.length == 1) ? "0"+Horas : Horas;
	Min   = new String(Min);	Min   = (Min.length == 1)   ? "0"+Min   : Min;
	return(Horas+":"+Min);
} // fim RetornaHorasDeMinutos



/*
 	Funcao .....: confirma(Msg)
	Descricao ..: Funcao para confirmar operacao
	Parametros .: msg .........: Mensagem a ser exibida

	Uso ........: confirm('Você deseja fechar a janela ?')
*/

function confirma(Msg) {
	var Checkado = false;
	ok=confirm(Msg,''); 
	if (ok) { 
		Checkado = true; 
	}
return Checkado;
}


function redireciona(url) { window.location = url; }
/*
function carregaPagina(destino,param) {
   theform = document.form1;
   destino = destino+param
   redireciona(destino);
}
*/

function carregaPagina(destino,param,frm) {
	if (frm == null) {
		frm = "form1";
	}   
	destino = destino+param
	document.forms[frm].action = destino;
	document.forms[frm].submit();
}

function enviaForm(url,frm) {
	if (frm == null) {
		frm = "form1";
	}
	document.forms[frm].action = url;
	document.forms[frm].submit();
}

/*
 	Funcao .....: iif(txtCondicao,condVerdade,condFalsa)
	Descricao ..: Funcao para teste de condicao
	Parametros .: txtCondicao ...: Expressão a ser validada
	              condVerdade ...: Retorno verdadeiro da condição
				  condFalsa .....: Retorno falso da condição

	Uso ........: 
*/
function iif(txtCondicao,condVerdade,condFalsa) {
	if (txtCondicao) { return condVerdade };
	return condFalsa;
}






// janela_sysWeb('http://localhost/weblawyer/')
function janela_sysWeb(str) {
	var largura = screen.width;
	var altura  = screen.height;
	var padraoRes = iif(((largura <= 800) || (altura <= 600)),0,1);

//	alert("Largura " +largura+" Altura "+altura+" Padrao = "+padraoRes);
	if (padraoRes==0) {
		largura = 790; // 800
		altura  = 540; // 600
//		alert("800x600");
	} else {
		largura = 1020; //1024;
		altura  = 730;  //768;
//		alert("1024x768");
	}

    sysWeb = window.open(str,'sysWeb','left=0, top=0, width= '+largura+' ,height= '+altura+',menubar=no ,scrollbars=yes,resizable=yes,menubar=no,statusbar=no');
//    sysWeb = window.open(str,'sysWeb','width=790,height=580,menubar=no,statusbar=yes,toolbar=no,resizable=yes');
	sysWeb.focus();
}


/* Formatação para qualquer mascara
OnKeyPress="colocaMask(this, '#####-###')"
*/
function colocaMask(txtField, mask) {
   var i = txtField.value.length;
   var saida = mask.substring(0,1);
   var texto = mask.substring(i)
   if (texto.substring(0,1) != saida) {
      txtField.value += texto.substring(0,1);
   }
}

/*
 	Funcao .....: compara(txtField1,txtField2,Msg)
	Descricao ..: Funcao de comparacao entre dois valores
	Parametros .: txtField1 ...: Nome do primeiro campo a ser comparado
				  txtField2 ...: Nome do segundo campo a ser comparado
				  Msg .........: Mensagem que sera enviada ao usuario

	Uso ........: !compara(senha,senhaconf,'As senhas estão diferentes. Verifique e tente novamente.')
*/
function compara(txtField1,txtField2,Msg) {
	if(txtField1.value != txtField2.value) {
		txtField1.focus();
		if (Msg) {
			alert(Msg);
		}
		return false;
	}
	return true;
}

/*
 	Funcao .....:  verCaracInvalido(texto) 
	Descricao ..: Funcao para verificar a existencia de caracteres invalidos
	Parametros .: texto  .........: Texto a ser verificado

	Uso ........: (! verCaracInvalido(theform.cod_usr.value))  

*/
function verCaracInvalido(texto) { // > < ( ) [ ] ' " ; : / \
	var achei
	var aspas='"'
	var tam = texto.length
	achei="0"
	for(i=0;i<=tam;i++) {
		if (texto.charAt(i)==aspas || texto.charAt(i)=="'" || 	
		    texto.charAt(i)=="#" ||   texto.charAt(i)=="<" || 
			texto.charAt(i)==">" ||   texto.charAt(i)==";" || 
			texto.charAt(i)==":" ||   texto.charAt(i)=="/" ||
			texto.charAt(i)=="\\" 		
			                       ) {
			achei="1";
			window.alert("Você não deve preencher os seguintes caracteres: #, "+aspas+", ', <, >,:, ;,/ ");
			texto.focus();
			return false;  
		}
	}
	return true;
}

/*
 	Funcao .....: trocaCarac(txtField,param1,param2)
	Descricao ..: Funcao de troca de caracteres de uma string 
	Parametros .: txtField ...: Campo no qual o conteudo sera trocado
				  param1 .....: Caracter a ser trocado
				  param2 .....: Caracter de troca

	Uso ........: trocaCarac('01-01-2002','-','/')
*/
function trocaCarac(txtField,param1,param2) {
	for (i=0;i<=txtField.length;i++) {
		txtField = txtField.replace(param1,param2);
	}
	return 
}

/*
 	Funcao .....: isNum(txtField)
	Descricao ..: Verificar se um numero é valido
	Parametros .: txtField ...: Campo no qual o conteudo sera verificado
	              txtExtra ...: Caracteres extras validos  ,.-/

	Uso ........: isNum('a',',.-/');
*/
function isNum(txtField,txtExtra,txtMsg) {
	if(txtField.value == '') {return true;}
	var valido = "1234567890";
	var vsub;
	var ind;

	if (txtMsg == undefined || txtMsg == "undefined" || txtMsg == 'undefined' || txtMsg == '') {txtMsg = 'Número Digitado Inválido!';}

	if (txtExtra != '') { valido = valido + txtExtra; }
	for (ind=0 ; ind < txtField.value.length ; ind++) {
		vsub=txtField.value.substring(ind,ind+1);
		if (valido.indexOf(vsub) == "-1") {
			alert(txtMsg);
			txtField.value = "";
			txtField.focus();
			return false;
		}
	}
	return true;
}

/*
 	Funcao .....: pulaCampo(txtField,Max)
	Descricao ..: Funcao pular de um campo a outro de forma automatica
	Parametros .: txtField ....: Nome do campo do formulario
                  Max .........: Numero maximo de caracter permitido para o campo
	Uso ........: <INPUT TYPE="text" NAME="campo1"  onKeyUp="pulaCampo(this,3)">	
*/
function pulaCampo(txtField,Max){
	if (txtField.value.length >= Max){
		for (var i=0;i<txtField.form.length;i++){
	    	if ((txtField.form[i]==txtField) && (txtField.form[i+1] != null)){
				if (txtField.form[i+1].type == 'text') txtField.form[i+1].value = '';
				txtField.form[i+1].focus();
				break;
			}
		}
	}
}


/*
 	Funcao .....: trim(txtField)
	Descricao ..: Funcao retirar espacos em branco do campo
	Parametros .: txtField ....: Nome do campo do formulario

	Uso ........: 
*/
function trim(txtField) {
	var sDado, Result, i, f;
	Result = "";
	sDado = txtField.toString();
	if (sDado.length > 0) {
		for (i=0; i<sDado.length; i++) {
			if (sDado.charAt(i) != " ") break;
		}
		if (i < sDado.length) {
			for (f=sDado.length-1; f>=0; f--) {
				if (sDado.charAt(f) != " ") break;
			}
			Result = sDado.substring(i, f+1);
		}
	}
	return Result;
}
 


/*
 	Funcao .....: ValidateDomain(str)
	Descricao ..: Funcao validar um dominio
	Parametros .: str ....: Nome do dominio a ser validado

	Uso ........: 
*/
function ValidateDomain(str){
	var resultStr = str.replace(/ /gi, "");
	var atIndex = resultStr.indexOf("@");
	var dotIndex = resultStr.lastIndexOf(".");
	if( resultStr=="" || !isASCII(resultStr) || dotIndex == -1)
		return "";
	if ( atIndex > 0 || resultStr.charAt(atIndex+1) == "." || dotIndex >= resultStr.length-1 )
		return "";
	return resultStr.replace(/@/i, "");
}



/*
 	Funcao .....: set_focus(set_focus)
	Descricao ..: Funcao de posicionamento do cursor no campo
	Parametros .: 

	Uso ........: <body onload="set_focus()">
*/
function set_focus() {
	if (document.forms.length > 0) {
		for (i = 0; i < document.forms.length; i++) {
			for (j = 0; j < document.forms[i].elements.length; j++) {
				var field = document.forms[i].elements[j];
				if ( (field.type == "text" || field.type == "textarea" || field.type == "password") ) {
					field.focus();
                    if (field.type == "text") {
                        field.select();
                    }
					break;
	    		}
			}
      	}
   	}
}

/*
 	Funcao .....: fechaJanela()
	Descricao ..: Funcao para fechar a janela em uso

	Uso ........: <A  class='linkMenu' HREF="" onclick="return fechaJanela();">Fechar</A>

*/
function fechaJanela() {
	if (confirm('Você deseja fechar a janela ?') ) {
		window.close();
	}
	return false;
}



function vldCPF(txtField) {
	trocaCarac(txtField,'-','');trocaCarac(txtField,'.','');
	trocaCarac(txtField,'/','');trocaCarac(txtField,',','');

  var calc;
  var soma = 0;
  var digit;
  var i;

  if (txtField.length != 11) {
    return false;
  }
  else {
    calc = txtField.substr(0, 9);
    for (i = 0; i < 9; i++) {
      soma += parseInt(calc.substr(i, 1)) * (10 - i);
    }
    digit = 11 - soma % 11;
    if ((digit == 10) || (digit == 11)) {
      calc = calc.concat("0");
    }
    else {
      calc = calc.concat(digit.toString());
    }
    soma = 0;
    for (i = 0; i < 10; i++) {
      soma += parseInt(calc.substr(i, 1)) * (11 - i);
    }
    digit = 11 - soma % 11;
    if ((digit == 10) || (digit == 11)) {
      calc = calc.concat("0");
    }
    else {
      calc = calc.concat(digit.toString());
    }
    return (txtField.toString() == calc.toString())
  }
}


function vldCNPJ(txtField) {
	trocaCarac(txtField,'-','');trocaCarac(txtField,'.','');
	trocaCarac(txtField,'/','');trocaCarac(txtField,',','');

  var calc;
  var soma = 0;
  var digit;
  var i;

  if (txtField.length != 14) {
    return false;
  }
  else {
    calc = txtField.substr(0, 12);
    for (i = 0; i < 4; i++) {
      soma += parseInt(calc.substr(i, 1)) * (5 - i);
    }
    for (i = 0; i < 8; i++) {
      soma += parseInt(calc.substr((i + 4), 1)) * (9 - i);
    }
    digit = 11 - soma % 11;
    if ((digit == 10) || (digit == 11)) {
      calc = calc.concat("0");
    }
    else {
      calc = calc.concat(digit.toString());
    }
    soma = 0;
    for (i = 0; i < 5; i++) {
      soma += parseInt(calc.substr(i, 1)) * (6 - i);
    }
    for (i = 0; i < 8; i++) {
      soma += parseInt(calc.substr((i + 5), 1)) * (9 - i);
    }
    digit = 11 - soma % 11;
    if ((digit == 10) || (digit == 11)) {
      calc = calc.concat("0");
    }
    else {
      calc = calc.concat(digit.toString());
    }
    return (txtField.toString() == calc.toString());
  }
}

function FormataCNPJ(el) {
	vr=el.value;
	tam=vr.length;
	if ( vr.indexOf(".") == -1 ) {
      		if ( tam <= 2 ) el.value = vr;
		if ( (tam > 2) && (tam <= 6) ) el.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, tam );
		if ( (tam >= 7) && (tam <= 10) ) el.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '.' + vr.substr( 5, 3 ) + '/';
		if ( (tam >= 11) && (tam <= 18) ) el.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '.' + vr.substr( 5, 3 ) + '/' + vr.substr( 8, 4 ) + '-' + vr.substr( 12, 2 ) ;
	}
	return true;
}


// FUNÇÃO PARA CRITICAR CAMPOS DE VALORES
function Formata_Valorxxx(campo,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = document.form[campo].value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;

	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 <= 2 ){ 
	 		document.form[campo].value = vr ; }
	 	if ( (tam > 2) && (tam <= 5) ){
	 		document.form[campo].value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		document.form[campo].value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		document.form[campo].value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 12) && (tam <= 14) ){
	 		document.form[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 - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		document.form[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 VoltaMaskxx(param,tipo) {
	// Número
	if (tipo == 1) {
		if      (param.value == "")     {param.value = "0,00";}
		else if (param.value == "0,00") {param.value = "";}
		else if (param.value.indexOf(",", 0) == -1) {param.value = param.value + ",00"}
	}
}



function Frases(){
	var Frases = new Array(5)
	Frases[0] = "aaa"
	Frases[1] = "bbb"
	Frases[2] = "ccc"
	Frases[3] = "ddd"
	Frases[4] = "eee"
	return(Frases[parseInt(Math.random()*5)])
}

function validaTecla(campo,event) {
	var BACKSPACE=8;
	var key;
	var tecla;
	CheckTAB=true;
	if(navigator.appName.indexOf("Netscape")!= -1) {
		tecla= event.which;
	} else {
		tecla= event.keyCode;
	}
	key=String.fromCharCode(tecla);
        //alert( 'key: ' + tecla + '  -> campo: ' + campo.value);
	if (tecla==13) {
                 return false;
	}
	if (tecla==BACKSPACE) {
		return true;
	}
	return (isNum(key));
}


//Formata data com mm/aaaa
function DataMesAno(Campo){

	if ((Campo.value != "/") || (event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)){
		if (Campo.value.length < 7){
			if (Campo.value.length == 2) Campo.value = Campo.value.substr(0,2) + "/" + Campo.value.substr(2,Campo.value.length);
		}
	}
}