
$(document).ready(function () {
	$('#pagina').hide();
	$('#firefox').hide();
	
	$('#total').hide();
	$('#nomeCli').hide();
	
	$("#txtTelefone").mask("(99)9999-9999");
	$("#txtCep").mask("99999-999");
	
	$.post("controle.php?opt=status_loja", function(data){
		if(data == 'true'){
			//alert("(!) True: Loja aberta!");
			$('#pagina').fadeIn(200);
			$('#firefox').fadeIn();
		}else{
			//alert("(X) False: Loja fechada!");
			window.location = "fechado.php";
		}
	});
	
	//carrega o email da sessão
	$.post("controle.php?opt=clicampo&campo=email", function(data){
		$("#txtEmail1").val('[Entre com seu endereço de email.]');
		if(data != 'null'){
			$("#txtEmail1").val(data);
		}
	});
	
	$("#txtEmail1").focus(function(){
		$('#cadObs').html('');
		$('#txtEmail1').css({border: '1px solid #AECCCE'});
		if($(this).val() == '[Entre com seu endereço de email.]'){
			$(this).val('');
		}
	});
	
	$("#txtEmail1").blur(function(){
		if($(this).val() == ''){
			$(this).val('[Entre com seu endereço de email.]');
		}
	});

	function validarEmail(valor) {
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
			//alert("O email informado deve ser um endereço '" + valor + "' deve ser válido. ");
			return (true)
		} else {
			$('#txtEmail1').css({border: '2px solid red'});
			$('#cadObs').css({color: 'red'});
			$('#cadObs').html('<span style="font-size:18px;">O e-mail informado é incorreto!</span>');
			//alert("O email informado é incorreto.");
			return (false);
		}
	}
	
	function deslogar(){
		gravaLog('Estou tentando deslogar');
		$.post("controle.php?opt=clearNoRed", function(data){
			gravaLog("deslogar data: " + data);
			if(data == 'true'){
				return true;
			}else{
				return false;
			}
		});
	}
	/** 
	 * função para efetuar o login
	 */

	function logar(email){
		email = email.replace(/^\s+|\s+$/g,"");

		$('#txtEmail1').css({border: '1px solid #DDDDDD'});
		$('#cadObs').css({color: 'red'});
		$('#cadObs').html('<span style="font-size:18px;"></span>');
		
		$('#aguarde').html('<img src="images/waiting.gif" /> Verificando CEP...');
		$('#aguarde').show();
		/*alert('OK');*/
		
		if(email == ''){
			alert('Preencha o campo e-mail');
			$('#txtEmail1').focus();
			return false;
		}
		
		if(validarEmail(email) != true){
			return false;
		}
		
		$.get("controle.php?opt=carregarcli&email=" + email, function(data){
			if(data == 'true'){
				window.location = 'pizza.php';
				return true;
			}else{
				$('#txtEmail1').css({border: '2px solid red'});
				$('#cadObs').css({color: 'red'});
				$('#cadObs').html('<span style="font-size:18px;">O e-mail informado não foi encontrado!</span>');
				//$('#txtEmail1').focus();
				$('#aguarde').hide();
				return false;
			}	
		});
	}
	/**
	 * 
	 */
	
	function clienteExiste(email){
		/*gravaLog('Estou tentando verificar se o email "'+email+'" existe.');
		gravaLog("controle.php?opt=checaCliente&email="+email);
		
		$.post("controle.php?opt=checaCliente&email="+email, function(data){
			gravaLog("clienteExiste data: " + data);
			alert("clienteExiste data: " + data)
			
			while(data == undefined);
			
			if(data == 'true'){
				return 'true';
			}else{
				return 'false';
			}
		});*/
		
		return 'false';
		
	}
	
	function estaLogado(email){
		gravaLog('Estou tentando verificar se o email "'+email+'" está logado.');
		gravaLog("controle.php?opt=clicampo&campo=email");
		
		$.post("controle.php?opt=clicampo&campo=email", function(data){
			gravaLog("estaLogado data: " + data);
			if(data ==  email){
				return true;
			}else{
				return false;
			}
		});
	}
	
	$('#proxPizza').click(function(){
		
		var email = $('#txtEmail1').val();
		var teste = logar(email);
		if( teste == true){
			//alert('Passei');
			window.location = "pizza.php";
		}
		
		/*
		var email = $('#txtEmail1').val();
		
		var valor = clienteExiste(email);
		while(valor == undefined){
			valor = clienteExiste(email);
			alert('aqui: '+  valor );
		}
		
		if(clienteExiste(email) == 'false'){
			
		}else{
			
			if(estaLogado(email) == true){
				window.location = 'pizza.php';
			}else{
				deslogar();
				if(logar(email) == true){
					window.location = 'pizza.php';
				}
			}
			
		}
		*/
	});
	
	function mostrarFormulario(){
		$('#aguarde').hide();
		
		$('#txtNome').val('');
		$('#txtEmail').val('');
		$('#txtTelefone').val('');
		$('#txtCep').val('');
		$('#txtBairro').val('');
		$('#txtEndereco').val('');
		$('#txtComplemento').val('');
		
		jQuery.blockUI({
                    message: jQuery('#formulario'),
                    css: {
                    top:  (jQuery(window).height() - 300) /2 + 'px',
                    left: (jQuery(window).width() - 465) /2 + 'px',
                    width: '465px',
                    height: '300px',
                    cursor:'default'
	        }
	    });
            $('#txtNome').ficus();
	}

	$('#cadastrar1').click(function(){
		mostrarFormulario();
	});

	$('#cancelar1').click(function(){
		$.unblockUI('#formulario');
	});


/******CEP***********************************************************/
$("#txtCep").blur( function () {
		ok = true;
		
		if($('#txtCep').val() == ''){
			return false;
		}
		
		$('#aguarde').html('<img src="images/waiting.gif" /> Verificando CEP...');
		$('#aguarde').show();

		$('input').enabled(false);
		
		 $.getJSON("controle.php?opt=vercep&cep="+$('#txtCep').val().replace("-",""),
		  function(json){
			$('#erros').html('');
		    if(json.row0 == 1){
				$('#txtCep').css({border: '1px solid #aaaaaa'});
				
			    $('#txtEndereco').val(json.row5 + " " + json.row6);
			    $('#txtBairro').val(json.row4);
			    
			    $('input').enabled(true);
				
			    $('#aguarde').fadeOut(1000);
				$('#txtComplemento').focus();
			}else{
				//alert('OK');
				
				$('input').enabled(true);
				
				$('#txtCep').css({border: '2px solid #999900'});
				$('#erros').html($('#erros').html() + '<span style="color:#999900;">*CEP</span>');

				$('#txtEndereco').val("");
			    $('#txtBairro').val("");
			    
				$('#aguarde').fadeOut(1000);
				ok = false;
			}
		  }
		)
});

$('#frmCliente').submit(function(){
    return false;
});

$("#cadastrar").click( function () {

    $('#aguarde').html('<img src="images/waiting.gif" /> Salvando Cliente...');
    $('#aguarde').fadeIn(200);

    $.ajax({
        type: "POST",
        url: "controle.php?opt=cadcliente",
        data: $("#frmCliente").serialize(),
        success: function(msg){
            if(msg!='')
                alert(msg);
            else{
                $('#txtEmail1').val( $('#txtEmail').val() );
                $.unblockUI();
                $("form")[0].reset();
            }
        }
    });
    $('#aguarde').fadeOut(100);
    return false;
});


$("#cadastrar_").click( function () {
		var errors = new Array();
		$('#erros').html('');
		$('#aguarde').html('<img src="images/waiting.gif" /> Verificando dados...');
		//$('#aguarde').show();
		
		if ($('#txtNome').val() == ''){
			//$('#erros').html($('#erros').html() + '<span style="color:red;">*Nome </span>');
			errors.push("O campo 'Nome' deve ser preenchido.");
			ok = false;
		}
		if ($('#txtTelefone').val() == ''){
			//$('#erros').html($('#erros').html() + '<span style="color:red;">*Telefone </span>');
			errors.push("O campo 'Telefone' deve ser preenchido.");
			ok = false;
		}
		if ($('#txtCep').val() == ''){
			//$('#erros').html($('#erros').html() + '<span style="color:red;">*CEP </span>');
			errors.push("O campo 'CEP' deve ser preenchido.");
			ok = false;
		}		
		if ($('#txtBairro').val() == ''){
			//$('#erros').html($('#erros').html() + '<span style="color:red;">*Bairro </span>');
			errors.push("O campo 'Bairro' deve ser preenchido.");
			ok = false;
		}
		if ($('#txtEndereco').val() == ''){
			//$('#erros').html($('#erros').html() + '<span style="color:red;">*Endereço </span>');
			errors.push("O campo 'Endereço' deve ser preenchido.");
			ok = false;
		}
		if ($('#txtComplemento').val() == ''){
			//$('#erros').html($('#erros').html() + '<span style="color:red;">*Complemento </span>');
			errors.push("O campo 'Complemento' deve ser preenchido.");
			ok = false;
		}
		
		if ($('#txtOrigem').val() == ''){
			//$('#erros').html($('#erros').html() + '<span style="color:red;">*Onde tomou conhecimento </span>');
			errors.push("O campo 'Onde tomou conhecimento' deve ser preenchido.");
			ok = false;
		}
/******Ver Email***********************************************************/
		if ($('#txtEmail').val() == ''){
			//$('#erros').html($('#erros').html() + '<span style="color:red;">*E-mail </span>');
			errors.push("O campo 'E-Mail' deve ser preenchido.");
			$('#aguarde').fadeOut(1000);
			ok = false;
		}else{
			$.post("controle.php?opt=veremail", {pEmail: $('#txtEmail').val()},
			function(data){
				alert("Data Loaded: " + data);
				if(data != 'false'){
					$('#txtEmail').css({border: '2px solid #red'});
					//$('#erros').html($('#erros').html() + '<span style="color: #999900;">*E-mail ja cadastrado</span>');
					errors.push("O campo 'E-Mail' já está cadastrado em nossa base de dados.");
					ok = false;
					$('#aguarde').fadeOut(500);
				}else{
					$('#txtEmail').css({border: '1px solid #aaaaaa'});
					$('#aguarde').fadeOut(500);
					//alert(ok);
					if(ok != false){
						$.post("controle.php?opt=cadcliente", { 
							pNome: $('#txtNome').val(),
							pEmail: $('#txtEmail').val(),
							pEndereco: $('#txtEndereco').val(),
							pComplemento: $('#txtComplemento').val(),
							pBairro: $('#txtBairro').val(),
							pCep: $('#txtCep').val(),
							pTelefone: $('#txtTelefone').val(),
							pOrigem: $('#txtOrigem').val()
						},function(data){
                                                   alert(data);
                                            });
						
						$('#cadObs').html('Cadastro concluído.<br/>Foi enviado um e-mail de confirmação para ' + $('#txtEmail').val());
						$('#txtEmail1').val($('#txtEmail').val());
						setTimeout(jQuery.unblockUI, 500);

					}
				}
				});
		}
		if(errors.length > 0){
			var mgs = "";
			for(var i = 0; i < errors.length;i++){
				mgs += " - " + errors[i] + "\n"; 
			}
			alert(mgs);
			$('#aguarde').fadeOut(50);
		}
		
});


	$("#txtEmail1").keypress(function(e){
		if (e.which == 13) {
			$("#proxPizza").click();
		}
		
	});
	
	$("input").keypress(function(e){
		if (e.which == 13) {
			$("#cadastrar").click();
		}
		
	});
	
});

