$(function()
{
	sr = new SRTwitterFeed();
});

function SRTwitterFeed()
{
    var path = 'http://twitter.com/statuses/user_timeline/smithandrobot.json';
	var element = $('#twitter');
	var filters = ['blog:', 'blog'];
	
    init();

    function init()
    {	
        var aObj             = {};
		aObj.url 			 = path;
		aObj.cache 			 = true;
        aObj.data            = {count:10}
		aObj.dataType 		 = 'jsonp';
		aObj.success 		 = onStreamLoaded;
		aObj.error 			 = onStreamError;
		
		element.html( getHTML('Loading Tweets...') );
		
 		$.ajax(aObj);
    }


    function onStreamLoaded( d )
    {
		var html, text;
		
		for(var i=0; i<= d.length-1; i++)
		{
			text = d[i].text;
			if(isAllowed( text )) 
			{
				html = getHTML( Util.linkify( d[i].text) ) ;
				break;
			}
		}
		
		element.html(html);
    }

    function onStreamError( d )
    {
		element.html( getHTML( 'Oh no! We couldn\'t talk to Twitter.') );
    }

	function getHTML( v )
	{
		html =	'<span>'+v+'</span>'+
				'<p><a href="http://www.twitter.com/smithandrobot">Visit our Twitter profile.</a></p>';
		return html;
	}
	
	
	function isAllowed( t )
	{
		var i;
		// if it's an @ reply
		if(t.split('')[0] === '@') return false;
		
		for(i in filters)
		{
			if( t.toLowerCase().indexOf( filters[i]) !== -1 ) return false;
		}
		
		return true;
	}

}

Util = {
	toString : function (){ return 'Utils Static class'; },
	linkify : function (text) 
	{
	    text = text.replace(/(https?:\/\/\S+)/gi, function (s) {
	        return '<a href="' + s + '" target="_blank">' + s + '</a>';
	    });
	
	    // text = text.replace(/(^|)@(\w+)/gi, function (s) {
	    //     return '<a href="http://twitter.com/' + s + '">' + s + '</a>';
	    // });
	    // 	
	    // text = text.replace(/(^|)#(\w+)/gi, function (s) {
	    //     return '<a href="http://search.twitter.com/search?q=' + s.replace(/#/,'%23') + '">' + s + '</a>';
	    // });
	    return text;
	},
	log : function( v )
	{
		try 
		{
			console.log( v);
		}catch( e ){
			// no console
		}
	}
}
