function validaEmail(mail)
{
  var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);

  if(er.test(mail))
      return true;
  else
      return false;
}

function newsletter()
{
    if( jQuery("#FEmailNewsletter").val() == '' )
    {
        jQuery("#retornoNewsletter").addClass("erro");
        jQuery("#FEmailNewsletter").focus();
        jQuery("#retornoNewsletter").html("Informe seu email!");
    }
    else
    if( !validaEmail(jQuery("#FEmailNewsletter").val()) )
    {
        jQuery("#retornoNewsletter").addClass("erro");
        jQuery("#FEmailNewsletter").focus();
        jQuery("#retornoNewsletter").html("Email inválido!");
    }
    else
    {
        jQuery("#newsletter input[type='image']").attr("disabled");
        x_newsletter( jQuery("#FEmailNewsletter").val(), callBackNewsletter );
    }
}

function callBackNewsletter( retorno )
{
    jQuery("#newsletter input[type='image']").removeAttr("disabled");

    if( retorno )
    {
        jQuery("#FEmailNewsletter").val('');
        jQuery("#retornoNewsletter").addClass("ok");
        jQuery("#retornoNewsletter").removeClass("erro");
        jQuery("#retornoNewsletter").html("Email cadatrado!");
    }
    else
    {
        jQuery("#FEmailNewsletter").focus();
        jQuery("#retornoNewsletter").addClass("erro");
        jQuery("#retornoNewsletter").removeClass("ok");
        jQuery("#retornoNewsletter").html("Email ja cadastrado!");
    }
}

function loginPainelControle()
{
    if( jQuery("#FUsuarioPainel").val() == '' )
    {
        jQuery("#retornoPainelControle").addClass("erro");
        jQuery("#FUsuarioPainel").focus();
        jQuery("#retornoPainelControle").html("Informe o Usuário!");
    }
    else
    if( jQuery("#FSenhaPainel").val() == '' )
    {
        jQuery("#retornoPainelControle").addClass("erro");
        jQuery("#FSenhaPainel").focus();
        jQuery("#retornoPainelControle").html("Informe a Senha!");
    }
    else
    {
        jQuery("#retornoPainelControle").html("Validando seus dados...");
        jQuery("#retornoPainelControle").addClass("validando");
        x_loginPainelControle( jQuery("#FUsuarioPainel").val(), jQuery("#FSenhaPainel").val(), callBackLoginPainelControle );
    }
}

function callBackLoginPainelControle( retorno )
{
    jQuery("#retornoPainelControle").removeClass("validando");

    if( retorno )
    {
        jQuery("#retornoPainelControle").removeClass("erro");
        jQuery("#retornoPainelControle").addClass("ok");
        jQuery("#retornoPainelControle").html("Aguarde, redirencionando...");

        jQuery("#FUsuarioPainel").val('');
        jQuery("#FSenhaPainel").val('');

        document.location.href = 'adm/';
    }
    else
    {
        jQuery("#retornoPainelControle").removeClass("ok");
        jQuery("#retornoPainelControle").addClass("erro");
        jQuery("#retornoPainelControle").html("Dados de acesso inválidos!");
    }
}

function codigoTecla( evento )
{
    var keycode = "";

    if (window.event)
    {
        keycode = window.event.keyCode;
    }
    else
    if(evento)
    {
        keycode = evento.which;
    }
    
    return keycode;
}

function enviarContato()
{
    var dados = new Array("nome:->"+jQuery("#FNome").val(),
                          "cpf:->"+jQuery("#FCPF").val(),
                          "cidade:->"+jQuery("#FCidade").val(),
                          "telefone:->"+jQuery("#FTelefone").val(),
                          "email:->"+jQuery("#FEmail").val(),
                          "assunto:->"+jQuery("#FAssunto").val(),
                          "mensagem:->"+jQuery("#FMensagem").val(),
                          "newsletter:->"+( jQuery("#FReceberNewsletter").is(':checked')?"S":"N" ) );

    jQuery("#retornoContato").html("Aguarde, enviando contato...");
    jQuery("#retornoContato").addClass("enviando");
    x_enviarContato( convertToPHP( dados ), callBackEnviarContato );
}

function callBackEnviarContato( retorno )
{
    jQuery("#retornoContato").removeClass("enviando");

    if( retorno )
    {
        jQuery("#retornoContato").removeClass("erro");
        jQuery("#retornoContato").addClass("ok");
        jQuery("#retornoContato").html("Contato enviado com sucesso!");

        jQuery.each(jQuery("#contato input[type='text']"), function()
        {
            this.value = '';
        });

        jQuery("#FMensagem").val('');
    }
    else
    {
        jQuery("#retornoContato").removeClass("ok");
        jQuery("#retornoContato").addClass("erro");
        jQuery("#retornoContato").html("Erro. Tente novamente!");
    }
}

function convertToPHP( obj )
{
    return obj.join("||:>");
}

function enviarOrcamento()
{

    var produtosSelecionados = '';

    jQuery.each(jQuery("#produtosSelecionados div"), function()
    {
        if( produtosSelecionados == '')
        produtosSelecionados = jQuery("#"+this.id+" span").attr('title')+"||-"+jQuery("#"+this.id+" input").val();
        else
        produtosSelecionados = produtosSelecionados + "||>"+jQuery("#"+this.id+" span").attr('title')+"||-"+jQuery("#"+this.id+" input").val();
    });

    var dados = new Array("nome:->"+jQuery("#FNome").val(),
                          "cpf:->"+jQuery("#FCPF").val(),
                          "cidade:->"+jQuery("#FCidade").val(),
                          "endereco:->"+jQuery("#FEndereco").val(),
                          "bairro:->"+jQuery("#FBairro").val(),
                          "telefone:->"+jQuery("#FTelefone").val(),
                          "celular:->"+jQuery("#FCelular").val(),
                          "email:->"+jQuery("#FEmail").val(),
                          "outros_produtos:->"+jQuery("#FOutrosProdutos").val(),
                          "observacoes:->"+jQuery("#FObservacoes").val(),
                          "produtos_selecionados:->"+produtosSelecionados,
                          "newsletter:->"+( jQuery("#FReceberNewsletter").is(':checked')?"S":"N" ) );

    jQuery("#retornoOrcamento").html("Aguarde, enviando orçamento...");
    jQuery("#retornoOrcamento").addClass("enviando");
    x_enviarOrcamento( convertToPHP( dados ), callBackEnviarOrcamento );
}

function callBackEnviarOrcamento( retorno )
{
    jQuery("#retornoOrcamento").removeClass("enviando");

    if( retorno )
    {
        jQuery("#retornoOrcamento").removeClass("erro");
        jQuery("#retornoOrcamento").addClass("ok");
        jQuery("#retornoOrcamento").html("Orçamento enviado com sucesso!");

        jQuery.each(jQuery("#contato input[type='text']"), function()
        {
            this.value = '';
        });

        jQuery("#FOutrosProdutos").val('');
        jQuery("#FObservacoes").val('');
        jQuery("#produtosSelecionados").html('Nenhum produto selecionado!');
    }
    else
    {
        jQuery("#retornoOrcamento").removeClass("ok");
        jQuery("#retornoOrcamento").addClass("erro");
        jQuery("#retornoOrcamento").html("Erro. Tente novamente!");
    }
}

function adicionarProdutosOrcamento()
{
    var atual = jQuery("#produtosSelecionados").html();

    jQuery.each(jQuery("#listaProdutos input"), function()
    {
        if( this.checked )
        {
            if( jQuery("#produtosSelecionados div").length == 0)
            jQuery("#produtosSelecionados").html('');
            
            if( !jQuery("#selecionado"+this.id).html() )
            jQuery("#produtosSelecionados").html(jQuery("#produtosSelecionados").html() + "<div id='selecionado"+this.id+"' name='selecionado"+this.id+"'><img title='Exlcuir este produto!' onclick='removerProdutoSelecionado(\""+this.id+"\")' src='img/erro.png'>&nbsp;<strong><span title='"+ document.getElementById("labelProduto"+this.id).title +"' >"+ jQuery("#labelProduto"+this.id).html() +"</span></strong><input type='text' maxlength='4' /></div>" );

            this.checked = false;
        }
    });
    if( atual == 'Nenhum produto selecionado!' )
    jQuery("#produtosSelecionados").html( "<span>Informe a quantidade de produtos!</span><br/><br/>" + jQuery("#produtosSelecionados").html() );
    else
    jQuery("#produtosSelecionados").html( jQuery("#produtosSelecionados").html() );
    

    jQuery("#listaProdutos").css('display', 'none');
}

function removerProdutoSelecionado( produto )
{
    jQuery("#selecionado"+produto).remove();

    if( jQuery("#produtosSelecionados div").length == 0)
    jQuery("#produtosSelecionados").html('Nenhum produto selecionado!');
}

function enviarPaginaEmail()
{
    if( jQuery('#FNomePagina').val() == '' )
    {
        jQuery('#retornoPaginaEmail').html('Informe seu Nome!');
        jQuery('#FNomePagina').focus();
        jQuery('#retornoPaginaEmail').css('color', '#FF0000');
    }
    else
    if( jQuery('#FEmailPagina').val() == '' )
    {
        jQuery('#retornoPaginaEmail').html('Informe o email!');
        jQuery('#FEmailPagina').focus();
        jQuery('#retornoPaginaEmail').css('color', '#FF0000');
    }
    else
    if( !validaEmail(jQuery('#FEmailPagina').val()) )
    {
        jQuery('#retornoPaginaEmail').html('Informe um email válido!');
        jQuery('#FEmailPagina').focus();
        jQuery('#retornoPaginaEmail').css('color', '#FF0000');
    }
    else
    {
        jQuery('#retornoPaginaEmail').css('color', '#000000');
        jQuery('#retornoPaginaEmail').html("<img src='img/loader.gif'/>&nbsp;Aguarde, enviando email...");
        x_enviarPaginaEmail( jQuery('#FEmailPagina').val(), jQuery('#FNomePagina').val(), callBackEnviarPaginaEmail );
    }
}

function callBackEnviarPaginaEmail( retorno )
{
    if( retorno )
    {
        jQuery('#retornoPaginaEmail').html('Email enviado com sucesso!');
        jQuery('#retornoPaginaEmail').css('color', '#1B6F36');
    }
    else
    {
        jQuery('#retornoPaginaEmail').html('Erro ao tentar enviar email. Tente novamente!');
        jQuery('#retornoPaginaEmail').css('color', '#FF0000');
    }
}
