$(function() {
	$('#s').focus(function(){
		var searchValue = $(this).val();
		if(searchValue == ''){
			$('#searchform label').fadeOut(200);
		}
	});
	$('#s').blur(function(){
		searchValue = $(this).val();
		if(searchValue == ''){
			$('#searchform label').fadeIn(200);
		}
	});

	// Twitter feed
	var K = function () {
		var a = navigator.userAgent;
		return { ie: a.match(/MSIE\s([^;]*)/) }
	}();

	var H = function (a) {
		var b = new Date();
		var c = new Date(a);
		if (K.ie) {
			c = Date.parse(a.replace(/( \+)/, ' UTC$1'))
		}
		var d = b - c;
		var e = 1000,
			minute = e * 60,
			hour = minute * 60,
			day = hour * 24,
			week = day * 7;
		if (isNaN(d) || d < 0) {
			return ""
		}
		if (d < e * 7) {
			return "right now"
		}
		if (d < minute) {
			return Math.floor(d / e) + " seconds ago"
		}
		if (d < minute * 2) {
			return "about 1 minute ago"
		}
		if (d < hour) {
			return Math.floor(d / minute) + " minutes ago"
		}
		if (d < hour * 2) {
			return "about 1 hour ago"
		}
		if (d < day) {
			return Math.floor(d / hour) + " hours ago"
		}
		if (d > day && d < day * 2) {
			return "yesterday"
		}
		if (d < day * 365) {
			return Math.floor(d / day) + " days ago"
		} else {
			return "over a year ago"
		}
	};
	var username = "TheDolinsGroup"; //"conspirator";
	function removeTwitterBox() {
		$('#twitter-content').closest('#twitterWidget').remove();
	}
	$.ajax({
		type: "GET",
		dataType: "json",
		url: "http://search.twitter.com/search.json?q=from:" + username + "&callback=?",
		success: function(data) {
			//console.log(data);
			if (!data.results.length) {
				removeTwitterBox();
			} else {
				var out = '<ul>';
				for (var i = 0; i < 3; i++) {
					var tweet = data.results[i].text;
					tweet = tweet.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url){return '<a href="' + url + '" target="_blank">' + url + '</a>';});
					tweet = tweet.replace(/(^|\s)@(\w+)/g, '$1<a href="http://www.twitter.com/$2" target="_blank">@$2</a>');
					tweet = tweet.replace(/(^|\s)#(\w+)/g, '$1<a href="http://search.twitter.com/search?q=%23$2" target="_blank">#$2</a>');
					tweet += '<div style="color:#999;text-align:right;">';
					tweet += H(data.results[i].created_at);
					tweet += "</div>";
					out += '<li>' + tweet + '</li>';
				};
				out += '</ul>';
				$('#twitter-content').html(out).find('li:last-child').addClass('last');
			}
		},
		error: function(data) {
			removeTwitterBox();
		}
	});
});

