﻿function checkNavegador (){
  try{
	return new XMLHttpRequest();
  }catch(ee){
    try{
	  return new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
	  try{
		 return new ActiveXObject("Microsoft.XMLHTTP");
	   }catch(E){
		 return false;
	   }
   }
  }
	
}

function clearInputFrete(){
	// Exclui os elementos caso possuir 
	var elm1 = document.getElementById('vlr_pac'); 
	var elm2 = document.getElementById('vlr_sedex'); 
	var elm3 = document.getElementById('vlr_e_sedex'); 
	if (elm1 && elm2) {
		elm1.removeNode(true); 
		elm2.removeNode(true);
		if (elm3)
			elm3.removeNode(true); 
	}
	
}
function calculaFrete(cep_destino){
	$("#btnFinalizaCompra").hide();
	
    var cep_destino	= (cep_destino.lenght > 0 ? cep_destino.replace("-", "") : $("#cep_destino").val());
	var newCep		= cep_destino.substring(0,5)+"-"+cep_destino.substring(5,9);
	// desmarca a opção do tipo de frete 	
	checkFalseRadio("tp_frete");

	if (cep_destino.length == 8){
		var msg	= "";
		var parametros 	= "";
		clearInputFrete();
		// Formata o cep e encaminha para a pagina em php 
		parametros	= "cep_destino="+cep_destino.replace("-", "");
		xmlhttp 	= null; // Libera a variavel 
		xmlhttp = checkNavegador(); // Verifica qual o navegador esta sendo utilizado 
		xmlhttp.open("POST", "./e-commerce/consultaFrete.php", true);	
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
		xmlhttp.setRequestHeader("Pragma", "no-cache");
		xmlhttp.onreadystatechange =  processaCalculoFrete;// Processamento do sistema 
		xmlhttp.send(parametros);
	} else {
		alert("CEP inválido");
		$("#cep_destino").focus();
		$("#aguarde_car").html("");
		return false;
	}
}

function processaCalculoFrete(){
	// Enquanto estiver realizando a solicitação ao servidor 
	if (xmlhttp.readyState == 1) {
		$("#resultCalcFrete").html("<center><br><img src='./e-commerce/imagens/carregando.gif' border=0><br> <span style='color:#FF0000; font-size:11px;'>Aguarde pesquisando!</span></center>");
	}
	// Apos ter carregado a pagina 
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			$("#resultCalcFrete").html(xmlhttp.responseText);
		} else 
			$("#resultCalcFrete").html("Problemas ao carregar o arquivo.");
	}
}


function limpaVarAut(){
	$("#cxAutUserErroLogin").css("background","");
	$("#cxAutUserErroLogin").html("");
//	$("#cxAutUserErroLogin").css("height","");
}

// Vereficasse se o usuario existe ou nao 

function autenticaUser(){
	var email = $("#email").val();
	var senha = $("#senha").val();
	
	limpaVarAut(); // Limpa as divs e seus retornos 
	
	if (email.length == 0) {
	  alert(CkLoginALERTcmpemail);
	  $("#email").focus();
	  return false;
	}
	
	// Caso seja queira se logar 
//	if ($("#esquecisenha")[0].checked == false){ 
		if (senha.length == 0) {
		  alert(VldPwdALERTcamposenha);
		  $("#senha").focus();
		  return false;
		}
	
		if (!checkEmail(email)) {
		  alert(CkLoginALERTcmpemailinc); 
		  $("#senha").focus();
		  return false;
		}
		
	//	$("#autUser").get(0).disabled	= true;
		// Inicia a consulta no servidor 
		xmlhttp = checkNavegador();
		xmlhttp.open("POST", "./e-commerce/actions/autenticaUser.php", true);	
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
		xmlhttp.setRequestHeader("Pragma", "no-cache");
		xmlhttp.onreadystatechange = function (){
				if (xmlhttp.readyState == 4) {
					if (xmlhttp.status == 200) {
						var retXml = xmlhttp.responseXML.getElementsByTagName('main');
//						alert(xmlhttp.responseText)
						if (retXml.length){
							var erro	= retXml[0].getElementsByTagName('erro');
							if (erro[0].firstChild.nodeValue == 0){
								location.replace("confirmacao.php");
							} else {
								$("#cxAutUserErroLogin").css("background","#FFFF99");
								$("#cxAutUserErroLogin").css("color","#CC0000");
								$("#cxAutUserErroLogin").html('<center>E-mail ou Senha inválidos!</center>');
							}
						}
					} else {
					   alert("Problemas ao carregar o arquivo.");
					}
				}
		};
		xmlhttp.send("email="+email+"&senha="+senha);
}

function processReqChangeEsqSenha() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			var retXml = xmlhttp.responseXML.getElementsByTagName('main');
			if (retXml.length){
				var erro	= retXml[0].getElementsByTagName('erro');
				$("#cxAutUserErroLogin").css("height","26px");
				$("#cxAutUserErroLogin").css("background","#FFFF99");
				$("#cxAutUserErroLogin").css("color","#CC0000");				
				if (erro[0].firstChild.nodeValue == 0){
					$("#cxAutUserErroLogin").html('   <img src="./e-commerce/imagens/warning_48.gif" alt="Atenção!" width="24" height="22" align="absmiddle" /> Sua senha foi enviada para o seu e-mail!');
				} else {
					$("#cxAutUserErroLogin").html('   <img src="./e-commerce/imagens/warning_48.gif" alt="Atenção!" width="24" height="22" align="absmiddle" /> O E-mail não esta cadastrado no sistema!');
				}
				$("#autUser").get(0).disabled	= false;
			}
		} else {
		   alert("Problemas ao carregar o arquivo.");
		}
	}

}



// Vereficasse se o usuario ja se encontra cadastrado no banco de dados 
function checkUserNew(){
	var email 	= $("#email_new").val();
	var cep 	= $("#cep1").val() +''+ $("#cep2").val();
	
	limpaVarAut(); // Limpa as divs e seus retornos 
	
	if (email.length == 0) {
	  alert(CkLoginALERTcmpemail);
	  $("#email_new").focus();
	  return false;
	}
	
	if (!checkMail(email)) {
	  alert(CkLoginALERTcmpemailinc); 
	  $("#email_new").focus();
	  return false;
	}
	
	if (cep.length < 8){	  
		alert(ValPesqCepALERTcepinvalido); 
		$("#cep1").focus();
		return false;		
	} 
	
	$("#cadNewUser").get(0).disabled	= true;
	// Inicia a consulta no servidor 
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/checkUser.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = processCheckUserNew;
	xmlhttp.send("email="+email+"&cep="+cep);
	
}

function processCheckUserNew() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			var retXml = xmlhttp.responseXML.getElementsByTagName('main');
			if (retXml.length){
					var erro	= retXml[0].getElementsByTagName('erro');
					if (erro[0].firstChild.nodeValue == 0)
						location.replace("check_usuario.php");
					// Caso o email já esteja cadastrado no sistemaa.
					if (erro[0].firstChild.nodeValue == 1){
						$("#cxAutUserErroLogin").css("height","26px");						
						$("#cxAutUserJaCadErro").css("background","#FFFFCC");
						$("#cxAutUserJaCadErro").css("color","#CC0000");						
						$("#cxAutUserJaCadErro").html('   <img src="./e-commerce/imagens/warning_48.gif" alt="Atenção!" width="24" height="22" align="absmiddle" /> Este e-mail já se encontra cadastrado no sistema! caso tenha esquecido sua senha clique em ESQUECEU A SENHA');
					}
					// Caso o cep do cliente não existe 
					if (erro[0].firstChild.nodeValue == 2){
						$("#cxAutUserErroLogin").css("height","26px");						
						$("#cxAutUserJaCadErro").css("background","#FFFFCC");
						$("#cxAutUserJaCadErro").css("color","#CC0000");						
						$("#cxAutUserJaCadErro").html('   <img src="./e-commerce/imagens/warning_48.gif" alt="Atenção!" width="24" height="22" align="absmiddle" /> CEP inválido!');
					}
					
				$("#cadNewUser").get(0).disabled	= false;
			}
		} else {
		   alert("Problemas ao carregar o arquivo.");
		}
	}

}


function autUserMinhaConta(){
	var email = $("#email").val();
	var senha = $("#senha").val();
	
	if (email.length == 0) {
	  alert(CkLoginALERTcmpemail);
	  $("#email").focus();
	  return false;
	}

	if (senha.length == 0) {
	  alert(VldPwdALERTcamposenha);
	  $("#senha").focus();
	  return false;
	}

	if (!checkMail(email)) {
	  alert(CkLoginALERTcmpemailinc); 
	  $("#senha").focus();
	  return false;
	}
	
	// Caso seja queira se logar 
	// Inicia a consulta no servidor 
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/actions/autenticaUser.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = processReqAutMinhaConta;
	xmlhttp.send("email="+email+"&senha="+senha);
	
	
}

function processReqAutMinhaConta() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			var retXml = xmlhttp.responseXML.getElementsByTagName('main');
			if (retXml.length){
					var erro	= retXml[0].getElementsByTagName('erro');
					if (erro[0].firstChild.nodeValue == 0)
						location.replace("minha_conta.php");
					else {
						$("#cxAutUserJaCadErro").css("background","#FFFFCC");
						$("#cxAutUserJaCadErro").html("E-mail ou Senha inválidos!");
					}
			}
		} else {
		   alert("Problemas ao carregar o arquivo.");
		}
	}

}

function checkUserCadNew(){
	var email = $("#email").val();
	// Inicia a consulta no servidor 
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./actions/cadastro_user.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = processCheckUserCadNew;
	xmlhttp.send("op=1&email="+email);
}

function processCheckUserCadNew() {
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			var retXml = xmlhttp.responseXML.getElementsByTagName('main');
			if (retXml.length){
				var erro	= retXml[0].getElementsByTagName('erro');
				if (erro[0].firstChild.nodeValue == 0)
					document.frmCadastro.submit();
				else {
					alert("O email ja se encontra cadastrado no nosso sistema!");
				}
			}
		} else {
		   alert("Problemas ao carregar o arquivo.");
		}
	}

}

function sendFormTipo_pgto(valor){
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/actions/edtFormaPgto.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function (){
									if (xmlhttp.readyState == 4) {
										if (xmlhttp.status == 200) {
											var retXml = xmlhttp.responseXML.getElementsByTagName('main');
											if (retXml.length){
												var total	= retXml[0].getElementsByTagName('valor_parcial');
												// Verifica se o cliente possui ou nao desconto 
												$("#dezPorcDescontoCar").html((valor == 2 || valor == 5 ? "10 % de Desconto" : ""));
												$("#totalCompraRet").html(total[0].firstChild.nodeValue+" ");
												if (checkOpcaoFrete()) {
													$("#cxContComprandoFinalizar").html('<img src="./e-commerce/imagens/carrinho_compra_final.gif" alt="Finalizar a Compra" name="finaliza_compra" width="128" height="47" border="0" id="finalizaCompraRodape" onclick="return check_opcaopag();" class="linkImg"/>');
												}
											}	
										}
									}
			
		};
	xmlhttp.send("tipo_pgto="+valor);		
}

function processFormTipoPgto(){
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.status == 200) {
			var retXml = xmlhttp.responseXML.getElementsByTagName('main');
			if (retXml.length){
				
			}
		}
	}
}

function setTamanhoProduto(codDiv,tamanho,qtdEstoque,codTamProduto){
	// Seleciona o tamanho selecionado pelo usuario
	for (var i=0; i <= tamArray; i++){
		if (i == codDiv)
			$("#cxTamanhoNum"+i).css("border","1 solid #0066CC");
		else 
			$("#cxTamanhoNum"+i).css("border","0");
	}
	if (qtdEstoque > 0) {
		// Realiza a consulta no banco para ver se o determinado produto possui salto
		document.getElementById("quantidade").options.length = 0;
		for (var i=1; i <= qtdEstoque; i++){
			novaOp 	  		= document.createElement('option');
			novaOp.value 	= i;
			novaOp.text  	= i;
			document.getElementById("quantidade").options.add(novaOp);
		}
		document.getElementById("quantidade").options[0].selected = true;
		document.getElementById("quantidade").disabled	= false;
		$("#cxDetalheProdutoQtdBotao").html('<img src="./e-commerce/imagens/botao_comprar.jpg" onclick="addCarrinho(\''+$("#uId").val()+'\',\''+$("#img_produto").val()+'\',\''+$("#cod_produto").val()+'\',\''+codTamProduto+'\',\''+tamanho+'\')" class="linkImg"/>');
	} else {
		document.getElementById("quantidade").options.length = 0;
		novaOp 	  		= document.createElement('option');
		novaOp.value 	= 0;
		novaOp.text  	= 0;
		document.getElementById("quantidade").options.add(novaOp);
		document.getElementById("quantidade").disabled	= true;	
		$("#cxDetalheProdutoQtdBotao").html('<img src="./e-commerce/imagens/botao_avise-me.jpg" alt="Esgotado - Avise-me quando chegar" class="linkImg"  onclick="janelaCenter(\'aviseme.php?id_tam_produto='+codTamProduto+'\',\'Aviso\',\'\',520,350);"/>');	
	}
}

function addCarrinho(uId,img_produto,cod_produto,codTamProduto,tamanho){
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/actions/addCarrinho.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function (){
									if (xmlhttp.readyState == 4) {
										if (xmlhttp.status == 200) {
											location.href = "carrinho.php";
										}
									}
			
		};
	xmlhttp.send("uId="+uId+"&img_produto="+img_produto+"&cod_produto="+cod_produto+"&id_tamanho="+codTamProduto+"&desc_tam="+tamanho);	
}

function atualizaQtdCarrinho(qtd,cod_prod,id_tamanho){
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/attCarrinho.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function (){
									if (xmlhttp.readyState == 4) {
										if (xmlhttp.status == 200) {
											if (xmlhttp.responseText == 0)
												location.href = "carrinho.php";
											else {
												var input = document.createElement("input");
												input.setAttribute("name","erroQtd");
												input.setAttribute("type","hidden");
												input.setAttribute("value","1");
												document.body.appendChild(input);
												
												$("#erroCxCarrinhoTitulo").css('display','block');
												$("#cxContComprandoFinalizar").html("");
												var erro = '<img src="./e-commerce/imagens/msg_error_limit_estoque.gif" alt="Alerta - Quantidade excedeu a quantidade disponivel no estoque!" width="22" height="22" align="absmiddle" />';
												erro +=' Ocorreu um Erro! Corrija as seguintes informações:<br><br>';
												erro += 'Quantidade informada excedeu a quantidade disponivel no estoque!<br><br>';
												$("#erroCxCarrinhoTitulo").html(erro);
											}
										}
									}
	};
	xmlhttp.send("qtd="+qtd+"&cod_prod="+cod_prod+"&id_tamanho="+id_tamanho);
}


function atualizaVlrFrete(valor,forma_envio){

	$("#cxContComprandoFinalizar").html('<img src="./e-commerce/imagens/carrinho_compra_final.gif" alt="Finalizar a Compra" name="finaliza_compra" width="128" height="47" border="0" id="finalizaCompraRodape" onclick="return check_opcaopag();" class="linkImg"/>');
}


function trocaEndEntrega(codigo){
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/actions/Endereco_entrega.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function (){
									if (xmlhttp.readyState == 4) {
										if (xmlhttp.status == 200) {
//											alert(xmlhttp.responseText)
											location.href = "iniciar_transacao.php";
										} else {
											alert('Erro ao tentar carregar o arquivo!')	
										}
									}
	};
	xmlhttp.send("action=4&uId="+codigo);		
}

function escFormaPgto(formaPgto){
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/actions/attFormaPgto.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function (){
									if (xmlhttp.readyState == 4) {
										if (xmlhttp.status == 200) {
											location.href = "iniciar_transacao.php";
										} else {
											alert('Erro ao tentar carregar o arquivo!')	
										}
									}
	};
	xmlhttp.send("formaPgto="+formaPgto);
}

function realizarPgtoDeposito(){
	$("#cadNewUser").get(0).disabled	= true;
	$("#cadNewUser").val("Aguarde Processando a informação!");
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/actions/RealizarPgto.php", false);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function (){
									if (xmlhttp.readyState == 4) {
										if (xmlhttp.status == 200) {
											location.href = "retorno_pgto.php";
										} else {
											alert('Erro ao tentar carregar o arquivo!')	
										}
									}
	};
	xmlhttp.send(null);
}

function realizarPgtoVisaNet(){
	$("#cadNewUser").get(0).disabled	= true;
	$("#cadNewUser").val("Aguarde Processando a informação!");
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/actions/VisaNet.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function (){
									if (xmlhttp.readyState == 4) {
										if (xmlhttp.status == 200) {
											var retXml = xmlhttp.responseXML.getElementsByTagName('main');
//											alert(xmlhttp.responseText);
											if (retXml.length){	
													var tid			= retXml[0].getElementsByTagName('tid')[0].firstChild.nodeValue;
													var orderid		= retXml[0].getElementsByTagName('orderid')[0].firstChild.nodeValue;
													$("#tid").val(tid); // Codigo de referencia do banco (VISANET)
													$("#orderid").val(orderid);
													document.frmPgtoVisaNet.submit();
												} // fim do if.length */
											
										} else {
											alert('Erro ao tentar carregar o arquivo!')	
										}
									}
	};
	xmlhttp.send("parcelas="+$("#parcelas").val());
}

function realizarPgtoMasterCard(){
	$("#cadNewUser").get(0).disabled	= true;
	$("#cadNewUser").val("Aguarde Processando a informação!");
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/actions/MasterCard.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function (){
									if (xmlhttp.readyState == 4) {
										if (xmlhttp.status == 200) {
											var retXml = xmlhttp.responseXML.getElementsByTagName('main');
//											alert(xmlhttp.responseText);
											if (retXml.length){	
													var cod_pedido		= retXml[0].getElementsByTagName('cod_pedido')[0].firstChild.nodeValue;
//													var parcMasterCard	= retXml[0].getElementsByTagName('parcMasterCard')[0].firstChild.nodeValue;
													
													$("#pedido").val(cod_pedido);
													document.frmPgtoMasterCard.submit();
												} // fim do if.length */
											
										} else {
											alert('Erro ao tentar carregar o arquivo!')	
										}
									}
	};
	xmlhttp.send("parcelas="+$("#parcelas").val());
}


/*
	Metodo criado para salvar o pagamento 
*/
function cadastrarPedido(){
	location.href = 'retorno_pgto.php?tp_pgto='+$("input[@name='tp_pgto']:checked").val();
/*	$.ajax({
		url			: "e-commerce/actions/RealizarPgto.php",
		dataType	: "text",
		type		: "POST",
		data		: 'tp_pgto='+$("input[@name='tp_pgto']:checked").val(), 
		success: function(text){
			location.href = 'retorno_pgto.php?tp_pgto='+$("input[@name='tp_pgto']:checked").val();
		}		
	});
*/
}

/* 
	Função para realizar a consulta da tamanho em relação a cor informada 
*/
var colecao = new Array();

function conCorRelTamanho(cod_produto,valor){
	var cor_produto = valor.value;
	limpaTodasInfoProd();
	
	if (cor_produto != "" ){
		xmlhttp = checkNavegador();
		xmlhttp.open("POST", "./e-commerce/actions/consultaEstoque.php", true);	
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
		xmlhttp.setRequestHeader("Pragma", "no-cache");
		xmlhttp.onreadystatechange = function (){
										if (xmlhttp.readyState == 4) {
											if (xmlhttp.status == 200) {
												// Transforma o primeiro caracter de uma string em maiusculo 
												$("#infoCorDetProduto").html(priLetraMaiusculo(url_decode(cor_produto)));
												
												/*
													Options Tamanho do Produto 
												*/
												document.getElementById("tamanho_produto").options.length = 0;
												novaOp 	  		= document.createElement('option');
												novaOp.value 	= 0;
												novaOp.text  	= "";
												document.getElementById("tamanho_produto").options.add(novaOp);
												/*
													options quantidade do produto 
												*/
												document.getElementById("qtd_produto").options.length = 0;
												novaOp 	  		= document.createElement('option');
												novaOp.value 	= 0;
												novaOp.text  	= "";
												document.getElementById("qtd_produto").options.add(novaOp);
												$("#qtd_produto").get(0).disabled = true;

												var retXml = xmlhttp.responseXML.getElementsByTagName('tamanho_qtd');
												var total_registro = retXml.length;

//												alert(xmlhttp.responseText)
	
												if (total_registro){	
													for (var i=0; i < total_registro; i++){
														var tamanho_produto = retXml[i].getElementsByTagName('tamanho_produto')[0].firstChild.nodeValue;
														var qtd_produto 	= retXml[i].getElementsByTagName('qtd_produto')[0].firstChild.nodeValue;
														novaOp 	  		= document.createElement('option');
														novaOp.value 	= tamanho_produto;
														novaOp.text  	= tamanho_produto;
														document.getElementById("tamanho_produto").options.add(novaOp);	
														colecao[tamanho_produto] = qtd_produto;
													}
													document.getElementById("tamanho_produto").options[0].selected = true;
													$("#tamanho_produto").get(0).disabled = false;
												}
	
												var img_produto 	= retXml[0].getElementsByTagName('img_produto');
												var total_registro 	= img_produto.length;
												
												if (img_produto[0].firstChild.nodeValue != 'null' && img_produto[0].firstChild.nodeValue != 0 ) {
													if (total_registro){	
														for (var i=0; i < total_registro; i++){
															$("#imgDetProduto").attr('src',"./imagens/produtos/med/"+img_produto[i].getElementsByTagName('img'+i)[0].firstChild.nodeValue);
														}
													}
												}
	
												// Atualiza a cor do produto no input cor_produto.
											/*	$("#cor_produto").val(cor_produto);
												$("#cod_produto").val(cod_produto);
												*/
	
											} else {
												alert('Erro ao tentar carregar o arquivo!')	
											}
										}
		};
		xmlhttp.send("act=1&cod_produto="+cod_produto+"&cor="+cor_produto);		
	} else {
		limpaTodasInfoProd();
	}
}

function conTamanhoRelQtd(tamanho){
	var tamanho = tamanho.value;

	if (tamanho !="" && tamanho != "0") {
		for ( key in colecao ) {
			if (key == tamanho)
				var qtd_estoque = colecao[key];
		}
		
		// Atualiza o tamanho do produto 
		$("#infoTamDetProduto").html(tamanho);
		
		// Monta o select de quantidades disponiveis no estoque 
		document.getElementById("qtd_produto").options.length = 0;
		novaOp 	  		= document.createElement('option');
		novaOp.value 	= 0;
		novaOp.text  	= "";
		document.getElementById("qtd_produto").options.add(novaOp);
		
		for (var i=1; i <= qtd_estoque; i++){
			novaOp 	  		= document.createElement('option');
			novaOp.value 	= i;
			novaOp.text  	= i;
			document.getElementById("qtd_produto").options.add(novaOp);
		}	
	
		document.getElementById("qtd_produto").options[0].selected = true;
		$("#qtd_produto").get(0).disabled = false;
		//$("#tamanho_produto").val(tamanho);
	} else {
		$("#imgBtnComprar").hide();
		$("#qtd_produto").get(0).disabled = true;
		$("#infoQtdDetProduto").html("");
	}
	
}

function conQtdRelProduto(quantidade){
	var quantidade = quantidade.value;
	if (quantidade > 0) {
		// Atualiza o tamanho do produto 
		$("#infoQtdDetProduto").html(quantidade);
		$("#imgBtnComprar").show();
	} else {
		$("#infoQtdDetProduto").html("");
		$("#imgBtnComprar").hide();
	}
}

function sendInfoCarrinho(){
//	alert();
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/actions/addCarrinho.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function (){
									if (xmlhttp.readyState == 4) {
										if (xmlhttp.status == 200) {
											//alert(xmlhttp.responseText)
											location.href = "carrinho.php";
										}
									}
			
		};
	xmlhttp.send("uId="+$("#cod_produto").val()+"&cor_produto="+url_encode($("#cor_produto").val())+"&tamanho_produto="+url_encode($("#tamanho_produto").val())+"&qtd_produto="+$("#qtd_produto").val());	

}

/*
	Função clica para zera todas as informações e desabilitar todos os botoes em caso de erro.
*/
function limpaTodasInfoProd(){
	$("#imgBtnComprar").hide();
	$("#tamanho_produto").get(0).disabled = true;
	$("#qtd_produto").get(0).disabled = true;
	// Atualiza a cor do produto no input cor_produto.
	$("#infoCorDetProduto").html("");
	$("#infoTamDetProduto").html("");
	$("#infoQtdDetProduto").html("");
	$("#tamanho_produto").val();
}

function validCampCadastro(){
	xmlhttp = checkNavegador();
	xmlhttp.open("POST", "./e-commerce/actions/validaCampos.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function (){
									if (xmlhttp.readyState == 4) {
										if (xmlhttp.status == 200) {
//											alert(xmlhttp.responseText)
											if (xmlhttp.responseText != "") {
												$("#msgErroCadastroCliente").css("background","#FFFFCC");
												$("#msgErroCadastroCliente").html("<b>Ocorreu os seguintes erros:</b><br>"+xmlhttp.responseText);
												location.replace("#erro");
												return false;
											} else {
												return true;	
											}
										} else {
											alert('Erro ao tentar carregar a pagina!')	
										}
									}
			
		};
	xmlhttp.send("act=1&cpf="+$("#cpf_cobranca").val()+"&nome="+$("#nome_cobranca").val()+"&email="+$("#email_cobranca").val()+"&telefone="+$("#telefone_cobranca").val());
}

/*
	Excluir item do meu carrinho de compras
*/
function excluirItemCarrinho(codigo,codigo_unico){
	xmlhttp = checkNavegador();
	xmlhttp.open ("POST", "./e-commerce/actions/Carrinho.php", true);	
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function (){
									if (xmlhttp.readyState == 4) {
										if (xmlhttp.status == 200) {
											//alert(xmlhttp.responseText)
											if (xmlhttp.responseText == "") {
												location.replace("?");
											} else {
												alert(xmlhttp.responseText)
											}
										} else {
											alert('Erro ao tentar carregar a pagina!')	
										}
									}
			
		};
	xmlhttp.send("action=1&uId="+codigo+"&codigo_unico="+codigo_unico);
	
}

function esqueciMinhaSenha()
{
	$.ajax({
		url			: "../actions/EsqueciMinhaSenha.php",
		dataType	: "text",
		type		: "POST",
		//clearForm	: true,
		data		: "email="+$("#email").val(),
		success:function(data) 
		{
			$("#msg_retorno").html(data);
			//alert(responseText);
			//alert("Seu orçamento foi enviado com sucesso!");
		}
	})
}
