var UserView = (function(){
	
	var previousBio = '';
	
	function save ()
	{
		$('div.bio span.info').text('(Saving... Please wait.)');
		var value = $('div.bio input').hide().val();
		if (value == previousBio) {
			$('div.bio a[rel="editable"]').show();
			$('div.bio span.info').text('(Click to edit)');
			return;
		}
		$.postJSON('/json/bio', {bio: value, session: _session}, updateBio);
	}
	
	function updateBio(json)
	{
		if (json.status == 'ERROR') {
			$('div.bio span.info').text(json.message).css('color', 'red');
			return;
		}
		var value = $('div.bio input').val();
		$('div.bio a[rel="editable"]').text(value).show();
		$('div.bio span.info').text('(Click to edit)');
	}
	
	return {
		
		makeEditable: function()
		{
			
			$('div.bio a[rel="editable"]')
				.wrapInner('<span class="text"></span>')
				.after(' <span class="info">(Click to edit)</span>')
				.after('<input class="ajax" style="display:none;" maxlength="140" />')
				.bind('click', function ()
					{
						var val = $(this).hide().text();
						
						$('div.bio span.info').text('(Press return to finish)');
						$('div.bio input').show().bind('keypress', function (e) {
							if (e.keyCode == 13) { this.blur(); } // ENTER KEY
						}).bind('blur', function () { save(); } ).val(val).get(0).focus();
						
						return false;
					});
			previousBio = $('div.bio input').val();
			return true;
		}
		
	};
	
})();

$(function () {
	UserView.makeEditable();
});