var rnHome = function()
{
// INI PUBLIC SCOPE	
	var public = {	
		
		timer	   : 750,
		timeout	   : 10000,
		idLanguage : document.location.href.split("/")[3],		
		
		paginate : function(next,img)
		{			
			originalSrc = img.src;															// Recuperamos la imagen original
			sct 		= $(img).parents("div[id^='sub_']")[0].id.split("_")[1];			// Recuperamos la seccion
			t 			= $('#'+sct+'Layer').attr("class");									// Recuperamos el maximo de paginas que habra en la páginacion
			url    		= '/'+G_RN_CONTEXT+'/'+sct+'Ajax.html';								// Preparamos la url de peticion			
			itemActual  = getItemActual(img);												// Recuperamos la pagina actual																
			newItem     = next ? itemActual - 1 : itemActual + 1;							// Recuperamos siguiente página			
			
			setItemActual(img,newItem);													// Incrementamos el numero de pagina
			
			$.ajax(
			{
				url		 : url,																// url destino
				data	 : 'item='+(newItem)+'&idLanguage='+G_RN_IDLANGUAGE, 				// Mandamos la pagina que queremos			
				success	 : function(xml)													// Peticion satisfactoria
				{					
					$('div#'+sct+'Layer').fadeOut(public.timer,	function()				// Escondemos capa de contenido
					{
						if (sct == 'noticias') $('#home_media').empty();				// Si la seccion a cargar es noticias limiamos zona de media
						renderSection(sct,xml);											// Renderizamos seccion con los datos recibidos
						img.src = originalSrc;											// Recuperamos src orginal de la boton pulsado (imagen)
						img.alt = img.title  = next ? 'next' : 'prev';					// Asignamos title y alt
						arrowOn(sct, next ? 'prev' : 'next', newItem, sct+'.html');		// Activamos boton prev|next
						if (next)
							if ( newItem == 1 ) arrowOff(sct,'next');					// Desactivamos el boton next
						else 
							if ( newItem >= t ) arrowOff(sct,'prev');				  	// Desactivamos el boton prev
					} );
				},
				beforeSend : function()
				{ 
					img.src = '/media/img/common/iconos/ajax-loader.gif'; 					// Mostramos indicativo de carga ajax
					img.alt = img.title="loading..."; 										// Asiganmos alt y title a la imagen
				}, 
				error	   : function(err) 
				{
					if (err.status == 200 && err.responseXML != null) 
						this.success(err.responseXML);										// Fallo pero recivimos correctamente los datos. (¿bug jQuery?) redirigimos a success()
					else  {
						img.src = '/media/img/common/iconos/alert.gif'; 					// Sustituimos imagen del boton por una de error de carga
						img.alt = img.title="Load error";									// Asiganmos alt y title a la imagen
					}
				}
			});		
		}
	};
// END PUBLIC SCOPE
	
	
	
// INI PRIVATE SCOPE
	
	// Estructura de los xml que recibimos [seccion]-[nodo]-[selector de contenido]
	var seccion = { 
		preguntale	: {
			pregunta  	: 'div#sub_preguntale h3',
			respuesta 	: 'div#sub_preguntale div#contentAnswer'
		},
		noticias	: {
			titular   	: 'div#sub_noticias h3 a',
			link        : 'div#sub_noticias h3 a',
			fecha       : 'div#sub_noticias h2.fecha_home',
			contenido 	: 'div#noticiasLayer div#contentNews',
			media     	: 'div#home_media'

		},
		foro		: {
			post      	: 'div#sub_foro ul li a',
			link      	: 'div#sub_foro ul li a'
		},
		blog		: {
			fecha     	: 'div.post_home h3',
			titular   	: 'div.post_home h4 a',
			link      	: 'div.post_home h4 a'
		},
		shop		: {
			imagen      : '#home_prod_img img',
			descripcion : '#home_prod_desc div#contentShop',
			link        : '#home_prod_img a'
		},
		juego		: {
			torneo      : '#sub_juego h3',
			categoria   : '#sub_juego h4',
			fecha	    : '#sub_juego h5',
			players     : '#sub_juego h6',
			descripcion : '#sub_juego p'
		}
	};		
	// Selector de los padres de los selectores de contenido del objeto 'seccion'
	// Solo para secciones que muestras mas de un item por pagina
	var parentSeccion = { 
		foro		: 'div#sub_foro ul li',
		blog		: 'div.post_home'
	};
		
	//Esconde un elemento
	function hide(el,t,fn)
	{
		$(el)
			.css({ display : 'block', overflow : 'hidden' })
			.animate({ height : 0, opacity : 0 },t,fn);
	}
	
	function getEstado(e)
	{
		return parseInt($(e).attr("class").split('-')[0]);
	}	
	
	function getItemActual(e)
	{
		return parseInt( $(e).attr("class").split('-')[1]);
	}
	
	function setItemActual(e,v)
	{
		$(e).attr("class", $(e).attr("class").split('-')[0] + '-' + v);
	}
	
	function renderSection(sct,xml)
	{
		for(i in seccion[sct]) 							// Recorremos la seccion del objeto 'seccion'
		{
			c = $('seccion item',xml).size(); 		 	// Numero de items recibidos
			e = $('seccion item '+i,xml);			 	// Nodos del tipo i (preguntale, noticias, blog... etc)
						
			typeAtribute = getAttrValue(e,'type');	 	// Recuperamos el tipo de contenido con el atributo type del nodo 'i' iterado
			
			totalActual = $(seccion[sct][i]).size(); 	// Recuperamos los items actuales en la subseccion 'sct'
			
			if ( c < totalActual )
			{ 											// Hay menos items(en el xml) que los actuales(en el documento)
				for(o=c;o<totalActual;o++) {			// Eliminamos elementos sobrantes
					$(seccion[sct][i]).eq(o).parent(parentSeccion[sct]).remove(); 
				}
			}
			else if ( c > totalActual && totalActual != 0)
			{ 											// Hay mas items(en el xml) que los actuales(en el documento)
				for(o=totalActual;o<c;o++) { 			//Añadimos elementos que faltan
					$(seccion[sct][i]).eq(0).parent(parentSeccion[sct]).clone().insertBefore( $(parentSeccion[sct]).filter(':last') );
				}
			}

			switch ( typeAtribute )
			{   										// Consultamos el tipo de contenido
				case "string":							// Escribimos contenido
					for (o=0;o<c;o++) {
						txtNode = getNodeValue(e,o);
						$(seccion[sct][i]).eq(o).html( txtNode );
					}
					break;
				case "link":							// Actualizamos link					
					for (o=0;o<c;o++) {
						txtNode = getNodeValue(e,o);
						$(seccion[sct][i]).eq(o).attr('href', txtNode );		
					}
					break;
				case "swf":		 						// Escribimos flash
					txtNode = getNodeValue(e);
					var so = new SWFObject(txtNode, "peli", "320", "291", "7", "#FFFFFF");
					so.addParam("wmode", "transparent");
					so.write("home_media");
					break;
				case "img":								// Actualizamos imagen
					txtNode = getNodeValue(e);
					$(seccion[sct][i]).attr("src",txtNode);
					break;
				case "image":							// Añadimos imagen
					txtNode = getNodeValue(e);
					$("div#home_media").html('<img src="'+txtNode+'" />'); //TODO (¿div#home_media: no podemos usar literales fijos?)
					break;
			}
		}		
		$("#"+sct+"Layer").css( { display:'block' } );
		$.scrollTo( $("#sub_"+sct)[0].offsetTop - 25, 200);
		$("#"+sct+"Layer").fadeIn(public.timer);
				
	}
   
	// Recupera el valor de un nodo
	function getNodeValue(e,i)
	{
		i = i || 0;
		try {
			return $(e)[i].firstChild.data;
		} catch(e){ return ""; }
	}
	
	// Recupera el valor de un atributode de un nodo
	function getAttrValue(e,atr)
	{
		try {
			return $(e).attr(atr).toLowerCase();
		} catch(e){ return ""; }
	}
	
	//Muestra imagen de prev/next habilitado
	function arrowOn(prnt,act,iActual,url) 
	{		
		e = $('#'+prnt+'Arrows .'+act+' img');
		$(e).attr({			
			'class'		: '1-'+iActual+'',
			src			: '/media/img/common/iconos/ico_'+act+'_on.gif',
			title		: act
		});

		if ( $(e).parent()[0].tagName.toUpperCase() == "DIV" ) $(e).wrap( '<a href="'+url+'.html"></a>' );
	}
	
	//Muestra imagen de prev/next dehabilitado
	function arrowOff(prnt,act)
	{
		e = $('#'+prnt+'Arrows .'+act+' img');
		$(e).attr({			
			'class'		: '0-'+$(e).attr('class').split("-")[1],
			src			: '/media/img/common/iconos/ico_'+act+'_off.gif',
			title		: act
		});
		$(e).parent().replaceWith($(e));
	}
	
	//inicializacion
	(function()
	{
		$(".prev, .next").click(function(){return false});					// Cancelamos click de todos los elementos prev y next
		
		$("div[id^='sub_']").each(function()								// Recorremos todas las subsecciones
		{
			$(this).find(".prev img").each(function()						// Buscamos y configuramos click prev de la seccio iterada
			{
				$(this).click(function()
				{					
					e = $(this).attr("class").split('-')[0];
					if ( getEstado(this) ) public.paginate(false,this);
				});
			});
			
			$(this).find(".next img").each(function(){						// Buscamos y configuramos click next de la seccio iterada
				$(this).click(function()
				{					
					e = $(this).attr("class").split('-')[0];
					if ( getEstado(this) ) public.paginate(true,this);
				});
			});
		});
			
		// Comprovamos si existe alguna seccion con solo una pagina para desactivar el boton prev	
		$('div[id*=Layer][class=1]').each(function()
		{   
			id = this.id.split('Layer')[0]+'Arrows';   
			replace = $('#'+id).find('a img');
			newImg = $('#'+id).find('a img')[0].src.replace('on.gif','off.gif');
			$('#'+id).find('a img').attr("src",newImg).unbind('click');
			$('#'+id).find('a').replaceWith(replace);
		});
		
		// configuracion general AJAX
		$.ajaxSetup({
			type	 : 'post',															// Metodo de la peticion
			dataType : 'xml',															// Tipo de datos que recogeremos (TODO: comprobar que sea un xml)
			timeout  : public.timeout													// Timeout de la llamada
		});
	})();
	//fin inicializacion
	
// END PRIVATE SCOPE
	return public;
}