{
  xtype: 'container'
	,title:ip2.i18n('menus')
  ,helpLink: '../help/html/menusandapplications.htm'
	,closable: true
	,autoScroll: true
	,labelAlign: 'top'
  ,layout:{
    type:'fit'
  }
  ,requires: [
    'Ext.ux.form.field.i18n.Text'
  ]
  ,onInitialize: function(myPanel) {
    // Menu tree grid
    if (!Ext.ClassManager.isCreated('managerMenus')) {
      Ext.define('managerMenus', {
        extend: 'Ext.data.Model'
        ,fields: [
          {name: 'id'}
          ,{name: 'title'}
          ,{name: 'url'}
          ,{name: 'rrn', type: 'int'}
          ,{name: 'type'}
          ,{name: 'system', type: 'string'}
          ,{name: 'applicationGroup', type: 'int'}
          ,{name: 'application', type: 'int'}
          ,{name: 'userGroups'}
        ]
        ,proxy:{
          type:'ajax'
          ,url:ip2.navigator.setUrl('updateMenusAndApplications', {language:ip2.session.getLanguage()})
        }
      });
    }

    var emptyNode = Ext.create('managerMenus', {})

    var rightClickMenu = Ext.create('Ext.menu.Menu', {
      items: [
        {text:ip2.i18n('update'), cls:'ip2-default', iconCls:'ip2-icon-edit', handler:function() { updateRow(); }}
        ,{text:ip2.i18n('delete'), iconCls:'ip2-icon-delete', handler:function() { deleteRow(); }}
        ,{text:ip2.i18n('newSystem'), iconCls:'ip2-tree-system', handler:function() { newSystem(); }}
        ,{text:ip2.i18n('newApplicationGroup'), iconCls:'ip2-tree-application-group', handler:function() { newApplicationGroup(); }}
        ,{text:ip2.i18n('newParentApplication'), iconCls:'ip2-tree-application', handler:function() { newParentApplication(); }}
        ,{text:ip2.i18n('newApplication'), iconCls:'ip2-tree-application', handler:function() { newApplication(); }}
      ]
    });

    var userGroupIdArray = [];
    var userGroupTextArray = [];
    var renderUserGroupIdsToText = function(value, meta, record, rowIndex, colIndex, store) {
      // this renderer is called before store load event, so this function must be here !!!
      if (Ext.isEmpty(userGroupIdArray) && store.proxy.reader.rawData.userGroupTextArray) {
        var a = store.proxy.reader.rawData.userGroupTextArray;
        for (var i = 0; i < a.length; i++) {
          userGroupIdArray[i] = a[i][0];
          userGroupTextArray[i] = a[i][1];
        }
        var columns = treegrid.headerCt.getGridColumns();
        for (var i = 0; i < columns.length; i++) {
          if (columns[i].dataIndex == 'userGroups') {
            columns[i].editor.value = {"value":[],"records":a}
            continue;
          }
        }
      }
      if (Ext.isArray(value) ) {
        // make string with user groups
        var string = '';
        var comma = '';
        for (var i = 0; i < value.length; i++) {
          if (typeof(value[i]) != 'undefined' && value[i] != -1) {
            string += comma + ' ' + userGroupTextArray[Ext.Array.indexOf(userGroupIdArray,value[i])];
            comma = ',';
          }
        }
        return string;
      } else {
        return value;
      }
    }

    var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
        clicksToEdit: 1
        ,listeners:{
          edit:function(editor, cell) {
            var params = {}
            params.rrn = cell.record.data.rrn;
            params.userGroups = cell.value;
            switch (cell.record.data.type) {
              case 'system':
                params.dbName = 'navsys';
                break;
              case 'applicationGroup':
                params.dbName = 'navagr';
                break;
              case 'application':
                params.dbName = 'navapp';
                break;
            }
            Ext.Ajax.request({
              url:ip2.navigator.setUrl('database', {action:'updateUserGroups'})
              ,params: params
              ,method: 'POST'
            })
          }
        }
    });

    var toolbarMenu = Ext.create('Ext.menu.Menu', {
      items: [
        {text:ip2.i18n('newSystem'), iconCls:'ip2-tree-system', handler:function() { newSystem(); }}
        ,{text:ip2.i18n('newApplicationGroup'), iconCls:'ip2-tree-application-group', handler:function() { newApplicationGroup(); }}
        ,{text:ip2.i18n('newParentApplication'), iconCls:'ip2-tree-application', handler:function() { newParentApplication(); }}
        ,{text:ip2.i18n('newApplication'), iconCls:'ip2-tree-application', handler:function() { newApplication(); }}
      ]
    });

    var treegrid = Ext.create('Ext.tree.Panel', {
      store:Ext.create('Ext.data.TreeStore', {
        model:'managerMenus'
        ,autoLoad: false
        ,autoSort: false
        ,autoFilter: false
      })
      ,columns: [
        {xtype:'treecolumn', text:ip2.i18n('description'), width:400, sortable:false, dataIndex:'title'}
        ,{text:ip2.i18n('url'), flex:1, sortable:false, dataIndex:'url'}
        ,{text:ip2.i18n('userGroups4menu'), flex: 2, sortable:false, dataIndex: 'userGroups', renderer:renderUserGroupIdsToText
          ,editor: {
            xtype:'ip2NavigatorUserGroupWithMultiSelectionAutoComboBox'
            ,hideLabel:true
          }
        }
      ]
      ,useArrows: true
      ,rootVisible: false
      ,multiSelect: false
      ,singleExpand: false
      ,dockedItems: [{
        xtype: 'toolbar'
        ,items: [{
          text:ip2.i18n('addNew')
          ,iconCls:'ip2-icon-add'
          ,menu:toolbarMenu
        },{
          text:ip2.i18n('refresh')
          ,iconCls:'ip2-icon-refresh'
          ,handler:function() {
            treegrid.store.load();
            treegrid.getView().refresh();
          }
        },{
          text: 'Expand All'
          ,iconCls:'ip2-icon-expand'
          ,handler: function(){
            treegrid.expandAll();
          }
        },{
          text: 'Collapse All'
          ,iconCls:'ip2-icon-collapse'
          ,handler: function(){
            treegrid.collapseAll();
          }
        }]
      }]
      ,listeners:{
        itemdblclick:function(view, node, item, index, e) {
          updateRow();
        },
        itemcontextmenu:function(view, node, item, index, e) {
          e.stopEvent();

          view.getSelectionModel().select(index);

          var coords = e.getXY();
          rightClickMenu.showAt([coords[0], coords[1]]);
        }
      }
      ,plugins: [cellEditing]
      ,viewConfig: {
        plugins: {
          ptype: 'treeviewdragdrop'
          ,expandDelay:200
        }
        ,listeners:{
          drop:function(node, data, overModel, dropPosition) {
            var targetNode = overModel;
            var params = {};
            params.dragType = data.records[0].data.type;
            params.dragRrn  = data.records[0].data.rrn;
            params.dropType = overModel.data.type;
            params.dropRrn  = overModel.data.rrn;
            params.dropSystem  = (typeof(overModel.data.system) != 'undefined') ? overModel.data.system : 0;
            params.dropApplicationGroup = (typeof(overModel.data.applicationGroup) != 'undefined') ? overModel.data.applicationGroup : 0;
            params.dropApplication = (typeof(overModel.data.application) != 'undefined') ? overModel.data.application : 0;
            params.dropPosition = dropPosition;
            Ext.Ajax.request({
              url:ip2.navigator.setUrl('moveTreeNode')
              ,params: params
              ,method: 'POST'
              ,success:function(response) {
                if (params.dropPosition == 'append' && targetNode.isLeaf()) {
                  targetNode.set('leaf',false);
                  targetNode.expand();
                }
                switch (params.dragType) {
                  case 'applicationGroup':
                    if (params.dropSystem > 0) {
                      data.records[0].set('system', params.dropSystem);
                    }
                    break;
                  case 'application':
                    if (params.dropSystem > 0) {
                      data.records[0].set('system', params.dropSystem);
                    }
                    if (params.dropApplicationGroup > 0) {
                      data.records[0].set('applicationGroup', params.dropApplicationGroup);
                    }
                    break;
                }
              }
            })
          }
        }
      }
    });
    var i_treegrid = Ext.widget(treegrid);
    var i_treestore = i_treegrid.getStore();
    i_treestore.on({
      beforeload:{
        fn: function(store, operation) {
          var i_node = operation.node;
          var o_params = operation.getParams();
          var o_extra = {
            type: i_node.get("type"),
            system: i_node.get("system"),
            applicationGroup: i_node.get("applicationGroup"),
            application: i_node.get("application"),
            node: i_node.get("id")
          };
          Ext.apply(o_params, o_extra);
          delete operation.node;
        }
      },
      load: {
        fn: function(store, a_records, success, operation, node) {
          if (!node.isExpanded()){
            node.expand();
          }
        }
      }
    });
    myPanel.add(i_treegrid);
    i_treestore.load();
    // Right click menu handler (update) for tree nodes (system, application group and application)
    var updateRow = function() {
      var nodes = treegrid.getSelectionModel().getSelection();
      for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        switch (node.data.type) {
          case 'system' :
            systemDetail('update', node);
            break;
          case 'applicationGroup' :
            applicationGroupDetail('update', node);
            break;
          case 'application' :
            var type = (node.data.url.length == 0) ? 'parent' : 'child';
            applicationDetail('update', node, type);
            break;
        }
      }
    }

    // Right click menu handler (delete) for tree nodes (system, application group and application)
    var deleteRow = function() {
      var nodes = treegrid.getSelectionModel().getSelection();
      for (var i = 0; i < nodes.length; i++) {
        switch (nodes[i].data.type) {
          case 'system' :
            Ext.MessageBox.show({
              title:ip2.i18n('confirmDeleteTitle')
              ,msg:ip2.i18n('confirmDeleteSystem')
              ,buttons: Ext.MessageBox.OKCANCEL
              ,fn:deleteSystem
              ,icon: Ext.MessageBox.WARNING
            });
            break;
          case 'applicationGroup' :
            Ext.MessageBox.show({
              title:ip2.i18n('confirmDeleteTitle')
              ,msg:ip2.i18n('confirmDeleteApplicationGroup')
              ,buttons: Ext.MessageBox.OKCANCEL
              ,fn:deleteApplicationGroup
              ,icon: Ext.MessageBox.WARNING
            });
            break;
          case 'application' :
            Ext.MessageBox.show({
              title:ip2.i18n('confirmDeleteTitle')
              ,msg:ip2.i18n('confirmDeleteApplication')
              ,buttons: Ext.MessageBox.OKCANCEL
              ,fn:deleteApplication
              ,icon: Ext.MessageBox.WARNING
            });
            break;
        }
      }
    }

    // Right click menu handler (new) for tree nodes (system)
    var newSystem = function() {
      var nodes = treegrid.getSelectionModel().getSelection();
      var node = (Ext.isEmpty(nodes)) ? emptyNode : nodes[0];
      systemDetail('create', node);
    }
    // Right click menu handler (new) for tree nodes (application group)
    var newApplicationGroup = function() {
      var nodes = treegrid.getSelectionModel().getSelection();
      var node = (Ext.isEmpty(nodes)) ? emptyNode : nodes[0];
      applicationGroupDetail('create', node);
    }
    // Right click menu handler (new) for tree nodes (application)
    var newParentApplication = function() {
      var nodes = treegrid.getSelectionModel().getSelection();
      var node = (Ext.isEmpty(nodes)) ? emptyNode : nodes[0];
      applicationDetail('create', node, 'parent');
    }
    // Right click menu handler (new) for tree nodes (application)
    var newApplication = function() {
      var nodes = treegrid.getSelectionModel().getSelection();
      var node = (Ext.isEmpty(nodes)) ? emptyNode : nodes[0];
      applicationDetail('create', node, 'child');
    }

    // Detail form (system)
    var systemDetail = function(action, node) {
      var rrn = (action == 'create') ? 0 : node.data.rrn;

      var dbName = 'navsys';
      if (!Ext.ClassManager.isCreated('systemManager')) {
        Ext.define('systemManager', {
          extend: 'Ext.data.Model'
          ,proxy:{
            type:'ajax'
            ,url:ip2.navigator.setUrl('database', {dbName:dbName, action:'get'})
            ,reader:{
              type:'json'
              ,rootProperty:'data'
            }
          }
        });
      }
      var systemStore = Ext.create('Ext.data.Store', {
        model:'systemManager'
      });
      systemStore.proxy.extraParams = {rrn:rrn};
      systemStore.load();
      systemStore.on('load', function() {
        var record = systemStore.getAt(0);
        var data = record.data;
        var windowTitle = ip2.i18n('newSystem');
        var descriptions = [];
        for (i=0; i<data.description.length; i++) {
          var desc = data.description[i];
          descriptions[i] = {};
          descriptions[i].fieldLabel = '<img src="' + ip2.locale.getCountryFlagByLanguageCode(desc['LNGID']) + '" style="padding-right:10px; vertical-align:top;" />' + ip2.locale.getLanguageTextByLanguageCode(desc['LNGID']) ;
          descriptions[i].name = 'text_' + desc['LNGID'];
          descriptions[i].value = desc['TEXT'];
          descriptions[i].allowBlank = false;
          if (desc['LNGID'] == ip2.session.getLanguage() && desc['TEXT'].length > 0) {
            windowTitle = desc['TEXT'];
          }
        };

        var form = Ext.create('Ext.form.Panel', {
          layout: "fit",
          url:ip2.navigator.setUrl('database', {dbName:dbName, action:action, rrn:rrn})
          ,items:[{
            xtype:'tabpanel'
            ,activeTab:0
            ,layout: "fit"
            ,defaults:{
              bodyStyle:'padding:10px;'
            }
            ,items:[{
              autoScroll: true
              ,title:ip2.i18n('general')
              ,defaults:{
                xtype:'textfield'
                ,labelAlign:'left'
                ,labelWidth:150
                ,width:400
              }
              ,items:[{
                xtype:'hidden'
                ,name:'SYSTOK'
                ,dataIndex:'SYSTOK'
              },{
                fieldLabel:ip2.i18n('SYSSEQ')
                ,name:'SYSSEQ'
                ,dataIndex:'SYSSEQ'
                ,allowBlank:false
                ,insertLastChildRecord:true
                ,xtype:'ip2NavigatorSystemAutoComboBox'
              },{
                fieldLabel:ip2.i18n('SYSHIV')
                ,name:'SYSHIV'
                ,dataIndex:'SYSHIV'
                ,allowBlank: true
              },{
                fieldLabel:ip2.i18n('SYSURL')
                ,name:'SYSURL'
                ,dataIndex:'SYSURL'
                ,emptyText:ip2.i18n('StandardSystemUrl')
              }]
            },{
              autoScroll: true
              ,title:ip2.i18n('systemText')
              ,defaults:{
                xtype:'textfield'
                ,labelAlign:'left'
                ,labelWidth:150
                ,width:400
              }
              ,items:descriptions
            },{
              autoScroll: true
              ,title:ip2.i18n('permissions')
              ,defaults:{
                xtype:'textfield'
                ,labelAlign:'left'
                ,labelWidth:150
                ,width:400
              }
              ,items:[{
                fieldLabel:ip2.i18n('userGroups4system')
                ,name:'userGroups'
                ,dataIndex:'userGroups'
                ,xtype:'ip2NavigatorUserGroupWithMultiSelectionAutoComboBox'
              }]
            }]
          }]
          ,buttons:[{
            text:ip2.i18n('ok')
            ,type: 'submit'
            ,handler: function() {
              var form = this.up('form').getForm();
              if (form.isValid()) {
                form.submit({
                  submitEmptyText:false
                  ,success: function(form, response) {
                    var data = response.result;
                    if (action == 'create') {
                      node = Ext.create('managerMenus', {});
                      node.set('id', 'system.'+data.rrn);
                      node.set('rrn', data.rrn);
                      node.set('type', 'application');
                      node.set('iconCls', 'ip2-tree-system');
                      node.set('leaf', true);
                      node.set('expanded', false);
                    }
                    node.set('system', data.system);

                    // update node position
                    if (data.insertBefore) {
                      if (data.insertBefore == '-1') {
                        var rootNode = treegrid.store.getRootNode();
                        rootNode.appendChild(node);
                      } else {
                        var insertBeforeNode = treegrid.store.getNodeById(data.insertBefore);
                        insertBeforeNode.parentNode.insertBefore(node,insertBeforeNode);
                      }
                    }

                    // update store (and grid row) information with form data
                    var values = form.getFieldValues();
                    for(var field in form.getValues()) {
                      var name = field;
                      switch (name) {
                        case 'text_'+ip2.session.getLanguage():
                          name = 'title';
                          break;
                        case 'SYSURL':
                          name = 'url';
                          break;
                      }
                      if (name == 'userGroups') {
                        node.set(name, data.userGroups);
                      } else {
                        node.set(name, values[field]);
                      }
                    }
                    window.hide();
                  }
                  ,failure: function(form, response) {
                    ip2.navigator.displayDBerror(response.result);
                  }
                });
              }
            }
            ,listeners:{
              afterrender:function(button) {
                ip2.setDefaultButtonStyle(button);
                ip2.mapButton2key(this.up('form').getForm().owner.el, button, 'ENTER');
              }
            }
          },{
            text:ip2.i18n('cancel')
            ,type: 'button'
            ,handler: function() {
              window.hide();
            }
          }]
          ,listeners:{
            afterrender:function(form) {
              form.getForm().loadRecord(record);
              form.getForm().findField('SYSSEQ').focus();
            }
          }
        });
        var window = Ext.create('Ext.window.Window', {
          id:'win'+ip2.unique()
          ,title:ip2.i18n('systemInformation') + ': ' + windowTitle
          ,closeAction: 'hide'
          ,width: 500
          ,height: 240
          ,layout: 'fit'
          ,resizable: true
          ,modal: true
          ,collapsible: false
          ,items: form
          ,constrain : true
        });
        window.show();
      });
    }

    // Handler for delete warning prompt (system)
    var deleteSystem = function(btn) {
      if (btn != 'ok') { return; }

      var result = {};
      var nodes = treegrid.getSelectionModel().getSelection();
      for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].data.type == 'system') {
          var node = nodes[i];
          Ext.Ajax.request({
            url:ip2.navigator.setUrl('database', {dbName:'navsys', action:'delete', rrn:node.data.rrn})
            ,success:function(response) {
              eval('result =' + response.responseText);
              if (result.success) {
                node.remove();
              } else {
                ip2.navigator.displayDBerror(response.result);
              }
            }
          })
        }
      }
    }

    // Detail form (application group)
    var applicationGroupDetail = function(action, node) {
      var rrn = (action == 'create') ? 0 : node.data.rrn;

      var dbName = 'navagr';
      if (!Ext.ClassManager.isCreated('applicationGroupManager')) {
        Ext.define('applicationGroupManager', {
          extend: 'Ext.data.Model'
          ,proxy:{
            type:'ajax'
            ,url:ip2.navigator.setUrl('database', {dbName:dbName, action:'get', language:ip2.session.getLanguage()})
            ,reader:{
              type:'json'
              ,rootProperty:'data'
            }
          }
        });
      }
      var applicationGroupStore = Ext.create('Ext.data.Store', {
        model:'applicationGroupManager'
      });
      applicationGroupStore.proxy.extraParams = {rrn:rrn, system:node.data.system};
      applicationGroupStore.load();
      applicationGroupStore.on('load', function() {
        var record = applicationGroupStore.getAt(0);
        var data = record.data;
        var windowTitle = ip2.i18n('newApplicationGroup');

        var descriptions = [];
        for (i=0; i<data.description.length; i++) {
          var desc = data.description[i];
          descriptions[i] = {};
          descriptions[i].fieldLabel = '<img src="' + ip2.locale.getCountryFlagByLanguageCode(desc['LNGID']) + '" style="padding-right:10px; vertical-align:top;" />' + ip2.locale.getLanguageTextByLanguageCode(desc['LNGID']) ;
          descriptions[i].name = 'text_' + desc['LNGID'];
          descriptions[i].value = desc['TEXT'];
          descriptions[i].allowBlank = false;
          if (desc['LNGID'] == ip2.session.getLanguage() && desc['TEXT'].length > 0) {
            windowTitle = desc['TEXT'];
          }
        };

        var form = Ext.create('Ext.form.Panel', {
          layout: "fit",
          itemId: "form-application",
          url:ip2.navigator.setUrl('database', {dbName:dbName, action:action, rrn:rrn})
          ,items:[{
            layout: "fit",
            xtype:'tabpanel'
            ,activeTab:0
            ,defaults:{
              bodyStyle:'padding:10px;'
            }
            ,items:[{
              autoScroll: true,
              title:ip2.i18n('general')
              ,defaults:{
                xtype:'textfield'
                ,labelAlign:'left'
                ,labelWidth:180
                ,width:400
              }
              ,items:[{
                xtype:'hidden'
                ,name:'AGRTOK'
                ,dataIndex:'AGRTOK'
              },{
                fieldLabel:ip2.i18n('AGRSYS')
                ,name:'AGRSYS'
                ,dataIndex:'AGRSYS'
                ,xtype:'ip2NavigatorSystemAutoComboBox'
                ,allowBlank:false
                ,listeners:{
                  select:function(box, records) {
                    Ext.Ajax.request({
                      url:ip2.navigator.setUrl('database', {dbName:'navagr', action:'listApplicationGroupBySystem'})
                      ,params:{
                        language:ip2.session.getLanguage()
                        ,system:box.getValue()
                      }
                      ,success:function(response) {
                        eval('data =' + response.responseText);
                        var form = box.up('form').getForm();
                        var field = form.findField('AGRSEQ');
                        field.setValue(-1);
                        field.store.loadData(data.records);
                        field.store.fireEvent('dataloaded', field.store);
                      }
                    })
                  }
                }
              },{
                fieldLabel:ip2.i18n('AGRSEQ')
                ,name:'AGRSEQ'
                ,dataIndex:'AGRSEQ'
                ,allowBlank:false
                ,insertLastChildRecord:true
                ,xtype:'ip2NavigatorApplicationGroupAutoComboBox'
              },{
                fieldLabel:ip2.i18n('AGRURL')
                ,name:'AGRURL'
                ,dataIndex:'AGRURL'
                ,emptyText:ip2.i18n('StandardSystemUrl')
              }]
            },{
              autoScroll: true,
              title:ip2.i18n('applicationGroupText')
              ,defaults:{
                xtype:'textfield'
                ,labelAlign:'left'
                ,labelWidth:180
                ,width:400
              }
              ,items:descriptions
            },{
              autoScroll: true,
              title:ip2.i18n('permissions')
              ,defaults:{
                xtype:'textfield'
                ,labelAlign:'left'
                ,labelWidth:180
                ,width:400
              }
              ,items:[{
                fieldLabel:ip2.i18n('userGroups4system')
                ,name:'userGroups'
                ,dataIndex:'userGroups'
                ,xtype:'ip2NavigatorUserGroupWithMultiSelectionAutoComboBox'
              }]
            }]
          }]
          ,buttons:[{
            text:ip2.i18n('ok')
            ,type: 'submit'
            ,handler: function() {
              var form = this.up('form').getForm();
              if (form.isValid()) {
                form.submit({
                  submitEmptyText:false
                  ,success: function(form, response) {
                    var data = response.result;

                    // update node position
                    var position = '', position = {};
                    if (data.insertBefore) {
                      if (data.insertBefore == '-1') { // last child
                        parentNode = treegrid.store.getNodeById(data.parentNode);
                        if (!parentNode.isExpanded()) {
                          if (parentNode.isLeaf()) {
                            parentNode.set('leaf', false);
                          }
                          position = 'expand';
                        } else {
                          position = 'append';
                        }
                      } else {
                        position = 'insertBefore';
                      }
                    }

                    if (position != 'expand') {
                      if (action == 'create') {
                        node = Ext.create('managerMenus', {});
                        node.set('id', 'applicationGroup.'+data.rrn);
                        node.set('rrn', data.rrn);
                        node.set('type', 'applicationGroup');
                        node.set('iconCls', 'ip2-tree-application-group');
                        node.set('leaf', true);
                        node.set('expanded', false);
                      }
                      node.set('system', data.system);
                      node.set('applicationGroup', data.applicationGroup);

                      // update store (and grid row) information with form data
                      var values = form.getFieldValues();
                      for(var field in form.getValues()) {
                        var name = field;
                        switch (name) {
                          case 'text_'+ip2.session.getLanguage():
                            name = 'title';
                            break;
                          case 'AGRURL':
                            name = 'url';
                            break;
                        }
                        if (name == 'userGroups') {
                          node.set(name, data.userGroups);
                        } else {
                          node.set(name, values[field]);
                        }
                      }

                    }

                    switch (position) {
                      case 'expand':
                        parentNode.expand();
                        break;
                      case 'append':
                        parentNode.appendChild(node);
                        break;
                      case 'insertBefore':
                        var insertBeforeNode = treegrid.store.getNodeById(data.insertBefore);
                        insertBeforeNode.parentNode.insertBefore(node,insertBeforeNode);
                        break;
                    }

                    window.hide();
                  }
                  ,failure: function(form, response) {
                    ip2.navigator.displayDBerror(data);
                  }
                });
              }
            }
            ,listeners:{
              afterrender:function(button) {
                ip2.setDefaultButtonStyle(button);
                ip2.mapButton2key(this.up('form').getForm().owner.el, button, 'ENTER');
              }
            }
          },{
            text:ip2.i18n('cancel')
            ,type: 'button'
            ,handler: function() {
              window.hide();
            }
          }]
          ,listeners:{
            afterrender:function(form) {
              form.getForm().loadRecord(record);
              form.getForm().findField('AGRSEQ').focus();
            }
          }
        });

        var window = Ext.widget('window', {
          id:'win'+ip2.unique()
          ,title:ip2.i18n('applicationGroupInformation') + ': ' + windowTitle
          ,closeAction: 'hide'
          ,width: 500
          ,height: 240
          ,layout: 'fit'
          ,resizable: true
          ,modal: true
          ,collapsible: true
          ,items: form
          ,constrain: true
        });
        window.show();
      });
    }

    // Handler for delete warning prompt (application group)
    var deleteApplicationGroup = function(btn) {
      if (btn != 'ok') { return; }

      var result = {};
      var nodes = treegrid.getSelectionModel().getSelection();
      for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].data.type == 'applicationGroup') {
          var node = nodes[i];
          Ext.Ajax.request({
            url:ip2.navigator.setUrl('database', {dbName:'navagr', action:'delete', rrn:node.data.rrn})
            ,success:function(response) {
              eval('result =' + response.responseText);
              if (result.success) {
                node.remove();
              } else {
                ip2.navigator.displayDBerror(response.result);
              }
            }
          })
        }
      }
    }


    // Detail form (application)
    var applicationDetail = function(action, node, type) {
      var rrn = (action == 'create') ? 0 : node.data.rrn;

      var dbName = 'navapp';
      if (!Ext.ClassManager.isCreated('applicationManager')) {
        Ext.define('applicationManager', {
          extend: 'Ext.data.Model'
          ,proxy:{
            type:'ajax'
            ,url:ip2.navigator.setUrl('database', {dbName:dbName, action:'get', language:ip2.session.getLanguage()})
            ,reader:{
              type:'json'
              ,rootProperty:'data'
            }
          }
        });
      }
      var applicationStore = Ext.create('Ext.data.Store', {
        model:'applicationManager'
      });
      applicationStore.proxy.extraParams = {rrn:rrn, system:node.data.system, applicationGroup:node.data.applicationGroup, application:node.data.application};
      applicationStore.load();
      applicationStore.on('load', function() {
        var record = applicationStore.getAt(0);
        var data = record.data;
        var windowTitle = (type == 'parent') ? ip2.i18n('newParentApplication') : ip2.i18n('newApplication');

        // create i18n object for description
        var description = {};
        for (i=0; i<data.description.length; i++) {
          description[data.description[i].LNGID] = data.description[i]  .TEXT;
        };
        record.data.description = description;
        if (record.data.APPURL.indexOf('.widget') > -1) {
          record.data.widget = record.data.APPURL;
          record.data.APPURL = '';
        }
        windowTitle = description[ip2.session.getLanguage()];

        var tabs = [];

        var tabDefaults = {
          xtype:'textfield'
          ,labelAlign:'left'
          ,labelWidth:150
          ,width:600
        }

        // general tab
        tabs.push(buildGeneralUI(type, description, tabDefaults));

        // application permission
        tabs.push(buildPermissionUI(type, tabDefaults));

        // application wizard
        if (type != 'parent') {
          tabs.push(buildWizardUI(type, tabDefaults));
        }


        var form = Ext.create('Ext.form.Panel', {
          layout: "fit",
          items:[{
            xtype:'tabpanel'
            ,activeTab:0
            ,"layout": "fit"
            ,defaults:{
              bodyStyle:'padding:10px;'
            }
            ,items:tabs
          }]
          ,buttons:[{
            text:ip2.i18n('ok')
            ,type: 'submit'
            ,handler: function() {
              var form = this.up('form').getForm();
              if (type != 'parent') {
                var field = ip2.lookUpForm(form, 'TEXT_da' );
                if (field != null) {
                  var value = field.getValue();
                  ip2.lookUpForm(form, 'DESC' ).setValue(value);
                }
              }
              if (form.isValid()) {
                var values = form.getFieldValues();
                var desc = values.description;
                for (var lang in desc) {
                  values['text_'+lang] = desc[lang];
                }
                if (values.APPURL && values.APPURL.length == 0) {
                  values.APPURL = values.widget;
                }
                Ext.Ajax.request({
                  url:ip2.navigator.setUrl('database', {dbName:dbName, action:action, rrn:rrn})
                  ,params:values
                  ,success:function(response, request) {
                    var data = Ext.decode(response.responseText);

                    // update node position
                    var position = '', parentNode = {};

                    if (data.insertBefore) {
                      if (data.insertBefore == '-1') { // last child
                        parentNode = treegrid.store.getNodeById(data.parentNode);
                        if (!parentNode.isExpanded()) {
                          if (parentNode.isLeaf()) {
                            parentNode.set('leaf', false);
                          }
                          position = 'expand';
                        } else {
                          position = 'append';
                        }
                      } else {
                        position = 'insertBefore';
                      }
                    }
                    if (position != 'expand') {
                      if (action == 'create') {
                        node = Ext.create('managerMenus', {});
                        node.set('id', 'application.'+data.rrn);
                        node.set('rrn', data.rrn);
                        node.set('type', 'application');
                        node.set('iconCls', 'ip2-tree-application');
                        node.set('leaf', true);
                        node.set('expanded', false);
                      }
                      node.set('system', data.system);
                      node.set('applicationGroup', data.applicationGroup);
                      node.set('application', data.application);

                      // update store (and grid row) information with form data
                      var values = request.params;
                      for(var field in values) {
                        var name = field;
                        switch (name) {
                          case 'text_'+ip2.session.getLanguage():
                            name = 'title';
                            break;
                          case 'APPURL':
                            name = 'url';
                            break;
                        }
                        if (name == 'userGroups') {
                          node.set(name, data.userGroups);
                        } else {
                          node.set(name, values[field]);
                        }
                      }
                    }

                    switch (position) {
                      case 'expand':
                        parentNode.expand();
                        break;
                      case 'append':
                        parentNode.appendChild(node);
                        break;
                      case 'insertBefore':
                        var insertBeforeNode = treegrid.store.getNodeById(data.insertBefore);
                        insertBeforeNode.parentNode.insertBefore(node,insertBeforeNode);
                        break;
                    }

                    window.hide();
                  }
                  ,failure: function(form, response) {
                    ip2.navigator.displayDBerror(response.result);
                  }
                });
              }
            }
            ,listeners:{
              afterrender:function(button) {
                ip2.setDefaultButtonStyle(button);
                ip2.mapButton2key(this.up('form').getForm().owner.el, button, 'ENTER');
              }
            }
          },{
            text:ip2.i18n('cancel')
            ,type: 'button'
            ,handler: function() {
              window.hide();
            }
          }]
          ,listeners:{
            afterrender:function(form) {
              form.getForm().loadRecord(record);
              form.getForm().findField('APPSEQ').focus();
            }
          }
        });
        var window = Ext.create('Ext.window.Window', {
          id:'win'+ip2.unique()
          ,title:ip2.i18n('applicationInformation') + ': ' + windowTitle
          ,closeAction: 'hide'
          ,width: 650
          ,height: type != "parent" ? 455 : 345
          ,layout: 'fit'
          ,resizable: true
          ,modal: true
          ,collapsible: false
          ,items: form
          ,constrain: true
        });
        window.show();
      });
    }

    // -----------------------------------------------------------------------------------------------------
    //  Build position UI
    // -----------------------------------------------------------------------------------------------------
    var buildGeneralUI = function(type, description, tabDefaults) {
      var tab = {
        autoScroll: true
        ,title:ip2.i18n('general')
        ,defaults:tabDefaults
        ,items:[]
      };
      tab.defaults.labelWidth = 200;
      tab.defaults.width = 600;

      tab.items.push({
        xtype:'hidden'
        ,name:'APPTOK'
        ,dataIndex:'AGRTOK'
      });

      tab.items.push({
        xtype: 'i18ntextfield'
        ,fieldLabel: ip2.i18n('applicationText')
        ,name: 'description'
        ,value: Ext.encode(description)
        ,languages: ip2.navigator.system.settings.languages
        ,allowBlank: false
      });
      if (type != 'parent') {

        tab.items.push({
          fieldLabel: ip2.i18n('APPURL')
          ,name: 'APPURL'
          ,dataIndex: 'APPURL'
          ,allowBlank: true
        });

        tab.items.push({
          xtype: 'label'
          ,text: '- or'
        });

        tab.items.push({
          xtype: 'ip2WidgetsCombobox'
          ,fieldLabel: ip2.i18n('widget')
          ,name: 'widget'
          ,dataIndex: 'widget'
          ,allowBlank: true
          ,listeners: {
            load: function(box, records) {
              box.setValue(box.getValue());
            }
          }
        });
      }

      var fs = Ext.create('Ext.form.FieldSet', {
        title: ip2.i18n('applicationLocation')
        ,collapsible: true
        ,defaultType: 'textfield'
        ,defaults: {
          anchor: '100%'
          ,labelWidth: 190
          ,width: 610
        }
        ,layout: 'anchor'
        ,items: []
      });

      fs.add({
        xtype: 'uploadpicker'
        ,path: "/system/images/icons/extjs5/16x16"
        ,minChars: 1
        ,fieldLabel: ip2.i18n('APPICO')
        ,name: 'APPICO'
        ,dataIndex: 'APPICO'
        ,allowBlank: true
        ,ignoreStaticDir: true
      });

      fs.add({
        fieldLabel: ip2.i18n('APPSYS')
        ,name: 'APPSYS'
        ,dataIndex: 'APPSYS'
        ,xtype: 'ip2NavigatorSystemAutoComboBox'
        ,listeners:{
          select:function(box, records) {
            Ext.Ajax.request({
              url:ip2.navigator.setUrl('database', {dbName:'navagr' ,action:'list'})
              ,params:{
                system:records[0].data.Token
                ,language:ip2.session.getLanguage()
              }
              ,success:function(response) {
                var data = {},
                    value = {};
                value.records = [];
                eval ('data = ' + response.responseText);
                for (var i = 0; i < data.totalRows; i++) {
                  var rec = [];
                  rec[0] = data.rows[i].AGRTOK;
                  rec[1] = data.rows[i].TITLE;
                  value.records.push(rec);
                }
                value.value = 0;
                applicationGroupField.setValue(value);
              }
            })
          }
        }
        ,allowBlank: false
      });

      var applicationGroupField = Ext.create('ip2.navigator.applicationGroupAutoComboBox', {
        fieldLabel: ip2.i18n('APPAGR')
        ,name: 'APPAGR'
        ,dataIndex: 'APPAGR'
        ,allowBlank: false
        ,labelWidth: 190
        ,width: 610
        ,listeners:{
          select:function(box, records) {
            Ext.Ajax.request({
              url:ip2.navigator.setUrl('database', {dbName:'navapp', action:'list'})
              ,params:{
                applicationGroup:records[0].data.Token
                ,language:ip2.session.getLanguage()
              }
              ,success:function(response) {
                var data = {},
                    value = {};
                value.records = [];
                eval ('data = ' + response.responseText);
                for (var i = 0; i < data.totalRows; i++) {
                  var rec = [];
                  rec[0] = data.rows[i].AGRTOK;
                  rec[1] = data.rows[i].TITLE;
                  value.records.push(rec);
                }
                value.value = 0;
                parentApplicationField.setValue(value);
              }
            })
          }
        }
      });
      fs.add(applicationGroupField);

      var parentApplicationField = Ext.create('ip2.navigator.applicationAutoComboBox', {
        fieldLabel: ip2.i18n('APPPAR')
        ,name: 'APPPAR'
        ,hiddenName: 'APPPAR'
        ,dataIndex: 'APPPAR'
        ,allowBlank: true
        ,labelWidth: 190
        ,width: 610
      });
      fs.add(parentApplicationField);

      fs.add({
        fieldLabel: ip2.i18n('APPSEQ')
        ,name: 'APPSEQ'
        ,hiddenName: 'APPSEQ'
        ,dataIndex: 'APPSEQ'
        ,insertLastChildRecord: true
        ,xtype: 'ip2NavigatorApplicationAutoComboBox'
        ,allowBlank: false
      });

      tab.items.push(fs);

      return tab;
    }

    // -----------------------------------------------------------------------------------------------------
    //  Build permission UI
    // -----------------------------------------------------------------------------------------------------
    var buildPermissionUI = function(type, tabDefaults) {
      var tab = {
        autoScroll: true
        ,title:ip2.i18n('permissions')
        ,defaults:tabDefaults
        ,items:[]
      };
      tab.items.push({
        fieldLabel: ip2.i18n('userGroups4system')
        ,name: 'userGroups'
        ,dataIndex: 'userGroups'
        ,xtype: 'ip2NavigatorUserGroupWithMultiSelectionAutoComboBox'
      });

      return tab;
    }

    // -----------------------------------------------------------------------------------------------------
    //  Build application wizard UI
    // -----------------------------------------------------------------------------------------------------
    var buildWizardUI = function(type, tabDefaults) {
      var tab = {
        autoScroll: true
        ,title:ip2.i18n('APPWIZ')
        ,defaults:tabDefaults
        ,items:[]
      };

      var column = {
        xtype: 'container'
        ,width: 600
        ,layout:'column'
        ,items:[{
          xtype: 'container'
          ,columnWidth:.5
          ,defaults:{
            labelAlign:'left'
            ,labelWidth:150
          }
          ,items: [{
            fieldLabel: ip2.i18n('APPGEN')
            ,name: 'APPGEN'
            ,dataIndex: 'APPGEN'
            ,xtype: 'checkboxfield'
            ,allowBlank: true
            ,width: 300
          }]
        },{
          xtype: 'container'
          ,columnWidth:.5
          ,defaults:{
            labelAlign:'left'
            ,labelWidth:150
          }
          ,items: [{
            fieldLabel: ip2.i18n('APPIPAD')
            ,name: 'APPIPAD'
            ,itemId: 'APPIPAD'
            ,dataIndex: 'APPIPAD'
            ,xtype: 'checkboxfield'
            ,width: 300
          }]
        }]
      };
      tab.items.push(column);

      tab.items.push({
        fieldLabel: ip2.i18n('APPTPL')
        ,name: 'APPTPL'
        ,itemId: 'APPTPL'
        ,width: 600
        ,dataIndex: 'APPTPL'
        ,xtype: 'ip2AppTemplatesComboBox'
        ,allowBlank: true
      });

      tab.items.push({
        fieldLabel: ip2.i18n('APPPLUG')
        ,name: 'APPPLUG'
        ,dataIndex: 'APPPLUG'
        ,width: 600
        ,xtype: 'ip2DataBasePlugin'
        ,allowBlank: true
        ,listeners:{
          select:function(box, record) {
            var tabpanel = box.up('tabpanel');
            var tab = tabpanel.getActiveTab();

            if (record[0].data['PLUGINTYPE'] == '*DMD') {
              var f = tab.getComponent('MODEL');
              if (f) {
                f.setValue('');
                f.hide();
              }
              var f = tab.getComponent('DMD');
              if (f) {
                f.setValue('');
                f.show();
              }
              var f = tab.getComponent('ENTITY');
              if (f) {
                f.setValue('');
                f.show();
              }
            } else {
              var f = tab.getComponent('MODEL');
              if (f) {
                f.setValue('');
                f.show();
              }
              var f = tab.getComponent('DMD');
              if (f) {
                f.setValue('');
                f.hide();
              }
              var f = tab.getComponent('ENTITY');
              if (f) {
                f.setValue('');
                f.hide();
              }
            }
          }
        }
      });
      tab.items.push({
        fieldLabel: ip2.i18n('APPMODEL')
        ,name :'MODEL'
        ,itemId: 'MODEL'
        ,dataIndex : 'MODEL'
        ,width: 600
        ,xtype: 'ip2DataModels'
        ,onFocus: function () {
          this.setPlugin (ip2.fld(this,'APPPLUG').getValue());
        }
        ,hidden:true
      });
      tab.items.push({
        fieldLabel: ip2.i18n('databaseModelFile')
        ,name:'DMD'
        ,itemId:'DMD'
        ,dataIndex:'DMD'
        ,width:600
        ,xtype:'ip2FieldWithBrowse'
        ,path:'*serverpath'
        ,fileExtention:[{ext:'dmd', desc:'Database Model (*.dmd)'},{ext:'', desc:'All Files (*.*)'}]
        ,selectButtonText:'Open'
        ,validSelectionExtention:'dmd'
        ,allowBlank:true
        ,hidden:true
      });
      tab.items.push({
        fieldLabel: ip2.i18n('entity')
        ,name :'ENTITY'
        ,itemId: 'ENTITY'
        ,dataIndex : 'ENTITY'
        ,width: 600
        ,xtype: 'ip2DmdEntityComboBox'
        ,dmdFieldId:'DMD'
        ,hidden:true
      });

      tab.items.push({
        name: 'DESC'
        ,dataIndex: 'DESC'
        ,xtype: 'hidden'
      });

      return tab;
    }

    // Handler for delete warning prompt (application group)
    var deleteApplication = function(btn) {
      if (btn != 'ok') { return; }

      var result = {};
      var nodes = treegrid.getSelectionModel().getSelection();
      for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].data.type == 'application') {
          var node = nodes[i];
          Ext.Ajax.request({
            url:ip2.navigator.setUrl('database', {dbName:'navapp', action:'delete', rrn:node.data.rrn})
            ,success:function(response) {
              eval('result =' + response.responseText);
              if (result.success) {
                node.remove();
              } else {
                ip2.navigator.displayDBerror(response.result);
              }
            }
          })
        }
      }
    }

  }
}
