$(function()
{
   $('#sgeo').keyup(function()
   {
      $input = $(this);
      if ($('#geosel').is('ul'))
         $('#geosel').css('height', 'auto').hide();
      if ($input.val().length > 1)
      {
         $.getJSON('/geojson.php', {k:$input.val()},
         function(res, status)
         {
            // prepare
            var h = '';
            for (var r in res)
            {
               h += '<li>' + res[r] + '</li>';
            }
            // output
            if (h != '')
            {
               $offset = $input.offset();
               // create popup
               if (!$('#geosel').is('ul'))
               {
                  $('body').append('<ul id="geosel"></ul>');
               }
               // fill popup
               $('#geosel')
                  .html(h)
                  .css({
                     top: $offset.top + $input.outerHeight() - 1,
                     left: $offset.left,
                     width: typeof $offset.width != "undefined"
                        ? $offset.width - 4
                        : $input.width()
                  })
                  .bind('mouseover', function(e)
                  {
                     $li = $(e.target).closest('li');
                     if ($li.length < 1)
                        return false;
                     $lis = $('#geosel').children('li');
                     $lis.filter('.hover').removeClass('hover');
                     $li.addClass('hover');
                  })
                  .bind('mouseout', function(e)
                  {
                     $lis = $('#geosel').children('li');
                     $lis.filter('.hover').removeClass('hover');
                  })
                  .bind('click', function(e)
                  {
                     $li = $(e.target).closest('li');
                     if ($li.length < 1)
                        return false;
                     $input.val($li.text());
                     $('#geosel').hide();
                  });
               $('#geosel').show();
               if (parseInt($('#geosel').height()) > 200)
               {
                  $('#geosel').css({
                     height: '200px',
                     overflow: 'auto'
                  });
               }
            }
         });
      }
   });
});
