
(function($) {
    $.fn.itfSelect2 = function() {
        return this.each(function() {
            var $this = $(this);
            var ctype_id = $this.attr("data-ctype");
            var url = '/autocomplete/' + ctype_id;
            $this.select2({
                ajax: {
                    'url': url,
                    dataType: 'json',
                    quietMillis: 100,
                    data: function(term, page) {
                        return {
                            q: term,
                            page_limit: 10,
                            page: page
                        }
                    },
                    results: function(data, page) {
                        //console.log(data);
                        var more = data.has_next;
                        //console.log(data);
                        return {results: data.items, more: more};
                    }
                },
                formatResult: function(item) {
                    return "<div>" + item.title +  "<div style='font-size:12px'><i>" + item.text + "</i></div></div>"
                },
                formatSelection: function(item) {
                    //console.log(item);
                    //return "<div>" + item.first_name + " " + item.last_name + "<div>" + item.about + "</div></div>";
                    //console.log("foo");
                    return item.title;           
                    //return "<div data-id='" + item.id + "'>" + item.first_name + " " + item.last_name + "</div>";
                }                                   
            });
            var id = $this.attr("data-id");
            //console.log(id);
            if ($.trim(id) !== '') {
                var title = $this.attr("data-title");
                $this.select2("val", {'id': id, 'title': title});
            }
            //return this;
        });
    }
})(jQuery);
