var path = 'http://www.sketchjobs.com/tell'

$(".count").ready(function()
{
	try
	{
		var currentLength = $("textarea").val().length;
		var max = parseInt($(".count").html());
		displayLimit(currentLength, max);
	} catch (e) {}
});

function limit(elem, max)
{
	var currentLength = elem.value.length;
	displayLimit(currentLength, max);
}

function displayLimit(currentLength, max)
{
	$(".count").css("visibility", "visible");

	if (currentLength > max)
	{
		$(".count").css("color", "#900");

		var num = currentLength - max;
		var plural = (num != 1) ? " characters" : " character";
		$(".count").html('You are ' + num + plural + ' over the limit');
	}
	else
	{
		$(".count").css("color", "#000");

		var num = max - currentLength;
		var plural = (num != 1) ? " characters" : " character";
		$(".count").html('You have ' + num + plural + ' remaining');
	}
}

function rateDown(id)
{
	jQuery.get(path + '/lame/' + id, '', updateDown, 'text');
}

function rateUp(id)
{
	jQuery.get(path + '/juicy/' + id, '', updateUp, 'text');
}

function updateUp(data, textStatus)
{
	var parts = data.split(':');
	$('#lame' + parts[0]).text(parts[2]);
	$('#juicy' + parts[0]).text(parts[1]);
}

function updateDown(data, textStatus)
{
	var parts = data.split(':');
	$('#lame' + parts[0]).text(parts[2]);
	$('#juicy' + parts[0]).text(parts[1]);
}

function deleteComment(id)
{
	jQuery.get(path + '/delete-comment/' + id, '', removeComment, 'text');
}

function removeComment(data, textStatus)
{
	if (textStatus === 'success')
	{
		var currentComment = 'comment' + data;
		var displayNumber = parseInt($('#' + currentComment + ' .comment-number').text());

		$('#' + currentComment).slideUp('slow');

		$('#num-comments').fadeOut('fast', function()
		{
			$(this).text(parseInt($(this).text()) - 1);
			$(this).fadeIn('fast');
		});

		while ($('#' + currentComment).next().text() != '')
		{
			currentComment = $('#' + currentComment).next().attr('id');
			$('#' + currentComment + ' .comment-number').fadeOut('fast', function()
			{
				$(this).text(displayNumber++);
				$(this).fadeIn('fast');
			});
		}
	}
}
