var listDiv = $('#autocomplete');
if (!listDiv.length) {
    $('body').append('<div id="autocomplete"></div>')
    var listDiv = $('#autocomplete');
}
$('.autocomplete').focus(function() {
    var sf_pos    = $(this).offset();
    var sf_top    = sf_pos.top;
    var sf_left   = sf_pos.left;
    var sf_height = $(this).height();
    var sf_width  = $(this).outerWidth();
    $('.autocomplete.current').removeClass('current');
    $(this).addClass('current');
    
    listDiv.css("position","absolute");
    listDiv.css("left", sf_left);
    listDiv.css("top", sf_top + sf_height + 6);
    listDiv.css("width", sf_width-2);

  fill_list(listDiv, $(this));
  listDiv.fadeIn('fast');
}).blur(function() {
  listDiv.fadeOut('fast');
});

function fill_list(listDiv, caller) {
    listDiv.html('');
    var array = caller.data('values').split(' '),
        out = new Array(),  str = caller.val();
    for (var i = 0; i < array.length; i++) {
        var s = array[i];
        if (s.substr(0, str.length) == str)
            out.push(s);
    }
    var list = listDiv.append('<ul></ul>').find('ul');
    for (var i = 0; i < out.length; i++)
    list.append('<li>'+out[i]+'</li>');
}

function autocomplete(caller, str) {
    var array = caller.data('values').split(' '), out = new Array();
    for (var i = 0; i < array.length; i++) {
        var s = array[i];
        if (s.substr(0, str.length) == str)
            out.push(s);
    }
    if (out.length > 0)
        caller.val(out[0]);
}
$('.autocomplete').keyup(function(event) {if (event.which == 13) {event.preventDefault(); autocomplete($(this), $(this).val());} else {fill_list(listDiv, $(this))}});
$('#autocomplete li').live('click',(function() {$('.autocomplete.current').val($(this).html())}));