/**
 * Snepo autocomplete JS
 */
$(function() {
  
  /**
   * Define custom autocomplete widget implementation
   */
  $.widget( "custom.catcomplete", $.ui.autocomplete, {
    _renderMenu: function ( ul, items ) {
      // Init
      var self = this, currentCategory = '';
      
      // Loop over items
      $.each( items, function( index, item ) {
        if( item.category != currentCategory )
        {
          /*var li = $( '<li></li>' ).addClass('snepo_autocomplete_category ui-menu-item');
          li.append(
            $( '<div />' ).html( '&nbsp;' )
          );
          ul.append( li );*/
          currentCategory = item.category;
        }
        self._renderItem( ul, item );
      });
    },
    _renderItem: function( ul, item ) {
      // Build row and attach data
      var li = $('<li class="snepo_autocomplete_row"></li>')
               .data('item.autocomplete', item);
      
      // Anchor
      var a = $('<a></a>');
      
      // If we have a Client, build Client and attach to Anchor
      if (item.client)
      {
        var client = $('<div></div>').addClass('snepo_autocomplete_client').text(item.client);
        a.append(client);
      }
      
      // Build Label and attach to Anchor
      var _label = $('<div></div>').addClass('snepo_autocomplete_label').text(item['label']);
      a.append(_label);
      
      
      // Attach and return
      return li.append(a).appendTo(ul);
    }
  });
  
  /**
   * Autocomplete search
   */
  $("input#snepo_search").catcomplete({
    delay: 100,
    minLength: 3,
    source: '/search',
    select: function (event, ui) {
      // Go to URL
      window.location.href = ui.item.url;
    },
    close: function (event, ui) {
      $( this ).val('');
    }
  });
  
});
