Ext.onReady(function(){
  Ext.override(Ext.form.DateField, {  
    // private
    validateValue : function(value){
        if (value == '0000.00.00') { return true; }
        
        value = this.formatDate(value);
        if(!Ext.form.DateField.superclass.validateValue.call(this, value)){
            return false;
        }
        if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
             return true;
        }
        var svalue = value;
        value = this.parseDate(value);
        if(!value){
            this.markInvalid(String.format(this.invalidText, svalue, this.format));
            return false;
        }
        var time = value.getTime();
        if(this.minValue && time < this.minValue.getTime()){
            this.markInvalid(String.format(this.minText, this.formatDate(this.minValue)));
            return false;
        }
        if(this.maxValue && time > this.maxValue.getTime()){
            this.markInvalid(String.format(this.maxText, this.formatDate(this.maxValue)));
            return false;
        }
        if(this.disabledDays){
            var day = value.getDay();
            for(var i = 0; i < this.disabledDays.length; i++) {
            	if(day === this.disabledDays[i]){
            	    this.markInvalid(this.disabledDaysText);
                    return false;
            	}
            }
        }
        var fvalue = this.formatDate(value);
        if(this.disabledDatesRE && this.disabledDatesRE.test(fvalue)){
            this.markInvalid(String.format(this.disabledDatesText, fvalue));
            return false;
        }
        return true;
    },
    formatDate : function(date) {
      fdate = Ext.isDate(date) ? date.dateFormat(this.format) : date;
      return (fdate == '01.01.1901') ? '00.00.0000' : fdate;
    }
  });

  var selectedRow;
  
  Ext.BLANK_IMAGE_URL = '/system/Components/ext-2/resources/images/default/s.gif';

  Ext.QuickTips.init();
  Ext.form.Field.prototype.msgTarget = 'under';
  Ext.form.Field.prototype.height = 20;

  var ds = new Ext.data.JsonStore({
      url:'/'+hive['mnu004l']+'/mnu004l.asp'
      ,remoteSort: false
    });

  function renderPreviousLogin(value, p, record){
    if (value.getFullYear() == '1950' || value.getFullYear() == '1901') {
      string = '';
    } else {
      string = String.format('{0} / {1}', Ext.util.Format.date(value, 'd.m.Y'), record.data['LOGTIM']);
    }
    return string;
  }

  var grid = new Ext.grid.GridPanel({
    renderTo:Ext.getBody()
    ,autoScroll:true
    ,autoHeight:true
    ,store: ds
    ,columns:
      [
        {header: menu.I18N['ID'], width:160, sortable:true, dataIndex: 'USRNAM'}
        ,{header: menu.I18N['name'], width:240, sortable:true, dataIndex: 'TXT'}
        ,{header: menu.I18N['type'], width:80, sortable:true, dataIndex: 'TYPE'}
        ,{header: menu.I18N['profileOnIBMi'], width:80, sortable:true, dataIndex: 'RUNASUSR'}
        ,{header: menu.I18N['userClass'], width:140, sortable:true, dataIndex: 'USRCLS'}
        ,{header: menu.I18N['previousLogin'], width:130, sortable:true, dataIndex: 'LOGDAT', renderer: renderPreviousLogin}
        ,{header: menu.I18N['userGroup'], width:240, sortable:true, dataIndex: 'USRGRP'}
      ]
    ,sm: new Ext.grid.RowSelectionModel({singleSelect:true})
    ,loadMask:false
	  ,tbar:
	    [
        {
          id:'addUser'
          ,text: menu.I18N['addNewUser']
          ,tooltip: menu.I18N['addNew']
          ,cls:'x-btn-text-icon mnu-tb-user-add'
          ,handler: onButtonClick
        }, '' ,{
          id:'addUserGroup'
          ,text: menu.I18N['addNewUserGroup']
          ,tooltip: menu.I18N['addNew']
          ,cls:'x-btn-text-icon mnu-tb-user-group-add'
          ,handler: onButtonClick
        }, '-' ,{
          xtype:'textfield'
          ,emptyText:menu.I18N['search']
          ,name:'query'
          ,allowBlank:true
          ,enableKeyEvents:true
          ,listeners:{
            render: function(fld)  {
              if (Ext.isIE) {
                var f = document.getElementById(fld.id);
                var placeholder = f.getAttribute('placeholder');
                if (placeholder != null && placeholder.length > 0 && f.value.length < 1) {
                  f.value = placeholder;
                  f.className += ' mnu-placeholder';
                }
              }
            }
            ,keyup : function(fld, e) {
              var key = e.getKey()
		          if (key == 13) { // ENTER
                ds.load({
                  params: {
                    query:fld.getValue()
                  }
                });

              }
            }
          }
        }
	    ]
  });

  // Row menu
  var rowMenu = new Ext.menu.Menu({
    id: 'rowMenu',
    items: [
      {id: 'edit', text: menu.I18N['edit'], cls:'mnu-icon-edit smd-default', handler:onRowRightClick}
      ,{id: 'copy', text: menu.I18N['copy'], cls:'mnu-icon-copy', handler:onRowRightClick}
    ]
  });

  grid.on('rowcontextmenu', onRowMenu);
  grid.on('rowclick', function(grid, rowIndex, e) {
    selectedRow = ds.data.items[rowIndex].id;
  });
  grid.on('rowdblclick', function(grid, rowIndex, e) {
    selectedRow   = ds.data.items[rowIndex].id;
    if (ds.getById(selectedRow).get('TYPE') == '*USER') {
      processUserRow(ds.getById(selectedRow).get('RRN'), 'update');
    } else {
      processUserGroupRow(ds.getById(selectedRow).get('RRN'), 'update');
    }
  });

  ds.load({
    params: {}
  });

  ds.on('load', function(store, records, options) {
    if(!store.reader.jsonData.success) {
      ds.removeAll();
      Ext.Msg.alert(menu.I18N['message'], store.reader.jsonData.message);
    }
  });

  // handler for grid toolbar
  function onButtonClick(btn){
    switch (btn.id) {
    case 'addUser':
      processUserRow(0, 'create');
      break;
    case 'addUserGroup':
      processUserGroupRow(0, 'create');
      break;
    }
  }

  function onRowMenu(grid, rowIndex, e) {
    e.stopEvent();
    var coords = e.getXY();
    rowMenu.showAt([coords[0], coords[1]]);
    selectedRow = ds.data.items[rowIndex].id;
    if (ds.getById(selectedRow).get('TYPE') == '*USER') {
      rowMenu.items.get('copy').enable();
    } else {
      rowMenu.items.get('copy').disable();
    }
  }

  function onRowRightClick(item) {
    switch (item.id) {
    case 'edit':
      if (ds.getById(selectedRow).get('TYPE') == '*USER') {
        processUserRow(ds.getById(selectedRow).get('RRN'), 'update');
      } else {
        processUserGroupRow(ds.getById(selectedRow).get('RRN'), 'update');
      }
      break;
    case 'copy':
      if (ds.getById(selectedRow).get('TYPE') == '*USER') {
        processUserRow(ds.getById(selectedRow).get('RRN'), 'copy');
      } else {
        processUserGroupRow(ds.getById(selectedRow).get('RRN'), 'copy');
      }
      break;
    }
  }

  var windowCount = 0, windowCount2 = 0;
  function processUserRow(rrn, func) {
    var passwordPromptOpen = false;
  
    // Loading store with detail data
    var action = (func == 'create') ? 'init' : 'get';
    var userRowData = new Ext.data.JsonStore({
      url:'/'+hive['mnu004s']+'/mnu004s.asp?rrn='+rrn+'&action='+action
    });
    if (func == 'copy') {
      rrn = 0;
      func = 'create';
    }
    userRowData.on('load', function() {
      dsStatus = new Ext.data.SimpleStore({
        fields:['STSTS', 'STTXT']
        ,data :Ext.array.userStatus
      });
      dsTheme = new Ext.data.SimpleStore({
        fields:['THMCSS', 'THMTXT']
        ,data :Ext.array.theme
      });
      dsUserrole = new Ext.data.SimpleStore({
        fields:['role', 'text']
        ,data :Ext.array.userRole
      });
      var dsMetaform = new Ext.data.JsonStore({
        url:'/menu/metaform02.aspx?form=user'
      });
      dsMetaform.on('load', function() {
        var data = userRowData.getAt(0).data;
        var defaultExpDat = data['USREXPDAT'];
      // Building window & form

        var loginKey = new Ext.form.TextField({
          hideLabel:true
          ,name:'LOGINKEY'
          ,value:data['LOGINKEY']
          ,width:525
        });
      
        windowCount++;
    
        // tabs
        var tabs = [];

        var tab = {};
        tab.title = menu.I18N['profilePassword'];
        tab.xtype = 'form';
        tab.id = 'userform' + tabs.length;
        tab.defaults = {width:300}
        tab.autoScroll = true;
        tab.items = [
          {xtype:'hidden',id:'RUNASPWD'+windowCount,name:'RUNASPWD',value:data['RUNASPWD']}
          ,{xtype:'hidden',id:'as400profile'+windowCount,name:'as400profile',value:data['as400profile']}
          ,{xtype:'textfield',fieldLabel:menu.I18N['userId'],id:'USRNAM'+windowCount,name:'USRNAM',value:data['USRNAM'],allowBlank:false,style:{textTransform: "uppercase"},listeners:{change:function() { getUserName(this.getValue()) }}}
          ,{xtype:'textfield',fieldLabel:menu.I18N['name'],id:'USRTXT'+windowCount,name:'USRTXT',value:data['USRTXT'],width:300,allowBlank:false}
          ,{xtype:'textfield',vtype:'email',fieldLabel:menu.I18N['emailAddress'],name:'USREML',id:'USREML'+windowCount,value:data['USREML'],allowBlank:true}
          ,{xtype:'ddUserProfile',fieldLabel:menu.I18N['profileOnIBMi'],id:'RUNASUSR'+windowCount,hiddenName:'RUNASUSR',value:data['RUNASUSR'],displayValue:data['RUNASUSR'],hive:hive['mnu004l2'],allowBlank:true,width:300,windowCount:windowCount,triggerClass:'x-form-arrow-trigger RUNASUSR' + windowCount}
          ,{xtype:'textfield',fieldLabel:menu.I18N['password'],id:'USRPWD'+windowCount,name:'USRPWD',value:data['USRPWD'],inputType: 'password',style:{textTransform: "uppercase"},width:300}
          ,{xtype:'datefield',fieldLabel:menu.I18N['expirationDate'],id:'USREXPDAT'+windowCount,name:'USREXPDAT',value:data['USREXPDAT'],format:'d.m.Y',altFormats:'dmY|d-m-Y|d/m/Y',width:90,triggerClass:'x-form-date-trigger USREXPDAT' + windowCount}
          ,{xtype:'fieldset',title:menu.I18N['loginKey'],autoHeight:true,autoWidth:true
            ,items:[
              loginKey
              ,{xtype:'button',text:menu.I18N['createLoginKey']
                ,handler: function() {	
                  Ext.Ajax.request({
                    url:'/'+hive['mnu004s3']+'/mnu004s3.asp'
                    ,method: 'GET'
                    ,success: function(result,request) {
                      loginKey.setValue(result.responseText);
                      var pwd = Ext.getCmp('RUNASPWD'+windowCount).getValue();
                      if (pwd.length == 0) {
                        var usrId = Ext.getCmp('USRNAM'+windowCount).getValue();
                        passwordPrompt(usrId)
                      }
                    }
                  })
                }
              }
            ]
          } 
        ]
        tabs.push(tab);

        var tab = {};
        tab.title = menu.I18N['authoritySession'];
        tab.xtype = 'form';
        tab.id = 'userform' + tabs.length;
        tab.defaults = {width:300}
        tab.autoScroll = true;
        tab.items = [
          {xtype:'fieldset',title:menu.I18N['authority'],autoHeight:true,autoWidth:true,defaults:{width:280},labelWidth:218
            ,items:[
              {xtype:'ddUserClass',hiddenName:'USRUCLID',id:'USRUCLID'+windowCount,value:data['USRUCLID'],displayValue:data['UCLTXT'],hive:hive['mnu009l'],width:280}
              ,{xtype:'ddUserGroup',hiddenName:'USRUGRID',id:'USRUGRID'+windowCount,value:data['USRUGRID'],displayValue:data['UGRTXT'],hive:hive['mnu010l'],width:280}
              ,{xtype:'combo',fieldLabel:menu.I18N['userRole'],hiddenName:'userrole',id:'userrole'+windowCount,value:data['userrole'],store:dsUserrole,displayField:'text',valueField:'role',allowBlank:false,editable:true,mode:'local',forceSelection: true,triggerAction:'all',typeAhead:false,selectOnFocus:true,valueNotFoundText:menu.I18N['selectUserrole'],emptyText:menu.I18N['selectUserrole'],listWidth:280}
              ,{xtype:'combo',fieldLabel:menu.I18N['status'],hiddenName:'USRSTS',id:'USRSTS'+windowCount,value:data['USRSTS'],store:dsStatus,displayField:'STTXT',valueField:'STSTS',allowBlank:false,editable:true,mode:'local',forceSelection: true,triggerAction:'all',typeAhead:false,selectOnFocus:true,valueNotFoundText:menu.I18N['selectStatus'],emptyText:menu.I18N['selectStatus'],listWidth:280}
            ]
          }
          ,{xtype:'fieldset',title:menu.I18N['session'],autoHeight:true,autoWidth:true,defaults:{width:280},labelWidth:218
            ,items:[
              {xtype:'ddCcsid',hiddenName:'USCCSID',id:'USCCSID'+windowCount,value:data['USCCSID'],displayValue:data['USCCSID'],hive:hive['mnu013l'],width:280}
              ,{xtype:'fieldset',title:menu.I18N['workstationID'],autoHeight:true,autoWidth:true,defaults:{width:298},labelWidth:206
                ,items:[
				          {xtype:'textfield',fieldLabel:menu.I18N['deviceName'],name:'USRDEV',id:'USRDEV'+windowCount,value:data['USRDEV'],allowBlank:true}
				          ,{xtype:'checkbox',hideLabel:true,boxLabel:menu.I18N['avoidConflictOnThisDevice'],name:'USRACF1',id:'USRACF1'+windowCount,checked:(data['USRACF1'] == '1') ? true: false,allowBlank:true}
                ]
              }
            ]
          }
        ]
        tabs.push(tab);

        var tab = {};
        tab.title = menu.I18N['interfacePortal'];
        tab.xtype = 'form';
        tab.id = 'userform' + tabs.length;
        tab.defaults = {width:300}
        tab.autoScroll = true;
        tab.items = [
          {xtype:'fieldset',title:menu.I18N['interface'],autoHeight:true,autoWidth:true,defaults:{width:280},labelWidth:218
            ,items:[
              {xtype:'ddLanguage',hiddenName:'USRLNG',id:'USRLNG'+windowCount,value:data['USRLNG'],displayValue:data['LNGTXT'],hive:hive['mnu008l'],width:280}
              ,{xtype:'combo',fieldLabel:menu.I18N['generelTheme'],hiddenName:'USRTHM',id:'USRTHM'+windowCount,value:data['USRTHM'],store:dsTheme,displayField:'THMTXT',valueField:'THMCSS',allowBlank:false,editable:true,mode:'local',forceSelection: true,triggerAction:'all',typeAhead:false,selectOnFocus:true,listWidth:280}
              ,{xtype:'ddIcecapTheme',hiddenName:'icecapTheme',id:'icecapTheme'+windowCount,value:data['icecapTheme'],displayValue:data['icecapThemeD'],hive:hive['cfgStyleS'],width:280}
            ]
          }
          ,{xtype:'fieldset',title:menu.I18N['portal'],autoHeight:true,autoWidth:true,defaults:{width:280},labelWidth:218
            ,items:[
              {xtype:'radio',fieldLabel:menu.I18N['portalStartPage'],name:'portalStartPage',checked:(data['portalStartPage'] == 'system') ? true: false,inputValue:'system',boxLabel:menu.I18N['portalStartDefault']
                ,listeners: {
                  check:function(box,checked){
                    if (checked) {
                      var obj = Ext.getCmp('portalStartPageUrl'+windowCount);
                      obj.setValue('');
                      var obj = Ext.getCmp('portalStartPageTitle'+windowCount);
                      obj.setValue('');
                    }
                  }
                }
              }
              ,{xtype:'radio',fieldLabel:'',labelSeparator: '',name:'portalStartPage',checked:(data['portalStartPage'] == 'portal') ? true: false,inputValue:'portal',boxLabel:menu.I18N['portalStartPagePortal']
                ,listeners: {
                  check:function(box,checked){
                    if (checked) {
                      var obj = Ext.getCmp('portalStartPageTitle'+windowCount);
                      if (obj.getValue() == '') {
                        obj.setValue('Portal');
                      }
                    }
                  }
                }
              }
              ,{xtype:'radio',fieldLabel:'',labelSeparator: '',name:'portalStartPage',checked:(data['portalStartPage'] == 'initialmenu') ? true: false,inputValue:'initialmenu',boxLabel:menu.I18N['portalStartPageInitalMenu']
                ,listeners: {
                  check:function(box,checked){
                    if (checked) {
                      var obj = Ext.getCmp('portalStartPageTitle'+windowCount);
                      if (obj.getValue() == '') {
                        obj.setValue('Initial Menu');
                      }
                    }
                  }
                }
              }
              ,{xtype:'radio',fieldLabel:'',labelSeparator: '',name:'portalStartPage',checked:(data['portalStartPage'] == 'customized') ? true: false,inputValue:'customized',boxLabel:menu.I18N['portalStartPageCustomized']
                ,listeners: {
                  check:function(box,checked){
                    var obj = Ext.getCmp('portalStartPageUrl'+windowCount);
                    if (checked) {
                      obj.enable();
                      var obj = Ext.getCmp('portalStartPageTitle'+windowCount);
                      if (obj.getValue() == '') {
                        obj.setValue('Customized');
                      }
                    } else {
                      obj.disable();
                    }
                  }
                }
              }
              ,{xtype:'textfield',fieldLabel:menu.I18N['portalStartPageUrl'],name:'portalStartPageUrl',id:'portalStartPageUrl'+windowCount,value:data['portalStartPageUrl'],disabled:(data['portalStartPage'] == 'customized') ? false: true}
              ,{xtype:'textfield',fieldLabel:menu.I18N['portalStartPageTitle'],name:'portalStartPageTitle',id:'portalStartPageTitle'+windowCount,value:data['portalStartPageTitle'],width:300}
            ]
          }
        ]
        tabs.push(tab);

        var menuMenuStore = new Ext.data.JsonStore({
          totalProperty:'totalRows'
          ,root:'rows'
          ,url:'/'+hive['mnu005l']+'/mnu005l.asp?all=1'
          ,id:'MNUID'
          ,fields:[
                    'MNUID'
                    ,'MTXTXT'
          ]
          ,remoteSort:false
        });
        var menuMenu = new Ext.form.ComboBox({
          fieldLabel:menu.I18N['link']
          ,hiddenName:'startPageMenu'
          ,value:data.startPageMenu
          ,store:menuMenuStore
          ,displayField:'MTXTXT'
          ,valueField:'MNUID'
          ,allowBlank:true
          ,editable:true
          ,mode:'local'
          ,forceSelection:false
          ,triggerAction:'all'
          ,typeAhead:false
          ,selectOnFocus:true
          ,valueNotFoundText:menu.I18N['selectLink']
          ,emptyText:menu.I18N['selectLink']
        });

        var menuSystem = new menu.ddSystem({
          hiddenName:'startPageSystem'
          ,value:data.startPageSystem
          ,displayValue:data['STXTXT']
          ,hive:hive['mnu007l']
          ,valueNotFoundText:menu.I18N['selectSystem']
          ,emptyText:menu.I18N['selectSystem']
          ,listeners: {
            select: function(box) {
              menuMenuStore.baseParams = {
                system: box.getValue()
              }
              menuMenuStore.load()
              menuMenuStore.on('load', function() {
                menuMenu.setValue('0')
              })
            }
          }
        });
        if (data.startPageSystem && data.startPageSystem.length > 0) {
          menuSystem.store.load();
          menuSystem.store.on('load', function() {
            menuSystem.setValue(data.startPageSystem);
          });
        }
        if (data.startPageSystem && data.startPageMenu && data.startPageMenu.length > 0) {
          menuMenuStore.load();
          menuMenuStore.on('load', function() {
            menuMenu.setValue(data.startPageMenu);
          });
        }

        var tab = {};
        tab.title = menu.I18N['startPage'];
        tab.xtype = 'form';
        tab.id = 'userform' + tabs.length;
        tab.defaults = {width:300, listWidth: 300}
        tab.autoScroll = true;
        tab.items = [
          menuSystem,
          menuMenu,
          {xtype:'checkbox', hideLabel:true, boxLabel:menu.I18N['startWithoutMenu'], name:'startPageWithoutMenu', checked:(data.startPageWithoutMenu == 'on') ? true: false, allowBlank:true}
        ]
        tabs.push(tab);

        var tab = {};
        tab.title = menu.I18N['history'];
        tab.xtype = 'form';
        tab.id = 'userform' + tabs.length;
        tab.defaults = {width:300}
        tab.autoScroll = true;
        tab.items = [
          {xtype:'fieldset',title:menu.I18N['previousLoginTime'],autoHeight:true,autoWidth:true,labelWidth:218
            ,items:[
              {xtype:'datefield',fieldLabel:menu.I18N['date'],name:'USRLOGDAT',id:'USRLOGDAT'+windowCount,value:data['USRLOGDAT'],format:'d.m.Y',readOnly:true,hideTrigger:true,tabIndex:-1,cls:'smd-form-field-readonly'}
              ,{xtype:'datefield',fieldLabel:menu.I18N['time'],name:'USRLOGTIM',id:'USRLOGTIM'+windowCount,value:data['USRLOGTIM'],format:'H:i:s',readOnly:true,hideTrigger:true,tabIndex:-1,cls:'smd-form-field-readonly'}
            ]
          }
          ,{xtype:'textfield',fieldLabel:menu.I18N['unsuccessfulLoginAttempts'],name:'USRATM',id:'USRATM'+windowCount,value:data['USRATM'],readOnly:true,tabIndex:-1,cls:'smd-form-field-readonly'}
        ]
        tabs.push(tab);

        // metaform tabs
        var maxi = dsMetaform.getTotalCount();
        for (i=0; i<=maxi-1; i++) {
          var tab = {};
          tab.title = dsMetaform.getAt(i).data['caption'];
          tab.xtype = 'panel';
          tab.layout = 'form';
          tab.autoScroll = true;
          tab.items = {
            xtype:'iceMetaForm'
            ,url:'/menu/metaForm.aspx?xml='+dsMetaform.getAt(i).data['xml']+'&form=user&key='+data['USRID']
          };
          tabs.push(tab);
        }          

        var windowID = 'mnu004-window-' + windowCount;
        var title = (func == 'create') ? menu.I18N['addNew'] : menu.I18N['update'];
        if (!winUsr) {
          var winUsr = new Ext.Window({
            id: windowID
            ,title:title
            ,width:590
            ,height:424
            ,minWidth:50
            ,minHeight:50
            ,autoScroll:true
            ,bodyStyle:'padding:5px;'
            ,layout:'fit'
            ,plain:true
            ,modal:false
            ,items:{
              xtype:'tabpanel'
              ,id:'tabs'
              ,activeTab: 0
              ,frame:false
              ,defaults:{autoHeight:true,bodyStyle:'padding:5px 5px 0',labelWidth:230}
              ,deferredRender:false
              ,items:tabs
            }
            ,buttons: [{
              text: menu.I18N['save']
              ,type: 'submit'
              ,handler: function() {
                var isValid = true;

                var i=0;
                var params = {};
                for (i=0;i<=tabs.length;i++) {
                  var form = Ext.getCmp('userform'+i);
                  if (form) {
                    if (form.getForm().isValid()) {
                      var p = form.getForm().getValues()
                      for (var o in p) {
                        params[o] = p[o];
                      }
                    } else {
                      isValid = false;
                      break;
                    }
                  }
                }

                if (isValid) {
                  var usr      = Ext.getCmp('USRNAM'+windowCount).getValue();
                  var runasusr = Ext.getCmp('RUNASUSR'+windowCount).getValue();
                  var runaspwd = Ext.getCmp('RUNASPWD'+windowCount).getValue();
                  if (usr.toUpperCase() != runasusr.toUpperCase() && runasusr.length > 0 && runaspwd.length == 0) {
                    passwordPrompt(runasusr)
                  } else {
                    Ext.Ajax.request({
                      url:'/'+hive['mnu004s']+'/mnu004s.asp?RRN='+rrn+'&action='+func
			                ,method:'POST'
                      ,params:params
			                ,success: function (response,request) {
                        winUsr.hide()
                        ds.load()
                        iceSaveMetaForm(winUsr);
                      }
                    })
                  }
                }
              }
              ,key:'ENTER'
            },{
              text: menu.I18N['delete'],
              handler: function(){
                Ext.MessageBox.confirm(menu.I18N['message'], menu.I18N['confirmDelete'] , doUserDelete);
              }
            },{
              text: menu.I18N['cancel']
              ,handler: function() {
                winUsr.hide();
              }
            }]
          })
        }
        winUsr.show();

        if (func == 'create') {
          winUsr.buttons[1].disable();
        }
      
	      Ext.getCmp('RUNASUSR'+windowCount).addListener(
	        'change'
	        ,function () {
		        Ext.getCmp('RUNASPWD'+windowCount).setValue('');
		        var runasusr = Ext.getCmp('RUNASUSR'+windowCount);
            var runAsUsrVal = runasusr.getValue();
            var promptPassword = (runAsUsrVal.length > 0) ? true : false;
		        checkRunAsUser(runasusr, promptPassword);
  	      }
  	      ,this
  	      ,{delay:100}
  	    ); 

        Ext.getCmp('USRNAM'+windowCount).on({
          'render' : {
            fn: Ext.getCmp('USRNAM'+windowCount).focus(false,50)
            ,delay:500
          }
        });

        openCloseFields(data['USRID'], data['RUNASUSR'], data['as400profile'], false);

        if (data['invalidPassword']) {
          Ext.MessageBox.alert(menu.I18N['message'], menu.I18N['invalidPassword'] , typeNewPassword);
        }
      
        function typeNewPassword() {
          var v = Ext.getCmp('RUNASUSR'+windowCount).getValue();
          if (v.length == 0) {
            var v = Ext.getCmp('USRNAM'+windowCount).getValue();
          }
          passwordPrompt(v);
        }
        function saveParams(params, field) {
          if (field instanceof Ext.form.DateField) {
            if (field.enable()) {
              params[field.getName()] = field.value;
            } else {
              params[field.getName()] = field.getValue().dateFormat("Y-m-d");
            }
          } else {
            params[field.getName()] = field.getValue();
          }
          return params;
        }
        function doUserDelete(btn) {
          if (btn == 'yes') {
					  Ext.Ajax.request({
              url:'/'+hive['mnu004s']+'/mnu004s.asp?rrn='+rrn+'&action=delete'
              ,success: function(rsp) {
                winUsr.hide();
                ds.load();
              }
              ,waitMsg:menu.I18N['deletingData']
            });
          }
        }
        function getUserName(usr) {
          usr = usr.toUpperCase();
          var tempData = new Ext.data.JsonStore({
            autoLoad:true
            ,url:'/'+hive['mnu004s4']+'/mnu004s4.asp?id='+usr
          });
          tempData.on('load', function() {
            var runAsUsr = Ext.getCmp('RUNASUSR'+windowCount);
            var runAsPwd = Ext.getCmp('RUNASPWD'+windowCount).getValue();

            var data = tempData.getAt(0).data;
            var found = (data['USRNAM'] == 'not found') ? false : true;
            if (found) {
              Ext.getCmp('USRTXT'+windowCount).setValue(data['USRNAM']);
              Ext.getCmp('as400profile'+windowCount).setValue('true');
            
              var value = runAsUsr.getValue();
              if (value == '0' || value.length == 0) {
                runAsUsr.setValue(usr);
              }
            } else {
              Ext.getCmp('as400profile'+windowCount).setValue('false');
            }
            var runAsUsrVal = runAsUsr.getValue();
            var promptPassword = (usr != runAsUsrVal && runAsUsrVal.length > 0 && runAsPwd.length == 0) ? true : false;
            checkRunAsUser(runAsUsr, promptPassword);
          })
        }
        function checkRunAsUser(f,promptPassword) {
          var usrid = Ext.getCmp('USRNAM'+windowCount).getValue().toUpperCase();
          var value = f.getValue();
          if (value.length == 0) {
            var runasUsrid = '';
            Ext.getCmp('RUNASPWD'+windowCount).setValue('');
          } else {
            var store = f.getStore();
            var index = store.find('USRID', value);
            var record = store.getAt(index);
            if (record == undefined) {
              var runasUsrid = value;
            } else {
              var runasUsrid = record.data['USRNAM'];
            }
          }
          var as400profile = Ext.getCmp('as400profile'+windowCount).getValue();
          openCloseFields(usrid, runasUsrid, as400profile, promptPassword);
        }
        function openCloseFields(usrid, runasUsrid, as400profile, promptPassword) {
          if (as400profile == 'false') {
            var open = true;
            var prompt = true;
          } else if (usrid.toUpperCase() == runasUsrid.toUpperCase()) {
            var open = false;
            var prompt = false;
          } else {
            var open = true;
            var prompt = true;
          }
          if (open && as400profile == 'false') {
            Ext.getCmp('USRPWD'+windowCount).enable();
            Ext.getCmp('USRPWD'+windowCount).removeClass('mnu-output-field');
          
            Ext.getCmp('RUNASUSR'+windowCount).enable();
            Ext.getCmp('RUNASUSR'+windowCount).removeClass('mnu-output-field');
            setTriggerFieldClass('RUNASUSR'+windowCount, 'x-form-arrow-trigger', true);
          
            Ext.getCmp('USREXPDAT'+windowCount).enable();
            Ext.getCmp('USREXPDAT'+windowCount).setValue(defaultExpDat);
            Ext.getCmp('USREXPDAT'+windowCount).removeClass('mnu-output-field');
            setTriggerFieldClass('USREXPDAT'+windowCount, 'x-form-date-trigger', true);
          } else {
            Ext.getCmp('USRPWD'+windowCount).setValue('');
            Ext.getCmp('USRPWD'+windowCount).addClass('mnu-output-field');
            Ext.getCmp('USRPWD'+windowCount).disable();

            Ext.getCmp('RUNASUSR'+windowCount).setValue('');
            Ext.getCmp('RUNASUSR'+windowCount).addClass('mnu-output-field');
            Ext.getCmp('RUNASUSR'+windowCount).disable();
            setTriggerFieldClass('RUNASUSR'+windowCount, 'x-form-arrow-trigger', false);

            Ext.getCmp('USREXPDAT'+windowCount).setValue('');
            Ext.getCmp('USREXPDAT'+windowCount).disable();
            Ext.getCmp('USREXPDAT'+windowCount).addClass('mnu-output-field');
            setTriggerFieldClass('USREXPDAT'+windowCount, 'x-form-date-trigger', false);
          }
          if (prompt && promptPassword) {
            passwordPrompt(runasUsrid);
          }
        }
        function setTriggerFieldClass(searchClass, triggerClass, add) {
          var els = document.getElementsByTagName('img');
          var elsLen = els.length;
          var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
          for (i = 0; i < elsLen; i++) {
            if ( pattern.test(els[i].className) ) {
              if (add) {
                els[i].className = 'x-form-trigger ' + triggerClass + ' ' + searchClass;
              } else {
                els[i].className = searchClass;
              }
              return;
            }
          }
          return;
        }
        function passwordPrompt(runasUsrid) {
          if (passwordPromptOpen) { return; }

          passwordPromptOpen = true;
          windowCount2++;

          var label = menu.I18N['verifyUseOfProfile'] + ' ' + runasUsrid + '<br/>' + menu.I18N['typingCorrespondingPassword']
          var frmPwd = new Ext.form.FormPanel({
            labelAlign: 'left'
            ,border:false
            ,frame:false
            ,bodyStyle:'padding:5px 5px 0'
            ,labelWidth:280
            ,items:[
              {xtype:'textfield',fieldLabel:label,id:'PASSWORD'+windowCount2,name:'PASSWORD',inputType:'password',style:{textTransform:"uppercase"},width:300,allowBlank:false}
            ]
          });
        
          var windowID = 'mnu004-prompt-' + windowCount2;
          if (!winPwd) {
            var winPwd = new Ice.Window({
              id: windowID
              ,title:menu.I18N['verifyUseOfProfile']
              ,width:630
              ,height:140
              ,minWidth:50
              ,minHeight:50
              ,autoScroll:true
              ,bodyStyle:'padding:5px;'
              ,layout:'fit'
              ,plain:true
              ,modal:false
              ,items:frmPwd
              ,buttons: [{
                text: 'OK'
                ,type: 'submit'
                ,handler: function() {
                  if (frmPwd.form.isValid()) {
                    frmPwd.form.submit({
                      url:'/'+hive['mnu004s5']+'/mnu004s5.asp?usrid='+runasUsrid.toUpperCase()
                      ,success: function() {
                        Ext.getCmp('RUNASPWD'+windowCount).setValue(Ext.getCmp('PASSWORD'+windowCount2).getValue());
                        Ext.getCmp('RUNASUSR'+windowCount).focus();
                        winPwd.hide();
                        passwordPromptOpen = false;
                      }
                    })
                  }
                }
                ,key:'ENTER'
              },{
                text: menu.I18N['cancel']
                ,handler: function() {
                  Ext.getCmp('RUNASUSR'+windowCount).focus();
                  winPwd.hide();
                  passwordPromptOpen = false;
                }
              }]
              ,listeners:{
                show: function(win) {
                  pos = win.getPosition();
                  win.setPagePosition(pos[0]+40,pos[1]+40);
                  Ext.getCmp('PASSWORD'+windowCount2).focus(false,50)
                }
              }
            })
          }
          winPwd.show();
        }
      })
      dsMetaform.load()
    })
    userRowData.load()
  }
  function processUserGroupRow(rrn, func) {
    // Loading store with detail data
    var action = (func == 'create') ? 'init' : 'get';
    var userGroupRowData = new Ext.data.JsonStore({
      url:'/'+hive['mnu010s']+'/mnu010s.asp?rrn='+rrn+'&action='+action
      ,root:'data'
      ,fields: [
                 'UGRID'
                 ,'UGRTXT'
                 ,'UGRICM'
                 ,'hasChildren'
                 ,'startPageSystem'
                 ,'startPageMenu'
                 ,'startPageWithoutMenu'
               ]
    });
    userGroupRowData.on('load', function() {  
      var data = userGroupRowData.getAt(0).data;

      var dsGrpMnu = new Ext.data.JsonStore({
        totalProperty:'totalRows'
        ,root:'rows'
        ,url:'/'+hive['mnu005l']+'/mnu005l.asp?mode=usergroup&UGRID='+data['UGRID']
        ,id:'MNUID'
        ,fields:[
                  'MNUID'
                  ,'MTXTXT'
                  ,'INDENT'
                  ,'CHECKED'
        ]
        ,remoteSort:false
      });
      dsGrpMnu.on('load', function() {
        // Building user group / application relation
        var grpMnuArray = new Array();
        var maxi = dsGrpMnu.getTotalCount();
        for (i=0; i<=maxi-1; i++) {
          var obj = new Object();
          if (dsGrpMnu.getAt(i).data['INDENT'] == 0) {
            var text = dsGrpMnu.getAt(i).data['MTXTXT'];
            obj.xtype='label';
            obj.text=text;
            obj.style='{font-weight:bold;}';
          } else {
            var value = dsGrpMnu.getAt(i).data['MTXTXT'];
            var text = String.format('<img src="/menu/images/space.gif" width="{0}" height="1" />{1}', dsGrpMnu.getAt(i).data['INDENT'] * 15, value);
            obj.xtype='checkbox';
            obj.hideLabel = true;
            obj.boxLabel=text;
            obj.name = 'MNUID.' + dsGrpMnu.getAt(i).data['MNUID'];
            if (dsGrpMnu.getAt(i).data['CHECKED'] == 'true') {
              obj.checked = true;
            } else {
              obj.checked = false;
            }
          }
          grpMnuArray[i] = obj;
        };
        var dsGrpWS = new Ext.data.JsonStore({
          totalProperty:'totalRows'
          ,root:'rows'
          ,url:'/'+hive['mnu015l']+'/mnu015l.asp?mode=relation&UGRID='+data['UGRID']
          ,id:'WSVID'
          ,fields:[
                    'WSVID'
                    ,'WSVAPP'
                    ,'CHECKED'
          ]
          ,remoteSort:false
        });
        dsGrpWS.on('load', function() {
          // Building user group / web service relation
          var grpWSArray = new Array();
          var maxi = dsGrpWS.getTotalCount();
          for (i=0; i<=maxi-1; i++) {
            var obj = {};
            obj.xtype='checkbox';
            obj.hideLabel = true;
            obj.boxLabel=dsGrpWS.getAt(i).data['WSVAPP'];
            obj.name = 'WSVID.' + dsGrpWS.getAt(i).data['WSVID'];
            if (dsGrpWS.getAt(i).data['CHECKED'] == 'true') {
              obj.checked = true;
            } else {
              obj.checked = false;
            }
            grpWSArray[i] = obj;
          };

          var dsMetaform = new Ext.data.JsonStore({
            url:'/menu/metaform02.aspx?form=usergroup'
          });
          dsMetaform.on('load', function() {
            var tabs = [];

            var tab = {};
            tab.title = menu.I18N['generel'];
            tab.xtype = 'form';
            tab.id = 'usergroupform' + tabs.length;
            tab.defaults = {width:300}
            tab.autoScroll = true;
            tab.items = [
              {xtype:'textfield',fieldLabel:menu.I18N['description'],name:'UGRTXT',value:data['UGRTXT'],allowBlank:false}
              ,{xtype:'label',text:menu.I18N['initialCommand4IceCap']+':',style:'font-size:12px;'}
              ,{xtype:'textfield',hideLabel:true,name:'UGRICM',value:data['UGRICM'],width:425,allowBlank:true}
            ]
            tabs.push(tab);

            var tab = {};
            tab.title = menu.I18N['application'];
            tab.xtype = 'form';
            tab.id = 'usergroupform' + tabs.length;
            tab.defaults = {width:300}
            tab.autoScroll = true;
            tab.items = grpMnuArray;
            tabs.push(tab);

            var tab = {};
            tab.title = menu.I18N['webservice'];
            tab.xtype = 'form';
            tab.id = 'usergroupform' + tabs.length;
            tab.defaults = {width:300}
            tab.autoScroll = true;
            tab.items = grpWSArray;
            tabs.push(tab);

            var menuMenuStore = new Ext.data.JsonStore({
              totalProperty:'totalRows'
              ,root:'rows'
              ,url:'/'+hive['mnu005l']+'/mnu005l.asp?all=1'
              ,id:'MNUID'
              ,fields:[
                        'MNUID'
                        ,'MTXTXT'
              ]
              ,remoteSort:false
            });
            var menuMenu = new Ext.form.ComboBox({
              fieldLabel:menu.I18N['link']
              ,hiddenName:'startPageMenu'
              ,value:data.startPageMenu
              ,store:menuMenuStore
              ,displayField:'MTXTXT'
              ,valueField:'MNUID'
              ,allowBlank:true
              ,editable:true
              ,mode:'local'
              ,forceSelection:false
              ,triggerAction:'all'
              ,typeAhead:false
              ,selectOnFocus:true
              ,valueNotFoundText:menu.I18N['selectLink']
              ,emptyText:menu.I18N['selectLink']
            });

            var menuSystem = new menu.ddSystem({
              hiddenName:'startPageSystem'
              ,value:data.startPageSystem
              ,displayValue:data['STXTXT']
              ,hive:hive['mnu007l']
              ,valueNotFoundText:menu.I18N['selectSystem']
              ,emptyText:menu.I18N['selectSystem']
              ,listeners: {
                select: function(box) {
                  menuMenuStore.baseParams = {
                    system: box.getValue()
                  }
                  menuMenuStore.load()
                  menuMenuStore.on('load', function() {
                    menuMenu.setValue('0')
                  })
                }
              }
            });
            if (data.startPageSystem && data.startPageSystem.length > 0) {
              menuSystem.store.load();
              menuSystem.store.on('load', function() {
                menuSystem.setValue(data.startPageSystem);
              });
            }
            if (data.startPageSystem && data.startPageMenu && data.startPageMenu.length > 0) {
              menuMenuStore.load();
              menuMenuStore.on('load', function() {
                menuMenu.setValue(data.startPageMenu);
              });
            }

            var tab = {};
            tab.title = menu.I18N['startPage'];
            tab.xtype = 'form';
            tab.id = 'usergroupform' + tabs.length;
            tab.defaults = {width:300, listWidth: 300}
            tab.autoScroll = true;
            tab.items = [
              menuSystem,
              menuMenu,
              {xtype:'checkbox', hideLabel:true, boxLabel:menu.I18N['startWithoutMenu'], name:'startPageWithoutMenu', checked:(data.startPageWithoutMenu == 'on') ? true: false, allowBlank:true}
            ]
            tabs.push(tab);

            var maxi = dsMetaform.getTotalCount();
            for (i=0; i<=maxi-1; i++) {
              var tab = {};
              tab.title = dsMetaform.getAt(i).data['caption'];
              tab.xtype = 'panel';
              tab.layout = 'form';
              tab.autoScroll = true;
              tab.items = {
                xtype:'iceMetaForm'
                ,url:'/menu/metaForm.aspx?xml='+dsMetaform.getAt(i).data['xml']+'&form=userGroup&key='+data['UGRID']
              };
              tabs.push(tab);
            }          
            // Building window
            var windowID = 'mnu005-window-' + windowCount++;
            var title = (func == 'create') ? menu.I18N['addNew'] : menu.I18N['update'];
            if (!winUsrGrp) {
              var winUsrGrp = new Ice.Window({
                id: windowID
                ,title: title
                ,border:false
                ,width: 486
                ,height: 525
                ,minWidth: 50
                ,minHeight: 50
                ,bodyStyle:'padding:5px;'
                ,buttonAlign:'left'
                ,layout: 'fit'
                ,plain:true
                ,modal: false
                ,items:{
                  xtype:'tabpanel'
                  ,id:'tabs'
                  ,activeTab: 0
                  ,frame:false
                  ,defaults:{height:530,bodyStyle:'padding:5px 5px 0',labelWidth:120}
                  ,deferredRender:false
                  ,items:tabs
                }
                ,buttons: [{
                  text: menu.I18N['save']
                  ,type: 'submit'
                  ,handler: function() {	
                    var isValid = true;

                    var i=0;
                    var params = {};
                    for (i=0;i<=tabs.length;i++) {
                      var form = Ext.getCmp('usergroupform'+i);
                      if (form) {
                        if (form.getForm().isValid()) {
                          var p = form.getForm().getValues()
                          for (var o in p) {
                            params[o] = p[o];
                          }
                        } else {
                          isValid = false;
                          break;
                        }
                      }
                    }

                    if (isValid) {
                      Ext.Ajax.request({
                        url:'/'+hive['mnu010s']+'/mnu010s.asp?RRN='+rrn+'&action='+func
			                  ,method:'POST'
                        ,params:params
			                  ,success: function (response,request) {
                          winUsrGrp.hide()
                          ds.load()
                          iceSaveMetaForm(winUsrGrp);
                        }
                      })
                    }
                  }
                  ,key:'ENTER'
                },{
                  text: menu.I18N['delete'],
                  handler: function(){
                    Ext.MessageBox.confirm(menu.I18N['message'], menu.I18N['confirmDelete'] , doUserGroupDelete);
                  }
                },{
                  text: menu.I18N['cancel']
                  ,handler: function() {
                    winUsrGrp.hide();
                  }
                }]
              })
            }
            winUsrGrp.show();

            if (func == 'create' || data['hasChildren'] == 'true') {
              winUsrGrp.buttons[1].disable();
            }

            function doUserGroupDelete(btn) {
              if (btn == 'yes') {
					      Ext.Ajax.request({
                  url:'/'+hive['mnu010s']+'/mnu010s.asp?rrn='+rrn+'&action=delete'
                  ,success: function(rsp) {
                    winUsrGrp.hide();
                    ds.load();
                  }
                  ,waitMsg:menu.I18N['deletingData']
                });
              }
            }
          })
          dsMetaform.load()
        })
        dsGrpWS.load()
      })
      dsGrpMnu.load()
    })
    userGroupRowData.load()
  }
});