(function($, undefined) {
    $.widget('incore.dictionary', {
        version: '0.0.1',
        options: {
            jsonPath: 'http://do.incore.lt/dictionary/index.php',
            dataAttribute: 'data-id'                   
        },
        _create: function() {
            $('a[' + this.options.dataAttribute + ']').tooltip().tooltip('close').tooltip('destroy'); //clear tooltip 
            this._createPopups();
        },
        _createPopups: function() {
            var widget = this;
            var linksIds = [];
            var links = this.element.find('a[' + widget.options.dataAttribute + ']');

            $.each(links, function(i, link) {
                var dataId = $(link).attr(widget.options.dataAttribute);
                linksIds.push(dataId);
            });

            if (linksIds.length > 0) {
                $.getJSON(widget.options.jsonPath, {id: linksIds}, function(info) {
                    $.each(info.data, function(key, val) {
                        if (val.active === '1') {
                            var ln = $('a[data-id="' + val.entry_id + '"]');
                            ln.attr("title", val.answer);

                            ln.tooltip({
                                content: function() {
                                    var holder = $("<div>").text(val.question).addClass("popupHeader").clone().wrap('<div>').parent().html();

                                    return  holder + $(this).prop('title');
                                },
                                position: {
                                    my: "center bottom-10",
                                    at: "center top",
                                    using: function(position, feedback) {
                                        $(this).css(position);
                                        $("<div>").addClass("arrow")
                                                .addClass(feedback.vertical)
                                                .addClass(feedback.horizontal)
                                                .appendTo(this);
                                    }
                                },
                            });
                        }
                    });
                });
            }
        },
        _setOptions: function(options) {
            this._superApply(arguments);
        },
        _setOption: function(key, val) {
            this._super(key, val);
        }
    });
}(jQuery));