(function($){
    var $document = $(document);

    $document.off('initClipartDraw');
    $document.on('initClipartDraw', function(){

        $document.off('mouseover', '.clipart_item');
        $document.on('mouseover', '.clipart_item:not(.ui-draggable-dragging)', function() {
            $('.clipart_popup').remove();
            var $this = $(this);
            var $clipart_block = $this.parents('.sys_clipart_container.clipart');
            var template = $.templateEngine.init('builder.clipart.categories');

            $clipart_block.append(template.applyTemplate('clipart_popup',{clipart_id:$this.attr('clipart_id')}));

            var $popup = $clipart_block.find('#clipart_popup');
            var position = $this.position();
            var scroll_params = $clipart_block.data("plugin_tinyscrollbar");
            position.top += $this.height() - parseInt(scroll_params.contentPosition);
            position.left -= 100;

            $popup.css('top', position.top + 'px');
            $popup.css('left', position.left + 'px');

        });

        $document.off('mouseout', '.clipart_item');
        $document.on('mouseout', '.clipart_item', function() {
            $('.clipart_popup').remove();
        });
    });

    $document.off('builder.clipart.draw');
    $document.on('builder.clipart.draw', function(event, clipart) {
        if (Object.keys(clipart).length > 0) {
            var $template = $.templateEngine.init('builder.clipart.categories');
            var $sys_clipart_container = $('.sys_clipart_container');
            var item_html = "";

            $.each(clipart, function(key, item){
                item_html += $template.applyTemplate(
                    'clipart_item',
                    {
                        clipart_id: item.id,
                        category_id: item.category_id.join(',')
                    }
                )
            });

            $sys_clipart_container.empty();
            $sys_clipart_container.html(item_html);
            $sys_clipart_container.html(
                '<div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div></div>' +
                '<div class="viewport">' +
                    '<div class="overview">' +
                        item_html +
                    '</div>' +
                '</div>'
            );

            if ($sys_clipart_container.data("plugin_tinyscrollbar") === undefined) {
                $sys_clipart_container.tinyscrollbar();
            }
            var scrollbar = $sys_clipart_container.data("plugin_tinyscrollbar");
            scrollbar.update();

            $document.trigger('builder.clipart.draggabler');
        }
    });
})(SWjQuery);