window.last_id = 0;
window.tweetstack = new Array();
window.currPageTweetCount = 0;
window.settings = {perPageCount: 3};
window.secs = {minute: 60, hour: 3600, day: 86400, week: 604800};
window.currPage = 1;

$(document).ready(function(){
	displayLivePage();
	//window.setTimeout(function(a,b){clearInterval(updateEvent);},100000);
	$('#livepage').click(function(){
		displayLivePage();
		return false;
	});
	$('#alltweets').click(function(){
		if (window.updateEvent != null) {
			clearInterval(updateEvent);
			window.updateEvent = null;
		}
		window.currPage = 1;
		displayTweetPage(window.currPage);
		generatePagination();
		return false;
	});
})

function displayLivePage(){
	window.updateEvent = window.setInterval(fetchNewTweets,15000);
	$('#paginate').empty();
	displayTweetPage(1);
}

function generatePagination(){
	var html ='';
	if (window.currPage > 1) {
		html += '<a href="" id="prevpage">Previous</a>';
	}
	html += '<a href="" id="nextpage">Next</a>';
	$('#paginate').html(html);
	
	$('#prevpage').click(function(){
		window.currPage -= 1;
		displayTweetPage(window.currPage);
		generatePagination();
		return false;
	})
	$('#nextpage').click(function(){
		window.currPage += 1;
		displayTweetPage(window.currPage);
		generatePagination();
		return false;		
	})
}

function displayTweetPage(numPage){
	var url = 'http://search.twitter.com/search.json?result_type=recent&q=sustnble&rpp=3&page='+numPage;
	$('#tweets').empty();
	window.currPageTweetCount = 0;
	fetchTwitterJSON(url);
}

function fetchNewTweets(){
	var url = 'http://search.twitter.com/search.json?result_type=recent&q=sustnble&rpp=3';
	if(window.last_id > 0){
		url += '&since_id='+window.last_id;
	}
	fetchTwitterJSON(url);
}

function fetchTwitterJSON(url){
	url += '&callback=?';
	$.getJSON(url,function(data){
		window.last_id = data.max_id;
		// process and dispaly JSON data
		for(i=data.results.length-1; i >= 0 ;i--){
			tweet = data.results[i];
			window.tweetstack[tweet.id] = tweet;
			generateAgoTimestamp(tweet.id);
			updateLivePage(tweet,i);
		}
		updateAgoStamps();
		if(window.currPageTweetCount != window.settings['perPageCount']){
			$('#nextpage').remove();
		}
		
	});	
}

function updateAgoStamps(){
	$('.tweet-agoStamp').each(function(){
		id = $(this).attr('id');
		generateAgoTimestamp(id);
		$(this).text(' '+window.tweetstack[id].agoStamp);
	});
}

function generateAgoTimestamp(id){
	tweet = window.tweetstack[id];
	// First get the current milliseconds
	var elapsed = ((new Date()).getTime() - Date.parse(tweet.created_at))/1000;
	if(elapsed < 60){
		tweet.agoStamp = 'just a moment ago';
		return;
	}
	// convert to required format
	if(elapsed > window.secs['week']){
		n1 = 'week';n2 = 'day';
	}
	else if(elapsed > window.secs['day']){
		n1 = 'day';n2 = 'hour';
	}
	else if(elapsed > window.secs['hour']){
		n1 = 'hour';n2 = 'minute';
	}
	else if(elapsed > window.secs['minute']){
		n1 = 'minute';n2 = 'sec';
	}
	var u1 = window.secs[n1]; var u2 = window.secs[n2];
	count1 = (elapsed - elapsed%u1)/u1;
	count2 = Math.ceil((elapsed%u1)/u2);
	agoStamp = count1 + ' '+n1;
	if(count1 > 1){
		agoStamp += 's';
	}
	if (n2 != 'sec') {
		agoStamp += ', ' + count2 + ' ' + n2;
		if (count2 > 1) {
			agoStamp += 's';
		}
	}
	agoStamp += ' ago';
	tweet.agoStamp = agoStamp;
}

function updateLivePage(tweet,i){
	// If greater than page length, throw out one from other end
	if(window.currPageTweetCount == window.settings['perPageCount']){
		$('.tweet-item:last').remove();
		window.currPageTweetCount -= 1;
	}
	// Add new tweet
	html = '<li class="tweet-item">';
	html += '<span class="profile-image-span"><img class="profile-image" alt="profile picture" src="'+tweet.profile_image_url+'"/></span>';
	html += '<div class="tweet-text">'+tweet.text.linkify().linkuser()+'</div>';
	html += '<div class="tweet-info">By '+('@'+tweet.from_user).linkuser();
	html += '<span class="tweet-agoStamp" id="'+tweet.id+'"> '+tweet.agoStamp+'</span>';
	html += '</div><div style="clear:both;"></div></li>';
	tweetObj = $(html).prependTo('#tweets');
	if(i == 0 && window.updateEvent != null){
		$('.last-tweet').removeClass("last-tweet");
		tweetObj.addClass('last-tweet').show("normal").animate({marginBottom: "-=30px"},500,"easeOutBounce");
	}
	window.currPageTweetCount += 1;
}

function paginateTweets(){
	window.numPages = (window.length - (window.length % 20))/20 + 1;
}

String.prototype.linktag = function () 
{
  return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) 
  {
    var tag = t.replace("#","%23");
    m = t.link("http://search.twitter.com/search?q="+tag);
    m = m.replace('href="','target="_blank" href="');
    return m;
  });
};

String.prototype.linkuser = function() 
{
  return this.replace(/[@][A-Za-z0-9-_]+/g, function(user) 
  {
    var user = user.replace("@","");
    u = user.link("http://twitter.com/"+user);
    u = u.replace('href="','target="_blank" href="');
    return '@'+u;
  });
};

String.prototype.linkify = function() 
{
 return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(m) 
  {
  	m = m.link(m);
  	m = m.replace('href="','target="_blank" href="');
  	return m;
  });
};