/**
 * 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.
 * 
 * @param function(<jQuery event object>)
 * @return object	Contains a method .delay(int) that can be used to set the delay in ms. 
 */
$.fn.typeWatch = function (f) {
	var changeOnly = true;
	var delay = 500;
	
	$(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 (changeOnly) {
					var value = elem.val();
					if (value == prevValue) {
						return;
					}
					prevValue = value;
				}
				f.call(elem, e);
			}, delay);
		});
	});
	
	return {
		// set the delay that the typeWatch takes into account
		delay: function (d) {
			delay = d;
		},
		// only fire if the input has actually been changed since the last fire
		changeOnly: function (c) {
			changeOnly = c ? true : false;
		}
	};
};

})(jQuery);