var msg = function(title, msg) {
  Ext.Msg.show({
    title: title,
    msg: msg,
    minWidth: 200,
    modal: true,
    icon: Ext.Msg.INFO,
    buttons: Ext.Msg.OK
  });
};

var deleteClient = function(title, msguam, id_row) {                  // function delete client
  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_Client.php",{func:'delete',id:id_row},function(data)
          {
            GridClient.store.load();
            GridClient.getView().refresh();
            var deleteButton = Ext.getCmp('delete');
            deleteButton.setDisabled(true);
        });                                              
      }
    }
  });
};

Ext.define('ModelClient', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name', 'phone', 'city', 'address']
});

/*var StoreClient = new Ext.data.Store({
  model: 'ModelClient',
  proxy: {
    type: 'ajax',
    url: 'app/SFALite_Client.php?func=show',
    reader: {
      type: 'json',
      root: 'rows'
    }
  }
});*/

Ext.define('ModelCity', {
    extend: 'Ext.data.Model',
    fields: [ 'id','name']
});
var StoreCity = new Ext.data.Store({
        model: 'ModelCity',
           proxy: {
              type: 'ajax',
              url: 'app/SFALite_Client.php?func=showCity',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });

Ext.define('ModelRegion', {
    extend: 'Ext.data.Model',
    fields: [ 'id','name']
});
var StoreRegion = new Ext.data.Store({
        model: 'ModelCity',
           proxy: {
              type: 'ajax',
              url: 'app/SFALite_Client.php?func=showRegion',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });

Ext.define('ModelNetwork', {
    extend: 'Ext.data.Model',
    fields: [ 'id','name']
});
var StoreNetwork = new Ext.data.Store({
        model: 'ModelCity',
           proxy: {
              type: 'ajax',
              url: 'app/SFALite_Client.php?func=showNetwork',
              reader: {
                  type: 'json',
                  root: 'rows'
              }
          }
   });   
   
   
   
// ----------------------------------Window ------------------------------------
var WindowClient;

function show_SFALite_Client_Window()
{
  if (!WindowClient || WindowClient.Window==null)
  {
      
   Ext.define('ModelClient', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name', 'region', 'network', 'city', 'address']
});

var StoreClient = 
Ext.create('Ext.data.Store', {
        //id: 'store',
        model: 'ModelClient',
       // remoteGroup: true,
        
       // buffered: true,
       // leadingBufferZone: 300,
        pageSize: 100,
        proxy: {
            // load using script tags for cross domain, if the data in on the same domain as
            // this page, an Ajax proxy would be better
            type: 'ajax',
            url: 'app/SFALite_Client.php?func=show',
            reader: {
                root: 'json',
                root: 'rows',
                totalProperty: 'totalCount'
            }//,

            //simpleSortMode: true,

           // simpleGroupMode: true,


           // groupParam: 'sort',
           // groupDirectionParam: 'dir'
        }/*,
        sorters: [{
            property: 'threadid',
            direction: 'ASC'
        }],
       // autoLoad: true,
        listeners: {

            // This particular service cannot sort on more than one field, so if grouped, disable sorting
            groupchange: function(store, groupers) {
                var sortable = !store.isGrouped(),
                    headers = grid.headerCt.getVisibleGridColumns(),
                    i, len = headers.length;
                
                for (i = 0; i < len; i++) {
                    headers[i].sortable = (headers[i].sortable !== undefined) ? headers[i].sortable : sortable;
                }
            },

            // This particular service cannot sort on more than one field, so if grouped, disable sorting
            beforeprefetch: function(store, operation) {
                if (operation.groupers && operation.groupers.length) {
                    delete operation.sorters;
                }
            }
        }*/
    });
      
    StoreClient.load();
    
var ClientPagingToolbar = new Ext.PagingToolbar({      // <---- создаем Paging
      displayInfo    : true,
      store          : StoreClient
});
    
    GridClient = new Ext.grid.GridPanel({
    selType: 'rowmodel',
    columnLines: true,
    id: 'GridClientId',
    store: StoreClient,
	bbar: ClientPagingToolbar,
    columns:[
      {
        text : 'id', 
        dataIndex : 'id',
        width:40,
        sortable: true,
        hidden: true
      },
      {
        xtype: 'rownumberer',
        text: '№',
        width: 40,
        hideable: false,
        sortable: true
      },
      {
        text : 'Название', 
        dataIndex : 'name',
        width: 140,
        sortable: true,
      },
      {
        text : 'Регион', 
        dataIndex : 'region',
        width: 140,
        sortable: true,
      },
      {
        text : 'Сеть', 
        dataIndex : 'network',
        width: 140,
        sortable: true,
      },
      {
        text : 'Город', 
        dataIndex : 'city',
        width: 140,
        sortable: true,
      },
      {
        text : 'Адрес', 
        dataIndex : 'address',
        width:200,
        sortable: true,
        id: 'firstName_uam'
      }
    ],
    listeners:
    {
      itemclick: function(View,record,item,index,e,eOpts )
      {
        id_row = record.get('id');
        id_row =parseInt(id_row);
        var deleteButton = Ext.getCmp('delete');
        deleteButton.setDisabled(false);
      },
      itemdblclick: function(View,record,item,index,e,eOpts )
      {
        id_row = record.get('id');
        id_row=parseInt(id_row);
        showFormClient(id_row);
        id_row=0;
      }
    }
  });
    
    
   // createGridClient();
    WindowClient = new Windows('Клиенты',675,380);       // create window
    WindowClient.CreateWindowMaximizableDestroy(WindowClient,GridClient);


    // ------------------------------ create button ------------------------------------------  
    var addClient = Ext.create('Ext.button.Button', { 
      text: 'Добавить',
      iconCls: 'adduser',
      handler: function(){showFormClient();}
    });
    var correctClient = Ext.create('Ext.button.Button', { 
      text: 'Редактировать',
      iconCls: 'createtask',
      handler: function()
      {
        if (!id_row){msg('Выбрано 0 записей.', 'Выберите запись!');}
        else
        {
          showFormClient(id_row);
          id_row=0;
        }
      }
    });
    var deleteClientButton = Ext.create('Ext.button.Button', { 
      text: 'Удалить',    
      iconCls: 'deluser',
      disabled: true,
      itemId: 'delete',
      id: 'delete',
      handler: function()
      {
        if (!id_row){msg('Выбрано 0 записей', 'Выберите запись!');}
        else{
          deleteClient('Удаление', 'Вы точно хотите удалить данного клиента !?',id_row);
        }
      }
    });
    
    var ButtonImportClient = Ext.create('Ext.button.Button', 
    { 
      text: 'Импортировать',    
      iconCls: 'deluser',
      itemId: 'import',
      id: 'import',
      handler: function()
      {
        $.post('scripts/UploadCustomers.php', {}, function(data)
        {
            StoreClient.load();    
        })
      }
    });
    
    WindowClient.Window.addDocked(
      {
        xtype: 'toolbar',
        dock: 'top',
        //items:[addClient,correctClient,deleteClientButton,ButtonImportClient]
		items:[addClient,correctClient,deleteClientButton]
		});
  }
  
  //---------------------------------------------------------------------------------------- 

  WindowClient.Window.show();
}



/*new Ext.data.Store(
           {
            model: 'ModelClient',
            buffered: true,
            remoteGroup: true,
            leadingBufferZone: 300,
            pageSize: 100,
            proxy: 
            {
              type: 'ajax',
              url: 'app/SFALite_Client.php?func=show',
              reader: 
              {
                  type: 'json',
                  root: 'rows',
                  totalProperty: 'totalCount'
              },
              simpleSortMode: true,
              simpleGroupMode: true,
              groupParam: 'sort',
              groupDirectionParam: 'dir'
            },
            sorters: 
            [{
                property: 'threadid',
                direction: 'ASC'
            }],
            autoLoad: true,
            listeners: {

            // This particular service cannot sort on more than one field, so if grouped, disable sorting
            groupchange: function(store, groupers) {
                var sortable = !store.isGrouped(),
                    headers = grid.headerCt.getVisibleGridColumns(),
                    i, len = headers.length;
                
                for (i = 0; i < len; i++) {
                    headers[i].sortable = (headers[i].sortable !== undefined) ? headers[i].sortable : sortable;
                }
            },

            // This particular service cannot sort on more than one field, so if grouped, disable sorting
            beforeprefetch: function(store, operation) {
                if (operation.groupers && operation.groupers.length) {
                    delete operation.sorters;
                }
            }
        }
});*/
          
//StoreClient.load();
// ------------------------------------- create Grid --------------------------------------    
function createGridClient()
{
  
}

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

function showFormClient(id_row)
{
  var idSelectingRow= id_row;

  $.post('app/SFALite_Client.php', {func:'edit',id:idSelectingRow}, function(data){
    var arrayDataClient  = data.split('/t');

    id = parseInt(arrayDataClient[0]);
    var name = arrayDataClient[1];
    //var phone = arrayDataClient[2];
    var id_city = arrayDataClient[2];
    var address = arrayDataClient[3];
	var number = arrayDataClient[4];
	var id_region = arrayDataClient[5];
	var id_network = arrayDataClient[6];
	
	
	
    var FormConstructor = new Forms();
    var fieldName = FormConstructor.CreateTextFieldWidthPercent('Название','top','95%',name);
    //var fieldPhone = FormConstructor.CreateTextFieldWidthPercent('Телефон','top','95%',phone);
    StoreCity.load();
    var fieldId_city = FormConstructor.CreateComboboxFieldProxyWidthPercent('Город','top',StoreCity,'name','id','95%',id_city);
    var fieldAddress = FormConstructor.CreateTextFieldWidthPercent('Адрес','top','95%',address);
	var fieldNumber = FormConstructor.CreateTextFieldWidthPercent('Код клиента','top','95%',number);
    var fieldId_region = FormConstructor.CreateComboboxFieldProxyWidthPercent('Регион','top',StoreRegion,'name','id','95%',id_region);
	var fieldId_network = FormConstructor.CreateComboboxFieldProxyWidthPercent('Сеть','top',StoreNetwork,'name','id','95%',id_network);
    var formClient = 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: [fieldNumber, fieldId_region, fieldId_city/*, fieldPhone*/]
          },
          {
            xtype: 'container',
            columnWidth:.5,
            layout: 'anchor',
            items: [fieldName, fieldId_network, fieldAddress]
          }]
        }]
    });
    var windowFormClient = new Windows('Данные клиента',600,250);
    windowFormClient.CreateWindowModal(windowFormClient,formClient);

    var saveDataClient = Ext.create('Ext.button.Button', { 
      text: 'Сохранить',    
      iconCls: 'save',
      handler: function()
      {
        var name = fieldName.getValue();
        //var phone = fieldPhone.getValue();
        var id_city = fieldId_city.getValue();
        var address = fieldAddress.getValue();
        var number = fieldNumber.getValue();
        var region = fieldId_region.getValue();
		var network = fieldId_network.getValue();

        if (id_city=='' || name=='' || address=='' || number=='' || region=='' || network=='')
        {
          msg('Ошибка!', 'Проверьте данные!');
          if (id_city==''){fieldId_city.markInvalid('Проверьте данные!');}
          if (name==''){fieldName.markInvalid('Проверьте данные!');}
          if (address==''){fieldAddress.markInvalid('Проверьте данные!');}
		  if (number==''){fieldNumber.markInvalid('Проверьте данные!');}
		  if (region==''){fieldId_region.markInvalid('Проверьте данные!');}
		  if (network==''){fieldId_network.markInvalid('Проверьте данные!');}
        }
        else 
        {
          $.post("app/SFALite_Client.php",{func:'update',id:id, name:name, /*phone:phone,*/ id_city:id_city, address:address, number:number, region:region, network:network}, function(data){
            //alert(data);
            windowFormClient.Window.destroy();
            GridClient.store.load();
            GridClient.getView().refresh();
            var deleteButton = Ext.getCmp('delete');
            deleteButton.setDisabled(true);
          });
        }
      }
    });
    var cancelInputDataClient = Ext.create('Ext.button.Button', { 
      text: 'Отмена',    
      handler: function(){
        windowFormClient.Window.destroy();
        GridClient.store.load();
        GridClient.getView().refresh();
        var deleteButton = Ext.getCmp('delete');
        deleteButton.setDisabled(true);
      }
    });
    windowFormClient.Window.addDocked(
      {
        xtype: 'toolbar',
        dock: 'bottom',
        items:['->',saveDataClient,'-',cancelInputDataClient]
      });

    windowFormClient.Window.show();
  });
}
