/*
 * @author Andrei Rafael Brayer - Guinho
 * @copyright InMeta Agência Digital - Guinho
 *
 */
$(function(){
    $('.newListSelected').hover(function(){}
    ,function(){
        $('.newListSelected').attr('style', 'position:static');
        $('.newList').hide();
    })
})

/*
 * Pega todos os links que tenhão o destino de http:// e manda abri los em outra aba
 */
$(function(){
    $("a[href^=http://]").click(function(){
        window.open($(this).attr("href"))
        return false
    })
})
$(function(){
    $(".blockOverlay").click(function(){
        $.unblockUI();
        return false
    })
})
/*
 * Tira o pontilhado dos elementos
 */
$(function(){
    $('a').click(function() {
        $(this).blur();
    });
})

/*
 *==========================================
 *
 * Indica a um amigo
 */

jQuery(function(){
    jQuery('.bt-indicar').each(function(){
       jQuery(this).bind('click', function(){
            var link = $(this).attr('href');
            var titulo = $(this).attr('title');
            var left = cauculaWigth(440);
            jQuery('#carregando').show();
            jQuery.blockUI({ message: jQuery('#div-carregando'),css: { width:'440px', left: left+'px', top:'50px',border:'0;'} });
            jQuery.get(baseUrl+'/indicar/form/link/'+link+'/titulo/'+titulo, null, function(result){
               jQuery('#carregando').hide();
               jQuery('#div-newsletter').show();
               jQuery('#div-newsletter').html(result);
            });
            return false;
        })
    })
});
/*
 *==========================================
 *
 * Chama formulario de newsletter
 */

jQuery(function(){
    jQuery('.bt-newsletter').each(function(){
       jQuery(this).bind('click', function(){
            var left = cauculaWigth(291);
            jQuery('#carregando').show();
            jQuery.blockUI({ message: jQuery('#div-carregando'),css: { width:'330px', left: left+'px', top:'20%',border:'0;'} });
            jQuery.get(baseUrl+'/newsletter/form', null, function(result){
               jQuery('#carregando').hide();
               jQuery('#div-newsletter').show();
               jQuery('#div-newsletter').html(result);
            });
            return false;
        })
    })
});


/*
 *
 * ==================================================
 *
 * Cadastro do contato
 */
$(document).ready(function(){
    $("#formcontato").bind('submit', function(){
        if(ValidaFormContato()){
            var left = cauculaWigth(415);
            jQuery('#carregando').show();
            jQuery.blockUI({ message: jQuery('#div-carregando'),css: { width:'415px', left: left+'px', top:'20%',border:'0;'} });
            
            var data = $(this).serialize();
            $.post(baseUrl+'/contato/enviar', data, function(result){
            $.unblockUI();
            window.setTimeout('alertContato('+result+')', 400);
               
            });
        }
        return false;
    });
});
function alertContato(result)
{
    if(result == 1){
       alert('Contato foi enviado com sucesso !');
       $('#nome').val('')
       $('#email').val('')
       $('#msg').val('')
    }else{
       alert('Erro ao enviar E-mail !');
       jQuery('#carregando').hide();
    }
    return false;
}
function ValidaEmail(obj)
{
    var txt = $(obj).val();
    if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))) {
        return false;
    }else{
        return true;
    }
}
function ValidaFormContato()
{
    if($('#nome').val() == ''){ $('#nome').focus(); alert('Preencha seu Nome!'); return false; }
    if($('#email').val() == ''){ $('#email').focus(); alert('Preencha seu E-mail!'); return false; }
    if(!ValidaEmail($('#email'))){ alert('Por favor preencha um E-mail válido!'); return false; }
    //if($('#empresa').val() == ''){ $('#empresa').focus(); alert('Preencha Empresa!');  return false; }
    //if($('#cidade').val() == ''){ $('#cidade').focus();alert('Preencha sua Cidade/Estado!'); return false; }
    if($('#msg').val() == ''){ alert('Preencha uma Mensagem!'); $('#msg').focus(); return false; }
    return true;
}
/*
 *
 * ==================================================
 *
 * Cadastro de reservas
 */
$(document).ready(function(){
    var URL = '';
    $("#formreserva").bind('submit', function(){
        if(ValidaFormReservas()){
            var left = cauculaWigth(415);
            jQuery('#carregando').show();
            jQuery.blockUI({ message: jQuery('#div-carregando'),css: { width:'415px', left: left+'px', top:'20%',border:'0;'} });

            var data = $(this).serialize();
            $.post(baseUrl+'/reservas/salvar', data, function(result){
            jQuery.unblockUI();

            //window.setTimeout('alertReservas('+result+')', 400);
            alertReservas(result);

            });
        }
        return false;
    });
});
function alertReservas(result)
{
    
    //alert(result);

    var explode = result.split('|');
    var resultado  = explode[0];
    var id      = explode[1];
    var seoUrl  = explode[2];
    var idEvento  = explode[3];
    var andar = 1;
    
    if(id > 13){
        andar = 1;
    }else{
        andar = 2;
    }
//    var verifica = UrlAtual.split('/');
//    if(verifica.length <= 5){
//        URL = UrlAtual+'/'+seoUrl+'/'+idEvento+'/andar/'+andar;
//    }else{
//        URL = UrlAtual;
//    }
    URL = UrlAtual;
    
    if(resultado == 1){
       jQuery('#carregando').hide();
       alert('Dados incorretos. Preencha seus dados corretamente!');
    }else if(resultado == 2){
       jQuery('#carregando').hide();
       alert('Reserva cancelada com sucesso!<br />Você receberá um e-mail com informações sobre o cancelamento de sua reserva.');
       window.setTimeout('window.location=URL',5000);
    }else if(resultado == 20){
       jQuery('#carregando').hide();
       alert('Reserva cancelada com sucesso!<br />Um erro inesperado ocorreu ao enviar o e-mail com informações de cancelamento da reserva.');
       window.setTimeout('window.location=URL',5000);
    }else if(resultado == 3){
       jQuery('#carregando').hide();
       alert('Esse e-mail já possui uma reserva!');
    }else if(resultado == 4){
       jQuery('#carregando').hide();
       alert('Você receberá um e-mail com informações sobre sua reserva.');
       window.setTimeout('window.location=URL',5000);
    }else if(resultado == 5){
       jQuery('#carregando').hide();
       alert('Sua reserva foi feita com sucesso!<br />Um erro inesperado ocorreu ao enviar o e-mail com informações da reserva.<br />Leia atentamente o regulamento de reserva que se encontra nesta página.');
    }else if(resultado == 6){
       jQuery('#carregando').hide();
       alert('Conforme regulamento não é mais possível reservar mesas para esse evento.');
    }else if(resultado == 7){
       jQuery('#carregando').hide();
       if(id <= 3){
          alert('Essa camarote já foi reservado. Escolha outro camarote.');
       }else{
          alert('Essa mesa já foi reservada. Escolha uma outra mesa.');
       }
    }
    return false;
}
function ValidaFormReservas()
{
    if($('#nomeR').val() == ''){ $('#nomeR').focus(); alert('Preencha seu Nome!'); return false; }
    if($('#emailR').val() == ''){ $('#emailR').focus(); alert('Preencha seu E-mail!'); return false; }
    if(!ValidaEmail($('#emailR'))){ alert('Por favor preencha um E-mail válido!'); return false; }
    if($('#telefoneR').val() == ''){ $('#telefoneR').focus(); alert('Preencha seu Telefone!');  return false; }
    var cancelar_reserva = $('#remover-remover');
    if(cancelar_reserva.attr('checked') == false){
        if($('#mesaR').val() == 0){ $('#mesaR').focus();alert('Escolha uma mesa!'); return false; }
        if($('#mesaR option:selected').text() == 'Reservado'){ $('#mesaR').focus();alert('Mesa já reservada. Por favor escolha outra mesa!!'); return false; }
    }
    return true;
}

/*
 *
 * =================================================
 *
 * Cria as mascaras dos Formularios
 *
 */
$(function(){
    $('form#formComentario').submit(function(){
        if($(this).find('#seunomeC').val() == ''){ alert('Por favor preencha seu Nome!'); return false; }
        if($(this).find('#seuemailC').val() == ''){ alert('Por favor preencha seu E-mail!'); return false; }
        if(!ValidaEmail($('#seuemailC'))){ alert('Por favor preencha um E-mail válido!'); return false; }
        //if(!echeck($('#seuemailC').val())){alert("O e-mail informado é inválido.") }
        //if($(this).find('#cidadeC').val() == ''){ alert('Por favor preencha sua Cidade!'); return false; }
        //if($(this).find('#estadoC').val() == ''){ alert('Por favor escolha um Estado!'); return false; }
        if($(this).find('#comentarioC').val() == ''){ alert('Por favor preencha seu Comentário!'); return false; }
        
        $.post(baseUrl+'/comentar', $(this).serialize(), function(data){
            if(data == 1){
                alert('Comentário feito com sucesso !');
                window.setTimeout('resetPaginaComent()',3000)
                
            }
        });

        return false;

    });
});
function resetPaginaComent()
{
    var t = location.href;
    var go = t.replace('#comentarios', '');
    location.href=go+'?c=1';
}
/*
 *
 * =================================================
 *
 * Cria as mascaras dos Formularios de reservas
 *
 */
$(function(){
    $('form#vips').submit(function(){
        if($(this).find('#nome').val() == ''){ alert('Por favor preencha Nome Completo!'); return false; }
        if($(this).find('#cidade').val() == ''){ alert('Por favor preencha Cidade!'); return false; }
        if($(this).find('#email').val() == ''){ alert('Por favor preencha seu E-mail!'); return false; }
        if(!ValidaEmail($('#email'))){ alert('Por favor preencha um E-mail válido!'); return false; }

        return true;

    });
});
/*
 *
 * ================================================
 *
 * Chama o RSS
 *
 */
jQuery(function(){
    jQuery('.bt-rss').each(function(){
       jQuery(this).bind('click', function(){
            var left = cauculaWigth(370);
            jQuery('#carregando').show();
            jQuery.blockUI({ message: jQuery('#div-carregando'),css: { width:'370px', left: left+'px', top:'20%',border:'0;'} });
            jQuery.get(baseUrl+'/feed/', null, function(result){
               jQuery('#carregando').hide();
               jQuery('#div-newsletter').show();
               jQuery('#div-newsletter').html(result);
            });
            return false;
        })
    })
});


/*
 *
 * =================================================
 *
 * CCheca o e-mail
 *
 */

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){
       alert("O e-mail informado é inválido.")
       return false
    }

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
       alert("O e-mail informado é inválido.")
       return false
    }

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        alert("O e-mail informado é inválido.")
        return false
    }

     if (str.indexOf(at,(lat+1))!=-1){
        alert("O e-mail informado é inválido.")
        return false
     }

     if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        alert("O e-mail informado é inválido.")
        return false
     }

     if (str.indexOf(dot,(lat+2))==-1){
        alert("O e-mail informado é inválido.")
        return false
     }

     if (str.indexOf(" ")!=-1){
        alert("O e-mail informado é inválido.")
        return false
     }
    return true
}

/*
 *
 * =================================================
 *
 * Cria as mascaras dos Formularios
 *
 */
$(function(){
    $('.mask-data').mask('99/99/9999'); //data
    $('.mask-fone').mask('(99) 9999-9999'); //telefone
    $('#telefoneR').mask('(99) 9999-9999'); //telefone
    $('.mask-rg').mask('9.999.999-9'); //RG
    $('.mask-cpf').mask('999.999.999-99'); //CPF
    $('.mask-cnpj').mask('99.999.999/0009-99'); //CNPJ
    $('.mask-cep').mask('99.999-999'); //CEP
    $('.mask-numero').mask('99999999999'); //NUMERO
})




/*
 *
 * ==================================================
 *
 * pega os valores do tamalnho da tela....
 */
function f_clientWidth() {
    return f_filterResults (
        window.innerWidth ? window.innerWidth : 0,
        document.documentElement ? document.documentElement.clientWidth : 0,
        document.body ? document.body.clientWidth : 0
    );
}
function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
function cauculaWigth(widthPop)
{
    var widthPop = widthPop;
    var widthJanela = f_clientWidth();
    var resultato = (widthJanela-widthPop)/2;
    return resultato;
}

/*
 * centraliza paginação
 */
//$(function(){
//    var offset = $('.paginacao').offset();
//    var ElementoPai = 714;
//    var resultato = (ElementoPai-offset.left)/2;
//    resultato = resultato+5;
//    $('.paginacao').attr('style','margin-left:'+resultato+'px');
//});
$(function(){
    var tamanhoConteudo = $('#conteudo').css('height');
    $('.bloco_esq').attr('style','height:'+tamanhoConteudo);

});

