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

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

        $document.trigger('builder.category.init');

        $document.off('click','.selector_items .item[parent_id="0"]');
        $document.on('click','.selector_items .item[parent_id="0"]',function(){
            $.coreUtilites.ajaxRequest(
                {
                    action: 'set_selected_category',
                    category_id: $(this).attr('category_id')
                },
                function() {
                    $document.trigger('builder.category.init');
                }
            );

        });

        $document.off('click','.selector_items .item[parent_id!="0"]');
        $document.on('click','.selector_items .item[parent_id!="0"]',function(){
            var $this = $(this);

            var category_id = $this.attr('category_id');
            var $parent_id  = $this.attr('parent_id');

            var $selected = $('.category_selector[parent_id="' + $parent_id +  '"]').find('.item.selected');
            $('.category_selector[parent_id="' + $selected.attr('category_id') + '"]').remove();
            $selected.removeClass('selected');
            $this.addClass('selected');
            $('.category_selector[parent_id="' + $parent_id + '"]').find('.title').html($this.html());
            var $clipart_items = $(".sys_clipart_container.clipart .clipart_item");

            if (category_id !== "") {

                $clipart_items.show();
                $clipart_items.not( "[category_id='" + category_id + "']" ).hide();
                /*
                    TODO: The full categories tree enable is there.
                 */
                /*
                $.coreUtilites.ajaxRequest(
                    {
                        action: 'get_subcategories_by_id',
                        category_id: $(this).attr('category_id')
                    },
                    function (data) {
                        if (Object.keys(data.message).length > 0) {
                            $document.trigger('builder.category.tree.builder', [
                                data.message,
                                false,
                                category_id
                            ])
                        }
                    }
                );/**/
            } else {
                $clipart_items.show();
            }
        });

    });

    $document.off('mouseover', '.category_selector');
    $document.on('mouseover', '.category_selector', function() {
        var $this = $(this);
        $this.children('.selector_items').show();
    });

    $document.off('mouseout', '.category_selector');
    $document.on('mouseout', '.category_selector', function() {
        var $this = $(this);
        $this.children('.selector_items').hide();
    });

})(SWjQuery);