///////// tabs.js
function addEvent(elm, evType, fn, useCapture) {
  if (elm.addEventListener) {
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent) {
    var r = elm.attachEvent('on' + evType, fn);
    return r;
  }
  else {
    elm['on' + evType] = fn;
  }
}

function preventDefault(e) {
  if (e.preventDefault) {
      e.preventDefault();
  }

  try {
    e.returnValue = false;
  } catch (e) {
  }
}

function ltarget(e) {
  var tmp;

  try {
    tmp = e.target;
    if (tmp != undefined) { return tmp; }
  } catch(e) {
  }

  try {
    tmp = e.srcElement;
    return tmp;
  } catch(e) {
  }

  return tmp;
}



function activa_tab(e) {
	//window.event.cancelBubble();
	preventDefault(e);
	var my_target = ltarget(e);
  var c = document.getElementById(my_target.href.substr(my_target.href.indexOf("#") + 1));
                 if (c) {

                                 //reset all tabs
                                for (var i = 0; i < my_target.tabs.length; i++)
                                      {
                                         document.getElementById(my_target.tabs[i].href.substr(my_target.tabs[i].href.indexOf("#") + 1)).style.display = "none";
                                         my_target.tabs[i].className = my_target.tabs[i].className.replace("active", "");
                                        }
                                my_target.className += " active";
                                c.style.display = "block";
	}
                              return false;

}
function initTabs()
{
	var sets = document.getElementsByTagName("ul");
	for (var i = 0; i < sets.length; i++)
	{
		if (sets[i].className.indexOf("tabset") != -1)
		{
			var tabs = [];
			var links = sets[i].getElementsByTagName("a");
			for (var j = 0; j < links.length; j++)
			{
				if (links[j].className.indexOf("tab") != -1)
				{
					tabs.push(links[j]);
					links[j].tabs = tabs;
					if (links[j].className.indexOf("active") != -1)
					{
						var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));
						if (c)
							c.style.display = "block";
					}
					addEvent(links[j], 'click', activa_tab, false);
				}
			}
		}
	}
}
addEvent(window, "load", initTabs, false);


///////// fontsize.js
function initPage()
{
	var f = document.getElementById("font-size");
	if (f)
	{
		var links = f.getElementsByTagName("a");
		for (var i = 0; i < links.length; i++)
		{
			links[i].onclick = function ()
			{
				document.body.style.fontSize = this.className;
				return false;
			}
		}
	}
}

addEvent(window, "load", initPage, false);


///////// nav.js
function initPageNav()
{
	var navs = new Array("header-tabs", "navigation");
	for (j=0; j<navs.length; j++)
	{
		var nav = document.getElementById(navs[j]);
		if (nav)
		{
			var nodes = nav.getElementsByTagName("li");
			for (var i = 0; i < nodes.length; i++)
			{
				if (nodes[i].parentNode.id == navs[j])
				{
					nodes[i].onmouseover = function ()
					{
						this.className += " hover";
					}
					nodes[i].onmouseout = function ()
					{
						this.className = this.className.replace(" hover", "");
					}
				}
			}
		}
	}
}
if (window.attachEvent && !window.opera)
	window.attachEvent("onload", initPageNav);


///////// reload.js
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
					window.location.reload();
			}
		}
		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);
	}
}

function initReload()
{
	switch (window.location.pathname)
	{
		case "":
		case "/":				url_refresco = '/htm/fijos/script/POR_D.txt'; break;
		case "/nacional/":		url_refresco = '/htm/fijos/script/ESP_D.txt'; break;
		case "/mundo/":			url_refresco = '/htm/fijos/script/MUN_D.txt'; break;
		case "/economia/":		url_refresco = '/htm/fijos/script/ECO_D.txt'; break;
		case "/internet/":		url_refresco = '/htm/fijos/script/AME_D.txt'; break;
		case "/sociedad/":		url_refresco = '/htm/fijos/script/SOC_D.txt'; break;
		case "/deportes/":		url_refresco = '/htm/fijos/script/DEP_D.txt';
	}
	if (url_refresco)
	{
		fecha_modificacion();
		setTimeout("recarga(240000)", 240000);
	}
}

function cuenta_atras(restante) {
  if (--restante<=0) {
    document.getElementById("cuenta_atras").innerHTML = " | <span><b>Actualizando</b></span>";
    xmlhttp.open("GET", "http://www.libertaddigital.com/rt/cajadeportes.html", true);
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
        document.getElementById("deportes").innerHTML = xmlhttp.responseText;
        if (document.getElementById("cuenta_atras")) iniciar_cuenta_atras();
      }
    }
    xmlhttp.send(null);
  }
  else {
    document.getElementById("cuenta_atras").innerHTML = " | <span> " + restante + " seg.</span>";
    setTimeout("cuenta_atras("+restante+")", 1000);
  }
}
function iniciar_cuenta_atras() { if (document.getElementById("cuenta_atras")) cuenta_atras(181); }

var xmlhttp = false;
var fecha_mod = 0;
var url_refresco = "";
/*@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();
}

addEvent(window, "load", initReload, false);
addEvent(window, "load", iniciar_cuenta_atras, false);


///////// nicetitle.js
/* =================================================================================================
* 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 };
        }
}

//=====================================================================
// 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, false);
