jQuery.fn.autocomplete = function(url) 
{
	return this.each( function()
	{
		var textInput = $(this);
		textInput.after('<ul class="autocomplete"></ul>');
		//var list = textInput.next().css({top: textInput.offset().top + textInput.outerHeight(), left: textInput.offset().left, width: textInput.width()});
		var list = textInput.next().css({top: 39, left: 15, width: textInput.width()+14}); //26 / 15 /-26
		//var list = textInput.next().css({top: textInput.offset().top-280 + textInput.outerHeight(), left: textInput.offset().left-417, width: textInput.width()-26});
		var oldText = '';
		var typingTimeout;
		var size = 0;
		var selected = 0;
		function getData(text)
		{
			window.clearInterval(typingTimeout);
			if (text != oldText && (text.length >= 2))
			{
				clear();
				$.getJSON(url,{"q": text},function(data)
				{
					var items = '';
					if (data)
					{
						size = data[1].length;
						selected = -1;
						$.each(data[1], function(i,item){
							items += '<li value="' + item + '">' + item.replace(new RegExp("(" + text + ")","i"),"<strong>$1</strong>") + '</li>';
						});
						list.html(items);
						list.show().children().
						hover(function() { $(this).addClass("selected").siblings().removeClass("selected");}, function() { $(this).removeClass("selected") } ).
						click(function () { textInput.val( $(this).attr('value') );textInput.val( $(this).text() ); clear();textInput.focus(); });
					}
				});
				oldText = text;
			}
		}
		function clear()
		{
			list.hide();
			size = 0;
			selected = 0;
		}	
		textInput.keydown(function(e) 
		{
			window.clearInterval(typingTimeout);
			if(e.which == 27)//escape
			{
				clear();
			}
			else if(e.which == 40 || e.which == 38)//move up, down 
			{
				switch(e.which) 
				{
					case 40: 
					case 9:
						selected = selected >= size - 1 ? 0 : selected + 1; break;
					case 38:
						selected = selected <= 0 ? size - 1 : selected - 1; break;
					default: break;
				}
				textInput.val( list.children().removeClass('selected').eq(selected).addClass('selected').text() );	
				textInput.focus();
			} else
			{
				typingTimeout = window.setTimeout(function() { getData(textInput.val()) },500);
			}
		});
	});
};