/**
 * ExedJS Library
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file license.txt.
 * It is also available through the world-wide-web at this URL:
 * http://exedjs.googlecode.com/files/license.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to open-source@exed.nl so we can send you a copy immediately.
 */

(function ($) {

/**
 * Create a type watch on an input box.
 * If the box receives input, and is subsequently left alone for a specified time (default: 500 ms),
 * the function passed to the typewatch will be fired.
 * 
 * Options:
 * - delay:			delay in ms before firing. Defaults to 500.
 * - changeOnly:	fire only when the value has changed? Defaults to true.
 * 
 * @param function(<jQuery event object>)
 * @param object	Options.
 */
$.fn.typeWatch = function (f, options) {
	var options = $.extend({
		changeOnly: true,
		delay: 500
	}, options);
	
	return $(this).each(function () {
		var timeout;
		var elem = $(this);
		var prevValue = elem.val();
		
		$(this).keyup(function (e) {
			if (timeout) {
				window.clearTimeout(timeout);
			}
			timeout = window.setTimeout(function () {
				if (options.changeOnly) {
					var value = elem.val();
					if (value == prevValue) {
						return;
					}
					prevValue = value;
				}
				f.call(elem, e);
			}, options.delay);
		});
	});
};

})(jQuery);
