/*
	getTweets v.1 - 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_user: "monkdev",
			format: "json",
			howmany: 3,
			tweetstring:"<div class='tweet'><a href='{tweeturl}'>{tweettext}</a> - {tweetdate}</div>"
		}

        var options = $.extend(defaults, settings); 
        return this.each(function(){
		      var $this = $(this); 
  	      var tweetoptions ={ 
  				  twitter_user:options.twitter_user,
  				  howmany:options.howmany,
  				  tweetstring:options.tweetstring
  			  }  
			
			$.ajaxSetup({ cache: true });
			
			/*
			 * Javascript Humane Dates
			 * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
			 * Re-write by Zach Leatherman (zachleat.com)
			 * 
			 * Adopted from the John Resig's pretty.js
			 * at http://ejohn.org/blog/javascript-pretty-date
			 * and henrah's proposed modification 
			 * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
			 * 
			 * Licensed under the MIT license.
			 */

			function humanDate(date_str){
				var time_formats = [
					[60, 'Just Now'],
					[90, '1 Minute'], // 60*1.5
					[3600, 'Minutes', 60], // 60*60, 60
					[5400, '1 Hour'], // 60*60*1.5
					[86400, 'Hours', 3600], // 60*60*24, 60*60
					[129600, '1 Day'], // 60*60*24*1.5
					[604800, 'Days', 86400], // 60*60*24*7, 60*60*24
					[907200, '1 Week'], // 60*60*24*7*1.5
					[2628000, 'Weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
					[3942000, '1 Month'], // 60*60*24*(365/12)*1.5
					[31536000, 'Months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
					[47304000, '1 Year'], // 60*60*24*365*1.5
					[3153600000, 'Years', 31536000], // 60*60*24*365*100, 60*60*24*365
					[4730400000, '1 Century'], // 60*60*24*365*100*1.5
				];

				  var time = new Date(date_str.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/,"$1 $2 $4 $3 UTC")), //correct format for twitter
					//('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "), old format didn't work in IE
					dt = new Date,
					seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
					token = ' Ago',
					i = 0,
					format;

				if (seconds < 0) {
					seconds = Math.abs(seconds);
					token = '';
				}

				while (format = time_formats[i++]) {
					if (seconds < format[0]) {
						if (format.length == 2) {
							return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
						} else {
							return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
						}
					}
				}

				// overflow for centuries
				if(seconds > 4730400000)
					return Math.round(seconds / 4730400000) + ' Centuries' + token;

				return date_str;
			}; 
			
			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;
			};
			
			$.ajax({
		  	    dataType:"json", 
		  	    url: options.twitter_api_url + tweetoptions.twitter_user + '.' + options.format + '?callback=?',
		  	    timeout: 1000,
		  	    type:"GET",
		  	    async:false, 
		  	    error: function(){ 
		  	    },
		  	    success: function(data){ 
		  	    //window.console.log(data);
			    	$.each(data, function(i, tweet) {
	                if(tweet.text !== undefined) {
        					    var tweet_html = tweetoptions.tweetstring.multiReplace({
        							'{tweetdate}' : humanDate(tweet.created_at) , // Calculate how many hours ago was the tweet posted  
        							'{tweeturl}'  : 'http://www.twitter.com' +  tweetoptions.twitter_user + '/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
        						}); 
        						
	                 $this.append(tweet_html);
	              } 
				   if(i === tweetoptions.howmany - 1){
					   return false;
					} 
	            }); 
				
				}	
			});
	  });
	};
})(jQuery);
