var tph = {
	graphSelector: "#graph",
	tweeters: [],
	data: [],

	refreshData: function () {
		this.data = [];
		for (i in this.tweeters) {
			var t = this.tweeters[i];
			$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?id=' + escape(t) + '&count=200&callback=?', tph.dataIn);
		}
	},

	formatLabel: function (label) {
		var url = 'http://twitter.com/' + label.replace(/.*\((.*)\)/, '$1');
		return '<a target="_new" href="' + url + '">' + label + '</a>';			 
	},


	refreshGraph: function () {
		$.plot($(this.graphSelector), this.data, 
			{
				xaxis: {mode: "time"},
				legend: {
					show: true, 
					position: "nw",
					labelFormatter: tph.formatLabel
				}
			});
	},

	dataIn: function (tdata) {
		var userSeries = [];		
		var lastHour = 0;
		var cnt = 0;
		var user = tdata[0].user;
		while (t = tdata.pop()) {
			ca = t.created_at.replace(/ \+[0-9]{4}/,'')
			var ut = Date.parse(ca);
			var hour = ut - (ut % (60 * 60 * 1000));
			cnt++;
			if (hour != lastHour && lastHour) {
				if (userSeries.length > 0) {
					curHour = userSeries[userSeries.length - 1][0];
					while (curHour < hour) {
						userSeries.push([curHour, 0]);
						curHour += (60 * 60 * 1000);
					}
				}
				userSeries.push([hour, cnt]);
				cnt = 0;
			}
			lastHour = hour;
		}
		userSeries.push([hour, cnt]);
		tph.data.push({data: userSeries, label: user.name + ' (' + user.screen_name + ')'});
		tph.refreshGraph();
	},


	addTweeter: function (name, refresh) {
		var add = true;
		for (i=0; i<this.tweeters.length; i++) {
			if (this.tweeters[i].toLowerCase() == name.toLowerCase()) {
				add = false;
			}
		}

		if (add) { 
			this.tweeters.push(name); 
			if (refresh) { this.refreshData();}
		}
		else {
			this.warn('You already added that user!');
		}
	},

	warn: function (msg) {
	  alert(msg);
	}
}

$(document).ready(function () {
	$('#tphform form').submit(function () {
		tph.addTweeter($('#addtweeter').val(), true);
		$('#addtweeter').val('');
		return false;
	});

	var initial = $(document).getUrlParam('tweeter');
	if (initial) {
		var users = initial.split(',');
		for (i in users) {
			tph.addTweeter(users[i], false);
		}
		tph.refreshData();
	}

});

