/*############################ FUNÃ‡ÃƒO QUE CRIA O OBJETO XMLHttpRequest #############################*/

/*Conexao assincrona
open(mode, url, boolean)

mode = Tipo de requisiÃ§Ã£o GET ou POST;

url = URL do objeto solicitado no modo assÃ­ncrono, pro questÃµes de seguranÃ§a. O
Firefox nÃ£o permite que a URL esteja em um servidor diferente da pÃ¡gina que esta
fazendo a solicitaÃ§Ã£o.

boolean: true (assÃ­ncrono) ou false (sÃ­ncrono).

send() Ã‰ o mÃ©todo SEND que ativa a conexÃ£o e faz a requisiÃ§Ã£o de informaÃ§Ãµes ao
documento aberto pelo mÃ©todo OPEN. Este mÃ©todo possui somente um parÃ¢metro que
serve para enviarmos dados extras ao documento que estamos acessando. Usamos este
parÃ¢metro quando, por exemplo, no mÃ©todo OPEN, acessamos o documento com POST
ao invÃ©s de GET, neste caso os dados do POST sÃ£o passados neste parÃ¢metro de SEND.

/*Valores de retorno do readystate
0 (uninitialized);
1 (a carregar);
2 (carregado);
3 (interativo);
4 (completo);
*/
function openajax() { 
	//cria a variavel xmlhttp;
    var xmlhttp;
	//verifica se o browser tem suporte a ajax 
    try { //IE atuais
        xmlhttp = new XMLHttpRequest();
    } catch(e) {
        try { //IE antigos
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(ex) {
            try { //Mozilla
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(exc) {
                alert("Esse browser nÃ£o tem recursos para uso do Ajax");
                xmlhttp = null;
            }
        }
    }
    return xmlhttp;
    /* Retorna um Boleano*/
}
/*############# FUNÃ‡ÃƒO CARREGA PAGINAS DO CONTEÃšDO PAGINAS SEM RELOAD #############*/
function verificaURLajax() {
	var url_2 = window.location.href;
	if(url_2.indexOf("#p=")!=-1 ) {
		return true;
	} else {
		return false;
	}
}

function extraiScript(texto){
//Maravilhosa função feita pelo SkyWalker.TO do imasters/forum
//http://forum.imasters.com.br/index.php?showtopic=165277&
        // inicializa o inicio ><
        var ini = 0;
        // loop enquanto achar um script
        while (ini!=-1){
                // procura uma tag de script
                ini = texto.indexOf('<script', ini);
                // se encontrar
                if (ini >=0){
                        // define o inicio para depois do fechamento dessa tag
                        ini = texto.indexOf('>', ini) + 1;
                        // procura o final do script
                        var fim = texto.indexOf('</script>', ini);
                        // extrai apenas o script
                        codigo = texto.substring(ini,fim);
                        // executa o script
                        //eval(codigo);
                        /**********************
                        * Alterado por Micox - micoxjcg@yahoo.com.br
                        * Alterei pois com o eval não executava funções.
                        ***********************/
                        novo = document.createElement("script")
                        novo.text = codigo;
                        document.body.appendChild(novo);
                }
        }
}

function carrega_pagina (pagina,parametro){
	//alert('primeira');
	//alert(verificaURLajax(window.location.href));
	/*
	var url_atual;
	setTimeout("url_atual = window.location.href;",5000)
	
	if() {
		
	}
	*/
	//alert(parametro);
	if(parametro.indexOf("#p=")!=-1) {
	//if(verificaURLajax() == true) {
		var url_atual = window.location.href;
		//alert('teste - '+url_atual);
		index1 = url_atual.indexOf("#");
		index2 = url_atual.indexOf("?");
		//if(index2 != -1) {
			sub_url_atual = url_atual.substring(index2, url_atual.length);
		//} else {
			//sub_url_atual = url_atual.substring(0, index1);
		//}
		//alert(' ---1 '+sub_url_atual);
		var nova_url = url_atual.replace(sub_url_atual,'')+parametro;
		//alert(' ---2 '+nova_url);
		window.location.href = nova_url.replace('#', '?');		
	} else {
		var ajax = openajax(); /* Chama a FunÃ§Ã£o que Instancia o AJAX */	
		//var carregando = document.getElementById('carregando');	
		//var conteudo = document.getElementById('conteudo');
		ajax.open("GET", pagina, true);
	    /* ajax.open = Abri uma SolicitaÃ§Ã£o ao Navegador */
	    /* GET = MÃ©todo Usado */
	    /* plink = pagina que tratara o solicitado */
	    /* true = Assicrono ou nÃ£o = Dando o Refresh no Browser ou Nao*/
	    ajax.onreadystatechange = function() {
	        /* ajax.onreadystatechange = O que ele fara de acordo com o tempo de execuaÃ§Ã£o*/
	        if (ajax.readyState < 4) {
	            //carregando.style.display = 'block';
				//conteudo.style.display = 'none';
				/* ajax.readystate = Estado que se encontra a RequisiÃ§Ã£o*/			
	        }
	        if (ajax.readyState == 4) {
	            if (ajax.status == 200) {
					var res = ajax.responseText;
					
					//alert(url_atual);              
					//carregando.style.display = 'none';	
					//conteudo.style.display = 'block';
					//alert(res);				
					//conteudo.innerHTML = res;					
					extraiScript(res);
					carrega_carrinho('carrega_carrinho.php');
					//addFancyBox();			
	            }
	        }        
	    }
	    ajax.send(null);
	}
}
/*##################################################################################################*/

/*############# FUNÃ‡ÃƒO CARREGA PAGINAS DO CONTEÃšDO PAGINAS SEM RELOAD #############*/
function carrega_dados (){
	var ajax = openajax(); /* Chama a FunÃ§Ã£o que Instancia o AJAX */	
	ajax.open("GET", 'confirma_pedido.php', true);
    /* ajax.open = Abri uma SolicitaÃ§Ã£o ao Navegador */
    /* GET = MÃ©todo Usado */
    /* plink = pagina que tratara o solicitado */
    /* true = Assicrono ou nÃ£o = Dando o Refresh no Browser ou Nao*/
    ajax.onreadystatechange = function() {
        /* ajax.onreadystatechange = O que ele fara de acordo com o tempo de execuaÃ§Ã£o*/
        if (ajax.readyState == 4) {
            if (ajax.status == 200) {
				var res = ajax.responseText;
				document.getElementById('ref_transacao').value = res;
				document.getElementById('form_pag_seguro').submit();
				//alert(res);
            }
        }        
    }
    ajax.send(null);
}
/*##################################################################################################*/

/*############# FUNÃ‡ÃƒO CARREGA PAGINAS DO CONTEÃšDO PAGINAS SEM RELOAD #############*/
function verifica_cep(campo){
	var campo1 = campo;
	var campo_ = document.getElementById(campo1);
	var cep = campo_.value;
	cep = cep.replace('-', '');
	
	if(cep != '') {
	
	if(cep.length == 8) {
//		var ajax = openajax(); /* Chama a FunÃ§Ã£o que Instancia o AJAX */	
//		ajax.open("GET", 'verifica_cep.php?cep='+cep, true);
//	    /* ajax.open = Abri uma SolicitaÃ§Ã£o ao Navegador */
//	    /* GET = MÃ©todo Usado */
//	    /* plink = pagina que tratara o solicitado */
//	    /* true = Assicrono ou nÃ£o = Dando o Refresh no Browser ou Nao*/
//	    ajax.onreadystatechange = function() {
//	        /* ajax.onreadystatechange = O que ele fara de acordo com o tempo de execuaÃ§Ã£o*/
//	        if (ajax.readyState == 4) {
//	            if (ajax.status == 200) {
//					var res = ajax.responseText;
//					if(res == '0') {
//						alert('O CEP informado é inválido.');
//						document.getElementById('sit_cep').value = '0';
//						//campo_.focus();
//						return;
//					} else {
						document.getElementById('sit_cep').value = '1';
						return;
//					}
//					//document.getElementById('ref_transacao').value = res;
//					//document.getElementById('form_pag_seguro').submit();
//					alert(res);
//	            }
//	        }        
//	    }
//	    ajax.send(null);
	} else {
		alert('O CEP informado é inválido.');
		//campo_.focus();
		return;
	}
	
	}
}
/*##################################################################################################*/


/*############# FUNÃ‡ÃƒO CARREGA PAGINAS DO CONTEÃšDO PAGINAS SEM RELOAD #############*/
function carrega_carrinho(pagina){
	var ajax = openajax(); /* Chama a FunÃ§Ã£o que Instancia o AJAX */	
	//var carregando = document.getElementById('carregando');	
	//var conteudo = document.getElementById('div_carrinho');
	ajax.open("GET", pagina, true);
    /* ajax.open = Abri uma SolicitaÃ§Ã£o ao Navegador */
    /* GET = MÃ©todo Usado */
    /* plink = pagina que tratara o solicitado */
    /* true = Assicrono ou nÃ£o = Dando o Refresh no Browser ou Nao*/
    ajax.onreadystatechange = function() {
        /* ajax.onreadystatechange = O que ele fara de acordo com o tempo de execuaÃ§Ã£o*/
        if (ajax.readyState < 4) {
            //carregando.style.display = 'block';
			//conteudo.innerHTML = '';
			/* ajax.readystate = Estado que se encontra a RequisiÃ§Ã£o*/			
        }
        if (ajax.readyState == 4) {
            if (ajax.status == 200) {
				var res = ajax.responseText;               
				//carregando.style.display = 'none';	
				//conteudo.innerHTML = 'block';				
				//conteudo.innerHTML = res;				
            }
        }        
    }
    ajax.send(null);
}
/*##################################################################################################*/

function ajax(url) 
{ 
	req = null; 
	// Procura por um objeto nativo (Mozilla/Safari) 
	if (window.XMLHttpRequest) { 
		req = new XMLHttpRequest(); 
		req.onreadystatechange = processReqChange; 
		req.open("GET",url,true); 		
		req.send(null); 
	// Procura por uma versÃ£o ActiveX (IE) 
	} else if (window.ActiveXObject) { 
		req = new ActiveXObject("Microsoft.XMLHTTP"); 
		if (req) { 
			req.onreadystatechange = processReqChange; 
			req.open("GET",url,true);			
			req.send(); 
		} 
	} 
} 
function processReqChange() 
{ 
	alert(req.readyState);
	alert(req.status);
	// apenas quando o estado for "completado" 
	//if (req.readyState == 4) { 
		// apenas se o servidor retornar "OK" 
		//if (req.status ==200) { 
			// procura pela div id="pagina" e insere o conteudo 
			// retornado nela, como texto HTML 
			//document.getElementById('pagina').innerHTML = req.responseText; 
		//} else { 
			alert("Houve um problema ao obter os dados:n" + req.statusText); 
		//} 
	//} 
} 

function MudaConteudo(objeto){
	var descricao = document.getElementById("btn_descricao");	
	var dados = document.getElementById("btn_dados");	
	var itens = document.getElementById("btn_itens");
	
	document.getElementById('div_texto_descricao').style.display="none";
	document.getElementById('div_texto_dados').style.display="none";
	document.getElementById('div_texto_itens').style.display="none";
	
	if(objeto=="btn_descricao"){
		document.getElementById("div_texto_descricao").style.display="block";
		descricao.className="botao_descricao_hover";
		dados.className="botao_dados";
		itens.className="botao_itens";
	}else if(objeto=="btn_dados"){
		document.getElementById("div_texto_dados").style.display="block";
		dados.className="botao_dados_hover";
		descricao.className="botao_descricao";
		itens.className="botao_itens";
	}else {
		document.getElementById("div_texto_itens").style.display="block";
		itens.className="botao_itens_hover";
		descricao.className="botao_descricao";
		dados.className="botao_dados";
	}
}
function carregar_div(mostrar_sub) {
	var div = document.getElementById(mostrar_sub);
	if ( div.style.display != "none" ) {
		div.style.display = 'none';			
	}
	else {
		div.style.display = "";					
	}
}

/*==================================================================================
	Funcoes para mascara de objetos CEP, CNPJ, CPF, INDENTIDADE E TELEFONE	
==================================================================================== */
function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function telefonem(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que nÃ£o Ã© dÃ­gito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parÃªnteses em volta dos dois primeiros dÃ­gitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hÃ­fen entre o quarto e o quinto dÃ­gitos
    return v
}

function cpfm(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que nÃ£o Ã© dÃ­gito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dÃ­gitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dÃ­gitos
                                             //de novo (para o segundo bloco de nÃºmeros)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hÃ­fen entre o terceiro e o quarto dÃ­gitos
    return v
}

function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que nÃ£o Ã© dÃ­gito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse Ã© tÃ£o fÃ¡cil que nÃ£o merece explicaÃ§Ãµes
    return v
}

function cepm(v){
    v=v.replace(/D/g,"")                //Remove tudo o que nÃ£o Ã© dÃ­gito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse Ã© tÃ£o fÃ¡cil que nÃ£o merece explicaÃ§Ãµes
    return v
}

function cnpjm(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que nÃ£o Ã© dÃ­gito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dÃ­gitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dÃ­gitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dÃ­gitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hÃ­fen depois do bloco de quatro dÃ­gitos
    return v
}


function site(v){
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}

function data(v){
	v=v.replace(/\D/g,"") 
	v=v.replace(/(\d{2})(\d)/,"$1/$2") 
	v=v.replace(/(\d{2})(\d)/,"$1/$2") 
	return v
}


/* =============================================================================================
	 FUNCAO PARA DESABILITAR O ENTER DE UM CAMPO TEXT	
================================================================================================ */
function handleEnter (field, event) {
        var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
        if (keyCode == 13) {
            var i;
            for (i = 0; i < field.form.elements.length; i++)
                if (field == field.form.elements[i])
                    break;
            i = (i + 1) % field.form.elements.length;
            return false;
        } 
        else
        return true;
    }    
	
function Calculo_Frete() {		
		
	if($('#cep').val() != $('#cep_informado').val() || $('input:radio[name=tipo_frete]:checked').val() != $('#tipo_frete_selecionado').val())	
	
	window.location = '?p=carrinho&op=frete&destino=' + $('#cep').val() + '&tipo_frete_selecionado=' + $('input:radio[name=tipo_frete]:checked').val();
		
}

function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if((tecla > 47 && tecla < 58)) return true;
    else{
    if (tecla != 8) return false;
    else return true;
    }
}

function verifica_dados(){	
	missinginfo = "";
	if ((document.frm_cadastro.login_cad.value == "") || 
	(document.frm_cadastro.login_cad.value.indexOf('@') == -1) || 
	(document.frm_cadastro.login_cad.value.indexOf('.') == -1)) {
	  missinginfo += "\n     -  E-mail inválido";
	}
	if (document.frm_cadastro.senha_cad.value == "") {
	  missinginfo += "\n     -  Senha";
	}
	if (document.frm_cadastro.repete_senha.value == "") {
	  missinginfo += "\n     -  Confirmação de senha";
	}
	if (document.frm_cadastro.cep_cad.value == "") {
	  missinginfo += "\n     -  CEP";
	}
	if (document.frm_cadastro.sit_cep.value == "0") {
	  missinginfo += "\n     -  CEP INVÁLIDO";
	} 
	if (document.frm_cadastro.senha_cad.value != document.frm_cadastro.repete_senha.value) {
	  missinginfo += "\n     -  As duas senhas não são iguais";
	}	
	if (missinginfo != "") {
	  missinginfo ="                                \n" +
	  "Existe algum erro nos seguintes campos:\n" +
	  missinginfo + "\n                               " +
	  "\nPreencha-os novamente e clique em Me cadastrar agora!.";
	  alert(missinginfo);
	  return false;
	} else {		
		$.post(
			'ajax_verifica_cep.php',
			{
				cep_cad : document.frm_cadastro.cep_cad.value
			},
			function(data) {
				if(data.rows > 0) {					
					document.getElementById('frm_cadastro').submit();					
				} else {
					alert("CEP INVÁLIDO!");					
				}
			
			}, "json"
		);
	} 
}

	function verificaSenha(senha1, senha2){
		if(senha1 != senha2){
			alert("Verifique se as duas senhas estão idênticas!");			
		}else{
			document.getElementById('sua_senha').submit();
		}			
	}
	
	function verificaEmail(){
		missinginfo = "";
		if ((document.seu_login.login.value == "") || 
			(document.seu_login.login.value.indexOf('@') == -1) || 
			(document.seu_login.login.value.indexOf('.') == -1)) {
			missinginfo += "\n     -  E-mail inválido";
			alert(missinginfo);
		}else{
			document.getElementById('seu_login').submit();
		}	
	}
	
function somenteNumeros(obj,n,virg){
	pos = obj.value.length-1;
	valor = obj.value.substr(0,pos-n);
	if(obj.value.charCodeAt(pos) == 44 && virg == '1'){
		obj.value = valor;
		obj.value += ".";
	}else if(obj.value.charCodeAt(pos) == 46 && virg == '1'){
		retorna = true;
	}else if((obj.value.charCodeAt(pos) < 48)||(obj.value.charCodeAt(pos) > 57)){
		obj.value = valor;
	}else{
		retorna = true;
	}
}

function CPFCNPJ(numCIC) {
	numCIC = numCIC.replace(".","");
	numCIC = numCIC.replace(".","");
	numCIC = numCIC.replace(".","");
	numCIC = numCIC.replace("-","");	
	numCIC = numCIC.replace("/","");	
	//alert(numCIC);
	var numDois = numCIC.substring(numCIC.length-2, numCIC.length);
	var novoCIC = numCIC.substring(0, numCIC.length-2);
	switch (numCIC.length){
		 case 11 :
		  numLim = 11;
		  break;
		 case 14 :
		  numLim = 9;
		  break;
		 default : return false;
	}
	var numSoma = 0;
	var Fator = 1;
	for (var i=novoCIC.length-1; i>=0 ; i--) {
	 Fator = Fator + 1;
	 if (Fator > numLim) {
	  Fator = 2;
	 }
	 numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
	}
	numSoma = numSoma/11;
	var numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
	   if (numResto > 1) {
	 numResto = 11 - numResto;
	   }
	   else {
	 numResto = 0;
	   }
    
	//-- Primeiro dígito calculado.  Fará parte do novo cálculo.
	   
	   var numDigito = String(numResto);
	   novoCIC = novoCIC.concat(numResto);
	   //--
	numSoma = 0;
	Fator = 1;
	for (var i=novoCIC.length-1; i>=0 ; i--) {
	 Fator = Fator + 1;
	 if (Fator > numLim) {
	  Fator = 2;
	 }
	 numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
	}
	numSoma = numSoma/11;
	numResto = numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
	   if (numResto > 1) {
	 numResto = 11 - numResto;
	   }
	   else {
	 numResto = 0;
	   }
	//-- Segundo dígito calculado.
	numDigito = numDigito.concat(numResto);
	if (numDigito == numDois) {
	 return true;
	}
	else {
	 return false;
	}
}

function verifica(){
	if(document.frm_cadastro.e_mail.value == ''){
		alert ('E-mail Inválido!'); 
		return false
	}	
	if(document.frm_cadastro.sexo.value == ''){
		alert ('Sexo Inválido!'); 	
		return false
	}	
	if(document.frm_cadastro.nome.value == ''){
		alert ('Campo Nome em branco!'); 	
		return false
	}	
	if(document.frm_cadastro.rg.value == ''){
		alert ('Campo RG em branco!');
		return false
	}	
	if (! CPFCNPJ(document.frm_cadastro.cpf.value)){
	   alert ('CPF Inválido!');
	   return false;
	}  
	
	if(document.frm_cadastro.endereco.value == ''){
		alert ('Campo Endereco em branco!');
		return false;
	}	
	if(document.frm_cadastro.numero.value == ''){
		alert ('Campo Número em branco!'); 
		return false;
	}	
	if(document.frm_cadastro.bairro.value == ''){
		alert ('Campo Bairro em branco!'); 
		return false;
	}	
	if(document.frm_cadastro.ddd_fixo.value == ''){
		alert ('Campo DDD em branco!'); 	
		return false;
	}	
	if(document.frm_cadastro.numero_fixo.value == ''){
		alert ('Campo Telefone em branco!'); 
		return false;
	}
	if(document.frm_cadastro.sit_cep.value == '0'){
		alert ('O CEP informado é inválido!');
		document.frm_cadastro.cep_cad.focus();
		return false;
	}
	
	return true;
} 	


function verifica2(){
	if(document.frm_cadastro.e_mail.value == ''){
		alert ('E-mail Inválido!'); 
		return false
	} 
	if(document.frm_cadastro.nome_fantasia.value == ''){
		alert ('Campo Nome em branco!'); 	
		return false
	}	
	if(document.frm_cadastro.razao_social.value == ''){
		alert ('Campo Sobrenome em branco!'); 	
		return false
	}	
	if (! CPFCNPJ(document.frm_cadastro.cnpj.value)){
	   alert ('CPF Inválido!');
	   return false;
	} else {
		return true;
	} 
	
	if(document.frm_cadastro.endereco.value == ''){
		alert ('Campo Endereco em branco!');
		return false;
	}	
	if(document.frm_cadastro.numero.value == ''){
		alert ('Campo Número em branco!'); 
		return false;
	}	
	if(document.frm_cadastro.bairro.value == ''){
		alert ('Campo Bairro em branco!'); 
		return false;
	}	
	if(document.frm_cadastro.ddd_fixo.value == ''){
		alert ('Campo DDD em branco!'); 	
		return false;
	}	
	if(document.frm_cadastro.numero_fixo.value == ''){
		alert ('Campo Telefone em branco!'); 
		return false;
	}
	if(document.frm_cadastro.sit_cep.value == '0'){
		alert ('O CEP informado é inválido!'); 
		document.frm_cadastro.cep_cad.focus();
		return false;
	}
}

function ValidaEmailCartao()
{ 
  var obj = document.frm.e_mail;  
  var txt = obj.value; 
  
  if ((txt.length != 0) && ((txt.indexOf("@") < 1) || (txt.indexOf('.') < 7)))
  {
    alert('Email incorreto');
	obj.focus();
	return false;	
  }   
  return true;  
}

function verifica_cartao(){
	if(document.frm.nome.value == ''){
		alert ('Nome Inválido!'); 
		return false
	}
	if(document.frm.e_mail.value == ''){
		alert ('E-mail Inválido!');
		return false; 				
	}
	if(!ValidaEmailCartao())return false;			 
	if(document.frm.sexo.value == ''){
		alert ('Campo Sexo Inválido!'); 	
		return false
	}	
	if(document.frm.estado_civil.value == ''){
		alert ('Campo Estado Civil Inválido!'); 	
		return false
	}	
	if(document.frm.data_nascimento.value == ''){
		alert ('Campo Data de Nascimento Inválido!');
		return false;
	}
	if(document.frm.nacionalidade.value == ''){
		alert ('Campo Nacionalidade Inválido!');
		return false;
	}
	if(document.frm.uf.value == ''){
		alert ('Campo UF Inválido!');
		return false;
	}
	if(document.frm.nome_mae.value == ''){
		alert ('Campo Nome da Mãe Inválido!');
		return false;
	}
	if(document.frm.nome_pai.value == ''){
		alert ('Campo Nome do Pai Inválido!');
		return false;
	}
	if(document.frm.identidade.value == ''){
		alert ('Campo Identidade Inválido!');
		return false;
	}
	if(document.frm.orgao_emissor.value == ''){
		alert ('Campo Órgão Emissor Inválido!');
		return false;
	}
	if(document.frm.uf_emissor.value == ''){
		alert ('Campo UF Emissor Inválido!');
		return false;
	}
	if(document.frm.data_expedicao.value == ''){
		alert ('Campo Data Expedição Inválido!');
		return false;
	}		
	if (!CPFCNPJ(document.frm.cpf.value)){
	   alert ('CPF Inválido!');
	   return false;
	}
	if(document.frm.grau_instrucao.value == ''){
		alert ('Campo Grau de Instrução Inválido!');
		return false;
	}  else {
		return true;	
	} 			
	
}

function fechaPedidoBoleto() {
	
	$.post(
		'confirma_pedido.php', 
	  	{},
	   	function(data) {
	   		
	   		$.post(
				'gera_boleto.php', 
			  	{},
			   	function(data) {
			   		
			   		window.location = "?p=finalizar_pedido";
			   		
			   	}
			);
	   		
	   	}
	);
	
}

function trocaTipoFrete() {
	
	var tipoFrete = $('#combo_tipo_frete').val();
	
	var valorFrete = $('#valor_frete_' + tipoFrete).val();
	
	var subtotal = $('#subtotal').val();
	
	var desconto = $('#desconto').val();
	
	$('#item_frete_1').val(valorFrete * 100);
	
	$('#valor_frete').html('R$ ' + number_format(valorFrete, 2, ',', '.'));
	
	$('#total_pedido').html('R$ ' + number_format(parseFloat(valorFrete) + parseFloat(subtotal) - parseFloat(desconto), 2, ',', '.'));
	
	$.post(
		'ajax_tipo_frete.php', 
	  	{
			tipo_frete : tipoFrete,
			valor_frete : valorFrete
	   	},
	   	function(data) {}
	);
	
}

function number_format(number, decimals, dec_point, thousands_sep) {
    number = (number+'').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }    return s.join(dec);
}

function verificaCPFDuplicado(varCpf) {
	
	$.post(
		'ajax_verifica_cpf.php', 
	  	{
			cpf : varCpf
	   	},
	   	function(data) {
	   		
	   		if(!isNaN(data)) {
	   			if(parseFloat(data) == 0) {
	   				document.frm_cadastro.submit();
	   				return true;
	   			}
	   		}
	   		
	   		alert("CPF/CNPJ já cadastrado no sistema!");
	   		
	   	}
	);
	
}


function consultaCEP(varCep){
	
	if(varCep != "") {
	
		$.post(
			'ajax_consulta_cep.php',
		  	{
				cep_cad : varCep
		   	},
		   	function(data) {		   		
		   		
		   		$("#endereco").val(data.endereco);		   		
		   		$("#bairro").val(data.bairro);
		   		$("#cidade option:selected").text(data.cidade);
		   		$("#cidade option").val(data.id_cidade);
		   		$("#estado option:selected").text(data.uf);
		   		$("#estado option").val(data.id_uf);
		   		$("#complemento").val(data.complemento);		   		   		
		   		
		   	}, 'json'
		);
		
	}
}
