;(function($, window, document, undefined) {
    'use strict';

    jQuery(function ($) {
        var lookup = $('.js-data-participant-lookup');
        lookup.select2({
            ajax: {
                minimumInputLength: 2,
                url: '/admin/data/api/participants',
                dataType: 'json',
                data: function (params) {
                    return {
                        search: $.trim(params.term),
                        page: params.page || 1,
                        type: 'public'
                    };
                },
                processResults: function (response, params) {
                    return {
                        results: response.data.map(function (participant) {
                            return {
                                id: participant['user_id'],
                                text: participant.first + ' ' + participant.last
                            };
                        }),
                        pagination: {
                            more: (params.page * 10) < response.data.total
                        }
                    };
                }
            }
        });

        var userId = lookup.attr('data-key') || null;
        if (userId) {
            $.ajax({
                type: 'GET',
                url: '/admin/data/api/participant/' + userId
            }).then(function (data) {
                var option = new Option(data.first + ' ' + data.last, data['user_id'], true, true);
                lookup.append(option).trigger('change');
                lookup.trigger({
                    type: 'select2:select',
                    params: {
                        data: data
                    }
                });
            });
        }
    });

} )(jQuery, window, document);
