// http://dyve.net/jquery/?autocomplete
jQuery.autocomplete = function(input, options) {
	// Create a link to self
	var me = this;

	// Create jQuery object for input element
	var $input = $(input).attr("autocomplete", "off");
	
	// Create results
	var results = document.createElement("div");

	// Create jQuery object for results
	// var $results = $(results);
	var $results = $(results).hide().addClass( options.resultsClass );
	if ( options.width > 0 ) {
		$results.css( "width", options.width );
	}
	
	// Add to body element
	$("body").append(results);

	input.autocompleter = me;

	var timeout = null;
	var prev = "";
	var active = -1;
	var keyb = false;
	var hasFocus = false;
	var lastKeyPressCode = null;
	var mouseDownOnSelect = false;
	var hidingResults = false;
	
	$input.keydown(function(e) {
		// track last key pressed
		lastKeyPressCode = e.keyCode;
		
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 9:  // tab
			case 13: // return
				if ( selectCurrent() ) {
					// make sure to blur off the current field
					$input.get(0).blur();
					e.preventDefault();
					if ( e.keyCode == 32 ) {
						$input.val( $input.val()+' ' );
					}
				} else if ( e.keyCode == 32 ) {
					inputChar();
				}
				break;
			default:
				inputChar();
				break;
		}
	})
	.focus(function(){
		// track whether the field has focus, we shouldn't process any results if the field no longer has focus
		hasFocus = true;
	})
	.blur(function() {
		// track whether the field has focus
		hasFocus = false;
		if (!mouseDownOnSelect) {
			hideResults();
		}
	});

	hideResultsNow();
	
	function inputChar() {
		active = -1;
		if (timeout) clearTimeout(timeout);
		timeout = setTimeout(function(){onChange();}, options.delay);
	}

	function onChange() {
		if ( options.onChange ) {
			setTimeout( function() { options.onChange() }, 1 );
		}
		
		// ignore if the following keys are pressed: [del] [shift] [capslock]
		if ( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
		var v = $input.val();
		if (v == prev) return;
		prev = v;
		if (v.length >= options.minChars) {
			requestData(v);
		} else {
			$results.hide();
		}
	};

 	function moveSelect(step) {
		var lis = $("li", results);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass("hover");

		$(lis[active]).addClass("hover");
		$input.val( $( lis[active] ).get(0).selectValue );
	};

	function selectCurrent() {
		var li = $("li.hover", results).get(0);
		if (!li) {
			var $li = $("li", results);
			if (options.selectOnly) {
				if ($li.length == 1) li = $li.get(0);
			} else if (options.selectFirst) {
				li = $li.get(0);
			}
		}
		if (li) {
			selectItem(li);
			return true;
		}
		
		return false;
	};

	function selectItem(li) {
		if (!li) {
			li = document.createElement("li");
			li.extra = [];
			li.selectValue = "";
		}
		var v = $.trim( li.selectValue ? li.selectValue : $(li).html() );
		input.lastSelected = v;
		prev = v;
		$results.html("");
		$input.val(v);		
		hideResultsNow();
		if ( options.onItemSelect ) {
			options.onItemSelect( li, input );
		}
	};

	// selects a portion of the input string
	function createSelection(start, end){
		// get a reference to the input element
		var field = $input.get(0);
		if( field.createTextRange ){
			var selRange = field.createTextRange();
			selRange.collapse(true);
			selRange.moveStart("character", start);
			selRange.moveEnd("character", end);
			selRange.select();
		} else if( field.setSelectionRange ){
			field.setSelectionRange(start, end);
		} else {
			if( field.selectionStart ){
				field.selectionStart = start;
				field.selectionEnd = end;
			}
		}
		field.focus();
	};
	
	function showResults() {
		// either use the specified width, or autocalculate based on form element
		var iWidth = ( options.width > 0 ? options.width : $input.outerWidth() );
		$results.css( {
			width: ( parseInt( iWidth, 10 ) - 2 ) + 'px',
			top: ( $input.offset().top + $input.outerHeight() )+"px",
			left: $input.offset().left + 'px'
		} ).show();
	};

	function hideResults() {
		if ( timeout ) { clearTimeout( timeout ); }
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		if (hidingResults) {
			return;
		}
		hidingResults = true;
	
		if ( timeout ) { clearTimeout( timeout ); }
		
		if ( $results.is(":visible") ) { $results.hide(); }
		
		if ( options.mustMatch && ( !input.lastSelected || input.lastSelected != $input.val() ) ) {
			selectItem( null );
		}
		
		hidingResults = false;
	};

	function receiveData(q, data) {
		if (data) {
			$(results).html('');

			// if the field no longer has focus or if there are no matches, do not display the drop down
			if( !hasFocus || data.length == 0 ) return hideResultsNow();

			if ($.browser.msie) {
				// we put a styled iframe behind the calendar so HTML SELECT elements don't show through
				$results.append('<iframe src="" frameborder="0"></iframe>');
			}
			
			results.appendChild( dataToDom( data ) );
			
			showResults();
		} else {
			hideResultsNow();
		}
	};
	
	function parseData(data) {
		if ( !data ) return null;
		var parsed = [];
		var rows = data.split( options.lineSeparator );
		for ( var i = 0; i < rows.length; i++ ) {
			var row = $.trim( rows[i] );
			if ( row ) {
				parsed[parsed.length] = row.split(options.cellSeparator);
			}
		}
		return parsed;
	};
	
	function dataToDom(data) {
		var ul = document.createElement("ul");
		var num = data.length;
		
		for ( var i = 0; i < num; i++ ) {
			var row = data[i];
			if ( !row ) { continue; }
			var li = document.createElement("li");
			if ( options.formatItem ) {
				$(li).html( options.formatItem(row, i, num) ).get(0).selectValue = row[0];
			} else {
				$(li).html( row[0] ).get(0).selectValue = row[0];
			}
			
			var extra = null;
			if ( row.length > 1 ) {
				extra = [];
				for ( var j=1; j < row.length; j++ ) {
					extra[extra.length] = row[j];
				}
			}
			li.extra = extra;
			ul.appendChild(li);
			
			$(li).hover(
				function() { $("li", ul).removeClass("hover"); $(this).addClass("hover"); active = $("li", ul).indexOf( $(this).get(0) ); },
				function() { $(this).removeClass("hover"); }
			).click( function(e) { 
				e.preventDefault();
				e.stopPropagation();
				selectItem(this);
			} );
		}
		
		$(ul).bind( 'mousedown mouseup', function(e) { mouseDownOnSelect = ( e.type == 'mousedown' ); } );
		
		return ul;
	};

	function requestData(q) {
		q = q.toLowerCase();
		
		// if an AJAX url has been supplied, try loading the data now
		if ( ( typeof options.url == "string") && ( options.url.length > 0 ) ) {
			$.ajax( {
				dataType: 'text',
				url: makeUrl(q),
				success: function( data ) {
					receiveData( q, parseData( data ) );
				}
			} );
		}
	};

	function makeUrl(q) {
		var sep = options.url.indexOf('?') == -1 ? '?' : '&'; 
		var url = options.url + sep + "q=" + encodeURI(q);
		for ( var i in options.extraParams ) {
			url += "&" + i + "=" + encodeURI( options.extraParams[i] );
		}
		return url;
	};
	
	this.setExtraParams = function(p) {
		options.extraParams = p;
	};
}

jQuery.fn.autocomplete = function(url, options, data) {
	// Make sure options exists
	options = options || {};
	// Set url as option
	options.url = url;
	// set some bulk local data
	options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

	// Set default values for required options
	options = $.extend( {
		resultsClass: "autocomplete-lijst",
		lineSeparator: "\n",
		cellSeparator: "|",
		minChars: 1,
		delay: 50,
		matchContains: 0,
		mustMatch: 0,
		extraParams: {},
		selectFirst: false,
		selectOnly: false,
		width: 0
	}, options );
	options.width = parseInt( options.width, 10 );

	this.each( function() {
		var input = this;
		new jQuery.autocomplete(input, options);
	} );

	// Don't break the chain
	return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
	return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
	for( var i=0; i<this.length; i++ ){
		if( this[i] == e ) return i;
	}
	return -1;
};
