@php $inputId = isset($select_id) ? $select_id : null; @endphp
<script>
  //var z= {!! $defaultValue!!};
  console.log('defaultValue '+typeof z);
  var unitHandler = {!! isset($handler)?1:0!!}
    $select = $('#{{$inputId}}').selectize({
        preload: true,
        valueField: '{!!$valueField!!}',
        labelField: '{!!$labelField!!}',
        delimiter: ',',
        openOnFocus : true,
        hideSelected:true,
        @if(isset($maxItem))
        maxItems : '{!! $maxItem !!}',
        @endif
        searchField: '{!!$searchField!!}',
        create: false,
        render: {
        option: function(item, escape) {
            return '<div>' +
                '<span class="title">' +
                    '<span class="name">' + escape(item.{!!$labelField!!}) + '</span>' +
                    '<p>' + escape(item.{!!$seclabelField!!}) + '</p>' +
                '</span>' +
            '</div>';
        }
    },
        onChange: function(value) {
          var contact = this.options[value];
          if(unitHandler){
            $( "#{{$inputId}}" ).trigger( "unit:change", contact.alias );
          }
          
          },
        load: function(query, callback) {
          console.log('Load');
          $.ajax({
            url: "{{env('APP_URL')}}" + "{!!$url!!}"+ encodeURIComponent(query),
            type: 'GET',
            error: function(err) {
                console.log('error occuered '+err.responseText);
              callback();
            },
            success: function(res) {
                //var r = JSON.parse(res);
                console.log('data loaded '+res);
                //$select.options = res; 
                callback(res);
                
              //callback(res.matches.slice(0, 10));
            }
          });
        },
        onLoad: function() {
            console.log('onLoad');
            @if(isset($defaultValue))
                preloadedItems = [ {!! $defaultValue!!} ];
                //console.log('populating item '+{!! $defaultValue!!});
                this.setValue(preloadedItems);
            @endif   
        
    }
      });

    

    </script>
