// TWITTERRRRRR

jQuery.fn.reverse = Array.prototype.reverse;
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; }); };


window.feedStack = [];
window.entryCount = 0;
window.feedTimer = 0;

var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );

$(document).ready(
	function() {
		initFeeds();
	}
);

initFeeds = function() {
	$("#twitter-feed").empty();
	window.lastFeedId = 0;
	window.feedStack = [];
	getFeed();
	//setTimeout('showEntries()',1000);
}

getFeed = function() {
	if( window.feedStack.length > 10 ) {
		setTimeout( "getFeed()", 120000 );
		return (false);
	}
	var since = window.lastFeedId;
	var sinceurl = "&since_id=";
	var cnt = 20;
	if( since > 0 ) {
		sinceurl += since;
		cnt = 99;
	}
	var url = 'http://search.twitter.com/search.json?callback=?&q=from%3Aovibynokia+from%3AWOMWorldNokia+from%3Anokconv&lang=all&ref='+ sinceurl + '&until=&rpp='+cnt;
	$.getJSON(url,
		function(data){
			if( data ) {
				data.results.reverse();
				$.each(data.results, function(i, item) {
					window.feedStack.push( item );
					window.lastFeedId = item.id;
				});
				showEntries()
			}
		}
	);
	setTimeout( "getFeed()", 60000 );
}

showSingleEntry = function(entry) {
	$("#feed-list li:gt(1)").each( function() { $(this).remove() } );
	$("#feed-list li:eq(0)").each( function() { $(this).animate({ opacity: .75 }) } );
	$("#feed-list li:eq(1)").each( function() { $(this).animate({ opacity: .5 }) } );
	var thedate = new Date(Date.parse(entry.created_at));
	var daystr = thedate.getDate();
	var monthstr = thedate.getMonth()+1;
	var yearstr = thedate.getFullYear();
	var hourstr = thedate.getHours();
	var minustr = new String(thedate.getMinutes());
	if(minustr.length<=1)
		minustr = '0'+minustr;
	var thedatestr = daystr + "." + monthstr + "." + yearstr + " " + hourstr+':'+minustr;
	var thedatestr = months[thedate.getMonth()] + " " + daystr + ", " + yearstr + " " + hourstr + ":" + minustr;
	var user = entry.from_user;
	var text = entry.text.linkify();
	li_str = '<li id="th'+entry.id+'"><p>'+text+'</p><p class="smaller">'+user+' '+ thedatestr +'</p></li>';
	window.entryCount++;
	window.lastFeedId=entry.id;
	$("#twitter-feed").prepend( li_str );
	$("#th"+entry.id).hide().fadeIn(1000);
	$("#twitter-feed li:eq(3)").remove();
}

function showEntries() {
	if( window.feedStack.length > 0 ) {
		var currentEntry = window.feedStack.shift();
		showSingleEntry( currentEntry );
		
	}
	var timeout = 5000;
	clearTimeout(window.feedTimer);
	window.feedTimer = setTimeout('showEntries()',timeout);
}
