<!--
// funções de Javascript




//AJAX_________________________________________

function cria_ajax()
	{
	var xmlhttp;
	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" || campo.type=="radio")
	      {
	 	  var obriga=campo.getAttribute('obrigatorio');
	 	  var nomecampoatual=campo.getAttribute('nomecampo');
		  
		  if(campo.type=="radio" && obriga==1)
		       {
			   var meuradio=document.getElementsByName(campo.getAttribute('name'));
			   var preencheu = false;
			   for (var k=0; k<meuradio.length; k++) 
			             {
						 //alert(k + "- teste: " + meuradio[k].value + " está " + meuradio[k].checked);
						 
						 if (meuradio[k].checked)
						           {
								   preencheu = true;
								   }
  						 }
			  if (preencheu==false)
			            {
						alert("Ao menos uma das opções do campo '" + nomecampoatual + "' deve ser selecionada.");
			   			return false;
						break;
						}
			   }
		  else if(obriga==1 && trim(campo.value)=="")
		       {
			   alert("O campo '" + nomecampoatual + "' não pode ficar vazio.");
			   campo.focus();
			   return false;
			   break;
			   }
		  }
	 }
return true;
}



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(el)
	{
	if (el.value.length < el.getAttribute('maxlength')) return;
	
	var f = el.form;
	var els = f.elements;
	var x, nextEl;
	for (var i=0, len=els.length; i<len; i++)
		{
		x = els[i];
		if (el == x && (nextEl = els[i+1]))
			{
			if (nextEl.focus) nextEl.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 amplia(url)
     {
	 var destino = "../../ferramentas/mostrafoto.php?url=" + url;

	 var altura=100;
	 var largura=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 toca_video(arquivo, arquivo_original)
	{
	var destino = "videoplayer.php?arquivo_video=" + arquivo + "&arquivo_original=" + arquivo_original;
	
	var largura=600;
	var altura=400;
	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-0-largura_div;
	 	  var coordenaday=imagemy+35;
		  

		  //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);
	 //alert('teste: ' + elemento.style.display);

	 if(elemento.style.display=='none')
	      {
	 	  elemento.style.display='block';
		  }
	 else
	      {
	 	  elemento.style.display='none';
		  }
     }
	 


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 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 switch_box(numero)
	{
	if(numero==1)
		{
		document.getElementById('box_funcionario').style.display='block';
		document.getElementById('box_cliente').style.display='none';
		}
	else
		{
		document.getElementById('box_funcionario').style.display='none';
		document.getElementById('box_cliente').style.display='block';
		}
	}


//______________________________________________


function lista_jobs(id_cliente, id_job_selecionado)
	{
	//alert(id_cidade + "-" + id_categoria_selecionada);
	toggle_job_selecionado(id_job_selecionado); // --> zera o input hidden para não permitir postar sem escolher um job (caso o combo não apareça porque o cliente não tem job ainda)
	
	var quadro=document.getElementById('campo_jobs');
	quadro.innerHTML="Pesquisando jobs...";
	quadro.style.display='block';
	
	var Ajax = cria_ajax(); // Inicia o Ajax. 
	Ajax.open("GET", "../ferramentas/ajax_lista_jobs.php?id_cliente=" + id_cliente + "&id_job_selecionado=" + id_job_selecionado, true); // fazendo a requisição 
	Ajax.onreadystatechange = function() 
		{ 
		if(Ajax.readyState == 4) 
			{ // Quando estiver tudo pronto. 
			if(Ajax.status == 200) 
				{
				var texto = Ajax.responseText; // Coloca o retornado pelo Ajax nessa variável 
				texto = texto.replace(/\+/g," "); // Resolve o problema dos acentos (saiba mais aqui: http://www.plugsites.net/leandro/?p=4) 
				texto = unescape(texto); // Resolve o problema dos acentos 
				//alert(texto);
				
				dados=eval(texto);
				
				var erro=dados[0];
				var mensagem=dados[1];
				
				if(erro==1)
					{
					quadro.innerHTML="erro! " + mensagem;
					}
				else
					{
					quadro.innerHTML=mensagem;
					}
				
				quadro.style.display='block';
				}
			}
		}
	Ajax.send(null); // submete 
	}


//______________________________________________



function init()
	{
		
	//___inicia o menu superior_________________________
	DynarchMenu.setup('menusup', {electric: true});
	//__________________________________________________
	
	
	
	//___cria o listener para o acordion do menu esquerdo_____
	vetor_caixas=$$('h3.boxmenu');
	for(i=0; i<vetor_caixas.length; i++)
		{
		Event.observe(vetor_caixas[i], 'click', toggle_box);
		}
	//_________________________________________________
	}



function toggle_box(e)
	{
	var item_clicado=Event.element(e);
	item_clicado.toggleClassName('on');
	var id_item=item_clicado.readAttribute('id_item');
	var box='box_' + id_item;
	//alert(box);
	//$(box).toggle();

	if(item_clicado.hasClassName('on'))
		{
		//alert('abre');
		Effect.SlideDown(box, {duration: 0.2});
		//$(box).show();
		}
	else
		{
		//alert('fecha');
		Effect.SlideUp(box, {duration: 0.5});
		//$(box).hide();
		}
	}



function box_peca()
	{
	var caixa=$('div_peca');
	caixa.toggleClassName('on');
	if(caixa.hasClassName('on'))
		{
		Effect.Appear(caixa, {duration: 0.5});
		//Effect.SlideDown(caixa, {duration: 0.2});
		}
	else
		{
		Effect.Fade(caixa, {duration: 0.5});
		//Effect.SlideUp(caixa, {duration: 0.5});
		}
	}


function toggle_job_selecionado(id_job)
	{
	alvo=document.getElementById('id_job_selecionado');
	//alert('selecionou: ' + id_job);
	alvo.value= id_job==0 ? "" : 1;
	}

-->
