// JavaScript Document
function open_url2(url, target) {
	please_wait = "<center><font size='2' color='#787878' face='Trebuchet MS'>aguarde. carregando...</font></center>";
 	if ( ! document.getElementById) {
  		return false;
 	}
 	if (please_wait != null) {
  		document.getElementById(target).innerHTML = please_wait;
 	}
 	if (window.ActiveXObject) {
  		link = new ActiveXObject("Microsoft.XMLHTTP");
 	} else if (window.XMLHttpRequest) {
  		link = new XMLHttpRequest();
 	}
 	if (link == undefined) {
  		return false;
 	}
 	link.onreadystatechange = function() { response2(url, target); }
 	link.open("GET", url, true);
 	link.send(null);
}
function response2(url, target) {
 	if (link.readyState == 4) {
	 	document.getElementById(target).innerHTML = (link.status == 200) ? link.responseText : "Ooops!! A broken link! Errorcode: " + link.status;
		if (link.status == 200) {
			if (target == "my_site_content_formaspagamento") {
				if (!document.getElementById('carrinho_cheio')) {
					open_url('vazio.php','my_site_content_aceito');
				}
			   vtotparcelas = 0;	
			   for (var i=0; i < document.getElementsByName("parcelas").length; i++) {
				   if (!document.getElementsByName("parcelas")[i].checked) {
						vtotparcelas += 1; 
				   }
   	   		   }
			   if ( vtotparcelas == 2) {
					    open_url('vazio.php','my_site_content_aceito');			   
			   }
//				if ((!document.getElementsByName("parcelas")[0].checked) && (!document.getElementsByName("parcelas")[1].checked)) {
//				    open_url('vazio.php','my_site_content_aceito');
//				}
			}
			if (target == "my_site_content_aceito") {
				if (url== "cadastro_compras_aceito.php") {
					open_url('vazio.php','my_site_content_seucadastro');
				}
			}
		}
	}
}

function open_url(url, target) {
	please_wait = "<center><font size='2' color='#787878' face='Trebuchet MS'>aguarde. carregando...</font></center>";
 	if ( ! document.getElementById) {
  		return false;
 	}
 	if (please_wait != null) {
  		document.getElementById(target).innerHTML = please_wait;
 	}
 	if (window.ActiveXObject) {
  		link = new ActiveXObject("Microsoft.XMLHTTP");
 	} else if (window.XMLHttpRequest) {
  		link = new XMLHttpRequest();
 	}
 	if (link == undefined) {
  		return false;
 	}
 	link.onreadystatechange = function() { response(url, target); }
 	link.open("GET", url, true);
 	link.send(null);
}
function response(url, target) {
 	if (link.readyState == 4) {
	 	document.getElementById(target).innerHTML = (link.status == 200) ? link.responseText : "Ooops!! A broken link! Errorcode: " + link.status;
		if (link.status == 200) {
			if (target == "my_site_content_carrinho") {
				open_url2('cadastro_compras_formas.php','my_site_content_formaspagamento');
			}
			if (target == "my_site_content_formaspagamento") {
				open_url2('cadastro_compras_aceito.php','my_site_content_aceito');
			}	
			if (target == "my_site_content_aceito") {
				if (url == "vazio.php") {
					open_url2('vazio.php','my_site_content_seucadastro')
				}
			}
		}
	}
}
function set_loading_message(msg) {
 	please_wait = msg;
}
// -------------------------------------------------------------------------------------------

function acaoformulariocomprascarrinho(vformulario,vacao,vcodigo) {
	if (vacao == "incluir") {
		open_url('cadastro_compras_carrinho.php?codigos='+vcodigo,'my_site_content_carrinho');		
	} 
	if (vacao == "excluir") {
	   open_url('cadastro_compras_carrinho.php?codexcluir='+vcodigo,'my_site_content_carrinho');
	}
}

function acaoformulariocomprasforma(vformulario,vacao,vcodigo) {
	if (vacao == "forma") {
		open_url('cadastro_compras_formas.php?codpagamento='+vcodigo,'my_site_content_formaspagamento');
	}	
}

function acaoformulariocomprascadastro(vformulario,vacao,vcodigo) {
	if (vacao == "seucadastro") {
		if (document.getElementById("aceito").checked) {
			open_url('cadastro_compras_seu_cadastro.php','my_site_content_seucadastro');
		} else {
			open_url('vazio.php','my_site_content_seucadastro');
		}
	}
	if (vacao == "tipo") {
		// aqui .........
		
		for (var i=0; i < document.getElementsByName("tipo_cadastro").length; i++) {
			   if (document.getElementsByName("tipo_cadastro")[i].checked) {
					vurl = i+1; 
    			}
   	   }
	   open_url('cadastro_compras_seu_cadastro.php?tipo='+vurl,'my_site_content_seucadastro');
		
//		if (document.getElementsById("tipo_cadastro")[0].checked) {
//			open_url('cadastro_compras_seu_cadastro.php?tipo=1','my_site_content_seucadastro');
//		}
//		if (document.getElementsById("tipo_cadastro")[1].checked) {
//			open_url('cadastro_compras_seu_cadastro.php?tipo=2','my_site_content_seucadastro');
//		}		
	}
	if (vacao == "continuar") {
		open_url('cadastro_compras_seu_cadastro.php?tipo=3','my_site_content_seucadastro');
	}
}

// Funcoes para POST ----------------------------------------------------
   var http_request = false;
   function makePOSTRequest(url, parameters) {
	  http_request = false;
      if (window.XMLHttpRequest) {
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) {
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      
      http_request.onreadystatechange = alertContents;
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
   }

   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            result = http_request.responseText;
			if (document.getElementById('tipo_cadastrado')) {
	            document.getElementById('tipo_cadastrado').innerHTML = result;
			}
			if (document.getElementById('tipo_naocadastrado')) {
	            document.getElementById('tipo_naocadastrado').innerHTML = result;
			}
			if (document.getElementById('tipo_salvar')) {
	            document.getElementById('tipo_salvar').innerHTML = result;
				window.open('http://www.casadoabada.com.br/paginas/abadas/retorno_cadastro.php','_self');
			}
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
   
   function get(obj,vcodigo) {
	   please_wait = "<center><font size='2' color='#787878' face='Trebuchet MS'>aguarde. carregando...</font></center>";
	   if (document.getElementById('tipo_cadastrado')) {
	       document.getElementById('tipo_cadastrado').innerHTML =  please_wait;
		   var poststr =  "login=" + escape(encodeURI(document.getElementById("login").value ))+"&senha=" + escape(encodeURI(document.getElementById("senha").value ));
		   makePOSTRequest('login.php', poststr);
	   }
	   if (document.getElementById('tipo_salvar')) {
		   document.getElementById('tipo_salvar').innerHTML =  please_wait;
		   var poststr =  "";
		   for (var i=0; i < document.getElementsByName("tipopagamento").length; i++) {
			   if (document.getElementsByName("tipopagamento")[i].checked) {
					poststr += "tipo_pagamento=" + escape(encodeURI(document.getElementsByName("tipopagamento")[i].value )); 
    			}
   		   }
		   for (var i=0; i < document.getElementsByName("parcelas").length; i++) {
			   if (document.getElementsByName("parcelas")[i].checked) {
					poststr += "&parcelas=" + escape(encodeURI(document.getElementsByName("parcelas")[i].value )); 
    			}
   		   }
	  	   makePOSTRequest('cadastro_compras_seu_cadastro_salvar.php', poststr);
	   }
	
	   if (document.getElementById('tipo_naocadastrado')) {
	       document.getElementById('tipo_naocadastrado').innerHTML =  please_wait;
		   	var erro = false;
		    var msg  = 'Erro :';	
			if (branco(document.getElementById("nome"))) {
				msg+='\n- Nome em branco.';
				erro=true;
			 }
			if (branco(document.getElementById("cpf"))) {
				msg+='\n- CPF em branco.';
				erro=true;
			 } else {
				 if(!IsNumeric(document.getElementById("cpf").value)) {
						msg+='\n- CPF suporta apenas números!';
						erro=true;			 					 
				 } else {
					 if(!validaCPF(document.getElementById("cpf"))) {
						msg+='\n- Número de CPF inválido!';
						erro=true;			 
					}
				 }
			}
			 if(!IsNumeric(document.getElementById("rg").value)) {
					msg+='\n- RG suporta apenas números!';
					erro=true;			 					 
			 } else {
				 if (branco(document.getElementById("rg"))) {
					msg+='\n- RG em branco.';
					erro=true;
				 } 
			 }
			 if (!echeck(document.getElementById("email").value)) {
					msg+='\n- Email inválido.';
					erro=true;				 
			 } else {
				 if (branco(document.getElementById("email"))) {
					msg+='\n- Email em branco.';
					erro=true;
				 }
			 }  
			 if (branco(document.getElementById("data_nascimento"))) {
				msg+='\n- Data de nascimento em branco.';
				erro=true;
			 } 
			if (branco(document.getElementById("endereco"))) {
				msg+='\n- Endereço em branco.';
				erro=true;
			 } 
			 if (branco(document.getElementById("bairro"))) {
				msg+='\n- Bairro em branco.';
				erro=true;
			 } 
			if (branco(document.getElementById("cidade"))) {
				msg+='\n- Cidade em branco.';
				erro=true;
			 } 
			 if(!IsNumeric(document.getElementById("cep").value)) {
					msg+='\n- CEP suporta apenas números!';
					erro=true;			 					 				 
			 } else {
				 if (branco(document.getElementById("cep"))) {
					msg+='\n- CEP em branco.';
					erro=true;
				 }
			 } 		 
			 if(!IsNumeric(document.getElementById("telefone").value)) {
				 	msg+='\n- Telefone suporta apenas números!';
					erro=true;
			 } else {
				 if (branco(document.getElementById("telefone"))) {
					msg+='\n- Telefone em branco.';
					erro=true;
				 }
			 } 
			 if (!branco(document.getElementById("celular"))) {
		 			 if(!IsNumeric(document.getElementById("celular").value)) {
						msg+='\n- Celular suporta apenas números!';
						erro=true;
					 }
			 }
			 if (erro) {
				  window.alert(msg);
			     document.getElementById('tipo_naocadastrado').innerHTML = "";
			 } else {
				 if (document.getElementById("maillist").checked) {
			         var vmaillist = 1;
				} else {
					 var vmaillist = 0;
				}
			     var poststr =  "nome=" + escape(document.getElementById("nome").value )+"&cpf=" + escape(document.getElementById("cpf").value )+"&rg=" + escape(document.getElementById("rg").value )+"&uf_rg=" + escape(document.getElementById("uf_rg").value )+"&email=" + escape(document.getElementById("email").value )+"&sexo=" + escape(document.getElementById("sexo").value )+"&data_nascimento=" + escape(document.getElementById("data_nascimento").value )+"&endereco=" + escape(document.getElementById("endereco").value )+"&bairro=" + escape(document.getElementById("bairro").value )+"&cidade=" + escape(document.getElementById("cidade").value )+"&cep=" + escape(document.getElementById("cep").value )+"&uf=" + escape(document.getElementById("uf").value )+"&telefone=" + escape(document.getElementById("telefone").value )+"&celular=" + escape(document.getElementById("celular").value )+"&maillist=" + escape(vmaillist);
		  	makePOSTRequest('cadastro_compras_seu_cadastro_salvar_cliente.php', poststr);
			 }
	   }	   
  }
  
  function branco(item){
	    var i;
	  	var caracter;
		caracter = true;
		for (i = 0; i < item.value.length; i++) {
        	if (item.value.charAt(i) !== " ") caracter = false;
		}
    	return caracter;
}

function IsNumeric(sText)

{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }

// JavaScript Document
function validaCPF(cpf)   
{  
  erro = new String;  
  
    if (cpf.value.length == 11)  
    {     
            cpf.value = cpf.value.replace('.', '');  
            cpf.value = cpf.value.replace('.', '');  
            cpf.value = cpf.value.replace('-', '');  
  
            var nonNumbers = /\D/;  
      
            if (nonNumbers.test(cpf.value))   
            {  
                    erro = "A verificacao de CPF suporta apenas números!";   
            }  
            else  
            {  
                    if (cpf.value == "00000000000" ||   
                            cpf.value == "11111111111" ||   
                            cpf.value == "22222222222" ||   
                            cpf.value == "33333333333" ||   
                            cpf.value == "44444444444" ||   
                            cpf.value == "55555555555" ||   
                            cpf.value == "66666666666" ||   
                            cpf.value == "77777777777" ||   
                            cpf.value == "88888888888" ||   
                            cpf.value == "99999999999" ||
							cpf.value == "98765432100") {  
                              
                            erro = "Número de CPF inválido!"  
                    }  
      
                    var a = [];  
                    var b = new Number;  
                    var c = 11;  
  
                    for (i=0; i<11; i++){  
                            a[i] = cpf.value.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.value.charAt(9) != a[9]) || (cpf.value.charAt(10) != a[10])) {  
                        erro = "Número de CPF inválido.";  
                    }  
            }  
    }  
    else  
    {  
        if(cpf.value.length == 0)  
            return false  
        else  
            erro = "Número de CPF inválido.";  
    }  
    if (erro.length > 0) {  
            //alert(erro);  
            cpf.focus();  
            return false;  
    }     
    return true;      
}  
  
//envento onkeyup  
function maskCPF(CPF) {  
    var evt = window.event;  
    kcode=evt.keyCode;  
    if (kcode == 8) return;  
    if (CPF.value.length == 3) { CPF.value = CPF.value + '.'; }  
    if (CPF.value.length == 7) { CPF.value = CPF.value + '.'; }  
    if (CPF.value.length == 11) { CPF.value = CPF.value + '-'; }  
}  
  
// evento onBlur  
function formataCPF(CPF)  
{  
    with (CPF)  
    {  
        value = value.substr(0, 3) + '.' +   
                value.substr(3, 3) + '.' +   
                value.substr(6, 3) + '-' +  
                value.substr(9, 2);  
    }  
}  
function retiraFormatacao(CPF)  
{  
    with (CPF)  
    {  
        value = value.replace (".","");  
        value = value.replace (".","");  
        value = value.replace ("-","");  
        value = value.replace ("/","");  
    }  
}  


function echeck(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}
	
function formata_data(x,tecla){ 
        // Por Tiago Araujo Silva (tiago@tiagoaraujo.com)
        separador="/"; // Voce pode definir o separador. Ex: "/" ou "-" ou "."
        
        tecla=tecla.keyCode; // Identifica a tecla, caso seja backspace
        
        valor=x.value.split(''); // Pega o valor do campo e transforma cada caractere em uma string
        formatado=""; // Variável para carregar formataçao temporariamente
        
        i=0; // variável de controle
        
        while(i<valor.length){ // Loop para cada caractere do campo
            caractere=valor[i]; // Seleciona um caractere para ser formatado
            numeros=/^\d+$/; // Variavel contendo números positivos
                // Verifica se é número ou "barra"
            if(numeros.test(caractere) || caractere==separador){ formatado+=String(caractere);}
                // Verifica se precisa de barra, se a tecla for backspace, entao a barra nao é adicionada
                // Se for para adicionar barra, aumenta ++ variável de controle "i" para pular a barra adicionada
            if((formatado.length==2 || formatado.length==5) && tecla!=8){formatado+=separador; i++;}
                
            i++; // Se houver, passa para o próximo caractere
        }
        x.value=formatado; // Atribui o valor formatado ao campo
}
