/*
	getTweets v.1.5 - a script get tweets from account 
	(c) 2011 Adam Randlett : monkdevelopment.com
*/  

(function($){
	$.fn.getTweets = function(settings){ 
		var defaults = {
			twitter_api_url: "http://api.twitter.com/1/statuses/user_timeline/",
			twitter_users: ["monkdev"],
			format: "json",
			howmany: 3,
			tweetstring:""
		}

        var options = $.extend(defaults, settings); 
        return this.each(function(){
		      var $this = $(this),
	  	      	  tweetoptions ={ 
	  				  twitter_users:options.twitter_users,
	  				  howmany:options.howmany,
	  				  tweetstring:options.tweetstring
	  			  },
				  global_tweets = [],
				  user_count,
				  twitter_users_last = tweetoptions.twitter_users.length -1;
			
			//$.ajaxSetup({ cache: true });
			
			function twitter_relative_time(time_value) {
			  var values=time_value.split(" ");
			  time_value=values[1]+" "+values[2]+", "+values[5]+" "+values[3];
			  var parsed_date=Date.parse(time_value);
			  var relative_to=(arguments.length>1)?arguments[1]:new Date();
			  var delta=parseInt((relative_to.getTime()-parsed_date)/1000);
			  delta=delta+(relative_to.getTimezoneOffset()*60);
			  if(delta<60){return 'less than a minute ago';}else if(delta<120){return 'about a minute ago';
			  }else if(delta<(60*60)){return (parseInt(delta/60)).toString()+' minutes ago';
			  }else if(delta<(120*60)){return 'about an hour ago';
			  }else if(delta<(24*60*60)){return 'about '+(parseInt(delta/3600)).toString()+' hours ago';
			  }else if(delta<(48*60*60)){return '1 day ago';
			  }else{return(parseInt(delta/86400)).toString()+' days ago';}
			} 
			
			function urlReplace(eurl){
			  var urlRegex = new RegExp(/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi);
			  return eurl.replace(urlRegex, function(url) {
			          return '<a href="' + url + '">' + url + '</a>';
			  });
			};
			
			String.prototype.multiReplace = function ( hash ) {
				var str = this, key;
				for ( key in hash ) {
					str = str.replace( new RegExp( key, 'g' ), hash[ key ] );
					
				}
				return str;
			};
			
			function twitter_parser(tweets){
				$.each(tweets, function(i,tweet){
					if(tweet.text !== undefined) {
					    var tweet_html = tweetoptions.tweetstring.multiReplace({
							'{tweetdate}' : twitter_relative_time(tweet.created_at) , // Calculate how many hours ago was the tweet posted  
							'{tweeturl}'  : 'http://www.twitter.com/' +  tweet.user.name + '/status/' + tweet.id ,
							'{tweettext}' : urlReplace(tweet.text),
							'{tweetuser:name}' : tweet.user.name,
							'{tweetuser:location}' : tweet.user.location,
							'{tweetuser:description}' : tweet.user.description,
							'{tweetuser:url}': tweet.user.url,
							'{tweetuser:image}': tweet.user.profile_image_url,
							'{tweetsource}': tweet.source
						});
						
						global_tweets.push({
							id:tweet.id,
							status:tweet_html
						});
	            	}
				});	
			}

			function twitter_output(){
				global_tweets.sort(function(a,b){return(b.id-a.id)});
				twitter_count=global_tweets.length;

				for(var i=0; i<tweetoptions.howmany; i++){
					$this.append(global_tweets[i].status);
				}
			}
			
			function get_tweets(current){
				$.ajax({
			  	    dataType:"json", 
			  	    url: options.twitter_api_url+tweetoptions.twitter_users[current]+'.'+options.format+'?&count='+tweetoptions.howmany+'&callback=?',
			  	    timeout: 1000,
			  	    type:"GET",
			  	    async:false,
					crossDomain:false,
			  	    error: function(){ 
			  	    },
					success:function(data){
						twitter_parser(data);
					},
					complete:function(){
						if(current<twitter_users_last){
					      //run this function (recursivly) to get all tweets for the next user
					      get_tweets(++current);
					    }else{
					      //if all tweets are loaded into the global_tweets array and launch twitter_render function
					      twitter_output();
					    }
					}//@end success	
				});	//@end ajax
			} // @end get_tweets
		
		   get_tweets(0);
	  });
	};
})(jQuery);
