(function() {
	var UpdatePanel = {
		init : function(options) {
			this.options = $.extend({
				interval : 5000,
				number : 3,
				hijackTweet : false
			}, options);

			this.updater();
		},

		updater : function() {
			(function updateBox() {
				this.timer = setTimeout(function() {
					updateIt();
					updateBox();
				}, UpdatePanel.options.interval);
			})();

			// get the ball rolling
			updateIt();

			function updateIt() {
				$.ajax({
					type : 'GET',
					url : UpdatePanel.options.url,
					dataType : 'jsonp',

					error : function() {
					},

					success : function(results) {
						var theTweets = '',
								elem = UpdatePanel.options.elem.empty();

						$.each(results.results, function(index, tweet) {
							if (UpdatePanel.options.hijackTweet) {
								tweet.text = tweet.text.replace(/(Justin )?Bieber/ig, 'Nettuts');
							}

							var user_avatar = 'http://api.twitter.com/1/users/profile_image/' + tweet.from_user + '.png';

							tweet.text = tweet.text.replace(/(http:\/\/[a-z\.A-Z\-0-9\/]*)/, '<a href="$1" target="_blank">[link]</a>');
							tweet.text = tweet.text.replace(/@([A-Za-z_\-0-9]*)/, '<a href="http://twitter.com/$1" target="_blank">@$1</a>');
							tweet.text = tweet.text.replace(/#([A-Za-z_\-0-9]*)/, '<a href="https://twitter.com/#!/search/%23$1" target="_blank">#$1</a>');

//							console.log(tweet);

							if (index === UpdatePanel.options.number) {
								return false;
							}
							else {
								theTweets += '<li> <img src="' + user_avatar + '"  alt="avatar" class="avatar"> ' + tweet.text + ' <br /> <small><a href="http://twitter.com/' + tweet.from_user + '">@' + tweet.from_user + '</a></small></li>';
							}
						});
						elem.append(theTweets);
					}
				});
			}
		},

		clearUpdater : function() {
			clearTimeout(this.timer);
		}
	};
	window.UpdatePanel = UpdatePanel;
})();

UpdatePanel.init({
	interval : 1000,
	number : 8,
	url : "http://search.twitter.com/search.json?q=auratemple",
	elem : $('#tweets')
});
