					   // formataData: Formata a data, com as barras, bastando digitar os números.
// formataCEP: Formata o CEP no formato (99999-999)
// verificaCEP: Verifica se o CEP é valido (99999-999)
// placeFocus: posiciona o foco na primeira caixa de texto da página (não funciona bem se a //página tem algum refresh em campos intermediários).


var nets = false;
var msie = false;
var versao = 0;

//funcao para retornar qual o browse
function verificaBrowse() {
	if (navigator.appName.substring(0, 8) == "Netscape") {
		nets = true;
	} else {
		msie = true ;
	}
	versao=navigator.appVersion.substr(22,1);
	/*
	if (navigator.appVersion.substr(17,6) == "MSIE 5") {
		versao = 5;
	} else {
		versao = parseFloat(navigator.appVersion.substring(0, 3) );
	}
	*/
	//alert('nets=' + nets + '\nmsie=' + msie + '\nversao=' + versao);
}

verificaBrowse();




/*
if (nets) {
	document.captureEvents(Event.CLICK);
}

document.onmousedown=click;


function click(e)
{ 
   return true;  // nao executar, temporariamente!!!
   if (msie) {
       k = event.button;
   } else {
       k = e.which;
   }
   if (k >=2)
   {
      window.alert('- ERRO -  \n\n\Não é permitida a visualização do código fonte.')
      return false;
   }
}
*/


Mascaras = {
IsIE: navigator.appName.toLowerCase().indexOf('microsoft')!=-1,
AZ: /[A-Z]/i,
Acentos: /[À-ÿ]/i,
Num: /[0-9]/,
carregar: function(parte){
 var Tags = ['input','textarea'];
 if (typeof parte == "undefined") parte = document;
 for(var z=0;z<Tags.length;z++){
  Inputs=parte.getElementsByTagName(Tags[z]);
  for(var i=0;i<Inputs.length;i++)
   if(('button,image,hidden,submit,reset').indexOf(Inputs[i].type.toLowerCase())==-1)
    this.aplicar(Inputs[i]);
 }
},
aplicar: function(campo){
 tipo = campo.getAttribute('tipo');
 if (!tipo || campo.type == "select-one") return;
 orientacao = campo.getAttribute('orientacao');
 mascara = campo.getAttribute('mascara');
 if (tipo.toLowerCase() == "decimal"){
  orientacao = "esquerda";
  casasdecimais = campo.getAttribute('casasdecimais');
  tamanho = campo.getAttribute('maxLength');
  if (!tamanho || tamanho > 50)
   tamanho = 15;
  if (!casasdecimais)
  casasdecimais = 2;
  campo.setAttribute("mascara", this.geraMascaraDecimal(tamanho, casasdecimais));
  campo.setAttribute("tipo", "numerico");
  campo.setAttribute("orientacao", orientacao);
 }
 
 if (tipo.toLowerCase() == "data"){
  orientacao = "esquerda";
  tamanho = 10;
  mascara = "##/##/####";
  campo.setAttribute("mascara", mascara);
  campo.setAttribute("tipo", "numerico");
 }
 
 if (orientacao && orientacao.toLowerCase() == "esquerda") campo.style.textAlign = "right";
 if (mascara) campo.setAttribute("maxLength", mascara.length);
 if (tipo){
  campo.onkeypress = function(e){return Mascaras.onkeypress(e?e:event);}; 
  campo.onkeyup = function(e){ campo.onkeyup; Mascaras.onkeyup(e?e:event, campo);};
  if (tipo.toLowerCase() == "data") {
	campo.onblur = function(e){Mascaras.isDate(campo)};
  }
 }
 campo.setAttribute("snegativo", ((campo.value).substr(0,1) == "-" ? "s" : "n"));
},
onkeypress: function(e){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 campo =  this.IsIE ? event.srcElement : e.target;
 readonly = campo.getAttribute('readonly');
 if (readonly) return;
 maxlength = campo.getAttribute('maxlength');
 pt = campo.getAttribute('pt');
 selecao = this.selecao(campo);
 if (selecao.length > 0 && KeyCode != 0){
  campo.value = ""; return true;
 }
 if (KeyCode == 0) return true;
 Char = String.fromCharCode(KeyCode);
 valor = campo.value;
 mascara = campo.getAttribute('mascara');

 if (KeyCode != 8){
  tipo = campo.getAttribute('tipo').toLowerCase();
  negativo = campo.getAttribute('negativo');
  if(negativo && KeyCode == 45){
   snegativo = campo.getAttribute('snegativo');
   snegativo = (snegativo == "s" ? "n" : "s");
   campo.setAttribute("snegativo", snegativo);
  }else{
   valor += Char
   if (tipo == "numerico" && Char.search(this.Num) == -1) return false;
   if (KeyCode != 32 && tipo == "caracter" && Char.search(this.AZ) == -1 && Char.search(this.Acentos) == -1) return false;
  }
 }
 if (mascara){
  this.aplicarMascara(campo, valor);
  return false;
 }
 return true;
},
onkeyup: function(e, campo){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 if (KeyCode != 9 && KeyCode != 16 && KeyCode != 109){
  valor = campo.value;
  if (KeyCode == 8 && !this.IsIE) valor = valor.substr(0,valor.length-1);
  this.aplicarMascara(campo, valor);
 }
},
//inplementado por klaid
isDate: function(campo){
  if (campo.value == '')
    return;
	
  var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
  var matchArray = campo.value.match(datePat); // is the format ok?

  if (matchArray == null){
    alert("Informe uma Data dd/mm/yyyy.");
    return false;
  }
  day = matchArray[1]; month = matchArray[3]; year = matchArray[5];
  if ((day < 1 || day > 31) 
  || (month < 1 || month > 12) 
  || ((month==4 || month==6 || month==9 || month==11) && day==31)) {
    alert("Data Inválida.");
    return false;
  }

  if (month == 2) {
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day > 29 || (day==29 && !isleap)) {
      alert("Fevereiro de " + year + " não tem " + day + " dias.");
      return false;}
  }
},
aplicarMascara: function(campo, valor){
	
 mascara = campo.getAttribute('mascara');
 if (!mascara) return;
 negativo = campo.getAttribute('negativo');
 snegativo = campo.getAttribute('snegativo');
 if (negativo && valor.substr(0,1) == "-") 
  valor = valor.substr(1,valor.length-1);
 orientacao = campo.getAttribute('orientacao');
 var i = 0;
 for(i=0;i<mascara.length;i++){
  caracter = mascara.substr(i,1);
  if (caracter != "#") valor = valor.replace(caracter, "");
 }
 retorno = "";
 if (orientacao != "esquerda"){
  contador = 0;
  for(i=0;i<mascara.length;i++){
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno += valor.substr(contador,1);
    contador++;
   }else
    retorno += caracter;
   if(contador >= valor.length) break;
  }
 }else{
  contador = valor.length-1;
  for(i=mascara.length-1;i>=0;i--){
   if(contador < 0) break;
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno = valor.substr(contador,1) + retorno;
    contador--;
   }else
    retorno = caracter + retorno;
  }
 }
 if (negativo && snegativo == "s")
  retorno = "-" + retorno;
 campo.value = retorno;
},
geraMascaraDecimal: function(tam, decimais){
 var retorno = ""; var contador = 0; var i = 0;
 decimais = parseInt(decimais);
 for (i=0;i<(tam-(decimais+1));i++){
  retorno = "#" + retorno;
  contador++;
  if (contador == 3){
   retorno = "." + retorno;
   contador=0;
  }
 }
 retorno = retorno + ",";
 for (i=0;i<decimais;i++) retorno += "#";
 return retorno;
},
selecao: function(campo){
 if (this.IsIE)
  return document.selection.createRange().text;
 else
  return (campo.value).substr(campo.selectionStart, (campo.selectionEnd - campo.selectionStart));
},
formataValor: function (valor, decimais){
 valor = valor.split('.');
 if (valor.length == 1) valor[1] = "";
 for(var i=valor[1].length;i<decimais;i++)
  valor[1] += "0"; 
 valor[1] = valor[1].substr(0,2);
 return (valor[0] + "." + valor[1]);
}
};




function roundNumber(numero, decimais) {
	var rnum = numero;
	var rlength = decimais; // The number of decimal places to round to
	if (rnum > 8191 && rnum < 10485) {
		rnum = rnum-5000;
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
		newnumber = newnumber+5000;
	} else {
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
	}
	return newnumber;
}


function findObj(n, d) { //v4.01
  // n: nome do objeto. Exemplo: findObj('span_municipio')
  // d: nao obrigatorio. Usar quando for procurar em uma janela que nao a atual. Exemplo: findObj('span_municipio', parent.document) ou findObj('span_municipio', opener.document)
	var p,i,x;  
	if(!d) d=document; 
	if((p=n.indexOf("?"))>0&&parent.frames.length) {

		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
	if(!(x=d[n])&&d.all) x=d.all[n]; 
	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}



//--------------------------------------------------------------------------------------------------------------
// INICIO - Função de formatação de DATA
//--------------------------------------------------------------------------------------------------------------
function mascaraData(campo)
{
	var tam_campo;
	tam_campo = campo.value.length;
	
	switch (tam_campo)
		{
			case 2:
				campo.value = campo.value + "/";			
				break; 
			case 5:
				campo.value = campo.value + "/";
				break;
		}		
}	



function formataData (Campo,teclapres) {
	if (Campo.readOnly) {
	  return;
	}

	var tecla = teclapres.keyCode;
	vr = RemoveNoNumeric(Campo.value);
	if (versao >= 5 || msie) {
		tam = vr.length + 1;
		if ( (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105 ) ) {
			if ( tam > 2 && tam < 5 ) {
				Campo.value = vr.substr( 0, 2  ) + '/' + vr.substr( 2, 2 );
			} // if
			if ( tam >= 5 && tam <= 10 ) {
				Campo.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 ); 
			} // if
		} else {
			if (tecla != 8 && tecla != 9 && tecla != 13) {
				tam = Campo.value.length;
				vr = RemoveNoNumeric(Campo.value);
				Campo.value = vr.substr(0, tam - 1);
			} // if
		} // if
	} else {
		if (nets) {
			tecla = teclapres.which;
		} else {
			tecla = teclapres.keyCode;
		} // if
		tam = vr.length;
		if ( tecla >= 48 && tecla <= 57 ) {
			if ( tam >= 8 ) {
				Campo.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 ); 
			}
		} // if
		else{
			if (tecla != 9 && tecla != 13) {
				tam = Campo.value.length;
				vr = RemoveNoNumeric(Campo.value);
				Campo.value = vr.substr(0, tam - 1);
			} // if
		} // if
	} // if
}
//--------------------------------------------------------------------------------------------------------------
// FIM - Função de formatação de DATA
//--------------------------------------------------------------------------------------------------------------







//--------------------------------------------------------------------------------------------------------------
// INICIO - Função que checa a DATA
//--------------------------------------------------------------------------------------------------------------
function checaData(xcampo){
	var campo = xcampo.value
	var datavalida = true;
	var quatro = true;
	if (campo!=""){
	  if (campo.length != 10)
		datavalida = false	
	  else {	
		dia = (campo.substr(0, 2));
		mes = (campo.substr(3, 2));
		ano = (campo.substr(6, 4));
		if (anoBissexto(ano) == true)
		  var dias = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
		else
		  var dias = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
		if (ano < 1000){
		  quatro = false;
		}
		if ((ano < 1) || (ano > 9999)) {
		    datavalida = false;
		} else
		   if ((mes < 1) || (mes > 12)) {
		      datavalida = false;
		   } else
		      if ((dia < 1) || (dia > dias[mes-1])) {
		            datavalida = false;
		      }
	  }	      
	}
	if (datavalida == false) {
	  alert('Data informada está inválida');
	  xcampo.value = "";
	  xcampo.focus();	  
	}
	else if (quatro == false) {
	  alert('Informe o ano com 4 dígitos');
	  xcampo.value = "";
	  xcampo.focus();
	}
	return datavalida;
}

function anoBissexto(ano){
	if (ano % 100 == 0) {
		if (ano % 400 == 0) { 
	  		return true;
		}
	} else {
		if ((ano % 4) == 0) {
			return true;
		}
	}
	return false;
}
//--------------------------------------------------------------------------------------------------------------
// FIM - Função que checa a DATA
//--------------------------------------------------------------------------------------------------------------













//--------------------------------------------------------------------------------------------------------------
// INICIO - Funções para verificação e Formatação de CEP
//--------------------------------------------------------------------------------------------------------------
function formataCEP(Campo,teclapres) {
	if (versao >= 5 || msie) {
		var tecla = teclapres.keyCode;
		vr = RemoveNoNumeric(Campo.value);
		tam = vr.length + 1;
		if (tecla == 8) {
			return true;
		} // if
		if ( tam >= 6 ) {
			Campo.value = vr.substr( 0, 5 ) + '-' + vr.substr( 5,3 ); 
		} else {
			Campo.value = vr;
		} // if
	} else {
		if (nets) {
			tecla = teclapres.which;
		} else {
			tecla = teclapres.keyCode;
		}
		vr = RemoveNoNumeric(Campo.value);
		tam = vr.length;
		if (tecla == 8) {
			return true;
		} // if
		if ( tam >= 8 ) {
			Campo.value = vr.substr( 0, 5 ) + '-' + vr.substr( 5, 3 ); 
		} else {
			Campo.value = vr;
		} // if
	} // if
}

function verificaCEP(Campo) {
	if (Campo != "") {
		if (Campo.value.length < 9) {
			alert('Preencha corretamente o nº do CEP');
			Campo.value = "";
			Campo.focus();
		} // if
		return true;
	} // if
}
//--------------------------------------------------------------------------------------------------------------
// FIM - Funções para verificação e Formatação de CEP
//--------------------------------------------------------------------------------------------------------------









//--------------------------------------------------------------------------------------------------------------
// INICIO - Formata campos com numeracao de CNPJ
//--------------------------------------------------------------------------------------------------------------
function formataCNPJ(Campo,teclapres) {
	if (versao >= 5 || msie) {
		var tecla = teclapres.keyCode;
		vr = RemoveNoNumeric(Campo.value);
		tam = vr.length + 1;
		if (tecla == 8) return true;
		if (tam <=2)
		  Campo.value = vr;
		else if ( tam > 2 && tam < 5 )
		  Campo.value = vr.substr( 0, 2  ) + '.' + vr.substr( 2, 3 );
		else if ( tam >= 5 && tam <= 7 )
		  Campo.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '.' + vr.substr( 5,3 ); 
		else if ( tam >= 7 && tam <= 10 )
		  Campo.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '.' + vr.substr( 5,3 ) + '/' + vr.substr( 8,4 ); 
		else if ( tam >= 11 )
		  Campo.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '.' + vr.substr( 5,3 ) + '/' + vr.substr( 8,4 )+ '-' + vr.substr( 12,2 );  
	} else {
		if (nets) {tecla = teclapres.which;} else {tecla = teclapres.keyCode;}
		vr = RemoveNoNumeric(Campo.value);
		tam = vr.length;
	
		if (tecla == 8) return true;
		if ( tam >= 13 ) 
		  Campo.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '.' + vr.substr( 5,3 ) + '/' + vr.substr( 8,4 )+ '/' + vr.substr( 12,2 ); 
		else Campo.value = vr;
	}
}


function calculaContraPartida(objValorFunasa, objValorTotalProjeto, objValorConcedente, objValorProponente, objContraPartida){
	
	objValorProponente.value 	= objValorConcedente.value.replace(/\./g, '').replace(',', '.');
	objValorConcedente.value	= objValorConcedente.value.replace(/\./g, '').replace(',', '.');
	objValorFunasa.value		= objValorFunasa.value.replace(/\./g, '').replace(',', '.');
	objValorTotalProjeto.value	=  objValorTotalProjeto.value.replace(/\./g, '').replace(',', '.');
	
	alert(objValorFunasa.value);
	
	if(isNaN(objValorConcedente.value))
	  objValorConcedente.value = '0';
	  
	if(isNaN(objValorProponente.value))
	  objValorProponente.value = '0';
	  
	if(isNaN(objValorFunasa.value))
	  objValorFunasa.value = '0';
	  
	if(isNaN(objValorTotalProjeto.value))
	  objValorTotalProjeto.value = '0';
	  


	if(isNaN(objValorConcedente.value) || isNaN(objValorProponente.value) || isNaN(objValorFunasa.value) || isNaN(objValorTotalProjeto.value))
	  return;
	
	objValorConcedente.value = objValorFunasa.value;
	objValorProponente.value = (parseFloat(objValorTotalProjeto.value) - parseFloat(objValorFunasa.value));
	
	//alert(parseFloat(objValorConcedente.value)+parseFloat(objValorProponente.value));
	//var iC=this.value;if(isNaN(iC))iC=0;this.value=(parseFloat(iC)).toFixed(2)
}



function calculaPercent ( oObj1, oObj2, strObj3, nObj, vTotal, vPercContraPartida, vPercMaxFunasa ) {
	var VL_SUBTOTAL;
	var vTotal       = parseFloat( vTotal.replace('.','').replace(',','.') );
	var minPercent   = parseFloat( vPercContraPartida.replace('.','').replace(',','.') );
	var nValorFunasa = parseFloat(oObj1.value.replace('.','').replace(',','.'));
	
	var valorPercent = parseFloat((nValorFunasa*100)/vTotal);
	
	if (valorPercent>parseFloat(vPercMaxFunasa)) {
		alert('O valor FUNASA não pode ser superior a ' + vPercMaxFunasa + '% do valor total.\n O percentual de contrapartida deve ser no mínimo ' +  minPercent + '%.');
		oObj1.value = "";
		oObj1.focus();
		return false;
	}
	
	oObj2.value = parseFloat(100-valorPercent).toPrecision(13);
	oObj2.value = oObj2.value.toLocaleString();
	for (i=0; i<nObj; i++) {
		VL_CONCEDENTE = document.getElementById('VL_CONCEDENTE'+frmDados.elements(strObj3,i).value);
		VL_PROPONENTE = document.getElementById('VL_PROPONENTE'+frmDados.elements(strObj3,i).value);
		VL_SUBTOTAL = document.getElementById('VL_SUBTOTAL'+frmDados.elements(strObj3,i).value);
		vSubTotal = parseFloat(VL_SUBTOTAL.value.replace('.','').replace(',','.'));
		/*
		alert(vTotal);
		alert(VL_CONCEDENTE.value);
		alert(VL_PROPONENTE.value);
		alert(VL_SUBTOTAL.value);
		alert( vSubTotal );
		alert( valorPercent );
		alert( ((valorPercent*vSubTotal)/100).toLocaleString()  );
		alert( (((100-valorPercent)*vSubTotal)/100).toLocaleString()  );
		*/
		VL_CONCEDENTE.value = ((valorPercent*vSubTotal)/100).toLocaleString();
		VL_PROPONENTE.value = (((100-valorPercent)*vSubTotal)/100).toLocaleString();
	}
	//oObj2.value = parseFloat(oObj2.value).toFixed(10);
}

function soma ( oObj1, oObj2, oObj3 ) {
	oObj3.value = parseFloat(oObj1.value.replace('.','').replace(',','.')) + 
				  parseFloat(oObj2.value.replace('.','').replace(',','.'));
	oObj3.value = FormataNumero(oObj3.value,2);
} 




// verifica se o CNPJ foi completamente digitado
function verificaCNPJ(valor){
	if (valor.value != "") {
    	tam = valor.value;
		if (tam.length < 18) {
 	     	alert('CNPJ incompleto!')
			valor.value = "";
			valor.focus();
			return false;
		}
		return true;
	}
}

//**********************************************
// Função: Valida o CNPJ
// Por: Gilvan Brandão Leandro em: 14/09/2006
// opt = Nome do campo do CNPJ (objeto)
//**********************************************
function validaCNPJ(obj) {
	CNPJ = obj.value;

	if (verificaCNPJ(obj)){  
		if (CNPJ == "00.000.000/0000-00" || CNPJ == "11.111.111/1111-11" || CNPJ == "22.222.222/2222-22" ||
			CNPJ == "33.333.333/3333-33" || CNPJ == "44.444.444/4444-44" || CNPJ == "55.555.555/5555-55" || 
			CNPJ == "66.666.666/6666-66" || CNPJ == "77.777.777/7777-77" || CNPJ == "88.888.888/8888-88" || 
			CNPJ == "99.999.999/9999-99") {
			alert("O campo \"CNPJ\" não foi preenchido corretamente.");
			obj.value = "";
			obj.focus();  
			return false;
		}
	  
		erro = new String;

		if (CNPJ.length < 18) {
			erro += "O campo \"CNPJ\" deve ser preenchido."; 
		}

		if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")) {
			if (erro.length == 0) {
				erro += "O campo \"CNPJ\" deve ser preenchido.";
			}
		}

		//substituir os caracteres que não são números
		if (document.layers && parseInt(navigator.appVersion) == 4) {
			x = CNPJ.substring(0,2);
			x += CNPJ. substring (3,6);
			x += CNPJ. substring (7,10);
			x += CNPJ. substring (11,15);
			x += CNPJ. substring (16,18);
			CNPJ = x; 
		} else {
			CNPJ = CNPJ. replace (".","");
			CNPJ = CNPJ. replace (".","");
			CNPJ = CNPJ. replace ("-","");
			CNPJ = CNPJ. replace ("/","");
		}

		var nonNumbers = /\D/;
		if (nonNumbers.test(CNPJ)) {
			erro += "O campo \"CNPJ\" suporta apenas números.";
		}

		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		for (i=0; i<12; i++){
			a[i] = CNPJ.charAt(i);
			b += a[i] * c[i+1];
		}

		if ((x = b % 11) < 2) { 
			a[12] = 0 
		} else { 
			a[12] = 11-x 
		}

		b = 0;
		for (y=0; y<13; y++) {
			b += (a[y] * c[y]); 
		}

		if ((x = b % 11) < 2) { 
			a[13] = 0; 
		} else { 
			a[13] = 11-x; 
		}

		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])) {
			erro +="CNPJ inválido!";
			obj.value = "";
			obj.focus();
		}
		if (erro.length > 0) {
			alert(erro);
			return false;
		}
		return true;
	}
}
//--------------------------------------------------------------------------------------------------------------
// FIM - Formata campos com numeracao de CNPJ
//--------------------------------------------------------------------------------------------------------------









//--------------------------------------------------------------------------------------------------------------
// INICIO - Formata campos com numeracao de CPF
//--------------------------------------------------------------------------------------------------------------
function formataCPF(Campo,teclapres) {
   if (versao >= 5 || msie) {
		var tecla = teclapres.keyCode;
		vr = RemoveNoNumeric(Campo.value);
		tam = vr.length + 1;
		if (tecla == 8) return true;
		if (tam <=3)
		  Campo.value = vr;
		else if ( tam > 3 && tam < 6 )
		  Campo.value = vr.substr( 0, 3  ) + '.' + vr.substr( 3, 3 );
		else if ( tam >= 6 && tam <= 8 )
		  Campo.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 3 ) + '.' + vr.substr( 6,3 ); 
		else if ( tam > 8 && tam <= 11 )
		  Campo.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 3 ) + '.' + vr.substr( 6,3 ) + '-' + vr.substr( 9,2 ); 
   } else {
		if (nets) {tecla = teclapres.which;} else {tecla = teclapres.keyCode;}
		vr = RemoveNoNumeric(Campo.value);
		tam = vr.length;
	
		if (tecla == 8) return true;
		if ( tam >= 10 ) 
		  Campo.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 3 ) + '.' + vr.substr( 6,3 ) + '-' + vr.substr( 9,2 ); 
		else Campo.value = vr;
   }
}

// verifica se o CPF foi completamente digitado
function verificaCPF(valor){

	//----------------------------------------------------------------------------------------------------------
	// Adicionado por: Gilvan Brandão Leandro em: 24/04/2007
	//----------------------------------------------------------------------------------------------------------
	if (valor.value == "000.000.000-00" || valor.value == "111.111.111-11" || valor.value == "222.222.222-22" ||
	    valor.value == "333.333.333-33" || valor.value == "444.444.444-44" || valor.value == "555.555.555-55" || 
	    valor.value == "666.666.666-66" || valor.value == "777.777.777-77" || valor.value == "888.888.888-88" || 
	    valor.value == "999.999.999-99") {
	     	alert('CPF incorreto!')
		valor.value = "";
		valor.focus();
		return false;
	}
	//----------------------------------------------------------------------------------------------------------


	if (valor.value != "") {
    	tam = valor.value;
	    if (tam.length < 14) {
 	     	alert('CPF incompleto!')
			valor.value = "";
			valor.focus();
			return false;
		}
		else return true;
	}
	else return false;
}

// valida o número do CPF
function validaCPF (valor){
	if (verificaCPF(valor)){
		cpf = RemoveNoNumeric(valor.value);
		soma = parseInt(cpf.substr(0,1)*10) + parseInt(cpf.substr(1,1)*9) + parseInt(cpf.substr(2,1)*8) + 
			   parseInt(cpf.substr(3,1)*7) + parseInt(cpf.substr(4,1)*6) + parseInt(cpf.substr(5,1)*5) + parseInt(cpf.substr(6,1)*4) + 
			   parseInt(cpf.substr(7,1)*3) + parseInt(cpf.substr(8,1)*2);
		resto = soma - (11 * Math.floor(soma / 11));
		if (resto == 0 || resto == 1) 
			DV = 0;
		else
			DV = 11 - resto;
		if (DV != cpf.substr(9,1)){
			alert('CPF inválido!');
			valor.value = '';
			valor.focus();
			return false;
		  }
		else{
			soma = parseInt(cpf.substr(0,1)*11) + parseInt(cpf.substr(1,1)*10) + parseInt(cpf.substr(2,1)*9) + 
				   parseInt(cpf.substr(3,1)*8) + parseInt(cpf.substr(4,1)*7) + parseInt(cpf.substr(5,1)*6) + parseInt(cpf.substr(6,1)*5) + 
				   parseInt(cpf.substr(7,1)*4) + parseInt(cpf.substr(8,1)*3) + parseInt(cpf.substr(9,1)*2);
			resto = soma - (11 * Math.floor(soma / 11));
			if (resto == 0 || resto == 1) 
				DV = 0;
			else
				DV = 11 - resto;
			if (DV != cpf.substr(10,1)){
				alert('CPF inválido!');
				valor.value = '';
				valor.focus();
				return false;
			}
		}
	}
	return true;
}
//--------------------------------------------------------------------------------------------------------------
// FIM - Formata campos com numeracao de CPF
//--------------------------------------------------------------------------------------------------------------




// Posiciona o foco no primeiro campo texto da página
function placeFocus() {
   if (document.forms.length > 0) {
      var field = document.forms[0];
      for (i = 0; i < field.length; i++) {
         if ((field.elements[i].type == "text") || (field.elements[i].type == "textarea") || (field.elements[i].type.toString().charAt(0) == "s")) {
           document.forms[0].elements[i].focus();
           break;
         }
      }
   }
}


function RemoveNoNumeric(n){
	var s = "";
	var n = String(n);
	for (i=0; i < n.length; i++) {
		if (n.charAt(i) >= "0" && n.charAt(i) <= "9") {
			s = s + n.charAt(i);
		} // if
	} // for
	return s;
}



//**********************************************
// Por: Gilvan Brandão Leandro em: 11/04/2007
// função para mover elementos de uma lista para outra lista
//**********************************************
function movelist(ori, des, qtd, ord){
  for (i=ori.length-1; i >=0; i--){
    if (qtd=='1') {
  	  if ( ori.options[i].selected ) {
  	  	des.options[des.length] = new Option(ori.options[i].text, ori.options[i].value, false, false);
  	  	ori.options[i] = null;
  	  } // if
    } //if
    else {
      for (i=ori.length-1; i >=0; i--){
      	des.options[des.length] = new Option(ori.options[i].text, ori.options[i].value, false, false);
      	ori.options[i] = null;
      } // for
    } // else
  } // for

  // ordena o destino
  for (i = des.length-1; i >= 0; i--) {
	for (k = 0 ; k < i; k++) {
	  if (des.options[k].text > des.options[i].text ){
		o = new Option(des.options[i].text, des.options[i].value, false, false);
		des.options[i].value = des.options[k].value;
		des.options[i].text = des.options[k].text;
		des.options[k].value = o.value;
		des.options[k].text = o.text;
	  } // if
	} // for
  } // for
} // function



//**********************************************
// Por: Rodrigo Gonçalves de Araújo em: 21/07/2009
// função para mover elementos de uma lista para outra lista
//**********************************************
function ValidaValores()
{
	if (frmDados.cbAnalistaDestino.length > 0){
		for(i=0;i<frmDados.cbAnalistaDestino.length;i++){
			frmDados.cbAnalistaDestino[i].selected = true;
		}
	}
	else{
		alert("Por favor, Selecione algum analista para o projeto.");
		return false;
	}
	

	return true;
}



function validaLista()
{
	if (ValidaValores()){
		frmDados.target = '_self';
		document.frmDados.action = 'definirAnalistaAcao.asp';
		document.frmDados.submit();
	}
	else
		return;
}

//******************************************************************************************
// INICIO - Função que executa o SUBMIT do form após fazer verificação de campos necessários
//******************************************************************************************
// Por: Gilvan Brandão Leandro em: 11/04/2007
//******************************************************************************************
// nUrl = valor a ser atribuido a propriedade ACTION do formulário.
// nOpt = '' = Submit sem opção, incluir = Inclui, alterar = Altera,
//								 excluir = Exclui e consultar = Consulta
// nIgnore = Ignora verificação de campo vazio na submissão do FORM.
// nTarget = Propriedade "target" do FORM.
// nForm = Nome do formulário a ser submetido.
//******************************************************************************************
// Ex: onClick="executaAcao('preProjetoAcao.asp','consultar',true);"
//******************************************************************************************
function executaAcao (nUrl, nOpt, nIgnore, nTarget, nForm) {
	var nomeForm = (nForm=='' || nForm==null) ? 'frmDados' : nForm;
	var objForm = eval("document."+nomeForm);
	var field = objForm;
	if (nOpt!='' && nOpt!=null) {
		if (nIgnore!=true) {
			for (i = 0; i < field.length; i++) {
				
				// Seleciona todos elementos de listas com a propriedade MULTIPLE ativa
				// para que o "submit" do FORM envie os dados deste para a pagina de destino.
				if (field.elements[i].multiple==true) {
					for (elemento=0; elemento < field.elements[i].length; elemento++) {
						field.elements[i].options[elemento].selected = true;
					}
				}
				
				vNome = field.elements[i].title;
				if(vNome!='' && vNome.charAt(0)=="*") {
					if(field.elements[i].value.replace(/(^\s*)|(\s*$)/g, '') =='') {
						alert("O campo " + vNome + " é de seleção obrigatória.");
						try {
							field.elements[i].value='';
							field.elements[i].focus();
						} catch (e) { }
						return false;
					} // if
				} // if
			} // for
		} // if
		if (nOpt=='incluir' || nOpt=='alterar' || nOpt=='consultar') {
			//verifica se ja foram passados parametros, caso ja tenha apenas concatena o parametro action
			objForm.action = nUrl.indexOf('?',0) == -1 ? nUrl+'?action='+nOpt : nUrl.indexOf('&',nUrl.length-1) == -1 ? nUrl+'&action='+nOpt : nUrl+'action='+nOpt;
		} // if
		if (nOpt=='excluir') {
			if (confirm("Deseja EXCLUIR o registro selecionado ?")) {
				objForm.action = nUrl.indexOf('?',0) == -1 ? nUrl+'?action='+nOpt : nUrl+'&action='+nOpt;
			} else {
				return false;	
			}
		} // if
	} // if
	else {
		if (nUrl!='' && nUrl!=null) {
			objForm.action = nUrl;
		} // if
	} // else
	if (nTarget!=null) {
		objForm.target = nTarget;
	}

	for (i = 0; i < field.length; i++) {
		vNome = field.elements[i].title;
		if(vNome!='' && vNome.charAt(0)=="*") {
			if(field.elements[i].disabled==true) {
				field.elements[i].disabled=false;
			} // if
		} // if
	} // for

	objForm.submit();

	if (nTarget!=null) {
		objForm.target = "";
	}
} // function
//******************************************************************************************
// FIM - Função que executa o SUBMIT do form após fazer verificação de campos necessários
//******************************************************************************************




//**********************************************
// Por: Gilvan Brandão Leandro em: 02/08/2006
// nForm = Nome do Formulário
// nUrl = URL que preenche o ACTION do form
// nScroll = Página SEM Scroll = 0, COM = 1
//**********************************************
function executaRelatorio(nForm, nUrl, nScroll) {
	if (nScroll=='') {
		nScroll = 0;
	}
	
	window.open("", "RELATORIO", "scrollbars="+ nScroll +", status=no, toolbar=no, location=no, menubar=no, resizable=yes, titlebar=yes", true);

	form = eval('document.'+nForm);

	form.action = nUrl;
	form.target = "RELATORIO";
	form.submit();
	form.action = "";
	form.target = "";	
}



var nomeFrame = "framePrincipal";
function abrePaginaSecundaria(nPagina, nFrame) {
	nomeFrame = nFrame;	
	nFrame = eval("top.framePrincipal.document.all."+nFrame);
	nFrame.src=nPagina;
}



//***********************************************************
// Por: Gilvan Brandão Leandro em: 05/05/2007
// Função que executa o SUBMIT do form passado como parametro
// nForm = Nome do Formulário
// Ex.:  onKeyDown="teclaEnter(this);" na tag <form>
//***********************************************************
function teclaEnter( nForm ) {
	var k = window.event.keyCode;
	if ( k == 13 ) {
		nForm.submit();	
	}
}



//**********************************************************************************
// Por: Gilvan Brandão Leandro 
// Em: 29/05/2007
// Atualizada: 18/02/2009
// Função que bloqueia todos os objetos do FORM
// oForm = Formulário a ser bloqueado
// bBloqueio = ignora os itens que tiver como CLASSE definida o item correspondente.
// bVerifica = Caso não seja usado bloqueia o elemento FORM.
// Ex.:  onLoad ="bloqueiaForm(document.forms[0]);" na tag <body>
//**********************************************************************************
function bloqueiaForm (oForm, bBloqueio, bVerifica) {
	var i;
	for (i = 0; i < oForm.length; i++) {
		if (oForm.elements[i].className.indexOf(bBloqueio==true?'desbloqueado':'bloqueado',0)==-1) {
			oForm.elements[i].disabled=bBloqueio;
		}
	} // for
	//alert(bVerifica=='');
	if (bVerifica==null) {
		oForm.disabled=bBloqueio;
	}
}





//******************************************************************************************
// INICIO do conjunto de funções que cria janelas NÃO POPUP e DRAG and DROP
//******************************************************************************************
// Por: Gilvan Brandão Leandro em: 08/05/2007
//******************************************************************************************
// nUrl = URL que quer abrir no iFrame do PopUpInterno
// nX = Largura do iFrame do PopUpInterno
// nY = Altura do iFrame do PopUpInterno
// nScroll = Define se o IFRAME terá ou não SCROLL (0 = SEM Scroll, 1 = COM Scroll)
// nTitulo = Titulo da janela no PopUpInterno
// nInstancia = Nome dado a Instancia de PopUpInterno
// nModal = Exibe uma janela do tipo MODAL sem opção de DRAG and DROP (true / false)
// nBtnFechar = Desativa o botão de Fechar (true / false)
// Ex.: onClick="PopUpInterno('pagina.asp', 600, 440, 0, 'Observações', 'janela001', true);"
//******************************************************************************************

function abrePopUpInterno (nUrl, nX, nY, nScroll, nTitulo, nInstancia, nModal, nBtnFechar) {
	var vEsq, vTopo, vEsqModal, vTopoModal, vParametro, objPopUp, buscaPopUp, contaPopUp

	contaPopUp = contaPopUpInterno();
	
	if (nScroll==1) {
		nScroll = "yes";
	} else {
		nScroll = "no";
	} // if

	if (nTitulo=='' || nTitulo==null) {
		nTitulo = "PopUp Interno";
	} // if

	if (nInstancia=='' || nInstancia==null) {
		nInstancia = "divPopUpInterno" + (contaPopUp==0 ? 1 : contaPopUp);
	} // if

	// window.document.body.scrollWidth
	// window.document.body.scrollHeight
	if (!nModal) {
		vEsq = ((top.document.body.offsetWidth - nX) / 2) < 10 ? 10 : ((top.document.body.offsetWidth - (nX+24)) / 2);
		vTopo = ((top.document.body.offsetHeight - nY) / 2) < 25 ? 25 : ((top.document.body.offsetHeight - (nY+52)) / 2);
	} else {
		vEsq = 0;
		vTopo = 0;
		vEsqModal = ((top.document.body.offsetWidth - nX) / 2) < 10 ? 10 : ((top.document.body.offsetWidth - (nX+24)) / 2);
		vTopoModal = ((top.document.body.offsetHeight - nY) / 2) < 25 ? 25 : ((top.document.body.offsetHeight - (nY+52)) / 2);
	} // if

	buscaPopUp = top.document.getElementById(nInstancia);
	if (buscaPopUp) {
		objPopUp = buscaPopUp;
		if (buscaPopUp.style.display=="block") {
			objPopUp.style.zIndex = sobrepoePopUpInterno()+1;
			return false;
		}
	} else {
		objPopUp = top.document.createElement("DIV");
	} // if

	objPopUp.style.display = "block";
	objPopUp.style.position = "absolute";
	objPopUp.style.width = nX + "px";
	objPopUp.style.height = nY + "px";
	objPopUp.style.top = vTopo + "px";
	objPopUp.style.left = vEsq + "px";
	objPopUp.style.zIndex = sobrepoePopUpInterno()+1;
	objPopUp.id = nInstancia;
	objPopUp.name = "divPopUpInterno";
	objPopUp.className = "janelaPopUpInterno";
	
	vParametro = "";
	//vParametro += "<div id='" + nInstancia + "' name='divPopUpInterno' style='display:block; position:absolute; width:" + nX + "px; height:" + nY + "px; top:" + vTopo + "px; left:" + vEsq + "px; z-index:" + sobrepoePopUpInterno()+1 + "'>";

	if (nModal) {
		vParametro += "<table width='" + (screen.width) + "' height='" + (screen.height) + "' border='0' cellspacing='0' cellpadding='0' style='background:url(/funasa/imagens/janela/transp.gif)'>";
		vParametro += "    <tr>";
		vParametro += "        <td width='100%' height='100%'>";
		vParametro += "<table width='" + nX + "' style='position:absolute; left:" + vEsqModal + "; top:" + vTopoModal + "' border='0' cellspacing='0' cellpadding='0'>";		
	} else {
		vParametro += "<table width='" + nX + "' border='0' cellspacing='0' cellpadding='0'>";
	}// if

		vParametro += "    <tr>";
		vParametro += "        <td width='12' height='40' background='/funasa/imagens/janela/top_esq.gif'>&nbsp;</td>";
		vParametro += "        <td background='/funasa/imagens/janela/top.gif' width='35' style='padding-top:9px'>";
		vParametro += "            <img src='/funasa/imagens/janela/logo.gif'>";
		vParametro += "        </td>";

	if (nModal) {
		vParametro += "        <td background='/funasa/imagens/janela/top.gif' width='" + (nX-75) + "' style='padding-top:8px; font-family:tahoma; font-size:12px; font-weight:bold;'>";
	} else {
		vParametro += "        <td background='/funasa/imagens/janela/top.gif' width='" + (nX-75) + "' style='cursor:move; padding-top:8px; font-family:tahoma; font-size:12px; font-weight:bold;' onMouseDown='top.document.all." + nInstancia + ".style.zIndex=sobrepoePopUpInterno()+1; top.document.all.conteudo" + nInstancia + ".style.display==\"block\" ? onloadPopUpInterno(\"" + nInstancia + "\", 1) : void(0);' onMouseUp='top.document.all.carregando" + nInstancia + ".style.display==\"block\" ? onloadPopUpInterno(\"" + nInstancia + "\",0) : void(0);'>";
	}

		vParametro += "            &nbsp;" + nTitulo;
		vParametro += "        </td>";

	if (nBtnFechar!=true) {
		vParametro += "        <td background='/funasa/imagens/janela/top.gif' width='20' align='center' style='padding-top:8px'>";
		vParametro += "            &nbsp;";
		//vParametro += "            <a href='#' onClick='top.document.all.conteudo" + nInstancia + ".style.display==\"none\" ? top.document.all.conteudo" + nInstancia + ".style.display=\"block\" : top.document.all.conteudo" + nInstancia + ".style.display=\"none\"' style='cursor:hand;'>";
		//vParametro += "                <img src='/funasa/imagens/janela/jan2.gif' border='0' onClick='top.document.all.conteudo" + nInstancia + ".style.display==\"none\" ? this.src=\"/funasa/imagens/janela/jan2.gif\" : this.src=\"/funasa/imagens/janela/jan1.gif\"' onMouseOver='top.document.all.conteudo" + nInstancia + ".style.display==\"none\" ? this.src=\"/funasa/imagens/janela/jan1c.gif\" : this.src=\"/funasa/imagens/janela/jan2c.gif\"' onMouseOut='top.document.all.conteudo" + nInstancia + ".style.display==\"none\" ? this.src=\"/funasa/imagens/janela/jan1.gif\" : this.src=\"/funasa/imagens/janela/jan2.gif\"'>";
		//vParametro += "            </a>";
		vParametro += "        </td>";
		vParametro += "        <td background='/funasa/imagens/janela/top.gif' width='20' align='center' style='padding-top:8px'>";
		vParametro += "            <a href='#' onClick='fechaPopUpInterno(\"" + nInstancia + "\");' style='cursor:hand;'>";
		vParametro += "                <img src='/funasa/imagens/janela/x.gif' border='0' onMouseOver='this.src=\"/funasa/imagens/janela/xc.gif\"' onMouseOut='this.src=\"/funasa/imagens/janela/x.gif\"'>";
		vParametro += "            </a>";
		vParametro += "        </td>";
	} else {
		vParametro += "        <td background='/funasa/imagens/janela/top.gif' width='20' align='center' style='padding-top:8px'>";
		vParametro += "            &nbsp;";
		vParametro += "        </td>";
		vParametro += "        <td background='/funasa/imagens/janela/top.gif' width='20' align='center' style='padding-top:8px'>";
		vParametro += "            &nbsp;";
/*
		vParametro += "            <a href='#' onClick='top.document.all.conteudo" + nInstancia + ".style.display==\"none\" ? top.document.all.conteudo" + nInstancia + ".style.display=\"block\" : top.document.all.conteudo" + nInstancia + ".style.display=\"none\"' style='cursor:hand;'>";
		vParametro += "                <img src='/funasa/imagens/janela/jan2.gif' border='0' onClick='top.document.all.conteudo" + nInstancia + ".style.display==\"none\" ? this.src=\"/funasa/imagens/janela/jan2.gif\" : this.src=\"/funasa/imagens/janela/jan1.gif\"' onMouseOver='top.document.all.conteudo" + nInstancia + ".style.display==\"none\" ? this.src=\"/funasa/imagens/janela/jan1c.gif\" : this.src=\"/funasa/imagens/janela/jan2c.gif\"' onMouseOut='top.document.all.conteudo" + nInstancia + ".style.display==\"none\" ? this.src=\"/funasa/imagens/janela/jan1.gif\" : this.src=\"/funasa/imagens/janela/jan2.gif\"'>";
		vParametro += "            </a>";
*/
		vParametro += "        </td>";
	}

		vParametro += "        <td width='12' background='/funasa/imagens/janela/top_dir.gif'>&nbsp;</td>";
		vParametro += "    </tr>";
		vParametro += "    <tr id='carregando" + nInstancia + "' style='display:block'>";
		vParametro += "        <td background='/funasa/imagens/janela/esq.gif'>&nbsp;</td>";
		vParametro += "        <td height='" + nY + "' colspan='4' bgcolor='#F6F6F6' align='center' valign='middle'>";
		vParametro += "            <img src='/funasa/imagens/janela/carregando.gif'>";
		vParametro += "        </td>";
		vParametro += "        <td background='/funasa/imagens/janela/dir.gif'><img src='spacer.gif' width='12' height='1'></td>";
		vParametro += "    </tr>";
		vParametro += "    <tr id='conteudo" + nInstancia + "' style='display:none'>";
		vParametro += "        <td background='/funasa/imagens/janela/esq.gif'>&nbsp;</td>";
		vParametro += "        <td height='" + nY + "' colspan='4' bgcolor='#F6F6F6' valign='top'>";
		vParametro += "            <iframe onLoad='onloadPopUpInterno(\"" + nInstancia + "\",0);' src='" + nUrl + "' align='middle' id='framePopUpInterno" + nInstancia + "' name='framePopUpInterno" + nInstancia + "' width='100%' height='100%' frameborder='0' marginheight='0' marginwidth='0' scrolling='" + nScroll + "'></iframe>";
		vParametro += "        </td>";
		vParametro += "        <td background='/funasa/imagens/janela/dir.gif'><img src='spacer.gif' width='12' height='1'></td>";
		vParametro += "    </tr>";
		vParametro += "    <tr>";
		vParametro += "        <td width='12' height='12' background='/funasa/imagens/janela/bot_esq.gif'><img src='spacer.gif' width='1' height='12'></td>";
		vParametro += "        <td colspan='4' background='/funasa/imagens/janela/bot.gif'><img src='spacer.gif' width='1' height='12'></td>";
		vParametro += "        <td width='12' background='/funasa/imagens/janela/bot_dir.gif'><img src='spacer.gif' width='1' height='12'></td>";
		vParametro += "    </tr>";
		vParametro += "</table>";

	if (nModal) {
		vParametro += "        </td>";
		vParametro += "    </tr>";
		vParametro += "</table>";
	} // if

	//	vParametro += "</div>";

	objPopUp.innerHTML = vParametro + "";
	
	//top.document.body.appendChild(objPopUp);
	//top.document.body.insertBefore(objPopUp);
	//top.document.body.insertAdjacentHTML("beforeEnd",vParametro);

	if (!buscaPopUp) {
		top.document.body.insertBefore(objPopUp);
	}
	
	if (!nModal) {
		new Draggable(top.document.getElementById(nInstancia));
	} // if
	
	//return objPopUp;
	//return true;
}


function fechaPopUpInterno ( nInstancia ) {
	var nInstancia, buscaPopUp, vLocal

	vLocal = top.document.body;
	buscaPopUp = top.document.getElementById(nInstancia);
	if (buscaPopUp) {
		//vLocal.removeChild(buscaPopUp);
		buscaPopUp.style.display="none";
		return true;
	} else {
		//alert("Não existe instância de PopUpInterno com o nome: " + nInstancia );
		return false;
	} // if
}


function onloadPopUpInterno ( nInstancia, nOpt ) {
	var nInstancia, nCarregando, nConteudo, buscaPopUp

	nCarregando = eval("top.document.all.carregando"+nInstancia);
	nConteudo = eval("top.document.all.conteudo"+nInstancia);

	buscaPopUp = top.document.getElementById(nInstancia);
	if (buscaPopUp) {
		if (nOpt==0) {
			nCarregando.style.display='none';
			nConteudo.style.display='block';
		} else {
			nConteudo.style.display='none';
			nCarregando.style.display='block';
		}
	}
}


function contaPopUpInterno () {
	var divCount, obj
	var vDiv = 0;
	divCount = top.document.all.tags("DIV");
	for (var i=0; i<divCount.length; i++) {
		obj = divCount(i);
		if (obj.name == "divPopUpInterno" && obj.style.zIndex>vDiv) {
				vDiv = vDiv+1;
		} // if
	} // for

	return vDiv;
}


function sobrepoePopUpInterno () {
	var divCount, obj
	var vDiv = 0;
	divCount = top.document.all.tags("DIV");
	for (var i=0; i<divCount.length; i++) {
		obj = divCount(i);
		if (obj.name == "divPopUpInterno" && obj.style.zIndex>vDiv) {
				vDiv = obj.style.zIndex;
		} // if
	} // for

	return vDiv;
}


/*
function cortinaPopUpInterno (nObj, nOpt) {
	// nOpt = 1 = Abre
	// pt = 0 = Fecha
}
*/



//----------------------------------------------------------------------------------------------------------

function Draggable(el) {
	var xDelta = 0, yDelta = 0;
	var xStart = 0, yStart = 0;
	

	function getStyle(oElm, strCssRule) {
		var strValue = "";
		if(document.defaultView && document.defaultView.getComputedStyle){
			var css = document.defaultView.getComputedStyle(oElm, null);
			strValue = css ? css.getPropertyValue(strCssRule) : null;
		}
		else if(oElm.currentStyle){
			strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
				return p1.toUpperCase();
			});
			strValue = oElm.currentStyle[strCssRule];
		}
		return strValue;
	}

	// remove the events
	function enddrag() {
		top.document.onmouseup = null;
		top.document.onmousemove = null;
		top.document.onmouseout = null;
		onloadPopUpInterno(el.id,0);
	}

	// fire each time it's dragged
	function drag(e) {
		e = e || top.window.event;
		xDelta = xStart - parseInt(e.clientX);
		yDelta = yStart - parseInt(e.clientY);
		xStart = parseInt(e.clientX);
		yStart = parseInt(e.clientY);
		el.style.top = (parseInt(el.style.top) - yDelta) + 'px';
		el.style.left = (parseInt(el.style.left) - xDelta) + 'px';
	}
	
	// initiate the drag
	function md(e) {
		e = e || top.window.event;
		xStart = parseInt(e.clientX);
		yStart = parseInt(e.clientY);
		el.style.top = parseInt(getStyle(el,'top')) + 'px';
		el.style.left = parseInt(getStyle(el,'left')) + 'px';
		top.document.onmouseup = enddrag;
		top.document.onmousemove = drag;
		top.document.onmouseout = enddrag;

		return false;
	}

	// tie it into the element
	el.onmousedown = md;
}


//************************************************************************************
// FIM da função que cria janelas NÃO POPUP e drag and drop
//************************************************************************************








//******************************************************************************************
// INICIO da função que LOCALIZA o form de origem de um POST.
//******************************************************************************************
// Por: Gilvan Brandão Leandro em: 25/05/2007
//******************************************************************************************
// Ex.: localizaFormOrigem()
//******************************************************************************************
var documentoOrigem, formLogin, formDados

function localizaFormOrigem() {
	var nFrames
	nFrames = top.document.frames;
	for (i=0; i < nFrames.length; i++) {
		nSubFrames = nFrames(i).document.frames;
		for (j=0; j < nSubFrames.length; j++) {
			if (nSubFrames(j).location==document.referrer) {
				formLogin = nSubFrames(j).document.getElementById("frmLogin");
				formDados = nSubFrames(j).document.getElementById("frmDados");
				documentoOrigem = nSubFrames(j).document;
			}
		}
		if (nFrames(i).location==document.referrer) {
			formLogin = nFrames(i).document.getElementById("frmLogin");
			formDados = nFrames(i).document.getElementById("frmDados");
			documentoOrigem = nFrames(j).document;
		}
	}
}
//************************************************************************************
// FIM da função que LOCALIZA elementos HTML no documento atual.
//************************************************************************************









//******************************************************************************************
// INICIO da função que ADICIONA elementos HTML no documento atual.
//******************************************************************************************
// Por: Gilvan Brandão Leandro em: 01/06/2007
//******************************************************************************************
// nObjDestino = Nome (texto) do objeto onde será inserido o novo elemento HTML.
// nConteudo = Variável contendo código HTML a ser inserido antes do objeto pprincipal.
// nNovoObj = ID do item HTML a ser inserido para futura remoção "Novo Objeto".
// nSubstituicao3 = Conteúdo que substituira a string "_SUBSTITUICAO3" no conteúdo dinamico.
// nSubstituicao4 = Conteúdo que substituira a string "_SUBSTITUICAO4" no conteúdo dinamico.
// Obs.: Criar nomes distintos "nNomeConteudo" pois na remoção deve-se informar este nome.
//******************************************************************************************
// Ex.: onClick="adicionaDinamicamente('conteudoDinamico', tagDinamica, 'novoItem01');"
//******************************************************************************************
function adicionaDinamicamente(nObjDestino, nConteudo, nNovoObj, nSubstituicao3, nSubstituicao4) {
	var objBusca = document.getElementById(nObjDestino);
	var objAdiciona = document.createElement("DIV");
	objAdiciona.id = nNovoObj;
	// 'gi' --> global (g), case-insensitive (i)
	nConteudo = nConteudo.replace(/_SUBSTITUICAO1/gi, nObjDestino);
	nConteudo = nConteudo.replace(/_SUBSTITUICAO2/gi, nNovoObj);
	nConteudo = nConteudo.replace(/_SUBSTITUICAO3/gi, nSubstituicao3);
	nConteudo = nConteudo.replace(/_SUBSTITUICAO4/gi, nSubstituicao4);
	objAdiciona.innerHTML = nConteudo;
	//objBusca.insertAdjacentHTML('afterBegin',objAdiciona);
	objBusca.insertBefore(objAdiciona);
}
//******************************************************************************************
// FIM da função que ADICIONA elementos HTML no documento atual.
//******************************************************************************************








//******************************************************************************************
// INICIO da função que REMOVE elementos HTML no documento atual.
//******************************************************************************************
// Por: Gilvan Brandão Leandro em: 01/06/2007
//******************************************************************************************
// nObjPrincipal = Nome (texto) do objeto em que esta o objeto a ser removido.
// nObjSecundario = Nome (texto) do objeto a ser removido.
// Ex.: onClick="removeDinamicamente('conteudoDinamico' ,'novoItem01');"
//******************************************************************************************
function removeDinamicamente(nObjPrincipal, nObjSecundario) {
	var nObjBusca = document.getElementById(nObjPrincipal); 
	var nObjRemove = document.getElementById(nObjSecundario);
	nObjBusca.removeChild(nObjRemove);
}
//************************************************************************************
// FIM da função que REMOVE elementos HTML no documento atual.
//************************************************************************************






String.prototype.trim = function()
{
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}




//************************************************************************************
// INICIO da função "limitaTexto" que restringe uma quantidade de caracters
//************************************************************************************
// Por: Klaid Pereira Dias em: 11/05/2007
// objLimitado = Objeto que conterá o texto a ser limitado
// objContagem = Objeto que conterá a contagem de caracteres.
// tamMaximo = Tamanho máximo do texto.
// Ex.: onKeyUp="limitaTexto(document.frmDados.OBS, document.frmDados.contOBS,100);"
//************************************************************************************
function limitaTexto(objLimitado, objContagem, tamMaximo) {
	if (objLimitado.value.length >= tamMaximo) {
		objLimitado.value = objLimitado.value.substring(0, tamMaximo);
		objContagem.value = '0';
	} else {
		//alert(objLimitado.value.length);
		objContagem.value = tamMaximo - objLimitado.value.length;
	}
}



//************************************************************************************
// FIM da função "MostraLimite" que restringe uma quantidade de caracters
//************************************************************************************










//******************************************************************************************
// INICIO da função "comparaData" que compara duas datas para crítica
//******************************************************************************************
// Por: Gilvan Brandão Leandro em: 16/08/2007
//******************************************************************************************
// nObjPrincipal = Nome (texto) do objeto em que esta o objeto a ser removido.
// nObjSecundario = Nome (texto) do objeto a ser removido.
// Ex.: onClick="removeDinamicamente('conteudoDinamico' ,'novoItem01');"
//******************************************************************************************
function comparaData (dataAnterior, dataPosterior, tipoVerificacao) {
	var data1 = dataAnterior.value
	var data2 = dataPosterior.value
	
	if (data1!="") {
		dia1 = (data1.substr(0, 2));
		mes1 = (data1.substr(3, 2));
		ano1 = (data1.substr(6, 4)); 
	   
		if (data2!="") {
			dia2 = (data2.substr(0, 2));
			mes2 = (data2.substr(3, 2));
			ano2 = (data2.substr(6, 4));   
		  	
			checagem = false  
			if (ano2>ano1) {
				checagem = true;
			} else {
				if (ano2==ano1)	{
					if (mes2>mes1){
						checagem = true;
					} else {
						if (mes2==mes1)	{
							if (dia2>=dia1)	{
								checagem = true;
							}
						}
					}	
				}
			}
			if (checagem==false) {
				if (tipoVerificacao=="anterior") {
					alert(''+dataAnterior.value + ' deve ser no máximo igual à ' + dataPosterior.value + ' (' + dia2 + '/' + mes2 + '/' + ano2 + ')' );
					dataAnterior.value = "";
					dataAnterior.focus();
				} else {
					alert(''+dataPosterior.value+' deve ser no mínimo igual à '+dataAnterior.value+' ('+dia1+'/'+mes1+'/'+ano1+')');
					dataPosterior.value = "";
					dataPosterior.focus();
				}
				if (checagem==false) {
					return false
				} else {
					return true
				}
			}
		}
	}			
}
//************************************************************************************
// FIM da função "comparaData" que compara duas datas para crítica
//************************************************************************************






function calcDays(){
  var date1 = document.getElementById('d1').lastChild.data;
  var date2 = document.getElementById('d2').lastChild.data;
  date1 = date1.split("-");
  date2 = date2.split("-");
  var sDate = new Date(date1[0]+"/"+date1[1]+"/"+date1[2]);
  var eDate = new Date(date2[0]+"/"+date2[1]+"/"+date2[2]);
  var daysApart = Math.abs(Math.round((sDate-eDate)/86400000));
  document.getElementById('diffDays').lastChild.data = daysApart;
}





//******************************************************************************************
// INICIO da função "comparaData" que compara duas datas para crítica
//******************************************************************************************
// Por: Gilvan Brandão Leandro em: 16/08/2007
//******************************************************************************************
// nObjPrincipal = Nome (texto) do objeto em que esta o objeto a ser removido.
// nObjSecundario = Nome (texto) do objeto a ser removido.
// Ex.: onClick="removeDinamicamente('conteudoDinamico' ,'novoItem01');"
//******************************************************************************************
function ComparaDatas (dataAnterior, dataPosterior, tipoVerificacao) {
	var data1 = document.getElementById(dataAnterior).value;
	var data2 = document.getElementById(dataPosterior).value;

	if (data1 == '' || data2 == '') {
		return;
	}

	var nova_data1 = parseInt(data1.split("/")[2].toString() + data1.split("/")[1].toString() + data1.split("/")[0].toString());
	var nova_data2 = parseInt(data2.split("/")[2].toString() + data2.split("/")[1].toString() + data2.split("/")[0].toString());

	if (nova_data2 > nova_data1) {
		alert("A data 2 é maior que a data 1.");
	} else {
		if (nova_data1 == nova_data2) {
			alert("As datas são iguais.");
		} else {
			alert("Data 2 é menor que a data 1.");
		}
	}
}






//******************************************************************************************
// INICIO da função "Formataprotocolo" que formata a data de um protocolo SCDWEB
//******************************************************************************************
// Por: Gilvan Brandão Leandro em: 11/09/2007
//******************************************************************************************
// Campo = Objeto em que esta o texto a ser formatado.
// teclapres = Evento a ser monitorado.
// Ex.: onKeyUp="Formataprotocolo(this, event);"
//******************************************************************************************
function Formataprotocolo(Campo, teclapres) {
	tecla = teclapres.keyCode;
	vr = RemoveNoNumeric(Campo.value);
	
	tam = vr.length + 1;
	if (tecla == 8) {
		return true;
	}
	if (tam <=5) {
		Campo.value = vr;
	} else if ( tam > 5 && tam < 9 ) {
		Campo.value = vr.substr( 0, 5  ) + '.' + vr.substr( 5, 3 );
	} else if ( tam >= 9 && tam <= 11 ) {
		Campo.value = vr.substr( 0, 5 ) + '.' + vr.substr( 5, 3 ) + '.' + vr.substr( 8,3 );
	} else if ( tam >= 12 && tam <= 15 ) {
		Campo.value = vr.substr( 0, 5 ) + '.' + vr.substr( 5, 3 ) + '.' + vr.substr( 8,3 ) + '/' + vr.substr( 11,4 );
	} else if ( tam >= 16 ) {
		Campo.value = vr.substr( 0, 5 ) + '.' + vr.substr( 5, 3 ) + '.' + vr.substr( 8,3 ) + '/' + vr.substr( 11,4 )+ '-' + vr.substr( 15,2 );
	}
} 
//******************************************************************************************
// FIM da função "Formataprotocolo" que formata a data de um protocolo SCDWEB
//******************************************************************************************















//*************************************************************************************************
// INICIO da função que restringe o numero de elmentos CHECKBOX a serem selecionados em um FildSet.
//*************************************************************************************************
// Por: Gilvan Brandão Leandro em: 03/10/2007
//*************************************************************************************************
// nInput = Objeto que foi atualmente marcado. ( this )
// nObj = Nome do objeto que contem os CheckBoxes.
// nElementos = Número máximo ou mínimo de elementos que devem/podem.
// nTipoCheck = Tipo de checagem a ser feita. (0 = Mínimo, 1 = Maximo)
// Ex.: onClick="contaCheck( this, 'fildSet1', '3' , 1);"
//*************************************************************************************************
function contaCheck( nInput, nObj, nElementos, nTipoCheck ) {
	if (nElementos!='' && nElementos!=null) { 
		var vObjeto = document.all.getElementById(nObj);
		var objChecado;
		var qtdChecado = 0;
		//alert(document.all.fst1.childNodes.length);
		for (var i=0; i<vObjeto.childNodes.length; i++) {
			//alert(obj.childNodes(i).type);
			myObj = nets ? vObjeto.childNodes[i] : vObjeto.childNodes(i);
			//alert(myObj.type);
			if (myObj.type == "checkbox") {
				objChecado = myObj.checked;
				if (objChecado) qtdChecado = qtdChecado+1;
				//if (!objChecado) qtdChecado = qtdChecado-1;
			} // if
		} // for
		//alert(qtdChecado);
		//alert(nElementos);
		if (nTipoCheck==0) {
			if (qtdChecado<nElementos) {
				if (nElementos==1) {
					alert("Você tem que escolher no mínimo " + nElementos + " opção deste grupo.");
				} else {
					alert("Você tem que escolher no mínimo " + nElementos + " opções deste grupo.");
				} // if
				nInput.checked = true;
				return false;
			} // if
		} else {
			if (qtdChecado>nElementos) {
				if (nElementos==1) {
					alert("Você pode escolher no máximo " + nElementos + " opção deste grupo.");
				} else {
					alert("Você pode escolher no máximo " + nElementos + " opções deste grupo.");
				} // if
				nInput.checked = false;
				return false;
			} // if
		} //if
	} // if
	return true;
}
//*************************************************************************************************
// FIM da função que restringe o numero de elmentos CHECKBOX a serem selecionados em um FildSet.
//*************************************************************************************************



//Funções estraido do SISCON
// Clério 01/11/2007

function EntraNumero()
{

	if(event.keyCode < 48 || event.keyCode > 57)
	{
	
		event.keyCode = 0;
	
	}

}

function SelectAll(Obj,TF)
	{
	var max = Obj.length;
	for (Inc = 0 ; Inc < max ; Inc++)
		{
		Obj.options[Inc].selected = TF;   // A variavel TF so pode receber "true" ou "false"
		}
	max = null;
	Inc = null;
	Obj = null;
	TF  = null;
	}

// Validação de Casas decimais

function FormataNumero(pNumeros, pCasasDecimais, pCampo, pTecla)
{
	var numero = 'document.forms[0].' + pCampo + '.value';
	numero = eval (numero);
	
	posicaoVirgula = numero.indexOf(',',0);
	
	// Permite a digitação de apenas números e vírgula
	if(pTecla != 44 && !(pTecla >= 48 && pTecla <= 57)) return false;
	
	// Permite a digitação de apenas uma vírgula
	if((numero.indexOf(',', 0) != -1) && (pTecla == 44)) return false;
	
	// Controla tamanho do número antes da vírgula
	if(numero.indexOf(',', 0) == -1 && (numero.length) == (pNumeros - pCasasDecimais) && pTecla != 44)
	{
		return false;
	}	
    else
    {
		// Controla digitação da vírgula
		if (posicaoVirgula != -1)
		{
			tamanho = numero.substring(posicaoVirgula + 1, numero.length);
			tamanho = tamanho.length;

			if (tamanho == pCasasDecimais)
			{
				return false;	
			}
		}
	}	
}

//Funcao que Bloqueia as Aspas Simples e Duplas

function BloqueiaAspas(){

	if(event.keyCode == 34 || event.keyCode == 39)
	
		event.keyCode = 0;

}

//FIM ---- Funções estraido do SISCON
// Clério 01/11/2007



















//--------------------------------------------------------------------------------------------------------------
// INICIO - Conjuntos de funções para formatação NUMÉRICA
//--------------------------------------------------------------------------------------------------------------
function validateCaracterNumber( str )
{
  var caracterStr;
  for( var j = 0; j < str.length; ++j )
  {
    caracterStr  = str.charAt( j );
    var charCode = str.charCodeAt( j );
    //caracter numérico
    if( !isDigit( caracterStr ) &&
        caracterStr != '+' &&
        caracterStr != '-' )
      return( false );
  }//for
  return( true )
}

function numberZeros( displayMask )
{
  var number = 0;
  for( var i = 0; i < displayMask.length; ++i )
    if( displayMask.charAt( i ) == '0' )
      ++number;
  return( number );
}

function insertZeros( value, displayMask )
{
  var number = numberZeros( displayMask );
  if( ( number > 0 ) &&
      ( value.length != 0 ) )
    value = fillLeft( deleteZerosLeft( value ), '0', number );
  return( value );
}

function deleteZerosLeft( value )
{
  var result = "";
  var i;
  for( i = 0; i < value.length; i++ )
  {
    var caracter = value.charAt( i );
    if( caracter != '0' )
    {
      if( isDigit( caracter ) )
        break;
      result = result + caracter;
    }
  }
  result = result + value.substring( i, value.length );
  if( result.length == 0 && value.indexOf( "0" ) != -1 )
    result = "0";
  return( result );
}

function deleteMaskNumber( value )
{
  var caracterValue;
  var valueDelete = "";
  for( var j = 0; j < value.length; ++j )
  {

    caracterValue = value.charAt( j );
    if( isDigit( caracterValue ) )
      valueDelete = valueDelete + caracterValue;
  }
  return( valueDelete );
}

function formatNumber( value, displayMask )
{
  //Verifica se o valor tem sinal e qual é o sinal
  var sinal      = "+";
  var sinalMinus = "";
//  if( value.indexOf( "-" ) != -1 )
  if( lastSignal( value ).indexOf( "-" ) > -1 )
  {
    sinal      = "-";
    sinalMinus = "-";
  }
  //Exclui símbolos do campo
  value = deleteMaskNumber( value );
  var formatValue = "";
  var caracter;
  var symbol;
  var anterior;
  //Coloca zeros no início da string
  value = insertZeros( value, displayMask );
  var lenValue = value.length - 1;
  //Percorre a máscara da direita para a esquerda
  for( var i = displayMask.length - 1; i > -1; --i )
  {
    caracter = displayMask.charAt( i );
    //Se já estiver após a primeira posição
    if ( i > 0 )
    {
      //Verifica se o anterior é um separador,
      //incluindo o caracter atual como símbolo do valor.
      anterior = findSymbol( displayMask.substring( i - 1, i ) );
      if ( anterior == SEPARATOR )
      {
        formatValue = caracter + formatValue;
        --i;
      }
    }
    if ( lenValue > -1)
    {
      symbol = findSymbol( caracter );
      if ( symbol == CARACTER )
      {
        formatValue = value.substring( lenValue, lenValue + 1 ) + formatValue;
        --lenValue;
      }
      else
      if ( symbol == SIGNAL )
        formatValue = sinal + formatValue;
	  else
        if ( symbol == MINUS )
          formatValue = sinalMinus + formatValue;
        else
          formatValue = caracter + formatValue;
    }
    else
      break;
  }
  if( hasMinusSignal( displayMask ) && formatValue.indexOf( "-" ) == -1 )
    formatValue = sinalMinus + formatValue;
  else
    if( hasSignal( displayMask ) && formatValue.indexOf( "+" ) == -1 && formatValue.indexOf( "-" ) == -1 )
      formatValue = sinal + formatValue;
  return( formatValue );
}

function lastSignal( value )
{
  var iPlus = value.lastIndexOf( "+" );
  var iMinus = value.lastIndexOf( "-" );
  if( ( iPlus == -1 && iMinus == -1 ) ||
      iPlus > iMinus )
    return "+";
  return "-";
}

function hasSignal( mask )
{
  return( mask.indexOf( "S" ) > -1 || mask.indexOf( "s" ) > -1 )
}

function hasMinusSignal( mask )
{
  return( mask.indexOf( "s" ) > -1 )
}

function formatValueNumber( field, displayMask, event )
{
  /* Tenta recuperar a tecla pelo Netscape */
  var key = event.keyCode;
  /* ou pelo IE */
  if( key == null )
    key = event.which;
  if( key != 9 )
  { 
    var value = field.value;
    var valueFormated = formatNumber( value, displayMask );
    if( value != valueFormated )
      field.value = valueFormated;
  }
}

function isDigit( str )
{
  for( var i = 0; i < str.length; i++ )
  {
    var charCode = str.charCodeAt( i );
    if( !(charCode >= 48 && charCode <= 57) )
      return( false );
  }
  return( true );
}

function fillLeft( str, c, len )
{
  for( var i = str.length; i < len; ++i )
    str = c + str;
  return( str );
}

/**
 * Format
 */

// Constantes
SYMBOL      = 0;
CARACTER    = 1;
SEPARATOR   = 2;
SIGNAL      = 3;
UPPER       = 4;
LOWER       = 5;
MINUS       = 6;
OTHER       = 7;

function findSymbol( symbol )
{
  var typeSymbol = SYMBOL;
  switch( symbol )
  {
    case '#':
	case '0':
    case 'L':
    case 'l':
    case 'A':
    case 'a':
    case 'C':
    case 'c': {
                typeSymbol = CARACTER;
                break;
              }
    case 'S': {
                typeSymbol = SIGNAL;
                break;
              }
    case 's': {
                typeSymbol = MINUS;
                break;
              }
    case '>': { typeSymbol = UPPER;
                break;
              }
    case '<': { typeSymbol = LOWER;
                break;
              }
    case '\\': {
                 typeSymbol = SEPARATOR;
                 break;
               }
    default: typeSymbol = OTHER;
  }
  return( typeSymbol );
}
//--------------------------------------------------------------------------------------------------------------
// FIM - Conjuntos de funções para formatação NUMÉRICA
//--------------------------------------------------------------------------------------------------------------





//Função para formatar MOEDA. Deve ser chamado no OnBlur
function formataMoeda(vObj) {
	x = 0;
	
	if (vObj<0) {
		vObj = Math.abs(vObj);
		x = 1;
	}   
	
	if (isNaN(vObj)) {
		vObj = "0";
	}
	
	cents = Math.floor((vObj*100+0.5)%100);
	vObj = Math.floor((vObj*100+0.5)/100).toString();
	
	if(cents < 10) {
		cents = "0" + cents;
	}
	
	for (var i = 0; i < Math.floor((vObj.length-(1+i))/3); i++) {
		vObj = vObj.substring(0,vObj.length-(4*i+3))+'.'
		+vObj.substring(vObj.length-(4*i+3));   
	}

	ret = vObj + ',' + cents;
	
	if (x == 1) {
		ret = ' - ' + ret;
	}
	
	return ret;
}



function subTotal(oObj1, oObj2, oObjSubTotal, oObjTotal, vOperacao) {
	//alert('1');
	if (parseFloat(oObj1.value.replace(/\./g, '').replace(',', '.'))>=0 && parseFloat(oObj2.value.replace(/\./g, '').replace(',', '.'))>=0 ) {


		//alert(oObj1.value.replace(/\./g, '').replace(',', '.'));
		//alert(oObj2.value.replace(/\./g, '').replace(',', '.'));
		//alert(oObjSubTotal.value.replace(/\./g, '').replace(',', '.'));
		//alert(oObjTotal.value.replace(/\./g, '').replace(',', '.'));
		/*
		alert(parseFloat(
					oObjTotal.value.replace(/\./g, '').replace(',', '.')
				)
				- 
				parseFloat(
					oObjSubTotal.value.replace(/\./g, '').replace(',', '.')
				));
		*/
		
		if (oObjTotal!='' && oObjTotal!=null && parseFloat(oObjSubTotal.value.replace(/\./g, '').replace(',', '.'))>=0 ) {
			oObjTotal.value = 
				parseFloat(
					oObjTotal.value.replace(/\./g, '').replace(',', '.')
				)
				- 
				parseFloat(
					oObjSubTotal.value.replace(/\./g, '').replace(',', '.')
				);
		}

		var v1 = parseFloat(oObj1.value.replace(/\./g, '').replace(',', '.'));
		var v2 = parseFloat(oObj2.value.replace(/\./g, '').replace(',', '.'));
		//alert('QTD: ' + v1);
		//alert('VR_UNIT: ' + v2);
		var v3;
		
		//alert('3');
		if (vOperacao==1) { // Adição
			v3 = v1+v2
		} else if (vOperacao==2) { // Subtração
			v3 = v1-v2
		} else if (vOperacao==3) { // Multiplicação
			v3 = roundNumber((v1*v2),2)
		} else if (vOperacao==4) { // Divisão
			v3 = v1/v2
		}		

		oObjSubTotal.value = formataMoeda(v3);

		if (oObjTotal!='' && oObjTotal!=null && parseFloat(oObjSubTotal.value.replace(/\./g, '').replace(',', '.'))>=0) {
			oObjTotal.value =	
				parseFloat(
					oObjTotal.value
				)
				+
				parseFloat(
					oObjSubTotal.value.replace(/\./g, '').replace(',', '.')
				);
			oObjTotal.value = formataMoeda(oObjTotal.value);
		}
	}	
}




function validaMesAno (oObjOrigem, oObjMenor, oObjMaior) {
	if (oObjOrigem.value.length==0) {
		return true;
	}
	
	if (oObjOrigem.value.length==6) {
		oObjOrigem.value = '0' + oObjOrigem.value;
	}

	if (oObjOrigem.value.length<7 && oObjOrigem.value.length>0) { 
		alert('Favor preencher o campo ' + oObjOrigem.title.toUpperCase() + ' corretamente.');
		oObjOrigem.value = ''; 
		return false;
	}
	
	if ( parseFloat(oObjMaior.value.substring(3, 7))<1900 || 
		 parseFloat(oObjMaior.value.substring(3, 7))>3000 || 
		 parseFloat(oObjMaior.value.substring(0, 2))<1 || 
		 parseFloat(oObjMaior.value.substring(0, 2))>12
		) {
		alert('O campo ' + oObjMaior.title.toUpperCase() + ' está incorreto.');
		oObjOrigem.value = ''; 
		oObjOrigem.focus(); 
		return false;
	}

	if ( parseFloat(oObjMenor.value.substring(3, 7))<1900 || 
		 parseFloat(oObjMenor.value.substring(3, 7))>3000 || 
		 parseFloat(oObjMenor.value.substring(0, 2))<1 || 
		 parseFloat(oObjMenor.value.substring(0, 2))>12
		) {
		alert('O campo ' + oObjMenor.title.toUpperCase() + ' está incorreto.');
		oObjOrigem.value = ''; 
		oObjOrigem.focus(); 
		return false;
	}

	if ( 
		 parseFloat(oObjMaior.value.substring(3, 7) + oObjMaior.value.substring(0, 2)) < 
		 parseFloat(oObjMenor.value.substring(3, 7) + oObjMenor.value.substring(0, 2))
		) {
		alert('A ' + oObjMaior.title.toUpperCase() + ' "' + oObjMaior.value + '" não pode ser inferior a ' + oObjMenor.title.toUpperCase() + ' "' + oObjMenor.value + '"'); 
		oObjOrigem.value = ''; 
		oObjOrigem.focus(); 
		return false;
	}
}








//******************************************************************************************
// INICIO da função de controle de DIVs para exibir ou ocultar.
//******************************************************************************************
// Por: Gilvan Brandão Leandro em: 24/11/2007 20h47
// E-mail: gilvan.leandro@gmail.com
//******************************************************************************************
// nBloco = PARTE do nome do bloco de DIVs a serem controladas (Obrigatório). 
//          Ex.: id="CADASTRO_complemento"
// nDiv   = Nome da DIV especifica que deve ser exibida, ou, "null" para exibir todos ou
//          ocultar todos (Opcional).
// nAcao  = Ação a ser tomada no caso de controlar todos os itens do grupo (Opcional).
//          (true = exibir todos / false = ocultar todos)
// Ex.: controlaDIVs('CADASTRO', null, true);
//******************************************************************************************
function controlaDIVs ( nBloco, nDiv, nAcao ) {
	var i;
	var arrDiv = parent.document.body.all.tags("DIV");
	
	oDiv = nDiv=='' || nDiv==null ? null : parent.document.getElementById(nDiv).id;

	for (i=0; i<arrDiv.length; i++) {
		//alert(arrDiv[i].id.indexOf(nDiv) > -1);
		if ( (nDiv=='' || nDiv==null || arrDiv[i].id!=oDiv) && arrDiv[i].id.indexOf(nBloco) > -1 ) {
			arrDiv[i].style.display= nAcao==null || nAcao=='' || nAcao==false ? 'none' : 'block';
		} else if ( (nDiv=='' || nDiv==null || arrDiv[i].id==oDiv) && arrDiv[i].id.indexOf(nBloco) > -1 ) {
			arrDiv[i].style.display='block';
		}
	}
}
//******************************************************************************************
// FIM da função de controle de DIVs para exibir ou ocultar.
//******************************************************************************************


//##################################
///Arquivo: crosshair.js
//##################################

/*
Crosshair routine
Released into the public domain by John Kaster and Jeff Overcash, 2000
Please submit any enhancements back to the CodeCentral repository
*/

function getobj( id )
{
  /* return document.all( id ); // only works with IE 4 and above */
  return document.getElementById(id);
  /* return self.document[ id ]; */
}

function crosshair(iRow,iCol,sColor)
{
  var r, c;
  var obj;

  if ( iRow && iCol ) // Crosshair
  {
    for ( r = 0; r <= iRow; r++ )
    {
      id = 'RC' + r + '_' + iCol;
	  obj = getobj( id );
      if (obj)
        obj.bgColor = sColor;
    }

    for ( c = 0; c <= iCol; c++ )
    {
      id = 'RC' + iRow + '_' + c;
      obj = getobj( id );
      if (obj)
        obj.bgColor = sColor;
    }
  }
  else if ( iRow == 0 ) // Doing the whole column
  {
    r = 0;
    id = 'RC' + r + '_' + iCol;
    obj = getobj( id );
    while (obj)
    {
      obj.bgColor = sColor;
      r++;
      id = 'RC' + r + '_' + iCol;
      obj = getobj( id );
  }
  }
  else if ( iCol == 0 ) // Doing the whole row
  {
    c = 0;
    id = 'RC' + iRow + '_' + c;
    obj = getobj( id );
    while (obj)
    {
      obj.bgColor = sColor;
      c++;
      id = 'RC' + iRow + '_' + c;
      obj = getobj( id );
    }
  }
}





//********************************************************************************************************************
// INICIO da função de move itens de uma combo dinâmica para um LIST.
//********************************************************************************************************************
// Por: Gilvan Brandão Leandro em: 20/02/2009 11h53
// E-mail: gilvan.leandro@gmail.com
//********************************************************************************************************************
// oObjOrigem = Nome do objeto de ORIGEM do dado a ser movido.
// oObjDestino = Nome do objeto de DESTINO do dado a ser movido.
//********************************************************************************************************************
// Ex.: controlaDIVs(moveComboDinamica(frmDados.selectListaComboLocalidadeMeta,frmDados.TB0044_COD_LOCALIDADE_META););
//********************************************************************************************************************
function moveComboDinamica(oObjOrigem, oObjDestino) {
	if (oObjOrigem.selectedIndex >=0 && oObjOrigem.options[oObjOrigem.selectedIndex].value!="") {
		oObjDestino.options[oObjDestino.length] = new Option(oObjOrigem.options[oObjOrigem.selectedIndex].text, oObjOrigem.options[oObjOrigem.selectedIndex].value, false, false);
		oObjOrigem.options[oObjOrigem.selectedIndex] = null;
	}
}
//*************************************************************************************************
// FIM da função de move itens de uma combo dinâmica para um LIST.
//*************************************************************************************************






function anuvia( nTipo, nPage ) {
	if (nTipo==true) {
		//alert(top.document.framePrincipal.frameTrabalho);
		top.document.framePrincipal.frameMenu.menu.style.visibility='visible';
	} else {
		//top.document.framePrincipal.frameMenu.menu.style.visibility='hidden';
		top.frames['framePrincipal'].frames['frameMenu'].location.reload(true);
		//top.document.getElementById("framePrincipal").src = '/sigob/menu.asp';
	}
	if (nPage!=null && nPage!='') {
		location.href=nPage;
	}
}



function criaBalao (vTitulo, vConteudo, vEsquerda, vTopo ) {
	
	if (typeof(vEsquerda)=='object') {
		vLeft = getXY(vEsquerda).x;
		vTop = getXY(vEsquerda).y;
	} else {
		vLeft = vEsquerda;
		vTop = vTopo;
	}
	
	vParametro = '	<div id="ajuda" style="background:url(/funasa/imagens/balao.png) no-repeat; width:298px; height:86px; position:relative; left:'+vLeft+'px; top:'+vTop+'px">';
	vParametro += '		<table width="298" height="70" border="0" cellpadding="0" cellspacing="0">';
	vParametro += '			<tr>';
	vParametro += '				<td style="padding-left:40px; font-weight:bold; padding-top:10px" height="15">';
	vParametro += '					' + vTitulo;
	vParametro += '				</td>';
	vParametro += '				<td align="right" style="padding-top:6px; padding-right:11px; cursor:pointer">';
	vParametro += '						<img src="/funasa/imagens/spacer.gif"s width="15" height="15" border="0" onClick="document.getElementById(\'ajuda\').style.display=\'none\';">';
	vParametro += '				</td>';
	vParametro += '			</tr>';
	vParametro += '			<tr>';
	vParametro += '				<td style="font-size:11px; padding-left:20px;" colspan="2">';
	vParametro += '					' + vConteudo;
	vParametro += '				</td>';
	vParametro += '			</tr>';
	vParametro += '		</table>';
	vParametro += '	</div>';

	if (typeof(vEsquerda)=='object') {
		//top.document.body.insertAdjacentHTML("beforeEnd",vParametro);
	} else {
		document.write(vParametro);
	}
		
}




function getXY(obj) {
	var curleft = 0;
	var curtop = 0;
	var border;
	var padding;
	if (obj.offsetParent) {
		do {
			// XXX: If the element is position: relative we have to add borderWidth
			if (getStyle(obj, 'position') != 'absolute') {
				if (border = getStyle(obj, 'border-top-width')) curtop += parseInt(border);
				if (border = getStyle(obj, 'border-left-width')) curleft += parseInt(border);
				
				if (padding = getStyle(obj, 'padding-top')) curtop += parseInt(padding);
				if (padding = getStyle(obj, 'padding-left')) curleft += parseInt(padding);
			}
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
		while (obj = obj.offsetParent)
	} else if (obj.x) {
		curleft += obj.x;
		curtop += obj.y;
	}
	return {'x': curleft, 'y': curtop};
}


function getStyle(obj, styleProp) {
  if (obj.currentStyle)
    return obj.currentStyle[styleProp];
  else if (window.getComputedStyle)
    return document.defaultView.getComputedStyle(obj,null).getPropertyValue(styleProp);
}







//verifica validade de e-mail
function validaEmail(oObj){
  if (oObj.value != ""){
	email = oObj.value;
    for (i=0; i < email.length; i++) {
        if (email.charAt(i) != "@") {
    		email_valido1 = false;
		} else {
    		email_valido1 = true;
			i = email.length;
	    }
    }
	email = oObj.value;
    for (i=0; i < email.length; i++) {
        if (email.charAt(i) != ".") {
    		email_valido2 = false;
		} else {
    		email_valido2 = true;
			i = email.length;
		}
    }
	if ((email_valido1==true) && (email_valido2==true)) {
		return false;
	}
	alert('Endereço eletrônico inválido!');
	oObj.value="";
	oObj.focus();
  }
}

function redireciona(url){
window.location.href = url;	
	
	}


//--------------------------------------------------------------------------------------------------------------
// INICIO - Formata campos Ctrl c e Ctrl v - Bruno Abrantes de Oliveira 
//--------------------------------------------------------------------------------------------------------------

function validateKey (evt)   
    {
		var ctrl=window.event.ctrlKey;
		var tecla=window.event.keyCode;
		if (ctrl && tecla==67) {
			event.keyCode=0; event.returnValue=false;}
		if (ctrl && tecla==86) {
			event.keyCode=0; event.returnValue=false;}



}
//--------------------------------------------------------------------------------------------------------------
// FIM  - Formata campos Ctrl v - Bruno Abrantes de Oliveira 
//-------------------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------------------------
// INICIO Função que bloqueia o botão direito do mouse para evitar copiar e colar nos campos - Bruno Abrantes de Oliveira 
//------------------------------------------------------------------------------------------------------------------------



/*function click() {
if (event.button==2||event.button==3) {
oncontextmenu='return false';
}
}
document.onmousedown=click
document.oncontextmenu = new Function("return false;")



--------------- A mesma função de cima porem bloqueia somentea a pagina desejada ---------------------------------
<script language="javascript">
function click() {
if (event.button==2||event.button==3) {
oncontextmenu='return false';
}
}
document.onmousedown=click
document.oncontextmenu = new Function("return false;")
</script> */


//--------------------------------------------------------------------------------------------------------------
// FIM  - Função que bloqueia o botão direito do mouse para evitar copiar e colar nos campos - Bruno Abrantes de Oliveira 
//--------------------------------------------------------------------------------------------------------------


//RETORNA O VALOR NUMÉRICO SEM A PARTE DECIMAL
function trataMoeda(valor){
	return parseFloat(valor.replace(/\./g, '').replace(',', '.'));
}

