var TOiR_planning_Window = null;
var PanelMapPlanning = null;
var addMasterWindow = null;
var globalUserID = null;
var createTripPlanningWindow = null;
var globalCount = 0;

/*var globalOfficeGeoX = 30.520423;
var globalOfficeGeoY = 50.496481;*/
//alert(globalOfficeGeoX);
var arrOfRoutsObj = [];
var arrOfWaypoints = [];

/*var globalOfficeGeoX = 30.9;
var globalOfficeGeoY = 50.9;*/

/*var directionsService = new google.maps.DirectionsService();
var directionsDisplayPlan = null;
var arrOfWaypoints = [];
var globalRouteAjax = [];
var dataForRequestUpdate = [];*/

Ext.define('TOiR_RequestPlannngStoreModel', {
    extend: 'Ext.data.Model',
    fields: ['id', 'status', 'client', 'outlet', 'address', 'time_execute', 'job_type', 'requestcount']
})
var requestPlanning = new Ext.data.Store({ 
			
    model: 'TOiR_RequestPlannngStoreModel',
       proxy: {
          type: 'ajax',
          url: 'app/TOiR_planning.php?func=showRequestNotBind',
          reader: {
            type: 'json',
            root: 'rows'
          }
	   }
});
Ext.define('TOiR_UsersPlanningModel', {
    extend: 'Ext.data.Model',
    fields: ['id' , 'name']
});


var TOiR_UsersPlanningStore = new  Ext.data.Store(
  {     
		autoLoad: true,	
        model: 'TOiR_UsersPlanningModel',
        proxy: 
        {
          type: 'ajax',
          url: 'app/TOiR_planning.php?func=showUsers',
          reader: 
          {
            type: 'json',
            root: 'rows'
          }
        }
});

Ext.define('TOiR_UsersTripPlanningModel', {
    extend: 'Ext.data.Model',
    fields: ['id' , 'name']
});

var TOiR_UsersPlanningTripStore = new  Ext.data.Store(
		  {     
				//autoLoad: true,	
		        model: 'TOiR_UsersTripPlanningModel',
		        proxy: 
		        {
		          type: 'ajax',
		          url: 'app/TOiR_planning.php?func=showTripUsers',
		          reader: 
		          {
		            type: 'json',
		            root: 'rows'
		          }
		        }
});

//tripPlanningGrid

Ext.define('TOiR_TripPlanningModel', {
    extend: 'Ext.data.Model',
    fields: ['id','closed',	'name',	'distance',	'time',	'comments',	'startTime', 'endTime', 'dispatcher_ID','name_master', 
             'calculate', 'masterID', {name: 'bildRoutePlan', type: 'bool'}, {name: 'bildRouteRealPath', type: 'bool'}, 
             {name: 'monit_car', type: 'bool', defaultValue: 'false'}, 'imei', 'Signal']
});


var TOiR_TripPlanningStore = new  Ext.data.Store(
  {     
		//autoLoad: true,	
        model: 'TOiR_TripPlanningModel',
        proxy: 
        {
          type: 'ajax',
          url: 'app/TOiR_planning.php?func=showTrip',
          reader: 
          {
            type: 'json',
            root: 'rows'
          }
        }
});

function show_TOiR_planning_Window(Xcoord,Ycoord,Wwidth,Wheight){
	
	$.post('scripts/CommonSettings.php',{func:'show'},function(data){
		values = data.split("/n");
	
	Xcoord = Xcoord ? Xcoord :40;
    Ycoord = Ycoord ? Ycoord :60;  
    Wwidth = Wwidth ? Wwidth :1100;  
    Wheight = Wheight ? Wheight :600;
  
	if (!TOiR_planning_Window){
  
    PanelMapPlanning = Ext.create('Ext.ux.GMapPanel', {       
        zoomLevel:11,    	
        gmapType: 'map',
//layout: 'fit',
        //resizable: true,
        //padding: 170,
    	id: 'planning_map_panel',        
        mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
        setCenter: {
            //lat:'50.5',
            //lng:'30.5'
			lat: parseFloat(values[2]),
			lng: parseFloat(values[3])
        }
    });
    var tripPlanningGrid = new Ext.grid.Panel({
    	//title: 'Маршруты',
    	title: plan_toir.routes,
    	selType: 'rowmodel',
        columnLines: true,
        layout: 'fit',
        id: 'TOiR_TripPlanningGridId',
        store: TOiR_TripPlanningStore,
        loadMask: true,
        border: false,
        autoScroll: true,
        //height: 213,
        columns:[/*{
        	xtype: 'rownumberer',
			width: 30,	
        }*/{
        	text: 'ID',
        	dataIndex: 'id',
        	style: 'text-align:center',            
            align: 'center',
        	sortable: false,
        	width: 40,
        }, {
        	//text: 'Расчитан',
        	text: plan_toir.calculated,
        	dataIndex: 'calculate',
        	style: 'text-align:center',            
            align: 'center',
            width: 65,
        	sortable: false,
        }, {        	
        	//text: 'Название',
        	text: outlet_toir.title, 
            dataIndex: 'name',
            sortable: true,
            //flex: 1
        }, {
        	//text: 'Бригада',
        	text: plan_toir.team, 
            dataIndex: 'name_master',
            sortable: true,
        }, {
        	//text: 'Дистанция, км',
        	text: plan_toir.distance_km,
            dataIndex: 'distance',
            sortable: true,
        }, {
        	//text: 'Время, мин',
        	text: plan_toir.time_min, 
            dataIndex: 'time',
            sortable: true,
        }, {
        	//text: 'Время старта',
        	text: plan_toir.start_time, 
            dataIndex: 'startTime',
            sortable: true,
            width: 120
        }, {
        	//text: 'Статус маршрута',
        	text: plan_toir.the_status_of_the_route, 
            dataIndex: 'closed',
            style: 'text-align:center',            
            align: 'center',
            sortable: true,
        }], 
        listeners: {
        	itemclick: function(cmp, records) {
        		clearMap();
        		var time = Ext.getCmp('data_of_request_id').getRawValue();
        		globalUserID = records.get('masterID');
        		pointsVisitStore.load({
        			params: {
        				userID: globalUserID,
        				time: time
        			}
        		});
        		
        		сheckAndPaintRoute(records.get('id'));
        		//tracingRouteInPlanin(records.get('id'));		
        	}
        }
    	
    });
    var PBPlanningGrig = new Ext.create('Ext.grid.Panel',{
        //title: 'Рабочие бригады',
        title: plan_toir.work_teams,
    	selType: 'rowmodel',
        columnLines: true,
        id: 'TOiR_PlanningGridId',
        store: TOiR_UsersRoutesStore,
        loadMask: true,
        border: false,
        autoScroll: true,
        columns:[{
        	xtype: 'rownumberer',
			width: 30,	
        }, {        	
        	//text: 'Рабочая бригада',
        	text: plan_toir.work_team, 
            dataIndex: 'name',
            sortable: true,
            flex: 1
        }/*, {
        	xtype: 'checkcolumn',
        	text: 'Трек',
        	dataIndex: 'track',
            sortable: false
        }*/],
        listeners: {
        	itemclick: function(cmp, records) {
        		var time = Ext.getCmp('data_of_request_id').getRawValue();
        		globalUserID = records.get('id');
        		pointsVisitStore.load({
        			params: {
        				userID: globalUserID,
        				time: time
        			}
        		});
        	}
        }
    });
    
    var requestPlanningGrig = new Ext.create('Ext.grid.Panel',{
        //title: 'Список непривязанных заявок',
        title: plan_toir.list_of_unbound_applications,
    	selType: 'rowmodel',
        columnLines: true,        
        height: 250,        
        minHeight: 100,        
        margin: '0 0 10 0',       
        store: requestPlanning,        
        viewConfig: {
        	plugins: {
                ptype: 'gridviewdragdrop',
                /*dragGroup: 'requestPlanningGrigGroup',
                dropGroup: 'southWestPanelPlanningGroup'*/
            },
            
            listeners: {
                drop: function(node, data, dropRec, dropPosition) {
                	console.log(data);
                	
                	console.log(data.records[0].get('id'));
                	var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
                	removeRequestFromTrip(data.records[0].get('id'), select.get('id'));
                	
                	$.post('app/TOiR_planning.php', {func: 'bindMaster', masterID: 0, requestID: data.records[0].get('id')}, function (data) {								
						var time = Ext.getCmp('data_of_request_id').getRawValue();
						
	       					requestPlanning.load({
	           				params: {
	           					time: time
	           				}
	           			});
						pointsVisitStore.load({
							params: {
								userID: globalUserID,
								time: time
							}
						});
						resetCalculateTrip();
					});                	
	                   
                }
            }
        },        
        loadMask: true,
        border: false,
        autoScroll: true,        
        columns:[/*{
        	xtype: 'rownumberer',
			width: 30,	
        },*/{
        	text: 'ID', 
            dataIndex: 'id',
            style: 'text-align:center',            
            align: 'center',
            sortable: true,
            width: 40,	
        }, {
        	//text: 'Статус',
        	text: plan_toir.status, 
            dataIndex: 'status',
            style: 'text-align:center',            
            align: 'center',
            sortable: true,
            width: 52
        }, {
        	//text: 'Клиент',
        	text: client_toir.client,
            dataIndex: 'client',
            sortable: true,
        },{
        	//text: 'Тип работ',
        	text: plan_toir.type_of_works, 
            dataIndex: 'job_type',
            sortable: true,
        }, {
        	//text: 'Торговая точка',
        	text: plan_toir.outlet, 
            dataIndex: 'outlet',
            sortable: true,
        }, {
        	//text: 'Адрес',
        	text: client_toir.address, 
            dataIndex: 'address',
            sortable: true,
            //flex: 1
        }, {
        	//text: 'Время приезда',
        	text: plan_toir.time_of_arrival, 
            dataIndex: 'time_execute',
            sortable: true,
            width: 130
        }, {
        	//text: 'Заявка создана по показаниям счетчика',
        	text: request_toir.request_requestcount, 
            dataIndex: 'requestcount',
            sortable: true,
            width: 130
        }
		],        
        listeners: {
        	itemdblclick: function(cmp, records) {        		
        		bindMaster(records.get('id'));        		
        	},
        	afterrender: function() {
        		var time = Ext.getCmp('data_of_request_id').getRawValue();
        		TOiR_TripPlanningStore.load({
        			params: {
        				time: time
        			}
        		});
				requestPlanning.load({
    				params: {
    					time: time
    				}
    			});
				
        	}
        	
        }
    });
    
    var westPanelPlanning = new Ext.panel.Panel({
    	//title: 'Заявки',
    	title: plan_toir.request,    
    	defaults: {			
			labelWidth: 120,
			msgTarget: 'side',			
		},
		//layout: 'fit',
    	items: [
    	    {
    	    	xtype: 'container',
    	    	layout: 'hbox',
    	    	items: [{
    	    		xtype: 'datefield',
    				//fieldLabel: 'Дата заявок',
    				fieldLabel: plan_toir.date_of_requests,
    				format: 'Y-m-d',
    				altFormats: 'Y-m-d',
    				id: 'data_of_request_id',
    				startDay: 1,
    				margin: '5 5 5 5',
    				name : 'date_create',
    				value: new Date(),
    				listeners: {
    					select: function( field, value, eOpts ) {
    						clearMap(); 
    						var time = Ext.getCmp('data_of_request_id').getRawValue();
    						requestPlanning.load({
    		    				params: {
    		    					time: time
    		    				}
    		    			});    						
    						
    						pointsVisitStore.loadData({});
    						
    						TOiR_TripPlanningStore.load({
    							params: {
    		    					time: time
    		    				}
    						});
    					}
    				}
    	    		
    		    	}, {
    		    		xtype: 'button',
    		    		//text: 'Автопланирование',
    		    		text: plan_toir.autoplanning,
    		    		margin: '5 5 5 100',
    		    		handler: function() {
    		    			var time = Ext.getCmp('data_of_request_id').getRawValue(); 
    		    			autoplan(time);/*
    		    			var time = Ext.getCmp('data_of_request_id').getRawValue();  
    		    			$.post('app/TOiR_planning.php', {func: 'addAutoTrip', time: time}, function(data) {
    		    				///var time = Ext.getCmp('data_of_request_id').getRawValue(); 
        		    			requestPlanning.load({
        	           				params: {
        	           					time: time
        	           				}
        	           			});
        		    			TOiR_TripPlanningStore.load({
        		        			params: {
        		        				time: time
        		        			}
        		        		});
        		    			pointsVisitStore.removeAll();
    		    			});
    		    		*/}
    		    	}, {
    		    		xtype: 'button',
    		    		//text: 'Обновить данные',
    		    		text: plan_toir.update_details,
    		    		margin: '5 5 5 10',
    		    		handler: function() {
    		    			//PanelMapPlanning.getMap().overlayMapTypes.setAt( 0, null);
    		    			//PanelMapPlanning.clearOverlays();
    		    			//PanelMapPlanning.getMap().setMap(null);
    		    			var time = Ext.getCmp('data_of_request_id').getRawValue();    		    			
    		    			requestPlanning.load({
    	           				params: {
    	           					time: time
    	           				}
    	           			});    		    			
    		    			TOiR_TripPlanningStore.load({
    		        			params: {
    		        				time: time
    		        			}
    		        		});
    		    			pointsVisitStore.removeAll();
    		    			closeRoute();
    		    		}
    		    	}]
    	    },    
    	    
    	    new Ext.panel.Panel ({    	    	
    	        height       : 400,
    	        layout: 'anchor',
    	        autoScroll: true,
    	        items        : [requestPlanningGrig],
    	        
    	    })    	   
    	]
    });
    
    
    
    var southWestPanelPlanning = new Ext.create('Ext.grid.Panel',{
        //title: 'Точки посещения',
        title: plan_toir.points_visit,
    	selType: 'rowmodel',
        columnLines: true,        
        store: pointsVisitStore,
        autoScroll: true,
        //height: 250,        
        //minHeight: 100,
        //layout: 'fit',
        viewConfig: {
        	plugins: {
                ptype: 'gridviewdragdrop',
                /*dragGroup: 'southWestPanelPlanningGroup',
                dropGroup: 'requestPlanningGrigGroup'*/
            },            
            listeners: {
                drop: function(node, data, dropRec, dropPosition) {
                	//console.log(node);
                	console.log(data.records[0].id);// что беру
                	//console.log(dropRec);
                	//console.log(dropPosition);
                	if (dropRec != null) {
                		console.log(dropRec.id);//куда бросаю
                		console.log(dropPosition);
                		var where_str = dropPosition;
                		var where_id = dropRec.id
                	} else {
                		var where_str = '';
                		var where_id = 0; 
                	}
                	
                	/*var what_id = data.records[0].id.split('_');
                	console.log(what_id[0]);
                	var where_id = dropRec.id.split('_');
                	console.log(where_id[0]);
                	
                	var pointsArr = [];
            		for (var i in data.records) {
            			pointsArr.push(data.records[i].get('ID'));
            		}		                		
            		var fromPointId = dropRec.data.ID;*/
                	
                	
                   console.log(data.records[0].get('id'));                   
                   var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
                   if (select) {
                	   bindRequestToTrip(data.records[0].get('id'), select.get('id'), where_id, where_str);
                	   
	                	   $.post('app/TOiR_planning.php', {func: 'bindMaster', masterID: globalUserID, requestID: data.records[0].get('id')}, function (data) {								
								var time = Ext.getCmp('data_of_request_id').getRawValue();
			       					requestPlanning.load({
			           				params: {
			           					time: time
			           				}
			           			});
								pointsVisitStore.load({
									params: {
										userID: globalUserID,
										time: time
									}
								});
								resetCalculateTrip();
								
								
							});
	                	   
	                   } else {
	                	   Ext.Msg.alert(all_toir.attention, plan_toir.select_a_route);
	                	   pointsVisitStore.removeAll();	                	   
	                	   var time = Ext.getCmp('data_of_request_id').getRawValue();
	       					requestPlanning.load({
	           				params: {
	           					time: time
	           				}
	           			});
	                   }
                }
            }
        },
        
        loadMask: true,
        border: false,
        autoScroll: true,        
        columns:[/*{
        	xtype: 'rownumberer',
			width: 30,	
        }*/{
        	text: 'ID', 
            dataIndex: 'id',
            width: 30,
            style: 'text-align:center',            
            align: 'center',
            sortable: true,
        }, {
        	//text: 'Статус',
        	text: plan_toir.status, 
            dataIndex: 'status',
            style: 'text-align:center',            
            align: 'center',
            sortable: true,
            width: 52
        }, {
        	//text: 'Клиент',
        	text: client_toir.client, 
            dataIndex: 'client',
            sortable: true,
        },{
        	//text: 'Тип работ',
        	text: plan_toir.type_of_works,
            dataIndex: 'job_type',
            sortable: true,
        }, {
        	//text: 'Торговая точка',
        	text: plan_toir.outlet,
            dataIndex: 'outlet',
            sortable: true,
        }, {
        	//text: 'Адрес',
        	text: client_toir.client, 
            dataIndex: 'address',
            sortable: true,
            width: 150,
            //flex: 1
        }, {
        	//text: 'Время приезда',
        	text: plan_toir.time_of_arrival, 
            dataIndex: 'time_beginning_work',
            sortable: true,
            width: 130
        }], 
        listeners: {
        	itemdblclick: function(cmp, record) {
        		console.log(record);
        		
        		focusOutlet(record);
        	}
        }       
    });
    
	
        Ext.getBody().mask(all.loading);
        TOiR_planning_Window = new Ext.Window({
            layout : 'border',
            //title : 'Планирование заявок',
            title : plan_toir.planning_of_requests,
            closeAction : 'destroy',
            width : parseInt(Wwidth),
            height : parseInt(Wheight),
            //minimizable: true,
			/*constrainHeader: true,
            maximizable:true,
            x : 20,
            y : 20,*/
            
            maximizable:true,
            constrainHeader: false,
            resizable: true,
			x : 2,
            y : 29,
           defaults: {
               collapsible: false,
               split: true,
                
            },
			listeners : {
            	destroy : function(){
            		TOiR_planning_Window = null;	
            	}
            },
            items : [{	                
	                layout: 'fit',            	    
	                region:'center',
	                margins: '5 5 5 0',	                
	                items:[
	                       PanelMapPlanning
					]
			    }, {				    
			    	layout: 'fit',  
			    	region:'west',
	                margins: '5 5 5 0',
	                width: '60%',
	                items:[	westPanelPlanning ]			    	
			    }, {			    	
	                region:'south',
	                margins: '5 5 5 0',
	                height: 250,
	                layout: 'border',
	                defaults: {
	                    collapsible: false,
	                    split: true,	                     
	                 },
	                items:[	                      
	                       {
	                    	   region:'center',
	                    	   width: '50%',
	                    	   layout: 'anchor',
	                    	   items: [{
	                    		   xtype: 'container',
	                    		   layout: 'hbox',
	                    		   //anchor: '100 100',
	                    		   anchor: '100% 15%',
	                    		   //height: 100,
	                    		   margin: '5 5 5 5',
	                    		   items: [ {
		                    		   xtype: 'button',
		                    		   //text: 'Создать маршрут',
		                    		   text: plan_toir.create_route,
		                    		   handler: function() {
		                    			   createTripPlanning(0, 'add');
		                    		   }
		                    		   
		                    	   }, {
		                    		   xtype: 'button',
		                    		   margin: '0 0 0 10',
		                    		   //hidden: true,
		                    		   //text: 'Удалить маршрут',
		                    		   text: plan_toir.delete_route,
		                    		   handler: function() {
		                    			   var time = Ext.getCmp('data_of_request_id').getRawValue();
		                    			   var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
		                    			   if (select) {		                    				   
		                                   	$.post('app/TOiR_planning.php', {func: 'delete', id: select.get('id')}, function() {
		                                   		clearMap();
		                                   		Ext.getCmp('TOiR_TripPlanningGridId').store.load({
		                                   			params: {
		                                   				time: time
		                                   			}
		                                   		});		                                   		
		        								Ext.getCmp('TOiR_TripPlanningGridId').getView().refresh();
		        								requestPlanning.load({
		        	    	           				params: {
		        	    	           					time: time
		        	    	           				}
		        	    	           			});
		        								pointsVisitStore.removeAll();
		                                   	});
			       							} else {
			                                       Ext.MessageBox.alert(all_toir.error, plan_toir.select_the_route_to_delete);
			                                   }
			                    		   } 
		                    	   },{
		                    		   xtype: 'button',
		                    		   margin: '0 0 0 10',
		                    		   //text: 'Редактировать маршрут',
		                    		   text: plan_toir.edit_route,
		                    		   handler: function() {
		                    			   //calculateTrip();
		                    			 var   select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
		                    			   createTripPlanning(select.get('id'), 'edit');
		                    			   //editTrip(select.get('id'));
				                    	 } 
		                    	   }, {
		                    		   xtype: 'button',
		                    		   margin: '0 0 0 10',
		                    		   //text: 'Просчитать маршрут',
		                    		   text: plan_toir.calculate_route,
		                    		   handler: function() {
		                    			   clearMap();
		                    			   calculateTrip();
				                    	 } 
		                    		   
		                    	   }]
	                    	   }, 
	                    	   //PBPlanningGrig
	                    	   {
	                    		xtype: 'panel',
	                    		//layout: 'fit',
	                    		anchor: '100% 85%',
	                    		
	                    		items: [tripPlanningGrid]
	                    	   }]
	                       },
	                       {
	                    	   region:'west',
	                    	   width: '50%',
	                    	   layout: 'fit',
	                    	   items: [ 	                    	           
	                    	           /*new Ext.panel.Panel ({	                    	    	    	
	                    	    	        height       : 300,
	                    	    	        layout: 'anchor',
	                    	    	        items        : [southWestPanelPlanning],
	                    	    	        
	                    	    	    })*/	                    	       
	                    	           southWestPanelPlanning
	                    	           ]
	                       }
					]	
			    }]
        });
	}      
	TOiR_planning_Window.show(); 
	 Ext.getBody().unmask(all.loading);	 
	
	});
}

function bindMaster(requestID) {	
	if (!addMasterWindow) {	 
		addMasterWindow = new Ext.Window({
	         layout : 'border',
	         //title : 'Назначить бригаду',
	         title : plan_toir.assign_a_team,
	         closeAction : 'destroy',
	         width : 400,
	         height : 150,
	         modal: true,
	         //minimizable: true,
				constrainHeader: true,
	         //maximizable:true,
	         //x : parseInt(Xcoord),
	         //y : parseInt(Ycoord),
				listeners : {
					destroy : function(){
	         		addMasterWindow = null;	
	         	}
	         },
	         items : [{
	        	 xtype: 'form',
	        	 //layout: 'fit',
	        	 width : 400,
		         height : 150,
		         id: 'bind_form_id',
	        	 items: [{
		        	 xtype: 'combo',
		        	 //fieldLabel: 'Выберите бригаду',
		        	 fieldLabel: plan_toir.select_a_team,
		        	 store: TOiR_UsersPlanningStore,
		        	 margin: '5 5 5 5',
		        	 labelWidth: 150,
		        	 id: 'bind_master_id',
		        	 valueField: 'id',
		        	 displayField: 'name',
		         }]
	         }],
	         buttons: [{
	        	 
					//text:'Cохранить',
					text: all_toir.save,
					//id:'buttonUploads',
					iconCls:'save',
					handler: function() {
						var masterID = Ext.getCmp('bind_master_id').getValue();
						console.log(masterID);
						$.post('app/TOiR_planning.php', {func: 'bindMaster', masterID: masterID, requestID: requestID}, function (data) {
							
							var time = Ext.getCmp('data_of_request_id').getRawValue();
							requestPlanning.load({
		           				params: {
		           					time: time
		           				}
		           			});
							pointsVisitStore.load({
								params: {
									userID: masterID,
									time: time
								}
							});
							addMasterWindow.destroy();							
						});
					}
					
	         }, {
                 //text: 'Отмена',
                 text: all_toir.cancel,
				 iconCls:'cancel',
                 handler: function(){
                	 addMasterWindow.destroy();
                 }
			}]
		 });          
	}
	addMasterWindow.show();
}

function createTripPlanning (trip_id, flag) {
	//TOiR_UsersPlanningTripStore.load();
	if (flag == 'edit') {
		//var title = 'Редактировать маршрут';
		var title = plan_toir.edit_route;
	} else {		
		//var title = 'Создать маршрут';
		var title = plan_toir.create_route;
		globalCount++;
	}
	var time = Ext.getCmp('data_of_request_id').getRawValue();	
	console.log(time);
	TOiR_UsersPlanningTripStore.load({
		params: {
			time: time,
			userFlag: trip_id
		}
	}); 
	if (!createTripPlanningWindow) {	 
		createTripPlanningWindow = new Ext.Window({
	         layout : 'border',
	         title : title,
	         closeAction : 'destroy',
	         width : 400,
	         height : 300,
	         modal: true,
	         //minimizable: true,
				constrainHeader: true,
	         //maximizable:true,
	         //x : parseInt(Xcoord),
	         //y : parseInt(Ycoord),
				listeners : {
					destroy : function(){
						createTripPlanningWindow = null;						
	         	}
	         },
	         items : [{
	        	 xtype: 'form',
	        	 //layout: 'fit',
	        	 width : 400,
		         height : 300,
		         id: 'trip_form_id',
	        	 items: [{
	        		 xtype: 'textfield',
	        		 margin: '5 5 5 5',
		        	 labelWidth: 150,
		        	 //fieldLabel: 'Название маршрута',
		        	 fieldLabel: plan_toir.name_of_the_route,
		        	 name: 'trip_name',
		        	 value: plan_toir.route_ + globalCount
	        	 },{
		        	 xtype: 'combo',
		        	 //fieldLabel: 'Выберите бригаду',
		        	 fieldLabel: plan_toir.select_a_team,
		        	 store: TOiR_UsersPlanningTripStore,
		        	 allowBlank: false,
		        	 margin: '5 5 5 5',
		        	 labelWidth: 150,
		        	 id: 'bind_master_id',
		        	 valueField: 'id',
		        	 displayField: 'name',
		        	 name: 'trip_master',
		        	 queryMode: 'local',
		         }, {
		        	xtype: 'container',
		        	layout: 'hbox',
		        	items: [{			        	 
			        	 xtype: 'numberfield',
			        	 labelWidth: 50,
			        	 margin: '5 5 5 5',
			        	 //fieldLabel: 'C часов',
			        	 fieldLabel: plan_toir.from_hours,
			        	 minValue: 0, 
			        	 maxValue: 23, 
			        	 step: 1, 			        	 
			        	 width: 100, 
			        	 value: 9,
			        	 name: 'trip_houre'
			         }, {			        	 
			        	 xtype: 'numberfield',
			        	 labelWidth: 50,
			        	 margin: '5 5 5 5',
			        	 //fieldLabel: 'C минут',
			        	 fieldLabel: plan_toir.from_minute,			
			        	 minValue: 0, 
			        	 maxValue: 59, 
			        	 step: 1,			        	
			        	 width: 100, 
			        	 value: 0,
			        	 name: 'trip_min'
			         }]
		         }, {
		        	 xtype: 'textfield',
	        		 margin: '5 5 5 5',
		        	 labelWidth: 150,
		        	 //fieldLabel: 'Комментарии',
		        	 fieldLabel: plan_toir.comments,
		        	 name: 'trip_comments'
		         }]
	         }],
	         buttons: [{
	        	 
					//text:'Сохранить',
					text: all_toir.save,
					//id:'buttonUploads',
					iconCls:'save',
					handler: function() {
						var time = Ext.getCmp('data_of_request_id').getRawValue();
						var form = Ext.getCmp('trip_form_id').getForm();
						var date = Ext.getCmp('data_of_request_id').getRawValue();
						if(form.isValid()){
						form.submit({
							//waitMsg:'Идет отправка...',
							waitMsg: all_toir.loading,
                            url: 'app/TOiR_planning.php',							
							wait: true,
							scope: this,
							method: 'post',							
							params: {func:'addTrip', date: date, flag: flag, trip_id: trip_id },
                            success: function(fp, o){
                            	
                            	Ext.getCmp('TOiR_TripPlanningGridId').store.load({
                            		params: {
                            			time: time
                            		} 
                            	});
								Ext.getCmp('TOiR_TripPlanningGridId').getView().refresh();                            	
                            	createTripPlanningWindow.destroy();
                            	
                            	//resetCalculateTrip();
                            	
                            	/*TOiR_request_WindowAddEdit.destroy();
                            	Ext.getCmp('TOiR_RequestGridId').store.load();
								Ext.getCmp('TOiR_RequestGridId').getView().refresh();
                            	*/
                            }
							
						});
					}	
						
					}
					
	         }, {
                 //text: 'Отмена',
                 text: all_toir.cancel,
				 iconCls:'cancel',
                 handler: function(){
                	 createTripPlanningWindow.destroy();
                	 //globalCount--;
                 }
			}]
		 });          
	}
	createTripPlanningWindow.show();
	
	if (flag == 'edit') {
		console.log('dddd');
		var form = Ext.getCmp("trip_form_id").getForm().getFields();
		var time = Ext.getCmp('data_of_request_id').getRawValue();
		/*TOiR_UsersPlanningTripStore.load({
			params: {
				time: time,
				userFlag: trip_id
			}
		}); */
		Ext.Ajax.request({
	            url: 'app/TOiR_planning.php',
	            method: 'POST',
	            params: {"func":"editTrip","id":trip_id},
	            success: function(response) {
	                var JSON = response.responseText;
	                console.log(JSON); 
	                if (JSON) {
	                    var decoded = Ext.decode(JSON);
						var i = 0;					
						var arrOfItems = [];
						for (k in decoded) {
							arrOfItems.push(decoded[k]);
						}					
						form.each(function(item) {
						if (item.xtype == 'combo') {
	                        
							item.setValue(parseInt(arrOfItems[i]));
	                    } else {
							item.setValue(arrOfItems[i]);
						}
						i++;
	                    });
	                }
	                
	                
	            },
	            failure: function(response) {
	                Ext.MessageBox.alert(all_toir.error, response.responseText);
	            }
	        });
	}
	
	/*TOiR_UsersPlanningTripStore.load({
		params: {
			time: time
		}
	});*/
}

function calculateTrip() {
	 var time = Ext.getCmp('data_of_request_id').getRawValue();
	   var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
	   console.log('select');
	   console.log(select);
	   console.log(select.get('id'));
	   /*if (trip_id) {
		   var tripID = trip_id;
	   } else {
		   var tripID = select.get('id');
	   }*/
	   if (select) {
		   $.post('app/TOiR_planning.php', {func: 'calculateTrip', id: select.get('id')}, function(data) {
				if (data != 0) { 
				var directionsService = new google.maps.DirectionsService();
				var directionsDisplayPlan = null;
				clearMap(); 
				/*if (arrOfRoutsObj.length > 0) {
					for (var key in arrOfRoutsObj) {
						arrOfRoutsObj[key].setMap(null);
					}
					arrOfRoutsObj = [];
				} */
				
				var globalRouteAjax = [];
				var dataForRequestUpdate = [];
				 var objData = Ext.decode(data);
				 console.log('objData');
				 console.log(objData);
				 var workDuration = 0;
				 /*if (arrOfWaypoints) {					
					 arrOfWaypoints = [];
					 PanelMapPlanning.deleteMarkersOutlets();
				 } */
				
				 
				 var polylineOptionsPlan = {
					      strokeColor: '#538929',
					      strokeOpacity: 1.0,
					      strokeWeight: 5
				   };
				 var arrOfCoordinateoForRequest = [];
				 arrOfCoordinateoForRequest.push(new google.maps.LatLng(globalOfficeGeoY,globalOfficeGeoX));
				 for (var key in objData) {					
					 GoogleLatLng = new google.maps.LatLng(objData[key][1],objData[key][0]);
					 PanelMapPlanning.addMarker(GoogleLatLng,{cursor:'outlet_'+objData[key][2], icon:'images/record.png'},false,true,null,'');
					 arrOfWaypoints.push({
				          location: GoogleLatLng,
				          stopover:true});
					 workDuration += objData[key][3];
					 //update time in toir_request
					 arrOfCoordinateoForRequest.push(new google.maps.LatLng(objData[key][1],objData[key][0]))
					 /* 
					 while (j<route.legs.length-1) {
									if (check) {
										var date = new Date(objData[i][4]);
										date.setMinutes(date.getMinutes() + route.legs[i].duration.value/60)
										newdate = getDateFormated(date);
										dataForRequestUpdate.push([objData[i][2], newdate]);
										check = 0;
									} else {
										date = new Date(newdate);
										date.setMinutes(date.getMinutes() + route.legs[i].duration.value/60)
										newdate = getDateFormated(date);
										dataForRequestUpdate.push([objData[i][2], newdate]);
									}
									j++;
									console.log(dataForRequestUpdate);
								}
					 */
					 
				 }
				 arrOfCoordinateoForRequest.push(new google.maps.LatLng(globalOfficeGeoY,globalOfficeGeoX));
				 console.log('+++arrOfCoordinateoForRequest+++');
				 console.log(arrOfCoordinateoForRequest);
				 var check = 1;
				 var j = 0;
				 var total = 0;
				 var totalTime = 0;
				 var motionTime = 0;
				 for (var i = 0; i < arrOfCoordinateoForRequest.length-1; i++) {
					 console.log(i);
					 var request = {
						      origin: arrOfCoordinateoForRequest[i],
						      destination: arrOfCoordinateoForRequest[i+1],
						      //waypoints: arrOfWaypoints,
						      optimizeWaypoints: true,
							  provideRouteAlternatives: false,
						      travelMode: google.maps.TravelMode.DRIVING
						};
					 
					 directionsService.route(request, function(response, status) {
						    if (status == google.maps.DirectionsStatus.OK){
						    
							directionsDisplayPlan = new google.maps.DirectionsRenderer({
								suppressMarkers: true, polylineOptions: polylineOptionsPlan});
							directionsDisplayPlan.setDirections(response);
							//path
							console.log('++globalRouteAjax++');
							console.log(globalRouteAjax);
							console.log('++directionsDisplayPlan++');
							console.log(directionsDisplayPlan.directions);
							//console.log(directionsDisplayPlan.directions.routes[0].overview_path);
							
							//globalRouteAjax.push(directionsDisplayPlan.directions.routes[0].overview_path);
							
							globalRouteAjax[globalRouteAjax.length] = directionsDisplayPlan.directions.routes[0].overview_path;
							
							arrOfRoutsObj.push(directionsDisplayPlan);
							directionsDisplayPlan.setMap(PanelMapPlanning.getMap());
							var route = response.routes[0];
						      console.log('++route++');
							  console.log(route);
						     //var total = 0;
							
							//var j=0;
								//for (var i = 0; i < route.legs.length; i++) {
									
									//total += route.legs[i].distance.value;
									//motionTime += route.legs[i].duration.value;
									//while (j<route.legs.length-1) {
										//console.log(j);	

										
								
										
										
											total += route.legs[0].distance.value/1000;
											motionTime += route.legs[0].duration.value/60;										
											console.log('total');
											console.log(total);	
										//var speed = 50;
										//var motionTime = total/speed * 60;
										
										
										while (j <  arrOfCoordinateoForRequest.length - 2) {
											if (check) {
												var date = new Date(objData[j][4]);
												date.setMinutes(date.getMinutes() + route.legs[0].duration.value/60)
												newdate = getDateFormated(date);
												dataForRequestUpdate.push([objData[j][2], newdate]);
												check = 0;
											} else {
												date = new Date(newdate);
												date.setMinutes(date.getMinutes() + route.legs[0].duration.value/60 + objData[j][3]);
												newdate = getDateFormated(date);
												
												dataForRequestUpdate.push([objData[j][2], newdate]);
											}
											j++;
										}
										
										console.log(dataForRequestUpdate);
									//}
								//}
								//console.log(total);
							//var route = response.routes[0];
							//console.log(route.legs[i].distance.value);
						   } else {
							    
						   }
				    });
					 
					 //console.log(arrOfCoordinateoForRequest[i]);
					 
				 }
				 var arrOfRoutPoints = [];
				 setTimeout(function() {
					 console.log('globalRouteAjax');
					 console.log(globalRouteAjax);
					 for (var key in globalRouteAjax) {
						 for (var key2 in globalRouteAjax[key]) {
							 //console.log(globalRouteAjax[key]);
							 //console.log( globalRouteAjax[key][key2].lat()+' = '+globalRouteAjax[key][key2].lng() );
							 //arrOfRoutPoints.push(globalRouteAjax[key][key2]);
							 arrOfRoutPoints.push( {lat:globalRouteAjax[key][key2].lat(),lng:globalRouteAjax[key][key2].lng()} );
						 }
					 }
					 
					 globalRouteAjax = Ext.encode(arrOfRoutPoints);
					 console.log(globalRouteAjax);
					 totalTime = motionTime + workDuration;
					 TOiR_TripPlanningStore.each(function(record) {
							
							if (record.get('id') == select.get('id')) {
								console.log('+++ updateTripDistanseTime total +++ '+total);
								record.set('distance',total.toFixed(0));
								record.set('time', totalTime.toFixed(0));
								$.post('app/TOiR_planning.php', {func: 'updateTripDistanseTime', 
									id: record.get('id'), distance: total.toFixed(0), time: totalTime.toFixed(0) , route: globalRouteAjax,
									'dataForRequestUpdate[]': dataForRequestUpdate}, function() {
									 Ext.getCmp('TOiR_TripPlanningGridId').store.load({
							        		params: {
							         				time: time
							         			}
							         		});
									Ext.getCmp('TOiR_TripPlanningGridId').getView().refresh();
									//directionsDisplayPlan.setMap(PanelMapPlanning.getMap());
									pointsVisitStore.load({
					        			params: {
					        				userID: globalUserID,
					        				time: time
					        			}
					        		});
								});
							}
						});
				 }, 1000); 
				 
				 
				 GoogleLatLng = new google.maps.LatLng(globalOfficeGeoY,globalOfficeGeoX);
				 PanelMapPlanning.addMarker(GoogleLatLng,{cursor:'outlet_', /*icon:'images/record.png'*/},false,true,null,'');
				  
				 
				 
				 /*var request = {
					      origin: new google.maps.LatLng(globalOfficeGeoY,globalOfficeGeoX),
					      destination: new google.maps.LatLng(globalOfficeGeoY,globalOfficeGeoX),
					      waypoints: arrOfWaypoints,
					      optimizeWaypoints: true,
						  provideRouteAlternatives: false,
					      travelMode: google.maps.TravelMode.DRIVING
					};*/
				 
				/* if (directionsDisplayPlan) {
					 directionsDisplayPlan.setMap(null);
					 //PanelMapPlanning.getMap().setMap(null);
				 }
				 //var dataForRequestUpdate = [];
				 directionsService.route(request, function(response, status) {
					    if (status == google.maps.DirectionsStatus.OK){
					    
						directionsDisplayPlan = new google.maps.DirectionsRenderer({
							suppressMarkers: true, polylineOptions: polylineOptionsPlan});
						directionsDisplayPlan.setDirections(response);
						//directionsDisplayPlan.setMap(PanelMapPlanning.getMap());
					    //console.log(directionsDisplayPlan.directions.routes[0].overview_path);
					    globalRouteAjax = Ext.encode(directionsDisplayPlan.directions.routes[0].overview_path);
					    //console.log(globalRouteAjax);
					    //directionsDisplay.setDirections(response);
						  
					      var route = response.routes[0];
					      //console.log(route);
					     var total = 0;
					     var motionTime = 0;
					     var check = 1;
					     var j=0;
							for (var i = 0; i < route.legs.length; i++) {								
								total += route.legs[i].distance.value;
								motionTime += route.legs[i].duration.value;
							}
							total = total/1000;
							//var speed = 50;
							//var motionTime = total/speed * 60;
							var totalTime = motionTime/60 + workDuration;
							
							TOiR_TripPlanningStore.each(function(record) {
								
								if (record.get('id') == select.get('id')) {
									record.set('distance',total.toFixed(0));
									record.set('time', totalTime.toFixed(0));
									$.post('app/TOiR_planning.php', {func: 'updateTripDistanseTime', 
										id: record.get('id'), distance: total.toFixed(0), time: totalTime.toFixed(0) , route: globalRouteAjax,
										'dataForRequestUpdate[]': dataForRequestUpdate}, function() {
										 Ext.getCmp('TOiR_TripPlanningGridId').store.load({
								        		params: {
								         				time: time
								         			}
								         		});
										Ext.getCmp('TOiR_TripPlanningGridId').getView().refresh();
										//directionsDisplayPlan.setMap(PanelMapPlanning.getMap());
										pointsVisitStore.load({
						        			params: {
						        				userID: globalUserID,
						        				time: time
						        			}
						        		});
									});
								}
							});
					    
					    }
					  });*/
                 
				
				} else {
					Ext.MessageBox.alert(all_toir.error, plan_toir.to_render_to_choose_at_least_one_point_of_visiting);
				}	
		  });
			} else {
				Ext.MessageBox.alert(all_toir.error, plan_toir.select_the_route_to_miscalculation);
			}
}

function resetCalculateTrip() {
	var time = Ext.getCmp('data_of_request_id').getRawValue();
	var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
	$.post('app/TOiR_planning.php', {func: 'resetCalculateTrip', id: select.get('id')}, function() {
		   Ext.getCmp('TOiR_TripPlanningGridId').store.load({
  			params: {
  				time: time
  			}
  		});
			Ext.getCmp('TOiR_TripPlanningGridId').getView().refresh(); 
	   	});
} 

function bindRequestToTrip(request_id, trip_id, where_id, where_str) {	
	$.post('app/TOiR_planning.php', {func: 'bindRequestToTrip', request_id: request_id, trip_id: trip_id,
		where_id: where_id, where_str: where_str}, function() {
		
	});	
}

function removeRequestFromTrip (request_id, trip_id) {
	console.log(request_id + ' '+ trip_id);
	$.post('app/TOiR_planning.php', {func: 'removeRequestFromTrip', request_id: request_id, trip_id: trip_id}, function() {
		
	});
}

function editTrip(trip_id) {
	console.log(trip_id);
	
}

function focusOutlet(record) {
	
	$.post('app/TOiR_planning.php', {func: 'checkCulculateTrip', request_id: record.get('id')}, function(data) {
		if (data != 0) {
			//PanelMapPlanning.getMap.
			//setCenter(new google.maps.LatLng(parseFloat(globalCenterY), parseFloat(globalCenterX)));
			PanelMapPlanning.setNewCenter(new google.maps.LatLng(record.get('geoY'),record.get('geoX')), 15);
		} else {
			Ext.Msg.alert(all_toir.attention, plan_toir.itinerary_for_this_application_have_not_yet_figured_out);
		}
	});
}

function getDateFormated(date) {
	var month = date.getMonth() + 1; //months from 1-12
	var day = date.getDate();
	var year = date.getFullYear();
	var hour = date.getHours();								
	var min = date.getMinutes();
	var second = date.getSeconds();
	if (month<10)  month = '0' + month;
	if (day<10)  day = '0' + day;
	if (hour<10)  hour = '0' + hour;
	if (min<10)  min = '0' + min;
	if (second<10)  second = '0' + second;
	
	return year + "-" + month + "-" + day + ' ' + hour + ':' + min + ':' + second;	
}

function clearMap() {
	if (arrOfWaypoints) {
		 PanelMapPlanning.deleteMarkersOutlets();
		 arrOfWaypoints = [];
	 }
	console.log('clearMap');
	console.log(arrOfRoutsObj);
	if (arrOfRoutsObj.length > 0) {
		for (var key in arrOfRoutsObj) {
			arrOfRoutsObj[key].setMap(null);
		}
		arrOfRoutsObj = [];
	}
}

function tracingRouteInPlanin (trip_id) {
	 $.post('app/TOiR_planning.php', {func: 'calculateTrip', id: trip_id}, function(data) {
		 console.log(data);
		 if (data != 0) {			 
			 
			 clearMap();
			 
			 var objData = Ext.decode(data);			 
			 for (var key in objData) {				 
				 GoogleLatLng = new google.maps.LatLng(objData[key][1],objData[key][0]);
				 var tooltip = '<p style="font-size: 8; font-style: italic;"><b>' + objData[key][5] + '</b></p>' +
				 '<p style = "margin-top: -7px">'+ objData[key][6] +'</p>';
				 PanelMapPlanning.addMarker(GoogleLatLng,{cursor:'outlet_'+objData[key][2], icon:'images/record.png'},false,false,null,tooltip);
				 
			 }
			 
			 GoogleLatLng = new google.maps.LatLng(globalOfficeGeoY,globalOfficeGeoX);
			 PanelMapPlanning.addMarker(GoogleLatLng,{cursor:'outlet_main_', /*icon:'images/record.png'*/},false,false,null,'');
			 
			 $.post('app/TOiR_routes.php', {func: 'getRoutePath', trip_id: trip_id}, function(data){
				 var path = eval("(" + data + ")");				 
				 var arrOfPoints = [];
				 for (var key in path) {					
					 //point = {lat: parseFloat(path[key]['k']), lng: parseFloat(path[key]['D'])};
					 //point = {lat: path[key]['k'], lng: path[key]['D']};
					 //point = {lat: path[key]['A'], lng: path[key]['F']};
					 point = {lat: path[key]['lat'], lng: path[key]['lng']};
					 
					 arrOfPoints.push(point);
				 }
				 console.log(arrOfPoints);
				 arrOfRoutsObj[0] =  PanelMapPlanning.addPolyline(arrOfPoints,{strokeColor: '#538929',strokeOpacity: 1.0,strokeWeight: 5} );
				 
			 });			
		 }
	 });	 
}

function сheckAndPaintRoute(trip_id) {	
	$.post('app/TOiR_planning.php', {func: 'checkCulculateTripForRoute', trip_id: trip_id}, function(data) {
		if (data != 0) {
			tracingRouteInPlanin(trip_id);
		} 
	});
}

function autoplan(time) {
	var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
	myMask.show();	
	$.post('app/TOiR_planning.php', {autoplan: true, time: time}, function(data) {		
		var objData = Ext.decode(data);		
		if(objData.succsess == true){			
			$.post('app/TOiR_planning.php', {autoplanInsertTrip: true, time: time}, function(data){
				var objData = Ext.decode(data);
				if (objData.succsess == true) {
					myMask.hide();
					var time = Ext.getCmp('data_of_request_id').getRawValue();    		    			
	    			requestPlanning.load({
           				params: {
           					time: time
           				}
           			});    		    			
	    			TOiR_TripPlanningStore.load({
	        			params: {
	        				time: time
	        			}
	        		});
	    			pointsVisitStore.removeAll();
	    			closeRoute();
	    			clearMap();
					Ext.MessageBox.alert('Cообщение', 'Автопланирование завершено успешно');
					
				} else {
					Ext.MessageBox.alert(all_toir.error, 'Автопланирование не удалось');
					myMask.hide();
				}				
			});
			
			/*Ext.MessageBox.alert(all_toir.attention, 'Маршрут просчитан');
			Ext.getCmp('TOiR_TripPlanningGridId').store.load();
			showRoute( select.get('TripID') );
			reloadTripStore();*/
		}else{
			
			myMask.hide();
			Ext.MessageBox.alert(all_toir.error, objData.message);			
		}		
	});
}