<!--
// funções de Javascript




//AJAX_________________________________________

function cria_ajax()
     {
	 try
	          {
              xmlhttp = new XMLHttpRequest();
		      }
	catch(ee)
	          {
    	 	  try
		                {
         	  			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    		  			}
	         catch(e)
		               {
					   try
			      	             {
            	  				 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        		  				 }
			          catch(E)
			     	            {
            	 				xmlhttp = false;
        		 				}
                      }
              }
     return xmlhttp;
	 }




//_____________________________________________


//função para pré-carregar imagens no documento. Basta digitar a URL das imagens, separadas por vírgula
//Não importa o número de argumentos. Cada argumento é uma imagem.

function carregar()
{
var imagens=new array();

for (i=0; i<arguments.length; i++)
     {
     imagens[i]=new Image();
     imagens[i].src=arguments[i];
     }
}




function validaDOC(formularionome, selecionou_pj)
     {
	 if(document.forms[formularionome].cnpj.value=='')
	      {
		  return true
		  }
	 else if(selecionou_pj==true)
	      {
		  return validaCNPJ(formularionome);
		  }
	 else
	      {
		  return validaCPF(formularionome);
		  }
	 }




function validaCPF(formulario) {
                 var cpf = document.forms[formulario].cnpj.value;
                 erro = new String;
                 if (cpf.length < 11) erro = "CPF inválido!"; 
                 var nonNumbers = /\D/;
                 if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! "; 
                 if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
                         erro = "CPF inválido!"; 
               }
               var a = [];
               var b = new Number;
               var c = 11;
               for (i=0; i<11; i++){
                       a[i] = cpf.charAt(i);
                       if (i < 9) b += (a[i] * --c);
               }
               if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
               b = 0;
               c = 11;
               for (y=0; y<10; y++) b += (a[y] * c--); 
               if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
               if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
                       erro = "CPF inválido!"; 
               }
               if (erro.length > 0)
		       {
                       alert(erro);
                       document.forms[formulario].cnpj.focus();
                       return false;
               	       }
		else 
		       {
        	       return true;
		       }
	}



function validaCNPJ(formulario) 
		{
		CNPJ = document.forms[formulario].cnpj.value;
		erro = new String;
		if (CNPJ.length < 14) erro = "CNPJ inválido! O número deve conter 14 carateres. \n\nVerifique se há um zero à esquerda deste CNPJ.";

		if (erro.length == 0)
			{
			var a = [];
			var b = new Number;
			var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
			for (i=0; i<12; i++)
			     {
			     a[i] = CNPJ.charAt(i);
				 b += a[i] * c[i+1];
				 }
		    if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
			b = 0;
			for (y=0; y<13; y++) 
			    {
				b += (a[y] * c[y]); 
				}
		    if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
			if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13]))
			    {
				erro = "CNPJ inválido!";
				}
		    }

		if (erro.length > 0)
			{
			alert(erro);
            document.forms[formulario].cnpj.focus();
			return false;
			}
		else 
		    {
        	return true;
		    }
	}



function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function






function checar(formulario)
{
for(var i=0;i<formulario.elements.length;i++)
     {
	 var campo=formulario.elements[i];
	 
	 if(campo.type=="text" || campo.type=="hidden" || campo.type=="select" || campo.type=="select-one" || campo.type=="password" || campo.type=="file" || campo.type=="textarea")
	      {
	 	  var obriga=campo.getAttribute('obrigatorio');
	 	  var nomecampoatual=campo.getAttribute('nomecampo');
		  
		  if(obriga==1 && trim(campo.value)=="")
		       {
			   alert("O campo '" + nomecampoatual + "' não pode ficar vazio.");
			   campo.focus();
			   return false;
			   break;
			   }
		  }
	 }
}



function define_pessoa(formulario)
	      {
		  //se está selecionado o contato, o campo select é obrigatório, senão, o campo text outro é obrigatório
		  if(formulario.quem_radio[0].checked==true)
		       {
			   var selecionado=formulario.quem_radio[0].value;
			   formulario.id_contato.obrigatorio=1;
			   formulario.quem.obrigatorio=0;
			   }
		  else
		       {
			   var selecionado=formulario.quem_radio[1].value;
			   formulario.id_contato.obrigatorio=0;
			   formulario.quem.obrigatorio=1;
			   }
		  }


function define_pessoa_cp(formulario)
	      {
		  if(formulario.check_cp.checked==true)
		       {
		  	   //se está selecionado o contato, o campo select é obrigatório, senão, o campo text outro é obrigatório
		  	   if(formulario.quem_radio_cp[0].checked==true)
		                 {
			   			 var selecionado=formulario.quem_radio_cp[0].value;
			   			 formulario.id_contato_cp.obrigatorio=1;
			   			 formulario.quem_cp.obrigatorio=0;
			   			 }
		  	   else
		       	   		 {
			   			 var selecionado=formulario.quem_radio_cp[1].value;
			   			 formulario.id_contato_cp.obrigatorio=0;
			   			 formulario.quem_cp.obrigatorio=1;
			   			 }
			   }
		  else
		       {
			   return true;
			   }
		  }



function limita_texto(field, countfield, maxlimit) 
     {
	 if (field.value.length > maxlimit) // if too long...trim it!
	      {
		  field.value = field.value.substring(0, maxlimit);
		  }
     else 
	      {
		  countfield.innerHTML = maxlimit - field.value.length;
		  }
     }




function validarmaximo(valor, maximo)
     {
	 if(valor>maximo)
	      {
		  window.alert("O valor máximo para este campo é " + maximo);
		  return true;
		  }
	 else
	      {
		  return false;
		  }
	 }



function validarminimo(valor, minimo)
     {
	 if(trim(valor)!="" && valor<minimo)
	      {
		  window.alert("O valor mínimo para este campo é " + minimo);
		  return true;
		  }
	 else
	      {
		  return false;
		  }
	 }


function validarnumero()
{
var tecla=window.event.keyCode;
var valor=String.fromCharCode(tecla);

if( ( (parseInt(valor) !=valor) && tecla!=13 && tecla!=46  && tecla!=8 ) || (valor=="."))
	{
	event.returnValue=false;
	}
}



function validardecimal()
{
var tecla=window.event.keyCode;
var valor=String.fromCharCode(tecla);

if (parseInt(valor)!=valor && valor!="-" && valor!="." && event.keyCode!="13")
	{
	event.returnValue=false;
	}
}



function validardecimalbr()
{
var tecla=window.event.keyCode;
var valor=String.fromCharCode(tecla);

if (parseInt(valor)!=valor && valor!="-" && valor!="," && event.keyCode!="13")
	{
	event.returnValue=false;
	}
}



function conferedecimalbr(pStr)
	      {
		  var reDecimal = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;
		  charDec = ",";
		  if (reDecimal.test(pStr))
		            {
					pos = pStr.indexOf(charDec);
					decs = pos == -1? 0: pStr.length - pos - 1;
					//alert(pStr + " é um float válido com " + decs + " decimais.");
					return true;
					}
		  else if (pStr != null && pStr != "")
		            {
					//alert(pStr + " NÃO é um float válido.");
					return false;
					}
          }



function convertedecimal_br_en(pStr)
	      {
		  var reDecimal = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;
		  charDec = ",";
		  if (reDecimal.test(pStr))
		            {
					pos = pStr.indexOf(charDec);
					decs = pos == -1? 0: pStr.length - pos - 1;
					//alert(pStr + " é um float válido com " + decs + " decimais.");
					return pStr.replace(",", ".");
					}
		  else if (pStr != null && pStr != "")
		            {
					//alert(pStr + " NÃO é um float válido.");
					return false;
					}
          }


function pular()
{

if(window.event.srcElement.type=='text')
	{
	var ele=window.event.srcElement;
	var index=ele.sourceIndex;
	if(ele.value.length==ele.getAttribute('maxlength'))
		{
		document.all.item(index+1).focus();
		}
	
	}
}







function nao_navega()
	{
	if(window.event.srcElement.tagName=="A" || window.event.srcElement.tagName=="IMG")
		{
		alert('Ops! \n\nEsta página é só para impressão. Não é possível navegar a partir dela.')
		}
	}





function exibe_foto(foto_url, largura, altura) 
{ 

var destino = '../ferramentas/mostrafoto.php?foto_url=' + foto_url + '&largura=' + largura + '&altura=' + altura;

var esquerda=(screen.availWidth-largura)/2;
var topo=(screen.availHeight-altura)/2;

window.open(destino, '','toolbar=no, scrollbars=no, left=' + esquerda + ', top=' + topo + ', width=' + largura + ', height= ' + altura + ''); 
} 



function amplia_galeria(galeria_id, foto_id_escolhida) 
{ 

var destino = '../galeria_janela.php?galeria_id=' + galeria_id + '&foto_id_escolhida=' + foto_id_escolhida;

var altura=100;
var largura=100;
var esquerda=(screen.availWidth-largura)/2;
var topo=(screen.availHeight-altura)/2;;

window.open(destino, '','toolbar=no, scrollbars=yes, left=' + esquerda + ', top=' + topo + ', width=' + largura + ', height= ' + altura + ''); 
} 


function imprime_nota(id_nota) 
{ 

var destino = '../faturamento/imprime_frames.php?id_nota=' + id_nota;

var largura=800;
var altura=600;

var esquerda=(screen.availWidth-largura)/2;
var topo=(screen.availHeight-altura)/2;;

window.open(destino, '','toolbar=no, scrollbars=yes, left=' + esquerda + ', top=' + topo + ', width=' + largura + ', height= ' + altura + ''); 
} 


function janela_envio(arquivo, usuario_id_selecionado, treino_id_selecionado) 
{ 

var destino = '../ferramentas/envia_frames.php?arquivo=' + arquivo + '&usuario_id_selecionado=' + usuario_id_selecionado + '&treino_id_selecionado=' + treino_id_selecionado;

var largura=580;
var altura=400;

var esquerda=(screen.availWidth-largura)/2;
var topo=(screen.availHeight-altura)/2;;

window.open(destino, '','toolbar=no, scrollbars=yes, left=' + esquerda + ', top=' + topo + ', width=' + largura + ', height= ' + altura + ''); 
} 


function imagem(url) 
{ 

var destino = '../ferramentas/imagem.php?url=' + url;

var largura=100;
var altura=100;
var esquerda=(screen.availWidth-largura)/2;
var topo=(screen.availHeight-altura)/2;

window.open(destino, '','toolbar=no, scrollbars=no, left=' + esquerda + ', top=' + topo + ', width=' + largura + ', height= ' + altura + ''); 
} 



function janela_entrada() 
{ 
var destino="entrada.php";

var largura=200;

var altura=200;

var esquerda=((screen.availWidth-largura)/2);

var topo=(screen.availHeight-altura)/2;

window.open(destino, '','toolbar=no, scrollbars=no, left=' + esquerda + ', top=' + topo + ', width=' + largura + ', height= ' + altura + ''); 
} 


function confirma(destino, mensagem)
{

var quero;

quero=window.confirm(mensagem);

if(quero)
     {
	 window.location.href=destino;
	 }
}


function formata_num(num)
     {
	 num = num.toString().replace(/\$|\,/g,'');
	 if(isNaN(num))
	 num = "0";
	 sign = (num == (num = Math.abs(num)));
	 num = Math.floor(num*100+0.50000000001);
	 cents = num%100;
	 num = Math.floor(num/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));
		  }
		  
	 return (((sign)?'':'-') + num + ',' + cents);
	 }





//_______FOLHINHA_________________

function fecha_folhinha()
     {
	 var removame=document.getElementById("divfolhinha");
	 if(removame!=null)
	      {
	 	  removame.parentNode.removeChild(removame);
		  }
	 }






function abre_folhinha(nome_formulario, campo_dia, campo_mes, campo_ano)
     {
	 var id_clicado=window.event.srcElement.id;
	 
	 var nome_campo_dia=nome_formulario + "." + campo_dia.name;
	 var nome_campo_mes=nome_formulario + "." + campo_mes.name;
	 var nome_campo_ano=nome_formulario + "." + campo_ano.name;

	 
	 var dia_sel=campo_dia.value;
	 var mes_sel=campo_mes.options[campo_mes.selectedIndex].value;
	 var ano_sel=campo_ano.value;
	 //alert("teste2: " + dia_sel + "/" + mes_sel + "/" + ano_sel);
	 
	 
	 //removendo outra instância do objeto que exista
	 if (document.getElementById("divfolhinha")!=null)
	      {
		  if(id_clicado==divfolhinha.origem)
		       {
			   //alert("já existe e é o mesmo: " + id_clicado + " e " + divfolhinha.origem);
			   var pode_criar=false;
			   }
		  else
		       {
			   //alert("já existe mas não é o mesmo: " + id_clicado + " e " + divfolhinha.origem);
			   var pode_criar=true;
			   }
          fecha_folhinha();
		  }
     else
	      {
		  var pode_criar=true;
		  }



     if(pode_criar)
	      {
	 	  var novodiv=document.createElement("div");
	 	  novodiv.id="divfolhinha";
	 	  document.body.appendChild(novodiv);
	 


		// Get the scroll offset of the window.
		var yScroll;
		if (self.pageYOffset) // all except Explorer
		{
			yScroll = self.pageYOffset;
		}
		else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
		{
			yScroll = document.documentElement.scrollTop;
		}
		else if (document.body) // all other Explorers
		{
			yScroll = document.body.scrollTop;
		}


		  var imagemid=window.event.srcElement.id;
		  var imagemclicada=document.getElementById(imagemid);
		  var imagemy=findPosY(imagemclicada);
		  var imagemx=findPosX(imagemclicada);
		  //alert("imagem clicada: " + imagemid);

	 	  var largura_div=150;
	 	  var altura_div=135;
	 
	 	  var pontox=window.event.clientX;
	 	  var pontoy=window.event.clientY;
	 	  var coordenadax=imagemx-5-largura_div;
	 	  var coordenaday=imagemy+20;
		  

		  //alert("ponto: " + pontoy + ", coordy: " + coordenaday);
		  //alert("ponto: " + pontox + ", coordx: " + coordenadax);
	 
	 	  divfolhinha.style.position="absolute";
	 	  divfolhinha.style.display="block";
	 	  divfolhinha.style.left=coordenadax + "px";
	 	  divfolhinha.style.top=coordenaday + "px";
	 	  divfolhinha.style.width=largura_div + "px";
	 	  divfolhinha.style.height=altura_div + "px";
	 	  divfolhinha.style.border="1px solid #666";
	 	  divfolhinha.style.background="#eee";
	 	  divfolhinha.origem=id_clicado;
	 	  divfolhinha.innerHTML='<iframe src="../ferramentas/folhinha.php?dia=' + dia_sel + '&mes=' + mes_sel + '&ano=' + ano_sel + '&nome_campo_dia=' + nome_campo_dia + '&nome_campo_mes=' + nome_campo_mes + '&nome_campo_ano=' + nome_campo_ano + '" frameborder="0" scrolling="no" width="150" height="135"></iframe>';
		  }
	 
	 
	 
	 //alert("selecionado atualmente: " + forms[0].dia.value + "/" forms[0].mes.value + "/" + forms[0].ano.value);
	 } 





function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}







function simulashiftab()
     {
	 var tecla=window.event.keyCode;
	 
	 if(tecla==40)
	      {
		  simulatab();
		  }

	 if(tecla==38)
	      {
		  var ele=window.event.srcElement;
		  var indice=ele.sourceIndex;
		  var anterior=indice-2;
		  document.all.item(anterior).focus();
		  }
	 }

function simulatab()
     {
	 if(window.event.keyCode==40)
	      {
	 	  event.keyCode = 9;
		  }
	 return false;
	 }

	 




function hide_and_seek(id_item)
     {
	 var elemento=document.getElementById(id_item);

	 if(elemento.style.display=='block')
	      {
	 	  elemento.style.display='none';
		  }
	 else
	      {
	 	  elemento.style.display='block';
		  }
     }
	 


function checkAll(theForm, cName) {
for (i=0,n=theForm.elements.length;i<n;i++)
if (theForm.elements[i].className.indexOf(cName) !=-1)
if (theForm.elements[i].checked == true) {
theForm.elements[i].checked = false;
} else {
theForm.elements[i].checked = true;
}
}


function exporta_contato(id_contato)
     {

	 var idimagem="btexp" + id_contato;
	 var imagemclicada=document.getElementById(idimagem);
	 //alert("você clicou no ID: " + id_contato); 
	 
	 var string_imagem=imagemclicada.src;
	 var tamanho=string_imagem.length;
	 var string_status=string_imagem.substr(tamanho-6, 2);
	 
	 if(string_status=="on")
	      {
		  imagemclicada.src="../imagens/botao_exportar_off.gif";
		  imagemclicada.style.cursor="default";
		  
	 	  var xmlhttp=cria_ajax();
	 	  xmlhttp.open("GET", "../ferramentas/exporta_contato.php?id_contato=" + id_contato, true);
	 	  xmlhttp.send(null);
	 	  delete xmlhttp;
		  }

	 }



function baixar_estoque(id_nota)
     {
	 var mensagem_confirma="Você tem certeza de que quer movimentar o estoque com os produtos da nota nº " + id_nota + "?";
	 
	 if(window.confirm(mensagem_confirma))
	           {
	 		   var idimagem="btmov" + id_nota;
	 		   var imagemclicada=document.getElementById(idimagem);
	 		   //alert("você clicou no ID: " + id_contato); 
	 
	 		   var string_imagem=imagemclicada.src;
	 		   var tamanho=string_imagem.length;
	 		   var string_status=string_imagem.substr(tamanho-6, 2);
	 
	 		   if(string_status=="on")
	      	             {
		  				 imagemclicada.src="../imagens/botao_baixar_estoque_off.gif";
		  				 imagemclicada.style.cursor="default";
		  
	 	  				 var xmlhttp=cria_ajax();
	 	  				 xmlhttp.open("GET", "../ferramentas/baixar_estoque.php?id_nota=" + id_nota, true);
	 	  				 xmlhttp.send(null);
	 	  				 delete xmlhttp;
		  				 }
               }
	 }



function find_contact(id_campo, id_div_alvo, id_mensagem)
     {
	 if(window.event.keyCode==9)
	      {
		  return false;
		  }
	 
	 unselect_contact(id_campo);
	 
	 var campo=document.getElementById(id_campo);
	 var div_alvo=document.getElementById(id_div_alvo);
	 var span_mensagem=document.getElementById(id_mensagem);
	 
	 span_mensagem.innerHTML="procurando contato...";
	 
	 var iniciais=campo.value;

	 var xmlhttp=cria_ajax();
	 xmlhttp.open("GET", "../ferramentas/ajax_procura_contato.php?iniciais=" + iniciais + "&id_div_alvo=" + id_div_alvo + "&id_campo=" + id_campo + "&id_mensagem=" + id_mensagem, true);
	 xmlhttp.onreadystatechange=function()
	  									   			       {
														   if(xmlhttp.readyState==4)
														             {
																	 span_mensagem.innerHTML="pronto";
																	 
																	 var texto=xmlhttp.responseText;
																	 texto=texto.replace(/\+/g," ");
																	 texto=unescape(texto);
																	 
																	 if(texto!="")
																	           {
																			   div_alvo.innerHTML=texto;
																			   div_alvo.style.display="block";
																			   span_mensagem.innerHTML="clique no contato para selecioná-lo";
																		  	   }
																	 else
																	           {
																			   div_alvo.style.display="none";
																			   span_mensagem.innerHTML="";
																		  	   }
																	 }
														   }
	 xmlhttp.send(null);
	 delete xmlhttp;
	 }


function select_contact(id_contato, nome_fantasia, id_campo)
     {
	 //alert("o contato com ID: " + id_contato + " foi selecionado");
	 
	 var campo=document.getElementById(id_campo);
	 var id_campo_auxiliar=id_campo + "_id";
	 var campo_auxiliar=document.getElementById(id_campo_auxiliar);
	 
	 campo.value=nome_fantasia;
	 campo_auxiliar.value=id_contato;
	 }

function unselect_contact(id_campo)
     {
	 //alert("des selecionou");
	 var campo=document.getElementById(id_campo);
	 var id_campo_auxiliar=id_campo + "_id";
	 var campo_auxiliar=document.getElementById(id_campo_auxiliar);
	 
	 campo_auxiliar.value="";
	 }



function troca_antispam()
	{
	var numero=Math.random();
	document.getElementById('antispam').src='ferramentas/antispam.php?id=' + numero;
	}

-->
