/*
 * @author Andrei Rafael Brayer - Guinho
 * @copyright InMeta Agência Digital - Guinho
 *
 */


/*
 * 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
    })
})
/*
 * Tira o pontilhado dos elementos
 */
$(function(){
    $('a').click(function() {
        $(this).blur();
    });
})

/*
 *
 * Indica a um amigo
 */
$(document).ready(function(){
    $("#forminamigo").bind('submit', function(){
        if(validaFormInAmigo()){
            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+'/indicar/index', data, function(result){
            jQuery.unblockUI();
            window.setTimeout('alertIndique('+result+')', 400);
               
            });
        }
        return false;
    });
});
function alertIndique(result)
{
    if(result == 1){
       alert('Indicação Feita com sucesso !');
   }else{
       alert('Erro ao enviar E-mail !');
       jQuery('#carregando').hide();
   }
   return false
}
function validaFormInAmigo(){
    var form = document.getElementById('forminamigo');
    if(form.seunome.value == ''){
        alert('Você deve preencher o campo Seu Nome');
        form.seunome.focus();
        return false;
    }
    if(form.seuemail.value == ''){
        alert('Você deve preencher o campo Seu E-mail');
        form.seuemail.focus();
        return false;
    }else{
        var txt = form.seuemail.value;
        if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))) {
            alert("Seu E-mail incorreto");
            form.seuemail.focus();
            return false;
        }
    }
    if(form.nomeAmigo.value == ''){
        alert('Você deve preencher o campo Nome do destinatário');
        form.nomeAmigo.focus();
        return false;
    }
    if(form.emailAmigo.value == ''){
        alert('Você deve preencher o campo E-mail do destinatário');
        form.emailAmigo.focus();
        return false;
    }else{
        var txt = form.emailAmigo.value;
        if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))) {
            alert("E-mail do destinatário incorreto");
            form.emailAmigo.focus();
            return false;
        }
    }
    return true;
}
/*
 *
 * ==================================================
 *
 * Cadastro de Newsletter
 */
var opcaoNews = 'cad';
$(document).ready(function(){
    $("#formNewsletter").bind('submit', function(){
        $('#actNews').val('cadastra');
        if(opcaoNews == 'cad'){
            if($('#newsNome').val() == '' || $('#newsNome').val() == 'seu nome'){ alert('Para se cadastrar na newsletter é preciso preencher seu nome!'); return false; }
        }else{
            $('#actNews').val('remove');
        }
        if($('#newsMail').val() == '' || $('#newsMail').val() == 'seu@email.com'){ alert('Para se cadastrar/descadastrar na newsletter é preciso preencher seu e-mail!'); return false; }
        if(!echeck($('#newsMail').val())){return false}

        var left = cauculaWigth(415);
        jQuery('#carregando').show();
        jQuery.blockUI({ message: jQuery('#div-carregando'),css: { width:'415px', left: left+'px', top:'20%',border:'0;'} });

        $.post(baseUrl+'/newsletter/cadastra', $('#formNewsletter').serialize(), function(data){
            jQuery.unblockUI();
            window.setTimeout('alertNews('+data+')', 400);
        });
        return false;
    });
});
function alertNews(data)
{
    if(data == 1){
        jQuery('#carregando').hide();
        alert('Este e-mail já está cadastrado!');
    }else{
        alert('Obrigado por se interessar em nossas notícias!');
        $('#newsNome').val('seu nome');
        $('#newsMail').val('seu@email.com');
    }
    return false;
}
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
}

/*
 *
 * ==================================================
 *
 * 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', data, function(result){
            $.unblockUI();
            window.setTimeout('alertContato('+result+')', 400);
               
            });
        }
        return false;
    });
});
function alertContato(result)
{
    if(result == 1){
       alert('Contato foi enviado com sucesso !');
    }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').html() == ''){ alert('Preencha a Cidade!'); $('#msg').focus(); 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(!echeck($('#seuemailC').val())){ alert($('#seuemailC').val()); return false}
        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 !');
                var t = location.href;
                var go = t.replace('#comentarios', '');
                location.href=go+'?c=1';
            }
        });

        return false;

    });
});
/*
 *
 * ================================================
 *
 * Chama o RSS
 *
 */
jQuery(function(){
    jQuery('.bt-rss').each(function(){
       jQuery(this).bind('click', function(){
            var left = cauculaWigth(440);
            jQuery('#carregando').show();
            jQuery.blockUI({ message: jQuery('#div-carregando'),css: { width:'440px', 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;
        })
    })
});


/*
 *
 * =================================================
 *
 * Cria as mascaras dos Formularios
 *
 */
$(function(){
    $('.mask-data').mask('99/99/9999'); //data
    $('.mask-fone').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);

});
/*
 * Troca os espaçamentos das img
 */
$(function(){
    $('img').each(function(){
        var align = $(this).attr('align');
        var borda = $(this).attr('border');
        var width = $(this).attr('hspace');
        var height = $(this).attr('vspace');

        if(align == "right"){
            $(this).css('float', 'right');
            $(this).css('margin-right', '15px');
        }
        if(align == "middle"){
            var tamanho = $(this).attr('width');
            var margin = (461 - tamanho)/2;
            $(this).css('margin-left', margin+'px');
            $(this).css('margin-right', margin+'px');
        }else{
            if(borda > 0){
                $(this).css('margin', borda+'px');
            }
            if(width > 0){
                $(this).css('margin-top', width+'px');
                $(this).css('margin-bottom', width+'px');
            }
            if(height > 0){
                $(this).css('margin-left', height+'px');
                $(this).css('margin-right', height+'px');
            }
            if(width < 45){
                $(this).css('clear', 'none');
            }
        }
    });
});