//request
var LogistMobile_checkpoint = null;
var LogistMobile_checkpoint_WindowAddEdit = null;

Ext.define('LogistMobile_checkpoint_Model', {
    extend: 'Ext.data.Model',
    fields: ['Id', 'StartCheckTime', 'EndCheckTime', 'Description', 'Name', 'FactTripID', 'is_factTrip', 'CarID', 'imei', 'car_name', 'GeoX', 'GeoY', 'Date',
			   'OrderInTrip', 'Distance', 'Time', 'PointState', 'Address']
});
var LogistMobile_checkpoint_Store =  new Ext.data.Store({		        
			    pageSize: 50,
		        model: 'LogistMobile_checkpoint_Model',
		        proxy: 
		        {
		          type: 'ajax',
		          url: 'app/LogistMobile_checkpoint.php?showCheckpoint=true',
		          reader: 
		          {
		            type: 'json',
		            root: 'rows'
		          }
		        }
		}); 

function show_FOTOS_checkpoint_Window(Xcoord,Ycoord,Wwidth,Wheight) {	
	LogistMobile_checkpoint_Store.load();	
	//closeRoute();	
    Xcoord = Xcoord ? Xcoord :40;
    Ycoord = Ycoord ? Ycoord :60;  
    Wwidth = Wwidth ? Wwidth :1100;  
    Wheight = Wheight ? Wheight :400;
        
    var PagingToolbarLogistMobile_checkpoint = 	Ext.create('Ext.PagingToolbar', {
        //height:30,
        border: false,
        frame: false,
        store: LogistMobile_checkpoint_Store,
        displayInfo: true
    });    	     
		
if (!LogistMobile_checkpoint) {
    Ext.getBody().mask('Загрузка...');
    LogistMobile_checkpoint = new Ext.Window({
        layout : 'fit',
        title : 'Заявки',
		//title : TOiR.request,
        closeAction : 'destroy',
        width : parseInt(Wwidth),
        height : parseInt(Wheight),
        //minimizable: true,
		constrainHeader: true,
        maximizable:true,
        //x : parseInt(Xcoord),
        //y : parseInt(Ycoord),
		listeners : {
        	destroy : function(){
        		LogistMobile_checkpoint = null;	
        	}
        },
		items : [					
		new Ext.create('Ext.grid.Panel',{
		    selType: 'rowmodel',
		    columnLines: true,
		    id: 'LogistMobile_checkpointGridId',
		    store: LogistMobile_checkpoint_Store,
		    loadMask: true,
		    border: false,
		    autoScroll: true,
			dockedItems: [{
		            xtype: 'toolbar',
		            items: [
					{
		                text: 'Добавить',
						//text: all_toir.add,
		                iconCls: 'add',
						hidden: true,
		                handler: function(){
							//show_TOiR_users_WindowAddEdit(false);
		                	show_LogistMobile_checkpoint_WindowAddEdit(false);
						}
						},/*'-',{
		                //text: 'Удалить',
						text: all_toir.del,
		                iconCls: 'delete',
		                handler: function(){
									var select = Ext.getCmp('TOiR_RequestGridId').getView().getSelectionModel().getSelection()[0];
		                            if (select) {
		                                Ext.MessageBox.confirm(all_toir.attention, request_toir.are_you_sure_you_want_to_delete_the_record, function(btn) {
		                                    if (btn == 'yes') {
		                                        //alert(select.get('id'));
		                                        Ext.Ajax.request({
		                                            url: 'app/TOiR_request.php',
		                                            method: 'POST',
		                                            params: { 'func':'delete', "id": select.get('id')},
		                                            success: function(response) {
		                                                Ext.MessageBox.alert(all_toir.skill, all_toir.record_deleted_successfully);
		                                                Ext.getCmp('TOiR_RequestGridId').store.load();
														Ext.getCmp('TOiR_RequestGridId').getView().refresh();
		                                            }
		                                        });
		                                    }
		                                });
		                            } else {
		                                Ext.MessageBox.alert(all_toir.error, all_toir.select_row);
		                            }
						}
						},'-',{
		                //text: 'Редактировать',
						text: all_toir.edit,
		                iconCls: 'edit',
		                handler: function(){
		                	//if () {
		                		var select = Ext.getCmp('TOiR_RequestGridId').getView().getSelectionModel().getSelection()[0];
		                        if (select) {
		    						//show_TOiR_users_WindowAddEdit(select.get('id'));
		                        	console.log(select);
		                        	isLocked(select);
		    					} else {
		                            Ext.MessageBox.alert(all_toir.error, all_toir.select_row);
		                        }
		                	//}
							
						}
						},'->', {
		 					xtype: 'textfield',
		 					width: 150,
		 					id: 'request_filter_field_id'
		 				},'-',{
		 					//text: 'Фильтровать',
							text: all_toir.filter,
		 					handler: function () {
		 						var filter = Ext.getCmp('request_filter_field_id').getValue(); 					
		 						TOiR_requestStore.setProxy({
		 							type: 'ajax',
		 					          url: 'app/TOiR_request.php?func=show&filter='+filter,
		 					          reader: 
		 					          {
		 					            type: 'json',
		 					            root: 'rows'
		 					          }
		 						});
		 						TOiR_requestStore.load();
		 						TOiR_requestStore.loadPage(1); 						
		 					}
		 					
		 				},'-', {
		 					//text: 'Очистить',
							text: all_toir.filter_reset,
		 					margin: '0 20 0 0',
		 					handler: function () {
		 						Ext.getCmp('request_filter_field_id').setValue('');
		 						TOiR_requestStore.setProxy({
		 							type: 'ajax',
		 					          url: 'app/TOiR_request.php?func=show',
		 					          reader: 
		 					          {
		 					            type: 'json',
		 					            root: 'rows'
		 					          }
		 						});
		 						TOiR_requestStore.load();
		 						TOiR_requestStore.loadPage(1); 						
		 					}
		 				}
		 				*/]
			}],
		    columns:[{
		    	  text: 'ID', 
		          dataIndex: 'Id',
		          sortable: true,
		          style: 'text-align:center',            
		          align: 'center',
		          width: 50
		      },  {
		        text: 'Начало работ',
		        dataIndex: 'StartCheckTime',
		        sortable: true
		      }, {
		        text: 'Конец работ',
		        dataIndex: 'EndCheckTime',        
		        sortable: true
		      }, {
		        text: 'Описание',
		        dataIndex: 'Description',
		        sortable: true
		      }, {
		        text: 'Название точки',
		        dataIndex: 'Name',
		        sortable: true
		      }, {
		        text: 'Маршрут',		 
		        dataIndex: 'is_factTrip',
		        sortable: true
		      }, {
		        text: 'Название авто',
		        dataIndex: 'car_name',
		        sortable: true
		      }, {
		        text: 'GeoX',
		        dataIndex: 'GeoX',
		        sortable: true
		      }, {
		        text: 'GeoY',
		        dataIndex: 'GeoY',
		        sortable: true
		      }, {
		    	  text: 'Адрес',		 
			      dataIndex: 'Address',
			      sortable: true
		      }, {
		        text: 'Дата создания',
		        dataIndex: 'Date',
		        sortable: true
		      }, {
		        text: 'Порядок в рейсе',
		        dataIndex: 'OrderInTrip',
		        sortable: true
		      }, {
		        text: 'Растояние',
		        dataIndex: 'Distance',
		        sortable: true
		      }, {
		        text: 'Статус',		 
		        dataIndex: 'PointState',
		        sortable: true
		      }],
		    bbar:[PagingToolbarLogistMobile_checkpoint],
		    listeners: {
		    	itemdblclick: function(cmp, records) {
		    		//showInfoAboutRequest(records);
		    		
		    	}
		    }
		})
	]
  });
}  
    LogistMobile_checkpoint.show();
    Ext.getBody().unmask('Загрузка');
}

function show_LogistMobile_checkpoint_WindowAddEdit(id, isLock) {
	//TOiR_UsersRequestStoreMy.load();
	//TOiR_RolesStore.load();
	
	if (!id){        
		var title = "Добавить заявку";		
		var isLock = false;		
    } else {        
		var title = "Редактировать заявку";
		var title = request_toir.edit_the_request;
    }
	var date = new Date();	
	
	if(!LogistMobile_checkpoint_WindowAddEdit){
		LogistMobile_checkpoint_WindowAddEdit = new Ext.Window({
                        width:800,
                        height:500,
                        title: title,
                        closeAction : 'destroy',
						listeners : {
							destroy : function(){
								LogistMobile_checkpoint_WindowAddEdit = null;	
							}
						},
                        layout:'fit',
                        resizable: true,
						constrainHeader: true,
                        modal:true,
                        items:[
						{
						xtype: 'form',
						autoScroll: true,
						bodyPadding: '5 5 5 5',
						id: "LogistMobile_checkpointFormId",
						border: false,
						frame: true,
						autoHeight: true,						
						layout: {
							type: 'table',
							columns: 2
							//align: 'stretch'
						},
						defaults: {
							//fileUpload: true,
							//labelAlign: 'left',
							labelWidth: 120,
							//msgTarget: 'side',
							margin: '5 5 5 5',
							width: 350							
						},
						items:[{
							xtype: 'datefield',						
							//disabled: isLock,
							fieldLabel: 'Начало',
							//fieldLabel: request_toir.date_of_creation,
							format: 'Y-m-d H:i:s',
							altFormats: 'Y-m-d H:i:s',
							startDay: 1,
							name : 'StartCheckTime',
							id: 'StartCheckTime_id',
							allowBlank: false,
							//value: new Date(),
							listeners: {/* 
								change: function(newValue, oldValue, eOpts){ 
									Ext.getCmp('date_execute_id').setMinValue( this.getValue() )
									Ext.getCmp('date_execute_id').setValue( this.getValue() )
								}
							*/}	
						},	{
							xtype: 'datefield',						
							//disabled: isLock,
							fieldLabel: 'Окончание',
							//fieldLabel: request_toir.date_of_creation,
							format: 'Y-m-d H:i:s',
							altFormats: 'Y-m-d H:i:s',
							startDay: 1,
							name : 'EndCheckTime',
							id: 'EndCheckTime_id',
							allowBlank: false,
							//value: new Date(),
							listeners: {}	
						}, 	{
							xtype: 'textfield',
							fieldLabel: 'Описание',
							//fieldLabel: client_toir.sity,
							//disabled: isTTLock,
							allowBlank: true,
							name : 'Description',
							id: 'Description_id'
						}, {
							xtype: 'textfield',
							fieldLabel: 'Название точки',
							//fieldLabel: client_toir.address,
							//disabled: isTTLock,
							name : 'Name',							
							allowBlank: true,
							id: 'Name_id'
						}, {
							xtype: 'textfield',
							fieldLabel: 'Адрес',
							//fieldLabel: client_toir.contact_phone,
							//disabled: isTTLock,
							name : 'Address',
							allowBlank: false,							
							id: 'Address_id'
						}, {
							xtype: 'textfield',
							fieldLabel: 'GeoX',
							//fieldLabel: client_toir.contact_person,
							//disabled: isTTLock,
							name : 'GeoX',
							allowBlank: false,
							id: 'GeoX_id'
						},
						{
							xtype: 'textfield',
							fieldLabel: 'GeoY',
							//disabled: isTTLock,
							allowBlank: false,
							name : 'GeoY',
							id: 'GeoY_id'
						},	/*{
							xtype: 'textfield',
							fieldLabel: 'Примечания',
							disabled: isTTLock,
							allowBlank: true,
							hidden: true,
							name : 'description',
							id: 'request_id_description',
						},
						{
							xtype: 'textfield',
							//fieldLabel: 'Тип ТТ',
							fieldLabel: request_toir.type_TT,
							disabled: isTTLock,
							allowBlank: false,
							name : 'outlet_type',
							id: 'request_id_outlet_type'
						},
						{
							xtype: 'textfield',
							//fieldLabel: 'Телефон торгового представителя',
							fieldLabel: client_toir.telephone_sales_representative,
							disabled: isTTLock,
							name : 'sales_man',
							allowBlank: false,
							id: 'request_id_sales_man'
						},
						{
							xtype: 'combo',
							//fieldLabel: 'Мастер',
							fieldLabel: request_toir.name_master,
							name : 'worker',
							disabled: isLock,
							store: TOiR_UsersRequestStoreMy,
							valueField: 'id',
							displayField: 'name',
							queryMode: 'local',
							value: 0
						},
						{
							xtype: 'checkbox',
							//fieldLabel: 'Мастерская',
							fieldLabel: request_toir.workshop,
							disabled: isLock,
							name : 'workshop',
							inputValue: 1
						},
						{
							xtype: 'checkbox',
							disabled: isLock,
							//fieldLabel: 'Заявка выполнена',
							fieldLabel: request_toir.request_executed,
							name : 'status',
							inputValue: 1
						},						
						{
							xtype: 'combo',
							//fieldLabel: 'Оборудование',
							fieldLabel: TOiR.Equipment,
							disabled: isLock,
							allowBlank: false,
							id: 'equipment_combo_id',
							name : 'equipment',
							store: TOiR_EquipmentStoreRequest,
							valueField: 'id',
							disabled: true,
							displayField: 'name',
							queryMode: 'local',
							listeners: {
								select: function(combo, record) {
									var clientID = record[0].get('id');
									TOiR_OutletStore.load({
										params: {
											clientID: clientID
										}
									});
								}
							}
						},						
						{
							xtype: 'datefield',
							disabled: isLock,
							//fieldLabel: 'Дата создания',
							fieldLabel: request_toir.date_of_creation,
							format: 'Y-m-d H:i:s',
							altFormats: 'Y-m-d H:i:s',
							startDay: 1,
							name : 'date_create',
							id: 'date_create_id',
							value: new Date(),
							listeners: { 
								change: function(newValue, oldValue, eOpts){ 
									Ext.getCmp('date_execute_id').setMinValue( this.getValue() )
									Ext.getCmp('date_execute_id').setValue( this.getValue() )
								}
							}							
						},
						{
							xtype: 'datefield',
							disabled: isLock,
							//fieldLabel: 'Дата визита',
							fieldLabel: request_toir.date_of_visit,
							allowBlank: false,
							//format: 'Y-m-d H:i:s',
							//altFormats: 'Y-m-d H:i:s',
							format: 'Y-m-d',
							altFormats: 'Y-m-d',
							startDay: 1,
							name : 'date_execut',
							id: 'date_execute_id',
							//value: new Date(date.setDate(date.getDate() + 1)),
							value: new Date(), 
							minValue: new Date(),						
						}, {
							xtype: 'textfield',
							name: 'work_duration',
							disabled: isLock,
							allowBlank: false,
							//fieldLabel: 'Время выполнения, мин',
							fieldLabel: request_toir.run_time_min,
						}, {
							xtype: 'textfield',
							name: 'external_id',
							//fieldLabel: 'Внешний ID'
							fieldLabel: request_toir.external_ID
						}*/], buttons:[
							{ 
							text:'Cохранить',
							//text: all_toir.save,
							//disabled: isLock,
							//id:'buttonUploads',
							iconCls:'save',
							handler: function() {
								console.log(id);
								var form = this.up('form').getForm();
								//var time = Ext.getCmp('date_execute_id').getRawValue();
								if(form.isValid()){
								form.submit({
									waitMsg:'Идет отправка...',
									//waitMsg: all_toir.loading,
                                    url: 'app/LogistMobile_checkpoint.php',
									//waitMsg: 'Збереження...',
									wait: true,
									scope: this,
									method: 'post',
									//timeout : 60000,
									params: {'addEditCheckpoint': true, id: id},
                                    success: function(fp, o){
                                    	//LogistMobile_checkpoint_WindowAddEdit.destroy();
                                    	
//                                    	Ext.getCmp('TOiR_RequestGridId').store.load();
//										Ext.getCmp('TOiR_RequestGridId').getView().refresh();
//										if (Ext.getCmp('TOiR_TripPlanningGridId')) {
//											Ext.getCmp('TOiR_TripPlanningGridId').store.load({
//									  			params: {
//									  				time: time
//									  			}
//									  		});
//											Ext.getCmp('TOiR_TripPlanningGridId').getView().refresh();
//											clearMap();
//										}
										
                                    	
                                    }
							});
							  }
						 }
							}, 	{
                            text: 'Отмена',
							//text: all_toir.cancel,
							iconCls:'cancel',
                            handler: function(){
                            	LogistMobile_checkpoint_WindowAddEdit.destroy();
                             }
							}
						]
						}
						]
		});
	}
	LogistMobile_checkpoint_WindowAddEdit.show();
	
	/*var form = Ext.getCmp("TOiR_RequestFormId").getForm().getFields();
    if (id) {
    	Ext.getCmp('equipment_combo_id').enable(true);
    	Ext.getCmp('outlet_combo_id').enable(true);
        Ext.Ajax.request({
            url: 'app/TOiR_request.php',
            method: 'POST',
            params: {"func":"editshow","id":id},
            success: function(response) {
                var JSON = response.responseText;
                if (JSON) {
                    var decoded = Ext.decode(JSON);
					var i = 0;					
					var arrOfItems = [];
					for (k in decoded) {
						arrOfItems.push(decoded[k]);
					}
					console.log(arrOfItems);
					form.each(function(item) {						
						if (i == 1) {
							TOiR_OutletStoreRequest.load({
								params: {
									clientID: arrOfItems[i]
								}
							});
						}	
						if (i == 2) {
						TOiR_EquipmentStoreRequest.load({
								params: {
									outletID: arrOfItems[i]
								}
							});
						}
						
						
					if (item.xtype == 'combo') {
                        //item.setRawValue(decoded[i]);
						item.setValue(parseInt(arrOfItems[i]));
                    } else {
						if (i == 18) {
							var arr = arrOfItems[i].split(' ');
							console.log(arr[0]);
							item.setValue(arr[0]);
						} else {
							item.setValue(arrOfItems[i]);
						}
					}
					i++;
                    });
                }
            },
            failure: function(response) {
                Ext.MessageBox.alert(all_toir.error, response.responseText);
            }
        });
    }*/
} 