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

    $document.off('builder.category.tree.builder');
    $document.on('builder.category.tree.builder', function(event, categories, first, parent_selector_category) {
        if(first == undefined) {first = true}
        if(parent_selector_category == undefined) {parent_selector_category = 0}

        var $category_tree = $('.category_tree');
        var template = $.templateEngine.init('builder.clipart.categories');

        var selected_element = {};
        var item_html = "";
        if (first==false) {
            selected_element = {
                title: 'All'
            };
            item_html += template.applyTemplate (
                'item',
                {
                    category_id: '',
                    parent_id: parent_selector_category,
                    title: 'All',
                    selected: 'selected'
                }
            );
        }

        $.each(categories, function(key, item) {
            if (item.selected) {
                selected_element = item;
            }
            item_html += template.applyTemplate (
                'item',
                {
                    category_id: item.category_id,
                    parent_id: item.parent_id,
                    title: item.title,
                    selected: (item.selected)?'selected':''
                }
            );
        });

        var items_html = template.applyTemplate (
            'items',
            {
                items: item_html
            }
        );

        var category_selector = template.applyTemplate (
            'category_selector',
            {
                title: selected_element.title,
                selector_items: items_html,
                parent_id: parent_selector_category
            }
        );

        if (first == true) {
            $category_tree.empty();
            $category_tree.html(category_selector);
        } else {
            $category_tree.append(category_selector);
        }


        if (selected_element.subcat_count>0) {
            $document.trigger('builder.category.tree.builder', [
                selected_element.subcats,
                false,
                selected_element.category_id
            ])
        }

        if (first == true) {
            $document.trigger('builder.cliparts.reload');
        }
    })

})(SWjQuery);