(function() {

    var defaultRenderer = function() {
        return "";
    };

    var defaultGroup = function() {
        return "";
    };

    myterra.Panel = myterra.extend(myterra.Observable, {

        title: null,

        constructor: function(el, opts) {
            myterra.inherited(this);
            this.el = el = $(el);
            this.opts = opts = myterra.applyIf(opts, {
                emptyText: "Список пуст"
            });
            this.title = opts.title || "";
        }

    });

    myterra.ListPanel = myterra.extend(myterra.Panel, { // renderer

        renderer: null,
        list: null,
        listEl: null,
        waitEl: null,

        constructor: function(el, opts) {
            myterra.inherited(this);
            opts = myterra.applyIf(opts, {
                waitCls: "panel-wait"
            });
            this.listEl = $(opts.listEl || this.el);
            this.waitEl = $(opts.waitEl);
            this.renderer = opts.renderer || defaultRenderer; // function(el, t)
        },

        render: function(list) {
            var listEl = (this.listEl);
            if (list.length > 0) {
                listEl.html("");
                var i, len;
                for (i = 0, len = list.length; i < len; i++) {
                    this.renderItem(listEl, list[i]);
                }
            } else {
                this.empty();
            }
            this.wait(false);
        },

        renderItem: function(el, item) {
            var t = $("<div/>").addClass("item");
            this.renderer.call(this, t, item);
            t.appendTo(el);
        },

        info: function(text) {
            this.listEl.empty().append($("<div class=\"panel-info\"/>")
                .text(text));
        },

        wait: function(f) {
            if (f === false) {
                this.waitEl.removeClass(this.opts.waitCls);
            } else {
                this.waitEl.addClass(this.opts.waitCls);
            }
        },

        empty: function() {
            this.info(this.opts.emptyText);
        },

        clear: function() {
            this.listEl.text("");
        }

    });

    myterra.GroupListPanel = myterra.extend(myterra.ListPanel, {

        group: null,

        constructor: function(el, opts) { // title, renderer, group
            myterra.inherited(this);
            this.group = opts.group || defaultGroup; // function(el, t, last)
        },

        render: function(list) {
            this.last = null;
            myterra.inherited(this);
        },

        renderItem: function(el, item) {
            this.last = this.group(el, item, this.last);
            myterra.inherited(this);
        }

    });

})();

