/********************************************************
*    Autor : Romildo Cantalice
*    Criado em : -/07/2002
*    Descrição : funcoes comuns a todo sistema(controle de popups e parametros)
*    
*    Atualizado por : Romildo Cantalice
*    Data da atualização : 02/08/2002
*    Descrição da atualização : Criacao da funcao fme_refreshMe()
*    
*    Arquivos dependentes : windows.js e variaveis.js
*********************************************************/


//Abre popup personalizado
function openPopup(href, w, h, pos, popupName){
	if(w==null)w=720;
	if(h==null)h=420;
	if(pos==null)pos="center";
	if(popupName==null)popupName="SIANPopup";
	_launchwin(href,popupName,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=0,resizable=no,menubar=no,width="+w+",height="+h,pos);
}



function openPopupS_Scroll(href, w, h, pos, popupName){
	if(w==null)w=720;
	if(h==null)h=420;
	if(pos==null)pos="center";
	if(popupName==null)popupName="SIANPopup";
	_launchwin(href,popupName,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=0,resizable=no,menubar=no,width="+w+",height="+h,pos);
}


//Abre popup padrao com controle (SEM PARAM) - está é a nova versão da função abaixo, mas não pode ser simplesmente substituida por causa dos parametros.
//function openPopupItem(href, popupName){
//	var w=720;
//	var h=420;
//	if(popupName==null)popupName="popupItem";
//	_launchwin("../include/popup.asp?href="+escape(href),popupName,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=0,resizable=no,menubar=no,width="+w+",height="+h,"center");
//}


//Abre popup padrao com controle
function openPopupItem(href, popupName){
	var w=720;
	var h=420;
	if(popupName==null)popupName="popupItem";
	_launchwin("include/popup.asp?href="+escape(href)+"&param="+escape(top.j_search),popupName,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=0,resizable=no,menubar=no,width="+w+",height="+h,"center");
}


function closewin(name){
	_closewin(name);
}


//atualiza ou cria mais algum parametro (para usar a funcao abaixo passe atualizacoes="&nomeCampo=x&nomeCampoN=xN")
//ATENCAO - inicie sempre com &
//Caso atualizacoes seja vazio o search somente sera repassado para o location
function parametros(atualizacoes){
	var aux_search=-1;
	var isUpdate=false;
	var parametro="";
	var params;
	
	if(!top.j_atual){
		top.j_atual=true;
		params=atualizacoes.substr(1).split('&');
		
		
		for(j=0;j<params.length;j++){
			parametro=params[j];
			//(INICIO)atualizando parametro a parametro ou criando novo parametro
			for(i=0;i<top.j_parametros.length;i++){
				aux_search = top.j_parametros[i].search('=');
				if(top.j_parametros[i].substring(0,aux_search)==parametro.substring(0,parametro.search('='))){
					top.j_parametros[i]=parametro;
					isUpdate=true;
				}
			}
			if(!isUpdate){
				top.j_parametros[top.j_parametros.length]=parametro;
			}
			//(FIM)
		}
		
		
		//atualizando a variavel top.j_search
		top.j_search="";
		for(i=0;i<top.j_parametros.length;i++){
			top.j_search+=top.j_parametros[i]+"&";
		}
		//atualiza o novo search no fme_principal.
		top.fme_direito.location.search="?"+top.j_search;
		
	}else{
		top.j_atual=false;
	}
}


//recarrega o fme_principal atualizando os parametros baseados na variavel j_search
function fme_refresh(){
	if(top.j_search!=""){
		top.parametros("&"+top.j_search);
		top.j_atual=false;
		return true;
	}
	return false;
}


//recarrega o fme_principal atualizando os parametros baseados na variavel j_search
//para ser utilizada do proprio fme p/ utilizar de outro lugar utilize a fme_refresh()
function fme_refreshMe(){
	if(top.j_search!=""){
		top.parametros("&"+top.j_search);
		return true;
	}
	return false;
}


//limpa o vetor de parametros e a variavel j_search
function clearParam(){
	for(i=0;i<top.j_parametros.length;i++){
		top.j_parametros[i]=null;
	}
	top.j_parametros.length=0;
	top.j_search="";
}


//retorna uma QueryString com todos os elementos do formulario ou retorna null se o formulario nao existir
function frmToStr(elements){
	var str="";
	if(elements!=null){
		for(i=0;i<elements.length;i++){
			str+="&"+elements[i].name+"="+elements[i].value;
		}
		return str;
	}else{
		return null;
	}
}


//funcao trim do JS
function trimStr(str){
	var i;
	var ret="";
	if(str!=null){
		for(i=0;i<str.length;i++){
			if(str.charAt(i)!=" ")
				ret+=str.charAt(i);
		}
	}
	return ret;
}


//um replace mais funcional
function replaceStr(str,strS,strR){
	var i;
	var ret="";
	if(str!=null){
		for(i=0;i<str.length;i++){
			if(str.charAt(i)!=strS)
				ret+=str.charAt(i);
			else
				ret+=strR;
		}
	}
	return ret;
}


//retira acentos, espacos e troca cedilha por c de uma string / Simplifica os caracteres de uma string
function simplifyStr(s){
	var vetC;
	var i,j,k;
	var ret="";
	var aux="";
	
	vetC = [["a","á","à","ã","â","ä"], ["e","é","è","ê","ë"], ["i","í","ì","î","ï"], ["o","ó","ò","õ","ô","ö"], ["u","ú","ù","û","ü"], ["c","ç"], ["_", " "], ["","(",")","{","}","+","-","="]];
	
	
	for(i=0;i<vetC.length;i++){
		
		for(j=1;j<vetC[i].length;j++){
			
			s = replaceStr(s, vetC[i][j],vetC[i][0]);
			
		}
		
	}
	
	s = s.substring(0,s.indexOf("[")) + s.substring(s.lastIndexOf("]")+1,s.length);
	
	return s;
}


//conta qntas vezes a string strC aparece na string str
function contStr(str,strC){
	var i=str.indexOf(strC);
	var ret=0;
	
	if(str!=null && strC!=null){
		while(i!=-1){
			ret+=1;
			i++;
			iAux = (i>=0)?((i-1)<str.length?i:str.length):str.length;
			i=str.indexOf(strC,iAux);
		}
	}
	return ret;
}


//essa funcao merece ser patentiada - ela cria um ponteiro para o objeto procurado independente dos frames.
/**********************************************************************************
Basta especificar o objName, mas se preferir pode dizer o topKnowed que é o objeto 
janela ou frame conhecido e o topAll que é o objeto window onde contem o objeto bw.
O objeto bw é um objeto de identificacao do browser.
Se especificar o topKnowed é obrigatório especificar topAll e vice-versa.
***********************************************************************************/
function findObj(objName, topKnowed, topAll){
	var fmeI, fmeJ;
	var ret, aux;//variavel aux foi criada devido a um BUG da funca eval no NE.
	
	topAll==null?topAll=top:void(0);
	topKnowed==null?topKnowed=top:void(0);
	
	if(topKnowed.frames.length!=0){
		for(fmeI=0;fmeI<topKnowed.frames.length;fmeI++){
			aux=topKnowed.frames[fmeI];
			ret=topAll.bw.dom?topKnowed.frames[fmeI].document.getElementById(objName):topAll.bw.ie4?topKnowed.frames[fmeI].document.all[objName]:topAll.bw.ns4?eval('aux.document.'+objName):0;
			if(ret!=null){
				break;
			}else{
				if(topKnowed.frames[fmeI].frames.length!=0)
					ret=findObj(objName, topKnowed.frames[fmeI], topAll);
			}
			if(ret!=null)
				break;
		}
	}else{
		ret=topAll.bw.dom?topKnowed.document.getElementById(objName):topAll.bw.ie4?topKnowed.document.all[objName]:topAll.bw.ns4?eval('topKnowed.document.'+objName):0;
	}
	
	return ret;
}




function lib_bwcheck(){
	this.ver=navigator.appVersion
	this.agent=navigator.userAgent
	this.dom=document.getElementById?1:0
	this.opera5=this.agent.indexOf("Opera 5")>-1
	this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0; 
	this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
	this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
	this.ie=this.ie4||this.ie5||this.ie6
	this.mac=this.agent.indexOf("Mac")>-1
	this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0; 
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
	return this
}
top.bw=new lib_bwcheck();


//funcao trim do JS
function trimStr(str){
	var i;
	var ret="";
	if(str!=null){
		for(i=0;i<str.length;i++){
			if(str.charAt(i)!=" ")
				ret+=str.charAt(i);
		}
	}
	return ret;
}


//um replace mais funcional
function replaceStr(str,strS,strR){
	var i;
	var ret="";
	if(str!=null){
		for(i=0;i<str.length;i++){
			if(str.charAt(i)!=strS)
				ret+=str.charAt(i);
			else
				ret+=strR;
		}
	}
	return ret;
}


//retira acentos e troca cedilha por c de uma string
function simplifyStr(s){
	var vetC;
	var i,j,k;
	var ret="";
	var aux="";
	
	vetC = [["a","á","à","ã","â","ä"], ["e","é","è","ê","ë"], ["i","í","ì","î","ï"], ["o","ó","ò","õ","ô","ö"], ["u","ú","ù","û","ü"], ["c","ç"], ["_", " "], ["","(",")","{","}","+","-","="]];
	
	
	for(i=0;i<vetC.length;i++){
		
		for(j=1;j<vetC[i].length;j++){
			
			s = replaceStr(s, vetC[i][j],vetC[i][0]);
			
		}
		
	}
	
	s = s.substring(0,s.indexOf("[")) + s.substring(s.lastIndexOf("]")+1,s.length);
	
	return s;
}


//conta qntas vezes a string strC aparece na string str
function contStr(str,strC){
	var i=str.indexOf(strC);
	var ret=0;
	
	if(str!=null && strC!=null){
		while(i!=-1){
			ret+=1;
			i++;
			iAux = (i>=0)?((i-1)<str.length?i:str.length):str.length;
			i=str.indexOf(strC,iAux);
		}
	}
	return ret;
}


//essa funcao merece ser patentiada - ela cria um ponteiro para o objeto procurado independente dos frames.
/**********************************************************************************
Basta especificar o objName, mas se preferir pode dizer o topKnowed que é o objeto 
janela ou frame conhecido e o topAll que é o objeto window onde contem o objeto bw.
O objeto bw é um objeto de identificacao do browser.
Se especificar o topKnowed é obrigatório especificar topAll e vice-versa.
***********************************************************************************/
function findObj(objName, topKnowed, topAll){
	var fmeI, fmeJ;
	var ret, aux;//variavel aux foi criada devido a um BUG da funca eval no NE.
	
	topAll==null?topAll=top:void(0);
	topKnowed==null?topKnowed=top:void(0);
	
	if(topKnowed.frames.length!=0){
		for(fmeI=0;fmeI<topKnowed.frames.length;fmeI++){
			aux=topKnowed.frames[fmeI];
			ret=topAll.bw.dom?topKnowed.frames[fmeI].document.getElementById(objName):topAll.bw.ie4?topKnowed.frames[fmeI].document.all[objName]:topAll.bw.ns4?eval('aux.document.'+objName):0;
			if(ret!=null){
				break;
			}else{
				if(topKnowed.frames[fmeI].frames.length!=0)
					ret=findObj(objName, topKnowed.frames[fmeI], topAll);
			}
			if(ret!=null)
				break;
		}
	}else{
		ret=topAll.bw.dom?topKnowed.document.getElementById(objName):topAll.bw.ie4?topKnowed.document.all[objName]:topAll.bw.ns4?eval('topKnowed.document.'+objName):0;
	}
	
	return ret;
}


//
function frameRefresh(){
	
	top.opener.fme_preprincipal.fme_principal.document.frm_registro.target = 'fme_principal';
	top.opener.fme_preprincipal.fme_principal.document.frm_registro.action = top.opener.fme_preprincipal.fme_principal.location;
	top.opener.fme_preprincipal.fme_principal.document.frm_registro.submit();
	
}


//
function popupRefresh(winname){
	var index;
	if(top.opener._isopened(winname)){
		
		index = top.opener._getwinindex(winname);
		if(index != -1){
			if(top.opener.newwin[index].ref && !top.opener.newwin[index].ref.closed){
				top.opener.newwin[index].ref.fme_principal.document.frm_registro.target = 'fme_principal';
				top.opener.newwin[index].ref.fme_principal.document.frm_registro.action = top.opener.newwin[index].ref.fme_principal.location;
				top.opener.newwin[index].ref.fme_principal.document.frm_registro.submit();
			}
		}
	}
}


//O refresh Ultra highObject elite frame
//atualiza todos os popups e o fme_principal
// mantendo seus proprios parametros, tanto dos forms quanto da URL
function allRefresh(){
	var index;
	
	if(!top.opener.onRefreshing){
		top.opener.onRefreshing = true;
		for(index=0;index<top.opener.newwin.length;index++){
			if(top.opener.newwin[index].ref && !top.opener.newwin[index].ref.closed){
				if(top.opener.newwin[index].ref.top.fme_principal!=null){
					if(top.opener.newwin[index].ref.top.fme_principal.frm_registro!=null){
						top.opener.newwin[index].ref.top.fme_principal.document.frm_registro.target = 'fme_principal';
						top.opener.newwin[index].ref.top.fme_principal.document.frm_registro.action = top.opener.newwin[index].ref.top.fme_principal.location;
						top.opener.newwin[index].ref.top.fme_principal.document.frm_registro.submit();
					}
				}
			}
		}
		top.opener.fme_preprincipal.fme_principal.document.frm_registro.target = 'fme_principal';
		top.opener.fme_preprincipal.fme_principal.document.frm_registro.action = top.opener.fme_preprincipal.fme_principal.location;
		top.opener.fme_preprincipal.fme_principal.document.frm_registro.submit();
		top.opener.onRefreshing = false;
	}
}


//Aplica os novos parametros passados separados por &, atualizando o fme_principal (ex.:teste=1,outro=2)
function applyParam(param){
	var i;
	var lastURL = String(top.opener.fme_preprincipal.fme_principal.location);
	var auxURL1="";
	var auxURL2="";
	var auxParam="";
	
	var newParam = param.split("&");
	var auxIndex;
	
	
	for(i=0;i<newParam.length;i++){
		
		auxIndex=lastURL.indexOf(newParam[i].substring(0,newParam[i].indexOf("=")));
		
		if(auxIndex!=-1){
			
			auxURL1=lastURL.substring(0,auxIndex);
			auxURL1=(auxURL1.charAt(auxURL1.length-1)=="&"||auxURL1.charAt(auxURL1.length-1)=="?")?auxURL1.substring(0,auxURL1.length-1):auxURL1;
			
			auxParam = lastURL.substring(auxIndex,lastURL.indexOf("&",auxIndex)!=-1?lastURL.indexOf("&",auxIndex):lastURL.length);
			
			auxURL2=lastURL.substring(auxIndex+auxParam.length,lastURL.length);
			lastURL=auxURL1+auxURL2;
			
		}
		
	}
	
	if(param.charAt(0)=="&" || param.charAt(0)=="?")param=param.substring(1,param.length);
	lastURL+=lastURL.indexOf("?")==-1?"?":"&";
	lastURL+=param;
	
	
	top.opener.fme_preprincipal.fme_principal.document.frm_registro.target = 'fme_principal';
	top.opener.fme_preprincipal.fme_principal.document.frm_registro.action = lastURL;
	top.opener.fme_preprincipal.fme_principal.document.frm_registro.submit();
}


//aplica o valor de um elemento na URL do fme_principal.
function applyElement(j_element, j_delimit, j_postNull){
	var index;
	var str="";
	if(j_delimit==null)j_delimit=",";
	
	if(j_element.length!=null && j_element.length!=0){
		str+=j_element[0].name + "=";
		for(index=0;index<j_element.length;index++){
			if(j_postNull!=null){
				if(index==j_element.length-1)
					str+= (j_element[index].value!=""?escape(j_element[index].value):"NULL");
				else
					str+= (j_element[index].value!=""?escape(j_element[index].value):"NULL")+j_delimit;
			}else{
				if(index==j_element.length-1)
					str+= escape(j_element[index].value);
				else
					str+= escape(j_element[index].value)+j_delimit;
			}
		}
	}else{
		str+=j_element.name + "=" + escape(j_element.value);
	}
	
	if(str!=""){
		return applyParam(str);
	}else{
		return false;
	}
}


//retorna o valor do radio checado. (VERSÃO 2)
function radioCheckedValue(radio){
	var index;
	
	if(radio.length!=null && radio.length!=0){
		for(index=0;index<radio.length;index++){
			if(radio[index].checked)
				return radio[index].value;
		}
	}else{
		if(radio.checked)
			return radio.value;
	}
	return "";
}




//retorna o valor do radio checado.
function checkedCount(check){
	var index;
	var ret=0;
	
	for(index=0;index<check.length;index++){
		if(check[index].checked)
			ret++;
	}
	return ret;
}

//apaga os caracteres que não forem numéricos
function clearNotInt(j_conteudo){
	var validChars="0123456789";
	var ret="";
	var retAux=j_conteudo!=null?String(j_conteudo):"";
	var i=0;
	
	for (i=0; i<retAux.length; i++)
		if (validChars.indexOf(retAux.charAt(i)) != -1)
			ret = ret + retAux.charAt(i);
	
	return ret;
	
}

//apaga os caracteres que não forem numéricos
function clearNotFloat(j_conteudo){
	var validChars="0123456789,";
	var ret="";
	var retAux=j_conteudo!=null?String(j_conteudo):"";
	var retAux2="";
	var i=0;
	var dotIndex=-1;
	
	for (i=0; i<retAux.length; i++)
		if (validChars.indexOf(retAux.charAt(i)) != -1)
			ret = ret + retAux.charAt(i);
	retAux2 = ret;
	ret = "";
			
	for (i=0; i<retAux2.length; i++)
	{
		if (i <= (dotIndex+2) || dotIndex == -1)
		{
			if (retAux2.charAt(i) == ",")
			{
				ret = ret + ".";
				dotIndex = i;
			}
			else
			{
				ret = ret + retAux2.charAt(i);
			}
		}
	}
	
	return ret;
	
}

function verificaCampo(valor,campo)
{			
	if (vazio(valor))
	{
		camp		= eval("document.all."+campo);
		camp.value	= "";
	}
}


//************************************************************************************
// *
// * Função    : vazio
// * Descrição : evita o usuario dar espaço no inicio do campo
// *
function vazio(texto) {
	if(document.activeElement.tagName == 'INPUT') {
		for(i=0; i < texto.length; i++)
			if(texto.charAt(i) != ' ')
				return false;
		return true;
	}
	else
		return false;		
}

function pula_campo(campo,campo2,tamanho,form)
{
	var campo = eval("document."+form+"."+campo);
	var proximo;
	proximo = eval("document."+form+"."+campo2);
	if (campo.value.length == tamanho)
	{
		proximo.focus();
		return false;
	}
	return false;
}





function blockNumbers(e)
{
	var key;
	var keychar;
	var reg;

	if(window.event) {
	  // for IE, e.keyCode or window.event.keyCode can be used
	  key = e.keyCode;
	}
	else if(e.which) {
	  // netscape
	  key = e.which;
		if (key == 8) {
			return true;
		}
	}
	else {
	  // no event, so pass through
	  return true;
	}

	keychar = String.fromCharCode(key);
	//reg = /[^\d-]/;
	reg = /[^\d]/;
	
	//alert("keychar:" +keychar)
	//alert("reg: "+reg)
	
	return !reg.test(keychar);
}






function VerificaNumbers(oCampo)
{
	if(isNaN(oCampo)) {
		return false;
	}
	return true;
}



function txtBoxFormat(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;


	if(document.all) { // Internet Explorer
	    nTecla = evtKeyPress.keyCode;
	} else if(document.layers) { // Nestcape
	    nTecla = evtKeyPress.which;
	} else {
	    nTecla = evtKeyPress.which;
	    if (nTecla == 8) {
	        return true;
	    }
	}

    sValue = objeto.value;

    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
      bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
      bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

      if (bolMask) {
        sCod += sMask.charAt(i);
        mskLen++; }
      else {
        sCod += sValue.charAt(nCount);
        nCount++;
      }

      i++;
    }

    objeto.value = sCod;

    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58)); }
      else { // qualquer caracter...
        return true;
      }
    }
    else {
      return true;
    }
  }





/*
Permite somente digitar números. Se passar o parâmetro
pInteiro true permite inclusão de 1 ponto também.
*/
function OnlyNumber(pInteiro, oCampo)
{	 

	

  if ((event.keyCode < 48) || (event.keyCode > 57)) 
  {
	if  (pInteiro == false)
	{
 		if ((event.keyCode != 46) && (event.keyCode != 45))  // ponto 
 	  		event.returnValue = false;
 		else
 		{
	 		if (event.keyCode == 45) 
	 		{
				//if (oCampo.value.indexOf("-") >= 0)
 	 			event.returnValue = false;
 	 		}
 	 		if (event.keyCode == 46) 
 	 		{
	 			//if (oCampo.value.indexOf(".") >= 0)
 	 			event.returnValue = false;
 	 		}
 	 	}
 	 }
 	 else{
 		if (event.keyCode != 46)
 			event.returnValue = false;
 		if (event.keyCode == 46) 
 	 		{
 	 			if (oCampo.value.indexOf(".") >= 0)
 	 			event.returnValue = false;
 	 		}
	 	 	
 	 }
  }
}


function VerificaEnter(evtKeyPress)
{
	if(document.all) { // Internet Explorer
	    nTecla = evtKeyPress.keyCode;
	} else if(document.layers) { // Nestcape
	    nTecla = evtKeyPress.which;
	} else {
	    nTecla = evtKeyPress.which;		    
	}
	
	
	
	if (nTecla == 13)
	{
		ExecutaAcaoEnter(555);		
		//document.frm_multinivel.AvisaFocus.value=4;
		//document.frm_multinivel.txt_pesquisa_hidden.value	= "";
	}
		
}


function OnlyNumberVirgula(pInteiro, oCampo, evtKeyPress)
{	 

	if(document.all) { // Internet Explorer
	    nTecla = evtKeyPress.keyCode;
	} else if(document.layers) { // Nestcape
	    nTecla = evtKeyPress.which;
	} else {
	    nTecla = evtKeyPress.which;
	    if (nTecla == 8) {
	        return true;
	    }
	}
	
	if ((nTecla != 44) && (nTecla < 48) || (nTecla > 57)) 
	{
		return false;
	}
	else
	{
		if (nTecla == 44) 
		{
			if (oCampo.indexOf(",") >= 0)
			{
 	 			return false;
			}
			return true;
		}
	}
 
}





//* Valida CNPJ
function validaCNPJ(form,nomecampo) 
{
	  campo = eval("document."+form+"."+nomecampo);
      CNPJ = campo.value;
      erro = new String;
      if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n"; 
      if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
      if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
      }
      //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 += "A verificação de CNPJ suporta apenas números! \n\n"; 
    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 +="Dígito verificador com problema!";
            //erro +="CNPJ incorreto!";
    }
    if (erro.length > 0){
            alert(erro);
            return false;
    } else {
            //alert("CNPJ valido!");
    }
    return true;
}

function Verifica_Caracter()
{
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
		var tecla = event.which;

	if (!(tecla == 32 || (tecla > 39 && tecla < 58) || (tecla > 64 && tecla < 128) || (tecla > 191 && tecla < 221) || (tecla > 223 && tecla < 253))) 
	//aceitando números, letras maiúsculas, letras minúsculas, letras acentuadas e * (),-
	{
		event.keyCode = 0;
	}

	return true;
}



function Mascara (formato, keypress, objeto)
{ 

	campo = eval(objeto); 
	
	
	// DATA 
	if (formato=='cnpj_emp')
	{ 
		separador1 = '.'; 
		separador2 = '/'; 
		separador3 = '-'; 
		conjunto1 = 2; 
		conjunto2 = 6; 
		conjunto3 = 10; 
		conjunto4 = 15; 
		if (campo.value.length == conjunto1){ 
			campo.value = campo.value + separador1; 
		} 
		if (campo.value.length == conjunto2){ 
			campo.value = campo.value + separador1; 
		} 
		if (campo.value.length == conjunto3){ 
			campo.value = campo.value + separador2; 
		} 
		if (campo.value.length == conjunto4){ 
			campo.value = campo.value + separador3; 
		} 
	} 
	if (formato=='cep_emp'){ 
		separador1 = '.'; 
		separador2 = '-'; 
		conjunto1 = 2; 
		conjunto2 = 6; 
		if (campo.value.length == conjunto1){ 
			campo.value = campo.value + separador1; 
		} 
		if (campo.value.length == conjunto2){ 
			campo.value = campo.value + separador2; 
		} 
	} 
	if (formato=='tel'){ 
		separador1 = '-'; 
		conjunto1 = 4; 
		if (campo.value.length == conjunto1){ 
			campo.value = campo.value + separador1; 
		} 		
	} 
} 

function validaEmail(strEmail) 
{

	if (strEmail.indexOf("@")==-1){
		alert("O e-mail '" + strEmail + "' está incorreto.");
		return false;
		}
	if (strEmail.indexOf("@.")!=-1){
		alert("O e-mail '" + strEmail + "' está incorreto.");
		return false;
		}
	if (strEmail.indexOf(".@")!=-1){
		alert("O e-mail '" + strEmail + "' está incorreto.");
		return false;
		}
	if (strEmail.indexOf(".")==-1){
		alert("O e-mail '" + strEmail + "' está incorreto.");
		return false;
		}
	if (strEmail.indexOf("..")!=-1){
		alert("O e-mail '" + strEmail + "' está incorreto.");
		return false;
		}
	if (strEmail.charAt(strEmail.length - 1) == "."){
		alert("O e-mail '" + strEmail + "' está incorreto.");
		return false;
		}
	if (strEmail.charAt(0) == "."){
		alert("O e-mail '" + strEmail + "' está incorreto.");
		return false;
		}

	var Erro = 0
	for (i=0 ; i < strEmail.length ; i++)
	{
		if (strEmail.charCodeAt(i) != 95 && ((strEmail.charCodeAt(i) < 45) || (strEmail.charCodeAt(i) == 47) || ((strEmail.charCodeAt(i) > 57) && (strEmail.charCodeAt(i) < 64)) || ((strEmail.charCodeAt(i) > 90) && (strEmail.charCodeAt(i) < 97)) || (strEmail.charCodeAt(i) > 122)))
		{
			Erro = 1
			i = strEmail.length
		}
	}
	if (Erro == 1)
	{
		alert('Caracteres inválidos no e-mail "' + strEmail + '".')
		return false
	}
	return true
}		



function VSaida()
{

    document.frm_login_erro.target = "fme_sian";
	document.frm_login_erro.action = "../include/topo.asp";
	document.frm_login_erro.submit();

	document.frm_login_erro.target = "fme_esquerdo";
	document.frm_login_erro.action = "Menu_Inicial.asp";
	document.frm_login_erro.submit();

	document.frm_login_erro.target = "fme_direito";
	//document.frm_login_erro.action = "../Seguranca/Apresentacao_Inicial.asp";
	document.frm_login_erro.action = "../Seguranca/login.asp";
	document.frm_login_erro.submit();
	
}


function VSaidaInicial()
{
	document.frm_login_erro.target = "fme_direito";
	document.frm_login_erro.action = "../Seguranca/Mensagem_Saida.asp";
	document.frm_login_erro.submit();
	
	document.frm_login_erro.target = "fme_esquerdo";
	document.frm_login_erro.action = "../Seguranca/Menu_Inicial.asp";
	document.frm_login_erro.submit();

	
	
	document.frm_login_erro.target = "fme_sian";
	document.frm_login_erro.action = "../include/topo.asp";
	document.frm_login_erro.submit();

}

function trimtodigits(tstring)
{ 
    s=""; 
    ts=new String(tstring); 
    for(x=0;x<ts.length;x++){ 
    ch=ts.charAt(x); 
    if(asc(ch)>=48 && asc(ch)<=57){ 
    s=s+ch; 
    } 
    } 
    return s; 
} 


function valida_texto()
{
	if (document.all) // Internet Explorer
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
		var tecla = event.which;

	if (!(tecla == 32 || (tecla > 39 && tecla < 58) || (tecla > 64 && tecla < 128) || (tecla > 191 && tecla < 221) || (tecla > 223 && tecla < 253))) 
	//aceitando números, letras maiúsculas, letras minúsculas, letras acentuadas e * (),-
	{
		event.keyCode = 0;
	}

	return true;
}

function fjs_SolicitaTabelas(tabela,inclusao,alteracao,exclusao)
{
		if (tabela != '')
		{
				openPopupS_Scroll("tabelas/pop_exibe.asp?tabela="+tabela+"&inclusao="+inclusao+"&alteracao="+alteracao+"&exclusao="+exclusao, "", "", "", "SolicitacaoTabelas");
				//openPopup("tabelas/pop_exibe.asp?tabela="+tabela+"&inclusao="+inclusao+"&alteracao="+alteracao+"&exclusao="+exclusao, "", "", "", "SolicitacaoTabelas");				
		}
}

// *
// * Função    : right
// * Descrição : Conserva na string apenas o número de caracteres
// *             informado da direita para a esquerda.
// *
function right (strText, pSize) {
 return strText.substring(strText.length - pSize, strText.length);
}

// *
// * Função    : left
// * Descrição : Conserva na string apenas o número de caracteres
// *             informado da esquerda para a direita.
// *
function left (strText, pSize) {
 return strText.substring(0, pSize);
}

// *
// * Função    : mid
// * Descrição : Conserva na string apenas o número de caracteres
// *             informado a partir da posição informada.
// *
function mid (strText, pPosition, pSize) {
 return strText.substring(pPosition - 1, pSize);
}

// *
// * Função    : rTrim
// * Descrição : Elimina espaços em branco ao final de campos String.
// *
function rTrim (strText) {
 while ('' + strText.charAt(strText.length - 1) == ' ')
  strText = strText.substring(0, strText.length - 1);

 return strText;
}

// *
// * Função    : lTrim
// * Descrição : Elimina espaços em branco no início de campos String.
// *
function lTrim (strText) {
 while ('' + strText.charAt(0) == ' ')
  strText = strText.substring(1, strText.length);

 return strText;
}



function centerWindow()
{
 var screenWidth   = screen.width;
 var screenHeight  = screen.height;

 var windowWidth   = document.body.clientWidth;
 var windowHeight  = document.body.clientHeight;

 window.top.moveTo((screenWidth - windowWidth) / 2, (screenHeight - windowHeight - 30) / 2);
}


function resizeWindow(x, y)
{
 window.top.resizeTo(x, y);
}


//Função que exibe o Alt da imagem
function fnDivMensagem(div,Status,Indice,contador,left,top )
{
//alert(contador)
	var mensagem
	var i
	
	//alert(navigator.appName)
					
					
	//var x = event.clientX;
	//var y = event.clientY;
					
	//alert("x: "+x +" Y: "+y)

	contador = 1
	//mensagem = "lalalalala";

	//for (i=0;i < mensagem.length; i++){
	//	mensagem = mensagem.replace("|"," "); 
	//	mensagem = mensagem.replace("::","<br>");
	//}		

	//document.getElementById('TdMensagem').innerHTML    = mensagem; 

	//document.getElementById('divMensagem').style.left     = 750;//event.clientX +(20*contador);
	//document.getElementById('divMensagem').style.top      = 100;//event.clientY -(20*contador);
	
	v_left = "60%";
	v_top  = "25%"
	
	if (left != "")
	{
		v_left = left;
	}
	if (top != "")
	{
		v_top = top;
	}
	
	
	document.getElementById(div).style.left     = v_left;
	document.getElementById(div).style.top      = v_top;
								
	document.getElementById(div).style.display  = Status;
}
