var RootPage = Class.create({
    initialize: function (host, cnf) {
        this.host = host;
        this.cnf = cnf;
        this.assets_page = new AssetsPage();
        this.init_photos();
        $$('div.b-top-block div.control').invoke('observe', 'click', this.update_block.bindAsEventListener(this));
        $$('div.b-top-block div.foot a.more').invoke('observe', 'click', this.append_block.bindAsEventListener(this));
    },
    init_photos: function () {
        if ('image_viewer' in this) {
            this.image_viewer.destroy();
            delete this.image_viewer;
        }
        this.image_viewer = new TopImageViewer(this.host, $('top_photos'), this.assets_page);
    },
    append_block: function (e) {
        var block = e.findElement('div.b-top-block');
        if (block) {
            var type = block.down('div.control div.select').className.replace("select",'').strip();
            Utils.fetch('/api/block/'+block.id+'/'+type+'/append/'+block.select('div.b-record').size(), function (block, json) {
                json.content.each(function (block, c) {
                    block.insert({ bottom: c });
                    this.assets_page.init_one(block.lastChild.appear());
                }.bind(this, block.down('div.body div.b-top-news'))); /* join div.body and div.b-top-news? */
            }.bind(this, block));
        }
    },
    update_block: function (e) {
        var el = e.findElement();
        if (el.up().hasClassName('control') && !el.hasClassName('select') && el.className) {
            var block = el.up('div.b-top-block');
            Utils.fetch('/api/block/'+block.id+'/'+el.className+'/default/'+block.select('div.b-record').size(), function (block, el, json) {

                switch (block.id) {
                    case 'photo':
                        $('top_photos').stopObserving();
                        break;
                }

                block.down('div.body').update(json.content);
                el.up().childElements().invoke('removeClassName', 'select');
                el.addClassName('select');

                switch (block.id) {
                    case 'photo':
                        this.init_photos();
                        this.assets_page.init_one(block.down('div.b-asset'));
                    case 'news':
                        this.assets_page.init_many(block);
                }

            }.bind(this, block, el));
        }
    }
});

