var COMPUTADORES = "computadores";
var EXCLUIR = "excluir";
var ARVORE = "plat";
var LISTA = "lista";

function valida_cpf(cpf)
      {
      var numeros, digitos, soma, i, resultado, digitos_iguais;
      digitos_iguais = 1;
      if (cpf.length < 11)
            return false;
      for (i = 0; i < cpf.length - 1; i++)
            if (cpf.charAt(i) != cpf.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                  soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                  soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
      }

function valida_cnpj(cnpj)
      {
      var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
      digitos_iguais = 1;
      if (cnpj.length < 14 && cnpj.length < 15)
            return false;
      for (i = 0; i < cnpj.length - 1; i++)
            if (cnpj.charAt(i) != cnpj.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            tamanho = cnpj.length - 2
            numeros = cnpj.substring(0,tamanho);
            digitos = cnpj.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            tamanho = tamanho + 1;
            numeros = cnpj.substring(0,tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
      } 
/*
função que valida se o numero passado eh um cpf ou cnpj válido.
*/
function validaCpfCnpj(numero){

  var tamanho;
  numero  = numero.replace("-","");
  numero  = numero.replace(".","");
  numero  = numero.replace("/","");
  tamanho = numero.length;
 if (tamanho==11){
  if(!valida_cpf(numero)){
   alert("Cpf Invalido!");
   return false;
  }
 }else{
  if (!valida_cnpj(numero)){
   alert("Cnpj Invalido");
   return false;
  }
 } 
   return true; 
}


/*
Abre tela de pesquisa de processo, formatando o tamanho e 
a posição da tela de acordo com a resolução
*/
function abrirPesquisaProcesso()
{
	var left = 0;
	var top = 0;
	var altura =0;
	var largura = 0;
	
	left = (screen.width - 750)/2;
	top = (screen.height - 525)/2;
	altura = 475;
	largura = 750;
	
	var props = 'width='+ largura + ',height=' + altura + ',top='+ top +',left='+ left ;
	window.open("../Processo/WFConsultarProcesso.aspx?campo=txtAnoProcesso", "_blank", props)
}

/****************************************************************
/* permite apenas que sejam digitados caracteres numéricos, ou 
/* os outros caracteres passados como parâmetro
/* Utilizar no evento onKeyPress de input texts ou textarea 
*****************************************************************/
function permitirCaracterNumerico()
{
	var tecla = window.event.keyCode;
	for(var i =0; i < arguments.length; i++)
	{
		if (arguments[i]== String.fromCharCode(tecla))
			return;
	}
	
	if (tecla < 48 || tecla > 57)
	{
		event.keyCode = 0;
	}
}

function Limpar(valor, validos) {
// retira caracteres invalidos da string
var result = "";
var aux;
for (var i=0; i < valor.length; i++) {
aux = validos.indexOf(valor.substring(i, i+1));
if (aux>=0) {
result += aux;
}
}
return result;
} 

//testa se o campo é número
function testarNumero(Form, campo) {

    if ((isNaN (Form.campo.value)) || (Form.campo.value == "")) {

      alert ("Número Inválido!!!");

    }
  }

//essa função faz referência a função limpar
function Formata(campo,tammax,teclapres,decimal) {
var tecla = teclapres.keyCode;
vr = Limpar(campo.value,"0123456789");
tam = vr.length;
dec=decimal

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 <= dec )
{ campo.value = vr ; }

if ( (tam > dec) && (tam <= 5) ){
campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 6) && (tam <= 8) ){
campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
}
if ( (tam >= 9) && (tam <= 11) ){
campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 12) && (tam <= 14) ){
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 - dec, tam ) ; }
if ( (tam >= 15) && (tam <= 17) ){
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 cancelarF5() 
 { 
	var tecla=window.event.keyCode; 
	if (tecla==116){
		event.keyCode=0; 
		event.returnValue=false;
	} 
 } 



  function pcFormataData(vloCampo) {
    var vlsTecla2 = event.keyCode;
    var vlsTecla1 = event.which;
    vlsTecla1 = event.keyCode;

    if ((vlsTecla1 >= 48 && vlsTecla1 <= 57) || (vlsTecla1 >= 96 && vlsTecla1 <= 105)) {
        var vlsStr = "";
        var vlsAux = "";
        var s = "";

        for (x = 0; x <= vloCampo.value.length; x++) {
            if (vloCampo.value.substring(x, x + 1) != '/')
                vlsStr += vloCampo.value.substring(x, x + 1);
        }

        s = vlsStr.substring(0, 2);
        vlsAux = vlsAux + vlsStr.substring(0, 2);
        if (s.length >= 2) {
            if (s >= 01 && s <= 31) {
                vlnDia = s;
                vlsAux = vlsAux + "/";
                s = vlsStr.substring(2, 4);
                vlsAux = vlsAux + s;
                if (s.length >= 2) {
                    if ((s >= 01 && s <= 12) && ((vlnDia >= 01 && vlnDia <= 29) || (vlnDia == 30 && (s != 02)) || (vlnDia == 31 && (s != 02 && s != 04 && s != 06 && s != 09 && s != 11)))) {
                        vlnMes = s;
                        vlsAux = vlsAux + "/";
                        s = vlsStr.substring(4, 8);
                        vlsAux = vlsAux + s;

                        if (s.length >= 4) {
                            if (vlnDia == 29 && vlnMes == 02 && ((s % 4) != 0))
                                vlsAux = vlsAux.substring(0, vlsAux.length - 1);
                        }
                    }
                    else
                        vlsAux = vlsAux.substring(0, vlsAux.length - 1);
                }
            }
            else
                vlsAux = vlsAux.substring(0, vlsAux.length - 1);
        }

        vloCampo.value = vlsAux;
        if (vlsAux.length == 10) {
            try {
                for (x = 0; x <= document.forms[0].length - 1; x++) {
                    if (document.forms[0].elements[x].name == vloCampo.name) {
                        document.forms[0].elements[x + 1].focus();
                        break;
                    }
                }
            }
            catch (e) {
                return true;
            }
        }
    }
}

/****************************************************************
* Função para efetuar a troca de imagens para dar um efeito visual
* no evento onmouseover.
* Como padrão, as imagens utilizadas devem ter uma imagem equivalente,
* terminando com o complemento "_over". A imagem será alternada, quando 
* o mouse está sobre a imagem, e quando está fora.
* Ex. de nomes de imagens:
* livro.gif
* livro_over.gif
* documento.gif
* documento_over.dif
* Para facilitar o uso das imagens nas telas de listagem e centralizar mudanças,
* caso necessário, existem algumas constantes definidas no topo deste arquivo,
* que são utilizadas nas telas de listagem
*****************************************************************/
function swapImg(objeto)
{
	var arquivo = objeto.src;
	
	//se a imagem possui _over no nome, retira o _over
	if (arquivo.indexOf("_over") > 0)
	{
		arquivo = arquivo.replace("_over","");
	}
	else
	{
		//caso contrário adiciona o over
		arquivo = arquivo.replace(".gif","_over.gif");
	}
	
	objeto.src = arquivo;
}


/****************************************************************
* Função responsável por abrir uma janela de seleção de usuário
* 
* Parâmetros:
* valorProcurado - O valor que será procurado ('nome' ou 'cpf')
* campoAlterado - nome do campo do form (na janela que chamou a função) 
*                 que deverá receber este valor procurado.
*****************************************************************/
function popupUsuario(valorProcurado,campoAlterado,valorProcurado2,campoAlterado2,callback) {
	var parametros = "valorProcurado=" + valorProcurado + "&campoValor=" + campoAlterado;

	//testa se vieram os outros parâmetros de valor procurado
	if (arguments.length >= 4 )
	{
		parametros += "&valorProcurado=" + valorProcurado2 + "&campoValor=" + campoAlterado2;
	}
	
	//testa se veio o parâmetro callback
	if (arguments.length == 5)
	{
		parametros += "&callback=" + callback;
	}
	
	return abrirJanela("../Usuarios/WFPopupUsuario.aspx?" + parametros,400,250);
}

function abrirJanela(url,largura,altura) {
	return window.open(url,"popup","TOP=100,LEFT=100,SCROLLBARS=yes,RESIZABLE=false,TOOLBARS=false,MENU=false,WIDTH=" + largura + ",HEIGHT=" + altura);
}

/****************************************************************
* Como o mecanismo de templates faz com q o framework gere nomes 
* como _ctl0:NOMEOBJETO, por exemplo, este método procura objetos que
* contenham parte do nome passado como parâmetro, que dá uma
* certa margem de erro...
* 
* Parâmetros:
* tipoElemento - String que indica o tipo de elemento (input, select, div)
* nome - Nome do elemento (no exemplo acima seria NOMEOBJETO)
*****************************************************************/
function buscarObjeto(tipoElemento,nome)
{
	var inputs = document.getElementsByTagName(tipoElemento);

	for (var i = 0; i < inputs.length; i++) 
	{
		if (inputs[i].name.indexOf(nome) >= 0 )
		{
			return inputs[i];
		}
	}

	return null;
}

/****************************************************************
* Função responsável por transferir valores entre options.
* Os options que estiverem selecionados no select origem serão transferidos
* para o select destino
*
* Parâmetros:
* origem - Objeto select (HTML) que terá os options transferidos
* destino - Objeto select (HTML) que receberá os options transferidos
*****************************************************************/
function transferirOption(origem,destino)
{
	if (origem.selectedIndex > -1) {
		for (var i = origem.options.length - 1; i >= 0; i--) {
			if (origem.options[i].selected) {
				var o = document.createElement("OPTION");
				destino.options.add(o);
				//Copia os valores do objeto a ser transferido
				o.text = origem.options[i].text;
				o.value = origem.options[i].value;
				//remove o elemento transferido
				origem.remove(i);		
			}
		}
	}
}

var QT_MIN_DIGITOS_HORA = 3;
var ZERO = new String("0");

/**********************************************************************
Método para ser utilizado no evento onKeyUp para formatar a hora.
Faz com que os valores do campo estejam sempre no formato HH:MM,
funcionando como máscara.
onkeyup="formatarhora(this)"
Parâmetros:
- obj: O próprio input text onde estará sendo levantado o evento
**********************************************************************/
function formatarHora(obj) {
	mascara(obj,":",QT_MIN_DIGITOS_HORA);
}

function mascaraDecimal(obj) {
	mascara(obj,",",2);
}

/**********************************************************************
Método para ser utilizado no evento onKeyUp para funcionar como máscara.
Faz com que os valores do campo estejam sempre no formato XXyWW
Onde:
XX - valores à esquerda do caracter separador
y - caracter separador
WW - valores à direita do caracter separador
**********************************************************************/
function mascara(obj,caracter,qtMinimaDigitos) {
	var valorAtual = obj.value.replace(caracter,"");
	valorAtual = removerCaracteresNaoNumericos(valorAtual);

	if (valorAtual.length < QT_MIN_DIGITOS_HORA) {
		valorAtual = acrescentarZeroAEsquerda(valorAtual,QT_MIN_DIGITOS_HORA);
	}
	else {
		valorAtual = removerZeroAEsquerda(valorAtual,QT_MIN_DIGITOS_HORA);
	}

	valorAtual = acrescentarMascara(valorAtual,caracter);

	obj.value = valorAtual;
}

/**********************************************************************
Função Auxiliar de mascara
Deixa apenas os caracteres numéricos em um texto, removendo o que não for
número.
**********************************************************************/
function removerCaracteresNaoNumericos(valor) {
	var novoValor = "";
	for (var i = 0; i < valor.length; i++) {
		var digito = valor.charAt(i);
		if (digito != " " && !isNaN(digito)) {
			novoValor += "" + digito;
		}
	}

	return novoValor;
}

/**********************************************************************
Função Auxiliar de mascara
Acrescenta zeros à esquerda para que os horários fiquem como nos possíveis
formatos abaixo:
0:00
0:01
0:10
* OBS: Esta função não trabalha com os dois pontos (":"), mas no exemplo
ele é exibido como ficaria no resultado final de formatarHora
**********************************************************************/
function acrescentarZeroAEsquerda(valorAtual, qtMinimaDigitos) {
	while (valorAtual.length < qtMinimaDigitos) {
		valorAtual = ZERO + valorAtual;
	}

	return valorAtual;
}

/**********************************************************************
Função Auxiliar de mascara
Remove os zeros à esquerda que possam existir em horários maiores que uma
hora. Ex: 06:00 ficaria 6:00
* OBS: Esta função não trabalha com os dois pontos (":"), mas no exemplo
ele é exibido como ficaria no resultado final de formatarHora
**********************************************************************/
function removerZeroAEsquerda(valorAtual,qtMinimaDigitos) {

	while (valorAtual.indexOf(ZERO) == 0 && valorAtual.length > qtMinimaDigitos) {
		valorAtual = valorAtual.replace(ZERO,"");
	}

	return valorAtual;
}

/**********************************************************************
Função Auxiliar de mascara
Acrescenta os dois pontos na antepenúltima posição da string que contém
o tempo, no formato de horas:
000 resultaria em 0:00, 001 resultaria em 0:01, etc
**********************************************************************/
function acrescentarMascara(valorAtual,separador) {
	var tamanho = valorAtual.length;

	return valorAtual.substring(0,tamanho - 2) + separador + valorAtual.substring(tamanho - 2, tamanho);
}

/**********************************************************************
Função para setar o foco no primeiro campo do formulario
**********************************************************************/
function setarFocu(){
	
	for(i=0;i<document.all.length;i++){
		if(document.all.item(i).type == 'text' || document.all.item(i).type == 'select-one' || document.all.item(i).type=='password' || document.all.item(i).type=='file' || document.all.item(i).type=='textarea')
		{
			if(!document.all.item(i).disabled){
				eval("document.all.item(i).focus()");
				break;
			}
		}
	}
}

/**********************************************************************
Função para setar o foco no primeiro campo apos o campo informado no parametro
**********************************************************************/
function setFocuNext(campo){
	var campoAchado = -1;
	for(i=0;i<document.all.length;i++){
		if(document.all.item(i).id==campo){
			campoAchado = i;
			break;
		}
	}
	if(campoAchado==-1){
		return;
	}
	for(i=campoAchado+1;i<document.all.length;i++){
		if(document.all.item(i).type == 'text' || document.all.item(i).type == 'select-one' || document.all.item(i).type=='password' || document.all.item(i).type=='file' || document.all.item(i).type=='textarea')
		{
			if(!document.all.item(i).disabled){
				eval("document.all.item(i).focus()");
				break;
			}
		}
	}
}


function limparCampos(){
	for(i=0;i<document.all.length;i++){
		if(document.all.item(i).type == 'text' || document.all.item(i).type=='password' || document.all.item(i).type=='file' || document.all.item(i).type=='textarea')
		{
			document.all.item(i).value = '';
		}
		if(document.all.item(i).type == 'select-one')
		{
			document.all.item(i).options.selectedIndex = 0;
		}
	}
}

function excluir(){
	var parametros = excluir.arguments;
	var mensagem;
	if(parametros.length>0){
		mensagem = parametros[0];
	}else{
		mensagem = "informado";
	}
	if (confirm ("Deseja excluir o item " + mensagem + "?"))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function verificarOpcaoFase(mensagem){
	var parametros = verificarOpcaoFase.arguments;
	//var mensagem;
	/*
	if(parametros.length>0){
		mensagem = parametros[0];
	}else{
		mensagem = "informado";
	}*/
	if (confirm ("Deseja alterar para a Fase " + mensagem + "?"))
	{
		return true;
	}
	else
	{
		return false;
	}
}


function abrirJanelaPesquisa(url) {
/*
	funcao que abre um novo browser para pesquisa	

*/
		var newWindow;
		var left = (screen.width - 400) / 2;
		var top = (screen.height - 500) / 2;
		var props = 'scrollBars=no,resizable=no,toolbar=no,menubar=no,location=no,directories=no,width=380,height=368'+',top='+top+',left='+left;
		newWindow = window.open(url, "Pesquisa", props);
}

function voltar(url){
	window.open(url,"target=principal");
}

function mensagem(texto){
	if (confirm (texto))
	{
		return true;
	}
	else
	{
		return false;
	}
}

/****************************************************************
/* verifica se o textarea está com tamanho menor ou igual que 
 * o definido
*****************************************************************/
function textCounter( field, maxlimit ) {
  if ( field.value.length > maxlimit )
  {
	event.keyCode = 0;
    //field.value = field.value.substring( 0, maxlimit );
    alert( 'Este campo so pode ter ' + maxlimit + ' caracteres.' );
    return false;
  }
}

/****************************************************************
/* chama a pagina inicial
*****************************************************************/
function paginaInicial() {
	window.open("../","_top");
}


function Trim(TRIM_VALUE){
	if(TRIM_VALUE.length < 1){
		return"";
	}
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	return TRIM_VALUE;

} //En


function RTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	var iTemp = v_length -1;
	if(v_length < 0){
		return"";
	}
	
	while(iTemp > -1){
		if(VALUE.charAt(iTemp) == w_space){
		}
		else{
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}
		iTemp = iTemp-1;
	} //End While
	return strTemp;

} //End Function

function LTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	var iTemp = 0;
	
	if(v_length < 1){
		return"";
	}
	while(iTemp < v_length){
		if(VALUE.charAt(iTemp) == w_space){
		}
		else{
			strTemp = VALUE.substring(iTemp,v_length);
			break;
		}
		iTemp = iTemp + 1;
	} //End While
	return strTemp;
} //End Function