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, _key) {
            _content.trimmed_description = _content.description.trim().replace(/(\n|\r|\r\n)/mg,' ').replace(/(^.{150,200})[\s].+$/m,'$1&hellip;');
            _content.hidden = (_key >= 5);
        });
        _tag.show_more = _tag.contents && _tag.contents.length > 5 ? _tag.contents.length - 5 : 0;
    });
    _(_data.contents).each(function(_content, _key) {
        _content.trimmed_description = _content.description.trim().replace(/(\n|\r|\r\n)/mg,' ').replace(/(^.{150,200})[\s].+$/m,'$1&hellip;');
        _content.hidden = (_key >= 5);
    });
    _data.show_more = _data.contents && _data.contents.length > 5 ? _data.contents.length - 5 : 0;
    var _prefix = '<li class="themeli {{#level}}folded {{/level}}"><p class="theme">{{category}} &mdash; {{#theme_count}}{{theme_count}} thème(s){{#contents_count}}, {{/contents_count}}{{/theme_count}}{{#contents_count}}{{contents_count}} ressource(s){{/contents_count}}</p><ul>',
        _contents = '{{#contents}}<li class="content{{#hidden}} hidden{{/hidden}}" id="content_{{id}}"><p class="title score_{{score}}">{{title}}</p><div class="foldedcontent"><div class="img-container"><img src="http://www.histoiredesarts.culture.fr/images/cached/images/{{hda_id}}.jpg" />'
            + '</div><p class="description">Source: {{organization}}<br /><a href="{{url}}" target="_blank" class="content">{{trimmed_description}}</a></p></div></li>{{/contents}}{{#show_more}}<li class="show_more">Plus de contenus (<span class="show_more_count">{{show_more}}</span>)&hellip;</li>{{/show_more}}',
        _suffix = '{{#tags}}<li class="themeli folded"><p class="theme">{{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.theme").click(function() {
                    $(this).parent().toggleClass("folded")
                    return false;
                });
                $("li.content").mouseenter(function() {
                    $(this).find(".foldedcontent")
                    .dequeue()
                    .animate({
                        height: $(this).find("p.description").outerHeight()
                    },
                    500);
                }).mouseleave(function() {
                    $(this).find(".foldedcontent")
                    .dequeue()
                    .animate({
                        height: "0"
                    },
                    500);
                });
                $(".show_more").click(function() {
                    $(this).siblings(".hidden:lt(5)").removeClass("hidden");
                    var _l = $(this).siblings(".hidden").length;
                    $(this).find(".show_more_count").html(_l);
                    if (!_l) {
                        $(this).detach();
                    } 
                })
                $(".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 )
    };
    gettree("peinture");
});