var TOiR_Client_Window = null;
var TOiR_Client_WindowAdd = null;
var TOiR_Client_WindowEdit = null;
var itemsPerPage = 25;

Ext.define('ClientModel', {
    extend: 'Ext.data.Model',
    fields: ['id_client', 'client','region','city','address','contact_number','contact_name','contract_number',
             'note','sales_contact_number', 'external_id']
  });

  var  ClientStore = new Ext.data.Store({
      autoLoad: true,
      // autoDestroy: true,
      pageSize: itemsPerPage,
      model: 'ClientModel',
      proxy: 
      {
        type: 'rest',
        url: 'app/TOiR_Client.php?func=show',
        reader: 
        {
          type: 'json',
          root: 'rows',
          totalProperty: 'results'
        }
      }
    });

function show_TOiR_Client_Window(Xcoord,Ycoord,Wwidth,Wheight){
  Xcoord = Xcoord ? Xcoord :40;
  Ycoord = Ycoord ? Ycoord :60;  
  Wwidth = Wwidth ? Wwidth :1100;  
  Wheight = Wheight ? Wheight :400;


  



  var ClientPagingToolbar = new Ext.PagingToolbar({
        displayInfo    : true,
        store          : ClientStore,

        });
  var ClientFilters = {
        ftype: 'filters',
        encode: false, // json encode the filter query
    };


  var ClientGrid = Ext.create('Ext.grid.Panel', {
    selType: 'rowmodel',

    columnLines: true,
    id: 'TOiR_ClientGridId',
    store: ClientStore,
    loadMask: true,
    bbar: [ClientPagingToolbar],
    border: false,
    autoScroll: true,
    dockedItems: [{
            xtype: 'toolbar',
            items: [{
                //text: 'Добавить',
                text: all_toir.add,
                iconCls: 'add',
                handler: function(){
                  show_TOiR_Client_WindowAdd();
                }
                },'-',{
                //text: 'Удалить',
                text: all_toir.del,
                iconCls: 'delete',
                handler: function(){
                  TOiR_Client_WindowRemove();
                },
                },'-',{
                  //text: 'Редактировать',
                  text: all_toir.edit,
                  iconCls: 'edit',
                  handler: function (){
                    var select = Ext.getCmp('TOiR_ClientGridId').getView().getSelectionModel().getSelection()[0];
                    // alert(select.get('id_client'));
                     if (select) {
                        var id_client = select.get('id_client');
                        var client = select.get('client');
                        // var name_TT = record.get('name_TT');
                        var region = select.get('region');
                        var city = select.get('city');
                        var address = select.get('address');
                        var contact_number = select.get('contact_number');
                        var contact_name = select.get('contact_name');
                        // var id_code_PSD = record.get('id_code_PSD');
                        var contract_number = select.get('contract_number');
                        var note =select.get('note');
                        // var type_TT = record.get('type_TT');
                        var sales_contact_number = select.get('sales_contact_number');
                        var external_id = select.get('external_id');
                        
                        show_TOiR_Client_WindowEdit(id_client,client,region,city,address,contact_number,contact_name,contract_number,note,sales_contact_number, external_id);
                      
                      } else {
                        Ext.MessageBox.alert(all_toir.error, all_toir.select_row);
                      }
                    }
                }
                ],
    }],
    listeners: {
      itemdblclick: function (View,record,item,index,e,eOpts){
        var id_client = record.get('id_client');
        var client = record.get('client');
        // var name_TT = record.get('name_TT');
        var region = record.get('region');
        var city = record.get('city');
        var address = record.get('address');
        var contact_number = record.get('contact_number');
        var contact_name = record.get('contact_name');
        // var id_code_PSD = record.get('id_code_PSD');
        var contract_number = record.get('contract_number');
        var note = record.get('note');
        // var type_TT = record.get('type_TT');
        var sales_contact_number = record.get('sales_contact_number');
        var external_id = record.get('external_id'); 
        
        show_TOiR_Client_WindowEdit(id_client,client,region,city,address,contact_number,contact_name,contract_number,note,sales_contact_number, external_id);
      }
    },
    columns:[
      {
        //text: 'Id Клиента',
        text: client_toir.client_Id,
        dataIndex: 'id_client',
        hidden:true,
        sortable: true,
        hideable: false
        // flex:1
      },
      {
        //text: 'Клиент', 
        text: client_toir.client,
        dataIndex: 'client',
        // width: 90,
        //hideable: false,
        sortable: true,
        filter: {
          type: 'string'
        },
        // flex:1
      },
      // {
      //   text: 'Название ТТ', 
      //   dataIndex: 'name_TT',
      //   hideable: false,
      //   sortable: true,
      //   filter: {
      //     type: 'string'
      //   },
        // flex:1
      // },
      {
        //text: 'Область',
        text: client_toir.domain, 
        dataIndex: 'region',
       //hideable: false,
        sortable: true,
        filter: {
          type: 'string'
        },
        // flex:1
      },
      {
        //text: 'Город',
        text: client_toir.sity, 
        dataIndex: 'city',
        //hideable: false,
        sortable: true,
        filter: {
          type: 'string'
        },
        // flex:1
      },
      {
        //text: 'Адрес',
        text: client_toir.address,
        dataIndex: 'address',
        //hideable: false,
        sortable: true,
        filter: {
          type: 'string'
        },
        // flex:1
      },
      {
        //text: 'Контактный телефон',
        text: client_toir.contact_phone,
        dataIndex: 'contact_number',
        //hideable: false,
        sortable: true,
        width: 120,
        // flex:1
      },
      {
        //text: 'Контактное лицо',
        text: client_toir.contact_person, 
        dataIndex: 'contact_name',
       // hideable: false,
        sortable: true,
        filter: {
          type: 'string'
        },
        // flex:1
      },
      // {
      //   text: 'ID код PS&D', 
      //   dataIndex: 'id_code_PSD',
      //   hideable: false,
      //   sortable: true,
      //   filter: {
      //     type: 'numeric'
      //   },
      //   flex:1
      // },
      {
        //text: 'Номер контракта',
        text: client_toir.contract_number, 
        dataIndex: 'contract_number',
        //hideable: false,
        sortable: true,
        filter: {
          type: 'string'
        },
        // flex:1
      },
      {
        //text: 'Примечание',
        text: client_toir.note, 
        dataIndex: 'note',
       // hideable: false,
        sortable: true,
        filter: {
          type: 'string'
        },
        // flex:1
      },
      // {
      //   text: 'Тип ТТ', 
      //   dataIndex: 'type_TT',
      //   hideable: false,
      //   sortable: true,
      //   filter: {
      //     type: 'string'
      //   },
      //   flex:1
      // },
      {
        //text: 'Телефон торгового представителя',
        text: client_toir.telephone_sales_representative, 
        dataIndex: 'sales_contact_number',
       // hideable: false,
        sortable: true
        
      }, {
    	  //text: 'Внешний ID',
    	  text: request_toir.external_ID,
    	  dataIndex: 'external_id',
    	  flex:1
    	  
      }
    ]
  });
  if (!TOiR_Client_Window) {
    TOiR_Client_Window = new Ext.Window({
      layout : 'fit',
      autoScroll:true,
      //title : 'Клиенты',
      title : TOiR.Client,
      closeAction : 'destroy',
      width : parseInt(Wwidth),
      height : parseInt(Wheight),
      // constrainHeader: true,
      maximizable:true,
      
      listeners : {
          destroy : function(){
              TOiR_Client_Window = null;   
          } 
      },
      items : [ClientGrid]
    });
  }

  function show_TOiR_Client_WindowAdd() {
    if(!TOiR_Client_WindowAdd){
      TOiR_Client_WindowAdd = new Ext.Window({
        autoScroll:true,
        closeAction : 'destroy',
        width: 350,
        //title : 'Добавить клиента',
        title : client_toir.add_client,
         modal:true,
         resizable: true,
        listeners : {
            destroy : function(){
            TOiR_Client_WindowAdd = null;    
            }
        },
        items: [{
          xtype: 'form',
          autoScroll: true,
          bodyPadding: '5 5 5 5',
          id: "ClientFormId",
          bodyPadding: 5,
          border: false,
          frame: true,
          autoHeight: true,
          layout: {
              type: 'vbox',
              align: 'stretch'
          },
          // defaults: {
          //     labelAlign: 'left',
          //     labelWidth: 90,
          //     msgTarget: 'side'
          // },
          items:[{
                //fieldLabel: 'Id Клиента',
                fieldLabel: client_toir.client_Id, 
                name: 'id_client',
                xtype:'hiddenfield'
              },
              {
                //fieldLabel: 'Клиент',
                fieldLabel: client_toir.client, 
                name: 'client',
                xtype:'textfield',
				allowBlank: false
              },
              // {
              //   fieldLabel: 'Название ТТ', 
              //   name: 'name_TT',
              //   xtype:'textfield'
              // },
              {
                //fieldLabel: 'Область',
                fieldLabel: client_toir.domain, 
                name: 'region',
                xtype:'textfield'
              },
              {
                //fieldLabel: 'Город',
                fieldLabel: client_toir.sity, 
                name: 'city',
                xtype:'textfield',
				allowBlank: false
              },
              {
                //fieldLabel: 'Адрес',
                fieldLabel: client_toir.address, 
                name: 'address',
                xtype:'textfield',
				allowBlank: false
              },
              {
                //fieldLabel: 'Контактный телефон',
                fieldLabel: client_toir.contact_phone, 
                name: 'contact_number',
                xtype:'textfield',
				allowBlank: false
              },
              {
                //fieldLabel: 'Контактное лицо',
                fieldLabel: client_toir.contact_person, 
                name: 'contact_name',
                xtype:'textfield'
              },
              // {
              //   fieldLabel: 'ID код PS&D', 
              //   name: 'id_code_PSD',
              //   xtype:'textfield'
              // },
              {
                //fieldLabel: 'Номер контракта',
                fieldLabel: client_toir.contract_number, 
                name: 'contract_number',
                xtype:'textfield'
              },
              {
                //fieldLabel: 'Примечание',
                fieldLabel: client_toir.note, 
                name: 'note',
                xtype:'textfield'
              },
              // {
              //   fieldLabel: 'Тип ТТ', 
              //   name: 'type_TT',
              //   xtype:'textfield'
              // },
              {
                //fieldLabel: 'Телефон торгового представителя',
                fieldLabel: client_toir.telephone_sales_representative, 
                name: 'sales_contact_number',
                xtype:'textfield'
              }, {
            	  xtype: 'textfield',
            	  //fieldLabel: 'Внешний ID',
            	  fieldLabel: request_toir.external_ID,            	  
            	  name: 'external_id'
              }
            ],
            buttons: 
            [{  
              //text: 'Добавить',
              text: all_toir.add,
              handler: function()
                {
                  var form = Ext.getCmp('ClientFormId').getForm();
                  if(form.isValid()){
                    form.submit(
                    {
                      //waitMsg:'Идет отправка...',
                      waitMsg: all_toir.loading,
                      url: 'app/TOiR_Client.php?func=add',
                      //params : {key : 'val', key2 : 'val2'},
                      success: function(fp, o)
                      {
                        // Ext.Msg.alert('Внимание','Успешно добавлен'); 
                        if(o.result.success == true){
							TOiR_Client_WindowAdd.destroy();
							Ext.getCmp('TOiR_ClientGridId').store.load();
							Ext.getCmp('TOiR_ClientGridId').getView().refresh();
						}else{
							Ext.Msg.alert(all_toir.attention, o.result.message);
						}
                      },
                      failure: function(fp, o)
                      {
                        Ext.Msg.alert(all_toir.attention, o.result.message); 
                      }
                    });
                  }else{
                    Ext.Msg.alert(all_toir.attention, all_toir.required_fields); 
                  }
              }
           },
           {
              //text: 'Отмена',
              text: all_toir.cancel,
              handler: function()
                        {
                          TOiR_Client_WindowAdd.close();
                        }
            }
          ] 

        }]
      });
    }
    TOiR_Client_WindowAdd.show();
  }
  function TOiR_Client_WindowRemove() {
    if (ClientGrid) {
      var sm = ClientGrid.getSelectionModel();
      var rs = sm.getSelection();
      if(!rs) return false;
      var id_client = rs[0].get('id_client');
      if (!rs.length) {
          Ext.Msg.alert(all_toir.attention, client_toir.the_client_is_not_selected);
          return;
          }
      Ext.Msg.confirm(all_toir.attention, client_toir.are_you_sure_want_to_delete_the_selected_customer, function (button) {
          if (button == 'yes') {
                      Ext.Ajax.request({  
                          url : 'app/TOiR_Client.php?func=del',
                          method: 'GET',
                          params: {id_client: id_client}, 
                          success: function(objServerResponse){
                        	  ClientGrid.store.load(); 
                          }
                      });
                       //ClientGrid.store.remove(rs[0]);
                                }
          });
      }
  }
  function show_TOiR_Client_WindowEdit(id_client,client,region,city,address,contact_number,contact_name,contract_number,note,sales_contact_number, external_id) {
    if(!TOiR_Client_WindowEdit) {
      TOiR_Client_WindowEdit = new Ext.Window ({
              autoScroll:true,
              modal:true,
              // bodyPadding: 5,
              width: 350,
              //title : 'Редактировать клиента',
              title : client_toir.edit_client,
              // id: 'ClientFormId',
              listeners : {
                    destroy : function(){
                    TOiR_Client_WindowEdit = null;    
                    }
                },

              items: [{
                xtype: 'form',
                autoScroll: true,
                bodyPadding: '5 5 5 5',
                id: "ClientFormId",
                border: false,
                frame: true,
                autoHeight: true,
                layout: {
                  type: 'vbox',
                  align: 'stretch'
                },
                // defaults: {
                //   labelAlign: 'left',
                //   labelWidth: 90,
                //   msgTarget: 'side'
                // },
                items: [{
                    //fieldLabel: 'Id Клиента',
                    fieldLabel: client_toir.client_Id, 
                    name: 'id_client',
                    xtype:'hiddenfield',
                    value: id_client
                  },
                  {
                    //fieldLabel: 'Клиент',
                    fieldLabel: client_toir.client, 
                    name: 'client',
                    xtype:'textfield',
                    value: client
                  },
                  // {
                  //   fieldLabel: 'Название ТТ', 
                  //   name: 'name_TT',
                  //   xtype:'textfield',
                  //   value: name_TT
                  // },
                  {
                    //fieldLabel: 'Область',
                    fieldLabel:  client_toir.domain, 
                    name: 'region',
                    xtype:'textfield',
                    value: region
                  },
                  {
                    //fieldLabel: 'Город',
                    fieldLabel: client_toir.sity, 
                    name: 'city',
                    xtype:'textfield',
                    value: city
                  },
                  {
                    //fieldLabel: 'Адрес',
                    fieldLabel: client_toir.address, 
                    name: 'address',
                    xtype:'textfield',
                    value: address
                  },
                  {
                    //fieldLabel: 'Контактный телефон',
                    fieldLabel: client_toir.contact_phone, 
                    name: 'contact_number',
                    xtype:'textfield',
                    value: contact_number
                  },
                  {
                    //fieldLabel: 'Контактное лицо',
                    fieldLabel: client_toir.contact_person, 
                    name: 'contact_name',
                    xtype:'textfield',
                    value: contact_name
                  },
                  // {
                  //   fieldLabel: 'ID код PS&D', 
                  //   name: 'id_code_PSD',
                  //   xtype:'textfield',
                  //   value: id_code_PSD
                  // },
                  {
                    //fieldLabel: 'Номер контракта',
                    fieldLabel:  client_toir.contract_number, 
                    name: 'contract_number',
                    xtype:'textfield',
                    value: contract_number
                  },
                  {
                    //fieldLabel: 'Примечание',
                    fieldLabel: client_toir.note, 
                    name: 'note',
                    xtype:'textfield',
                    value: note
                  },
                  // {
                  //   fieldLabel: 'Тип ТТ', 
                  //   name: 'type_TT',
                  //   xtype:'textfield',
                  //   value: type_TT
                  // },
                  {
                    //fieldLabel: 'Телефон торгового представителя',
                    fieldLabel: client_toir.telephone_sales_representative, 
                    name: 'sales_contact_number',
                    xtype:'textfield',
                    value: sales_contact_number
                  }, {
                	  xtype: 'textfield',
                	  //fieldLabel: 'Внешний ID',
                	  fieldLabel: request_toir.external_ID,                	  
                	  name: 'external_id',
                	  value: external_id
                  }
                ],
                buttons: [
                {  // Набор кнопок. Здесь она всего одна.
                    //text: 'Сохранить',
                    text: all_toir.save,
                    handler: function()
                      {
                        var form = Ext.getCmp('ClientFormId').getForm();
                        if(form.isValid())
                        {
                          form.submit(
                          {
                            //waitMsg:'Идет отправка...',
                            waitMsg: all_toir.loading,
                            url: 'app/TOiR_Client.php?func=update',
                            //params : {key : 'val', key2 : 'val2'},
                            success: function(fp, o)
							{
								// Ext.Msg.alert('Внимание','Успешно добавлен'); 
								if(o.result.success == true){
									TOiR_Client_WindowEdit.destroy();
									Ext.getCmp('TOiR_ClientGridId').store.load();
									Ext.getCmp('TOiR_ClientGridId').getView().refresh();
								}else{
									Ext.Msg.alert(all_toir.attention, o.result.message);
								}
							},
							failure: function(fp, o)
							{
								Ext.Msg.alert(all_toir.attention, o.result.message); 
							}
                          });
                        }else
                          {
                            Ext.Msg.alert(all_toir.attention, all_toir.required_fields); 
                          }
                      }
                },
                {
                  //text: 'Отмена',
                  text: all_toir.cancel,
                  handler: function()
                            {
                              TOiR_Client_WindowEdit.close();
                            }
                }
                ] 
              }]
               
            });
    }
    TOiR_Client_WindowEdit.show();
  }
TOiR_Client_Window.show();


}