(
  function($)
  {
    var config = {};
    var methods =
    {
      init: function ()
      {
        eval('config = ' + $(this).attr('data-checkbox-search'));
        var options =
        {
          source: function(request, response)
          {
            $(this).checkbox_search('fetch', request, response);
          },

          select: function(event, ui)
          {
            // add checkbox to parent
            var target = $(event.target);
            var div = target.parents('td').children('span').children('div[class=checkbox-search-container]');

            var checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.name = config.name + '[]';
            checkbox.value = ui.item.id;
            checkbox.checked = 'checked';
            div.append(checkbox, ' ' + ui.item.label + '<br>');
          }
        }
        $(this).autocomplete(options);
      },

      fetch: function(request, response)
      {
        var option = config;
        option.search = config.search;
        option.term = request.term;

        var success = function(result)
        {
          eval('result = ' + result);
          response(result);
        }

        var call =
        {
          url: '/resources/php/ajax/search.php',
          data: option,
          success: success
        }
        $.ajax(call);
      }
    }

    $.fn.checkbox_search = function(method)
    {
      // method calling logic
      if (methods[method])
      {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
      }
      else if(typeof method === 'object' || !method)
      {
        return methods.init.apply(this, arguments);
      }
      else
      {
        $.error( 'Method ' +  method + ' does not exist on jQuery.validate' );
      }
    };
  }
)
(jQuery);

