[%# 1.0@bugzilla.org %]
[%# The contents of this file are subject to the Mozilla Public
  # License Version 1.1 (the "License"); you may not use this file
  # except in compliance with the License. You may obtain a copy of
  # the License at http://www.mozilla.org/MPL/
  #
  # Software distributed under the License is distributed on an "AS
  # IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
  # implied. See the License for the specific language governing
  # rights and limitations under the License.
  #
  # The Original Code is the Bugzilla Test Runner System.
  #
  # The Initial Developer of the Original Code is Maciej Maczynski.
  # Portions created by Maciej Maczynski are Copyright (C) 2001
  # Maciej Maczynski. All Rights Reserved.
  #
  # Contributor(s): Greg Hendricks <ghendricks@novell.com>
  #                 Scott Sudweeks <ssudweeks@novell.com>
  #                 Andrew Nelson <anelson@novell.com>
  #%]

[%# INTERFACE:
  # ...
  #%]
  
[% PROCESS global/variables.none.tmpl %]
[% PROCESS testopia/style.none.tmpl %]
[% PROCESS testopia/blocks.html.tmpl %]

[% javascript_urls.push( 'testopia/js/case.js') %]

[% title = "Environment Editor" %]

[% PROCESS global/header.html.tmpl %]

<style type = "text/css"> 
.product .x-tree-node-icon{
background:url(testopia/img/product.gif);
}
.product .x-tree-node-icon{
background:url(testopia/img/product.gif);
}
.element .x-tree-node-icon{
background:url(testopia/img/element.gif);
}
.property .x-tree-node-icon{
background:url(testopia/img/property.gif);
}
.category .x-tree-node-icon{
background:url(testopia/img/category.gif);
}
.validexp .x-tree-node-icon{
background:url(testopia/img/validexpRed.png);
}
.validexpYellow .x-tree-node-icon{
background:url(testopia/img/validexpYellow.png);
}
</style> 

<script type="text/javascript">
Ext.onReady(function(){
    var Tree = Ext.tree;
    var testopia_form = new Ext.form.BasicForm('testopia_helper_frm');
/*
 * etree - Environment Tree Panel
 *     This panel represents the environment
 */               
    var etree = new Tree.TreePanel({
        animate: true,
        autoScroll: true,
        enableDD:true,
        containerScroll: true,
        region: 'center',
        title: 'Editing Environment [% environment.name FILTER js %]',
        split: true,
        id: 'environment_tree',
        root: new Tree.AsyncTreeNode({
            text: '[% environment.name %]',
            draggable:false,
            id: '[% environment.id %]',
            type: 'environment'
        }),
        dropConfig :{allowContainerDrop: true},
        loader: new Tree.TreeLoader({
            url: "tr_environments.cgi",
            listeners: {'beforeload':function(l, node) {
                 l.baseParams.action = 'getChildren'; 
                 l.baseParams.tree_type = 'env';
                 l.baseParams.type = node.attributes.type;
                 l.baseParams.env_id = [% environment.id FILTER js %];
            }}
        }),
        listeners:{
            "textchange": function(node, text, oldText){
                var httpRequest = new Ext.data.Connection();
                httpRequest.request({
                    url: 'tr_environments.cgi', 
                    params:{
                        action: 'rename',
                        name: text, 
                        env_id: node.id,
                        isactive: true
                    }, 
                    success:function(object){
                        TestopiaUtil.notify.msg('Test Environment Updated', 'Environment renamed successfully');
                    }, 
                    failure: testopiaError
                });      
            },
            "contextmenu": function(node, event){
                node.getOwnerTree().getSelectionModel().select(node);
                this.menu = new Ext.menu.Menu({
                    id: 'etree_menu', 
                    items: [{
                        text: 'Remove Element',
                        disabled: true,
                        id: 'etree_remove_node', 
                        handler: function (){
                            Ext.Msg.show({
                                title: 'Remove Selected Elements', 
                                msg: 'Are you sure?',
                                buttons: Ext.MessageBox.YESNO,
                                icon: Ext.MessageBox.QUESTION,
                                fn: function(btn, text){
                                    if (btn == 'yes'){
                                        var elements = [];
                                        if(node.attributes.type == 'category'){
                                            node.eachChild(function(n){
                                                if (n.attributes.type == 'element')
                                                    elements.push(n.id);
                                            });
                                        }
                                        else {
                                            elements.push(node.id);
                                        }
                                        testopia_form.submit({
                                            url: 'tr_environments.cgi', 
                                            params:{
                                                action: 'remove_env_node',
                                                element_ids: elements.join(','), 
                                                env_id: [% environment.id FILTER js %]
                                            }, 
                                            success:function(f,a){
                                                if(node != null)
                                                    node.remove();
                                            }, 
                                            failure: testopiaError
                                        });      
                                    }
                                }
                            });
                        }          
                    },{
                        text: 'Rename Environment',
                        hidden: true,
                        id: 'etree_rename_env',
                        handler: function(){
                            environmentTreeEditor.startEdit(etree.root.ui.textNode);
                        }
                    },{
                        text: 'Mark this value "Selected"',
                        hidden: true,
                        id: 'etree_value_selector',
                        handler: function(){
                            testopia_form.submit({
                                url: 'tr_environments.cgi', 
                                params:{
                                    action: 'set_selected',
                                    id: node.id, 
                                    type: node.attributes.type, 
                                    env_id: [% environment.id FILTER js %],
                                    value: node.attributes.value
                                }, 
                                success:function(object){
                                    var parentNode = node.parentNode;
                                    var children = parentNode.childNodes;
                                    for(i=0; i<children.length; i++){
                                        c = children[i].getUI();
                                        c.removeClass(["validexpYellow"]);
                                        c.addClass(["validexp"]);
                                    }
                                    c = node.getUI();
                                    c.removeClass(["validexp"]);
                                    c.addClass(["validexpYellow"]);             
                                }, 
                                failure: testopiaError
                            }); 
                        }
                    },{
                        text: 'Refresh',
                        handler: function(){
                            node.getOwnerTree().getLoader().load(node);
                        }
                    }]
                });
                    
                Ext.getCmp('etree_remove_node').disable();
                Ext.getCmp('etree_value_selector').hide();
                Ext.getCmp('etree_rename_env').hide();
                if (node.attributes.type == 'category' || (node.attributes.type == 'element' && node.getDepth() <= 2)) {
                    Ext.getCmp('etree_remove_node').enable();
                }
                else 
                    if (node.attributes.type == 'validexp') {
                        Ext.getCmp('etree_value_selector').show();
                    }
                    else 
                        if (node.attributes.type == 'environment') {
                            Ext.getCmp('etree_rename_env').show();
                        }
                    
                this.menu.showAt([event.getPageX(), event.getPageY()]);
            }
        }
    });
    
/*
 * vtree - Variables Tree Panel
 *     This panel represents the environment variables
 */               
    var vtree = new Tree.TreePanel({
        animate: true,
        autoScroll: true,
        enableDD:true,
        containerScroll: true,
        region: 'north',
        title: 'Environment Items',
        split: true,
        height: 300,
        collapsible: true,
        rootVisible: false,
        id: 'variable_tree',
        loader: new Tree.TreeLoader({
            url: "tr_environments.cgi",
            listeners: {"beforeload": function(l, node) {
                 l.baseParams.action = 'getChildren';
                 l.baseParams.tree_type = 'var'; 
                 l.baseParams.type = node.attributes.type;
                 l.baseParams.env_id = [% environment.id FILTER js %];
           }}
        }),
        root: new Tree.AsyncTreeNode({
            text: 'root',
            draggable: false,
            id:'0',
            action: 'getChildren',
            type: 'root',
            env_id: '0'               
        }),
        listeners: {
            "textchange": editNode,
            "contextmenu": ctxMenu
        }
    });
    var ptree = new Tree.TreePanel({
        animate: true,
        autoScroll: true,
        enableDD:true,
        containerScroll: true,
        region: 'center',
        title: 'Product "[% environment.product.name FILTER js %]" Items',
        split: true,
        width: '300',
        collapsible: true,
        rootVisible: false,
        id: 'prod_variable_tree',
        loader: new Tree.TreeLoader({
            url: "tr_environments.cgi",
            listeners: {"beforeload": function(l, node) {
                 l.baseParams.action = 'getChildren';
                 l.baseParams.tree_type = 'var'; 
                 l.baseParams.type = node.attributes.type;
                 l.baseParams.env_id = [% environment.id FILTER js %];
           }}
        }),
        root: new Tree.AsyncTreeNode({
            text: 'root',
            draggable: false,
            id: [% environment.product_id FILTER none %],
            type: 'root'
        }),
        listeners: {
            "textchange": editNode,
            "contextmenu": ctxMenu
        }
    });

/*
 * Tree Editor defs
 */   
    var environmentTreeEditor = new Tree.TreeEditor(etree, {id: 'etree_editor'});
    environmentTreeEditor.cancelOnEscape = true;
    environmentTreeEditor.ignoreNoChange = true;
    environmentTreeEditor.completeOnEnter = true;
    environmentTreeEditor.autosize = true;

    var itemTreeEditor = new Tree.TreeEditor(vtree, {id: 'vtree_editor'});
    itemTreeEditor.cancelOnEscape = true;
    itemTreeEditor.ignoreNoChange = true;
    itemTreeEditor.completeOnEnter = true;
    itemTreeEditor.autosize = true;

    var productTreeEditor = new Tree.TreeEditor(ptree, {id: 'vtree_editor'});
    productTreeEditor.cancelOnEscape = true;
    productTreeEditor.ignoreNoChange = true;
    productTreeEditor.completeOnEnter = true;
    productTreeEditor.autosize = true;

    
/*
 * Functions
 */

    function editNode(node, text, oldText){
        var id = node.attributes.id; 
        var type = node.attributes.type;
        
        testopia_form.submit({
            url: 'tr_environments.cgi', 
            params:{
                action: 'edit',
                text: text, 
                id: node.attributes.property_id || node.attributes.id, 
                type: node.attributes.type
            }, 
            success:function(f,a){
                TestopiaUtil.notify.msg('Environment' + type + 'Updated', type + ' renamed successfully');
            }, 
            failure: testopiaError
        });      
    }
    
    
    function expandCallBack(node){
        var children = node.childNodes;
        for(i=0;i<children.length;i++){
            var child = children[i];
            checkAndRemoveNode(child);                     
        }
        node.remove();
        return;        
    }
        
    function checkAndRemoveNode(node){
        if(node.attributes.type != 'element')
            return;
        if(node.getDepth() > 2)
            return;
        
        var item = {};
        item.id = node.attributes.id; 
        item.type = node.attributes.type; 
        deleteNode(item);
    }       
    
    function ctxMenu (node, event){
            ctxmenu = new Ext.menu.Menu({
                id: 'variable_ctx_menu',
                items: [{
                    text: 'New Category',
                    id: 'add_category_mnu',
                    hidden: true,
                    nodeId: node.attributes.id, 
                    type: node.attributes.type,
                    handler: addNode.createDelegate(this, [node, 'category'])          
                },{
                    text: 'New Element',
                    id: 'add_element_mnu',
                    hidden: true,
                    nodeId: node.attributes.id, 
                    type: node.attributes.type,
                    handler: addNode.createDelegate(this, [node, 'element'])
                },{
                    text: 'New Property',
                    id: 'add_property_mnu',
                    hidden: true,
                    nodeId: node.attributes.id, 
                    type: node.attributes.type,
                    handler: addNode.createDelegate(this, [node, 'property'])
                },{
                    text: 'New Property Value',
                    id: 'add_value_mnu',
                    hidden: true,
                    nodeId: node.attributes.id, 
                    type: node.attributes.type,
                    handler: addNode.createDelegate(this, [node, 'value']) 
                },{
                    text: 'Delete This Item',
                    id: 'delete_node_mnu',
                    hidden: true,
                    nodeId: node.attributes.id, 
                    type: node.attributes.type,
                    handler: deleteNode.createDelegate(this, [node]) 
                },{
                    text: 'Rename This Item',
                    id: 'rename_node_mnu',
                    hidden: true,
                    nodeId: node.attributes.id, 
                    type: node.attributes.type,
                    handler: renameNode.createDelegate(this, [node]) 
                }]
            });
        
        Ext.getCmp('add_category_mnu').hide();
        Ext.getCmp('add_element_mnu').hide();
        Ext.getCmp('add_property_mnu').hide();
        Ext.getCmp('add_value_mnu').hide();
        Ext.getCmp('delete_node_mnu').hide();
        Ext.getCmp('rename_node_mnu').hide();

        switch (node.attributes.type){
        case 'product':
            Ext.getCmp('add_category_mnu').show();
            break;

        case 'category':
            Ext.getCmp('add_element_mnu').show();
            Ext.getCmp('delete_node_mnu').show();
            Ext.getCmp('rename_node_mnu').show();
            break;

        case 'element':
            Ext.getCmp('add_element_mnu').show();
            Ext.getCmp('add_property_mnu').show();
            Ext.getCmp('delete_node_mnu').show();
            Ext.getCmp('rename_node_mnu').show();
            break;

        case 'property':
            Ext.getCmp('add_value_mnu').show();
            Ext.getCmp('delete_node_mnu').show();
            Ext.getCmp('rename_node_mnu').show();
            break;

        case 'value':
            Ext.getCmp('delete_node_mnu').show();
            Ext.getCmp('rename_node_mnu').show();
            break;
            
        }
        
        ctxmenu.showAt(event.getXY());

    }
    
    function addNode(node, newtype){
        var type = newtype == 'element' && node.attributes.type == 'element' ? 'child' : newtype;
        
        testopia_form.submit({
            url: 'tr_environments.cgi', 
            params:{
                action: 'create_child',
                id: node.id, 
                type: type,
                env_id: [% environment.id FILTER js %]
            }, 
            success:function(f,a){
                node.leaf = false;
                var newNode = new Ext.tree.TreeNode(a.result.env_object);
                node.appendChild(newNode);
                node.expand(false, true, function(){
                    if (node.getOwnerTree().id == 'variable_tree'){
                        itemTreeEditor.triggerEdit(newNode);
                    }
                    else {
                        productTreeEditor.triggerEdit(newNode);
                    }
                });
            }, 
            failure: testopiaError
        });      
    }
    
    function deleteNode(node){
        testopia_form.submit({
            url: 'tr_environments.cgi', 
            params:{
                action: 'delete_element',
                id: node.attributes.property_id || node.id, 
                type: node.attributes.type, 
                env_id: [% environment.id FILTER js %]
            }, 
            success:function(object){
                node.remove();
                TestopiaUtil.notify.msg('Environment '+ node.attributes.type +' Deleted', '');
            }, 
            failure: testopiaError
        }); 
    }
    
    function renameNode(node){
        if (node.getOwnerTree().id == 'variable_tree'){
            itemTreeEditor.triggerEdit(node);
        }
        else {
            productTreeEditor.triggerEdit(node);
        }
                
    }
    
    
    function copyNode(node){
        var copy = new Tree.TreeNode(Ext.apply({}, node.attributes));
        for(var i=0; i < node.childNodes.length; i++){
            n = node.childNodes[i];
            if(n){
                copy.appendChild(copyNode(n));
            }
        }
        return copy; 
    };
   
    itemTreeEditor.on("beforestartedit", function(editor, element, value){
       if(!editor.editNode)
           return true;
       var type = editor.editNode.attributes.type;
       if(type == 'product' || type == 'classification')
           return false;
    });
    
    productTreeEditor.on("beforestartedit", function(editor, element, value){
       if(!editor.editNode)
           return true;
       var type = editor.editNode.attributes.type;
       if(type == 'product' || type == 'classification')
           return false;
    });
   
    environmentTreeEditor.on('beforestartedit', function(editor, element, value){
        if(Ext.getCmp('environment_tree').getSelectionModel().getSelectedNode().attributes.type != "environment")
               return false;
    }); 
    
    vtree.on("enddrag", applyElement, this);
    ptree.on("enddrag", applyElement, this); 
    
    etree.on("beforenodedrop", function(event){
        event.target = event.tree.root;
        event.point = 'append';
        event.dropNode = copyNode(event.dropNode);
    });
        
    function applyElement(treePanel, node, dd, e){
        testopia_form.submit({
            url: 'tr_environments.cgi',
            params: {id: node.id, env_id: [% environment.id FILTER js %], type: node.attributes.type, action: 'apply_element'},
            success: function(f,a){
                etree.getLoader().load(etree.root, function(){etree.root.expand()});
            },
            failure: testopiaError
        });
    }
    
    var EnvironmentPanel = new Ext.Panel({
        id: 'environment_panel',
        layout: 'border',
        applyTo: 'environment_div',
        height: 800,
        items: [
            etree,
        {
            layout: 'border',
            region: 'east',
            width: 300,
            split: true,
            items: [vtree, ptree]
        },{
            title: 'Help',
            collapsible: true,
            region: 'south',
            split: true,
            height: 200
        }]
    });
    vtree.dropZone.isTarget = false;
    ptree.dropZone.isTarget = false;
});


</script>

<div id="environment_div"></div>

[% PROCESS global/footer.html.tmpl %]
