var windowEditorTrip = null;

Ext.define('modelEditorTrip', {
    extend: 'Ext.data.Model',
	fields: ['Trip_ID','Name','TripPrice','Distance','Time','Comments','OrderCount','StartTime','EndTime'] 
});

var storeEditorTrip = new Ext.data.Store({		        
			    pageSize: 30,
				groupField: 'DriverId',
		        model: 'modelEditorTrip',
		        proxy: 
		        {
		          type: 'ajax',
		          url: 'app/LogistMobile_EditorTrip.php?load=1',
		          reader: 
		          {
		            type: 'json',
		            root: 'rows',
					totalProperty: 'total'
		          }
		        }
		});

   
//-----------------window-----------------------------------------------------   
function show_LogistMobile_EditorTrip_Window()
{
	
	
	if(!windowEditorTrip){
	
	storeEditorTrip.load();
	
	var pagingToolbarEditorTrip = Ext.create('Ext.PagingToolbar', {
        border: false,
        frame: false,
        store: storeEditorTrip,
        displayInfo: true
    });
	
	
	var gridEditorTrip = new Ext.create('Ext.grid.Panel',{
		    selType: 'rowmodel',
		    columnLines: true,
		    store: storeEditorTrip,
		    loadMask: true,
			id: 'EditorTrip_GridId',
		    border: false,
		    autoScroll: true,
			bbar:[pagingToolbarEditorTrip],
			/*features: [{
				ftype: 'groupingsummary',
				//groupHeaderTpl: '{[values.rows.trade_point]} {name}',//{[values.rows[0].trade_point]}
				groupHeaderTpl: '{[values.rows[0].data["Driver"]]}',
				hideGroupedHeader: false,
				//startCollapsed: true,
				enableGroupingMenu: false
			}],
			tbar:[
				{
							tooltip: 'Обновить данные',
							iconCls: 'refresh',
	    		    		handler: function(){
								
							}
				},'-',{
                            xtype: 'datefield',
                            format: 'Y-m-d',
                            altFormats: 'Y-m-d',
                            startDay: 1,
                            fieldLabel: 'Период с',
                            labelAlign: 'left',
                            labelWidth: 60,
                            style:' margin-left:3px;',
                            id: 'EditorTrip_startdt',
                            width: 165,
                            value: new Date(),
                            maxValue: new Date(),
                            listeners:{
                                change: function(newValue, oldValue, eOpts){

                                }
                            }
                },
                {
                             xtype: 'datefield',
                             format: 'Y-m-d',
                             altFormats: 'Y-m-d',
                             startDay: 1,
                             fieldLabel: 'Период по',
                             labelAlign: 'left',
                             labelWidth: 60,
                             id: 'EditorTrip_enddt',
                             style:'margin-left:3px;',
                             width: 165,
                             value: new Date()
                },
                {
                            text: "Сформировать",
                            //iconCls: 'left-right',
                            //id:'filter_data',
                            handler:function(){
                               
							   Ext.getCmp('EditorTrip_GridId').store.load({
									params: {
									reportQues_startdt: Ext.getCmp('EditorTrip_startdt').getRawValue(),
									reportQues_enddt: Ext.getCmp('EditorTrip_enddt').getRawValue()
									}
								});
								
								storeEditorTrip.setProxy({
									type: 'ajax',
									url: 'app/LogistMobile_EditorTrip.php?load=1&reportQues_startdt='+Ext.getCmp('EditorTrip_startdt').getRawValue()+'&reportQues_enddt='+Ext.getCmp('EditorTrip_enddt').getRawValue(),
									reader: 
									{
										type: 'json',
										root: 'rows',
										totalProperty: 'total'
									}
								});
							   
                            }
                },'-',
				{
	  						  text: all.export_xls,
	  						  tooltip: all.export_xls,
	  						  iconCls:'xls',
	  						  handler:function() 
	  						  {
								var ArrData=new Array(); 
								var columnCount = modelEditorTrip.fields.length;
								//if(Ext.getCmp('EditorTrip_GridId').store.getCount() > 0){
								if(Ext.getCmp('EditorTrip_GridId').store.getTotalCount() > 0){
									ArrData = save_table_data(columnCount); 
									export_xls(ArrData,Ext.getCmp('EditorTrip_startdt').getRawValue(),Ext.getCmp('EditorTrip_enddt').getRawValue());
								}
	  						  }
	  			}
			],*/
			columns:[
			/*{
				xtype: 'checkcolumn', 
				width: 30, 
				dataIndex: 'indoor', 
				hideable: false, 
				sortable: false,
				listeners:
                {
                    checkchange:function(CheckColumn, rowIndex, checked, eOpts )
                    {
						
					}
				}
			},*/
			{
	        	xtype: 'rownumberer',
				width: 30
	        },
			{
	        	text: 'Назва',
	            dataIndex: 'Name',            
	            width: 200,
	            sortable: true,
				//summaryRenderer: function(value, summaryData, dataIndex) { return ('Итого:'); }
	        },
			{
	        	text: 'Час',
	            dataIndex: 'Time',
	            width: 80,
				sortable: true
	        },
			{
	        	text: 'Відстань',
	            dataIndex: 'Distance',  
				width: 80,
	            sortable: true
	        },
			{
	        	text: 'Початок',
	            dataIndex: 'StartTime',  
				width: 120,
	            sortable: true
	        },
			{
	        	text: 'Кінець',
	            dataIndex: 'EndTime',
	            width: 120,
				sortable: true
	        },
			{
	        	text: 'К-сть заявок',
	            dataIndex: 'OrderCount',
	            width:70,
				sortable: true
	        },
			{
	        	text: 'Коментар',
	            dataIndex: 'Comments',
	            width:200,
				sortable: true
	        }
			],
			listeners: {
				beforeedit: function(editor, ctx, e, eOpts, record)
				{
           
				},
				edit: function(editor, ctx, e, eOpts, record) {
           
				},
				itemdblclick: function(cmp, records) {    		
					show_LogistMobile_EditorTripPlanning_Window(records);
				}
			}
	});

	
	
        windowEditorTrip = new Ext.Window({
                        width: 800,
                        height: 400,
                        title: LogistMobile.EditorTrip,
                        closeAction : 'destroy',
                        layout: 'fit',
                        resizable:true,
                        //modal:true,
						constrainHeader: true,
						listeners: {
							destroy: function(){
							windowEditorTrip = null;
							}
						},
                        //bodyStyle:{'background-color': '#FFFFFF'},
                 items:[
					gridEditorTrip
				 ]
                     

        });    
         
    }
    windowEditorTrip.show();
	
	
}





var LogistMobile_EditorTripPlanning_Window = null;

function show_LogistMobile_EditorTripPlanning_Window(row){
   
	
	
    if(!LogistMobile_EditorTripPlanning_Window){
		
		var lat = getCookie("MapCenter_latitude");
		var lng = getCookie("MapCenter_longitude");
		
		var PanelMapForEditorTripPlanning = Ext.create('Ext.ux.GMapPanel', {
	    zoomLevel: 11,
	    gmapType: 'map',
	    //padding: 170,
		mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
	    setCenter: {
	        lat:lng,
	        lng:lat
	    }
		});
		
		var GridEditorTripPlanning = new Ext.form.Panel({
			autoScroll: true,
            id:'GridEditorTripPlanningId',
			border: false,
            frame: true,
            autoHeight: true,
			//html: '<div class="x-container x-field-text x-field x-label-align-top x-field-labeled x-form-label-nowrap x-empty" id=""><div class="x-form-label" id="" style="width: 100% !important;"><span id="ext-element-251">Address</span></div><div class="x-component-outer" id=""><div class="x-unsized x-field-input" id=""><input class="x-input-el x-form-field x-input-text" type="text" id="locationField" name="locationPoint" maxlength="50" placeholder=""><div class="x-field-mask" style="display: none !important;" id=""></div><div class="x-clear-icon" id=""></div></div></div></div>',
            //fieldwidth:'width:150px',
            layout:'anchor',
            items:[
				{
					xtype: 'fieldset',
                    title: 'Маршрут',
					layout: 'anchor',
					defaults: {
						anchor: '100%'
					},
				items: [
				{
		        	xtype: 'textfield',
			        labelWidth: 150,
			        fieldLabel: 'Назва маршрута',
			        name: 'Name',
					readonly: true,
					anchor: '50%',
			        value: ''
		        },
				/*{
				    xtype: 'timefield',
				    labelWidth: 150,
					name: 'EstimateTime',
				    fieldLabel: 'Початок',
				    format:'H:i',
				    minValue: '00:00',
				    maxValue: '23:45',
				    increment: 15,
				    anchor: '50%',
				    allowBlank:false
				},*/
				{
		        	xtype: 'textfield',
					fieldLabel: 'Початок',
			        labelWidth: 150,
			        name: 'StartTime',
					readonly: true,
					anchor: '50%',
			        value: ''
		        },
				{
		        	xtype: 'textfield',
					fieldLabel: 'Кінець',
			        labelWidth: 150,
			        name: 'EndTime',
					readonly: true,
					anchor: '50%',
			        value: ''
		        }
				]
				},
				{
					xtype: 'fieldset',
                    title: 'Точки відвідування',
					layout: 'anchor',
					defaults: {
						anchor: '100%'
					},
					items: [
						{
						xtype: 'timefield',
						labelWidth: 150,
						name: 'EstimateTime',
						fieldLabel: 'Час відправлення',
						format:'H:i',
						minValue: '00:00',
						maxValue: '23:45',
						increment: 5,
						anchor: '50%',
						allowBlank:false
						},
						{
						xtype: 'textfield',
						fieldLabel: 'Адрес',
						labelWidth: 150,
						name: 'Address',
						anchor: '100%',
						value: ''
						},
						{
						xtype: 'textfield',
						fieldLabel: 'GeoX',
						labelWidth: 150,
						name: 'GeoX',
						anchor: '50%',
						value: ''
						},
						{
						xtype: 'textfield',
						fieldLabel: 'GeoY',
						labelWidth: 150,
						name: 'GeoY',
						anchor: '50%',
						value: ''
						}
					]
				}
			]
		});
		
		var pointsVisitStoreRoutesTemp = new Ext.data.Store({    			
	    fields: ['TripPoint_ID','Name','Address','EstimateTime','DurationInPoint','EstimateOutTime','OrderInTrip','Route','Distance','Time','GeoX','GeoY'],
	       proxy: {
	          type: 'ajax',
	          url: 'app/LogistMobile_EditorTrip.php?trippoint=1',
	          reader: {
	            type: 'json',
	            root: 'rows'
	          }
		   }
		});
		pointsVisitStoreRoutesTemp.load({
	    	params: {
	    	Trip_ID: row.get('Trip_ID')				           					
	    	}
		});
		
		
		var GridEditorTripPlanningTemp = new Ext.grid.Panel({
	    	selType: 'rowmodel',
	        columnLines: true,
	        id: 'GridEditorTripPlanningTempId',
	        store:  pointsVisitStoreRoutesTemp,
	        loadMask: true,
	        border: false,
	        autoScroll: true,
	        viewConfig: {
	        	preserveScrollOnRefresh: true,
	        },
	        columns:[
			{
				text: 'Порядок',
				width: 70,
	            dataIndex: 'OrderInTrip',
	            sortable: false,
	        },
			{
				text: 'Назва',
				width: 150,
	            dataIndex: 'Name',
	            sortable: false,
				hidden: false
	        },
			{
	            text: 'Адрес',
				width: 150,
				dataIndex: 'Address',
	            //style: 'text-align:center',            
	            //align: 'center',
	            sortable: false,
				hidden: false
	        },
			{
	            text: 'Час прибуття',
				width: 100,
				dataIndex: 'EstimateTime',
	            sortable: false,
				hidden: false
	        },
			{
				text: 'Час відправлення',
				width: 100,
	            dataIndex: 'EstimateOutTime',
	            sortable: false,
	        },
			{
				text: 'Час руху',
				width: 80,
	            dataIndex: 'Time',
	            sortable: false,
	        },
			{
				text: 'Час стоянки',
				width: 80,
	            dataIndex: 'DurationInPoint',
	            sortable: false,
	        },
			{
				text: 'Відстань',
				width: 80,
	            dataIndex: 'Distance',
	            sortable: false,
	        }
			],
			listeners: {
				itemdblclick: function(cmp, records) {    		
					
				},
				itemclick: function(cmp, records) {    		
					var form = Ext.getCmp("GridEditorTripPlanningId").getForm();
					form.findField("EstimateTime").setValue( records.get('EstimateTime') );
					form.findField("Address").setValue( records.get('Address') );
					form.findField("GeoX").setValue( records.get('GeoX') );
					form.findField("GeoY").setValue( records.get('GeoY') );
				}
			}
		});
		
		
		var arrOfRoutsObj = [];
		var directionsService = new google.maps.DirectionsService();
		var directionsDisplayPlan = null;

        LogistMobile_EditorTripPlanning_Window = new Ext.Window({
            width: (window.innerWidth)-150,
            height: (window.innerHeight)-100,
            //title: 'Ручное планирование',
			title:all_LogistMobile.manualPlaningBtn,
            closeAction : 'destroy',
            listeners : {
                destroy : function()
				{
                    LogistMobile_EditorTripPlanning_Window = null;
                },
				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: '50%',
			region: 'center',
			minWidth: 200,
			layout: 'fit',
            //margin: '0 0 0 0',
            items:[ PanelMapForEditorTripPlanning ]
			},
			{
            title:'',
			region:'east',
            width: '50%',
			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: [
			GridEditorTripPlanning,
			GridEditorTripPlanningTemp
			]
			}
			
			]
			}
   
            ],
                    buttons:[
                    
					{
                        text:'Створити рейс',
                        //text: all_toir.save,
                        iconCls: 'save',
                        handler: function() {

                        }
                    },
					{
                        //text:'Cохранить',
                        text: all_toir.save,
                        iconCls: 'save',
                        handler: function() {

                        }
                    },
                    {
                        //text: 'Отмена',
                        text: all_toir.cancel,
                        iconCls:'cancel',
                        handler: function(){
                            LogistMobile_EditorTripPlanning_Window.destroy();
                        }
                    }
					
					]

            
        });
    }
    LogistMobile_EditorTripPlanning_Window.show(this, function(){
		
		try{
			
			var form = Ext.getCmp("GridEditorTripPlanningId").getForm();
			form.findField("Name").setValue( row.get('Name') );
			form.findField("StartTime").setValue( row.get('StartTime') );
			form.findField("EndTime").setValue( row.get('EndTime') );
			

		
				
				var myMask = new Ext.LoadMask(LogistMobile_EditorTripPlanning_Window, {msg: all.loading});
				myMask.show();		
				
				var arrOfMarkers = [];
				var bounds = new google.maps.LatLngBounds();
	
				// ---- удаляем ранее просчитнаый маршрут если есть ----
				if (arrOfRoutsObj.length > 0) {
					for (var key in arrOfRoutsObj) {
						arrOfRoutsObj[key].setMap(null);
					}
					arrOfRoutsObj = [];
				}

				// ---- заполняем масив координатами точек latlng ----
				var MarkerObjOrder = [];
				pointsVisitStoreRoutesTemp.each(function(record){
					// --- google route ---
					//MarkerObjOrder.push(new google.maps.LatLng(record.get('GeoY'),record.get('GeoX')));
					//alert( record.get('GeoY')+','+record.get('GeoX') );
					// --- innotech route ---
					MarkerObjOrder.push( record.get('GeoY')+','+record.get('GeoX') );
					
					var tooltip = '';
					iconmark = "point_16";
					var GoogleLatLng = new google.maps.LatLng(record.get('GeoY'),record.get('GeoX'));
					var marker = PanelMapForEditorTripPlanning.addMarker(GoogleLatLng,{cursor:'o_'+record.get('TripPoint_ID'), icon:'images/'+iconmark+'.png'},false,false,null,tooltip);
					arrOfMarkers.push(marker);
					bounds.extend(GoogleLatLng);
				});
				
				PanelMapForEditorTripPlanning.getMap().setCenter(bounds.getCenter());
				PanelMapForEditorTripPlanning.getMap().fitBounds(bounds);
				//------------------- innotech route -----------------------
				
				// ---- отправляем на просчет масив координатами точек latlng ----
				Ext.Ajax.request({
						url: 'app/LogistMobile_facttrip.php',
						method: 'POST',
						timeout: 120000,
						wait:true,
						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){
		polyline.getPath().push(new google.maps.LatLng(geoX[key2],geoY[key2]));
		bounds_poly.extend(new google.maps.LatLng(geoX[key2],geoY[key2]));
	}
	//polyline.getPath().push(poly);
	arrOfRoutsObj.push(polyline);
	polyline.setMap(PanelMapForEditorTripPlanning.getMap());
	
	
	
	}
	
										
									}else{
										Ext.MessageBox.alert(all_toir.error, all_LogistMobile.manualPlaningErrorMsg);
										myMask.hide();
									}
								}else{
									Ext.MessageBox.alert(all_toir.error, all_LogistMobile.manualPlaningErrorMsg);
									myMask.hide();
								}
						},
						failure: function(response) {
							Ext.MessageBox.alert(all_toir.error, all_LogistMobile.manualPlaningErrorMsg);
							myMask.hide();
						}
				});
				

			
		}catch(e) {
			Ext.MessageBox.alert(all_toir.error, 'Error ' + e.name + ":" + e.message + "\n" + e.stack);
			myMask.hide();
		}
		
	});
	
	
		
	
	
	
		
	
}