
function loadTwitter(username, store) {
	//http://www.quietless.com/kitchen/format-twitter-created_at-date-with-javascript/
	var parseTwitterDate = function(text) {
		var newtext = text.replace(/(\+\S+) (.*)/, '$2 $1'),
			date = new Date(Date.parse(newtext)).toLocaleDateString(),
			time = new Date(Date.parse(newtext)).toLocaleTimeString();
		return date + ' at ' + time;
	},
	replace_tweets = function(text) {
		text = text.replace(/(https?:\/\/([-\w\.]+)+(\/([\w\/_\-\.]*(\?\S\-+)?(#\S+)?)?)?)/g, '<a target="_blank" href="$1">$1</a>')
			.replace(/@(\w+)/g, '<a target="_blank" href="http://twitter.com/$1">@$1</a>')
			.replace(/\s#(\w+)/g, ' <a target="_blank" href="http://search.twitter.com/search?q=%23$1">#$1</a>');
		return text;
	},
	showTweets = function(item) {
		$('#tweets').html(
			Template.replace(Template.get('#twitter_tmpl'), item).trim()
		);
	},
	url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+username+"&count=1&trim_user=1";

	if (store.get(url) ) {
		showTweets( JSON.parse(store.get(url)) );
	} else {
		$('#tweets').html('');
		$.ajax({
			url:url,
			success:function(data, textStatus) {
				//test textStatus for a good return value
				for (var i in data) {
					var item = data[i];
					item.created_date = parseTwitterDate(item.created_at);
					item.text = replace_tweets(item.text);

					store.put(url, JSON.stringify(item), 5*60);
					showTweets(item);
				}
			},
			dataType:'jsonp'
		});
	}
}

var Template = {
	_cache: {},
	get: function(selector) {
		if (!Template._cache[selector]) {
			Template._cache[selector] = $(selector).html().replace('<!--<![CDATA[', '').replace(']]>-->', '');
		}
		return Template._cache[selector];
	},
	replace: function(template, params, prefix) {
		//pr('Template.replace(template, params, prefix)', template, params, prefix);
		prefix = (prefix ? prefix + '.' : '');
		var param, obj_type;
		for(param in params) {
			obj_type = typeof(params[param]);
			if (params[param] !== null
			&& params[param] !== undefined
			&& ((obj_type != 'object' && template.indexOf("{" + prefix + param + "}") >= 0) || obj_type == 'object')
			) {
				if (obj_type == 'object') {
					template = Template.replace(template, params[param], prefix + param);
				} else if (obj_type == 'function') {
					template = template.split("{" + prefix + param +"}").join(params[param]());
				} else {
					template = template.split("{" + prefix + param +"}").join(params[param]);
				}
			}
		}
		return template;
	}
};

(function(){
	function supports_html5_storage() {
		try {
			return 'localStorage' in window && window["localStorage"] !== null;
		} catch (e) {
			return false;
		}
	}
	function Store() {
		this.appendTo = function(key, val, cacheDuration) {
			var arr = (this.get(key) || []);
			arr.push(val);
			this.put(key, arr, cacheDuration);
		}
		this.now = function() {
			return parseInt((new Date).getTime() / 1000, 10); //time in seconds (as an int)
		}
		this.fire = function(key, action, oldVal, newVal) {
			var event = key + '.' + action,
			data = {oldVal:oldVal, newVal:newVal};
			//console.debug("Trigger:", event, data);
			$(this).trigger(event, data);
		}
	}

	getStore = function() {
		return supports_html5_storage() ? new LocalStore() : new JSStore();
	}

	var LocalStore = function() {};
	LocalStore.prototype = new Store();
	LocalStore.prototype.get = function(key) {
		var expiresTime = localStorage.getItem(key + '_expires');

		if (expiresTime == null || parseInt(expiresTime, 10) > this.now()) {
			return JSON.parse(localStorage.getItem(key));
		} else {
			localStorage.removeItem(key);
			localStorage.removeItem(key + '_expires');
			return null;
		}
	}
	LocalStore.prototype.put = function(key, val, cacheDuration) {
	if (cacheDuration > 0) {
		localStorage.setItem(key + '_expires', this.now() + cacheDuration);
	}

	var oldVal = this.get(key);
		localStorage.setItem(key, JSON.stringify(val));
		(oldVal ? this.fire(key, 'change', oldVal, val) : this.fire(key, 'add', null, val));
	}
	LocalStore.prototype.remove = function(key) {
		var oldVal = this.get(key);
		localStorage.removeItem(key);
		this.fire(key, 'remove', oldVal, null);
	}
	LocalStore.prototype.clear = function() {
		localStorage.clear();
		this.fire('*', 'clear', null, null);
	}

	var JSStore = function() {};
	JSStore.prototype = new Store();
	JSStore.prototype.data = {};
	JSStore.prototype.get = function(key) {
		return this.data[key] || null;
	}
	JSStore.prototype.put = function(key, val) {
		var oldVal = this.get(key);
		this.data[key] = val;
		(oldVal ? this.fire(key, 'change', oldVal, val) : this.fire(key, 'add', null, val));
	}
	JSStore.prototype.remove = function(key) {
		var oldVal = this.get(key);
		unset(this.data[key]);
		this.fire(key, 'remove', oldVal, null);
	}
	JSStore.prototype.clear = function() {
		this.data = {};
		this.fire('*', 'clear', null, null);
	}
})();

if (!String.prototype.trim) {
	String.prototype.trim = function() {
		return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	};
}

