/* jslint verified 2009.02.16 */
/*jslint browser: true, onevar: true, undef: true, white: false, eqeqeq: true */
/*global document, $, $$, Ajax, DateHelper */

var Tweets = function () {
	var self = {
			// parsing code from http://forum.cmsmadesimple.org/index.php/topic,29083.new/spam,true.html
			// parses all Twitter hashtags, URLs and usernames
			// view the example here http://www.simonwhatley.co.uk/examples/twitter/prototype/
			parseURL: function (str) {
				return str.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g,
					function (url) { return '<a href="'+url+'">'+url+'</a>'; });
			},
			parseUsername: function (str) {
				return str.replace(/[@]+[A-Za-z0-9-_]+/g,
					function(u) {
						var username = u.replace("@",""),
							url = "http://twitter.com/"+username.toLowerCase();
						return '<a href="'+url+'">'+'@'+username+'</a>';
					});
			},
			parseHashtag: function (str) {
				return str.replace(/[#]+[A-Za-z0-9-_]+/g,
					function(t) {
						var tag = t.replace("#","%23"),
							url = "http://search.twitter.com/search?q="+tag.toLowerCase();
						return '<a href="'+url+'">'+t+'</a>';
					});
			},
			show: function (response) {
				var tweets = response.results,
					box = $('tweets'), short = $('shortlink'),
					i, tweetBox, tsrc, span, text;
				short = short ? short.href : 'http://tra.kz/';
				box.stylify('fontFamily', "'Lucida Grande',sans-serif");
				if (tweets.length > 0) {
					for (i = 0; i < tweets.length; ++i) {
						text = self.parseHashtag(self.parseUsername(self.parseURL(tweets[i].text)));
						tweetBox = box.create('div').classify('tweet');
						tsrc = 'https://twitter.com/'+tweets[i].from_user.toLowerCase();
						tweetBox.create('span').classify('img').
							create('a').attrib('href', tsrc).
								create('img').attrib('src', tweets[i].profile_image_url);
						span = tweetBox.create('span').classify('text');
						span.create('strong').
								create('a').update(tweets[i].from_user).attrib('href', tsrc);
						span.append(' '+text);
						span.create('span').classify('action').
							create('a').update('reply').attrib('href', "http://twitter.com/home?status=@" + tweets[i].from_user + ' ' + short + "%20").
							parentNode.textify(' | ').
							create('a').update('retweet').attrib('href', 'http://twitter.com/home?status=RT @'+tweets[i].from_user+': '+tweets[i].text).
							parentNode.textify(' | ').
							create('a').update('message').attrib('href', "http://twitter.com/home?status=d " + tweets[i].from_user + ' ' + short + "%20").
							parentNode.textify(' | ').
							create('a').update('tra.kz tweets from @' + tweets[i].from_user).attrib('href', '/u/'+encodeURIComponent(tweets[i].from_user));
						span.create('span').classify('time').
							create('a').attrib('href', 'http://twitter.com/'+tweets[i].from_user+'/status/'+tweets[i].id).
								update(DateHelper.time_ago_in_words_with_parsing(tweets[i].created_at)).parentNode.
							append(' from ' + tweets[i].source.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"'));
						if (isset(typeof(tweets[i].to_user))) {
							span.getElementsByClassName('time', 'span')[0].
								append(' ').create('a').update('in reply to ' +tweets[i].to_user).attrib('href', 'http://search.twitter.com/search?from='+tweets[i].to_user+'&rpp=1&max_id='+tweets[i].id);
						}
					}
				} else {
					box.update('<div id="initShare"><div id="messaging">'+
					"\n" + '<div class="header">What is tra.kz?</div>' +
					"\n" + '<ul>' +
						"\n" + '<li><b>tra.kz</b> connects artists with their fan communities on Twitter to promote music and related content</li>' +
						"\n" + '<li><b>tra.kz</b> is how fans and members of the Twitter community share music and cool music content</li>' +
						"\n" + '<li class="last">Music brings peace, love, and happiness, so share it, spread it, and <b>tra.kz</b> it!</li>' +
					"\n" + '</ul>' +
				"\n" + '</div></div>');
				}
				window.addLoad(function () {
					try { $('footer').stylify('paddingTop', '0px'); } catch (e) { }
				});
			}
		};
	return self;
}();

var DateHelper = {
	// from http://gist.github.com/58761, adapted by Jordan Harband 2009.02.16
	// Takes the format of "Jan 15, 2007 15:45:00 GMT" and converts it to a relative time
	// Ruby strftime: %b %d, %Y %H:%M:%S GMT
	time_ago_in_words_with_parsing: function(from) {
		var date = new Date();
		date.setTime(Date.parse(from));
		return this.time_ago_in_words(date);
	},
	time_ago_in_words: function(from) {
		return this.distance_of_time_in_words(new Date(), from);
	},
	distance_of_time_in_words: function(to, from) {
		var distance_in_seconds = ((to - from) / 1000),
			distance_in_minutes = Math.floor(distance_in_seconds / 60),
			words;

		if (distance_in_minutes === 0) { words = 'less than a minute ago'; }
		else if (distance_in_minutes === 1) { words = 'a minute ago'; }
		else if (distance_in_minutes < 45) { words = distance_in_minutes + ' minutes ago'; }
		else if (distance_in_minutes < 90) { words = 'about 1 hour ago'; }
		else if (distance_in_minutes < 1440) { words = 'about ' + Math.floor(distance_in_minutes / 60) + ' hours ago'; }
		else if (distance_in_minutes < 2880) { words = '1 day ago'; }
		else if (distance_in_minutes < 43200) { words = Math.floor(distance_in_minutes / 1440) + ' days ago'; }
		else if (distance_in_minutes < 86400) { words = 'about 1 month ago'; }
		else if (distance_in_minutes < 525960) { words = Math.floor(distance_in_minutes / 43200) + ' months ago'; }
		else if (distance_in_minutes < 1051199) { words = 'about 1 year ago'; }
		else { words = 'over ' + Math.floor(distance_in_minutes / 525960) + ' years ago'; }

		return words;
	}
};