/*

	http://api.twitter.com/1/statuses/user_timeline.json?screen_name=steviebeleven27&count=5&include_rts=1&page=1&callback=?
	
*/


// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};


(function($) {

    $.fn.tweet = function(method) {
		var globalVars;
		var jquerySelected;
		
		
        var methods = {

            init : function(options) {
				globalVars = $.extend({}, this.tweet.defaults, options);
                this.tweet.settings = $.extend({}, this.tweet.defaults, options);
                return this.each(function() {
                    var $element = $(this), // reference to the jQuery version of the current DOM element
                         element = this;      // reference to the actual DOM element
					jquerySelected = $(element)
                   	methods._getTwitterData();
                });

            },
			_make_api_url: function() {
				var apiURL = 'http://' + globalVars.twitter_api_url + '/1/statuses/user_timeline.json?'
				var queryCount = 0;
				
				if(globalVars.screen_name.length > 0){ apiURL += '&screen_name=' + globalVars.screen_name; }
				if(globalVars.count){ apiURL += '&count=' + globalVars.count; }		
				if(globalVars.include_rts){ apiURL += '&include_rts=' + globalVars.include_rts; }		
				if(globalVars.include_entities){ apiURL += '&include_entities=' + globalVars.include_entities; }
				if(globalVars.exclude_replies){ apiURL += '&exclude_replies=' + globalVars.exclude_replies; }
				
				
				apiURL += "&callback=?"
				return apiURL;
            },
            _getTwitterData: function() {
                jquerySelected.html(globalVars.loading_html)
				$.getJSON(methods._make_api_url(), function(data){
					methods.generate_markup(data);
				});
            },
			generate_markup : function(data){
				var markup = "";
				for (var i=0; i < globalVars.count; i++){
					var o = {};
					o.item = data[i];
					o.screen_name = o.item.from_user || o.item.user.screen_name;
					o.avatar_url = helpers.extract_avatar_url(o.item, (document.location.protocol === 'https:'));
					o.retweet = typeof(o.item.retweeted_status) != 'undefined';
					o.tweet_time = helpers.parse_date(o.item.created_at);
					o.tweet_id = o.item.id_str;
					o.twitter_base = "http://"+globalVars.twitter_url+"/";
					o.user_url = o.twitter_base+o.screen_name;
					o.tweet_url = o.user_url+"/status/"+o.tweet_id;
					o.reply_url = o.twitter_base+"intent/tweet?in_reply_to="+o.tweet_id;
					o.retweet_url = o.twitter_base+"intent/retweet?tweet_id="+o.tweet_id;
					o.favorite_url = o.twitter_base+"intent/favorite?tweet_id="+o.tweet_id;
					o.retweeted_screen_name = o.retweet && o.item.retweeted_status.user.screen_name;
					o.tweet_relative_time = helpers.relative_time(o.tweet_time);
					o.tweet_raw_text = o.retweet ? ('RT @'+o.retweeted_screen_name+' '+o.item.retweeted_status.text) : o.item.text; // avoid '...' in long retweets
					o.tweet_text = $([o.tweet_raw_text]).linkUrl().linkUser().linkHash()[0];
					o.tweet_text_fancy = $([o.tweet_text]).makeHeart().capAwesome().capEpic()[0];
					
					if (globalVars.markup_format != null){
						markup += globalVars.markup_format(o);
					} else {
						markup += "<li><a href='"+o.user_url+"'><img src='" + o.avatar_url + "' alt='"+ o.screen_name +"'/></a><div><h3><a href='"+o.user_url+"'>@"+ o.screen_name +"</a></h4><p>"+ o.tweet_text +"</p><p class='timeStamp'><a href='"+ o.tweet_url +"'>"+ o.tweet_relative_time + "</a></p></div></li>"		
					}
				}
				jquerySelected.html(markup);
				
			}


        }

        var helpers = {
			parse_date : function(date_str) {
			  return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
			},
			relative_time : function(date) {
				var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
				var delta = parseInt((relative_to.getTime() - date) / 1000, 10);
				var r = '';
				if (delta < 60) {
					r = delta + ' seconds ago';
				} else if(delta < 120) {
					r = 'a minute ago';
				} else if(delta < (45*60)) {
					r = (parseInt(delta / 60, 10)).toString() + ' minutes ago';
				} else if(delta < (2*60*60)) {
					r = 'an hour ago';
				} else if(delta < (24*60*60)) {
					r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago';
				} else if(delta < (48*60*60)) {
					r = 'a day ago';
				} else {
					var days = (parseInt(delta / 86400, 10))
					 if (days > 30 ){
						 var tweetDate = new Date(date);
						 var dateDay = tweetDate.getDate();
						 var dateMonth = tweetDate.getMonth();
						 var dateYear = tweetDate.getFullYear();
						 
						 if (dateMonth == 0){ dateMonth = "Jan" }
						 if (dateMonth == 1){ dateMonth = "Feb" }
						 if (dateMonth == 2){ dateMonth = "Mar" }
						 if (dateMonth == 3){ dateMonth = "Apr" }
						 if (dateMonth == 4){ dateMonth = "May" }
						 if (dateMonth == 5){ dateMonth = "Jun" }
						 if (dateMonth == 6){ dateMonth = "Jul" }
						 if (dateMonth == 7){ dateMonth = "Aug" }
						 if (dateMonth == 8){ dateMonth = "Sept" }
						 if (dateMonth == 9){ dateMonth = "Oct" }
						 if (dateMonth == 10){ dateMonth = "Nov" }
						 if (dateMonth == 11){ dateMonth = "Dec" }
						 
						 return dateDay + " " + dateMonth + " " + dateYear;
					 } else {
						  r = days.toString() + ' days ago';
					 }
				}
				return 'about ' + r;
			},
			extract_avatar_url:function(item, secure) {
				if (secure) {
					return ('user' in item) ?
					item.user.profile_image_url_https :
					extract_avatar_url(item, false);
				} else {
					return item.profile_image_url || item.user.profile_image_url;
				}
			}
			
        }

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error( 'Method "' +  method + '" does not exist in tweet plugin!');
        }

    }
	
	var url_regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;
	var replacer = function(regex, replacement) {
		return function() {
			var returning = [];
			this.each(function() {
				returning.push(this.replace(regex, replacement));
			});
			return $(returning);
		};
	}

	
	$.fn.extend({
		linkUrl: replacer(url_regexp, function(match) {
			var url = (/^[a-z]+:/i).test(match) ? match : "http://"+match;
			return "<a href=\""+url+"\">"+match+"</a>";
		}),
		linkUser: replacer(/@(\w+)/gi, "<a href=\"http://"+ 'www.twitter.com' +"/$1\">@$1</a>"),
		// Support various latin1 (\u00**) and arabic (\u06**) alphanumeric chars
		linkHash: replacer(/(?:^| )[\#]+([\w\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0600-\u06ff]+)/gi,'#'),
		capAwesome: replacer(/\b(awesome)\b/gi, '<span class="awesome">$1</span>'),
		capEpic: replacer(/\b(epic)\b/gi, '<span class="epic">$1</span>'),
		makeHeart: replacer(/(&lt;)+[3]/gi, "<tt class='heart'>&#x2665;</tt>")
	});


    $.fn.tweet.defaults = {
       	screen_name: "",
		count: 3,
		include_rts: false,
		include_entities: false,
		exclude_replies: false,
		list: null,
		loading_html: "<li><strong>Loading Twitter Feed</strong></li>",
		twitter_api_url: "api.twitter.com",
		twitter_search_url: "search.twitter.com",
		twitter_url: "twitter.com",
		markup_format: null
    }

    $.fn.tweet.settings = {}

})(jQuery);
