loadTimeline = function() {
	// append a script tag to the DOM which will load a user's timeline
	console.log("Loading page ", offset);
	
	var username = Ext.get('username').dom.value;
	username = username.replace(/[#@]/, '');
	if (username) {
		window.username = username;
		location.hash = ('#' + username);
		if (username) {
		
			Ext.ux.JSONP.request('http://twitter.com/statuses/user_timeline.json', {
				params: {
					count: 200
					,page: window.offset
					,screen_name: username
				}
				,callbackKey: 'callback'
				,callback: timelineCallback
			})
			
		}				
	}
}

tpls = {
	list: new Ext.Template('<li class="{evenodd}">{text}</li>')
	,desc: new Ext.Template("@{name} has {count} perfect {tweets} out of {length} total. That's {percent}%!")
	,loading: new Ext.Template("Loaded {length} tweets...")
}

addTweets = function (tweets) {
	Ext.each(tweets, function (t) {
		tweetStore[tweetStore.length] = t;
	});
}

resetDisp = function () {
	window.tweetStore = [];
	window.offset = 1;	// pages start at page 1 for some reason
	Ext.get('description').update('');
	Ext.get('perfectList').update('');
};

hideLoading = function () {
	Ext.get('loading').setVisible(false, true);
}

showLoading = function () {
	Ext.get('loading').setVisible(true, true);
}

timelineCallback = function (timeline) {
	addTweets(timeline);
	
	if (timeline.length < 200 || window.offset == 15) {
		// no more available
		update();
	} else {
		// there are probably more
		window.offset++;
		loadTimeline();
		tpls.loading.overwrite(Ext.get('description'), {length: tweetStore.length});
	}
}

window.update = function () {
	var perfect = 0, pts = [], desc = {}, listDiv = Ext.get('perfectList');
	listDiv.update('');
	var n = 1;
	Ext.each(window.tweetStore, function (t, i) {
		if (t.text.length == 140) {
			perfect++;
			pts.push(t);
			t.evenodd = (n = 1 - n) ? 'dim' : '';
			tpls.list.append(listDiv, t);
		}
		desc = {
			count: perfect
			,name: username
			,percent: Math.ceil((perfect / tweetStore.length) * 100)
			,tweets: (perfect == 1) ? 'tweet' : 'tweets'
			,length: tweetStore.length
		}
		tpls.desc.overwrite(Ext.get('description'), desc);
	});
	
	hideLoading();
}

Ext.onReady(function () {

	window.resetDisp();
	var fn = function (cmp) {
		resetDisp();
		loadTimeline(Ext.get('username').dom.value);
		showLoading();
	};
	Ext.get('go').on('click', fn);
	Ext.get('username').on('keypress', function (e) {
		if (e.getKey() == 13) {fn();}
	});
	
});