(function ($) {
    $.field_states = function (element, options) {
        var defaults = {
            list_state: [],
            input_field: ""
        }
        var plugin = this;
        
        plugin.settings = {}
        var $element = $(element), 
            element = element;    
        
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            let input_field = plugin.settings.input_field;
            $element.find('.state').select2({
                formatResult: plugin.format,
                formatSelection: plugin.format,
                templateResult: function (data) {
                    let $result = "";
                    if (typeof data.id !== "undefined") {
                        $result = $(
                            `<div class="row">
                                <div class="col-md-4">${data.id}</div>
                                <div class="col-md-4">${data.name}</div>
                                <div class="col-md-4">${data.countryname}</div>
                            </div>`
                        );
                    }
                    return $result;
                },
                templateSelection: function (data) {
                    let $result = $(
                        `<div>${data.name}-${data.countryname}</div>`
                    );
                    $element.find(`input[name="${input_field}"]`).val(data.id);
                    return $result;
                },
                escapeMarkup: function (m) {
                    return m;
                },
                data: plugin.settings.list_state,
                dropdownCssClass: "state-field",
            });
        };
        plugin.example_function = function () {
        };
        plugin.init();
    }
    
    $.fn.field_states = function (options) {
        
        return this.each(function () {
            
            if (undefined == $(this).data('field_states')) {
                var plugin = new $.field_states(this, options);
                $(this).data('field_states', plugin);
            }
        });
    }
})(jQuery);