/* Funcões JS */

//Função de mostrar objetos ao clicar
function mostrainfo(id_mostrainfo) { //sempre chama o id_mostrainfo
	if(document.getElementById(id_mostrainfo).style.display == '') {	//em branco para não aparecer
		document.getElementById(id_mostrainfo).style.display = 'none';	//colocar none para o display ficar vazio na DIV
	} else {
		document.getElementById(id_mostrainfo).style.display = '';
	};
}

// Mascara data
function mascaradata(i,evento) {
 var texto = i.value


   //if (event.keyCode  == 47 || event.keyCode == 46) event.returnValue = false;
  

  if (texto.length >= 10)
		 evento.returnValue = false;


  if (evento.keyCode  < 48 || evento.keyCode > 57) evento.returnValue = false;

  if (texto == "." || texto == "/" ) evento.returnValue = false;
 
  if (texto.length == 2 || texto.length == 5 ) 
   {
   i.value = texto +"/";
   }

 }


// Validação do campo DATA. 
 function validadata (i)
 {    var str = i.value;
 
      if (str == '')
      { return true ; }
      
         // Verifica se foram digitados 10 caracteres.
         if (str.length != 10)
            {
            //alert("\nO campo DATA requer 10 dígitos no formato:\n\nDD/MM/AAAA")
           // i.focus() ;
            return false;
            }

       // Verifica se os caracteres são números e barra.
         for (var x = 0; x < str.length; x++) 
            {
            var ch = str.substring(x, x + 1);
            if ((ch < "0" || "9" < ch) && ch != "/") 
               {
              // alert("\nO campo DATA aceita somente números e um barra no formato:\n\nDD/MM/AA");
            //i.focus() ;
            return false;
               }
            }
         // Verifica o valor do dia.
         if ( (str.substring(0, 2) < 1)  ||  (str.substring(0, 2) > 31)  ) 
            {
            //alert("\nDia incorreto.");
            //i.focus() ;
            return false;
            }
         // Verifica o valor do dia no valor do mês.
            // Fevereiro
               if ( (str.substring(3, 5) == 2 )  &&  (str.substring(0, 2) > 29)  )
                  {
                  //alert("\nFevereiro não tem mais que 29 dias.");
				 // i.focus() ;
            return false;
                  }
               if ( (str.substring(3, 5) == 2 )  &&  (str.substring(0, 2) == 29)  )
                  { alert("\nVocê entrou com 29 de Fevereiro...\n\nVocê tem certeza de que é ano bissexto?"); }
            // Abril
               if ( (str.substring(3, 5) == 4 )  &&  (str.substring(0, 2) > 30)  )
                  {
                  //alert("\nAbril não tem mais que 30 dias.");
				 // i.focus() ;
				  return false;
                  }
            // Junho
               if ( (str.substring(3, 5) == 6 )  &&  (str.substring(0, 2) > 30)  )
                  {
                  // alert("\nJunho não tem mais que 30 dias..");
				  // i.focus() ;
				  return false;
                  }
            // Setembro
               if ( (str.substring(3, 5) == 9 )  &&  (str.substring(0, 2) > 30)  )
                  {
                  //  alert("\nSetembro não tem mais que 30 dias..");
				  //  i.focus() ;
				    return false;
                  }
            // Novembro
               if ( (str.substring(3, 5) == 11 )  &&  (str.substring(0, 2) > 30)  )
                  {
                  // alert("\nNovembro não tem mais que 30 dias.");
                  // i.focus() ;
				   return false;
                  }
         // Verifica o valor do mês.
         if ( (str.substring(3, 5) < 1)  ||  (str.substring(3, 5) > 12)  ) 
            {
            //alert("\nMês incorreto.");
           // i.focus() ;
            return false;
            }
         // Verifica o valor do ano.
         if ( (str.substring(6, 8) < 1)  ||  (str.substring(6, 8) > 99)  ) 
            {
           //// alert("\nAno incorreto.");
            //i.focus() ;
            return false;
            }
         // Verifica posicionamento da barra.
         if ( str.substring(3, 4) == "/"  || str.substring(4, 5) == "/" ) 
            {
           // alert("\nBarra misturada com o mês.");
           // i.focus() ;
            return false;
            }
         if ( str.substring(0, 1) == "/"  || str.substring(1, 2) == "/" ) 
            {
           // alert("\nBarra misturada com o dia.");
           // i.focus() ;
            return false;
            }
         if ( str.substring(6, 7) == "/"  || str.substring(7, 8) == "/" ) 
            {
           // alert("\nBarra misturada com o ano.");
           // i.focus() ;
            return false;
            }
         if ( str.substring(2, 3) != "/"  ||  str.substring(5, 6) != "/" ) 
            {
           // alert("\nBarra misturada com a data.");
           //i.focus() ;
            return false;
            }
       
   return true;

 }

// Validação de CPF

 function validacpf(c) {
   var CPF = c.value;
   CPF = CPF.toString().replace( ".", "" );
   CPF = CPF.toString().replace( ".", "" );
   CPF = CPF.toString().replace( "-", "" );
    if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
		CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
		CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
		CPF == "88888888888" || CPF == "99999999999")
	{
	    //alert("CPF inválido");
       // c.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("CPF inválido");
       // document.forms[0].elements[c].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("CPF inválido");
      //  document.forms[0].elements[c].focus() ;
		return false;
	}
	return true;
 }
 
 
 
 
    function comparadata(i,j){
 		 data1 = i.value;
         data2 = j.value;
		 
		 if(data2=='') {
		  return true;
		 }
		 
         datainicial = data1.substring(6, 10) + data1.substring(3, 5) + data1.substring(0, 2)
         datafinal   = data2.substring(6, 10) + data2.substring(3, 5) + data2.substring(0, 2)
		if(datainicial > datafinal){
			return false;
		}
		return true;
     }

// permite o cadastramento apenas de números
 
 function formatanumero(i){   
//alert(event.keyCode)

	if (event.keyCode == 45 || event.keyCode == 46 || event.keyCode == 47) event.returnValue = false;
	if (event.keyCode  < 44 || event.keyCode > 57) event.returnValue = false;
	if (event.keyCode  == 8) event.returnValue = true;
	if (event.keyCode  >= 96 && event.keyCode <= 105) event.returnValue = true;
	

}
 

/*
prototypeUtils.js from http://jehiah.com/
Licensed under Creative Commons.
version 1.0 December 20 2005

Contains:
+ Form.Element.setValue()
+ unpackToForm()

*/

/* Form.Element.setValue("fieldname/id","valueToSet") */
Form.Element.setValue = function(element,newValue) {
    element_id = element;
    element = $(element);
    if (!element){element = document.getElementsByName(element_id)[0];}
    if (!element){return false;}
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.SetSerializers[method](element,newValue);
}

Form.Element.SetSerializers = {
  input: function(element,newValue) {
    switch (element.type.toLowerCase()) {
      case 'submit':
      case 'hidden':
      case 'password':
      case 'text':
        return Form.Element.SetSerializers.textarea(element,newValue);
      case 'checkbox':
      case 'radio':
        return Form.Element.SetSerializers.inputSelector(element,newValue);
    }
    return false;
  },

  inputSelector: function(element,newValue) {
    fields = document.getElementsByName(element.name);
    for (var i=0;i<fields.length;i++){
      if (fields[i].value == newValue){
        fields[i].checked = true;
      }
    }
  },

  textarea: function(element,newValue) {
    element.value = newValue;
  },

  select: function(element,newValue) {
    var value = '', opt, index = element.selectedIndex;
    for (var i=0;i< element.options.length;i++){
      if (element.options[i].value == newValue){
        element.selectedIndex = i;
        return true;
      }        
    }
  }
}

function unpackToForm(data){
   for (i in data){
     Form.Element.setValue(i,data[i].toString());
   }
}

	


		
	function replaceAll(string, token, newtoken) {
		while (string.indexOf(token) != -1) {
			string = string.replace(token, newtoken);
		}
		return string;
	}



	function marcartodos(chkbox,numformulario,nomecheck) {	     
			
		for (var i=0;i < document.forms[numformulario].elements.length;i++) {
		var elemento = document.forms[numformulario].elements[i];
		 if (elemento.type == "checkbox") {
			 if(elemento.name==nomecheck){
				elemento.checked = chkbox.checked;
			 }
		 }
		}
			
	}

// Função que valida o e-mail .
 function validaemail(e) {   
 
 	var str = e.value;

	if (str == ""){
            return true;
	   }
      
      if (str.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
        return true;
	  } else {
        return false;
      }
}

	
	// SELEÇÃO DE MUNICÍPIOS	
	function retornaMunicipios(coduf,idemunicipio,setavalor) {
	//alert(setavalor);
		$(idemunicipio).options.length = 0;
		$(idemunicipio).options[0] = new Option('Carregando...','');
		
		if(coduf.value=='') {
			coduf.focus();
			return false;
		}
		
		new Ajax.Request('carrinho_ajax.php',  
			{ 
				method:'POST',   
				parameters: 'coduf='+coduf.value+'&acao=retornaMunicipios',
				onSuccess: function(transport){  
						// primeira chave
						//alert(transport.responseText);
						//return false;
						var mjson = transport.responseText.evalJSON(true);
						
						$(idemunicipio).options[0] = new Option('Escolha um Município','');
						
						var tot = mjson.length+1;
						var a   = 0;
						for(i=1;i<=tot;i++) {
							
							$(idemunicipio).options[i] = new Option(mjson[a].nommunicipio,mjson[a].idemunicipio);
							
							if(setavalor==mjson[a].idemunicipio) {
								$(idemunicipio).options[i].selected = true 
								}
								a++;
	
							};
						// ultima chave
					}   
				} ); 
	}	

	// VALIDA E SALVA OS DADOS DA PESSOA
	function salvarPessoa() {

		var erro = '';
		var xerr = 0;
		
		
		if(validacpf($('numcpf'))==false) {
			erro = 1;
			$('numcpf').style.backgroundColor = "#FFFF99";
		
		} else {$('numcpf').style.backgroundColor = "#FFFFFF";}
		
		if($('nompessoa').value=="") {
			erro = 1;
			$('nompessoa').style.backgroundColor = "#FFFF99";
		
		} else {$('nompessoa').style.backgroundColor = "#FFFFFF";}
		
		if($('nommae').value=="") {
			erro = 1;
			$('nommae').style.backgroundColor = "#FFFF99";
		
		} else {$('nommae').style.backgroundColor = "#FFFFFF";}
		
		if($('numidentidade').value=="") {
			erro = 1;
			$('numidentidade').style.backgroundColor = "#FFFF99";
		
		} else {$('numidentidade').style.backgroundColor = "#FFFFFF";}
		
		if($('dessiglaorgaoemissor').value=="") {
			erro = 1;
			$('dessiglaorgaoemissor').style.backgroundColor = "#FFFF99";
		
		} else {$('dessiglaorgaoemissor').style.backgroundColor = "#FFFFFF";}
		
		if($('datemissao').value=="") {
			erro = 1;
			$('datemissao').style.backgroundColor = "#FFFF99";
		
		} else {
			
			if(validadata($('datemissao'))==false) {
			erro = 1;
			alert('Data datemissao!');
			return false;
				$('datemissao').style.backgroundColor = "#FFFF99";
			
			} else { $('datemissao').style.backgroundColor = "#FFFFFF"; }
		
		} 
		
		
		if($('datnascimento').value!="") {
		
			if(validadata($('datnascimento'))==false) {
			erro = 1;
			alert('Data inválida!');
			return false;
				$('datnascimento').style.backgroundColor = "#FFFF99";
			
			} else { $('datnascimento').style.backgroundColor = "#FFFFFF"; }
		
		}
		
		
		if($('flasexo').value=="") {
			erro = 1;
			$('flasexo').style.backgroundColor = "#FFFF99";
		
		} else {$('flasexo').style.backgroundColor = "#FFFFFF";}
		
		if($('codestadocivil').value=="") {
			erro = 1;
			$('codestadocivil').style.backgroundColor = "#FFFF99";
		
		} else {$('codestadocivil').style.backgroundColor = "#FFFFFF";}
		
		if($('idepais').value=="" || $('idepais').value=="0") {
			erro = 1;
			$('idepais').style.backgroundColor = "#FFFF99";
		
		} else {$('idepais').style.backgroundColor = "#FFFFFF";}
		
		if($('idepais').value=="22") {
			if($('codufnaturalidade').value=="") {
				erro = 1;
				$('codufnaturalidade').style.backgroundColor = "#FFFF99";
				
			} else {$('codufnaturalidade').style.backgroundColor = "#FFFFFF";}
			
			if($('idemunicipionaturalidade').value=="") {
				erro = 1;
				$('idemunicipionaturalidade').style.backgroundColor = "#FFFF99";
			
			} else {$('idemunicipionaturalidade').style.backgroundColor = "#FFFFFF";}
		}
		
		if($('desendereco').value=="") {
			erro = 1;
			$('desendereco').style.backgroundColor = "#FFFF99";
			
		} else {$('desendereco').stylebackgroundColor = "#FFFFFF";}
		
		if($('nombairro').value=="") {
			erro = 1;
			$('nombairro').style.backgroundColor = "#FFFF99";
			
		} else {$('nombairro').stylebackgroundColor = "#FFFFFF";}
		
		if($('numcep').value=="") {
			erro = 1;
			$('numcep').style.backgroundColor = "#FFFF99";
			
		} else {$('numcep').stylebackgroundColor = "#FFFFFF";}
		
		if($('coduf').value=="") {
			erro = 1;
			$('coduf').style.backgroundColor = "#FFFF99";
			
		} else {$('coduf').stylebackgroundColor = "#FFFFFF";}
		
		if($('idemunicipioendereco').value=="") {
			erro = 1;
			$('idemunicipioendereco').style.backgroundColor = "#FFFF99";
			
		} else {$('idemunicipioendereco').stylebackgroundColor = "#FFFFFF";}
		
		if($('numdddtelefone').value=="") {
			erro = 1;
			$('numdddtelefone').style.backgroundColor = "#FFFF99";
		
		} else {$('numdddtelefone').style.backgroundColor = "#FFFFFF";}
		
		if($('numdddtelefone').value<3) {
			erro = 1;
			$('numdddtelefone').style.backgroundColor = "#FFFF99";
		
		} else {$('numdddtelefone').style.backgroundColor = "#FFFFFF";}
		
		if($('numtelefone').value=="") {
			erro = 1;
			$('numtelefone').style.backgroundColor = "#FFFF99";
		
		} else {$('numtelefone').style.backgroundColor = "#FFFFFF";}
		
		if($('numcelular').value=="") {
			erro = 1;
			$('numcelular').style.backgroundColor = "#FFFF99";
		
		} else {$('numcelular').style.backgroundColor = "#FFFFFF";}
		
		if($('desemail').value=="") {
			erro = 1;
			$('desemail').style.backgroundColor = "#FFFF99";
		
		} else {
			
				if(validaemail($('desemail'))==false) {
					erro = 1;
					alert('E-mail inválido!');
					return false;
					$('desemail').style.backgroundColor = "#FFFF99";
				
				} else {
				
					$('desemail').style.backgroundColor = "#FFFFFF";
				
				}

			
			}
		
		if($('codnivel').value=="") {
			erro = 1;
			$('codnivel').style.backgroundColor = "#FFFF99";
		
		} else {$('codnivel').style.backgroundColor = "#FFFFFF";}
		
		
		if(erro!='') {
			//$('msg_ajax').innerHTML		= '<font color=red>'+erro+'</font>';
			alert('Por favor, preencha todos os campos destacados.');
			return false;
		} 
		

		var pars = Form.serialize("frmcadastro");
		
		var destino = 'carrinho_ajax.php';
		
		
			new Ajax.Request(destino, { 
					method:"POST",   
					parameters: pars+'&acao=salvarPessoa',
					onSuccess: function(transport) {  
					//alert(transport.responseText);  
					//$('rodape_matricula').innerHTML = transport.responseText
					//return false;
						var rjson = transport.responseText.evalJSON(true); 
							if(rjson.retorno=="true") {
								formaPagamento();
							} else {
								return false;
							}/**/
					
					}   
			} ); 
	
	};

	
	function verificaCPF(){

		
		if($('frmnumcpf').value == ''){
			alert('Informe o seu CPF!');
			return false;
			} else {
				if(validacpf($('frmnumcpf'))==false) {
					alert('CPF inválido!');
					return false;
				} 
			}
		
		var pars = Form.serialize('frmcadastro');
	
			var myAjax = new Ajax.Updater('conteudo_matricula', 'carrinho_ajax.php', {
				method:'POST',
				parameters : pars+ '&acao=buscacpf',
				evalScripts : true
			  });
	}
	
	function login(){
	
			
		if($('frmsenha').value == ''){
			alert('Informe a sua senha!');
			return false;
			}
	
		var pars = Form.serialize('frmcadastro');

		var myAjax = new Ajax.Updater('conteudo_matricula', 'carrinho_ajax.php', {
			method:'POST',
			parameters : pars+ '&acao=login',
			evalScripts : true
		  });
	
	}
	


	function novajanela(paginahtml, janelanome, largura, altura, barra) {
		var winl = (screen.width - largura) / 2;
		var wint = (screen.height - altura) / 2;
		winprops = 'height='+altura+',width='+largura+',top='+wint+',left='+winl+',scrollbars='+barra+',resizable'
		win = window.open(paginahtml, janelanome, winprops)
		if (parseInt(navigator.appVersion) >= 4) {
			win.window.focus();
		}
	}
	
	function nova_jan(janela){
		window.open(janela,'_blank')
	}
	function EsqueceuaSenha() {
		novajanela('http://www.poseadvirtual.com.br/pop_senha.php', 'Login', 450, 280, 'no');
	}
	
	function finalizarCompra() {
		

		var pars = Form.serialize("frmcadastro");
		
		var destino = 'carrinho_ajax.php';
	
		new Ajax.Request(destino, { 
				method:"POST",   
				parameters: pars+'&acao=finalizarCompra',
				onSuccess: function(transport) {  
				//alert(transport.responseText);  
				$('conteudo_matricula').innerHTML = transport.responseText
				//return false;
					/*var rjson = transport.responseText.evalJSON(true); 
						if(rjson.retorno=="true") {
							loadPagePost('carrinho_ajax.php','acao=formaPagamento','conteudo_matricula');
						} else {
							return false;
						}*/
				
				}   
		} ); 
		
	}
	
	function  setaTitulo(fase){
			
			switch(fase) {
				case 1:
					$('fase_matricula').innerHTML = "<img src='imagens/fase1.png' border='0'>"; 
				break;
				case 2:
					$('fase_matricula').innerHTML = "<img src='imagens/fase2.png' border='0'>"; 
				break;
				case 3:
					$('fase_matricula').innerHTML = "<img src='imagens/fase3.png' border='0'>"; 
				break;
				}
		
		}
		
		
		
		
		
		
		
		
		