function render(_data, _level) {
    _data.theme_count =
        (typeof _data.sub_categories == "object" && typeof _data.sub_categories.slice == "function" ? _data.sub_categories.length : 0)
        + (typeof _data.tags == "object" && typeof _data.tags.slice == "function" ? _data.tags.length : 0);
    _data.contents_count = (typeof _data.contents == "object" && typeof _data.contents.slice == "function" ? _data.contents.length : 0);
    _data.level = !!_level;
    _(_data.tags).each(function(_tag) {
        _(_tag.contents).each(function(_content) {
            _content.trimmed_description = _content.description.trim().replace(/(\n|\r|\r\n)/mg,' ').replace(/(^.{150,200})[\s].+$/m,'$1&hellip;');
        });
    });
    _(_data.contents).each(function(_content) {
        _content.trimmed_description = _content.description.trim().replace(/(\n|\r|\r\n)/mg,' ').replace(/(^.{150,200})[\s].+$/m,'$1&hellip;');
    });
    var _prefix = '<li {{#level}}class="folded"{{/level}}><p class="category">{{category}} &mdash; {{theme_count}} thème(s), {{contents_count}} ressource(s)</p><ul>',
        _contents = '{{#contents}}<li class="content folded" id="content_{{id}}"><p class="title">{{title}}</p><div class="img-container"><img src="http://www.histoiredesarts.culture.fr/images/cached/images/{{hda_id}}.jpg" /></div><p class="description"><a href="{{url}}" target="_blank" class="content">{{trimmed_description}}</a></p></li>{{/contents}}',
        _suffix = '{{#tags}}<li class="folded"><p class="tag">{{label}} &mdash; {{contents.length}} ressource(s)</p><ul>'
            + _contents
            + '</ul></li>{{/tags}}'
            + _contents
            + '</ul></li>',
        _html = Mustache.to_html(_prefix, _data);
    if (typeof _data.sub_categories == "object" && typeof _data.sub_categories.slice == "function") {
        for (var _i = 0; _i < _data.sub_categories.length; _i++) {
            _html += render(_data.sub_categories[_i], _level + 1);
        }
    }
    _html += Mustache.to_html(_suffix, _data);
    return _html;
}

function histoclick(_el) {
    gettree($(_el).text());
}

function gettree(_label) {
    $.getJSON(
        endpoints.cat_tree,
        { label: _label },
        function(_data) {
            $(".label-name").html(_label);
            if (_data) {
                $("#tree").html(render(_data, 0));
                $(".cattree p.category, .cattree p.tag, .cattree p.title").click(function() {
                    $(this).parent().toggleClass("folded");
                    return false;
                });
                $(".results").show();
                $(".content-count").html($(".cattree a.content").length);
                $(".category-count").html(Math.max(0, $("p.category").length - 1));
                $(".tag-count").html($("p.tag").length);
            } else {
                $("#tree").html("");
                $(".results").hide();
            }
            var _hist = $(".historique"),
                _html = _hist.text().length ? ' &raquo; ' : '';
            _html += '<a href="#" onclick="histoclick(this); return false;">' + _label + '</a>';
            _hist.append(_html);
            $('.bloc-historique').show();
        }
    );
}

$(function() {
    $( "#catsearch" ).autocomplete({
        source: endpoints.cat_search,
        minLength: 2,
        select: function( event, ui ) {
            gettree(ui.item.value);
        }
    })
    .data("autocomplete")._renderItem = function(ul, item) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append(
                "<a>"
                + item.label.replace(
                    new RegExp('('
                        + $("#catsearch").val().replace(/(\W)/g, '\\$1')
                        + ')','gi') ,
                    '<strong>$1</strong>')
                + "</a>" )
            .appendTo( ul )
    };
});