(function(app, $) { 'use strict';
var namespace = 'talkers',
tooltip_class = '.talkers-tooltip',
COUNT_TALKERS = 32,
WAIT_CLASS = 'wait',
api;
var tpl = '
' + '\n';
tpl += ' ';
tpl += '';
function convertURLs(tweet) {
var regex = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z0-9+&@#\/%=~_|])/ig;
return tweet.replace(regex, '$1');
}
function generateUserLinks(tweet) {
var regex = /([@])([\w]+)/ig;
return tweet.replace(regex, '$1$2');
}
function generateSearchLinks(tweet) {
var regex = /([#])([\w]+)/ig;
return tweet.replace(regex, '$1$2');
}
function linkifyText(text) {
return generateSearchLinks(generateUserLinks(convertURLs(text)));
}
function getNumTalkers($dom) {
var wRow = $dom.parent().width(),
wItem = $dom.find('li:last').outerWidth(true),
EMPTY_SPACES = 3,
num = Math.floor(wRow / wItem) * 2 - EMPTY_SPACES;
return num;
}
function processTweets(data, $dom, $more) {
if (!data || !data.results || !data.results.length) {
return;
}
if (data.error) {
console.error(data.error);
return;
}
var results = data.results.slice(0, getNumTalkers($dom));
$dom.show();
$.each(results, function(i, tweet) {
var s = tpl.replace('{avatar}', tweet.profile_image_url, 'g')
.replace('{user}', tweet.from_user, 'g')
.replace('{user_name}', tweet.from_user_name, 'g')
.replace('{text}', linkifyText(tweet.text), 'g');
$more.before(s);
});
$(tooltip_class).tooltip();
}
function errorLoading(err) {
app.log('getTweets error', err);
}
function getSearchUrl(url, $dom) {
var search_url = 'http://search.twitter.com/search.json?';
search_url += 'q=' + url + ' -bahiadigital';
var page = $dom.data('page') || 1;
if (page > 1) {
search_url += '&page=' + (parseInt(page, 10));
}
$dom.data('page', page + 1);
search_url += '&rpp=' + COUNT_TALKERS;
return search_url + '&callback=?';
}
function getTweets(url, $dom, $more) {
var search_url = getSearchUrl(url, $dom);
$dom.addClass(WAIT_CLASS);
$.ajax({
url: search_url,
dataType: 'jsonp',
success: function(data) {
$dom.removeClass(WAIT_CLASS);
processTweets(data, $dom, $more);
},
error: function(err) {
$dom.removeClass(WAIT_CLASS);
errorLoading(err);
}
});
}
function resolve_url(dom) {
var url = dom.data('href');
if (url === undefined) {
if (app.environment.debug === true) {
url = 'www.infobae.com';
} else {
url = window.location.href;
}
}
return url;
}
function setupTalkers(domSel) {
var $dom = $(domSel);
if (! $dom.length) {
return;
}
var tlk = $dom.data('talkers-first');
if (tlk != undefined) {
COUNT_TALKERS = tlk;
}
var $more = $dom.find('[data-more-talkers]');
var url = encodeURIComponent(resolve_url($dom));
getTweets(url, $dom, $more);
$more.on('click', function(e) {
e.preventDefault();
getTweets(url, $dom, $more);
});
}
app.on(namespace + '.show', setupTalkers);
app.on(namespace + '.more', getTweets);
api = {};
app.register(namespace, api);
}(infobae, window.jQuery));