// JavaScript Document
/* Verificando o tipo de navegador*/
var eva_userAgent = navigator.userAgent.toLowerCase();
var eva_isOpera = eva_userAgent.indexOf('opera 7') != -1 ? 1 : 0;
var eva_isKonq = eva_userAgent.indexOf('konq') != -1 ? 1 : 0;
var eva_isIE = !eva_isKonq && !eva_isOpera && document.all ? 1 : 0;
var eva_isIE50 = eva_isIE && eva_userAgent.indexOf('msie 5.0') != -1;
var eva_isIE55 = eva_isIE && eva_userAgent.indexOf('msie 5.5') != -1;
var eva_isIE5 = eva_isIE50 || eva_isIE55;
var eva_isGecko = eva_userAgent.indexOf('gecko') != -1 ? 1 : 0;
var eva_mouseover = eva_isIE ? 'hand' : 'pointer';

//mostra qq objeto html q esteja oculto na tela
function mostraObjeto(obj){
	if ( document.getElementById(obj).style.display == 'block'){
		document.getElementById(obj).style.display = 'none';
		document.getElementById(obj).style.visibility = 'hidden';
	}else{
		document.getElementById(obj).style.display = 'block';
		document.getElementById(obj).style.visibility = 'visible';
	}
}

//Exemplo: formatarQualquerMascara(this, '##/##/####');
function formatarQualquerMascara(src, mask){
	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);
	}
}

function mascararData(src, mask, evento){
	if (filtraTecla(src,evento)==true){
		return formatarQualquerMascara(src, mask);
	}else{
		return false;
	}
}

function trim(str){
	return str.replace( /(^\s*)|(\s*$)/g, '' ) ;
}

function ltrim(str){
	return str.replace( /^\s*/g, '' ) ;
}

function rtrim(str){
	return str.replace( /\s*$/g, '' ) ;
}
/* função para exibir a data do formato extenso 12 de dezembro de 2006 */
function exibirData(){
	var mydate=new Date();
			var year=mydate.getYear();
			if (year < 1000)
			year+=1900;
			var day=mydate.getDay();
			var month=mydate.getMonth();
			var daym=mydate.getDate();
			if (daym<10)
			daym="0"+daym;
			var dayarray=new Array("Domingo","Segunda","Ter&ccedil;a","Quarta","Quinta","Sexta","S&aacute;bado");
			var montharray=new
			Array("janeiro","fevereiro","mar&ccedil;o","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro");
			return dayarray[day]+", "+daym+" de "+montharray[month]+" de "+year;	
}

// função que permite passar o valor de um listbox para um campo oculto
function moverItemListBoxCampoOculto(campo_origem,campo_destino)
{
	var origem = document.getElementById(campo_origem);
	var destino = document.getElementById(campo_destino);
	destino.value='';
	for(ListaSel=0; ListaSel < origem.options.length; ListaSel++)
	{
		destino.value += origem.options[ListaSel].value+',';
	}
}
// função que verifica se a data inicial émenor que a data final
function comparaData(dtInicial, dtFinal){
	dataInicial = document.getElementById(dtInicial).value;
	dataFinal = document.getElementById(dtFinal).value;
	if (dataInicial != '' && dataFinal != ''){
		diferenca = Date.parse(dataInicial) - Date.parse(dataFinal);
		if(diferenca > 0){
			alert('A data inicial, não pode ser maior que a data final.');
			return false;
		}else {
			return true;
		}
	}else{
		document.getElementById(dtInicial).className = '' ;
		document.getElementById(dtFinal).className = '' ;
		if(dataInicial==''){
			alert('É necessario informar a data inicial.');
			document.getElementById(dtInicial).className = 'inputAlerta' ;
			document.getElementById(dtInicial).focus();
		}else{
			alert('É necessario informar a data final.');
			document.getElementById(dtFinal).className = 'inputAlerta' ;
			document.getElementById(dtFinal).focus();
		}
		return false;
	}
}

//Esta funcao transfere um ou mais itens de um listbox para outro
function moverItem(campo_origem,campo_destino)
{
	var origem = document.getElementById(campo_origem);
	var destino = document.getElementById(campo_destino);

	if( origem.options.length == 0 )
	{
		alert("Não existe nenhum elemento para ser movido.");
		return ;
	}

	ListaSel = origem.options.selectedIndex;
	if (ListaSel == -1)
	{
		alert("Selecione pelo menos um item");
		origem.focus();
		return false;
	}

	for(i = origem.options.length-1; i>=0; i--)
	{
		if(origem.options[i].selected)
		{
			IdNome  = origem.options[i].value;
			TxtNome = origem.options[i].text;
			origem.options[i].selected = false;
			origem.options[i] = null;
			QtdSel  = destino.options.length;

			destino.options.length = QtdSel + 1;
			destino.options[QtdSel].value = IdNome;
			destino.options[QtdSel].text = TxtNome;
		}

	}
}

//Esta funcao remover um ou mais itens de um listbox
function removerItem(campo)
{
	var origem = document.getElementById(campo);

	if( origem.options.length == 0 ){
		alert("Não existe nenhum item a ser removido.");
		return false;
	}

	ListaSel = origem.options.selectedIndex;
	if (ListaSel == -1){
		alert("Selecione pelo menos um item");
		origem.focus();
		return false;
	}

	for(i = origem.options.length-1; i>=0; i--){
		if(origem.options[i].selected)
		{
			origem.options[i].selected = false;
			origem.options[i] = null;
		}
	}
}

//Função para mover todos itens de um listbox
function moverTodosItens(campo_origem,campo_destino)
{

	var origem = document.getElementById(campo_origem);
	var destino = document.getElementById(campo_destino);

	if( origem.options.length == 0 )
	{
		alert("Não existe nenhum elemento para ser movido.");
		return ;
	}

	for(ListaSel=0; ListaSel < origem.options.length; ListaSel++)
	{
		IdNome = origem.options[ListaSel].value;
		TxtNome = origem.options[ListaSel].text;

		QtdSel = destino.options.length;
		destino.options.length = QtdSel + 1;
		destino.options[QtdSel].value = IdNome;
		destino.options[QtdSel].text = TxtNome;
	}
	origem.length = 0;
}


function ColocaFocus(form,nome_campo)
{
	var nome_campo = nome_campo;
	document.form.nome_campo.focus();
}
function Link(pagina)
{
	window.self.location = pagina;
}

function CarregaPagina(url)
{
	window.location.replace(url);
}


function AbreJanela(URLtoOpen, windowName, windowFeatures)
{
	newWindow = window.open(URLtoOpen, windowName,windowFeatures);
}


function FecharJanela()
{
	window.close();
}


//Filtra os caracteres digitados mostra, retorna apenas numeros
//OnkeyPress = "return filtraTecla(this,event);"
function filtraTecla(Objeto,event)
{
	var tecla;
	var key;
	var strValidos = "0123456789"

	if( navigator.appName.indexOf("Netscape")!= -1 )
	tecla= event.which;
	else
	tecla= event.keyCode;
	return isNum( String.fromCharCode( tecla) );
}



function FormataValor(campo,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	vr = document.getElementById(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.getElementById(campo).value = vr ; }
			if ( (tam > 2) && (tam <= 5) ){
				document.getElementById(campo).value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
				if ( (tam >= 6) && (tam <= 8) ){
					document.getElementById(campo).value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
					if ( (tam >= 9) && (tam <= 11) ){
						document.getElementById(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.getElementById(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.getElementById(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 ) ;}
	}

	for (var ct = 0; ct < document.form.elements.length; ct++) {
		if (document.form.elements[ct].name == document.form.elements[campo].name) {
			if ( !teclapres.shiftKey && tecla == 9 && document.form.elements[ct+1] && document.form.elements[ct+1].name == "senhaConta" && document.applets['tclJava'] ){
				document.applets['tclJava'].setFocus();
			}
		}
	}
}

function verificaCaracteres(tecla){
	var retorno;
	var expReg = new RegExp("[0-9\.-]");
	retorno = expReg.exec(tecla);
	//alert(retorno);
	return retorno;
}

//Marca todos os checkboxs de uma pagina
function MarcaTudo(form){

	for (i=0; i< document.getElementById(form).length; i++){
		if (document.getElementById(form).elements[i].type == "checkbox"){
			if (document.getElementById(form).ckb_marca_tudo.checked == true)
			document.getElementById(form).elements[i].checked = true;
			else
			document.getElementById(form).elements[i].checked = false;

		}
	}

}//fim da funcao

function PulaCampo(campo1,campo2,tamanho)
{
	if ( document.campo1.value.length==tamanho )
	document.campo2.focus();
}


//funcao para carregar os links no iframe
function CarregaPaginaIframe(url,iframe)
{
	window.frames[iframe].location.replace(url);
}

//funcao para confirmar saida do sistema
function Sair(url)
{
	if ( confirm('Deseja realmente sair do sistema?') )
	{
		window.self.location = url;
	}
}

// Função para validar e-mail
function validarEmail(campo){
	if(document.getElementById(campo).value.indexOf("@")==-1 || document.getElementById(campo).value.indexOf(".")==-1){
		alert("O campo email não está preenchido corretamente!");
		document.getElementById(campo).focus();
		return false;
	}
}

// Garante que seja digitados apenas numeros e barras e traço
function isNum( caractere )
{
	var strValidos = "0123456789";
	if ( strValidos.indexOf( caractere ) == -1 )
	return false;
	else
	return true;
}

// função utilizada para habilitar ou desabilitar compos na interface, pode receber
// como entrada um array de campos ou a string contendo o id de um campo, caso o
// campo esteja habilitado a função desabilita, caso contrario habilita
function habilitarCampo(campo){
	if(isArray(campo)){
		for(ar in campo){
			habilitar = document.getElementById(campo[ar]).disabled;
			document.getElementById(campo[ar]).disabled = !habilitar;
		}
	}else{
		habilitar = document.getElementById(campo).disabled;
		document.getElementById(campo).disabled = !habilitar;
	}
}
// função que verifica se o objeto é um array ou não
function isArray(obj) {
	return (obj.constructor.toString().indexOf("Array") == -1)? false : true ;
}



//Funcao para ocultar a camada de alerta
function ocultaObjeto(obj){
	document.getElementById(obj).style.visibility='hidden';
	document.getElementById(obj).style.display='none';
}


function carregaPopup(url){
	AbreJanela(url, 'teste', 'width=640,height=480,toolbar=0');
}

/**
* Função que exibe alerta em camadana tela, quando passada a string verde exibe alerta de sucesso, caso contrario de não sucesso
* @param alerta string verde para o sucesso
* @param mensagem string com html e/ou texto
* exemplo exibeAlertaCamada('verde', 'teste', '20%', '-0.9%', 'teste', 0);
*/
function exibeAlertaCamada(alerta, mensagem, posicao_x, posicao_y, titulo, tempo){
	var posicao_x = (posicao_x!='')?posicao_x:'20%';
	var posicao_y = (posicao_y!='')?posicao_y:'-0.9%';
	var tempo = (parseInt(tempo)>0)?tempo:0;

	if (alerta!=""){
		if(alerta=="verde"){
			image = "greenled.png";
			texto = (mensagem!="")?mensagem:"Operação realizada com sucesso.";
		}
		else if(alerta=="vermelho"){
			image = "redled.png";
			texto = (mensagem!="")?mensagem:"Erro ao tentar realizar a operação, tente novamente.";
		}else if (alerta=="amarelo"){
			image = "yellowled.png";
			texto = mensagem;
		}
	}
	
	document.getElementById('exibeAlerta').style.visibility='visible';
	document.getElementById('exibeAlerta').style.display='block';	
	
	mensagem = "<!-- Inicio div exibeAlerta--> "
	+"<div id='exibeAlerta' style=\"position:absolute; z-index:100000; left:"+posicao_x+"; top:"+posicao_y+";\">"
	+"<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"
	+"<tr>"
	+"<td height=\"100%\"><img src=\"imagens/icones/box_01.gif\" width=\"19\" height=\"18\"></td>"
	+"<td height=\"100%\" align=\"center\" valign=\"top\" background=\"imagens/icones/box_02.gif\"></td>"
	+"<td height=\"100%\"><img src=\"imagens/icones/box_03.gif\" width=\"20\" height=\"18\"></td>"
	+"</tr>"
	+"<tr>"
	+"<td background=\"imagens/icones/	box_04.gif\" height=\"100%\">&nbsp;</td>"
	+"<td width=\"0%\" height=\"100%\" align=\"center\" valign=\"top\" bgcolor=\"#FFFFFF\">"
	+"<table width=\"0%\"  border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"
	+"<tr>"
	+"<td width=\"12%\"><img src=\"imagens/icones/16x16/actions/"+image+"\" width=\"16\" height=\"16\" align=\"absmiddle\" vspace=\"5\"></td>"
	+"<td width=\"82%\" class=\"alerta\" valign=\"top\"><strong>"+titulo+"</strong><br>"+texto+"</td>"
	+"<td width=\"6%\" height=\"100%\" valign=\"middle\"><img src=\"imagens/icones/16x16/actions/remove.png\" width=\"16\" height=\"16\" title=\"fechar mensagem\" "
    +"onClick=\"ocultaObjeto('exibeAlerta'); ocultaObjetosHtml('exibeAlerta');\" "
	+"onMouseOver=\"javascript:this.style.cursor='hand';\" vspace=\"5\"> "
	+"</td>"
	+"</tr>"
	+"</table>"
	+"</td>"
	+"<td background=\"imagens/icones/box_06.gif\" height=\"100%\">&nbsp;</td>"
	+"</tr>"
	+"<tr>"
	+"<td width=\"19\" ><img src=\"imagens/icones/box_07.gif\" width=\"19\" height=\"21\"></td>"
	+"<td background=\"imagens/icones/	box_08.gif\">&nbsp;</td>"
	+"<td width=\"0\"><img src=\"imagens/icones/box_09.gif\" width=\"20\" height=\"21\"></td>"
	+"</tr>"
	+"</table>"
	+"</div>"
	+"<!-- Fim do div exibeAlerta-->";
	//alert(mensagem);
	// oculta div sob select, iframe e applet
	ocultaObjetosHtml('exibeAlerta');
	
	if(parseInt(tempo)>0){
		setTimeout("ocultaObjeto('exibeAlerta');ocultaObjetosHtml('exibeAlerta')",tempo);
	}
	document.getElementById('exibeAlerta').innerHTML = mensagem;
}