dojo.require("dojo.io.script");
dojo.declare("twitter", null, {
	imgUrl: window.siteroot + "wp-content/themes/clubajax/img/logo_32.png",
	baseClass:"twitWidget",
	headContent:"",
	constructor: function(options, node){
		this.domNode = node;
		dojo.addClass(this.domNode, this.baseClass);
		this.loadFeed();
	},

	parse: function(data){
		//console.dir(data.query.results.entry);
		//console.log("items:", data.query.results);
		var rows = "";
		dojo.forEach(data.query.results.statuses.status, function(m){
			var dateStr = this.getTimePhrase(m.created_at);
			var link = '<a class="timeStamp" href="#">'+dateStr+'</a>'
			var str = m.text;
			str = str.replace(/http\S*(\s|$)/gi, function(s){
				s = dojo.trim(s);
				return '<a href="'+s+'" target="_blank">'+s+'</a>';
			});
			str = str.replace(/clubajax:/gi, function(s){
				return '<a class="twitterer" href="http://twitter.com/clubajax" target="_blank">'+s+'</a>';
			});

			var thumb = '<div class="thumb"><img src="'+this.imgUrl+'" /></div>'
			var content = '<div class="twitContent">'+str +" "+ link +'</div>';
			rows += '<div class="twitRow">' + content + '</div>';

		}, this);
		dojo.query(".tweets", this.domNode)[0].innerHTML = '<div class="page">' + rows + '</div>';
	},
	loadFeed: function(){
		//console.warn("load twitter feed...")
		var query = "select * from twitter.user.timeline where id='clubajax'";
		var url = "http://query.yahooapis.com/v1/public/yql";
		var self = this;
		window.handleResult = function(data){
			self.parse(data);
		}
		dojo.io.script.get({
			url:url,
			content:{
				q:query,
				format:"json",
				callback:"handleResult",
				env:"http://datatables.org/alltables.env"
			}
		});
	},

	getDateObj: function(dateStr){
		//var dateStr = "2009-06-29T20:44:46+00:00"
		//              "Tue Jun 01 13:47:43 +0000 2010"

		return new Date(dateStr);
	},

	getTimePhrase: function(dateStr){
		var d = this.getDateObj(dateStr);
		var ms = Math.ceil((new Date().getTime() - d.getTime())/1000);

		var MIN = 60,
			HR = 3600,
			DAY = 86400,
			PRE = " about ",
			POST = " ago",
			str, tm, type;

		if(ms <= MIN){
			// within the minute
			str = "one minute"
			tm = 1;
			type = "minute";
		}else if(ms < HR){
			// within the hour
			tm = Math.round(ms/MIN);
			type = "minute";
		}else if(ms < DAY){
			// within the day
			tm = Math.round(ms/HR);
			type = "hour";
		}else{
			// days
			tm = Math.round(ms/DAY);
			type = "day";
		}
		type = tm==1 ? type : type + "s";
		var res = PRE + tm +" "+ type + POST;
		//console.log("   ", res);
		return res;
	}
});
dojo.addOnLoad(function(){
	new twitter({}, dojo.byId("twitterFeed"))
});

