function limitField(field, char_limit, line_limit) {
	
	Event.observe(field, 'keypress', function(e) { 
		var el = Event.element(e); 
		if (e.target.rows && e.target.rows == 1 && e.keyCode == 13) {
		  Event.stop(e);
		}
		if (char_limit - el.value.length == 0) {
			if (![8, 9, 13, 27, 37, 38, 39, 40, 46, 36, 35, 33, 34, 45].include(e.keyCode)) {
				Event.stop(e);
			}
		}
	});
	
	Event.observe(field, 'keyup', function(e) {
		setUnloadWarning();
		updateCharCount(Event.element(e), char_limit);
		updateLineCount(Event.element(e), line_limit);
	});
	
	Event.observe(field + '_char_limit', 'change', function(e) {
		el = Event.element(e);
		if (el.value == '0') {
			el.addClassName('warning');
		} else {
			el.removeClassName('warning');
		}
	});
	
	Event.observe(field + '_line_limit', 'change', function(e) {
		el = Event.element(e);
		if (el.value == '0') {
			el.addClassName('warning');
		} else {
			el.removeClassName('warning');
		}
	});
	
	updateCharCount($(field), char_limit);
	updateLineCount($(field), line_limit);
}

function updateCharCount(textarea, limit) {
	charsLeft = limit - textarea.value.length; 
	$(textarea.id + '_char_limit').value = charsLeft;
  $(textarea.id + '_char_label').update('character' + (charsLeft == 1 ? '' : 's') + ' ');
	setWarning($(textarea.id + '_char_limit'));
}

function updateLineCount(textarea, limit) {
	// Count the number of carriage returns
	if (match = textarea.value.match(/\r?\n/g)) {
		linesLeft = limit - match.length;
	} else {
		linesLeft = limit;
	}
	
	// Long lines get wrapped and create newlines
	textarea.value.split(/\r?\n/).each(function(str) {
		linesLeft -= parseInt(str.length / textarea.cols);
	});
	
	// Prevent negative value
	if (linesLeft < 0) linesLeft = 0;
	
	$(textarea.id + '_line_limit').value = linesLeft;
  $(textarea.id + '_line_label').update('line' + (linesLeft == 1 ? '' : 's') + ' ');
	setWarning($(textarea.id + '_line_limit'));
}

function setWarning(el) {
	if (el.value == 0) {
		el.addClassName('warning');
	} else {
		el.removeClassName('warning');
	}
}

function checkAll(el) {
	$$('#' + el + ' input[type=checkbox]').each(function(box) {
		box.checked = true;
	});
}

function uncheckAll(el) {
	$$('#' + el + ' input[type=checkbox]').each(function(box) {
		box.checked = false;
	});
}
