[%# 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>
  #         Brian Kramer <bkramer@student.neumont.edu>
  #         Michael Hight <mjhight@gmail.com>
  #%]

[%# INTERFACE:
  # ...
  #%]
<script type="text/javascript">
  //var djConfig = {isDebug: true };
</script>  
<script src="testopia/dojo/dojo.js" type="text/javascript"></script>
<script src="testopia/js/util.js" type="text/javascript"></script>
<script type="text/javascript">
    dojo.require("dojo.event.*");
    dojo.require("dojo.io.*");
    dojo.require("dojo.widget.Tree");
    dojo.require("dojo.widget.TreeNode");
    dojo.require("dojo.widget.TreeSelector");
    dojo.require("dojo.widget.TreeLoadingController");
    dojo.require("dojo.widget.TreeRPCController");
    dojo.require("dojo.widget.TreeContextMenu");
    
    
    function treeSelectFired() {
        
        //<!-- get a reference to the treeSelector and get the selected node -->
        var treeSelector = dojo.widget.manager.getWidgetById('treeSelector');
        var selectedNode = treeSelector.selectedNode;
        
        var hostDiv = document.getElementById("message");
        
        dojo.io.bind({
          url:        "tr_admin_environment.cgi",
          content:    {  action: "edit", id: selectedNode['objectId'], type: selectedNode['widgetId'] },
          load:     function(type, data, evt){
                          hostDiv.innerHTML = data;
                      },
          error:     function(type, error){ dojo.debug(error.message);},
          mimetype:    "text/html"
      });
    }
    
    // CONTEXT MENU FUNCTIONS
    function createClicked(selectedNode, controllerId, icon) {
        if (!selectedNode || selectedNode.actionIsDisabled(selectedNode.actions.ADDCHILD)) {
            return false;
        }

        this.controller = dojo.widget.manager.getWidgetById(controllerId);
        var res = controller.createChild(selectedNode, 0, { });
    }

    function createElementClicked(selectedNode, controllerId, icon) {
        if (!selectedNode || selectedNode.actionIsDisabled(selectedNode.actions.ADDCHILD)) {
            return false;
        }

        this.controller = dojo.widget.manager.getWidgetById(controllerId);
        var res = controller.createChild(selectedNode, 0, { createType: "Element" });
    }
    
    function editClicked(selectedNode, controllerId, icon) {
        var hostDiv = document.getElementById("message");
        var treeSelector = dojo.widget.manager.getWidgetById('treeSelector');
        treeSelector.deselect;
        treeSelector.doSelect(selectedNode);
        dojo.io.bind({
          url:        "tr_admin_environment.cgi",
          content:    {  action: "edit", id: selectedNode['objectId'], type: selectedNode['widgetId'] },
          load:     function(type, data, evt){
                          hostDiv.innerHTML = data;
                      },
          error:     function(type, error){ dojo.debug(error.message);},
          mimetype:    "text/html"
      });
    }
    
    function removeClicked(selectedNode, controllerId, icon) {
        if (!selectedNode) {
            alert('No node selected');
            return false;
        }

        if (selectedNode.actionIsDisabled(selectedNode.actions.REMOVE)) {
            return false;
        }
        var action = confirm("You are about to delete this item with all its children. Continue?");
        this.controller = dojo.widget.manager.getWidgetById(controllerId);

        if (action){
          var res = controller.removeNode(selectedNode);
        }

        // local checks failed
        if (res == false) {
            var hostDiv = document.getElementById("message");
            hostDiv.innerHTML = "FAILED";
        } else {
            var hostDiv = document.getElementById("message");
            hostDiv.innerHTML = "";
        }
    }
        
    function init() {
        <!-- get a reference to the treeSelector -->
        var treeSelector = dojo.widget.manager.getWidgetById('treeSelector');
        
        <!-- connect the select event to the function treeSelectFired() -->
        dojo.event.connect(treeSelector,'select','treeSelectFired');
    }
        
    dojo.addOnLoad(init);
    
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
//////////// functions for valid_exp.html.tmpl ////////////////////////////    
        
    var lastIndex = -1;
    
    function moveUp(){
        var array = new Array();
        var exp_list = document.getElementById("valid_exp");
        var index = exp_list.selectedIndex;
        
        for(i = 0; i < exp_list.length; i++){
            if(index - 1 == i)
            {
                // when we have gotten to the item BEFORE the one to move up
                //add the next one first,
                    array[i] = exp_list[i+1];
                //then add the one were on
                    array[i + 1] = exp_list[i];
                //update the selected index
                    exp_list.selectedIndex = i -1;
                //count past next since we did both this loop
                i++;
            }
            else
            {
                array[i] = exp_list[i];
            }
        }
        
        //now need to clear and rebuild the DOM list
        exp_list.options.length = 0;
        for (i = 0; i < array.length; i++)
        {
            exp_list.add(array[i],null);
        }
        
        lastIndex = -1;
        document.getElementById("text_exp_value").value = "";
    }
    
    function moveDown() {
        var array = new Array();
        var exp_list = document.getElementById("valid_exp");
        var index = exp_list.selectedIndex;
        
        for(i = 0; i < exp_list.length; i++){
            if(index == i)
            {
                //when we have gotten to the one to move down
                //check to see if there is a next one
                if (i < exp_list.length -1){
                    //add the next one first,
                    array[i] = exp_list[i+1];
                    //then add the one were on
                    array[i + 1] = exp_list[i];
                    //update the selected index
                    exp_list.selectedIndex = i +1;
                    //count past next since we did both this loop
                    i++;
                }
                else{
                    //end of list just add like normal
                    array[i] = exp_list[i];
                }
            }
            else
            {
                array[i] = exp_list[i];
            }
        }
        
        //now need to clear and rebuild the DOM list
        exp_list.options.length = 0;
        for (i = 0; i < array.length; i++)
        {
            exp_list.add(array[i],null);
        }
        
        exp_list.selectedIndex = -1;
        lastIndex = -1;
        document.getElementById("text_exp_value").value = "";
    }
    
    function update_text()
    {
        var exp_list = document.getElementById("valid_exp");
        var textbox = document.getElementById("text_exp_value");
        var text = textbox.value;
        
        if (lastIndex != -1)
        {
            exp_list[lastIndex].value = text;
            exp_list[lastIndex].text = text;
        }
        textbox.value = exp_list[exp_list.selectedIndex].value;
        lastIndex = exp_list.selectedIndex;
   }
   
   function selected_expression_change()
   {
       var exp_list = document.getElementById("valid_exp");
       lastIndex = exp_list.selectedIndex;
       document.getElementById('text_exp_value').value = exp_list.value;
       
   }
   
   function submit_valid_exp()
   {
           var exp_list = document.getElementById("valid_exp");
           exp_list.multiple = true;
           for (i = 0; i < exp_list.length; i++)
           {
               exp_list[i].selected = true;
           }
   }
    
    
    
</script>

<script type="text/javascript">
//    dojo.require("dojo.widget.Editor");
    
    function getCategories(prod)
    {
      prod.disabled = true;
      dojo.byId('element_submit').disabled = true;
      dojo.io.bind({
          url:        "tr_admin_environment.cgi",
          content:    {  action: "getcategories", product_id: prod[prod.selectedIndex].value  },
          load:     function(type, data, evt){
                          var target = document.getElementById("categoryCombo");
                          var element = document.getElementById("elementCombo");
                          element.options.length = 0;
                          element.disable;
                          target.options.length = 0;
                          target.add(new Option("[please select]","none"), null);
                          if(data != ""){
                              var categories = data.split("|||");
                              for (i = 0; i < categories.length; i++){
                                  var cat = categories[i].split("||");
                                  var myOp = new Option(cat[1], cat[0]);
                                  target.add(myOp,null);
                              }
                          }
                          prod.disabled = false;
                          target.disabled = false;
                          dojo.byId('element_submit').disabled = false;
                      },
          error:     function(type, error){ dojo.debug(error.message);},
          mimetype:    "text/plain"
      });
    }
    
    function getElements(elem){
      elem.disabled = false;
      dojo.io.bind({
          url:        "tr_admin_environment.cgi",
          content:    {  action: "getelements", cat_name: elem[elem.selectedIndex].value  },
          load:     function(type, data, evt){
                          var target = document.getElementById("elementCombo");
                          target.options.length = 0;
                          target.add(new Option("[please select]","none"), null);
                          if(data != ""){
                              var elements = data.split("|||");
                              for (i = 0; i < elements.length; i++){
                                  var elem = elements[i].split("||");
                                  var myOp = new Option(elem[1], elem[0]);
                                  target.add(myOp,null);
                              }
                          }
                          
                          elem.disabled = false;
                          target.disabled = false;                         
                      },
          error:     function(type, error){ dojo.debug(error.message);},
          mimetype:    "text/html"
      });
    }
</script> 

<div dojoType="TreeContextMenu" toggle="explode" contextMenuForWindow="false" widgetId="treeContextMenu">
    <div dojoType="TreeMenuItem" treeActions="addCategory" iconSrc="" caption="Add Category" widgetId="treeContextMenuCreate"></div>
    <div dojoType="TreeMenuItem" treeActions="addElement" iconSrc="" caption="Add Element" widgetId="treeContextMenuCreateElement"></div>
    <div dojoType="TreeMenuItem" treeActions="addProperty" iconSrc="" caption="Add Property" widgetId="treeContextMenuCreate"></div>
    <div dojoType="TreeMenuItem" treeActions="addValue" iconSrc="" caption="Add Value" widgetId="treeContextMenuCreate"></div>
    <div dojoType="TreeMenuItem" treeActions="edit" iconSrc="" caption="Edit" widgetId="treeContextMenuEdit"></div>
    <div dojoType="TreeMenuItem" treeActions="remove" iconSrc="" caption="Remove" widgetId="treeContextMenuRemove"></div>
</div>

<script>
/* setup menu actions */
dojo.addOnLoad(function() {

    dojo.event.topic.subscribe('treeContextMenuCreate/engage',
        function (menuItem) { 
            createClicked( menuItem.getTreeNode(), 'treeController',  menuItem.getTreeNode().expandIcon); 
        }
    );

    dojo.event.topic.subscribe('treeContextMenuCreateElement/engage',
        function (menuItem) { 
            createElementClicked( menuItem.getTreeNode(), 'treeController',  menuItem.getTreeNode().expandIcon); 
        }
    );

    dojo.event.topic.subscribe('treeContextMenuEdit/engage',
        function (menuItem) { 
            editClicked( menuItem.getTreeNode(), 'treeController',  menuItem.getTreeNode().expandIcon); 
        }
    );

    dojo.event.topic.subscribe('treeContextMenuRemove/engage',
        function (menuItem) { 
            removeClicked( menuItem.getTreeNode(), 'treeController',  menuItem.getTreeNode().expandIcon, 'up'); 
        }
    );
});

function updateCategory(){
    var treeSelector = dojo.widget.manager.getWidgetById('treeSelector');
    var selectedNode = treeSelector.selectedNode;
    var tree = dojo.widget.manager.getWidgetById('environmentTree');
    
    dojo.io.bind({
          url:      "tr_admin_environment.cgi",
          content:  {  action: "do_edit", type: "category", id: selectedNode['objectId'], product: document.getElementById('product').value, name: document.getElementById('name').value},
          load:     function(type, data, evt){
                        if (data.error){
                          alert(data.error);
                          return;
                        }
                        var newParent = dojo.widget.manager.getWidgetById(data.product);
                        var cat = dojo.widget.manager.getWidgetById(data.widget);
                        cat.edit({title: data.name});
                        tree.move(cat,newParent,0);
                      },
          error:     function(type, error){ dojo.debug(error.message);},
          mimetype:    "text/json"
    });
}

function updateElement(){
    var treeSelector = dojo.widget.manager.getWidgetById('treeSelector');
    var selectedNode = treeSelector.selectedNode;
    var tree = dojo.widget.manager.getWidgetById('environmentTree');
    
    dojo.io.bind({
          url:      "tr_admin_environment.cgi",
          content:  {  action: "do_edit", type: "element", id: selectedNode['objectId'], categoryCombo: document.getElementById('categoryCombo').value, elementCombo: document.getElementById('elementCombo').value, name: document.getElementById('name').value},
          load:     function(type, data, evt){
                        if (data.error){
                          alert(data.error);
                          return;
                        }
                        var newParent = dojo.widget.manager.getWidgetById(data.parent);
                        var obj = dojo.widget.manager.getWidgetById(data.widget);
                        obj.edit({title: data.name});
                        tree.move(obj,newParent,0);
                      },
          error:     function(type, error){ dojo.debug(error.message);},
          mimetype:    "text/json"
    });
}

function updateProperty(){
    var treeSelector = dojo.widget.manager.getWidgetById('treeSelector');
    var selectedNode = treeSelector.selectedNode;
    var tree = dojo.widget.manager.getWidgetById('environmentTree');
    
    dojo.io.bind({
          url:      "tr_admin_environment.cgi",
          content:  {  action: "do_edit", type: "property", id: selectedNode['objectId'], element: document.getElementById('element').value, name: document.getElementById('name').value},
          load:     function(type, data, evt){
                        if (data.error){
                          alert(data.error);
                          return;
                        }
                        var newParent = dojo.widget.manager.getWidgetById(data.element);
                        var obj = dojo.widget.manager.getWidgetById(data.widget);
                        obj.edit({title: data.name});
                        tree.move(obj,newParent,0);
                      },
          error:     function(type, error){ dojo.debug(error.message);},
          mimetype:    "text/json"
    });
}
</script>

<table>
    <tr>
        <td><h3>Environment Variables</h3>
            <div dojoType="TreeRPCController" 
                 RPCUrl="tr_admin_environment.cgi" 
                 widgetId="treeController" 
                 DNDController="create"></div>
                 
            <div dojoType="TreeSelector" 
                 widgetId="treeSelector"></div>
                 
            <div dojoType="Tree" 
                 menu="treeContextMenu" 
                 DNDMode="between"
                 strictFolders="false" 
                 selector="treeSelector" 
                 widgetId="environmentTree" 
                 controller="treeController">
                 [% IF type == 'classification' %]
                    <div dojoType="TreeNode" 
                         title="--ANY PRODUCT--" 
                         widgetId="product0" 
                         objectId="0" 
                         actionsDisabled="remove;edit;addElement;addProperty;addValue" 
                         childIconSrc="testopia/img/folder_red.gif"
                         [% 'isFolder="true"' IF allhaschild %] ></div>
                 [% END %]
                 [% FOREACH item = toplevel %]
                    <div dojoType="TreeNode" 
                         title="[% item.name %]" 
                         widgetId="[% type %][% item.id %]" 
                         objectId="[% item.id %]" 
                         actionsDisabled="remove;edit;addElement;addProperty;addValue;[% 'addCategory' IF type == 'classification' %]" 
                         childIconSrc="[% type == 'classification' ? 'testopia/img/folder_blue.gif' : 'testopia/img/folder_red.gif' %]"
                         [% 'isFolder="true"' IF (type == 'classification' OR item.cat_count > 0) %] ></div>
                 [% END %]
            </div>
        </td>
        <td style="width:30px" ></td>
        <td valign="top"><div id="message" style="border:none"></div>
        </td>
    </tr>
</table>
