//*****************************************************//
// FUNCOES1.JS: Funcoes para uso geral nas aplicações
// Resumo das funções:
// TransformData() = Formatação para datas (DD/MM/AAAA)
//*****************************************************//

var cor;

/*-------------------------------------------------------------------------
 * Funções utilizadas para controle de pageFrames
 * Waldir: 12/07/2007
 *-------------------------------------------------------------------------*/ 
var objTab=null;
function jsTabOver(o,F){
   var bSegue = false;
   if (objTab==null)
      bSegue = true;
   else{
      if (objTab.id!=o.id)
         bSegue=true;
   }
   if (bSegue){
      if (F==0){
         o.style.backgroundImage="url(../imagens/tab_left_inativo.gif)";
         o.getElementsByTagName("IMG")[0].src="../imagens/tab_right_inativo.gif";
      }
      if (F==1){
         o.style.backgroundImage="url(../imagens/tab_left_over.gif)";
         o.getElementsByTagName("IMG")[0].src="../imagens/tab_right_over.gif";
      }
   }
}
function jsTabAtivar(obj, url){
   if (objTab!=null){
      objTab.style.backgroundImage="url(../imagens/tab_left_inativo.gif)";
      objTab.getElementsByTagName("IMG")[0].src="../imagens/tab_right_inativo.gif";
   }
   objTab = obj;
   obj.style.backgroundImage="url(../imagens/tab_left_ativo.gif)";
   obj.getElementsByTagName("IMG")[0].src="../imagens/tab_right_ativo.gif";

   var cmd = url+"processo="+new Date().getTime();
   window.frames[0].location=cmd;
}

/*-------------------------------------------------------------------------
 * Controla itens desabilitados de um combo, com base na propriedade
 * "acesso", que deve ser criada via código.
 * Waldir: 26/07/2007
 *-------------------------------------------------------------------------*/ 
function jsComboValidar(o){
   //debugger;   
   if (o.options[o.selectedIndex].acesso=="false"){
      alert("Op\u00E7\u00E3o inv\u00E1lida!\nEscolha um item habilitado para sele\u00E7\u00E3o!");
      o.selectedIndex=0;
   }
}

/*-------------------------------------------------------------------------
 * Converte uma string com tamanho (Ftam) determinado, completando com 
 * zeros a esquerda.
 * Waldir/Alex: 26/02/2007
 *-------------------------------------------------------------------------*/ 
function strzero(Fobj,Ftam){
	var Fcodigo  = Fobj.value;
	var Wlen     = Fobj.value.length;
	var Wretorno = "";
	var Wvezes   = (Ftam-Wlen)-1
	if (Wlen>0){
	   for (i=0;i<=Wvezes;i++)	{
		   Wretorno=Wretorno+"0";
	   }
	   Fobj.value=Wretorno+Fcodigo;
	}
}

/*-------------------------------------------------------------------------
 * MANIPULAÇÃO DE DATAS
 *-------------------------------------------------------------------------
 * Formatação para digitação de data
 * Waldir/Alex: Jul/2006
 *-------------------------------------------------------------------------*/ 
function TransformData(Objeto){

   if (event.keyCode == 13){ 
      event.returnValue=false; 
      event.cancel = true;
		event.cancelBubble = true;
		return false;
	}

   if (window.event.keyCode == 37 || window.event.keyCode == 8 || 
      window.event.keyCode == 36 || window.event.keyCode == 46 || 
      window.event.keyCode == 16 || window.event.keyCode == 9)
      return;

   if (window.event.keyCode == 111 || window.event.keyCode == 191) {
		if (Objeto.value.length == 3 || Objeto.value.length == 6) {
			return;
		}
		if (Objeto.value.length == 4 || Objeto.value.length == 7) {
			var newpos = Objeto.value.length - 1;
			Objeto.value = Objeto.value.substring(0,newpos);
			return;
		}
   }

   if (Objeto.value.length == 2 || Objeto.value.length == 5) {
      Objeto.value = Objeto.value + "/";
      return;
   }
}
/*-------------------------------------------------------------------------
 * Ajustar ano digitado: de 07 para 2007
 * Waldir: Jul/2007
 *-------------------------------------------------------------------------*/ 
function TransformAno(o){
   if (o.value=="")
      alert("Nao foi informado o ano!");
   else{
      if (o.value.length<4)   // Não digitou 4 numeros...
         o.value=(parseInt(o.value)+2000);
      else{
         if (parseInt(o.value)<1950 || parseInt(o.value)>2050){
            alert("Ano invalido!");
            o.value="";
            return false;
         }
      }
   }
   return true;
}
/*-------------------------------------------------------------------------
 * Waldir: Jul/2007
 *-------------------------------------------------------------------------*/ 
function jsValidarData(sData){
   if (sData.length==8 || sData.length==10){
      var dia = eval(sData.substring(0,2));
      var mes = eval(sData.substring(3,5));
      if (sData.length==8)
         var ano = eval(sData.substring(6,8))+2000;
      else
         var ano = eval(sData.substring(6,10))
      // validar o ano
      if (ano>=1900 && ano<=2099){
         if (mes>=1 && mes<=12){
            if (mes==4 || mes==6 || mes==9 || mes==11){
               if (dia==31){
                  return false;
               }
            }
            if (mes==2){
               var anoBissexto = ano%4;
               if (anoBissexto==0 && dia>29){
                  return false;
               }
               if (anoBissexto==1 && dia>28){
                  return false;
               }
               return true;
            }
            return true;
         }else{
            return false;
         }
      }else{
         return false;
      }
   }else{
      return false;
   }
}
/*-------------------------------------------------------------------------
 * Waldir: Abr/2008
 *-------------------------------------------------------------------------*/ 
function jsValidarData2(o){
   var bRet=false;
   var sData=o.value;
   if (sData.length>0){
      if (sData.length==8 || sData.length==10){
         var dia = eval(sData.substring(0,2));
         var mes = eval(sData.substring(3,5));
         if (sData.length==8)
            var ano = eval(sData.substring(6,8))+2000;
         else
            var ano = eval(sData.substring(6,10))
         // validar o ano
         if (ano>=1900 && ano<=2099){
            if (mes>=1 && mes<=12){
               if ((mes==1 || mes==3 || mes==5 || mes==7 || mes==8 || mes==10 || mes==12) && dia<=31){
                  bRet=true;
               }
               if ((mes==4 || mes==6 || mes==9 || mes==11) && dia<31){
                  bRet=true;
               }
               if (mes==2){
                  var anoBissexto = ano%4;
                  if (anoBissexto==0 && dia<=29){bRet=true;}
                  if (anoBissexto==1 && dia<=28){bRet=true;}
               }
            }
         }
      }
      if (bRet){
         dia = eval(dia+100);
         mes = eval(mes+100);
         o.value = new String(dia).substring(1,3)+'/'+new String(mes).substring(1,3)+'/'+ano;
      }else{
         alert("Data invalida!");
         o.focus();
      }
   }
}
/*-------------------------------------------------------------------------
 * Faz com que a tecla ENTER não funcione nos comandos que possuirem este
 * javascript.
 * Como usar:  onkeypress="return TravaEnter(cmdGravar);"
 * Waldir: Jul/2007
 *-------------------------------------------------------------------------*/ 
function TravaEnter(cmdDefault){ 
   if (event.keyCode == 13){ 
      event.returnValue=false; 
      event.cancel = true;
      if (cmdDefault.type=="object")
         cmdDefault.click();
      return false;
   }
}

function CarregaPagina(strUrl){
   document.location.href = strUrl;
}

/*-------------------------------------------------------------------------
 * Formata entrada de valores, em formato REAL, ex: 1.234,56
 * Como usar: onKeyDown="FormataValor(this,event,17,2);" 
 * Waldir/Alex: Jul/2006
 *-------------------------------------------------------------------------*/ 
function FormataValor(obj,teclapres,tammax,decimais) {
	var tecla = teclapres.keyCode;
   var nIni = obj.value.length;

   // Não aceita tecla ENTER...
   if (tecla == 13){ 
      event.cancelBubble = true;
      event.returnValue=false; 
      event.cancel = true;
      return false;
   } //         0              9                0               9
   if ((tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105)){
      if (document.selection.createRange().text!="")
         obj.value="";
      if (obj.value.length < tammax){
         if (tecla=="48" || tecla=="96") {obj.value += "0";}
         if (tecla=="49" || tecla=="97") {obj.value += "1";}
         if (tecla=="50" || tecla=="98") {obj.value += "2";}
         if (tecla=="51" || tecla=="99") {obj.value += "3";}
         if (tecla=="52" || tecla=="100"){obj.value += "4";}
         if (tecla=="53" || tecla=="101"){obj.value += "5";}
         if (tecla=="54" || tecla=="102"){obj.value += "6";}
         if (tecla=="55" || tecla=="103"){obj.value += "7";}
         if (tecla=="56" || tecla=="104"){obj.value += "8";}
         if (tecla=="57" || tecla=="105"){obj.value += "9";}
         MascaraValor(obj,decimais);
      }
   } //  [-] sinal de menos
   if (tecla==109 || tecla==189){
      if (document.selection.createRange().text!="")
         obj.value="";
      if (obj.value.substring(0,1)=="-")
         obj.value = obj.value.substring(1,obj.value.length);
      else{
         if (obj.value.length < tammax)
            obj.value = "-"+obj.value;
      }
   } //  [+] sinal de mais
   if (tecla==107 || tecla==187){
      if (document.selection.createRange().text!="")
         obj.value="";
      if (obj.value.substring(0,1)=="-")
         obj.value = obj.value.substring(1,obj.value.length);
   } //  Backspace
   if (tecla==8){
      if (document.selection.createRange().text!="")
         obj.value="";
      else
         obj.value = obj.value.substring(0,obj.value.length-1);
      MascaraValor(obj,decimais);
   } //  Delete sem range selecionado...
   if (tecla==46 && document.selection.createRange().text==""){
      obj.value = obj.value.substring(0,obj.value.length-1);
      MascaraValor(obj,decimais);
   } // Tab ou (delete com range selecionado)
   if (tecla==9 || (tecla==46 && document.selection.createRange().text!="")){
      return true;
   } 
   else{
      event.cancelBubble = true;
      event.returnValue=false; 
//      event.cancel = true;
      obj.focus();
//      return false;
   }
}
function MascaraValor(o,dec){
   // Retira o sinal negativo, se houver!
   var sinal = "";
   if (o.value.substring(0,1)=="-"){
      o.value = o.value.substring(1,o.value.length);
      sinal="-";
   }
   // Retira a formatação (pontos e virgulas)
   o.value = o.value.replace( ".", "" );
   o.value = o.value.replace( ".", "" );
   o.value = o.value.replace( ".", "" );
   o.value = o.value.replace( ".", "" );
   o.value = o.value.replace( ".", "" );
   o.value = o.value.replace( ",", "" );
   
   var nDecimal="";
   var nInteiro="";
   //alert("eval('0858325')="+eval("0858325"));
   if (parseInt(dec)>0){
      // Completa com zeros a esquerda se o número for menor que as casas decimais...
      //alert("o.value.length="+o.value.length+"\ndec="+dec+"\no.value.length-parseInt(dec)="+(o.value.length-parseInt(dec)));
      while (o.value.length<=parseInt(dec)){
         o.value = "0"+o.value;
         //alert("o.value="+o.value+"\no.value.length="+o.value.length+"\ndec="+dec);
      }
      if (o.value.length>=parseInt(dec)){
         nDecimal=o.value.substring(o.value.length-parseInt(dec),o.value.length);
         nInteiro=eval(o.value.substring(0,o.value.length-parseInt(dec)));
      }else{
         nDecimal=o.value;
      }
   }else{
      nDecimal="";
      nInteiro=eval(o.value);
   }
   //alert("o.value="+o.value+"\nnInteiro="+nInteiro+"\nnDecimal="+nDecimal);

   nInteiro = String(nInteiro);
   if (nInteiro.length>3){
      var nValor = "";
      while (nInteiro.length>3){
         nValor = "."+nInteiro.substring(nInteiro.length-3,nInteiro.length)+nValor
         nInteiro=nInteiro.substr(0,nInteiro.length-3);
      }
      if (nInteiro.length>0)
         nValor = nInteiro+nValor;
      nInteiro = nValor;
   }
   if (parseInt(dec)>0)
      o.value=sinal+nInteiro+","+nDecimal;
   else
      o.value=sinal+nInteiro;
}

function ForcaCasaDecimal(o,dec){
   var idx=dec;
   if (o.value.indexOf(".")>0)
      idx=dec - o.value.substr(o.value.indexOf(".")+1,o.value.length).length;

   while (idx>0){
      o.value += "0";
      idx--;
   }
}
//function FormataValor2(objeto,teclapres,tammax,decimais) {
//	var tecla			= teclapres.keyCode;
//	//alert(tecla);
//	var tamanhoObjeto	= objeto.value.length;
//	if ((tecla == 8) && (tamanhoObjeto == tammax))
//	{
//		tamanhoObjeto = tamanhoObjeto - 1 ;
//	}
//	//    num[-]        [-]           [BkSpace]     [x]             >=[0]          <=[9]            >=[0]          <=[9]
//   if (( tecla==109 || tecla==189 || tecla == 8 || tecla == 88 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) ) && ((tamanhoObjeto+1) <= tammax))
//	{
//      //var oRange = objeto.createTextRange();
//      //for(starname in oRange) 
//      //   alert(starname); 
//      //alert(oRange.boundingHeight);
//      //alert(oRange.boundingTop);
//      //alert(oRange.boundingLeft);
//      //alert(oRange.boundingWidth);
//      //alert(oRange.offsetTop);
//      //alert(oRange.offsetLeft);
//      //alert(oRange.text);
//      //alert(oRange.htmlText);
//      //alert(oRange.text==objeto.value);

//      //if (objeto.value=="0,00"){
//      //   vr = "0,";
//      //} else {
//		   vr	= objeto.value;
//		   vr	= vr.replace( "/", "" );
//		   vr	= vr.replace( "/", "" );
//		   vr	= vr.replace( ",", "" );
//		   vr	= vr.replace( ".", "" );
//		   vr	= vr.replace( ".", "" );
//		   vr	= vr.replace( ".", "" );
//		   vr	= vr.replace( ".", "" );
//		//}
//		tam	= vr.length;
//		if (tam < tammax && tecla != 8)  // tecla != backspace
//		{
//			tam = vr.length + 1 ;
//		}
//		if ((tecla == 8) && (tam > 1))   // tecla == backspace
//		{
//			tam = tam - 1 ;
//			vr = objeto.value;
//			vr = vr.replace( "/", "" );
//			vr = vr.replace( "/", "" );
//			vr = vr.replace( ",", "" );
//			vr = vr.replace( ".", "" );
//			vr = vr.replace( ".", "" );
//			vr = vr.replace( ".", "" );
//			vr = vr.replace( ".", "" );
//		}
//		if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
//			if (decimais > 0){
//				if ( (tam <= decimais) ){ 
//					objeto.value = ("0," + vr) ;
//					//objeto.value = vr ;
//				}
//				if( (tam == (decimais + 1)) && (tecla == 8)){
//					objeto.value = vr.substr( 0, (tam - decimais)) + ',' + vr.substr( tam - (decimais), tam ) ;	
//				}
//				if ( (tam > (decimais + 1)) && (tam <= (decimais + 3)) &&  ((vr.substr(0,1)) == "0")){
//					objeto.value = vr.substr( 1, (tam - (decimais+1))) + ',' + vr.substr( tam - (decimais), tam ) ;
//				}
//				if ( (tam > (decimais + 1)) && (tam <= (decimais + 3)) &&  ((vr.substr(0,1)) != "0"))
//				{
//				    objeto.value = vr.substr( 0, tam - decimais ) + ',' + vr.substr( tam - decimais, tam ) ; 
//				}
//				if ( (tam >= (decimais + 4)) && (tam <= (decimais + 6)) )
//				{
//			 		objeto.value = vr.substr( 0, tam - (decimais + 3) ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
//				}
//			 	if ( (tam >= (decimais + 7)) && (tam <= (decimais + 9)) )
//				{
//			 		objeto.value = vr.substr( 0, tam - (decimais + 6) ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
//				}
//				if ( (tam >= (decimais + 10)) && (tam <= (decimais + 12)) )
//				{
//			 		objeto.value = vr.substr( 0, tam - (decimais + 9) ) + '.' + vr.substr( tam - (decimais + 9), 3 ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
//				}
//				if ( (tam >= (decimais + 13)) && (tam <= (decimais + 15)) )
//				{
//			 		objeto.value = vr.substr( 0, tam - (decimais + 12) ) + '.' + vr.substr( tam - (decimais + 12), 3 ) + '.' + vr.substr( tam - (decimais + 9), 3 ) + '.' + vr.substr( tam - (decimais + 6), 3 ) + '.' + vr.substr( tam - (decimais + 3), 3 ) + ',' + vr.substr( tam - decimais, tam ) ;
//				}
//			}
//			else if(decimais == 0)
//			{
//				if ( tam <= 3 )
//				{ 
//			 		objeto.value = vr ;
//				}
//				if ( (tam >= 4) && (tam <= 6) )
//				{
//					if(tecla == 8)
//					{
//						objeto.value = vr.substr(0, tam);
//						window.event.cancelBubble = true;
//						window.event.returnValue = false;
//					}
//					objeto.value = vr.substr(0, tam - 3) + '.' + vr.substr( tam - 3, 3 ); 
//				}
//				if ( (tam >= 7) && (tam <= 9) )
//				{
//					if(tecla == 8)
//					{
//						objeto.value = vr.substr(0, tam);
//						window.event.cancelBubble = true;
//						window.event.returnValue = false;
//					}
//					objeto.value = vr.substr( 0, tam - 6 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ); 
//				}
//				if ( (tam >= 10) && (tam <= 12) )
//				{
//			 		if(tecla == 8)
//					{
//						objeto.value = vr.substr(0, tam);
//						window.event.cancelBubble = true;
//						window.event.returnValue = false;
//					}
//					objeto.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ); 
//				}

//				if ( (tam >= 13) && (tam <= 15) )
//				{
//					if(tecla == 8)
//					{
//						objeto.value = vr.substr(0, tam);
//						window.event.cancelBubble = true;
//						window.event.returnValue = false;
//					}
//					objeto.value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, 3 ) ;
//				}			
//			}
//		}
//	}     // [BkSpace]                      [tab]                          [Enter]                         [end]                           [Home]                          [delete]
//	else if((window.event.keyCode != 8) && (window.event.keyCode != 9) && (window.event.keyCode != 13) && (window.event.keyCode != 35) && (window.event.keyCode != 36) && (window.event.keyCode != 46))
//	{
//		window.event.cancelBubble = true;
//		window.event.returnValue = false;
//	}
//}

function FormataCPFouCNPJ(oText,event,oPessoa)
{
   if (oPessoa.value=="J")
      return FormataTexto(oText, '99.999.999/9999-99', event);
   else
      return FormataTexto(oText, '999.999.999-99', event);
}

/*-------------------------------------------------------------------------
 * Funcão para formar a máscara de dados (Tanto Firefox (Mozilla) quanto IE)
 * Alexsander Antunes - CTIS
 * 16/12/2005
 *-------------------------------------------------------------------------*/ 
function FormataTexto(txtbox, mask, event) 
{
	var nTecla, sTexto;
	var i;
	
	try
	{
		nTecla = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	}
	catch (ex)
	{
		nTecla = event.keyCode;
	}
	
	sTexto = txtbox.value;

	// Valida a tecla atual
	if (nTecla != 8 && nTecla != 9 && nTecla != 127 && nTecla != 37 && nTecla!=38 && nTecla!=39 && nTecla!=40) 
	{ 
		// Valida os valores anteriores
		for (i =0;i < sTexto.length; i++)
		{	
			if (mask.charAt(i) == "-" ||
				mask.charAt(i) == "." ||
				mask.charAt(i) == "," ||
				mask.charAt(i) == "/" ||
				mask.charAt(i) == "(" ||
				mask.charAt(i) == ")")
			{
				// Verifica se bate com a máscara, senão troca o valor
				if (sTexto.charAt(i) != mask.charAt(i))
				{
					sTexto = sTexto.substring(0, i) + 
							mask.charAt(i);
					txtbox.value = sTexto;
					return false;
				}
			}
			else if (mask.charAt(i) == "9") {
				// apenas números
				if (sTexto.charCodeAt(i) < 48 ||	sTexto.charCodeAt(i) > 57){
					sTexto = sTexto.substring(0, i);
					txtbox.value = sTexto;
					return false;
				}
			}
			else if (mask.charAt(i) == "0") 
			{ 
				// apenas números de 0 a 9 e espaço
				if ((sTexto.charCodeAt(i) < 48 || sTexto.charCodeAt(i) > 57) &&
					sTexto.charCodeAt(i) != 32)
				{
					sTexto = sTexto.substring(0, i);
					txtbox.value = sTexto;
					return false;
				}
			}
			else if (mask.charAt(i) == "A") 
			{ 
				// Apenas letras de A-Z a-z`a
				if ((sTexto.charCodeAt(i) < 65 || sTexto.charCodeAt(i) > 90) &&
					(sTexto.charCodeAt(i) < 97 || sTexto.charCodeAt(i) > 122))
				{
					sTexto = sTexto.substring(0, i);
					txtbox.value = sTexto;
					return false;
				}
			}
			else if (mask.charAt(i) == "@") 
			{ 
				// Apenas espaço
				if (sTexto.charCodeAt(i) != 32)
				{
					sTexto = sTexto.substring(0, i);
					txtbox.value = sTexto;
					return false;
				}
			}
		}

		// Se for diferente de backspace, valida
		i = sTexto.length;
		
		if (mask.charAt(i) == "-" ||
		    mask.charAt(i) == "." ||
		    mask.charAt(i) == "," ||
		    mask.charAt(i) == "/" ||
		    mask.charAt(i) == "(" ||
		    mask.charAt(i) == ")")
		{
			// Verifica se bate com a máscara, senão troca o valor
			if (nTecla != mask.charAt(i))
			{
				sTexto = sTexto + mask.charAt(i);
				txtbox.value = sTexto;
				i++;
			}
		}
		
		if (mask.charAt(i) == "9") 
		{
			// apenas números
			if (nTecla < 48 ||
			    nTecla > 57)
			{
				return false;
			}

		}
		else if (mask.charAt(i) == "0") 
		{ 
			// apenas números de 0 a 9 e espaço
			if ((nTecla < 48 || nTecla > 57) &&
			    nTecla != 32)
			{
				return false;
			}
		}
		else if (mask.charAt(i) == "A") 
		{ 
			// Apenas letras de A-Z a-z`a
			if ((nTecla < 65 || nTecla > 90) &&
			    (nTecla < 97 || nTecla > 122))
			{
				return false;
			}
		}
		else if (mask.charAt(i) == "@") 
		{ 
			// Apenas espaço
			if (nTecla != 32)
			{
				return false;
			}
		}
		else
		{
			return true;
		}
	}
}
/*-------------------------------------------------------------------------
 * Apresenta uma cor diferente na linha de um grid onde o mouse esta posicionado
 * Waldir: Jun/2006
 *-------------------------------------------------------------------------*/ 
function grdLinha(obj,Fmodo)
{
   if (Fmodo==0)
   {
      cor=obj.style.backgroundColor;
      obj.style.backgroundColor="#FFE0C0";
   }
   if (Fmodo==1)
   {
      obj.style.backgroundColor=cor;
   }
   obj.style.cursor="hand";
}

function ClickBotao(sBotao, sCampo, sIdRegistro){
   document.form1.all(sCampo).Value = sIdRegistro;
   document.form1.all(sBotao).click();
}

/*-------------------------------------------------------------------------
 * Funcão para habilitar (mostrar) uma marca na linha selecionada (clicada)
 * de um GridView
 * Waldir - 07/11/2006
 *-------------------------------------------------------------------------*/ 
function grdMarcaLinha(nID)
{
   var o = document.getElementsByTagName("input")
   for(var x=0;x<o.length;x++)
      if (o[x].type.toLowerCase()=="image"){
         if (o[x].id.indexOf("imgMarca")>0){
            var sBmp = o[x].src.toLowerCase();
            if (sBmp.indexOf("errado.bmp")==-1){
               o[x].style.visibility="hidden";
            }
            if (o[x].modoprg==nID){
               o[x].style.visibility="visible";
            }
         }
      }
}
/*-------------------------------------------------------------------------
 * Funcão para carregar a página para pesquisa na tabela de imoveis
 *-------------------------------------------------------------------------*/ 
function pesquisaImovel(vStatus, sFiltro, obj)
{
   //debugger;
   var nomeObjImovel = obj.name.substring(0,obj.name.indexOf("$")) + "$txtImovel";
   var sCmd = "../OMI_pesquisa.aspx";
   sCmd += "?status="+vStatus;
   sCmd += "&descricao="+sFiltro;
   sCmd += "&nomeObjImovel="+nomeObjImovel;
   sCmd += "&processo="+new Date().getTime();
   window.open(sCmd,"Pesquisar","width=610,height=370,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no");
}
function pesquisaImovel2(vStatus, sFiltro, nomeObjImovel)
{
   var sCmd = "../OMI_pesquisa.aspx";
   sCmd += "?status="+vStatus;
   sCmd += "&descricao="+sFiltro;
   sCmd += "&nomeObjImovel="+nomeObjImovel;
   sCmd += "&processo="+new Date().getTime();
   window.open(sCmd,"Pesquisar","width=610,height=370,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no");
}
function pesquisaAjaxAutoComplete(vStatus, sFiltro, obj)
{
   var sCmd = "../OMI_pesquisa.aspx";
   sCmd += "?status="+vStatus;
   sCmd += "&descricao="+sFiltro;
   sCmd += "&nomeObjImovel="+obj.parentElement.parentElement.childNodes.item(1).childNodes.item(0).id;
   sCmd += "&codigoObjImovel="+obj.parentElement.parentElement.childNodes.item(0).childNodes.item(0).id;
   sCmd += "&processo="+new Date().getTime();
   window.open(sCmd,"Pesquisar","width=610,height=370,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no");
}
function jsPesquisaTabela(sTabela, sCampo, sFiltro)
{
   var sCmd = "../INCLUDE/PesquisaTabela.aspx";
   sCmd += "?tabela="+sTabela;
   sCmd += "&nomeObjImovel="+sCampo;
   sCmd += "&filtro="+sFiltro;
   sCmd += "&processo="+new Date().getTime();
   window.open(sCmd,"Pesquisar","width=400,height=370,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no");
}
function jsOpenFichaImovel(sIDimovel, sIDfoto, sOrigem, obj) {
   if (sIDimovel != "0") {
      ajaxAtualizaLog(sIDimovel, sOrigem, '1')

      var sCmd = "../Ficha/OMI_ficha.aspx";
      sCmd += "?id_imovel=" + sIDimovel;
      sCmd += "&id_foto=" + sIDfoto;
      sCmd += "&processo=" + new Date().getTime();
      window.open(sCmd, "Pesquisar", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no");
   }
}
function jsOpenFichaImovelCliente(sIDimovel, sIDfoto, sOrigem, obj)
{
   if (sIDimovel != "0") {
      ajaxAtualizaLog(sIDimovel, sOrigem, '1')

      var sCmd = "../../Ficha/OMI_ficha.aspx";
      sCmd += "?id_imovel=" + sIDimovel;
      sCmd += "&id_foto=" + sIDfoto;
      sCmd += "&processo=" + new Date().getTime();
      window.open(sCmd, "Pesquisar", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no");
   }
}

/*-------------------------------------------------------------------------
 * Funcão para habiitar ou desabilitar a edição na página
 * Waldir - 05/02/2007
 *-------------------------------------------------------------------------*/ 
function jsHabilitaCampos(sCampo, bModo){
   if (bModo){
      document.getElementsByName(sCampo).item(0).style.backgroundColor="#dddddd";
      document.getElementsByName(sCampo).item(0).readOnly=true;
      document.getElementsByName(sCampo).item(0).disabled=true;
   } else {
      document.getElementsByName(sCampo).item(0).style.backgroundColor="#ffffff";
      document.getElementsByName(sCampo).item(0).readOnly=false;
      document.getElementsByName(sCampo).item(0).disabled=false;
   }
}

/*-------------------------------------------------------------------------
 * FUNCOES MATEMÁTICAS
 *-------------------------------------------------------------------------
 * Funcão para retirar o ponto separador de milhares e depois substituir a 
 * virgula pelo ponto na casa decimal.
 * Waldir - 05/02/2007
 *-------------------------------------------------------------------------*/ 
function jsValor(sValor){
   var nRet = sValor.replace('.','').replace(',','.');
   return nRet;
}
function jsTransform(sValor) 
{
   var nRet = sValor.toFixed(2);
   nRet = nRet.replace('.',',');
   return nRet;
}

function FmascTempoReal(e,ConteudoCampo){
   var valor = (window.Event) ? e.which : e.keyCode;
   if (valor != 8){  // BackSpace
      NumDig = ConteudoCampo.value;
      TamDig = NumDig.length;
      Contador = 0;
      if (TamDig > 1){
         numer = "";
         for (i = TamDig; (i >= 0); i--){
            if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9)){
               Contador++;
               if ((Contador == 2) && ((TamDig -i) < 4)){
                  numer = ","+numer;
                  Contador = 0;
               }
               else if (Contador == 3){
                  numer = "."+numer;
                  Contador = 0;
               }
               numer = NumDig.substr(i, 1)+numer;
            }
         }
         ConteudoCampo.value = numer;
      };
   }
   else{
      NumDig = ConteudoCampo.value;
      TamDig = NumDig.length;
      TamDig--;
      Contador = 0;
      if (TamDig >= 0){ 
         numer = "";
         for (i = TamDig; (i >= 0); i--){
            if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9)){
               Contador++;
               if ((Contador == 4) && ((TamDig -i) < 5)){
                  numer = ","+numer;
                  Contador = 0;
               }
               else if ((Contador == 3) && ((numer.length) > 4)){
                  numer = "."+numer;
                  Contador = 0;
               }
               numer = NumDig.substr(i, 1)+numer;
            }
         }
         ConteudoCampo.value = numer;
      }
   }
}

function Transform(o){
   if (o.value.indexOf(".")==-1){
      o.value+=".00";
   } else {
      var nDecimais = o.value.substr(o.value.indexOf(".")+1,o.value.length).length;
      if (nDecimais==1){
         o.value+="0";
      }
      if (nDecimais>2){
         o.value=o.value.substr(0,o.value.indexOf("."))+o.value.substr(o.value.indexOf("."),3);
      }
   }
   nDecimal=o.value.substr(o.value.indexOf(".")+1,o.value.length);
   nInteiro=o.value.substr(0,o.value.indexOf("."));
   if (nInteiro.length>3){
      var nValor = "";
      while (nInteiro.length>3){
         nValor = "."+nInteiro.substring(nInteiro.length-3,nInteiro.length)+nValor
         nInteiro=nInteiro.substr(0,nInteiro.length-3);
      }
      if (nInteiro.length>0){
         nValor = nInteiro+nValor;
      }
      nInteiro = nValor;
   }
   o.value=nInteiro+","+nDecimal;
}


/*-------------------------------------------------------------------------
 * FUNCOES DE IMPRESSAO / RELATORIOS POR E-mail
 *-------------------------------------------------------------------------
 * Nome da Função: jsPrint(nFrame)
 * Funcão para imprimir apenas o relatório e não a página toda
 * Waldir/Alex: 26/02/2007
 *-------------------------------------------------------------------------*/ 
function jsPrint(nFrame){
   document.frames[nFrame].focus();
	self.print();
}
/*-------------------------------------------------------------------------
 * Carrega em uma popup a janela para informações sobre o e-mail
 * Waldir/Alex: 26/02/2007
 *-------------------------------------------------------------------------*/ 
function jsEmail(){
   var sCmd = "../INCLUDE/EnviaEmail.aspx";
   sCmd += "?processo="+new Date().getTime();
   window.open(sCmd,"Email","width=511,height=370,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no");
}

/*-------------------------------------------------------------------------
 * Ajustar a altura de um iFrame de acordo com as dimensões da página
 * Waldir: 12/07/2007
 *-------------------------------------------------------------------------*/ 
function jsAjustaIframe(sIDframe, nAjuste, nMinimo){
   var frmTemp;
   if (document.getElementById) {
      // Height da página
      var h = document.documentElement.clientHeight;
      // Se tamanho da página menos o ajuste for menor que o tamanho mínimo
      // a ser apresentado o iFrame, mantém o o iFrame com o tamano mínimo.
      if ((h-nAjuste) < nMinimo){
         if (document.getElementById(sIDframe).height)
            document.getElementById(sIDframe).height=nMinimo;
         else
            document.getElementById(sIDframe).style.height=nMinimo;
      }else{
         if (document.getElementById(sIDframe).height)
            document.getElementById(sIDframe).height=(h-nAjuste);
         else
            document.getElementById(sIDframe).style.height=(h-nAjuste);
      }
   }
}

function jsAtuQtd(obj){
    //debugger;
    var qtd = parseInt(obj.value);
    if(qtd < 0){
      obj.value = "0";
    }  
}

/*-------------------------------------------------------------------------
 * Player para video e som
 * Waldir/Alex: 05/10/2007
 *-------------------------------------------------------------------------*/ 
function MM_controlSound(x, _sndObj, sndFile) { //v3.0
   var i, method = "", sndObj = eval(_sndObj);
   if (sndObj != null) {
      if (navigator.appName == 'Netscape') 
         method = "Play";
      else {
         if (window.MM_WMP == null) {
            window.MM_WMP = false;
            for(i in sndObj){
               if (i == "ActiveMovie") {
                  window.MM_WMP = true;
                  break;
               }
            }
         }
         if (window.MM_WMP) 
            method = "play";
         else if (sndObj.FileName) 
            method = "run";
      }
   }
   if (method) 
      eval(_sndObj+"."+method+"()");
   else 
      window.location = sndFile;
}

/*-------------------------------------------------------------------------
 * Controle dos avisos e mensagens ao usuário
 * Waldir: 15/11/2007
 *-------------------------------------------------------------------------*/ 
var msgErro = {Text:"", Title:"Aten\u00E7\u00E3o!"};

function divAviso(oPagina, sTitulo, sMensagem, button1Text, button1Action, button2Text, button2Action){
   var alertStr = "";
   if (typeof(sTitulo) !== "string") 
      sTitulo = "";
   var hasButton1 = typeof(button1Text) == "string" && typeof(button1Action) == "string";
   var hasButton2 = typeof(button2Text) == "string" && typeof(button2Action) == "string";

   alertStr  = '<table cellspacing="0" cellpadding="0" border="0" style="width:100%; background-color:#333e70;">';
   alertStr += '<tr>';
   alertStr += '   <td style="font-size: 18px; text-align: left; font-family: Arial, sans-serif; color: #ffffff; padding-top: 5px; padding-bottom: 0px; padding-left: 8px; padding-right: 5px;">'+sTitulo+'</td>';
   alertStr += '   <td style="padding-top: 5px; padding-right: 5px; padding-bottom: 0px; text-align: right;" valign="top">';
   alertStr += '      <a href=\'javascript:divAvisoFechar()\'><img src="../imagens/xp-cancel.gif" border="0"></a>';
   alertStr += '   </td>';
   alertStr += '</tr>';

   if (sTitulo == ""){
      alertStr += '<tr><td></td></tr>';
      alertStr += '<tr><td colspan="2" style="text-align: left; font-family: Tahoma; font-size: 12px; color: #fff; padding-top: 5px; padding-bottom: 5px; padding-left: 32px; padding-right: 32px;">'+sMensagem+'</td></tr>';
   }else{
      alertStr += '<tr><td style="height: 15px;"></td></tr>';
      alertStr += '<tr><td colspan="2" style="text-align: left; font-family: Tahoma; font-size: 12px; color: #fff; padding-top: 5px; padding-bottom: 5px; padding-left: 32px; padding-right: 32px;">'+sMensagem+'</td></tr>';
   }
   
   if (hasButton1){
      alertStr += '<tr><td colspan="2" style="textAlign:center;">';
      alertStr += '   <input type="button" value=\''+button1Text+'\' onClick=\''+button1Action+'\' />';
      if (hasButton2) 
         alertStr += '&nbsp;<input type="button" value=\''+button2Text+'\' onClick=\''+button2Action+'\' />';
      alertStr += '</td></tr>';
   }
 
   alertStr += '<tr><td style="height: 15px;"></td></tr>';
   alertStr += '</table>';
   if (!oPagina.getElementById("divAvisoID")){
      newDiv = oPagina.createElement("div");
      newDiv.id = "divAvisoID";
      oPagina.body.appendChild(newDiv);
   }

   oPagina.getElementById("divAvisoID").innerHTML = alertStr;

   cWidth = oPagina.body.clientWidth;
   cHeight = oPagina.body.clientHeight;
   if (parseInt(cHeight)==0)
      cHeight = oPagina.documentElement.clientHeight;
      
   if (parseInt(cHeight)>0)
      oPagina.getElementById("divAvisoID").style.top = (cHeight / 4);
   else
      oPagina.getElementById("divAvisoID").style.top = oPagina.body.scrollTop + 100;
      
   //oPagina.getElementById("divAvisoID").style.left = (cWidth / 2)-260;
   oPagina.getElementById("divAvisoID").style.display = "block";
   oPagina.getElementById("divAvisoID").style.position = "absolute";
   oPagina.getElementById("divAvisoID").style.zIndex = "100";
   oPagina.getElementById("divAvisoID").style.width = "70%";
   oPagina.getElementById("divAvisoID").style.left = "15%";
   oPagina.getElementById("divAvisoID").style.top = "25%";
   oPagina.getElementById("divAvisoID").style.border = "solid 1px #a3c7e2";
   oPagina.getElementById("divAvisoID").style.verticalAlign = "middle";
   oPagina.getElementById("divAvisoID").style.textAlign = "center";

   if (!oPagina.getElementById("divSombra")){
      newDiv2 = oPagina.createElement("div");
      newDiv2.id = "divSombra";
      oPagina.body.appendChild(newDiv2);
   }
   oPagina.getElementById("divSombra").style.width = oPagina.documentElement.clientWidth + 'px';
   document.getElementById("divSombra").style.display = "block";
}

function divAguarde(oPagina){
   sAguarde  = '<table cellspacing="0" cellpadding="0" border="0" style="width:100%; background-color:#ffffae;">';
   sAguarde += '<tr>';
   sAguarde += '   <td style="font-size: 18px; text-align: left; font-family: Arial, sans-serif; color: #333333; padding-top: 5px; padding-bottom: 0px; padding-left: 8px; padding-right: 5px;">Aguarde!</td>';
   sAguarde += '   <td style="padding-top: 5px; padding-right: 5px; padding-bottom: 0px; text-align: right;" valign="top">';
   sAguarde += '      <a href=\'javascript:divAvisoFechar()\'><img src="../imagens/xp-cancel.gif" border="0"></a>';
   sAguarde += '   </td>';
   sAguarde += '</tr>';

   sAguarde += '<tr><td style="height: 15px;"></td></tr>';
   sAguarde += '<tr><td colspan="2" style="text-align: left; font-family: Tahoma; font-size: 12px; color: #333333; padding-top: 5px; padding-bottom: 5px; padding-left: 32px; padding-right: 32px;">Trabalhando em sua solicita\u00E7\u00E3o...</td></tr>';
   sAguarde += '<tr><td style="height: 15px;"></td></tr>';
   sAguarde += '</table>';

   if (!oPagina.getElementById("divAguardeID")){
      newDiv = oPagina.createElement("div");
      newDiv.id = "divAguardeID";
      oPagina.body.appendChild(newDiv);
   }
   oPagina.getElementById("divAguardeID").innerHTML = sAguarde;
   cWidth = oPagina.body.clientWidth;
   cHeight = oPagina.body.clientHeight;
   if (parseInt(cHeight)==0)
      cHeight = oPagina.documentElement.clientHeight;

   if (parseInt(cHeight)>0)
      oPagina.getElementById("divAguardeID").style.top = (cHeight / 4);
   else
      oPagina.getElementById("divAguardeID").style.top = oPagina.body.scrollTop + 100;

   //oPagina.getElementById("divAguardeID").style.left = (cWidth / 2)-260;
   oPagina.getElementById("divAguardeID").style.display = "block";
   oPagina.getElementById("divAguardeID").style.position = "absolute";
   oPagina.getElementById("divAguardeID").style.zIndex = "100";
   oPagina.getElementById("divAguardeID").style.width = "50%";
   oPagina.getElementById("divAguardeID").style.left = "25%";
   oPagina.getElementById("divAguardeID").style.top = "25%";
   oPagina.getElementById("divAguardeID").style.border = "solid 1px #a3c7e2";
   oPagina.getElementById("divAguardeID").style.verticalAlign = "middle";
   oPagina.getElementById("divAguardeID").style.textAlign = "center";

   if (!oPagina.getElementById("divAguarde")){
      newDiv = oPagina.createElement("div");
      newDiv.id = "divAguarde";
      oPagina.body.appendChild(newDiv);
   }
   oPagina.getElementById("divAguarde").style.width = oPagina.documentElement.clientWidth + 'px';
   document.getElementById("divAguarde").style.display = "block";
}

function divAvisoFechar(){
   if (document.getElementById("divAvisoID"))
      document.getElementById("divAvisoID").style.display = "none";
   if (document.getElementById("divSombra"))
      document.getElementById("divSombra").style.display = "none";
   if (document.getElementById("divAguardeID"))
      document.getElementById("divAguardeID").style.display = "none";
   if (document.getElementById("divAguarde"))
      document.getElementById("divAguarde").style.display = "none";
}

/*-------------------------------------------------------------------------
 * Validação CPF e CNPJ
 *-------------------------------------------------------------------------*/ 
function jsValidaCPF(CAMPO){
   var soma, i, resto;
   var cpf = CAMPO.value;

   cpf=cpf.replace(".", "");
   cpf=cpf.replace(".", "");
   cpf=cpf.replace("-", "");

   if (cpf == "") return false;
   if (cpf == "00000000000" || cpf == "11111111111" || 
      cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
      cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
      cpf == "88888888888" || cpf == "99999999999"){
      alert('N'+String.fromCharCode(250)+'mero de CPF Inv'+String.fromCharCode(225)+'lido\nPor favor, tente novamente');
      CAMPO.value = "";
      CAMPO.focus();
      return false;
   }  

   soma = 0;
   for (i=0; i < 9; i ++)
      soma += parseInt(cpf.charAt(i)) * (10 - i);
   resto = 11 - (soma % 11);
   if (resto == 10 || resto == 11)
      resto = 0;
   if (resto != parseInt(cpf.charAt(9))){  
      alert('N'+String.fromCharCode(250)+'mero de CPF Inv'+String.fromCharCode(225)+'lido\nPor favor, tente novamente');
      CAMPO.value = "";
      CAMPO.focus();
      return false;
   }
   soma = 0;
   for (i = 0; i < 10; i ++)
      soma += parseInt(cpf.charAt(i)) * (11 - i);
   resto = 11 - (soma % 11);
   if (resto == 10 || resto == 11)
      resto = 0;
   if (resto != parseInt(cpf.charAt(10))){  
      alert('N'+String.fromCharCode(250)+'mero de CPF Inv'+String.fromCharCode(225)+'lido\nPor favor, tente novamente');
      CAMPO.value = "";
      CAMPO.focus();
      return false;
   }
   return true;
}
function jsValidaCNPJ(CAMPO){
   // verifica o tamanho
   var pcnpj=CAMPO.value;

   //Retira a mascara
   pcnpj=pcnpj.replace(".", "");
   pcnpj=pcnpj.replace(".", "");
   pcnpj=pcnpj.replace("/", "");
   pcnpj=pcnpj.replace("-", "");

   if (pcnpj == "") return false;
   if (pcnpj == "00000000000000"){
      alert('N'+String.fromCharCode(250)+'mero de CNPJ Inv'+String.fromCharCode(225)+'lido\nPor favor, tente novamente');
      CAMPO.focus();
      return false;
   }

   if (pcnpj.length != 14){
      alert ('Tamanho Inv'+String.fromCharCode(225)+'lido de CNPJ\nPor favor, tente novamente');
      CAMPO.focus();
      return false;
   }else{
      sim=true;
   }
   if (sim){  // verifica se e numero
      for (i=0;((i<=(pcnpj.length-1))&& sim); i++){
         val = pcnpj.charAt(i);
         if ((val!="9")&&(val!="0")&&(val!="1")&&(val!="2")&&(val!="3")&&(val!="4") && (val!="5")&&(val!="6")&&(val!="7")&&(val!="8")){
            sim=false;
         }
      }
      if (sim){  // se for numero continua
         m2 = 2;
         soma1 = 0;
         soma2 = 0;
         for (i=11;i>=0;i--){
            val = eval(pcnpj.charAt(i));
            m1 = m2;
            if (m2<9) {m2 = m2+1;} else {m2 = 2;}
            soma1 = soma1 + (val * m1);
            soma2 = soma2 + (val * m2);
         }
         soma1 = soma1 % 11;
         if (soma1 < 2) {d1 = 0;} else {d1 = 11- soma1;}
         soma2 = (soma2 + (2 * d1)) % 11;
         if (soma2 < 2) {d2 = 0;} else {d2 = 11- soma2;}
         if ((d1==pcnpj.charAt(12)) && (d2==pcnpj.charAt(13))){
            return true;			
         }else{
            alert('N'+String.fromCharCode(250)+'mero de CNPJ Inv'+String.fromCharCode(225)+'lido\nPor favor, tente novamente');
            CAMPO.focus();
            return false;
         }
      }else{	
         alert('N'+String.fromCharCode(250)+'mero de CNPJ Inv'+String.fromCharCode(225)+'lido\nPor favor, tente novamente');
         return false;
      }	
   }
}

