    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;
	var globalMarkerObjOrder;
	
	var createChangeCarWindow = null;
	
	var idorders = new Array;
	var recorders = new Array;
	var myMaskGlob;
	
	var LogistMobile_carsnapshot_Window = null;
	var LogistMobile_VariableData_Window = null;
	
	var Uploads_Window_ImportTrip = null;
	
	var LogistMobile_ManualPlanning_Window = null;

	var stateInfoWindowManualPlanning = true;
	
//обработка некоректного JSON
function check_result_message(json){
	var reg = new RegExp('\\."',"g");
	var reg2 = new RegExp('\\.}',"g");
	json = json.replace(reg,',"');
	json = json.replace(reg2,'}');
							
	var obj = Ext.decode(json);
	if(lang=='ru'){
		message = obj.ru;
	}else if(lang=='en'){
		message = obj.en;
	}else if(lang=='ua'){
		message = obj.ua;
	}else{
		message = obj.data[0].result_message;
	}
	return message;
}							
					
// --- check web task status with progress --->
function checkwebtaskprogress(id,fact,funcupdate){ //funcupdate2,funcupdate2param

		var me = this,
        i = 0,
        fn;

        MessageBoxProgress = Ext.MessageBox.show({
			//title: 'Задача в обработке',
            title: routes_LogistMobile.taskprogress,
			//msg: 'Loading items...',
            progressText: all.loading+'...',
            width:300,
            progress:true,
            closable:false,
            //animateTarget: btn
        });

        // Fake progress fn
        fn = function() {
            //var id = 8;
			$.post("app/LogistMobile_checkwebtaskprogress.php",{id:id}, function(data){
				//alert(data);
				var obj = Ext.decode(data);
				//console.log(obj);
				if(obj.success == true){
				//alert(obj.data.length);
				if(obj.data.length > 0){
					if(obj.data[0].in_progress == 1){
						//Ext.MessageBox.hide();
						MessageBoxProgress.hide();
						MessageBoxProgress = null;
						if(!obj.data[0].result_message || obj.data[0].result_message=='null'){
							//alert(funcupdate);
							if(funcupdate){
								eval(funcupdate)();
							}
							Ext.MessageBox.alert(all_toir.attention, routes_LogistMobile.taskprogresscomplete);
						}else{
							
							//if(funcupdate2){
							//	eval(funcupdate2)(obj.data[0].result_message,funcupdate2param);
							//}else{
								var result_message = check_result_message(obj.data[0].result_message);
								Ext.MessageBox.alert(all_toir.attention, result_message);
							//}
						}
						//alert('fact - '+fact);
						if(fact){
							updateDetails();
						}
					}else if(obj.data[0].in_progress == -1){
						if(!obj.data[0].result_message || obj.data[0].result_message=='null'){
							Ext.MessageBox.alert(all_toir.attention, routes_LogistMobile.taskprogressnotcomplete);
						}else{
							var result_message = check_result_message(obj.data[0].result_message);
							Ext.MessageBox.alert(all_toir.attention, result_message);
						}
					}else{
						var val = obj.data[0].progress_percent / 100;
						Ext.MessageBox.updateProgress(val, obj.data[0].progress_percent + '%');
						setTimeout(fn, 1000);
					}
				}else{
					//Ext.MessageBox.hide();
					MessageBoxProgress.hide();
					MessageBoxProgress = null;
					Ext.MessageBox.alert(all_toir.error, obj.message);
				}
				}else{
					//Ext.MessageBox.hide();
					MessageBoxProgress.hide();
					MessageBoxProgress = null;
					Ext.MessageBox.alert(all_toir.error, obj.message);
				}
				//updateDetails();
			}).fail(function(){});
			
			/*++i;
            if (i === 12) {
                
				Ext.MessageBox.hide();
            
			} else {
                var val = i / 11;
                Ext.MessageBox.updateProgress(val, Math.round(100 * val) + '% completed');
                setTimeout(fn, 2000);
            }*/
			
        };
        setTimeout(fn, 1000);
	
	return fn;
}
// <--- check web task status with progress ---
	
	
// --- get full date y-m-d --->
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;
}
// <--- get full date y-m-d ---


// --- is point in polygon --->
function IsPointInConvexPolygon(i_xp, i_yp, i_coords){
            var result = false;
            var i = 0;

            if (i_coords.length == 0) return false;
            do
            {
                //console.log(i_coords[i].Y+' - '+i_coords[i].X);
				if (!((i_yp > i_coords[i].Y) ^ (i_yp <= i_coords[i + 1].Y)))
                {
                    if (i_xp - i_coords[i].X < (i_yp - i_coords[i].Y) * (i_coords[i + 1].X - i_coords[i].X) / (i_coords[i + 1].Y - i_coords[i].Y))
                    {
                        result = !result;
                    }
                }
                i++;
            }
            while (i < i_coords.length - 1);
            //i_coords.RemoveAt(i_coords.Count - 1);
            
			return result;
}
// <--- is point in polygon ---


// --- orders on map --->
function calculateGroupOrders(coordinates,event,listenerDrawingManagerIn){
	
	var result = false;
	//var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
	//myMask.show();
	
	if(coordinates){
		idorders = [];
		recorders = [];
		coordinates.push(coordinates[0]);
		console.log(coordinates);
		
		requestPlanning.each(function(record){
			//поиск попаданий точки в полигон
			var res = IsPointInConvexPolygon(record.get('GeoX'), record.get('GeoY'), coordinates);
			if(res){
				//console.log('record');
				//console.log(record);
				//console.log(record.getId());
				
				idorders.push(record.get('ID'));
				recorders.push(record);
				//Ext.getCmp('requestPlanningGrigId').getView().select(record);
				Ext.getCmp('requestPlanningGrigId').getSelectionModel().select(record, true);
			}
		});
		
		console.log('recorders');
		console.log(recorders);
		
		if(idorders.length>0){
			listenerDrawingManagerIn.setDrawingMode(null);
			listenerDrawingManagerIn.setMap(null);
			event.setMap(null);
			
			if (globalMarkerObjOrder) {
			for (var key in globalMarkerObjOrder){
				globalMarkerObjOrder[key].setMap(null);
			}
			globalMarkerObjOrder = [];
			}
			if(Ext.getCmp('buttonCheckOrdersOnMap').pressed == true){
				Ext.getCmp('buttonCheckOrdersOnMap').toggle(false);
			}
			
			
		}else{
			Ext.Msg.alert(all_toir.attention, plan_toir.no_points_grouped);
			event.setMap(null);
		}
		
	}else{ result = false; }
	
	//myMask.hide();
	myMaskGlob.hide();
	return result;
}
// <--- orders on map ---
	

// --- update window with all grids --->
function updateDetails(){
	
								var time = Ext.getCmp('planning_date_id').getRawValue();
	    		    			//var project = Ext.getCmp('project_planning_id').getRawValue();
								
								pointsVisitStoreRoutes_factrip.removeAll();
								LogistMobile_TripPlanningStoreRoutes_factrip.removeAll();
								requestPlanning.removeAll();
								
								Ext.getCmp('project_planning_id').store.load({
									params: {
									time: time,
									}
								});
								
								var project = Ext.getCmp('project_planning_id').getValue();
								
								if(project){
	    		    			requestPlanning.load({
            	    				params: {
            	    					time: time,
										project: project
            	    				}
            	    			});	
	    		    			
								LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time,
										   project: project
				           				}
								});
								
								}
								
								clearMapLogist();
}
// <--- update window with all grids ---	
	

function checkImeiBeforeAutoplan(type){
	var project = Ext.getCmp('project_planning_id').getValue();
	
	$.post('app/LogistMobile_facttrip.php', {checkImeiBeforeAutoplan: true, project:project}, function(data){					
	if(data){
		var obj = Ext.decode(data);
	}
	if(obj.length > 0){
		Ext.MessageBox.confirm(all_toir.attention, all_LogistMobile.checkImeiAutoplan, function(btn){
		if(btn=='yes'){
			
						Ext.Ajax.request({
						url: 'app/LogistMobile_facttrip.php',
						method: 'POST',
						params: { blockcarsnapshot:true, 'login[]':obj, checked:true, project:project },
						success: function(response) {
							//console.log(response);
						},
						failure: function(response) {
							//console.log(response);
							Ext.MessageBox.alert(all_toir.error, '');
						}
						});
			
						autoplanTrip(type);
		}
		});
	}else{
		autoplanTrip(type);
	}
	});
}
	

function autoplanTrip(type){
	
								var time = Ext.getCmp('planning_date_id').getRawValue();
								var project = Ext.getCmp('project_planning_id').getValue();
								var d1 = new Date(time);
								var dbox = d1.getTime();
								var d2 = new Date(getFullDate());
								var dnow = d2.getTime();
								
								//console.log(dbox);
								//console.log(dnow);


								if( requestPlanning.getTotalCount()!=0 ){

								if( dbox >= dnow){
									var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
									myMask.show();
									//Ext.MessageBox.alert(all_toir.attention,'На данный момент этот функционал недоступен');
									$.post('app/LogistMobile_facttrip.php', {AutoplanTrip: true, time: time, project:project, type:type}, function(data) {
										//alert('data '+data);
										if(data){
											var obj = Ext.decode(data);
											if(obj.success == true){
												myMask.hide();
												var result = checkwebtaskprogress(obj.message,true);
												//alert('result '+result);
											}else{
												myMask.hide();
												Ext.MessageBox.alert(all_toir.error, obj.message);
											}
				
											
											/*myMask.hide();
											Ext.MessageBox.alert(all_toir.attention, plan_toir.autoplanning_formed);
											requestPlanning.load({
												params: {
													time: time,
													project: project
												}
											});
											LogistMobile_TripPlanningStoreRoutes_factrip.load({
												params: {
													time: time,
													project: project
												}
											});
											pointsVisitStoreRoutes_factrip.removeAll();
											*/
										}else{
											Ext.MessageBox.alert(all_toir.error, plan_toir.autoplanning_failed);
											myMask.hide();
										}
									});
									
								}else{
									Ext.MessageBox.alert(all_toir.error, plan_toir.autoplanning_less_current_date);
								}
								
								}else{
									Ext.MessageBox.alert(all_toir.error, plan_toir.applications_for_autoplanning);
								}
				
	
	
}

	
	
	
	
	
	/*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'
	          }
	        }
	});
	Ext.define('model_Device_store_change', {
	    extend: 'Ext.data.Model',
		fields: ['ID','Login','CarId']
	});
	var Device_store_change = new  Ext.data.Store({   
			//autoLoad: true,	
	        model: 'model_Device_store_change',
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_facttrip.php?func=tms_device_change',
	          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','Code']
	});
	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: ['TID','Name','Car_ID','Login','Login2','TripPrice','Distance','Time','Comments','StartTime','StartTime2','EndTime', 'Closed','Closed2','Closed3','Project_ID', 'Calculated','Calculated2', 'ColChek', 'is_lock', 'is_lock2', 'lock_nav', {name: 'indoor', type: 'bool'}, 'WalkerNum', 'Volume', 'Weight', 'dateRelease']
	});
	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', 'CustomInt', 'Priority', 'CustomString1','CustomString2','CustomString3','CustomString4','CustomString5','CustomString6','CustomString7','CustomString8', 'ZoneName']
	});
	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','OrderInTrip','OrderInTrip2','EstimateTime','Duration','Distance','CustomInt','Priority','CustomString1','CustomString2','CustomString3','CustomString4','CustomString5','CustomString6','CustomString7','CustomString8','PointState','Trip_ID','DurationInPoint','WarehouseType2']
	});
	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 completedCheckCalculateTrip(){
					
					var arrayTripId=[];
					Ext.getCmp('TOiR_TripPlanningGridId').store.each(function(record){
						if(record.get('indoor') == true){
							arrayTripId.push(record.get('TID'));
						}					
					});
					
					reloadTripStore();
					showRoute( arrayTripId[0] );
					var time = Ext.getCmp('planning_date_id').getRawValue();
					var project = Ext.getCmp('project_planning_id').getValue();
					pointsVisitStoreRoutes_factrip.load({
	    				params: {
	    				//FactTripID: select.get('TID')
						FactTripID: arrayTripId[0]					
	    				}
					});
}

function completedCheckReleaseTrip(){
					var Project_ID = Ext.getCmp('project_planning_id').getValue();
					lockReleaseTrips(Project_ID);
					reloadTripStore();
}

function completedCheckAddProject(){
					
					createTripPlanningWindow.destroy();
					//alert('flag22 - '+flag22);
					//if(flag22){
					//	show_LogistMobile_facttrip_Window2( dateprojectcrwin );
					//}else{
					//	createTripPlanning_logist(0, 'add', false);
					//}
					
					$.post("app/LogistMobile_facttrip.php",{'create_project_to_users':true}, function(data){			
						//alert(data);
					});
					
}									


/* main window --> */
function show_LogistMobile_facttrip_Window() {
	
	
	//alert(globalUserRights.manual_planning);
	
	// проверка созданого проекта, создание проекта при старте если его нет 
	//createTripPlanning_logist(0, 'add', true);
	
	// открытие окна планирования 05-01-2016
	show_LogistMobile_facttrip_Window2(false);
		
}

function checkwebtaskonload(){
	
	var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
	myMask.show();
	
	$.post("app/LogistMobile_checkwebtaskprogress.php",{}, function(data){
		var obj = Ext.decode(data);
		if(obj.success == true){
		if(obj.data.length > 0){
			myMask.hide();
			checkwebtaskprogress(obj.data[0].id,true);
		}else{
			myMask.hide();
		}
		}else{
			myMask.hide();
		}
	});
	
	/*$.post("app/LogistMobile_checkwebtaskonload.php",{}, function(data){
			if(data == 1 || data == 'true'){
		      Ext.MessageBox.alert(all_toir.attention, 'Задача выполнена');
		    }else if(data != 'ok'){
			  Ext.MessageBox.alert(all_toir.error, data);  
			}         
			updateDetails();
			myMask.hide();
	});
	*/
	
	/*Ext.Ajax.request({
		url: 'app/LogistMobile_checkwebtaskonload.php',
		method: 'POST',
		wait:true,
		//params: {"func":""},
		success: function(response) {
			var data = response.responseText;
			if(data == 1 || data == 'true'){
		      Ext.MessageBox.alert(all_toir.attention, 'Задача выполнена');
		    }else if(data != 'ok'){
			  Ext.MessageBox.alert(all_toir.error, data);  
			}         
		    myMask.hide();
		},
		failure: function(response) {
			myMask.hide();
		}
	});*/
	
}






function show_LogistMobile_facttrip_Window2( timeprojectcreate ) {
	
	//alert('show_LogistMobile_facttrip_Window2 timeprojectcreate '+timeprojectcreate);
	
	/*interval_update_status_route = setInterval(function() {
		update_status_route();
		update_status_point();
	}, 22000);*/
	
	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;
		
	var lot = getCookie("MapCenter_latitude");
	var lat = getCookie("MapCenter_longitude");
	
	//alert(lat+' - '+lot);
	
	PanelMapPlanning = Ext.create('Ext.ux.GMapPanel', {       
	        zoomLevel:11,    	
	        gmapType: 'map',
	        //padding: 170,
	    	id: 'planning_map_panel',        
	        mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
	        setCenter: {
	            lat:lat,
	            lng:lot
	        }
	    });
	    
	    
	    
	

			
/* 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,	
	        }*/
			{
				xtype: 'checkcolumn', dataIndex: 'indoor', width: 35, hideable: false, sortable: false
			},
			{
	        	text: 'ID',
	        	dataIndex: 'TID',
	        	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: 'Cтатус Фактический',
				width: 40,
				dataIndex: 'Closed3',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true
	        },
			{
	        	//text: 'Статус рейса',
	        	text: plan_toir.the_status_of_the_trip,
	            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: 'Экс. в Nav',
				width: 65,
	            dataIndex: 'lock_nav',
	            sortable: true,
				hidden: true,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID == 74) {
						//if (globalClientID == 74 || globalClientID == 87) {	            			
	            			col.show();
	            		}
	            	}
	            }

	        },
			{        	
	        	//text: 'Название',
	        	text: plan_toir.title, 
	            dataIndex: 'Name',
	            sortable: true,
	            //flex: 1
	        },
			{
				//text: 'Кол-во заявок',
				text: plan_toir.quantity_applications,
				dataIndex: 'ColChek'
			},
			{
	        	//text: 'Устройство',
	        	text: routes_LogistMobile.device,
	            dataIndex: 'Login',
	            sortable: true
	        },
			{
	        	//text: 'Стоимость, грн',
	        	text: routes_LogistMobile.cost+', '+routes_LogistMobile.cash,
	            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: 'Блокирован',
				text: plan_toir.locked,
				dataIndex: 'is_lock2'
			},{
				//text: 'Вес, %',
				text: routes_LogistMobile.weight,
				dataIndex: 'Weight'
			},{
				//text: 'Объём, %',
				text: routes_LogistMobile.volume,
				dataIndex: 'Volume'
			},{
	        	//text: 'Время выпуска',
	        	text: routes_LogistMobile.dateRelease,
	            dataIndex: 'dateRelease',
	        }], 
	        listeners: {
	        	itemclick: function(cmp, records) {
	        		console.log(records);
	        		clearMapLogist();
	        		var time = Ext.getCmp('planning_date_id').getRawValue();
	        		globalUserIDRout = records.get('Login2');
					globalFactTripID = records.get('TID');
					
					
					
			var selectionModel = Ext.getCmp('TOiR_TripPlanningGridId').getSelectionModel();		                				 
			var selectedRecord = selectionModel.getSelection()[0];
			globalSelectedIndex = Ext.getCmp('TOiR_TripPlanningGridId').store.indexOfId(selectedRecord.data.id);

		   
		   
					
					pointsVisitStoreRoutes_factrip.load({
	        			params: {
						userID: globalUserIDRout,
						FactTripID: globalFactTripID,
        				time: time
						}
	        		});
					//if (records.get('is_lock') == 'Да') {
					if (records.get('is_lock') == 1) {
						Ext.getCmp('lock_button_id').enable(true);
					} else {
						Ext.getCmp('lock_button_id').disable(true);
					}
					
					if(records.get('Calculated2') == 1){
						showRoute( globalFactTripID );
					}
					
					
	        		}
					
					
					
	        },
			tbar:[
				{
					xtype: 'button',
					//text: 'Создать маршрут', 
					id: 'createRoutePlanBtn',
			        //text: plan_toir.create_route,
					tooltip: plan_toir.create_route,
					iconCls: 'add',
			        handler: function() {
			            //createTripPlanning(0, 'add');
			            if( Ext.getCmp('project_planning_id').getValue() ){
							createTripPlanning_logist(0, 'add', false);
						}else{
							Ext.MessageBox.alert(all_toir.error,plan_toir.choose_project);
						}
						
						
			        }
			                    		   
			    },
				{
		                xtype: 'button',
			            id: 'deleteRoutePlanBtn',
						margin: '0 0 0 3',
						//text: 'Удалить',
						iconCls: 'delete',
						tooltip: plan_toir.delete_route,
		                handler: function(){
							//Ext.MessageBox.alert('Ошибка','К сожалению, данный функционал для вас недоступен');
							
						/*	var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
							console.log(select);
							if(select){
								if(parseInt(select.get('Closed2')) == 0){
								var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
								myMask.show();
								$.post("app/LogistMobile_facttrip.php",{'DeleteTrip':true, 'arrayOrdersId[]':select.get('TID')}, function(data){
								myMask.hide();
								LogistMobile_TripPlanningStoreRoutes_factrip.load();
								pointsVisitStoreRoutes_factrip.removeAll();
								});
								}else{ Ext.Msg.alert('Ошибка','Выпущен рейс нельзя удалить'); }
							}else {
		                	   Ext.Msg.alert(all_toir.attention, plan_toir.select_a_route); 	
							}
						*/	
							var time = Ext.getCmp('planning_date_id').getRawValue();
							var project = Ext.getCmp('project_planning_id').getValue();
							
							
							var arrayOrdersId=[];									
							LogistMobile_TripPlanningStoreRoutes_factrip.each(function(record)   
							{
								//console.log( record );
								console.log( record.get('Closed2') );
								if(record.get('indoor') == true){
									if(parseInt(record.get('Closed2')) == 0){
									arrayOrdersId.push(record.get('TID'));
									}else{ Ext.Msg.alert(all_toir.error,plan_toir.released_trip_not_removed); }
								}
								
							});
							console.log(arrayOrdersId);
							
							if (arrayOrdersId.length==0){
								//Ext.Msg.alert('Ошибка','Выберите рейс(ы) для удаления');
								Ext.Msg.alert(all_toir.error, plan_toir.select_trip_or_check_status);
							} else {
								Ext.MessageBox.confirm(all_toir.attention, plan_toir.want_delete_trip,  function(btn){
								if(btn=='yes'){
									
								var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
								myMask.show();
								$.post("app/LogistMobile_facttrip.php",{'DeleteTrip':true, 'arrayOrdersId[]':arrayOrdersId}, function(data){
								
										//alert('data '+data);
										if(data){
											
											var obj = Ext.decode(data);
											if(obj.success == true){
												myMask.hide();
												var result = checkwebtaskprogress(obj.message,true);
												//alert('result '+result);
											}else{
												myMask.hide();
												Ext.MessageBox.alert(all_toir.error, obj.message);
											}
				
											
											/*myMask.hide();
											Ext.MessageBox.alert(all_toir.attention, plan_toir.autoplanning_formed);
											requestPlanning.load({
												params: {
													time: time,
													project: project
												}
											});
											LogistMobile_TripPlanningStoreRoutes_factrip.load({
												params: {
													time: time,
													project: project
												}
											});
											pointsVisitStoreRoutes_factrip.removeAll();
											*/
										}else{
											Ext.MessageBox.alert(all_toir.error, '');
											myMask.hide();
										}
								
								/*
								//LogistMobile_TripPlanningStoreRoutes_factrip.load();
								LogistMobile_TripPlanningStoreRoutes_factrip.load({
								params: {
									time: time,
									project: project
								}
								});
								
								pointsVisitStoreRoutes_factrip.removeAll();
								
								requestPlanning.load({params: {time: time, project: project}});
								
								clearMapLogist();
								*/
								
								
								});
								
								//myMask.hide();
								
								}});
							}
							
						}
				},
				{
			                    		   xtype: 'button',
			                    		   margin: '0 0 0 3',
			                    		   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 3',
			                    		   //text: 'Просчитать маршрут',
			                    		   text: plan_toir.calculate_route,
										   id: 'calcRoutePlanBtn',
										   arrowAlign: 'right',
											menu      : 
											[
												{
													xtype: 'checkboxfield',
													//boxLabel  : 'с изменением последовательности',
													boxLabel  : plan_toir.variation_sequence,
													id:'withchange',
												},
												{
													xtype: 'button',
													//text: 'Просчитать',
													text: plan_toir.calculate,
													handler: function() 
													{
													 var memu_cb = Ext.getCmp('withchange').getValue();
													 //alert(memu_cb);
													 calculateTripLogist(memu_cb);
													 Ext.getCmp('calcRoutePlanBtn').hideMenu();
													} 
												}
											],
			    },
				{
							xtype: 'button',
							tooltip: 'Указать маршрут',
							text: 'Указать маршрут',
							id: 'buttonManualPlanning',
							hidden: true,
							//iconCls: 'wrench',
							margin: '3 3 3 3',
							handler: function(){
								
								var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
								if(select){
									
									if (select.get('is_lock') == 0) {
									if( pointsVisitStoreRoutes_factrip.getTotalCount() > 2 ){
									
									show_LogistMobile_ManualPlanning_Window(select);
									
									}else{
										Ext.Msg.alert(all_toir.error, plan_toir.applications_for_display);
									}
									}else{
										Ext.Msg.alert(all_toir.attention, plan_toir.edit_route_unlock);
									}
									
								}else{
									Ext.Msg.alert(all_toir.attention, plan_toir.select_a_route); 	
								}
								
							}
				},
				{
			                    		   xtype: 'button',
			                    		   margin: '0 0 0 3',
			                    		   //text: 'Выпустить рейсы',
			                    		   text: plan_toir.release_trip,
										   id: 'releaseRoutePlanBtn',
			                    		   handler: function(){
											   ReleaseTripLogist('ReleaseTrip');
											   //reloadTripStore();
										   } 
			    },
				{
			                    		   xtype: 'button',
			                    		   margin: '0 0 0 3',
			                    		   text: 'Экспорт в Nav',
										   id: 'releaseRouteNAVPlanBtn',
										   hidden: true,
			                    		   handler: function(){
											   ReleaseTripLogist('ReleaseTripNav');
										   } 
			    },
				{
			                    		   xtype: 'button',
			                    		   margin: '0 0 0 3',
			                    		   //text: 'Разблокировать',
			                    		   text: plan_toir.unblock,
			                    		   disabled: true,
			                    		   id: 'lock_button_id',
			                    		   handler: function(){
											   //ReleaseTripLogist();
			                    			   unLockTrip(globalFactTripID);
											   //reloadTripStore();
				}
			    },
				{
		                xtype: 'button',
						id: 'ChangeCarPlanBtn',
			            margin: '0 0 0 3',
						//text: 'Сменить авто',
						text: plan_toir.change_car,
		                handler: function(){
							var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
							console.log(select);
							if(select){
								console.log( select.get('TID') );
								showChangeCarWindow(select.get('TID'),select.get('Login2'));
							}else {
		                	   Ext.Msg.alert(all_toir.attention, plan_toir.select_a_route); 	
							}
						}
				},
				{
							xtype: 'button',
							iconCls: 'print',
							margin: '0 0 0 3',
							//tooltip: 'Маршрутный лист',
							tooltip: plan_toir.routing_sheet,
							handler: function(){
								showItineraryWindow();
							}
				},
				{
							xtype: 'button',
							iconCls: 'xls',
							margin: '0 0 0 3',
							//tooltip: 'Маршрутный лист',
							tooltip: plan_toir.routing_sheet,
							handler: function(){
								export_xls_run_trip();
							}
				},{
		                xtype: 'button',
						id: 'ImportTripBtn',
						iconCls: 'xmlico',
			            margin: '0 0 0 3',
						//text: 'Import Trip',
						text: routes_LogistMobile.import_trip,
		                handler: function(){
							if( Ext.getCmp('project_planning_id').getValue() ){
								Show_Uploads_Window_ImportTrip(Ext.getCmp('project_planning_id').getValue());
							}else{
								Ext.MessageBox.alert(all_toir.error,plan_toir.choose_project);
							}
						}
				}/*,{
						text: request_toir.XML_import_template,
		                iconCls: 'xmlico',
		                handler: function(){
							//window.open('app/name.zip', '_blank');
							window.location.href = 'app/tripxml.zip';
						}
				}*/
			]
	    	
	    });
/* <-- 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,        
	        id: 'requestPlanningGrigId',
			height: 250,        
	        minHeight: 100,        
	        //margin: '0 0 10 0',       
	        store: requestPlanning,
	        multiSelect: true,
			//stateful: true,
            //forceFit: 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();	
	                	
						var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
						myMask.show();
						
						if (select) {
	                		
							var time = Ext.getCmp('planning_date_id').getRawValue();	                	
	    	                var project = Ext.getCmp('project_planning_id').getValue();
							
							//if (select.get('is_lock') == 'Нет') {
							if (select.get('is_lock') == 0) {
	                			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');
	    	                	
								
	    	                	$.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
	    		            	    				}
	    		            	    		   });*/
										requestPlanning.load({
										params: {
											time: time,
											project: project
										}
										});
	    		                			    
	    		                		reloadTripStore();
	    							    clearMapLogist();
										myMask.hide();
	    	                			} else {
	    	                				Ext.Msg.alert(all_toir.attention, plan_toir.start_warehouse_and_end_warehouse);
	    	                				pointsVisitStoreRoutes_factrip.load({
	    				           				params: {
	    				           					FactTripID: globalFactTripID				           					
	    				           				}
	    			           	            });
	    	                				/*requestPlanning.load({
	    	            	    				params: {
	    	            	    					time: time
	    	            	    				}
	    	            	    			});*/
										requestPlanning.load({
										params: {
											time: time,
											project: project
										}
										});
											
											
	    	                				reloadTripStore(); 
											myMask.hide();
	    	                			}
	    	                			
	    							}); 
	                		} else {
	                			Ext.Msg.alert(all_toir.attention, plan_toir.edit_route_unlock);
	                			
	                			   /*requestPlanning.load({
		           	    				params: {
		           	    					time: time
		           	    				}
	           	    			   });*/
								    requestPlanning.load({
										params: {
											time: time,
											project: project
										}
									});
								   
	                			   pointsVisitStoreRoutes_factrip.load({
				           				params: {
				           					FactTripID: globalFactTripID				           					
				           				}
			           	            });		                			   
	                			 reloadTripStore();	
								 myMask.hide();
	                		}
	                	}	
	                	
						
						
	                	}
	            }
	        },        
	        loadMask: true,
	        border: false,
	        autoScroll: true,        
	        columns:[
			{
	        	text: 'ID', 
	            dataIndex: 'ID',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	            width: 50,	
	        },{
	        	text: 'Собран', 
	            dataIndex: 'CustomInt',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	            width: 50,
	            id: 'ready_status_id',
	            listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 74) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },
			{
	        	//text: 'Название',
	        	text: plan_toir.title,
	            dataIndex: 'Name',
	            sortable: true,
	        },
			{
	        	//text: 'Код',
	        	text: plan_toir.code, 
	            dataIndex: 'Code',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	            width: 60
	        },{
	        	//text: 'Клиент',
	        	text: plan_toir.client, 
	            dataIndex: 'Client',
	            sortable: true,
	        },/*{
	        	text: 'Время приезда',	        	 
	            dataIndex: 'EstimateTime',
	            sortable: true,
	        },*/ {
	        	//text: 'Адрес',	        	 
	        	text: plan_toir.address,	        	 
	            dataIndex: 'OriginalAddress',
	            sortable: true,
	            flex: 1
	        },{
	        	//text: 'Тип точки',	        	 
	        	text: plan_toir.typepoint,	        	 
	            dataIndex: 'WarehouseType',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID == 74) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },
			{
		        //text: 'Начало работ',
		        text: plan_toir.beginning_of_work,
				dataIndex: 'StartTime',
				sortable: true
			},
			{
		        //text: 'Конец работ',
		        text: plan_toir.end_of_works,
				dataIndex: 'EndTime',
				sortable: true
			},
			{
		        //text: 'Приоритет',
		        text: plan_toir.priority,
				dataIndex: 'Priority',
				sortable: true
			},
			{        	 
	        	text: 'Зона',	        	 
	            dataIndex: 'ZoneName',
	            sortable: true,
	            width: 70
	        }
			
			// --- 08.12.2016 custom fields add for client 120 PTU --->
			,{        	 
	        	text: 'CustomString1',	        	 
	            dataIndex: 'CustomString1',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{        	 
	        	text: 'CustomString2',	        	 
	            dataIndex: 'CustomString2',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{        	 
	        	text: 'CustomString3',	        	 
	            dataIndex: 'CustomString3',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{        	 
	        	text: 'CustomString4',	        	 
	            dataIndex: 'CustomString4',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },
			{        	 
	        	text: 'CustomString5',	        	 
	            dataIndex: 'CustomString5',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{       	 
	        	text: 'CustomString6',	        	 
	            dataIndex: 'CustomString6',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{        	 
	        	text: 'CustomString7',	        	 
	            dataIndex: 'CustomString7',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{        	 
	        	text: 'CustomString8',	        	 
	            dataIndex: 'CustomString8',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        }
			// <--- 08.12.2016 custom fields add for client 120 PTU ---
			],        
	        listeners: {
	        	itemdblclick: function(cmp, records) {        		
	        		//bindMaster(records.get('id'));        		
	        	},
	        	afterrender: function() {
	        		
					
					/*TOiR_TripPlanningStore.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,
	    				//fieldLabel: plan_toir.date_of_requests,
	    				format: 'Y-m-d',
	    				altFormats: 'Y-m-d',
	    				id: 'planning_date_id',
	    				startDay: 1,
	    				margin: '3 3 3 3',
	    				name : 'date_create',
						width: 125,
						labelWidth: 30,
	    				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);
									Ext.getCmp('lock_button_id').setDisabled(true);
									Ext.getCmp('ChangeCarPlanBtn').setDisabled(true);
									
								}else{
									Ext.getCmp('releaseRoutePlanBtn').setDisabled(false);
									Ext.getCmp('calcRoutePlanBtn').setDisabled(false);
									Ext.getCmp('deleteRoutePlanBtn').setDisabled(false);
									Ext.getCmp('createRoutePlanBtn').setDisabled(false);
									Ext.getCmp('lock_button_id').setDisabled(false);
									Ext.getCmp('ChangeCarPlanBtn').setDisabled(false);
								}
								
								/*requestPlanning.load({
            	    				params: {
            	    					time: time
            	    				}
            	    			});	
	    						LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time
				           				}
								});*/
/*	    						pointsVisitStoreRoutes_factrip.removeAll();
								LogistMobile_TripPlanningStoreRoutes_factrip.removeAll();
								requestPlanning.removeAll();
								
								//Ext.getCmp('project_planning_id').setRawValue();
								Ext.getCmp('project_planning_id').setValue();
								
								Project_store.load({
									params: {
									time: time,
									}
								});
								
								clearMapLogist();
								
							}
	    				}
	    	    		
	    		    	},
						{
			        	 xtype: 'combo',
			        	 //fieldLabel: 'Проект',
			        	 fieldLabel: plan_toir.project,
			        	 store: Project_store,
			        	 allowBlank: false,
			        	 margin: '3 3 3 3',
			        	 editable: false,
						 labelWidth: 45,
						 width: 170,
			        	 valueField: 'ID',
			        	 displayField: 'Name',
			        	 queryMode: 'local',
						 id: 'project_planning_id',
							listeners: {
							afterrender: function(combo) {
								//alert('afterrender project_planning_id');
								var thisCombo = this;
								var project;
								if(timeprojectcreate){
									var time = timeprojectcreate;
								}else{
									var time = Ext.getCmp('planning_date_id').getRawValue();		
								}
								this.store.load({
									params: {
										time: time,
									},
									callback: function(){
										project = thisCombo.store.getAt(0).get(thisCombo.valueField);
										//alert(project);
										thisCombo.setValue(project);
										
										requestPlanning.load({
										params: {
											time: time,
											project: project
										}
										});
										
										LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				    params: {
	                					   time: time,
										   project: project
				           				}
								});
									}
								});

								
							},
							change : function(combo, newValue, oldValue, eOpts){
								var time = Ext.getCmp('planning_date_id').getRawValue();
								var project = newValue;
								
								requestPlanning.load({
										params: {
											time: time,
											project: project
										}
								});
								
								requestPlanning.load({
										params: {
											time: time,
											project: project
										}
								});
								
								LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time,
										   project: project
				           				}
								});
							}
							}
						},
						
						/* {
	    		    		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,
							tooltip: plan_toir.update_details,
							iconCls: 'refresh',
							margin: '3 3 3 3',
	    		    		handler: function() {	    		    			
	    		    			var time = Ext.getCmp('planning_date_id').getRawValue();
	    		    			//var project = Ext.getCmp('project_planning_id').getRawValue();
								
								pointsVisitStoreRoutes_factrip.removeAll();
								LogistMobile_TripPlanningStoreRoutes_factrip.removeAll();
								requestPlanning.removeAll();
								
								Ext.getCmp('project_planning_id').store.load({
									params: {
									time: time,
									}
								});
								
								var project = Ext.getCmp('project_planning_id').getValue();
								
								if(project){
	    		    			requestPlanning.load({
            	    				params: {
            	    					time: time,
										project: project
            	    				}
            	    			});	
	    		    			
								LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time,
										   project: project
				           				}
								});
								
								}
								
								
								clearMapLogist();
	    		    			
								//pointsVisitStoreRoutes_factrip.load({
			           			//	params: {
			           			//		FactTripID: globalFactTripID				           					
			           			//	}
		           	            //});
                				
								
	    		    			//Ext.getCmp('visitPoint').getView().refresh();
	    		    			//requestPlanning.load({
	    	           			//	params: {
	    	           			//		time: time
	    	           			//	}
	    	           			//});
	    		    			
	    		    			//TOiR_TripPlanningStore.load({
	    		        		//	params: {
	    		        		//		time: time
	    		        		//	}
	    		        		//});
	    		    			//pointsVisitStore.removeAll();
	    		    			//closeRoute();
								
								
								
								
								
	    		    		}
	    		    	},
						{
	    		    		xtype: 'button',
	    		    		//text: 'Автопланирование',
							text: plan_toir.autoplanning,
	    		    		id: 'autoplanRoutePlanBtn',
							margin: '3 3 3 3',
	    		    		handler: function() {
								var time = Ext.getCmp('planning_date_id').getRawValue();
								var project = Ext.getCmp('project_planning_id').getValue();
								var d1 = new Date(time);
								var dbox = d1.getTime();
								var d2 = new Date(getFullDate());
								var dnow = d2.getTime();
								
								//console.log(dbox);
								//console.log(dnow);

								if( requestPlanning.getTotalCount()!=0 ){

								if( dbox >= dnow){
									var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
									myMask.show();
									//Ext.MessageBox.alert(all_toir.attention,'На данный момент этот функционал недоступен');
									$.post('app/LogistMobile_facttrip.php', {AutoplanTrip: true, time: time, project:project}, function(data) {
										if(data){
											myMask.hide();
											Ext.MessageBox.alert(all_toir.attention, plan_toir.autoplanning_formed);
											requestPlanning.load({
												params: {
													time: time,
													project: project
												}
											});
											LogistMobile_TripPlanningStoreRoutes_factrip.load({
												params: {
													time: time,
													project: project
												}
											});
											pointsVisitStoreRoutes_factrip.removeAll();
										}else{
											Ext.MessageBox.alert(all_toir.error, plan_toir.autoplanning_failed);
											myMask.hide();
										}
									});
									
								}else{
									Ext.MessageBox.alert(all_toir.error, plan_toir.autoplanning_less_current_date);
								}
								
								}else{
									Ext.MessageBox.alert(all_toir.error, plan_toir.applications_for_autoplanning);
								}
							}
						},
						{
							xtype: 'button',
							//text: 'Заявки на карте',
							text: plan_toir.applications_on_map,
							id: 'buttonCheckOrdersOnMap',
							margin: '3 3 3 3',
							pressed: false,
							enableToggle: true,
							handler: function(){
								
								var time = Ext.getCmp('planning_date_id').getRawValue();
								var project = Ext.getCmp('project_planning_id').getValue();
								
								requestPlanning.load({params: {time: time, project: project}});
								//Ext.getCmp('requestPlanningGrigId').getView().refresh();
								//PanelMapPlanning.deleteMapDrawingTools();
								
								//console.log( count = requestPlanning.getCount() );
								
								if(myMaskGlob){myMaskGlob.hide();}
								
								if( requestPlanning.getTotalCount() != 0 ){
								
								if(this.pressed){
									console.log('press');
									
									myMaskGlob = new Ext.LoadMask(Ext.getCmp('requestPlanningGrigId'), {msg: all.loading});
									myMaskGlob.show();
									
									$.post('app/LogistMobile_facttrip.php', {tms_order_onmap: true, time: time, project: project}, function(data) {
									if(data || data!=""){		 
									var objData = Ext.decode(data);
									if (globalMarkerObjOrder) {
										for (var key in globalMarkerObjOrder){
											globalMarkerObjOrder[key].setMap(null);
										}
										globalMarkerObjOrder = [];
									}
			 
									var arrOfMarkers = [];
									for (var key in objData) {
										var GoogleLatLng = new google.maps.LatLng(objData[key]['GeoY'],objData[key]['GeoX']);
										var Client = objData[key]['Client'] ? objData[key]['Client'] : '';
										var Name = objData[key]['Name'] ? objData[key]['Name'] : '';
										var Address = objData[key]['OriginalAddress'] ? objData[key]['OriginalAddress'] : '';
										var Code = objData[key]['Code'] ? objData[key]['Code'] : '';
										
										var StartTime = objData[key]['StartTime'] ? objData[key]['StartTime'] : '';
										var EndTime = objData[key]['EndTime'] ? objData[key]['EndTime'] : '';
										
										var priority = objData[key]['Priority'];
										if(priority || priority!=""){ var img="images/Point_Red_"+priority+".png"; }else{ var img="images/Point_Red_old.png"; }
										console.log(img);
										var tooltip = '<div class="grad"><p><b>'+plan_toir.name_client+'</b>'+Client+'</p><p><b>'+plan_toir.address+': </b>'+Address+'</p><p><b>'+plan_toir.request_code+': </b>'+Code+'</p><p><b>'+plan_toir.beginning_of_work+': </b>'+StartTime+'</p><p><b>'+plan_toir.end_of_works+': </b>'+EndTime+'</p></div>';
										
										var marker = PanelMapPlanning.addMarker(GoogleLatLng,{cursor:'order_'+objData[key]['Order_ID'], icon:img},false,false,null,tooltip);
										arrOfMarkers.push(marker);
									}
			 
									globalMarkerObjOrder = arrOfMarkers;
									}
									});
									

									PanelMapPlanning.clickOnMapDrawingTools(calculateGroupOrders);
									
									
								}else{
									console.log('unpress');
									if (globalMarkerObjOrder) {
										for (var key in globalMarkerObjOrder){
											globalMarkerObjOrder[key].setMap(null);
										}
										globalMarkerObjOrder = [];
									}
									PanelMapPlanning.deleteMapDrawingTools();
									myMaskGlob.hide();
								}
								
								}else{ Ext.Msg.alert(all_toir.error, plan_toir.applications_for_display); Ext.getCmp('buttonCheckOrdersOnMap').toggle(false); }
							}
						},
						{
							xtype: 'button',
							//text: 'Удалить проект',
							//tooltip: 'Удалить проект',
							tooltip: plan_toir.remove_project,
							iconCls: 'delete',
							id: 'buttonDeleteProject',
							margin: '3 3 3 3',
							handler: function(){
								if( Ext.getCmp('project_planning_id').getValue() ){
								
								Ext.MessageBox.confirm(all_toir.attention, plan_toir.want_delete_project,  function(btn){
								if(btn=='yes'){
								
								var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
								myMask.show();
								$.post("app/LogistMobile_checkpoint.php",{'DeleteProject':true, 'arrayProjectId':Ext.getCmp('project_planning_id').getValue()}, function(data){
									
									
								var time = Ext.getCmp('planning_date_id').getRawValue();
	    		    			//var project = Ext.getCmp('project_planning_id').getRawValue();
								
								pointsVisitStoreRoutes_factrip.removeAll();
								LogistMobile_TripPlanningStoreRoutes_factrip.removeAll();
								requestPlanning.removeAll();
								
								Ext.getCmp('project_planning_id').store.load({
									params: {
									time: time,
									}
								});
								
								var project = Ext.getCmp('project_planning_id').getValue();
								
								if(project){
	    		    			requestPlanning.load({
            	    				params: {
            	    					time: time,
										project: project
            	    				}
            	    			});	
	    		    			
								LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time,
										   project: project
				           				}
								});
								
								}
								
								
								clearMapLogist();
								
								myMask.hide();
									
								});
								
								}});
								}else{
									Ext.MessageBox.alert(all_toir.error,plan_toir.choose_project);
								}
							}
						},{
							xtype: 'button',
							//text: 'Удалить проект',
							tooltip: 'Блокировка/Разблокировка авто',
							iconCls: 'car',
							margin: '3 3 3 3',
							handler: function(){
								show_LogistMobile_carsnapshot_Window();
							}
						}
						]
	    	    },    
	    	    
	    	    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,
			loadMask: true,
	        border: false, 
	        viewConfig: {	        	
	        	plugins: {
	                ptype: 'gridviewdragdrop',	                
                    containerScroll: true
                    
	                /*dragGroup: 'southWestPanelPlanningGroup',
	                dropGroup: 'requestPlanningGrigGroup'*/
	            },            
	            listeners: {
	                beforedrop( node, data, overModel, dropPosition, dropHandlers, eOpts ){
						/*alert('beforedrop');
						console.log('beforedrop');
						console.log(node);
			            console.log(data);
			            console.log(overModel);
			            console.log(dropPosition);
						console.log(dropHandlers);*/
						
						var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
						myMask.show();
						var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
	                	if (!select){
							Ext.Msg.alert(all_toir.attention, plan_toir.select_a_route);
							myMask.hide();
							return false;
						}
						myMask.hide();
					},
					drop: function(node, data, dropRec, dropPosition) {
					
						var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
						myMask.show();
						
	                	var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
	                	if (select) {
	                		
							
							console.log('is_lock - '+select.get('is_lock'));
							var time = Ext.getCmp('planning_date_id').getRawValue();	                	
	    	                var project = Ext.getCmp('project_planning_id').getValue();
							
							//if (select.get('is_lock') == 'Нет') {
							if (select.get('is_lock') == 0) {
	                			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(all_toir.attention, plan_toir.location_warehouses_not_changed);
			                				}
			                				pointsVisitStoreRoutes_factrip.load({
						           				params: {
						           					FactTripID: globalFactTripID				           					
						           				}
					           	            });
			                			requestPlanning.load({
										params: {
											time: time,
											project: project
										}
										});
			                				reloadTripStore();
											myMask.hide();
			                		});
			                	} 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) {								
			                			   pointsVisitStoreRoutes_factrip.load({
						           				params: {
						           					FactTripID: globalFactTripID				           					
						           				}
					           	            });		                			   
			                			   reloadTripStore();
										   myMask.hide();
				                	});
									
			                	}
			                	
								
	                		} else {
	                			Ext.Msg.alert(all_toir.attention, plan_toir.edit_route_unlock);
	                			   requestPlanning.load({
										params: {
											time: time,
											project: project
										}
										});
	                			   pointsVisitStoreRoutes_factrip.load({
				           				params: {
				           					FactTripID: globalFactTripID				           					
				           				}
			           	            });		                			   
	                			 reloadTripStore();	
			                	   //pointsVisitStoreRoutes_factrip.removeAll();
								   myMask.hide();
	                			
	                		}
	                		
		                } else {
		                	   Ext.Msg.alert(all_toir.attention, plan_toir.select_a_route);
		                	   myMask.hide();
							   
							   requestPlanning.load({
										params: {
											time: time,
											project: project
										}
								});
		                	   pointsVisitStoreRoutes_factrip.removeAll();

								
		                }
	                	
						
						
	                clearMapLogist();
	                }
	            }
	        },
	        // ----  
	        columns:[
	        {
	        	text: 'ID', 
	            dataIndex: 'ID',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	            width: 50,	
	        },
			{
				text: 'Cтатус Фактический', 
	            dataIndex: 'PointState',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	            width: 40,
			},
			{
	        	//text: 'Название',
	        	text: plan_toir.title,
	            dataIndex: 'Name',
	            sortable: true,
	        },
			{
	        	//text: 'Порядковый номер',
	        	text: plan_toir.sequence_number,
	            dataIndex: 'OrderInTrip',
				hidden: true,
	            sortable: true,
	        },
			{
	        	//text: 'Порядковый номер',
				text: plan_toir.sequence_number,
	            dataIndex: 'OrderInTrip2',
	            sortable: true,
	        },
			/*{
				xtype: 'rownumberer',
				hidden: false,
	            sortable: false,
				text: 'Порядковый номер'
			},*/
			{
	        	//text: 'Код',
	        	text: plan_toir.code, 
	            dataIndex: 'Code',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: true,
	            width: 60
	        },{
	        	//text: 'Клиент',
	        	text: plan_toir.client, 
	            dataIndex: 'Client',
	            sortable: true,
	        },
//add			
		
			{
	        	//text: 'Время приезда',
	        	text: plan_toir.time_of_arrival,
	            dataIndex: 'EstimateTime',
	            sortable: true,
	        },
			{
	        	//text: 'Время отъезда',
	        	text: plan_toir.time_of_departure,
	            dataIndex: 'Duration',
	            sortable: true,
	        },
//endadd			
			{
	        	//text: 'Адрес',	        	 
	        	text: plan_toir.address,	        	 
	            dataIndex: 'OriginalAddress',
	            sortable: true,
	            flex: 1
	        },
//aad
			{
	        	//text: 'Расстояние',
	        	text: plan_toir.distance,
	            dataIndex: 'Distance',
	            sortable: true,
	        },
			{
	        	//text: 'Cостояние загрузки',
	        	text: plan_toir.download_status,
	            dataIndex: 'CustomInt',
	            sortable: true,
				id: 'status_trippoint',
				listeners: {
	            	beforerender: function() {
	            		if (globalClientID != 74) {	            			
	            			Ext.getCmp('status_trippoint').hide();
	            		}
	            	}
	            }
				
	        },
//endadd	
			{
		        //text: 'Начало работ',
		        text: plan_toir.beginning_of_work,
				dataIndex: 'StartTime',
				sortable: true
			},
			{
		        //text: 'Конец работ',
		        text: plan_toir.end_of_works,
				dataIndex: 'EndTime',
				sortable: true
			},
			{
		        //text: 'Приоритет',
		        text: plan_toir.priority,
				dataIndex: 'Priority',
				sortable: true
			},
			{
	        	//text: 'Тип точки',	        	 
	        	text: plan_toir.typepoint,	        	 
	            dataIndex: 'WarehouseType',
	            sortable: true,
	            width: 70,
				id:'type_point_trippoint',
				listeners: {
	            	beforerender: function() {
	            		if (globalClientID == 74) {	            			
	            			Ext.getCmp('type_point_trippoint').hide();
	            		}
	            	}
	            }
	        }
			// --- 08.12.2016 custom fields add for client 120 PTU --->
			,{        	 
	        	text: 'CustomString1',	        	 
	            dataIndex: 'CustomString1',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{        	 
	        	text: 'CustomString2',	        	 
	            dataIndex: 'CustomString2',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{        	 
	        	text: 'CustomString3',	        	 
	            dataIndex: 'CustomString3',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{        	 
	        	text: 'CustomString4',	        	 
	            dataIndex: 'CustomString4',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },
			{        	 
	        	text: 'CustomString5',	        	 
	            dataIndex: 'CustomString5',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{       	 
	        	text: 'CustomString6',	        	 
	            dataIndex: 'CustomString6',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{        	 
	        	text: 'CustomString7',	        	 
	            dataIndex: 'CustomString7',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        },{        	 
	        	text: 'CustomString8',	        	 
	            dataIndex: 'CustomString8',
	            sortable: true,
	            width: 70,
				listeners: {
	            	beforerender: function(col) {
	            		if (globalClientID != 120) {	            			
	            			col.hide();
	            		}
	            	}
	            }
	        }
			// <--- 08.12.2016 custom fields add for client 120 PTU ---
			], 
	        listeners: {
	        	itemdblclick: function(cmp, record) {
	        		//console.log(record);
	        		focusOutlet(record);
	        	}
	        }       
	    });
	    
		
		
		
		// -- window create -->
		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: true,
				constrain : true,
				resizable: true,
				
				x : 2,
	            y : 29,
	            
				defaults: {
					collapsible: true,
					split: true,
					stateful: true
				},
				listeners : {
	            	destroy : function(){
	            		TOiR_planning_Window = null;
						//clearInterval(interval_update_status_route);
	            	}
	            },
				dockedItems: [
					{   
					xtype: 'toolbar',
					border: true,
					items: [
						{
							xtype: 'button',
							//text: 'Создать проект',
							text: plan_toir.create_project,
							tooltip: plan_toir.create_project,
							iconCls: 'add',
							id: 'buttonCreateProject',
							margin: '3 3 3 3',
							handler: function(){
									createTripPlanning_logist(0, 'add', true);
							}
						},
						{
							xtype: 'button',
							//text: 'Удалить проект',
							text: plan_toir.remove_project,
							//tooltip: 'Удалить проект',
							tooltip: plan_toir.remove_project,
							iconCls: 'delete',
							id: 'buttonDeleteProject',
							margin: '3 3 3 3',
							handler: function(){
								if( Ext.getCmp('project_planning_id').getValue() ){
								
								Ext.MessageBox.confirm(all_toir.attention, plan_toir.want_delete_project,  function(btn){
								if(btn=='yes'){
								
								var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
								myMask.show();
								$.post("app/LogistMobile_checkpoint.php",{'DeleteProject':true, 'arrayProjectId':Ext.getCmp('project_planning_id').getValue()}, function(data){
									
									
									if(data){
											var obj = Ext.decode(data);
											if(obj.success == true){
												myMask.hide();
												var result = checkwebtaskprogress(obj.message,true);
												//alert('result '+result);
												
												
												
											}else{
												myMask.hide();
												Ext.MessageBox.alert(all_toir.error, obj.message);
											}

										}else{
											Ext.MessageBox.alert(all_toir.error, '');
											myMask.hide();
										}
									
									
								/*var time = Ext.getCmp('planning_date_id').getRawValue();
	    		    			//var project = Ext.getCmp('project_planning_id').getRawValue();
								
								pointsVisitStoreRoutes_factrip.removeAll();
								LogistMobile_TripPlanningStoreRoutes_factrip.removeAll();
								requestPlanning.removeAll();
								
								Ext.getCmp('project_planning_id').store.load({
									params: {
									time: time,
									}
								});
								
								var project = Ext.getCmp('project_planning_id').getValue();
								
								if(project){
	    		    			requestPlanning.load({
            	    				params: {
            	    					time: time,
										project: project
            	    				}
            	    			});	
	    		    			
								LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time,
										   project: project
				           				}
								});
								
								}
								
								
								clearMapLogist();
								
								myMask.hide();
								*/
								
								});
								
								}});
								}else{
									Ext.MessageBox.alert(all_toir.error,plan_toir.choose_project);
								}
							}
						},
						'-',
						{
	    	    		xtype: 'datefield',
	    				//fieldLabel: 'Дата',
	    				fieldLabel: plan_toir.date,
	    				//fieldLabel: plan_toir.date_of_requests,
	    				format: 'Y-m-d',
	    				altFormats: 'Y-m-d',
	    				id: 'planning_date_id',
	    				startDay: 1,
	    				margin: '3 3 3 3',
	    				name : 'date_create',
						width: 125,
						labelWidth: 30,
	    				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);
									Ext.getCmp('lock_button_id').setDisabled(true);
									Ext.getCmp('ChangeCarPlanBtn').setDisabled(true);
									
									Ext.getCmp('autoplanRoutePlanBtn').setDisabled(true);
									Ext.getCmp('buttonCheckOrdersOnMap').setDisabled(true);
									Ext.getCmp('buttonDeleteProject').setDisabled(true);
									Ext.getCmp('buttonBlockUnblockCar').setDisabled(true);
									
									Ext.getCmp('ImportTripBtn').setDisabled(true);
									Ext.getCmp('lock_button_id').setDisabled(true);
									
								}else{
									Ext.getCmp('releaseRoutePlanBtn').setDisabled(false);
									Ext.getCmp('calcRoutePlanBtn').setDisabled(false);
									Ext.getCmp('deleteRoutePlanBtn').setDisabled(false);
									Ext.getCmp('createRoutePlanBtn').setDisabled(false);
									Ext.getCmp('lock_button_id').setDisabled(false);
									Ext.getCmp('ChangeCarPlanBtn').setDisabled(false);
									
									Ext.getCmp('autoplanRoutePlanBtn').setDisabled(false);
									Ext.getCmp('buttonCheckOrdersOnMap').setDisabled(false);
									Ext.getCmp('buttonDeleteProject').setDisabled(false);
									Ext.getCmp('buttonBlockUnblockCar').setDisabled(false);
									
									Ext.getCmp('ImportTripBtn').setDisabled(false);
									Ext.getCmp('lock_button_id').setDisabled(false);
									
								}
								
								/*requestPlanning.load({
            	    				params: {
            	    					time: time
            	    				}
            	    			});	
	    						LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time
				           				}
								});*/
	    						pointsVisitStoreRoutes_factrip.removeAll();
								LogistMobile_TripPlanningStoreRoutes_factrip.removeAll();
								requestPlanning.removeAll();
								
								//Ext.getCmp('project_planning_id').setRawValue();
								Ext.getCmp('project_planning_id').setValue();
								
								Project_store.load({
									params: {
									time: time,
									}
								});
								
								clearMapLogist();
								
							}
	    				}
	    	    		
	    		    	},
						{
			        	 xtype: 'combo',
			        	 //fieldLabel: 'Проект',
			        	 fieldLabel: plan_toir.project,
			        	 store: Project_store,
			        	 allowBlank: false,
			        	 margin: '3 3 3 3',
			        	 editable: false,
						 labelWidth: 45,
						 width: 170,
			        	 valueField: 'ID',
			        	 displayField: 'Name',
			        	 queryMode: 'local',
						 id: 'project_planning_id',
							listeners: {
							afterrender: function(combo) {
								//alert('afterrender project_planning_id');
								var thisCombo = this;
								var project;
								if(timeprojectcreate){
									var time = timeprojectcreate;
								}else{
									var time = Ext.getCmp('planning_date_id').getRawValue();		
								}
								this.store.load({
									params: {
										time: time,
									},
									callback: function(){
										project = thisCombo.store.getAt(0).get(thisCombo.valueField);
										//alert(project);
										thisCombo.setValue(project);
										
										requestPlanning.load({
										params: {
											time: time,
											project: project
										}
										});
										
										LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				    params: {
	                					   time: time,
										   project: project
				           				}
								});
									}
								});

								
							},
							change : function(combo, newValue, oldValue, eOpts){
								var time = Ext.getCmp('planning_date_id').getRawValue();
								var project = newValue;
								
								pointsVisitStoreRoutes_factrip.removeAll();
								
								requestPlanning.load({
										params: {
											time: time,
											project: project
										}
								});
								
								requestPlanning.load({
										params: {
											time: time,
											project: project
										}
								});
								
								LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time,
										   project: project
				           				}
								});
							}
							}
						},
						{
							xtype: 'button',
	    		    		//text: 'Обновить данные',
	    		    		//text: plan_toir.update_details,
							tooltip: plan_toir.update_details,
							iconCls: 'refresh',
							margin: '3 3 3 3',
	    		    		handler: function() {	    		    			
	    		    			
								updateDetails();
								
								/*var time = Ext.getCmp('planning_date_id').getRawValue();
	    		    			//var project = Ext.getCmp('project_planning_id').getRawValue();
								
								pointsVisitStoreRoutes_factrip.removeAll();
								LogistMobile_TripPlanningStoreRoutes_factrip.removeAll();
								requestPlanning.removeAll();
								
								Ext.getCmp('project_planning_id').store.load({
									params: {
									time: time,
									}
								});
								
								var project = Ext.getCmp('project_planning_id').getValue();
								
								if(project){
	    		    			requestPlanning.load({
            	    				params: {
            	    					time: time,
										project: project
            	    				}
            	    			});	
	    		    			
								LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time,
										   project: project
				           				}
								});
								
								}
								
								
								clearMapLogist();
	    		    			*/
								
	    		    		}
	    		    	},
						'-',
					{
                    text: plan_toir.autoplanning,
					id: 'autoplanRoutePlanBtn',
					menu:[
						{
	    		    		//xtype: 'button',
	    		    		//text: 'Автопланирование',
							//text: 'Автопланирование без учета зон',
							text: plan_toir.autoplanning,
	    		    		//id: 'autoplanRoutePlanBtn',
							//margin: '3 3 3 3',
	    		    		handler: function() {
								//autoplanTrip(0);
								checkImeiBeforeAutoplan(0);
							}
						},
						{
							//text: 'Раздельно по зонам с учетом соседства зон',
							text: all_LogistMobile.SeparateZonesNeighborhood,
							handler: function() {
								//autoplanTrip(1);
								checkImeiBeforeAutoplan(1);
							}
						},
						{
							//text: 'Раздельно по зонам',
							text: all_LogistMobile.SeparateZones,
							handler: function() {
								//autoplanTrip(2);
								checkImeiBeforeAutoplan(2);
							}
						}
					]},
						{
							xtype: 'button',
							//text: 'Заявки на карте',
							text: plan_toir.applications_on_map,
							id: 'buttonCheckOrdersOnMap',
							margin: '3 3 3 3',
							pressed: false,
							enableToggle: true,
							handler: function(){
								
								var time = Ext.getCmp('planning_date_id').getRawValue();
								var project = Ext.getCmp('project_planning_id').getValue();
								
								requestPlanning.load({params: {time: time, project: project}});
								//Ext.getCmp('requestPlanningGrigId').getView().refresh();
								//PanelMapPlanning.deleteMapDrawingTools();
								
								//console.log( count = requestPlanning.getCount() );
								
								if(myMaskGlob){myMaskGlob.hide();}
								
								if( requestPlanning.getTotalCount() != 0 ){
								
								if(this.pressed){
									console.log('press');
									
									myMaskGlob = new Ext.LoadMask(Ext.getCmp('requestPlanningGrigId'), {msg: all.loading});
									myMaskGlob.show();
									
									$.post('app/LogistMobile_facttrip.php', {tms_order_onmap: true, time: time, project: project}, function(data) {
									if(data || data!=""){		 
									var objData = Ext.decode(data);
									if (globalMarkerObjOrder) {
										for (var key in globalMarkerObjOrder){
											globalMarkerObjOrder[key].setMap(null);
										}
										globalMarkerObjOrder = [];
									}
									
									var bounds = new google.maps.LatLngBounds();
									
									var arrOfMarkers = [];
									for (var key in objData) {
										var GoogleLatLng = new google.maps.LatLng(objData[key]['GeoY'],objData[key]['GeoX']);
										var Client = objData[key]['Client'] ? objData[key]['Client'] : '';
										var Name = objData[key]['Name'] ? objData[key]['Name'] : '';
										var Address = objData[key]['OriginalAddress'] ? objData[key]['OriginalAddress'] : '';
										var Code = objData[key]['Code'] ? objData[key]['Code'] : '';
										
										var StartTime = objData[key]['StartTime'] ? objData[key]['StartTime'] : '';
										var EndTime = objData[key]['EndTime'] ? objData[key]['EndTime'] : '';
										
										var priority = objData[key]['Priority'];
										if(priority || priority!=""){ var img="images/Point_Red_"+priority+".png"; }else{ var img="images/Point_Red_old.png"; }
										console.log(img);
										var tooltip = '<div class="grad"><p><b>'+plan_toir.name_client+'</b>'+Client+'</p><p><b>'+plan_toir.address+': </b>'+Address+'</p><p><b>'+plan_toir.request_code+': </b>'+Code+'</p><p><b>'+plan_toir.beginning_of_work+': </b>'+StartTime+'</p><p><b>'+plan_toir.end_of_works+': </b>'+EndTime+'</p></div>';
										
										var marker = PanelMapPlanning.addMarker(GoogleLatLng,{cursor:'order_'+objData[key]['Order_ID'], icon:img},false,false,null,tooltip);
										arrOfMarkers.push(marker);
										
										bounds.extend(GoogleLatLng);
									}
			 
									globalMarkerObjOrder = arrOfMarkers;
									
									PanelMapPlanning.getMap().setCenter(bounds.getCenter());
									PanelMapPlanning.getMap().fitBounds(bounds);
									
									}
									});
									
									PanelMapPlanning.clickOnMapDrawingTools(calculateGroupOrders);							
									
									
								}else{
									console.log('unpress');
									if (globalMarkerObjOrder) {
										for (var key in globalMarkerObjOrder){
											globalMarkerObjOrder[key].setMap(null);
										}
										globalMarkerObjOrder = [];
									}
									PanelMapPlanning.deleteMapDrawingTools();
									myMaskGlob.hide();
								}
								
								}else{ Ext.Msg.alert(all_toir.error, plan_toir.applications_for_display); Ext.getCmp('buttonCheckOrdersOnMap').toggle(false); }
							}
						},
						
						{
							xtype: 'button',
							//tooltip: 'Блокировка/Разблокировка авто',
							tooltip: routes_LogistMobile.blockunblockcar,
							id: 'buttonBlockUnblockCar',
							iconCls: 'car',
							margin: '3 3 3 3',
							handler: function(){
								show_LogistMobile_carsnapshot_Window();
							}
						},
						{
							xtype: 'button',
							//tooltip: 'Переменные данные',
							tooltip: routes_LogistMobile.variable_data,
							id: 'buttonVariableData',
							hidden: true,
							iconCls: 'wrench',
							margin: '3 3 3 3',
							handler: function(){
								show_LogistMobile_VariableData_Window();
							}
						},
						'-'
						
					]
					},
				],
	            items: [
				{
            //title: 'Footer',
            region: 'south',
            height: 200,
            minHeight: 75,
            maxHeight: 300,
			collapsible: false,
			layout: {
			type: 'hbox',
			pack: 'start',
			align: 'stretch'
			},
			items:[
			
			{
            //bodyPadding: 5,
            //region: 'west',
            //title: 'Collapse/Width Panel 1',
            flex: 1,
			//width: 240,
            //stateId: 'statePanelExample',
            //stateful: true,
            split: true,
            collapsible: false,
			layout: {
				type: 'hbox',
				align: 'stretch'
			},
			defaults: { flex: 1 },
            items: [southWestPanelPlanning]
			},
			{
            //region: 'east',
            //title: 'Collapse/Width Panel 2',
			flex: 1,
			//stateful: true,
            //stateId: 'stateGridExample',
            split: true,
            collapsible: false,
			layout: {
				type: 'hbox',
				align: 'stretch'
			},
			defaults: { flex: 1 },
			items: [tripPlanningGrid]
			}
			]
            //html: '<p>Footer content</p>'
        },
        {
            //title: 'Navigation',
            title: plan_toir.list_of_unbound_applications,
			region:'west',
            //floatable: false,
            //margin: '0 0 0 0',
            width: '50%',
            minWidth: 200,
			layout: {
				type: 'hbox',
				align: 'stretch'
			},
			defaults: { flex: 1 },
            //maxWidth: 250,
			items: [requestPlanningGrig]
        },
        {
            //title: 'Main Content',
            collapsible: false,
            width: '50%',
			region: 'center',
			minWidth: 200,
			layout: 'fit',
            //margin: '0 0 0 0',
            items:[ PanelMapPlanning ]
        }
/*					
					{	                
		                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,
										   tooltip: plan_toir.create_route,
										   iconCls: 'add',
			                    		   handler: function() {
			                    			   //createTripPlanning(0, 'add');
			                    			   createTripPlanning_logist(0, 'add', false);
			                    		   }
			                    		   
			                    	   },
						{
		                xtype: 'button',
			            id: 'deleteRoutePlanBtn',
						margin: '0 0 0 3',
						//text: 'Удалить',
						iconCls: 'delete',
						tooltip: plan_toir.delete_route,
		                handler: function(){
							//Ext.MessageBox.alert('Ошибка','К сожалению, данный функционал для вас недоступен');
							
						/*	var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
							console.log(select);
							if(select){
								if(parseInt(select.get('Closed2')) == 0){
								var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
								myMask.show();
								$.post("app/LogistMobile_facttrip.php",{'DeleteTrip':true, 'arrayOrdersId[]':select.get('TID')}, function(data){
								myMask.hide();
								LogistMobile_TripPlanningStoreRoutes_factrip.load();
								pointsVisitStoreRoutes_factrip.removeAll();
								});
								}else{ Ext.Msg.alert('Ошибка','Выпущен рейс нельзя удалить'); }
							}else {
		                	   Ext.Msg.alert(all_toir.attention, plan_toir.select_a_route); 	
							}
						*/	
/*							var time = Ext.getCmp('planning_date_id').getRawValue();
							var project = Ext.getCmp('project_planning_id').getValue();
							
							
							var arrayOrdersId=[];									
							LogistMobile_TripPlanningStoreRoutes_factrip.each(function(record)   
							{
								//console.log( record );
								console.log( record.get('Closed2') );
								if(record.get('indoor') == true){
									if(parseInt(record.get('Closed2')) == 0){
									arrayOrdersId.push(record.get('TID'));
									}else{ Ext.Msg.alert(all_toir.error,plan_toir.released_trip_not_removed); }
								}
								
							});
							console.log(arrayOrdersId);
							
							if (arrayOrdersId.length==0){
								//Ext.Msg.alert('Ошибка','Выберите рейс(ы) для удаления');
								Ext.Msg.alert(all_toir.error, plan_toir.select_trip_or_check_status);
							} else {
								Ext.MessageBox.confirm(all_toir.attention, plan_toir.want_delete_trip,  function(btn){
								if(btn=='yes'){
									
								var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
								myMask.show();
								$.post("app/LogistMobile_facttrip.php",{'DeleteTrip':true, 'arrayOrdersId[]':arrayOrdersId}, function(data){
								
								//LogistMobile_TripPlanningStoreRoutes_factrip.load();
								LogistMobile_TripPlanningStoreRoutes_factrip.load({
								params: {
									time: time,
									project: project
								}
								});
								
								pointsVisitStoreRoutes_factrip.removeAll();
								
								requestPlanning.load({params: {time: time, project: project}});
								
								clearMapLogist();
								});
								
								myMask.hide();
								
								}});
							}
							
						}
						},
									   {
			                    		   xtype: 'button',
			                    		   margin: '0 0 0 3',
			                    		   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 3',
			                    		   //text: 'Просчитать маршрут',
			                    		   text: plan_toir.calculate_route,
										   id: 'calcRoutePlanBtn',
										   arrowAlign: 'right',
											menu      : 
											[
												{
													xtype: 'checkboxfield',
													//boxLabel  : 'с изменением последовательности',
													boxLabel  : plan_toir.variation_sequence,
													id:'withchange',
												},
												{
													xtype: 'button',
													//text: 'Просчитать',
													text: plan_toir.calculate,
													handler: function() 
													{
													 var memu_cb = Ext.getCmp('withchange').getValue();
													 //alert(memu_cb);
													 calculateTripLogist(memu_cb);
													 Ext.getCmp('calcRoutePlanBtn').hideMenu();
													} 
												}
											],
			                    	   },
									   {
			                    		   xtype: 'button',
			                    		   margin: '0 0 0 3',
			                    		   //text: 'Выпустить рейсы',
			                    		   text: plan_toir.release_trip,
										   id: 'releaseRoutePlanBtn',
			                    		   handler: function(){
											   ReleaseTripLogist();
											   //reloadTripStore();
										   } 
			                    	   }, {
			                    		   xtype: 'button',
			                    		   margin: '0 0 0 3',
			                    		   //text: 'Разблокировать',
			                    		   text: plan_toir.unblock,
			                    		   disabled: true,
			                    		   id: 'lock_button_id',
			                    		   handler: function(){
											   //ReleaseTripLogist();
			                    			   unLockTrip(globalFactTripID);
											   //reloadTripStore();
										   }
			                    	   },
						
						{
		                xtype: 'button',
						id: 'ChangeCarPlanBtn',
			            margin: '0 0 0 3',
						//text: 'Сменить авто',
						text: plan_toir.change_car,
		                handler: function(){
							var select = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
							console.log(select);
							if(select){
								console.log( select.get('TID') );
								showChangeCarWindow(select.get('TID'),select.get('Login2'));
							}else {
		                	   Ext.Msg.alert(all_toir.attention, plan_toir.select_a_route); 	
							}
						}
						},
						{
							xtype: 'button',
							iconCls: 'print',
							margin: '0 0 0 3',
							//tooltip: 'Маршрутный лист',
							tooltip: plan_toir.routing_sheet,
							handler: function(){
								showItineraryWindow();
							}
						}
						
									   ]
		                    	   }, 
		                    	   //PBPlanningGrig
								   
								   {
		                    		//xtype: 'panel',
									//xtype: 'container',
		                    		//region: 'south',
									//layout: 'fit',
		                    		//anchor: '100% 85%',
									//autoScroll: true,
									height: 250,
									width: '50%',
									//minHeight: 200,
									//autoScroll: true,
									frame:false,
									//align: 'stretch',
									layout: {
										type: 'hbox',
										align: 'stretch'
									},
									defaults: { flex : 1 },
									
		                    		items: [tripPlanningGrid]
									}
								   
		                    	   ]
								   
								   
								   
		                       },
		                       
							   
							   
							   
							   {
		                    	   xtype: 'panel',
								   region:'west',
		                    	   width: '50%',
		                    	   //layout: 'fit',
								   align: 'stretch',
									layout: {
										type: 'hbox',
										align: 'stretch'
									},
									defaults: { flex : 1 },
		                    	   items: [ southWestPanelPlanning ]
		                       }
							   
						]	
				    }
*/
					]

	        });
		}      
		TOiR_planning_Window.show(); 
		Ext.getBody().unmask(all.loading);
		// <-- window create --
		
		if(timeprojectcreate){
			var time = timeprojectcreate;
		}else{
			var time = Ext.getCmp('planning_date_id').getRawValue();		
		}
		
		//if (globalClientID == 74 || globalClientID == 87) {
		if (globalClientID == 74){	
	        Ext.getCmp('buttonVariableData').setVisible(true);
			Ext.getCmp('releaseRouteNAVPlanBtn').setVisible(true);
	    }
		
		if(globalUserRights.manual_planning == 1){
			Ext.getCmp('buttonManualPlanning').setVisible(true);
		}
		
		
		setTimeout(function(){		                				  
				
				if(!timeprojectcreate || timeprojectcreate==false){
					//console.log('timeprojectcreate');
					//console.log(timeprojectcreate);
					//alert('checkwebtaskonload');
					checkwebtaskonload();		                				 
				}
				
				trafficLayer.setMap(PanelMapPlanning.getMap());
				
		}, 500);
		
		
		
		/*
		LogistMobile_TripPlanningStoreRoutes_factrip.load({
			params: { time: time }
		});
		*/
	}
	
	
}

/* <-- main window */	




////////////////
	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();
								var project = Ext.getCmp('project_planning_id').getValue();
								requestPlanning.load({
            	    				params: {
            	    					time: time,
										project: project
            	    				}
            	    			});
								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();
	                            	
	                            	/*
									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(withchange){
		
		var arrayTripId=[];
		var arrayLogin=[];
		var arrayWalkerNum=[];
		Ext.getCmp('TOiR_TripPlanningGridId').store.each(function(record){
			if(record.get('indoor') == true){
				//console.log( 'TID+++'+record.get('TID') );
				arrayTripId.push(record.get('TID'));
				arrayLogin.push(record.get('Login2'));
				arrayWalkerNum.push(record.get('WalkerNum'));
			}					
		});
		
		if (arrayTripId.length==0){
			Ext.MessageBox.alert(all_toir.error, plan_toir.select_the_route_to_miscalculation);
			//myMask.hide();
		} else {
		
		var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
		myMask.show();
		
		//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, Withchange: withchange, 'Trip_ID[]': arrayTripId, 'Login[]': arrayLogin, 'WalkerNum[]': arrayWalkerNum }, function(data) {
				
				//alert('data '+data);
				if(data){
				var obj = Ext.decode(data);
				if(obj.success == true){
					myMask.hide();
					var result = checkwebtaskprogress(obj.message,true,completedCheckCalculateTrip.name);
				}else{
					myMask.hide();
					Ext.MessageBox.alert(all_toir.error, obj.message);
				}
				}else{
					myMask.hide();
					Ext.MessageBox.alert(all_toir.error, plan_toir.select_the_route_to_miscalculation);
				}
				/*
				if(data == 1 || data == 'true'){

					myMask.hide();
					Ext.MessageBox.alert(all_toir.attention, plan_toir.route_is_calculated);
					//showRoute( select.get('TID') );
					showRoute( arrayTripId[0] );
					
					reloadTripStore();
					//Ext.getCmp('TOiR_TripPlanningGridId').store.load();
					var time = Ext.getCmp('planning_date_id').getRawValue();
					var project = Ext.getCmp('project_planning_id').getValue();
					Ext.getCmp('TOiR_TripPlanningGridId').store.load({
						params: {
							time: time,
							project: project
						}
					});
					
					pointsVisitStoreRoutes_factrip.load({
	    				params: {
	    				//FactTripID: select.get('TID')
						FactTripID: arrayTripId[0]					
	    				}
	    			});
					
				}else if(data.length > 3)
				{
					
					myMask.hide();
					Ext.MessageBox.alert(all_toir.error, plan_toir.calculation_with_errors+': ' + data);
					
					//showRoute( select.get('TID') );
					showRoute( arrayTripId[0] );
					reloadTripStore();
					
					var time = Ext.getCmp('planning_date_id').getRawValue();
					var project = Ext.getCmp('project_planning_id').getValue();
					Ext.getCmp('TOiR_TripPlanningGridId').store.load({
						params: {
							time: time,
							project: project
						}
					});
					
					pointsVisitStoreRoutes_factrip.load({
	    				params: {
	    				//FactTripID: select.get('TID')				           					
	    				FactTripID: arrayTripId[0]
						}
	    			});
				}else
				{
					myMask.hide();
					Ext.MessageBox.alert(all_toir.error, plan_toir.calculation_with_errors+': ' + data);
					
					//showRoute( select.get('TID') );
					showRoute( arrayTripId[0] );
					reloadTripStore();
					
					var time = Ext.getCmp('planning_date_id').getRawValue();
					var project = Ext.getCmp('project_planning_id').getValue();
					Ext.getCmp('TOiR_TripPlanningGridId').store.load({
						params: {
							time: time,
							project: project
						}
					});
					
					pointsVisitStoreRoutes_factrip.load({
	    				params: {
	    				//FactTripID: select.get('TID')			           					
	    				FactTripID: arrayTripId[0]
						}
	    			});
				}
				*/
				
			});
			// Новый функционал просчета с учетом последовательности и с сообщениями
			//}
			
		
		//} else {
		//			Ext.MessageBox.alert(all_toir.error, plan_toir.select_the_route_to_miscalculation);
		//}
		
		}
	}
	
	function ReleaseTripLogist(func){
		/*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('Login2') }, 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);
		}*/
		
		var myMask = new Ext.LoadMask(TOiR_planning_Window, {msg: all.loading});
		myMask.show();
		
		var arrayLock=[];
		var arrayTripId=[];
		var arrayLogin=[];
		var arraySt=[];
		//var Project_ID;
		var Project_ID = Ext.getCmp('project_planning_id').getValue();
		var Login; 
		Ext.getCmp('TOiR_TripPlanningGridId').store.each(function(record){
			
			if(record.get('indoor') == true){
				//console.log( 'TID+++'+record.get('TID') );
				
				
				if(func=='ReleaseTrip'){
					if( parseInt(record.get('is_lock')) < 1 ){
						if( record.get('Calculated2') == 1 || record.get('Distance')> 0){
							arrayTripId.push(record.get('TID'));
							arrayLogin.push(record.get('Login2'));
							arraySt.push(record.get('StartTime2'));
						}//else{ Ext.MessageBox.alert(all_toir.error, plan_toir.you_can_not_release); myMask.hide();}
					}else{ arrayLock.push(record.get('TID')); }
				}else if(func=='ReleaseTripNav'){
					if( record.get('Calculated2') == 1 || record.get('Distance')> 0 ){
						arrayTripId.push(record.get('TID'));
					}
				}
			}					
		});
		
		if(arrayLock.length == 0){
		if (arrayTripId.length==0){
			Ext.Msg.alert(all_toir.error,plan_toir.trips_not_selected);
			myMask.hide();
		} else {
								
			$.post("app/LogistMobile_facttrip.php",{func:func, 'arrayTripId[]':arrayTripId, 'Project_ID':Project_ID, arrayLogin: arrayLogin, arraySt:arraySt}, function(data){
				
				//alert('data '+data);
				if(data){
				var obj = Ext.decode(data);
				if(obj.success == true){
					
					
					
					myMask.hide();
					
					if(obj.exception){
						Ext.MessageBox.alert(all_toir.attention, obj.exception);
						setTimeout(function(){
							checkwebtaskprogress(obj.message,true,completedCheckReleaseTrip.name);
						}, 9000);
					}else{
						checkwebtaskprogress(obj.message,true,completedCheckReleaseTrip.name);
					}

					
					
				}else{
					myMask.hide();
					Ext.MessageBox.alert(all_toir.error, obj.message);
				}
				}else{
					myMask.hide();
					Ext.MessageBox.alert(all_toir.error, plan_toir.trips_not_released);
					reloadTripStore();
				}
				/*if(data){
					myMask.hide();
					Ext.MessageBox.alert(all_toir.attention, plan_toir.trips_released);
					lockReleaseTrips(Project_ID);
					reloadTripStore();
					Ext.getCmp('lock_button_id').enable(true);
					//Ext.getCmp('TOiR_TripPlanningGridId').store.load();
					var time = Ext.getCmp('planning_date_id').getRawValue();
					
					Ext.getCmp('TOiR_TripPlanningGridId').store.load({
						params: {
							time: time,
							project: Project_ID
						}
					});
				}else{
					myMask.hide();
					Ext.MessageBox.alert(all_toir.error, plan_toir.trips_not_released);
					reloadTripStore();
				}*/
				
			});
								
		}
		}else{ Ext.Msg.alert(all_toir.attention, plan_toir.edit_route_unlock); myMask.hide(); }
		
		
	}
	
	function ReleaseTripNavLogist(){
		
	}
	

	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/LogistMobile_facttrip.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 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();
	
	}	
*/	
	
	
	//+++
	var flag22;
	function createTripPlanning_logist(trip_id, flag, flag2) {
		
		flag22 = flag2;
		//alert('flag2 - '+flag2);
		
		/*if( Ext.getCmp('planning_date_id') ){
			var time = Ext.getCmp('planning_date_id').getRawValue();
		}else{
			var time = getFullDate();
		}*/
		
		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 - '+res[0].RESULT);
		
//if(flag2 && res[0].RESULT > 0){
	
//	show_LogistMobile_facttrip_Window2( false );
	
//}else{	
		
		//if(res[0].RESULT > 0){
		
		if(!flag2){
		
		var project = Ext.getCmp('project_planning_id').getValue();
		
		//Device_store.load();
		
		pointsVisitStoreRoutes_factrip.removeAll();
		
		Device_store.load({
			params: { time: time, project: project }
		});
		
		//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++;
		}*/
		
		globalCount = Ext.getCmp('TOiR_TripPlanningGridId').store.getTotalCount();
		globalCount ++;
		
		var title = plan_toir.create_route;
		
		
		//alert(project);
		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: 'combobox',
			        	 //fieldLabel: 'Выберите устройство',
			        	 fieldLabel: plan_toir.select_device,
			        	 store: Device_store, //TOiR_UsersPlanningTripStore,
			        	 allowBlank: false,
			        	 margin: '5 5 5 5',
			        	 labelWidth: 150,
						 editable: false,
			        	 id: 'bind_master_id',
			        	 valueField: 'ID',
			        	 displayField: 'Login',
			        	 name: 'trip_master',
			        	 queryMode: 'local',
						 selectOnFocus:true,
							listeners: {
							afterrender: function(combo) {
								var thisCombo = this;
								this.store.load({
									params: {
										time: time,
										project: project
									},
									callback: function(){
									thisCombo.setValue(thisCombo.store.getAt(0).get(thisCombo.valueField));
								}});
							}
							}
			         },{
			        	 xtype: 'combobox',
			        	 //fieldLabel: 'Проект',
			        	 fieldLabel: plan_toir.project,
			        	 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',
						 //autoSelect:true,
						 //selectOnFocus:true,
						 //typeAhead: true,
						 //triggerAction: 'all',
						 //lazyRender:true,
						 readOnly:true,
						 value: project,
						 listeners: {
							/*afterrender: function(combo) {
								var thisCombo = this;
								this.store.load({callback: function(){
									thisCombo.setValue(thisCombo.store.getAt(0).get(thisCombo.valueField));
								}});
							}*/
							}
			         },{
			        	 xtype: 'combo',
			        	 //fieldLabel: 'Склад 1',
			        	 fieldLabel: plan_toir.warehouse_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',
						 listeners: {
							afterrender: function(combo) {
								var thisCombo = this;
								this.store.load({callback: function(){
									thisCombo.setValue(thisCombo.store.getAt(0).get(thisCombo.valueField));
								}});
							}
							}
			         },{
			        	 xtype: 'combo',
			        	 //fieldLabel: 'Склад 2',
						 fieldLabel: plan_toir.warehouse_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',
						 listeners: {
							afterrender: function(combo) {
								var thisCombo = this;
								this.store.load({callback: function(){
									thisCombo.setValue(thisCombo.store.getAt(0).get(thisCombo.valueField));
								}});
							}
							}
			         }, {
			        	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;
			var title = plan_toir.create_project;
			
			item = [
				{
		        	 xtype: 'form',
		        	 //layout: 'fit',
		        	 width : width,
			         height : height,
			         id: 'trip_form_id2',
		        	 items: [
						{
		        		 xtype: 'textfield',
			        	 labelWidth: 110,
						 margin: '5 5 5 5',
						 //fieldLabel: 'Название проекта',
						 fieldLabel: routes_LogistMobile.nameProject,
						 allowBlank: false,
						 name: 'name_project'
						},
						{
	    	    		xtype: 'datefield',
	    				//fieldLabel: 'Дата проекта',
						fieldLabel: routes_LogistMobile.dateProject,
						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, plan_toir.on+' '+field.rawValue+' '+plan_toir.project_already_created);
											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){
							if(!flag2){
								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, project:project} 
	                            	});                       	
	                            	createTripPlanningWindow.destroy();					
									
	                            },
								failure: function(fp, o){
									Ext.MessageBox.alert(all_toir.error, plan_toir.project_not_created);
								}
								});
								}
							}else{
								var form = Ext.getCmp('trip_form_id2').getForm();
								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);
									
								
									
				if(o.result.success == true){
					var result = checkwebtaskprogress(o.result.message,true,completedCheckAddProject.name);		
				}else{
					Ext.MessageBox.alert(all_toir.error, o.result.message);
				}
									
									
	                            },
								failure: function(fp, o){
									//console.log(o);
									Ext.MessageBox.alert(all_toir.error, plan_toir.project_not_created);
									
									//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 Client = objData[key]['Client'] ? objData[key]['Client'] : '';
				 var Code = objData[key]['Name'] ? objData[key]['Name'] : '';
				 var Address = objData[key]['Address'] ? objData[key]['Address'] : '';
				 var Phone = objData[key]['Phone'] ? objData[key]['Phone'] : '';
				 
				 var tooltip = '<div class="grad"><p><b>'+routes_LogistMobile.name_client+': </b>'+Client+'</p><p><b>'+routes_LogistMobile.address2+': </b>'+Address+'</p><p><b>'+routes_LogistMobile.request_code+': </b>'+Code+'</p><p><b>'+routes_LogistMobile.phone+': </b>'+Phone+'</p><p><b>'+routes_LogistMobile.delivery_time+': </b>'+objData[key]['EstimateTime']+'</p><p><b>'+plan_toir.sequence_number+': </b>'+objData[key]['OrderInTrip2']+'</p></div>';
				 
				 if( objData[key]['Type']==0 ){ iconmark = 'start_point'; }else{ iconmark = 'record'; }
				 
				 if( objData[key]['Type']==0 ){
					var marker = PanelMapPlanning.addMarker(GoogleLatLng,{cursor:'outlet_'+objData[key]['Id'], icon:'images/'+iconmark+'.png'},false,false,null,tooltip);
				 }else{
					var marker = PanelMapPlanning.addMarkerInfoWin(GoogleLatLng,{cursor:'outlet_'+objData[key]['Id'], icon:'images/'+iconmark+'.png'},false,false,null,tooltip,objData[key]['OrderInTrip2']);
				 }
				 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];
						var point = {lat: parseFloat(LocX), lng: parseFloat(LocY)};
						//var point = new google.maps.LatLng(parseFloat(LocX),parseFloat(LocY));
						flightPlanCoordinates.push(point);
						
						}
					//}
					if (globalRouteLinePlan) {
						globalRouteLinePlan.setMap(null);		
					}
					globalRouteLinePlan = PanelMapPlanning.addPolylineBounds(flightPlanCoordinates,{strokeColor: '#538929',strokeOpacity: 1.0,strokeWeight: 3} );
					
					}
		});
		
		
		
		
		
		
		
		}
		});
		
	}
	
	function clearMapLogist(){
			if (globalMarkerObjPlan) {
				for (var key in globalMarkerObjPlan){
					globalMarkerObjPlan[key].setMap(null);
				}
				globalMarkerObjPlan = [];
			}
			
			if (globalRouteLinePlan) {
				globalRouteLinePlan.setMap(null);		
			}
			
			if (globalMarkerObjOrder) {
			for (var key in globalMarkerObjOrder){
				globalMarkerObjOrder[key].setMap(null);
			}
			globalMarkerObjOrder = [];
			}
			
			if(Ext.getCmp('buttonCheckOrdersOnMap').pressed == true){
				Ext.getCmp('buttonCheckOrdersOnMap').toggle(false);
			}
			PanelMapPlanning.deleteMapDrawingTools();
	}
	
	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 project = Ext.getCmp('project_planning_id').getValue();
		   
		   /*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,
					project: project
				}
		   });
		   
		   
		   
		   setTimeout(function(){		                				  
				//Ext.getCmp('TOiR_TripPlanningGridId').getSelectionModel().select(selectedIdx);		 
				Ext.getCmp('TOiR_TripPlanningGridId').getSelectionModel().select(globalSelectedIndex, true);
		   }, 500);
}

function unLockTrip(trip_id){	
	$.post('app/LogistMobile_facttrip.php', {unLockTrip: true, trip_id: trip_id}, function (data) {
		Ext.Msg.alert(all_toir.message, plan_toir.route_unlocked);
		Ext.getCmp('lock_button_id').disable(true);
		reloadTripStore();
	});
}
function lockReleaseTrips(projectId){
	$.post('app/LogistMobile_facttrip.php', {lockTrips: true, projectId: projectId}, function (data) {
		
	});
}





// +++ change car function
function showChangeCarWindow(trid,crid) {

var time = Ext.getCmp('planning_date_id').getRawValue();
var project = Ext.getCmp('project_planning_id').getValue();
Device_store_change.load({
	params: { time: time }
});	
	
if (!createChangeCarWindow) {	 
	createChangeCarWindow = new Ext.Window({
		         layout : 'border',
		         //title : 'Смена устройства в рейсе',
		         title : plan_toir.changing_device_trip,
		         closeAction : 'destroy',
		         width : 315,
		         height : 120,
		         modal: true,
		         //minimizable: true,
					constrainHeader: true,
					resizable: false,
		         //maximizable:true,
		         //x : parseInt(Xcoord),
		         //y : parseInt(Ycoord),
					listeners : {
						destroy : function(){
							createChangeCarWindow = null;						
		         	}
		         },
		         items: [
					new Ext.create('Ext.form.Panel', {
		        	 border: false,
						frame: true,
					 layout: {
							type: 'vbox',
							align: 'stretch'
						},
		        	 //width : 300,
			         //height : 150,
			         //id: 'trip_form_id2',
		        	 items: [
						{
			        	 xtype: 'combo',
			        	 //fieldLabel: 'Выберите устройство',
			        	 fieldLabel: plan_toir.select_device,
			        	 store: Device_store_change, //TOiR_UsersPlanningTripStore,
			        	 allowBlank: false,
			        	 margin: '5 5 5 5',
			        	 labelWidth: 130,
						 width: 280,
						 editable: false,
			        	 //id: 'bind_master_id',
			        	 valueField: 'ID',
			        	 displayField: 'Login',
			        	 name: 'trip_master',
			        	 queryMode: 'local',
						 listeners:{
								select:function(combo, records, eOpts){
										//records[0].data.CarId;
										//records[0].data.ID;
										
					Ext.Ajax.request({
		            url: 'app/LogistMobile_facttrip.php',
		            method: 'POST',
					waitMsg: all_toir.loading,					
					wait: true,
		            params: {"func":"checkCarIn","ID":records[0].data.ID,"CarId":records[0].data.CarId,"time":time,"project":project},
		            success: function(response) {
						var JSON = response.responseText;
		                if (JSON) {
		                    var decoded = Ext.decode(JSON);
							if(!decoded.message || decoded.message==0){
								changeCarInTrip(records[0].data.CarId,records[0].data.ID,crid,trid,time,project);
								
							}else{
								console.log(crid +' - '+ records[0].data.ID);
								if(crid != records[0].data.ID){
								Ext.MessageBox.confirm(all_toir.attention, plan_toir.device_use_another_trip,  function(btn){
								if(btn=='yes'){
									changeCarInTrip(records[0].data.CarId,records[0].data.ID,crid,trid,time,project,true);
								}});
								}else{ Ext.MessageBox.alert(all_toir.error, plan_toir.this_device_assigned); }
							}
						}
		            },
		            failure: function(response) {
		                Ext.MessageBox.alert(all_toir.error, response.responseText);
		            }
					});
										
								}
						 }
						}
					 ]
					})
				 ],
		         buttons: [
					/*{
						//text:'Сохранить',
						text: all_toir.save,
						iconCls:'save',
						handler: function() {
						}
					},*/
					{
						//text: 'Отмена',
						text: all_toir.cancel,
						iconCls:'cancel',
						handler: function(){
							createChangeCarWindow.destroy();	                	
						}
					}
				 ]
	});
}
createChangeCarWindow.show();
}
// +++ change car function


function changeCarInTrip(carid,login,loginold,trid,time,project,between){
	if(between){ between = true; }
	Ext.Ajax.request({
	url: 'app/LogistMobile_facttrip.php',
	method: 'POST',
	//waitMsg: all_toir.loading,					
	//wait: true,
	scope: this,
	params: {"func":"changeCarIn","carid":carid,"login":login,"loginold":loginold,"trid":trid,"between":between,"time":time,project:project},
	success: function(response) {
		console.log(response.responseText);
		if (response.responseText) {
		    var decoded = Ext.decode(response.responseText);
			if(decoded.success==true){
				Ext.MessageBox.alert(all_toir.skill, plan_toir.device_changed_trip);
				createChangeCarWindow.destroy();
									var Project_ID = Ext.getCmp('project_planning_id').getValue();
									var time = Ext.getCmp('planning_date_id').getRawValue();

									Ext.getCmp('TOiR_TripPlanningGridId').store.load({
									params: {
										time: time,
										project: Project_ID
									}
									});
			}else{
				Ext.MessageBox.alert(all_toir.error, decoded.message);
			}
		}
		
	},
	failure: function(response) {
		console.log(response.responseText);
		Ext.MessageBox.alert(all_toir.error, response.responseText);
	}
	});
	
}



function export_xls_run_trip(id, id_organization, date_to, date_from, str_drivers)
{
	var time = Ext.getCmp('planning_date_id').getRawValue();
	var project = Ext.getCmp('project_planning_id').getValue();

    $.post("app/LogistMobile_facttrip.php",{"export_xls":true, "time":time, "project":project, "globalClientID":globalClientID }, function(data){
        //console.log(data);
        window.open('app/LogistMobile_facttrip.php?save_export_xls=true', '_blank');
        //alert('Данные сохранены');
    });                                   
}


function showItineraryWindow(){
	var time = Ext.getCmp('planning_date_id').getRawValue();
	var project = Ext.getCmp('project_planning_id').getValue();
	
	
	Ext.Ajax.request({
		url: 'app/LogistMobile_facttrip.php',
        method: 'POST',
        params: { 'print':true, "time":time, "project":project  },
        success: function(response) {
				//alert(response.responseText);
				var obj = Ext.decode(response.responseText);
				if(!obj || obj=="" || obj=="null" || obj==null){
					Ext.MessageBox.alert(all_toir.error, plan_toir.no_trips_routing_sheet);
				}else{
					
					if (globalClientID == 120) {
						show_print_window_120(obj);
					}else{
						show_print_window(obj);
					}
				}				
        },
        failure: function(response) {
            Ext.MessageBox.alert(all_toir.error, response.responseText);
        }
	});
}


function show_print_window(obj){
	
	var windowHTML = '<html><head><title>Print</title></head><style type="text/css">@media all {.page-break  { display: none; }}@media print {.page-break  { display: block; page-break-before: always; }}</style><body>';
	//windowHTML += '<table style="font-size: 12px; font-family: calibri, sans-serif; width:100%;" border="1" cellpadding="1" cellspacing="0"><tbody>';
	
	for(key in obj['facttrip']){
		//console.log('==facttrip==');
		//console.log(obj['facttrip'][key]);
		
		windowHTML += '<table style="font-size: 12px; font-family: calibri, sans-serif; width:100%;" border="1" cellpadding="1" cellspacing="0"><tbody>';
		windowHTML += '<tr><td colspan="8"><center><b>Маршрутный лист</b></center></td></tr><tr>'+
		'<td><b>Рейс №</b></td><td colspan="7"><b>'+obj['facttrip'][key]['ID']+'</b></td></tr><tr>'+
		'<td><b>Машина:</b></td><td colspan="7"><b>'+obj['facttrip'][key]['car_name']+'</b></td></tr><tr>'+
		'<td><b>Водитель:</b></td><td colspan="7"><b>'+obj['facttrip'][key]['driver']+'</b></td></tr>'+
		'<tr><td>Время старта:</td><td colspan="3">'+obj['facttrip'][key]['StartTime']+'</td><td>Время финиша:</td><td colspan="3">'+obj['facttrip'][key]['EndTime']+'</td></tr>'+
		'<tr><td>Макс. вес:</td><td colspan="3">'+obj['facttrip'][key]['sumWeight']+'</td><td>Макс. объем:</td><td colspan="3">'+obj['facttrip'][key]['sumVolume']+'</td></tr>'+
		'<tr><td>Пробег, км:</td><td colspan="3">'+obj['facttrip'][key]['Distance']+'</td><td>Продолжительность:</td><td colspan="3">'+obj['facttrip'][key]['Time']+'</td></tr>'+
		'<tr><td>Стоимость, грн:</td><td colspan="3">'+obj['facttrip'][key]['sumCost']+'</td><td>Кол-во точек:</td><td colspan="3">'+obj['facttrip'][key]['count']+'</td></tr>';
		
		/*if (globalClientID == 120) {
			windowHTML += '<tr><td>CustomStr1:</td><td>-</td><td>CustomStr2:</td><td>-</td><td>CustomStr3:</td><td>-</td><td>CustomStr4:</td><td>-</td></tr>';
			windowHTML += '<tr><td>CustomStr5:</td><td>-</td><td>CustomStr6:</td><td>-</td><td>CustomStr7:</td><td>-</td><td>CustomStr8:</td><td>-</td></tr>';
		}*/
		
		windowHTML += '<tr><td><b>№</b></td><td colspan="2"><b>Клиент</b></td><td><b>Адрес</b></td><td><b>Вес</b></td><td><b>Объем</b></td><td><b>Прибытие</b></td><td><b>Разгрузка</b></td></tr>';
		
		for(key2 in obj['checkpoint'][obj['facttrip'][key]['ID']]){
			//console.log('==checkpoint==');
			//console.log(obj['checkpoint'][obj['facttrip'][key]['ID']][key2]);
			var address = obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['Address'];
			var weight = obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['CargoValueWeight'];
			var volume = obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['CargoValueVolume'];
			var client = obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['ClientName'];
			address = address ? address : "";
			weight = weight ? weight : "";
			volume = volume ? volume : "";
			client = client ? client : "";
			windowHTML += '<tr><td>'+obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['chID']+'</td><td colspan="2">'+client+'</td><td>'+address+'</td><td>'+weight+'</td><td>'+volume+'</td><td>'+obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['EstimateTime']+'</td><td>'+obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['DurationInPoint']+'</td></tr>';
			
		}
		windowHTML += '</tbody></table><div class="page-break"></div>';
	}
		windowHTML += '</body></html>';
		
		
		
		window_open_print(windowHTML);
		
		
}

function show_print_window_120(obj){
	
	var windowHTML = '<html><head><title>Print</title></head><style type="text/css">@media all {.page-break  { display: none; }}@media print {.page-break  { display: block; page-break-before: always; }}</style><body>';
	
	for(key in obj['facttrip']){
				
		windowHTML += '<table style="font-size: 12px; font-family: calibri, sans-serif; width:100%;" border="1" cellpadding="1" cellspacing="0"><tbody>';

		windowHTML += '<tr><td colspan="10"><center><b>Маршрутный лист</b></center></td></tr>'+
		'<tr><td></td><td><b>Покупатель</b></td><td><b>Адрес доставки</b></td><td><b>Бумага</b></td><td><b>Пач.</b></td><td><b>Мест</b></td><td><b>Документ счет</b></td><td><b>Примечание</b></td><td><b>Место на складе</b></td><td><b>Менеджер</b></td></tr>';
		
		for(key2 in obj['checkpoint'][obj['facttrip'][key]['ID']]){

			var address = obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['Address'];
			var client = obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['ClientName'];
			address = address ? address : "";
			client = client ? client : "";
			
			/*
			var weight = obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['CargoValueWeight'];
			var volume = obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['CargoValueVolume'];
			weight = weight ? weight : "";
			volume = volume ? volume : "";
			*/
			windowHTML += '<tr><td>'+obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['OrderInTrip']+'</td><td>'+client+'</td><td>'+address+'</td><td>'+obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['CustomString1']+'</td><td>'+obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['CustomString2']+'</td><td>'+obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['CustomString3']+'</td><td>'+obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['CustomString4']+'</td><td>'+obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['CustomString5']+'</td><td>'+obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['CustomString6']+'</td><td>'+obj['checkpoint'][obj['facttrip'][key]['ID']][key2]['CustomString7']+'</td></tr>';
			
		}
		windowHTML += '</tbody></table><div class="page-break"></div>';
	}
		windowHTML += '</body></html>';
		
		window_open_print(windowHTML);
			
}

function window_open_print(windowHTML) {
		var w = window.open("", "", "width=830,height=1200,left=100,top=100,resizable=yes,scrollbars=yes");
		if(w){
		w.document.write(windowHTML);
		if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1){
                w.PPClose = false;                                  
                w.onbeforeunload = function(){                        
                    if(w.PPClose === false){                           
                        return 'Необходимо нажать отмена в окне печати!"';
                    }else {
                        w.PPClose = true;
                    }
                }
				w.print();
				w.PPClose = true;									   
				w.close();
		}else{
				w.print();
				w.close();
		}
		}
}

/* window block car snapshot --> */	
function show_LogistMobile_carsnapshot_Window() {
	
	Ext.define('carsnapshotLogistMobileModel', {
	    extend: 'Ext.data.Model',
		fields: ['Login','Login2',{name: 'indoor', type: 'bool'}]
	});
	var project = Ext.getCmp('project_planning_id').getValue();
	var carsnapshotLogistMobileStore = new  Ext.data.Store({   
			//autoLoad: true,	
	        model: 'carsnapshotLogistMobileModel',
	        proxy: 
	        {
	          type: 'ajax',
	          url: 'app/LogistMobile_facttrip.php?showcarsnapshot=true&project='+project,
	          reader: 
	          {
	            type: 'json',
	            root: 'rows'
	          }
	        },
			listeners: {
				load: function(store, records, successful, operation, eOpts) {
					
					store.each(function(record){
						if( record.get('indoor') == true ){
							Ext.getCmp('carsnapshotLogistMobileBtnBlockAll').setText(available_cars.btnunblockcarsnapshotall);
							Ext.getCmp('carsnapshotLogistMobileBtnBlockAll').toggle(true);
						}
					});
				}
			}
	});
	carsnapshotLogistMobileStore.load();
	
	/*setTimeout(function(){
        carsLogistMobileStore.load();
    }, 10000);*/
	
	if (!LogistMobile_carsnapshot_Window) {
		//Xcoord = Xcoord ? Xcoord :40;
	    //Ycoord = Ycoord ? Ycoord :60;  
	    //Wwidth = Wwidth ? Wwidth :1100;  
	    //Wheight = Wheight ? Wheight :600;
	    Xcoord = 40;
	    Ycoord = 60;  
	    Wwidth = 360;  
	    Wheight = 250;
			
		
	    var carsnapshotLogistMobileGrid = new Ext.grid.Panel({
	    	selType: 'rowmodel',
	        columnLines: true,
	        layout: 'fit',
	        store:  carsnapshotLogistMobileStore,
	        loadMask: true,
	        border: false,
	        autoScroll: true,
	        viewConfig: {
	        	preserveScrollOnRefresh: true,
	        },	        
	        columns:[
			{
	        	xtype: 'rownumberer',
				width: 30,	
	        },
			{
	        	//text: 'Авто',
				text: available_cars.auto,
	        	dataIndex: 'Login',
	        	//style: 'text-align:center',            
	            //align: 'center',
	        	sortable: false,
	        	width: 200,
	        },
			{
				xtype: 'checkcolumn', 
				//text: 'Блокировать авто', 
				text: available_cars.block_cars, 
				width: 117, 
				dataIndex: 'indoor', 
				hideable: false, 
				sortable: false,
				listeners:
                {
                    checkchange:function(CheckColumn, rowIndex, checked, eOpts )
                    {
						var row = carsnapshotLogistMobileStore.getAt(rowIndex);
						
						if(checked){ text_checked = available_cars.block;}else{ text_checked = available_cars.unblock;}
						
						//Ext.MessageBox.confirm(all_toir.attention, text_checked+' '+available_cars.car_for_planning,  function(btn){
						//		if(btn=='yes'){
									
						Ext.Ajax.request({
						url: 'app/LogistMobile_facttrip.php',
						method: 'POST',
						params: { blockcarsnapshot:true, 'login[]':row.get('Login2'), checked:checked, project:project },
						success: function(response) {
							//console.log(response);
						},
						failure: function(response) {
							//console.log(response);
							Ext.MessageBox.alert(all_toir.error, '');
						}
						});
									
						//		}else{
						//			row.set('indoor') == false;
						//		}
						//});
						
						
					}
				}
			}
			],
			tbar:[
				{
					text: available_cars.btnblockcarsnapshotall,
					id: 'carsnapshotLogistMobileBtnBlockAll',
					pressed: false,
					enableToggle: true,
					handler: function(){
						if(this.pressed){
							this.setText(available_cars.btnunblockcarsnapshotall);
							carsnapshotLogistMobileStore.each(function(record){
								record.set('indoor',true);
							});
						}else{
							this.setText(available_cars.btnblockcarsnapshotall);
							carsnapshotLogistMobileStore.each(function(record){
								record.set('indoor',false);
							});
						}
								Ext.Ajax.request({
								url: 'app/LogistMobile_facttrip.php',
								method: 'POST',
								params: { blockcarsnapshotall:true, project:project, pressed:this.pressed },
								success: function(response) {
									//console.log(response);
								},
								failure: function(response) {
									//console.log(response);
									Ext.MessageBox.alert(all_toir.error, '');
								}
								});
					}
				}
			],
	        listeners: {
	        	itemclick: function(cmp, records) {
					
	        	}	
	        }
	    	
	    });	    
	    
		
		
	        Ext.getBody().mask(all.loading);
	        LogistMobile_carsnapshot_Window = new Ext.Window({
	            layout : 'fit',
	            //title: 'Автомобили в рейсе',
	            title : available_cars.cars_in_trip,
	            closeAction : 'destroy',
	            width : parseInt(Wwidth),
	            height : parseInt(Wheight),
	            //maximizable:true,
				modal: true,
				constrain : true,
				resizable: true,
				//x : 2,
	            //y : 29,
	            defaults: {
	                //collapsible: true,
	                //split: true,
	            },
				listeners : {
	            	destroy : function(){
	            		LogistMobile_carsnapshot_Window = null;
						
	            	}
	            },
	            items: [carsnapshotLogistMobileGrid]
			})      
		LogistMobile_carsnapshot_Window.show(); 
		Ext.getBody().unmask(all.loading);

	}
}
/* <-- window block car snapshot --- */	



/* --- window variable data 19.01.2016 --> */	
function show_LogistMobile_VariableData_Window() {
	
	
	
	if (!LogistMobile_VariableData_Window) {
		Ext.getBody().mask(all.loading);
	        LogistMobile_VariableData_Window = new Ext.Window({
	            layout : 'fit',
	            title : routes_LogistMobile.variable_data,
	            closeAction : 'destroy',
	            width: 190,
	            height: 180,
	            //maximizable:true,
				modal: true,
				constrain : true,
				resizable: false,
				//x : 2,
	            //y : 29,
	            defaults: {
	                //collapsible: true,
	                //split: true,
	            },
				listeners : {
	            	destroy : function(){
	            		LogistMobile_VariableData_Window = null;	
	            	}
	            },
	            items: [
					new Ext.create('Ext.form.Panel', {
					id: 'formvariabledata',
					bodyPadding: '2 2 2 3',
					border: false,
					frame: true,
					defaults: {
					msgTarget: 'side'
					},
					items:[
						{
						xtype: 'fieldcontainer',
						layout: 'hbox',
						defaults: {
							anchor:'100%'
						},
						items: [
							{
								xtype: 'numberfield',
								//fieldLabel: 'Время у клиента',
								fieldLabel: routes_LogistMobile.client_time,
								name: 'variabledata1',
								allowBlank: false,
								width: 160,
								minValue: 0,
								maxValue: 300,
								labelWidth: 100
							}
						]
						},
						{
						xtype: 'fieldcontainer',
						layout: 'hbox',
						defaults: {
							anchor:'100%'
						},
						items: [
							{
								xtype: 'numberfield',
								//fieldLabel: 'Время на складе',
								fieldLabel: routes_LogistMobile.warehouse_time,
								name: 'variabledata2',
								allowBlank: false,
								width: 160,
								minValue: 0,
								maxValue: 300,
								labelWidth: 100
							}							
						]
						},
						{
						xtype: 'fieldcontainer',
						layout: 'hbox',
						defaults: {
							anchor:'100%'
						},
						items: [
							{
								xtype: 'numberfield',
								//fieldLabel: 'Коэффициент скорости',
								fieldLabel: routes_LogistMobile.speed_coefficient,
								name: 'variabledata3',
								allowBlank: false,
								width: 160,
								labelWidth: 100,
								minValue: 1,
								maxValue: 2,
								decimalPrecision: 1,
								allowDecimals: true,
								step: 0.1
							}
						]
						}
					],
					buttons:[
						{
								xtype: 'button',
								text: 'Сохранить',
								margin: '0 0 0 5',
								handler: function(){
									var value = Ext.getCmp("formvariabledata").getForm().findField('variabledata1').getValue()+';'+Ext.getCmp("formvariabledata").getForm().findField('variabledata2').getValue()+';'+Ext.getCmp("formvariabledata").getForm().findField('variabledata3').getValue();
									variable_data_getset('VariableDataSet',-1,value);         	
								}
						}
					]
					})
				]
			})      
			LogistMobile_VariableData_Window.show();
			
			//1 - разгрузка для ТТ
			//2 - разгрузка для склада
			//3 - коэффициент скорости
			var form = Ext.getCmp("formvariabledata").getForm().getFields();
			var i = 1;
			//form.each(function(item){
					//variable_data_getset('VariableDataGet',i,item.name);
				//i++;
			//});
			
			variable_data_getset('VariableDataGet',-1,'');
				
			
		Ext.getBody().unmask(all.loading);
	}
	
	
	
	
	
}

function smallcheckwebtaskprogress(id){

		var me = this,
        i = 0,
        fn;

        MessageBoxProgress = Ext.MessageBox.show({
			//title: 'Задача в обработке',
            title: routes_LogistMobile.taskprogress,
			//msg: 'Loading items...',
            progressText: all.loading+'...',
            width:300,
            progress:true,
            closable:false,
            //animateTarget: btn
        });

        // Fake progress fn
        fn = function() {
            //var id = 8;
			$.post("app/LogistMobile_checkwebtaskprogress.php",{id:id}, function(data){
				var obj = Ext.decode(data);
				if(obj.success == true){
				if(obj.data.length > 0){
					if(obj.data[0].in_progress == 1){
						MessageBoxProgress.hide();
						MessageBoxProgress = null;
						
						//alert(obj.data[0].result_message);
						
						
						if(!obj.data[0].result_message || obj.data[0].result_message=='null'){
							Ext.MessageBox.alert(all_toir.attention, routes_LogistMobile.taskprogresscomplete);
						}else{
							var result = obj.data[0].result_message.split(';');
							//for(key in result){
							//	var i = key++;
							//	Ext.getCmp("formvariabledata").getForm().findField('variabledata'+i).setValue(result[key]);
							//}
							Ext.getCmp("formvariabledata").getForm().findField('variabledata1').setValue(result[0]);
							Ext.getCmp("formvariabledata").getForm().findField('variabledata2').setValue(result[1]);
							Ext.getCmp("formvariabledata").getForm().findField('variabledata3').setValue(result[2]);
						}

					}else if(obj.data[0].in_progress == -1){
							//var obj = Ext.decode(obj.data[0].result_message);
							//{"ru":"Необработанное исключение"."ua":"Необроблене виняток"."en":"Unhandled exception".}
							//lang
							Ext.MessageBox.alert(all_toir.attention, obj.data[0].result_message);
							//Ext.MessageBox.alert(all_toir.attention, obj.data[0].result_message);
					}else{
						var val = obj.data[0].progress_percent / 100;
						Ext.MessageBox.updateProgress(val, obj.data[0].progress_percent + '%');
						setTimeout(fn, 1000);
					}
				}else{
					MessageBoxProgress.hide();
					MessageBoxProgress = null;
					Ext.MessageBox.alert(all_toir.error, obj.message);
				}
				}else{
					MessageBoxProgress.hide();
					MessageBoxProgress = null;
					Ext.MessageBox.alert(all_toir.error, obj.message);
				}

			}).fail(function(){});
			
        };
        setTimeout(fn, 1000);
	
	return fn;
}



function variable_data_getset(param,settingType,value){
		
		Ext.Ajax.request({
		url: 'app/LogistMobile_facttrip.php',
		method: 'POST',
		scope: this,
		wait: true,
		params: {func:param,type:settingType,value:value},
		success: function (response){
			var JSON = response.responseText;
		    if (JSON) {
				var decoded = Ext.decode(JSON);
				smallcheckwebtaskprogress(decoded['message']);
			}
		},
		failure: function (response){ 
			
		}
		});
		
}
/* <-- window variable data --> */



function Show_Uploads_Window_ImportTrip(project)
{
    if(!Uploads_Window_ImportTrip){
         Uploads_Window_ImportTrip = new Ext.Window({
                        width: 390,
                        height: 110,
                        //title: 'Загрузка файлов',
                        title: all_toir.upload_files,
                        closeAction : 'destroy',
                        layout:'border',
						//iconCls: 'Load16',
                        resizable:false,
                        modal:true,
						constrainHeader: true,
						listeners: {
							destroy : function(){
								Uploads_Window_ImportTrip = null;
							}
						},
                 items:[
		Ext.create('Ext.form.Panel', {
        width: '100%',
        bodyPadding: '5 5 5 5',
		border: false,
		frame: true,
        defaults: {
			fileUpload: true,
            msgTarget: 'side'
        },
		items: [
		{
            xtype: 'filefield',
            name: 'file',
            //emptyText: 'Выберите файл для загрузки',
            emptyText: all_toir.select_file_upload,
			width: 357,
            //buttonText: 'Открыть',
            buttonText: all_toir.open,
			allowBlank: false,
			//clearOnSubmit: true,
			listeners:{
						change: function(val, value, eOpts ){
							
							var form = this.up('form').getForm();
							if(form.isValid()){
							if(value){
							var extn = value.split('.').pop();
							console.log(extn);
							if((extn=='xml') || (extn=='XML')){
								
							}else{
								//val.reset();
								form.reset();
								//val.setValue('');
								//val.setRawValue('');
								Ext.MessageBox.alert(all_toir.error, all_toir.incorrect_file_format);
							}
							}
							}
						}
			}
        }
		],
		buttons:[
								{ 
                                //text:'Загрузить',
                                text:all_toir.upload,
                                id:'buttonUploadsLMcheckpoint',
								//iconCls:'Load16',
								 handler: function() {
									
									
				var form = this.up('form').getForm();
                if(form.isValid()){
                    form.submit({
                        //url: 'scripts/UploadFiles.php',
						url: 'app/Logist/file-upload.php',
                        //waitMsg: 'Загрузка...',
                        waitMsg: all_toir.loading3,
						wait:true,
						scope: this,
						method: 'post',
						timeout : 60000,
						params: {project:project, trip:true},
                        success: function(fp, o) {
							//alert(o.result.success);
							if(o.result.success == true){
								//var result = checkwebtaskprogress(o.result.message,false,completedCheckCheckpointUpdate.name);
								var result = checkwebtaskprogress(o.result.message,true);
							}else{
								Ext.MessageBox.alert(all_toir.error, o.result.message);
							}
							
                        },
						failure: function(fp, o) {
							Ext.MessageBox.alert(all_toir.error, o.result.message);
						}
                    });
                }
									

								 }
                                },
								
								{ 
                                //text:'Отмена',
                                text:all_toir.cancel,
                                id:'buttonCancel',
                                handler:function(){
                                        Uploads_Window_ImportTrip.destroy();        
                                           }

                                }
								]
		})	 
				 ]
                     

                })      
         
     }
    Uploads_Window_ImportTrip.show(); 
	
}



function update_status_route(){
	var time = Ext.getCmp('planning_date_id').getRawValue();
	var project = Ext.getCmp('project_planning_id').getValue();
	
//var record = Ext.getCmp('TOiR_TripPlanningGridId').getView().getSelectionModel().getSelection()[0];
	    		    			
								LogistMobile_TripPlanningStoreRoutes_factrip.load({
	                				   params: {
	                					   time: time,
										   project: project
				           				}
								});
	
	//if(record){ Ext.getCmp('requestPlanningGrigId').getSelectionModel().select(record, true); }
	//alert(globalSelectedIndex);
	Ext.getCmp('TOiR_TripPlanningGridId').getSelectionModel().select(globalSelectedIndex, true);
	
	/*
	$.post("app/LogistMobile_facttrip.php",{func:'update_status_route',project:project}, function(data){
	if(data){
		var obj = Ext.decode(data);
		var i=0;
		LogistMobile_TripPlanningStoreRoutes_factrip.each(function(record){
			//console.log(record.get('Closed3'));
			if(obj[i]){ record.set(obj[i]); }
			i++;
		});
		Ext.getCmp('TOiR_TripPlanningGridId').getView().refresh();
	}
	});
	*/
}

function update_status_point(){
					pointsVisitStoreRoutes_factrip.load({
	        			params: {
						userID: globalUserIDRout,
						FactTripID: globalFactTripID,
        				time: time
						}
	        		});
}





function show_LogistMobile_ManualPlanning_Window(row){
   
	
	
    if(!LogistMobile_ManualPlanning_Window){
		
		var lat = getCookie("MapCenter_latitude");
		var lng = getCookie("MapCenter_longitude");
		
		var PanelMapForManualPlanning = Ext.create('Ext.ux.GMapPanel', {
	    zoomLevel: 11,
	    gmapType: 'map',
	    //padding: 170,
		mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
	    setCenter: {
	        lat:lng,
	        lng:lat
	    }
		});
		
		
		var StoreManualPlanning = new Ext.data.Store({    
		fields: ['ID','Client','WarehouseType','Code','OriginalAddress','StartTime','EndTime','LoadUnloadTime','GeoX','GeoY','Name','OrderInTrip','OrderInTrip2','EstimateTime','Duration','Distance','CustomInt','Priority','CustomString1','CustomString2','CustomString3','CustomString4','CustomString5','CustomString6','CustomString7','CustomString8','PointState','Trip_ID','DurationInPoint','WarehouseType2',{name: 'Duration2', type: 'float'},{name: 'Distance2', type: 'float'}],
		groupField: 'Trip_ID'
		});
		
		
		var pointsVisitStoreRoutesTemp = new Ext.data.Store({    			
	    fields: ['ID','Client','WarehouseType','Code','OriginalAddress','StartTime','EndTime','LoadUnloadTime','GeoX','GeoY','Name','OrderInTrip','OrderInTrip2','EstimateTime','Duration','Distance','CustomInt','Priority','CustomString1','CustomString2','CustomString3','CustomString4','CustomString5','CustomString6','CustomString7','CustomString8','PointState','Trip_ID','DurationInPoint','WarehouseType2'],
		model: 'bind_factrip',
	       proxy: {
	          type: 'ajax',
	          url: 'app/LogistMobile_facttrip.php?func=tms_trippoint',
	          reader: {
	            type: 'json',
	            root: 'rows'
	          }
		   }
		});
		pointsVisitStoreRoutesTemp.load({
	    	params: {
	    	FactTripID: globalFactTripID				           					
	    	}
		});
		
		
		var GridManualPlanning = new Ext.grid.Panel({
	    	//title: '',
	    	selType: 'rowmodel',
	        columnLines: true,
	        //layout: 'fit',
	        id: 'GridManualPlanningId',
	        store:  StoreManualPlanning,
	        loadMask: true,
	        border: false,
	        autoScroll: true,
	        viewConfig: {
	        	preserveScrollOnRefresh: true,
	        },
			/*features: [{
				ftype: 'summary'
			}],*/
			features: [{
            ftype: 'groupingsummary',
            groupHeaderTpl: '{name}',
			//groupHeaderTpl: '',
            hideGroupedHeader: false,
            enableGroupingMenu: false
			}],
	        columns:[
			/*{
	        	xtype: 'rownumberer',
				width: 30,	
	        },*/
			{text: '', xtype: 'actioncolumn', width: 40, sortable: false, hidden: false, menuDisabled: true, items: [
                {
                    tooltip: '',
                    scope: this,
                    getClass: function(value, metadata, record) {
                                //var confirm = record.get('block');
                                //if (confirm == 1) {
								if( record.get('WarehouseType') == "Магазин" ){
                                    return 'center-icon-del';
								}
                                //}
                    },
                    getTip: function(value, metadata, record) {
                                //var confirm = record.get('block');
                                //if (confirm == 1) {
                                //    return 'Запис блоковано';
                                //}
                    },
					handler: function(grid, rowIndex, colIndex){
      
						var record1 = grid.getStore().getAt(rowIndex);
						
						if( record1.get('WarehouseType2') == 2 ){
						
						var array_record_del = new Array();
						var array_record_del_id = new Array();
						
						var record_del = record1;
						var record_del_id = record1.get('ID');
						var record_del_x = record1.get('GeoX');
						var record_del_y = record1.get('GeoY');
						
						array_record_del_id.push(record_del_id);
						array_record_del.push(record1);
						//alert('record_del_id '+record_del_id);
						
						
						// --- удаляем маршрут с карты ---
						if (arrOfRoutsObj.length > 0) {
						for (var key in arrOfRoutsObj) {
							arrOfRoutsObj[key].setMap(null);
						}
						arrOfRoutsObj = [];
						}
						
						
						
						//alert('del store count '+Ext.getCmp('GridManualPlanningId').getStore().getData().length);
						
						// --- ищем и удаляем одинаковые координат либо в радиусе 50м от удаляемой ---
						StoreManualPlanning.each(function(record,index){
							var dist = distance_beetwen_to_point(record_del_y,record_del_x,record.get('GeoY'),record.get('GeoX'),'K').toFixed(3) * 1000;
							if( (parseInt(dist) > 0) && (parseInt(dist) < 50) ){
								//alert('== >0 <50 '+record.get('ID'));
								array_record_del_id.push(record.get('ID'));
								array_record_del.push(record);
								Ext.getCmp('GridManualPlanningId').getStore().remove( record );
								PanelMapForManualPlanning.removeOnMapInfoWindowManualPlanning(record.get('ID'));
							}
							else if( parseInt(dist) == 0 ){
								//alert('== 0 '+record.get('ID'));
								array_record_del_id.push(record.get('ID'));
								array_record_del.push(record);
								Ext.getCmp('GridManualPlanningId').getStore().remove( record );
								PanelMapForManualPlanning.removeOnMapInfoWindowManualPlanning(record.get('ID'));
							}
							//alert((index) +1);
							
						});
						
						// --- удаляем точку с грида и обнуляем расстояние и дистанцыю ---
						Ext.getCmp('GridManualPlanningId').getStore().remove( record_del );
						PanelMapForManualPlanning.removeOnMapInfoWindowManualPlanning(record_del_id);
						
						StoreManualPlanning.each(function(record,index){
							record.set('OrderInTrip2',((index) +1));
							record.set('Distance2',0);
							record.set('Duration2',0);
						});
						
						
						// -- возвращаем строки в временной грид
							var i = 0;
							//var indexx = Ext.getCmp('GridManualPlanningId').getStore().getData().length;
							while(i < array_record_del_id.length){
								//var indexx = array_record_del[i].get('OrderInTrip2');
								//alert(indexx);
								Ext.getCmp('GridManualPlanningTempId').getStore().insert( 1, array_record_del[i] );

								i++;
							}
							
							Ext.getCmp('GridManualPlanningTempId').getView().refresh();
						// -- 
						
						
						}
						
						global_index = 1;
						
						//alert('del store count '+Ext.getCmp('GridManualPlanningId').getStore().getData().length);
						Ext.getCmp('GridManualPlanningId').getView().refresh();
						
						
						
						
					}

					
				}]
            },
			{
	        	text: '№',
	        	//text: plan_toir.sequence_number,
	            dataIndex: 'OrderInTrip2',
	            width: 60,
				sortable: false,
				hidden: false,
				summaryRenderer: function(value, summaryData, dataIndex) { return ('Итого:'); }
	        },
			/*{
	        	//text: 'Название',
	        	text: plan_toir.title,
	            dataIndex: 'Name',
	            sortable: false,
				hidden: false
	        },
			{
	        	//text: 'Код',
	        	text: plan_toir.code, 
	            dataIndex: 'Code',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: false,
	            //width: 60
	        },*/
			{
	        	//text: 'Клиент',
	        	text: plan_toir.client, 
	            dataIndex: 'Client',
	            sortable: false,
	        },
			{
	        	text: plan_toir.address, 
	            dataIndex: 'OriginalAddress',
	            sortable: false,
	        },
			{
	        	text: 'Время, мин.',	        	         	 
	            dataIndex: 'Duration2',
	            sortable: false,
				xtype: 'numbercolumn',
				format:'0.00',
				summaryType: 'sum'
				
	        },
			{
	        	text: 'Дистанция, км',	        	         	 
	            dataIndex: 'Distance2',
	            sortable: false,
				xtype: 'numbercolumn',
				format:'0.00',
				summaryType: 'sum'
				/*summaryType: function(records){
							var i = 0,
							length = records.length,
							total = 0,
							record;
							for (; i < length; ++i) {
								record = records[i];
								total += record.get('Distance2');
							}
	                
							total = total.toFixed(2);
							return total;
				},*/
	        },
			{
		        //text: 'Приоритет',
		        text: plan_toir.priority,
				dataIndex: 'Priority',
				width: 60,
				sortable: true,
				hidden: false
			}
			]
		});
		
		
		
		var GridManualPlanningTemp = new Ext.grid.Panel({
	    	selType: 'rowmodel',
	        columnLines: true,
	        id: 'GridManualPlanningTempId',
	        store:  pointsVisitStoreRoutesTemp,
	        loadMask: true,
	        border: false,
	        autoScroll: true,
	        viewConfig: {
	        	preserveScrollOnRefresh: true,
	        },
	        columns:[
			/*{
	        	text: '№',
	            dataIndex: 'OrderInTrip2',
	            width: 60,
				sortable: false,
				hidden: false
			},*/
			{
	        	text: plan_toir.title,
	            dataIndex: 'Name',
	            sortable: false,
				hidden: false
	        },
			{
	        	text: plan_toir.code, 
	            dataIndex: 'Code',
	            style: 'text-align:center',            
	            align: 'center',
	            sortable: false
	        },
			{
	        	text: plan_toir.client, 
	            dataIndex: 'Client',
	            sortable: false,
	        },
			{
	        	text: plan_toir.address, 
	            dataIndex: 'OriginalAddress',
	            sortable: false,
	        },
			{
		        text: plan_toir.priority,
				dataIndex: 'Priority',
				width: 60,
				sortable: true,
				hidden: false
			}
			]
		});
		
		
		var arrOfRoutsObj = [];
		var directionsService = new google.maps.DirectionsService();
		var directionsDisplayPlan = null;

        LogistMobile_ManualPlanning_Window = new Ext.Window({
            width: window.innerWidth,
            height: window.innerHeight,
            title: 'Ручное планирование',
            closeAction : 'destroy',
            listeners : {
                destroy : function()
				{
                    LogistMobile_ManualPlanning_Window = null;
					globalMarkerObjOrder = [];
					global_index = 1;
					PanelMapForManualPlanning.removeOnMapInfoWindowManualPlanningAll();
                },
				afterrender: function( eOpts )
				{
					
				}
            },
            layout: 'border',
            resizable: true,
			maximizable: true,
            //constrainHeader: true,
            modal:true,
			maximizable:true,
			
			constrain : true,
			defaults: {
				//collapsible: true,
				//split: true,
				stateful: true
			},
            items:[
                
            
			{
            title: '',
            collapsible: false,
            width: '60%',
			region: 'center',
			minWidth: 200,
			layout: 'fit',
            //margin: '0 0 0 0',
            items:[ PanelMapForManualPlanning ]
			},
			{
            title:'',
			region:'east',
            width: '40%',
			layout: 'fit',
            //minWidth: 200,
			/*layout: {
				type: 'hbox',
				align: 'stretch'
			},
			defaults: { flex: 1 },*/
			items: [
			
			{
			flex: 1,
            split: false,
            collapsible: false,
			border:false,
			layout: {
				type: 'vbox',
				align: 'stretch'
			},
			defaults: { flex: 1 },
			items: [
			GridManualPlanning,
			GridManualPlanningTemp
			]
			}
			
			//GridManualPlanning,
			//GridManualPlanningTemp
			
			]
			}
   
            ],
                    buttons:[
                    
					{
                        text: 'Показать маршрут',
                        //text: all_toir.cancel,
                        //iconCls:'cancel',
                        handler: function(){
                        
						
						
						try{
				global_index = 1;
				
				var myMask = new Ext.LoadMask(LogistMobile_ManualPlanning_Window, {msg: all.loading});
				myMask.show();		
						
				//alert('Показать маршрут');	
	
				// ---- удаляем ранее просчитнаый маршрут если есть ----
				if (arrOfRoutsObj.length > 0) {
					for (var key in arrOfRoutsObj) {
						arrOfRoutsObj[key].setMap(null);
					}
					arrOfRoutsObj = [];
				}

				// ---- заполняем масив координатами точек latlng ----
				var MarkerObjOrder = [];
				StoreManualPlanning.each(function(record){
					// --- google route ---
					//MarkerObjOrder.push(new google.maps.LatLng(record.get('GeoY'),record.get('GeoX')));
					
					// --- innotech route ---
					MarkerObjOrder.push( record.get('GeoY')+','+record.get('GeoX') );
				});
				
				
				//------------------- innotech route -----------------------
				
				// ---- отправляем на просчет масив координатами точек latlng ----
				Ext.Ajax.request({
						url: 'app/LogistMobile_facttrip.php',
						method: 'POST',
						params: { classGeoRoute:true, 'points[]':MarkerObjOrder},
						success: function(response) {
								if (response.responseText) {
									var decoded = Ext.decode(response.responseText);
									if(decoded.success==true){
										myMask.hide();
										var geoXY = decoded.geoXgeoY;
	for(key in geoXY){
	
	//console.log(geoXY);
	
	var bounds_poly = new google.maps.LatLngBounds();
	var polyline = new google.maps.Polyline({
		path: [],
		//strokeColor: '#538929',
		strokeColor: "#"+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6),
		strokeOpacity: 1.0,
		strokeWeight: 5
	});
	
	var poly = [];
	
	var geoY = geoXY[key]['X'].split(',');
	var geoX = geoXY[key]['Y'].split(',');
	
	var distance = parseFloat(geoXY[key]['Dist']) / 1000;
	distance = distance.toFixed(2);
	var duration = geoXY[key]['Dur'];
	duration = Math.round(duration/60);
	
	for(key2 in geoX){
		//console.log(geoX);
		//console.log(geoY);
		polyline.getPath().push(new google.maps.LatLng(geoX[key2],geoY[key2]));
		bounds_poly.extend(new google.maps.LatLng(geoX[key2],geoY[key2]));
		//poly.push(new google.maps.LatLng(geoX[key],geoY[key]));
		//poly.push({lat: geoX[key], lng: geoY[key]});
		//polyline.getPath().push({lat: geoX[key], lng: geoY[key]});
	}
	//polyline.getPath().push(poly);
	arrOfRoutsObj.push(polyline);
	polyline.setMap(PanelMapForManualPlanning.getMap());
	
	setDistanceDuration(distance,duration,polyline,bounds_poly.getCenter(),PanelMapForManualPlanning);
	
	}
	
	//or(key in arrOfRoutsObj){
	//	arrOfRoutsObj[key].setMap(PanelMapForManualPlanning.getMap());
	//}		
										
									}else{
										Ext.MessageBox.alert(all_toir.error, 'Ошибка расчета маршрута роутинг сервером');
										myMask.hide();
									}
								}else{
									Ext.MessageBox.alert(all_toir.error, 'Ошибка расчета маршрута роутинг сервером');
									myMask.hide();
								}
						},
						failure: function(response) {
							Ext.MessageBox.alert(all_toir.error, 'Ошибка расчета маршрута роутинг сервером');
							myMask.hide();
						}
				});
				
				
				
					
					
					
				
					
					
					
					//------------------- google route -----------------------
/*	 
					var total = 0;
					var totalTime = 0;
					var motionTime = 0;
					distance = 0;
					duration = 0;
					
					if(MarkerObjOrder.length >= 2){
				
					var i = 0;
					var globalRouteAjax = [];
					while(i < MarkerObjOrder.length-1){
					
					var request = {
						      //origin: globalMarkerObjOrder[i].getPosition(),
						      //destination: globalMarkerObjOrder[i+1].getPosition(),
							  origin: MarkerObjOrder[i],
						      destination: MarkerObjOrder[i+1],
						      //waypoints: arrOfWaypoints,
						      optimizeWaypoints: true,
							  provideRouteAlternatives: false,
						      travelMode: google.maps.TravelMode.DRIVING
					};
					var polylineOptionsPlan = {
					      strokeColor: '#538929',
					      strokeOpacity: 1.0,
					      strokeWeight: 5
					};
					
					directionsService.route(request, function(response, status) {
						    
														
							if (status == google.maps.DirectionsStatus.OK){
						    
							
							//directionsDisplayPlan = new google.maps.DirectionsRenderer({
							//	suppressMarkers: true,
							//	polylineOptions: polylineOptionsPlan
							//});
							//directionsDisplayPlan.setDirections(response);

	
					var polyline = new google.maps.Polyline({
						path: [],
						//strokeColor: '#538929',
						strokeColor: "#"+('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6),
						strokeOpacity: 1.0,
						strokeWeight: 5
					});
							
							var bounds_poly = new google.maps.LatLngBounds();

							Ext.each(response.routes[0].overview_path, function(item) {
								polyline.getPath().push(item);
								bounds_poly.extend(item);
							});
							polyline.setMap(PanelMapForManualPlanning.getMap());
							arrOfRoutsObj.push(polyline);
							
							//alert(bounds_poly.getCenter());
							//console.log('++bounds_poly.getCenter++');
							//console.log(bounds_poly.getCenter());

							//globalRouteAjax[globalRouteAjax.length] = directionsDisplayPlan.directions.routes[0].overview_path;
							
							//arrOfRoutsObj.push(directionsDisplayPlan);
							//directionsDisplayPlan.setMap( PanelMapForManualPlanning.getMap() );
							
							var route = response.routes[0];
						    
							//console.log('++route++');
							//console.log(route);
							
							distance = 0;
							//distance = Math.round(route.legs[0].distance.value/1000);
							distance = route.legs[0].distance.value/1000;
							distance = distance.toFixed(2);
							total += distance;
							
							duration = 0;
							duration = Math.round(route.legs[0].duration.value/60);
							motionTime += duration;										
							
							console.log('+++total+++');
							console.log(total);

							console.log('+++motionTime+++');
							console.log(motionTime);
							
							setDistanceDuration(distance,duration,polyline,bounds_poly.getCenter(),PanelMapForManualPlanning);
							
							//alert(bounds_poly.getCenter());
							
							//PanelMapForManualPlanning.clickOnMapPolylineManualPlanning(polyline,bounds_poly.getCenter(),distance,duration);
								
						   } else {
							    Ext.MessageBox.alert(all_toir.error, 'Ошибка расчета маршрута. Directions request failed, '+ status);
								myMask.hide();
						   }
				    });
					
					i++;
					
					}
					
					myMask.hide();
					
					}else{
							Ext.MessageBox.alert(all_toir.error, 'Недостаточно точек для расчета маршрута');
							myMask.hide();
					}
					
*/					
						
					
						
					
					
				 
						
				 
							
						}catch(e) {
							Ext.MessageBox.alert(all_toir.error, 'Error ' + e.name + ":" + e.message + "\n" + e.stack);
							myMask.hide();
						}
						
							
                        }
						
								
					
                    },
					{
                        text: 'Cкрыть/Отобразить',
                        handler: function() {
							//alert(stateInfoWindowManualPlanning);
							stateInfoWindowManualPlanning = PanelMapForManualPlanning.hideOnMapInfoWindowManualPlanning(stateInfoWindowManualPlanning);
							//alert(stateInfoWindowManualPlanning);
						}
					},
					{
                        //text:'Cохранить',
                        text: all_toir.save,
                        iconCls: 'save',
                        handler: function() {
							
							var k = 2;
							var array_pointID = [];
							var array_pointOrderIn = [];
							StoreManualPlanning.each(function(record){
								if( record.get('WarehouseType2') == 2 ){
								array_pointID.push(record.get('ID'));
								array_pointOrderIn.push(record.get('OrderInTrip2'));
								}
							});
							
							var array_pointIDOut = [];
							pointsVisitStoreRoutes_factrip.each(function(record,index){
								if( record.get('WarehouseType2') == 2 ){
								if(array_pointID.indexOf(record.get('ID')) < 0){
									array_pointIDOut.push(record.get('ID'));
								}
								}
							});
							
							Ext.Ajax.request({
							url: 'app/LogistMobile_facttrip.php',
							method: 'POST',
							params: { manualPlanning:true, 'pointID[]':array_pointID, 'pointIn[]':array_pointOrderIn, tripID:globalFactTripID, 'pointOut[]':array_pointIDOut },
							success: function(response) {
								if (response.responseText) {
									var decoded = Ext.decode(response.responseText);
									if(decoded.success==true){
										
										pointsVisitStoreRoutes_factrip.load({
	    					           				params: {
	    					           					FactTripID: globalFactTripID				           					
	    					           				}
	    				           	    });
										
		Ext.getCmp('TOiR_TripPlanningGridId').store.each(function(record){
			if(record.get('TID') == globalFactTripID){
				record.set('indoor',true);
			}					
		});
										
		calculateTripLogist();
										
										LogistMobile_ManualPlanning_Window.destroy();
										
									}else{
										Ext.MessageBox.alert(all_toir.error, decoded.message);
									}
								}else{
									Ext.MessageBox.alert(all_toir.error, '');
								}
							},
							failure: function(response) {
								Ext.MessageBox.alert(all_toir.error, response.responseText);
							}
							});
							
							
					
                        }
                    },
                    {
                        //text: 'Отмена',
                        text: all_toir.cancel,
                        iconCls:'cancel',
                        handler: function(){
                            LogistMobile_ManualPlanning_Window.destroy();
                        }
                    }
					]

            
        });
    }
    LogistMobile_ManualPlanning_Window.show(this, function(){
		
		try{
		console.log(PanelMapForManualPlanning);
	
		if (globalMarkerObjOrder) {
			for (var key in globalMarkerObjOrder){
				globalMarkerObjOrder[key].setMap(null);
			}
			globalMarkerObjOrder = [];
		}
		
		var arrOfMarkers = [];
		var bounds = new google.maps.LatLngBounds();
		
		var totMain = (pointsVisitStoreRoutes_factrip.getData().length) - 1;
		
		pointsVisitStoreRoutes_factrip.each(function(record,index){
			//alert(record.get('ID'));
			
			

			var Client = record.get('Client') ? record.get('Client') : '';
			var Name = record.get('Name') ? record.get('Name') : '';
			var Address = record.get('OriginalAddress') ? record.get('OriginalAddress') : '';
			var Code = record.get('Code') ? record.get('Code') : '';
			var StartTime = record.get('StartTime') ? record.get('StartTime') : '';
			var EndTime = record.get('EndTime') ? record.get('EndTime') : '';
										
										
			var tooltip = '<div class="grad"><p><b>'+plan_toir.name_client+'</b>'+Client+'</p><p><b>'+plan_toir.address+': </b>'+Address+'</p><p><b>'+plan_toir.request_code+': </b>'+Code+'</p><p><b>'+plan_toir.beginning_of_work+': </b>'+StartTime+'</p><p><b>'+plan_toir.end_of_works+': </b>'+EndTime+'</p></div>';

			var GoogleLatLng = new google.maps.LatLng(record.get('GeoY'),record.get('GeoX'));
			
			if( record.get('WarehouseType2') == 2 ){ 
				if(record.get('Priority') == 1){ iconmark = "point_red_16"; }else{ iconmark = "point_16"; }
			}else{ iconmark = 'point_24'; }
			
			var marker = PanelMapForManualPlanning.addMarker(GoogleLatLng,{cursor:'o_'+record.get('ID'), icon:'images/'+iconmark+'.png'},false,false,null,tooltip);
			arrOfMarkers.push(marker);
			
			if( record.get('WarehouseType2') == 2 ){
				PanelMapForManualPlanning.clickOnMapMarkerManualPlanning(marker);
			}
			
			//console.log(record);
			//console.log(index);
			//alert(totMain);
			//alert(index);
			if(index==0){
				record.set('Duration2',0);
				record.set('Distance2',0);
				StoreManualPlanning.insert( index, record );
				record.set('OrderInTrip2',1);
			}
			if(index==totMain){
				record.set('Duration2',0);
				record.set('Distance2',0);
				StoreManualPlanning.insert( index, record );
				record.set('OrderInTrip2',2);
			}
			
			bounds.extend(GoogleLatLng);
			
		});
		
		globalMarkerObjOrder = arrOfMarkers;
		
		//PanelMapForManualPlanning.clickOnMapMarkerManualPlanning(globalMarkerObjOrder);
		
		PanelMapForManualPlanning.getMap().setCenter(bounds.getCenter());
        PanelMapForManualPlanning.getMap().fitBounds(bounds);
		//PanelMapForManualPlanning.fitBounds(bounds);
		
		trafficLayer.setMap(PanelMapForManualPlanning.getMap());
		
		
		}catch(e) {
			Ext.MessageBox.alert(all_toir.error, 'Error ' + e.name + ":" + e.message + "\n" + e.stack);
		}
		
	});
	
	
		
	
	
	
		
	
}


var global_index = 1;
function setDistanceDuration(distance,duration,polyline,bounds,map){
	
	//alert(global_index);
	
	var rec = Ext.getCmp('GridManualPlanningId').getStore().getAt(global_index);
	var durationInPoint = rec.get('DurationInPoint');
	//alert('durationInPoint = '+durationInPoint);
	rec.set('Distance2',parseFloat(distance));
	rec.set('Duration2',(duration + durationInPoint));
	
	map.clickOnMapPolylineManualPlanning(polyline,bounds,distance,duration,durationInPoint);
	
	global_index++;
}


function distance_beetwen_to_point(lat1, lon1, lat2, lon2, unit) {
	var radlat1 = Math.PI * lat1/180
	var radlat2 = Math.PI * lat2/180
	var theta = lon1-lon2
	var radtheta = Math.PI * theta/180
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist)
	dist = dist * 180/Math.PI
	dist = dist * 60 * 1.1515
	if (unit=="K") { dist = dist * 1.609344 }
	if (unit=="N") { dist = dist * 0.8684 }
	return dist
}
