
	var lastEntryTime = 0;

	function showReply(entryEl) {
		var entryId = entryEl.className.split('entry-')[1];		
		$('#inReplyToEntryId')[0].value = entryId;
		$('#replyContent')[0].innerHTML = $(entryEl).find('.entryContentText')[0].innerHTML;
		
		$('#replyContentWrapper').show();
		jQT.goTo('#newPost','slide');
	}
	
	function resetNewPostForm() {
		if($('#replyContentWrapper'))
			$('#replyContentWrapper').hide();

		if($('#inReplyToEntryId')[0])
			$('#inReplyToEntryId')[0].value = '';
			
		$('#tags')[0].value='';
		$('#tagsSelector .curr').removeClass('curr');
		// alert($('#inReplyToEntryId')[0].value);
	}
	
	function sendNewPost(formName) {
		// $('#updateButton').toggle();
		var formEl = $('#'+formName);
		$.ajax({
			type: "POST",
			url: sysUrl+"ajax/",
			data: "ajaxAction=entryPostNew&"+formEl.serialize(),
			success: function(response) {
				if(response != 'ignore')
				{
					if(response == 'false')
						alert('Sorry but there was a problem posting your entry to Staction.');
					else
					{
						$('#inReplyToEntryId')[0].value = '';
						formEl[0].reset();
						refreshStream();
					}
				}
			},
			error: function() {
				alert('Sorry but there was a problem posting your entry to Staction.');
			}
		});
		
		if($('.current.panel')[0].id == 'newPost')
		{
			$('#newPostBackButton').tap();
			// $('#updateButton').toggle();
		}
	}
	
	var isRefreshing = false;
	function refreshStream() {
		if(lastEntryTime == 0 || isRefreshing)
			return;
		else
		{
			isRefreshing = true;
			$.ajax({
				type: "POST",
				dataType: 'json',
				url: sysUrl+"ajax/",
				data: "ajaxAction=refreshStream&lastEntryTime="+encodeURIComponent(lastEntryTime),
				success: function(response) {
					isRefreshing = false;
					$('.entryTimestamp').each(function(idx,ets) {
						$(ets).next('.entryTime')[0].innerHTML = time_since(ets.innerHTML) + ' ago';
					});
					if(response.status == 'empty')
						return;
					else if(response.status == false)
						alert('Sorry but there was a problem refreshing your Staction stream.');
					else
					{
						$('#mainStreamContainer').prepend(response.xhtml);
						// alert($('#newPostBackButton').tap);
						lastEntryTime = response.newLastEntryTime;
						
 						if(response.xhtml.indexOf('incompleteTodo') != -1)
							refreshTodos();
							

					}
					

				},
				error: function() {
					alert('Sorry but there was a problem posting your entry to Staction.');
				}
			});
		}
	}
	
	function refreshStreamClick() {
		// alert('refreshStreamClick');
		refreshStream();
	}

	var isRefreshingTodos = false;
	function refreshTodos() {
		if(isRefreshingTodos)
			return;
		else
		{
			isRefreshingTodos = true;
			$.ajax({
				type: "POST",
				url: sysUrl+"ajax/",
				data: "ajaxAction=refreshTodos",
				success: function(response) {
					isRefreshingTodos = false;
					$('#incompleteTodos .entryTimestamp').each(function(idx,ets) {
						$(ets).next('.entryTime')[0].innerHTML = time_since(ets.innerHTML) + ' ago';
					});
					
					
					if(response == '')
						return;
					else if(response == 'false')
						alert('Sorry but there was a problem refreshing your Staction stream.');
					else
						$('#todosContainer').replaceWith(response);
				},
				error: function() {
					alert('Sorry but there was a problem posting your entry to Staction.');
				}
			});
		}
	}
	
	function toggleTodo(ev, checkboxCSSId, newStatus) {
		ev.stopPropagation();
		var checkbox = $('#todo-'+checkboxCSSId)[0];

		$.ajax({
			type: "POST",
			url: sysUrl+"ajax/",
			data: "ajaxAction=toggleTodo&id="+checkbox.value+'&newStatus='+newStatus,
			success: function(response) {
				if(response != 'ignore')
				{
					if(response == 'false')
						alert('Sorry but there was a problem marking your Todo on Staction.');
					else
					{
						$('.entry-'+checkbox.value).remove();
						refreshStream();
					}
				}
			},
			error: function() {
				alert('Sorry but there was a problem marking your Todo on Staction.');
			}
		});
	}
	
	function switchPanel(panelName) {
		$('#'+panelName).show();
		$('.panel').hide();
	}

	function addTag(el, content) {
		var tagsEl = $('#tags')[0];
		var newValuePrefix = (tagsEl.value != '') ? tagsEl.value+', ' : '';

		var valueToAdd = (typeof(content) != 'undefined') ? content : el.innerHTML;
		
		// if($(el).hasClass('curr'))
		if(el.className.indexOf('curr') != -1)
		{
			tagsEl.value = tagsEl.value.replace(valueToAdd,'');

			tagsEl.value = tagsEl.value.replace(', ,',',');
			if(tagsEl.value == ', ') tagsEl.value   = '';
			if(tagsEl.value[0] == ',') tagsEl.value = tagsEl.value.substr(1,tagsEl.value.length-1);
			tagsEl.value = trimString(tagsEl.value);

			// $(el).removeClass('curr');
			el.className = el.className.replace('curr','');

			return;
		}
		
		// if($(el).hasClass('time'))
		if(el.className.indexOf('time') != -1)
		{
			newValuePrefix = newValuePrefix.replace(/[0-9]{1,2}\:[0-9]{1,2}(\,(\s)?)?/, '');
			$('.time.curr').removeClass('curr');
		}
		
		var finalNewValue = newValuePrefix+valueToAdd;
		tagsEl.value = trimString(finalNewValue);
		
		// $(el).addClass('curr');
		el.className+=' curr';
	}
	
	function showAddTags() 
	{
		var tagsContainer = $('#tagsContainer')[0];
		if(tagsContainer.style.display == 'none')
		{
			$('#newPostForm').addClass('tagsShown');
			$('#addTagsButton').addClass('on');
		}
		else
		{
			$('#newPostForm').removeClass('tagsShown');
			$('#addTagsButton').removeClass('on');
		}

		$('#tagsContainer').toggle();
		
	}

	function trimString(str)
	{
		return str.replace(/^\s*/, "").replace(/\s*$/, "");
	}
	
	// function by Dunstan Orchard, found at 
	// http://www.1976design.com/blog/archive/2004/07/23/redesign-time-presentation/
	// adapted from original code by Natalie Downe
	// http://blog.natbat.co.uk/archive/2003/Jun/14/time_since

	// inputs must be in a format that Date.parse can understand (such as RFC 2822 (Thu, 21 Dec 2000 16:01:07 +0200))
	// newer_date variable is optional
	function time_since(older_date, newer_date)
	{
		// array of time period chunks
		var chunks = 
		[
			[60 * 60 * 24 * 365 , 'year'],
			[60 * 60 * 24 * 30 , 'month'],
			[60 * 60 * 24 * 7, 'week'],
			[60 * 60 * 24 , 'day'],
			[60 * 60 , 'hour'],
			[60 , 'minute']
		];

		// $newer_date will equal false if we want to know the time elapsed between a date and the current time
		// $newer_date will have a value if we want to work out time elapsed between two known dates
		if(typeof(newer_date) == 'undefined')
			var newer_date = Math.round(Date.now()/1000);
 		
		if(typeof(older_date) != 'number')
			older_date = new Date(older_date).getTime()/1000;
		// console.log('Older date: ' + older_date);
		// console.log('Newer date: ' + newer_date);		
	
		// difference in seconds
		since = newer_date - older_date;

		// we only want to output two chunks of time here, eg:
		// x years, xx months
		// x days, xx hours
		// so there's only two bits of calculation below:

		// step one: the first chunk
		for (i = 0, j = chunks.length; i < j; i++)
		{
			seconds = chunks[i][0];
			name = chunks[i][1];

			// finding the biggest chunk (if the chunk fits, break)
			if ((count = Math.floor(since/seconds)) != 0)
				break;
		}


		// set output var
		output = (count == 1) ? '1 '+name : count+' '+name+'s';
		// output = count+name;

		return output;
	}
	

