/*
* Author:      Marco Kuiper (http://www.marcofolio.net/)
*/

$(document).ready(function()
{
	var pageSize = 4;
	//~ var username = 'Rosebrandtnl';
	var currentPage = 1;
	var elementId = 'tweets';
	var username = $('#'+elementId).attr('rel');
	if(username!==""){;
		
		// Appends the new tweet to the UI
		var appendTweet = function(tweet, id) {
			$("<p />")
				.html('<span>'+ tweet +'</span>')
				.prepend('<div class="TweetTop"></div>')
				.append('</span><div class="TweetBottom"></div>')
			.appendTo($("#"+elementId));
		};
		
		// Loads the next tweets
		var loadTweets = function() {
			var url = "http://twitter.com/status/user_timeline/"
					+ username + ".json?count="+pageSize+"&page="+currentPage+"&callback=?";
					
			$.getJSON(url,function(data) {
				$.each(data, function(i, post) {
					appendTweet(post.text, post.id);
				});
				
				// We're done loading the tweets, so hide the overlay and update the UI
				$("#overlay").fadeOut();
				
				$('#'+elementId+'>p:odd').addClass('TweetOdd');
				$('#'+elementId+'>p:even').addClass('TweetEven');
			});
		};
		
		// First time, directly load the tweets
		loadTweets();
		
		// Append a scroll event handler to the container
		$("#"+elementId).scroll(function() {
			// We check if we're at the bottom of the scrollcontainer
			if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) {
				// If we're at the bottom, show the overlay and retrieve the next page
				currentPage++;
				if(currentPage > 10) {
					alert("Om meer berichten te zien kun je naar onze twitter pagina gaan.");
					return false;
				}
				$("#overlay").fadeIn();
				loadTweets();
			}
		});
	}
});
