// ----------------------------------------------
// StyleSwitcher functions written by Paul Sowden
// http://www.idontsmoke.co.uk/ss/
// - - - - - - - - - - - - - - - - - - - - - - -
// For the details, visit ALA:
// http://www.alistapart.com/stories/alternate/
//
// nifty StyleSwitcher scripts modified by Aaron Jones 10/10/2002
// ----------------------------------------------

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);

// ----------------------------------------------
// Funciones Dreamweaver para rollover
// ----------------------------------------------

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// ----------------------------------------------
// Funciones para formulario de búsqueda
// ----------------------------------------------

function valido()
{
  if (document.frmbuscador.claves.value=='')
  {
    alert("Debe introducir una o más palabras clave.");
    document.frmbuscador.claves.focus();
  }
  else
  {
    document.frmbuscador.submit();
  }
}
function Buscar()
{
  if (document.frmbuscador.claves.value=='')
  {
    alert("Debe introducir una o más palabras clave");
    document.frmbuscador.claves.focus();
    return false;
  }
  else
  {
    return true;
  }
}

// ----------------------------------------------
// Funciones para el menu inferior de suplementos
// ----------------------------------------------

var previoustab=""

function expandcontent(cid, aobject){
  if (document.getElementById) {
    highlighttab(aobject);
    if (previoustab!="")
      document.getElementById(previoustab).style.display="none";
    document.getElementById(cid).style.display="block";
    previoustab=cid;
  }
}

function highlighttab(aobject){
  if (typeof tabobjlinks=="undefined")
    collecttablinks();
  for (i=0; i<tabobjlinks.length; i++)
    tabobjlinks[i].className="";
  aobject.className="current";
}

function collecttablinks(){
  var tabobj=document.getElementById("tablist");
  tabobjlinks=tabobj.getElementsByTagName("A");
}

function do_onload(){
  if (typeof initialtab != "undefined") {
    collecttablinks();
    expandcontent(initialtab[1], tabobjlinks[initialtab[0]-1]);
  }
}

// ----------------------------------------------
// Funciones para recarga de portadas de seccion
// ----------------------------------------------
function recarga(t) {
  if (xmlhttp) {
    xmlhttp.open("GET", url_refresco, true);
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
        if (fecha_mod>=xmlhttp.responseText)
          setTimeout("recarga("+t+")", t);
        else
          location.href = location.href;
      }
    }
    xmlhttp.send(null);
  }
}
function fecha_modificacion() {
  if (xmlhttp) {
    xmlhttp.open("GET", url_refresco, true);
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
        fecha_mod = xmlhttp.responseText;
      }
    }
    xmlhttp.send(null);
  }
}
var xmlhttp = false;
var fecha_mod = 0;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  xmlhttp = new XMLHttpRequest();
}

// ----------------------------------------------
// Funcion de recarga de la caja de deportes
// ----------------------------------------------
function cuenta_atras(restante) {
  if (--restante<=0) {
    document.getElementById("cuenta_atras").innerHTML = " | <span style='color:black'>Actualizando<span>";
    xmlhttp.open("GET", "http://www.libertaddigital.com:83/htm/fragmentos/caja_deportes.html", true);
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
        document.getElementById("deportes").innerHTML = xmlhttp.responseText;
        if (document.getElementById("cuenta_atras")) cuenta_atras(181);
      }
    }
    xmlhttp.send(null);
  }
  else {
    document.getElementById("cuenta_atras").innerHTML = " | <span style=\"color:black\"><img src=\"/images/i_reloj.gif\" alt=\"\" /> Actualización en " + restante + " segundos</span>";
    setTimeout("cuenta_atras("+restante+")", 1000);
  }
}

// ----------------------------------------------
// Eventos de carga y descarga de la página
// ----------------------------------------------
window.onload = function(e) {
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
  do_onload();
  MM_preloadImages('/files/aa1.gif','/files/aa2.gif','/files/aa3.gif');
  if (typeof url_refresco!='undefined') {
    fecha_modificacion();
    setTimeout("recarga(240000)", 240000);
  }
  if (xmlhttp && document.getElementById("cuenta_atras"))
    cuenta_atras(181);
}

window.onunload = function(e) {
  var title = getActiveStyleSheet();
  createCookie("style", title, 365);
}

/* =================================================================================================
* NiceTitles
* 21st January 2004
* http://neo.dzygn.com/code/nicetitles
*
* NiceTitles turns your boring (X)HTML tags into a dynamic experience
*
* Copyright (c) 2003 - 2004 Stuart Langridge, Paul McLanahan, Peter Janes, Brad Choate, Dunstan Orchard, Ethan Marcotte, Mark Wubben
*
* Licensed under MIT - http://www.opensource.org/licenses/mit-license.php
==================================================================================================*/

function NiceTitles(sTemplate, nDelay, nStringMaxLength, nMarginX, nMarginY, sContainerID, sClassName){
        var oTimer;
        var isActive = false;
        var sNameSpaceURI = "http://www.w3.org/1999/xhtml";

        if(!sTemplate){ sTemplate = "attr(nicetitle)";}
        if(!nDelay || nDelay <= 0){ nDelay = false;}
        if(!nStringMaxLength){ nStringMaxLength = 80; }
        if(!nMarginX){ nMarginX = 15; }
        if(!nMarginY){ nMarginY = 15; }
        if(!sContainerID){ sContainerID = "nicetitlecontainer";}
        if(!sClassName){ sClassName = "nicetitle";}

        var oContainer = document.getElementById(sContainerID);
        if(!oContainer){
                oContainer = document.createElementNS ? document.createElementNS(sNameSpaceURI, "div") : document.createElement("div");
                oContainer.setAttribute("id", sContainerID);
                oContainer.className = sClassName;
                oContainer.style.display = "none";
                document.getElementsByTagName("body").item(0).appendChild(oContainer);
        }

        //=====================================================================
        // Method addElements (Public)
        //=====================================================================
        this.addElements = function addElements(collNodes, sAttribute){
                var currentNode, sTitle;

                for(var i = 0; i < collNodes.length; i++){
                        currentNode = collNodes[i];

                        sTitle = currentNode.getAttribute(sAttribute);
                        if(sTitle){
                                currentNode.setAttribute("nicetitle", sTitle);
                                currentNode.removeAttribute(sAttribute);
                                addEvent(currentNode, 'mouseover', show);
                                addEvent(currentNode, 'mouseout', hide);
                                addEvent(currentNode, 'focus', show);
                                addEvent(currentNode, 'blur', hide);
                        }
                }

        }

        //=====================================================================
        // Other Methods (All Private)
        //=====================================================================
        function show(e){
                if(isActive){ hide(); }

                var oNode = window.event ? window.event.srcElement : e.currentTarget;
                if(!oNode.getAttribute("nicetitle")){
                        while(oNode.parentNode){
                                oNode = oNode.parentNode; // immediately goes to the parent, thus we can only have element nodes
                                if(oNode.getAttribute("nicetitle")){ break;        }
                        }
                }

                var sOutput = parseTemplate(oNode);
                setContainerContent(sOutput);
                var oPosition = getPosition(e, oNode);
                oContainer.style.left = oPosition.x;
                oContainer.style.top = oPosition.y;

                if(nDelay){
                        oTimer = setTimeout(function(){oContainer.style.display = "block";}, nDelay);
                } else {
                        oContainer.style.display = "block";
                }

                isActive = true;
                // Let's put this event to a halt before it starts messing things up
                window.event ? window.event.cancelBubble = true : e.stopPropagation();
        }

        function hide(){
                clearTimeout(oTimer);
                oContainer.style.display = "none";
                removeContainerContent();
                isActive = false;
        }

        function setContainerContent(sOutput){
                sOutput = sOutput.replace(/&/g, "&amp;");
                if(document.createElementNS && window.DOMParser){
                        var oXMLDoc = (new DOMParser()).parseFromString("<root xmlns=\""+sNameSpaceURI+"\">"+sOutput+"</root>", "text/xml");
                        var oOutputNode = document.importNode(oXMLDoc.documentElement, true);
                        var oChild = oOutputNode.firstChild;
                        var nextChild;
                        while(oChild){
                                nextChild = oChild.nextSibling; // One's the child is appended, the nextSibling reference is gone
                                oContainer.appendChild(oChild);
                                oChild = nextChild;
                        }
                } else {
                        oContainer.innerHTML = sOutput;
                }
        }

        function removeContainerContent(){
                var oChild = oContainer.firstChild;
                var nextChild;

                if(!oChild){ return; }
                while(oChild){
                        nextChild = oChild.nextSibling;
                        oContainer.removeChild(oChild);
                        oChild =  nextChild;
                }
        }

        function getPosition(e, oNode){
                var oViewport = getViewport();
                var oCoords;
                var commonEventInterface = window.event ? window.event : e;

                if(commonEventInterface.type == "focus"){
                        oCoords = getNodePosition(oNode);
                        oCoords.x += nMarginX;
                        oCoords.y += nMarginY;
                } else {
                        oCoords = { x : commonEventInterface.clientX + oViewport.x + nMarginX, y : commonEventInterface.clientY + oViewport.y + nMarginY};
                }

                oContainer.style.visiblity = "hidden"; // oContainer needs to be displayed before width and height can be retrieved
                oContainer.style.display =  "block";
                var containerWidth = oContainer.offsetWidth;
                var containerHeight = oContainer.offsetHeight;
                oContainer.style.display = "none"; // hide it again
                oContainer.style.visiblity = "visible";

                if(oCoords.x + containerWidth + 10 >= oViewport.width + oViewport.x){
                        oCoords.x = oViewport.width + oViewport.x - containerWidth - 10;
                }
                if(oCoords.y + containerHeight + 10 >= oViewport.height + oViewport.y){
                        oCoords.y = oViewport.height + oViewport.y - containerHeight - oNode.offsetHeight - 10;
                }

                oCoords.x += "px";
                oCoords.y += "px";

                return oCoords;
        }

        function parseTemplate(oNode){
                var sAttribute, collOptionalAttributes;
                var oFound = {};
                var sResult = sTemplate;

                if(sResult.match(/content\(\)/)){
                        sResult = sResult.replace(/content\(\)/g, getContentOfNode(oNode));
                }

                var collSearch = sResult.split(/attr\(/);
                for(var i = 1; i < collSearch.length; i++){
                        sAttribute = collSearch[i].split(")")[0];
                        oFound[sAttribute] = oNode.getAttribute(sAttribute);
                        if(oFound[sAttribute] && oFound[sAttribute].length > nStringMaxLength){
                                oFound[sAttribute] = oFound[sAttribute].substring(0, nStringMaxLength) + "...";
                        }
                }

                var collOptional = sResult.split("?")
                for(var i = 1; i < collOptional.length; i += 2){
                        collOptionalAttributes = collOptional[i].split("attr(");
                        for(var j = 1; j < collOptionalAttributes.length; j++){
                                sAttribute = collOptionalAttributes[j].split(")")[0];

                                if(!oFound[sAttribute]){ sResult = sResult.replace(new RegExp("\\?[^\\?]*attr\\("+sAttribute+"\\)[^\\?]*\\?", "g"), "");        }
                        }
                }
                sResult = sResult.replace(/\?/g, "");

                for(sAttribute in oFound){
                        sResult = sResult.replace("attr\("+sAttribute+"\)", oFound[sAttribute]);
                }

                return sResult;
        }

        function getContentOfNode(oNode){
                var sContent = "";
                var oSearch = oNode.firstChild;

                while(oSearch){
                        if(oSearch.nodeType == 3){
                                sContent += oSearch.nodeValue;
                        } else if(oSearch.nodeType == 1 && oSearch.hasChildNodes){
                                sContent += getContentOfNode(oSearch);
                        }
                        oSearch = oSearch.nextSibling
                }

                return sContent;
        }

        function getNodePosition(oNode){
                var x = 0;
                var y = 0;

                do {
                        if(oNode.offsetLeft){ x += oNode.offsetLeft }
                        if(oNode.offsetTop){ y += oNode.offsetTop }
                }        while((oNode = oNode.offsetParent) && !document.all) // IE gets the offset 'right' from the start

                return {x : x, y : y}
        }

        // Idea from 13thParallel: http://13thparallel.net/?issue=2002.06&title=viewport
        function getViewport(){
                var width = 0;
                var height = 0;
                var x = 0;
                var y = 0;

                if(document.documentElement && document.documentElement.clientWidth){
                        width = document.documentElement.clientWidth;
                        height = document.documentElement.clientHeight;
                        x = document.documentElement.scrollLeft;
                        y = document.documentElement.scrollTop;
                } else if(document.body && document.body.clientWidth){
                        width = document.body.clientWidth;
                        height = document.body.clientHeight;
                        x = document.body.scrollLeft;
                        y = document.body.scrollTop;
                }
                // we don't use an else if here, since Opera 7 tends to get the height on the documentElement wrong
                if(window.innerWidth){
                        width = window.innerWidth - 18;
                        height = window.innerHeight - 18;
                }

                if(window.pageYOffset){
                        x = window.pageXOffset;
                        y = window.pageYOffset;
                } else if(window.scrollY){
                        x = window.scrollX;
                        y = window.scrollY;
                }

                return {width : width, height : height, x : x, y : y };
        }
}

//=====================================================================
// Event Listener
// by Scott Andrew - http://scottandrew.com
// edited by Mark Wubben, <useCapture> is now set to false
//=====================================================================
function addEvent(obj, evType, fn){
        if(obj.addEventListener){
                obj.addEventListener(evType, fn, false);
                return true;
        } else if (obj.attachEvent){
                var r = obj.attachEvent('on'+evType, fn);
                return r;
        } else {
                return false;
        }
}

//=====================================================================
// Time Since
// by Mark Wubben - http://neo.dzygn.com
//=====================================================================
Date.prototype.toTimeSinceString = function(nLimit, sBetween, sLastBetween){
        if(!nLimit){ nLimit = 2; }
        if(!sBetween){ sBetween = ", "; }
        if(!sLastBetween){ sLastBetween = " and "; }
        if(!Date.prototype.toTimeSinceString._collStructs){
                Date.prototype.toTimeSinceString._collStructs = new Array(
                        {seconds: 60 * 60 * 24 * 365, name: "year"},
                        {seconds: 60 * 60 * 24 * 30, name: "month"},
                        {seconds: 60 * 60 * 24 * 7, name: "week"},
                        {seconds: 60 * 60 * 24, name: "day"},
                        {seconds: 60 * 60, name: "hour"},
                        {seconds: 60, name: "minute"}
                );
        }

        var collStructs = Date.prototype.toTimeSinceString._collStructs;
        var nSecondsRemain = ((new Date).valueOf() - this.valueOf()) / 1000;
        var sReturn = "";
        var nCount = 0;
        var nFloored;

        for(var i = 0; i < collStructs.length && nCount < nLimit; i++){
                nFloored = Math.floor(nSecondsRemain / collStructs[i].seconds);
                if(nFloored > 0){
                        if(sReturn.length > 0){
                                if(nCount == nLimit - 1 || i == collStructs.length - 1){
                                        sReturn += sLastBetween;
                                } else if(nCount < nLimit && i < collStructs.length){
                                        sReturn += sBetween;
                                }
                        }
                        sReturn += nFloored + " " + collStructs[i].name;
                        if(nFloored > 1){
                                sReturn += "s";
                        }
                        nSecondsRemain -= nFloored * collStructs[i].seconds;
                        nCount++;
                }
        }

        return sReturn;
}

//=====================================================================
// Here the default nice titles are created
//=====================================================================
NiceTitles.autoCreation = function(){
        if(!document.getElementsByTagName){ return; }

        NiceTitles.autoCreated = new Object();

        NiceTitles.autoCreated.anchors = new NiceTitles("<p class=\"titletext\">attr(nicetitle)?</p>", 300, 500);
        NiceTitles.autoCreated.anchors.addElements(document.getElementsByTagName("a"), "title");
}

addEvent(window, "load", NiceTitles.autoCreation);
