﻿String.prototype.startsWith = function(s) { return this.indexOf(s)==0; }
        
// Añado operador :dvisible para emular el compartamiento < jQuery-1.3.2 para calcular la visibilidad de un objeto, esto lo utilizo en algunos sitios
jQuery.extend( jQuery.expr[ ":" ],  { dvisible: function (a) { return jQuery(a).css("display") != "none" }} );

function isInteger(val)
{
	if (isBlank(val)){return false;}
	for(var i=0;i<val.length;i++){
		if(!isDigit(val.charAt(i))){return false;}
		}
	return true;
}

function isBlank(val){
	if(val==null){return true;}
	for(var i=0;i<val.length;i++) {
		if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){return false;}
		}
	return true;
}

function isDigit(num) {
	if (num.length>1){return false;}
	var string="1234567890";
	if (string.indexOf(num)!=-1){return true;}
	return false;
}

function cimg(filename, pie)
{
    document.getElementById('imagen').src = filename;
    document.getElementById('textopie').innerHTML = pie;
}

function dameAlto(objeto)
{
    document.write(this.height);
}

function iniciarCampo(objeto)
{
    if (objeto.value == "Escriba aquí su búsqueda...") objeto.value = "";
    objeto.style.color = "#222222";
    objeto.style.background = "#EEEEEE";
}

function olvidarCampo(objeto)
{
    if (objeto.value == "")
    {
        objeto.value = "Escriba aquí su búsqueda...";
        objeto.style.color = "#BBBBBB";
    }
    else
    {
        objeto.style.color = "#222222";
    }
    objeto.style.background = "#FFFFFF";
}

function desplegar(objeto)
{
    if (objeto.src.indexOf("menos.gif") >= 0)
    {
        objeto.src = "../inc/img/mas.gif";
        objeto.parentNode.childNodes[3].className = "oculto";
    }
    else if (objeto.src.indexOf("mas.gif") >= 0)
    {
        objeto.src = "../inc/img/menos.gif";
        objeto.parentNode.childNodes[3].className = "visible";
    }
}

function desplegaro(objeto)
{
    img = objeto.parentNode.childNodes[0];
    ul = objeto.parentNode.childNodes[3];

    if (img.src.indexOf("menos.gif") >= 0)
    {
        ul.addClass("oculto");
        img.src = "../inc/img/mas.gif";
    }
    else
    {
        ul.addClass("oculto");
        img.src = "../inc/img/menos.gif";
    }
}

function desplegarObj(sender, obj)
{
    objeto = document.getElementById(obj);
        
    if (sender.src.indexOf("menos.gif") >= 0)
    {
        sender.src = "/inc/img/mas.gif";
        // objeto.style.display = "none";
		$(objeto).slideUp("fast");
    }
    else
    {
        sender.src = "/inc/img/menos.gif";
        //objeto.style.display = "block";
		$(objeto).slideDown("slow");
    }
}

function mostrarFicha(ficha)
{
    var fichas = document.getElementById("contenedorFichas").getElementsByTagName("DIV");
    
    for (var i = 0; i < fichas.length; i++)
    {
		if (fichas[i].style.display == "block")
		{
			// fichas[i].style.display = "none";
			$(fichas[i]).css("display","none");
		}
    }
	
	
	
	$("div#" + ficha).fadeIn("slow");
	
    // document.getElementById(ficha).style.display = "block";
	// $(document).find("Ficha1").css("display","block");
	
}

function pause(Amount)
{
    d = new Date() //today's date
    while (1)
    {
        mill=new Date() // Date Now
        diff = mill-d //difference in milliseconds
        if( diff > Amount ) {break;}
    }
}

function mostrarPopup(id)
{
    $("div#" + id).show();
}

function ocultarPopup(id)
{
    $("div#" + id).hide();
}

function desplegarDetallesFichaObra(div, _this)
{
    var obj = $(div)[0];

    if($(obj).css("display") == "none")
    {
        $(obj).slideDown();
        $(_this).css("background", "#eeeeee url(/inc/img/iconos/circulo_flecha_up_gris.gif) no-repeat 10px 50%");
    }
    else
    {
        $(obj).slideUp();
        $(_this).css("background", "#eeeeee url(/inc/img/iconos/circulo_flecha_down_gris.gif) no-repeat 10px 50%");
    }
}

function CrearNotas(ch, nosup)
{
    var contador = 1;
    if (ch) contador = ch;

    $("img.nota").each
    (
        function()
        {
            var idnota = $(this).attr("alt");
            
            if (nosup)
            {
                $(this).replaceWith("<span class=\"referencia\" id=\"nota-" + idnota + "\">" + contador + "</span>");
            }
            else
            {
                $(this).replaceWith("<sup class=\"referencia\" id=\"nota-" + idnota + "\">" + contador + "</sup>");
            }
            
            if (!ch) contador++;
        }
    );
    
    $(".referencia").click
    (
        function()
        {
            var idnota = $(this).attr("id").split("-")[1];
            var result = false;
            
            ImgNotaNow = $(this);
            $("div.extraPopupWrapper").remove();
            
            if (idnota != "null")
            {
				$.post
				(
					"/inc/GetNota.aspx",
					{ idnota: idnota },
                    function(data, result)
                    {
                        if (data != "error")
                        {
                            $(ImgNotaNow).after(data);
                           
                            var popup = $("div.extraPopup");
                            var ancho = $(popup).outerWidth();
                            var left = $(popup).offset().left;
                            var anchodoc = $(window).width();
                            
                            if (ancho + left > anchodoc)
                            {
                                $(popup).css("left", "-370px");
                                $(popup).find("div.top").css("background-image", "url(/inc/img/topmodalpopup.right.gif)")
                                        .find("img.cerrarPopup").css("right", "26px");
                            }
                        }
                        else
                        {
                            alert("Se produjo un error inesperado al cargar la nota.");
                        }
                    }
				);
            }
        }
    );
}

function PopupTituladosIndividuo(icono, idindividuo,idtitulo)
{
    if (idindividuo && idtitulo)
    {
        $("div.extraPopupWrapper").remove();
        
        $.get
        (
            "/inc/GetPopupTituladosIndividuo.aspx",
            { idindividuo: idindividuo, idtitulo: idtitulo },
            function (data, result)
            {
                if (data != "error" && result == "success")
                {
                    $("div.Popup").remove();
                    $(icono).after(data);
                    
                    var VerticalPosition = $("div.Popup div.bottom tr.seleccionada").position().top;
                    
                    if (VerticalPosition > 150)
                    {
                        VerticalPosition = VerticalPosition - 150;
                        $("div.Popup div.bottom").scrollTop(VerticalPosition);
                    }
                }
                else
                {
                    alert("Se produjo un error inesperado al cargar la nota.");
                }
            }
        );
    }
}

function CrearNotaTng(icono_obj, idnota)
{       
    var e = $(icono_obj).next()[0];
    
    if ($(e).hasClass("extraPopupWrapper"))
        return false;

    if (idnota)
    {
        $("div.extraPopupWrapper").remove();
        
        $.post
        (
            "/inc/GetNotaTng.aspx",
            { idnota: idnota },
            function(data, result)
            {
                if (data != "error")
                {
                    $(icono_obj).after(replaceURLWithHTMLLinks(data));
                }
                else
                {
                    alert("Se produjo un error inesperado al cargar la nota.");
                }
            }
        );
    }
    else
    {
        alert("Se produjo un error inesperado al cargar la nota.");
    }
}

function replaceURLWithHTMLLinks(text)
{
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>");
}

function PopupArticulo(url,titulo)
{
    nw = window.open(url, titulo, "width=880,height=690,top=100,left=100,scrollbars=YES,resizable=YES,status=NO,toolbar=NO,menubar=NO,directories=NO,location=NO,titlebar=NO");
    if (window.focus) nw.focus();
}

function Popup(url, nombre, width, height)
{
    var _width = "880";
    var _height = "690";
    
    if (width) _width = width;
    if (height) _height = height;

    nw = window.open(url, nombre, "width=" + _width + ",height=" + _height + ",top=100,left=100,scrollbars=YES,resizable=YES,status=NO,toolbar=NO,menubar=NO,directories=NO,location=NO,titlebar=NO");
    if (window.focus) nw.focus();
}

function disableEnterKey(e)
{
     var key;     
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox     

     return (key != 13);
}

function EnterKey(e, llamada)
{
     var key;     
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox     

     if (key == 13)
     {
        llamada();
        return false;
     }

    return true;
}

function BuscaRutaPopup(monumento, origen)
{
    window.open("/monumentos/comollegar.aspx?monumento=" + monumento + "&origen=" + origen, "Cómo llegar", "width=880,height=690,top=100,left=100,scrollbars=YES,resizable=YES,status=NO,toolbar=NO,menubar=NO,directories=NO,location=NO,titlebar=NO");
}













function ActivaPopupsTitulados()
{
    $("img.ImgVerPersonajes")
    .click
    (
        function()
        {
            $("div.Popup").hide();
            $(this).attr({ src: "/inc/img/loading.gif" });
            GeneraListasServ.GetPersonajesSegunTitulo(this.alt, OnCompletePersonajes, OnTimeOut, OnError);
            ObjImg = this;
        }
    );
}

function ActivaPopupsTitulos()
{
    $("img.ImgVerTitulos")
    .click
    (
        function()
        {
            $("div.Popup").hide();
            $(this).attr({ src: "/inc/img/loading.gif" });
            GeneraListasServ.GetTitulosSegunCasa(this.alt, OnCompleteTitulos, OnTimeOut, OnError);
            ObjImg = this;
        }
    );
}

function OnCompletePersonajes(arg)
{
    $(ObjImg).parent().append(arg);
    $(ObjImg).attr({ src: "/inc/img/iconos/rel_ind.gif" });
    
    $("img.cerrarPopup")
    .click
    (
        function()
        {
            $(this).parent().parent().slideUp("fast");
            $(ObjImg).attr({ src: "/inc/img/iconos/rel_ind.gif" });
        }
    );
}
        
function OnCompleteTitulos(arg)
{
    $(ObjImg).parent().append(arg);
    $(ObjImg).attr({ src: "/inc/img/iconos/rel_tit.gif" });
    
    $("img.cerrarPopup")
    .click
    (
        function()
        {
            $(this).parent().parent().slideUp("fast");
            $(ObjImg).attr({ src: "/inc/img/iconos/rel_tit.gif" });
        }
    );
}

function OnTimeOut(arg) { alert("TimeOut encountered when calling Say Hello."); }
function OnError(arg) { alert("Error encountered when calling Say Hello."); }

function ModificacionesTablaDatosLateral()
{
    $("table.TablaIntegradaDesplegables tr")
    .mouseover( function() { $(this).addClass("over"); } )
    .mouseout( function() { $(this).removeClass("over"); } );
}

function CrearNotasAyuda()
{
    $('img.ImgHelp')
    .mouseover(function()
    {
        $(this).attr("src","/inc/img/iconos/circulo_help_over.gif");
        $(this).parent().next().slideDown("fast");
    })
    .mouseout(function()
    {
        $(this).attr("src","/inc/img/iconos/circulo_help.gif");
        $(this).parent().next().slideUp("fast");
    })
}

function PrepararDivsLaterales()
{
    $("div.datoslateral div h3").
    click
    (
        function()
        {
            var obj = $(this).nextAll(":not(.ImgHelp)")[0]
            
            if ($(obj).is(":visible"))
            {
                $(obj).slideUp("slow");
                $(this).addClass("plegado");
            }
            else
            {
                $(obj).slideDown("slow");
                $(this).removeClass("plegado");
            }
        }
    );
    
    $("div.oculto").each
    (
        function()
        {
            $(this).children("h3").addClass("plegado");
            $(this).children("div").filter(":not(.ImgHelp)").hide();
        }
    );
}

function PrepararPaginacion()
{
    var paginas = $("div.PaginaDosificada");
    var num = paginas.length;
    var actual = 1;
    
    if (paginas.find("h4").length > 0)
    {
        var indice = $("span.MsgIndice").length ? $("span.MsgIndice").text() : "Índice";
    
        // Generación del índice
        $("div.PaginaDosificada").eq(0).before(
            "<div class=\"IndicePaginas\">" +
            "<h4>" + indice + "</h4>" +
            "  <ol></ol>" + 
            "</div>");
        
        
        $("div.IndicePaginas ol").hide();
        
        $("div.IndicePaginas h4")
        .click
        (
            function()
            {
                var enabled = $(this).hasClass("enabled");
                
                if (enabled)
                {
                    $(this).next().hide("fast");
                    $(this).removeClass("enabled");
                }
                else
                { 
                    $(this).next().show("fast");
                    $(this).addClass("enabled");
                }
            }
        );
        
        // Recorriendo los títulos
        var auxcount = 0;
        $("div.PaginaDosificada h4").each
        (
           function()
           {
                auxcount++; // Contador
                var titulo = $(this).html();
                var idpage = $(this).parent().attr("id");
                $("div.IndicePaginas ol").append("<li class=\"" + idpage + "\">" + titulo + "</li>");
                $("div.IndicePaginas").find("sup").remove();
                
                // Enumerar
                $(this).prepend(auxcount + ".&nbsp;&nbsp;");
                
                $("div.IndicePaginas ol li")
                .click
                (
                    function()
                    {
                        var idpage = $(this).attr("class");
                        $(paginas).hide().removeClass("Actual");
                        $("div#" + idpage).show().addClass("Actual");
                        actual = parseInt(idpage.substr(3, idpage.length));
                        $("span#PaginadorIndicador").html(actual);
                        
                        if (actual == num)
                        {
                            $("span#PaginadorSiguiente").hide();
                            $("span#PaginadorAnterior").show();
                        }
                        else if (actual == 1)
                        {
                            $("span#PaginadorSiguiente").show();
                            $("span#PaginadorAnterior").hide();
                        }
                        else
                        {
                            $("span#PaginadorSiguiente").show();
                            $("span#PaginadorAnterior").show();
                        }
                    }
                );
           }
        )
    }
      
    if (paginas.length <= 1) $("div#paginador").hide();
    
    $(paginas).not(".Actual").hide();
    $("span#PaginadorAnterior").hide();
    if (num == 1) $("span#PaginadorSiguiente").hide();
    
    $("span#PaginadorSiguiente").click
    (
        function()
        {
            var obj = $(paginas).filter(".Actual")[0];
            $(obj).removeClass("Actual");
            
            if ($(obj).next().hasClass("PaginaDosificada"))
            {
                $(obj).next().addClass("Actual").show();
                $(paginas).not(".Actual").hide();
                actual = actual + 1;
                $("span#PaginadorIndicador").html(actual);
                if (actual == num) $("span#PaginadorSiguiente").hide();
                $("span#PaginadorAnterior").show();
            }
        }
    );
    
    $("span#PaginadorAnterior").click
    (
        function()
        {
            var obj = $(paginas).filter(".Actual")[0];
            $(obj).removeClass("Actual");
            
            if ($(obj).prev().hasClass("PaginaDosificada"))
            {
                $(obj).prev().addClass("Actual").show();
                $(paginas).not(".Actual").hide();
                actual = actual - 1;
                $("span#PaginadorIndicador").html(actual);
                if (actual == 1) $("span#PaginadorAnterior").hide();
                $("span#PaginadorSiguiente").show();
            }
        }
    );
}

function PrepararPopupsSucesionTransmision()
{
    $("ol.hijos li a.EnlaceSucesionTransmision").each
    (
        function()
        {
            if ($(this).parent().hasClass("sucesion") || $(this).parent().hasClass("transmision"))
            {
                $(this).cluetip({ showTitle: false, width: 220, cluetipClass: "fcdm", attribute: "id" });                
            }
        }
    );
}

function GetListaTitulosFromCasa(sender, idcasa)
{
    var Visible = $(sender).next().is(":visible");   
    var YaCargado = $(sender).next().is("div.Popup");
    var SrcOriginal = $(sender).attr("src");

    $("div.Popup").hide();
    
    if (YaCargado)
    {
        if (!Visible) $(sender).next("div.Popup").show();
    }
    else
    {
        $(sender).attr("src","/inc/img/loading.gif");
        
        $.get
        (
            "/inc/GetPopupTitulosFromIDcasa.aspx",
            { idcasa: idcasa },
            function(data)
            {
                $(sender).after(data);
                $(sender).attr("src", SrcOriginal);
            }
        );
    }
}

function PrepararDesplegablesCasasHijas()
{
    $("img.casashijas")
    .click
    (
        function()
        {
            var obj = $(this).parent().parent().next();
            
            if ($(obj).is(":visible"))
            {
                obj.hide();
                $(this).attr("src","/inc/img/iconos/rel_cas.gif");                
            }
            else
            {
                obj.show();
                $(this).attr("src","/inc/img/iconos/rel_cas_over.gif");
            }
        }
    )
}

function GetListaPersonajesFromTitulo(sender, idtitulo)
{
    var Visible = $(sender).next().is(":visible");   
    var YaCargado = $(sender).next().is("div.Popup");
    var SrcOriginal = $(sender).attr("src");

    $("div.Popup").hide();
    
    if (YaCargado)
    {
        if (!Visible) $(sender).next("div.Popup").show();
    }
    else
    {
        $(sender).attr("src","/inc/img/loading.gif");
        
        $.get
        (
            "/inc/GetPopupPersonajesFromIDtitulo.aspx",
            { idtitulo: idtitulo },
            function(data,success)
            {
                $(sender).after(data);
                $(sender).attr("src", SrcOriginal);
            }
        );
    }
}

var TitulosRelacionadosObtenidos = false;
var tits;
var countits = 0;

function GetTitulosRelacionados()
{
    if (TitulosRelacionadosObtenidos) return;

    var ids = "";                

    $("td.idrel").each(
        function()
        {
            ids += $(this).html() + ",";
            $(this).html("Cargando...");
        }
    );
    
    if (ids.length > 0)
    {
        $.post
        (
	        "/inc/GetTitulos.aspx",
	        { ids: ids },
            function(data, result)
            {
                if (data != "error")
                {
                    var tits = data.split("<ii>");
                    
                    $("td.idrel").each(
                        function()
                        {
                            // $(this).html(tits[countits]);
                            var tr = $(this).parent();
                            $(tr).empty();
                            tr.html(tits[countits]);
                            countits++;
                        }
                    );
                    
                    ActivaPopupsTitulados();
                    TitulosRelacionadosObtenidos = true;
                }
                else
                {
                    alert("error");
                }
            }
        );
    }
}

$.fn.extend
(
    {
        Pager: function(ElementsPerPage, PaggerMessages, Position, CssClass)
        {
            if (!ElementsPerPage) var ElementsPerPage = 2;
            if (!PaggerMessages) var PaggerMessages = new Array("Página", "Anterior", "Siguiente");
            if (!Position) var Position = "before"; // before, after, both
            if (!CssClass) var CssClass = "default";
        
            return this.each
            (
                function()
                {
                    // Compruebo si hace falta el paginador según el número de elementos
                    if ($(this).children().size() <= ElementsPerPage) return;
                
                    // El objeto que contiene cada div que hay que paginar
                    var continente = $(this).wrapInner("<div class=\"pager_wrap\"></div>");
                    
                    var pager_widget =  "<div class=\"pager_browser pager_browser" + "_" + CssClass + "\">" +
                                        "<a href=\"#\" class=\"browser_arrow_left browser_arrow_disabled\" onclick=\"Pager_NewPage(this, " + ElementsPerPage + ", 'previous'); return false;\">&laquo; " + PaggerMessages[1] + "</a>" +
                                        "&nbsp;<span class=\"browser_led\">" + PaggerMessages[0] + " <i></i></span>" +
                                        "<a href=\"#\" class=\"browser_arrow_right\" onclick=\"Pager_NewPage(this, " + ElementsPerPage + ", 'next'); return false;\">" + PaggerMessages[2] + " &raquo;</a>" +
                                        "</div>";
                    
                    if (Position == "both") { continente.prepend(pager_widget); continente.append(pager_widget); }
                    else if (Position == "after") continente.append(pager_widget);
                    else { continente.prepend(pager_widget); }
                    
                    // El nuevo continete es el wrapper
                    continente = continente.find("div.pager_wrap");
                    
                    // Muestro los ElementsPerPage primeros
                    continente.children().slice(ElementsPerPage).hide();
                    
                    // Iniciamos el led
                    Pager_Led(continente, ElementsPerPage);
                }
            );
        }
    }
);

function Pager_Led(continente, ElementsPerPage)
{   
    var elements = continente.children();
    var nElements = continente.children().size();
    var iFirstVisible = elements.index(elements.filter(":visible:first"));
    var page = iFirstVisible / ElementsPerPage + 1;
    var pages = Math.ceil(nElements / ElementsPerPage);

    continente.parent().parent().find(".pager_browser").each
    (
        function()
        {
            $(this).find("span.browser_led i").text(page + "/" + pages);
        }
    );
}

function Pager_Arrows(continente)
{
    var elements = continente.children();
    
    continente.parent().parent().find(".pager_browser").each
    (
        function()
        {
            var fl = $(this).find("a.browser_arrow_left");
            var fr = $(this).find("a.browser_arrow_right");
            
            if (elements.filter(":first").is(":visible")) fl.addClass("browser_arrow_disabled");
            else fl.removeClass("browser_arrow_disabled");

            if (elements.filter(":last").is(":visible")) fr.addClass("browser_arrow_disabled");
            else fr.removeClass("browser_arrow_disabled");
        }
    );
}

function Pager_NewPage(sender, ElementsPerPage, Direction)
{
    if ($(sender).hasClass("browser_arrow_disabled")) return;
    
    var continente = $(sender).parent().parent().find("div.pager_wrap");
    var elements = continente.children();
    
    if (Direction == "next" || !Direction)
    {
        var iLastVisible = elements.index(elements.filter(":visible:last"));
        
        elements.hide();
        elements.slice(iLastVisible + 1, iLastVisible + ElementsPerPage + 1).show();
    }
    else if (Direction == "previous")
    {
        var iFirstVisible = elements.index(elements.filter(":visible:first"));
        
        elements.hide();
        var iStart = iFirstVisible - ElementsPerPage;
        if (iStart < 0) iStart = 0;
        elements.slice(iStart, iStart + ElementsPerPage).show();
    }
    
    // Actualizo flechas y contador
    Pager_Arrows(continente);
    Pager_Led(continente, ElementsPerPage);
}