var socket,
    tweets = [],
    waitoldtweets = true,
    tl,
    tc;

function tweetToHtml(tweet) {
	html = '<li class="tweet';
	for (var i in tweet.annotations) {
		html += ' a_' + tweet.annotations[i]
	}
	html += '" id="tweet_' + tweet.id + '">';
	a_user = '<a href="http://twitter.com/' + tweet.user.screen_name + '" target="_blank" title="' + tweet.user.name + '">';
	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 = '';
	entities = [];
	for (var i in tweet.entities.hashtag) {
	    entities.push({
	        "start" : tweet.entities.hashtag[i].indices[0],
	        "end" : tweet.entities.hashtag[i].indices[1],
	        "html" : '<a href="http://twitter.com/search?q=%23' + tweet.entities.hashtag[i].text + '" target="_blank">#' + tweet.entities.hashtag[i].text + '</a>'
	    });
	}
	for (var i in tweet.entities.urls) {
	    entities.push({
	        "start" : tweet.entities.urls[i].indices[0],
	        "end" : tweet.entities.urls[i].indices[1],
	        "html" : '<a href="' + tweet.entities.urls[i].expanded_url + '" target="_blank">' + tweet.entities.urls[i].display_url + '</a>'
	    });
	}
	for (var i in tweet.entities.user_mentions) {
	    entities.push({
	        "start" : tweet.entities.user_mentions[i].indices[0],
	        "end" : tweet.entities.user_mentions[i].indices[1],
	        "html" : '<a href="http://twitter.com/' + tweet.entities.user_mentions[i].screen_name + '" target="_blank" title="' + tweet.entities.user_mentions[i].name + '">@' + tweet.entities.user_mentions[i].screen_name + '</a>'
	    });
	}
 	entities.sort(function(a, b) { return a.start - b.start });
    for (var i in entities) {
 		txt += tweet.text.substring(lastend, entities[i].start) + entities[i].html;
        lastend = entities[i].end;
    }
	txt += tweet.text.substring(lastend);
	html += txt + '</p></li>';
	return html;
}

function discardTweets() {
    if (tweets.length) {
        while (tl.height() - (tc.scrollTop() + tc.height()) > 1000) {
 	        tl.children().last().detach();
            tweets.pop();
        }
    }
}

// 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() {
    tl = $("#tweetlist");
    tc = $("#tweetcontainer");
    socket = io.connect('http://' + S_IO_HOST + ':' + S_IO_PORT );
    socket.on('tweets', function (data) {
        tweets = data;
        data.reverse();
        html = '';
        for (var i in data) {
            html += tweetToHtml(data[i]);
        }
        $("#tweetlist").html(html);
        discardTweets();
    });
    socket.on('oldtweets', function (data) {
        tweets = tweets.concat(data);
        html = '';
        for (var i = data.length - 1; i >= 0; i--) {
            html += tweetToHtml(data[i]);
        }
        $("#tweetlist").append(html);
        discardTweets();
        waitoldtweets = true;
    });
    socket.on('newtweet', function (data) {
        tweets.splice(0,0,data);
        html = tweetToHtml(data);
        var scrollpos = tc.scrollTop(),
            fixScroll = (scrollpos > 80);
        scrollpos -= tl.height();
        $("#tweetlist").prepend(html);
        if (fixScroll) {
    		tc.scrollTop(tl.height() + scrollpos);
		}
        discardTweets();
    });
    $("#tweetcontainer").scroll(function() {
        if ( waitoldtweets && tl.height() - (tc.scrollTop() + tc.height()) < 120 ) {
            socket.emit('tweetsbefore', tweets[tweets.length-1].id );
            waitoldtweets = false;
        }
    });
});