/**
 *
 * Últimas do Twitter
 *
 **/
var	tags = '@mb_marketing';
var	since_id = null;
var	tweets_per_page = 3;


jQuery( function( $ )
{

	/**
	 *
	 * Cria a área do Twitter na index
	 *
	 **/
	$( 'div#info-about' ).append( '<div id="tweets" />' );



	/**
	 *
	 * Cria a área na qual os Tweets serão carregados
	 *
	 **/
	$( 'div#tweets' ).append( '<ul />' );



	/**
	 *
	 * Cria a área na qual os Tweets serão carregados
	 *
	 **/
	$( 'div#tweets' ).append( '<a href="http://twitter.com/mb_marketing" class="follow" target="_blank">Siga-nos!</a>' );



	/**
	 *
	 * Inicia o carregamento dos Tweets
	 *
	 **/
	startLoadingTweets( );
	

});



/**
 *
 * Carrega os Tweets
 *
 * @return void
 *
 **/
function startLoadingTweets( )
{


	/**
	 *
	 * Executa a verificação se há novos Tweets ao carregar a página
	 *
	 **/
	getMoreTweets( );



	/**
	 *
	 * Efetua a verificação de acordo com o tempo estipulado ( 60 segundos = 60000 milissegundos )
	 *
	 **/
	var	update = setInterval( 'getMoreTweets( );', 60000 );

}



/**
 *
 * Verifica se há novos Tweets via Ajax
 *
 * @return void
 *
 **/
function getMoreTweets( )
{

	/**
	 *
	 * Processa a consulta retornando os dados em formato JSON
	 *
	 **/
	$.get( 'http://search.twitter.com/search.json',
	{
		q			: tags,
		rpp			: tweets_per_page,
		since_id	: since_id
	},
	processTweets,
	'jsonp' );
}



/**
 *
 * Processa o resultado da consulta via Ajax
 *
 * @param tweets: Novos Tweets encontrados
 * @return void
 *
 **/
function processTweets( tweets )
{

	/**
	 *
	 * Se Tweets foram retornados...
	 *
	 **/
	if( tweets.results.length )
	{

		/**
		 *
		 * Percorre cada Tweet retornado
		 *
		 **/
		for( i = ( tweets.results.length - 1 ); i >= 0; i-- )
		{

			/**
			 *
			 * Verifica se o Tweet já foi adicionado ou não
			 *
			 **/
			if( $( 'li#tweet-' + tweets.results[ i ].id ).length === 0 )
			{

				/**
				 *
				 * Identifica quantos Tweets existem na lista. Se a lista já estiver cheia, remove o último Tweet
				 *
				 **/
				if( $( 'li.tweet' ).length === tweets_per_page )
				{
					$( 'li.tweet:last-child' ).remove( );
				}



				/**
				 *
				 * Adiciona o Tweet
				 *
				 **/
				addTweet( tweets.results[ i ] );

			}

		}

	}

}



/**
 *
 * Adiciona um nvo Tweet à lista de Tweets existentes
 *
 * @param tweet: Informações do Tweet que será criado ( id, user, text, etc. )
 * @return void
 *
 **/
function addTweet( tweet )
{

	/**
	 *
	 * Constrói um novo Tweet e instancia um objeto para manipulá-lo
	 *
	 **/
	var	tweet_element = buildTweetElement( tweet );



	/**
	 *
	 * Adiciona o Tweet à lista de Tweets exibidos
	 *
	 **/
	$( 'div#tweets ul' ).prepend( tweet_element );



	/**
	 *
	 * Exibe o Tweet adicionado
	 *
	 **/
	tweet_element.fadeIn( 'fast' );

}



/**
 *
 * Constrói um novo Tweet
 *
 * @param tweet: Informações do Tweet que será criado ( id, user, text, etc. )
 * @return jQuery
 *
 **/
function buildTweetElement( tweet )
{

	/**
	 *
	 * Instancia um novo Tweet
	 *
	 **/
	var	tweet_element = $( '<li class="tweet" id="tweet-' + tweet.id + '" />' );



	/**
	 *
	 * Nome do usuário ( link para a página do usuário no site do Twitter )
	 *
	 **/
	var	the_user_link = '<a href="http://twitter.com/' + tweet.from_user + '" class="user" target="_blank">' + tweet.from_user + '</a>';



	/**
	 *
	 * Texto do Tweet
	 *
	 **/
	var	tweet_text = tweet.text;



	/**
	 *
	 * Identifica URLs no corpo do texto do Tweet e adiciona o link externo para a URL
	 *
	 **/
	tweet_text = tweet_text.replace( /(((https?|ftp):\/\/)?(localhost|[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,3})((\/\S*)|(\/)[a-zA-Z0-9\.\?\/\{\}_%=&+-]+)?)/gm, '<a href="$1" title="$1" target="_blank">$1</a>' );



	/**
	 *
	 * Identifica nomes de usuários no corpo do texto do Tweet e adiciona o link para a página do mesmo no site do Twitter
	 *
	 **/
	tweet_text = tweet_text.replace( /@([a-zA-Z0-9_]+)/gm, '<a href="http://twitter.com/$1" title="@$1" target="_blank">@$1</a>' );



	/**
	 *
	 * Identifica "hash-tags" ( # ) no corpo do texto do Tweet e adiciona o link para a página de busca pelo termo no site do Twitter
	 *
	 **/
	tweet_text = tweet_text.replace( /#([a-zA-Z0-9]+)/gm, '<a href="http://search.twitter.com/search?q=%23$1" title="#$1" target="_blank">#$1</a>' );


	/**
	 *
	 * Monta o texto do Tweet
	 *
	 **/
	var	the_tweet_txt = '<p>' + the_user_link + ': ' + tweet_text + '</p>';



	/**
	 *
	 * Adiciona o conteúdo do Tweet e retorna o novo objeto ( Tweet ) criado
	 *
	 **/
	tweet_element
		.hide( )
		.append( the_tweet_txt );


	return tweet_element;

}



