/*
 * jQuery Character Counter plugin v0.3
 *
 * http://www.jesse-dawson.com
 *
 * Copyright (c) 2009 Jesse Dawson
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

;(function($) {
	
	// Default options
	var defaults = {
		// Max # of characters
		max: 200,
		// Text & border color of counter
		color: '#666666',
		// Background color of count indicator
		backgroundColor: '#dddddd'
	};
	
	$.fn.charcount = function(options)
	{
		// private variables
		options = $.extend({}, defaults, options);
		
		// private functions
		var show = function(e) 
		{
			var textEl = $(this),
				countEl = textEl.data('charcount').el;
			
			countEl.show();
		};
		
		var hide = function(e)
		{
			var textEl = $(this),
				countEl = textEl.data('charcount').el;
				
			countEl.hide();
		};
		
		var limit = function(e)
		{
			var textEl = $(this),
				max = textEl.data('charcount').max,
				count = textEl.val().length,
				key = e.keyCode || e.which;
				
			if (count >= max && !e.ctrlKey && !e.altKey && (key > 50 || key == 32 || key == 0 || key == 13)) {
				return false;
			}
		};
		
		var update = function(e)
		{
			var textEl = $(this),
				data = textEl.data('charcount'),
				countEl = data.el,
				max = data.max,
				count = textEl.val().length;

			// Cut off any excess length (if key held down)
			if (count > max) {
				textEl.val(textEl.val().substr(0, max));
				count = max;
			}
			
			countEl.html(count + ' used');
			position(textEl, countEl);
		};
		
		var position = function(textEl, countEl)
		{
			countEl.css({
				'top': textEl.offset().top + textEl.outerHeight(),
				'left': textEl.offset().left + textEl.outerWidth() - countEl.outerWidth()
			});
		};
		
		return this.each(function() {
			var me = $(this),
				max = options.max,
				attr;
			
			// Only textareas or text/password inputs
			if (! me.is('textarea,input[type=text],input[type=password]')) {
				return;
			}
			
			// Check for text input's 'maxlength' attribute
			attr = me.attr('maxlength');
			// Browsers implicity set maxlength (e.g. IE=524288, FF=-1)
			max =  (attr > -1 && attr <= 524288) ? attr : max;

			// Create count element
			var el = $('<div class="jqp-charcount">' + me.val().length + ' used</div>')
				.css({
					'position': 'absolute',
					'color': options.color,
					'border': '1px solid ' + options.color,
					'background-color': options.backgroundColor,
					'padding': '1px 4px'
				})
				.hide();
			
			// Add to page
			el.appendTo('body');
			position(me, el);
			
			// Store settings
			me.data('charcount', {
				'el': el,
				'max': max
			});
			
			// Event listeners
			me.focus(show);
			me.keydown(limit);
			me.keyup(update);
			me.blur(hide);
			
		});
	};
	
	$.fn.charcount.setDefaults = function(o)
	{
		$.extend(defaults, o);
	};
	
})(jQuery);

