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

$(document).ready(function()
{
	/**
	* Set the size for each page to load
	*/
	var pageSize = 5;
	
	/**
	* Username to load the timeline from
	*/
	var username = 'replaygamesinc';
	
	/**
	* Variable for the current page
	*/
	var currentTweet = 1;
	var currentPage = 1;
	var tweetCount = 0;
	
	// Appends the new tweet to the UI
	var appendTweet = function(tweet, id, time,source) {
		tweetCount++;

		tweetTime = time.split(' ');

		$("<p />")
			.attr('id','tweet-'+tweetCount)
			.attr('class','tweet')
			.html(tweet.replace(/(http\S+)/gi, "<a href='$1'>$1</a>"))
			.append($("<a />")
					.attr("href", "http://twitter.com/" + username + "/status/" + id)
					.attr("title", "Go to Twitter status")
					.attr('class','tweet-time')
					.append('<br /><span>'+tweetTime[1]+' '+tweetTime[2]+', '+tweetTime[5]+'</span>')
			)
			.append('<span class="tweet-source"> via '+source+'</span>')
		.appendTo($("#tweets"));
	};
	
	// 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, post.created_at, post.source);
				//console.log(post);
			});
			
			$('#tweets p').not('#tweet-'+currentTweet).hide();
			
		});
		
	};
	
	// First time, directly load the tweets
	loadTweets();
	
	
	$('#next-tweet').click(function(e){
		e.preventDefault();
		if(currentTweet == 1){
			return false;
		}
		$('#tweet-'+currentTweet).hide();
		currentTweet--;
		$('#tweet-'+currentTweet).show();
	});
	$('#prev-tweet').click(function(e){
		e.preventDefault();
		$('#tweet-'+currentTweet).hide();
		currentTweet++;
		$('#tweet-'+currentTweet).show();
		if(currentTweet+1 == tweetCount){
			// we're at the last tweet, so load some more
			currentPage++;
			loadTweets();
		}
	});
	// Append a scroll event handler to the container
	// $("#tweets").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('We should not spam the Twitter API with calls. I hope you get the idea!');
	// 			return false;
	// 		}
			
	// 		$("#overlay").fadeIn();
	// 		loadTweets();
	// 	}
	// });
	
});
