/* cavaliba_select2.js
 * Data-attribute-driven Select2 initialisation.
 *
 * Reads data-cv-select2 on <select> elements:
 *   "simple"         – plain Select2, no AJAX
 *   "ajax-instance"  – AJAX search for DataInstance; needs:
 *                        data-cv-ajax-url   : URL to app_data:ajax_instance
 *                        data-cv-classname  : dataformat_ext (target class)
 *                        data-cv-placeholder: (optional) placeholder text
 *   "ajax-user"      – AJAX search for users; needs:
 *                        data-cv-ajax-url   : URL to app_user:ajax_user
 *                        data-cv-placeholder: (optional) placeholder text
 */

$(document).ready(function () {

    /* ---- simple ---- */
    $('select[data-cv-select2="simple"]').select2({
        width: '100%'
    });

    /* ---- ajax-instance ---- */
    $('select[data-cv-select2="ajax-instance"]').each(function () {
        var $el = $(this);
        $el.select2({
            width: '100%',
            ajax: {
                url: $el.data('cv-ajax-url'),
                dataType: 'json',
                delay: 250,
                cache: true,
                data: function (params) {
                    return {
                        q: params.term,
                        c: $el.data('cv-classname')
                    };
                }
            },
            placeholder: $el.data('cv-placeholder') || 'Select items'
        });
    });

    /* ---- ajax-user ---- */
    $('select[data-cv-select2="ajax-user"]').each(function () {
        var $el = $(this);
        $el.select2({
            width: '100%',
            ajax: {
                url: $el.data('cv-ajax-url'),
                dataType: 'json',
                delay: 250,
                cache: true,
                data: function (params) {
                    return { q: params.term };
                }
            },
            placeholder: $el.data('cv-placeholder') || 'Select users'
        });
    });

});
