/*
 *	TypeWatch 0.3.0
 *	requires jQuery 1.1.3
 *	
 *	Examples/Docs: www.dennydotnet.com
 *	Copyright(c) 2007 Denny Ferrassoli
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
*/

jQuery.fn.extend({
	typeWatch:function(options) {
		waitTextbox(this, options);
	}
});

function waitTextbox(element, options) {
	element.each(
		function() {
			// Set to current element
			thisEl = jQuery(this);

			// Must be text or textarea
			if (this.type.toLowerCase() == "text" 
				|| this.nodeName.toLowerCase() == "textarea") {

				// Defaults
				var _wait = 750;
				var _callback = function() { };
				var _highlight = true;

				// Allocate timer element
				var timerLoc = window["tmr_" + thisEl[0].id];
				var timerTxt = window["txt_" + thisEl[0].id];
				var timerCB = window["cb_" + thisEl[0].id];
				if (timerLoc != null) window["tmr_" + thisEl[0].id] = null;
				if (timerTxt != null) window["txt_" + thisEl[0].id] = null;
				if (timerCB != null) window["cb_" + thisEl[0].id] = null;

				// Get options
				if (options) {
					if(options["wait"] != null)
						_wait = parseInt(options["wait"]);
					if(options["callback"] != null)
						_callback = options["callback"];
					if(options["highlight"] != null)
						_highlight = options["highlight"];
				}

				// Set default value
				window["txt_" + thisEl[0].id] = thisEl.val().toLowerCase();
				window["cb_" + thisEl[0].id] = _callback.toString();

				// Initiate new timer
				window["tmr_" + thisEl[0].id] =
					setTimeout(buildFunc(thisEl[0].id, _callback.toString(), _wait), _wait);

				// Set focus action (highlight)
				if (_highlight) {
					thisEl.focus(
						function() {
							this.select();
						});
				}

				// Key watcher / clear and reset the timer
				thisEl.keydown(
					function() {
						clearTimeout(window["tmr_" + this.id]);
						window["tmr_" + this.id] = 
							setTimeout(buildFunc(this.id, window["cb_"+this.id], _wait), _wait);
					});
			}
		});
}

function waitTextboxCheck( id, func, wait ) {
	var elementTxt = jQuery("#"+id).val();
	if (elementTxt.length > 2 && elementTxt.toLowerCase() != window["txt_" + id]) {
		window["txt_" + id] = elementTxt.toLowerCase();
		func( elementTxt );
	}

	// Reset timer
	window["tmr_" + id] = setTimeout(buildFunc(id, func, wait), wait);
}

function buildFunc( id, func, wait ) {
	return "waitTextboxCheck('" + id + "', " + func + ", " + wait + ")"
}