function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

/* Start image rollover */
var actImgTag;
var selImgTag;
var clsRoll;
var imgList;
var images;
var activeImages;
var inactiveImages;

// UIR (Unobtrusive Image Rollover) v2.0.1-20060309
if (document.getElementById) {
   function initUIR() {
      actImgTag = "_on";
      //actImgTag = "";
      selImgTag = "_sel";
      clsRoll = "roll";

      imgList = '';
      var images = document.getElementsByTagName('img');

      for (var i=0; i<images.length; i++) {
         if (eval('/' + clsRoll + '/').test(images[i].className)) {
            imgList += images[i].src + ",";
            setEvents(images[i]);
         }
      }

      if (imgList != '') {
         imgList = imgList.substring(0, imgList.length-1);
         preload(imgList.split(","));
      }
   }

   function setEvents(element) {
      element.parentNode.onmouseover = function() { roll(this); }
      element.parentNode.onmouseout = function() { roll(this); }
      element.parentNode.onfocus = function() { roll(this); }
      element.parentNode.onblur = function() { roll(this); }
   }

   function preload(imgList) {
      activeImages = new Array(imgList.length);
      inactiveImages = new Array(imgList.length);

      for (var i=0; i<imgList.length; i++) {
         activeImages[i] = new Image();
         activeImages[i].src = getBaseName(imgList[i]) + actImgTag + getExt(imgList[i]);
         inactiveImages[i] = new Image();
         inactiveImages[i].src = getBaseName(imgList[i]) + getExt(imgList[i]);
      }
   }

   function getBaseName(filename) {
      if (eval('/'+actImgTag+'\./').test(filename)) filename = filename.replace(actImgTag+'.', '.');
      if (eval('/'+selImgTag+'\./').test(filename)) filename = filename.replace(selImgTag+'.', '.');
      return filename.substring(0, filename.lastIndexOf('.'));
   }

   function getExt(filename) {
      return filename.substring(filename.lastIndexOf('.'), filename.length);
   }

   function getImage(imageName, isActive) {
      (isActive==0) ? images = inactiveImages : images = activeImages;
      for (var i=0; i<images.length; i++) {
         if (getBaseName(imageName) == getBaseName(images[i].src)) {
            return images[i];
            break;
         }
      }
      return [];
   }

   function roll(element) {
      var src, newSrc;
      var node, currNode;

      for (var i=0; i<element.childNodes.length; i++) {
         currNode = element.childNodes[i];
         if (currNode.nodeType==1 && /img/i.test(currNode.nodeName)) {
            node = i;
            break;
         }
      }
      src = element.childNodes[node].src;
      if (!(eval('/'+selImgTag+'\./').test(src))) {
         newSrc = getImage(src,!(eval('/'+actImgTag+'\./').test(src))).src;
      }
      if (!(typeof(newSrc)=='undefined')) element.childNodes[node].src = newSrc;
   }

   addLoadEvent(initUIR);
} // (C) 2005 Emanuele Rodriguez <erodri@gmail.com>

/* End image rollover */

// Set Body text size
function setSize(iSize) {
	if (!document.getElementsByTagName) return false;
		var bodyTag = document.getElementsByTagName("body");

	for (var i=0; i < bodyTag.length; i++) {
		if (!bodyTag[i].style.fontSize) {
			if (!readCookie("resize")) {
				bodyTag[i].style.fontSize = "62.5%";
			}
			else {
				bodyTag[i].style.fontSize = ((parseFloat(readCookie("resize"))) + "%");
			}
		}
		else {
			if (!readCookie("resize")) {
				bodyTag[i].style.fontSize = "62.5%";
			}
			else {
				var newSize = parseFloat(iSize) + parseFloat(readCookie("resize"));
				if ((newSize <= 72.5) && (newSize >= 62.5))
					bodyTag[i].style.fontSize = newSize + "%";
			}
		}
		cookieValue = bodyTag[i].style.fontSize;
		writeCookie("resize", cookieValue, 10000);
	}
}

// Attaches the onclick event to the correct ids to allow resizing
function resizeT(iID, iDir) {
	if (!document.getElementById) return false;
		var incLink = document.getElementById(iID);

	if (iDir == "decrease") {
		incLink.onclick = function() {
			setSize("-5%");
			return false;
		}
	}

	if (iDir == "increase") {
		incLink.onclick = function() {
			setSize("5%");
			return false;
		}
	}
}

function isDate(Data)
{
	var esFecha = false;
	var aux = Data.split("/");

	if (aux.length == 3)
	{
		if ( (!isNaN(aux[0])) && (!isNaN(aux[1])) && (!isNaN(aux[2])) )
		{
			if ( (aux[1] >= 1) && (aux[1] <= 12) &&  (aux[2].length == 4))
			{
				if ( (aux[1] == 1) || (aux[1] == 3) || (aux[1] == 5) || (aux[1] == 7) || (aux[1] == 8) || (aux[1] == 10) || (aux[1] == 12) )
				{

						if ( (aux[0] >= 1) && (aux[0] <= 31) )
						{
							esFecha = true;
						}
				}
				else
				{
					if ( (aux[1] == 4) || (aux[1] == 6) || (aux[1] == 9) || (aux[1] == 11) )
					{
						if ( (aux[0] >= 1) && (aux[0] <= 30) )
						{
							esFecha = true;
						}
					}
					else
					{
						if ( aux[1] == 2)
						{
							if ( esBisiesto(aux[2]) )
							{
								if ( (aux[0] >= 1) && (aux[0] <= 29) )
								{
									esFecha = true;
								}
							}
							else
							{
								if ( (aux[0] >= 1) && (aux[0] <= 28) )
								{
									esFecha = true;
								}
							}
						}
					}
				}
			}
		}
	}
	if (Data=="")
	{
		esFecha = true;
	}
	return esFecha;
}

function esBisiesto(Any)
{
	//Un año es bisiesto si es divisible por 4 y no por 100, excepto los años divisibles por 400. 
	return (((Any % 4 == 0) && (Any % 100 != 0)) || (Any % 400 == 0))
}


// add increase / decrease font event handlers
addLoadEvent( function(){ resizeT("fntIncrease", "increase") } );
addLoadEvent( function(){ resizeT("fntDecrease", "decrease") } );

// set base font size
addLoadEvent( function(){ setSize("62.5%") } );



// Writes cookie
// writeCookie("myCookie", "my name", 24);
// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.

function writeCookie(name, value, hours) {
	var expire = "";
	if(hours != null) {
		expire = new Date((new Date()).getTime() + hours * 3600000);
		expire = "; expires=" + expire.toGMTString();
	}
	document.cookie = name + "=" + escape(value) + expire;
}

// Read Cookie
// alert( readCookie("myCookie") );
function readCookie(name){
	var cookieValue = "";
	var search = name + "=";

	if(document.cookie.length > 0) {
		offset = document.cookie.indexOf(search);

	if (offset != -1) {
		offset += search.length;

	end = document.cookie.indexOf(";", offset);

	if (end == -1) end = document.cookie.length;
		cookieValue = unescape(document.cookie.substring(offset, end)) }
	}

	return cookieValue;
}




/* Start external links handler */
function externalLinks() {
   if (!document.getElementsByTagName) return;
   var anchors = document.getElementsByTagName("a");
   for (var i=0; i<anchors.length; i++) {
      var anchor = anchors[i];
      if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
         anchor.target = "_blank";
   }
}

addLoadEvent(externalLinks);
/* End external links handler */

function editPlayListItem(playListItemId, action) {
	var opciones ={requestHeaders: ["If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 GMT"], evalScripts: true, method: "get", onSuccess: printPlayListItems};
	// Ponemos el cursor del ratón a 'wait'
	switchCursorStatus();
	new Ajax.Request("/playlist/editAJAX.action?playListItemId="+playListItemId+'&action='+action, opciones);	
	return false;
}

function addPlayListItem(elem, itemId) {
	elem.href = '/playlist/addAJAX.action?itemId='+itemId+'&height=245&width=655&modal=true';
	return true;
}

function printPlayListItems(resp) {
	// Reseteamos el cursor del ratón
	switchCursorStatus("default");
	document.getElementById('playListItems').innerHTML = resp.responseText;
	// Llamada asincrona al flash
	var opciones ={requestHeaders: ["If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 GMT"], evalScripts: true, method: "get", onSuccess: setXmlPath};
	new Ajax.Request("/playlist/articleListAJAX.action", opciones);	
}

function setXmlPath(resp) {
	document.getElementById("videoPlayerViewer").setXmlPath("/article/xml.action?"+resp.responseText);
}

/**
 * Cambia el puntero del ratón para todos los elementos de tipo "A"
 */
function switchCursorStatus(m){
    m = (m) ? m : "wait";
    var a = document.getElementsByTagName("A");
    document.body.style.cursor = m;
    for (var i = 0; i < a.length; i++)
        a[i].style.cursor = m;
}

/** 
 * Función llamada por video_player.swf para indicar que se ha empezado
 * a reproducir este video.
 * Esta función incrementa el número de visualizaciones del video.
 * Esta función hace la llamada para actualizar la barra de extras (visualizaciones, 
 * votaciones, comentarios, etc.) en listarticles.jsp
 */
function actualVideo(id, ordering, mediaTypeId, embed) {
	var opciones = {requestHeaders: ["If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 GMT"], method: "get"};
	new Ajax.Request("/public/media/addVisit.action?articleId="+id+"&mediaTypeId="+mediaTypeId, opciones);
	
	if((embed=="false")&&(articleId!=id)){
		var opciones ={requestHeaders: ["If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 GMT"], evalScripts: true, method: "get", onSuccess: printExtras};
		new Ajax.Request("/articles/findExtrasAJAX.action?id="+id+"&playlist="+playlist, opciones);	
		if (jQuery('#epilogVideoPlayer').get(0)) {
			opciones ={requestHeaders: ["If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 GMT"], evalScripts: true, method: "get", onSuccess: printEpilog};
			new Ajax.Request("/articles/findEpilogAJAX.action?id="+id, opciones);	
		}
	}
	articleId = id;
	if (jQuery('.video_actual')) {
		jQuery('.video_actual').removeClass('video_actual');
	}
	if (jQuery('.image_'+id).get(ordering-1)) {
		jQuery('.image_'+id).get(ordering-1).className += ' video_actual';
	}
}

// Textos que necesita jQuery para escribir las estrellas de votaciones
var printExtrasText1, printExtrasText2;

/**
 * Función llamada por el onSuccess de actualVideo
 * Esta función actualiza la barra de extras (visualizaciones, votaciones,
 * comentarios, etc.) en listarticles.jsp
 */
function printExtras(resp){
	document.getElementById('extrasVideoPlayer').innerHTML = resp.responseText;
	jQuery(function(){
            jQuery('form.rating').rating(printExtrasText1, printExtrasText2).animate({opacity: 'show'}, 2000);
        });
}

function printEpilog(resp){
	document.getElementById('epilogVideoPlayer').innerHTML = resp.responseText;
}

/**
 * Función que incrementa el número de votos del video con el
 * valor elegido.
 */
function voteMedia(url) {
	if (!readCookie("vote_"+articleId)) {
		var opciones = {method: "post", onSuccess: voteReceived(url)};
		new Ajax.Request(url, opciones);
	}
}

/**
 * Función que realiza las acciones posteriores a recibir un voto
 */
function voteReceived(url) {
	// Mostramos la capa de 'Gracias por votar'
	showElem('resultado');
	writeCookie("vote_"+articleId, "voto", 10000);
	jQuery(".estrella").unbind("click");
}

// Varaible donde guardamos el identificador del articulo actual
var articleId = 0;

// Variable que indica si estamos reproduciendo la playlist o no
var playlist = false;

/**
 * Función que hace visible un elemento.
 */
function showElem(elemId) {
	document.getElementById(elemId).style.visibility="visible";
}

/**
 * Función que oculta un elemento.
 */
function hideElem(elemId) {
	document.getElementById(elemId).style.visibility="hidden";
}

/**
 * Función que valida/corrige el key introducido en el buscador de dominios.
 * 1-Elimina .es
 * 2-Convierte a minúsculas.
*/
function validateDomain(){
	 xxx= document.getElementById("Dominio").value;
	 xxx=xxx.replace(/\r\n/g,"\n");
     variable = P(xxx);
     document.getElementById("tDominio.nombreDominio").value= variable
     document.form1.action= "https://www.nic.es/sgnd/dominio/publicBuscarDominios.action";
     document.form1.submit();
}

 /**
  * Funcion que valida/corrige el key introducido en el buscador de Area IDN.
  */
function validateConversor(){
	xxx= document.getElementById("nDominio").value;	
    variable = P(xxx);
    document.getElementById("nombreDominio").value= variable
    document.formConvertidor.action= "https://www.nic.es/esnic/esn/comprobarDominioEPAction";
    document.formConvertidor.submit();
	
}
 
 
function P (string) {
		
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	}


function validateDomainPressKey(event){
	if(isKeyEnter(event)){
		validateDomain();
		//$('dominio').value = $('dominio').value.replace(/\.es/g,"");
	}
}
function isKeyEnter(e){ 
	var characterCode;

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}

	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		return true
	}else{
		return false
	}
}
	