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;




// 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 = "85.0%";
			}
			else {
				bodyTag[i].style.fontSize = ((parseFloat(readCookie("resize"))) + "%");
			}
		}
		else {
			if (!readCookie("resize")) {
				bodyTag[i].style.fontSize = "85.0%";
			}
			else {
				var newSize = parseFloat(iSize) + parseFloat(readCookie("resize"));
				if ((newSize <= 135.0) && (newSize >= 85.0))
					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("-10%");
			return false;
		}
	}

	if (iDir == "increase") {
		incLink.onclick = function() {
			setSize("10%");
			return false;
		}
	}
}


// add increase / decrease font event handlers
addLoadEvent( function(){ resizeT("fntIncrease", "increase") } );
addLoadEvent( function(){ resizeT("fntDecrease", "decrease") } );

// set base font size
addLoadEvent( function(){ setSize("75.0%") } );



// 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(){
	$('dominio').value = $('dominio').value.replace(/\.es/g,"");
	$('dominio').value = $('dominio').value.toLowerCase();
}
function validateDomainPressKey(event){
	if(isKeyEnter(event)){
		$('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
	}
}
	