/*
 * jQuery UI Autocomplete HTML Extension
 *
 * Copyright 2010, Scott González (http://scottgonzalez.com)
 * Extended by Paul Hamer (Mediamens)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * http://github.com/scottgonzalez/jquery-ui-extensions
 * Test for jQueryUI 1.8.14
 */
(function($)
{
  var proto = $.ui.autocomplete.prototype,
  initSource = proto._initSource;
  
  function filter( array, term )
  {
    var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
    return $.grep(array,function(value)
      {
        return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
      });
  }

  $.extend(proto,{
    _initSource: function()
      {
        if ( this.options.html && $.isArray(this.options.source) )
        {
          this.source = function( request, response )
            {
              response( filter( this.options.source, request.term ) );
            };
        }
        else initSource.call( this );
      },
    _renderItem: function( ul, item) // code based on original code
      {
        return $( "<li></li>" )
          .data( "item.autocomplete", item )
          .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
          .appendTo( ul );
      }
  });
})(jQuery);


(function($)
{
  var proto = $.Widget.prototype;

  $.extend(proto,{
    _init: function()
      {
        if (this.options.html) // overwrite/create focus/select function
        {
          this.options.focus = function(event, ui)
            {
              $(this).val(ui.item.value.replace(/<.*?>/g,""));
              return false;
            };
          this.options.select = function(event, ui)
            {
              $(this).val(ui.item.value.replace(/<.*?>/g,""));
              e = jQuery.Event("keypress");
              e.which = 13;
              e.keyCode = 13;
              $(this).trigger(e);
              return false;
            };
        }
      }
  });
})(jQuery);

