BLIP.Class.create("BLIP.Unit.TwitterFeed", BLIP.Unit,
	function(config) {
		BLIP.Unit.call(this, config);
	},
	{

		selector : ".TwitterFeed",

		init : function() {
			this.userReg = /(^|\s)@(\w+)/gi;
			this.hashReg = /(^|\s)#(\w+)/gi;
			this.urlReg = /(^|\s)(https?:\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z0-9+&@#\/%=~_|])/gi;

			this.initContents();
		},

		initContents : function() {
			if (this.domRoot.attr('data-twitter-name').length) {
				var url = new BLIP.Utils.UrlBuilder('/show/get_recent_tweets');
				url.addParam('screen_name', this.domRoot.attr('data-twitter-name'));
				url.addParam('no_wrap', '1');

				$.getJSON(url.getFullUrl(), this.delegate(this.on_twitterFeedResults));
			}
		},

		on_twitterComplete: function(xhr, statusText) {
			if (xhr && xhr.status === 400) {
				this.buildTwitterFeed([{
					text: "Twitter is unavailable right now."
				}]);
			}
		},

		on_twitterFail: function () {
			this.buildTwitterFeed([{
				text: "Twitter is unavailable right now."
			}]);
		},

		on_twitterFeedResults : function(json) {
			if (json.length > 0) {
				this.setTwitterUser(json[0].screen_name);
				this.buildTwitterFeed(json);
			}
		},

		setTwitterUser : function(user) {
/*			this.domRoot.find("h2")
				.prepend("<span>@"+user.screen_name+"</span>")
				.find("a").attr("href","http://www.twitter.com/"+user.screen_name);
			this.domRoot.find(".Feed").before(
				$("<img>").attr("src", user.profile_image_url).addClass("TwitterPicture")
			);*/
		},

		getNiceDateTime : function(datetime) {
			var ago = $.timeago(datetime);
			return ago.indexOf('NaN') >= 0 || !ago.length ? 'Some time ago' : ago;
		},

		buildTwitterFeed : function(json) {
			var feedUL = this.domRoot.find("ul.Feed"),
					i,
					feedItem;

			for (i = 0, len = json.length; i < len; i++) {

/*
				var feedItem = this.buildTwitterFeedItem(json[i].datestamp,
					json[i].tweet_text);

				feedItem.click((function(screen_name, id) {
					return function() {
						var w = window.open(
							'http://www.twitter.com/' +
								screen_name +
								'/statuses/' +
								id,
							'_bl'
						);
						w.focus();
					};
				})(json[i].screen_name, json[i].tweet_id));
*/
				feedItem = this.buildTwitterFeedItem(json[i]);

				feedUL.append(feedItem);

			}

			this.fadeInTwitterFeed();
			this.startFeedCycle();
		},

		buildTwitterFeedItem : function(post) {
//			post.replace(this.urlRegex, "<a href='$1'>$1</a>");	 // linkify everything
			var twitterLink,
					userPattern = '$1<a href="http://twitter.com/$2" rel="nofollow" target="_blank">@$2</a>',
					hashPattern = '$1<a href="http://twitter.com/search/%23$2" rel="nofollow" target="_blank">#$2</a>',
					urlPattern = '$1<a href="http://$2" rel="nofollow" target="_blank">$2</a>',
					postText,
					anchor;

			twitterLink = [
				'http://www.twitter.com',
				post.screen_name,
				'statuses',
				post.tweet_id
			].join('/');

			postText = post.tweet_text.replace(this.userReg, userPattern)
				.replace(this.hashReg, hashPattern)
				.replace(this.urlReg, function(url) {
					var textArr = [], text = "",
							i;

					for (i = 0, l = url.length; i < l; i++) {
						textArr.push(url.charAt(i) + '<wbr />');
					}

					text = textArr.join('');

					return ['<a href="', url, '" rel="nofollow" target="_blank">', text, '</a>'].join('');
				});

			anchor = $('<a>')
				.addClass('TimePosted')
				.attr('href', twitterLink)
				.attr('rel', 'nofollow')
				.attr('target', '_blank')
				.append()
				.append(this.getNiceDateTime(post.datestamp));

			return $("<li>")
				.append(
					$("<div class='Post' />").append(postText)
				)
				.append(anchor);
		},

		fadeInTwitterFeed : function() {
			this.domRoot.find(".LoadingWrap").fadeIn();
		},

		startFeedCycle : function() {
			var thisContext = this,
					n = 0,
					maxN = this.domRoot.find("li").length;

			thisContext.domRoot.find("li").eq(0).fadeIn();
			setInterval(function() {
				thisContext.domRoot.find("li").eq(n).fadeOut(function() {
					n = n < maxN-1 ? n+1 : 0;
					thisContext.domRoot.find("li").eq(n).fadeIn();
				});
			}, 5000);
		}
	}
);

