﻿var scrollInicialProgramacionTele;
var ColbensonRelURL;
var ItemsGaleriaFaldon;


function cargaItemGaleriaFaldon(i){
    if (ItemsGaleriaFaldon && ItemsGaleriaFaldon.length > i && !ItemsGaleriaFaldon[i].cargado) {
        var $items = $("#galeria_portada_central .items");
        var $boxes = $("#galeria_portada_central_boxes");
        
        var item = ItemsGaleriaFaldon[i]
        var $img = $("<img />").attr({src:item.URL_thumb, title:item.titulo, alt:item.titulo});
        var $a = $("<a />").attr({href:"#foto_screen_"+item.id, rel:"superbox[content#superbox.superbox_galeria_central]", title:item.titulo});
        $a.append($img);
        $items.append($("<li />").addClass("item").append($a));

        item.cargado = true;
        if ($img.height() < 150 && $img.height() > 17) $img.css({ position: 'relative', top: (150 - $img.height()) / 2 })
        
        var $img2 = $("<img />").attr({src:item.URL, title:item.titulo, alt:item.titulo});
        var $a2 = $("<a />").attr({href:item.link, title:item.titulo});
        var $a3 = $("<a />").attr({href:item.link, title:item.titulo}).html(item.titulo);
        var $caption = $("<div />").addClass("caption h4");
        $caption.append($a3);
        $a2.append($img2)
        $boxes.append($("<div />").attr("id", "foto_screen_"+item.id).addClass("superbox_fotogaleria").append($a2).append($caption));
        
        $("a[rel^=superbox],area[rel^=superbox]").unbind("click");
        $.superbox();
        
        return true;

    } else {
    
        return false;
    }
}

function playStopGaleriaFaldon() {
    var elem = $(".scrollable");
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = elem.offset().top;
    var elemBottom = elemTop + elem.height();
    var elemMiddle = (elemTop + elemBottom) / 2;

    var visible = (((elemTop >= docViewTop) && (elemMiddle <= docViewBottom))
      || ((elemBottom <= docViewBottom) &&  (elemMiddle >= docViewTop)) );

    if (visible) elem.scrollable().play(); else elem.scrollable().stop();
}
    
(function ($) {
    $.fn.rotatorFotos = function (conf) {
        var defaultConfig = { timer: 4000, timerMouseOut: 1000 };
        var config = jQuery.extend(defaultConfig, conf);
        config.timerControl = null;
        var BTN_OFFSET = {"top":3, "prevLeft":5, "nextRight":21 }

        if ($(this).find('.item').length > 1) {
            var maxItemHeight = 0;
            var container = $(this);

            var rotate = function() {
                var docViewTop = $(window).scrollTop();
                var docViewBottom = docViewTop + $(window).height();

                var elemTop = container.offset().top;
                var elemBottom = elemTop + container.height();
                var elemMiddle = (elemTop + elemBottom) / 2;

                var visible = (((elemTop >= docViewTop) && (elemMiddle <= docViewBottom))
                            || ((elemBottom <= docViewBottom) && (elemMiddle >= docViewTop)));

                // Sólo animo la rotación si el elemento está visible
                if (visible)  move(1);
            };

            var move = function (direccion) {
                var $actual = container.find('.item.activo');

                var nuevo;
                if (direccion >= 0) {
                    nuevo = $actual.next('.item');
                    if (!nuevo.is('.item')) { nuevo = container.find('.item:first') };
                } else if (direccion < 0) {
                    nuevo = $actual.prev('.item');
                    if (!nuevo.is('.item')) nuevo = container.find('.item:last');
                }

                if (nuevo.is('.item')) {
                    if (nuevo.find("img").length == 0) {
                        var img = container.find("img").eq(0).clone();
                        img.attr("src", nuevo.find("a[rel]").attr("rel"));
                        if (nuevo.find(".title").length) img.attr("alt", nuevo.find(".title").text());
                        img.appendTo(nuevo.find(".crop a").empty());
                    }

                    $actual.removeClass('activo').fadeOut('fast', function () { nuevo.addClass('activo').fadeIn('fast'); });
                }

                var pos = container.position();
                var posBotonPrev = container.find('.control_scroll').position();

                if (posBotonPrev.top != pos.top + BTN_OFFSET.top || posBotonPrev.left != pos.left + BTN_OFFSET.prevLeft) {
                    container.find('.prev').css({ top: pos.top + BTN_OFFSET.top, left: pos.left + BTN_OFFSET.prevLeft });
                    container.find('.next').css({ top: pos.top + BTN_OFFSET.top, left: pos.left + container.width() - BTN_OFFSET.nextRight });
                }

                return false;
            };

            $(this).hover(function () {
                if (config.timerControl) {
                    clearInterval(config.timerControl);
                    config.timerControl = null;
                }
            }, function () {
                if (config.timerControl) clearInterval(config.timerControl);
                setTimeout(rotate, config.timerMouseOut);
                config.timerControl = setInterval(rotate, config.timer);

            }).find('.item').each(function () {
                if ($(this).height() > maxItemHeight) maxItemHeight = $(this).height();
            }
            ).css('height', maxItemHeight)
            .filter(':gt(0)').hide().removeClass('activo');

            $nav = $(this).find('.header');
            $('<a class="control_scroll prev" title="Anterior"><span>|&lt;</span></a>').click(function () { move(-1); }).css({ position: 'absolute', top: $nav.position().top + BTN_OFFSET.top, left: $nav.position().left + BTN_OFFSET.prevLeft }).prependTo($nav);
            $('<a class="control_scroll next" title="Siguiente"><span>&gt;|</span></a>').click(function () { move(1); }).css({ position: 'absolute', top: $nav.position().top + BTN_OFFSET.top, left: $nav.position().left + $nav.width() - BTN_OFFSET.nextRight }).appendTo($nav);

            $(this).find('.item:eq(0)').addClass('activo');
            if (config.timerControl) clearInterval(config.timerControl);
            config.timerControl = setInterval(rotate, config.timer);

            $(window).resize(function () {
                var pos = container.position();
                var posBotonPrev = container.find('.control_scroll').position();
                if (posBotonPrev.top != pos.top + BTN_OFFSET.top || posBotonPrev.left != pos.left + BTN_OFFSET.prevLeft) {
                    container.find('.prev').css({ top: pos.top + BTN_OFFSET.top, left: pos.left + BTN_OFFSET.prevLeft });
                    container.find('.next').css({ top: pos.top + BTN_OFFSET.top, left: pos.left + container.width() - BTN_OFFSET.nextRight });
                }
            });
        }
    };
})(jQuery);

$(document).ready(function () {
    var MGF_TIMEOUT = 7000;
    var SCROLL_INTERVAL = 4000;
    var mgf_timeout_id;
    var mgf_rotate = true;
    $('ul.mgf_thumbs').galleria({
        insert: '.mgf_container .mgf_imagen',
        onImage: function (image, caption, thumb) {
            if (mgf_timeout_id) clearTimeout(mgf_timeout_id);
            $('ul.mgf_thumbs div.visible').hide().removeClass("visible");
            var height = $('div.mgf_container').height();
            var link = thumb.parent().find('a[rel!=img]');
            if (link.is('a') && link.attr('href') && link.attr('href').length > 1) {
                image.click(function () { window.location.href = link.attr('href'); });
                image.css('cursor', 'pointer');
            }
            image.css('display', 'none').fadeIn('fast');
            var $box = thumb.parent().find('div:eq(0)');
            var offset = $box.outerHeight() - height * 0.4; offset = (offset < 0 ? 0 : -offset);
            if (!$box.has(".comentarios_portada")) offset -= 15;
            var pos = $('div.mgf_container').position();
            $box.css({ position: "absolute", top: pos.top + height * 0.6 + offset, left: pos.left }).fadeIn('fast').addClass("visible").fadeTo('fast', 0.75);


            if (mgf_rotate) {
                clearTimeout(mgf_timeout_id);
                mgf_timeout_id = setTimeout('$.galleria.next();', MGF_TIMEOUT);
            }
        },
        history: false,
        clickNext: false
    });
    // Marcado Nielsen de la interacción del usuario
    $('.mgf_thumbs img').click(function () { if (trac) trac.slideEvent('galeria'); });

    $('.mgf_container > .mgf_imagen > img').remove();
    $('.mgf_container > .mgf_imagen > div.mgf_caption').remove();
    $('.mgf_container').hover(function () { if (mgf_timeout_id) { mgf_rotate = false; clearTimeout(mgf_timeout_id); mgf_timeout_id = null; } },
        function () { mgf_rotate = true; mgf_timeout_id = setTimeout('$.galleria.next();', 1000); });

    $(".scrollable_parent").append($("<a />").addClass("control_scroll prev").attr("title", "Anterior").html("<span>|&lt;</span>"));
    $(".scrollable_parent").append($("<a />").addClass("control_scroll next").attr("title", "Siguiente").html("<span>&gt;|</span>"));

    $(".scrollable").scrollable({ speed: 800, loop: true, onBeforeSeek: function () { if (cargaItemGaleriaFaldon(this.getSize())) this.reload() } }).autoscroll({ interval: SCROLL_INTERVAL, autoplay: false });
    setTimeout('playStopGaleriaFaldon();', SCROLL_INTERVAL);
    $(window).scroll(function () { playStopGaleriaFaldon(); });

    $('.scrollable .items .item img').each(function () {
        if ($(this) && $(this).height() && $(this).height() < 150 && $(this).height() > 17) $(this).css({ position: 'relative', top: (150 - $(this).height()) / 2 });
    });

    if ($('div.programacion_tele').length) {
        // Asumo que si existe el elemento también está definida la variable
        $('div.programacion_tele').animate({ scrollLeft: scrollInicialProgramacionTele * 4 - $('div.programacion_tele').width() / 2 });

        $('div.programacion_tele .programacion .title').each(function () {
            $(this).mouseover(function (event) {
                $('#tooltip').remove();
                var me = $(this);
                // Quitamos el title para que no muestre el tooltip del navegador
                me.data('title', me.attr('title'));
                me.removeAttr('title');

                var tooltip = $('<div id="tooltip"></div>').hide();
                tooltip.append('<h1 class="title h1">' + me.data('title') + '</h1>')

                tooltip.append(me.parent().find('p').html());
                tooltip.css({ position: 'absolute', top: event.pageY - 50, left: event.pageX + 40, 'z-index': 1000, width: '300px', background: '#FFF', border: 'solid 1px #333', padding: '8px' }).appendTo('body').show();

            });
            $(this).mouseout(function () {
                $('#tooltip').remove();
                var me = $(this);
                me.data('title');
                me.attr('title', me.data('title'));
                me.removeData('title');
            });
        });

        $(".tele").append($("<a />").addClass("control_scroll prev").attr("title", "Anterior").html("<span>|&lt;</span>").click(function () { $('div.programacion_tele').animate({ scrollLeft: $('div.programacion_tele').scrollLeft() - 480 }); }));
        $(".tele").append($("<a />").addClass("control_scroll next").attr("title", "Siguiente").html("<span>&gt;|</span>").click(function () { $('div.programacion_tele').animate({ scrollLeft: $('div.programacion_tele').scrollLeft() + 480 }); }));
    }

    $('.secundario #videos_portada_derecha').rotatorFotos({ timer: 5000 });
    $('.secundario #cartelera').rotatorFotos();

    $(".scrollable_parent, .tele").find(".control_scroll").each(function (i, a) {
        var offset = $(a).hasClass("next") ? 40 : 90;
        var p = $(a).parent();
        $(a).css({ position: 'absolute', top: p.position().top + 7, left: p.position().left + p.width() - offset });
        $(window).resize(function () { $(a).css({ top: p.position().top + 7, left: p.position().left + p.width() - offset }); });
    });

 
});

function doRelacionadasChance(selector, texto, relacionadas) {
    var $cont = $(selector);
    $cont.hide();
    if (!relacionadas || relacionadas.length == 0) {
        $cont.remove();
        return false;
    }
    var ul = $('<ul />');
    $.each(relacionadas, function (i, item) {
        li = $('<li />');
        $('<a />').attr('href', item.url).attr('onclick', 'trackEventGA(\'Relacionadas\', \'click\');').html(item.titular).appendTo(li);
        li.append(' ');
        $('<span />').addClass('fecha').html('(' + item.fecha + ')').appendTo(li);
        li.appendTo(ul);
    });
    $cont.empty();
    var header = $('<h3 />').addClass('header').html(texto);
    $cont.append(header);
    ul.appendTo($cont);
    $cont.slideDown('normal', function () { try { $(window).trigger("resize"); } catch (err) { } });
    return false;
};

