<!--suppress JSAnnotator -->
<template>
	<div class="page" data-name="report-show-playback">
		<div class="navbar">
			<div class="navbar-inner">
				<div class="left"></div>
				<div class="title">{{PageTitle}} - {{AdditionalReportInfo.TimePeriodText}}</div>
				<div class="right">
					<a href="#" class="link popup-close" data-popup=".popup-fullscreen-report">
						<i class="f7-icons">close</i>
					</a>
				</div>
			</div>
		</div>
		<div class="page-content bg-color-lightgray ">
			<div class=" no-gap overflow-hidden">
				<div class="col-100 tablet-100  ">
					<div class="card dashboard-card-type1 elevation-3 elevation-hover-4 elevation-transition">
						<div class="card-header bg-color-darkgray text-color-white">
							{{@global.LANGUAGE.REPORT_PANEL_MSG97}}
						</div>
						<div class="card-content">
							<div id="chart-Mileage"></div>
						</div>
					</div>
				</div>
				<div class="col-100 tablet-100  ">
					<div class="card dashboard-card-type1 elevation-3 elevation-hover-4 elevation-transition">
						<div class="card-header bg-color-darkgray text-color-white">
							{{@global.LANGUAGE.REPORT_PANEL_MSG278}}
						</div>
						<div class="card-content">
							<div id="chart-Speed"></div>
						</div>
					</div>
				</div>

			</div>
			<div class="display-flex justify-content-space-between">
				<div class="block display-flex">
					<div class="block no-margin">
						<p class="text-color-black">
							<i class="f7-icons icon-name text-color-gray vertical-middle margin-right"></i>
							<span class="text-color-gray">{{ @global.LANGUAGE.REPORT_PANEL_MSG37 }}:</span>
							{{ AdditionalReportInfo.AssetName }}
						</p>
						<p class="text-color-black">
							<i class="f7-icons icon-header-reports text-color-gray vertical-middle margin-right"></i>
							<span class="text-color-gray">{{ @global.LANGUAGE.REPORT_PANEL_MSG139 }}:</span>
							{{ AdditionalReportInfo.Registration }}
						</p>
						<p class="text-color-black">
							<i
								class="f7-icons icon-interval-reminder-engine text-color-gray vertical-middle margin-right"></i>
							<span class="text-color-gray">{{ @global.LANGUAGE.REPORT_PANEL_MSG168 }}:</span>
							{{ AdditionalReportInfo.EngineCapacity }}
						</p>
						<p class="text-color-black">
							<i class="f7-icons icon-calendar text-color-gray vertical-middle margin-right"></i>
							<span class="text-color-gray">{{ @global.LANGUAGE.REPORT_PANEL_MSG110 }}:</span>
							{{ AdditionalReportInfo.StartTime }}
						</p>
						<p class="text-color-black">
							<i class="f7-icons icon-calendar text-color-gray vertical-middle margin-right"></i>
							<span class="text-color-gray">{{ @global.LANGUAGE.REPORT_PANEL_MSG111 }}:</span>
							{{ AdditionalReportInfo.EndTime }}
						</p>
					</div>
					<div class="block no-margin">
						<p class="text-color-black">
							<i class="f7-icons icon-imei text-color-gray vertical-middle margin-right"></i>
							<span class="text-color-gray">{{ @global.LANGUAGE.REPORT_PANEL_MSG38 }}:</span>
							{{ AdditionalReportInfo.IMEI }}
						</p>
						<p class="text-color-black">
							<i class="f7-icons icon-admin-assets text-color-gray vertical-middle margin-right"></i>
							<span class="text-color-gray">{{ @global.LANGUAGE.REPORT_PANEL_MSG140 }}:</span>
							{{ AdditionalReportInfo.Make }}
						</p>
						<p class="text-color-black">
							<i class="f7-icons icon-admin-assets text-color-gray vertical-middle margin-right"></i>
							<span class="text-color-gray">{{ @global.LANGUAGE.REPORT_PANEL_MSG141 }}:</span>
							{{ AdditionalReportInfo.Model }}
						</p>
						<p class="text-color-black">
							<i class="f7-icons icon-admin-assets text-color-gray vertical-middle margin-right"></i>
							<span class="text-color-gray">{{ @global.LANGUAGE.REPORT_PANEL_MSG142 }}:</span>
							{{ AdditionalReportInfo.Color }}
						</p>
						<p class="text-color-black">
							<i class="f7-icons icon-admin-assets text-color-gray vertical-middle margin-right"></i>
							<span class="text-color-gray">{{ @global.LANGUAGE.REPORT_PANEL_MSG143 }}:</span>
							{{ AdditionalReportInfo.Year }}
						</p>
					</div>
				</div>
			</div>

			<table id="table-report" class="mdl-data-table " style="width:100%">
				<thead>
					<tr>
						<th class="no-export"> {{@global.LANGUAGE.REPORT_PANEL_MSG36}} </th> <!-- Map  -->
						<th> {{@global.LANGUAGE.REPORT_PANEL_MSG40}} </th> <!-- Date, time  -->
						<th> {{@global.LANGUAGE.HOME_MSG005}} </th> <!-- Speed  -->
						<th> {{@global.LANGUAGE.REPORT_PANEL_MSG122}} </th> <!-- Mileage  -->
						<th> {{@global.LANGUAGE.HOME_MSG010}} </th> <!-- Direction  -->
						<th> {{@global.LANGUAGE.COM_MSG98}} </th> <!-- Event Name  -->
						<th> {{@global.LANGUAGE.REPORT_PANEL_MSG146}} </th> <!-- Coords  -->
						<th> {{@global.LANGUAGE.REPORT_PANEL_MSG41}} </th> <!-- Address  -->
						<th> Elevation </th>
					</tr>
				</thead>
				<tbody>
					{{#ReportData}}
					<tr data-item-index="{{@index}}">
						<td @click="showMap" class=" cursor-pointer text-color-red"><i
								class="f7-icons icon-address"></i></td>
						<td>{{DateTime}}</td>
						<td>{{Speed}}</td>
						<td>{{Mileage}}</td>
						<td>{{Direction}}</td>
						<td data-order="{{EventName}}">
							{{#if EventName}}
							<div class="display-flex align-items-center">
								<div
									class='user-icon text-align-center text-color-white display-flex align-items-center justify-content-center text-transform-uppercase {{IconBg}}'>
									<i class='f7-icons size-12 line-height-icon-fix {{Icon}} '></i>
								</div>
								{{EventName}}
								{{#if EventOtherName}}
								(<b>{{EventOtherName}}</b>)
								{{/if}}
								{{#if EventDuration}}
								({{EventDuration}})
								{{/if}}
							</div>
							{{/if}}
						</td>
						<td>{{Coords}}</td>
						<td class="white-space-normall min-width-200">
							<a @click="getAddressInTable" href="#"
								class="link">{{@global.LANGUAGE.REPORT_PANEL_MSG63}}</a>
						</td>
						<td class="white-space-normall min-width-200">
							<a @click="getElevationInTable" href="#"
								class="link">Show elevation</a>
						</td>
						
					</tr>
					{{/ReportData}}

				</tbody>
			</table>
		</div>
	</div>

</template>
<!-- -->
<script>
	// script must return component object
	return {
		data: function () {
			var self = this;

			var type = self.$route.query.type;
			var isOptimized = self.$route.query.isOptimized;

			var pageTitle = Protocol.Helper.getReportTypeName(type);
			var assetList = self.$app.methods.getFromStorage('assetList');
			var geofenceList = self.$app.methods.getFromStorage('geofenceList');
			var asset = assetList[self.$route.query.imei];

			var reportData = self.$app.methods.getFromStorage('historyArray');

			var reportEventsData = self.$app.methods.getFromStorage('historyEvents');
			var formattedReportData = [];
			var contactList = self.$app.methods.getFromStorage('contactList');
			if (contactList && contactList.length) {
				contactList = self.$app.methods.sortContactList(contactList);
			}


			var geofenceListArr = [];
			if (!self.$app.methods.isObjEmpty(geofenceList)) {
				const keys = Object.keys(geofenceList);
				for (const key of keys) {
					geofenceListArr.push({
						Code: geofenceList[key].Code,
						Name: geofenceList[key].Name
					});
				}
			}

			if (reportData && reportData.length) {
				for (let i = reportData.length - 1; i >= 0; i--) {
					if (isOptimized == 'true') {
						if (!reportData[i - 1] || reportData[i].lat !== reportData[i - 1].lat || reportData[i].lng !== reportData[i - 1].lng) {
							formattedReportData.push(self.$app.methods.formatPlaybackData(reportData[i], asset));
						}
					} else {
						formattedReportData.push(self.$app.methods.formatPlaybackData(reportData[i], asset));
					}
				}

			}

			if (reportEventsData && reportEventsData.length) {
				for (let i = reportEventsData.length - 1; i >= 0; i--) {
					if (parseFloat(reportEventsData[i].lat) !== 0 && parseFloat(reportEventsData[i].lng) !== 0) {
						//if (reportEventsData[i].eventClass === 1 || reportEventsData[i].eventClass === 2 && reportEventsData[i].eventType === 1 || reportEventsData[i].eventClass === 4 && reportEventsData[i].eventType === 0) {  //filtering to display only   1-Alert(alarms) , 2-ACC , 4 - static  events
						if (reportEventsData[i].eventClass) {
							let point = self.$app.methods.formatPlaybackEventData(reportEventsData[i], geofenceListArr);


							let index = formattedReportData.findIndex(el => el.DateTime === point.BeginTimeLocal);
							console.log(index)
							if (index !== -1) {
								formattedReportData[index].EventName = point.EventName;
								formattedReportData[index].IconBg = point.IconBg;
								formattedReportData[index].Icon = point.Icon;
								if (point.Duration) {
									formattedReportData[index].EventDuration = point.Duration;
								}
								if (point.OtherName) {
									formattedReportData[index].EventOtherName = point.OtherName;
								}
							}
						}
					}
				}
			}

			if (!pageTitle) {
				pageTitle = LANGUAGE.REPORT_PANEL_MSG35;
			}

			return {
				Type: type,
				DataTable: false,
				PageTitle: pageTitle,
				HistoryArray: reportData,
				EventsArray: reportEventsData,
				ReportData: formattedReportData,
				ContactList: contactList,
				ChartsArr: [],

				AdditionalReportInfo: {
					TimePeriodText: self.$route.query.timePeriodText,
					ReportDateFromUTC: self.$route.query.reportDateFromUTC,
					ReportDateToUTC: self.$route.query.reportDateToUTC,
					StartTime: formattedReportData[0].DateTime,
					EndTime: formattedReportData[formattedReportData.length - 1].DateTime,
					AssetName: asset.Name ? asset.Name : LANGUAGE.COM_MSG103,
					Registration: asset.Registration ? asset.Registration : LANGUAGE.COM_MSG103,
					EngineCapacity: asset.EngineCapacity ? asset.EngineCapacity : LANGUAGE.COM_MSG103,
					IMEI: asset.IMEI ? asset.IMEI : LANGUAGE.COM_MSG103,
					Make: asset.Describe1 ? asset.Describe1 : LANGUAGE.COM_MSG103,
					Model: asset.Describe2 ? asset.Describe2 : LANGUAGE.COM_MSG103,
					Color: asset.Describe3 ? asset.Describe3 : LANGUAGE.COM_MSG103,
					Year: asset.Describe4 ? asset.Describe4 : LANGUAGE.COM_MSG103,
					Id: asset.Id,
				},

				//EncodedPolyline: latLngPolyline ? latLngPolyline.encodePath() : false,
				DynamicMapPopup: false,
				ReportMarker: false,
				MapTrackReport: false,

			};
		},
		methods: {
			buildGraphics: function (graphicSlist = []) {
				var self = this;

				console.log('graphicSlist', graphicSlist)

				if (graphicSlist.length) {
					for (var i = graphicSlist.length - 1; i >= 0; i--) {



						var dates = graphicSlist[i].columns.map(function (item) { return item[0]; });
						var speeds = graphicSlist[i].columns.map(function (item) { return parseInt(item[1]); });

						var chartDates = dates.map(function (date) {
							return new Date(date).getTime();
						});

						self.ChartsArr.push(c3.generate({
							bindto: graphicSlist[i].bindto,
							color: {
								pattern: self.$app.data.ChartCustomization.colors
							},
							
							data: {
								x: 'x',
								columns: [
									['x', ...chartDates],
									['speed', ...speeds]
								],
								types: {
									speed: 'line' 
								},
								labels: {
									format: function (v, id, i, j) {
										return (i % 10 === 0) ? v : null;
									}
								}
							},
							bar: {
								width: {
									ratio: 1 // this makes bar width 50% of length between ticks
								},
								space: 0.25
							},
							axis: {
								x: {
									type: 'timeseries',
									tick: {
										multiline: false,
										rotate: 45,
										culling: {
											max: 30,
										},
										format: function (x) { return x.getHours() + ':' + x.getMinutes() + ':' + x.getSeconds(); }
									},
								 
									label: 'Time'
								},
								y: {
									label: graphicSlist[i].name === "Speed" ? 'Speed (km/h)' : 'Mileage (km)',
									tick: {
										culling: {
											max: 30,
										},
										format: function (d) { return  graphicSlist[i].name === "Speed" ? d +  ' km/h' : d +  ' km'; }
									},
									
								}
							},
							legend: {
								show: false
							}
						}));
					}
				}

			},
			showMap: function (e) {
				var self = this;
				var wrapper = $$(e.target).closest('[role="row"]');
				var index = wrapper.data('item-index');
				var positionData = self.ReportData[index];

				if (!positionData.Lat || !positionData.Lng) {
					self.$app.methods.customNotification({
						title: self.AdditionalReportInfo.AssetName ? self.AdditionalReportInfo.AssetName : self.AdditionalReportInfo.IMEI,
						text: LANGUAGE.PROMPT_MSG031
					});
				} else {

					self.showMapInModal({
						PageTitle: positionData.DateTime ? positionData.DateTime : self.PageTitle,
						index: index,
						positionData: positionData,
						fromGroup: false,
					});
				}

			},
			showMapInModal: function (params) {
				var self = this;

				if (self.DynamicMapPopup && !self.DynamicMapPopup.destroyed) {
					self.DynamicMapPopup.close();
				}

				setTimeout(function () {
					self.DynamicMapPopup = app.popup.create({
						backdrop: true,
						closeByBackdropClick: false,
						animate: false,
						content: `
                                    <div class="popup popup-report-map" >
                                        <div class="view">
                                            <div class="page">
                                                <div class="navbar">
                                                    <div class="navbar-inner">
                                                        <div class="left"></div>
                                                        <div class="title">${params.PageTitle}</div>  
                                                        <div class="right">
                                                            <a href="#" class="link popup-close" data-popup=".popup-report-map">
                                                                <i class="f7-icons">close</i>
                                                            </a>
                                                        </div>                              
                                                    </div>
                                                </div>                                    
                                                <div class="page-content bg-color-lightgray" >
                                                    <div id="mapReport" class="mapReport"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    `,
						on: {
							open: function (popup) {
								self.MapTrackReport = Protocol.Helper.createMap({ target: 'mapReport', latLng: [params.positionData.Lat, params.positionData.Lng], zoom: 14 });
								self.ReportMarker = L.marker([params.positionData.Lat, params.positionData.Lng], { icon: Protocol.MarkerIcon[2] });
								var markerData = self.getMarkerDataTable(params.positionData, params.index);
								self.ReportMarker.bindPopup(markerData, { maxWidth: self.$app.data.MaxMapPopupWidth, closeButton: false })
									.on('popupopen', function (marker) {
										if (params.positionData.CustomAddress) {
											$$('body .popup-report-map #mapReport').find('[data-popupIdAddress="' + params.index + '"]').html(params.positionData.CustomAddress);
										} else {
											Protocol.Helper.getAddressByGeocoder(this.getLatLng(), function (address) {
												$$('body .popup-report-map #mapReport').find('[data-popupIdAddress="' + params.index + '"]').html(address);
												self.ReportData[params.index].CustomAddress = address;
											});
										}
									});
								self.ReportMarker.addTo(self.MapTrackReport);
							},
							closed: function (popup) {
								self.MapTrackReport.removeLayer(self.ReportMarker);
								self.MapTrackReport.remove();
								popup.$el.remove();
								popup.destroy();
							},
						}
					}).open();

				}, 200);
			},

			showSendOnEmailModal: function () {
				var self = this;
				if (self.DynamicSendOnEmailPopup && !self.DynamicSendOnEmailPopup.destroyed) {
					self.DynamicSendOnEmailPopup.close();
				}
				let content = `
								<div class="popup popup-send-on-email" >
									<div class="view">
										<div class="page">
											<div class="navbar">
												<div class="navbar-inner">
													<div class="left"></div>
													<div class="title">${LANGUAGE.REPORT_PANEL_MSG190}</div>
													<div class="right">
														<a href="#" class="link popup-close" data-popup=".popup-send-on-email">
															<i class="f7-icons">close</i>
														</a>
													</div>
												</div>
											</div>
											<form name="FormSendOnEmail" class="page-content bg-color-white " >
												<input type="submit" id="submit-form-send-on-email" class="display-none" />
												<div class="block">
													<p>${LANGUAGE.PROMPT_MSG0114}</p>
												</div>
												<div class="list ">
													<ul>
														<li >
															<a class="item-link smart-select custom-smart-select smartSelectContactList" >
																<select name="ContactList" multiple required validate>`;
				if (self.ContactList && self.ContactList.length) {
					for (let i = 0; i < self.ContactList.length; i++) {
						if (self.ContactList[i].EMail) {
							content += `<option value="${self.ContactList[i].Code}" data-display-as="${self.ContactList[i].EMail}" >${self.ContactList[i].FullName}(${self.ContactList[i].EMail})</option>`;
						}
					}
				}
				content += `</select>
																<div class="item-content item-input">
																	<div class="item-media text-color-lightgray">
																		<i class="f7-icons icon-email"></i>
																	</div>
																	<div class="item-inner">
																		<div class="item-title item-label">${LANGUAGE.REPORT_PANEL_MSG23}</div>
																	</div>
																</div>
															</a>
														</li>
													</ul>
												</div>
											</form>
											<div class="bottom-section-wrapper bottom-section-button-wrapper bg-color-white">
												<div class="row">
													<label for="submit-form-send-on-email" class="col button button-fill color-green elevation-2 sendReportOnEmail" tabindex="0">${LANGUAGE.COM_MSG117}</label>
												</div>
											</div>
										</div>
									</div>
								</div>
				`;
				setTimeout(function () {
					self.DynamicSendOnEmailPopup = app.popup.create({
						backdrop: true,
						closeByBackdropClick: false,
						animate: false,
						content: content,
						on: {
							open: function (popup) {
								let SmartSelectEl = popup.$el.find('.smartSelectContactList');
								let formEl = popup.$el.find('[name="FormSendOnEmail"]');
								let contactListEl = popup.$el.find('[name="ContactList"]');

								self.SmartSelectContactList = app.smartSelect.create({
									el: SmartSelectEl,
									view: reportView,
									openIn: 'popup',
									searchbar: true,
									searchbarPlaceholder: LANGUAGE.COM_MSG02,
									appendSearchbarNotFound: LANGUAGE.PROMPT_MSG008,
									pageTitle: LANGUAGE.REPORT_PANEL_MSG23
								});

								formEl.on('submit', function (e) {
									e.preventDefault();

									let userInfo = self.$app.methods.getFromStorage('userInfo');
									let contactCodes = contactListEl.val();
									let recipients = [];
									if (contactCodes.length && self.ContactList) {
										for (var i = contactCodes.length - 1; i >= 0; i--) {
											recipients.push(self.ContactList.find(x => x.Code === contactCodes[i]).EMail);
										}
									}

									let offsetZZformat = self.$app.methods.convertTimZoneValToZZformat(userInfo.UserInfo.TimeZone);
									let data = {
										Assets: [
											{
												Color: self.AdditionalReportInfo.Color,
												EngineCapacity: self.AdditionalReportInfo.EngineCapacity,
												Id: self.AdditionalReportInfo.Id,
												IMEI: self.AdditionalReportInfo.IMEI,
												Make: self.AdditionalReportInfo.Make,
												Model: self.AdditionalReportInfo.Model,
												Name: self.AdditionalReportInfo.AssetName,
												Registration: self.AdditionalReportInfo.Registration,
												Year: self.AdditionalReportInfo.Year
											},
										],
										DateFrom: self.AdditionalReportInfo.ReportDateFromUTC, // UTC!
										DateTo: self.AdditionalReportInfo.ReportDateToUTC, // UTC!
										extension: "pdf", // pdf, xlsx, json, html
										MajorToken: userInfo.MajorToken,
										MinorToken: userInfo.MinorToken,
										Recipients: recipients,
										displayTimeZone: self.$app.methods.findTimeZoneNameByOffset(offsetZZformat),
									};

									self.$app.methods.sendReportPlaybackOnEmail(data, function () {
										//success
										self.DynamicSendOnEmailPopup.close();
										self.$app.methods.customNotification({ text: LANGUAGE.PROMPT_MSG0109 });
									});
									return false;
								});
							},
							closed: function (popup) {

								if (self.SmartSelectContactList) {
									self.SmartSelectContactList.destroy();
								}

								popup.$el.remove();
								popup.destroy();
							},
						}
					}).open();

				}, 200);
			},

			showMapPlayback: function (additioanalData) {
				var self = this;

				var asset = POSINFOASSETLIST[additioanalData.IMEI];
				self.$setState({
					PointsCount: self.HistoryArray.length - 1
				});

				if (self.DynamicMapPopup && !self.DynamicMapPopup.destroyed) {
					self.DynamicMapPopup.close();
				}

				setTimeout(function () {
					self.DynamicMapPopup = app.popup.create({
						backdrop: true,
						closeByBackdropClick: false,
						animate: false,
						content: `
								<div class="popup popup-report-map" >
									<div class="view">
										<div class="page">
											<div class="navbar">
												<div class="navbar-inner">
													<div class="left"></div>
													<div class="title">${additioanalData.Name}</div>
													<div class="right">
														<a href="#" class="link popup-close" data-popup=".popup-report-map">
															<i class="f7-icons">close</i>
														</a>
													</div>
												</div>
											</div>
											<div class="page-content bg-color-lightgray padding-bottom-120 " >
												<div id="mapReport" class="mapReport"></div>
												<div class="modal-playback-controls">
													<div class="list no-hairlines margin-bottom-8">
														<ul>
															<div class="row">
																<div class="col-50 desktop-33">
																	<li>
																		<a class="item-link smart-select smartSelectPlaybackSpeed" data-open-in="popover" data-close-on-select="true">
																			<select name="PlaybackSpeed" >
																				<option value="1000">x1</option>
																				<option value="500">x2</option>
																				<option value="250">x4</option>
																				<option value="125">x8</option>
																				<option value="62">x16</option>
																			</select>
																			<div class="item-content">
																				<div class="item-inner">
																					<div class="item-title "> ${LANGUAGE.ASSET_PLAYBACK_MSG07}</div>
																				</div>
																			</div>
																		</a>
																	</li>
																</div>
																<div class="col-50 desktop-33">
																	<li class="item-content">
																		<div class="item-inner">
																			<div class="item-title">${LANGUAGE.ASSET_PLAYBACK_MSG01}</div>
																			<div class="item-after">
																				<label class="toggle">
																					<input type="checkbox" name="checkbox-optimized" ${self.OptimizedRouteState ? 'checked="checked"' : ''}  >
																					<span class="toggle-icon"></span>
																				</label>
																			</div>
																		</div>
																	</li>
																</div>
															</div>
														</ul>
													</div>
													<div class="list simple-list card card-playback-range-slider elevation-6 elevation-hover-9 elevation-transition no-margin-top no-hairlines">
														<ul class="card-content bg-color-red text-color-white">
															<li>
																<div class="item-cell width-auto flex-shrink-0 link padding-top-4 playback-controll-button playbackControllButton cursor-pointer">
																	<i class="f7-icons icon-play size-15"></i>
																</div>
																<div class="item-cell flex-shrink-3">
																	<div class="range-slider range-slider-playback rangeSliderPlayback color-white " >
																		<input type="range" min="0" max="${self.PointsCount}" step="1" value="0">
																	</div>
																</div>
															</li>
														</ul>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
								`,
						on: {
							open: function (popup) {
								var rangeSliderEl = popup.$el.find('.rangeSliderPlayback');
								var optimizedSwitcher = popup.$el.find('input[name="checkbox-optimized"]');
								var playbackControllButton = popup.$el.find('.playbackControllButton');
								var playbackControllButtonIcon = popup.$el.find('.playbackControllButton i');
								var playbackSmartSelectEl = popup.$el.find('.smartSelectPlaybackSpeed');
								var playbackSpeed = popup.$el.find('[name="PlaybackSpeed"]');
								var lastQueryPosinfo = {};//save last  query  position

								self.MapTrackReport = Protocol.Helper.createMap({ target: 'mapReport', latLng: [self.HistoryArray[0].lat, self.HistoryArray[0].lng], zoom: 14 });
								self.showPlaybackRoute();
								self.getOptimizedRoute(self.HistoryArray);

								/*MARKER ADDING*/
								var PlaybackMarkerData = self.$app.methods.getPlaybackMarkerDataTable(asset, self.HistoryArray[0]);
								self.PlaybackMarkerGroup = L.markerClusterGroup({ 'maxClusterRadius': 35, });
								self.PlaybackMarker = L.marker([self.HistoryArray[0].lat, self.HistoryArray[0].lng], { icon: Protocol.MarkerIcon[2] });
								self.PlaybackMarker.bindPopup(PlaybackMarkerData, { maxWidth: self.$app.data.MaxMapPopupWidth, closeButton: false });

								self.PlaybackMarker.addTo(self.PlaybackMarkerGroup);
								self.PlaybackMarkerGroup.addTo(self.MapTrackReport);

								Protocol.Helper.getAddressByGeocoder({ lat: self.HistoryArray[0].lat, lng: self.HistoryArray[0].lng }, function (address) {
									self.HistoryArray[0].customAddress = address;
									var newMarkerData = self.$app.methods.getPlaybackMarkerDataTable(asset, self.HistoryArray[0]);
									self.PlaybackMarker.setPopupContent(newMarkerData);
								});


								self.RangeSliderPlayback = app.range.create({
									el: rangeSliderEl,
									on: {
										change: function (e, val) {
											//console.log('changed');
											var MarkerData = self.$app.methods.getPlaybackMarkerDataTable(asset, self.HistoryArray[val]);

											self.PlaybackMarker.setLatLng([self.HistoryArray[val].lat, self.HistoryArray[val].lng]).setPopupContent(MarkerData);
											self.MapTrackReport.setView([self.HistoryArray[val].lat, self.HistoryArray[val].lng]);

											if (lastQueryPosinfo && Math.floor(self.HistoryArray[val].lat * 10000) / 10000 === lastQueryPosinfo.lat && Math.floor(self.HistoryArray[val].lng * 10000) / 10000 === lastQueryPosinfo.lng) {

												self.HistoryArray[val].customAddress = lastQueryPosinfo.address;
												MarkerData = self.$app.methods.getPlaybackMarkerDataTable(asset, self.HistoryArray[val]);
												self.PlaybackMarker.setPopupContent(MarkerData);
											} else {
												var latlng = {
													lat: self.HistoryArray[val].lat,
													lng: self.HistoryArray[val].lng
												};

												Protocol.Helper.getAddressByGeocoder(latlng, function (address) {
													lastQueryPosinfo = { lat: Math.floor(latlng.lat * 10000) / 10000, lng: Math.floor(latlng.lng * 10000) / 10000, address: address };

													self.HistoryArray[val].customAddress = address;
													if (self.HistoryArray[val + 1]) {
														self.HistoryArray[val + 1].customAddress = address;
													}

													MarkerData = self.$app.methods.getPlaybackMarkerDataTable(asset, self.HistoryArray[val]);
													self.PlaybackMarker.setPopupContent(MarkerData);
												});
											}


										}
									}
								});

								self.SmartSelectPlaybackSpeed = app.smartSelect.create({
									el: playbackSmartSelectEl,
									view: reportView,
									openIn: 'popover',
									closeOnSelect: true,
								});

								optimizedSwitcher.on('change', function () {
									if (!self.CantBeOptimised) {
										self.$setState({
											OptimizedRouteState: this.checked
										});
										if (this.checked) {
											if (self.PlaybackRouteLayerGroupOptimized) {
												self.MapTrackReport.removeLayer(self.PlaybackRouteLayerGroup);
												self.MapTrackReport.addLayer(self.PlaybackRouteLayerGroupOptimized);
											}
										} else {
											if (self.PlaybackRouteLayerGroup) {
												self.MapTrackReport.removeLayer(self.PlaybackRouteLayerGroupOptimized);
												self.MapTrackReport.addLayer(self.PlaybackRouteLayerGroup);
											}
										}
									} else {
										self.$app.methods.customNotification({
											title: LANGUAGE.ASSET_PLAYBACK_MSG00,
											text: LANGUAGE.PROMPT_MSG041
										});
										this.checked = false;

										self.$setState({
											OptimizedRouteState: false
										});
									}
								});

								playbackControllButton.on('click', function () {
									if (self.PlaybackTimer) {
										self.stopPlaybackPlayer(playbackControllButtonIcon);

									} else {
										playbackControllButtonIcon.removeClass('icon-play').addClass('icon-stop');

										var interval = parseInt(playbackSpeed.val());
										self.PlaybackTimer = setInterval(playbackIntrvalFunc, interval);
									}
								});

								function playbackIntrvalFunc() {
									clearInterval(self.PlaybackTimer);
									var interval = parseInt(playbackSpeed.val());
									self.PlaybackTimer = setInterval(playbackIntrvalFunc, interval);

									var value = self.RangeSliderPlayback.getValue();
									if (value != self.PointsCount) {
										value++;
										self.RangeSliderPlayback.setValue(value);
									} else {
										self.RangeSliderPlayback.setValue(0);
										value = 0;
										self.stopPlaybackPlayer(playbackControllButtonIcon);
									}
								}

							},
							closed: function (popup) {
								//self.MapTrackReport.removeLayer(self.ReportMarker);
								if (self.PlaybackRouteLayerGroup) {
									MapTrack.removeLayer(self.PlaybackRouteLayerGroup);
								}
								if (self.PlaybackRouteLayerGroupOptimized) {
									MapTrack.removeLayer(self.PlaybackRouteLayerGroupOptimized);
								}
								if (self.PlaybackMarkerGroup) {
									MapTrack.removeLayer(self.PlaybackMarkerGroup);
								}
								if (self.PlaybackEventsLayerGroup) {
									MapTrack.removeLayer(self.PlaybackEventsLayerGroup);
								}
								if (self.RangeSliderPlayback) {
									self.RangeSliderPlayback.destroy();
								}
								if (self.SmartSelectPlaybackSpeed) {
									self.SmartSelectPlaybackSpeed.destroy();
								}

								self.stopPlaybackPlayer();
								self.$setState({
									PlaybackRouteLayerGroup: false,
									PlaybackRouteLayerGroupOptimized: false,
									PlaybackMarkerGroup: false,
									PlaybackEventsLayerGroup: false,
								});
								self.MapTrackReport.remove();
								popup.$el.remove();
								popup.destroy();
							},
						}
					}).open();

				}, 200);


			},
			stopPlaybackPlayer: function ($icon) {
				var self = this;
				if ($icon) {
					$icon.removeClass('icon-stop').addClass('icon-play');
				}
				clearInterval(self.PlaybackTimer);
				self.PlaybackTimer = false;
			},
			showPlaybackRoute: function () {
				var self = this;

				if (self.PlaybackRouteLayerGroup && self.PlaybackMarkerGroup) {
					if (self.OptimizedRouteState && self.PlaybackRouteLayerGroupOptimized) {
						self.MapTrackReport.addLayer(self.PlaybackRouteLayerGroupOptimized);
						self.MapTrackReport.fitBounds(self.PlaybackRouteLayerGroupOptimized.getBounds());
					} else {
						self.MapTrackReport.addLayer(self.PlaybackRouteLayerGroup);
						self.MapTrackReport.fitBounds(self.PlaybackRouteLayerGroup.getBounds());
					}
					self.MapTrackReport.addLayer(self.PlaybackMarkerGroup);
					self.MapTrackReport.addLayer(self.PlaybackEventsLayerGroup);


				} else {

					/*PLAYBACK ROUTE ADDING*/
					var polylinePoints = [];

					for (var i = self.HistoryArray.length - 1; i >= 0; i--) {
						var point = new L.LatLng(self.HistoryArray[i].lat, self.HistoryArray[i].lng);
						polylinePoints.push(point);
					}

					var polylineBG = new L.Polyline(polylinePoints, self.$app.data.PolylineCustomization.mainBg);
					var polyline = new L.Polyline(polylinePoints, self.$app.data.PolylineCustomization.main);
					self.PlaybackRouteLayerGroup = L.featureGroup([polylineBG, polyline]);
					self.PlaybackRouteLayerGroup.addTo(self.MapTrackReport);

					self.MapTrackReport.fitBounds(polyline.getBounds());     // zoom the map to the polyline

					/*EVENTS POINTS ADDING*/
					if (self.EventsArray && self.EventsArray.length) {
						self.PlaybackEventsLayerGroup = L.markerClusterGroup({ 'maxClusterRadius': 35, });
						var markerData = '';
						var point = '';
						var popupAddresses = {};

						$.each(self.EventsArray, function (index, value) {
							if (parseFloat(value.lat) !== 0 && parseFloat(value.lng) !== 0) {
								if (value.eventClass == 1 || value.eventClass == 4 && value.eventType == 0) {  //filtering to display only   1-Alert(alarms) , 2-ACC , 4 - static  events
									value.index = index;
									markerData = self.$app.methods.getPlaybackMarkerDataTableInfoPin(value); //, {GeofenceList: self.GeofenceList}
									point = L.marker([value.lat, value.lng], { icon: Protocol.MarkerIcon[3] });
									point.bindPopup(markerData, { maxWidth: self.$app.data.MaxMapPopupWidth, closeButton: false })
										.on('popupopen', function (marker) {
											if (popupAddresses[index]) {
												$$('body #mapReport').find('[data-popupIdAddress="' + index + '"]').html(popupAddresses[index]);
											} else {
												Protocol.Helper.getAddressByGeocoder(this.getLatLng(), function (address) {
													$$('body #mapReport').find('[data-popupIdAddress="' + index + '"]').html(address);
													popupAddresses[index] = address;
												});
											}
										});
									self.PlaybackEventsLayerGroup.addLayer(point);
								}
							}
						});

						self.MapTrackReport.addLayer(self.PlaybackEventsLayerGroup);
					}


				}


			},
			getOptimizedRoute: function (historyArray) {
				var self = this;

				var rawArray = [];
				$.each(historyArray, function (index, value) {
					rawArray.push([
						null,
						null,
						null,
						new Date(value.positionTime * 1000),
						null,
						null,
						null,
						null,
						null,
						null,
						value.lat,   //lat
						value.lng,   // lng
						null,
						value.direct,   //direct
						value.speed,   //speed
						value.mileage    //mileage
					]);
				});

				app.progressbar.show();

				$.ajax({
					type: "POST",
					url: API_URL.GET_PLAYBACK_ARR_OPTIMISED,
					dataType: "json",
					data: JSON.stringify(rawArray),
					contentType: 'application/json',
					async: true,
					cache: false,
					timeout: 10000,
					success: function (result) {
						//console.log(result);
						var polylineOptBg = new L.Polyline(result.polylines, self.$app.data.PolylineCustomization.mainBg);
						var polylineOpt = new L.Polyline(result.polylines, self.$app.data.PolylineCustomization.main);
						self.PlaybackRouteLayerGroupOptimized = L.featureGroup([polylineOptBg, polylineOpt]);

						if (result.dropped) {
							var polylineOptDroppedBg = new L.Polyline(result.dropped, self.$app.data.PolylineCustomization.droppedBg);
							var polylineOptDropped = new L.Polyline(result.dropped, self.$app.data.PolylineCustomization.dropped);
							self.PlaybackRouteLayerGroupOptimized.addLayer(polylineOptDroppedBg).addLayer(polylineOptDropped);
						}
						if (result.boundaries) {
							var polylineOptBoundariesBg = new L.Polyline(result.boundaries, self.$app.data.PolylineCustomization.boundariesBg);
							var polylineOptBoundaries = new L.Polyline(result.boundaries, self.$app.data.PolylineCustomization.boundaries);
							self.PlaybackRouteLayerGroupOptimized.addLayer(polylineOptBoundariesBg).addLayer(polylineOptBoundaries);
						}
						if (self.OptimizedRouteState) {
							if (self.MapTrackReport.hasLayer(self.PlaybackRouteLayerGroup)) {
								self.MapTrackReport.removeLayer(self.PlaybackRouteLayerGroup);
							}
							self.PlaybackRouteLayerGroupOptimized.addTo(self.MapTrackReport);
							self.MapTrackReport.fitBounds(self.PlaybackRouteLayerGroupOptimized.getBounds());     // zoom the map to the polyline
						}

						app.progressbar.hide();
					},
					error: function (textStatus) {
						app.progressbar.hide();
						setTimeout(function () {
							app.progressbar.hide();
						}, 500);

						console.log(textStatus);
						if (self.OptimizedRouteState) {
							self.$app.methods.customNotification({
								title: LANGUAGE.ASSET_PLAYBACK_MSG00,
								text: LANGUAGE.PROMPT_MSG041
							});
						}

						self.$setState({ OptimizedRouteState: false, CantBeOptimised: true });
						self.showPlaybackRoute();
					}
				});

			},
			getElevationInTable: function (e) {
				var self = this;
				var wrapper = $$(e.target).closest('[role="row"]');
				var parent = $$(e.target).closest('td');
				var index = wrapper.data('item-index');
				var positionData = self.ReportData[index];

				if (!positionData.Lat || !positionData.Lng) {
					self.$app.methods.customNotification({
						title: self.AdditionalReportInfo.AssetName ? self.AdditionalReportInfo.AssetName : self.AdditionalReportInfo.IMEI,
						text: LANGUAGE.PROMPT_MSG031
					});
				} else {
					self.showElevationInTable({
						parent: parent,
						index: index,
						positionData: positionData
					});

				}

			},
			getAddressInTable: function (e) {
				var self = this;
				var wrapper = $$(e.target).closest('[role="row"]');
				var parent = $$(e.target).closest('td');
				var index = wrapper.data('item-index');
				var positionData = self.ReportData[index];

				if (!positionData.Lat || !positionData.Lng) {
					self.$app.methods.customNotification({
						title: self.AdditionalReportInfo.AssetName ? self.AdditionalReportInfo.AssetName : self.AdditionalReportInfo.IMEI,
						text: LANGUAGE.PROMPT_MSG031
					});
				} else {
					self.showAddressInTable({
						parent: parent,
						index: index,
						positionData: positionData
					});

				}

			},
			//promises.push(self.getAllElevations(latlngArr[0][0], latlngArr[0][1]));
			showElevationInTable: function (params) {
				var self = this;

				if (!params.positionData.CustomElevation) {
					params.parent.html('<p><span class="progressbar-infinite color-red"></span></p>');
					Protocol.Helper.getElevationByGeocoder({ lat: params.positionData.Lat, lng: params.positionData.Lng }, function (elev) {
						self.ReportData[params.index].CustomElevation = elev;
						params.parent.html(elev);
					});
				} else {
					params.parent.html(params.positionData.CustomElevation);
				}

			},
			showAddressInTable: function (params) {
				var self = this;

				if (!params.positionData.CustomAddress) {
					params.parent.html('<p><span class="progressbar-infinite color-red"></span></p>');
					Protocol.Helper.getAddressByGeocoder({ lat: params.positionData.Lat, lng: params.positionData.Lng }, function (address) {
						self.ReportData[params.index].CustomAddress = address;
						params.parent.html(address);
					});
				} else {
					params.parent.html(params.positionData.CustomAddress);
				}

			},
			getMarkerDataTable: function (positionData, index) {
				let self = this;

				var markerData = `<table cellpadding="0" cellspacing="0" border="0" class="marker-data-table">`;
				if (self.AdditionalReportInfo.AssetName) {
					markerData += `<tr>
                                        <td class="marker-data-caption">${LANGUAGE.REPORT_PANEL_MSG37}</td>
                                        <td class="marker-data-value">${self.AdditionalReportInfo.AssetName}</td>
                                    </tr>`;
				}

				if (positionData.DateTime) {

					//let newPosDateTime = moment(positionData.DateTime,'DD/MM/YYYY HH:mm:ss').utc().add(userInfo.UserInfo.TimeZone, 'hours').add(app.data.UTCOFFSET,'minutes').format('DD/MM/YYYY HH:mm:ss');
					markerData += `<tr>
                                        <td class="marker-data-caption">${LANGUAGE.REPORT_PANEL_MSG40}</td>
                                        <td class="marker-data-value">${positionData.DateTime}</td>
                                    </tr>`;
				}
				if (positionData.Speed) {
					markerData += `<tr>
                                        <td class="marker-data-caption">${LANGUAGE.HOME_MSG005}</td>
                                        <td class="marker-data-value">${positionData.Speed}</td>
                                    </tr>`;
				}
				if (positionData.Direction) {
					markerData += `<tr>
                                        <td class="marker-data-caption">${LANGUAGE.HOME_MSG010}</td>
                                        <td class="marker-data-value">${positionData.Direction}</td>
                                    </tr>`;
				}
				if (positionData.Mileage) {
					markerData += `<tr>
                                        <td class="marker-data-caption">${LANGUAGE.REPORT_PANEL_MSG122}</td>
                                        <td class="marker-data-value">${positionData.Mileage}</td>
                                    </tr>`;
				}
				markerData += `<tr>
                                    <td class="marker-data-caption">${LANGUAGE.REPORT_PANEL_MSG41}</td>
                                    <td class="marker-data-value marker-address" data-popupIdAddress="${index}">${positionData.CustomAddress ? positionData.CustomAddress : LANGUAGE.COM_MSG08}</td>
                                </tr>
                            </table>`;
				return markerData;
			},
			getAllElevations: function (lat, lng) {
				return new Promise((resolve) => {
					Protocol.Helper.getElevationByGeocoder({ lat: lat, lng: lng }, function (elev) {
						resolve(elev);
					});
				});
				
				
					//https://api.open-elevation.com/api/v1/lookup?locations=41.161758,-8.583933

			},
			getAllAddresses: function (lat, lng) {
				return new Promise((resolve) => {
					Protocol.Helper.getAddressByGeocoder({ lat: lat, lng: lng }, function (address) {
						resolve(address);
					});
				});
				

			},
			getDTExportColumnsIndx: function (table) {
				let allColumns = table.find('thead th');
				let indexes = [];
				for (var i = 0; i < allColumns.length; i++) {
					if (!$$(allColumns[i]).hasClass('no-export')) {
						indexes.push(i);
					}
				}
				return indexes;
			},
		},

		on: {
			pageInit: function (e, page) {
				var self = this;
				if (self.Type) {
					let $table = $('#table-report');
					var columnDefs = [
						{ targets: [0], orderable: false, }
					];
					var order = [[1, 'desc']]; //order by timestamp

					//console.log(self.EncodedPolyline);

					let dtExportColumnIndxs = self.getDTExportColumnsIndx(page.$el.find('table'));
					DATATABLEReport = $table.DataTable({
						columnDefs: columnDefs,
						order: order,
						dom: '<"mdl-grid"<"mdl-cell mdl-cell--12-col margin-top-0 margin-bottom-0"B>><"mdl-grid"<"mdl-cell mdl-cell--6-col"l><"mdl-cell mdl-cell--6-col"f>><"mdl-grid dt-table"<"mdl-cell mdl-cell--12-col"rt>><"mdl-grid"<"mdl-cell mdl-cell--4-col"i><"mdl-cell mdl-cell--8-col"p>>',
						/*data: self.ReportData,
						createdRow: function ( row, data, index ) {
							$$(row).data('item-index', index);
						},
						columns: [
							{
								"data": null,
								className: 'cursor-pointer text-color-red showMap',
								render: function ( data, type, row ) {
									return '<i class="f7-icons icon-address"></i>';
								}
							},
							{ "data": 'DateTime' },
							{ "data": 'Speed' },
							{ "data": 'Mileage' },
							{ "data": 'Direction' },
							{
								"data": 'EventName',
								render: function ( data, type, row ) {
									//console.log(data);
									let ret = '';
									if (row && row.EventName){
										ret +=`
										<div class="display-flex align-items-center">
											<div class='user-icon text-align-center text-color-white display-flex align-items-center justify-content-center text-transform-uppercase ${row.IconBg}'>
											<i class='f7-icons size-12 line-height-icon-fix ${row.Icon} '></i>
										</div>
										${row.EventName}
										${row.EventOtherName ? '('+row.EventOtherName+')' : ''}
										${row.EventDuration ? '('+row.EventDuration+')' : ''}
										`;
									}
									return ret;
								}
							},
							{
								"data": 'Coords',
							},
							{
								"data": null,
								className: 'white-space-normall min-width-200',
								render: function ( data, type, row ) {
									return `<a href="#" class="link getAddressInTable">${LANGUAGE.REPORT_PANEL_MSG63}</a>`;
								}
							},
						],*/
						buttons: {
							dom: {
								container: {
									className: 'datatable-additional-buttons '
								}
							},
							buttons: [
								{
									text: LANGUAGE.REPORT_PANEL_MSG109,
									className: 'mdl-button mdl-button--raised bg-color-9 text-color-white',
									action: function (e, dt, node, config) {
										self.showMapPlayback({
											Name: self.AdditionalReportInfo.AssetName,
											IMEI: self.AdditionalReportInfo.IMEI,
										});
									}
								},
								{
									text: LANGUAGE.REPORT_PANEL_MSG190,
									className: 'mdl-button mdl-button--raised bg-color-6 text-color-white',
									action: function (e, dt, node, config) {
										self.showSendOnEmailModal();
									}
								},
								{
									text: LANGUAGE.COM_MSG105,
									className: 'mdl-button mdl-button--raised bg-color-darkgray text-color-white',
									action: function (e, dt, node, config) {
										this.disable();
										self.$app.progressbar.show();

										let latlngArr = [];
										for (var i = 0; i < self.ReportData.length; i++) {
											latlngArr.push([self.ReportData[i].Lat, self.ReportData[i].Lng]);
										}

										const promises = [];

										for (var i = 0; i < latlngArr.length; i++) {
											promises.push(self.getAllAddresses(latlngArr[i][0], latlngArr[i][1]));
										}
										
										
										/*for (var i = 0; i < latlngArr.length; i++) {
											promises.push(self.getAllElevations(latlngArr[i][0], latlngArr[i][1]));
										}
										*/
										//promises.push(self.getAllElevations(latlngArr[0][0], latlngArr[0][1]));

										Promise.all(promises)
											.then(values => {
												self.$app.progressbar.hide();
												if (values) {
													DATATABLEReport.rows().every(function (rowIdx, tableLoop, rowLoop) {
														if (values[rowIdx]) {
															var data = this.data();
															data[7] = values[rowIdx];
															this.data(data);
															self.ReportData[rowIdx].CustomAddress = values[rowIdx];
														}
													});
												}
											})
											.catch((error) => {
												return error
											})
									}
								},
								{
									extend: 'excelHtml5',
									text: '<i class="f7-icons icon-export-excel vertical-middle margin-right"></i>Excel',
									className: 'mdl-button mdl-button--raised bg-color-1 text-color-white',
									title: self.PageTitle + ' - ' + self.AdditionalReportInfo.TimePeriodText,
									exportOptions: {
										columns: dtExportColumnIndxs
									}
								},
								{
									extend: 'pdfHtml5',
									text: '<i class="f7-icons icon-export-pdf vertical-middle margin-right"></i>PDF',
									className: 'mdl-button mdl-button--raised bg-color-2 text-color-white',
									title: self.PageTitle + ' - ' + self.AdditionalReportInfo.TimePeriodText,
									exportOptions: {
										columns: dtExportColumnIndxs
									},
									//orientation: 'landscape',
									customize: function (doc) {
										var now = new Date();
										//var jsDate = now.getDate()+'/'+(now.getMonth()+1)+'/'+now.getFullYear();
										var jsDate = ('0' + now.getDate()).slice(-2) + '/' + ('0' + (now.getMonth() + 1)).slice(-2) + '/' + now.getFullYear();

										doc.pageMargins = [20, 60, 20, 30];
										// Set the font size fot the entire document
										doc.defaultStyle.fontSize = 7;
										// Set the fontsize for the table header
										doc.styles.tableHeader.fontSize = 7;
										// Create a header object with 3 columns
										// Left side: Logo
										// Middle: brandname
										// Right side: A document title

										doc['header'] = (function () {
											return {
												columns: [

													/*{
														alignment: 'left',
														italics: true,
														text: messageTopLeft,
														fontSize: 9,
														margin: [10,0]
													},*/
													// {
													// 	image: self.$app.data.AppDetails.logoBase64,
													// 	alignment: 'center',
													// 	width: 120
													// },
													/*{
														alignment: 'right',
														fontSize: 9,
														text: messageTopRight
													}*/
												],
												margin: 20
											}
										});
										// Create a footer object with 2 columns
										// Left side: report creation date
										// Right side: current page and total pages
										doc['footer'] = (function (page, pages) {
											return {
												columns: [
													{
														alignment: 'left',
														text: [LANGUAGE.COM_MSG106 + ': ', { text: jsDate.toString() }]
													},
													{
														alignment: 'right',
														text: [LANGUAGE.COM_MSG107 + ' ', { text: page.toString() }, ' ' + LANGUAGE.COM_MSG108 + ' ', { text: pages.toString() }]
													}
												],
												margin: 20
											}
										});
									}
								},
								{
									extend: 'csvHtml5',
									text: '<i class="f7-icons icon-export-csv vertical-middle margin-right"></i>CSV',
									className: 'mdl-button mdl-button--raised bg-color-4 text-color-white',
									title: self.PageTitle + ' - ' + self.AdditionalReportInfo.TimePeriodText,
									exportOptions: {
										columns: dtExportColumnIndxs
									}
								},
								{
									extend: 'print',
									text: '<i class="f7-icons icon-export-print vertical-middle margin-right"></i>Print',
									className: 'mdl-button mdl-button--raised bg-color-3 text-color-white',
									title: self.PageTitle + ' - ' + self.AdditionalReportInfo.TimePeriodText,
									//orientation: 'landscape',
									exportOptions: {
										columns: dtExportColumnIndxs
									}
								}
							]
						},
					});

					$table.on('click', '.showMap', function (e) {
						self.showMap(e);
					});

					$table.on('click', '.getAddressInTable', function (e) {
						self.getAddressInTable(e);
					});
				}
				let graphicsColumns = {
					Speed: [],
					Mileage: [],

				};
				console.log('self.ReportData', self.ReportData)
				for (var i = self.ReportData.length - 1; i >= 0; i--) {
					graphicsColumns.Speed.push([self.ReportData[i].DateTime, self.ReportData[i].Speed]);
					graphicsColumns.Mileage.push([self.ReportData[i].DateTime, self.ReportData[i].Mileage]);
				}
				self.buildGraphics([
					{
						name: LANGUAGE.REPORT_PANEL_MSG96 + ' (' + LANGUAGE.COM_MSG82 + ')',
						bindto: '#chart-Mileage',
						columns: graphicsColumns.Mileage
					},
					{
						name: 'Speed',
						bindto: '#chart-Speed',
						columns: graphicsColumns.Speed
					},

				]);
			},
			pageAfterIn: function () {
				//var self = this;  
				//console.log('page in');


			},
			pageAfterOut: function () {
				// page has left the view
				console.log('here');
			},
			pageBeforeRemove: function (e, page) {
				let self = this;
				if (self.ChartsArr && self.ChartsArr.length) {
					for (var i = self.ChartsArr.length - 1; i >= 0; i--) {
						self.ChartsArr[i].destroy();
					}
				}
				//console.log('removed');
			},

		}
	};
</script>