var mainPlanSettingsWindow;
var mainPlanSettingsWindowAddEdit;

function show_LogistMobile_plan_settings_Window()
{

	var settings_plan_grid_store = new  Ext.data.Store({   
	        fields: ['id','Rule_Name','Rule_Comments','user_id','filial_code','cars_ids','zones_ids','day_of_week','time','dif_time_before','dif_time_after','express','spec',{name: 'check', type: 'bool'}, 'day_start'],
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_plan_settings.php?load_settings=1',
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        }
	});
	
		
	
	if (!mainPlanSettingsWindow) 
	{
		
		
		var grid_plan_settings = new Ext.grid.GridPanel({
    selType: 'rowmodel',
	//title: 'Автопарк',
	//height: 150,
	layout: 'fit',
    store: settings_plan_grid_store,
	id: 'grid_plan_settings_id',
	viewConfig: {
		//preserveScrollOnRefresh: true,
		markDirty: false
    },
	//bbar: [PagingToolbar],
    columns: [
	{
		xtype: 'checkcolumn',
		//text : 'Правило',
		text: plan_settings.lrule,
		dataIndex: 'check',
		sortable: false,
		width: 70,
		listeners: {
			checkchange:function(CheckColumn, rowIndex, checked, eOpts ) {
				
				var record = grid_plan_settings.store.getAt(rowIndex);
				var idrow = record.get('id');
				
				if (checked==true)
                {
					check = 1;
				}else{
					check = 0;
				}
				
				Ext.Ajax.request({
		            url: 'app/LogistMobile_plan_settings.php',
		            method: 'POST',
		            params: {"check_rule":1,"id":idrow,"check":check},
		            success: function(response) {
		                var JSON = response.responseText;
		                if (JSON) {
		                    var decoded = Ext.decode(JSON);
							if(decoded.success==true){
								if (checked==true)
								{
									Ext.MessageBox.alert(all.skill, plan_settings.rule_on);
								}else{
									Ext.MessageBox.alert(all.skill, plan_settings.rule_off);
								}
								
							}else{
								Ext.MessageBox.alert(all.error, decoded.message);
								record.set('check',false);
							}
		                }
		            },
		            failure: function(response) {
		                Ext.MessageBox.alert(all.error, response.responseText);
						record.set('check',false);
		            }
		        });
				
			}, 
			headerclick: function(ct, column, e, t, eOpts) {
				
			}
		}
    },
	{
            text : plan_settings.name_rule,
            dataIndex : 'Rule_Name',
			flex: 1,
            sortable: true,
            hideable: false
    },
	/*{
            text : 'Филиал',
            dataIndex : 'filial_code',
			width: 120,
            sortable: true,
            hideable: false
    },
	{
            text : 'Запуск правила',
            dataIndex : 'day_start',
            sortable: true,
            hideable: false
    },*/
	{
            text : plan_settings.start_trip,
            dataIndex : 'time',
            sortable: true,
            hideable: false
    },
	/*{
            text : 'Начало периода',
            dataIndex : 'dif_time_before',
            sortable: true,
            hideable: false
    },
	{
            text : 'Конец периода',
            dataIndex : 'dif_time_after',
            sortable: true,
            hideable: false
    },*/
	{
            text : plan_settings.comments,
            dataIndex : 'Rule_Comments',
            sortable: true,
            hideable: false
    }
	],
	tbar:[
			{
                    text: all_LogistMobile.add,
					iconCls: 'add',
					handler: function(){
						show_LogistMobile_plan_settings_Window_AddEdit();
					}
			},
			{
                    text: all_LogistMobile.edit,
					iconCls: 'edit',
					handler: function(){
						var select = Ext.getCmp('grid_plan_settings_id').getView().getSelectionModel().getSelection()[0];
						if(select)
						{
							show_LogistMobile_plan_settings_Window_AddEdit(select);
						}else{
							Ext.MessageBox.alert(all.error, all_LogistMobile.select_row);	
						}
					}
			},{
                    text: all_LogistMobile.del,
					iconCls: 'delete',
					handler: function(){
						var select = Ext.getCmp('grid_plan_settings_id').getView().getSelectionModel().getSelection()[0];
						if(select)
						{
					
					Ext.MessageBox.confirm(all.attention, all_LogistMobile.are_you_sure_you_want_to_delete_the_record, function(btn){
					if(btn=='yes'){
					
				Ext.Ajax.request({
		            url: 'app/LogistMobile_plan_settings.php',
		            method: 'POST',
		            params: {"delete":1,"id":select.get('id')},
		            success: function(response) {
		                var JSON = response.responseText;
		                if (JSON) {
		                    var decoded = Ext.decode(JSON);
							if(decoded.success==true){
								Ext.MessageBox.alert(all.skill, all_LogistMobile.skill);
								Ext.getCmp('grid_plan_settings_id').store.load();
								Ext.getCmp('grid_plan_settings_id').getView().refresh();
							}else{
								Ext.MessageBox.alert(all.error, decoded.message);
							}
		                }
		            },
		            failure: function(response) {
		                Ext.MessageBox.alert(all.error, response.responseText);
		            }
		        });
						
					}
					});
						
						
						}else{
							Ext.MessageBox.alert(all.error, all_LogistMobile.select_row);	
						}
					}
			}
		],
		listeners: {
		itemdblclick: function(cmp, record, item, index, e, eOpts ) {
	   
			show_LogistMobile_plan_settings_Window_AddEdit(record);
			
		}
	},
	});
	
	
	
	
	
	
	settings_plan_grid_store.load({
						params: {
							//filial: obj.value_rule1
						}		
						});
		
		
		mainPlanSettingsWindow = new Ext.Window(
        {
            layout : 'fit', 
        	title : LogistMobile.plan_settings,
        	//title : rights.permissions,
            closeAction : 'destroy',
            width : 700,
            height : 520,
            resizable : true,
            autoScroll: true,
            items : [
			
			grid_plan_settings
		
			],
            listeners : 
            {
                destroy : function()
                {
                	mainPlanSettingsWindow = null;
                }
            }
            
        });
		mainPlanSettingsWindow.show(this, function(){
			//load_plandata(global_filial_code);
		});
		
	
	}
	
	
	
	
}







function show_LogistMobile_plan_settings_Window_AddEdit(row)
{
	//console.log(global_filial_code);
	//alert(global_filial_code);
	var idx = null;
	if(row){
		title = all_LogistMobile.edit;
		//filial_code = row.get('filial_code');
		edit = 1;
		idx = row.get('id');
	}else{
		title = all_LogistMobile.add;
		//filial_code = global_filial_code;
		edit = 0;
		idx = null;
	}
	
	
	// --- combobox store filial --->
	var Filial_store = new  Ext.data.Store({   
			//autoLoad: true,	
	        fields: ['ID','Name'],
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_plan_settings.php?func=tms_filial',
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        }
	});
	
	// <--- combobox store filial ---
	
	
	// --- grid store cars --->
	var store_plan_settings_cars = new  Ext.data.Store({   
			//autoLoad: true,	
	        fields: ['id','name','imei',{name: 'check', type: 'bool'}],
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_plan_settings.php?func=cars',
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        }
	});
	
	
	var grid_plan_settings_cars = new Ext.grid.GridPanel({
    selType: 'rowmodel',
	//title: 'Автопарк',
	height: 150,
    store: store_plan_settings_cars,
	viewConfig: {
        //preserveScrollOnRefresh: true,
		markDirty: false
    },
	//bbar: [PagingToolbar],
    columns: [
	{
		xtype: 'checkcolumn',
		dataIndex: 'check',
		sortable: false,
		width: 70,
		listeners: {
			checkchange:function(CheckColumn, rowIndex, checked, eOpts ) {
				
			}, 
			headerclick: function(ct, column, e, t, eOpts) {
				
			}
		}
    },
    {
            text : plan_settings.name_rule,
            dataIndex : 'name',
			flex: 1,
            sortable: true,
            hideable: false
    },
	{
            text : 'imei',
            dataIndex : 'imei',
			flex: 1,
            sortable: true,
            hideable: false
    }
	
	]
	});
	// <--- grid store cars ---
	
	
	// --- grid store zone --->
	var store_plan_settings_zone = new  Ext.data.Store({   
			autoLoad: true,	
	        fields: ['id','name',{name: 'check', type: 'bool'}],
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_plan_settings.php?func=zone',
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        }
	});
	
	
	var grid_plan_settings_zone = new Ext.grid.GridPanel({
    selType: 'rowmodel',
	height: 150,
	//title: 'Геозоны',
    store: store_plan_settings_zone,
	viewConfig: {
        //preserveScrollOnRefresh: true,
		markDirty: false
    },
	//bbar: [PagingToolbar],
    columns: [
	{
		xtype: 'checkcolumn',
		dataIndex: 'check',
		sortable: false,
		width: 70,
		listeners: {
			checkchange:function(CheckColumn, rowIndex, checked, eOpts ) {
				
			}, 
			headerclick: function(ct, column, e, t, eOpts) {
				
			}
		}
    },
    {
            text : plan_settings.name_rule,
            dataIndex : 'name',
			flex: 1,
            sortable: true,
            hideable: false
    }
	]
	});
	// <--- grid store zone ---
	
	
	//Filial_store.load();
	
	store_plan_settings_cars.load({
						params: {
							//filial: filial_code,
							edit: edit,
							id: idx
						}		
						});

	store_plan_settings_zone.load({
						params: {
							//filial: filial_code,
							edit: edit,
							id: idx
						}		
						});
	
	
	
	if (!mainPlanSettingsWindowAddEdit) 
	{
		mainPlanSettingsWindowAddEdit = new Ext.Window(
        {
            layout : 'fit', 
        	title : title+' '+plan_settings.urule,
        	//title : rights.permissions,
            closeAction : 'destroy',
            width : 500,
            height : 550,
            resizable : true,
            autoScroll: true,
            items : [
			
		Ext.create('Ext.form.Panel', {
        //width: '100%',
        id: 'formid_plan_settings',
		bodyPadding: '5 5 5 5',
		border: false,
		frame: true,
		autoHeight: true,
		autoScroll: true,
        defaults: {
			fileUpload: true,
            msgTarget: 'side'
        },
		fieldDefaults: {
            labelAlign: 'left',
			labelWidth: 50,
            //msgTarget: 'side'
        },
		items: [
				{
					xtype: 'textfield',
					fieldLabel: plan_settings.name_rule,
					labelWidth: 90,
					name: 'name',
				},
				{
					xtype: 'textfield',
					fieldLabel: plan_settings.comments,
					labelWidth: 90,
					name: 'comment'
				},
				{
					xtype: 'textfield',
					fieldLabel: 'Специализация груза',
					labelWidth: 90,
					name: 'spec',
					id: 'spectextfield'
				},
			/*{
            xtype: 'fieldset',
            title: 'Филиал',
			//bodyStyle: 'padding: ' + (Ext.isIE ? '0' : '10px'),
			style: 'padding: 5px 5px 0 5px',
            items: [
				{
			        xtype: 'combobox',
			        //fieldLabel: 'Филиал',
			        store: Filial_store,
			        editable: false,
					allowBlank: false,
			        valueField: 'ID',
			        displayField: 'Name',
					name: 'filial',
			        queryMode: 'local',
					value: global_filial_code,
					listeners: {
						//change : function(combo, newValue, oldValue, eOpts){
						select: function( combo, record, eOpts ){
							//load_plandata(combo.getValue());
							store_plan_settings_cars.load({
							params: {
								filial: combo.getValue()
							}		
							});
						}
					}
				},
			]
			},*/
			{
            xtype: 'fieldset',
            title: plan_settings.cars,
			style: 'padding: 5px',
            items: [
				grid_plan_settings_cars
			]
			},
			{
            xtype: 'fieldset',
            title: plan_settings.geozones,
            style: 'padding: 5px',
			items: [
				grid_plan_settings_zone
			]
			},
			
			
			{
            xtype: 'fieldset',
            title: plan_settings.rule_fro_planing,
            style: 'padding: 5px',
			items: [
				/*{
                xtype:'displayfield',
                //style:'margin-bottom:15px;',              
                value: 'Старт правила',
				},*/
			{
            xtype: 'fieldset',
            //title: 'Запуск правила',
			title: plan_settings.start_trip,
            style: 'padding: 5px',
			items: [
				{
	    	    	xtype: 'container',
	    	    	layout: 'hbox',
	    	    	items: [
						{
				        xtype: 'timefield',
						fieldLabel:  plan_settings.trip_time,
						labelAlign: 'top',
				        name: 'time_project',
				        //fieldLabel: 'Врем старта',
				        margin: '0 10 10 10',
						format:'H:i',
				        minValue: '00:00',
				        maxValue: '23:45',
						value: '10',
				        increment: 30,
						width: 60,
						editable: false,
						value: '06:00'
				        }
						/*{
	    	    		xtype: 'datefield',
	    				fieldLabel: 'Дата',
						labelWidth: 50,
						name: 'date_project',
	    				format: 'Y-m-d',
						editable: false,
						minValue: new Date(),
						//allowBlank: false,
	    				altFormats: 'Y-m-d',
	    				startDay: 1,
	    				margin: '0 10 10 0',
	    				value: new Date(),
						width: 145,
						listeners: {
	    					select: function( field, value, eOpts ) {
								//console.log(field.rawValue);
							}
						}
						},--/
						{
	    	    		xtype: 'combobox',
	    				fieldLabel: 'Дни',
						labelAlign: 'top',
						store: new  Ext.data.Store({   
							fields: ['id','value'],
							data: [{"id":0,"value":"Вс"},{"id":1,"value":"Пн"},{"id":2,"value":"Вт"},{"id":3,"value":"Ср"},{"id":4,"value":"Чт"},{"id":5,"value":"Пт"},{"id":6,"value":"Сб"}]
						}),
						editable: false,
						valueField: 'id',
						displayField: 'value',
						name: 'date_project',
						queryMode: 'local',
						value: 1,
						width: 60
						},
						{
				        xtype: 'timefield',
						fieldLabel: 'Часы',
						labelAlign: 'top',
				        name: 'time_project',
				        //fieldLabel: 'Врем старта',
				        margin: '0 10 10 10',
						format:'H:i',
				        minValue: '00:00',
				        maxValue: '23:45',
						value: '10',
				        increment: 30,
						width: 60,
						editable: false,
						value: '06:00'
				        }
						*/
					]
				},
			]},
			/*{
	    	    	xtype: 'container',
	    	    	layout: 'hbox',
	    	    	items: [
			{
            xtype: 'fieldset',
            title: 'Начало периода',
            style: 'padding: 5px',
			items: [
			
				{
	    	    	xtype: 'container',
	    	    	layout: 'hbox',
	    	    	items: [
						/*{
						xtype: 'numberfield',
						//fieldLabel: obj.amount_of_points,
						name: 'date_from',
						//labelWidth: 160,
						margin: '0 10 0 0',
						//allowBlank: false,
						enableKeyEvents: true,
						//maskRe: /^[1-9]+$/,
						minValue: -31,
						maxValue: 31,
						enforceMaxLength: true,
						minLength: 1,
						maxLength: 3,
						value: -0,
						width: 60
						},--/
						{
						xtype: 'textfield',
						fieldLabel: 'Дни<b style="color:red">*</b>',
						labelAlign: 'top',
						margin: '0 10 0 0',
						name: 'date_from',
						enableKeyEvents: true,
						maskRe: /^[0-9-]*$/,
						enforceMaxLength: true,
						minValue: -31,
						maxValue: 31,
						minLength: 1,
						maxLength: 2,
						value: 0,
						width: 60
						},
						{
				        xtype: 'timefield',
						fieldLabel: 'Часы',
						labelAlign: 'top',
				        name: 'time_from',
				        //fieldLabel: 'Врем старта',
						margin: '0 10 0 0',
				        format:'H:i',
				        minValue: '00:00',
				        maxValue: '23:45',
				        increment: 30,
						editable: false,
						value: '06:00',
						width: 60
				        }
				]}
			]},			
			{
            xtype: 'fieldset',
            title: 'Конец периода',
            style: 'padding: 5px',
			items: [		
					{
	    	    	xtype: 'container',
	    	    	layout: 'hbox',
	    	    	items: [	
						/*{
                                xtype:'displayfield',
                                //style:'margin-bottom:15px;',              
                                value: ' - ',
                        },*/
						/*{
						xtype: 'numberfield',
						//fieldLabel: obj.amount_of_points,
						name: 'date_to',
						//labelWidth: 160,
						margin: '0 10 0 10',
						//allowBlank: false,
						enableKeyEvents: true,
						//maskRe: /^[1-9]+$/,
						minValue: -31,
						maxValue: 31,
						enforceMaxLength: true,
						minLength: 1,
						maxLength: 3,
						value: 0,
						width: 60
						},--/
						{
						xtype: 'textfield',
						fieldLabel: 'Дни<b style="color:red">*</b>',
						labelAlign: 'top',
						margin: '0 10 0 10',
						name: 'date_to',
						enableKeyEvents: true,
						maskRe: /^[0-9-]*$/,
						enforceMaxLength: true,
						minValue: -31,
						maxValue: 31,
						minLength: 1,
						maxLength: 2,
						value: 0,
						width: 60
						},
						{
				        xtype: 'timefield',
						fieldLabel: 'Часы',
						labelAlign: 'top',
				        name: 'time_to',
				        //fieldLabel: 'Врем старта',
				        format:'H:i',
				        minValue: '00:00',
				        maxValue: '23:45',
				        increment: 30,
						editable: false,
						value: '06:00',
						width: 60
				        }
					]},
			]},
				
			]},
			{
                xtype:'displayfield',
                //style:'margin-bottom:15px;',              
                value: '<b style="color:red">*</b> знак "-" перед количеством дней означаем обратный отсчет от времени старта',
			}*/
				
			]},
			/*{
					xtype: 'fieldset',
					title: 'Экспресс',
					style: 'padding: 5px',
					items: [
						{
						xtype:'checkboxfield',              
						name: 'express',
						inputValue: 1,
						checked: 0
						}
					]
			}*/
		]
		})
		
			],
            listeners : 
            {
                destroy : function()
                {
                	mainPlanSettingsWindowAddEdit = null;
                }
            },
            buttons: [{
    	    	//text: 'Сохранить',
    	    	text: all.save,
    	    	handler: function() {
    	    		
					var form = Ext.getCmp('formid_plan_settings').getForm();
					if(form.isValid()){
						
							var arrayCars=[];									
							var arrayZone=[];	
												
							store_plan_settings_cars.each(function(record)   
							{
								if(record.get('check') == true){
									arrayCars.push(record.get('id'));
								}
							
							});
							
							store_plan_settings_zone.each(function(record)   
							{
								if(record.get('check') == true){
									arrayZone.push(record.get('id'));
								}
							
							});
							
					if(arrayCars.length >0){
					if(arrayZone.length >0){
					
					//if( form.findField('date_from').getValue() == "-" || form.findField('date_to').getValue() == "-"){
					//	Ext.Msg.alert(all.error, 'Дни периода указаны некорректно');
					//}else{
                    form.submit({
                        url: 'app/LogistMobile_plan_settings.php',
						params: {addedit:1,'arrayCars[]':arrayCars,'arrayZone[]':arrayZone,idx:idx},
                        waitMsg: all.loading,
						wait:true,
						scope: this,
						method: 'post',
						timeout: 60000,
                        success: function(fp, o) {
							if(o.result.success == true || o.result.success == 'true'){
								Ext.Msg.alert(all.skill, plan_settings.rule_save);
								mainPlanSettingsWindowAddEdit.destroy();
								Ext.getCmp('grid_plan_settings_id').store.load();
								Ext.getCmp('grid_plan_settings_id').getView().refresh();
							}else{
								Ext.MessageBox.alert(all.error, o.result.message);
							}
                        },
						failure: function(fp, o) {
							Ext.Msg.alert(all.error, o.result.message);
						}
                    });
					
					//}
					}else{
						Ext.Msg.alert(all.error, plan_settings.select_zone);
					}
					}else{
						Ext.Msg.alert(all.error, plan_settings.select_car);
					}
					
					}else{
						Ext.Msg.alert(all.error, plan_settings.select_filial);
					}
					
    	    	}
    	    }, {
    	    	//text: 'Отмена',
    	    	text: all.cancel,
    	    	handler: function () {
    	    		mainPlanSettingsWindowAddEdit.destroy();
    	    	}
    	    }]
        });
		mainPlanSettingsWindowAddEdit.show(this, function(){
			//load_plandata(global_filial_code);
			
			if(row){
			
			var form = Ext.getCmp('formid_plan_settings').getForm();
				//console.log(row.get('spec'));		
			form.findField('name').setValue(row.get('Rule_Name'));
			form.findField('comment').setValue(row.get('Rule_Comments'));
form.findField('spec').setValue(row.get('spec'));			
			//form.findField('filial').setValue(row.get('filial_code'));
			form.findField('date_project').setValue(parseInt(row.get('day_of_week')));
			form.findField('time_project').setValue(row.get('time'));
			var objDateFrom = row.get('dif_time_before').split(':');
			var objDateTo = row.get('dif_time_after').split(':');
			form.findField('date_from').setValue(objDateFrom[0]);
			form.findField('time_from').setValue(objDateFrom[1]+':'+objDateFrom[2]);
			form.findField('date_to').setValue(objDateTo[0]);
			form.findField('time_to').setValue(objDateTo[1]+':'+objDateTo[2]);
			form.findField('express').setValue(row.get('express'));
			//form.findField('spec').setValue(row.get('spec'));
			//Ext.getCmp('spectextfield').setValue(row.get('spec'));
			//console.log(form.findField('spec'));
			//console.log(Ext.getCmp('spectextfield'));
			}
			
		});
		
	}
}