// ----------------------------------Window ------------------------------------
var Users_adm_menWin;       // variable creating window declaration
//var Users_adm_menForm;
var users_adm_men_win_delete;
var select;

var msguam_user = function(title, msguam, select) {                  // function delete user
        Ext.Msg.show({
            title: title,
            msg: msguam,
            minWidth: 200,
            modal: true,
            icon: Ext.Msg.QUESTION,
            buttons:Ext.Msg.YESNO,
            fn:function(btn){
                 if(btn=='no'){
           var deleteButton = Ext.getCmp('delete');
                   deleteButton.setDisabled(true);     
                 }
                 if(btn=='yes'){
                  //alert (select);
                                                $.post("app/SFALite_Users.php",{func:'delete',id:select},function(data)
                                                {
                                                    Users_adm_menGrid.store.load();
                                                    Users_adm_menGrid.getView().refresh();
                                                    var deleteButton = Ext.getCmp('delete');
                                                    deleteButton.setDisabled(true);
                                                
                                                });                                              
                 }
            }


      
        });
    };



Ext.define('client_id', {
    extend: 'Ext.data.Model',
    fields: [ 'id','name']
});

Ext.define('Users_adm_menFields', {
    extend: 'Ext.data.Model',
    fields: ['id', 'login', 'first_name', 'last_name', 'name']
});

Ext.define('ModelRolenames', {
    extend: 'Ext.data.Model',
    fields: [ 'id','name']
});


var Data_client_id = new Ext.data.Store({
        model: 'client_id',
           proxy: {
              type: 'ajax',
              url: 'app/SFALite_Users.php?func=client',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });
   
var StoreRolenames = new Ext.data.Store({
    model: 'ModelRolenames',
           proxy: {
              type: 'ajax',
              url: 'app/SFALite_Users.php?func=getRolenames',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
});

var Users_adm_menStore = new Ext.data.Store({
        model: 'Users_adm_menFields',
           proxy: {
              type: 'ajax',
              url: 'app/SFALite_Users.php?func=users_adm_menfields',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
});




function show_SFALite_Users_Window()
{
  if (!Users_adm_menWin || Users_adm_menWin.Window==null)
  {
    Users_adm_menWin = new Windows('Пользователи',600,380);
    Users_adm_menStore.load();
    createGridAdministrationUsers();
    Users_adm_menWin.CreateWindowMaximizableDestroy(Users_adm_menWin,Users_adm_menGrid);
   

  // ------------------------------ create button ------------------------------------------  
    var addUser = Ext.create('Ext.button.Button', { 
          text: 'Добавить',
          iconCls: 'adduser',
          handler: function(){showFormUser();}
    });
    var correctUser = Ext.create('Ext.button.Button', { 
          text: 'Редактировать',
          iconCls: 'createtask',
          handler: function(){
                    if (!select){msg('Выбрано 0 записей.', 'Выберите запись!');}
                    else{
                    showFormUser(select);
                    select=0;
                    }
          }
    });
    var deleteUser = Ext.create('Ext.button.Button', { 
        text: 'Удалить',    
        iconCls: 'deluser',
        disabled: true,
        itemId: 'delete',
        id: 'delete_user',
        handler: function(){
                       if (!select){msg('Выбрано 0 записей', 'Выберите запись!');}
                       else{
                       msguam_user('Удаление', 'Вы точно хотите удалить даного пользователя!?',select);
                       }
                  }
    });
    Users_adm_menWin.Window.addDocked(
    {
      xtype: 'toolbar',
      dock: 'top',
      items:[addUser,correctUser,deleteUser]
    });
  }
  
//---------------------------------------------------------------------------------------- 
 
  Users_adm_menWin.Window.show();
  
   
}

// ------------------------------------- create Grid --------------------------------------    
function createGridAdministrationUsers()
{
  var Users_adm_men_gridId = "Users_adm_men_grid";
  Users_adm_menGrid = new Ext.grid.GridPanel({
  selType: 'rowmodel',
  columnLines: true,
  //plugins: [rowEditing_report],
  id: 'Users_adm_men_gridId',
  store: Users_adm_menStore,
  columns:[
  {
    text : '№', 
    dataIndex : 'id',
    width:40,
    sortable: true,
    id: 'id_uam'
  },
  {
    text : 'Логин', 
    dataIndex : 'login',
    width: 140,
    sortable: true,
    id: 'login_uam'
  },
  {
    text : 'Фамилия', 
    dataIndex : 'first_name',
    width:140,
    sortable: true/*,
    id: 'firstName_uam'*/
  },
  {
    text : 'Имя', 
    dataIndex : 'last_name',
    width: 140,
    sortable: true/*,
    id: 'lastName_uam'*/
  },
  {
    text : 'Права пользователя', 
    dataIndex : 'name',
    width: 125,
    sortable: true/*,
    id: 'role_uam'*/
  }
  ],
  listeners:
  {
    itemclick: function(View,record,item,index,e,eOpts )
    {
      select = record.get('id');
      select =parseInt(select);
      var deleteButton = Ext.getCmp('delete_user');
      deleteButton.setDisabled(false);
    },
    itemdblclick: function(View,record,item,index,e,eOpts )
    {
      select = record.get('id');
      select=parseInt(select);
      //showUsers_adm_menFormEdit(select);
      showFormUser(select);
      select=0;
    }
  }
  });
}

// ------------------------------- Create Form for Add and Correct User Data ------------------------

function showFormUser(select)
{
  sel_adm_men_edit=select;

  $.post('app/SFALite_Users.php', {func:'users_adm_men_edit',sel_adm_men_edit:sel_adm_men_edit}, function(data){
  adm_men_edit = data.split('/t');

      id_adm_men_edit=parseInt(adm_men_edit[0]);
      formBossIdValue = parseInt(adm_men_edit[1]);
      formLoginValue=adm_men_edit[2];
      password_adm_men_edit=adm_men_edit[3];
      formFirstNameValue = adm_men_edit[4];
      formLastNameValue = adm_men_edit[5];
      formMiddleNameValue = adm_men_edit[6];
      formPositionValue = adm_men_edit[7];
      formEmailValue = adm_men_edit[8];
      formTelValue = adm_men_edit[9];
      formAddressValue = adm_men_edit[10];
      formCommentsValue=adm_men_edit[11];
      formRoleValue = parseInt(adm_men_edit[12]);
  
		imeiValue = adm_men_edit[13];
  
  
  var FormConstructor = new Forms();
var formLogin = FormConstructor.CreateTextFieldWidthPercent('Логин','top','95%',formLoginValue);
var formNewPassword = FormConstructor.CreateTextFieldWidthPercent('Новый пароль','top','95%','');
var formConfirmPassword = FormConstructor.CreateTextFieldWidthPercent('Подтверждение пароля','top','95%','');
StoreRolenames.load();
var formRole = FormConstructor.CreateComboboxFieldProxyWidthPercent('Права пользователя','top',StoreRolenames,'name','id','95%',formRoleValue);
var formFirstName = FormConstructor.CreateTextFieldWidthPercent('Фамилия','top','95%',formFirstNameValue);
var formLastName = FormConstructor.CreateTextFieldWidthPercent('Имя','top','95%',formLastNameValue);
var formMiddleName = FormConstructor.CreateTextFieldWidthPercent('Отчество','top','95%',formMiddleNameValue);
var formPosition = FormConstructor.CreateTextFieldWidthPercent('Должность','top','95%',formPositionValue);
Data_boss_id.load();
var formBossId = FormConstructor.CreateComboboxFieldProxyWidthPercent('Подчиняется','top',Data_boss_id,'FIO_B','id','95%',formBossIdValue);
var formEmail = FormConstructor.CreateTextFieldWidthPercent('e-mail','top','95%',formEmailValue);
var formTel = FormConstructor.CreateTextFieldWidthPercent('Телефон','top','95%',formTelValue);
var formAddress = FormConstructor.CreateTextFieldWidthPercent('Адрес','top','95%',formAddressValue);
var formComments = FormConstructor.CreateTextFieldWidthPercent('Дополнительная информация','top','95%',formCommentsValue);

var formImei = FormConstructor.CreateTextFieldWidthPercent('IMEI','top','95%',imeiValue);

var formUser = Ext.create('Ext.form.Panel', 
                        {
                            frame:true,
                            bodyStyle:'padding:5px 5px 0',
                            width: '100%',
                            autoScroll: true,
                            fieldDefaults: {
                                labelAlign: 'top',
                                msgTarget: 'side'
                            },                
                            items:[{
                              xtype: 'fieldcontainer',
                              anchor: '100%',
                              layout:'column',
                              items:[{
                                  xtype: 'fieldcontainer',
                                  columnWidth:.5,
                                  layout: 'anchor',
                                  items: [formLogin,formNewPassword,formConfirmPassword,formRole,formFirstName,formLastName,formMiddleName]
                                },
                                {
                                  xtype: 'container',
                                  columnWidth:.5,
                                  layout: 'anchor',
                                  items: [formPosition,formBossId,formEmail,formTel,formAddress,formComments,formImei]
                              }]
                          }]
                        });
    var windowFormUser = new Windows('Данные пользователя',600,410);
    windowFormUser.CreateWindowModal(windowFormUser,formUser);
    
    var saveUserData = Ext.create('Ext.button.Button', { 
      text: 'Сохранить',    
      iconCls: 'save',
      handler: function(){
            var id = id_adm_men_edit;
            var login = formLogin.getValue();
            var password2 = formNewPassword.getValue();
            var password3 = formConfirmPassword.getValue();
            var role = formRole.getValue();
            var firstName = formFirstName.getValue();
            var lastName = formLastName.getValue();
            var middleName = formMiddleName.getValue();
            var position = formPosition.getValue();
            var bossID = formBossId.getValue();
            var email = formEmail.getValue(); 
            var tel = formTel.getValue(); 
            var address = formAddress.getValue();
            var comments = formComments.getValue(); 
            var imei = formImei.getValue();
			
            if (login=='' || password2 != password3 || password2=='' || formBossId == '' || role == '')
            {
              msg('Ошибка!', 'Проверьте данные!');
              if (login==''){formLogin.markInvalid('Проверьте данные!');}
              if (password2==''){formNewPassword.markInvalid('Проверьте данные!');}
              if (password3==''){formConfirmPassword.markInvalid('Проверьте данные!');}
              if (bossID==''){formBossId.markInvalid('Проверьте данные!');}
              if (role ==''){formRole.markInvalid('Проверьте данные!');}
            }
            else 
            {
              $.post("app/SFALite_Users.php",{func:'users_adm_update',id:id,login:login,password:password2,id_role:role,first_name:firstName,last_name:lastName,middle_name:middleName,position:position,id_boss:bossID,email:email,phone:tel,address:address,comments:comments,imei:imei}, function(data){
                          //alert(data);
                          windowFormUser.Window.destroy();
                          Users_adm_menGrid.store.load();
                          Users_adm_menGrid.getView().refresh();
                          var deleteButton = Ext.getCmp('delete');
                          deleteButton.setDisabled(true);
                          });
            }
            }
  });
  var cancelInputUserData = Ext.create('Ext.button.Button', { 
      text: 'Отмена',    
      handler: function(){
                windowFormUser.Window.destroy();
                Users_adm_menGrid.store.load();
                Users_adm_menGrid.getView().refresh();
                var deleteButton = Ext.getCmp('delete');
                deleteButton.setDisabled(true);
            }
  });
  windowFormUser.Window.addDocked(
  {
    xtype: 'toolbar',
    dock: 'bottom',
    items:['->',saveUserData,'-',cancelInputUserData]
  });
    
    windowFormUser.Window.show();
  });
  
}
