function setCssCapabilities(){
	var browser = '';
	var version = $.browser.version.split('.');	
	var mozversion = [1,9,2,3];
	var webkitversion = [533,16];
	var ieversion = [8,0];
	var operaversion = [10,54];
	
	if($.browser.msie){
		browser = 'msie';		
		if (version[0] > ieversion[0] ){
			version = ieversion;			
		} else if ( version[0] == ieversion[0] ) {
			if ( version[1] >= ieversion[1]){
				version = ieversion;
			}
		}		
	}
						
	if($.browser.webkit){
		browser = 'webkit';		
		if (version[0] > webkitversion[0] ){
			version = webkitversion;			
		} else if ( version[0] == webkitversion[0] ) {
			if ( version[1] >= webkitversion[1]){
				version = webkitversion;
			}
		}	
	}
		
	if($.browser.mozilla){
		browser = 'mozilla';
		if (version[0] > mozversion[0] ){
			version = mozversion;			
		} else if ( version[0] == mozversion[0] ) {
			if ( version[1] > mozversion[1]){
				version = mozversion;
			} else if ( version[1] == mozversion[1] ) {
				if ( version[2] > mozversion[2] ) {
					version = mozversion;
				} else if ( version[2] == mozversion[2] ) {
					if (version[3] > mozversion[3]) {
						version = mozversion;
					} 
				}
			}
		}
	}
		
	if($.browser.opera){
		browser = 'opera';
		if (version[0] > operaversion[0] ){
			version = operaversion;			
		} else if ( version[0] == operaversion[0] ) {
			if ( version[1] >= operaversion[1]){
				version = operaversion;
			}
		}
	}
	
	$('body').addClass(browser + version.join(''));
}

function showDropDown(id){	
	// Ocultamos todos los que haya abiertos
	if ( id != 'top_bar_list_topics') $('#top_bar_list_topics').hide();
	if ( id != 'top_bar_list_cobrands') $('#top_bar_list_cobrands').hide();
	if ( id != 'top_bar_list_countries') $('#top_bar_list_countries').hide();	
	
	// Desplegamos el que nos piden
	$('#' + id).toggle();	
}

// Función que será llamada cuando el usuario esté logado en Facebook
function onConnected(){
	$('#tophunted_path_fblogin').html('Bienvenido, <fb:name uid="loggedinuser" useyou="false"></fb:name>&nbsp;&nbsp;<a href="#" onclick="FB.Connect.logout(function() { reload(); }); return false;" >Cerrar sesi&oacute;n</a>');
	
	// because this is XFBML, we need to tell Facebook to re-process the document 
  	FB.XFBML.Host.parseDomTree();
}

// Función que será llamada cuando el usuario no esté logado en Facebook
function onNotConnected(){
	$('#tophunted_path_fblogin').html('<a href="#" onclick="FB.Connect.requireSession(); return false;">Login usando Facebook</a>')
}

// Función que tratará el mouseover de un profile número uno de la lista de tops
function overTopOne(which){
	// Quitamos la clase on a todos los que la tengan
	$('#tophunted_body_ones > ul > li > a').each(function(){ $(this).removeClass('on')});
	// Ocultamos la descripción de todos
	$('#tophunted_body_ones > ul > li > div').each(function(){ $(this).hide()});
	$('#tophunted_body_ones > ul > li > p').each(function(){ $(this).hide()});
	
	// Se la ponemos al que estamos encima
	$(which).find('a:first').addClass('on');
	// Mostramos la descripción del que estamos encima
	$(which).find('div:first').show();
	$(which).find('p:first').show();
}

// Función que tratará los resultados devueltos por twitter
function handleTwitterSearch(data){				
				
	$('#twitter-sidebar').html('<h3><span class="toggle-button off showatfirst">Ahora en Twitter:</span></h3><div></div>');
	
	$(data.results).each(function(){
												
		var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
		
		var twitterEntry = document.createElement('div');
		var twitterEntry_img = document.createElement('img');
		var twitterEntry_user = document.createElement('span');
		var twitterEntry_text = document.createElement('span');
		
		$(twitterEntry_img).attr('src', this.profile_image_url);
		$(twitterEntry_user).text(this.from_user);
		$(twitterEntry_text).html(this.text.replace(regexp, "<a href=\"$1\">$1</a>"));		
		
		$('#twitter-sidebar > div').append(twitterEntry)
		$(twitterEntry).append(twitterEntry_img);
		$(twitterEntry).append(twitterEntry_user);
		$(twitterEntry).append(twitterEntry_text);
	});

}

// Función que tratará los resultados devueltos por youtube
function handleYoutubeSearch(data){				
	
	var feed = data.feed;
	var entries = feed.entry || [];
	var html = ['<h3><span class="toggle-button off showatfirst">Ahora en Youtube:</span></h3><ul class="videos group">'];
	for (var i = 0; i < entries.length; i++) {
		var entry = entries[i];
		var title = entry.title.$t.substr(0, 20);
		var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
		var playerUrl = entries[i].media$group.media$player.url;
		html.push('<li onclick="window.open(\'', playerUrl, '\', true)">',
		          '<span class="titlec">', title, '...</span><img src="', 
		          thumbnailUrl, '" width="130" height="97"/>', '</span></li>');
	}
	html.push('</ul><div class="clearboth"></div>');
	
	html = html.join('');
	
	$('#youtube-sidebar').html(html);
}

// Función que recogerá una serie de tops comprendidos entre dos parámetros
function getTops(from, size, topic){
	
	var url = '';
	
	if (topic != undefined){
		 url = "/getLastTopsByTopic/" + topic + "/" + from + "/" + size;
	} else {
		url = "/getLastTops/" + from + "/" + size;		
	}		
	
	$.ajax({
		type: "GET",		
		url: url,
		success: function(data){
										
			if ($(data).find('top').length > 0){				
				
				if (topic != undefined) {
					
					replaceTopicTops(data);					
										
				} else {
					replaceTops(data);
				}
										
				setPagination(from, size, $(data).find('top').length, topic);
			
				$.scrollTo('#tophunted_body_left_pub', 500);				
				
																																																							
			} else {
				// Do nothing
			}						
											
		},
		error: function(msg){
			// Do nothing									
		}
	});
	
}

// Función que sustituirá la lista de tops por la recibida por parámetro
function replaceTops(data){

	var html = '';	
	
	$(data).find('top').each(function(index){
		
		if ( index == 1 || index == 4 || index == 7 ){
			html += '<li class="top_center">';
		} else {
			html += '<li>';
		}
		
		if ($(this).find('sponsorName').text() != ''){
			html += '<div class="featured-logo">Patrocinado por: <strong>' + $(this).find('sponsorName').text()+ '</strong></div>';
		}
		
		html += '<div class="avatar">\
					<a href="/' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '">\
						<img alt="' + $(this).find('profile_title').text() + '" src="/getProfileAvatarImage?profileName=' + $(this).find('profile_url').text() + '&w=241&h=" onerror="this.src=\'/img/profile_preview_embed.gif\'"/>\
					</a>\
				</div>\
				<div class="top_title">\
				<h3>\
				<a href="/' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '">' + $(this).find('top_title').text() + '</a><br />';
		
		if ( parseInt($(this).find('countUpdates').text()) > 1 ){
			html += '<cite>por <a href="/hunter/' + $(this).find('user_url').text() + '">' + $(this).find('vc_alias').text() + '</a>, en <a href="/' + $(this).find('topic_url').text() + '">' + $(this).find('topic_name').text() + '</a>, actualizado el <span class="date" title="' + $(this).find('dt_publishedDate').text() + '">' + $(this).find('dt_publishedDate').text() + '</span></cite>';
		} else {
			html += '<cite>por <a href="/hunter/' + $(this).find('user_url').text() + '">' + $(this).find('vc_alias').text() + '</a>, en <a href="/' + $(this).find('topic_url').text() + '">' + $(this).find('topic_name').text() + '</a>, creado el <span class="date" title="' + $(this).find('dt_publishedDate').text() + '">' + $(this).find('dt_publishedDate').text() + '</span></cite>';
		}
		
		html += '</h3>\
					</div>\
					<div class="tophunted_body_left_last_top_more">\
						<a href="/' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '">ver lista »</a>\
					</div>\
				</li>';
	});
	
	$('#tophunted_body_left_last_tops').html(html);
		
}

// Función que sustituirá la lista de tops por la recibida por parámetro
function replaceTopicTops(data){

	var html = '';	
	
	$(data).find('top').each(function(index){
		
		if ( index == 1 || index == 4 || index == 7 ){
			html += '<li class="top_center">';
		} else {
			html += '<li>';
		}
		
		html += '<div class="avatar">\
					<a href="/' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '">\
						<img alt="' + $(this).find('profile_title').text() + '" src="/getProfileAvatarImage?profileName=' + $(this).find('profile_url').text() + '&w=241&h=" onerror="this.src=\'/img/profile_preview_embed.gif\'"/>\
					</a>\
				</div>\
				<div class="top_title">\
				<h3>\
				<a href="/' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '">' + $(this).find('top_title').text() + '</a><br />';
		
		if ( parseInt($(this).find('countUpdates').text()) > 1 ){
			html += '<cite>por <a href="/hunter/' + $(this).find('user_url').text() + '">' + $(this).find('vc_alias').text() + '</a>, actualizado el <span class="date" title="' + $(this).find('dt_publishedDate').text() + '">' + $(this).find('dt_publishedDate').text() + '</span></cite>';
		} else {
			html += '<cite>por <a href="/hunter/' + $(this).find('user_url').text() + '">' + $(this).find('vc_alias').text() + '</a>, creado el <span class="date" title="' + $(this).find('dt_publishedDate').text() + '">' + $(this).find('dt_publishedDate').text() + '</span></cite>';
		}
		
		html += '</h3>\
					</div>\
					<div class="tophunted_body_left_last_top_more">\
						<a href="/' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '">ver lista »</a>\
					</div>\
				</li>';
	});
	
	$('#tophunted_body_left_last_tops').html(html);
		
}

// Función que mostrará los links de paginación activados y con los valores que les corresponde
function setPagination(from, size, total, topic){
		
	var html = '';
	var newFromPrev = from - 10;
	var newFromNext = from + 10;
	var strTopicParam = '';
	
	if ( topic != undefined){
		strTopicParam = ',\'' + topic + '\'';
	}
	
	if (total < size) {			
		// Hemos recibido menos de los que hemos pedido. Deshabilitamos el link de anteriores.
		html += '<li class="previous"><a href="#" class="disabled">&laquo; listas anteriores<br /><small>Ver listas antiguas</small></a></li>\
				<li class="next"><a href="javascript:getTops(' + newFromPrev + ',9' + strTopicParam + ')">listas recientes »<br /><small>Ver listas recientes</small></a></li>'
	} else if ( from != 0 ){				
		// Habilitamos los dos links porque no estamos al principio
		html += '<li class="previous"><a href="javascript:getTops(' + newFromNext + ',9' + strTopicParam + ')">&laquo; listas anteriores<br /><small>Ver listas antiguas</small></a></li>\
				<li class="next"><a href="javascript:getTops(' + newFromPrev + ',9' + strTopicParam + ')">listas recientes »<br /><small>Ver listas recientes</small></a></li>'
	} else {
		newFrom = from + 9;
		// Estamos al principio, sólo habilitamos el link de anteriores
		html += '<li class="previous"><a href="javascript:getTops(' + newFromNext + ',9' + strTopicParam + ')">&laquo; listas anteriores<br /><small>Ver listas antiguas</small></a></li>\
				<li class="next"><a href="#" class="disabled">listas recientes »<br /><small>Ver listas recientes</small></a></li>'
	}
	
	$('#tophunted_pagination').html(html);
	
}

// Función que recogerá una serie de tops comprendidos entre dos parámetros
function getTops2(from, size, topic, link){
	
	var url = '';
	
	if (topic != undefined){
		 url = "/getLastTopsByTopic/" + topic + "/" + from + "/" + size;
	} else {
		url = "/getLastTops/" + from + "/" + size;		
	}		
	
	$('#' + link).prev().addClass('disabled');
	$('#' + link).addClass('pagination-loader');
	
	$.ajax({
		type: "GET",		
		url: url,
		success: function(data){
										
			if ($(data).find('top').length > 0){				
				
				if (topic != undefined) {
					
					replaceTopicTops2(data);					
										
				} else {
					replaceTops(data);
				}
													
				setPagination2(from, size, $(data).find('top').length, topic);
				
				$.scrollTo('#tophunted-body-left-last-tops-title', 500);									
																																																							
			} else {
				// Do nothing
			}						
											
		},
		error: function(msg){
			// Do nothing									
		}
	});
	
}

// Función que sustituirá la lista de tops por la recibida por parámetro
function replaceTopicTops2(data){

	var html = '';	
	
	$(data).find('top').each(function(index){
						
		html += '<li>';
		
		if ($(this).find('sponsorName').text() != ''){
			html += '<div class="featured-logo">Patrocinado por: <strong>' + $(this).find('sponsorName').text()+ '</strong></div>';
		}
		
		html +=	'<div class="avatar">\
						<a href="/' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '">\
							<img alt="' + $(this).find('profile_title').text() + '" src="/getProfileAvatarImage?profileName=' + $(this).find('profile_url').text() + '&w=241&h=" onerror="this.src=\'/img/profile_preview_embed.gif\'"/>\
						</a>\
					</div>\
					<div class="tophunted-body-left-last-top-more"><a href="' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '">Ver Top</a></div>\
					<div class="top_title">\
					<h3>\
						<a href="/' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '" title="Ver Top">' + $(this).find('top_title').text() + '</a><br />\
					</h3>';
		
		if ( parseInt($(this).find('countUpdates').text()) > 1 ){
			html += '<p>Actualizado <span class="date" title="' + $(this).find('dt_publishedDate').text() + '">' + getAge($(this).find('dt_age').text()) + '</span></p></div>';
		} else {
			html += '<p>Creado <span class="date" title="' + $(this).find('dt_publishedDate').text() + '">' + getAge($(this).find('dt_age').text()) + '</span></p></div>';			
		}
		
		if ($(this).find('dt_age').text() == 0){
			html += '<div class="top-goodies">\
						<div class="goodies-new" title="Ficha nueva">Nuevo</div>\
					</div>';
		}
		
		html += '</li>';
	});
		
	$('#tophunted-body-left-last-tops').html(html);
		
}

// Función que mostrará los links de paginación activados y con los valores que les corresponde
function setPagination2(from, size, total, topic){
		
	var html = '';
	var newFromPrev = from - 10;
	var newFromNext = from + 10;
	var strTopicParam = '';
	
	if ( topic != undefined){
		strTopicParam = ',\'' + topic + '\'';
	}
	
	if (total < size) {			
		// Hemos recibido menos de los que hemos pedido. Deshabilitamos el link de anteriores.
		html += '<li class="previous"><a href="#" class="disabled">Tops m&aacute;s antiguos</a><span id="tophunted-pagination-span-prev"></span></li>\
				<li class="next"><a href="javascript:getTops2(' + newFromPrev + ',9' + strTopicParam + ',\'tophunted-pagination-span-next\')">Tops m&aacute;s recientes</a><span id="tophunted-pagination-span-next"></span></li>'
	} else if ( from != 0 ){				
		// Habilitamos los dos links porque no estamos al principio
		html += '<li class="previous"><a href="javascript:getTops2(' + newFromNext + ',9' + strTopicParam + ',\'tophunted-pagination-span-prev\')">Tops m&aacute;s antiguos</a><span id="tophunted-pagination-span-prev"></span></li>\
				<li class="next"><a href="javascript:getTops2(' + newFromPrev + ',9' + strTopicParam + ',\'tophunted-pagination-span-next\')">Tops m&aacute;s recientes</a><span id="tophunted-pagination-span-next"></span></li>'
	} else {
		newFrom = from + 9;
		// Estamos al principio, sólo habilitamos el link de anteriores
		html += '<li class="previous"><a href="javascript:getTops2(' + newFromNext + ',9' + strTopicParam + ',\'tophunted-pagination-span-prev\')">Tops m&aacute;s antiguos</a><span id="tophunted-pagination-span-prev"></span></li>\
				<li class="next"><a href="#" class="disabled">Tops m&aacute;s recientes</a><span id="tophunted-pagination-span-next"></span></li>'
	}
	
	$('#tophunted-pagination').html(html);
	
}

// Función que calculará la unidad de tiempo en función de los días
function getAge(days){
	
	var age = 'hoy';
	
	if (days ==1){
		age = 'ayer';
	} else if (days > 1 && days < 7){
		age = 'hace ' + days + ' días';
	} else if (days > 6 && days < 14){
		age = 'hace 1 semana';
	} else if (days > 13 && days < 30){
		age = 'hace ' + Math.floor(days/7) + ' semanas';
	} else if (days > 29 && days < 60){
		age = 'hace 1 mes';
	} else if (days > 30 && days < 365){
		age = 'hace ' + Math.floor(days/30) + ' meses';
	} else if (days > 364 && days < 730){
		age = 'hace 1 año';
	} else if (days > 729){
		age = 'hace ' + Math.floor(days/365) + ' años';
	}
	
	return age;
		
}

// Función que tratará el click sobre el botón de twitter
function tweetThisAction(text, url){

	$('#tweetbox').empty();
	
	var shortURL = url;
	
	$.ajax({
		type: "GET",
		dataType: "jsonp",
		url: "http://api.bit.ly/v3/shorten?login=sircom&apiKey=R_9a8f00c70df95ac9d32f20e2a0283a6e&uri=" + escape(url) + "&format=json",
		success: function(json){
		
			showTwitterBox(json.data.url, text);
			
		},
		error: function(msg){
			showTwitterBox(url, text);							
		}
	});
}

// Función que mostrará el text box de twitter
function showTwitterBox(url, text){
	
	$('#th_modal_bg').show();
	
	text = 'RT @tophunted ' + text;		
	var myTweet = text + " - " + url;
		
	if ( myTweet.length > 140 ){		
		myTweet = text.substr(0, 140 - url.length - 6);
		myTweet += "... - " + url;
	}		

	twttr.anywhere("1", function (twitter) {
		$('#tweetbox').removeClass('twitter_loading');
		twitter("#tweetbox").tweetBox({
			label: "Compartir en Twitter:",
			defaultContent: myTweet,
			onTweet: function (tweet, renderedTweet) {
       			closeTweetBox();
      		},
			complete: function(tb){
				$("#tweetbox iframe")[0].contentWindow.jQuery("#tweet-box").focus();
			}
		});
	});
	
	$('#tweetbox').append('<a href="javascript:closeTweetBox()">Cancel</a>');
	
	$('#tweetbox').fadeIn();
}

// Función que ocultará el text box de twitter
function closeTweetBox(){
	$('#tweetbox').fadeOut();
	$('#tweetbox').empty();
	$('#tweetbox').addClass('twitter_loading');
	$('#th_modal_bg').hide();	
}

// Función que inicializará la página de tops

function initTops(){
	
	$("#calendar").hide(); 
	
	$(".toggle-button").parent().next().hide();
	
	$(".showatfirst").removeClass("off").parent().next().show(); 

	$(".toggle-button").toggle(function(){
		$(this).toggleClass("off");
		$(this).parent().next().slideToggle("fast");		
		}, function () {
		$(this).toggleClass("off");
		$(this).parent().next().slideToggle("fast");
	});
	
	$("#socialbutton-embed").toggle(function(){
		$("#social-embed").slideToggle("fast");
		}, function(){
		$("#social-embed").slideToggle("fast"); 
		}
	);
	
	$(".time-archive a").toggle(function(){
		$("#calendar").slideToggle("fast");
		$(this).text("Ocultar Archivo del Top");
		}, function(){
		$("#calendar").slideToggle("fast"); 
		$(this).text("Ver Archivo del Top");
		}
	);
																			
	if (aUpdates.length > 0){
		
		$("#calendar").datepicker({ changeMonth: true, changeYear: true, hideIfNoPrevNext: true, beforeShowDay: setUpdateDates, onSelect: goToUpdate });				
	
		$('#calendar').append('<div id="calendar_footer_text" class="extra-text">Selecciona un día</div>');
	
		$("#calendar").datepicker( "option", "minDate", $.datepicker.parseDate( 'ddmmyy', aUpdates[aUpdates.length - 1] ) );
		$("#calendar").datepicker( "option", "maxDate", $.datepicker.parseDate( 'ddmmyy', aUpdates[0] ) );				
				
	}
	
	// Acortamos los titulares de los profiles
	
	$('#tophunted-body-left-top .top-data').each(function(){
		
	 	var elem = $(this).find('h3 > a');
				
	 	if( $(elem)[0].offsetHeight > 41 ){
		 			
			var text = $(elem).text().substr(0,70);
			
			var lastBlank = text.lastIndexOf(' ');
			
			text = text.substr(0,lastBlank);
			
			$(elem).text(text + '...');
			
	
		 }
	 });
		
};

// Función que trartará el click sobre el dia del calendario de updates
function goToUpdate(date){
	var updateDate = $.datepicker.parseDate( 'dd/mm/yy', date );
	window.location = "/" + myTopic + "/" + myTop + "/" + $.datepicker.formatDate('ddmmyy', updateDate );	
}

// Función que marcará los updates disponibles en el calendario
function setUpdateDates(date){	
	
	for (i = 0; i < aUpdates.length; i++) {
		if ( aUpdates[i] == $.datepicker.formatDate('ddmmyy', date ) ){
			if (myUpdateDate == '' && i == 0){				
				return [true,'current-day', 'Update disponible'];
			} else if (myUpdateDate == $.datepicker.formatDate('ddmmyy', date )){				
				return [true,'current-day', 'Update disponible'];
			} else {
				return [true,'update-day', 'Update disponible'];
			}			
		}		
	}
	
	return [false,'', 'Sin updates'];
}

// Función para paginar los profiles de un Top desde la página de profiles
function showTopProfiles(page){
	
	var pages = $('#top-current > ul').length;
	
	$('#top-current > ul').hide();
	
	$('#profiles_page_' + page).show();
		
	var html = '<ul class="tophunted-pagination group">';
	
	if ( page == 0){
		html += '<li class="previous"><a title="profile_title_prev" class="disabled">Anteriores</a></li>\
				 <li class="next"><a href="javascript:showTopProfiles(1)" title="profile_title_next">Siguientes: <strong>11-' + parseInt( 10 + $('#profiles_page_1 > li').length) + '</strong></a></li>';
	} else if ( page > 0 && page < parseInt(pages - 1) ){
		html += '<li class="previous"><a href="javascript:showTopProfiles(' + parseInt(page - 1) + ')" title="profile_title_prev">Anteriores: <strong>' + parseInt((page - 1) * 10 + 1) + '-' + parseInt(page * 10) + '</strong></a></li>\
				 <li class="next"><a href="javascript:showTopProfiles(' + parseInt(page + 1) + ')" title="profile_title_next">Siguientes: <strong>' + parseInt( (page + 1) * 10 + 1) + '-' + parseInt( ( (page + 1) * 10) + $('#profiles_page_' + parseInt(page + 1) + '> li').length)  + '</strong></a></li>';
	} else {
		html += '<li class="previous"><a href="javascript:showTopProfiles(' + parseInt(page - 1) + ')" title="profile_title_prev">Anteriores: <strong>' + parseInt((page - 1) * 10 + 1) + '-' + parseInt(page * 10) + '</strong></a></li>\
				 <li class="next"><a title="profile_title_next" class="disabled">Siguientes</a></li>';
	}
						
	html += '</ul>';
	
	$('#top-navigation').html(html);
}

// Función que recogerá una serie de tops comprendidos entre dos parámetros para la Home
function getHomeTops(from, size, link){
			
	$('#' + link).prev().addClass('disabled');
	$('#' + link).addClass('pagination-loader');
	
	$.ajax({
		type: "GET",		
		url: "/getLastTops/" + from + "/" + size,
		success: function(data){
										
			if ($(data).find('top').length > 0){				
				
				replaceHomeTops(data);
													
				setTopsHomePagination(from, size, $(data).find('top').length);															
																																																							
			} else {
				// Do nothing
			}						
											
		},
		error: function(msg){
			// Do nothing									
		}
	});
	
}

// Función que sustituirá la lista de tops por la recibida por parámetro en la Home
function replaceHomeTops(data){

	var html = '';	
	
	$(data).find('top').each(function(index){
						
		if ( index == 0) {
			html += '<li class="first">';
		} else {
			html += '<li>';
		}
		
		if ($(this).find('sponsorName').text() != ''){
			html += '<div class="featured-logo">Patrocinado por: <strong>' + $(this).find('sponsorName').text()+ '</strong></div>';
		}
		
		html +=	'<div class="avatar">\
						<a href="/' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '">\
							<img alt="' + $(this).find('profile_title').text() + '" src="/getProfileAvatarImage?profileName=' + $(this).find('profile_url').text() + '&w=241&h=" onerror="this.src=\'/img/profile_preview_embed.gif\'"/>\
						</a>\
					</div>\
					<div class="tophunted-body-left-last-top-more"><a href="' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '">Ver Top</a></div>\
					<div class="top_title">\
					<h3>\
						<a href="/' + $(this).find('topic_url').text() + '/' + $(this).find('top_urlname').text() + '" title="Ver Top">' + $(this).find('top_title').text() + '</a><br />\
					</h3>';
		
		if ( parseInt($(this).find('countUpdates').text()) > 1 ){
			html += '<p>Actualizado <span class="date" title="' + $(this).find('dt_publishedDate').text() + '">' + getAge($(this).find('dt_age').text()) + '</span></p></div>';
		} else {
			html += '<p>Creado <span class="date" title="' + $(this).find('dt_publishedDate').text() + '">' + getAge($(this).find('dt_age').text()) + '</span></p></div>';			
		}
		
		if ($(this).find('dt_age').text() == 0){
			html += '<div class="top-goodies">\
						<div class="goodies-new" title="Ficha nueva">Nuevo</div>\
					</div>';
		}
		
		html += '</li>';
	});
		
	$('#tophunted-body-left-last-tops').html(html);
		
}

// Función que mostrará los links de paginación activados y con los valores que les corresponde en la Home
function setTopsHomePagination(from, size, total){
		
	var html = '';
	var newFromPrev = from - 4;
	var newFromNext = from + 4;	
	
	if (total < size) {			
		// Hemos recibido menos de los que hemos pedido. Deshabilitamos el link de anteriores.
		html += '<li class="previous"><a href="#" class="disabled">Tops m&aacute;s antiguos</a><span id="tophunted-pagination-span-prev"></span></li>\
				<li class="next"><a href="javascript:getHomeTops(' + newFromPrev + ',4,\'tophunted-pagination-span-next\')">Tops m&aacute;s recientes</a><span id="tophunted-pagination-span-next"></span></li>'
	} else if ( from != 1 ){				
		// Habilitamos los dos links porque no estamos al principio
		html += '<li class="previous"><a href="javascript:getHomeTops(' + newFromNext + ',4,\'tophunted-pagination-span-prev\')">Tops m&aacute;s antiguos</a><span id="tophunted-pagination-span-prev"></span></li>\
				<li class="next"><a href="javascript:getHomeTops(' + newFromPrev + ',4,\'tophunted-pagination-span-next\')">Tops m&aacute;s recientes</a><span id="tophunted-pagination-span-next"></span></li>'
	} else {		
		// Estamos al principio, sólo habilitamos el link de anteriores
		html += '<li class="previous"><a href="javascript:getHomeTops(' + newFromNext + ',4,\'tophunted-pagination-span-prev\')">Tops m&aacute;s antiguos</a><span id="tophunted-pagination-span-prev"></span></li>\
				<li class="next"><a href="#" class="disabled">Tops m&aacute;s recientes</a><span id="tophunted-pagination-span-next"></span></li>'
	}
	
	$('#tops_pagination').html(html);
	
}

// Función para cerrar la ventana modal de búsqueda
function closeSearch(){
	$('#th_modal_bg_google').hide();
	$('#gresults').hide();	
}

// Función que inicializará el objeto de búsqueda de Google en la ventana modal
function showWindow(searchControl, searcher){
	
	$('#gresults_null').remove();
	if ( searcher.results.length == 0 ){			
		$('#gresults_page').append('<div id="gresults_null">No hay resultados</div>');
	}					
		
	$('#gresults').show();
	$('#th_modal_bg_google').show();
	$('#gresults_page').show();
	
	var siteSearch = new google.search.WebSearch();		
	siteSearch.setSiteRestriction('012395834233795022848:y3wujdd94um');
	
	var options = new google.search.SearcherOptions();				
	options.setRoot(document.getElementById("gresults_window"));
	
	var drawOptions = new google.search.DrawOptions();
	drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
	
	var searchControlWindow = new google.search.SearchControl();
	searchControlWindow.addSearcher(siteSearch, options);
	searchControlWindow.draw(document.getElementById("gresults_input"), drawOptions);
					
	searchControlWindow.setLinkTarget(google.search.Search.LINK_TARGET_TOP);				
	searchControlWindow.setSearchCompleteCallback(this, function(searchControl, searcher){
		$('#gresults_page').hide();
		$('#gresults_null').remove();
		if ( searcher.results.length == 0 ){			
			$('#gresults_window').append('<div id="gresults_null">No hay resultados</div>');
		}
	});
	
	$('#gresults_input input:first').val(searchControl.Rc);	
	
}

// Función que inicializará el objeto de búsqueda de Google en la página
function OnLoadGoogleSearch() {
													
	var siteSearch = new google.search.WebSearch();		
	siteSearch.setSiteRestriction('012395834233795022848:y3wujdd94um');
	
	var options = new google.search.SearcherOptions();				
	options.setRoot(document.getElementById("gresults_page"));
	
	var drawOptions = new google.search.DrawOptions();
	drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
	
	var searchControlPage = new google.search.SearchControl();
																																															
	searchControlPage.addSearcher(siteSearch, options);																											
	searchControlPage.draw(document.getElementById("cse"), drawOptions);
	searchControlPage.setLinkTarget(google.search.Search.LINK_TARGET_TOP);
	searchControlPage.setSearchCompleteCallback(this,showWindow);
											

}

