/*
  
/\/\/\/\/\/\/\/\/\/\/\/\/\/\
\                          /
/   jQuery twitit plugin   \
\      By Jack Bliss       /
/                          \
\/\/\/\/\/\/\/\/\/\/\/\/\/\/


n.b., Whenever content is appended to something, unless I'm specifically outputing it somewhere else, I'm appending it to some element 
with an id of 'sidebar'. Of course, this element isn't necessary and you can append things where ever you want. Heck, you can prepend 
them for all I care.

!-----------<<< Standard Implementation >>>-----------!

<span id='twitter' rel="jackbliss99"></span>
$('twitter').twitit();

That will get you where you need to be. You can use a callback.

!-----------<<< With a Callback >>>-----------!

$('<span rel="jackbliss99" />').appendTo('#sidebar').twitit(function(data){
	$(this).prepend('<img src="'+data[0].user.profile_image_url+'" />');
});

$(this) references the node(s) the function was called on. Passing a variable into the callback gives you access to the data returned 
from the server by twitter. If you want to see how it's laid out, I suggest doing something like this:

$('<span rel="jackbliss99" />').hide().appendTo('body').twitit(function(data){
	console.log(data);
});

Using developer tools (I recommend the one on chrome) you can see the architecture of the object.

In addition to these ways, you can set the parameters with an object.

!-----------<<< Using the Object >>>-----------!

$('<span />').appendTo('#sidebar').twitit(function(data){}, {
	query : 'jQuery', //The query string to be used - either a username or a search term (see below).
	linkClass : 'links', //A string to be used as a class for all the links in the tweet.
	error : 'There was a grave error. Please contact your administrator.', //A message to use instead of the tweet in case of errors.
	mode : 'search' //Either 'search' or 'user'. User returns the users latest tweet, search returns the latest search result for 'query'.
});

!-----------<<< Tweetify >>>-----------!

As a bonus, you get the .tweetify() plugin, which I stripped from css-tricks.com. Basically converts @s, #s and regular links into 
clickable links. Really quite useful. Used as standard on all returned tweets.

!-----------<<< jQuery Based tweetme() Function >>>-----------!

This is not a plugin. It is a function that returns a neat object containing twitter information as specified by the user.

tweetme('query', callback(twitter), 'mode');

Query and mode function exactly the same as with twitit.

Not passing a variable into the callback is entirely pointless - in this instance, the data will be insterted into the 'twitter' variable.
Here's what you get:

mode = 'user' :

twitter.latest      => stores the latest tweet by the user.
twitter.tweets      => stores the latest 15 tweets as an array.
twitter.followers   => stores the number of followers the user has.
twitter.name        => stores the user's name.
twitter.location    => stores the user's location.
twitter.picture     => stores the user's profile picture url.
twitter.description => stores the user's description.
twitter.url         => stores the url of the user's website.
twitter.echo(token) => writes the latest tweet to the html node 'token'. Returns the node.
twitter.data        => the full data object as returned by twitter.

mode = 'search' :

twitter.name 	    => stores the search query. 
twitter.latest      => stores the latest tweet from the query.
twitter.tweets 	    => stores all the tweets in text form as an array.
twitter.full_tweets => stores the actual tweet objects returned from twitter.
twitter.latest_user => stores the username of the last person to tweet the search term.
twitter.echo(token) => writes the latest tweet to the html node 'token'. Returns the node.
twitter.data 	    => the full data object as returned by twitter.

For example:

tweetme('jQuery', callback(t){
	for(i = 0; i<5; i++){
		var p = $('<p />').appendTo('#sidebar');
		var a = $('<a href="http://twitter.com/'+t.full_tweets[i].from_user+'" />').appendTo(p);
		var img = $('<img src="'+t.full_tweets[i].profile_image_url+'" height="16" width="16" />').appendTo(a);
		var span = $('<span />').appendTo(p).html(' '+t.tweets[i]).tweetify();
	}
}, 'search');

Will display the latest five tweets to mention 'jQuery', with the tweeter's profile picture in front linking to their profile.

*/

(function($){ 
		  
	$.fn.tweetify = function(lclass) {
		if(!lclass){
			lclass = 'twitter_link';
		}
		this.each(function() {
			$(this).html(
				$(this).html()
					.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'<a rel="link" class="'+lclass+'" href="$1">$1</a>')
					.replace(/(^|\s)#(\w+)/g,'$1<a rel="hash" class="'+lclass+'" href="http://search.twitter.com/search?q=%23$2">#$2</a>')
					.replace(/(^|\s)@(\w+)/g,'$1<a rel="at" class="'+lclass+'" href="http://twitter.com/$2">@$2</a>')
			);
		});
		return this;
	}
	
	$.fn.twitit = function(callback, options){
		
		//Set defaults, then combine them with arguments.
		var defaults = {
				query: '',
				linkClass: 'twitter_link',
				error: 'There was an error connecting to twitter.',
				mode: 'user'
			},
			settings = $.extend({}, defaults, options);	
			
		this.each(function(){
			var $this = $(this);
			if(settings.query === ''){
				settings.query = $this.attr('rel');
			}
			try{
			//Select mode
				if(settings.mode === 'user'){
					$.getJSON("http://twitter.com/statuses/user_timeline/"+settings.query+".json?callback=?", function(data) {
						$this.html(data[0].text).tweetify(settings.linkClass);
						if(typeof(callback) == 'function'){
							//Set the 'this' of the callback to $(this). Not important to running the function, just convenient.
							$this.callback = callback;
							$this.callback(data);
						}
					});
				} else if(settings.mode === 'search'){
					$.ajax({
						url : 'http://search.twitter.com/search.json?q='+settings.query,
						dataType : 'jsonp',
						success : function(data){
							$this.html('@'+data.results[0].from_user+': '+data.results[0].text).tweetify(settings.linkClass);
							if(typeof(callback) == 'function'){
								$this.callback = callback;
								$this.callback(data);
							}
						}
					});
				}
			}
			catch(err){
				$this.html(settings.error);
			}
		});
		
		//Chainability
		return this;	
	}
})(jQuery);

function tweetme(query, callback, mode){
	if(typeof(mode) == 'undefined'){
		mode = 'user';
	}
	if(mode === 'user'){
		$.ajax({
			url : "http://twitter.com/statuses/user_timeline/"+query+".json?callback=?", 
			dataType : 'jsonp',
			success : function(data) {
				var twitter = new Object();
				if(data.length > 0){
					twitter.latest = data[0].text;
					twitter.tweets = new Array();
					for(i = 0; i < data.length; i++){
						twitter.tweets.push(data[i].text);
					}
					twitter.followers = data[0].user.followers_count;
					twitter.name = data[0].user.name;
					twitter.location = data[0].user.location;
					twitter.picture = data[0].user.profile_image_url;
					twitter.description = data[0].user.description;
					twitter.url = data[0].user.url;
					twitter.echo = function(token){
						token.html(twitter.latest);
						return token;
					}
					twitter.data = data;
					callback(twitter);
				} else {
					console.log('error retrieving tweets.');
					twitter = false;
				}
			},
			error : function(){
				callback(false);
			}
		});
	} else if(mode === 'search'){
		$.ajax({
			url : 'http://search.twitter.com/search.json?q='+query,
			dataType : 'jsonp',
			success : function(data){
				var twitter = new Object();
				if(data.results.length > 0){
					twitter.name = query;
					twitter.latest = data.results[0].text;
					twitter.tweets = new Array();
					for(i = 0; i<data.results.length; i++){
						twitter.tweets.push(data.results[i].text);
					}
					twitter.full_tweets = new Array();
					for(i = 0; i<data.results.length; i++){
						twitter.full_tweets.push(data.results[i]);
					}
					twitter.latest_user = data.results[0].from_user;
					twitter.echo = function(token){
						token.html(twitter.latest);
						return token;
					}
					twitter.data = data;
				} else {
					console.log('error retrieving tweets.');
					twitter = false;
				}
				callback(twitter);
			},
			error : function(){
				callback(false);
			}
		});
	}
}

