var LogistMobile_routes_Window = null;
var PanelMapRoutes = null;
var globalUserIDRout;
var globalFactTripID;
var directionsService = new google.maps.DirectionsService();

var globalRouteLineFixed = {};
var globalRouteStopFixed = {};
var globalRouteParkFixed = {};
/*Ext.define('LogistMobile_UsersRoutesModel', {
    extend: 'Ext.data.Model',
    fields: ['id' , 'name', {name: 'track', type: 'bool', defaultValue:'false'}]
});
var LogistMobile_UsersRoutesStore = new Ext.data.Store(
  {     
		autoLoad: true,
		//autoDestroy: true,
        model: 'LogistMobile_UsersRoutesModel',
        proxy: 
        {
          type: 'ajax',
          url: 'app/LogistMobile_routes.php?func=showUsers',
          reader: 
          {
            type: 'json',
            root: 'rows'
          }
        }
});*/



/* store and model of grid tms_facttrip --> */
Ext.define('LogistMobile_TripPlanningModelRoutes', {
    extend: 'Ext.data.Model',
	fields: ['ID','TripId','Closed','Car_ID','Login','Login2','Name','WalkerNum','TripPrice','Distance','Time','Comments','StartTime','EndTime','Dispatcher_ID','Driver_ID','Forwarder_ID','Start_speedometer','End_speedometer','Signal',{name: 'bildRoutePlan', type: 'bool'}, {name: 'bildRouteRealPath', type: 'bool'},{name: 'monit_car', type: 'bool', defaultValue: 'false'},'calculate', {name: 'indoor', type: 'bool'}, 'project','dateRelease' ]
});
var LogistMobile_TripPlanningStoreRoutes = new  Ext.data.Store({
		//autoLoad: true,
		groupField: 'project',
        model: 'LogistMobile_TripPlanningModelRoutes',
        proxy: 
        {
          type: 'ajax',
          url: 'app/LogistMobile_routes.php?func=showTrip',
          reader: 
          {
            type: 'json',
            root: 'rows'
          }
        }
});
/* <-- store and model of grid tms_facttrip */



/* store and model of grid tms_checkpoint --> */
Ext.define('LogistMobile_pointsVisitStoreModel', {
    extend: 'Ext.data.Model',
	fields: ['Id', 'StartCheckTime', 'EndCheckTime', 'Description', 'Necessary', 'Name', 'GeoX', 'GeoY', 'PointState', 'Date', 'OrderInTrip', 'Distance', 'Time', 'WaitTime', 'LateTime', 'EstimateTime', 'Address', 'DurationInPoint', 'Type', 'IsOrderPoint', 'StartWorkTime', 'EndWorkTime', 'Code', 'ClientName','calculate']
});
var pointsVisitStore = new Ext.data.Store({     
	//autoLoad: true,				
    model: 'LogistMobile_pointsVisitStoreModel',
       proxy: {
          type: 'ajax',
          url: 'app/LogistMobile_routes.php?func=show',
          reader: {
            type: 'json',
            root: 'rows'
          }
	   }
});

Ext.define('LogistMobile_pointsVisitStoreModelRoutes', {
    extend: 'Ext.data.Model',
    fields: ['Id', 'StartCheckTime', 'EndCheckTime', 'Description', 'Necessary', 'Name', 'GeoX', 'GeoY', 'PointState', 'Date', 'OrderInTrip', 'Distance', 'Time', 'WaitTime', 'LateTime', 'EstimateTime', 'EstimateTimeFact', 'Address', 'DurationInPoint', 'Type', 'IsOrderPoint', 'StartWorkTime', 'EndWorkTime', 'Code', 'ClientName','calculate','EstimateTimeOut','EstimateTimeFactOut']
});
var pointsVisitStoreRoutes = new Ext.data.Store({     
	//autoLoad: true,				
    model: 'LogistMobile_pointsVisitStoreModelRoutes',
       proxy: {
          type: 'ajax',
          url: 'app/LogistMobile_routes.php?func=show',
          reader: {
            type: 'json',
            root: 'rows'
          }
	   }
});
/* <-- store and model of grid tms_checkpoint */



function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}


function completedCheckRoutesUpdate(){
		var time = Ext.getCmp('monitoring_date_id').getRawValue();
		var warehouse = Ext.getCmp('bind_warehouse_monitoring').getRawValue();
		var device = Ext.getCmp('filter_cars_field_monitoring').getValue();
		LogistMobile_TripPlanningStoreRoutes.load({
			params: {
				time: time,
				warehouse: warehouse,
				device: device
			}
		});
}


function filterReportMonitoring(){
					
					//var time = Ext.getCmp('monitoring_date_id').getRawValue();
					
					loadDetails();
					
					
}


/* main window --> */
function show_LogistMobile_routes_Window(Xcoord,Ycoord,Wwidth,Wheight){
	var intervalID = null;
	var intervalID2 = null;
	pointsVisitStoreRoutes.removeAll();
	Xcoord = Xcoord ? Xcoord :40;
    Ycoord = Ycoord ? Ycoord :60;  
    Wwidth = Wwidth ? Wwidth :1100;  
    Wheight = Wheight ? Wheight :600;

	var lot = getCookie("MapCenter_latitude");
	var lat = getCookie("MapCenter_longitude");
	
	Warehouse_store.load();
	
/* map panel --> */	
    PanelMapRoutes = Ext.create('Ext.ux.GMapPanel', {
        zoomLevel:11,
        gmapType: 'map',
        //padding: 170,
    	id: 'routes_map_panel',	
        //width: 325,
        //height: '50%', 
        mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
        setCenter: {
            lat:lat,
            lng:lot
        }
    });
/* <-- map panel */	   
	
/* grid facttrip --> */	
    var PBRoutesGrig = new Ext.create('Ext.grid.Panel',{
        //title: 'Маршруты',
		title: routes_LogistMobile.routes,
    	selType: 'rowmodel',
        columnLines: true,
        id: 'LogistMobile_RoutesGridId',
        layout: 'fit',
        //store: LogistMobile_UsersRoutesStore,
        store: LogistMobile_TripPlanningStoreRoutes,
        loadMask: true,
        border: false,
		frame: false,
        autoScroll: true,
        //bodyPadding: 1, 
		stripeRows: true,
		viewConfig: {
			preserveScrollOnRefresh: true,
    		stateful: false
		},
		features: [{
	  					  ftype: 'groupingsummary',
	  					  groupHeaderTpl: plan_toir.project+': {name}',
	  					  hideGroupedHeader: false,
	  					  enableGroupingMenu: false
	  				  }],
        columns:[
		/*{
			xtype: 'checkcolumn', dataIndex: 'indoor', width: 35, hideable: false, sortable: false
		},*/
		{
        	//xtype: 'rownumberer',
        	text: '№',
        	dataIndex: 'ID',
			width: 40,	
        }, {
        	//text: 'Статус',
			text: routes_LogistMobile.status,
        	dataIndex: 'calculate',
        	style: 'text-align:center',            
            align: 'center',
			width: 50,
        	sortable: false,
        }, {        	
        	//text: 'Название', 
			text: routes_LogistMobile.title, 
            dataIndex: 'Name',
            sortable: true,
            width: 100
        }, {
        	//text: 'Устройство', 
			text: routes_LogistMobile.device, 
            dataIndex: 'Login2',
            sortable: true,
            width: 70
        },{
        	//text: 'Расстояние, км', 
			text: routes_LogistMobile.distance, 
            dataIndex: 'Distance',
            sortable: true,
            width: 70
        },{
        	//text: 'Начало', 
			text: routes_LogistMobile.starttime, 
            dataIndex: 'StartTime',
            sortable: true,
            width: 110
        },{
        	//text: 'Конец', 
			text: routes_LogistMobile.endtime, 
            dataIndex: 'EndTime',
            sortable: true,
            width: 110
        },
		/*{
			text: plan_toir.project, 
            dataIndex: 'project',
            sortable: true,
            width: 110
        },*/
		{
        	xtype: 'checkcolumn',
        	//text: 'Маршрут',
			text: routes_LogistMobile.route,
        	dataIndex: 'bildRoutePlan',
            sortable: false,
			width: 80,
            listeners:
            {
                checkchange:function(CheckColumn, rowIndex, checked, eOpts )
                {
                	//RecordCarPanel=Car_panel_Grid.store.getAt(rowIndex);
                	var record = LogistMobile_TripPlanningStoreRoutes.getAt(rowIndex);
                	//console.log(record);
                	//console.log(rowIndex);
                	console.log('checked - '+checked);
                	var imei = record.get('Login');
					var trpid = record.get('ID');
					
                	if (record.get('Distance')) {
                    	
                        if (checked==true)
                        {                  	
                        	$.post('scripts/CommonSettings.php',{func:'show'},function(data)
							{
							var values=data.split("/n");
							
							console.log(values[12]);
							console.log(values[13]);
							
							if(parseInt(values[13])==3){
								tracingRoute(record.get('ID'));
								//---перенесено с колонки мониторинга
								show_fixed_data_track(imei,time,trpid,record.get('StartTime'),record.get('EndTime'));
							}else if(parseInt(values[13])==2){
								show_fixed_data_track(imei,time,trpid,record.get('StartTime'),record.get('EndTime'));
							}else if(parseInt(values[13])==1){
								tracingRoute(record.get('ID'));
							}
							
							
							
							
							});
							
                        }
                        else  
                        {
                            offTracingPoute(record.get('ID'));
							//---перенесено с колонки мониторинга
							console.log('--del_fixed_data_track--');
							del_fixed_data_track(trpid);
							var map_googl=Ext.getCmp('routes_map_panel');
							var imei_point = "point_" + imei;
							map_googl.deleteMarker(imei_point);
							//---
                        }    
                    } else {
                    	Ext.Msg.alert(all_LogistMobile.attention, routes_LogistMobile.you_can_not_build_uncount_route);
                    	record.set('bildRoutePlan', false);
                    }
                	
                }
            }
        },{
            //text : 'Состояние соединения',
            //id:'cooord_come_monit',
            //text : '<img src="images/conection-type.png" style="margin: 0 0 0 0">',
//            text : '<img src="images/conection-type.png" >',
            //text: 'Соединение',
			text: routes_LogistMobile.connection,
            //titleAlign: 'right',
            //tooltip: 'Состояние соединения',
            style: 'text-align:center',            
            align: 'center',
            textAlign: 'right', 
            tooltip: cars.connection_status,
            dataIndex: 'Signal',
            width: 80,
            sortable: false,
            hideable: false,
            /*sortable: true,
            hideable: true,*/
			groupable: false/*,
            editor: 'textfield'*/
           
        },/*, {
        	xtype: 'checkcolumn',
        	text: 'Путь',
        	dataIndex: 'bildRouteRealPath',
            sortable: false,
            listeners: {
            	checkchange:function(CheckColumn, rowIndex, checked, eOpts )
                {
                	//RecordCarPanel=Car_panel_Grid.store.getAt(rowIndex);
                	var record = LogistMobile_TripPlanningStore.getAt(rowIndex);
                	console.log(record);
                	console.log(rowIndex);
                	console.log(checked);
                	
                	if (record.get('distance')) {
                    	
                        if (checked==true)
                        {                  	
                            
                        	tracing('');
                        }
                        else  
                        {
                        	 off_tracing('');
                        }    
                    } else {
                    	Ext.Msg.alert(all_LogistMobile.attention, 'Нельзя построить непросчитанный маршрут');
                    	record.set('bildRoutePlan', false);
                    }
                	
                }
            }
        }*/{
        	xtype: 'checkcolumn',
        	//text: 'Мониторинг',
			width: 80,
			text: routes_LogistMobile.monitoring,
        	dataIndex: 'monit_car',
            sortable: false,
            listeners: {
            	checkchange:function(CheckColumn, rowIndex, checked, eOpts )
                {
            		var record = LogistMobile_TripPlanningStoreRoutes.getAt(rowIndex);
            		var imei = record.get('Login');
					var trpid = record.get('ID');
            		
					//alert('checked - '+checked);
					//alert('Login - '+imei);
					//alert('interval_monitToir - '+interval_monitToir);
						var time = Ext.getCmp('monitoring_date_id').getRawValue();
						
						var d1 = new Date(time);
						var dbox = d1.getTime();
						var d2 = new Date(getFullDate());
						var dnow = d2.getTime();
					
/*          		// закоментировано так как постоянно рисует трек на все авто, перенесено на чекбокс маршрута
					if (checked==true)
                    {						
						show_fixed_data_track(imei,time,trpid);
                    }
                    else  
                    {
                    	del_fixed_data_track(trpid);
						var map_googl=Ext.getCmp('routes_map_panel');
                    	var imei_point = "point_" + imei;
                    	map_googl.deleteMarker(imei_point);
                    }
*/
                }
            }
        },
		{
	        	//text: 'Время выпуска',
	        	text: routes_LogistMobile.dateRelease,
	            dataIndex: 'dateRelease',
	    }
		],
		
		tbar: [
		{
    		xtype: 'datefield',
			//fieldLabel: 'Дата мониторинга',
			fieldLabel: plan_toir.date,
			format: 'Y-m-d',
			labelWidth: 30,
			width: 125,
			altFormats: 'Y-m-d',
			id: 'monitoring_date_id',
			startDay: 1,
			//margin: '5 5 5 5',
			name : 'date_create',
			value: new Date(),
			listeners: {
				select: function( field, value, eOpts ) {
					
								//var time = field.rawValue;
								//alert(time);
								loadDetails();
		
				}
			}
    	},
		{
							xtype: 'button',
							tooltip: plan_toir.update_details,
							iconCls: 'refresh',
							//margin: '3 3 3 3',
	    		    		handler: function() {
								//var time = Ext.getCmp('monitoring_date_id').getRawValue();
								loadDetails();
							}
		},
		'-',
		{
			xtype: 'button',
			text: routes_LogistMobile.closeRoute,
			handler: function(){
				var select = Ext.getCmp('LogistMobile_RoutesGridId').getView().getSelectionModel().getSelection()[0];
				if(select){
				if( select.get('Closed') != 1){
				Ext.MessageBox.confirm(all_toir.attention, routes_LogistMobile.confirmcloseRoute,  function(btn){
				if(btn=='yes'){
					var myMask = new Ext.LoadMask(LogistMobile_routes_Window, {msg: all.loading});
					myMask.show();
					$.post("app/LogistMobile_routes.php",{'CloseFacttrip':true, 'Facttrip_ID':select.get('ID')}, function(data){
						
						if(data){
											var obj = Ext.decode(data);
											if(obj.success == true){
												myMask.hide();
												var result = checkwebtaskprogress(obj.message,false,completedCheckRoutesUpdate.name);
												//alert('result '+result);
											}else{
												myMask.hide();
												Ext.MessageBox.alert(all_toir.error, obj.message);
											}
						}else{
							Ext.MessageBox.alert(all_toir.error, '');
							myMask.hide();
						}
					});
				}});
				}else{
					Ext.Msg.alert(all_toir.attention, routes_LogistMobile.routeClosed);
				}
				}else{
		            Ext.Msg.alert(all_toir.attention, plan_toir.select_a_route);
				}
			}
		},'-'			
					,{
			        	 xtype: 'combo',
			        	 //fieldLabel: 'Склад 1',
			        	 //fieldLabel: plan_toir.warehouse_1,
			        	 store: Warehouse_store,
			        	 allowBlank: false,
			        	 //margin: '5 5 5 5',
			        	 width: 80,
						 editable: false,
			        	 id: 'bind_warehouse_monitoring',
			        	 valueField: 'ID',
			        	 displayField: 'Name',
			        	 queryMode: 'local',
						 listeners: {
							
							}
		           },
				   {
		        	   xtype: 'textfield',
		        	   id: 'filter_cars_field_monitoring',
					   width: 80,
		        	   enableKeyEvents: true,
		        	   listeners:  {
		        		   keypress: function(field, e, eOpts) {
		        			   if (e.getKey() == e.ENTER) {
		        				   //var filterValCar = Ext.getCmp('filter_cars_field_monitoring').getValue();
		        				   //filterReportMonitoring(Data_CarsRun_panel ,filterValCar);
		        			   } 

		        		   }
		        	   }
		           }, {
		        	   xtype: 'button',
		        	   //text: 'Фильтровать',
		        	   text: all.filter,
		        	   handler: function() {            		
		        		   var filterValCar = Ext.getCmp('filter_cars_field_monitoring').getValue();
		        		   filterReportMonitoring();
		        	   }
		           }, {
		        	   xtype: 'button',
		        	   //text: 'Сброс',
		        	   text: all.reset,
		        	   handler: function() {
		        		   var filterValCar = ''; 
		        		   Ext.getCmp('filter_cars_field_monitoring').setValue('');
						   Ext.getCmp('bind_warehouse_monitoring').setValue('');
						   filterReportMonitoring();
		        	   }
		           }
		],
        listeners: {
        	itemclick: function(cmp, records) {
        		//console.log(records);
        		var time = Ext.getCmp('monitoring_date_id').getRawValue();
        		globalUserIDRout = records.get('Login');
				globalFactTripID = records.get('ID');
        		
        		if (intervalID) {
        			clearInterval(intervalID);
        			intervalID = null;
        		}
        		if (!intervalID) {
        			intervalID = setInterval(function() {
        				reloadGridByTime(globalUserIDRout, time, globalFactTripID)
        			}, 20000);
        		}        		
        		
        		pointsVisitStoreRoutes.load({
        			params: {
        				userID: globalUserIDRout,
						FactTripID: globalFactTripID,
        				time: time
        			}
        		});
				Ext.getCmp('southPanelGridMonit').getView().refresh();
        	}
        }
    });
/* <-- grid facttrip */	
	

    var westPanel = new Ext.panel.Panel({
    	//title: 'Точки посещения',
    	/*defaults: {
			labelWidth: 120,
			msgTarget: 'side',
		},*/
		align: 'stretch',
		layout: {
			type: 'hbox',
			align: 'stretch'
		},
		defaults: { flex : 1 },
		
    	items: [PBRoutesGrig]
    });
	
/* grid tms_checkpoint --> */	 
    var southPanel = new Ext.create('Ext.grid.Panel',{
        //title: 'Точки посещения',
		id: 'southPanelGridMonit',
		title: routes_LogistMobile.points_visit,
    	selType: 'rowmodel',
        columnLines: true,
        //id: 'LogistMobile_RoutesGridId',
        store: pointsVisitStoreRoutes,
        loadMask: true,
        border: false,
        autoScroll: true,
		/*
		viewConfig: {
			stripeRows:true,
			preserveScrollOnRefresh: true,
    		stateful: false
		},
		stripeRows: true,
		stateful: true,
		forceFit: true,
		*/
		stripeRows: true,
		viewConfig: {
            preserveScrollOnRefresh: true
        },
        columns:[
		{
        	//xtype: 'rownumberer',
        	text: 'ID',
        	dataIndex: 'Id',
			width: 50,	
        }, {
        	//text: 'Статус', 
			text: routes_LogistMobile.status, 
            dataIndex: 'calculate',
            style: 'text-align:center',            
            align: 'center',
            sortable: true,
			width: 50,
        }, {
        	//text: 'Название', 
			text: routes_LogistMobile.title, 
            dataIndex: 'Name',
            sortable: true,
        }, {
        	//text: 'Клиент', 
			text: routes_LogistMobile.client, 
            dataIndex: 'ClientName',
            sortable: true,
			width: 90
        }, {
        	//text: 'Адрес', 
			text: routes_LogistMobile.address, 
            dataIndex: 'Address',
            sortable: true,
            flex: 1
        },{
        	//text: 'Время приезда', 
			text: routes_LogistMobile.time_of_arrival, 
            dataIndex: 'EstimateTime',
            sortable: true,
			width: 110
        },{
            //text: 'Фактическое время приезда',
			text: routes_LogistMobile.actual_time,
			dataIndex: 'EstimateTimeFact',
            sortable: true,
			width: 130
		},{
        	//text: 'Время уезда', 
			text: routes_LogistMobile.time_of_leave, 
            dataIndex: 'EstimateTimeOut',
            sortable: true,
			width: 110
        },{
            //text: 'Фактическое время уезда',
			text: routes_LogistMobile.actual_leave,
			dataIndex: 'EstimateTimeFactOut',
            sortable: true,
			width: 130
		},{
        	//text: 'Тип точки', 
			text: routes_LogistMobile.typepoint,
            dataIndex: 'Type',
            sortable: true,
        }],
        listeners: {
        	itemdblclick: function (cmp, record) {
        		console.log(record);
        		
				var select = Ext.getCmp('LogistMobile_RoutesGridId').getView().getSelectionModel().getSelection()[0];
        		
				//if (record.get('Distance')) {        			
        			GoogleLatLng = new google.maps.LatLng(record.get('GeoY'), record.get('GeoX'));
					
        			var Client = record.get('ClientName') ? record.get('ClientName') : '';
					var Code = record.get('Name') ? record.get('Name') : '';
					var Address = record.get('Address') ? record.get('Address') : '';
					var Phone = record.get('Phone') ? record.get('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>'+record.get('EstimateTime')+'</p></div>';
					
					PanelMapRoutes.addMarker(GoogleLatLng,{cursor:'pointOnMap', icon:'images/record.png'},false,false,null,tooltip);
        			PanelMapRoutes.setNewCenter(new google.maps.LatLng(record.get('GeoY'),record.get('GeoX')), 15);
        			setTimeout(function(){
        				PanelMapRoutes.deleteMarker('pointOnMap');
        			}, 9000);
        		//} else {
        			//Ext.Msg.alert(all_LogistMobile.error, routes_LogistMobile.you_can_not_see_the_point_of_uncount_route);
        		//}
        		
        	}
        } 
    });
/* <-- grid tms_checkpoint */	    
	
	if (!LogistMobile_routes_Window){
        Ext.getBody().mask(all_LogistMobile.loading);
        LogistMobile_routes_Window = new Ext.Window({
            layout : 'border',
            //title : 'Мониторинг маршрутов',
			title : routes_LogistMobile.monitoring_routes,
            closeAction : 'destroy',
            width : parseInt(Wwidth),
            height : parseInt(Wheight),
            //minimizable: true,
			/*constrainHeader: true,
            maximizable:true,*/
            maximizable:true,
            //constrainHeader: false,
			constrain : true,
			resizable: true,
			x : 2,
            y : 29,
            defaults: {
                //collapsible: true,
                //split: true,
                //resizable: true,
				stateful: true
            },
            //x : parseInt(Xcoord),
            //y : parseInt(Ycoord),
			listeners : {
            	destroy : function(){
            		LogistMobile_routes_Window = null;	
            	}
            },
            items : [{
	                layout: 'fit',
				    collapsible: false,
	                region:'center',
	                margins: '5 5 5 0',
	                items:[
	                       	PanelMapRoutes
					]
			    }, {
			    	layout: 'fit',
				    collapsible: false,
	                region:'west',
	                margins: '5 5 5 0',
	                width: '55%',
	                items:[
	                       	westPanel  	
					]			    	
			    }, {
			    	layout: 'fit',
				    collapsible: false,
	                region:'south',
	                margins: '5 5 5 0',
	                height: '40%',
	                items:[
	                       southPanel
					]	
			    }]
        });
	}      
	LogistMobile_routes_Window.show(); 
	Ext.getBody().unmask(all_LogistMobile.loading);
		
		var time = Ext.getCmp('monitoring_date_id').getRawValue();
		var warehouse = Ext.getCmp('bind_warehouse_monitoring').getRawValue();
		var device = Ext.getCmp('filter_cars_field_monitoring').getValue();
		LogistMobile_TripPlanningStoreRoutes.load({
			params: {
				time: time,
				warehouse: warehouse,
				device: device
			}
		});
		
		if(intervalID2){
			clearInterval(intervalID2);
			intervalID2 = null;
		}
		
		if(!interval_monitToir){
			startMonitoringToir(interval);
		}
		
		//intervalID2 = setInterval(function() {
        	/*LogistMobile_TripPlanningStoreRoutes.load({
			params: {
				time: time
			}
			});*/
			
			//console.log( globalRouteLine );
			
			/*LogistMobile_TripPlanningStoreRoutes.each(function(rec){	
			if( rec.get('monit_car') == true ){
				//console.log('monit_car');
				show_fixed_data_track(rec.get('Login'),time,rec.get('ID'))
			}else{
				del_fixed_data_track(rec.get('ID'));
			}
			if(globalRouteLine[rec.get('ID')]){
						rec.set('bildRoutePlan',true);
			}
			});*/
			
        //}, 20000);
}

/* <-- main window */





/* route show on the map --> */	
var globalMarkerObj = {};
var globalRouteLine = {};
var globalMarkerObjIn = {};
function tracingRoute (trip_id) {
			
			$.post('app/LogistMobile_routes.php', {func: 'calculateTrip', trip_id: trip_id}, function(data) {
			if(data || data!=""){		 
			 //alert(data);
			 var objData = Ext.decode(data);
			 var arrOfWaypoints = [];
			 var arrOfMarkers = [];
			 var arrOfMarkersIn = [];
			 
			 for (var key in objData) {
				 //console.log(objData[key]['GeoX']+' '+objData[key]['GeoY']);
				 var GoogleLatLng = new google.maps.LatLng(objData[key]['GeoY'],objData[key]['GeoX']);
				 
				 var Client = objData[key]['ClientName'] ? objData[key]['ClientName'] : '';
				 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>'+routes_LogistMobile.actual_delivery_time+' </b>'+objData[key]['EstimateTimeFact']+'</p></div>';
				 
				 if( objData[key]['Type']==0 ){ iconmark = 'start_point'; }else{ iconmark = 'record'; }
				 
				 var marker = PanelMapRoutes.addMarker(GoogleLatLng,{cursor:'outlet_'+objData[key]['Id'], icon:'images/'+iconmark+'.png'},false,false,null,tooltip);
				 arrOfWaypoints.push({
			          location: GoogleLatLng,
			          stopover:true});
				 arrOfMarkers.push(marker);
			 }	 
				 $.post('app/LogistMobile_routes.php', {func: 'calculateTrip2', trip_id: trip_id}, function(data) {
					var objData = Ext.decode(data);
					for (var key in objData) {
				 if(objData[key]['GeoYIn']!=null || objData[key]['GeoYIn']!='null' || objData[key]['GeoYIn']!=0 || objData[key]['GeoYIn']!=''){
				 //alert(objData[key]['GeoYIn']);
				 var st = '';
				 if( objData[key]['EventType']==13 ){ st = routes_LogistMobile.drive_point_in_time; }
				 else if( objData[key]['EventType']==14 ){ st = routes_LogistMobile.driver_point_late; }
				 else if( objData[key]['EventType']==15 ){ st = routes_LogistMobile.driver_not_hit_points_radius; }
				 else if( objData[key]['EventType']==16 ){ st = routes_LogistMobile.driver_point_ahead; }
				 else if( objData[key]['EventType']==19 ){ st = routes_LogistMobile.drive_point_in_time; }
				 
				 else { st = routes_LogistMobile.drive_point_in_time; }
				 var tooltip = '<div class="grad"><p><b>'+st+'</b></p><p><b>'+routes_LogistMobile.request_code+' </b>'+objData[key]['Name']+'</p></div>';
				 var GoogleLatLng = new google.maps.LatLng(objData[key]['GeoYIn'],objData[key]['GeoXIn']);
				 var marker = PanelMapRoutes.addMarker(GoogleLatLng,{cursor:'outletIn_'+objData[key]['Id'], icon:'images/'+objData[key]['calculate']+'.png'},false,false,null,tooltip);
				 arrOfMarkersIn.push(marker);
				 }
					}
				});
			 //}
			 
			 console.log('arrOfMarkers');
			 console.log(arrOfMarkers);
			 
			 console.log('arrOfMarkersIn');
			 console.log(arrOfMarkersIn);
			 
			 globalMarkerObj[trip_id] = arrOfMarkers;
			 globalMarkerObjIn[trip_id] = arrOfMarkersIn;
			 /*
			 //console.log(globalMarkerObj);
			 GoogleLatLng = new google.maps.LatLng(globalOfficeGeoY,globalOfficeGeoX);
			 PanelMapRoutes.addMarker(GoogleLatLng,{
			 cursor:'outlet_main_' + trip_id,
			 icon:'images/record.png'
			 },false,false,null,'');
			 */
			 
			 $.post('app/LogistMobile_routes.php', {func: 'getRoutePath', trip_id: trip_id}, 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(',');
						for (key in arrPol)
						{
						var arrPolLoc = arrPol[key].split(' ');
						var LocY = arrPolLoc[0];
						var LocX = arrPolLoc[1];
						point = {lat: parseFloat(LocX), lng: parseFloat(LocY)};
						flightPlanCoordinates.push(point);
						}
					//}
					//globalRouteLine[trip_id] = PanelMapRoutes.addPolyline(flightPlanCoordinates,{strokeColor: '#538929',strokeOpacity: 1.0,strokeWeight: 3} );
					globalRouteLine[trip_id] = PanelMapRoutes.addPolyline(flightPlanCoordinates,{strokeColor: "#"+('00000'+(Math.random()*(1<<12)|0).toString(8)).slice(-6),strokeOpacity: 1.0,strokeWeight: 3} );
					
					}
			 });
			
			}

			});
}
/* <-- route show on the map */

/* route hide from map --> */	
function offTracingPoute(trip_id) {
	//PanelMapRoutes.deleteMarker('outlet_main_' + trip_id);
	
	console.log('offTracingPoute');
	console.log(globalMarkerObj);
	console.log(globalMarkerObjIn);
	
	if (globalMarkerObj[trip_id]) {
		for (var key in globalMarkerObj[trip_id]) {
			globalMarkerObj[trip_id][key].setMap(null);
			delete globalMarkerObj.trip_id;
		}
	}
	
	if (globalMarkerObjIn[trip_id]) {
		for (var key in globalMarkerObjIn[trip_id]) {
			globalMarkerObjIn[trip_id][key].setMap(null);
			delete globalMarkerObjIn.trip_id;
		}
	}
	
	//var ind = globalMarkerObj.indexOf(trip_id);
	//globalMarkerObj.splice(ind, 1);
	//globalMarkerObj[trip_id] 
	
	if (globalRouteLine[trip_id]) {
		globalRouteLine[trip_id].setMap(null);
		delete globalRouteLine[trip_id];
	 }
}
/* <-- route hide from map */	

function clearMapMonitoring() {
	
	//PanelMapRoutes.deleteMarker('outlet_main_');
	for (var key in globalMarkerObj) {
		for (var key2 in globalMarkerObj[key]) {
			//console.log(key + ' ' + key2);
			globalMarkerObj[key][key2].setMap(null);
		}
	}
	globalMarkerObj = {};
	
	for (var key in globalMarkerObjIn) {
		for (var key2 in globalMarkerObjIn[key]) {
			//console.log(key + ' ' + key2);
			globalMarkerObjIn[key][key2].setMap(null);
		}
	}
	globalMarkerObjIn = {};
	
	for (var key in globalRouteLine) {		
		globalRouteLine[key].setMap(null);
		//PanelMapRoutes.deleteMarker('outlet_main_' + key);		
	}	
	globalRouteLine = {};
}

function reloadGridByTime(globalUserIDRout, time, globalFactTripID) {
	pointsVisitStoreRoutes.load({
		params: {
			userID: globalUserIDRout,
			FactTripID: globalFactTripID,
			time: time
		}
	});
	Ext.getCmp('southPanelGridMonit').getView().refresh();
	console.log('monit');
}



function show_fixed_data_track( imei,time,trpid,StartTime,EndTime ){
	$.post('app/LogistMobile_routes.php', {func: 'start_archive', imei: imei, time:time, StartTime:StartTime, EndTime:EndTime }, function(data){
		//console.log(data);
		if(data || data!=""){
			
			
			
			//track polyline
			if ( globalRouteLineFixed[trpid] ) {
				globalRouteLineFixed[trpid].setMap(null);
				delete globalRouteLineFixed[trpid];
			}
			
			var objData = Ext.decode(data);
			var flightPlanCoordinates = [];
			for (key in objData['track'])
			{
				var latitude = objData['track'][key]['latitude'];
				var longitude = objData['track'][key]['longitude'];
				point = {lat: parseFloat(latitude), lng: parseFloat(longitude)};
				flightPlanCoordinates.push(point);
			}
			globalRouteLineFixed[trpid] = PanelMapRoutes.addPolyline(flightPlanCoordinates,{strokeColor: '#FF0000',strokeOpacity: 1.0,strokeWeight: 3} );
			
			//marker Stop
			if ( globalRouteStopFixed[trpid] ) {
			for (var key in globalRouteStopFixed[trpid]) {
			globalRouteStopFixed[trpid][key].setMap(null);
			delete globalRouteStopFixed.trpid;
			}
			}
			
			var arrOfMarkersStop = [];
			for (key in objData['stop'])
			{
			if(objData['stop'][key]['EventType']==6){
			var GoogleLatLng = new google.maps.LatLng(objData['stop'][key]['GeoY'],objData['stop'][key]['GeoX']);
			var marker = PanelMapRoutes.addMarker(GoogleLatLng,{icon:'images/Events/StopEventSmall.png'},false,false,null,false);
			arrOfMarkersStop.push(marker);
			}
			}
			globalRouteStopFixed[trpid] = arrOfMarkersStop;
			//console.log( 'show_fixed_data_track arrOfMarkersStop '+arrOfMarkersStop );
			//console.log( 'show_fixed_data_track globalRouteStopFixed '+globalRouteStopFixed[trpid] );
			
			//marker Parking
			/*
			if ( globalRouteParkFixed[trpid] ) {
				globalRouteParkFixed[trpid].setMap(null);
				delete globalRouteParkFixed[trpid];
			}
			var arrOfMarkersPark = [];
			for (key in objData['park'])
			{
			var GoogleLatLng = new google.maps.LatLng(objData['park'][key]['GeoY'],objData['park'][key]['GeoX']);
			var marker = PanelMapRoutes.addMarker(GoogleLatLng,{icon:'images/Events/ParkingEventSmall.png'},false,false,null,false);
			arrOfMarkersPark.push(marker);
			}
			globalRouteParkFixed[trpid] = arrOfMarkersPark;
			*/
		}
	});
}
function del_fixed_data_track(trpid){
	//console.log('del_fixed_data_track');
	//console.log(globalRouteLineFixed);
	if ( globalRouteLineFixed[trpid] ) {
		globalRouteLineFixed[trpid].setMap(null);
		delete globalRouteLineFixed[trpid];
	}
	
	//console.log('del_fixed_data_track '+globalRouteStopFixed[trpid]);
	if ( globalRouteStopFixed[trpid] ) {
		for (var key in globalRouteStopFixed[trpid]) {
			//globalRouteStopFixed[trpid].setMap(null);
			//delete globalRouteStopFixed[trpid];
			globalRouteStopFixed[trpid][key].setMap(null);
			delete globalRouteStopFixed.trpid;
		}
	}
	
	/*if ( globalRouteParkFixed[trpid] ) {
				globalRouteParkFixed[trpid].setMap(null);
				delete globalRouteParkFixed[trpid];
	}*/
	
	
}


function loadDetails(){
				
								var d1 = new Date(time);
								var dbox = d1.getTime();
								var d2 = new Date(getFullDate());
								var dnow = d2.getTime();
					
					//alert(intervalID);
					//alert(intervalID2);
					
					var time = Ext.getCmp('monitoring_date_id').getRawValue();
					var warehouse = Ext.getCmp('bind_warehouse_monitoring').getRawValue();
					var device = Ext.getCmp('filter_cars_field_monitoring').getValue();
					
					pointsVisitStoreRoutes.removeAll();
					clearMapMonitoring();
					
					if( dbox < dnow ||  dbox > dnow){
					
					if (intervalID) {
	        			clearInterval(intervalID);
	        			intervalID = null;
	        		}
					if (intervalID2) {
	        			clearInterval(intervalID2);
	        			intervalID2 = null;
	        		}
					
					if (interval_monitToir) {
	        			clearInterval(interval_monitToir);
	        			interval_monitToir = null;
	        		}
					
					
					
					}else{
						//alert('startMonitoringToir');
						if(!interval_monitToir){
							startMonitoringToir(interval);
						}
						//intervalID2 = setInterval(function() {
							
							
		/*LogistMobile_TripPlanningStoreRoutes.load({
							params: {
								time: time
							}
							});
		*/
		
		/*LogistMobile_TripPlanningStoreRoutes.each(function(rec){	
			if( rec.get('monit_car') == true ){
				//console.log('monit_car');
				show_fixed_data_track(rec.get('Login'),time,rec.get('ID'))
			}else{
				del_fixed_data_track(rec.get('ID'));
			}
			if(globalRouteLine[rec.get('ID')]){
				rec.set('bildRoutePlan',true);
			}
		});*/
			
						//}, 20000);
						
					}
					
					
					
						
					LogistMobile_TripPlanningStoreRoutes.load({
						params: {
							time: time,
							warehouse: warehouse,
							device: device
						}
					});
}