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

	var arrOfRoutsObj = [];
	var arrOfWaypoints = [];

	var globalRouteLinePlan;
	var globalMarkerObjPlan;
	
	
function getFullDate()
{
  year = new Date().getFullYear();
  month = new Date().getMonth();
  month = month + 1;
  date = new Date().getDate();
  if (month < 10)
  {
    month = '0' + month;
  }
  if (date < 10)
  {
    date = '0' + date;
  }
  var FullDate = year + '-' + month + '-' + date;
  return FullDate;
}
	
	
	/*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=tms_trip',
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        }
	});*/
	
	
/* store & model for tms_device --> */	
	Ext.define('model_Device_store', {
	    extend: 'Ext.data.Model',
		fields: ['ID','Login']
	});
	var Device_store = new  Ext.data.Store({   
			//autoLoad: true,	
	        model: 'model_Device_store',
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_facttrip.php?func=tms_device',
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        }
	});
/* store & model for tms_device --> */

/* store & model for tms_project --> */	
	Ext.define('model_Project_store', {
	    extend: 'Ext.data.Model',
		fields: ['ID','Name']
	});
	var Project_store = new  Ext.data.Store({   
			//autoLoad: true,	
	        model: 'model_Project_store',
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_facttrip.php?func=tms_project',
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        }
	});
/* store & model for tms_project --> */

/* store & model for tms_warehouse --> */	
	Ext.define('model_Device_store', {
	    extend: 'Ext.data.Model',
		fields: ['ID','Name']
	});
	var Warehouse_store = new  Ext.data.Store({   
			//autoLoad: true,	
	        model: 'model_Device_store',
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_facttrip.php?func=tms_warehouse',
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        }
	});
/* store & model for tms_warehouse --> */


/* store & model for tms_trip --> */	
	Ext.define('LogistMobile_TripPlanningModelRoutes_factrip', {
	    extend: 'Ext.data.Model',
		fields: ['TripID','Name','Car_ID','Login','TripPrice','Distance','Time','Comments','StartTime','EndTime',
		         'Closed','Project_ID', 'Calculated', 'ColChek', 'is_lock']
	});
	var LogistMobile_TripPlanningStoreRoutes_factrip = new  Ext.data.Store({     
			//autoLoad: true,	
	        model: 'LogistMobile_TripPlanningModelRoutes_factrip',
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_facttrip.php?func=tms_trip',
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        }
	});
/* store & model for tms_trip --> */



/* tms_order --> */
	Ext.define('plan_point', {
	    extend: 'Ext.data.Model',
	    //fields: [ 'Order_ID','CanUseLeaseCar','OriginalAddress','Warehouse_ID','StartTime','EndTime','LoadUnloadTime','ClientCar','Zone_ID','IsInTrip','GeoX','GeoY','Project_ID','Dispatcher_ID','Category_ID','IsPassive','IsGrouped','Date','PictureIDInTrip','SelectedPictureIDInTrip','PictureIDNotInTrip','SelectedPictureIDNotInTrip','LinkAddress','Priority','Name','Code' ]
		fields: ['ID','Client','WarehouseType','Code','OriginalAddress','StartTime','EndTime','LoadUnloadTime','GeoX','GeoY','Name']
	})
	var requestPlanning = new Ext.data.Store({ 
				
	    model: 'plan_point',
	       proxy: {
	          type: 'ajax',
	          url: 'app/LogistMobile_facttrip.php?tms_order=true',
	          reader: {
	            type: 'json',
	            root: 'rows'
	          }
		   }
	});
/* <-- tms_order */

	
/* store & model for tms_trippoint --> */
	Ext.define('bind_factrip', {
	    extend: 'Ext.data.Model',
	    //fields: ['TripPoint_ID','Type','Point_ID','Address','EstimateTime','DurationInPoint','OrderInTrip','Trip_ID','Route','Distance','Time','GeoX','GeoY','Name','WaitTime','LateTime']
		fields: ['ID','Client','WarehouseType','Code','OriginalAddress','StartTime','EndTime','LoadUnloadTime','GeoX','GeoY','Name']
	});
	var pointsVisitStoreRoutes_factrip = new Ext.data.Store({     
		//autoLoad: true,				
	    model: 'bind_factrip',
	       proxy: {
	          type: 'ajax',
	          url: 'app/LogistMobile_facttrip.php?func=tms_trippoint',
	          reader: {
	            type: 'json',
	            root: 'rows'
	          }
		   }
	});
/* store & model for tms_trippoint --> */


function show_FOTOS_facttrip_Window() {
	
	createTripPlanning_logist(0, 'add', true);
	
	
}

function show_LogistMobile_facttrip_Window2( timeprojectcreate ) {
	if (!TOiR_planning_Window) {
		//Xcoord = Xcoord ? Xcoord :40;
	    //Ycoord = Ycoord ? Ycoord :60;  
	    //Wwidth = Wwidth ? Wwidth :1100;  
	    //Wheight = Wheight ? Wheight :600;
	    Xcoord = 40;
	    Ycoord = 60;  
	    Wwidth = 1100;  
	    Wheight = 600;
		
	    PanelMapPlanning = Ext.create('Ext.ux.GMapPanel', {       
	        zoomLevel:11,    	
	        gmapType: 'map',
	        //padding: 170,
	    	id: 'planning_map_panel',        
	        mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
	        setCenter: {
	            lat:'50.5',
	            lng:'30.5'
	        }
	    });
	    
	    
	    
	

			
/* grid for tms_trip --> */			
	    var tripPlanningGrid = new Ext.grid.Panel({
	    	//title: 'Маршруты',
	    	title: plan_toir.routes,
	    	selType: 'rowmodel',
	        columnLines: true,
	        layout: 'fit',
	        id: 'TOiR_TripPlanningGridId',
	        store:  LogistMobile_TripPlanningStoreRoutes_factrip,
	        loadMask: true,
	        border: false,
	        autoScroll: true,
	        viewConfig: {
	        	preserveScrollOnRefresh: true,
	        },	        
	        //height: 213,
	        columns:[/*{
	        	xtype: 'rownumberer',
				width: 30,	
	        }*/
			{
	        	text: 'ID',
	        	dataIndex: 'TripID',
	        	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: plan_toir.the_status_of_the_route, 
	            dataIndex: 'Closed',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	        },
			{
	        	//text: 'Статус маршрута',
	        	text: plan_toir.the_status_of_the_route, 
	            dataIndex: 'Calculated',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	        },
			{        	
	        	//text: 'Название',
	        	text: outlet_toir.title, 
	            dataIndex: 'Name',
	            sortable: true,
	            //flex: 1
	        }, {
	        	//text: 'Устройство',
	        	text: routes_LogistMobile.device,
	            dataIndex: 'Login',
	            sortable: true,
	        },
			{
	        	text: 'Стоимость, грн',
	        	//text: plan_toir.distance_km,
	            dataIndex: 'TripPrice',
	            hidden: true,
	            sortable: true,
	        },
			{
	        	//text: 'Дистанция, км',
	        	text: plan_toir.distance_km,
	            dataIndex: 'Distance',
	            sortable: true,
	        },
			{
	        	text: routes_LogistMobile.starttime,
	        	//text: plan_toir.time_min, 
	            dataIndex: 'StartTime',
	            sortable: true,
	        }, {
	        	text: routes_LogistMobile.endtime,	        	 
	            dataIndex: 'EndTime',
	            sortable: true,
	            width: 120
	        },{
				text: 'Кол-во заявок',
				dataIndex: 'ColChek'
			}, {
				text: 'Блокирован',
				dataIndex: 'is_lock'
			}], 
	        listeners: {
	        	itemclick: function(cmp, records) {
	        		console.log(records);
	        		clearMapLogist();
	        		var time = Ext.getCmp('planning_date_id').getRawValue();
	        		globalUserIDRout = records.get('Login');
					globalFactTripID = records.get('TripID');

					pointsVisitStoreRoutes_factrip.load({
	        			params: {
						userID: globalUserIDRout,
						FactTripID: globalFactTripID,
        				time: time
						}
	        		});
					if (records.get('is_lock') == 'Да') {
						Ext.getCmp('lock_button_id').enable(true);
					} else {
						Ext.getCmp('lock_button_id').disable(true);
					}
					
					if(records.get('Calculated')=='просчитан'){
						showRoute( globalFactTripID );
					}
					
					
	        		}
					
					
					
	        }
	    	
	    });
/* <-- grid for tms_trip */		    
	    
		
		
		
	    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
	        			}
	        		});
	        	}
	        }
	    });
	    
		
		
		
		
/* grid for tms_order --> */
	    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,
	        multiSelect: true,
	        viewConfig: {	        	 
	        	plugins: {
	                ptype: 'gridviewdragdrop',
	                containerScroll: true
	                /*dragGroup: 'requestPlanningGrigGroup',
	                dropGroup: 'southWestPanelPlanningGroup'*/
	            },
	            
	            listeners: {
	                drop: function(node, data, dropRec, dropPosition) {
	                	var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
	                	var time = Ext.getCmp('planning_date_id').getRawValue();	
	                	if (select) {
	                		if (select.get('is_lock') == 'Нет') {
	                			console.log(node);
	    	                	console.log(data);
	    	                	console.log(dropRec);
	    	                	console.log(dropPosition);
	    	                	
	    	                	/*var what_id = data.records[0].id.split('_');
	    	                	console.log(what_id[0]);
	    	                	var where = dropRec.id.split('_');
	    	                	console.log(where);
	    	                	console.log(where[0]);*/
	    	                	
	    	                	
	    	                	
	    	                	//console.log(data);
	    	                	var pointsArr = [];
	                    		for (var i in data.records) {
	                    			pointsArr.push(data.records[i].get('ID'));
	                    		}
	                    		
	    	                	data.records[0].get('ID');
	    	                	var time = Ext.getCmp('planning_date_id').getRawValue();	                	
	    	                	
	    	                	$.post('app/LogistMobile_facttrip.php', {unBindPointFromTrip: true, trip_id: globalFactTripID, 
	    	                		'pointsArr[]': pointsArr}, function (data) {
	    	                			if (parseInt(data) != 0) {	                				
	    		                			   pointsVisitStoreRoutes_factrip.load({
	    					           				params: {
	    					           					FactTripID: globalFactTripID				           					
	    					           				}
	    				           	            });
	    		                			   requestPlanning.load({
	    		            	    				params: {
	    		            	    					time: time
	    		            	    				}
	    		            	    		   });
	    		                			    
	    		                		reloadTripStore();
	    							    clearMapLogist();
	    							
	    	                			} else {
	    	                				Ext.Msg.alert('Внимание!', 'Нельзя убрать из рейса склад начала и склад конца');
	    	                				pointsVisitStoreRoutes_factrip.load({
	    				           				params: {
	    				           					FactTripID: globalFactTripID				           					
	    				           				}
	    			           	            });
	    	                				requestPlanning.load({
	    	            	    				params: {
	    	            	    					time: time
	    	            	    				}
	    	            	    			});
	    	                				reloadTripStore();  
	    	                			}
	    	                			
	    							}); 
	                		} else {
	                			Ext.Msg.alert('Внимание!', 'Для редактирования разблокируйте маршрут!');
	                			
	                			   requestPlanning.load({
		           	    				params: {
		           	    					time: time
		           	    				}
	           	    			   });
	                			   pointsVisitStoreRoutes_factrip.load({
				           				params: {
				           					FactTripID: globalFactTripID				           					
				           				}
			           	            });		                			   
	                			 reloadTripStore();	
	                		}
	                	}	
	                	 
	                	}
	            }
	        },        
	        loadMask: true,
	        border: false,
	        autoScroll: true,        
	        columns:[
			{
	        	text: 'ID', 
	            dataIndex: 'ID',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	            width: 50,	
	        },
			{
	        	text: 'Название',
	        	//text: client_toir.client,
	            dataIndex: 'Name',
	            sortable: true,
	        },
			{
	        	text: 'Код',
	        	//text: plan_toir.status, 
	            dataIndex: 'Code',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	            width: 60
	        },{
	        	text: 'Клиент',
	        	//text: plan_toir.type_of_works, 
	            dataIndex: 'Client',
	            sortable: true,
	        },/*{
	        	text: 'Время приезда',	        	 
	            dataIndex: 'EstimateTime',
	            sortable: true,
	        },*/ {
	        	text: 'Адрес',	        	 
	            dataIndex: 'OriginalAddress',
	            sortable: true,
	            flex: 1
	        },{
	        	text: 'Тип точки',	        	 
	            dataIndex: 'WarehouseType',
	            sortable: true,
	            width: 70
	        }],        
	        listeners: {
	        	itemdblclick: function(cmp, records) {        		
	        		//bindMaster(records.get('id'));        		
	        	},
	        	afterrender: function() {
	        		var time = Ext.getCmp('planning_date_id').getRawValue();
	        		/*TOiR_TripPlanningStore.load({
	        			params: {
	        				time: time
	        			}
	        		});*/
					requestPlanning.load({
	    				params: {
	    					time: time
	    				}
	    			});
					
	        	}
	        	
	        }
	    });
/* <-- grid for tms_order */
		
		
	    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: 'planning_date_id',
	    				startDay: 1,
	    				margin: '5 5 5 5',
	    				name : 'date_create',
	    				value: timeprojectcreate != false ? timeprojectcreate : new Date(),
						listeners: {
	    					select: function( field, value, eOpts ) {
	    						clearMapLogist();
	    						//var time = Ext.getCmp('planning_date_id').getRawValue();
	    						var time = field.rawValue;
								
								var d1 = new Date(time);
								var dbox = d1.getTime();
								var d2 = new Date(getFullDate());
								var dnow = d2.getTime();

								if( dbox < dnow ){
									Ext.getCmp('releaseRoutePlanBtn').setDisabled(true);
									Ext.getCmp('calcRoutePlanBtn').setDisabled(true);
									Ext.getCmp('deleteRoutePlanBtn').setDisabled(true);
									Ext.getCmp('createRoutePlanBtn').setDisabled(true);
									
								}else{
									Ext.getCmp('releaseRoutePlanBtn').setDisabled(false);
									Ext.getCmp('calcRoutePlanBtn').setDisabled(false);
									Ext.getCmp('deleteRoutePlanBtn').setDisabled(false);
									Ext.getCmp('createRoutePlanBtn').setDisabled(false);
									
								}
								
								requestPlanning.load({
            	    				params: {
            	    					time: time
            	    				}
            	    			});	
	    						LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time
				           				}
								});
	    						pointsVisitStoreRoutes_factrip.removeAll();
	    					
							}
	    				}
	    	    		
	    		    	},/* {
	    		    		xtype: 'button',
	    		    		//text: 'Автопланирование',
	    		    		text: plan_toir.autoplanning,
	    		    		margin: '5 5 5 100',
	    		    		handler: function() {
	    		    			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() {	    		    			
	    		    			var time = Ext.getCmp('planning_date_id').getRawValue();
	    		    			
	    		    			requestPlanning.load({
            	    				params: {
            	    					time: time
            	    				}
            	    			});	
	    		    			
	    		    			/*pointsVisitStoreRoutes_factrip.load({
			           				params: {
			           					FactTripID: globalFactTripID				           					
			           				}
		           	            });*/
                				
                				
	    		    			LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time
				           				}
	                		   });
	    		    			pointsVisitStoreRoutes_factrip.removeAll();
	    		    			//Ext.getCmp('visitPoint').getView().refresh();
	    		    			/*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: pointsVisitStoreRoutes_factrip,
	        autoScroll: true,
	        id: 'visitPoint',
	        //height: 250,        
	        //minHeight: 100,
	        //layout: 'fit',
	        multiSelect: true,
	        viewConfig: {	        	
	        	plugins: {
	                ptype: 'gridviewdragdrop',	                
                    containerScroll: true
                    
	                /*dragGroup: 'southWestPanelPlanningGroup',
	                dropGroup: 'requestPlanningGrigGroup'*/
	            },            
	            listeners: {
	                drop: function(node, data, dropRec, dropPosition) {

	                	var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
	                	if (select) {
	                		if (select.get('is_lock') == 'Нет') {
	                			console.log(node);
			                	console.log(data);
			                	console.log(dropRec);
			                	console.log(dropPosition);
			                	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;
		                		
			                	if (what_id[0] == where_id[0]) {
			                		console.log(pointsArr);		                		
			                		$.post('app/LogistMobile_facttrip.php', {removePointPositionInTrip: true, fromPointId: fromPointId,
			                			dropPosition: dropPosition, 'pointsArr[]': pointsArr, trip_id: globalFactTripID}, function(data){
			                				if (parseInt(data) == 0) {
			                					Ext.Msg.alert('Внимание!', 'Расположение складов менять нельзя!');
			                				}
			                				pointsVisitStoreRoutes_factrip.load({
						           				params: {
						           					FactTripID: globalFactTripID				           					
						           				}
					           	            });
			                				requestPlanning.load({
			            	    				params: {
			            	    					time: time
			            	    				}
			            	    			});	
			                				 reloadTripStore();
			                		});
			                		
			                	} else {
			                		
			                		$.post('app/LogistMobile_facttrip.php', {bindPointToTrip: true, 
				                		   trip_id: globalFactTripID, /*order_id: data.records[0].get('ID'),*/
				                		   dropPosition: dropPosition, 'pointsArr[]': pointsArr, fromPointId: fromPointId
			                		}, function (data) {								
			                			   var time = Ext.getCmp('planning_date_id').getRawValue();
			                			   pointsVisitStoreRoutes_factrip.load({
						           				params: {
						           					FactTripID: globalFactTripID				           					
						           				}
					           	            });		                			   
			                			 reloadTripStore();		                			 
				                	});
			                	}
			                	   
	                		} else {
	                			Ext.Msg.alert('Внимание!', 'Для редактирования разблокируйте маршрут!');
	                			   requestPlanning.load({
		           	    				params: {
		           	    					time: time
		           	    				}
	           	    			   });
	                			   pointsVisitStoreRoutes_factrip.load({
				           				params: {
				           					FactTripID: globalFactTripID				           					
				           				}
			           	            });		                			   
	                			 reloadTripStore();	
			                	   //pointsVisitStoreRoutes_factrip.removeAll();
	                			
	                		}
	                		
		                } else {
		                	   Ext.Msg.alert(all_toir.attention, plan_toir.select_a_route);
		                	   requestPlanning.load({
	           	    				params: {
	           	    					time: time
	           	    				}
           	    			   });	
		                	   pointsVisitStoreRoutes_factrip.removeAll();	
		                }
	                	
	                clearMapLogist();
	                }
	            }
	        },
	        // ----
	        
	        loadMask: true,
	        border: false,
	        autoScroll: true,        
	        columns:[
	        {
	        	text: 'ID', 
	            dataIndex: 'ID',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	            width: 50,	
	        },
			{
	        	text: 'Название',
	        	//text: client_toir.client,
	            dataIndex: 'Name',
	            sortable: true,
	        },
			{
	        	text: 'Код',
	        	//text: plan_toir.status, 
	            dataIndex: 'Code',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	            width: 60
	        },{
	        	text: 'Клиент',
	        	//text: plan_toir.type_of_works, 
	            dataIndex: 'Client',
	            sortable: true,
	        },/*{
	        	text: 'Время приезда',	        	 
	            dataIndex: 'EstimateTime',
	            sortable: true,
	        },*/ {
	        	text: 'Адрес',	        	 
	            dataIndex: 'OriginalAddress',
	            sortable: true,
	            flex: 1
	        },{
	        	text: 'Тип точки',	        	 
	            dataIndex: 'WarehouseType',
	            sortable: true,
	            width: 70
	        }
			], 
	        listeners: {
	        	itemdblclick: function(cmp, record) {/*
	        		console.log(record);
	        		
	        		focusOutlet(record);
	        	*/}
	        }       
	    });
	    
		if (!TOiR_planning_Window){
	        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,
				x : 2,
	            y : 29,
	            defaults: {
	                //collapsible: true,
	                //split: true,
	                resizable: true,
	            },
				listeners : {
	            	destroy : function(){
	            		TOiR_planning_Window = null;	
	            	}
	            },
	            items : [{	                
		                layout: 'fit',
					    collapsible: false,
		                region:'center',
		                margins: '5 5 5 0',
		                items:[
		                       PanelMapPlanning
						]
				    }, {
				    	//layout: 'fit',
					    collapsible: false,
		                region:'west',
		                margins: '5 5 5 0',
		                width: '60%',
		                items:[	westPanelPlanning ]			    	
				    }, {
				    	//layout: 'fit',
					    collapsible: false,
		                region:'south',
		                margins: '5 5 5 0',
		                height: 250,
		                layout: 'border',
		                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: 'Создать маршрут', 
										   id: 'createRoutePlanBtn',
			                    		   text: plan_toir.create_route,
			                    		   handler: function() {
			                    			   //createTripPlanning(0, 'add');
			                    			   createTripPlanning_logist(0, 'add', false);
			                    		   }
			                    		   
			                    	   }, {
			                    		   xtype: 'button',
			                    		   margin: '0 0 0 10',
			                    		   hidden: true,
			                    		   //text: 'Удалить маршрут',
			                    		   text: plan_toir.delete_route,
										   id: 'deleteRoutePlanBtn',
			                    		   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() {
			                                   		Ext.getCmp('TOiR_TripPlanningGridId').store.load({
			                                   			params: {
			                                   				time: time
			                                   			}
			                                   		});
			        								Ext.getCmp('TOiR_TripPlanningGridId').getView().refresh();
			        								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,
										   id: 'calcRoutePlanBtn',
			                    		   handler: function() {/*
			                    			   clearMap();
			                    			   calculateTrip();
					                    	 */
											 calculateTripLogist();
											
											 
											 } 
			                    		   
			                    	   },
									   {
			                    		   xtype: 'button',
			                    		   margin: '0 0 0 10',
			                    		   text: 'Выпустить рейсы',
										   id: 'releaseRoutePlanBtn',
			                    		   handler: function(){
											   ReleaseTripLogist();
											   //reloadTripStore();
										   } 
			                    	   }, {
			                    		   xtype: 'button',
			                    		   margin: '0 0 0 10',
			                    		   text: 'Разблокировать',
			                    		   disabled: true,
			                    		   id: 'lock_button_id',
			                    		   handler: function(){
											   //ReleaseTripLogist();
			                    			   unLockTrip(globalFactTripID);
											   //reloadTripStore();
										   }
			                    	   }
									   ]
		                    	   }, 
		                    	   //PBPlanningGrig
		                    	   {
		                    		xtype: 'panel',
		                    		//layout: 'fit',
		                    		anchor: '100% 85%',
		                    		items: [tripPlanningGrid]
		                    	   }]
		                       },
		                       {
		                    	   region:'west',
		                    	   width: '50%',
		                    	   layout: 'fit',
		                    	   items: [             	           
		                    	                               	       
		                    	           southWestPanelPlanning
		                    	           ]
		                       }
						]	
				    }]
	        });
		}      
		TOiR_planning_Window.show(); 
		Ext.getBody().unmask(all.loading);
		
		if(timeprojectcreate){
			var time = timeprojectcreate;
		}else{
			var time = Ext.getCmp('planning_date_id').getRawValue();		
		}
		LogistMobile_TripPlanningStoreRoutes_factrip.load({
			params: { time: time }
		});
	}
}






////////////////
	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 calculateTripLogist(){
		var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
		console.log(select);
		if(select){
			var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
			myMask.show();
			
			//console.log(select.get('Calculated'));
			/*if(select.get('Calculated')=='просчитан'){
			
			$.post('app/LogistMobile_facttrip.php', {'RecalculateTrip':true, Trip_ID: select.get('Trip_ID'), Login: select.get('Login') }, function(data) {
				//if(data){
					myMask.hide();
					Ext.MessageBox.alert(all_toir.attention, 'Маршрут пересчитан');
					Ext.getCmp('TOiR_TripPlanningGridId').store.load();
				//}else{
					//myMask.hide();
					//Ext.MessageBox.alert(all_toir.error, 'Маршрут не пересчитан');
				//}
			});
			
			}else{
			*/
			$.post('app/LogistMobile_facttrip.php', {'CalculateTrip':true, Trip_ID: select.get('TripID'), Login: select.get('Login') }, function(data) {
				//alert('data '+data);
				if(data){
					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, 'Маршрут не просчитан');
					reloadTripStore();
				}
			});
			//}
			
		
		} else {
					Ext.MessageBox.alert(all_toir.error, plan_toir.select_the_route_to_miscalculation);
		}
		
		
	}
	
	function ReleaseTripLogist(){
		var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
		if(select){
			
				if(select.get('Calculated')=='просчитан'){
		
			var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
			myMask.show();
			
			
			$.post('app/LogistMobile_facttrip.php', {'ReleaseTrip':true, Project_ID: select.get('Project_ID'), Login: select.get('Login') }, function(data) {
				if(data){
					myMask.hide();
					Ext.MessageBox.alert(all_toir.attention, 'Рейсы выпущены');
					Ext.getCmp('TOiR_TripPlanningGridId').store.load();
					lockReleaseTrips(select.get('Project_ID'));
					reloadTripStore();
				}else{
					myMask.hide();
					Ext.MessageBox.alert(all_toir.error, 'Рейсы не выпущены');
					reloadTripStore();
				}
			});

				}else{ Ext.MessageBox.alert(all_toir.error, 'Нельзя выпустить непросчитаные рейсы');  }

		
		} else {
			Ext.MessageBox.alert(all_toir.error, plan_toir.select_the_route_to_miscalculation);
		}	
	}
	
	
	
	
	
	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);
					 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);
					 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(directionsDisplayPlan.directions.routes[0].overview_path);
								globalRouteAjax.push(directionsDisplayPlan.directions.routes[0].overview_path);
								arrOfRoutsObj.push(directionsDisplayPlan);
								directionsDisplayPlan.setMap(PanelMapPlanning.getMap());
								var route = response.routes[0];
							      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);
						 for (var key in globalRouteAjax) {
							 for (var key2 in globalRouteAjax[key]) {
								 arrOfRoutPoints.push(globalRouteAjax[key][key2]);
							 }
						 }
						 
						 globalRouteAjax = Ext.encode(arrOfRoutPoints);
						 console.log(globalRouteAjax);
						 totalTime = motionTime + 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
						        			}
						        		});
									});
								}
							});
					 }, 500); 
					 
					 
					 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) {
		$.post('app/TOiR_planning.php', {func: 'bindRequestToTrip', request_id: request_id, trip_id: trip_id}, 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) {
			 
			 if (data != 0) {			 
				 
				 clearMap();
				 
				 var objData = Ext.decode(data);			 
				 for (var key in objData) {
					 console.log(objData[key][0]);
					 GoogleLatLng = new google.maps.LatLng(objData[key][1],objData[key][0]);
					 PanelMapPlanning.addMarker(GoogleLatLng,{cursor:'outlet_'+objData[key][2], icon:'images/record.png'},false,false,null,'');
					 
				 }
				 
				 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'])};
						 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);
			} 
		});
	}

//my functions
	
	
	
	
	
	
	
	
/*	
	function createTripPlanning_logist(trip_id, flag) {
		
		var time = Ext.getCmp('planning_date_id').getRawValue();
		
		Device_store.load();
		//Project_store.load();
		Project_store.load({
			params: { time: time }
		});
		Warehouse_store.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();	
		//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: Device_store, //TOiR_UsersPlanningTripStore,
			        	 allowBlank: false,
			        	 margin: '5 5 5 5',
			        	 editable: false,
			        	 labelWidth: 150,
			        	 id: 'bind_master_id',
			        	 valueField: 'Login',
			        	 displayField: 'Login',
			        	 name: 'trip_master',
			        	 queryMode: 'local',
			         },{
			        	 xtype: 'combo',
			        	 fieldLabel: 'Проект',
			        	 store: Project_store,
			        	 allowBlank: false,
			        	 margin: '5 5 5 5',
			        	 editable: false,
						 labelWidth: 150,
			        	 id: 'bind_project_id',
			        	 valueField: 'ID',
			        	 displayField: 'Name',
			        	 name: 'trip_project',
			        	 queryMode: 'local',
			         },{
			        	 xtype: 'combo',
			        	 fieldLabel: 'Склад 1',
			        	 store: Warehouse_store,
			        	 allowBlank: false,
						 editable: false,
			        	 margin: '5 5 5 5',
			        	 labelWidth: 150,
			        	 id: 'bind_warehouse1_id',
			        	 valueField: 'ID',
			        	 displayField: 'Name',
			        	 name: 'trip_warehouse1',
			        	 queryMode: 'local',
			         },{
			        	 xtype: 'combo',
			        	 fieldLabel: 'Склад 2',
			        	 store: Warehouse_store,
			        	 allowBlank: false,
						 editable: false,
			        	 margin: '5 5 5 5',
			        	 labelWidth: 150,
			        	 id: 'bind_warehouse2_id',
			        	 valueField: 'ID',
			        	 displayField: 'Name',
			        	 name: 'trip_warehouse2',
			        	 queryMode: 'local',
			         }, {
			        	xtype: 'container',
			        	layout: 'hbox',
			        	hidden: true,
			        	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 form = Ext.getCmp('trip_form_id').getForm();
							var time = Ext.getCmp('planning_date_id').getRawValue();							
							var date = Ext.getCmp('planning_date_id').getRawValue();
							
							if(form.isValid()){
							form.submit({
								//waitMsg:'Идет отправка...',
								waitMsg: all_toir.loading,
	                            url: 'app/LogistMobile_facttrip.php',							
								wait: true,
								scope: this,
								method: 'post',							
								params: {addTrip: true, 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();                          	
	                            }
								
							});
							}	
							
						}
						
		         }, {
	                 //text: 'Отмена',
	                 text: all_toir.cancel,
					 iconCls:'cancel',
	                 handler: function(){
	                	 createTripPlanningWindow.destroy();	                	
	                 }
				}]
			 });          
		}
		createTripPlanningWindow.show();
	
	}	
*/	
	
	
	//+++
	function createTripPlanning_logist(trip_id, flag, flag2) {
		
		//alert(flag2);
		
		if( Ext.getCmp('planning_date_id') ){
			var time = Ext.getCmp('planning_date_id').getRawValue();
		}else{
			var time = getFullDate();
		}
		
		$.post('app/LogistMobile_facttrip.php', { checkProjectExist:true, time:time }, function(data){
		
		var res = Ext.decode(data);
		var item;
		var width = 400;
		var height = 300;
		
		//alert(res[0].RESULT);
		
if(flag2 && res[0].RESULT > 0){
	show_LogistMobile_facttrip_Window2( false );
}else{		
		
		if(res[0].RESULT > 0){

		//Device_store.load();
		Device_store.load({
			params: { time: time }
		});
		
		//Project_store.load();
		Project_store.load({
			params: { time: time }
		});
		
		Warehouse_store.load();
		
		if (flag == 'edit') {
			//var title = 'Редактировать маршрут';
			var title = plan_toir.edit_route;
		} else {		
			//var title = 'Создать маршрут';
			var title = plan_toir.create_route;
			globalCount++;
		}
		
		
		
		item = [
					{
		        	 xtype: 'form',
		        	 //layout: 'fit',
		        	 width : width,
			         height : height,
			         id: 'trip_form_id1',
		        	 items: [
					 {
		        		 xtype: 'textfield',
		        		 margin: '5 5 5 5',
			        	 labelWidth: 150,
			        	 //fieldLabel: 'Название маршрута',
			        	 fieldLabel: plan_toir.name_of_the_route,
						 allowBlank: false,
			        	 name: 'trip_name',
			        	 value: plan_toir.route_ + globalCount
		        	 },{
			        	 xtype: 'combo',
			        	 fieldLabel: 'Выберите устройство',
			        	 //fieldLabel: plan_toir.select_a_team,
			        	 store: Device_store, //TOiR_UsersPlanningTripStore,
			        	 allowBlank: false,
			        	 margin: '5 5 5 5',
			        	 labelWidth: 150,
						 editable: false,
			        	 id: 'bind_master_id',
			        	 valueField: 'Login',
			        	 displayField: 'Login',
			        	 name: 'trip_master',
			        	 queryMode: 'local',
			         },{
			        	 xtype: 'combo',
			        	 fieldLabel: 'Проект',
			        	 store: Project_store,
			        	 allowBlank: false,
			        	 margin: '5 5 5 5',
			        	 labelWidth: 150,
			        	 id: 'bind_project_id',
			        	 valueField: 'ID',
			        	 displayField: 'Name',
			        	 editable: false,
						 name: 'trip_project',
			        	 queryMode: 'local',
						 listeners: {
							afterrender: function(combo) {
							//var recordSelected = combo.getStore().getAt(0);
							//console.log(recordSelected);
							//combo.setValue(recordSelected.get('ID'));
							}
							}
			         },{
			        	 xtype: 'combo',
			        	 fieldLabel: 'Склад 1',
			        	 store: Warehouse_store,
			        	 allowBlank: false,
			        	 margin: '5 5 5 5',
			        	 labelWidth: 150,
						 editable: false,
			        	 id: 'bind_warehouse1_id',
			        	 valueField: 'ID',
			        	 displayField: 'Name',
			        	 name: 'trip_warehouse1',
			        	 queryMode: 'local',
			         },{
			        	 xtype: 'combo',
			        	 fieldLabel: 'Склад 2',
			        	 store: Warehouse_store,
			        	 allowBlank: false,
			        	 margin: '5 5 5 5',
			        	 labelWidth: 150,
						 editable: false,
			        	 id: 'bind_warehouse2_id',
			        	 valueField: 'ID',
			        	 displayField: 'Name',
			        	 name: 'trip_warehouse2',
			        	 queryMode: 'local',
			         }, {
			        	xtype: 'container',
			        	layout: 'hbox',
			        	hidden: true,
			        	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,
						 //width: '100%', 
			        	 //fieldLabel: 'Комментарии',
			        	 fieldLabel: plan_toir.comments,
			        	 name: 'trip_comments'
			         }
					 ]
		         }
				]
        
	
		

		
	
		}else{
			//alert('create project');
			
			width = 300;
			height = 150;
			
			item = [
				{
		        	 xtype: 'form',
		        	 //layout: 'fit',
		        	 width : width,
			         height : height,
			         id: 'trip_form_id2',
		        	 items: [
						{
		        		 xtype: 'textfield',
			        	 labelWidth: 110,
						 margin: '5 5 5 5',
						 fieldLabel: 'Название проекта',
						 allowBlank: false,
						 name: 'name_project'
						},
						{
	    	    		xtype: 'datefield',
	    				fieldLabel: 'Дата проекта',
						name: 'date_project',
						id: 'date_project_crwin',
	    				format: 'Y-m-d',
						labelWidth: 110,
						editable: false,
						minValue: new Date(),
						allowBlank: false,
	    				altFormats: 'Y-m-d',
	    				startDay: 1,
	    				margin: '5 5 5 5',
	    				//value: new Date()
						value: time,
						listeners: {
	    					select: function( field, value, eOpts ) {
								//console.log(field.rawValue);
								$.post('app/LogistMobile_facttrip.php', { checkProjectExist:true, time:field.rawValue }, function(data){
										var res = Ext.decode(data);
										if(res[0].RESULT > 0){
											Ext.MessageBox.alert(all_toir.attention,'На '+field.rawValue+' проект уже создан');
											field.setValue(new Date());
										}
								});
							}
						}
						}
					 ]
				}
			];
		}
		
		
		
		
		
		if (!createTripPlanningWindow) {	 
			createTripPlanningWindow = new Ext.Window({
		         layout : 'border',
		         title : title,
		         closeAction : 'destroy',
		         width : width,
		         height : height,
		         modal: true,
		         //minimizable: true,
					constrainHeader: true,
		         //maximizable:true,
		         //x : parseInt(Xcoord),
		         //y : parseInt(Ycoord),
					listeners : {
						destroy : function(){
							createTripPlanningWindow = null;						
		         	}
		         },
		         items: item,
		         buttons: [{
		        	 
						//text:'Сохранить',
						text: all_toir.save,
						//id:'buttonUploads',
						iconCls:'save',
						handler: function() {
							
							
							if(res[0].RESULT > 0){
								var form = Ext.getCmp('trip_form_id1').getForm();
								var time = Ext.getCmp('planning_date_id').getRawValue();							
								var date = Ext.getCmp('planning_date_id').getRawValue();
								if(form.isValid()){
								form.submit({
								//waitMsg:'Идет отправка...',
								waitMsg: all_toir.loading,
	                            url: 'app/LogistMobile_facttrip.php',							
								wait: true,
								scope: this,
								method: 'post',							
								params: { addTrip: true, date: date, flag: flag, trip_id: trip_id },
	                            success: function(fp, o){
	                            	Ext.getCmp('TOiR_TripPlanningGridId').store.load({
	                            		params: {time: time} 
	                            	});                       	
	                            	createTripPlanningWindow.destroy();                          	
	                            }
								});
								}
							}else{
								var form = Ext.getCmp('trip_form_id2').getForm();
								var dateprojectcrwin = Ext.getCmp('date_project_crwin').getRawValue();
								if(form.isValid()){
								form.submit({
								//waitMsg:'Идет отправка...',
								waitMsg: all_toir.loading,
	                            url: 'app/LogistMobile_facttrip.php',							
								wait: true,
								//scope: this,
								method: 'post',							
								params: { addProject: true},
	                            success: function(fp, o){                  	
									//alert('success');
									//console.log(o);
									createTripPlanningWindow.destroy();
									if(flag2){
										show_LogistMobile_facttrip_Window2( dateprojectcrwin );
									}else{
										createTripPlanning_logist(0, 'add', false);
									}
	                            },
								failure: function(fp, o){
									//console.log(o);
									Ext.MessageBox.alert(all_toir.error,'Проект не создан');
									
									//console.log(o);
								}
								});
								}
							}
						}
		         }, {
	                 //text: 'Отмена',
	                 text: all_toir.cancel,
					 iconCls:'cancel',
	                 handler: function(){
	                	 createTripPlanningWindow.destroy();	                	
	                 }
				}]
			});
		}
		
			createTripPlanningWindow.show();
}

	});
		
	
	}	
//+++
	
	
	
	
	function showRoute( TripID ){
		
		$.post('app/LogistMobile_facttrip.php', {func: 'getRoutePoint', TripID: TripID}, function(data) {
			console.log(data);
			if(data || data!=""){		 
			 //alert(data);
			 var objData = Ext.decode(data);
			 //var arrOfWaypoints = [];
			 
			 console.log( globalMarkerObjPlan );
			 if (globalMarkerObjPlan) {
				for (var key in globalMarkerObjPlan){
					globalMarkerObjPlan[key].setMap(null);
				}
			}
			 
			 var arrOfMarkers = [];
			 for (var key in objData) {
				 console.log(objData[key]['GeoX']+' '+objData[key]['GeoY']);
				 GoogleLatLng = new google.maps.LatLng(objData[key]['GeoY'],objData[key]['GeoX']);
				 var marker = PanelMapPlanning.addMarker(GoogleLatLng,{cursor:'outlet_'+objData[key]['Id'], icon:'images/record.png'},false,false,null,'');
				 arrOfMarkers.push(marker);
			 }
			 
			 globalMarkerObjPlan = arrOfMarkers;
			 //console.log(globalMarkerObjPlan);
				
			 
			 
			
		
		
		$.post('app/LogistMobile_facttrip.php', {func: 'getRoutePath', TripID: TripID}, function(data){				 
					//console.log(data);
					if(data || data!=""){
					//alert(data);
					//data = data.substring(11,data.length - 1);
					//var objData = Ext.decode(data);
					var arrPol = data.split(',');
					var flightPlanCoordinates = [];
					//for (var key in objData) {
						//alert(objData[key]);
						//var arrPol = objData[key].split(',');
						arrPol = arrPol.splice(0, arrPol.length-1);
						for (key in arrPol)
						{
						var arrPolLoc = arrPol[key].split(' ');
						var LocY = arrPolLoc[0];
						var LocX = arrPolLoc[1];
						point = {lat: parseFloat(LocX), lng: parseFloat(LocY)};
						flightPlanCoordinates.push(point);
						}
					//}
					if (globalRouteLinePlan) {
						globalRouteLinePlan.setMap(null);		
					}
					globalRouteLinePlan = PanelMapPlanning.addPolyline(flightPlanCoordinates,{strokeColor: '#538929',strokeOpacity: 1.0,strokeWeight: 3} );
					}
		});
		
		
		}
		});
		
	}
	
	function clearMapLogist(){
			if (globalMarkerObjPlan) {
				for (var key in globalMarkerObjPlan){
					globalMarkerObjPlan[key].setMap(null);
				}
			}
			if (globalRouteLinePlan) {
				globalRouteLinePlan.setMap(null);		
			}
	}
	
	function resetCalculate() {
		 var time = Ext.getCmp('planning_date_id').getRawValue();
		$.post('app/LogistMobile_facttrip.php', {resetCalculate: true}, function(data){
			Ext.getCmp('TOiR_TripPlanningGridId').store.load({
				   params: {
					   time: time
					}
			   });
			Ext.getCmp('TOiR_TripPlanningGridId').getSelectionModel().getLastSelected();
			   //Ext.getCmp('TOiR_TripPlanningGridId').getView().refresh();
		});
		
	}
	
function reloadTripStore() {
		   var time = Ext.getCmp('planning_date_id').getRawValue();
		   var selectionModel = Ext.getCmp('TOiR_TripPlanningGridId').getSelectionModel();		                				 
		   var selectedRecord = selectionModel.getSelection()[0];
		   var selectedIdx = Ext.getCmp('TOiR_TripPlanningGridId').store.indexOfId(selectedRecord.data.id);

		   LogistMobile_TripPlanningStoreRoutes_factrip.load({
			   params: {
				   time: time
 				}
		   });
		   setTimeout(function() {		                				  
				 Ext.getCmp('TOiR_TripPlanningGridId').getSelectionModel().select(selectedIdx);		                				 
			  }, 500);
}

function unLockTrip(trip_id){	
	$.post('app/LogistMobile_facttrip.php', {unLockTrip: true, trip_id: trip_id}, function (data) {
		Ext.Msg.alert('Сообщение', 'Маршрут разблокирован');
		reloadTripStore();
	});
}
function lockReleaseTrips(projectId) {
	$.post('app/LogistMobile_facttrip.php', {lockTrips: true, projectId: projectId}, function (data) {
		
	});
}
