var TOiR_article_Window = null;
var TOiR_article_WindowAddEdit = null;

var modelEquipmentStore;
var typeWorkStore;
var articleStore;

Ext.define('ArticleModel', {
    extend: 'Ext.data.Model',
    fields: ['id','type_work', 'model', 'article']
});

articleStore = new Ext.data.Store({
    autoLoad: true,
    pageSize: 25,
    model: 'ArticleModel',
    proxy: {
        type: 'ajax',
        url: 'app/TOiR_article.php?func=show',
        reader: {
            type: 'json',
            root: 'rows'
        }
    }
});

function show_TOiR_article_Window(Xcoord,Ycoord,Wwidth,Wheight) {

	Xcoord = Xcoord ? Xcoord :40;
    Ycoord = Ycoord ? Ycoord :60;  
    Wwidth = Wwidth ? Wwidth :600;  
    Wheight = Wheight ? Wheight :400;

Ext.define('typeWorkModel', {
        extend: 'Ext.data.Model',
        fields: ['id_type_work', 'name_job', 'name_job2']
    });

    typeWorkStore = new Ext.data.Store({
        autoLoad: true,
        model: 'typeWorkModel',
        proxy: {
            type: 'ajax',
            url: 'app/TOiR_article.php?func=typeWorkStore',
            reader: {
                type: 'json',
                root: 'rows'
            }
        }
    });

    Ext.define('modelEquipment', {
    	extend: 'Ext.data.Model',
    	fields: ['id','model', 'model2']
    });

    modelEquipmentStore = new Ext.data.Store({
    	autoLoad: true,
    	model: 'modelEquipment',
    	proxy: {
    		type: 'ajax',
    		url: 'app/TOiR_article.php?func=modelEquipmentStore',
    		reader: {
    			type: 'json',
    			root: 'rows'
    		}
    	}
    });

   

    var articleGridPaging = new Ext.PagingToolbar({
        displayInfo    : true,
        store          : articleStore
    });

    articleGrid = Ext.create('Ext.grid.Panel', {
    	 selType: 'rowmodel',
    columnLines: true,
    id: 'articleGrid',
    store: articleStore,
    loadMask: true,
    border: false,
    autoScroll: true,
        bbar: [articleGridPaging],
	    dockedItems: [{
	    	xtype: 'toolbar',
	    	items: [
	    		{
	    			//text: 'Добавить',
	    			text: all_toir.add,
	    			iconCls: 'add',
	    			handler: function () {
                        // alert(1);
	    				show_TOiR_article_WindowAddEdit();
	    			}
	    		},
	    		'-',
	    		{
	    			//text: 'Удалить',
	    			text: all_toir.del,
	    			iconCls: 'delete',
	    			handler: function() {
	    				TOiR_article_WindowRemove();
	    			}
	    		},'-',{
                  //text: 'Редактировать',
                  text: all_toir.edit,
                  iconCls: 'edit',
                  handler: function (){
                    var select = Ext.getCmp('articleGrid').getView().getSelectionModel().getSelection()[0];
                    // alert(select.get('id_client'));
                     if (select) {
                        var id = select.get('id');
                        var article = select.get('article');
                        var model = select.get('model');
                        var type_work = select.get('type_work');
                        // alert(type_work);
                        show_TOiR_article_WindowAddEdit(id,article,model,type_work);
                      } else {
                        Ext.MessageBox.alert(all_toir.error, all_toir.select_row);
                      }
                    }
                }],
    }
	    	
	    ],
        columns: [
        {
            //text: 'ID Необходимых запчастей',
            text: article_toir.ID_necessary_spare_parts,
            dataIndex: 'id',
            id:'id',
            hidden: true
        },
        {
            //text: 'Вид работы',
            text: article_toir.type_of_work,
            dataIndex: 'type_work',
            id:'type_work',
            sortable: true,
            flex:1
        },
        {
            //text: 'Модель работы',
            text: article_toir.the_model_works,
            dataIndex: 'model',
            id:'model',
            sortable: true,
            flex:1
        },
        {
            //text: 'Необходимые запчасти',
            text: article_toir.required_parts,
            dataIndex: 'article',
            id:'article',
            sortable: true,
            flex:1
        }],
	    listeners: {
	    	itemdblclick: function(View,record,item,index,e,eOpts) {
	    		var id = record.get('id');
	    		var article = record.get('article');
                var model = record.get('model');
                var type_work = record.get('type_work');
                // alert(type_work);
	    		show_TOiR_article_WindowAddEdit(id,article,model,type_work);
	    	}
	    }
	    
    });

    

	if (!TOiR_article_Window) {
		TOiR_article_Window = new Ext.Window({
			autoScroll:true,
            layout : 'fit',
        	closeAction : 'destroy',
        	width : parseInt(Wwidth),
            height : parseInt(Wheight),
             maximizable:true,
        	//title : 'Необходимые запчасти',
        	title : article_toir.required_parts,
        	listeners : {
            	destroy : function(){
            		TOiR_article_Window = null;    
            	}
        	},
			items: [articleGrid]
		});
	}
	TOiR_article_Window.show();

	function show_TOiR_article_WindowAdd() {

    }
	function TOiR_article_WindowRemove() {
        if (articleGrid) {
          var sm = articleGrid.getSelectionModel();
          var rs = sm.getSelection();
          if(!rs) return false;
          var id_article = rs[0].get('id');
          // alert(id_article);
          if (!rs.length) {
              Ext.Msg.alert(all_toir.attention, mess_toir.article_is_not_selected);
              return;
              }
            Ext.Msg.confirm(all_toir.attention, mess_toir.are_you_sure_you_want_to_delete_the_selected_article, function (button) {
           if (button == 'yes') {
                      Ext.Ajax.request({  
                          url : 'app/TOiR_article.php?func=del',
                          method: 'GET',
                          params: {id_article: id_article}, 
                          success: function(objServerResponse){  
                               ///TOiR_article_WindowAddEdit.destroy();
                                    Ext.getCmp('articleGrid').store.load();
                                    //Ext.getCmp('articleGrid').getView().refresh();
                               }
                          });
                       //articleGrid.store.remove(rs[0]);
                                }
          });
        }   
    }
	function show_TOiR_article_WindowAddEdit(id,article,model,type_work) {
        if (typeof id !== 'undefined') {
            //title = 'Редактировать';
            title = all_toir.edit;
            //titleBtn = 'Сохранить';
            titleBtn = all_toir.save;
        } else {
            //title = 'Добавить';
            title = all_toir.add;
            titleBtn = all_toir.add;
            id = '';
            article = ''; 
            model = '';
            type_work = '';

        }

        if (!TOiR_article_WindowAddEdit) {
            TOiR_article_WindowAddEdit = new Ext.Window({
                width: 400,
                height: 300,
                title: title,
                closeAction: 'destroy',
                layout: 'fit',
                resizable: true,
                modal:true,
                listeners : {
                    destroy : function(){
                    TOiR_article_WindowAddEdit = null;    
                    }
                },
                items: [{
                    xtype: 'form',
                    autoScroll: true,
                    bodyPadding: '5 5 5 5',
                    id: "TOiR_articleFormId",
                    border: false,
                    frame: true,
                    autoHeight: true,
                    //fieldwidth:'width:150px',
                    //layout: 'anchor',
                    layout: {
                        type: 'vbox',
                        align: 'stretch'
                    },
                    defaults: {
                        //fileUpload: true,
                        labelAlign: 'left',
                        labelWidth: 90,
                        //fieldWidth: '90%',
                        msgTarget: 'side'
                    },
                    items: [
                    {
                        xtype:'hidden',
                        fieldLabel: 'ID',
                        name : 'id_article',
                        allowBlank: false,
                        value: id
                    },
                    {
                        xtype:'textfield',
                        //fieldLabel: 'Артикул',
                        fieldLabel: article_toir.article,
                        name : 'article',
                        allowBlank: false,
                        value: article
                    },
                    {
                        xtype:'combo',
                        //fieldLabel: 'Вид работы',
                        fieldLabel: article_toir.type_of_work,
                        name : 'type_work',
                        allowBlank: false,
                        store: typeWorkStore,
                        displayField: 'name_job',
                        valueField: 'name_job2',
                        value: type_work
                    },
                    {
                        xtype:'combo',
                        //fieldLabel: 'Модель',
                        fieldLabel: article_toir.model,
                        name : 'model',
                        allowBlank: false,
                        store: modelEquipmentStore,
                        displayField: 'model',
                        valueField: 'model2',
                        value: model
                    }
                
                ],
                buttons: [
                    {  // Набор кнопок. Здесь она всего одна.
                      text: titleBtn,
                      handler: function()
                        {
                            if (titleBtn == all_toir.add) {
                                var f = 'add';
                            } else 
                            {
                                var f = 'edit';
                            }
                          var form = this.up('form').getForm();
                              if(form.isValid())
                              {
                                form.submit(
                                {

                                  //waitMsg:'Идет отправка...',
                                  waitMsg: all_toir.loading,
                                  url: 'app/TOiR_article.php?func=add',
                                  params : {flag : f},
                                  success: function(form,response) 
                                  {
                                    // Ext.Msg.alert('Внимание','Успешно добавлен'); 
                                    TOiR_article_WindowAddEdit.destroy();
                                    Ext.getCmp('articleGrid').store.load();
                                    Ext.getCmp('articleGrid').getView().refresh();
                                  },
                                  failure : function()
                                  {
                                    Ext.Msg.alert(all_toir.attention, all_toir.error); 
                                  }
                                });
                              }else
                                {
                                  Ext.Msg.alert(all_toir.attention, all_toir.required_fields); 
                                }
                        }
                    },
                    {
                        //text: 'Отмена',
                        text: all_toir.cancel,
                        handler: function()
                                  {
                                   TOiR_article_WindowAddEdit.destroy();
                                  }
                      }
                    ] 
                }]
                 
            });
            TOiR_article_WindowAddEdit.show();
        }
    }
}