function shift_tab(evt, id_atual, id_anterior, id_blur)
{
	 var oEvent = (window.event) ? window.event : evt;

        //hmmm in mozilla this is jacked, so i have to record these seperate
        //what key was pressed
        var nKeyCode =  oEvent.keyCode ? oEvent.keyCode : oEvent.which ? oEvent.which : void 0;
		
		var bShiftPressed = (oEvent.shiftKey) ? oEvent.shiftKey : oEvent.modifiers & 4 > 0;
		
		if(bShiftPressed && nKeyCode == 9)
		{ // Shift + Tab
            document.getElementById(id_atual).onblur='';
			if (document.getElementById(id_anterior).type == "text")
			{
				setTimeout("document.getElementById('"+id_anterior+"').select();",400);
			}
			else
			{
				setTimeout("document.getElementById('"+id_anterior+"').focus();",400);
			}
			setTimeout("document.getElementById('"+id_atual+"').onblur=document.getElementById('"+id_blur+"').onblur;",200);
        }
		return true;
}

function Habilitar_Blur(taxa_antiga, taxa_atual, evento)
{
	var tecla;

	if(window.event) { // Internet Explorer
	  tecla = event.keyCode;
	}
	else { // Firefox
	  tecla = evento.which;
	}
	
	if (tecla == 9 && taxa_antiga == taxa_atual) 
	{
		//document.getElementById('valor').onchange="";
		//atribuir_blur_valor();
		return false;
	}
	else
		return true;
}



function BloqueiaTab(evento)
{
	var tecla;

	if(window.event) { // Internet Explorer
	  tecla = event.keyCode;
	}
	else { // Firefox
	  tecla = evento.which;
	}
	
	if (tecla == 9) 
	{
		//event.keyCode = 0;
		setTimeout("document.getElementById('forma_pagamento1').focus();",1000);
		return false;
	}

    if(tecla >= 48 && tecla <= 57 || tecla == 44 || tecla == 46 || tecla == 8 || tecla >= 96 && tecla <= 105 || tecla == 110 || tecla == 188 || tecla == 190 || tecla == 194 || tecla == 13 || tecla == 9 || tecla >= 37 && tecla <= 40) 
		return true;
	else
		return false;
}

function textCounter(field,countfield,maxlimit)
{
	if (field.value.length > maxlimit)
		field.value = field.value.substring(0, maxlimit);
	else 
		countfield.value = field.value.length +" de " + maxlimit;
	return true;
}



function BloqueiaLetrasEdit(evento)
{
	var tecla;

	if(window.event) { // Internet Explorer
	  tecla = event.keyCode;
	}
	else { // Firefox
	  tecla = evento.which;
	}

    if(tecla >= 48 && tecla <= 57 || tecla == 44 || tecla == 46 || tecla == 8 ||tecla == 0 || tecla >= 37 && tecla <= 40) return true;
   return false;
}

function BloqueiaLetras(evento)
{
	var tecla;

	if(window.event) { // Internet Explorer
	  tecla = event.keyCode;
	}
	else { // Firefox
	  tecla = evento.which;
	}

    if(tecla >= 48 && tecla <= 57 || tecla == 8 || tecla == 0 || tecla == 9 || tecla >= 37 && tecla <= 40) return true;
	return false;
}


function BloqueiaLetrasGrid(evento)
{
	var tecla;

	if(window.event) { // Internet Explorer
	  tecla = event.keyCode;
	}
	else { // Firefox
	  tecla = evento.which;
	}

    if(tecla >= 48 && tecla <= 57 || tecla == 44 || tecla == 46 || tecla == 8 || tecla >= 96 && tecla <= 105 || tecla == 110 || tecla == 188 || tecla == 190 || tecla == 194 || tecla == 13 || tecla == 9 || tecla >= 37 && tecla <= 40) 
		return true;
	else
		return false;
}



function formatar(src, mask) 
{


  var i = src.value.length;
  var saida = mask.substring(0,1);
  var texto = mask.substring(i)
	if (texto.substring(0,1) != saida) 
  	{
		src.value += texto.substring(0,1);
  	}
  	/*
  	
   	var cod_tecla=47; //tecla que quer bloquear. 116 é o código da tecla F5

	if(!document.all)
	{	
	  	if (e.keyCode == cod_tecla)  		
		return false;
	}else
	{
		
	   
	
	    //filtrando o evento
	    var oEvent = oEvent ? oEvent : window.event;
	    var tecla = (oEvent.keyCode) ? oEvent.keyCode : oEvent.which;
	    
	    if(oEvent.type=="keydown" && navigator.appName.indexOf('Internet Explorer')<0 ){
	        //se for keydown e não for o IE, vazarei pois o keypress já foi executado
	        return false;
	    }
	    
	    if (typeof(oEvent.keyCode)=='number' && oEvent.keyCode == cod_tecla){
	        if (typeof(oEvent.preventDefault)=='function'){
	            oEvent.preventDefault();
	        } else {
	            oEvent.returnValue = false;
	            oEvent.keyCode = 0;
	        }
	    }
	    return false;
	}		
  	
  	
  	
  	*/

}

function validar_data(data)
{
	var aux_data = data;
	/*
	hoje = new Date();
	diaAtual = new Date().getDate(),
	mesAtual = new Date().getMonth(), // 0-11
	anoAtual = new Date().getFullYear(), // 4-digit year
	mesAtual = mesAtual +1;
    barras = aux_data.split("/");
    aux_data = aux_data.replace(/['/']/g,"");
	var tamanho = aux_data.length;
	
	today = anoAtual+''+mesAtual+''+diaAtual;

	if (tamanho == 8)
	{
        dia = barras[0];
        mes = barras[1];
        ano = barras[2];
		datum1 = ano+''+mes+''+dia;
		
		for (i = 0; i < tamanho; i++)
		{
			if(!isNaN(aux_data))
		    {
				if (datum1 > today)
				{
					erro = "alert('ERRO! A DATA DE NASCIMENTO NÃO PODE SER MAIOR QUE A DATA DE HOJE');";
				}
				else
				{
				
			        dat  = (datum1 < today)? datum1 : today;
			        datv = (datum1 < today)? today : datum1;
			        i    = 0;
			        while( dat < datv)
			        {
			            i++;
			            switch(dat.substr(6,2))
			            {
			                case '28': dat += (dat.substr(4,2) == 02 && dat.substr(0,4)%4 > 0 )? 73 : 1;
			                    break;
			                case '29': dat += (dat.substr(4,2) == 02 && dat.substr(0,4)%4 == 0 )? 72 : 1;
			                    break;
			                case '30': dat += (in_array( dat.substr(4,2), array(04,06,09,11)))? 71 : 1;
			                    break;
			                case '31': dat += (dat.substr(4,2) == 12 )? 8870 : 70;
			                    break;
			                default:   dat++;
			                    break;
			            }
			        }
					
				}
			}
		}

		if (texto.substring(0,1) != saida) 
		{
			src.value += texto.substring(0,1);
		}
	
	}
	*/
	return true;
}


function FormatTC(valor)
{
  
  var total = valor.length;
  var resultado;	  
  var inicio;
  var fim;

  resultado ='';
  
  if(total >2 && total<7)		  
  {
  	qtd = 1;  
  }else
  {	
  	if(total>6 && total <10)
	{  	 
	    qtd = 2;
	}
	else
	{qtd=3;}
  } 
  
  inicio = total - 3;    

  for(i=0;i<qtd;i++)	 
  {

    
	if(total>3)    
	{
		fim = inicio + 3;		
		resultado =  '.'+ valor.substring(inicio,fim)+resultado ; 
		inicio = inicio - 3;
		
	}
	else
	{
	  
	  resultado  = valor;
	 
	  return resultado;
	}
  }

  resultado = valor.substring(0,inicio+3)+resultado;
 
  return resultado;

}

function ValidaDataGrid(object,rowId,cellInd)
{
		var data  =  object.cells(rowId,cellInd).getValue();
		var separa_campos = data.split("/");
		var dia = separa_campos[0];
		var mes = separa_campos[1];
		var ano = separa_campos[2];
		
		if(data.length >0 && data.length <8)
		{	
		  	object.cells(rowId,cellInd).setValue("");		  	
			alert('Data inválida!!!');			
			return false;
		}
	
		if (dia > 31)
		{
		  	object.cells(rowId,cellInd).setValue("");		  	
			alert('Data inválida!!!');			
			return false;
		}
		if (dia > 30 && (mes == 4 || mes == 6 || mes == 9 || mes == 11))
		{	object.cells(rowId,cellInd).setValue("");
			alert('Data inválida!!!');
			
			return false;
		}
		if (mes == 2)
		{
			if (ano%4 == 0 && dia > 29)
			{	
			  	object.cells(rowId,cellInd).setValue("");
				alert('Data inválida!!!');				
				return false;
			}
			if (ano%4 != 0 && dia > 28)
			{	
			  	object.cells(rowId,cellInd).setValue("");
				alert('Data inválida!!!');				
				return false;
			}
		}
		if (mes > 12)
		{	object.cells(rowId,cellInd).setValue("");
			alert('Data inválida!!!');	
			return false;
		}
		if (!document.all && document.getElementById)//firefox
		{		
			if (ano < 1000) //NAO Funciona no DhtmlxCalendar...
			{	
				if (ano <= 30)
				{
					var aux_ano = dia+'/'+mes+'/20'+ano;
					object.cells(rowId,cellInd).setValue(aux_ano);
	
		
				}
				if (ano > 30)
				{
					var aux_ano = dia+'/'+mes+'/19'+ano;
					object.cells(rowId,cellInd).setValue(aux_ano);
				}
				return true;
			}
		}
}

function FormatDateGrid(object,mask,key_code)
{
	//exemplo
	//var mask  ='##/##/####'

	if(key_code ==8 || key_code ==46)
	{
	  return true;
	}
	
	if(document.all)//browser IE
	{	
		//trava Tecla para IE
		if(key_code==111)
		{
			//deixo passar pois preciso fazer verificação depois com o tamanho do campo
		}
		else if (key_code != 9)
		{
			if(key_code <=47  || key_code >=58)
			{
				if(key_code <= 95 || key_code >= 106)
					return false;						
			}
		}
	}

	var tecla;	
	var elemento; 
	var barra = "";
  	var rowId 	= object.getSelectedRowId();
  	var cellInd = object.getSelectedCellIndex();
	var string = object.cells2(rowId,cellInd).getValue();
	var aux_string;
	var data ="";
	var aux;	
	var count = string.length;
	
	if (!document.all && document.getElementById)//firefox
	{
		var dhx_combo_edit = document.getElementsByClassName("dhx_combo_edit");

		//busca todos os inputs com a classe de dhx_combo_edit		
		for (i=0;dhx_combo_edit && i < dhx_combo_edit.length; i++)
		{	
		  	//verifica qual objeto esta com foco	  
		 	if(dhx_combo_edit[i].focus)
		 	{
				data = dhx_combo_edit[i].value;	 
				dhx_combo_edit[i].style.maxlength=10;

			}
		}	
			
		if(key_code==111)
		{
			//deixo passar pois preciso fazer verificação depois com o tamanho do campo
		}
		else if (key_code != 9)
		{
			if(key_code <=47  || key_code >=58)
			{
				if(key_code <= 95 || key_code >= 106)
				{	
				  	
					object.cells(rowId,cellInd).setValue('');				
					object.editor.edit();				
					return false;						
				}
			}
		}
	}else if(document.all)//I.E.
	{
		//pega o  valor do campo e decodifica somente o valor da data entre as Tag de TEXTAREA
		for(var i=0;i<count;i++)
		{
		  	aux_string = string.substring(i,i+1);
			if(aux_string ==">")
			{			  	
				for(var j=i+1;j<count;j++)  	
				{			  
				  	aux = string.substring(j,j+1);
				  	if (aux=="<")
				  	{
				  		break;  
				  	}
				  	else
				  	{						    
					 	data +=aux;   
					}			  
				}
			  	break;
			}	  					 	 			  	
		}	  
	}

	if(data=="")
		return true;

	if(key_code==111)
	{	
	  	if (data.length==2 ||data.length==5)
	  	{
		    //posição 2 ou 5 quando for apertado a barra "/", deixar incluir,caso contrario nao inclui
		    if (!document.all && document.getElementById)//firefox
		    	return true;
		}
	  	else
	  	{	
		    if (!document.all && document.getElementById)//firefox
		    {	    		  
			  object.cells(rowId,cellInd).setValue("");				
			  object.editor.edit();
			}					
		    return false;
		}
	  
	}
			
  	var saida = mask.substring(0,1);
	var texto = mask.substring(data.length)

	//coloca a barra de formatação
	if (texto.substring(0,1) != saida) 
	{	
		barra += texto.substring(0,1);
		//seta o valor digitado mais a barra de formatação		
		object.cells(rowId,cellInd).setValue(data+barra);
		
		//abre a edição do objeto
		object.editor.edit();
		if (document.all)//somente para InternetExplorer
		{
			//busca o objeto  textarea
			var x=document.getElementsByTagName("TEXTAREA");
			for (i=0;x && i < x.length; i++)
			{	//seleciona o objeto do textarea no qual esta com foco					  
				if(x[i].onfocus)
				{
					if(x[i].createTextRange)
					{	
					  	//move o cursor para o final do objeto  para IE
						var range = x[i+1].createTextRange();
						
						range.move("character",x[i+1].value.length);
						range.select();						
					}  				  			  
				}  		  
			}
		}
	}	
	return true;
}

function FormatFloat(moeda){

   moeda = moeda.replace(/[.]/g,"");

   moeda = moeda.replace(",",".");

   return  float2moeda(parseFloat(moeda));

}

function float2moeda(num)
{
   x = 0;

   if(num<0) {
      num = Math.abs(num);
      x = 1;
   }   if(isNaN(num)) num = "0";
      cents = Math.floor((num*100+0.5)%100);


   num = Math.floor((num*100+0.5)/100).toString();
   if(cents < 10) cents = "0" + cents;
      for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
         num = num.substring(0,num.length-(4*i+3))+'.'
               +num.substring(num.length-(4*i+3));   ret = num + ',' + cents;   if (x == 1) ret = ' - ' + ret;
			return ret;
}

function popup(url,nome_janela,largura,altura){
     
     var vertical = (screen.height-altura)/2;
     var horizontal = (screen.width-largura)/2;
     
     if (!document.all && document.getElementById) // Firefox
        janela=window.open(url,nome_janela,"menubar=no,scrollbars=yes,status=no,toolbar=no,width="+largura+",height="+altura+",screenX="+horizontal+",screenY="+vertical);
     
     if (document.all) // IE
        janela=window.open(url,nome_janela,"menubar=no,scrollbars=yes,status=no,toolbar=no,width="+largura+",height="+altura+",left="+horizontal+",top="+vertical);
     
     text = "Se a janela nao estava abrindo talvez seja porque voce tenha um programa bloqueador de pop-up! Observacao ï¿½ O windows XP service pack 2 bloqueia pop-ups!";
     if(janela == null) { alert(text); return; }
     
     if (window.focus) {janela.focus()}
}

function grid_parameters(param_array,param_num){
     /*
     PARÂMETROS: param_array=array com as colunas
                 param_num=número da coluna que deseja retornar.
     
     EXEMPLO DE USO:     
     var arr_mygrid = new Array(
               new Array("CÓDIGO",60,"right","ro","int",""),
               new Array("EVENTO",240,"left","ro","str",""),
               new Array("HISTÓRICO",250,"left","ed","str","#E5F2F8")
          );
	 
	 mygrid = new dhtmlXGridObject('gridbox');
     mygrid.setImagePath("../../lib/dhtmlxGrid/imgs/");
     mygrid.setHeader(grid_parameters(arr_mygrid,0));
     mygrid.setInitWidths(grid_parameters(arr_mygrid,1));
     mygrid.setColAlign(grid_parameters(arr_mygrid,2));
     mygrid.setColTypes(grid_parameters(arr_mygrid,3));
     mygrid.setColSorting(grid_parameters(arr_mygrid,4));
     mygrid.setColumnColor(grid_parameters(arr_mygrid,5));
     mygrid.setSkin("clear");
     mygrid.init();
     */
     
     var str = "";
     for(x=0; x<=param_array.length-1;x++){
          str = str + param_array[x][param_num] + ",";
     }
     return str.substring(0,str.length-1)
}

// PEGA O EVENTO DA TECLA PRESSIONADA
function getKeyCode(event) {
   event = event || window.event;
   return event.keyCode;
}

// FUNÇÃO QUE QUANDO O OPERADOR TECLAR ENTER DISPARA O EXIBIR_DADOS
function displayKeyCode(evento)
{
	var tecla;
	if(window.event) { // Internet Explorer
	  tecla = event.keyCode;
	}
	else { // Firefox
	  tecla = evento.which;
	}
	if (tecla == 13)
	{
		xajax_Verifica_Usuario(document.getElementById('login').value,document.getElementById('senha').value); //  ENTER
		return true;
	}
}

function displayKeyCode_367_2(evento)
{
	var tecla;
	if(window.event) { // Internet Explorer
	  tecla = event.keyCode;
	}
	else { // Firefox
	  tecla = evento.which;
	}
	if (tecla == 13)
	{
		exibir_pesquisa(document.getElementById('pesq').value);
		return true;
	}
}
