// ControlMin JS Api
function fcnTransVirgula() {
	str = String.fromCharCode(event.keyCode).replace(",",".");
	event.keyCode = str.charCodeAt(0);
}
function fcnUpperCase() {
	strLo = String.fromCharCode(event.keyCode).toUpperCase();
	event.keyCode = strLo.charCodeAt(0);
}
function fcnSetOrder(campo) {
	document.getElementById('o').value = campo;
}

/* Função para habilitar todos os campos do formulário para passar os campos com ENTER */
function fcnConfInputs() { 
	for (var i=0; i<document.forms[0].elements.length; i++) {
   		if (document.forms[0].elements[i].type == "text") {
			document.forms[0].elements[i].onkeydown=function(){fcnFocusNext()}; 
		}
	}
}

/* Função que muda de campo quando for pressionado ENTER */
function fcnFocusNext() {
	if(event.keyCode==13) event.keyCode=9;
}

/* Função que habilita todos os campos do formulário a submeter o formulário quando pressionado ENTER */
function fcnSubmitInputs() { 
	for (var i=0; i<document.forms[0].elements.length; i++) {
   		if (document.forms[0].elements[i].type == "text") {
			document.forms[0].elements[i].onkeydown=function(){fcnConfirmarConsulta()}; 
		}
 		if (document.forms[0].elements[i].type == "password") {
			document.forms[0].elements[i].onkeydown=function(){fcnConfirmarConsulta()}; 
		}		
	}
}

/* Função que limpa todos os campos do formulário  */
function fcnLimpaCampos() { 
	for (var i=0; i<document.forms[0].elements.length; i++) {
   		if ((document.forms[0].elements[i].type == "text") || (document.forms[0].elements[i].type == "textarea")) {	
			if (document.forms[0].elements[i].readOnly == false) {					
				document.forms[0].elements[i].value = '';			
			}
		}
	}
}

/* 
 * Função para submeter o relatório quando for pressionar ENTER 
 * OBS: A função fcnConfirmar() é a função padrão para submeter formulários.
 */
function fcnConfirmarConsulta() { 
	if (event.keyCode == 13) {
		fcnConfirmar();
	}
}       
function fcnOnlyNum() {
	var caract = new RegExp(/^[0-9a-zA-Z]+$/i);
	var caract = caract.test(String.fromCharCode(event.keyCode));

	if(!caract){
		event.keyCode=0;
		return;
	}
}
function fcnOnlyNum2() {
	var caract = new RegExp(/^[0-9.,]+$/i);
	var caract = caract.test(String.fromCharCode(event.keyCode));

	if(!caract){
		event.keyCode=0;
		return;
	}
}
function fcnExpulsa() {
	alert('Você não tem acesso a essa sessão (Tela: <%=idTela%>)');
	history.back();
}

/**
 * Função para formatar campos especiais que necessitam de uma máscara de edição.
 * @param tipo: Tipo de formatação.
 * @param nome: Nome do campo a ser formatado.
 */
function mask(tipo, campo, e) {	
	var codigo;
	if(window.event) {
		codigo = event.keyCode
	} else { 
		if(e.which) {
			codigo = e.which
		}
	}		
//	alert(codigo);

	if (codigo == 0 || codigo == 8 || codigo == 9 || codigo == 46 || codigo == 88 || codigo == 120) {
		return true;
	}
	
	var str = codigo.toString();
//	alert(str);
	if (str == 'undefined') {
		return true;
	}
	
	if (codigo < 48) { return false; } 
    if (codigo > 57) { return false; } 		
	
//	alert('entrou');
//	alert('tipo: '+tipo);
//	alert('campo: '+campo);
	len = document.getElementById(campo).value.length;
//	alert('len: '+len);
	cmp = document.getElementById(campo);
//	alert('cmp: '+cmp.value);
//	if (isNaN(String.fromCharCode(codigo))) { return false; }

	if (tipo == 'cep') {
		if (len == 2) { cmp.value = cmp.value + '.'; return; }
		if (len == 6) { cmp.value = cmp.value + '-'; return; }
		if (cmp.value.charAt(2) != '.') { keyCode = 0 };
		if (cmp.value.charAt(6) != '-') { keyCode = 0 };
	}
	if (tipo == 'ha') {
		if (len == 2) { cmp.value = cmp.value + '.'; return; }
		if (len == 5) { cmp.value = cmp.value + ','; return; }
		if (len > 7) { return false; }
		if (cmp.value.charAt(2) != '.') { keyCode = 0 };
		if (cmp.value.charAt(5) != '.') { keyCode = 0 };
		
	}

	if (tipo == 'cpf') {
		if (len == 3) { cmp.value = cmp.value + '.'; return; }
		if (len == 7) { cmp.value = cmp.value + '.'; return; }
		if (len == 11) { cmp.value = cmp.value + '-'; return; }
		if (len > 13) { return false; }
		if (cmp.value.charAt(3) != '.') { keyCode = 0 };
		if (cmp.value.charAt(7) != '.') { keyCode = 0 };
		if (cmp.value.charAt(11) != '-') { keyCode = 0 };
	}

	if (tipo == 'cnpj') {
		if (len == 2) { cmp.value = cmp.value + '.'; return; }
		if (len == 6) { cmp.value = cmp.value + '.'; return; }
		if (len == 10) { cmp.value = cmp.value + '/'; return; }
		if (len == 15) { cmp.value = cmp.value + '-'; return; }
		if (len > 17) { return false; }
		if (cmp.value.charAt(3) != '.') { keyCode = 0 };
		if (cmp.value.charAt(7) != '.') { keyCode = 0 };
		if (cmp.value.charAt(11) != '/') { keyCode = 0 };
		if (cmp.value.charAt(16) != '-') { keyCode = 0 }
	}
	
	if ( (tipo == 'tel') || (tipo == 'telefone') || (tipo == 'cel') || (tipo == 'celular') || (tipo == 'fax') ) {
		if (len == 2) { cmp.value = cmp.value + ' '; return; }
		if (len == 7) { cmp.value = cmp.value + '-'; return; }
		if (cmp.value.charAt(2) != ' ') { keyCode = 0 };
		if (cmp.value.charAt(7) != '-') { keyCode = 0 }
	}
	
	if ( (tipo == 'mip') || (tipo == 'map') || (tipo == 'fx1') || (tipo == 'fx2') || (tipo == 'fx3') ) {
		if (len == 1) { cmp.value = cmp.value + '.'; return; }
		if (cmp.value.charAt(1) != '.') { keyCode = 0 };
	}	
	
	if (tipo == 'hectare') {
		return currencyFormat(cmp,event);
	}
	if (tipo == 'hectarePadrao') {
		return fcnFormataHectare(cmp,event);
	}	
	if (tipo == 'valor') {
		return currencyFormat(cmp,event);
	}
	if (tipo == 'valor3') {
		return currencyFormat3(cmp,event);
	}
	if (tipo == 'valor4') {
		return currencyFormat4(cmp,event);
	}
	if (tipo == 'valor5') {
		return currencyFormat5(cmp,event);
	}	
	if (tipo == 'valor6') {
		return currencyFormat6(cmp,event);
	}
	if (tipo == 'codigo_detalhado') {
		return fcnFormataCodigo(cmp,'#.#.##.##.###');
	}
}

/**
 * Função para retirar a máscara do campo editado.
 * @param campo_editado: CPF Editado.
 * @return campo_editado: CPF Numérico.
 */
function fcnRetiraMascara(tipo, campo_editado)
{
	switch(tipo) {
		case 'cpf': 
			return String(campo_editado).replace(/\-/g,"").replace(/\./g,""); 
			break;
		case 'cnpj':
			return String(campo_editado).replace(/\D/g, "").replace(/\./g,"").replace(/\//,"");
			break;
		case 'cep':
			return String(campo_editado).replace(/\D/g, "").replace(/^0+/, "0").replace(/-/,"");
			break;
		case 'hectare':
			return String(campo_editado).replace(/\./g,"").replace(/^0+/, "0").replace(/,/,".");
			break;
		case 'valor':
			return String(campo_editado).replace(/\./g,"").replace(/^0+/, "0").replace(/,/,".");
			break;			
		case 'data':
			return String(campo_editado).replace(/\-/g,"").replace(/^0+/, "0").replace(/,/,"");
			break;	
		case 'codigo_detalhado':
			return String(campo_editado).replace(/\./g,"");
			break;
	}
} 

/**
 * Função para validar o CPF digitado
 * @param: Numero de CPF
 * Esta função é mais simples que a função anterior.
 */
function fcnValidaCpf (cpf_editado) {
	var cpf = fcnRetiraMascara('cpf', cpf_editado);	
	if (cpf.length < 11 || cpf == "00000000000" || cpf == "11111111111" ||
		cpf == "22222222222" ||	cpf == "33333333333" || cpf == "44444444444" ||
		cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
		cpf == "88888888888" || cpf == "99999999999")
		return false;
	soma = 0;
	for (i=0; i < 9; i ++)
		soma += parseInt(cpf.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(cpf.charAt(9)))
		return false;
	soma = 0;
	for (i = 0; i < 10; i ++)
		soma += parseInt(cpf.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(cpf.charAt(10)))
		return false;
	return true;
}

/*
function fcnValidaCpf(cpf_editado) {
	  var cpf = fcnRetiraMascara('cpf', cpf_editado);
//	  alert(cpf);
//	  alert(cpf_editado);
	  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;
}
*/

/**
 * Função para validar o CPF digitado
 * @param cnpj_editado: Numero de CPF
 */
function fcnValidaCnpj(cnpj_editado) {
	  var cnpj = fcnRetiraMascara('cnpj', cnpj_editado);
//	  alert(cnpj);
//	  alert(cnpj_editado);
      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 para validar o e-mail digitado.
 * @param cep: Numero de e-mail.
 * @return boolean: True, se verdadeiro. False, se falso.
 */
function fcnValidaEmail(email) { 
	if(email.value.indexOf("@")==-1 || email.value.indexOf(".")==-1){ 
		return false; 
	} else {
		return true;
	}	
} 

/**
 * Função para validar o CEP digitado.
 * @param cep: Numero de CEP.
 */
function fcnValidaCep(cep) { 
	
	if(cep.value.length == 10){
		if(cep.value.indexOf(".")==-1 || cep.value.indexOf("-")==-1){ 

			return false; 
		} else {

			return true;
		}
	}else{
		return false;	
	}
} 	


/* 
function mask(campo) {
	len = document.getElementById(campo).value.length;
	cmp = document.getElementById(campo);

	if (campo == 'cep') {
		if (len == 2) { cmp.value = cmp.value + '.'; return; }
		if (len == 6) { cmp.value = cmp.value + '-'; return; }
		if (cmp.value.charAt(2) != '.') { keyCode = 0 };
		if (cmp.value.charAt(6) != '-') { keyCode = 0 };
	}

	if (campo == 'cpf') {
		if (len == 3) { cmp.value = cmp.value + '.'; return; }
		if (len == 7) { cmp.value = cmp.value + '.'; return; }
		if (len == 11) { cmp.value = cmp.value + '-'; return; }
		if (cmp.value.charAt(3) != '.') { keyCode = 0 };
		if (cmp.value.charAt(7) != '.') { keyCode = 0 };
		if (cmp.value.charAt(11) != '-') { keyCode = 0 };
	}

	if (campo == 'cnpj') {
		if (len == 3) { cmp.value = cmp.value + '.'; return; }
		if (len == 7) { cmp.value = cmp.value + '.'; return; }
		if (len == 11) { cmp.value = cmp.value + '/'; return; }
		if (len == 16) { cmp.value = cmp.value + '-'; return; }
		if (cmp.value.charAt(3) != '.') { keyCode = 0 };
		if (cmp.value.charAt(7) != '.') { keyCode = 0 };
		if (cmp.value.charAt(11) != '/') { keyCode = 0 };
		if (cmp.value.charAt(16) != '-') { keyCode = 0 }
	}
	
	if ( (campo == 'tel') || (campo == 'telefone') || (campo == 'cel') || (campo == 'celular') || (campo == 'fax') ) {
		if (len == 2) { cmp.value = cmp.value + ' '; return; }
		if (len == 7) { cmp.value = cmp.value + '-'; return; }
		if (cmp.value.charAt(2) != ' ') { keyCode = 0 };
		if (cmp.value.charAt(7) != '-') { keyCode = 0 }
	}
	
	if ( (campo == 'mip') || (campo == 'map') || (campo == 'fx1') || (campo == 'fx2') || (campo == 'fx3') ) {
		if (len == 1) { cmp.value = cmp.value + '.'; return; }
		if (cmp.value.charAt(1) != '.') { keyCode = 0 };
	}
}
*/

// Funções para validação de data.
function GotFocus(item,cor) {
  if (!item.contains(event.fromElement)) {
    item.style.cursor = "hand";
	item.bgColor = cor;
	}
}

function digitaData(objeto,e){
  //Digitação de campos do tipo Data
  if (objeto.value.length == 2 || objeto.value.length == 5) objeto.value += '/';	 
  return numeric(e);}
  
function criticaData(objeto){
  //Para críticas em campo
  if (objeto.value=="") return true;
  var resultado=isDate(objeto.value);
  if (resultado==false){
    alert("A data digitada não é válida, por favor confira a digitação !!!");
	  objeto.focus();
	  return false;}
  return true;}

function isDate(strData){
  //Verifica se a data é válida ou não
  var dia, mes, ano;	
	if(strData.length < 10) return false;		
  mes = strData.substr(3,2); 
	if(mes > "12" || mes == "00") return false;	    
  dia = strData.substr(0,2);       
	if(dia=="00") return false;
	ano = strData.substr(6,4);	
	if (ano < "0200") return false;
	if (mes=="01"||mes=="03"||mes=="05"||mes=="07"||mes=="08"||mes=="10"||mes=="12"){//Meses que têm 31 dias
	if (dia > "31") return false;}		
	if(mes=="04"||mes=="06"||mes=="09"||mes=="11"){//Meses que têm 30 dias
	if (dia > "30") return false;}
	if(mes=="02"){	
	if((parseInt(ano) % 4) ==0){
	  //Ano Bisexto
	  if (dia > "29") return false;}		
	else		
	  if (dia > "28") return false;}	
	return true;}
	
// Funções para validação de campos numéricos editados ou não.
function numeric(e) { 
	var codigo;
	if(window.event) {
		codigo = event.keyCode
	} else { 
		if(e.which) {
			codigo = e.which
		}
	}		
//	alert(codigo);

	if (codigo == 0 || codigo == 8 || codigo == 9 || codigo == 46 || codigo == 88 || codigo == 120) {
		return true;
	}
	
	var str = codigo.toString();
//	alert(str);
	if (str == 'undefined') {
		return true;
	}
	
	if (codigo < 48) { return false; } 
    if (codigo > 57) { return false; } 		  
  
	return true;
}
  
function noKey(e) {
  var navegador=navigator.appName
  if (navegador.indexOf("Microsoft") >= 0)
    { return false;}
  else
    { if (e.keyCode==9)
        return true
      else
        return false
    }
}

function currencyFormat(objTextBox, e){
	var SeparadorMilesimo = '.';
	var SeparadorDecimal = ','; 
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
	tam = objTextBox.size;
	if (len >= tam -1) return false;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

function currencyFormat3(objTextBox, e){
	var SeparadorMilesimo = '.';
	var SeparadorDecimal = ','; 
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
	tam = objTextBox.size;
	if (len >= tam - 1) return false;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 3) objTextBox.value = '0'+ SeparadorDecimal + aux;	
    if (len > 3) {
        aux2 = '';
        for (j = 0, i = len - 4; i >= 0; i--) {
            if (j == 4) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 3, len);
    }
    return false;
}

function currencyFormat4(objTextBox, e){
	var SeparadorMilesimo = '.';
	var SeparadorDecimal = ','; 
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
	tam = objTextBox.size;
	if (len >= tam - 1) return false;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + '0' + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + '0' + '0' + aux;		
    if (len == 3) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;			
    if (len == 4) objTextBox.value = '0'+ SeparadorDecimal + aux;				
    if (len > 4) {
        aux2 = '';
        for (j = 0, i = len - 5; i >= 0; i--) {
            if (j == 5) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 4, len);
    }
    return false;
}

function currencyFormat5(objTextBox, e){
	var SeparadorMilesimo = '.';
	var SeparadorDecimal = ','; 
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
	tam = objTextBox.size;
	if (len >= tam - 1) return false;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + '0' + '0' + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + '0' + '0' + '0' + aux;	
    if (len == 3) objTextBox.value = '0'+ SeparadorDecimal + '0' + '0' + aux;		
    if (len == 4) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;			
    if (len == 5) objTextBox.value = '0'+ SeparadorDecimal + aux;				
    if (len > 5) {
        aux2 = '';
        for (j = 0, i = len - 6; i >= 0; i--) {
            if (j == 6) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 5, len);
    }
    return false;
}

function currencyFormat6(objTextBox, e){
	var SeparadorMilesimo = '.';
	var SeparadorDecimal = ','; 
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
	tam = objTextBox.size;
	if (len >= tam - 1) return false;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + '0' + '0' + '0' + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + '0' + '0' + '0' + '0' + aux;
    if (len == 3) objTextBox.value = '0'+ SeparadorDecimal + '0' + '0' + '0' + aux;	
    if (len == 4) objTextBox.value = '0'+ SeparadorDecimal + '0' + '0' + aux;		
    if (len == 5) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;			
    if (len == 6) objTextBox.value = '0'+ SeparadorDecimal + aux;				
    if (len > 6) {
        aux2 = '';
        for (j = 0, i = len - 7; i >= 0; i--) {
            if (j == 7) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 6, len);
    }
    return false;
}

function fcnFormataHectare(objTextBox, e){
	var SeparadorMilesimo = '.';
	var SeparadorDecimal = ','; 
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
	tam = 9;
	if (len >= tam - 1) return false;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 2) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

/*
function fcnFormataHectare(fld, e) {
  var sep = 0;
  var key = '';
  var i = j = 0;
  var len = len2 = 0;
  var strCheck = '0123456789';
  var aux = aux2 = '';
  var whichCode = (window.Event) ? e.which : e.keyCode;
  var navegador=navigator.appName
  
  if (whichCode == 13) return true;  // Enter
  if (navegador.indexOf("Microsoft") < 0){if (e.keyCode == 9) return true;}   // Tab
  if (navegador.indexOf("Microsoft") < 0){if (e.keyCode == 8) return true;}   // Backspace
  if (navegador.indexOf("Microsoft") < 0){if (e.keyCode == 255) fld.value="";}   // Del
  key = String.fromCharCode(whichCode);  // Get key value from key code
  if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
  len = fld.value.length;
  for(i = 0; i < len; i++)
  if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != ".")) break;
  aux = '';
  for(; i < len; i++)
  if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
  aux += key;
  len = aux.length;
  if (len > 6) return false;
  if (len == 0) fld.value = '';
  if (len == 1) fld.value = '0'+ "," + '0' + aux;
  if (len == 2) fld.value = '0'+ "," + aux;
  if (len > 2) {
    aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--) {
      if (j == 3) {
        aux2 += "";
        j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
    }
    fld.value = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
    fld.value += aux2.charAt(i);
    fld.value += "," + aux.substr(len - 2, len);
  }
  if (len > 4) {
    aux3 = '';
    for (j = 0, i = len - 5; i >= 0; i--) {
      if (j == 3) {
)        aux3 += "";
        j = 0;
      }
      aux3 += aux.charAt(i);
      j++;
    }
    fld.value = '';
P    len3 = aux3.length;
    for (i = len3 - 1; i >= 0; i--)
    fld.value += aux3.charAt(i);
    fld.value += '.' + aux2.substr(len2 - 2, len2) + "," + aux.substr(len - 2, len);
  }
  return false;
}
*/
function fcnFormataValores(valor,valor1) {
	if (valor.length <= 3) {
		aux = valor.substring(0,1) + "," + valor.substring(1,3);
	}
	if ((valor.length > 3) && (valor.length <= 5)) {
		aux = valor.substring(0,3) + "," + valor.substring(3,5);
	}
	alert(aux);
}

/*
 * Função que converte a data no formato DD/MM/AAAA para o formato SQL (AAAA-MM-DD).
 * @param data;  Recebe data no formato DD/MM/AAAA  
 * @return data; Retorna data no formato AAAA-MM-DD
 */
function fcnRetornaDataSQL(data) {	
//	data = trim(data);
	if (data.length != 0) {
		data = data.substring(6,10) + "-" + data.substring(3,5) + "-" + data.substring(0,2);
	}
	return data;
}

/*
 * Função que converte a data no formato AAAA-MM-DD para o formato de data brasileiro (DD/MM/AAAA).
 * @param data;  Recebe data no formato AAAA-MM-DD   
 * @return data; Retorna data no formato DD/MM/AAAA
 */
function fcnFormataDataSQL(data) {
//	data = trim(data);
	if (data.length != 0) {
		data = data.substring(8,10) + '/' + data.substring(5,7) + '/' + data.substring(0,4);
	}
	return data;
}

/*
 * Função que converte o cep no formato NNNNNNNN para o formato de mascara (NN.NNN-NNN).
 * @param cep;  Recebe data no formato NNNNNNNN   
 * @return cep; Retorna data no formato NN.NNN-NNN
 */
function fcnFormataCep(cep) {
//	cep = trim(cep);
	if (cep.length != 0) {
		cep = cep.substring(0,2) + '.' + cep.substring(2,5) + '-' + cep.substring(5,9);
	}
	return cep;
}

/*
 * Função que converte o cpf no formato 00000000000 para o formato de mascara (000.000.000-00).
 * @param cpf;  Recebe data no formato 00000000000   
 * @return cpf; Retorna data no formato 000.000.000-00
 */
function fcnFormataCpf(cpf) {
//	cpf = trim(cpf);
	if (cpf.length != 0) {
		cpf = cpf.substring(0,3) + '.' + cpf.substring(3,6) + '.' + cpf.substring(6,9) + '-' + cpf.substring(9,11);
	}
	return cpf;
}

/*
 * Função que converte o cnpj no formato 00000000000000 para o formato de mascara (00.000.000/0000-00).
 * @param cnpj;  Recebe data no formato 00000000000000   
 * @return cnpj; Retorna data no formato 00.000.000/0000-00
 */
function fcnFormataCnpj(cnpj) {
//	cnpj = trim(cnpj);
	if (cnpj.length != 0) {
		cnpj = cnpj.substring(0,2) + '.' + cnpj.substring(2,5) + '.' + cnpj.substring(5,8) + '/' + cnpj.substring(8,12) + '-' 
			 + cnpj.substring(12,14);
	}
	return cnpj;
}


/**
 * Função para criar uma janela com valores fixos. Usa a função fcnJanelaConf() .
 */											   
function fcnJanela(janela) {
	fcnJanelaConf(janela,50,100,800,300);	
}

/**
 * Função para criar uma janela com valores fixos. Usa a função fcnJanelaConf() .
 */											   
function fcnJanelaRelatorio(janela) {
	var parametros="toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,copyhistory=0,fullscreen=0, width=800, height=300, left=200, top=100";
	window.open(janela,'JanelaRelatorio',parametros); 	
}

/*
 * Funcao para criar uma janela secundária de tamanho configurável
 * @param janela: Nome da Janela
 * @param linhaInicio.: Linha inicial que a janela será criada.
 * @param colunaInicio: Coluna inicial que a janela será criada.
 * @param altura......: Tamanho horizontal da Janela.
 * @param largura.....: Tamanho vertical da Janela.
 */
function fcnJanelaConf(janela,linhaInicio,colunaInicio,altura,largura) { 
/*	alert(janela);
	alert(linhaInicio);
	alert(colunaInicio);
	alert(altura);
	alert(largura); */
	var parametros="toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,copyhistory=0,fullscreen=0, width="+largura+", height="+altura+", left="+colunaInicio+", top="+linhaInicio+"";
	window.open(janela,'Janela',parametros); 
}  
function fcnJanelaDialog(janela) { 
/*	alert(janela);
	alert(linhaInicio);
	alert(colunaInicio);
	alert(altura);
	alert(largura); */
	//var parametros="toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=0,resizable=0,copyhistory=0,fullscreen=0, width="+largura+", height="+altura+", left="+colunaInicio+", top="+linhaInicio+"";
	//window.open(janela,'Janela',parametros); 
	showModelessDialog(janela,document,'edge:sunken;help:no;minimize:no; dialogWidth:650px; dialogHeight:400px;  status:no; center:yes;minbutton:no;dialogTop:170;dialogLeft:350')
} 

/**
 * Função para redirecionar o site para outra página. Usada geralmente nas páginas de exclusão.
 *@ param url; Nome da página.
 *@ param delay; Tempo de espera para redirecionar.
 */
function fcnRedireciona (url, delay) {
	this.url = url;
	setTimeout('fcnSetUrl()',delay*1000);
}

/** Função para armazenar a url a ser redirecionada. */
function fcnSetUrl() {
	window.location = url;
}

/** 
  * Função para validação de radio buttons do formulário 
  * @param rb; Nome do radio button.
  * @param num; numero de opções
  */ 
function isRadio(rb, num) {
		// Validação de radio button.		
/*
		alert(rb[0].checked);
		alert(rb[1].checked);
		alert(num);
*/
		var count = 0;
		var flagExiste = false;
		for (count = 0; count < num; count++) {
			if (rb[count].checked) {
//		  		alert(rb[count].value);
				flagExiste = true;
				break;
			} else {
				flagExiste = false;
			}
		}
		return flagExiste;
/*
		if (!flagExiste) {
			alert("Selecione o sexo da pessoa");
			rd_sexo.focus();
			return false;
		}		
*/
}

function fcnIndiceRadio(rb, num) {
		var count = 0;
		var indice;
		for (count = 0; count < num; count++) {
			if (rb[count].checked) {
//		  		alert(rb[count].value);
				indice = rb[count].value;
				break;
			} else {
				indice = "";
			}
		}
		return indice;	
}

/** 
  * Função para validação de campos alfanuméricos
  * @param campoAlpha; Nome do campo.
  * Esta função valida se o campo é alfanumérico e ele deve ter no mínimo 1 caracter alfanumérico.
  */ 
function isAlpha(campoAlpha) {
//	alert(campoAlpha.value);
	if ((campoAlpha.value == "") || (!isNaN (campoAlpha.value))) {				 
		return false;
	} else {
		return true;
	}
}

function isAlphaNew(campoAlpha) {
//	alert(campoAlpha.value);
//	alert(campoAlpha.value.length);
	var alpha = trim(campoAlpha);
	if (alpha.length == 0) {
		return 1;
	} else {
		if ((campoAlpha.value == "") || (!isNaN (campoAlpha.value))) {				 
			return 2;
		} else {
			return false;
		}
	}
}

/** 
  * Função para validação de combo boxes.
  * @param itemSelect; Campo selecionado da combo box.
  */ 
function isSelect(itemSelect) {
//	alert(itemSelect.value);
	if (itemSelect.value == '' || itemSelect.value == 0) {
		return false; 
	} else {
		return true;
	}
}

/** 
  * Função para validação de campos numérico
  * @param campoNumerico; Nome do campo.
  */ 
function isNumero(campoNumerico) {
//	alert(campoNumerico.value);
//	alert(campoNumerico.value.length);
	if ((campoNumerico.value == 0) || (isNaN (campoNumerico.value))) {
		return false;
	} else {
		return true;
	}
}

function isNumeroNew(campoNumerico) {
//	alert(campoNumerico.value);
//	alert(campoNumerico.value.length);
	var numero = trim(campoNumerico);
	if (numero.length == 0) {
		return 1;
	} else {
		if (isNaN (campoNumerico.value)) {
			return 2;
		} else {
			return false;
		}
	}
}

/** 
  * Função para Formatar um valor em moeda
  * @param valor; campo string a ser formatado.
  * @return retorno: string formatada.
  */ 

function fcnFormataMoeda(valor){
		
	var pos = 0;
	var pos2 = 0;
	var subs = '';
	var subs2 = '';
	var int = '';
	var inteiro = '';
	var decimal = '';
	var cont = 1;
	var fimSubs = 0;
	var retorno = '';
		
	if(valor.length == 0){
		retorno = valor;
		return retorno;
	}	
	pos = valor.indexOf(".");
	pos2 = valor.length;
	if((pos != -1) && ((pos2 - pos) == 3)){
		inteiro = valor.substring(0,pos);
		decimal = valor.substring(pos+1,pos2);				
	}
	if((pos != -1) && ((pos2 - pos) > 3)){
		valor = parseFloat(valor);
		valor = (Math.round(valor*100)/100);
		valor = valor.toString();
		pos = valor.indexOf(".");
		pos2 = valor.length;
		inteiro = valor.substring(0,pos);
		decimal = valor.substring(pos+1,pos2);				
	}
	if((pos != -1) && ((pos2 - pos) == 2)){
		inteiro = valor.substring(0,pos);
		decimal = valor.substring(pos+1,pos2) + '0';
	}
	if(pos == -1){
		inteiro = valor;
		decimal = '00';
	}
	fimSubs = inteiro.length;
	for(i = inteiro.length; i > 0; i--){
		if((cont % 3) == 0){
			subs = inteiro.substring((inteiro.length - cont),fimSubs);
			int = '.' + subs + subs2;
			subs2 = int;
			fimSubs = (inteiro.length - cont);
		}
		if((((inteiro.length) - cont) == 0) && (((inteiro.length) % 3 != 0))){
			int = inteiro.substring(0,((inteiro.length) % 3)) + int;
			inteiro = int;
		}else if((((inteiro.length) - cont) == 0)){
			inteiro = int.substring(1,int.length);	
		}
		cont++;
	}
	retorno = inteiro + ',' + decimal;
	return retorno;
}

function fcnFormataCodigo(src,mask) {
//	alert(e.keyCode)
	if (isNaN(String.fromCharCode(event.keyCode))) { return false; }
	var i = src.value.length;
	var saida = mask.substring(0,1);
	var texto = mask.substring(i);
	if (texto.substring(0,1) != saida)	{
		if (event.keyCode == 8) {
			if (!texto.substring(0,1) == '.') {
				src.value -= texto.substring(0,1);					
			}
		} else { 	 
			src.value += texto.substring(0,1);
		}
	}
	return true;
}

/*
 * Função para remover espaços em branco.
 *@param str: string a ser removida.
 *@return str: string modificada.
 */
function trim(str) {
	var string = str.value;
	while (string.charAt(0) == " ")
	string = string.substr(1,string.length -1);
	
	while (string.charAt(string.length-1) == " ")
	string = string.substr(0,string.length-1);

	return string;
}

/*
 * Função para remover espaços em branco de variáveis em javascript.
 *@param str: string a ser removida.
 *@return str: string modificada.
 */
function trimJs(str) {
	var string = str;
	while (string.charAt(0) == " ")
	string = string.substr(1,string.length -1);
	
	while (string.charAt(string.length-1) == " ")
	string = string.substr(0,string.length-1);

	return string;
}

/*
 * Função para enviar mensagens de validação p/ tela.
 *@param codigo: Código da mensagem.
 *@param nomeCampo: Nome do campo a ser mostrado na mensagem.
 */
function fcnMensagem (codigo,nomeCampo) {		
		var mensagens = new Array (50);
		
		mensagens [1] = "O Campo "+ nomeCampo +" está vazio";
		mensagens [2] = "O Campo "+ nomeCampo + " deve ser numérico";
		mensagens [3] = "O Campo "+ nomeCampo+ " deve ser alfanumérico";
		
		alert (mensagens[codigo]);
}

/**
 * Função parar marcar todos os objetos de tela
 * Usada para radio-buttons e check-boxes, até o momento.
 * @param objTela: Tipo de objeto de tela('radio' ou 'checkbox').
 */
function fcnMarcaObjeto(objTela,form) {
	for (i=0;i<form.elements.length;i++) {
      if(form.elements[i].type == objTela) {
         form.elements[i].checked=1;
	  }
	}
}

/**
 * Função parar desmarcar todos os objetos de tela
 * Usada para radio-buttons e check-boxes, até o momento.
 * @param objTela: Tipo de objeto de tela('radio' ou 'checkbox').
 */
function fcnDesmarcaObjeto(objTela,form) {
   for (i=0;i<form.elements.length;i++) {
      if(form.elements[i].type == objTela) {
         form.elements[i].checked=0;
		}
	}
}

function fcnDesmarcaObjetoTela(obj) {
	var count = 0;
	var indice;
	for (count = 0; count < obj.length; count++) {
		obj[count].checked=0;
	}
}

function fcnAdicionaLogoFlash(NOME, URL, WIDTH, HEIGHT, TRANSPARENT, TEXTO)
{
document.write (' <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ');
document.write (' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" ');
document.write (' width="'+ WIDTH +'" height="'+ HEIGHT +'" title="'+NOME+'">');
// alert (' width="'+ WIDTH +'" height="'+ HEIGHT +'" title="'+NOME+'">');
document.write (' <param name="movie" value="'+ URL +'" />');
document.write (' <param name="quality" value="high" />');
document.write (' <param name="enabled" value="1" />');
document.write (' <param name="mousepointer" value="0" />');			
document.write (' <param name="flashVars" value="texto='+TEXTO+'">');
// alert (' <param name="flashVars" value="texto='+TEXTO+'">');

if ( TRANSPARENT ) {
  document.write (' <param name="Wmode" value="Transparent" />'); 
}

document.write (' <embed src="'+ URL +'" quality="high" enabled="1" mousepointer="0"');
document.write ('  flashVars="'+TEXTO+'"' );
// alert ('  texto="'+TEXTO+'"' );

if ( TRANSPARENT ) {
document.write (' Wmode = "transparent" ');
}

document.write (' pluginspage="http://www.macromedia.com/go/getflashplayer" ');
document.write (' type="application/x-shockwave-flash" width="'+ WIDTH +'" height="'+ HEIGHT +'"></embed> ');
document.write (' </object>');

}

function fcnAdicionaFlash(NOME, URL, WIDTH, HEIGHT, TRANSPARENT, TEXTO)
{
document.write (' <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ');
document.write (' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" ');
document.write (' width="'+ WIDTH +'" height="'+ HEIGHT +'" title="'+NOME+'">');
document.write (' <param name="movie" value="'+ URL +'" />');
document.write (' <param name="quality" value="high" />');
document.write (' <param name="enabled" value="1" />');
document.write (' <param name="mousepointer" value="0" />');			

if ( TRANSPARENT ) {
  document.write (' <param name="Wmode" value="Transparent" />'); 
}

document.write (' <embed src="'+ URL +'" quality="high" enabled="1" mousepointer="0"');

if ( TRANSPARENT ) {
document.write (' Wmode = "transparent" ');
}

document.write (' pluginspage="http://www.macromedia.com/go/getflashplayer" ');
document.write (' type="application/x-shockwave-flash" width="'+ WIDTH +'" height="'+ HEIGHT +'"></embed> ');
document.write (' </object>');

}


/**
 * Seleciona todas as opções dos campos tipo select-multiple
 * no form obedecendo o nome informado nas variávies "globais":
 *
 * @variable formLista
 * @variable detalhe - Nome do detalhe. Se não for detalhe deixar vazio.
 * @variable itensDetalhe - Número de itens no detalhe.
 * @variable lista - Nome do campo lista.
 */
	var detalhe = "";
	var itensDetalhe = 1;
	var lista = "";
	var listaEspelho = "";
	var listaOriginal = "";
	var formLista = "";
function listSelectAll(){


	if (formLista == "" || ""+formLista == "undefined" || formLista == null) formLista = "0";
	if (lista == "") return true;

	var prefixo = "";
	
	if (itensDetalhe == 0) return true;

	for ( var n = 0; n < itensDetalhe; n++ )
	{
		if (detalhe != "" && itensDetalhe > 0)
			prefixo = detalhe+"["+n+"].";
		campo = eval("document.forms["+formLista+"].elements['"+ prefixo + lista +"']");
		if (campo && campo.type == "select-multiple")
		{
			for(var k = 0; k < campo.length; k++)
			{
				if (campo.options[k] != null)
					campo.options[k].selected = true;
			}
		}
	}
	
	return true;
}

function fcnRetornaDataSistema() {
	var d = new Date();
	return fcnRetornaIndiceDec(d.getDate())+"/"+fcnRetornaIndiceDec(d.getMonth()+1)+"/"+d.getFullYear();
}

function fcnRetornaDataSistemaSQL() {
	var d = new Date();
	return d.getFullYear()+"-"+fcnRetornaIndiceDec(d.getMonth()+1)+"-"+fcnRetornaIndiceDec(d.getDate());
}

function fcnRetornaHoraSistema() {
	var d = new Date();
	return fcnRetornaIndiceDec(d.getHours())+":"+fcnRetornaIndiceDec(d.getMinutes())+":"+fcnRetornaIndiceDec(d.getSeconds());
}

function fcnMostraHora(camada) {
	var d=new Date();
	var h=d.getHours();
	var m=d.getMinutes();
	var s=d.getSeconds();
	// add a zero in front of numbers<10
	m=fcnRetornaIndiceDec(m);
	s=fcnRetornaIndiceDec(s);
	document.getElementById(camada).innerHTML=h+":"+m+":"+s;
//	t=setTimeout("fcnMostraHora('"+camada+"')",500);
	return setTimeout("fcnMostraHora('"+camada+"')",500);
}

function fcnRetornaIndiceDec(i) {
	if (i<10) {
		i="0" + i
	}
	return i;
}		

/** 
 * funcao para verificar se o cooperado está bloqueado.
 */
function fcnPessoaBloqueada(bloqueio,motivo,data) {
	var mensagem = 'Este cadastro não pode ser alterado pois a pessoa em questão está bloqueada\n'+
			       'Motivo: '+motivo+'\n'+
			       'Data..: '+data;
	if (bloqueio == 'S') { 
		alert(mensagem);
		return true;
	} 
	return false;
}

/** 
 * funcao para verificar se o cooperado está demitido.
 */
function fcnPessoaDemitida(demissao,motivo,data) {
	var mensagem = 'Este cadastro não pode ser alterado pois a pessoa em questão está demitida\n'+
			       'Motivo: '+motivo+'\n'+
			       'Data..: '+data;
	if (demissao == 'S') { 
		alert(mensagem);
		return true;
	} 
	return false;
}

/**
 * Função recursiva para capitalizar(Transformar em maiusculas e minusculas)
 * o texto passado como parametro.
 * Ele faz um replace e chama uma função para trocar os valores passados.  							  *
 *
 * @param texto
 * @return texto
 **/
function fcnCapitalize(texto) {
	return texto.replace(/\S+/g, function(a){
		return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
	});
}							

/**
 * Função para verificar se a URL digitada é verdadeira ou não.
 *@param url: Nome da url passada como campo.value.
 *@return boolean: True, se verdadeiro. False, se falso.
 */
function isURL (url) {
	var urlPattern = /^(?:(?:ftp|https?):\/\/)?(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)+(?:com|edu|biz|org|gov|int|info|mil|net|name|museum|coop|aero|[a-z][a-z])\b(?:\d+)?(?:\/[^;"'<>()\[\]{}\s\x7f-\xff]*(?:[.,?]+[^;"'<>()\[\]{}\s\x7f-\xff]+)*)?/;
	return urlPattern.test(url.toLowerCase());
}  

/**
 * Exemplo de função de validação de site.
 *@param valor: URL a se validar.
 *@return boolean: True, se a url é válida. False, se a url é inválida.
 */
function fcnValidaSite(valor) {
//	alert(valor.value);
//	alert(isURL(valor.value));
	if (valor.value != "") {
		if (!isURL(valor.value)) {
			alert("URL Inválida");
			form.txt_url.focus();
			form.txt_url.select();
			return false;
		} else {
			alert("URL Valida");
			return true;
		}
	} else {
		alert("URL Inválida");
		form.txt_url.focus();
		form.txt_url.select();
		return false;
	}
}
