/**
 * It's the little things
 * Andrew Hedges, andrew@hedges.name
 * Created: 2009-07-05
 */

String.prototype.truncate = function (limit) {
	var bits, i;
	bits = this.split('');
	if (bits.length > limit) {
		for (i = bits.length - 1; i > -1; --i) {
			if (i > limit) {
				bits.length = i;
			}
			else if (' ' === bits[i]) {
				bits.length = i;
				break;
			}
		}
		bits.push('…');
	}
	return bits.join('');
};
// END: String.prototype.truncate

(function () {
	var placeholder;
	
	// do font replacement
	Cufon.replace('h1,h2,h3,p.featured-action,input[type=submit],button');
	Cufon.now();
	
	placeholder = 'The next little thing should be …';
	
	// when the user clicks on the suggest box, the text should clear
	$('#suggest-a-thing textarea[name=thing]').focus(function (evt) {
		if (placeholder === $(this).val()) {
			$(this).val('');
		}
	});
	
	// when the user clicks away from the suggest box, the text should return
	$('#suggest-a-thing textarea[name=thing]').blur(function (evt) {
		if ('' === $(this).val()) {
			$(this).val(placeholder);
		}
	});
	
	// ajaxify the suggest box
	$('#suggest-a-thing').submit(function (evt) {
		var form, thanks, error;
		form   = $(this);
		thanks = $('#thanks-for-thing');
		error  = $('#suggest-a-thing-error');
		$.post(form.attr('action'), form.serialize(), function(response) {
			if ('OK' === response) {
				form.hide();
				error.hide();
				thanks.show();
			}
			else {
				thanks.hide();
				error.show();
			}
		});
		evt.preventDefault();
	});
	
	// ajaxify the ratings
	$('.rating > li > a').click(function (evt) {
		var a, url, id;
		a   = $(this);
		if (!a.hasClass('selected')) {
			url = a.attr('href');
			id  = url.split('id=');
			id  = 'undefined' !== typeof id[1] ? id[1] : 0;
			$.get(url, '', function (response) {
				if ('OK' === response) {
					$('.rating > li > a').removeClass('selected');
					a.addClass('selected');
					// update the aggregate ratings
					$.get('/wp-content/themes/itlt/rating-results.php?id=' + id, '', function (response) {
						if ('ERROR' !== response) {
							$('#rating-results').fadeOut('slow', function () {
								$('#rating-results')
									.html(response)
									.fadeIn('slow')
								;
							});
						}
					});
				}
			});
		}
		evt.preventDefault();
	});
	
	// code below borrowed from http://blabalong.us (a site also written by me!)
	var tweet, actions, rgxps, repls, wwwer, linker, hasher, link, prepareJSON;
	
	tweet = jsontemplate.Template((function () {
		var t;
		t  = '{.repeated section @}';
		t += 	'<li>';
		t += 		'<span class="tweet">{text}</span><br>';
		t += 		'<div>';
		t += 			'<em>{created_at}</em>';
		t += 			' | {retweet}';
		t += 		'</div>';
		t += 	'</li>';
		t += '{.end}';
		return t;
	})());
	// END: tweet
	
	actions = {
		retweet   : jsontemplate.Template('<a href="http://twitter.com/home?status=RT%20@ITLT%20{retweet}">Retweet</a>')
	};
	// END: actions
	
	rgxps = {
		ats  : /(?:@([A-Za-z0-9_]+))/gim,
		hash : /(?:#([A-Za-z0-9_]+))/gim,
		www  : /\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/gim
	};
	// END: rgxps
	
	repls = {
		ats  : jsontemplate.Template('@<a href="http://twitter.com/{p1}">{p1}</a>'),
		hash : jsontemplate.Template('#<a href="http://twitter.com/search?q=%23{p1}">{p1}</a>'),
		www  : jsontemplate.Template('<a href="{p1}">{p1}</a>')
	};
	// END: repls
	
	wwwer = function (p1, offset) {
		if (p1.indexOf('http://') < 0) {
			p1 = 'http://' + p1;
		}
		return repls.www.expand({p1:p1});
	};
	// END: wwwer
	
	linker = function (str, p1, offset) {
		return repls.ats.expand({p1:p1});
	};
	// END: linker
	
	hasher = function (str, p1, offset) {
		return repls.hash.expand({p1:p1});
	};
	// END: hasher
	
	link = function () {
		$.each($('ul.tweets li .tweet'), function () {
			var li, html;
			li   = $(this);
			html = li.html();
			html = html.replace(rgxps.www, wwwer);
			html = html.replace(rgxps.ats, linker);
			html = html.replace(rgxps.hash, hasher);
			li.html(html);
		});
	};
	// END: link
	
	prepareJSON = function (json) {
		json = json || [];
		
		$.map(json, function (item) {
			var retweet, created_at;
			if (null === item.text) {
				item.text = '';
			}
			retweet      = encodeURIComponent(item.text.truncate(125));
			item.retweet = actions.retweet.expand({retweet:retweet});
			created_at   = (function () {
				var date, str;
				date = new Date(item.created_at * 1000);
				return date.getDate() + ' ' + ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][date.getMonth()] + ' ' + date.getFullYear();
			})();
			item.created_at = created_at;
			return item;
		});
		
		return json;
	};
	// END: prepareJSON
	
	// populate the "latest tweets" list
	$.getJSON('/tweets.php', '', function (json) {
		var html;
		json = prepareJSON(json);
		html = tweet.expand(json);
		$('ul.tweets').html(html);
		// link up @replies and #hashtags
		setTimeout(link, 0);
	});
})();

