Ext.ux.ComboBoxChoose = Ext.extend(Ext.form.ComboBox, {
  forceSelection: true,
  typeAhead: true,
  triggerAction: 'all',
  selectOnFocus:true,
  listeners: {
    beforeselect: function(c, r, i){
      if(r.json.customField){
        setTimeout(function(){
          Ext.Msg.prompt('Add Custom Item', 'Please type the new item:', function(btn, text){
            if (btn == 'ok'){
              c.setValue(text);
            }
          });
        }, 10);
        c.collapse();
        return false;
      }
    }
  }
});

CS2.Content = {};
CS2.Content.Delete = function(initOptions){
    var _self = this;
    this.settings = {};
    Ext.apply(this.settings, initOptions);
    this.win = new Ext.Window({
        title: 'Delete Content',
        width:380,
        resizable: false,
        constrainHeader: true,
        cls: 'x-window-dlg',
        layout: 'fit',
        plain: true,
        bodyStyle: 'font-size: 13px; padding: 10px;',
        html: new Ext.XTemplate(
          '<div class="x-dlg-icon">',
            '<div class="ext-mb-icon ext-mb-warning"></div>',
            '<div class="ext-mb-content">',
              '<span class="ext-mb-text">',
                '<strong>Are you sure you want to delete this item and associated navigation?</strong>',
                '<br /><br />',
                'By deleting this content any linking navigation items will be removed too! This cannot be undone!',
              '</span>',
            '</div>',
            '<div class="x-clear"></div>',
          '</div>'
        ).apply(),
        buttons: [{
            text:'Delete (3)',
            ref: '../DeleteButton',
            disabled:true,
            handler: function(){
              var params = {dataID: _self.settings.dataID};
              Ext.Ajax.request({
                 url: '/ajax/editor/deleteData.cfm',
                 method: 'GET',
                 'params': params,
                 reader : new Ext.data.JsonReader({
                  success : '@success'
                 }),
                 success: function(response, opts) {
                    var obj = Ext.decode(response.responseText);
                    if (obj.success){
                      window.location.reload(true);
                      _self.win.hide();
                    }else{
                      Ext.Msg.alert('Error Deleting Content', 'This content could not be deleted. Please try again.');
                    }
                 },
                 failure: function(response, opts) {
                  Ext.Msg.alert('Error Deleting Content', 'There was a problem communicating with the server. Please check your internet connection and try again.');
                 }
              });   
              
            }
        },{
            text: 'Cancel',
            handler: function(){
                this.ownerCt.ownerCt.hide();
            }
        }]
    });
    this.win.show(this);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete (2)'); }, CS2.countDownSpeed * 1);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete (1)'); }, CS2.countDownSpeed * 2);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete'); _self.win.DeleteButton.enable(); }, CS2.countDownSpeed * 3);
};
CS2.Content.DeleteSyndicatedItem = function(initOptions){
    var _self = this;
    this.settings = {};
    Ext.apply(this.settings, initOptions);
    this.win = new Ext.Window({
        title: 'Remove Syndicated Item',
        width:380,
        resizable: false,
        cls: 'x-window-dlg',
        constrainHeader: true,
        layout: 'fit',
        plain: true,
        bodyStyle: 'font-size: 13px; padding: 10px;',
        html: new Ext.XTemplate(
          '<div class="x-dlg-icon">',
            '<div class="ext-mb-icon ext-mb-warning"></div>',
            '<div class="ext-mb-content">',
              '<span class="ext-mb-text">',
                '<strong>Are you sure you would like to remove the syndication of the item to this '+CS2.schoolSubsiteVerbage()+'?</strong>',
                '<br /><br />',
                'By removing this content only the syndication of this item and its recurrences will be removed, the item will not be deleted.',
              '</span>',
            '</div>',
            '<div class="x-clear"></div>',
          '</div>'
        ).apply(),
        buttons: [{
            text:'Delete (3)',
            ref: '../DeleteButton',
            disabled:true,
            handler: function(){
              var params = {dataID: _self.settings.dataID};
              Ext.Ajax.request({
                 url: '/ajax/editor/deleteSyndicatedData.cfm',
                 method: 'GET',
                 'params': params,
                 reader : new Ext.data.JsonReader({
                  success : '@success'
                 }),
                 success: function(response, opts) {
                    var obj = Ext.decode(response.responseText);
                    if (obj.success){
                      window.location.reload(true);
                      _self.win.hide();
                    }else{
                      Ext.Msg.alert('Error Deleting Content', 'This content could not be deleted. Please try again.');
                    }
                 },
                 failure: function(response, opts) {
                  Ext.Msg.alert('Error Deleting Content', 'There was a problem communicating with the server. Please check your internet connection and try again.');
                 }
              });   
              
            }
        },{
            text: 'Cancel',
            handler: function(){
                this.ownerCt.ownerCt.hide();
            }
        }]
    });
    this.win.show(this);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete (2)'); }, CS2.countDownSpeed * 1);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete (1)'); }, CS2.countDownSpeed * 2);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete'); _self.win.DeleteButton.enable(); }, CS2.countDownSpeed * 3);
};
CS2.User = {};
CS2.User.genPassSettings = {};
CS2.User.genPassSettings.ucase = true;
CS2.User.genPassSettings.numbers = true;
CS2.User.genPassSettings.symbols = false;
CS2.User.genPassSettings.maxlength = 8;
CS2.User.GeneratePassword = function(initOptions){
    var _self = this;
    this.settings = {};
    Ext.apply(this.settings, initOptions);
    
    this.passOptions = {
                        xtype: 'panel',                
                        border: true,
                        padding: 10,
                        layout: 'fit',
                        items: {
                                xtype: 'checkboxgroup',
                                hideLabel: true,
                                columns: 1,
                                items: [
                                    {boxLabel: 'Include Uppercase', id: 'passIncludeUCase', name: 'gp-uc', checked: CS2.User.genPassSettings.ucase},
                                    {boxLabel: 'Include Numbers', id: 'passIncludeNumbers', name: 'gp-num', checked: CS2.User.genPassSettings.numbers},
                                    {boxLabel: 'Include Symbols', id: 'passIncludeSymbols', name: 'gp-sym', checked: CS2.User.genPassSettings.symbols},
                                    {
                                      xtype: 'spinnerfield',
                                      fieldLabel: 'Length',
                                      id: 'max_length_field',
                                      name: 'max_length',
                                      value: CS2.User.genPassSettings.maxlength,
                                      minValue: 5,
                                      maxValue: 14,
                                      allowDecimals: false,
                                      decimalPrecision: 1,
                                      incrementValue: 1,
                                      alternateIncrementValue: 2
                                    }
                                ]
                        }
                      };
    
    var winUploadThumbnail = new Ext.Window({title: 'Generate Password', constrainHeader: true, width: 250, height: 210, modal: true, resizable: false, padding: 10, closeAction:'close', items:this.passOptions,
        buttons: [{
                    text: 'Generate',
                    handler: function(){
                      var newPassword = '';
                      var includeNumbers = Ext.getCmp('passIncludeNumbers').getValue();
                      var includeSymbols = Ext.getCmp('passIncludeSymbols').getValue();
                      var includeUCase = Ext.getCmp('passIncludeUCase').getValue();
                      var maxLen = Ext.getCmp('max_length_field').getValue();
                      CS2.User.genPassSettings.numbers = includeNumbers;
                      CS2.User.genPassSettings.symbols = includeSymbols;
                      CS2.User.genPassSettings.ucase = includeUCase;
                      CS2.User.genPassSettings.maxlength = maxLen;
                      var charList = "";
                      var abcList = "abcdefghijklmnopqrstuvwxyz";
                      var ABCList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                      var numList = "0123456789";
                      var sysList = "~!@#$%^&*()_+-={}[]|\/?<>,.;:";
                      
                      charList = abcList;
                      if (includeUCase)
                        charList += ABCList;
                      if (includeNumbers)
                        charList += numList;
                      if (includeSymbols)
                        charList += sysList;
                      
                      for(var m=0; m<1000; m++){
                        newPassword = "";
                        found_abc = false;
                        found_ABC = false;
                        found_num = false;
                        found_sys = false;
                        for(var n=0; n<maxLen; n++){
                          for(var nn=0; nn<100; nn++){
                            var charIndex1 = Math.floor(Math.random()*(charList.length+1));
                            var charIndex2 = Math.floor(Math.random()*(charList.length+1));
                            if (charIndex1==charIndex2)
                              continue;
                          }
                          var curChar = charList.substring(charIndex1, charIndex1+1);
                          
                          if (abcList.indexOf(curChar, 0) !== -1) found_abc = true;
                          if (ABCList.indexOf(curChar, 0) !== -1) found_ABC = true;
                          if (numList.indexOf(curChar, 0) !== -1) found_num = true;
                          if (sysList.indexOf(curChar, 0) !== -1) found_sys = true;
                          newPassword += curChar;
                        }
                        
                        $fail = false;
                        if (!found_abc) $fail = true;
                        if (includeUCase && !found_ABC) $fail = true;
                        if (includeNumbers && !found_num) $fail = true;
                        if (includeSymbols && !found_sys) $fail = true;
                          
                        if (!$fail)
                          continue;
                      }
                      
                      winUploadThumbnail.close();
                      _self.settings.password.setValue(newPassword);
                    }
                  },{
                    text: 'Cancel',
                    handler: function(){
                      winUploadThumbnail.close();
                    }
                  }]
    });
    winUploadThumbnail.show(this);
}
CS2.User.UploadPhoto = function(initOptions){
    var _self = this;
    this.settings = {user_id: 0};
    Ext.apply(this.settings, initOptions);
    var upThumbPanel = new Ext.FormPanel({
        labelWidth: 75, // label settings here cascade unless overridden
        clientValidation: true,
        standardSubmit:false, 
        fileUpload: true,
        isUpload: true,
        method: 'POST',
        border: false,
        items: [{
            border: false,
            xtype:'fieldset',
            defaults: {
                anchor: '-20',
                msgTarget: 'side'
            },
            defaultType: 'textfield',
            items :[{
                      xtype: 'displayfield',
                      hideLabel: true,
                      html: '<strong>We currently support the following image types:</strong><br /> jpg, png, gif, bmp<br /><br />'
                    },{
                      xtype: 'fileuploadfield',
                      emptyText: 'Select a photo',
                      fieldLabel: 'Image File',
                      name: 'eventFile_1',
                      allowBlank: false,
                      emptyText: 'Select a photo',
                      buttonText: '',
                      buttonCfg: {
                          iconCls: 'upload-icon'
                      }
                    },{
                      xtype: 'button',
                      anchor: '0',
                      cls: 'bigPrint1',
                      text: 'Upload Profile Photo',
                      style: 'margin-top: 10px',
                      handler: function(){
                        Ext.Msg.wait('Please wait...', 'Uploading Photo');
                        upThumbPanel.getForm().submit({
                          clientValidation: true, 
                          standardSubmit:false, 
                          fileUpload:true,
                          isUpload: true,
                          method: 'POST',
                          url:'/ajax/editor/uploadFile.cfm?t=_',
                          params: {
                            id: _self.settings.user_id,
                            uimg: 1,
                            action: "profile",
                            max:1
                          },
                          reader : new Ext.data.JsonReader({
                            success : '@success'
                          }),
                          success: function(form, action) {
                              winUploadThumbnail.hide();
                              Ext.Msg.hide();
                              setTimeout(function(){
                                var thumber = Ext.get('imgUserPhoto_'+ _self.settings.user_id);
                                thumber.dom.src = getProfileImage(_self.settings.user_id);
                                var thumber2 = Ext.get('imgUserPhotoPage_'+ _self.settings.user_id);
                                thumber2.dom.src = getProfileImage(_self.settings.user_id);
                              }, 100);
                          },
                          failure: function(form, action) {
                            Ext.Msg.hide();
                            switch (action.failureType) {
                                case Ext.form.Action.CLIENT_INVALID:
                                    Ext.Msg.alert('Failure', 'Please verify fields are correct.');
                                    break;
                                case Ext.form.Action.CONNECT_FAILURE:
                                    Ext.Msg.alert('Failure', 'Ajax communication failed');
                                    break;
                                case Ext.form.Action.SERVER_INVALID:
                                default:
                                    Ext.Msg.alert('Failure', action.result.msg);
                            }
                          }
                        });
                      }
                    }
            ]
        }]
    });
    var winUploadThumbnail = new Ext.Window({title: 'Select a Profile Photo', constrainHeader: true, width: 400, height: 200, modal: true, resizable: false, closeAction:'close', items:upThumbPanel,
        buttons: [{
                    text: 'Cancel',
                    handler: function(){
                      winUploadThumbnail.close();
                    }
                  }]
    });
    winUploadThumbnail.show(this);
};
CS2.User.CreateEdit = function(initOptions){
    var _self = this;
    this.settings = {user_id: 0, configMode: false};
    Ext.apply(this.settings, initOptions);
        
    if (this.settings.treeNode)
      this.settings.user_id = this.settings.treeNode.attributes.uid;

    var jsonCols = [];
    jsonCols.push({name: 'user_id', mapping: 'id'});
    jsonCols.push({name: 'user_first', mapping: 'first'});
    jsonCols.push({name: 'user_last', mapping: 'last'});
    jsonCols.push({name: 'user_username', mapping: 'username'});
    jsonCols.push({name: 'user_profile_alias', mapping: 'aliasname'});
    jsonCols.push({name: 'user_profile_Bio', mapping: 'intro'});
    jsonCols.push({name: 'user_password', mapping: 'password'});
    jsonCols.push({name: 'user_enabled', mapping: 'enabled', type: 'bool'});
    jsonCols.push({name: 'user_show', mapping: 'show', type: 'bool'});
    jsonCols.push({name: 'user_email', mapping: 'email'});
    jsonCols.push({name: 'user_email2', mapping: 'email2'});
    jsonCols.push({name: 'user_positionName', mapping: 'position'});
    jsonCols.push({name: 'user_accountName', mapping: 'accountType'});
    jsonCols.push({name: 'user_typeName', mapping: 'type'});
    jsonCols.push({name: 'user_roomNum', mapping: 'roomnum'});
    jsonCols.push({name: 'user_schoolName', mapping: 'schoolID'});
    
    jsonCols.push({name: 'user_fax', mapping: 'phone/fax'});
    jsonCols.push({name: 'user_phone_home', mapping: 'phone/home'});
    jsonCols.push({name: 'user_phone_mobile', mapping: 'phone/mobile'});
    jsonCols.push({name: 'user_phone_other', mapping: 'phone/other'});
    jsonCols.push({name: 'user_phone_other', mapping: 'phone/other'});
    jsonCols.push({name: 'user_address1', mapping: 'address/address1'});
    jsonCols.push({name: 'user_address2', mapping: 'address/address2'});
    jsonCols.push({name: 'user_city', mapping: 'address/city'});
    jsonCols.push({name: 'user_state', mapping: 'address/state'});
    jsonCols.push({name: 'user_zip', mapping: 'address/zip'});
    jsonCols.push({name: 'user_dob', mapping: 'dob'});
    jsonCols.push({name: 'user_ethnicName', mapping: 'ethnicity'});
    jsonCols.push({name: 'user_genderName', mapping: 'gender'});
    jsonCols.push({name: 'user_langName', mapping: 'language'});
    jsonCols.push({name: 'user_internal_id', mapping: 'internalID'});
    jsonCols.push({name: 'user_health_allergies', mapping: 'health/allergies'});
    jsonCols.push({name: 'user_health_medications', mapping: 'health/medications'});
    jsonCols.push({name: 'user_health_memo', mapping: 'health/memo'});

    var totalShares=shareStore.getTotalCount();
    for(var n=1;n<=totalShares;n++){
      var schoolInfo = shareStore.getById(n);        
      jsonCols.push({name: 'GLOBALROAM_'+schoolInfo.data['id'], mapping: 'roam/site_'+schoolInfo.data['id'], type: 'bool'});
    }
    
    this.editMode = this.settings.user_id ? true : false;
    this.dialogTitle = this.editMode ? 'Modify Existing User' : 'Create New User';
    this.dialogTitle = !this.settings.configMode ? 'Edit Profile BIO' : this.dialogTitle;
    this.dialogSaveTitle = this.editMode ? 'Save' : 'Create';
    
    var reqField = '<span class="requiredFormField">*Required</span>';
    var requiredUser = '<span class="requiredFormField">*Required (5-14 characters)</span>';
    var requiredPass = '<span class="requiredFormField">*Required (5-14 characters)</span>';
    var editPass = '<span class="passwordChangeFormField">Specify a new password to override their old one</span>';
    
    var requiredField = {
                            xtype: 'panel',
                            style: 'position: relative; top: -7px; left: 3px',
                            bodyStyle: 'padding: 0; margin: 0;',
                            html: reqField
                        };
                        
    var changeUserField = {
                            xtype: 'panel',
                            style: 'position: relative; top: -5px',
                            bodyStyle: 'padding: 0; margin: 0;',
                            html: requiredUser
                        }
    var changePassField = {
                            xtype: 'panel',
                            style: 'position: relative; top: -5px',
                            bodyStyle: 'padding: 0; margin: 0;',
                            html: _self.settings.user_id==0 ? requiredPass : editPass
                        };
                        
    var fieldTPL = new Ext.XTemplate(
      '<div tabindex="-1" class="x-form-item " id="ext-gen262">',
        '<label class="x-form-item-label" style="width: auto;" for="ext-comp-1040" id="ext-gen263">First Name:</label>',
        '<div style="padding-left: 0pt;" id="x-form-el-ext-comp-1040" class="x-form-element">',
          '<input type="text" name="user_first" id="ext-comp-1040" autocomplete="off" size="20" class=" x-form-text x-form-field" style="width: 244px;">',
        '</div>',
        '<div class="x-form-clear-left"></div>',
      '</div>'
    );
    
    this.accountInfo = {
                title: 'General',
                autoScroll:true,
                border: true,
                padding: 10,
                items: [{
                    layout:'column',
                    items:[{
                            columnWidth:.25,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20', allowBlank:true},
                            items: [{
                                      fieldLabel: 'User ID',
                                      name: 'user_internal_id'
                                    }]
                          },{
                            columnWidth:.25,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20', width: 200, allowBlank:false},
                            items: [new Ext.form.ComboBox({
                                  fieldLabel: 'Account Type',
                                  hiddenId:'user_accountType',
                                  hiddenName:'user_accountName',
                                  store: new Ext.data.ArrayStore({
                                      fields: ['accountType', 'accountName'],
                                      data: CS2.isCyberSchool() ? [
                                              ['', 'Staff'],
                                              ['P', 'Parent'],
                                              ['S', 'Student'],
                                              ['G', 'Guest']
                                            ] : [
                                              ['', 'Staff'],
                                              ['G', 'Guest'],
                                              ['M', 'Management'],
                                              ['U', 'Member'],
                                              ['K', 'Client'],
                                              ['C', 'Contractor'],
                                              ['T', 'Temp'],
                                              ['O', 'Office']
                                            ]
                                  }),
                                  forceSelection: true,
                                  valueField:'accountType',
                                  displayField:'accountName',
                                  mode: 'local',
                                  typeAhead: true,
                                  triggerAction: 'all',
                                  selectOnFocus:true
                              }), requiredField]
                          },{
                            columnWidth:.25,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20', width: 200, allowBlank:true},
                            items: [new Ext.form.ComboBox({
                                  fieldLabel: 'Gender',
                                  hiddenId:'user_genderType',
                                  hiddenName:'user_genderName',
                                  store: new Ext.data.ArrayStore({
                                      fields: ['genderType', 'genderName'],
                                      data: [
                                              ['M', 'Male'],
                                              ['F', 'Female']
                                            ]
                                  }),
                                  forceSelection: true,
                                  valueField:'genderType',
                                  displayField:'genderName',
                                  mode: 'local',
                                  typeAhead: true,
                                  triggerAction: 'all',
                                  selectOnFocus:true
                              })]
                          },{
                            columnWidth:.25,
                            layout: 'form',
                            items: new Ext.Panel({html: CS2.cyberschoolVerbage()+' ID<br />' + (this.settings.user_id == 0 ? 'NEW' : '#'+this.settings.user_id), bodyStyle: 'text-align: right'})
                          }]
                    },new Ext.Panel({
                        html: '<hr />'
                    }),{
                    layout:'column',
                    items:[{
                        columnWidth:.5,
                        layout: 'form',
                        defaults: {xtype: 'textfield', anchor: '-20', allowBlank:false},
                        items: [{
                                  fieldLabel: 'Username',
                                  name: 'user_username',
                                  minLength: 5,
                                  maxLength: 14,
                                  vtype: 'username'
                              }, changeUserField]
                        },{
                            columnWidth:.35,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '0', allowBlank: false},
                            items: [{
                                  fieldLabel: 'Password',
                                  name: 'user_password', 
                                  ref: '../user_password',
                                  allowBlank:true,
                                  minLength: 5,
                                  maxLength: 14,
                                  emptyText: 'Type to override existing',
                                  vtype: 'password'
                              }]
                        },{
                            columnWidth:.15,
                            layout: 'form',
                            defaults: {xtype: 'button', anchor: '0', allowBlank: false},
                            items: [{
                                  hideLabel: true,
                                  style: 'margin: 18px 0 0 -2px',
                                  text: 'Generate...',
                                  handler: function(b,e){
                                    new CS2.User.GeneratePassword({button: b, password: b.ownerCt.ownerCt.user_password});
                                  }
                              }]
                        }]
                    },{
                    layout:'column',
                    items:[{
                        columnWidth:.5,
                        layout: 'form',
                        defaults: {xtype: 'textfield', anchor: '-20', allowBlank:false},
                        items: [{
                                  fieldLabel: 'First Name',
                                  ref: '../../firstName',
                                  name: 'user_first'
                                }, requiredField]
                        },{
                            columnWidth:.5,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20', allowBlank:false},
                            items: [{
                                  fieldLabel: 'Last Name',
                                  name: 'user_last'
                              }, requiredField]
                        }]
                    },{
                    layout:'column',
                    items:[{
                        columnWidth:.5,
                        layout: 'form',
                        defaults: {xtype: 'textfield', anchor: '-20', width: 200, allowBlank:false},
                        items: [new Ext.form.ComboBox({
                                  fieldLabel: CS2.schoolSubsiteVerbage(),
                                  hiddenId:'user_schoolID',
                                  hiddenName:'user_schoolName',
                                  store: new Ext.data.JsonStore({
                                      autoDestroy: true,
                                      url: '/ajax/login/getSchools.cfm',
                                      storeId: 'userSchoolStore',
                                      root: 'schools',
                                      idProperty: 'schoolID',
                                      fields: ['schoolID', 'userSchool']
                                  }),
                                  forceSelection: true,
                                  loadingText: 'Loading '+CS2.schoolsVerbage()+'...',
                                  valueField:'schoolID',
                                  displayField:'userSchool',
                                  typeAhead: true,
                                  mode: 'remote',
                                  triggerAction: 'all',
                                  emptyText:'Select a '+CS2.schoolSubsiteVerbage()+'...',
                                  selectOnFocus:true
                              }), requiredField]
                        },{
                        columnWidth:.5,
                        layout: 'form',
                        defaults: {xtype: 'textfield', anchor: '-20', width: 200, allowBlank:false},
                        items: [new Ext.ux.ComboBoxChoose({
                              fieldLabel: 'User Type',
                              hiddenId:'user_positionID',
                              hiddenName:'user_positionName',
                              store: new Ext.data.JsonStore({
                                  autoDestroy: true,
                                  url: '/ajax/login/getUserPositions.cfm',
                                  storeId: 'userPositionStore',
                                  root: 'positions',
                                  idProperty: 'userPosition',
                                  fields: ['userPosition']
                              }),
                              loadingText: 'Loading Types...',
                              valueField:'userPosition',
                              displayField:'userPosition',
                              mode: 'remote',
                              emptyText:'Select a type...'
                              
                          }), requiredField]
                        }]
                    },new Ext.Panel({
                        html: '<hr />'
                    }),{
                    layout:'column',
                    items:[{
                            columnWidth:.5,
                            layout: 'form',
                            defaults: {xtype: 'checkbox'},
                            items: [{
                                        hideLabel: true,
                                        boxLabel: 'Account Enabled (User can LOGIN)',
                                        name: 'user_enabled'
                                    }]
                          },{
                            columnWidth:.5,
                            layout: 'form',
                            defaults: {xtype: 'checkbox'},
                            items: [{
                                        hideLabel: true,
                                        boxLabel: 'Show User in Staff Module',
                                        name: 'user_show'
                                    }]
                          }]
                    },{
                      layout:'column',
                      items:[{
                              columnWidth:.33,
                              layout: 'form',
                              defaults: {xtype: 'textfield', anchor: '-20'},
                              items: new Ext.form.DateField({
                                  fieldLabel: 'Date of Birth',
                                  name: 'user_dob',
                                  allowBlank:true
                                })
                            },{
                            columnWidth:.33,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20', width: 200, allowBlank:true},
                            items: [new Ext.form.ComboBox({
                                  fieldLabel: 'Ethnicity',
                                  hiddenId:'user_ethnicType',
                                  hiddenName:'user_ethnicName',
                                  store: new Ext.data.ArrayStore({
                                      fields: ['ethnicType', 'ethnicName'],
                                      data: [
                                              ['CW', 'Caucasian'],
                                              ['AA', 'African American'],
                                              ['HI', 'Hispanic'],
                                              ['AI', 'American Indian'],
                                              ['AN', 'Alaskan Native'],
                                              ['FI', 'Filipino'],
                                              ['AS', 'Asian'],
                                              ['PI', 'Pacific Island'],
                                              ['O', 'Other']
                                            ]
                                  }),
                                  forceSelection: true,
                                  valueField:'ethnicType',
                                  displayField:'ethnicName',
                                  mode: 'local',
                                  typeAhead: true,
                                  triggerAction: 'all',
                                  value: 'CW',
                                  selectOnFocus:true
                              })]
                          },{
                            columnWidth:.33,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20', width: 200, allowBlank:true},
                            items: [new Ext.form.ComboBox({
                                  fieldLabel: 'Language',
                                  hiddenId:'user_langType',
                                  hiddenName:'user_langName',
                                  store: new Ext.data.ArrayStore({
                                      fields: ['langType', 'langName'],
                                      data: [ //based on 639-1
                                              ['EN', 'English'],
                                              ['ZH', 'Chinese'],
                                              ['ES', 'Spanish'],
                                              ['JA', 'Japanese'],
                                              ['DE', 'German'],
                                              ['FR', 'French'],
                                              ['KO', 'Korean'],
                                              ['IT', 'Italian'],
                                              ['PT', 'Portuguese'],
                                              ['RU', 'Russian'],
                                              ['NL', 'Dutch'],
                                              ['MS', 'Malay'],
                                              ['AR', 'Arabic'],
                                              ['PL', 'Polish'],
                                              ['SV', 'Swedish'],
                                              ['TH', 'Thai'],
                                              ['TR', 'Turkish'],
                                              ['VI', 'Vietnamese'],
                                              ['FA', 'Persian'],
                                              ['RO', 'Romanian'],
                                              ['CS', 'Czech'],
                                              ['HE', 'Hebrew'],
                                              ['DA', 'Danish'],
                                              ['FI', 'Finnish'],
                                              ['HU', 'Hungarian'],
                                              ['EL', 'Greek'],
                                              ['CA', 'Catalan'],
                                              ['NO', 'Norwegian'],
                                              ['SK', 'Slovak'],
                                              ['UK', 'Ukrainian'],
                                              ['PA', 'Punjabi'],
                                              ['SL', 'Slovene'],
                                              ['IS', 'Icelandic'],
                                              ['O', 'Other']
                                            ]
                                  }),
                                  forceSelection: true,
                                  valueField:'langType',
                                  displayField:'langName',
                                  mode: 'local',
                                  typeAhead: true,
                                  triggerAction: 'all',
                                  value: 'EN',
                                  selectOnFocus:true
                              })]
                          }]
                    }
                  ]};
    this.accountStaff = {
                title: 'Staff',
                autoScroll:true,
                border: true,
                padding: 10,
                items: [
                  {
                    layout:'column',
                    items:[{
                          columnWidth:.7,
                          layout: 'form',
                          defaults: {xtype: 'textfield', anchor: '-20'},
                          items: [new Ext.ux.ComboBoxChoose({
                              fieldLabel: 'Position',
                              hiddenId:'user_typeID',
                              hiddenName:'user_typeName',
                              store: new Ext.data.JsonStore({
                                  autoDestroy: true,
                                  url: '/ajax/login/getUserTypes.cfm',
                                  storeId: 'userTypeStore',
                                  root: 'types',
                                  idProperty: 'userType',
                                  fields: ['userType']
                              }),
                              loadingText: 'Loading Positions...',
                              valueField:'userType',
                              displayField:'userType',
                              mode: 'remote',
                              emptyText:'Select a position...'
                          }), requiredField]
                        },{
                            columnWidth:.3,
                            layout: 'form',
                            defaults: {xtype: 'textfield'},
                            items: {
                              fieldLabel: CS2.isCyberSchool() ? 'Room Num' : 'Room/Floor Num',
                              name: 'user_roomNum',
                              width: 90,
                              allowBlank:true
                          }
                        }]
                    }
                  ]};
    this.accountContact = {
                title: 'Contact',
                autoScroll:true,
                border: true,
                padding: 10,
                items: [
                  {
                    layout:'column',
                    items:[{
                            columnWidth:.5,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20'},
                            items: [{
                                  fieldLabel: 'Home Phone',
                                  name: 'user_phone_home',
                                  allowBlank:true
                              }]
                          },{
                            columnWidth:.5,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20', width: 200, allowBlank:false},
                            items: [{
                                  fieldLabel: 'Mobile Phone',
                                  name: 'user_phone_mobile',
                                  allowBlank:true
                              }]
                          }]
                  },{
                    layout:'column',
                    items:[{
                            columnWidth:.5,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20'},
                            items: [{
                                  fieldLabel: 'Other Phone',
                                  name: 'user_phone_other',
                                  allowBlank:true
                              }]
                          },{
                            columnWidth:.5,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20', width: 200, allowBlank:false},
                            items: [{
                                  fieldLabel: 'Fax',
                                  name: 'user_fax',
                                  allowBlank:true
                              }]
                          }]
                  },{
                    layout:'column',
                    items:[{
                            columnWidth:1,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20'},
                            items: [{
                                        fieldLabel: 'Address',
                                        name: 'user_address1',
                                        allowBlank:true
                                    },{
                                        hideLabel: true,
                                        name: 'user_address2',
                                        allowBlank:true
                                    }]
                          }]
                  },{
                    layout:'column',
                    items:[{
                            columnWidth:.6,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20'},
                            items: [{
                                        fieldLabel: 'City',
                                        name: 'user_city',
                                        allowBlank:true
                                    }]
                          },{
                            columnWidth:.2,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20'},
                            items: [{
                                        fieldLabel: 'State',
                                        name: 'user_state',
                                        allowBlank:true
                                    }]
                          },{
                            columnWidth:.2,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20'},
                            items: [{
                                        fieldLabel: 'Zip',
                                        name: 'user_zip',
                                        allowBlank:true
                                    }]
                          }]
                  },{
                    layout:'column',
                    items:[{
                            columnWidth:.5,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20'},
                            items: [{
                                  fieldLabel: 'Email',
                                  name: 'user_email',
                                  vtype:'email',
                                  allowBlank:true
                              }]
                          },{
                            columnWidth:.5,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20', width: 200, allowBlank:false},
                            items: [{
                                  fieldLabel: 'Alternate Email',
                                  name: 'user_email2',
                                  vtype:'email',
                                  allowBlank:true
                              }]
                          }]
                    }
                  ]};
    this.accountMedical = {
                title: 'Medical',
                autoScroll:true,
                border: true,
                padding: 10,
                items: [{
                    layout:'column',
                    items:[{
                        columnWidth:.5,
                        layout: 'form',
                        defaults: {anchor: '-10', allowBlank:false},
                        items: [{
                              xtype: 'htmleditor',
                              fieldLabel: 'Allergies',
                              name: 'user_health_allergies',
                              height: 150
                          }]
                        },{
                        columnWidth:.5,
                        layout: 'form',
                        defaults: {anchor: '0', allowBlank:false},
                        items: [{
                              xtype: 'htmleditor',
                              fieldLabel: 'Medications',
                              name: 'user_health_medications',
                              height: 150
                          }]
                        }]
                    },{
                    layout:'column',
                    items:[{
                        columnWidth:1,
                        layout: 'form',
                        defaults: {anchor: '0', allowBlank:false},
                        items: [{
                              xtype: 'htmleditor',
                              fieldLabel: 'Other Health Issues',
                              name: 'user_health_memo',
                              height: 150
                          }]
                        }]
                    }
                  ]};
    this.accountBIO = {
                title: 'Profile',
                autoScroll:true,
                border: true,
                padding: 10,
                items: [{
                    layout:'column',
                    items:[{
                            columnWidth:1,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20'},
                            items: {
                              fieldLabel: 'Public Alias (Nickname)',
                              name: 'user_profile_alias',
                              allowBlank:true,
                              width: 180
                          }
                        }]
                    },{
                    layout:'column',
                    items:[{
                        columnWidth:1,
                        layout: 'form',
                        defaults: {anchor: '0', allowBlank:false},
                        items: [
                                //xtype: 'htmleditor',
                                new Ext.Panel({
                                  height: 300,
                                  fieldLabel: 'Profile Biography',
                                  layout: 'fit',
                                  items: new Ext.ux.form.FCKeditor({
                                    ref:'FCK',
                                    ToolbarSet: 'Default',
                                    id:Ext.id(),
                                    name: 'user_profile_Bio',
                                    autoHeight: true
                                  })
                                })
                              ]
                        }]
                    }
                  ]};
    this.accountBIO2 = {
                title: 'Profile',
                autoScroll:true,
                border: true,
                padding: 10,
                items: [{
                    layout:'column',
                    items:[{
                            columnWidth:.5,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '-20'},
                            items: {
                              fieldLabel: 'Public Alias (Nickname)',
                              name: 'user_profile_alias',
                              allowBlank:true,
                              width: 180
                          }
                        },{
                            columnWidth:.35,
                            layout: 'form',
                            defaults: {xtype: 'textfield', anchor: '0', allowBlank: false},
                            items: [{
                                  fieldLabel: 'Password',
                                  name: 'user_password', 
                                  ref: '../user_password',
                                  allowBlank:true,
                                  minLength: 5,
                                  maxLength: 14,
                                  emptyText: 'Type to override existing',
                                  vtype: 'password'
                              }]
                        },{
                            columnWidth:.15,
                            layout: 'form',
                            defaults: {xtype: 'button', anchor: '0', allowBlank: false},
                            items: [{
                                  hideLabel: true,
                                  style: 'margin: 18px 0 0 -2px',
                                  text: 'Generate...',
                                  handler: function(b,e){
                                    new CS2.User.GeneratePassword({button: b, password: b.ownerCt.ownerCt.user_password});
                                  }
                              }]
                        }]
                    },{
                    layout:'column',
                    items:[{
                        columnWidth:1,
                        layout: 'form',
                        defaults: {anchor: '0', allowBlank:false},
                        items: [
                                new Ext.Panel({
                                  height: 300,
                                  fieldLabel: 'Profile Biography',
                                  layout: 'fit',
                                  items: new Ext.ux.form.FCKeditor({
                                    ref:'FCK',
                                    ToolbarSet: 'Default',
                                    id:Ext.id(),
                                    name: 'user_profile_Bio',
                                    autoHeight: true
                                  })
                                })
                               ]
                        }]
                    }
                  ]};
    this.accountPhoto = {
                title: 'Photo',
                tbar: [{
                        xtype: 'button',
                        text: 'Upload Photo...',
                        handler: function(){ CS2.User.UploadPhoto({user_id: _self.settings.user_id}); }
                      }],
                autoScroll:true,
                border: true,
                padding: 10,
                html: '<img src="/images/getProfilePicture.cfm?id='+_self.settings.user_id+'" width="100%" id="imgUserPhoto_'+_self.settings.user_id+'" />'
              };
    

    var schoolListArr=[];
    var totalShares=shareStore.getTotalCount();
    for(var n=1;n<=totalShares;n++){
      var schoolInfo = shareStore.getById(n);
      schoolListArr.push({xtype: 'checkbox', boxLabel: schoolInfo.data['title'], name: 'GLOBALROAM_'+schoolInfo.data['id']});
    }
    this.globalLogin = {
                title: 'Roaming',
                autoScroll:true,
                border: true,
                padding: 10,
                items: [{
                          layout: 'form',
                          title: 'Roaming Permissions',
                          xtype:'fieldset',
                          labelWidth: 10,
                          padding: 5,
                          autoHeight: true,
                          items: [{
                                  xtype: 'displayfield',
                                  hideLabel: true,
                                  html: 'While login sessions are maintained between '+CS2.schoolsVerbage()+', permissions are not unless explicitly defined here:'
                                },{
                                  xtype: 'checkboxgroup',
                                  itemCls: 'x-check-group-alt',
                                  hideLabel: true,
                                  columns: 1,
                                  items: schoolListArr
                                },{
                                  xtype: 'displayfield',
                                  hideLabel: true,
                                  html: 'Unselecting all '+CS2.schoolsVerbage()+' will only revolk permissions and not the ability to login. To disable an account from login, see \'Account Enabled\' in the General Tab.'
                                }
                              ]                       
                        }
                ]};
                
    /*
    this.ldapSettings = {
                title: 'LDAP',
                autoScroll:true,
                border: true,
                padding: 10,
                items: [{
                          labelWidth: 10,
                          padding: 5,
                          autoHeight: true,
                          html: 'Linking a CyberSchool account with an LDAP account will allow logging into CyberSchool via your Intranet Username and Password.<br /><br />'
                        },{
                          layout: 'form',
                          title: 'Link account to LDAP ',
                          xtype:'fieldset',
                          checkboxToggle: true,
                          collapsed: true,
                          labelWidth: 10,
                          padding: 5,
                          autoHeight: true,
                          items: [{
                                  xtype: 'textfield',
                                  name:'username',
                                  id: 'login_user',
                                  maskRe:/^([ _a-zA-Z0-9\^\$\.\+\?\=\:\|\\\/\(\)\[\]\&\-])+$/,
                                  selectOnFocus: true,
                                  blankText: 'Username is Required',
                                  allowBlank: false,
                                  fieldLabel: 'Active Directory Username',
                                  value: lastLoggedInUserName
                                }]
                        }
                ]};
    */
    
    var currentItems = [this.accountBIO2, this.accountPhoto];
    if (this.settings.configMode && currentUser.schoolID == 1 && currentUser.isAdminGroup && currentUser.canUseManageUsers){
      currentItems = [this.accountInfo, this.accountStaff, /*this.ldapSettings, */this.globalLogin, this.accountContact, this.accountMedical, this.accountBIO, this.accountPhoto];
    }else if(this.settings.configMode){
      currentItems = [this.accountInfo, this.accountStaff, this.accountContact, this.accountMedical, this.accountBIO, this.accountPhoto];
    }
    
    var mainFormPanel = new Ext.FormPanel({
          ref : 'NewUserForm',
          waitMsgTarget: !Ext.isIE,
          frame: true,
          labelAlign: 'top',
          border: false,
          monitorValid:true,
          labelWidth: 85,
          layout: 'fit',
          width:340,
          reader : new Ext.data.XmlReader({
                record : 'user',
                success : '@success'
            }, jsonCols),
          listeners: {
            afterrender: function(fp){
              if (_self.settings.user_id){
                var newURL = '/ajax/siteconfig/userGroups/getUser.cfm?id='+_self.settings.user_id;
                fp.getForm().load({url: newURL, waitMsg:'Loading...', success: function(f, a){
                  fp.firstName.focus(true);
                }});
              }
            },
            clientvalidation : function(fp, valid){
              _self.win.CreateNewUserButton.setDisabled(!valid);
            }
          },
          items: {
                    xtype: 'tabpanel',
                    activeTab:0,
                    deferredRender:false,
                    forceLayout:true,
                    plain: true,
                    items: currentItems,
                    listeners: {
                      tabchange: function(el, tab){
                        tab.doLayout(false, true);
                      }
                    }
                }
      });

    this.win = new Ext.Window({
      title: _self.dialogTitle,
      width:600,
      height: 500,
      layout: 'fit',
      maximizable: true,
      constrainHeader: true,
      plain: true,
      modal: true,
      items: mainFormPanel,
      buttons: [{
          text: _self.dialogSaveTitle + ' User',
          ref: '../CreateNewUserButton',
          disabled:true,
          handler: function(t){
            Ext.Msg.wait('Please wait...', 'Saving User...');
            _self.win.NewUserForm.getForm().submit({
              clientValidation: true,
              url: _self.settings.configMode ? '/ajax/siteconfig/userGroups/createUser.cfm' : '/ajax/siteconfig/userGroups/editProfileBIO.cfm',
              params: {user_id: _self.settings.user_id},  
              errorReader : new Ext.data.JsonReader({
                  root:'errors',
                  successProperty:'success'
                }, ['id', 'msg']),
              success: function(form, action) {
                if (action.result.user_id)
                  _self.settings.user_id = action.result.user_id;
                  
                if (_self.settings.treePanel){
                  var root = _self.settings.treePanel.getRootNode();
                  _self.settings.treePanel.getLoader().load(root);
                }
                
                if (!_self.settings.configMode)
                  window.location.reload(true);
                  
                Ext.Msg.wait('Saving Profile', 'Please wait...');
                setTimeout(function(){
                  Ext.Msg.hide();
                }, CS2.quickPop);
                _self.win.close();
                return true;
              },
              failure: function(form, action) {
                Ext.Msg.hide();
                switch (action.failureType) {
                  case Ext.form.Action.CLIENT_INVALID:
                    Ext.Msg.alert('Failure', 'Please verify all form fields are correct.');
                    break;
                  case Ext.form.Action.CONNECT_FAILURE:
                    Ext.Msg.alert('Failure', 'Ajax communication failed');
                    break;
                  case Ext.form.Action.SERVER_INVALID:
                  default:
                    Ext.Msg.show({
                       title:action.result.title,
                       msg: action.result.msg,
                       buttons: Ext.Msg.OK,
                       icon: action.result.errType == 'error' ? Ext.MessageBox.ERROR : Ext.MessageBox.INFO
                    });
                }
                return false;
              }
          });
        }
      },{
          text: 'Cancel',
          handler: function(){
              this.ownerCt.ownerCt.hide();
          }
      }]
    });
    this.win.show(this);
};
CS2.User.Delete = function(initOptions){
    var _self = this;
    this.settings = {};
    
    Ext.apply(this.settings, initOptions);
        
      this.win = new Ext.Window({
          title: 'Delete User?',
          width:380,
          resizable: false,
          cls: 'x-window-dlg',
          constrainHeader: true,
          layout: 'fit',
          plain: true,
          bodyStyle: 'font-size: 13px; padding: 10px;',
          html: new Ext.XTemplate(
            '<div class="x-dlg-icon">',
              '<div class="ext-mb-icon ext-mb-warning"></div>',
              '<div class="ext-mb-content">',
                '<span class="ext-mb-text">',
                  '<strong>The user &quot;{group_name}&quot; <i>and all of their data</i> is about to be permanently deleted, are you sure?</strong>',
                  '<br /><br />',
                  'By deleting this user, all of their data will be deleted too! This cannot be undone!',
                '</span>',
              '</div>',
              '<div class="x-clear"></div>',
            '</div>'
          ).apply({group_name: this.settings.treeNode.attributes.text}),
          buttons: [{
              text:'Delete (3)',
              ref: '../DeleteButton',
              disabled:true,
              handler: function(){
                var params = {USERID: _self.settings.treeNode.attributes.uid};
                Ext.Ajax.request({
                   url: '/ajax/siteconfig/userGroups/deleteUser.cfm',
                   method: 'GET',
                   'params': params,
                   reader : new Ext.data.JsonReader({
                    success : '@success'
                   }),
                   success: function(response, opts) {
                      var obj = Ext.decode(response.responseText);
                      if (obj.success){
                        var node = _self.settings.treeNode;
                        node.parentNode.childNodes[0].select();
                        if (_self.settings.treePanel){
                          var root = _self.settings.treePanel.getRootNode();
                          _self.settings.treePanel.getLoader().load(root);
                        }
                        node.remove();
                        _self.win.hide();
                      }else{
                        Ext.Msg.alert('Error Deleting User', 'This user "'+_self.settings.treeNode.text+'" could not be deleted. Please try again.');
                      }
                   },
                   failure: function(response, opts) {
                    Ext.Msg.alert('Error Deleting User', 'There was a problem communicating with the server. Please check your internet connection and try again.');
                   }
                });   
                
              }
          },{
              text: 'Cancel',
              handler: function(){
                  this.ownerCt.ownerCt.hide();
              }
          }]
      });
    this.win.show(this);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete (2)'); }, CS2.countDownSpeed * 1);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete (1)'); }, CS2.countDownSpeed * 2);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete'); _self.win.DeleteButton.enable(); }, CS2.countDownSpeed * 3);
};
CS2.Group = {};
CS2.Group.Create = function(settings){
    var _self = this;
    this.settings = settings;
    this.win = new Ext.Window({
        title: 'Create Group',
        layout:'fit',
        width:340,
        height:113,
        constrainHeader: true,
        resizable: false,
        closeAction:'hide',
        plain: true,
        items: new Ext.FormPanel({
          labelWidth: 75, // label settings here cascade unless overridden
          url:'save-form.php',
          frame:true,
          monitorValid:true,
          monitorPoll:0,
          bodyStyle:'padding:5px 5px 0',
          defaults: {width: 203, msgTarget: 'side'},
          defaultType: 'textfield',
          items: [{
                    fieldLabel: 'Group Name',
                    name: 'groupName',
                    ref: '../GroupName',
                    allowBlank:false,
                    listeners: {
                      valid: function(field){
                        this.ownerCt.ownerCt.CreateButton.enable();
                      },
                      invalid: function(field, msg){
                        this.ownerCt.ownerCt.CreateButton.disable();
                      }
                    }
                  }]
        }),
        buttons: [{
            text:'Create',
            ref: '../CreateButton',
            disabled:true,
            handler: function(){
              Ext.Msg.wait('Please wait...', 'Saving Group...');
              var params = {gcdID: _self.settings.gcdID, name: _self.win.GroupName.getValue()};
              Ext.Ajax.request({
                 url: '/ajax/siteconfig/userGroups/addGroup.cfm',
                 method: 'GET',
                 'params': params,
                 reader : new Ext.data.JsonReader({
                  success : '@success'
                 }),
                 success: function(response, opts) {
                    var obj = Ext.decode(response.responseText);
                    if (obj.success){
                      var newGroup = _self.settings.treePanel.getRootNode().appendChild(new Ext.tree.TreeNode({
                          text: _self.win.GroupName.getValue(),
                          leaf:false,
                          iconCls: 'iconUserGroup',
                          allowDrag: false,
                          ugid: obj.group_id,
                          children: []
                        }));

                      Ext.Msg.wait('Group added!', 'Saving Group...');
                      setTimeout(function(){
                        Ext.Msg.hide();
                      }, CS2.quickPop);
                      _self.win.close();
                    }else{
                      Ext.Msg.hide();
                      Ext.Msg.alert('Error Creating Group', 'This group name "'+_self.win.GroupName.getValue()+'" is already taken. Please choose a different name.');
                    }
                 },
                 failure: function(response, opts) {
                  Ext.Msg.hide();
                  Ext.Msg.alert('Error Creating Group', 'There was a problem communicating with the server. Please check your internet connection and try again.');
                 }
              });   
              
            }
        },{
            text: 'Cancel',
            handler: function(){
                this.ownerCt.ownerCt.hide();
            }
        }]
    });
    this.win.show(this);
};
CS2.Group.Edit = function(initOptions){
    var _self = this;
    this.settings = {group_id: 0, gcdID: 0, gcdType: '', isGCDMode: false};
    Ext.apply(this.settings, initOptions);
        
    if (this.settings.treeNode)
      this.settings.group_id = this.settings.treeNode.attributes.ugid;
      
    var fm = Ext.form;
    var checkColumnView = new Ext.grid.CheckColumn({
       header: 'Post',
       dataIndex: 'view',
       markDirty: false,
       width: 50
    });
    var checkColumnEdit = new Ext.grid.CheckColumn({
       header: 'Moderate',
       dataIndex: 'edit',
       markDirty: false,
       width: 60
    });
    var checkColumnAdmin = new Ext.grid.CheckColumn({
       header: 'Administer',
       dataIndex: 'admin',
       markDirty: false,
       width: 65
    });
    var cm = new Ext.grid.ColumnModel({
        // specify any defaults for each column
        defaults: {
            sortable: true // columns are not sortable by default           
        },
        columns: [
            {
                id: 'title',
                header: 'Module Name',
                dataIndex: 'title',
                width: 220
            },
            checkColumnView,
            checkColumnEdit,
            checkColumnAdmin
        ]
    });

    var store = new Ext.data.Store({
        autoDestroy: true,
        url: '/ajax/permissions/getGroupPerms.cfm?id='+_self.settings.group_id+'&gcd='+this.settings.gcdID,
        reader: new Ext.data.XmlReader({
            record: 'module',
            fields: [
                {name: 'id', type: 'int'},
                {name: 'title', type: 'string'},
                {name: 'view', type: 'bool'},
                {name: 'edit', type: 'bool'},
                {name: 'admin', type: 'bool'}
            ]
        }),
        listeners: {
          update : function(store, record, operation ){
            switch (operation){
              case 'edit':
                Ext.Ajax.request({
                   url: '/ajax/permissions/setGroupPerms.cfm',
                   method: 'POST',
                   params : Ext.apply(record.data, {groupid: _self.settings.group_id}),
                   reader : new Ext.data.JsonReader({
                    success : '@success'
                   }),
                   success: function(response, opts) {
                      var obj = Ext.decode(response.responseText);
                   },
                   failure: function(response, opts) {
                      Ext.Msg.alert('Setting Permission Failed', 'Whoops, we were unable to apply those last changes.<br/><br/>Please contact your system administrator.');
                   }
                });
             }
          }
        },
        sortInfo: {field:'title', direction:'ASC'}
    });
    store.load();
    
    jsonCols = [];
    jsonCols.push({name: 'id', mapping: 'id'});
    jsonCols.push({name: 'groupName', mapping: 'groupName'});
    jsonCols.push({name: 'is_admin', mapping: 'config/admin', type: 'bool'});
    jsonCols.push({name: 'is_global', mapping: 'config/global', type: 'bool'});
    jsonCols.push({name: 'is_invisible', mapping: 'config/invisible', type: 'bool'});
    
    jsonCols.push({name: 'view_intranet', mapping: 'view/intranet', type: 'bool'});
    jsonCols.push({name: 'site_config', mapping: 'view/siteconfig', type: 'bool'});
    jsonCols.push({name: 'manage_slideshow', mapping: 'view/slideshow', type: 'bool'});
    jsonCols.push({name: 'manage_users', mapping: 'view/manageusers', type: 'bool'});
    jsonCols.push({name: 'login_as', mapping: 'view/loginas', type: 'bool'});
    jsonCols.push({name: 'session_timeout', mapping: 'view/sessiontimeout', type: 'int'});
    jsonCols.push({name: 'gcd_navigation', mapping: 'view/gcdnavigation', type: 'bool'});
    jsonCols.push({name: 'gcd_users', mapping: 'view/gcdusers', type: 'bool'});
    jsonCols.push({name: 'gcd_config', mapping: 'view/gcdconfig', type: 'bool'});
    
    var normalGroup = [
                          {
                            fieldLabel: 'Group Name',
                            width: 185,
                            ref: 'GroupName',
                            name: 'groupName',
                            allowBlank:false,
                            listeners: {
                              valid: function(field){
                                _self.win.UpdateButton.enable();
                              },
                              invalid: function(field, msg){
                                _self.win.UpdateButton.disable();
                              }
                            }
                          },{
                            ref: 'CheckBoxGroup1',
                            xtype: 'checkboxgroup',
                            fieldLabel: 'Special Flags',
                            itemCls: 'x-check-group-alt',
                            columns: 1,
                            items: [
                              {boxLabel: 'System Administrator', ref: 'AdminChk', name: 'is_admin'},
                              {boxLabel: 'Login as other users', ref: 'LoginAsChk', name: 'login_as'}
                            ]
                          },{
                            ref: 'CheckBoxGroup2',
                            xtype: 'checkboxgroup',
                            fieldLabel: 'Users can',
                            itemCls: 'x-check-group-alt',
                            columns: 1,
                            items: [
                              {boxLabel: 'View Intranet Items', ref: 'IntranetChk', name: 'view_intranet'},
                              {boxLabel: 'Access Site Config', ref: 'SiteConfigChk', name: 'site_config'},
                              {boxLabel: 'Manage Slideshows', ref: 'SlideshowChk', name: 'manage_slideshow'},
                              {boxLabel: 'Manage Groups & Users', ref: 'ManageUsersChk', name: 'manage_users'}
                            ]
                          },{
                              xtype:'fieldset',
                              labelWidth: 90,
                              title: 'User Session Timeout',
                              autoHeight:true,
                              defaultType: 'textfield',
                              items :[{
                                xtype: 'spinnerfield',
                                fieldLabel: 'Minutes',
                                name: 'session_timeout',
                                minValue: 0,
                                maxValue: 120,
                                width: 60,
                                allowDecimals: false,
                                incrementValue: 1,
                                alternateIncrementValue: 5,
                                accelerate: true
                              },{
                                xtype: 'displayfield',
                                html: '&nbsp;0 = No Timeout'
                              }]
                            }
                        ];
                        
    var gcdGroup = [
                          {
                            fieldLabel: 'Group Name',
                            width: 185,
                            ref: 'GroupName',
                            name: 'groupName',
                            allowBlank:false,
                            listeners: {
                              valid: function(field){
                                _self.win.UpdateButton.enable();
                              },
                              invalid: function(field, msg){
                                _self.win.UpdateButton.disable();
                              }
                            }
                          },{
                            ref: 'CheckBoxGroup1',
                            xtype: 'checkboxgroup',
                            fieldLabel: 'Special Flags',
                            itemCls: 'x-check-group-alt',
                            columns: 1,
                            items: [
                              {boxLabel: this.settings.gcdType+' Administrator', ref: 'AdminChk', name: 'is_admin'},
                              {boxLabel: 'Invisible Member', ref: 'VisibleChk', name: 'is_invisible'}
                            ]
                          },{
                            ref: 'CheckBoxGroup2',
                            xtype: 'checkboxgroup',
                            fieldLabel: 'Members can',
                            itemCls: 'x-check-group-alt',
                            columns: 1,
                            items: [
                              {boxLabel: 'Manage '+this.settings.gcdType+' Config', ref: 'gcdNavChk', name: 'gcd_config'},
                              {boxLabel: 'Manage '+this.settings.gcdType+' Members', ref: 'gcdUsersChk', name: 'gcd_users'},
                              {boxLabel: 'Manage '+this.settings.gcdType+' Menus', ref: 'gcdNavChk', name: 'gcd_navigation'},
                              {boxLabel: 'Manage '+this.settings.gcdType+' Slideshows', ref: 'SlideshowChk', name: 'manage_slideshow'}
                            ]
                          }
                        ];
    
    
    if(!this.win){
        this.win = new Ext.Window({
            title: this.settings.treeNode.attributes.text+' - Edit Group',
            layout: 'fit',
            constrainHeader: true,
            width:360,
            height:500,
            resizable: false,
            plain: true,            
            items: new Ext.TabPanel({
                    title: 'tabs dont have titles..',
                    activeTab: 0,
                    items: [new Ext.Panel({
                              title: 'General',
                              border: false,
                              frame: false,
                              layout: 'border',
                              items: [
                                        new Ext.Panel({
                                          region: 'north',
                                          padding: 5,
                                          border: false,
                                          bodyStyle: 'text-align: center; background: #DFE8F6; border-bottom: 1px solid #99BBE8;',
                                          html: 'These settings will be applied when you click Update'
                                        }),
                                        new Ext.FormPanel({
                                          labelWidth: 100,
                                          border: false,
                                          frame: false,
                                          region: 'center',
                                          waitMsgTarget: !Ext.isIE,
                                          ref: '../../GroupForm',
                                          url:'save-form.php',
                                          bodyStyle:'padding: 10px',
                                          defaults: {msgTarget: 'side'},
                                          defaultType: 'textfield',
                                          reader : new Ext.data.XmlReader({
                                              record : 'group',
                                              success : '@success'
                                          }, jsonCols),
                                          listeners: {
                                            render: function(fp){
                                              var newURL = '/ajax/siteconfig/userGroups/getGroup.cfm?id='+_self.settings.group_id;
                                              fp.getForm().load({url: newURL, waitMsg:'Loading Group Info...', success: function(f,a){
                                                  
                                                  fp.CheckBoxGroup1.setValue('is_admin', a.result.data.is_admin);
                                                  fp.CheckBoxGroup1.setValue('is_global', a.result.data.is_global);
                                                  fp.CheckBoxGroup1.setValue('is_invisible', a.result.data.is_invisible);
                                                  fp.CheckBoxGroup1.setValue('LoginAsChk', a.result.data.login_as);
                                                  
                                                  fp.CheckBoxGroup2.setValue('view_intranet', a.result.data.view_intranet);
                                                  fp.CheckBoxGroup2.setValue('site_config', a.result.data.site_config);
                                                  fp.CheckBoxGroup2.setValue('manage_slideshow', a.result.data.manage_slideshow);
                                                  fp.CheckBoxGroup2.setValue('manage_users', a.result.data.manage_users);
                                                  fp.CheckBoxGroup2.setValue('session_timeout', a.result.data.session_timeout);
                                                  fp.CheckBoxGroup2.setValue('gcd_navigation', a.result.data.gcd_navigation);
                                                  fp.CheckBoxGroup2.setValue('gcd_users', a.result.data.gcd_users);
                                                  fp.CheckBoxGroup2.setValue('gcd_config', a.result.data.gcd_config);
                                              
                                                }
                                              });
                                            }
                                          },    
                                          items: this.settings.isGCDMode ? gcdGroup : normalGroup
                                        })
                                      ]
                          }),
                          new Ext.Panel({
                                title: 'Module Permissions',
                                layout: 'border',
                                items: [
                                          new Ext.Panel({
                                            region: 'north',

                                            padding: 5,
                                            border: false,
                                            bodyStyle: 'text-align: center; background: #fc3; border-bottom: 1px solid #99BBE8;',
                                            html: '<strong>Notice:</strong> Changes are automatically saved as you make them.'
                                          }),
                                          new Ext.grid.EditorGridPanel({
                                                          region: 'center',
                                                          store: store,
                                                          anchor: '0',
                                                          markDirty: false,
                                                          height: 280,
                                                          stripeRows: true,                        
                                                          cm: cm,
                                                          border: false,
                                                          autoExpandColumn: 'title',
                                                          clicksToEdit: 1,
                                                          plugins: [checkColumnView, checkColumnEdit, checkColumnAdmin],
                                                          listeners: {
                                                            validateedit: function(e){
                                                              switch (e.field){
                                                                case "view":
                                                                  if (e.value){
                                                                    //e.record.data['view']=true;
                                                                  }else{
                                                                    //e.record.data['view']=false;
                                                                    e.record.data['edit']=false;
                                                                    e.record.data['admin']=false;
                                                                  }
                                                                  break;
                                                                case "edit":
                                                                  if (e.value){
                                                                    e.record.data['view']=true;
                                                                    //e.record.data['edit']=true;
                                                                    e.record.data['admin']=false;
                                                                  }else{
                                                                    //e.record.data['edit']=false;
                                                                    e.record.data['admin']=false;
                                                                  }
                                                                  break;
                                                                case "admin":
                                                                  if (e.value){
                                                                    e.record.data['view']=true;
                                                                    e.record.data['edit']=true;
                                                                    //e.record.data['admin']=true;
                                                                  }else{
                                                                    //e.record.data['admin']=false;
                                                                  }
                                                                  break;
                                                              }
                                                              if (e.record.data['id']==0){
                                                                Ext.Msg.wait('Please wait...', 'Changing Permissions');
                                                                var myStore = e.grid.getStore();
                                                                setTimeout(function(){
                                                                      var allRecord = myStore.getAt(0);
                                                                      myStore.each(function(curRecord){
                                                                        if (curRecord.get('id') != 0){
                                                                          curRecord.set('edit', allRecord.get('edit'));
                                                                          curRecord.set('view', allRecord.get('view'));
                                                                          curRecord.set('admin', allRecord.get('admin'));
                                                                        }
                                                                      });
                                                                      Ext.Msg.hide();
                                                                  }, 100);
                                                              }
                                                          }
                                                        }
                                        })
                                      ]
                        })
                      ]
            }),
            buttons: [{
                text:'Update',
                ref: '../UpdateButton',
                handler: function(){

                          
                  _self.win.GroupForm.getForm().submit({
                    clientValidation: true,            
                    url:'/ajax/siteconfig/userGroups/editGroup.cfm', 
                    waitMsg:'Saving Group Info...',
                    params: _self.settings,
                    errorReader : new Ext.data.JsonReader({
                        root:'errors',
                        successProperty:'success'
                      }, ['id', 'msg']),
                    success: function(form, action) {
                
                      if (_self.settings.treeNode)
                        _self.settings.treeNode.setText(_self.win.GroupForm.GroupName.getValue());
                      _self.win.hide();

                      return true;
                    },
                    failure: function(form, action) {
                      switch (action.failureType) {
                        case Ext.form.Action.CLIENT_INVALID:
                          Ext.Msg.alert('Failure', 'Please verify all form fields are correct.');
                          break;
                        case Ext.form.Action.CONNECT_FAILURE:
                          Ext.Msg.alert('Failure', 'Ajax communication failed');
                          break;
                        case Ext.form.Action.SERVER_INVALID:
                        default:
                          Ext.Msg.show({
                             title:action.result.title,
                             msg: action.result.msg,
                             buttons: Ext.Msg.OK,
                             icon: action.result.errType == 'error' ? Ext.MessageBox.ERROR : Ext.MessageBox.INFO
                          });
                      }
                      return false;
                    }
                  });
                },
                disabled:true
            },{
                text: 'Close',
                handler: function(){
                  _self.win.hide();
                }
            }]
        });
    }
    this.win.show(this);

};
CS2.Group.Delete = function(initOptions){
    var _self = this;
    this.settings = {};
    
    Ext.apply(this.settings, initOptions);
        
      this.win = new Ext.Window({
          title: 'Delete Group?',
          width:380,
          resizable: false,
          cls: 'x-window-dlg',
          constrainHeader: true,
          layout: 'fit',
          plain: true,
          bodyStyle: 'font-size: 13px; padding: 10px;',
          html: new Ext.XTemplate(
            '<div class="x-dlg-icon">',
              '<div class="ext-mb-icon ext-mb-warning"></div>',
              '<div class="ext-mb-content">',
                '<span class="ext-mb-text">',
                  '<strong>The group &quot;{group_name}&quot; is about to be permanently deleted, are you sure?</strong>',
                  '<br /><br />',
                  'This action will remove all users from the group and revolk whatever privledges they had in it! This cannot be undone!',
                '</span>',
              '</div>',
              '<div class="x-clear"></div>',
            '</div>'
          ).apply({group_name: this.settings.treeNode.attributes.text}),
          buttons: [{
              text:'Delete (3)',
              ref: '../DeleteButton',
              disabled:true,
              handler: function(){
                var params = {GROUPID: _self.settings.treeNode.attributes.ugid};
                Ext.Ajax.request({
                   url: '/ajax/siteconfig/userGroups/deleteGroup.cfm',
                   method: 'GET',
                   'params': params,
                   reader : new Ext.data.JsonReader({
                    success : '@success'
                   }),
                   success: function(response, opts) {
                      var obj = Ext.decode(response.responseText);
                      if (obj.success){
                        var node = _self.settings.treeNode;
                        node.parentNode.childNodes[0].select();
                        node.remove();
                        _self.win.hide();
                      }else{
                        Ext.Msg.alert('Error Deleting Group', 'This group name "'+_self.settings.treeNode.text+'" could not be deleted. Please try again.');
                      }
                   },
                   failure: function(response, opts) {
                    Ext.Msg.alert('Error Deleting Group', 'There was a problem communicating with the server. Please check your internet connection and try again.');
                   }
                });   
                
              }
          },{
              text: 'Cancel',
              handler: function(){
                  this.ownerCt.ownerCt.hide();
              }
          }]
      });
    this.win.show(this);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete (2)'); }, CS2.countDownSpeed * 1);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete (1)'); }, CS2.countDownSpeed * 2);
    setTimeout(function(){ _self.win.DeleteButton.setText('Delete'); _self.win.DeleteButton.enable(); }, CS2.countDownSpeed * 3);
};
CS2.Group.RemoveUserFromGroup = function(initOptions){
    var _self = this;
    this.settings = {};
    
    Ext.apply(this.settings, initOptions);
    
    var n = this.settings.treeNode;
    
    var params = {ID:n.attributes.uid, GROUPID: n.parentNode.attributes.ugid};
    Ext.Ajax.request({
       url: '/ajax/siteconfig/userGroups/deleteGroupUser.cfm',
       method: 'GET',
       'params': params,
       reader : new Ext.data.JsonReader({
        success : '@success'
       }),
       success: function(response, opts) {
          n.parentNode.select();
          n.remove();
       },
       failure: function(response, opts) {
          Ext.Msg.alert('Error Deleting User', 'There was an error deleting user "'+newEl.attributes.text+'" from "'+e.source.text+'"');
       }
    });     

};

    //var treeMenuGroup;
    //var treeMenuUser;
    //var treeMenuUserGroup;
    

function windowUserGroups(loadGCDID, gcdType){
     
      var _self = this;
      if (!canEdit)
        return false;
        
      this.period = 0;
      var gcdID = loadGCDID > 0 ? loadGCDID : 0;
      var isGCDMode = gcdID > 0 ? true : false;


      ///// SETUP MENUS /////
      this.treeMenuGroup = new Ext.menu.Menu({
        listeners: {
          itemclick: function(item) {
            var n = item.parentMenu.contextNode;
            switch (item.menu_id) {
              case 'mnu_item_group-properties':
                new CS2.Group.Edit({treePanel: n.tree, treeNode: n, gcdID: gcdID, gcdType: gcdType, isGCDMode: isGCDMode}); 
                break;
              case 'mnu_item_group-delete':
                new CS2.Group.Delete({treePanel: n.tree, treeNode: n}); 
                break;
            }
          }
        }
      });
      
      this.treeMenuUser = new Ext.menu.Menu({
        listeners: {
          itemclick: function(item) {
            var n = item.parentMenu.contextNode;
            switch (item.menu_id) {                    
              case 'mnu_item_user-delete':
                CS2.User.Delete({treePanel: n.tree, treeNode: n});
                break;
              case 'mnu_item_user-edit':
                CS2.User.CreateEdit({treePanel: n.tree, treeNode: n, configMode: true});
                break;
            }
          }
        }
      });
      
      this.treeMenuUserGroup = new Ext.menu.Menu({
          listeners: {
            itemclick: function(item) {
              var n = item.parentMenu.contextNode;
              switch (item.menu_id) {                    
                case 'mnu_item_groupUser-revolk':
                  CS2.Group.RemoveUserFromGroup({treeNode: n});
                  break;
                case 'mnu_item_groupUser-edit':
                  CS2.User.CreateEdit({treePanel: n.tree,treeNode: n, configMode: true});
                  break;
              }
            }
          }
        });
        
      this.treeMenuGroup.add({menu_id: 'mnu_item_group-properties', iconCls: 'iconUserGroupEdit', text: 'Edit Group...'});
      this.treeMenuGroup.add('-');
      this.treeMenuGroup.add({menu_id: 'mnu_item_group-delete', iconCls: 'iconUserGroupDelete', text: 'Delete Group (Permanent)'});
      
      if (!isGCDMode){
        this.treeMenuUserGroup.add({menu_id: 'mnu_item_groupUser-edit', iconCls: 'iconUserGroupEdit', text: 'Edit User...'});
        this.treeMenuUserGroup.add('-');
      }
      this.treeMenuUserGroup.add({menu_id: 'mnu_item_groupUser-revolk', iconCls: 'iconUserRevolk', text: 'Revolk User'});
      
      this.treeMenuUser.add({menu_id: 'mnu_item_user-edit', iconCls: 'iconUserEdit', text: 'Edit User...'});
      this.treeMenuUser.add('-');
      this.treeMenuUser.add({menu_id: 'mnu_item_user-delete', ref: 'deleteUser', iconCls: 'iconUserDelete', text: 'Delete User (Permanent)'});
      ///// MENUS DONE! /////

      this.treeLeft = new Ext.Panel({
          border: false,
          region: 'center',
          layout: 'border',
          margins:'0 0 5 0',
          cmargins:'3 3 3 3',
          items: [
                  {
                    region: 'north', 
                    margins:'0 0 -1 0',
                    baseCls: 'siteConfigHeaderTab',
                    cmargins:'3 3 3 3',
                    html: '<strong>User Groups</strong>'
                  },
                  new Ext.tree.TreePanel({                    
                    useArrows:true,
                    ref: 'GroupTreePanel',
                    autoScroll:true,
                    animate:true,
                    region: 'center',
                    enableDD:true,
                    containerScroll: true,
                    rootVisible: false,
                    root: { nodeType: 'async', allowDrop: false},
                    dataUrl : '/ajax/login/getUserGroupTree.cfm?gcdid='+gcdID+'&pt=none',
                    tbar: [
                      {
                        xtype: 'buttongroup',
                        title: 'Group',
                        autoWidth: true,
                        defaults: {
                            xtype: 'button',
                            scale: 'small',
                            width: '100%',
                            iconAlign: 'left'
                        },
                        items: [
                          {tooltip: 'Add Group', text: 'Add', iconCls: 'iconUserGroupNew', handler: function(t){ new CS2.Group.Create({gcdID: gcdID, treePanel: t.ownerCt.ownerCt.ownerCt}); }},
                          {tooltip: 'Edit Group', text: 'Edit', iconCls: 'iconUserGroupEdit', disabled: true, disabledClass: 'x-item-disabled-image', ref: '../../EditGroupBtn', handler: function(t){
                            var curNode = t.ownerCt.ownerCt.ownerCt.getSelectionModel().getSelectedNode();
                            new CS2.Group.Edit({treePanel: t.ownerCt.ownerCt, treeNode: curNode, gcdID: gcdID, isGCDMode: isGCDMode}); 
                          }},
                          {tooltip: 'Delete Group', text: 'Delete', iconCls: 'iconUserGroupDelete', disabled: true, disabledClass: 'x-item-disabled-image', ref: '../../DeleteGroupBtn', handler: function(t){
                            var curNode = t.ownerCt.ownerCt.ownerCt.getSelectionModel().getSelectedNode();
                            new CS2.Group.Delete({treePanel: t.ownerCt.ownerCt, treeNode: curNode}); 
                          }}
                        ]
                      },{
                        xtype: 'buttongroup',
                        title: 'User',
                        autoWidth: true,
                        defaults: {
                            xtype: 'button',
                            scale: 'small',
                            width: '100%',
                            iconAlign: 'left'
                        },
                        items: [
                          {tooltip: 'Edit User', text: 'Edit', iconCls: 'iconUserEdit', disabled: true, disabledClass: 'x-item-disabled-image', ref: '../../EditGroupUserBtn', handler: function(t){
                            var curNode = t.ownerCt.ownerCt.ownerCt.getSelectionModel().getSelectedNode();
                            new CS2.User.CreateEdit({treePanel: curNode.tree,treeNode: curNode, configMode: true});
                          }, hidden: isGCDMode},
                          {tooltip: 'Revolk User', text: 'Revolk', iconCls: 'iconUserRevolk', disabled: true, disabledClass: 'x-item-disabled-image', ref: '../../DeleteGroupUserBtn', handler: function(t){
                            var curNode = t.ownerCt.ownerCt.ownerCt.getSelectionModel().getSelectedNode();
                            new CS2.Group.RemoveUserFromGroup({treeNode: curNode});
                          }}
                        ]
                      }                         
                    ],
                    listeners: {
                      load: function(node){
                        Ext.Msg.hide();
                      },
                      click: function(node, e){
                        if (node.getDepth() == 1){
                          _self.treeLeft.GroupTreePanel.EditGroupBtn.enable();
                          _self.treeLeft.GroupTreePanel.DeleteGroupBtn.enable();
                          _self.treeLeft.GroupTreePanel.EditGroupUserBtn.disable();
                          _self.treeLeft.GroupTreePanel.DeleteGroupUserBtn.disable();
                        }else{
                          _self.treeLeft.GroupTreePanel.EditGroupBtn.disable();
                          _self.treeLeft.GroupTreePanel.DeleteGroupBtn.disable();
                          _self.treeLeft.GroupTreePanel.EditGroupUserBtn.enable();
                          _self.treeLeft.GroupTreePanel.DeleteGroupUserBtn.enable();
                        }
                      },
                      contextmenu: function(node, e) {
                        node.select();
                        node.gcdID = gcdID;
                        node.pt = _self.period;
                        var c = node.leaf ? _self.treeMenuUserGroup : _self.treeMenuGroup;
                        c.contextNode = node;
                        c.showAt(e.getXY());
                      },
                      beforenodedrop: function(e){
                        e.target.expand();
                        if((e.target.getDepth() == 1 && e.point!="append") || e.target.getDepth() > 1 || e.target.getDepth() == 0){
                          e.cancel=true;
                          return false;
                        }else if(child=e.target.findChild('uid', e.dropNode.attributes.uid)){
                          Ext.Msg.show({
                             title:'Already a member!',
                             msg: 'This user already exists in this group!',
                             buttons: Ext.Msg.OK,
                             fn: function(){
                              child.select();
                             },
                             icon: Ext.MessageBox.INFO
                          });
                          e.cancel=true;
                          return false;                      
                        }

                        if (e.source.tree.id==e.tree.id){
                          e.cancel=true;
                          var newEl = e.dropNode.clone();
                          var parentNode = e.source.dragData.node.parentNode;
                          var params = {GCDID: gcdID, curPeriod: _self.period, ID:e.dropNode.attributes.uid, OLDGROUPID: parentNode.attributes.ugid, GROUPID: e.target.attributes.ugid};
                          Ext.Msg.show({
                             title:'Copy or Move user?',
                             msg: 'Would you like to Copy (Yes) or Move (No) "'+newEl.attributes.text+'" to the "'+e.target.text+'" group?',
                             buttons: Ext.Msg.YESNOCANCEL,
                             buttonText: {yes: 'Copy', no: 'Move', cancel: 'Cancel'},
                             fn: function(r){
                              if (r=='yes'){
                                Ext.Ajax.request({
                                   url: '/ajax/siteconfig/userGroups/addGroupUser.cfm',
                                   method: 'GET',
                                   'params': params,
                                   reader : new Ext.data.JsonReader({
                                    success : '@success'
                                   }),
                                   success: function(response, opts) {
                                      e.target.appendChild(newEl);
                                      newEl.select();
                                   },
                                   failure: function(response, opts) {
                                      newEl.remove();
                                      Ext.Msg.alert('Error Adding User', 'There was an error adding "'+newEl.attributes.text+'" to "'+e.target.text+'"');
                                   }
                                });
                              }else if(r=='no'){
                                Ext.Ajax.request({
                                   url: '/ajax/siteconfig/userGroups/moveGroupUser.cfm',
                                   method: 'GET',
                                   'params': params,
                                   reader : new Ext.data.JsonReader({
                                    success : '@success'
                                   }),
                                   success: function(response, opts) {
                                    e.target.appendChild(newEl);
                                    e.dropNode.remove();
                                   },
                                   failure: function(response, opts) {
                                      Ext.Msg.alert('Error Adding User', 'There was an error adding "'+newEl.attributes.text+'" to "'+e.target.text+'"');
                                   }
                                });
                              }
                             },
                             icon: Ext.MessageBox.QUESTION
                          });
                          return false;
                        }else{
                          var newEl = e.dropNode.clone();
                          e.dropNode = newEl;
                          var params = {GCDID: gcdID, curPeriod: _self.period, ID:e.dropNode.attributes.uid, GROUPID: e.target.attributes.ugid};
                          Ext.Ajax.request({
                             url: '/ajax/siteconfig/userGroups/addGroupUser.cfm',
                             method: 'GET',
                             'params': params,
                             reader : new Ext.data.JsonReader({
                              success : '@success'

                             }),
                             success: function(response, opts) {
                             
                             },
                             failure: function(response, opts) {
                                newEl.remove();
                                Ext.Msg.alert('Error Adding User', 'There was an error adding "'+newEl.attributes.text+'" to "'+e.source.text+'"');
                             }
                          });
                        }
                      }
                    }
                  })
                ]
        });
        
          
        this.treeRight = new Ext.Panel({
            border: false,
            region: 'east',
            layout: 'border',
            margins:'0 0 5 5',
            cmargins:'3 3 3 3',
            width: 260,
            items: [
              {
                region: 'north', 
                margins:'0 0 -1 0',
                baseCls: 'siteConfigHeaderTab',
                cmargins:'3 3 3 3',
                html: '<strong>Available Users</strong>'
              },{
                region: 'south', 
                margins:'10 10 10 10',
                cmargins:'3 3 3 3',
                baseCls: 'x-plain', 
                border: true, 
                html: '<strong>Drag & Drop above users</strong> to the left to assign them to a group.'
              },new Ext.tree.TreePanel({
                  id : 'mainuserEditorTree',
                  ref: 'UserTreePanel',
                  useArrows:true,
                  autoScroll:true,
                  animate:true,
                  region: 'center',
                  enableDD:true,
                  //tbar: [{text: 'Add'},{text: 'Rename'},{text: 'Delete'}],
                  containerScroll: true,
                  rootVisible: false,
                  root: { nodeType: 'async', allowDrop: false},
                  dataUrl : '/ajax/login/getUserTree.cfm',
                  tbar: [
                    {
                        xtype: 'buttongroup',
                        title: 'User',
                        hidden: isGCDMode,
                        autoWidth: true,
                        defaults: {
                            xtype: 'button',
                            scale: 'small',
                            width: '100%',
                            iconAlign: 'left'
                        },
                        items: [  
                          {tooltip: 'Add User', text: 'Add', ref: '../../AddUserBtn', iconCls: 'iconUserNew', handler: function(t){
                            var curTree = t.ownerCt.ownerCt.ownerCt;
                            new CS2.User.CreateEdit({treePanel: curTree, configMode: true})
                          }},
                          {tooltip: 'Edit User', text: 'Edit', ref: '../../EditUserBtn', disabled: true, disabledClass: 'x-item-disabled-image', iconCls: 'iconUserEdit', handler: function(t){
                            var curTree = t.ownerCt.ownerCt.ownerCt;
                            var curNode = t.ownerCt.ownerCt.ownerCt.getSelectionModel().getSelectedNode();
                            new CS2.User.CreateEdit({treePanel: curTree, treeNode: curNode, configMode: true})
                          }},
                          {tooltip: 'Delete User', text: 'Delete', ref: '../../DeleteUserBtn', disabled: true, disabledClass: 'x-item-disabled-image', iconCls: 'iconUserDelete', handler: function(t){
                            var curTree = t.ownerCt.ownerCt.ownerCt;
                            var curNode = t.ownerCt.ownerCt.ownerCt.getSelectionModel().getSelectedNode();
                            new CS2.User.Delete({treePanel: curTree, treeNode: curNode});
                          }}
                        ]
                      },{
                        xtype: 'buttongroup',
                        title: 'Change Period',
                        hidden: !isGCDMode,
                        //autoWidth: true,
                        defaults: {
                            scale: 'small',
                            width: '100%'
                        },
                        items: [
                          new Ext.form.ComboBox({
                              typeAhead: true,
                              mode: 'local',
                              triggerAction: 'all',
                              emptyText: 'Select a period...',
                              selectOnFocus: true,
                              getListParent: function() {
                                  return this.el.up('.x-menu');
                              },
                              iconCls: 'no-icon',
                              displayField: 'name',
                              ref: '../../PeriodCombo',
                              store: new Ext.data.Store({
                                autoLoad: isGCDMode,
                                url: '/ajax/siteconfig/gcd/getGCDPeriodsJson.cfm?id='+gcdID,
                                reader : new Ext.data.JsonReader({
                                    root : 'periods'                           
                                  },[
                                    {name: 'id', mapping: 'id'},
                                    {name: 'name', mapping: 'name'}
                                  ]
                                ),
                                listeners: {
                                  load: function(s,r,o){
                                    if (!isGCDMode)
                                      return false;
                                    if (r[0].data.id == "error_no_periods"){
                                      var n = _self._settings;
                                      var winName = 'gcd_edit';
                                      var switchTabToPeriod = function(){
                                        Ext.getCmp('editPanel_tabs_'+winName).activate(1);
                                      }
                                      Ext.Msg.show({
                                         title:'Setup Error',
                                         msg: 'There are no periods defined. The properties for this location will now open so you can specify them.',
                                         buttons: Ext.Msg.OK,
                                         fn: function(){
                                          _self.winNavEdit.close();
                                          if (n.parentNode) {
                                            if (n.attributes.data_type=='department'){
                                              setTimeout(function(){
                                                callEditor({navigationContextNode: n, afterFn: switchTabToPeriod, 'winName': winName, editorDataID: n.attributes.gcd_id, editorType: 'Department', editorModal: true});
                                              }, 100);
                                            }else if (n.attributes.data_type=='class'){
                                              setTimeout(function(){
                                                callEditor({navigationContextNode: n, afterFn: switchTabToPeriod, 'winName': winName, editorDataID: n.attributes.gcd_id, editorType: 'Class', editorModal: true});
                                              }, 100);
                                            }
                                          }
                                         },
                                         icon: Ext.MessageBox.ALERT
                                      });
                                      return false;
                                    }
                                    Ext.Msg.wait('Loading users...', 'Please wait');
                                    var rID = 0;
                                    _self.period=r[rID].data.id;
                                    _self.treeRight.UserTreePanel.PeriodCombo.setValue(r[rID].data.name);
                                    //treeLeft.GroupTreePanel.getLoader().dataUrl = '/ajax/siteconfig/gcd/getGCDUsersJson.cfm?id='+gcdID+'&pt='+r[rID].data.id;
                                    _self.treeLeft.GroupTreePanel.getLoader().dataUrl = '/ajax/login/getUserGroupTree.cfm?gcdid='+gcdID+'&pt='+r[rID].data.id;
                                    _self.treeLeft.GroupTreePanel.getRootNode().reload();
                                  }
                                }
                              }),
                              listeners: {
                                select: function(c,r,i){
                                  _self.period=r.data.id;
                                  Ext.Msg.wait('Loading users...', 'Please wait');
                                  //treeLeft.GroupTreePanel.getLoader().dataUrl = '/ajax/siteconfig/gcd/getGCDUsersJson.cfm?id='+gcdID+'&pt='+r.data.id;
                                  _self.treeLeft.GroupTreePanel.getLoader().dataUrl = '/ajax/login/getUserGroupTree.cfm?gcdid='+gcdID+'&pt='+r.data.id;
                                  _self.treeLeft.GroupTreePanel.getRootNode().reload();
                                }
                              }
                            })
                        ]
                      }  
                  ],
                  listeners: {
                    click: function(node, e){
                      treeRight.UserTreePanel.EditUserBtn.setDisabled(node.getDepth() == 1);
                      treeRight.UserTreePanel.DeleteUserBtn.setDisabled(node.getDepth() == 1 || node.attributes.uid == 1 || node.attributes.username == 'admin');
                    },
                    contextmenu: function(node, e) {
                      node.select();
                      if (!isGCDMode && node.getDepth() > 1){
                        node.gcdID = gcdID;
                        node.pt = _self.period;
                        var c = _self.treeMenuUser;
                        c.contextNode = node;
                        c.deleteUser.setDisabled(node.attributes.uid == 1 || node.attributes.username == 'admin');
                        c.showAt(e.getXY());
                      }
                    },
                    checkchange: function(node, checked){
                      if(checked){
                        node.getUI().addClass('complete');
                      }else{
                        node.getUI().removeClass('complete');
                      }
                    }
                  }
              })]
          });
  
  this.navInfo = '<strong>Notice:</strong> Changes are automatically saved as you make them.';
  
  this.userGroupWin = new Ext.Window({
      title: isGCDMode ? gcdType + ' Members' : 'Group Manager',
      iconCls: 'cpi_userGroups',
      minWidth: 600,
      minHeight: 400,
      width: 600,
      height: 400,
      constrainHeader: true,
      border: true,          
      layout: 'fit',
      padding: 5,
      modal: true,
      bodyStyle: 'background: #DFE8F6',
      id: 'tabUserGroups',
      listeners: {
        afterRender: function(win){
          Ext.Msg.hide()
        }
      },
      items: new Ext.Panel({
              border: false,
              layout: 'border',
              items: [
                {
                  region: 'south',
                  padding: 5,
                  border: true,
                  bodyStyle: 'text-align: center; background: #fc3;',
                  html: _self.navInfo
                },
                _self.treeLeft,
                _self.treeRight]
              })
  });  
  this.userGroupWin.show(this);
    
}


reportingIn('userGroups');
reportingIn('userGCDMembers');
