﻿

function AbrePopUp(url) {
    window.open(url, 'EP', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=570,height=640,top=10,left=10');
}

function AbrePopUpRedim(url, ancho, alto) {
    window.open(url, 'EP', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=' + ancho + ',height=' + alto + ',top=200,left=200');
}

function activaTab(marco, contenido, tab) {

    //buscamos la caja
    var todosdivs = document.getElementsByTagName("div");
    var encontrado = false;
    var j = todosdivs.length - 1;
    var caja;

    while (!encontrado && j >= 0) {
        if (todosdivs[j].id.indexOf(marco) != -1) {
            caja = todosdivs[j];
            encontrado = true;
        }
        j--;
    }

    if (encontrado) {

        var tabs = caja.getElementsByTagName("li"); //lista de li (tab)
        var conts = caja.getElementsByTagName("div"); //lista de DIVs   

        //tabs 
        for (var i = 0; i < tabs.length; i++) {
            if (tabs[i].id.indexOf(tab) == -1)
                tabs[i].className = "";
            else
                tabs[i].className = "tabActivo"; // tab activo
        }

        //divs    	
        for (var k = 0; k < conts.length; k++) {
            if (conts[k].id.indexOf(contenido) == -1)
                conts[k].style.display = "none";
            else
                conts[k].style.display = "block"; // contenido del div
        }

    }
}


function activaTabColumna(marco, contenido, tab) {

    //buscamos la caja
    var todosdivs = document.getElementsByTagName("div");
    var encontrado = false;
    var j = todosdivs.length - 1;
    var caja;

    while (!encontrado && j >= 0) {
        if (todosdivs[j].id.indexOf(marco) != -1) {
            caja = todosdivs[j];
            encontrado = true;
        }
        j--;
    }

    if (encontrado) {

        var tabs = caja.getElementsByTagName("li"); //lista de li (tab)
        var conts = caja.getElementsByTagName("div"); //lista de DIVs   

        //tabs 
        for (var i = 0; i < tabs.length; i++) {
            if (tabs[i].id.indexOf('link') > -1) {
                if (tabs[i].id.indexOf(tab) == -1)
                    tabs[i].className = "";
                else
                    tabs[i].className = "tabActivo"; // tab activo
            }
        }

        //divs    	
        for (var k = 0; k < conts.length; k++) {
            if (conts[k].id.indexOf('lista') > -1) {
                if (conts[k].id.indexOf(contenido) == -1)
                    conts[k].style.display = "none";
                else
                    conts[k].style.display = "block"; // contenido del div
            }
        }

    }
}


function redirectSectorial(codigo) {
    if (codigo != '')
        location.href = "http://www.europapress.es/economia/sector-" + codigo + ".html";
}

function trackEventGA(category, action) {
    try { _gaq.push(['_trackEvent', category, action, '', 0]); } catch (err) {}
    return true;
}

function trackEventGAFull(category, action, label, value) {
    try { _gaq.push(['_trackEvent', category, action, label, value]); } catch (err) {}
    return true;
}

function EP_loadBanner(t) {
    var l = document.getElementById("BannerLoad_" + t);
    var p = document.getElementById("BannerPlaceHolder_" + t);
    if (l != null && p != null) { p.appendChild(l); l.style.display = "block"; }
}

if (jQuery) {
    /* Ponemos el userId en el campo oculto y provocamos postback*/
    function facebook_onlogin() {
        var fbUserId = FB.Connect.get_loggedInUser();
        jQuery('.fbUidTb').attr('value', fbUserId);
        jQuery('.fbLoginButton').click();
    }

    (function ($) {
        $.fn.CuentaComentarios = function (conf) {
            var $elem = $(this);
            if (!conf || conf == undefined) {
                var f; var ff = []; var fechorRE = /\d{14}/;
                $(this).children().each(function () {
                    f = fechorRE.exec($(this).find("a:eq(0)").attr("href"));
                    if (f && f != undefined && f.length) ff.push(f[0]);
                });
                conf = { "cod": ff.join(" ") };
            }

            var processData = function (data) {
                if (data != undefined && data.length != undefined) {
                    var $noticias = $elem.children(":has(a)");
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].comentarios >= 0) {
                            var $noticia = $noticias.filter(":has(a[href*=-" + data[i].noticia + ".html])").not(":has(.comentarios_portada)").eq(0);
                            var $c = $("<div />").append("<img src=\"http://s01.europapress.net/imagenes/estaticos/t.gif\" alt=\"\" class=\"IEN_Comentarios\" />").addClass("comentarios_portada").hide();
                            var $a = $("<a />").attr("href", $noticia.find("a[href*=-" + data[i].noticia + ".html]:eq(0)").attr("href") + "#Comentarios");
                            if (data[i].comentarios == 0) $a.text("Deja tu comentario"); else if (data[i].comentarios == 1) $a.text("1 Comentario"); else $a.text(data[i].comentarios + " Comentarios");
                            $a.appendTo($c);
                            var $t = (conf.target && conf.target != undefined && conf.target != "" ? $noticia.find(conf.target) : $noticia);
                            $t.append($c);
                        }
                    }
                }
                $(".comentarios_portada:hidden").slideDown("fast", function () { try { $(window).resize(); } catch (err) { } });
            };

            if ((conf.gr && conf.gr != undefined) || ((conf.cod && conf.cod != undefined))) {
                var params = jQuery.extend({ "a": "contar" }, conf);
                $.getJSON("/ws/ComentariosNoticia_JSON.ashx", params, processData);
            } else if (conf.data && conf.data != undefined) {
                processData(conf.data);
            }
        };
    })(jQuery);

    (function ($) {
        jQuery.fn.ImgDelay = function (conf) {
            var defaultConfig = { margen: 300, dataArray: window.delayedLoadImg, resizeContainer: true };
            var config = jQuery.extend(defaultConfig, conf);

            var pendingImg = new Array();

            var delayedImgLoad = function () {
                var docViewTop = $(window).scrollTop();
                var docViewBottom = docViewTop + $(window).height();

                // No puedo usar $.each() porque voy quitando elementos dinámicamente...
                var i = 0; var item;
                while (i < pendingImg.length) {
                    item = pendingImg[i];
                    var elemTop = Math.round(item.offset().top) - config.margen; elemTop = (elemTop >= 0 ? elemTop : 0);
                    var elemBottom = Math.round(item.offset().top) + item.height() + config.margen; elemBottom = (elemBottom <= $(document).height() ? elemBottom : $(document).height());
                    var elemMiddle = (elemTop + elemBottom) / 2;

                    var visible = (((elemTop >= docViewTop) && (elemTop <= docViewBottom))
                              || ((elemBottom <= docViewBottom) && (elemBottom >= docViewTop)));

                    if (visible) {
                        pendingImg.splice(i, 1);
                        var $inner = $(item.find("noscript").remove().text());
                        var $img;
                        var data = item.data("delayedImgData");
                        if (data && !$inner.length) {
                            $img = $("<img />").attr("src", data.s).attr("alt", data.a).attr("border", "0").css("width", data.w);
                            if (data.h) $img.css("height", data.h);
                            if (data.l != "") {
                                $inner = $("<a>").attr("href", data.l).attr("title", data.t).append($img);
                                if (data.d != "") $inner.attr("target", data.d);
                            } else
                                $inner = $img;
                        } else {
                            $img = (($inner).is("img") ? $inner : $inner.find("img"));
                        }
                        $img.data("c", item);
                        if (config.resizeContainer) $img.bind("load", function () {
                            if ($(this).outerHeight() > 20) {
                                $(this).data("c").animate({ height: $(this).outerHeight() }, "fast");
                                $(this).unbind("load");
                            }
                        });
                        item.prepend($inner);
                        //$img.trigger("load");

                    } else {
                        i++;
                    }
                }

                if (!pendingImg.length) $(window).unbind("scroll", delayedImgLoad).unbind("resize", delayedImgLoad);
            }

            if (config.dataArray != undefined && config.dataArray.length > 0) {
                for (var i = 0; i < config.dataArray.length; i++) {
                    $(config.dataArray[i].c).data("delayedImgData", config.dataArray[i]);
                }
            }

            $(this).each(function () { pendingImg.push($(this)); });
            if (pendingImg.length) { delayedImgLoad(); $(window).bind("scroll", delayedImgLoad).bind("resize", delayedImgLoad); }

            return $(this);
        };
    })(jQuery);

    $(document).ready(function () {
        var $MenuSecciones = $("#MenuSecciones");
        if ($MenuSecciones.length > 0) $.each($MenuSecciones.attr("class").split(" "), function (i, $i) { $MenuSecciones.find("li." + $i).addClass("menu_seleccionado"); });
        var $MenuCanal = $("#MenuCanal");
        if ($MenuCanal.length && $MenuCanal.attr("class") && $MenuCanal.attr("class") != "") $.each($MenuCanal.attr("class").split(" "), function (i, $i) { $MenuCanal.find("." + $i).addClass("menu_seleccionado"); });

        $("#MenuSecciones .submenu").each(function () { if ($(this).width() < $(this).parent().outerWidth(false)) $(this).width($(this).parent().outerWidth(false)); });

        try { var _myTracker = _gat._getTrackerByName(); } catch (err) { }
     
        if ($("div.IEN_contador").length) {
            var url = $("link[rel=canonical], a[rel=canonical]").eq(0).attr("href");
            if (!url || url == "") {
                $("div.IEN_contador a[rel]").each(function (index) {
                    var aRel = $(this).attr("rel").match(/https?:\/\/[\w\-\.\/\?]*/);
                    if (aRel.length) {
                        url = aRel[0];
                        return false;
                    } else {
                        return true;
                    }
                });
            }
            $.ajax({ url: "http://titulares.europapress.es/UrlShareStats.ashx?url=" + url, dataType: "jsonp", jsonpCallback: "EP_Contadores_Callback", cache: true, success: function (data) {
                for (var sitio in data) {
                    if (data[sitio].contador > 0) {
                        var $c = $("div.IEN_" + sitio).find(".contador");
                        if ($c.length) {
                            $c.html(data[sitio].contador);
                        } else {
                            $c = $("<span />").addClass("globo_mini").append($("<span />").addClass("spike")).append($("<span />").addClass.addClass("inner").addClass("contador").html(data.facebook.contador)).filter("a").attr("href", data.facebook.accion);
                        }
                       if (data[sitio].accion && data[sitio].accion != "") $("div.IEN_" + sitio + " a").attr("href", data[sitio].accion);
                    }
                };
            }
            });
            $("div.IEN_contador").click(function () {
                if ($(this).find("span.contador").length) {
                    var k = parseInt($(this).find("span.contador").text());
                    $(this).find("span.contador").text(isNaN(k) ? "+1" : k + 1);
                } else {
                    var $a = $(this).find("a").length ? $(this).find("a") : $(this);
                    $a.append($("<span />").addClass("globo_mini").append($("<span />").addClass("spike")).append($("<span />").addClass("inner").addClass("contador").text("+1")));
                }
            });

        }

        if ($(".rotator_chance").length && $(".rotator_chance").rotatorEP) $(".rotator_chance").rotatorEP();
        if ($(".rotator_deportes").length && $(".rotator_deportes").rotatorEP) $(".rotator_deportes").rotatorEP({ timer: 5500 });

        if ($.superbox) {
            if ($("html").attr("lang") == "ca")
                $.superbox.settings = {
                    boxId: "superbox", // Id attribute of the "superbox" element
                    boxClasses: "", // Class of the "superbox" element
                    overlayOpacity: .8, // Background opaqueness
                    boxWidth: "550", // Default width of the box
                    boxHeight: "550", // Default height of the box
                    loadTxt: "Carregant...", // Loading text
                    closeTxt: "Tanqueu", // "Close" button text
                    prevTxt: "Anterior", // "Previous" button text
                    nextTxt: "Següent", // "Next" button text
                    beforeShow: function () { if (trac) trac.slideEvent('galeria'); } // Seguimiento de clicks de superbox (galerías)
                };
            else
                $.superbox.settings = {
                    boxId: "superbox", // Id attribute of the "superbox" element
                    boxClasses: "", // Class of the "superbox" element
                    overlayOpacity: .8, // Background opaqueness
                    boxWidth: "550", // Default width of the box
                    boxHeight: "550", // Default height of the box
                    loadTxt: "Cargando...", // Loading text
                    closeTxt: "Cerrar", // "Close" button text
                    prevTxt: "Anterior", // "Previous" button text
                    nextTxt: "Siguiente", // "Next" button text
                    beforeShow: function () { if (trac) trac.slideEvent('galeria'); } // Seguimiento de clicks de superbox (galerías)
                };
            $.superbox();
        }



        $(".scrollPage").click(function (event) {
            //http://beski.wordpress.com/2009/04/21/scroll-effect-with-local-anchors-jquery/
            //prevent the default action for the click event
            event.preventDefault();

            //split the url by # and get the anchor target name - home in mysitecom/index.htm#home
            var trgt = this.href.split("#")[1];

            //animate to top offset of the target anchor
            if ($("#" + trgt).length) $('html, body').animate({ scrollTop: $("#" + trgt).offset().top }, 500);
        });
        var $directorioLetra = $(".directorioLetraLabel");
        var $directorioCabecera = $("ul.directorioCabecera");
        if ($directorioLetra.length > 0) $.each($directorioLetra.attr("class").split(" "), function (i, $i) { $directorioCabecera.find("li." + $i).addClass("letraSeleccionado"); });
        if ($("#resultadosBusqueda div.resultado").length > 0) $("#resultadosBusqueda div.resultado").click(function () { window.location = $(this).find("a").attr("href"); });

        $(".img_delay").ImgDelay();
        $(".img_delay_fixed").ImgDelay({ resizeContainer: false });
    });


    /*!
    * Color animation jQuery-plugin
    * http://www.bitstorm.org/jquery/color-animation/
    * Based on code copyright 2007 John Resig
    * Copyright 2010 Edwin Martin <edwin@bitstorm.org>
    * Released under the MIT and GPL licenses.
    */

    (function (d) {
        function h(a, b, c) { return "#" + g(a[0] + c * (b[0] - a[0])) + g(a[1] + c * (b[1] - a[1])) + g(a[2] + c * (b[2] - a[2])) } function g(a) { a = parseInt(a).toString(16); return a.length == 1 ? "0" + a : a } function e(a) {
            var b, c; if (b = /#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(a)) c = [parseInt(b[1], 16), parseInt(b[2], 16), parseInt(b[3], 16)]; else if (b = /#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(a)) c = [parseInt(b[1], 16) * 17, parseInt(b[2], 16) * 17, parseInt(b[3], 16) * 17]; else if (b = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(a)) c = [parseInt(b[1]), parseInt(b[2]), parseInt(b[3])]; return c
        } var i = ["color", "backgroundColor", "borderBottomColor", "borderLeftColor", "borderRightColor", "borderTopColor", "outlineColor"]; d.each(i, function (a, b) { d.fx.step[b] = function (c) { if (!c.init) { c.a = e(d(c.elem).css(b)); c.end = e(c.end); c.init = true } c.elem.style[b] = h(c.a, c.end, c.pos) } }); d.fx.step.borderColor = function (a) {
            if (!a.init) a.end = e(a.end); var b = i.slice(2, 6); d.each(b, function (c, f) { a.init || (a[f] = { a: e(d(a.elem).css(f)) }); a.elem.style[f] = h(a[f].a, a.end, a.pos) });
            a.init = true
        }
    })(jQuery);


}
