// ##############################################################################################################################
// Instructions page: see OTYS wiki
// Last Edit by: Maikel Doeze
//
// ## OTYS Change log ###########################################################################################################
// -Added animation var to switch animations - MD - 18-08-2011 
// -Changed Query bug so now it will work even in combination - MD - 10-06-2011
// -Added target blank to text links - MD - 25-05-2011
// -Changed "tweetTime" href because API changed - MD - 16-02-2011
// -Removed test name - MD - 16-02-2011
// -Fixed typo of offical code - MD - 26-08-2010
// -Cleaned up javascript - MD - 26-08-2010
// -Fixed html bug in IE - MD - 26-08-2010
// -Changed twitterAPI url for better query use - MD - 26-08-2010
// -Setup javascript for div use - MD - 26-08-2010
// -Renamed classes - MD - 26-08-2010
// -Removed message system - MD - 26-08-2010
// -Removed theme system - MD - 26-08-2010
// ##############################################################################################################################

(function($) {
	$.fn.tweet = function(o){
		var s = {
			username: ['otys'],	// [string]   required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"]
			query: null,	// [string]   optional search query
			list: null,	//[string]   optional name of list belonging to username
			count: 10,	// [integer]  how many tweets to load?
			loading_text: null,	// [string]   optional loading text, displayed while tweets load
			animation: 'cycle', // false, cycle, multi
			speed: 1000, // [normal|slow|fast|time in ms]
			timeout: 5000, // waiting time between 2 display, in ms
			items: 2 // number of DOM elements to display
		};

		if(o) $.extend(s, o);

		$.fn.extend({
			linkUrl: function() {
				var returning = [];
				var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
				this.each(function() {
					returning.push(this.replace(regexp,"<a href=\"$1\" target=\"_blank\">$1</a>"));
				});
				return $(returning);
			},
			linkUser: function() {
				var returning = [];
				var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
				this.each(function() {
					returning.push(this.replace(regexp,"<a href=\"http://twitter.com/$1\" target\"_blank\">@$1</a>"));
				});
				return $(returning);
			},
			linkHash: function() {
				var returning = [];
				var regexp = /(?:^| )[\#]+([A-Za-z0-9-_]+)/gi;
				this.each(function() {
					returning.push(this.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all&from='+s.username.join("%2BOR%2B")+'" target="_blank">#$1</a>'));
				});
				return $(returning);
			},
			capAwesome: function() {
				var returning = [];
				this.each(function() {
					returning.push(this.replace(/\b(awesome)\b/gi, '<span class="awesome">$1</span>'));
				});
				return $(returning);
			},
			capEpic: function() {
				var returning = [];
				this.each(function() {
					returning.push(this.replace(/\b(epic)\b/gi, '<span class="epic">$1</span>'));
				});
				return $(returning);
			},
			makeHeart: function() {
				var returning = [];
				this.each(function() {
					returning.push(this.replace(/(&lt;)+[3]/gi, "<span class='heart'>&#x2665;</span>"));
				});
				return $(returning);
			}
		});

		function parse_date(date_str) {
			return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
		}

		function relative_time(time_value) {
			var parsed_date = parse_date(time_value);
			var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
			var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
			var pluralize = function (singular, n) {
				return '' + n + ' ' + singular + (n == 1 ? '' : 's');
			};
			if(delta < 60) {
				return 'less than a minute ago';
			} else if(delta < (60*60)) {
				return 'about ' + pluralize("minute", parseInt(delta / 60)) + ' ago';
			} else if(delta < (24*60*60)) {
				return 'about ' + pluralize("hour", parseInt(delta / 3600)) + ' ago';
			} else {
				return 'about ' + pluralize("day", parseInt(delta / 86400)) + ' ago';
			}
		}

		function build_url() {
			var proto = ('https:' == document.location.protocol ? 'https:' : 'http:');
			if (s.list) {
				return proto+"//api.twitter.com/1/"+s.username[0]+"/lists/"+s.list+"/statuses.json?per_page="+s.count+"&callback=?";
			} else if (s.query == null || s.query == "" && s.username.length == 1) {
				return proto+'//api.twitter.com/1/statuses/user_timeline.json?screen_name='+s.username[0]+'&count='+s.count+'&callback=?';
			} else {
				var query = (s.query || 'from:'+s.username.join(' OR from:'));
				return proto+'//search.twitter.com/search.json?&q='+encodeURIComponent(query)+'&rpp='+s.count+'&callback=?';
			}
		}

		return this.each(function(i, widget){
			var list = $('<div class="tweetList">').appendTo(widget);
			var loading = $('<div class="tweetLoading">'+s.loading_text+'</div>');
	
			if(typeof(s.username) == "string"){
				s.username = [s.username];
			}

			if (s.loading_text) $(widget).append(loading);
			$.getJSON(build_url(), function(data){
				if (s.loading_text) loading.remove();
				var tweets = (data.results || data);
				$.each(tweets, function(i,item){
					var from_user = item.from_user || item.user.screen_name;
					var profile_image_url = item.profile_image_url || item.user.profile_image_url;
					var avatarTpl = '<span class="tweetAvatar"><a target="_blank" href="http://twitter.com/'+from_user+'"><img src="'+profile_image_url+'" alt="'+from_user+'\'s avatar" title="'+from_user+'\'s avatar" border="0"/></a></span>';
					var usernameTpl = '<span class="tweetUser"><a target="_blank" href="http://twitter.com/'+from_user+'">'+from_user+'</a></span>';
					var dateTpl = '<span class="tweetTime"><a target="_blank" href="http://twitter.com/'+from_user+'" title="view tweet on twitter">'+relative_time(item.created_at)+'</a></span>';
					var text = '<span class="tweetText">' +$([item.text]).linkUrl().linkUser().linkHash().makeHeart().capAwesome().capEpic()[0]+ '</span>';
					var cleaner = '<span class="cleaner"></span>';
					
					// until we create a template option, arrange the items below to alter a tweet's display.
					list.append('<div>' + avatarTpl + usernameTpl + dateTpl + text + cleaner +'</div>');

					list.children('div:odd').addClass('tweetItem tweetEven');
					list.children('div:even').addClass('tweetItem TweetOdd');
					list.children('div:first').addClass('tweetFirst');
				});
	        	$(widget).trigger("loaded").trigger((tweets.length == 0 ? "empty" : "full"));
				
				if(s.animation == 'cycle')
				{
					$('.tweetList').cycle({
						fx: 'scrollDown',
						pause: true,
						cleartype: true,
						speed: s.speed,
						timeout: s.timeout
					});
				}
				else if(s.animation == 'multi')
				{
					var sIdContainer	= '.tweetList';	// id of list container
					var sSelector		= '.tweetItem'; // class of DOM element list						 

					// Move each DOM element, with position > cycleitems, at the top of list
					$( sSelector + ':gt(' + (s.items - 1) + ')').each
					(
						function()
						{
							$(this).clone().hide().prependTo($(sIdContainer));
							$(this).remove();
						}
					);

					// Function definition
					var fCarrousel = function()
					{
						// Execute code at specific moment
						setTimeout
						(
							function()
							{
								// Hide last DOM element and move it at the top of list
								$(sSelector + ':visible:last').slideUp
								(
									s.speed,
									function ()
									{
										$(this).clone().hide().prependTo($(sIdContainer));
										$(this).remove();
									}
								);
								
								// Display the last DOM element hidden
								$(sSelector + ':hidden:last').slideDown(s.speed);
								
								// Recursivity
								fCarrousel();
							},
							s.timeout
						);
					}
					fCarrousel();
				}
				else
				{
					// false
				}
			});
		});
	};
})(jQuery);
