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



/*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','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' ]
});
var LogistMobile_TripPlanningStoreRoutes = new  Ext.data.Store({     
		//autoLoad: true,	
        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', 'Address', 'DurationInPoint', 'Type', 'IsOrderPoint', 'StartWorkTime', 'EndWorkTime', 'Code', 'ClientName','calculate']
});
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 */









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

/* 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:'50.5',
            lng:'30.5'
        }
    });
/* <-- 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, 
		
		
        columns:[
		{
        	//xtype: 'rownumberer',
        	text: 'ID',
        	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: 'Login',
            sortable: true,
            width: 70
        },{
        	text: 'Расстояние', 
			//text: plan_LogistMobile.team, 
            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
        },{
        	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);
                	
                	if (record.get('Distance')) {
                    	
                        if (checked==true)
                        {                  	
                            
                        	tracingRoute(record.get('ID'));
                        }
                        else  
                        {
                            offTracingPoute(record.get('ID'));
                        }    
                    } 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('imei');
            		
            		if (checked==true)
                    {						
						
                    }
                    else  
                    {
                        
                    	var map_googl=Ext.getCmp('routes_map_panel');
                    	var imei_point = "point_" + imei;
                    	map_googl.deleteMarker(imei_point);					
						
                    }
                }
            }
        }],
		
		tbar: [
		{
    		xtype: 'datefield',
			//fieldLabel: 'Дата мониторинга',
			fieldLabel: routes_LogistMobile.date_monitoring,
			format: 'Y-m-d',
			labelWidth: 100,
			width: 195,
			altFormats: 'Y-m-d',
			id: 'monitoring_date_id',
			startDay: 1,
			margin: '5 5 5 5',
			name : 'date_create',
			value: new Date(),
			listeners: {
				select: function() {
					if (intervalID) {
	        			clearInterval(intervalID);
	        			intervalID = null;
	        		}
					pointsVisitStoreRoutes.removeAll();
					clearMapMonitoring();
					var time = Ext.getCmp('monitoring_date_id').getRawValue();		
					LogistMobile_TripPlanningStoreRoutes.load({
						params: {
							time: time
						}
					});
				}
			}
    		
    	}
		],
        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
        			}
        		});
        	}
        }
    });
/* <-- 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: 'Точки посещения',
		title: routes_LogistMobile.points_visit,
    	selType: 'rowmodel',
        columnLines: true,
        //id: 'LogistMobile_RoutesGridId',
        store: pointsVisitStoreRoutes,
        loadMask: true,
        border: false,
        autoScroll: true,
        columns:[
		{
        	//xtype: 'rownumberer',
        	text: 'ID',
        	dataIndex: 'Id',
			width: 40,	
        }, {
        	//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.typepoint,
            dataIndex: 'Type',
            sortable: true,
        }],
        listeners: {
        	itemdblclick: function (cmp, record) {
        		console.log(record);
        		var select = Ext.getCmp('LogistMobile_RoutesGridId').getView().getSelectionModel().getSelection()[0];
        		if (select.get('Distance')) {        			
        			GoogleLatLng = new google.maps.LatLng(record.get('GeoY'), record.get('GeoX'));
        			PanelMapRoutes.addMarker(GoogleLatLng,{cursor:'pointOnMap', icon:'images/record.png'},false,false,null,'');
        			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,
			x : 2,
            y : 29,
            defaults: {
                //collapsible: true,
                //split: true,
                resizable: 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: '40%',
	                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();		
		LogistMobile_TripPlanningStoreRoutes.load({
			params: {
				time: time
			}
		});
		
		
		intervalID2 = setInterval(function() {
        	LogistMobile_TripPlanningStoreRoutes.load({
			params: {
				time: time
			}
			});
        }, 20000);
}

/* <-- main window */





/* route show on the map --> */	
var globalMarkerObj = {};
var globalRouteLine = {};
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 = [];
			 for (var key in objData) {
				 console.log(objData[key]['GeoX']+' '+objData[key]['GeoY']);
				 GoogleLatLng = new google.maps.LatLng(objData[key]['GeoY'],objData[key]['GeoX']);
				 var marker = PanelMapRoutes.addMarker(GoogleLatLng,{cursor:'outlet_'+objData[key]['Id'], icon:'images/record.png'},false,false,null,'');
				 arrOfWaypoints.push({
			          location: GoogleLatLng,
			          stopover:true});
				 globalMarkerObj[trip_id] = arrOfMarkers;
				 arrOfMarkers.push(marker);
			 }
			 
			 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} );
					}
			 });
			
			}
			});
}
/* <-- route show on the map */

/* route hide from map --> */	
function offTracingPoute(trip_id) {
	PanelMapRoutes.deleteMarker('outlet_main_' + trip_id);
	if (globalMarkerObj[trip_id]) {
		for (var key in globalMarkerObj[trip_id]) {
			globalMarkerObj[trip_id][key].setMap(null);
		}
	}
	if (globalRouteLine[trip_id]) {
		globalRouteLine[trip_id].setMap(null);		
	 }
}
/* <-- 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 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
		}
	});
	console.log('monit');
}