// Callback para tag <script> criada on-the-fly pelo botão "curtir"
function curtirCallback(response) {
    var botao = $('.btn-curti-' + response.id_materia);
    var box = $('.box-curti-' + response.id_materia);
    if(response.resultado == 1) {
        box.hide();
        botao.html(response.curtiram + ' pessoas').css('color','#515151');
    } else if(response.resultado == 2) {
        box.hide();
        botao.html('você já curtiu').css('color','#cc0000');
    }
}

// Callback para tag <script> criada on-the-fly pelo form "interativo"
function enqueteCallback(response) {
    $("#lightbox-enquete-conteudo").html(response);
    $("#lightbox-enquete").lightbox_me({
        centered: true,
        closeSelector: '.close-button',
        onLoad: function() {}
    });
}

$(function(){

    // 10/01/2011 - Removido todo o código deprecated

    //Subnavegacao
    $("#navegacao").find('li').mouseover(function(){
      $(this).addClass('hover');
    }).mouseout(function(){
      $(this).removeClass('hover');
    });

    // Curtir matéria
    $('.btn-curti').click(function() {
        // Cria tag <script> com 'src' igual ao 'href' deste link,
        // que irá devolver código JavaScript com chamada para curtirCallback()
        var scriptElement = document.createElement('script');
        scriptElement.src = $(this).attr('href');
        document.getElementsByTagName('head')[0].appendChild(scriptElement);
        return false;
    });

    // Botão imprimir
    $('.btn-imprimir').click(function(){
        window.print();
        return false;
    });

    //Resize dos textos de matéria
    var current_size = 'resize-100';
    function resizeTextoMateria(tamanho, obj) {
        $('.materia-corpo-materia').removeClass(current_size).addClass('resize-'+tamanho);
        current_size = 'resize-'+tamanho;

        if(obj) {
            $('.text-resize .active').removeClass('active');
            obj.addClass('active');
        }
    }
    $('.text-resize-1').addClass('active');
    $('.text-resize-1').click(function(){
        resizeTextoMateria('100', $(this));
        return false;
    });
    $('.text-resize-2').click(function(){
        resizeTextoMateria('115', $(this));
        return false;
    });
    $('.text-resize-3').click(function(){
        resizeTextoMateria('130', $(this));
        return false;
    });

    // Fotos destaques home
    // Carrega as imagens do destaque
    $('#destaques-capa-left').find('a').each(function(e){
        jQuery.preLoadImages($(this).attr('href'));
        $(this).attr('title',e);
    });

    // Ini timer destaques
    var atual = 1;
    var destaques = $('#destaques-capa-left').find('a');

    // Seta intervalo entre a troca das imagems do destaque
    function setTimerDestaques() {
        intervaloDestaque = setInterval(function(){
            $(destaques[atual]).mouseover();
            if(atual < destaques.length - 1) {
                atual++;
            } else {
                atual = 0;
            }
        },5000);
    }
    setTimerDestaques();

    //Mouse over destaques
    $('#destaques-capa-left').find('a').mouseover(function(){
        //Imagem
        var img = $(this).attr('id');
        //Link do clique na imagem maior
        var link = $(this).attr('href');
        var imgDestaque = $('<img />');
        var linkDestaque = $('<a></a>');
        var targetDestaque = $(this).attr('target');
        //
        $('#destaques-capa-left').find('a').each(function(){
            $(this).removeClass('active');
        });
        $(this).addClass('active');
        //
        imgDestaque.attr('src',img);
        linkDestaque.attr('href',link);
        linkDestaque.attr('target',targetDestaque);
        linkDestaque.append(imgDestaque);

        $("#destaques-capa-right").html(linkDestaque);

        clearInterval(intervaloDestaque);
        atual = $(this).attr('title');
        setTimerDestaques();
    });

    $('#destaques-capa-left').find('a:first').mouseover();

    //Lightbox enquete
    $('.btn-enviar-enquete').click(function(e) {
        var action = $('#form_enquete').attr('action');
        var dados = $('#form_enquete').serialize();

        // Cria tag <script> com 'src' igual ao 'action' deste form,
        // que irá devolver HTML via callback
        var scriptElement = document.createElement('script');
        scriptElement.src = action + '?' + dados;
        document.getElementsByTagName('head')[0].appendChild(scriptElement);

        e.preventDefault();
        return false;
    });

    // Lighbox de clippings
    $('.lb-clipping').click(function(){
        var img = $('<img/>');

        var src = $(this).attr('href');
        img.attr('src',src);

        $('.lb-img-clipping').html(img);

        img.load(function(){
            ww = $(window).width();
            wh = $(window).height();
            imgw = img.width();
            imgh = img.height();

            wcenter = (ww / 2) - (imgw / 2);
            hcenter = (wh / 2) - (imgh / 2);
            $('.close-button').hide();
            img.hide();

            $('#lightbox-clipping').css({width:0, height:0, 'left': ww /2 + 'px', 'top': wh / 2 + 'px'});
            $('#lightbox-clipping').animate({width:imgw, height:imgh, left:wcenter, top:hcenter}, function(){
                img.fadeIn();
            });
        });

        $("#lightbox-clipping").modal({
            closeClass: 'close-button',
            closeEsc: true,
            overlayClose: true,
            overlayCss: {backgroundColor:"#000"},
            opacity: 80,
            position: ['20%', null],
            onOpen: function(dialog) {
                dialog.overlay.fadeIn();
                dialog.container.fadeIn();
                dialog.data.fadeIn(function(){
                    $('.close-button').fadeIn();
                });
            }

        });
        return false;
    });


    // Carrega todas imagens antes de mostrar no lightbox
    $('.lb-clipping').each(function(){
        jQuery.preLoadImages($(this).attr('href'));
    });


    // Lightbox diversão
    $('.game-trigger').click(function(){

        ww = $(window).width();
        wh = $(window).height();
        imgw = $("#lightbox-diversao").width();
        imgh = $("#lightbox-diversao").height() + 30;
        img = $("#lightbox-diversao").hide();
        wcenter = (ww / 2) - (imgw / 2);
        hcenter = (wh / 2) - (imgh / 2);

        $("#lightbox-diversao").modal({
            closeClass: 'close-button',
            closeEsc: true,
            overlayClose: true,
            overlayCss: {backgroundColor:"#000"},
            opacity: 80,
            position: ['10%', null],
            onOpen: function(dialog) {
                dialog.overlay.fadeIn();
                dialog.container.fadeIn();
                dialog.data.fadeIn(function(){
                    $('.close-button').fadeIn();
                });
            }
        });

        $('#lightbox-diversao-game').find('iframe').attr('src',$(this).attr('href'));
        $('#lightbox-diversao-titulo').html($(this).attr('title'));

        $('#lightbox-diversao').css({width:0, height:0, 'left': ww /2 + 'px', 'top': wh / 2 + 'px'});
        $('#lightbox-diversao').animate({width:imgw, height:imgh, left:wcenter, top:hcenter}, function(){
            img.fadeIn();
        });

        return false;
    });
    // Botão Favoritos
    $('.favoritos').jFav();
});

// Preload de imagens
(function($) {
    var cache = [];
    // Arguments are image paths relative to the current page.
    $.preLoadImages = function() {
        var args_len = arguments.length;
        for (var i = args_len; i--;) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery);

function showSubNav() {
    if($('#subnav').find('.hidden').length != $('#subnav').find('ul').length) {
        $('#subnav').show();
    }
}

// Quantidade de views do youtube
function getYoutubeViews(videoId) {
    var url = 'http://gdata.youtube.com/feeds/api/videos?q='+videoId+'&alt=json&max-results=1';
    $.getJSON(url, function(data) {
        if (data && data.feed.entry) {
            viewCount = data.feed.entry[0].yt$statistics.viewCount;
            viewCountFormatted = '';
            for(i=1; i <= viewCount.length; i++) {
                if(i % 3 == 0) {
                    viewCountFormatted += viewCount[viewCount.length - i] + ',';
                } else {
                    viewCountFormatted += viewCount[viewCount.length - i];
                }
            }
            if(viewCountFormatted[viewCountFormatted.lastIndexOf(',')] == viewCountFormatted[viewCountFormatted.length -1]) {
                viewCountFormatted = viewCountFormatted.slice(0,-1);
            }
            viewCountFormatted = viewCountFormatted.split("").reverse().join("");
            $('.count-'+videoId).html(viewCountFormatted);
        }
        else {
            $('.views-count').hide();
        }
    });
}

// Mostrar data
function currentDate() {
    var current_date = new Date();
    var display_date;
    var month_names = [
        "Janeiro",
        "Fevereiro",
        "Março",
        "Abril",
        "Maio",
        "Junho",
        "Julho",
        "Agosto",
        "Setembro",
        "Outubro",
        "Novembro",
        "Dezembro"
    ];

    var dia = current_date.getDate();
    if (dia < 10) {
        dia = '0'+dia;
    }

    display_date = dia;
    display_date +=  " de " + month_names[current_date.getMonth()];
    display_date += " de " + current_date.getFullYear();

    $('#header-current-date').html(display_date);
}

