/*
FUNÇÕES ÚTEIS PARA O SISTEMA
*/

// Recebe campos para validar, e retorna um array
function formatar(mascara, documento){
  var i = documento.value.length;

  var saida = mascara.substring(0,1);

  var texto = mascara.substring(i)

  if (texto.substring(0,1) != saida){
	documento.value += texto.substring(0,1);
  }
  
}
function verificaCampos(campos){
	var letra;
	var cont = 0;
	var verificaVazio = 1;
	camposParaValidar = new Array(1);
	for (i=0;i<campos.length;i++){
		letra = campos.charAt(i);
		if (letra == ','){
			camposParaValidar.length++;
			cont = cont + 1;
			verificaVazio = 1;
		}
		else{
			if (verificaVazio == 1){
				camposParaValidar[cont] = letra;
				verificaVazio = 0;
			}
			else
				camposParaValidar[cont] = camposParaValidar[cont] + letra;
		}
	}
	return camposParaValidar;
}

//Validar o email do setor
function verificaemail(txtemail){
	email = document.getElementById(txtemail).value;
	alert(email);
	var temp = email.split("@");
	var valida = new Array(true,false);

	if (temp.length == 2 ){
		if (temp[0].length > 0){
			for (i=0; i < temp[0].length; i++){
				if (temp[0][i] == ".")
					valida[0] = false;
			}

			for (i=0; i < temp[1].length; i++){
				if (temp[1][i] == ".")
					valida[1] = true;
			}
		}
		else
			valida[0] = false;
	}
	else
		valida[0] = valida[1] = false;

	if (valida[0] && valida[1]){
		return true;
	}
	else{
		alert("Email inválido!");
		document.getElementById(txtemail).value = '';
		document.getElementById(txtemail).select();
		document.getElementById(txtemail).focus();	
		return false;
	}
 }


// Verifica se os campos estão em branco
function validaCampos(idForm,t){
	var num;
	var k;
	nomeForm = document.getElementById(idForm);
	num = t.length;
	for (i=0;i<t.length;i++){
		if (nomeForm.elements[t[(t.length - 1) - i]].value == ""){
			num = num - 1;
			k = t[(t.length - 1) - i];
		}
	}
	if (num != t.length){
		alert("Preencha os campos Corretamente!");
		nomeForm.elements[k].focus();
		return false;
	}
	else{
		return true;
	}
}

//FUNÇÃO PARA CONFIRMAR A EXCLUSOA
function confirmaDelete(strTexto)
{
	var agree=confirm("Tem certeza que deseja excluir ?");
	if (agree)
		return true;
	else
		return false;
}
//FUNÇÃO PARA CONFIRMAR A EXCLUSAO COM VERIFICACAO DE PERMISSAO
function confirmaDelete1(intval)
{
    var nivel= intval;

    if(nivel==''){
         alert("Não recebeu valor como parametro");
         return false;
    }
     
    if(nivel==1){
	      var agree=confirm("Tem certeza que deseja excluir ?");

	      if (agree){
		     return true;
		  }
	      else{
             return false;
          }
    }
    if(nivel==2){
       alert('Usuário sem permissão!!!');
       return false;
    }
    if(nivel==3){
       alert('Usuário sem permissão!!!');
       return false;
    }
}

//FUNCAO PARA VALIDAR O CADASTRO DE SETOR
function cadastroSetor()
{
		if (document.frmcadastrarprocesso.txtsiglasetor.value == "")
		{
				alert('Por favor preencha o campo SIGLA.');				
				document.frmcadastrarprocesso.txtsiglasetor.focus();
				return false;
		}
		else
		if (document.frmcadastrarprocesso.txtdescricaosetor.value == "")
		{
				document.frmcadastrarprocesso.txtdescricaosetor.focus();
				alert('Por favor preencha o campo DESCRIÇÃO.');
				return false;
		}
		else
			document.frmcadastrarprocesso.submit();
}

//FUNCAO PARA VALIDAR O CADASTRO DE NATUREZA
function cadastroNatureza()
{
		if (document.frmcadastrarprocesso.txtdescricaonatureza.value == "")
		{
				document.frmcadastrarprocesso.txtdescricaonatureza.focus();
				alert('Por favor preencha o campo DESCRIÇÃO.');
				return false;
		}
		else
		{
		    document.frmcadastrarprocesso.submit();
		}
}
//FUNÇÃO PARA HABILITAR/DESABILITAR O CAMPO "MOTIVO PARALISADO" NO CCADASTRO DE PROCESSOS
function habilita(form)
{ 
	form.txtmotivo.disabled = false;
}
function desabilita(form)
{ 
	form.txtmotivo.value="";
	form.txtmotivo.disabled = true;
}
//FIM DA FUNÇÃO

//FUNÇÃP PARA ABRIR A POPUP COM O RELATÓRIO DA ETIQUETA CAPA
function popup(f,l,a)
{
var i = (screen.width - l)/2;
var j = (screen.height - a)/2;
  window.open(f,'janelapopup','height='+a+',width='+l+',top='+j+',left='+i); 
}
//FUNÇÃO QUE COLOCA O FOCO DO CURSOR NO CAMPO DO FORM
function setFocus()
{
	document.frmlogin.txtusuario.select();
	document.frmlogin.txtusuario.focus();
}

//FUNÇÃO QUE COLOCA O FOCO DO CURSOR NO CAMPO DO FORM
function setFocusTramitar()
{
	document.frmcadastrarprocesso.txtnumprocesso.select();
	document.frmcadastrarprocesso.txtnumprocesso.focus();
}


/* FUNÇÕES PARA MOSTRAR E ESCONDER OS DIV'S */
function mudaDiv(divId,checkId)
{
	var div = document.getElementById(divId);
	var check = document.getElementById(checkId);
	if (check.checked)
	{
		div.className = "aparece";
	}
	else
	{
		div.className = "some";
	}
}

/**
 * FUNÇÃO QUE DESABILITA OS CAMPOS NUM PROCESSO E ANO CASO SEJA SELECIONADO O ORGÃO 41010
 * PARA PODER PEGAR O NUMERO
 */
function verificaOrgaoSelecionado()
{
   orgao = document.getElementById("txtnumsecretaria").value;
   
   //Se for 41010 desabilita do campos
   if( orgao == '41010' )
   {
      document.getElementById("txtnumprocesso").disabled    = true;
      document.getElementById("txtnumprocessoano").disabled = true;
   }
   else
   {
      document.getElementById("txtnumprocesso").disabled    = false;
      document.getElementById("txtnumprocessoano").disabled = false;
   }
}

//FUNCAO PARA VALIDAR O CADASTRO DE UNIDADES
function cadastroUnidade()
{
		if (document.frmcadastrarprocesso.txtsiglasetor.value == "")
		{
				alert('Por favor preencha o campo SIGLA.');				
				document.frmcadastrarprocesso.txtsiglasetor.focus();
				return false;
		}
		else if (document.frmcadastrarprocesso.txtdescricaosetor.value == "")
		{
				document.frmcadastrarprocesso.txtdescricaosetor.focus();
				alert('Por favor preencha o campo DESCRIÇÃO.');
				return false;
		}
		else
		{
			document.frmcadastrarprocesso.submit();
		}
}

function numbersonly(myfield, e, dec)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) || 
    (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;

// decimal point jump
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}

//-->

function upperCase(event) {
    var keynum;

    // IE
    if (window.event) {
        keynum = event.keyCode;
    }
    // Netscape/Firefox/Opera
    else if (event.which) {
        keynum = event.which;
    }

    if ((keynum >= 97 && keynum <= 122) || (keynum >= 224 && keynum <= 255)) {
        // converte de acordo com o valor decimal da tecla na tabela ascii    
        keynum = keynum - 32;
        
        // IE
        if (window.event) {
            window.event.keyCode = keynum;
        }
        // firefox e outros que usam o Gecko
        else if (event.which) {
            var newEvent = document.createEvent("KeyEvents");
            newEvent.initKeyEvent("keypress", true, true, document.defaultView,
                        event.ctrlKey, event.altKey, event.shiftKey,
                        event.metaKey, 0, keynum);
            event.preventDefault();
            event.target.dispatchEvent(newEvent);
        }
    }
    
    return true;
}

// FUNÇÃO AUTO TAB
	
	function autoTab(input,len, e) {
		var isNN = (navigator.appName.indexOf("Netscape")!=-1);
		var keyCode = (isNN) ? e.which : e.keyCode;
		var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
		if(input.value.length >= len && !containsElement(filter,keyCode)) {
			input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
		}
	
	function containsElement(arr, ele) {
		var found = false, index = 0;
		while(!found && index < arr.length)
		if(arr[index] == ele)
			found = true;
		else
			index++;
		return found;
	}

	function getIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
			if (input.form[i] == input)index = i;
			else i++;
		return index;
	}

	return true;
}
// End -->

//INICIO
//Enter como TAB
function tabOnEnter (field, evt) {
	var keyCode = document.layers ? evt.which : document.all ? evt.keyCode : evt.keyCode;
	if (keyCode != 13)
		return true;
	else {
		getNextElement(field).focus();
		return false;
	}
}
	 
function getNextElement (field) {
	var form = field.form;
	for (var e = 0; e < form.elements.length; e++)
	if (field == form.elements[e])
		break;
	return form.elements[++e % form.elements.length];
}

// Início do código de Aumentar/ Diminuir a letra
 
// Para usar coloque o comando: "javascript:mudaTamanho('tag_ou_id_alvo', -1);" para diminuir
// e o comando "javascript:mudaTamanho('tag_ou_id_alvo', +1);" para aumentar
 
	var tagAlvo = new Array('p'); //pega todas as tags p//
 
	// Especificando os possíveis tamanhos de fontes, poderia ser: x-small, small...
	var tamanhos = new Array( '9px','10px','11px','12px','13px','14px','15px','16px','17px','18px','24px' );
	var tamanhoInicial = 2;
	
function mudaTamanho( idAlvo,acao ){

	if (!document.getElementById) return
	var selecionados = null,tamanho = tamanhoInicial,i,j,tagsAlvo;
	tamanho += acao;
	if ( tamanho < 0 ) tamanho = 0;
	if ( tamanho > 10 ) tamanho = 10;
	tamanhoInicial = tamanho;
	if ( !( selecionados = document.getElementById( idAlvo ) ) ) selecionados = document.getElementsByTagName( idAlvo )[ 0 ];
  
	selecionados.style.fontSize = tamanhos[ tamanho ];
	
	for ( i = 0; i < tagAlvo.length; i++ ){
		tagsAlvo = selecionados.getElementsByTagName( tagAlvo[ i ] );
		for ( j = 0; j < tagsAlvo.length; j++ )
			tagsAlvo[ j ].style.fontSize = tamanhos[ tamanho ];
	}
}
//FIM