//http://search.twitter.com/search.atom?q=from%3AdePriet
//http://api.twitter.com/1/statuses/user_timeline.atom?screen_name=dePriet
/**
 * @author 		Serve it V.O.F.
 * @copyright	Copyright (c) Serve it V.O.F. 2010
 */
Ext.ns("Twitter");
Twitter.Feed = Ext.extend(Ext.util.Observable, {
	screen_name: "oldbasics",
	elId: "divTwitter",

	arrTweets: [],
	taskId: null,
	tweetDuration: 3000,
	tweetEffect: 2000,

	constructor: function(config) {
		Ext.apply(this, config || {});

		Twitter.Feed.superclass.constructor.call(this, config);
	},

	getTweets: function() {
		var _this = this;
		this.arrTweets = [];

		var url = 'http://twitter.com/status/user_timeline/'+this.screen_name+'.json?count=2&callback=?';

		$.getJSON(url, function(arrData) {
			$.each(arrData, function(i) {
				_this.arrTweets.push({
					id: this.id_str,
					text: this.text
				});
			});

			_this.updateView.call(_this);
		});

		this.updateView.call(this);
	},

	updateView: function() {
		var _this = this;

		var $div = $("#" + this.elId).html("");
		if (this.taskId != null) clearInterval(this.taskId);

		$.each(this.arrTweets, function(i) {
			$("<div class='tweet'>" + _this.parseTweet(this.text) + "</div>").data("tweet_id", this.id).appendTo($div);
		});

		$div.find("div.tweet:first-child").show();

		if (this.arrTweets.length > 1) {
			var $cur, $next;
			this.taskId = setInterval(function() {
				$cur = $div.find("div.tweet:visible");
				$next = $div.find("div.tweet:visible").next("div.tweet");

				$cur.animate({
					"margin-top": "-77px"
				}, _this.tweetEffect, function() {
					$(this).css({
						"margin-top": "77px",
						"display": "none"
					});
					$(this).appendTo($div);
				});

				$next.css({
					"display": "block",
					"margin-top": "77px"
				}).animate({
					"margin-top": "0px"
				}, _this.tweetEffect);

				//clearInterval(_this.taskId);
			}, this.tweetDuration + this.tweetEffect);
		}
	},

	parseTweet: function(str) {
		// URL
		var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
		str = str.replace(regexp,"<a href=\"$1\" target=\"_blank\">$1</a>");

		// User
		regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
		str = str.replace(regexp,"<a href=\"http://twitter.com/$1\" target=\"_blank\">@$1</a>");

		// Hash
		regexp = / [\#]+([A-Za-z0-9-_]+)/gi;
		str = str.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all" target=\"_blank\">#$1</a>');

		return str;
	}
});

$(document).ready(function() {
	var objFeeds = new Twitter.Feed();
	objFeeds.getTweets();
});
