function VideosModule(externalConfig)
{
	// Default configuration
	var defaultConfig = {
		position: "superior",
		videos: 6,
		cyclical: true,
		playable: false,
		debug: false && typeof console == "object"
	};

	// Configuration variable
	var config = {};
	jQuery.extend(config, defaultConfig, externalConfig);
	if (config.debug) console.log(config);

	// Objects variable. Direct access to objects. Optimization
	var objects = {
		me: jQuery("#" + config.id)
	};
	objects.parent = objects.me.parent();

	// Check configuration
	if (config.id == undefined || config.url == undefined || objects.me.length == 0)
	{
		if (objects.me.length > 0)
		{
			displayError();
		}
		return;
	}

	// Pager variable
	var pager = {
		index: 0,
		total: 0
	};

	// Data variable. Stores data information loaded from XML request
	var data = false;

	// Load XML data. Asynchronous request (logic continues in the function)
	loadXML(true);

	function loadXML(first)
	{
		jQuery.ajax({
			type: "GET",
			url: config.url,
			dataType: "xml",
			timeout: 5000,
			success: function(xml)
			{
				var num = jQuery("item", xml).length;
				if (num == 0)
				{
					displayError();
					return;
				}

				// Next steps
				processXML(xml, first);
			},
			error: function(request, status, error)
			{
				if (config.debug) console.log(error);
				displayError();
			}
		});
	}

	function processXML(xml, first)
	{
		extractData(xml);
		displayData(true);

		if (first)
		{
			// Configure main events only once
			configureOnloadEvents();
		}
		
	}

	function extractData(xml)
	{
		var channel = jQuery("channel", xml);
		data = {
			title: channel.find("title").text(),
			url: channel.attr("rdf:about"),
			urlTV: channel.find("link").text(),
			videos: []
		};

		// Get channel name
		if (data.title)
		{
			data.title = data.title.substring(15, data.title.length);
			if (data.title == "")
			{
				data.title = "Los vídeos del día";
			}
		}

		jQuery("item", xml).each(function(i) {
			var item = jQuery(this);

			var video = {
				guid: item.find("guid").text(),
				url: item.find("link").text(),
				title: item.find("title").text(),
				description: item.find("description").text(),
				duration: item.find("duration").text(),
				images: {
					"big": item.find("image").attr("rdf:about"),
					"small": item.find("enclosure").attr("url")
				},
				numcomments: item.find("numComments").text(),
				valoration: item.find("valoration").text(),
				date: item.find("guid").next().text()
			};
			
			if (video.duration)
			{
				var seconds = Math.floor(video.duration%60);
				var minutes = Math.floor(video.duration/60);
				video.duration = minutes + ':' + (seconds < 10 ? "0" + seconds : seconds);
			}

			if (config.debug) video.title = "[" + i + "] " + video.title;
			data.videos[i] = video;
		});
		pager.total = data.videos.length;

		if (config.debug) console.log(data);
	}

	function displayData(firstLoad)
	{
		switch (config.position)
		{
			case "superior": {
				var videosHTML = getVideosHTML();
				var pagerHTML = getPagerHTML();

				objects.me.html(pagerHTML.previous + videosHTML + pagerHTML.next);
				break;
			}
			case "lateral": {
				if (firstLoad)
				{
					var headerHTML = '<h3><a href="' + data.url + '" title="' + data.title + ' en 20minutos.tv" target="_blank">' + data.title + '</a></h3>';
					var playerHTML = getPlayerHTML(data.videos[0]);

					// Remove first video (used in the player) only if others videos are not playable
					if (!config.playable)
					{
						data.videos.shift(); 
						pager.total = pager.total - 1;
					}

					var videosHTML = getVideosHTML();
					var pagerHTML = getPagerHTML();
					// Integrated Ad BBVA
					var bannerHTML = '';
					/*
					if (config.url.match(/\/deportes/))
					{
						bannerHTML = '<div style="margin-top:8px;"><a href="http://smart.20minutos.es/call/cliccommand/1921289/?" target="_blank" title="La Jornada de tu Vida"><img src="http://estaticos.20minutos.es/mmedia/microsites/bbva/i/banner_jornada.gif" /></a></div>';
					}
					*/

					objects.me.html(headerHTML + playerHTML + bannerHTML + videosHTML + '<div class="vpag">' + pagerHTML.previous + pagerHTML.next + '</div>');
				}
				else
				{
					// Pager event does not reload player HTML
					var videosHTML = getVideosHTML();
					var pagerHTML = getPagerHTML();

					objects.me.find("ul.thumnitems, div.vpag").remove(); // Remove small images and pager
					objects.me.append(videosHTML + '<div class="vpag">' + pagerHTML.previous + pagerHTML.next + '</div>');
				}
				break;
			}
		}

		configureVideoEvents();
	}

	function getPlayerHTML(video)
	{
		var title = video.title;
		title = title.replace(/</g, '').replace(/>/g, '').replace(/&/g, '&amp;').replace(/"/g,'&quot;');
		var videoplayer = data.urlTV + "videoplayer/" + video.guid + "/";

		return getVideoPlayerHTML(videoplayer, video.url, title, video.numcomments, video.valoration, video.date);
	}

	function getVideoPlayerHTML(videoplayer, link, title, numcomments, valoration, date)
	{
		var html = '<div class="cont_video"><embed src="' + videoplayer + '" style="width: 350px; height: 205px;" allowfullscreen="true" wmode="transparent" type="application/x-shockwave-flash" /></div>';

		html +='<div class="info">';
		html +='<h4><a href="' + link + '" title="' + title + '" target="_blank">' + title + '</a></h4>';

		if( (valoration != '') || (numcomments != ''))
		{
			html +='<div class="estirar">';
			if (valoration != '')
			{
				var valorationclass = '';
				switch(valoration)
				{
					case '1': valorationclass = 'uno'; break;
					case '2': valorationclass = 'dos'; break;
					case '3': valorationclass = 'tres'; break;
					case '4': valorationclass = 'cuatro'; break;
					case '5': valorationclass = 'cinco'; break;
					default: valorationclass = 'cero'; break;
				}
				html +='<p class="puntuacion '+ valorationclass +'">Tu puntuación es de '+ valoration + '</p>';
			}//fin if valoration

			//Parser separador
			var html_barrita = '';
			if( (valoration != '') && (numcomments != '')){
				html_barrita = '| ';
			}
				
			if (numcomments != '')
			{
				html +='<p class="n_comentarios">';
				if (numcomments != '')
				{
					var textcomments = 'Comenta este vídeo';
					if (numcomments == 1)
					{
						textcomments = '1 comentario';
					}
					else if (numcomments > 1)
					{
						textcomments = numcomments + ' comentarios';
					}
					html +=  html_barrita + '<a href="' + link + '#comentarios" title="Comenta este vídeo" target="_blank">'  + textcomments + '</a>';
				}
				html += '</p>';
			}//fin del if numcomments
			
			html += '</div>';
		}//fin del if valoration y numcomments
		
		html +='</div>';

		return html;
	}

	function getVideosHTML()
	{
		var html = '<ul class="' + (config.position == "superior" ? "thumnitemstop" : "thumnitems") + '">';
		var current = pager.index;
		for (var i = 0; i < pager.total && i < config.videos; i++, current++)
		{
			if (current >= pager.total) {
				if (config.cyclical)
				{
					current = current - pager.total;
				}
				else
				{
					break; // No cycle pager
				}
			}
			html += getVideoHTML(data.videos[current]);
		}
		html += '</ul>';
		return html;
	}

	function getVideoHTML(video)
	{
		var title = video.title;
		if (title)
		{
			if (title.length > 42)
			{
				title = title.substring('0','39') + '...';
			}
			title = title.replace(/</g, '').replace(/>/g, '').replace(/&/g, '&amp;').replace(/"/g,'&quot;');
		}
		
		var html = '<li>';
		html += '<a href="' + video.url + '" class="imgcontainer" style="background:url(' + video.images.small + ') no-repeat center center;" target="_blank">';
		html += '<img src="' + url_css3 + 'i/videos_20minutostv/playthumn.png" title="' + title + '" class="playpng" />';
		if (video.duration)
		{
			html += '<span class="caption">' + video.duration + '</span>';
		}
		html += '</a>';
		html += '<a href="' + video.url + '" title="' + title + '" target="_blank">' + title + '</a>';
		html += '</li>';
		return html;
	}

	function getPagerHTML()
	{
		var pagerHTML = {
			previous: '<a href="#" class="prev noprev"><span>&laquo; Anteriores</span></a>',
			next: '<a href="#" class="next nonext"><span>Siguientes &raquo;</span></a>'
		};

		if (pager.total > config.videos && config.videos > 0)
		{
			if (config.cyclical)
			{
				pagerHTML.previous = '<a href="#" class="prev"><span>&laquo; Anteriores</span></a>';
				pagerHTML.next = '<a href="#" class="next"><span>Siguientes &raquo;</span></a>';
			}
			else
			{
				if (pager.index > 0) {
					pagerHTML.previous = '<a href="#" class="prev"><span>&laquo; Anteriores</span></a>';
				}

				if (pager.total > pager.index + config.videos)
				{
					pagerHTML.next = '<a href="#" class="next"><span>Siguientes &raquo;</span></a>';
				}
			}
		}
		return pagerHTML;
	}

	function displayError()
	{
		objects.me.html('<h3 class="error">Lo sentimos.</h3><p class="error">Se ha producido un error. Por favor, vuelve a intentarlo.</p>');
	}

	function displayLoading()
	{
		objects.me.html('<p><img src="' + url_css3 + 'i/videos_20minutostv/loading_black.gif" alt="Cargando..." /></p>');
	}

	function configureVideoEvents()
	{
		// Pager events
		objects.me.find("a.prev").bind("click", function() {
			pager.index = pager.index - config.videos;
			if (pager.index < 0)
			{
				pager.index = pager.total + pager.index;
			}
			displayData(false);
			return false;
		});

		objects.me.find("a.next").bind("click", function() {
			pager.index = pager.index + config.videos;
			if (pager.index >= pager.total)
			{
				pager.index = pager.index - pager.total;
			}
			displayData(false);
			return false;
		});

		// Play icon
		objects.me.find(".thumnitemstop, .thumnitems").find("li a").mouseover( function() {
			jQuery(this).children(".playpng").show();
		}).mouseout( function() {
			jQuery(this).children(".playpng").hide();
		});

		// Playable videos
		if (config.playable) {
			objects.me.find("ul a.imgcontainer").bind("click", function() {
				var object = jQuery(this).parent().find("a[@title]");
				var link = object.attr("href");
				var title = object.attr("title");
				var videoplayer = link.replace(/(.+)\/video\/([^-]+)-(.+)$/, '$1/videoplayer/$2/');

				// TODO: No soportada la opción de modificar el número de comentarios y valoración. No tenemos la información en el HTML, replantear utilizando la lista de vídeos cuando se utilice.
				var playerHTML = getVideoPlayerHTML(videoplayer, link, title, '', '', '');

				var object = objects.me.find("div.cont_video");
				object.next().remove();
				object.remove();
				objects.me.find("h3").after(playerHTML);
				return false;
			});
		}
	}

	function configureOnloadEvents()
	{
		// Change channel
		objects.me.prev("select").bind("change", function(){
			if (this.value != "no")
			{
				config.url = this.value;
				pager.index = 0;
				displayLoading();

				// Patronicio BBVA
				if (this.value.match(/\/deportes/))
				{
					objects.parent.find('div.patrocinio').show();
				}
				else
				{
					objects.parent.find('div.patrocinio').hide();
				}
				

				loadXML(false);
			}
		});
	}
}

function LoadModuleRankings()
{
	$(".cont_pestanas").find("a.tab").click(function ()
	{
		var tab_show = $(this);
		var content_show = tab_show.attr("href");
		
		var contenedor = tab_show.parents('.cont_pestanas').parent();
		var tab_hide = contenedor.find(".activo");
		var content_hide = tab_hide.attr("href");
		
		tab_hide.removeClass("activo");
		tab_show.addClass("activo");

		contenedor.find(content_hide).slideUp();
		contenedor.find(content_show).slideDown();

		return false;
	});
}