jQuery(function() {
	$('.warn a.close').click(function(e){
		e.stopPropagation; e.preventDefault();
		$(this).parent('.warn, .brd').fadeOut();
	});
	
	$('.clean').focus(VisaoPrev._resetField);

	$('#page-actions .small, #page-actions .big').click(VisaoPrev._setFontSize);
	
	VisaoPrev._pngfix();
    VisaoPrev._tooTipSaldo();
    VisaoPrev._alternaQuestion();
	VisaoPrev._validate();
	VisaoPrev._boxGrupo();
	VisaoPrev._header();
	VisaoPrev._fonte();
	VisaoPrev._pop();
	VisaoPrev._topContent();
	VisaoPrev._closeTutorial();
});

/**
* Fecha o box de mudar grupo
* @author Douglas Castilho <douglas.castilho@agenciaclick.com.br>
*/
function closeGrupo ( e ){
    var ev = e || window.event, target = ev.target;	
    var valor = $(target).attr('id');

    if (valor != 'box-altera-grupo' && valor != ''){
        $("#box-altera-grupo").hide();
    }
};

var VisaoPrev = {

    /**
    * png fix
    * @author André Machado <andre.machado@agenciaclick.com.br>
    */
    _pngfix: function() {
        if (!/msie [^6]\.0/i.test(navigator.userAgent) && /msie 6\.0/i.test(navigator.userAgent)) {
            DD_belatedPNG.fix('img, .pngfix, #ae-menu');
        };
    },

    /**
    * acessibilidade
    * @author Douglas Castilh <douglas.castilho@agenciaclick.com.br>
    */
    _fonte: function() {
        var area = 'ae-content', limite = 5, cont = 0, target = 'h1, h2, h3, h4, p, blockquote, li, span, td, th';
        // aumenta font
        $("a.big").click(function() {
            $('#' + area).find(target).not('.normal, .bt_nov > *, #page-actions li').each(function() {
                var e = $(this), s = parseInt(e.css('font-size').substring(0, 2));
                if (cont != limite) { e.css('font-size', (s) + 1); };
            });
            cont != limite ? cont++ : '';
            return false;
        });
        // diminui font
        $("a.small").click(function() {
            $('#' + area).find(target).not('.normal, .bt_nov > *, #page-actions li').each(function() {
                var e = $(this), s = parseInt(e.css('font-size').substring(0, 2));
                if (cont != 0) { e.css('font-size', (s) - 1); };
            });
            cont != 0 ? cont-- : '';
            return false;
        });
    },

    /**
    * Reseta campos com a class .clean
    * @author Luís Eduardo Miranda <luiseduardo.miranda@gmail.com>
    * @modified Luís Eduardo Miranda <luiseduardo.miranda@gmail.com>
    */
    _resetField: function() {
        var current_value = $(this).val();
        $(this).val('').blur(function() {
            var new_current_value = $(this).val();
            if (new_current_value == "") {
                $(this).val(current_value);
            }
        });
    },

    /**
    * Atribui Tooltip aos objetos necessários
    * @author Luís Eduardo Miranda <luiseduardo.miranda@gmail.com>
    * @modified Luís Eduardo Miranda <luiseduardo.miranda@gmail.com>
    */
    _tooTipSaldo: function() {
        $('#last-months tr.div').tooltip({
            tip: '#tip-change-progile',
            position: ['top', 'center']
        });

        $('#val-desc .month').tooltip({
            tip: '#tip-calendar',
            effect: 'toggle',
            position: ['bottom', 'center']
        });
    },
    /**
    * imagens slide da home
    * @author Douglas Castilho <douglas.castilho@agenciaclick.com.br>
    */
    _slideHome: function() {
        var viewPhoto = 0;
        function nextPhoto() {
            $('ul.slide li a').removeClass('on');
            $('.boxGaleriaAux > div').hide();

            viewPhoto += 1;
            if (viewPhoto == $('.boxGaleriaAux > div').length)
                viewPhoto = 0;

            $('.boxGaleriaAux > div').eq(viewPhoto).show();
            $('ul.slide li a').eq(viewPhoto).addClass('on');
        }

        function prevPhoto() {
            $('ul.slide li a').removeClass('on');
            $('.boxGaleriaAux > div').hide();

            if (viewPhoto == 0)
                viewPhoto = $('.boxGaleriaAux > div').length;

            viewPhoto -= 1;
            $('.boxGaleriaAux > div').eq(viewPhoto).show();
            $('ul.slide li a').eq(viewPhoto).addClass('on');
        }

        function goPhoto(obj) {
            $('ul.slide li a').removeClass('on');
            $('.boxGaleriaAux > div').hide();

            if (viewPhoto == 0)
                viewPhoto = $('.boxGaleriaAux > div').length;

            viewPhoto = parseInt(obj);
            $('.boxGaleriaAux > div:eq(' + viewPhoto + ')').show();
            $("ul.slide li a").eq(viewPhoto).addClass('on');
            return false
        }

        var intAutoSlideClick = null;
        var intAutoSlide = null;

        function timerSlide(timer) {
            intAutoSlide = setInterval(function() {
                nextPhoto('.btProximo');
            }, timer);
        }

        function autoSlideClick() {
            clearInterval(intAutoSlide);
            clearInterval(intAutoSlideClick);

            intAutoSlideClick = setInterval(function() {
                timerSlide(5000);
                clearInterval(intAutoSlideClick);
            }, 5000)
        }

        $('ul.slide li a').click(function() {
            var valRel = $(this).attr('rel');
            goPhoto(valRel);
            return false;
        });
        timerSlide(5000);
    },
    /**
    * imagens slide da home
    * @author Douglas Castilho <douglas.castilho@agenciaclick.com.br>
    */
    _alternaQuestion: function() {
        $('.list-questions').each(function() {
            $(this).find(".question:even").addClass("even");
        });
        $('.list-search').each(function() {
            $(this).find(".search:even").addClass("even");
        });
    },

    /**
    * Load nas abas, resgata o primeiro link e carrega dentro da div com o class "brd"
    * @author Douglas Castilho <douglas.castilho@agenciaclick.com.br>
    * @modified Rafael Lazarini <joao.lazarini@agenciaclick.com.br>
    */
    _tabs: function() {
        var firstUrl = $("#tabs li a:first");
        var alturaLoad = $("#cont-shadow-middle").height()
        firstUrl.parent().addClass("current");
        $("#content_tab").load(firstUrl.attr("href"));
        $("#tabs li a").click(function() {
            var url = $(this).attr("href");
            $("#tabs li").removeClass("current");
            $(this).parent().addClass("current");
            $("#content_tab").load(url);
            return false
        });
    },

    /**
    * ativa o botão mudar no head
    * @author Douglas Castilho <douglas.castilho@agenciaclick.com.br>
    */
    _boxGrupo: function() {
        $(".mudaPlano").click(function() {
            if ($("#box-altera-grupo").is(":visible")) {
                $("#box-altera-grupo").hide();
                return false
            } else {
                $("#box-altera-grupo").show();
                return false
            }
        });
    },

    /**
    * construindo data para validação
    * @author André Machado <andre.machado@agenciaclick.com.br>
    */
    _buildDate: function() {
        $('#dia, #mes, #ano').keyup(function() { $('#data').val($('#dia').val() + '/' + $('#mes').val() + '/' + $('#ano').val()); });
    },
    /**
    * validações de formulário
    * @author André Machado <andre.machado@agenciaclick.com.br>
    */
    _validate: function() {
        // indique um amigo
        $('#indique_amigo').validate({
            rules: {
                'seu_nome': { required: true },
                'seu_email': { required: true, email: true },
                'nome_destinatario': { required: true },
                'email_destinatario': { required: true, email: true }
            },
            messages: {
                'seu_nome': { required: 'Informe seu nome' },
                'seu_email': { required: 'Informe seu e-mail', email: 'Informe um e-mail v&aacute;lido' },
                'nome_destinatario': { required: 'Informe o nome do destinat&aacute;rio' },
                'email_destinatario': { required: 'Informe o e-mail do destinat&aacute;rio', email: 'Informe um e-mail v&aacute;lido' }
            }
        });

        // esqueci a senha
        $('#esqueci_senha').validate({
            errorElement: "p",
            errorLabelContainer: $("#msg_error"),
            rules: {
                'cpf': { required: true, cpf: true },
                'data': { dateBR: true }
            },
            messages: {
                'cpf': { required: 'Informe seu cpf', cpf: 'Informe um cpf v&aacute;lido' },
                'data': { dateBR: 'Informe um data v&aacute;lida' }
            }
        });

        // alterar senha
        $('#alterar_senha').validate({
            rules: {
                'nova_senha': { required: true, minlength: 6, senha: true, senhaAlphaNumerica: true },
                'confirmar_nova_senha': { equalTo: '#nova_senha' }
            },
            messages: {
                'nova_senha': {
                    required: 'Crie sua nova senha',
                    minlength: 'A senha deve ter no m&iacute;nimo 6 caracteres',
                    senha: 'N&atilde;o use repeti&ccedil;&atilde;o de algarismos',
                    senhaAlphaNumerica: 'Utilize letras e n&uacute;meros'
                },
                'confirmar_nova_senha': { equalTo: 'Confirma&ccedil;&atilde;o n&atilde;o confere.' }
            }
        });

        // fale por e-mail
        $('#fale_email').validate({
            rules: {
                'nome': { required: true },
                'email': { required: true, email: true },
                'patrocinadora': { required: function(element) { return $(element).val() == '' } },
                'plano': { required: function(element) { return $(element).val() == '' } },
                'cpf': { required: true, cpf: true },
                'assunto': { required: function(element) { return $(element).val() == '' } },
                'mensagem': { required: true }
            },
            messages: {
                'nome': { required: 'Informe seu nome' },
                'email': { required: 'Informe seu e-mail', email: 'Informe um e-mail v&aacute;lido' },
                'patrocinadora': { required: 'Selecione um(a) patrocinador(a)' },
                'plano': { required: 'Selecione um plano' },
                'cpf': { required: 'Informe seu cpf', cpf: 'Informe um cpf v&aacute;lido' },
                'assunto': { required: 'Selecione um assunto' },
                'mensagem': { required: 'Digite sua mensagem' }
            }
        });
    },
    /*
    *   Busca
    *   @author Douglas Castilho <douglas.castilho@agenciaclick.com.br>
    */
    _busca: function() {
        $("#caps-search").submit(function() {
            $('#reg-list').removeHighlight()
            var conteudo = $("#c_name").val();
            $("#reg-list").highlight(conteudo);
            return false;
        });
    },
    /**
    *  Imagem do header randomica
    *  @author Douglas Castilho <douglas.castilho@agenciaclick.com.br>
    */
    _header: function() {
        var vRand = rand(1, 5); // número randomico de 1 a 5

        //Workaround pra fixar a imagem por Seção do Browser
        //A variável do input foi setada na full.master
        vRand = $("#headerImage").text();
        if (!vRand) { //Quando não vier valor por algum motivo, forçar o comportamento antigo
            var vRand = rand(1, 5); // número randomico de 1 a 5
        }

        var vFinal = 0;
        var url = window.location.href;

        if (url.indexOf("/home/") > -1) {
            $("#header").addClass("bgHome" + vRand);
            setInterval(bg, 15000)
        } else {
            $("#header").addClass("bgInterno" + vRand)
            setInterval(bgInterno, 15000)
        }
        function bg() {
            $("#header").removeClass("bgHome" + vFinal)
            if (vRand > 5) {
                vFinal = 1;
                vRand = 1;
            }
            vFinal = vRand++
            $("#header").addClass("bgHome" + vFinal)
        }
        function bgInterno() {
            $("#header").removeClass("bgInterno" + vFinal)
            if (vRand > 5) {
                vFinal = 1;
                vRand = 1;
            }
            vFinal = vRand++
            $("#header").addClass("bgInterno" + vFinal)

        }
        function rand(min, max) {
            return Math.floor((Math.random() * (max - min + 1)) + min);
        }
    },

    /**
    *  Insere um alinhamento right nos boxes de eventos
    *  @author Douglas Castilho <douglas.castilho@agenciaclick.com.br>
    */
    _calendario: function() {
        $('#events div.event:odd').css('float', 'right');
    },

    _igualaBox: function() {
        var a = $('#next-dates dl dd:first').height()
        var b = $('#next-dates dl dd:last').height()

        if (a >= b) {
            $('#next-dates dl dd:last').height(a + 'px')
        } else {
            $('#next-dates dl dd:fist').height(b + 'px')
        }
    },
    _pop: function() {
        $('.adobe-reader-download a').click(function() {
            var link = $(this).attr('href');
            window.open(link)
            return false
        });
    },
    _topContent: function() {
        $('document').ready(function() {
            if ($('#top-content h2').size() > 0) {
                $('#top-content').width('630px')
            }
        })
    },
    
    /**
    *  Remove a caixa de Tutorial
    *  @author Rafael Lazarini <joao.lazarini@agenciaclick.com.br>
    */
    _closeTutorial: function() {
        $('span.ocultar-tutorial').click(function(){
            $('#header-tutorial').animate({ 
                marginTop: "-74px"
              }, 1000);
        });
    }
};
