function AcertaStringSql(campo)
{
    //a variavel valid contem todos os caracteres permitidos, o que nao estiver em valid eh suprimido da string
    var valid = " !#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ªºÁÀÃÂÄÉÊÎÍÓÕÔÚÛÜÇáàãâäéêîíóõôúûüç"
    var temp;
    var ehenter=0;
    var stringok = "";
    for (var i=0; i<campo.length; i++) {
        temp = campo.substr(i, 1);
     if (valid.indexOf(temp) != "-1") 
    stringok = stringok + temp;
        else 
           if (temp == "\n") //enter
            stringok = stringok + "  ";
    } 
    return(stringok);
}

//----------------------------------------------------------------------------------------

function Refresh_form(){
	top.main2.location.reload();
}

//-----------------------------------------------------------------------------------------
function funNumerico(event)
{
	var BACKSPACE = 8;
    var strValidos = "0123456789"    
	var key; 
	var tecla; 
	
	if(navigator.appName.indexOf("Netscape")!= -1) 
	  tecla= event.which; 
	else 
	  tecla= event.keyCode; 

	key = String.fromCharCode(tecla); 
	if ( tecla == BACKSPACE ) 
	 return true; 
	if ( tecla == 0 ) //tab
	 return true; 
	if (strValidos.indexOf( key ) == -1 ){
	  return false;
	}
	return true;
} 

//-----------------------------------------------------------------------------------------
function funFormataData(data,event){
	if (funNumerico(event) == true){
		if (event.keyCode != 8) {
			if(data.value.length == 2){
				data.value = data.value + '/';
			}
			if (data.value.length == 5){
				data.value = data.value + '/';						
			}
		}
	}
	else {
		return false;
	}
		
}	

//-----------------------------------------------------------------------------------------
function wData() {
	this.dia = 0;
	this.mes = 0;
	this.ano = 0;
}

//-----------------------------------------------------------------------------------------
function ValidaData(str) {

	var wd = new wData();

	if (str.length < 1)
		return true;

	if (str.length != 10) 
		return false;      

	for (i = 0; i < str.length; i++)
		if (str.charAt(i) == "/" ||
				(str.charAt(i) >= "0" &&
				 str.charAt(i) <= "9"))
			continue;
		else
			return false;

	if (str.charAt(2) != "/" ||
	    str.charAt(5) != "/")
		return false;

	wd.dia = str.substring(0,2);
	wd.mes = str.substring(3,5);
	wd.ano = str.substring(6,10);
		
	if (wd.dia < 1 || wd.dia > 31)
		return false;

	if (wd.mes < 1 || wd.mes > 12)
		return false;

	if (wd.mes == 4 || wd.mes == 6 ||
		wd.mes == 9 || wd.mes == 11)
		if (wd.dia > 30)
			return false;
		else
			return true;

	if (wd.mes == 2)
		if (wd.dia > 29)
			return false;
		else
			if (wd.dia == 29)
				if (Bissexto(wd.ano))
					return true;
				else
					return false;

	return true;
}

//-----------------------------------------------------------------------------------------
function Bissexto(ano) {

	var resto;

	if (ano == 0) return true ;

	resto = (ano % 400);
	if (resto == 0) return true;
  
	resto = (ano % 100);
	if (resto == 0) return false;
  
	resto = (ano % 4);
	if (resto == 0) return true;

	return false;
}

//-----------------------------------------------------------------------------------------
function parseDate(dateval, tp){
	dary=dateval.split("/");
	i=new Date(dary[2],dary[1],dary[0]);
	if (tp == 'D') t=i.getDate();
	if (tp == 'M') t=i.getMonth();
	if (tp == 'A') t=i.getYear();
	if (tp == 'T') t=dary[2].toString()+dary[1].toString()+dary[0].toString();
	return t;
}//dateval

//-----------------------------------------------------------------------------------------
function ValidaCPF(st)
{
 	if (st == "")
		return (false);
	
	l = st.length;

	//aleterado para se usuário não digitar os zeros na frente do CPF, completar sozinho
	if ((l == 9) || (l == 8))
	{
		for (i = l ; i < 10; i++)
		{
			st = '0' + st
		}
	}
	l = st.length;
	st2 = "";

	for (i = 0; i < l; i++)
	{
		caracter = st.substring(i,i+1);
		if ((caracter >= '0') && (caracter <= '9'))
			st2 = st2 + caracter;
	}

	if ((st2.length > 11) || (st2.length < 10))
		return (false);

	if (st2.length==10)
		st2 = '0' + st2;
	
	digito1 = st2.substring(9,10);
	digito2 = st2.substring(10,11);
	digito1 = parseInt(digito1,10);
	digito2 = parseInt(digito2,10);
	sum = 0; mul = 10;
	
	for (i = 0; i < 9 ; i++) 
	{
		digit = st2.substring(i,i+1);
		tproduct = parseInt(digit ,10) * mul;
		sum += tproduct;
		mul--;
	}
	
	dig1 = ( sum % 11 );
	if ( dig1==0 || dig1==1 )
		dig1=0;
	else
		dig1 = 11 - dig1;

	if (dig1!=digito1)
		return (false);
	sum = 0;
	mul = 11;
	
	for (i = 0; i < 10 ; i++)
	{
		digit = st2.substring(i,i+1);
		tproduct = parseInt(digit ,10)*mul;
		sum += tproduct;
		mul--;
	}
	
	dig2 = (sum % 11);
	if ( dig2==0 || dig2==1 )
		dig2=0;
	else
		dig2 = 11 - dig2;
	
	if (dig2 != digito2)
		return (false);
	
	return (true);
}

//-----------------------------------------------------------------------------------------
function AbrePopUp(pArquivo){
	window.open(pArquivo, "Pesquisa", "status=no,scrollbars=yes,menubar=no,toolbar=no,location=no,width=600,height=450,top=0,left=0");
}

//------------------------------------------------------------------------------------------------
function MascaraCPF (campo,event)
{
	if (funNumerico(event) == true){
		if (event.keyCode != 8) {
			if(campo.value.length == 3){
				campo.value = campo.value + '.';
			}
			if (campo.value.length == 7){
				campo.value = campo.value + '.';						
			}
			if (campo.value.length == 11){
				campo.value = campo.value + '-';	
			}
		}
	}else {
		return false;
	}
}

//------------------------------------------------------------------------------------------------
function HabDesabPregao(){
	if (document.form_licit_medic.chkPregao.checked == true){
		document.form_licit_medic.chkPregaoEletSRP.disabled = false;
		document.form_licit_medic.chkPregaoEletTrad.disabled = false;
		document.form_licit_medic.chkPregaoPresSRP.disabled = false;
		document.form_licit_medic.chkPregaoPresTrad.disabled = false;
	}else{
		document.form_licit_medic.chkPregaoEletSRP.checked = false;
		document.form_licit_medic.chkPregaoEletTrad.checked = false;
		document.form_licit_medic.chkPregaoPresSRP.checked = false;
		document.form_licit_medic.chkPregaoPresTrad.checked = false;
		
		document.form_licit_medic.chkPregaoEletSRP.disabled = true;
		document.form_licit_medic.chkPregaoEletTrad.disabled = true;
		document.form_licit_medic.chkPregaoPresSRP.disabled = true;
		document.form_licit_medic.chkPregaoPresTrad.disabled = true;
	}
}

//------------------------------------------------------------------------------------------------
function HabDesabConcor(){
	if (document.form_licit_medic.chkPublica.checked == true){
		document.form_licit_medic.chkConcor.disabled = false;
		document.form_licit_medic.chkConcorSRP.disabled = false;
		document.form_licit_medic.chkConcorInter.disabled = false;
		document.form_licit_medic.chkConcorInterSRP.disabled = false;
	}else{
		document.form_licit_medic.chkConcor.checked = false;
		document.form_licit_medic.chkConcorSRP.checked = false;
		document.form_licit_medic.chkConcorInter.checked = false;
		document.form_licit_medic.chkConcorInterSRP.checked = false;
		
		document.form_licit_medic.chkConcor.disabled = true;
		document.form_licit_medic.chkConcorSRP.disabled = true;
		document.form_licit_medic.chkConcorInter.disabled = true;
		document.form_licit_medic.chkConcorInterSRP.disabled = true;
	}
}

//------------------------------------------------------------------------------------------------
function HabDesabEstrutura(pTp){
	if (pTp == 'E'){
		if (document.form_licit_medic.chkEI.checked == true){
			document.form_licit_medic.chkEE.disabled = true;
			document.form_licit_medic.chkEF.disabled = true;
			document.form_licit_medic.chkEM.disabled = true;
					
			document.form_licit_medic.chkEE.checked = false;
			document.form_licit_medic.chkEF.checked = false;
			document.form_licit_medic.chkEM.checked = false;
		}else{
			document.form_licit_medic.chkEE.disabled = false;
			document.form_licit_medic.chkEF.disabled = false;
			document.form_licit_medic.chkEM.disabled = false;
		}
				
	}
			
	if (pTp == 'P'){
		if (document.form_licit_medic.chkPI.checked == true){
			document.form_licit_medic.chkPE.disabled = true;
			document.form_licit_medic.chkPJ.disabled = true;
			document.form_licit_medic.chkPL.disabled = true;
					
			document.form_licit_medic.chkPE.checked = false;
			document.form_licit_medic.chkPJ.checked = false;
			document.form_licit_medic.chkPL.checked = false;
		}else{
			document.form_licit_medic.chkPE.disabled = false;
			document.form_licit_medic.chkPJ.disabled = false;
			document.form_licit_medic.chkPL.disabled = false;
				
		}
	}
}

//------------------------------------------------------------------------------------------------
//Funções para excluir itens selecionados de uma lista.
function Exc(voLst, vParam) {
	var vArr, i, vContinue = true;
	if (vParam == 'undefined'){
		vParam = '';
	}
	
	if (voLst.selectedIndex == -1){
		alert("Selecione pelo menos um item a ser excluído!");
		voLst.focus();
	}else{
	
			do {
				vArr = GetSelectedItems(voLst);
				if (vArr == null)
					return;
				voLst.remove(vArr[0]);
			} while(LstNumSelected(voLst) > 0)
	
			if (voLst.name=='lstMaterial'){
			
				if(voLst.length == 0){
					var oOption = parent.document.createElement("OPTION");
				    oOption.value = '';
				    
				    if (vParam == '0'){
						oOption.text  = '';
					}else{
						
						oOption.text  = '<Selecione um ou mais materiais>';							
						
					}
					
				    voLst.options.add(oOption);
				   // voLst.options[0].selected = true;
				}

			}else{
				if(voLst.length == 0){
					var oOption = parent.document.createElement("OPTION");
				    oOption.value = '';
				    
				    if (vParam == '0'){
						oOption.text  = '';
					}else{
						if (vParam == '1'){
							oOption.text  = '<Todas>';
						}else{
							oOption.text  = '<Todos>';
						}
					}
					
				    voLst.options.add(oOption);
				   // voLst.options[0].selected = true;
				}
			}
	}
}

//------------------------------------------------------------------------------------------------
function GetSelectedItems(voLst) {
	var vArr = new Array();
	var i = 0;

	for (i = 0; i < voLst.length; i++) {
		if (voLst.options[i].selected)
			vArr[vArr.length] = i;
	}

	if (vArr.length == 0)
		return null;

	return vArr;
}

//------------------------------------------------------------------------------------------------
function LstNumSelected(voLst) {
	var vCnt = 0, i = 0;

	for (i = 0; i < voLst.length; i++) {
		if (voLst.options[i].selected) { vCnt += 1 }
	} 

	return vCnt;
}

//------------------------------------------------------------------------------------------------
function PreparaValueList(pControle, pValor) {
	var vVlr = "";
	var vlLen;
	vlLen = pControle.options.length;

	for(ln=0; ln<vlLen; ln++) {
		vVlr = vVlr + ",'" + pControle.options[ln].value + "'";
	}

	vVlr = vVlr.substring(1);
	if (vVlr == "''") { vVlr = "";}
	pValor.value = vVlr;
	return true;
}

//------------------------------------------------------------------------------------------------
function PreparaValueListSemAspas(pControle, pValor) {
	var vVlr = "";
	var vlLen;
	vlLen = pControle.options.length;

	if(vlLen>1) {
		for(ln=0; ln<vlLen-1; ln++) {
			vVlr = vVlr + pControle.options[ln].value + ",";
		}
	}
	if(vlLen>0) {
		vVlr = vVlr + pControle.options[vlLen-1].value;
	}
	pValor.value = vVlr;
	return true;
}

//------------------------------------------------------------------------------------------------
function comparaDatas(dt_ini, dt_fim) 
{
	if(dt_ini.substring(2,3)!="/" || dt_fim.substring(5,6)!="/") 
	{
		alert("Formato deve ser dd/mm/aaaa."); 
		return;
	}
	dataA= new Date(dt_ini.substring(6),(dt_ini.substring(3,5)-1),dt_ini.substring(0,2));
	dataB= new Date(dt_fim.substring(6),(dt_fim.substring(3,5)-1),dt_fim.substring(0,2));
	ano_fim = dt_ini.substring(6,10);
	
	dataA= dataA.getTime();
	dataB= dataB.getTime();
	dif = Math.abs((dataB-dataA)/1000/60/60/24);
	Mod = ano_fim%4;
	
	// ano Bissexto
	
	if (Mod == 0)
	{
		if (dif > 366)
			return (false);
		else
			return (true);
	}
	else
	{
		if (dif > 365)
			return (false);
		else
			return (true);
	}
	
}

//------------------------------------------------------------------------------------------------
function menorQueInicio(dataIni,dataFim){
	  // desmembra a data inicial
	  var diaIni = parseInt(dataIni.substring(0,2),10);
	  var mesIni = parseInt(dataIni.substring(3,5),10);
	  var anoIni = parseInt(dataIni.substring(6,10),10);
	  
	  // desmembra a data final
	  var diaFim = parseInt(dataFim.substring(0,2),10);
	  var mesFim = parseInt(dataFim.substring(3,5),10);
	  var anoFim = parseInt(dataFim.substring(6,10),10);
	  
	  // testa se é maior que 1 ano
	  if(anoFim < anoIni){
	    return true;
	  }	  
	  else if((anoFim == anoIni) && (mesFim < mesIni)){
	    return true;
	  }
	  else if ((anoFim == anoIni) && (mesFim == mesIni) && (diaFim < diaIni)){
	    return true;
	  }
	  else{
	    return false;
	  }
	}

//------------------------------------------------------------------------------------------------
function abreJanela(url){
  var top = Math.random()*100;
  var left = Math.random()*100;
  window.open (url, "", "status=no,scrollbars=yes,menubar=no,toolbar=no,location=no,width=700,height=500,top=" + top + ",left=" + left);	
}

//------------------------------------------------------------------------------------------------
// função genérica para limpar apenas as seleções feitas nas listas
function limparChecksGen(pCampo, pCampoTodos, pQtdItens) {
  if (pQtdItens == 1)
    pCampo.checked = false;
  else	
    for (i = 0; i < pQtdItens; i++)
      pCampo[i].checked = false;
  // Se o check 'TODOS' não existe
  if (pCampoTodos == null)    
    ;
  else
	pCampoTodos.checked = false;
 }

//------------------------------------------------------------------------------------------------
// função genérica para marcar/desmarcar todos os itens da lista
function marcarChkTodosGen(pCampo, pCampoTodos, pQtdItens) {
  if(pCampoTodos.checked){  	
	if (pQtdItens == 1)
		pCampo.checked = true;
	else
		for (i = 0; i < pQtdItens; i++)
			pCampo[i].checked = true;
  }
  else{  	
	if (pQtdItens == 1)
		pCampo.checked = false;
	else
		for (i = 0; i < pQtdItens; i++)
			pCampo[i].checked = false;
  }
}
 
//------------------------------------------------------------------------------------------------
// função genérica para desmarcar opção 'todos' quando um item da lista é desmarcado
function tirarChkTodosGen(pCampo, pCampoTodos){
  if (!pCampo.checked)
    pCampoTodos.checked = false;
}

//------------------------------------------------------------------------------------------------
// Função que abre a pagina do combobox da barra amarela e seta para o default o combo da barra
function comboChange(comoBox,usado){ 
	window.open( comoBox.options[comoBox.selectedIndex].value);
	if (usado) comoBox.selectedIndex=0;
}

//------------------------------------------------------------------------------------------------
// Função que utiliza expressão regular para retirar os espaços em branco do início e do fim da string
function trim(texto){
   var r, re;
   re = /^\s+|\s+$/g; //cria a expressão regular que tira os espaços em branco do INÍCIO ou do FIM da string
   r = texto.replace(re,"");
   return(r);
}

//------------------------------------------------------------------------------------------------
// Função que utiliza expressão regular para verificar se existem strings longas no texto
function testaStringGrande(texto){
	var re, r;
	re = /\S{50}/g; //cria a expressão regular que testa strings maiores que 50 caracteres sem espaço
	if(re.test(texto)){
		r = true;
	}
	else{
		r = false;
	}
	return(r);	
}

//------------------------------------------------------------------------------------------------
// Função que remove caracteres nocivos ao BD

function removeCaracteresInvalidos(campo){
	
	var retorno = 0;
	var campo_saida = campo.value;
	for (var i=0; i<campo.value.length; i++){
		campo_saida = campo_saida.replace( "--", "" );
		campo_saida = campo_saida.replace( "'", "" );
		campo_saida = campo_saida.replace( "%", "" );
		campo_saida = campo_saida.replace( "=", "" );
		campo_saida = campo_saida.replace( ">", "" );
		campo_saida = campo_saida.replace( "<", "" );
		campo_saida = campo_saida.replace( "*", "" );
		campo_saida = campo_saida.replace( '"', "" );
	}
	if (campo.value.length > campo_saida.length)
		retorno=1;

	campo.value = campo_saida;
	return(retorno);
	
}

//Retorna diferenca entre datas (em dias)
function SubData(pDiaIni, pDiaFim) {

	var dia = (RetornaData(pDiaFim) - RetornaData(pDiaIni)) / 86400000;
	return dia;
}

//Converte uma string no formato dd/mm/aaaa em formato data do javascript
function RetornaData(pDia){

	var dia, mes, ano, data, myDate;
	dia = pDia.substring(0,2);
	mes = pDia.substring(3,5);
	ano = pDia.substring(6,10);
	data = mes+"/"+dia+"/"+ano;
	myDate=new Date(eval('"'+data+'"'));
	return myDate;
}

//Verifica se é digitado apenas números,
//Usar em onKeyPress = "return validaNum(event, 'S')" 
function validaNum(e,AceitaDecimal) { 

    var BACKSPACE = 8;
    var key; 
    var tecla; 

    if (AceitaDecimal == 'S')
       var strValidos = "0123456789," 
    else
       var strValidos = "0123456789"    

    if (navigator.appName.indexOf("Netscape")!= -1) 
      tecla= e.which; 
    else 
      tecla= e.keyCode; 

    key = String.fromCharCode(tecla); 

    if ( tecla == BACKSPACE ) 
     return true; 

    if ( tecla == 0 ) //tab
     return true; 

    if (strValidos.indexOf( key ) == -1 )
      return false;

    return true;
} 

