function LoadHome(){
	setTimeout(LoadRanking, 1);
	setTimeout('LoadCalendarAgenda()', 1);
	setTimeout(LoadNoticias, 1);
	createPlayer('audio');
	createPlayer('video');
	createPlayer('entrevista');
	setInterval(videoStatus.fixPos, 100);;
	// Observa los botones de cambio de fotos de las galerias
	observeGalButtons();
	if($('galeriaIndex') != null){
		var galerias = $('galeriaIndex').select('.thumb'),
			id;
		if(galerias && galerias[0]) {
			id = galerias[0].id.slice(8);
			setGal(id);
		}
	}
	
	if(/bad_login/.test(window.location.hash.slice(1))) {
		new ctAlert(false,				
			'<div style="margin:0 auto;width:415px;text-align: center">' +
				'DNI o clave no v&aacute;lidos.' +
			'</div>'				
		);
	}
}

var titulos = {
	getModal : function(id) {}
};
function LoadCalendarAgenda(){
        if($('tabsCalAgenda')){
            new Control.Tabs('tabsCalAgenda', {
                    afterChange: function(new_container){
                            var imgObjs = $('tabsCalAgenda').select('img');
                            imgObjs.each(function(item){
                                    item.src = cambiarNombreFile(item.src, (item.up('a').href.search('#'+new_container.id) != -1), 'jpg', '_selected');
                            });
                    }
            });
	}
	if(typeof(CalendarioHomeObj) != 'undefined') {
		CalObj = new CalendarioHomeObj("calendario");
	}
}

function LoadNoticias(){
	if(!($('tabsNoticias') && $('tabsNoticias') != 'undefined')) {
		return;
	}
	
	new Control.Tabs('tabsNoticias', {
		afterChange: function(new_container){
			var imgObjs = $('tabsNoticias').select('img');
			imgObjs.each(function(item){
				item.src = cambiarNombreFile(item.src, (item.up('a').href.search('#'+new_container.id) != -1), 'jpg', '_selected');
			});
		}
	});	

	(function() {		
		function carousel() {
			var span_selected 	= $$('span.goto.active')[0] ? $$('span.goto.active')[0] : null,
				spans 			= $$('span.goto'),
				index			= spans.indexOf(span_selected);
			//console.log(span_selected, spans);
			if(!span_selected) {
				return;
			}
			
			if(spans[index+1]) {
				Utils.fire(spans[index+1], 'click');
			} else {
				Utils.fire(spans[0], 'click');				
			}
		}
		
		setInterval(carousel, 12000);
	})();	
}

function LoadRanking(){
	if(typeof(RankingObj) == 'undefined') {
		return;
	}
	
	var rankClass = new RankingObj();
	
	rankClass.setTiposContainer('rankingTypes');
	new Control.Tabs('tabsRanking', {
		beforeChange: function(old_container, new_container){
			var change = rankClass.cambioSistema(new_container);
			if(!change){
				throw $break;
				return;
			}
			var imgObjs = $('tabsRanking').select('img');
			imgObjs.each(function(item){
				item.src = cambiarNombreFile(item.src, (item.up('a').href.search('#'+new_container.id) != -1), 'jpg', '_selected');
			});
		}
	});
	var x;
	
	/*$("rankingSE", "rankingCC").each(function(e) {
		
		e.observe('mouseover', function(event) {
			var el = event.element() || false,
				id;
			
			if(!el || !el.hasClassName("nombre") || !el.readAttribute("href")) {
				return;
			}
			
			//id = el.href.slice(29, -5);
			id = el.href.split("/")[5].slice(0, -5);
			//ex = el.href;
			
			if(id.empty()) {
				return;
			}
			if(!x) {
				x = $("ranking").cumulativeOffset()[0] - 210;
			}
			//console.log(event, event.pointerX(), event.pointerY());
			playerWidget.show(id, x, event.pointerY() - 3);
			//alert("MOSTRANDO WIDGET DEL JUGADOR " + id);
		});
		e.observe('mouseout', function(event) {
			playerWidget.destroy();
		});		
	});*/

}
/**
 * Manager para los widgets de los jugadores
 * 
 */
var playerWidget = {
	CONTAINER_ID: 'p_widget',
	LOADING_ID: 'p_widget_l',
	working: false,
	_cache: {},
	/**
	 * Datasource de los widgets.
	 * Se recibe HTML
	 * 
	 * La data de los jugadores solicitados
	 * se guarda en cache.
	 * 
	 * @param {Int} id
	 * @param {Function} callback
	 * @return {void}
	 */
	get: function(id, callback) {
		var pw = playerWidget;
		
		if(pw._cache[id]) {
			try {
				callback(pw._cache[id]);
			} catch(e) {}
			return;
		}
		
		new Ajax.Request('/jugador/get_widget_data/#{id}.html'.interpolate({id:id}), {
			onSuccess: function(xhr) {
				var t = xhr.responseText;
				pw._cache[id] = t;
				
				try {
					callback(pw._cache[id]);
				} catch(e) {}				
			}
		});
	},
	/**
	 * Muestra el widget del jugador
	 * 
	 * @param {Int} id
	 * @param {Int} x
	 * @param {Int} y
	 * @return {void}
	 */
	show: function(id, x, y) {
		var pw = playerWidget,
			d;

		pw.loading(true, x + 55, y);
		
		if(pw.working) {
			pw.get(id);
			return;
		}			
		pw.working = true;	
		
		pw.get(id, function(data) {
		
			/*
			 * Eliminamos el div si es que existe
			 */
			pw.destroy();
			
			/*
			 * Creamos el widget
			 */
			d = new Element('div', {
				id: pw.CONTAINER_ID,
				'class': 'player-widget-container'
			});
			
			d.setStyle({
				top: y + 'px',
				left: x + 'px'
			});
			
			d.update(data);
			
			/*
			 * Lo insertamos y ocultamos el loading
			 */
			$$('body')[0].insert(d);
			
			pw.loading(false);
			pw.working = false;
		});
	},
	destroy: function() {
		if($(playerWidget.CONTAINER_ID)) {
			$(playerWidget.CONTAINER_ID).remove();
		}		
	},
	/**
	 * Muestra/oculta el cartel de loading
	 * 
	 * @param {Boolean} status
	 * @param {Int} x
	 * @param {Int} y
	 * @return {void}
	 */
	loading: function(status, x, y) {
		var pw = playerWidget,
			el = $(pw.LOADING_ID),
			img,
			label;
		
		if(el && !status) {
			el.hide();
			return;
		} else if(!el && !status) {
			return;
		}
		
		/*
		 * Creamos el componente y lo mostramos
		 */
		if(!el) {
			el = new Element("div", {
				id: pw.LOADING_ID
			});
			
			img = new Element("img", {
				height: 16,
				width: 16,
				src: "/images/frontend/nacional/loading_chico.gif"
			});
			
			label = new Element("div", { "class": pw.LOADING_ID + "_text"}).update("Cargando info del jugador...");
			
			el.insert(img).insert(label).insert("<div class='clear'></div>");
			$$('body')[0].insert(el);			
		}
		
		el.setStyle({
			top: y + "px",
			left: x + "px"
		});
		
		el.show();
	}
};

var miCT = {
	saveDatos : function() {
		var params 	= $('datosJugadorForm').serialize(true);
		var _url 		= _base_url+'home/saveMisDatos';
		new Ajax.Request(_url, { parameters: params });
	}
}

/* <![CDATA[ */
function createPlayer(_type) {
    if(_type=="audio") {
	    var flashvars = {
	            file:"",
	            autostart:"true"
	    }
      var params = {
              allowfullscreen:"false",
              allowscriptaccess:"always"
      }
      var attributes = {
              id:"player1",
              name:"player1"
      }
      var placeholder = 'placeHolderAudio';
      var height = 1;
      var width = 1;


    } else if(_type=="video") {

	    var flashvars = {
	            file:"",
	            autostart:"false"
	    }
      var params = {
              allowfullscreen:"true",
              allowscriptaccess:"always"
      }
      var attributes = {
              id:"player2",
              name:"player2"
      }
      var placeholder = 'placeHolderVid';
      var height = 250;
      var width = 300;
    } else {
	    var flashvars = {
	            file:"",
	            autostart:"false"
	    }
      var params = {
              allowfullscreen:"true",
              allowscriptaccess:"always"
      }
      var attributes = {
              id:"player3",
              name:"player3"
      }
      var placeholder = 'placeHolderEntre';
      var height = 250;
      var width = 300;
    }

    swfobject.embedSWF(_base_url+"addons/player.swf", placeholder, width, height, "9.0.115", false, flashvars, params, attributes);

}
/* ]]> */

/**
 * Objeto que engloba los reproductores de Noticias
 */
var players = {
	audioPlayer : null,
	videoPlayer : null,
	entrevistasPlayer: null
};

/**
 * Event Handler para el loading de los reproductores
 */
function playerReady(thePlayer) {
    //alert(thePlayer.id);
    if(thePlayer.id == 'player1') {
        players.audioPlayer = window.document[thePlayer.id];
        players.audioPlayer.addModelListener("STATE", "audioStatus._handler");
    } else if(thePlayer.id == 'player2') {
        players.videoPlayer = window.document[thePlayer.id];
    } else {
        players.entrevistasPlayer = window.document[thePlayer.id];
    }
}

/**
 * Objeto que maneja los estados del reproductor de audio
 */
var audioStatus = {
	_actual	: null,
	_playing : false,
	_handler : function(obj) {
		if(obj.newstate == "PLAYING" && !this._playing) {
			this._playing = true;
		} else if (obj.newstate == "COMPLETED" || obj.newstate == "PAUSED" ) {
			this._playing = false;
			this.setInactive();
		}
	},
	play : function(_path, _nodo) {
		// generar un aviso si el archivo no existe
		new Ajax.Request('/home/verificar_archivo', {
			parameters: {'path': _path.gsub(/.+\/asset/, 'asset#{1}') },
			onSuccess: function(xhr) {
				var json = xhr.responseText.evalJSON();
				if(json.ok == "OK") {
					audioStatus.playOK(_path, _nodo);
				} else {
					alert('Archivo no encontrado'); // hacer esto bien
				}
			}
		});
	},
	/**
	 * Reproduce el video _path y
	 * marca como activo el li _nodo
	 *
	 * @param String _path
	 * @param Object _nodo
	 */
	playOK : function(_path, _nodo) {
		if(!this._playing) {
			/*
			 * Si actualmente no esta reproduciendo enviamos
			 * un evento por el API del reproductor
			 * El evento LOAD recibe como parametro la ruta del archivo
			 */
			players.audioPlayer.sendEvent("LOAD",_path);
			this._playing = true;
			this.setActive(_nodo);
		} else {
			/*
			 * Detiene la reproduccion actual del player
			 */
			players.audioPlayer.sendEvent("PLAY","false");
		}
		return false;
	},
	setActive : function(_nodo) {
  	_nodo.up(2).setStyle({backgroundColor: '#F37022'});
  	_nodo.down(0).src = _base_url+'images/frontend/nacional/audio/volA.jpg';
		this._actual = _nodo;
	},
	setInactive : function() {
 		if(this._actual && this._actual != null) {
    	this._actual.up(2).setStyle({backgroundColor: '#312F32'});
    	this._actual.down(0).src = _base_url+'images/frontend/nacional/audio/volD.jpg';
 		}
	},
	updateAudios : function(json) {
		new Effect.Fade('audioItems', {
			duration: 0.2,
			afterFinish: function() {
				$('audioItems').hide();
				$('audioItems').update();
				json.each(function(e) {
					$('audioItems').insert(audioStatus.buildLi(e));
				})
				$('audioItems').appear();
			}
		});
	},
	buildLi : function(item) {
		var li = '<li>' +
					'<div>' +
						'<div class="playButton">' +
							'<a href="'+_base_url+'asset/web_notas_audio/path/'+item.path+'" onclick ="pPlay(this.href, this); return false;">' +
								'<img src="'+_base_url+'images/frontend/nacional/audio/volD.jpg" alt="play!" title="play!"/>'+
							'</a>' +
						'</div>' +
						'<div class="fechaAudio">'+item.fecha+'</div>'+
						'<div class="datosJugador">' +
							'NOMBRE: ' + item.lastname + ', '+ item.name +'<br />'+
							'TORNEO: ' + item.torneo +
						'</div>' +
						'<div class="categoriaYsede">' +
							'CATEGOR&Iacute;A: '+item.categoria+'<br />' +
							'SEDE: '+item.sede+
						'<div>'+
					'</div>' +
				'</li>';
		return li;
	}
};

/**
 * Proxy que se requiere por motivos no muy claros
 */
function pPlay(_path, _nodo) {
	audioStatus.play(_path, _nodo);
}
var test1;
/**
 * Objeto que maneja el estado del reproductor de video
 * @var videoDataList[newOff] Variable global que almacena la lista de videos
 */
var videoStatus = {
	_videoData : [],
	_actualPath : null,
	_videoOffset : 0,
	setData : function (_id) {
		if(typeof this._videoData[_id] == "undefined" ) {
			new Ajax.Request(_base_url+'home/getVideoData/'+_id,
				{
					onSuccess: function(xhr) {
						var data = xhr.responseText.evalJSON(true);
						videoStatus.addData(_id, data);
					}
				});
		} else {
			$('fechaVideo').update(this._videoData[_id].fechaHora);
			$('videoNombre').update(this._videoData[_id].name);
			$('videoApellido').update(this._videoData[_id].lastname);
			$('videoTorneo').update(this._videoData[_id].torneo);
			$('videoCategoria').update(this._videoData[_id].categoria);
			$('videoSede').update(this._videoData[_id].sede);
		}
	},
	addData : function(_id, _data) {
		this._videoData[_id] = _data;
		this.setData(_id);
	},
 	fixPos : function() {
		$$('.videoImagen').each(function(e) {
			var _dim = e.getDimensions();
			var n_dim = Math.round((100-_dim.height)/2)+'px';
			e.setStyle({marginTop: n_dim});
		});
	},
	preloadPag : function(i, action) {
			new Ajax.Request(_base_url+'home/getVideos/'+i,
				{ onSuccess: function(xhr) {
						// se agrega al cache
						videoDataList[i] = xhr.responseText.evalJSON(true);
						videoStatus.moveVideoIndex(action)
						return;
					}
				}
			);
	},
	/**
	 * Estan cruzados prev y next!
	 */
	moveVideoIndex : function(_action) {
		//this.preloadPag();

		if(_action == 'next') {
			var newOff = this._videoOffset-1;
			if(newOff < 0 ) {
				return;
			}
			/*
			 * Si no existe la pagina solicitada de videos en el cache
			 * se genera un pedido ajax
			 */

			if(!videoDataList[newOff] || typeof videoDataList[newOff] == "undefined" || videoDataList[newOff] == null) {
				this.preloadPag(newOff, _action);
				this.fixPos(newOff);
				return;
			}

			$('indexWrapper').update();
			/*
			 * Por cada item cacheado generamos el thumb del vid
			 */
			videoDataList[newOff].each(function(e) {
				var _nPath = e.path.split('.');
				var img = new Element('img', { 'src': _base_url+'asset/web_videos/image/'+e.image, 'class': 'videoImagen' });
				var link2 = '<a onclick="videoStatus.playVideo(this.href, '+e.idVideo+');" href="#'+_nPath[0]+'"><img src="'+_base_url+'asset/web_videos/image/'+e.image+'" class="videoImagen"/></a>';
				var div = new Element('div', { 'class': 'videoItem', 'style': 'display: none' }).insert(link2);
				$('indexWrapper').insert(div);
			});
			$$('.videoItem').invoke('appear');
			this._videoOffset--;
			setTimeout('videoStatus.fixPos()', 100);
		} else {
			//prev
			var newOff = this._videoOffset+1;

			// Si el ultimo indice del cache no tiene 4 items no hacemos nada
			if(videoDataList[this._videoOffset].length < 4 ) { return ; }

			if(!videoDataList[newOff] || videoDataList[newOff] == "undefined" || videoDataList[newOff] == null) {
				this.preloadPag(newOff, _action);
				this.fixPos(newOff);
				return;
			}

			$('indexWrapper').update();
			videoDataList[newOff].each(function(e) {
				var _nPath = e.path.split('.');
				var img = new Element('img', { 'src': _base_url+'asset/web_videos/image/'+e.image, 'class': 'videoImagen' });
				var link2 = '<a onclick="videoStatus.playVideo(this.href, '+e.idVideo+'); " href="#'+_nPath[0]+'"><img src="'+_base_url+'asset/web_videos/image/'+e.image+'" class="videoImagen"/></a>';
				var div = new Element('div', { 'class': 'videoItem', 'style': 'display: none' }).insert(link2);
				$('indexWrapper').insert(div);
			});
			$$('.videoItem').invoke('appear');
			this._videoOffset++;
			setTimeout('videoStatus.fixPos()', 100);
		}
		this.fixPos();
	},
	playVideo : function(_path, _id) {
		var _fixedPath = _path.split('#');
		_path = _base_url+'asset/web_videos/path/'+_fixedPath[1]+'.flv';
		if(this._actualPath != _path) {
			players.videoPlayer.sendEvent("LOAD",_path);
			players.videoPlayer.sendEvent("PLAY");
			this._actualPath = _path;
			this.setData(_id);
		}
	}
}
/**
 * GALERIA
 */

var _imgA = 0;

function observeGalButtons() {
	if(!$('nextImg')) {
		return false;
	}
	Event.observe('nextImg', 'click', function() {
		if(_imgA < galeria.length) {
			if(galeria[_imgA++] != '' && galeria[_imgA] != undefined && galeria[_imgA]) {
				$('fotoMain').src = galeria[_imgA]['path'];
				$('textoFoto').update(galeria[_imgA]['es']);
			}
		}
	});
	Event.observe('prevImg', 'click', function() {
		if(_imgA > 0) {
			if(galeria[_imgA--] != '' && galeria[_imgA] != undefined && galeria[_imgA]) {
				$('fotoMain').src = galeria[_imgA]['path'];
				$('textoFoto').update(galeria[_imgA]['es']);
			}
		}
	});
}
/* scroll galeria */
var galeriaStatus = {
	_videoOffset : 0,
	fixPosG : function(i) {
		$$('.sumaThumb').each(function(e) {
			var _thDim = $('sumaThumb').getDimensions();
			_thDim.width;
			var _dim = e.getDimensions();
			var _mag = e.getStyle('margin-left');
			var n_dim = Math.round(strstr( _mag , 'px' , true)) + i;
			if(n_dim < 90 && (-(_thDim.width - (92 * 4))) < n_dim) {
				e.setStyle({marginLeft: n_dim + "px"});
			}
		});
	},
	moveGaleriaIndex : function(_action) {
		if(_action == 'next') {
			var newOff = this._videoOffset + 92;
			this.fixPosG(newOff);

		} else {
			var newOff = this._videoOffset - 92;
			this.fixPosG(newOff);
		}
	}
}

function centerLoadingImg() {
	var _dim = document.viewport.getDimensions();
	var _loadingDim = $('AJAXPaginationLoading').getDimensions();
	var _left 	= (_dim.width-_loadingDim.width)/2;
	var _top 	= (_dim.height-_loadingDim.height)/2;
	$('AJAXPaginationLoading').setStyle({top: _top+'px', left: _left+'px'});
}

function strstr (haystack, needle, bool) {
    var pos = 0;

    haystack += '';
    pos = haystack.indexOf( needle );
    if (pos == -1) {
        return false;
    } else{
        if (bool){
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}

/**
 * galeria sedes
 */
//var _imgS = 1;
//var _alreadyObservedSedes = false;
//function observeSedesButtons() {
//	Event.observe('Snext', 'click', function() {
//
//	});
//
//	Event.observe('Sprev', 'click', function() {
//		if($('fotoSede_'+(_imgS-1)) != null) {
//			$$('.fotos_sedes').invoke('hide');
//			$('fotoSede_'+(--_imgS)).show();
//		}
// 	});
//}

var sede_img = {
	img : 1,
	next : function() {
		if($('fotoSede_'+(sede_img.img+1)) != null) {
			$$('.fotos_sedes').invoke('hide');
			$('fotoSede_'+(++sede_img.img)).show();
		}
	},
	prev : function() {
		if($('fotoSede_'+(sede_img.img-1)) != null) {
			$$('.fotos_sedes').invoke('hide');
			$('fotoSede_'+(--sede_img.img)).show();
		}
	}
};

function setGal(_id) {
	var gal = eval('galerias.galeria_'+_id);
	if(gal) {
		galeria = gal;
		_imgA = 0;
		$('fotoMain').src = galeria[_imgA]['path'];
		//$('datosAlbumText').update(galeria[_imgA]['en']);
		_imgA++;
		var _cant = galeria.length;
		_cant += galeria.length > 1 ? ' fotos' : ' foto';
		$('datosAlbumText').update(_rotulos[_id].titulo+' | '+_rotulos[_id].fecha+' | '+_cant);
	} else {
		//mostrar el loading
		if(!$('AJAXPaginationLoading')) {
			var img = new Element(
				'img',
				{
					src: '/js/ajaxPagination/bigSnakeOrange.gif',
					alt: 'Cargando'
				}
			);
			var loading = new Element(
				'div',
				{
					id: 'AJAXPaginationLoading',
					style: 'display: block',
					'class': 'bigSnakeOrange'
				}
			).update(img);
			document.body.insert(loading);
			centerLoadingImg();
		} else {
			centerLoadingImg();
			$('AJAXPaginationLoading').show();
		}
		new Ajax.Request(_base_url+'home/getGaleria/'+_id, {
			onSuccess: function(xhr) {
				galerias['galeria_'+_id] = xhr.responseText.evalJSON(true);
				setGal(_id);
			},
			onComplete: function(xhr) {
				//ocultar el loading
				$('AJAXPaginationLoading').hide();
			}
		});
	}
}

Event.observe(window, 'load', function() {
	LoadHome();
});


var titulosHandler = {
	/**
	 * Regenera el html del listado de los
	 * titulos en funcion al paginado
	 * del mismo
	 */
	updateTitulos : function(json) {

		var html = '';
		json.each( function(e) {

			var img = '';
			
			if(e.foto_PE_1 && !e.foto_PE_1.empty()) {
				img = 
				'<div class="foto_holder">' +
                	'<img src="/asset/people/foto/'+e.foto_PE_1+'" height="58" width="40" />' +
	            '</div>'   
			}
			
			var pHTML = '<li onclick="window.location.href = \'/home/ver/'+e.idNoticiaTitulo+'\'">'+
							'<div class="contenidoNoticiaTituloComun">' +
								img +		
								'<div style="float: left; position: relative; height: 65px">' +
									'<div class="fechaNoticiaTituloComun">' +
										e.fechaHora + ' | <span style="text-transform: uppercase">' +	e.name_SD + '</span>'+
									'</div>' +
									'<div class="tituloNoticiaTituloComun">' +
										'<span class="_titulo">' + e.titulo + '</span>' +
									'</div>' +									
									'<div class="noticia_ampliar">' +
									 	'<a href="/home/ver/'+e.idNoticiaTitulo+'">&#187; AMPLIAR</a>' +
									'</div>' +		
								'</div>' +
							'</div>' +
						'</li>'
			html += pHTML;
		});
		$('listaNoticiasComunesUL').update(html);
	},
	swapDestacada : function(index) {
		$$('#paginado_destacadas span.goto').invoke('removeClassName', 'active')[index].addClassName('active');
		$$('#listaNoticiasDestacadas ul li').invoke('hide')[index].show();
	}
}

var entrevistaModalProxy;
entrevistasHandler = {
	nodo : 'entrevistasItems',
	popup : function(e) {
		_id = parseInt(e.up(1).id.slice(4));
		$('entrevistaModalProxy').href = _base_url+'home/cargoEntrevista/'+_id;
		entrevistaModalProxy = new Control.Modal($('entrevistaModalProxy'),{
		     className: 'simple_window',
		     closeOnClick: 'overlay',
		     offsetLeft: 150,
		     overlayOpacity: 0.75
		 });
		entrevistaModalProxy.open();
	},
	update : function(json) {
		new Effect.Fade(entrevistasHandler.nodo, {
			duration: 0.2,
			afterFinish: function() {
				$(entrevistasHandler.nodo).hide();
				$(entrevistasHandler.nodo).update();
				json.each(function(e) {
					$(entrevistasHandler.nodo).insert(entrevistasHandler.buildLi(e));
				})
				$(entrevistasHandler.nodo).appear();
			}
		});
	},
	buildLi : function(item) {
		var li = '<li id="en__'+item.idEntrevista+'">' +
						'<div>' +
							'<div class="fotoEntrevistado">' +
									'<img src="'+item.fotoE+'" alt="foto" />'+
							'</div>' +
							'<div class="datosJugador">' +
									item.fecha + ' &nbsp;&nbsp;|&nbsp;&nbsp '+ item.entrevistado +
							'</div>' +
							'<div class="tituloEntrevista" onclick="entrevistasHandler.popup(this)">' +
									item.titulo +
							'</div>'+
						'</div>' +
					'</li>';
		return li;
	}
}
/*
 * Manejamos las paginaciones
 */

// AUDIO
document.observe("botonesItems:indexChanged", function(event) {
	audioStatus.updateAudios(botonesItems.cachedData[event.memo.page]);
});

// TITULOS
document.observe("botonesTitulos:indexChanged", function(event) {
	titulosHandler.updateTitulos(botonesTitulos.cachedData[event.memo.page]);
});


var nEntrevistaStatus = {
		_nEntrevistaData : [],
		_actualPath : null,
		_nEntrevistaOffset : 0,
		setData : function (_id) {
			if(typeof this._nEntrevistaData[_id] == "undefined" ) {
				new Ajax.Request(_base_url+'home/getNEntrevistaData/'+_id,
					{
						onSuccess: function(xhr) {
							var data = xhr.responseText.evalJSON(true);
							nEntrevistaStatus.addData(_id, data);
						}
					});
			} else {
				if(this._nEntrevistaData[_id].name == null ) {
					$('boxEntrevistasEntrevistado').show();
					$('boxEntrevistasJugador').hide();
					
					$('entrevistaJugador').update(this._nEntrevistaData[_id].entrevistado);
				} else {
					$('boxEntrevistasEntrevistado').hide();
					$('boxEntrevistasJugador').show();
					
					$('entrevistaFecha').update(this._nEntrevistaData[_id].fechaHora);
					$('entrevistaNombre').update(this._nEntrevistaData[_id].name);
					$('entrevistaApellido').update(this._nEntrevistaData[_id].lastname);
					$('entrevistaCategoria').update(this._nEntrevistaData[_id].categoria);
				}
			}
		},
		addData : function(_id, _data) {
			this._nEntrevistaData[_id] = _data;
			this.setData(_id);
		},
	 	fixPos : function() {
			$$('.videoImagen').each(function(e) {
				var _dim = e.getDimensions();
				var n_dim = Math.round((100-_dim.height)/2)+'px';
				e.setStyle({marginTop: n_dim});
			});
		},
		preloadPag : function(i, action) {
				new Ajax.Request(_base_url+'home/getNEntrevistas/'+i,
					{ 
						onSuccess: function(xhr) {
							entrevistaDataList[i] = xhr.responseText.evalJSON(true);
							nEntrevistaStatus.moveVideoIndex(action)
							return;
						}
					}
				);
		},
		/*
		 * Estan cruzados prev y next!
		 */
		moveVideoIndex : function(_action) {
			//this.preloadPag();
			if(_action == 'next') {
				var newOff = this._nEntrevistaOffset-1;
				if(newOff < 0 ) {
					return;
				}
				/*
				 * Si no existe la pagina solicitada de videos en el cache
				 * se genera un pedido ajax
				 */

				if(!entrevistaDataList[newOff] || entrevistaDataList[newOff] == "undefined" || entrevistaDataList[newOff] == null) {
					this.preloadPag(newOff, _action);
					this.fixPos(newOff);
					return;
				}

				$('indexWrapperEntrevistas').update();
				/*
				 * Por cada item cacheado generamos el thumb del vid
				 */
				entrevistaDataList[newOff].each(function(e) {
					var _nPath = e.videoPath.split('.');
					var img = new Element('img', { 'src': _base_url+'asset/web_entrevistas/videoImage/'+e.videoImage, 'class': 'videoImagen' });
					var link2 = '<a onclick="nEntrevistaStatus.playVideo(this.href, '+e.idEntrevista+');" href="#'+e.videoPath+'"><img src="'+_base_url+'asset/web_entrevistas/videoImage/'+e.videoImage+'" class="videoImagen"/></a>';
					var div = new Element('div', { 'class': 'videoItem', 'style': 'display: none' }).insert(link2);
					$('indexWrapperEntrevistas').insert(div);
				});

				$$('.videoItem').invoke('appear');
				this._nEntrevistaOffset--;
				setTimeout('nEntrevistaStatus.fixPos()', 100);
			} else {
				//prev
				var newOff = this._nEntrevistaOffset+1;

				// Si el ultimo indice del cache no tiene 4 items no hacemos nada
				if(entrevistaDataList[this._nEntrevistaOffset].length < 4 ) { return ; }

				if(!entrevistaDataList[newOff] || entrevistaDataList[newOff] == "undefined" || entrevistaDataList[newOff] == null) {
					this.preloadPag(newOff, _action);
					this.fixPos(newOff);
					return;
				}
				$('indexWrapperEntrevistas').update();

				entrevistaDataList[newOff].each(function(e) {
					var _nPath = e.videoPath.split('.');
					var img = new Element('img', { 'src': _base_url+'asset/web_entrevistas/videoImage/'+e.videoImage, 'class': 'videoImagen' });
					var link2 = '<a onclick="nEntrevistaStatus.playVideo(this.href, '+e.idEntrevista+'); " href="#'+e.videoPath+'"><img src="'+_base_url+'asset/web_entrevistas/videoImage/'+e.videoImage+'" class="videoImagen"/></a>';
					var div = new Element('div', { 'class': 'videoItem', 'style': 'display: none' }).insert(link2);
					$('indexWrapperEntrevistas').insert(div);
				});

				$$('.videoItem').invoke('appear');
				this._nEntrevistaOffset++;
				setTimeout('nEntrevistaStatus.fixPos()', 100);
			}
			this.fixPos();
		},
		playVideo : function(num_path, _id) {
			var __path = num_path.split('#');
			_path = _base_url+'asset/web_entrevistas/videoPath/'+__path[1];
			if(this._actualPath != _path) {
				players.entrevistasPlayer.sendEvent("LOAD",_path);
				players.entrevistasPlayer.sendEvent("PLAY");
				this._actualPath = _path;
				this.setData(_id);
			}
		}
	}
