//<![CDATA[
(function($) {


$(document).ready(function(){
 
	$.getJSON('http://twitter.com/status/user_timeline/dontpanicevents.json?count=2&callback=?', function(data){
		replaceHtml('tweets','');
		$.each(data, function(index, item){
			$('#tweets').append('<div class="tweet"><p class="tweetText">' + item.text.linkify() + '</p><p class="tweetDate">' + relative_time(item.created_at) + ' from ' + item.source + '</p></div>');
		});
	
	});
	
	function relative_time(time_value) {
	  var values = time_value.split(" ");
	  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	  var parsed_date = Date.parse(time_value);
	  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	  delta = delta + (relative_to.getTimezoneOffset() * 60);
	  
	  var r = '';
	  if (delta < 60) {
		r = 'a minute ago';
	  } else if(delta < 120) {
		r = 'couple of minutes ago';
	  } else if(delta < (45*60)) {
		r = (parseInt(delta / 60)).toString() + ' minutes ago';
	  } else if(delta < (90*60)) {
		r = 'an hour ago';
	  } else if(delta < (24*60*60)) {
		r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
	  } else if(delta < (48*60*60)) {
		r = '1 day ago';
	  } else {
		r = (parseInt(delta / 86400)).toString() + ' days ago';
	  }
	  
	  return r;
	}
	
	String.prototype.linkify = function() {
		return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
			return m.link(m);
		});
	};


/* This is much faster than using (el.innerHTML = str) when there are many
existing descendants, because in some browsers, innerHTML spends much longer
removing existing elements than it does creating new ones. 
Taken from article: http://ajaxian.com/archives/replacehtml-for-when-innerhtml-dogs-you-down
*/
function replaceHtml(el, html) {
        var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
        var newEl = document.createElement(oldEl.nodeName);

		// Preserve the element's id and class (other properties are lost)
        newEl.id = oldEl.id;
        newEl.className = oldEl.className;
        
		// Replace the old with the new
        newEl.innerHTML = html;
        oldEl.parentNode.replaceChild(newEl, oldEl);
        
		/* Since we just removed the old element from the DOM, return a reference
        to the new element, which can be used to restore variable references. */
        return newEl;
};



 







});

} )(jQuery);
//]]>