gtto = null;
tweets = [];

function tweetToHtml(tweet) {
	html = '<li class="tweet';
	for (var i in tweet.annotations) {
		html += ' a_' + tweet.annotations[i].name
	}
	html += '" id="tweet_' + tweet.id + '">';
	a_user = '<a href="http://twitter.com/"' + tweet.user.screen_name + ' target="_blank">';
	if (tweet.user.profile_image_url) {
		html += a_user + '<img class="tweet_profile_image" src="' + tweet.user.profile_image_url + '" /></a>';
	}
	html += '<h4>' + a_user + '@' + tweet.user.screen_name + '</a></h4><p class="tweet_created_at">' + tweet.created_at + '</p><p>';
	lastend = 0;
	txt = '';
	tweet.entities.sort(function(a, b) { return a.indice_start - b.indice_start });
	for (var i in tweet.entities) {
		txt += tweet.text.substring(lastend, tweet.entities[i].indice_start);
		lastend = tweet.entities[i].indice_end;
		switch(tweet.entities[i].type) {
			case "entity_hashtag":
				txt += '<a href="http://twitter.com/search?q=%23' + tweet.entities[i].entity.text + '" target="_blank">#' + tweet.entities[i].entity.text + '</a>';
				break;
			case "entity_user":
				txt += '<a href="http://twitter.com/' + tweet.entities[i].entity.screen_name + '" target="_blank">@' + tweet.entities[i].entity.screen_name + '</a>';
				break;
			case "entity_url":
			case "entity_media":
				txt += '<a href="' + tweet.entities[i].entity.expanded_url + '" target="_blank">' + tweet.entities[i].entity.expanded_url + '</a>';
				break;
		}
	}
	txt += tweet.text.substring(lastend);
	html += txt + '</p></li>';
	return html;
}

function scheduleTweets() {
	var tl = $("#tweetlist"), tc = $("#tweetcontainer");
	if (tweets.length != tl.children().length) {
		console.log("Tweet count error");
	}
	if (tweets.length) {
		while (tl.height() - (tc.scrollTop() + tc.height()) > 1000) {
			tl.children().last().detach();
			tweets.pop();
		}
		if (tl.height() - (tc.scrollTop() + tc.height()) < 120) {
			getTweets({
				before_id : tweets[tweets.length - 1].id,
				limit : 5
			});
		}
		getTweets({
			after_id : tweets[0].id
		});
	} else {
		getTweets({
			limit: 15
		});
	}
}

function getTweets(params) {
	$.getJSON("http://" + document.location.hostname + ":8888/?callback=?", params, function(data, a, b) {
		if (data.tweets && data.tweets.length) {
			var tl = $("#tweetlist"), tc = $("#tweetcontainer");
			html = '';
			for (var i in data.tweets) {
				html += tweetToHtml(data.tweets[i]);
			}
			if (params.before_id) {
				tl.append(html);
				tweets = tweets.concat(data.tweets);
			} else {
				var pos = tc.scrollTop(), fixScroll = (pos > 80);
				pos -= tl.height();
				tl.prepend(html);
				tweets = data.tweets.concat(tweets);
				if (fixScroll) {
					tc.scrollTop(tl.height() + pos);
				}
			}
		}
	});
}

$(document).ready(function() {
	gtto = setInterval(scheduleTweets, 1500);
});