function render(_data) {
    var _prefix = '<li><p class="category">{{category}}</p><ul>',
        _suffix = '{{#tags}}<li><p class="tag">{{label}}</p><ul>{{#contents}}<li><a href="{{url}}" target="_blank" class="content">{{title}}</a></li>{{/contents}}</ul></li>{{/tags}}{{#contents}}<li><a href="{{url}}" target="_blank" class="content">{{title}}</a></li>{{/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]);
        }
    }
    _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));
                $(".cattree p").click(function() {
                    $(this).parent().toggleClass("folded");
                });
                $(".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 )
    };
});