Rkns.ResourceList = {};

Rkns.ResourceList.Bin = Rkns.Utils.inherit(Rkns._BaseBin);

Rkns.ResourceList.Bin.prototype.resultTemplate = renkanJST['templates/list-bin.html'];

Rkns.ResourceList.Bin.prototype._init = function(_renkan, _opts) {
    this.renkan = _renkan;
    this.title_$.html(_opts.title);
    if (_opts.list) {
        this.data = _opts.list;
    }
    this.refresh();
};

Rkns.ResourceList.Bin.prototype.render = function(searchbase) {
    var search = searchbase || Rkns.Utils.regexpFromTextOrArray();
    function highlight(_text) {
        var _e = _(_text).escape();
        return search.isempty ? _e : search.replace(_e, "<span class='searchmatch'>$1</span>");
    }
    var _html = "",
        _this = this,
        count = 0;
    Rkns._.each(this.data,function(_item) {
        var _element;
        if (typeof _item === "string") {
            if (/^(https?:\/\/|www)/.test(_item)) {
                _element = { url: _item };
            } else {
                _element = { title: _item.replace(/[:,]?\s?(https?:\/\/|www)[\d\w\/.&?=#%-_]+\s?/,'').trim() };
                var _match = _item.match(/(https?:\/\/|www)[\d\w\/.&?=#%-_]+/);
                if (_match) {
                    _element.url = _match[0];
                }
                if (_element.title.length > 80) {
                    _element.description = _element.title;
                    _element.title = _element.title.replace(/^(.{30,60})\s.+$/,'$1…');
                }
            }
        } else {
            _element = _item;
        }
        var title = _element.title || (_element.url || "").replace(/^https?:\/\/(www\.)?/,'').replace(/^(.{40}).+$/,'$1…'),
            url = _element.url || "",
            description = _element.description || "",
            image = _element.image || "";
        if (url && !/^https?:\/\//.test(url)) {
            url = 'http://' + url;
        }
        if (!search.isempty && !search.test(title) && !search.test(description)) {
            return;
        }
        count++;
        _html += _this.resultTemplate({
            url: url,
            title: title,
            htitle: highlight(title),
            image: image,
            description: description,
            hdescription: highlight(description),
            static_url: _this.renkan.options.static_url
        });
    });
    _this.main_$.html(_html);
    if (!search.isempty && count) {
        this.count_$.text(count).show();
    } else {
        this.count_$.hide();
    }
    if (!search.isempty && !count) {
        this.$.hide();
    } else {
        this.$.show();
    }
    this.renkan.resizeBins();
};

Rkns.ResourceList.Bin.prototype.refresh = function() {
    if (this.data) {
        this.render();
    }
};
