(function() {

var $ = jQuery;

var ecnextjs = {};
ecnextjs.twitter = {};

window.ecnextjs = ecnextjs;

function Control() {
	var me = this;

	me.fetchUserinfo = function(username) {
		var deferred = new SimpleDeferred();
		deferred.getJSON(
			"http://twitter.com/users/show.json?suppress_response_codes=1&callback=?",
			{ screen_name: username }
		);
		return deferred;
	};
	me.fetchTimeline = function(username) {
		var deferred = new SimpleDeferred();
		deferred.getJSON(
			"http://twitter.com/statuses/user_timeline.json?suppress_response_codes=1&callback=?",
			{ screen_name: username }
		);
		return deferred;
	};
}
ecnextjs.twitter.Control = Control;

function Displayer() {
	this.container = undefined;
	this.qt = undefined;

	this.append = function(data) {
		this.container.append(tmpl(this.qt, data));
	};
	this.empty = function() {
		this.container.empty();
	};
	this.replaceContents = function(data) {
		this.empty();
		this.append(data);
	};
}

function TimelineDisplayer(parentSelector, template, maxTweets) {
	this.container = $(parentSelector);
	this.qt = template;
	this.maxTweetsDefault = 5;
	
	this.append = function(data, maxTweets) {
		var me = this;
		if (maxTweets == undefined) { maxTweets = this.maxTweetsDefault; }
		if (data.length > maxTweets) { data.length = maxTweets; }
		$.each(data, function() {
			this.text = twitterLink(this.text);
			this.created_at = relative_time(this.created_at);
			TimelineDisplayer.prototype.append.apply(me, [this]);
		});
	};
}
TimelineDisplayer.prototype = new Displayer;
ecnextjs.twitter.TimelineDisplayer = TimelineDisplayer;

function UserinfoDisplayer(parentSelector, template) {
	this.container = $(parentSelector);
	this.qt = template;
}
UserinfoDisplayer.prototype = new Displayer;
ecnextjs.twitter.UserinfoDisplayer = UserinfoDisplayer;

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();
var tmpl = this.tmpl;

function twitterLink(text) {
	var blink = function(t, h) {
		//return $('<a></a>').text(t).attr('href',h).attr('target','_blank');
		return '<a href="' + h + '" target="_blank">' + t + '</a>';
	};
	var a = text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function (m) {
		return blink(m,m);
	});
	a = a.replace(/@[A-Za-z0-9_]+/g, function (m) {
		m = m.replace(/@/, '');
		return '@' + blink(m, 'http://twitter.com/'+m);
	});
	return a;
}

function SimpleDeferred() {
	this.callbacks = [];
	this.returned = false;
	this.data = undefined;
	this.lastReturn = undefined;
	
	this.addCallback = function(fn) {
		if (this.returned) {
			this.run(fn);
		}
		else {
			this.callbacks.push(fn);
		}
	};
	this.runAll = function () {
		var me = this;
		$.each(this.callbacks, function() {
			me.run(this);
		});
	};
	this.run = function(fn) {
		this.lastReturn = fn.apply(this, [this.lastReturn]);
	};
	this.getJSON = function (url, data) {
		this.returned = false;
		this.data = undefined;
		this.lastReturned = undefined;
		var me = this;
		$.getJSON(url, data, function (d) { me.dataReturned(d); });
		return this;
	};
	this.dataReturned = function(d) {
		this.data = d;
		this.lastReturn = this.data;
		this.runAll();
	};

}

// Borrowed from:
// http://ralphwhitbeck.com/2007/11/20/PullingTwitterUpdatesWithJSONAndJQuery.aspx
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;
}


})();
