// JavaScript Document

//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';
	}
}

// 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;
	
	//datas devem seguir padrao mm/dd/yyyy
	dataInicial = dataInicial.substr(3,2)+'/'+dataInicial.substr(0,2)+'/'+dataInicial.substr(6,4);
	dataFinal = dataFinal.substr(3,2)+'/'+dataFinal.substr(0,2)+'/'+dataFinal.substr(6,4);
	
	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 MostraDataAtual()
{
	var mydate=new Date();
	var year=mydate.getYear();
	if (year<2000)
	year="19"+year
	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ça","Quarta","Quinta","Sexta","Sábado");
	var montharray=new Array("janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro",
	"outubro","novembro","dezembro");
	document.write("<font color='FF6600' face='Tahoma, Verdana, Arial'><b>"+dayarray[day]+", "+daym+" de "+montharray[month]+" de "+year+"</b></font>");

}

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


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;
	if (tecla==0 || tecla==8){
		return true;
	}else 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, com o id do form
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.getElementById(campo1).value.length==tamanho )
	document.getElementById(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 e-mail não está preenchido corretamente!");
		document.getElementById(campo).focus();
		return false;
	}else return true;
}

// 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 que retorna true se a tecla entre for digitada
function enter(e){
	if (window.event){
		x = window.event.keyCode;
	}else if(e){
		x = e.which;
	}else{
		x = null;
	};
	if(x == 13){
		return true;
	};
	return false;
};

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

function buscaLinha(tabela,nome){
	var obj=document.getElementById(tabela);
	for (cont=0;cont<obj.rows.length;cont++)
	 if (obj.rows[cont].name==nome) return cont;
}

/**
* 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;
		}
	}

	 var navegador = navigator.appName;
	 //Para colocar efeito de alpha no fundo do png
	 if (navegador == "Microsoft Internet Explorer"){
		caminho_imagem = "src=\"imagens/spacer.png\" style=\"width: 16px; height: 16px; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=imagens/16x16/actions/"+image+", sizingMethod=scale);\"";
	 }else{
		caminho_imagem = "src=\"imagens/16x16/actions/"+image+"\"";		
	 }
	 
	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+"\">"
	//linha 1
	+"<div style='float:left;width:289px'>"
	+"<div style='float:left;width:19px;background-image:url(imagens/box_01.gif);background-repeat: no-repeat;	height:18px;background-position:bottom'></div>"
	+"<div style='float:left;width:250px;background-image:url(imagens/box_02.gif);background-repeat: repeat-x;	height:18px;background-position:bottom'></div>"	
	+"<div style='float:left;width:20px;background-image:url(imagens/box_03.gif);background-repeat: no-repeat;	height:18px;background-position:bottom'></div>"
	+"</div>"
	//fim da linha 1
	//linha 2
	+"<div style='float:left;width:289px;background-color:#FFFFFF;height:100%'>"
	+"<div style='float:left;width:19px;height:100%;background-image:url(imagens/box_04.gif);background-repeat: repeat-y'></div>"
	+"<div style='float:left;width:250px;background-color:#FFFFFF;font-family:verdana;font-size:10px;text-align:justify'>"
	+"<div style='float:left;width:19px;height:100%;vertical-align:middle;'>"
	+"<img "+caminho_imagem+" align='absmiddle' vspace='5'>"
	+"</div>"
	+"<div style='float:left;width:212px;height:100%;vertical-align:top;text-align:justify;padding: 3px'>"	
	+"<div style='text-align:center;'><strong>"+titulo+"</strong></div>"	
	+texto+""
	+"</div>"	
	+"<div style='float:left;width:19px;height:100%;vertical-align:middle'>"	
	+"<img align=\"absmiddle\" src=\"imagens/16x16/actions/remove.png\" width=\"16\" height=\"16\" title=\"fechar mensagem\" "
    +"onclick=\"ocultaObjeto('exibeAlerta'); ocultaObjetosHtml(document.getElementById('exibeAlerta'));\" "
	+"onmouseover=\"javascript:this.style.cursor='hand';\" vspace=\"5\"> "
	+"</div>"	
	+"</div>"
	+"<div style='float:left;width:20px;background-image:url(imagens/box_06.gif);background-repeat: repeat-y;height:100%'></div>"
	+"</div>"
	//fim da linha 2
	//linha 3
	+"<div style='float:left;width:289px;'>"
	+"<div style='float:left;width:19px;background-image:url(imagens/box_07.gif);background-repeat: no-repeat;	height:21px'></div>"
	+"<div style='float:left;width:250px;background-image:url(imagens/box_08.gif);background-repeat: repeat-x;	height:21px'></div>"
	+"<div style='float:left;width:20px;background-image:url(imagens/box_09.gif);background-repeat: no-repeat;	height:21px'></div>"
	+"</div>"
	//fim da linha 3	
	+"</div>"
	+"<!-- Fim do div exibeAlerta-->";
	// oculta div sob select, iframe e applet
	ocultaObjetosHtml(document.getElementById('exibeAlerta'));
	
	if(parseInt(tempo)>0){
		setTimeout("ocultaObjeto('exibeAlerta');ocultaObjetosHtml(document.getElementById('exibeAlerta'))",tempo);
	}
	document.getElementById('exibeAlerta').innerHTML = mensagem;
}
// função paragerara mensagem de erro mostrada pela função debugJS
function mostraErro(msg, url, linenumber){
	alert('Mensagem de Erro = '+msg+'\nURL= '+url+'\nNumero da Linha = '+linenumber);
	return true;
}

// Função para debugar erros java script na tela
function debugJS(){
	window.onerror=mostraErro;
}

function abrePopUpCentro(url, vwidth, vheight,vscroll){
	//pega a resolução do visitante
	w = screen.width;
	h = screen.height;
	
	//divide a resolução por 2, obtendo o centro do monitor
	meio_w = w/2;
	meio_h = h/2;

	//diminui o valor da metade da resolução pelo tamanho da janela, fazendo com q ela fique centralizada
	altura2 = vheight/2;
	largura2 = vwidth/2;
	meio1 = meio_h-altura2;
	meio2 = meio_w-largura2;
		
	window.open(url,'','toolbar=0,menubar=0,width=' + vwidth + ',height=' + vheight + ',top=' + meio1 + ',left=' + meio2 + ',scrollbars='+vscroll+'');
}

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

/*
onkeypress = "return formataMoeda(this, '.', ',', event);"
*/
function formataMoeda(campo, separador_mil, separador_dec, e){
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	
	var whichCode = (window.Event) ? e.which : e.keyCode;
		
    switch(e.keyCode)
    {
        case 8:     // backspace
        case 9:     // tab
        case 37:    // left arrow
        case 39:    // right arrow
        case 46:    // delete
        e.returnValue = true;
        return;
    }		

	if (whichCode == 13) return true; // Enter
	
	key = String.fromCharCode(whichCode); // Get key value from key code

	if (strCheck.indexOf(key) == -1) return false; // Not a valid key

	len = campo.value.length;

	for(i = 0; i < len; i++)
	if ((campo.value.charAt(i) != '0') && (campo.value.charAt(i) != separador_dec)) break;

	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(campo.value.charAt(i))!=-1) aux += campo.value.charAt(i);

	aux += key;
	len = aux.length;

	if (len == 0) campo.value = '';

	if (len == 1) campo.value = '0'+ separador_dec + '0' + aux;

	if (len == 2) campo.value = '0'+ separador_dec + aux;

	if (len > 2)
	{
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--)
		{
			if (j == 3)
			{
				aux2 += separador_mil;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}

		campo.value = '';
		len2 = aux2.length;

		for (i = len2 - 1; i >= 0; i--)
		campo.value += aux2.charAt(i);
		campo.value += separador_dec + aux.substr(len - 2, len);
	}
	return false;
}

/* 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);
	}
}

//onkeypress="return mascararData(this, '##/##/####',event);"
function mascararData(src, mask, evento){
	if (filtraTecla(src,evento)==true){	
		return formatarQualquerMascara(src, mask);
	}else{
		return false;
	}
}

/* funcao para contar a qtd de caracteres e definir limite */
function contarLimiteCaracteres(campo_texto,campo_contador, limite, frase)
{
   inputString = campo_texto;
   inputContador = document.getElementById(campo_contador).value;
   inputContador = inputString.value.length + 1;

	if (inputString.value.length > 0)
	   document.getElementById(campo_contador).value = inputString.value.length;

	if( inputString.value.length > limite ){
		if (frase!=""){
			alert(frase);	
		}else{
			alert("Por favor, digite no máximo "+limite+" caracteres neste campo.\nSó serão aceitos os "+limite+" caracteres digitados.");
		}
	inputString.focus();
	}
  inputString.value = inputString.value.substring(0,limite);
}

// esta função funciona no FF e no IE testado.  07/05/2007
// Mangabeira
function apenasNumero(e){
//<input type="text" onkeypress="javascript:return apenasNumero(event);">
    var tecla=new Number();
     if(window.event) {
 		tecla = e.keyCode;
    }else if(e.which) {
		tecla = e.which;
    }else {
		return true;
    }

    if(((tecla < 48) || (tecla > 57)) && (tecla!=8)){// bloqueia caracateres não numericos, com excessão do backspace
		return false;
    }
}
