// JavaScript Document

var janela;
function popup(theURL,winName,params)
{
	if(janela != null)
		{
			janela.close();
		}
	janela = window.open(theURL,winName,params);
	janela.focus();
}

// final abre janela-->



 function RemoverMascara(Objeto)
 	{
		var campo_limpar = Objeto.value;
		return  campo_limpar.replace(/[\/.-]/g, '');
	}
 	
	
 function soNums(e,args) 
    {         
    // Função que permite apenas teclas numéricas e  
    // todos os caracteres que estiverem na lista 
    // de argumentos. 
    // Deve ser chamada no evento onKeyPress desta forma 
    //  onKeyPress ="return (soNums(event,'(/){,}.'));" 
    // caso queira apenas permitir caracters 

        if (document.all){var evt=event.keyCode;} // caso seja IE 
        else{var evt = e.charCode;}    // do contrário deve ser Mozilla 
        var chr= String.fromCharCode(evt);    // pegando a tecla digitada 
        // Se o código for menor que 20 é porque deve ser caracteres de controle 
        // ex.: <ENTER>, <TAB>, <BACKSPACE> portanto devemos permitir 
        // as teclas numéricas vão de 48 a 57 
        if (evt <20 || (evt >47 && evt<58) || (args.indexOf(chr)>-1 ) ){return true;} 
        return false; 
    } 	
	
	
function mascara_cnpj(Objeto)
	{	
		if (Objeto.value.length == 2)	{ Objeto.value = Objeto.value + '.'; }
		if (Objeto.value.length == 6) 	{ Objeto.value = Objeto.value + '.'; }
		if (Objeto.value.length == 10) 	{ Objeto.value = Objeto.value + '/'; }
		if (Objeto.value.length == 15) 	{ Objeto.value = Objeto.value + '-'; }
	}
		
function valida_cnpj(Objeto)
	{
		if(Objeto.value.length > 1)
			{
				pri = Objeto.value.substring(0,2);
				seg = Objeto.value.substring(3,6);
				ter = Objeto.value.substring(7,10);
				qua = Objeto.value.substring(11,15);
				qui = Objeto.value.substring(16,18);
				var i;
				var numero;
				var resultado = 'verdadeiro';
				numero = (pri+seg+ter+qua+qui);
				s = numero;
				c = s.substr(0,12);
				var dv = s.substr(12,2);
				var d1 = 0;
				for (i = 0; i < 12; i++) {	d1 += c.charAt(11-i)*(2+(i % 8)); }
				if (d1 == 0) {	resultado = 'falso'; }
				d1 = 11 - (d1 % 11);
				if (d1 > 9) d1 = 0;
				if (dv.charAt(0) != d1){	resultado = 'falso';	}
				d1 *= 2;
				for (i = 0; i < 12; i++){	d1 += c.charAt(11-i)*(2+((i+1) % 8));	}
				d1 = 11 - (d1 % 11);
				if (d1 > 9) d1 = 0;
				if (dv.charAt(1) != d1){	resultado = 'falso';	}
				
				if(resultado !="verdadeiro")
					{
						alert("CNPJ invalido!");						
						Objeto.value = '';
						Objeto.focus();
						return false;
					}
		
						
			}
	}
	
function mascara_cpf(Objeto)
	{
		if (Objeto.value.length == 3)	{ Objeto.value = Objeto.value + '.';}
		if (Objeto.value.length == 7)	{ Objeto.value = Objeto.value + '.';}
		if (Objeto.value.length == 11)	{ Objeto.value = Objeto.value + '-';}
	}
	

function valida_cpf(Objeto)
	{
		var i; 
		var valordocpf = Objeto.value;
		var resultado = "verdadeiro";

		valordocpf = valordocpf.replace(".","");
		valordocpf = valordocpf.replace("-","");
		valordocpf = valordocpf.replace(".","");		

		var c = valordocpf.substr(0,9); 
		var dv = valordocpf.substr(9,2); 
		var d1 = 0; 
		for (i = 0; i < 9; i++) {  d1 += c.charAt(i)*(10-i);  } 
		if (d1 == 0) { resultado = "falso"; } 		
		d1 = 11 - (d1 % 11); 
		if (d1 > 9) d1 = 0;
		if (dv.charAt(0) != d1){ resultado = "falso"; } 			
		d1 *= 2;
		for (i = 0; i < 9; i++)	{	d1 += c.charAt(i)*(11-i);	} 		
		d1 = 11 - (d1 % 11); 
		if (d1 > 9) d1 = 0;
		if (dv.charAt(1) != d1){ resultado = "falso"; } 
		if(resultado != "verdadeiro")
			{
				alert("CPF Invalido. Digite  um CPF Valido !") ;
				Objeto.focus();				
				Objeto.value = "";				
				return false;				
			} 			
		
	} 	
	
	
function Mascara_CPFCNPJ(Objeto)
	{
		if(document.getElementById('tipo_pessoa_0').checked == true) { mascara_cpf(Objeto); }	
		if(document.getElementById('tipo_pessoa_1').checked == true) { mascara_cnpj(Objeto); }
	}
	
function Verifica_CPFCNPJ(Objeto,Acao)
	{
		if(Objeto.value.length > 1)
			{
				if(document.getElementById('tipo_pessoa_0').checked == true)
					{
						if(valida_cpf(Objeto)!=false)
							{
								if(Acao=="CarregarListaAplicativo")
									{
										CarregarXMLHTTP('Aplicativo.ComboBox.php?CpfCnpj='+RemoverMascara(Objeto),'layer_aplicativo');
										document.getElementById('email').focus();
									}
							}
					}	
				if(document.getElementById('tipo_pessoa_1').checked == true)
					{
						if(valida_cnpj(Objeto)!=false)
							{
								if(Acao=="CarregarListaAplicativo")
									{
										CarregarXMLHTTP('Aplicativo.ComboBox.php?CpfCnpj='+RemoverMascara(Objeto),'layer_aplicativo');
										document.getElementById('email').focus();
									}
							}						
					}				
			}
		else
			{
				CarregarXMLHTTP('Aplicativo.ComboBox.php?CpfCnpj=','layer_aplicativo');
				document.getElementById('email').focus();
			}

	}		
	
function CarregarXMLHTTP(url_arquivo,div_resposta)
	{
//		alert(url_arquivo+parametro_arquivo+div_resposta);
		valor_rand = "&" + Math.ceil(Math.random() * 100000) + "="+ Math.ceil(Math.random() * 100000);
		var carregando = "<strong><font color='#FF0000'>Carregando... </font></strong>";
		req = null;
		// Procura por um objeto nativo (Mozilla/Safari)
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
			req.open("GET", url_arquivo+valor_rand, true);
			req.onreadystatechange =function()
				{
					if (req.readyState == 1) // apenas enquanto estiver carregando
						{
							document.getElementById(div_resposta).innerHTML = carregando;
						}
					// apenas quando o estado for "completado"
					if (req.readyState == 4)
						{
							// apenas se o servidor retornar "OK"
							if (req.status == 200)
								{
									// procura pela div id="atualiza" e insere o conteudo
									// retornado nela, como texto HTML
									document.getElementById(div_resposta).innerHTML = req.responseText;
								}
							else
								{
									alert("Houve um problema ao obter os dados:\n" + req.statusText);
								}
						}						

				}
			
			req.send(null);
		// Procura por uma versao ActiveX (IE)
		} else if (window.ActiveXObject) {
			req = new ActiveXObject("Microsoft.XMLHTTP");
			if (req) {
			req.open("GET", url_arquivo+valor_rand, true);
			req.onreadystatechange =function()
				{					
					if (req.readyState == 1) // apenas enquanto estiver carregando
						{
							document.getElementById(div_resposta).innerHTML = carregando;
							
						}
					// apenas quando o estado for "completado"
					if (req.readyState == 4)
						{
							// apenas se o servidor retornar "OK"
							if (req.status == 200)
								{
									// procura pela div id="atualiza" e insere o conteudo
									// retornado nela, como texto HTML
									document.getElementById(div_resposta).innerHTML = req.responseText;
								}
							else
								{
									alert("Houve um problema ao obter os dados:\n" + req.statusText);
								}
						}						

				}
				req.send();
			}
		}


	}	
	
	
function VerificarCadadastro()
	{
		var situacao = "verdadeiro";
		
		if(document.getElementById('aplicativo').value=="x")
			{
				alert('Selecione Aplicativo Desejado !');
				situacao = "falso";
				return false;
			}
			
		if(document.getElementById('tipo_pessoa_0').checked== false && document.getElementById('tipo_pessoa_1').checked== false )			
			{
				alert('Selecione Tipo  Fisica/Juridica !');
				return false;
			}
			
		if(document.getElementById('tipo_pessoa_1').checked== true)
			{
				// valida cnpj
				if(valida_cnpj(document.getElementById('cpf_cnpj'))== false)
					{
						situacao = "falso";
						return false;
					}				
			}

			
		if(situacao=="verdadeiro")
			{
				CarregarXMLHTTP('AreadoCliente.Cadastro.Form.php?Aplicativo='+document.getElementById('aplicativo').value+'&CpfCnpj='+RemoverMascara(document.getElementById('cpf_cnpj')),'layer_cadastro');
				
			}	
	}
	

	function MostrarLayerCpfCnpj()
		{
		  if(document.getElementById('tipo_pessoa_0').checked == true)
			  {
				  document.getElementById('layer_cpf').style.display = "";
				  document.getElementById('layer_cnpj').style.display = "none";
			  }
		  if(document.getElementById('tipo_pessoa_1').checked == true)
			  {
				  document.getElementById('layer_cpf').style.display = "none"
				  document.getElementById('layer_cnpj').style.display = "";
			  }			
		}
	
	function ValidarLoginPainelCliente()
		{
			if(document.getElementById('tipo_pessoa_0').checked== false && document.getElementById('tipo_pessoa_1').checked== false )			
				{
					alert('Selecione Tipo  Fisica/Juridica !');
					return false;
				}



			if(document.getElementById('cpf_cnpj').value=="")
				{
					
					if(document.getElementById('tipo_pessoa_0').checked == true)
						{
							alert('Digite o CPF');
						}
					if(document.getElementById('tipo_pessoa_1').checked == true)
						{
							alert('Digite o CNPJ');
						}						
					
					document.getElementById('cpf_cnpj').focus();
					return false;
				}
			else
				{				
					if(document.getElementById('tipo_pessoa_0').checked == true) {valida_cpf(document.getElementById('cpf_cnpj')); }	
					if(document.getElementById('tipo_pessoa_1').checked == true) { valida_cnpj(document.getElementById('cpf_cnpj')); }					
				}
								
		
			if(document.getElementById('aplicativo').value=="" || document.getElementById('aplicativo').value=="x")			
				{
					alert('Selecione Aplicativo!');
					return false;
				}	
	
				
			if(document.getElementById('email').value=="")
				{
					alert("Preencha Campo Email!");
					document.getElementById('email').focus();
					return false				
				}
			else
				{	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
					var regex = new RegExp(emailReg);
					if(!regex.test(document.getElementById('email').value))
						{	alert("Seu e-mail é inválido");
							document.getElementById('email').focus();
							return false;
						}      
				}	
			
			if(document.getElementById('senha').value=="")			
				{
					alert('Preencha campo senha');
					return false;
				}					
				
				
		}




		
	function LembrarSenha()
		{
			var aplicativo	=	"";
			var cpf_cnpj	=	"";
			
			if(document.getElementById('cpf_cnpj').value=="")
				{
					alert('Preencha os campos CPF/CNPJ e aplicativo para o reenvio da senha por e-mail')
					return false;
				}	
			else
				{
					cpf_cnpj="&CpfCnpj="+document.getElementById('cpf_cnpj').value;
				}			

				
				
			if(document.getElementById('aplicativo').value=="" || document.getElementById('aplicativo').value=="x" )
				{
					alert('Selecione Aplicativo')
					return false;
				}
			else
				{
					aplicativo="&Aplicativo="+document.getElementById('aplicativo').value;
				}				
			
				
			window.open('LembrarSenha.php?Validar=Sim'+aplicativo+cpf_cnpj,'_parent');
		}
	
	function MascararCep(Objeto)
		{
			if (Objeto.value.length == 5)	{ Objeto.value = Objeto.value + '-'; }
////			return Objeto.value;
		}
		
	function LimparCampo(objeto)
		{
			objeto.value = "";
		}
		
	function CarregarCEP(NomeCampo,ValorCep,DivResposta)
		{
			if(document.getElementById(NomeCampo).value.length < 8)
				{
					alert("Preencha corretamente o campo Cep.");
					document.getElementById(NomeCampo).value="";
					document.getElementById(NomeCampo).focus();
				}
			else
				{
					valor_rand = "&" + Math.ceil(Math.random() * 100000) + "="+ Math.ceil(Math.random() * 100000);
			
					req = null;
					// Procura por um objeto nativo (Mozilla/Safari)
					if (window.XMLHttpRequest) {
						req = new XMLHttpRequest();
						req.open("GET", "Atalho_BuscaCep.php?CEP_CODIGO="+ValorCep+valor_rand, true);
						req.onreadystatechange =function()
							{
								if (req.readyState == 1) // apenas enquanto estiver carregando
									{
										document.getElementById(DivResposta).innerHTML="<strong><font color='#FF0000'>Carregando...</font></strong>";
									}
								// apenas quando o estado for "completado"
								if (req.readyState == 4)
									{
										// apenas se o servidor retornar "OK"
										if (req.status == 200)
											{
												var retornocep = req.responseText.split('|');
												document.getElementById('endereco').value = unescape(retornocep[1]);
												document.getElementById('bairro').value = unescape(retornocep[2]);
												document.getElementById('cidade').value = unescape(retornocep[3]);
												document.getElementById('uf').value = unescape(retornocep[4]);
												document.getElementById('cidade_ibge').value = unescape(retornocep[5]);
												document.getElementById(DivResposta).innerHTML = "";
//												document.getElementById(DivResposta).innerHTML = req.responseText;
											}
										else
											{
												alert("Houve um problema ao obter os dados:\n" + req.statusText);
											}
									}						
			
							}
						
						req.send(null);
					// Procura por uma versao ActiveX (IE)
					} else if (window.ActiveXObject) {
						req = new ActiveXObject("Microsoft.XMLHTTP");
						if (req) {
						req.open("GET", "Atalho_BuscaCep.php?CEP_CODIGO="+ValorCep+valor_rand, true);
						req.onreadystatechange =function()
							{
								if (req.readyState == 1) // apenas enquanto estiver carregando
									{
										document.getElementById(DivResposta).innerHTML="<strong><font color='#FF0000'>Carregando...</font></strong>";
									}
								// apenas quando o estado for "completado"
								if (req.readyState == 4)
									{
										// apenas se o servidor retornar "OK"
										if (req.status == 200)
											{									
												var retornocep = req.responseText.split('|');
												document.getElementById('endereco').value = unescape(retornocep[1]);
												document.getElementById('bairro').value = unescape(retornocep[2]);
												document.getElementById('cidade').value = unescape(retornocep[3]);
												document.getElementById('uf').value = unescape(retornocep[4]);
												document.getElementById('cidade_ibge').value = unescape(retornocep[5]);
												document.getElementById(DivResposta).innerHTML = "";
//												document.getElementById(DivResposta).innerHTML = req.responseText;
			
											}
										else
											{
												alert("Houve um problema ao obter os dados:\n" + req.statusText);
											}
									}						
			
							}
							req.send();
						}
					}			
				}
		}			
		


	
function ValidarFormCadastroAplicativo()
	{
		
/*		if(document.getElementById('razao').value=="")
			{
				alert('Preencha campo Razao Social !');
				document.getElementById('razao').focus();
				return false;
			}
			
			
			
		if(document.getElementById('cep').value.length < 9)
			{
				alert('Digite Cep !');
				document.getElementById('cep').focus();
				return false;
			}				
			
		
		if(trim(RemoverMascara(document.getElementById('cep').value)).length < 9)
			{
				alert('Digite Cep !');				
				document.getElementById('cep').focus();
				return false;
			}
			
		if(document.getElementById('endereco').value.length < 9)
			{
				alert('Preencha campo Endereco!');				
				document.getElementById('endereco').focus();
				return false;				
			}


		if(document.getElementById('numero').value=="")
			{
				alert('Preencha campo Numero !');
				document.getElementById('numero').focus();
				return false;				
			}
			
		if(document.getElementById('bairro').value=="")
			{
				alert('Preencha campo bairro !');
				document.getElementById('bairro').focus();
				return false;				
			}					
							
			
		if(document.getElementById('cidade').value=="")
			{
				alert('Prencha cidade !');
				document.getElementById('cidade').focus();
				return false;				
			}				
			
		if(document.getElementById('nome_contato').value=="")
			{
				alert('Prencha nome Contato !');
				document.getElementById('nome_contato').focus();
				return false;				
			}			

		if(document.getElementById('ddd_contato').value=="")
			{
				alert('Preencha DDD Contato !');
				document.getElementById('ddd_contato').focus();
				return false;				
			}	
			
		if(document.getElementById('fone_contato').value=="")
			{
				alert('Preencha Fone Contato !');
				document.getElementById('fone_contato').focus();
				return false;				
			}	
*/			
			
		if(document.getElementById('email_login').value=="")
			{
				alert('Preencha campo Email!');
				document.getElementById('email_login').focus();
				return false;				
			}				
			
		if(document.getElementById('email_login').value=="")
			{
				alert("Preencha Campo Email!");
				document.getElementById('email_login').focus();
				return false				
			}
		else
			{	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
				var regex = new RegExp(emailReg);
				if(!regex.test(document.getElementById('email_login').value))
					{	alert("Seu e-mail e invalido");
						document.getElementById('email_login').focus();
						return false;
					}      
			}						
			

		if(document.getElementById('senha_login').value=="")
			{
				alert('Preencha campo Senha!');
				document.getElementById('senha_login').focus();
				return false;				
			}
		else
			{
				if(document.getElementById('senha_login').value.length < 6)
					{
						alert('A senha deve possuir no minimo 6 caracteres !');
						document.getElementById('senha_login').focus();
						return false;				
					}				
			}
			
		if(document.getElementById('senha_login').value != document.getElementById('repete_senha').value)
			{
				alert('O campo repete senha nao confere com a senha digitada!');
				document.getElementById('senha_login').focus();
				return false;				
			}				
	}			
	
  function LembrarSenha(Aplicativo)
	  {
		  if(document.getElementById('cpf_cnpj').value =="")
			  {
				  alert('Para solicitar o lembrete de senha, preencha o Campo CNPJ');
				  document.getElementById('cpf_cnpj').focus();
				  return false;
			  }
		  var cpf_cnpj = RemoverMascara(document.getElementById('cpf_cnpj'));				
		  window.open('index.php?Secao=LembrarSenha&Aplicativo='+Aplicativo+'&CpfCnpj='+cpf_cnpj,'_parent');
	  }
	  
  function ValidarLoginAplicativo(Aplicativo)
	  {
		  if(document.getElementById('cpf_cnpj').value =="")
			  {
				  alert('Preencha campo CNPJ');
				  document.getElementById('cpf_cnpj').focus();
				  return false;
			  }
			  
		  if(document.getElementById('email_login').value =="")
			  {
				  alert('Preencha campo Email!');
				  document.getElementById('email_login').focus();
				  return false;
			  }	
			  
		  if(document.getElementById('senha_login').value =="")
			  {
				  alert('Preencha campo Senha!');
				  document.getElementById('senha_login').focus();
				  return false;
			  }				  
	  }
	  
function CarregarCalendario(valor)
	{
		CarregarAjax('CalendarioAns.php?Calendario='+valor,'DivCalendarioAns');
	}
	
function CarregarAjax(url_arquivo,div_resposta)
	{
//		alert(url_arquivo+parametro_arquivo+div_resposta);
		valor_rand = "&" + Math.ceil(Math.random() * 100000) + "="+ Math.ceil(Math.random() * 100000);
		var carregando = "<img src=\"/imagens/loading.gif\" />";
		req = null;
		// Procura por um objeto nativo (Mozilla/Safari)
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
			req.open("GET", url_arquivo+valor_rand, true);
			req.onreadystatechange =function()
				{
					if (req.readyState == 1) // apenas enquanto estiver carregando
						{
							document.getElementById(div_resposta).innerHTML = carregando;
						}
					// apenas quando o estado for "completado"
					if (req.readyState == 4)
						{
							// apenas se o servidor retornar "OK"
							if (req.status == 200)
								{
									// procura pela div id="atualiza" e insere o conteudo
									// retornado nela, como texto HTML
									document.getElementById(div_resposta).innerHTML = req.responseText;
								}
							else
								{
									alert("Houve um problema ao obter os dados:\n" + req.statusText);
								}
						}						

				}
			
			req.send(null);
		// Procura por uma versao ActiveX (IE)
		} else if (window.ActiveXObject) {
			req = new ActiveXObject("Microsoft.XMLHTTP");
			if (req) {
			req.open("GET", url_arquivo+valor_rand, true);
			req.onreadystatechange =function()
				{
					if (req.readyState == 1) // apenas enquanto estiver carregando
						{
							document.getElementById(div_resposta).innerHTML = carregando;
						}
					// apenas quando o estado for "completado"
					if (req.readyState == 4)
						{
							// apenas se o servidor retornar "OK"
							if (req.status == 200)
								{
									// procura pela div id="atualiza" e insere o conteudo
									// retornado nela, como texto HTML
									document.getElementById(div_resposta).innerHTML = req.responseText;
								}
							else
								{
									alert("Houve um problema ao obter os dados:\n" + req.statusText);
								}
						}						

				}
				req.send();
			}
		}


	}	
	
	
function MarcaDesmarcaCheckbox(CheckboxPrincipal,CheckBoxLista)
	{
		var checkbox = document.getElementsByName(CheckBoxLista);
		//var checkbox = document.getElementById(CheckBoxLista);
		var boxLength = checkbox.length;
		
		
		
		if(CheckboxPrincipal.checked)
			{
				for (i = 0; i < checkbox.length; i++)
				checkbox[i].checked = true ;
			}
		else
			{
				for (i = 0; i < checkbox.length; i++)
				checkbox[i].checked = false ;
			}
			

	}
	
