/*
 * LINGUIST.LLMAP.ServiceChooser
 * Written by Joshua M. Thompson <joshua@linguistlist.org>
 *
 * This implements an Ext.Panel for browsing the Featured Services list and
 * allows dragging of services and layers to suitable drop targets such as an
 * Overlay Manager panel.
 */

LINGUIST.LLMAP.ServiceChooser = Ext.extend(Ext.tree.TreePanel, {
    sortTree: false,

    constructor: function(config) {
        Ext.applyIf(config, {
            animate: true,
            autoScroll: true,
            containerScroll: true,
            enableDrag: true,
            ddGroup: 'MapServiceDD',
            minWidth: 100,
            rootVisible: false
        });

        if (config.dataUrl == null) {
            config.root   = new Ext.tree.TreeNode({ id: '0' });
        }
        else {
            config.loader = new Ext.tree.TreeLoader({
                requestMethod: 'GET',
                dataUrl: config.dataUrl,
                baseParams: { mode: 'tree' }
            });
            config.root   = new Ext.tree.AsyncTreeNode({ id: '0' });
        }

        LINGUIST.LLMAP.ServiceChooser.superclass.constructor.call(this, config);

        if (this.sortTree) {
            new Ext.tree.TreeSorter(this, {
                folderSort: true,
                dir: 'asc'
            });
        }

        this.addListener({
            scope: this,
            click: function(node, e) {
                var service = node.attributes.service;

                if (service.type != 'folder') {
                    this.showServiceInfo(service);
                }
            },
            contextmenu: function(node, e) { e.stopEvent(); }
        });
    },

    addCategory: function(category, title) {
        var node = new Ext.tree.TreeNode({ text: title, category: category, expandable: true });

        this.root.appendChild(node);
    },

    addService: function(config, category, doSelect) {
        var service_node = new Ext.tree.TreeNode({
            text: config.name,
            cls: 'llmap-service-q0',
            service: config
        });

        this.root.eachChild(function(node) {
            if (node.attributes.category == category) {
                node.appendChild(service_node);

                if (doSelect) {
                    this.getSelectionModel().select(service_node);

                    node.expand();
                }
            }
        }, this);
    },

    showServiceInfo: function(service) {
        if (this.tip) {
            this.tip.destroy();
        }

        this.tip = new Ext.Tip({
            autoLoad: { url: '/services/' + service.id + '/info.html' },
            autoScroll: true,
            bodyStyle: 'padding: 5px',
            autoHeight:false,
            closable: true,
            height: 380,
            width: 450
        });

        this.tip.showBy(this.ownerCt.getEl(), 'tl-tr?');
    }
});

Ext.ComponentMgr.registerType('servicechooser', LINGUIST.LLMAP.ServiceChooser);
