/*
	jQuery - tweetGrab Plugin
	@copyright Michael Kafka
	@version 2.3
*/
(function($){		  
	var tweet_id;
	
	$.fn.tweetGrab = function(options) {
		var opts = $.extend({}, $.fn.tweetGrab.defaults, options);

		return this.each(function(i) {
			obj = $(this);
			set = {};
				set.url = obj.attr('href');
				set.text = obj.text();
				set.urlCheck = /^(https?:\/\/)?([\da-z\.\-]+)\.([a-z\.]{2,6})([\/\w \.\-]*)*\/?$/.test(set.url);
				set.center = 'margin-left:auto; margin-right:auto;';
				set.searchTerm = false;

				if(/^\@/.test(set.text)){
					set.type = 'user';
				} else if( /^\#/.test(set.text) ){
					set.type = 'hashtag';
				} else if( /^\$/.test(set.text) ){
					set.type = 'ticker';
				} else if( /^\?/.test(set.text) ){
					set.type = 'search';
					set.text = set.text.replace(/^\?/,'');
				}

			if(opts.user !== '' && opts.list !== ''){

                if(set.type === 'user'){
                    opts.user = set.text;
                }
                set.type = 'list';
                set.id = opts.user + i;
                set.twitterURL = 'http://api.twitter.com/1/' + opts.user + '/lists/' + opts.list + '/statuses.json?callback=?';
                set.displayURL = 'http://twitter.com/' + opts.user + '/' + opts.list;

			} else if(opts.user !== '' || set.type === 'user'){

				if(set.type === 'user'){
					opts.user = set.text;
				}
				set.type = 'user';
				if(/^\@/.test(opts.user)){
					opts.user = opts.user.substr(1,opts.user.length);
				}
				set.id = opts.user + i;
				set.twitterURL = 'http://twitter.com/statuses/user_timeline/' + opts.user + '.json?count=' + opts.tweetCount + '&callback=?';
				set.displayURL = 'http://twitter.com/' + opts.user;
				
			} else if(opts.hashtag !== '' || set.type === 'hashtag') {
				
				if(set.type === 'hashtag'){
					opts.hashtag = set.text;
				}
				set.type = 'hashtag';
				if(/^\#/.test(opts.hashtag)){
					set.id = opts.hashtag.substr(1,opts.hashtag.length) + i;
				} else {
					set.id = opts.hashtag + i;
					opts.hashtag = '#'+opts.hashtag; 
				}
				set.searchTerm = escape(opts.hashtag);
				
			} else if(opts.ticker !== '' || set.type === 'ticker') {
				
				if(set.type === 'ticker'){
					opts.ticker = set.text;
				}
				set.type = 'ticker';
				if(/^\$/.test(opts.ticker)){
					set.id = opts.ticker.substr(1,opts.ticker.length) + i;
				} else {
					set.id = opts.ticker + i;
					opts.ticker = '$'+opts.ticker; 
				}
				set.searchTerm = escape(opts.ticker);
				
			} else if(set.urlCheck) {
				var regex = '^(https?:\/\/)?([twier]+)\.([com]+)/.*/([status]+)/';
				if(set.url.match(regex)){
					set.type = 'quote';
					set.id = set.url.replace(/.+(?=[^0-9])./i,'');
					set.twitterURL = 'http://twitter.com/statuses/show/' + set.id + '.json?callback=?';
					set.displayURL = set.url;
				}
				
			} else {
				set.searchTerm = escape(set.text);
			}
			
			if(set.searchTerm){
				set.type = 'search';
				set.twitterURL = 'http://search.twitter.com/search.json?callback=?&q=' + set.searchTerm + '&rpp=' + opts.tweetCount;
				set.displayURL = 'http://search.twitter.com/search?q=' + set.searchTerm;
			}
			
			// replace the static link with tweetGrab container and "loading"
			if(!opts.center){set.center = '';}
			
			obj.replaceWith(' ' +
                '<div class="tweetgrab_container" id="' + set.id + '" style="width:' + opts.width + '; ' + set.center + '">' +
				'<span class="tweetgrab_loading" id="' + set.id + '">loading <a href="' + set.displayURL + '">' + set.displayURL + '</a></span>' +
                '</div>'
			);
			
			// fetch tweet info
			fetchTweet(opts, set, i);
		
		}); 
    }; // end $.fn.siteFeature


	$.fn.tweetGrab.defaults = {
		user: '',						// UserName (makfak) or ID (12345) to retrieve tweets
		hashtag: '',					// HashTag (#haiku) used to retrieve tweets
		ticker: '',						// Ticker ($money) used to retrieve tweets
		list: '',                       // List (peeps) will pull a list-feed from a user ('user' required)
		tweetCount: '10',				// the number of tweets to fetch (if not fetching a single tweet)
		width: '99%',					// sets the width of each tweetGrab
		center: false,					// centers each tweetGrab relative to the parent (true / false)
		animateHeightDuration: 500,		// height animation duration in milliseconds
		animateHeightEasing: 'linear',	// tweetGrab is fully compatible with the jQuery Easing Plugin
		animateFadeDuration: 500,		// fade animation duration in milliseconds
		errorMessage: ''				// message displayed if the request fails or returns null
	}; // end $.fn.siteFeature.defaults
	
	/*var clearTimeoutArr = Array;*/
	
	// JSONP call to the Twitter API
	function fetchTweet(opts, set, i){
		$.getJSON(set.twitterURL, function(data){
			if(data.results === '') {
				
				if(opts.errorMessage === ''){
					$('#' + set.id).children('.tweetgrab_loading').html(
						$('#' + set.id).children('.tweetgrab_loading').html().replace(/loading/,'error')
					).addClass('error');
				} else {
					$('#' + set.id).children('.tweetgrab_loading').text(opts.errorMessage).addClass('error');
				}
				
			} else {

				var tweetHTML = '';
				var userLinkColor;
	
				if(set.type === 'search'){
					$.each(data.results,function(i){
						if(i === 0){
							tweetHTML = ' ' +
                                '<div class="tweetgrab_background tweetgrab_search" style="visibility:hidden;">' +
                                '<div class="tweetgrab_content">' +
                                '<span class="tweetgrab_speech-bubble"></span>';
						}
						
						tweetHTML += ' ' +
                            '<div>' +
                                '<span class="tweet_author"><a href="http://www.twitter.com/' + this.from_user + '" style="background:url(' + this.profile_image_url + ') 0px 0px no-repeat;" title="' + this.from_user + '"></a></span>' +
                                '<span class="tweet_text">' +
                                    '<a href="http://www.twitter.com/' + this.from_user + '">' + this.from_user + '</a>: ' + linkify(this.text) +
                                    '<span class="tweet_meta"><a href="http://twitter.com/' + this.from_user  + '/status/' + this.id + '">' + relative_time(this.created_at) + '</a></span>' +
                                '</span>' +
                                '<span class="clear"></span>' +
                            '</div>';
	
						if(i === data.results.length - 1){	
							tweetHTML += ' ' +
                                    '<span class="tweet_info">Search Results for: <a href="' + set.displayURL + '">' + unescape(set.searchTerm) + '</a></span>' +
                                '</div>' +
                            '</div>';
						}
					});
				}
			
			
			
			
				if(set.type === 'quote'){
					tweetHTML = ' ' +
                        '<div class="tweetgrab_background" style="background-image:url(' + data.user.profile_background_image_url + '); background-color:#' + data.user.profile_background_color + ';visibility:hidden;">' +
                            '<div class="tweetgrab_content">' +
                                '<span class="tweetgrab_speech-bubble"></span>' +
                                '<span class="tweet_text" style="color:#' + data.user.profile_text_color + ';">' + linkify(data.text) + '</span>' +
                                '<span class="tweet_meta"><a href="' + set.url  + '">' + relative_time(data.created_at) + '</a></span>' +
                                '<span class="tweet_author"><a href="http://www.twitter.com/' + data.user.screen_name + '" style="background:url(' + data.user.profile_image_url + ') 0px 0px no-repeat; color:#' + data.user.profile_link_color + ';">' + data.user.screen_name + '</a></span>' +
                            '</div>' +
                        '</div>';
				}
			
			
			
			
				if(set.type === 'user'){
					$.each(data,function(i){
					    
						if(i === 0){
							userLinkColor = this.user.profile_link_color;
							tweetHTML = ' ' +
                                '<div class="tweetgrab_background" style="background-image:url(' + this.user.profile_background_image_url + '); background-color:#' + this.user.profile_background_color + ';visibility:hidden;">' +
                                    '<div class="tweetgrab_content">' +
                                        '<span class="tweetgrab_speech-bubble"></span>';
						}
					
						tweetHTML += '<span class="tweet_text" style="color:#' + this.user.profile_text_color + ';">' + linkify(this.text) + '</span>' +
                            '<span class="tweet_meta"><a href="http://twitter.com/' + this.user.screen_name + '/status/' + this.id + '">' + relative_time(this.created_at) + '</a></span>';
		
						if(i === data.length - 1){
							tweetHTML += ' ' +
                                    '<span class="tweet_author"><a href="http://www.twitter.com/' + this.user.screen_name + '" style="background:url(' + this.user.profile_image_url + ') 0px 0px no-repeat; color:#' + this.user.profile_link_color + ';">' + this.user.screen_name + '</a></span>' +
                                '</div>' +
                            '</div>';
						}
					});
				}
				
				if(set.type === 'list'){
				    $.each(data,function(i){
				        if(i === 0){
                            tweetHTML = ' ' +
                                '<div class="tweetgrab_background tweetgrab_search" style="visibility:hidden;">' +
                                    '<div class="tweetgrab_content">' +
                                        '<span class="tweetgrab_speech-bubble"></span>';
                        }
                        
                        tweetHTML += '<div>' +
                            '<span class="tweet_author"><a href="http://www.twitter.com/' + this.user.screen_name + '" style="background:url(' + this.user.profile_image_url + ') 0px 0px no-repeat;" title="' + this.user.screen_name + '"></a></span>' +
                            '<span class="tweet_text">' +
                                '<a href="http://www.twitter.com/' + this.user.screen_name + '">' + this.user.screen_name + '</a>: ' + linkify(this.text) +
                                '<span class="tweet_meta"><a href="http://twitter.com/' + this.user.screen_name  + '/status/' + this.id_str + '">' + relative_time(this.created_at) + '</a></span>' +
                            '</span>' +
                            '<span class="clear"></span>' +
                        '</div>';

                        if(i === data.length - 1){   
                            tweetHTML += '<span class="tweet_info">List: <a href="' + set.displayURL + '">@' + opts.user + '/' + opts.list + '</a></span>' +
                                '</div>' +
                            '</div>';
                        }

                    });
                }
				
				tweet_id = set.id;
				
				// inject the output into the DOM and apply appropriate style
				$('#' + set.id).children('.tweetgrab_loading')
					.parent().prepend(tweetHTML)
					.find('span.tweet_text a').css({'color':'#' + userLinkColor})
				;
				
				// get the final height and animate to it
				var tweetHeight = $('#' + set.id).children('.tweetgrab_background').height();
				
				$('#' + set.id).children('.tweetgrab_loading').animate({'opacity':'1'},500,function(){
					$(this).animate({'height':tweetHeight},opts.animateHeightDuration, opts.animateHeightEasing, function(){
						$(this).parent().css({'height':tweetHeight}).children('.tweetgrab_background').css({'visibility':'visible'});
						$(this).animate({'opacity':'0'},opts.animateFadeDuration, function(){
							$(this).css({'display':'none'});
						});
					});
				});
			} // end Error IF/ELSE
		});
		return;
	}
	
	// Twitter returns an HTML-less string... This puts the HTML back.
	function linkify(content) {
		// linkify Links
		content = content.replace(/[A-Za-z]+:\/\/[A-Za-z0-9\-\_]+\.[A-Za-z0-9\-\_:~%&\?\/.=]+/, function(links) {
			return links.link(links);
		});
		
		// linkify @users
		content = content.replace(/@+[A-Za-z0-9\-\_]+/g, function(ats) {
			content = ats.replace(/[A-Za-z0-9\-\_]+/,function(i){
				return '<a href="http://twitter.com/' + i + '">' + i + '</a> ';
			});
			return content;
		});
		
		// linkify #hash tags
		content = content.replace(/#+[A-Za-z0-9\-\_]+/g, function(hashes) {
			content = hashes.replace(/[A-Za-z0-9\-\_]+/,function(i){
				return '<a href="http://search.twitter.com/search?q=+%23' + i + '">' + i + '</a> ';
			});
			return content;
		});
		
		// linkify $ticker tags
		content = content.replace(/\$+[A-Za-z0-9\-\_]+/g, function(tickers) {
			content = tickers.replace(/[A-Za-z0-9\-\_]+/,function(i){
				return '<a href="http://search.twitter.com/search?q=+%24' + i + '">' + i + '</a> ';
			});
			return content;
		});
		
		return content;
	}
	
	// Twitter returns generic PHP time... this turns it into the Twitter Relative Time we all love so bad
	function 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);
		
		var r = '';
		if (delta < 60) {
			r = 'a minute ago';
		} else if(delta < 120) {
			r = 'couple of minutes ago';
		} else if(delta < (45*60)) {
			r = (parseInt(delta / 60)).toString() + ' minutes ago';
		} else if(delta < (90*60)) {
			r = 'an hour ago';
		} else if(delta < (24*60*60)) {
			r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
		} else if(delta < (48*60*60)) {
			r = '1 day ago';
		} else {
			r = (parseInt(delta / 86400)).toString() + ' days ago';
		}
		return r;
	}

})(jQuery);
