

$(document).ready(function() {

	$("#navlist li").hover(
	  function () {
	    $(this).addClass("hover");
	  },
	  function () {
	    $(this).removeClass("hover");
	  }
	);
	
	var limit = 3000, factor = 25;
	
	$('.idc-new:not textarea, .idc-reply textarea').live('focus', function() {
		var form = $(this).parents('.idc-new, .idc-reply').addClass('ready');
		var title = form.children('h3, p').first();
		
		if (title.children('span').length) return;
		
		var status = $('<span />').appendTo(title);
		var message = form.find('textarea');
		
		var reply_button = form.find('.idc-btn_l');
		var reply_action = reply_button.attr('href');
		var reply_disable = function() {
			reply_button.attr('href', '#');
			reply_button.bind('click', function() {
				return false;
			});
		};
		var reply_enable = function() {
			reply_button.attr('href', reply_action);
			reply_button.unbind('click');
		};
		
		var update = function() {
			var length = limit - message.get(0).value.length;
			
			status.html(' (' + length + ' characters remaining)');
			status.appendTo(title);
			
			if (length < 0) {
				status.css('color', 'rgb(255, 0, 0)');
				reply_disable();
			}
			
			else if (length <= (limit - factor)) {
				var colour = (255 * ((0 - (length - factor)) / factor)).toFixed();
				
				status.css('color', 'rgb(' + colour + ', 0, 0)');
				reply_enable();
			}
			
			else {
				status.css('color', 'rgb(0, 0, 0)');
				reply_enable();
			}
		};
		
		message.bind('change', update);
		message.bind('keypress', update);
		message.bind('keyup', update);
		
		setTimeout(update, 100);
	});
});
