<!--suppress JSAnnotator -->
<template>
  <!-- Page, data-name contains page name which can be used in callbacks -->
  <div class="page " data-name="asset-playback-show">
    <!-- page-with-subnavbar -->
    <!-- Top Navbar -->
    <div class="navbar">
      <div class="navbar-inner">
        <div class="left">
          <a href="#" class="link back">
            <i class="icon icon-back"></i>
          </a>
        </div>
        <div class="title sliding">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG00}}</div>
        <div class="right">
          <a href="#" class="link" @click="showSendOnEmailModal">
            <i class="f7-icons icon-email"></i>
          </a>
        </div>
      </div>
    </div>

    <div class="toolbar tabbar tabbar-custom">
      <div class="toolbar-inner">
        <!-- Links have "tab-link" class instead of just "link" to switch tabs -->
        <a href="#tab-playback-info"  class="tab-link tab-link-active size-10">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG12}}</a>
        <a href="#tab-playback-position"   class="tab-link size-10">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG21}}</a>
        {{#unless isLife}}
        {{#unless isQProtect}}
        <a href="#tab-playback-activity"   class="tab-link size-10">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG13}}</a>
        <a href="#tab-playback-trips" class="tab-link size-10">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG20}}</a>
        {{/unless}}
        {{/unless}}
      </div>
    </div>

    <div class="tabs-animated-wrap">
      <div class="tabs">

        <!-- Scrollable page content-->
        <div name="AssetPlaybackForm" class="page-content tab tab-active" id="tab-playback-info">
          <!--{{#unless isOptimisedPlaybackLoaded}}<div class="progressbar-infinite position-absolute color-{{@global.DEALER_PRELOADER_COLOR_CLASS}}"></div>{{/unless}}-->
          <input type="hidden" name="IMEI" value="{{IMEI}}">

          <div class="block-title">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG05}}</div>
          <div class="list ">
            <ul>
              <li>
                <div class="item-content three-rows">
                  <!-- <div class="item-media text-color-lightgray">
                          <i class="f7-icons icon-name"></i>
                      </div> -->
                  <div class="item-inner">
                    <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG00}}</div>
                    <div class="item-after">{{Name}}</div>
                  </div>
                </div>
              </li>
              <li>
                <div class="item-content">
                  <!-- <div class="item-media text-color-lightgray">
                          <i class="f7-icons icon-imei"></i>
                      </div> -->
                  <div class="item-inner">
                    <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG01}}</div>
                    <div class="item-after">{{IMEI}}</div>
                  </div>
                </div>
              </li>
              {{#if SolutionType}}
              <li>
                <div class="item-content">
                  <!-- <div class="item-media text-color-lightgray">

                  </div> -->
                  <div class="item-inner">
                    <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG18}}</div>
                    <div class="item-after">{{SolutionType}}</div>
                  </div>
                </div>
              </li>
              {{/if}}
              {{#if TagName}}
              <li>
                <div class="item-content">
                  <!-- <div class="item-media text-color-lightgray">

                      </div> -->
                  <div class="item-inner">
                    <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG15}}</div>
                    <div class="item-after">{{Registration}}</div>
                  </div>
                </div>
              </li>
              {{/if}}
              {{#if Describe1}}
              <li>
                <div class="item-content">
                  <!-- <div class="item-media text-color-lightgray">

                      </div> -->
                  <div class="item-inner">
                    <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG16}}</div>
                    <div class="item-after">{{Describe1}}</div>
                  </div>
                </div>
              </li>
              {{/if}}
              {{#if Describe2}}
              <li>
                <div class="item-content">
                  <!-- <div class="item-media text-color-lightgray">

                      </div> -->
                  <div class="item-inner">
                    <div class="item-title">{{@global.LANGUAGE.ASSET_TRACKING_INTERVAL_MSG17}}</div>
                    <div class="item-after">{{Describe2}}</div>
                  </div>
                </div>
              </li>
              {{/if}}
            </ul>
          </div>
          {{#unless isLife}}
          {{#unless isQProtect}}
          <div class="list no-hairlines  no-margin-bottom">
            <ul>
              <li class="item-content">
                <div class="item-inner">
                  <div class="item-title">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG01}}</div>
                  <div class="item-after">
                    <label class="toggle">
                      <input type="checkbox" name="checkbox-optimized" {{#if OptimizedRouteState}} checked="checked" {{/if}}>
                      <span class="toggle-icon"></span>
                    </label>
                  </div>
                </div>
              </li>
              <li>
                <a class="item-link smart-select smartSelectPlaybackEventsIcon" data-open-in="popover" data-close-on-select="true">
                  <select name="PlaybackEventsIcon" multiple>
                    {{#PlaybackFilterEventsList}}
                    <option value="{{Value}}" data-option-icon="{{IconHTML}}" selected>{{Name}}</option>
                    {{/PlaybackFilterEventsList}}
                    <!-- <option value="1" data-option-icon="TEst1" checked>Stopped</option>
                                                                                             <option value="2" data-option-icon="TEst2" checked>Ignition On</option>
                                                                                             <option value="3" data-option-icon="TEst3" checked>Enter Geofence</option>
                                                                                             <option value="4" data-option-icon="TEst4" checked>Leave Geofence</option>
                                                                                             <option value="5" data-option-icon="TEst5" checked>Other Alarms</option>   -->
                  </select>
                  <div class="item-content">
                    <div class="item-inner">
                      <div class="item-title ">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG16}} <i class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.ASSET_PLAYBACK_MSG17}}"></i></div>
                    </div>
                  </div>
                </a>
              </li>
              <li>
                <a class="item-link smart-select smartSelectPlaybackHistoryIcon" data-open-in="popover" data-close-on-select="true">
                  <select name="PlaybackHistoryIcon" multiple>
                    {{#PlaybackFilterHistoryList}}
                    <option value="{{Value}}" data-option-icon="{{IconHTML}}" selected>{{Name}}</option>
                    {{/PlaybackFilterHistoryList}}
                    <!-- <option value="1" data-option-icon="TEst1" checked>Stopped</option>
                                                                                             <option value="2" data-option-icon="TEst2" checked>Ignition On</option>
                                                                                             <option value="3" data-option-icon="TEst3" checked>Enter Geofence</option>
                                                                                             <option value="4" data-option-icon="TEst4" checked>Leave Geofence</option>
                                                                                             <option value="5" data-option-icon="TEst5" checked>Other Alarms</option>   -->
                  </select>
                  <div class="item-content">
                    <div class="item-inner">
                      <div class="item-title ">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG16}} <i class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.ASSET_PLAYBACK_MSG17}}"></i></div>
                    </div>
                  </div>
                </a>
              </li>
              <li>
              <li>
                <a class="item-link smart-select smart-select-init" 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 ">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG07}}</div>
                    </div>
                  </div>
                </a>
              </li>

            </ul>
          </div>

     {{/unless}}
          {{/unless}}
          <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 {{#if @global.DEALER_BG_COLOR_CLASS}} {{@global.DEALER_BG_COLOR_CLASS}} {{else}} bg-color-red {{/if}} text-color-white">
              <li>
                <div class="item-cell width-auto flex-shrink-0 link padding-top-4 playback-controll-button text-color-white 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 color-white " >
                    <input type="range" min="0" max="{{PointsCount}}" step="1" value="0">
                  </div>
                </div>
              </li>
            </ul>
          </div>
     
          <div class="block-title">{{@global.LANGUAGE.ASSET_PLAYBACK_MSG06}}</div>
          <div class="list">
            <ul>

              <li>
                <div class="item-content">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-date"></i>
                  </div>
                  <div class="item-inner">
                    <div class="item-title tooltip-init" data-tooltip="{{@global.LANGUAGE.NOTIFICATIONS_MSG01}}">{{@global.LANGUAGE.NOTIFICATIONS_MSG01}}</div>
                    <div class="item-after">{{PlaybackData.DateTime}}</div>
                  </div>
                </div>
              </li>
              <li>
                <div class="item-content">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-speed"></i>
                  </div>
                  <div class="item-inner">
                    <div class="item-title">{{@global.LANGUAGE.NOTIFICATIONS_MSG16}}</div>
                    <div class="item-after">{{PlaybackData.Speed}}</div>
                  </div>
                </div>
              </li>
              <li>
                <div class="item-content">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-direction"></i>
                  </div>
                  <div class="item-inner">
                    <div class="item-title">{{@global.LANGUAGE.NOTIFICATIONS_MSG02}}</div>
                    <div class="item-after">{{PlaybackData.Direction}}</div>
                  </div>
                </div>
              </li>
              <li>
                <div class="item-content">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-mileage"></i>
                  </div>
                  <div class="item-inner">
                    <div class="item-title">{{@global.LANGUAGE.NOTIFICATIONS_MSG03}}</div>
                    <div class="item-after">{{PlaybackData.Mileage}}</div>
                  </div>
                </div>
              </li>
              <li>
                <div class="item-content three-rows">
                  <div class="item-media text-color-lightgray">
                    <i class="f7-icons icon-address"></i>
                  </div>
                  <div class="item-inner">
                    <div class="item-text">{{CustomAddress}}</div>
                  </div>
                </div>
              </li>



            </ul>
          </div>
        </div>
        <div  class="page-content tab " id="tab-playback-position">
          {{#unless isHistoryAddressesLoaded}}<div class="progressbar-infinite position-absolute color-{{@global.DEALER_PRELOADER_COLOR_CLASS}}"></div>{{/unless}}

          <div class="list media-list no-hairlines no-margin-top">
            <ul>
              {{#HistoryList}}
              <li data-markerid="{{MarkerId}}" data-event-name="{{EventName}}">
                <a  @click="showClickedHistoryMarker" href="#" class="item-content item-link"  >
                  <div class="item-media">
                    <div class="user-icon text-align-center text-color-white {{IconBg}}  display-flex align-items-center justify-content-center text-transform-uppercase">
                      <i class="f7-icons size-16 line-height-icon-fix {{Icon}} "></i>
                    </div>
                  </div>
                  <div class="item-inner">
                    <div class="item-title-row">
                      <div class="item-title weight-500 text-color-black text-transform-uppercase">
                        <div class="item-header">
                          {{BeginTimeLocal}}
                        </div>
                        {{EventName}}
                      </div>
                    </div>
                    <div class="divider"></div>
                    <div class="item-text">
                      <div class="row no-gutter">
                        {{#if Duration}}
                        <div class="col-100" >
                          <i class="f7-icons size-16 icon-engine asset_list_icon text-color-lightgray vertical-middle"></i>
                          <span class="size-14 vertical-middle">{{Duration}}</span>
                        </div>
                        {{/if}}
                      
                        <div class="col-100" >
                          <i class="f7-icons size-16 icon-speed asset_list_icon text-color-lightgray vertical-middle"></i>
                          <span class="size-14 vertical-middle"> {{Speed}} </span>
                        </div>
                        <div class="col-100 display-flex" >
                          <i class="f7-icons size-16 icon-address asset_list_icon text-color-lightgray vertical-middle"></i>
                            <span href="#" data-lat="{{lat}}"  data-lng="{{lng}}" @click="showAddress" class="link ">
                              {{@global.LANGUAGE.REPORT_PANEL_MSG63}}
                            </span>
                            <!-- {{#if CustomAddress}}{{CustomAddress}}{{else}}{{@global.LANGUAGE.COM_MSG08}}{{/if}} -->
                        </div>
                      </div>
                    </div>
                  </div>
                </a>
              </li>
              {{else}}
              <li>
                <div class="item-content">
                  <div class="item-inner">
                    <div class="item-title">
                      {{@global.LANGUAGE.PROMPT_MSG094}}
                    </div>
                  </div>
                </div>
              </li>
              {{/HistoryList}}

            </ul>
          </div>

        </div>

        <div class="page-content tab " id="tab-playback-activity">
          <!-- {{#unless isActivityAddressesLoaded}}<div class="progressbar-infinite position-absolute color-{{@global.DEALER_PRELOADER_COLOR_CLASS}}"></div>{{/unless}} -->
          <div class="list media-list no-hairlines no-margin-top">
            <ul>
              {{#EventsList}}
              <li data-markerid="{{MarkerId}}" data-event-name="{{EventName}}">
                <a  @click="showClickedMarker" href="#" class="item-content item-link"  >
                  <div class="item-media">
                    <div class="user-icon text-align-center text-color-white {{IconBg}}  display-flex align-items-center justify-content-center text-transform-uppercase">
                      <i class="f7-icons size-16 line-height-icon-fix {{Icon}} "></i>
                    </div>
                  </div>
                  <div class="item-inner">
                    <div class="item-title-row">
                      <div class="item-title weight-500 text-color-black text-transform-uppercase">
                        <div class="item-header">
                          {{showTime}}
                        </div>
                        {{EventName}}
                      </div>
                    </div>
                    <div class="divider"></div>
                    <div class="item-text">
                      <div class="row no-gutter">
                        {{#if Duration}}
                        <div class="col-100" >
                          <i class="f7-icons size-16 icon-engine asset_list_icon text-color-lightgray vertical-middle"></i>
                          <span class="size-14 vertical-middle">{{Duration}}</span>
                        </div>
                        {{/if}}
                        {{#if OtherName}}
                        <div class="col-100" >
                          <i class="f7-icons size-16 icon-service-plan asset_list_icon text-color-lightgray vertical-middle"></i>
                          <span class="size-14 vertical-middle">{{OtherName}}</span>
                        </div>
                        {{/if}}

                        <div class="col-100 display-flex" >
                            <i class="f7-icons size-16 icon-address asset_list_icon text-color-lightgray vertical-middle"></i>
                          <span href="#" data-lat="{{lat}}"  data-lng="{{lng}}" @click="showAddress" class="link ">
                            {{@global.LANGUAGE.REPORT_PANEL_MSG63}}
                          </span>
                          <!-- 
                          <span class="size-14 vertical-middle">{{#if CustomAddress}}{{CustomAddress}}{{else}}{{@global.LANGUAGE.COM_MSG08}}{{/if}}</span> -->
                        </div>
                      </div>
                    </div>
                  </div>
                </a>
              </li>
              {{else}}
              <li>
                <div class="item-content">
                  <div class="item-inner">
                    <div class="item-title">
                      {{@global.LANGUAGE.PROMPT_MSG094}}
                    </div>
                  </div>
                </div>
              </li>
              {{/EventsList}}

            </ul>
          </div>
        </div>

        <div class="page-content tab " id="tab-playback-trips">
          {{#unless isTripsLoaded}}
          <div key="key-preloader-trips-addresses" class="progressbar-infinite position-absolute color-{{@global.DEALER_PRELOADER_COLOR_CLASS}}">
            <div key="key-preloader-trips" class="block block-strong text-align-center ">
              <div class="preloader {{@global.DEALER_PRELOADER_COLOR_CLASS}}"></div>
            </div>
            {{else}}
            <div key="trip-list" class="list no-hairlines no-margin-top no-chevron trip-list">
              <ul>
                {{#TripList}}
                  {{#if Divider}}
                  <!--<li class="item-divider">{{StartTimeLocalDate}}</li>-->
                <!---->
                  <li class="item-content item-divider no-padding-right">
                    <div class="item-media">
                      <div class="item-toggle ripple active">
                        <span class="icon icon-plus">+</span>
                        <span class="icon icon-minus">-</span>
                      </div>
                    </div>
                    <div class="item-inner">
                      <div class="item-title">

                        {{StartTimeLocalDate}}</div>
                      <div class="item-after">
                        <label class="toggle toggle-ignore-between">
                          <input type="checkbox" name="checkbox-trip-visibility-group" checked="checked">
                          <span class="toggle-icon"></span>
                        </label>
                      </div>
                    </div>
                  </li>
                  {{else}}
                  <li class="dynamic-max-height">
                    <label class="item-content item-checkbox {{color}}">
                      <input type="checkbox" name="checkbox-trip-visibility" value="{{@index}}" checked/>
                      <i class="icon icon-checkbox"></i>
                      <div class="item-inner flex-direction-column align-items-stretch">
                        <div class="item-title only-3-rows size-14">
                          <div class="item-header text-color-black">
                            {{StartTimeLocal}}
                          </div>
                          <span class="text-color-gray">
                              {{#if StartCustomAddress}}{{StartCustomAddress}}{{else}}{{@global.LANGUAGE.COM_MSG08}}{{/if}}
                          </span>
                        </div>
                        <div class="item-text margin-8">
                          <div class="row no-gap">
                            <div class="col-50 tooltip-init" data-tooltip="{{@global.LANGUAGE.ASSET_PLAYBACK_MSG11}}">
                              <i class="f7-icons size-16 icon-engine text-color-lightgray vertical-align-middle"></i>
                              <span class="size-14 vertical-align-middle margin-left-half text-color-black">{{Duration}}</span>
                            </div>
                            <div class="col-50 tooltip-init" data-tooltip="{{@global.LANGUAGE.HOME_MSG004}}">
                              <i class="f7-icons size-16 icon-report-distance text-color-lightgray vertical-align-middle"></i>
                              <span class="size-14 vertical-align-middle margin-left-half text-color-black">{{Distance}} {{@global.LANGUAGE.COM_MSG79}}</span>
                            </div>
                            <div class="col-50 tooltip-init" data-tooltip="{{@global.LANGUAGE.REPORT_PANEL_MSG105}}">
                              <i class="f7-icons size-16 icon-speed text-color-lightgray vertical-align-middle"></i>
                              <span class="size-14 vertical-align-middle margin-left-half text-color-black">{{MaxSpeed}} {{@global.LANGUAGE.COM_MSG81}}</span>
                            </div>
                            <div class="col-50 tooltip-init" data-tooltip="{{@global.LANGUAGE.REPORT_PANEL_MSG106}}">
                              <i class="f7-icons size-16 icon-speed text-color-lightgray vertical-align-middle"></i>
                              <span class="size-14 vertical-align-middle margin-left-half text-color-black">{{AvgSpeed}} {{@global.LANGUAGE.COM_MSG81}}</span>
                            </div>
                          </div>
                        </div>
                        <div class="item-title only-3-rows size-14">
                          <div class="item-header text-color-black">
                            {{EndTimeLocal}}
                          </div>
                          <span class="text-color-gray ">
                              {{#if EndCustomAddress}}{{EndCustomAddress}}{{else}}{{@global.LANGUAGE.COM_MSG08}}{{/if}}
                          </span>
                        </div>
                      </div>
                    </label>
                  </li>
                  {{/if}}

                {{else}}
                <li>
                  <div class="item-content">
                    <div class="item-inner">
                      <div class="item-title">{{@global.LANGUAGE.COM_MSG11}}</div>
                    </div>
                  </div>
                </li>
                {{/TripList}}
              </ul>
            </div>
            {{/unless}}
          </div>
        </div>
      </div>
    </div>
</template>
<script>
  // script must return component object
  return {
    data: function() {
      var self = this;
      var ret = {};
	  
	  var elevation_options = {

		// Default chart colors: theme lime-theme, magenta-theme, ...
		theme: "lightblue-theme",

		// Chart container outside/inside map container
		detached: true,

		// if (detached), the elevation chart container
		elevationDiv: "#elevation-div",

		// if (!detached) autohide chart profile on chart mouseleave
		autohide: false,

		// if (!detached) initial state of chart profile control
		collapsed: false,
		
		// if (!detached) control position on one of map corners
		position: "topright",
		
		// Toggle close icon visibility
		closeBtn: true,

		// Autoupdate map center on chart mouseover.
		followMarker: true,

		// Autoupdate map bounds on chart update.
		autofitBounds: true,

		// Chart distance/elevation units.
		imperial: false,

		// [Lat, Long] vs [Long, Lat] points. (leaflet default: [Lat, Long])
		reverseCoords: false,

		// Acceleration chart profile: true || "summary" || "disabled" || false
		acceleration: false,

		// Slope chart profile: true || "summary" || "disabled" || false
		slope: false,

		// Speed chart profile: true || "summary" || "disabled" || false
		speed: false,

		// Altitude chart profile: true || "summary" || "disabled" || false
		altitude: true,

		// Display time info: true || "summary" || false
		time: true,

		// Display distance info: true || "summary" || false
		distance: true,

		// Summary track info style: "inline" || "multiline" || false
		summary: 'multiline',

		// Download link: "link" || false || "modal"
		downloadLink: 'link',

		// Toggle chart ruler filter
		ruler: true,

		// Toggle chart legend filter
		legend: true,

		// Toggle "leaflet-almostover" integration
		almostOver: true,

		// Toggle "leaflet-distance-markers" integration
		distanceMarkers: false,

		// Toggle "leaflet-edgescale" integration
		edgeScale: false,
		
		// Toggle "leaflet-hotline" integration
		hotline: true,

		// Display track datetimes: true || false
		timestamps: false,

		// Display track waypoints: true || "markers" || "dots" || false
		waypoints: true,

		// Toggle custom waypoint icons: true || { associative array of <sym> tags } || false
		wptIcons: {
		  '': L.divIcon({
			className: 'elevation-waypoint-marker',
			html: '<i class="elevation-waypoint-icon"></i>',
			iconSize: [30, 30],
			iconAnchor: [8, 30],
		  }),
		},

		// Toggle waypoint labels: true || "markers" || "dots" || false
		wptLabels: true,

		// Render chart profiles as Canvas or SVG Paths
		preferCanvas: true,

	  };
	  
	  
      //app.methods.storageSetupTime();
      if (self.$route.params) {
        if (self.$route.params.imei) {
          var assetList = self.$app.methods.getFromStorage('assetList');
          var asset = assetList[self.$route.params.imei];
		  //console.log('asssse',POSINFOASSETLIST[self.$route.params.imei])
          var optimisedState = self.$route.params.optimisedState;
          var historyArray = self.$app.methods.getFromStorage('historyArray');
          var geofenceList = self.$app.methods.getFromStorage('geofenceList');
          var groupList = self.$app.methods.getFromStorage('groupList');
          var playbackFilterEventsList = self.$app.methods.getPlaybackFilterEventsList();
          var playbackFilterHistoryList = self.$app.methods.getPlaybackFilterHistoryList();
          var contactList = self.$app.methods.getFromStorage('contactList');
          if(contactList && contactList.length){
            contactList = self.$app.methods.sortContactList(contactList);
          }
          //console.log(self.$route.params.from);
          //console.log(self.$route.params.to);

          var geofenceListArr = [];
          if (!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 (groupList && groupList.length) {
            for (var i = groupList.length - 1; i >= 0; i--) {
              geofenceListArr.push({
                Code: groupList[i].Code,
                Name: groupList[i].Name
              })
            }
          }
console.log('ifasset', asset)
 
          if (asset) {
            ret = {
			elevationOptions: elevation_options,
              Name: asset.Name,
              IMEI: asset.IMEI,
              Id: asset.Id,
              SolutionType: asset.SolutionType,
              Describe1: asset.Describe1,
              Describe2: asset.Describe2,
              Describe3: asset.Describe3,
              Describe4: asset.Describe4,
              Registration: asset.Registration,
              EngineCapacity: asset.EngineCapacity,
              PlaybackFrom: decodeURIComponent(self.$route.params.from),
              PlaybackTo: decodeURIComponent(self.$route.params.to),
            
              OptimizedRouteState: (optimisedState == 'true'),
              CantBeOptimised: false,
              isOptimisedPlaybackLoaded: false,
              isActivityAddressesLoaded: false,
              isHistoryAddressesLoaded: false,
              PlaybackTimer: false,
              PlaybackRouteLayerGroup: false,
              PlaybackRouteLayerGroupOptimized: false,
              PlaybackMarkerGroup: false,
              PlaybackMarker: false,
              PlaybackEventsLayerGroup: false,
              PlaybackHistoryLayerGroup: false,
              PlaybackEventsLayerSubGroups: {},
              PlaybackHistoryLayerSubGroups: {},
              PlaybackData: self.$app.methods.formatPlaybackData(historyArray[0], asset),
              CustomAddress: LANGUAGE.COM_MSG08,
              PointsCount: historyArray.length-1,
              PlaybackSmartSelectEventsIcon: false,
              PlaybackSmartSelectHistoryIcon: false,
              //PlaybackEventsLayerArr: [],

              GeofenceList: geofenceListArr,
              PlaybackFilterEventsList: playbackFilterEventsList,
              PlaybackFilterHistoryList: playbackFilterHistoryList,
              ContactList: contactList,

              isTripsLoaded: false,
              TripList: [],
              TripsRoutes: {},
              TripsRoutesOptimized: {},
              TripsDirectionIcons: {},
              isDirectionIconsOnMap: true,
              isLife: asset.SolutionType == 'LongLifePortable' ? true : false,
              isQProtect: asset.SolutionType == 'QProtect' ? true : false,
            };
        
          } else {
            console.log('There is no asset with such imei');
          }
        } else {
          console.log('There is no imei param');
        }
      } else {
        console.log('There is no params');
      }
      //console.log(ret);
      return ret;
    },
    methods: {
     
      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({
            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: leftView,
                  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: [
                      {
                        Name: self.Name,
                        IMEI: self.IMEI,
                        Id: self.Id,
                        Make: self.Describe1,
                        Model: self.Describe2,
                        Color: self.Describe3,
                        Year: self.Describe4,
                        Registration: self.Registration,
                        EngineCapacity: self.EngineCapacity,
                      },
                    ],
                    DateFrom: self.PlaybackFrom, // UTC!
                    DateTo: self.PlaybackTo, // UTC!
                    extension: "pdf", // pdf, xlsx, json, html
                    Logo: self.$app.data.AppDetails.logoExternal ? self.$app.data.AppDetails.logoExternal : 'https://client.quikloc8.com/resources/images/login/client/logo.png',
                    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});
                  });*/
                  let templateData = {
                    MinorToken: userInfo.MinorToken,
                    MajorToken: userInfo.MajorToken,
                    TimeZone: userInfo.TimeZone,
                    Code: self.Id,
                    From: self.PlaybackFrom,
                    To: self.PlaybackTo,
                    IMEI: self.IMEI,
                    Logo: self.$app.data.logoExternal,
                  };
                  let data = {
                    PaperKind: 9,
                    Orientation: 1,
                    Url: API_URL.REPORT_PLAYBACK_URL_TEMPLATE + '?' + self.$app.utils.serializeObject(templateData),

                    recipients: recipients
                  };

                  self.$app.preloader.show();
                  self.$app.methods.sendReportPlaybackOnEmail(data, function(downloadLink){
                    self.$app.preloader.hide();
                    //success
                    //self.$app.methods.customNotification({text: LANGUAGE.PROMPT_MSG067});
                    self.DynamicSendOnEmailPopup.close();
                    self.$app.methods.customDialog({
                      text: LANGUAGE.PROMPT_MSG0135,
                      buttons: [
                        {
                          text: LANGUAGE.COM_MSG134,
                        },
                        {
                          text: LANGUAGE.COM_MSG31,
                          onClick: function () {
                            self.$app.methods.openExternal(downloadLink)
                          }
                        }
                      ]
                    });
                  }, function () {
                    self.$app.preloader.hide();
                    //err
                  });

                  return false;
                });
              },
              closed: function(popup){

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

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

        }, 200);
      },
      stopPlaybackPlayer: function(){
        var self = this;

        var playbackControllButtonIcon = self.$el.find('.playback-controll-button i');

        playbackControllButtonIcon.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) {
            MapTrack.addLayer(self.PlaybackRouteLayerGroupOptimized);
            MapTrack.fitBounds(self.PlaybackRouteLayerGroupOptimized.getBounds());
			
          }else{
            MapTrack.addLayer(self.PlaybackRouteLayerGroup);
            MapTrack.fitBounds(self.PlaybackRouteLayerGroup.getBounds());
          }
		
		console.log('elev')
          MapTrack.addLayer(self.PlaybackMarkerGroup);
          MapTrack.addLayer(self.PlaybackEventsLayerGroup);


        }else{

          /*PLAYBACK ROUTE ADDING*/
          var historyArray = self.$app.methods.getFromStorage('historyArray');
          var polylinePoints = [];

          $.each( historyArray, function(index,value){
            var point = new L.LatLng(value.lat, value.lng);
            polylinePoints.push(point);
          });

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

          if(self.isLife || self.isQProtect) {
            polylineBG.options.opacity = 0
            polyline.options.opacity = 0
          }
        

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

          /*EVENTS POINTS ADDING*/
          var historyEvents = self.$app.methods.getFromStorage('historyEvents');

          if(historyArray && historyArray.length) {
           self.PlaybackHistoryLayerGroup = L.markerClusterGroup({
             'maxClusterRadius':35,    
             spiderfyOnMaxZoom: false, 
             showCoverageOnHover: false, 
             zoomToBoundsOnClick: false
            });
      
            var markerData = '';
            let point = '';
            var popupAddresses = {};
            let newHistoryArr = []     
            let pinDetails = {};
            let rotDeg = 0
            let playbackHistoryGroups = {};
       

            //console.log(self.PlaybackHistoryLayerGroup, 'self.PlaybackHistoryLayerGroup')
 
            for (var i = self.PlaybackFilterHistoryList.length - 1; i >= 0; i--) {
              self.PlaybackHistoryLayerSubGroups[self.PlaybackFilterHistoryList[i].Value] = L.featureGroup.subGroup(self.PlaybackHistoryLayerGroup).addTo(MapTrack);
            }
            $.each( historyArray, function(index,value){ //console.log('HIS:', value)
              pinDetails = self.getPlaybackMapHisPinDetails(value);
                  value.index = index;
				  value.pclass = POSINFOASSETLIST[self.$route.params.imei].posInfo.protocolClass;
				  value.PRDTFeatures = POSINFOASSETLIST[self.$route.params.imei]?.PRDTFeatures;
				  value.defVol = +POSINFOASSETLIST[self.$route.params.imei].posInfo?.Voltage + 0.5 - Math.random()
				  value.defBat = +POSINFOASSETLIST[self.$route.params.imei].posInfo?.Battery + 0.5 - Math.random()
                  if(value.status == 2097157) {
                    rotDeg =  +value.direct
                  }
                
               
                  markerData = self.$app.methods.getPlaybackMarkerDataTableInfoPin(value, {GeofenceList: self.GeofenceList}, true);
                  point = L.marker([value.lat, value.lng], {icon: pinDetails.Icon, customPlaybackFilterType: pinDetails.CustomFilterType,  rotationAngle: rotDeg });
                  point.bindPopup(markerData,{ maxWidth:self.$app.data.MaxMapPopupWidth, closeButton: false})
                    .on('popupopen', function (marker) {
                      if (popupAddresses[index]) {
                        $$('body #map').find('[data-popupIdAddress="'+index+'"]').html(popupAddresses[index]);
                      }else{
                        Protocol.Helper.getAddressByGeocoder(this.getLatLng(),function(address){
                          $$('body #map').find('[data-popupIdAddress="'+index+'"]').html(address);
                          popupAddresses[index] = address;
                        });
                      }
                    });
                    
                  newHistoryArr.push(self.formatHistoryData(value));
              

                  
                    

                  self.PlaybackHistoryLayerSubGroups[pinDetails.CustomFilterType].addLayer(point);
                  value.MarkerId = self.PlaybackHistoryLayerSubGroups[pinDetails.CustomFilterType].getLayerId(point);

              
            })
           
			//var gpxString = L.ConvertCoords.GPX.convert(self.PlaybackHistoryLayerGroup);
			//console.log('gpxString',gpxString)
			
			
     
			
            MapTrack.addLayer(self.PlaybackHistoryLayerGroup);
            self.$setState({
              HistoryList: newHistoryArr
            })
                 self.$setState({
                  
                  isHistoryAddressesLoaded: true
                });
                self.PlaybackHistoryLayerGroup.on('clusterclick', function (a) {
                  let zoom = MapTrack.getZoom()

              
                  if (zoom < 15) {
                   // MapTrack.setView(a.layer.getLatLng(),15)
                  }
                     a.layer.spiderfy()
                });
            // let promise = new Promise(function(resolve, reject) {
            //   self.getAddresses(newHistoryArrLatLngs, resolve, reject);
            // });
            // self.$setState({
            //   isHistoryAddressesLoaded: false
            // })
            // promise.then(function(result) {
            //   //console.log(result);
            //   if (result && result.length) {
            //     for (var i = result.length - 1; i >= 0; i--) {
            //       if (result[i] && typeof result[i] === 'object' && result[i].display_name) {
            //         self.HistoryList[i].CustomAddress = result[i].display_name;
            //       }

            //     }
            //     self.$setState({
            //       HistoryList: self.HistoryList,
            //       isHistoryAddressesLoaded: true
            //     });
            //   }
            // }, function(error){
            //   console.log(error);
            // });
          }

          if (historyEvents && historyEvents.length) {
            self.PlaybackEventsLayerGroup = L.markerClusterGroup({'maxClusterRadius':35,});
            var markerData = '';
            let point = '';
            var popupAddresses = {};
            let newEventsArr = [];
            let newEventsArrLatLngs = [];
            let pinDetails = {};
            //let playbackEventsGroups = {};
            for (var i = self.PlaybackFilterEventsList.length - 1; i >= 0; i--) {
              self.PlaybackEventsLayerSubGroups[self.PlaybackFilterEventsList[i].Value] = L.featureGroup.subGroup(self.PlaybackEventsLayerGroup).addTo(MapTrack);
            }


            $.each( historyEvents, function(index,value){ //console.log('EV:', value)
              if (parseFloat(value.lat) !== 0 && parseFloat(value.lng) !== 0) {
                if (value.eventClass == 1 || value.eventClass == 2 && value.eventType == 1 || value.eventClass == 4 && value.eventType == 0) {  //filtering to display only   1-Alert(alarms) , 2-ACC , 4 - static  events
                  pinDetails = self.getPlaybackMapPinDetails(value);
                  value.index = index;
				  value.pclass = POSINFOASSETLIST[self.$route.params.imei].posInfo.protocolClass;
				  value.PRDTFeatures = POSINFOASSETLIST[self.$route.params.imei]?.PRDTFeatures;
				  value.defVol = +POSINFOASSETLIST[self.$route.params.imei].posInfo?.Voltage + 0.5 - Math.random()
				  value.defBat = +POSINFOASSETLIST[self.$route.params.imei].posInfo?.Battery + 0.5 - Math.random() 
                  markerData = self.$app.methods.getPlaybackMarkerDataTableInfoPin(value, {GeofenceList: self.GeofenceList});
                  point = L.marker([value.lat, value.lng], {icon: pinDetails.Icon, customPlaybackFilterType: pinDetails.CustomFilterType});
                  point.bindPopup(markerData,{ maxWidth:self.$app.data.MaxMapPopupWidth, closeButton: false})
                    .on('popupopen', function (marker) {
                      if (popupAddresses[index]) {
                        $$('body #map').find('[data-popupIdAddress="'+index+'"]').html(popupAddresses[index]);
                      }else{
                        Protocol.Helper.getAddressByGeocoder(this.getLatLng(),function(address){
                          $$('body #map').find('[data-popupIdAddress="'+index+'"]').html(address);
                          popupAddresses[index] = address;
                        });
                      }
                    });



                  //self.PlaybackEventsLayerArr.push(point);

                  //self.PlaybackEventsLayerGroup.addLayer(point);
                  //console.log(pinDetails.CustomFilterType);
                  self.PlaybackEventsLayerSubGroups[pinDetails.CustomFilterType].addLayer(point);
                  value.MarkerId = self.PlaybackEventsLayerSubGroups[pinDetails.CustomFilterType].getLayerId(point);

                  newEventsArr.push(self.formatEventData(value));
                  newEventsArrLatLngs.push([value.lat,value.lng]);
                }
              }
            });

            /*self.PlaybackEventsLayerGroup.eachLayer(function(layer){
                console.log(layer)
            });*/
            MapTrack.addLayer(self.PlaybackEventsLayerGroup);

            self.$setState({
              EventsList: newEventsArr
            });
           

            self.PlaybackEventsLayerGroup.on('clusterclick', function (a) {
                  //MapTrack.setView(a.layer.getLatLng(),15)
    
            });
            // let promise = new Promise(function(resolve, reject) {
            //   self.getAddresses(newEventsArrLatLngs, resolve, reject);
            // });
            // self.$setState({
            //   isActivityAddressesLoaded: false
            // })
            // promise.then(function(result) {
            //   //console.log(result);
            //   if (result && result.length) {
            //     for (var i = result.length - 1; i >= 0; i--) {
            //       if (result[i]) {
            //         self.EventsList[i].CustomAddress = result[i];
            //       }

            //     }
            //     self.$setState({
            //       EventsList: self.EventsList,
            //       isActivityAddressesLoaded: true
            //     });
            //   }
            // }, function(error){
            //   console.log(error);
            // });
          }

          /*MARKER ADDING*/
          self.PlaybackMarkerGroup = L.markerClusterGroup({'maxClusterRadius':35,});
          self.PlaybackMarker = L.marker([historyArray[0].lat, historyArray[0].lng], {icon: !self.$app.data.AppDetails.customMapMarker ? Protocol.MarkerIcon[2] : self.$app.data.AppDetails.customMapMarker});
          self.PlaybackMarker.bindTooltip(self.Name,{permanent: false, direction: 'right'});
          self.PlaybackMarker.addTo(self.PlaybackMarkerGroup);
          self.PlaybackMarkerGroup.addTo(MapTrack);
        }

      },

      formatHistoryData: function(point={}) {
        let self = this;
        var assetList = self.$app.methods.getFromStorage('assetList');
        var asset = assetList[self.$route.params.imei];
			  var userInfo = app.methods.getFromStorage('userInfo');

        //point.BeginTimeLocal = moment(point.positionTime, 'X').format(window.COM_TIMEFORMAT);
		    point.BeginTimeLocal = moment.utc(point.positionTime, 'X').add(userInfo.UserInfo.TimeZone, 'hours').format(window.COM_TIMEFORMAT);
	   		point.Speed = Protocol.Helper.getSpeedValue(asset.Unit, point.speed) + ' ' + Protocol.Helper.getSpeedUnit(asset.Unit);
        
		if (point.status & 1 > 0) {
         //if (point.status == 2097225 & 1 > 0) {
            point.EventName = LANGUAGE.ASSET_ALARM_MSG11;
            point.IconBg = 'bg-color-green';
            point.Icon = 'icon-ignition';
         } else {
               point.EventName = LANGUAGE.ASSET_ALARM_MSG10;
                point.IconBg = 'bg-color-gray';
                point.Icon = 'icon-ignition';
         }
       
        return point;


      },
      formatEventData: function(point={}){
	  //console.log('p', point)
        let self = this;
			var userInfo = app.methods.getFromStorage('userInfo');
        point.BeginTimeLocal = moment(point.beginTime).format(window.COM_TIMEFORMAT);
        point.BeginTimeLocal = moment.utc(point.BeginTimeLocal).add(userInfo.UserInfo.TimeZone, 'hours').toDate();
        point.BeginTimeLocal = moment(point.BeginTimeLocal).local().format(window.COM_TIMEFORMAT);
		
		var beginTime = moment(point.beginTime).format(window.COM_TIMEFORMAT);
			beginTime = moment.utc(beginTime).toDate();
			beginTime = moment(beginTime).local().format(window.COM_TIMEFORMAT);
			
		point.showTime = point?.positionTime ? moment.unix(point?.positionTime).format(window.COM_TIMEFORMAT) : beginTime

        /* point.EndTimeLocal = moment(point.endTime).format(window.COM_TIMEFORMAT);
         point.EndTimeLocal = moment.utc(point.EndTimeLocal).toDate();
         point.EndTimeLocal = moment(point.EndTimeLocal).local().format(window.COM_TIMEFORMAT);*/

        switch (point.eventClass){
          case 1:
            point.IconBg = 'bg-color-red';
            point.Icon = 'icon-admin-alarms';

            switch (point.eventType){
              case 8:
                point.EventName = LANGUAGE.ASSET_ALARM_MSG12;
                point.IconBg = 'bg-color-green';
                point.Icon = 'icon-admin-geofences';
                point.OtherName = self.$app.methods.getGeofenceName(point.otherCode, self.GeofenceList);
                break;
              case 16:
                point.EventName = LANGUAGE.ASSET_ALARM_MSG13;
                point.IconBg = 'bg-color-red';
                point.Icon = 'icon-admin-geofences';
                point.OtherName = self.$app.methods.getGeofenceName(point.otherCode, self.GeofenceList);
                break;
              default:
                $.each(Protocol.PositionAlerts,function(key,val){
                  if (val == point.eventType) {
                    point.EventName = key;
                  }
                });
            }

            break;

          case 2:     // ACC
            point.Icon = 'icon-ignition';
            if (point.eventType === 0) {
              point.IconBg = 'bg-color-gray';
              point.EventName = LANGUAGE.ASSET_ALARM_MSG10;
            }else{
              point.IconBg = 'bg-color-green';
              point.EventName = LANGUAGE.ASSET_ALARM_MSG11;
            }
            break;

          case 4:     // ACTIVE
            point.Icon = 'icon-header-tracking';
            point.Duration = Protocol.Helper.getDifferenceBTtwoDates(point.beginTime,point.endTime);
            point.Duration = moment.duration(point.Duration, "milliseconds").format('d[d] h[h] m[m] s[s]');
            if (point.eventType === 0) {
              point.IconBg = 'bg-color-gray';
              point.EventName = LANGUAGE.HOME_MSG015;
            }else{
              point.IconBg = 'bg-color-green';
              point.EventName = LANGUAGE.HOME_MSG014;
            }
            break;
        }

        return point;
      },
      getPlaybackMapHisPinDetails: function(point={}) {
        let ret = {
          Icon: Protocol.MarkerIcon[3],
          CustomFilterType: '2'
        }
        switch (point.status){
 
       
              case 2097157:
                ret = {
                  Icon: Protocol.MarkerIcon[11],
                  CustomFilterType: '1'
                }
                break;
              case 2097156:
                ret = {
                  Icon: Protocol.MarkerIcon[6],
                  CustomFilterType: '2'
                }
                break;
              }
        return ret;
      },
      getPlaybackMapPinDetails: function(point={}){
        let ret = {
          Icon: Protocol.MarkerIcon[3],
          CustomFilterType: '5'
        }
        switch (point.eventClass){
          case 1:
            switch (point.eventType){
              case 8:
                ret = {
                  Icon: Protocol.MarkerIcon[8],
                  CustomFilterType: '3'
                }
                break;
              case 16:
                ret = {
                  Icon: Protocol.MarkerIcon[7],
                  CustomFilterType: '4'
                }
                break;
              default:
                ret = {
                  Icon: Protocol.MarkerIcon[4],
                  CustomFilterType: '5'
                }
            }
            break;
          case 2:
            ret = {
              Icon: Protocol.MarkerIcon[5],
              CustomFilterType: '1'
            }
            break;
          case 4:
            ret = {
              Icon: Protocol.MarkerIcon[6],
              CustomFilterType: '2'
            }
            break;
        }
        return ret;
      },
      /*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();
        self.$setState({
          isOptimisedPlaybackLoaded: false
        })
        $.ajax({
          type: "POST",
          url: API_URL.GET_PLAYBACK_ARR_WITHOUTADDRESSES_OPTIMISED2,  //API_URL.GET_PLAYBACK_ARR_WITHOUTADDRESSES_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.PolylineCustomizationSemi.mainBg);
            var polylineOpt = new L.Polyline(result.polylines, self.$app.data.PolylineCustomizationSemi.main);
            self.PlaybackRouteLayerGroupOptimized = L.featureGroup([polylineOptBg,polylineOpt]);

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

            //app.progressbar.hide();
            self.$setState({
              isOptimisedPlaybackLoaded: true
            })
          },
          error: function (textStatus) {
            self.$setState({
              isOptimisedPlaybackLoaded: true
            })
            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();
          }
        });

      },*/
      getTrips: function(){
        let self = this;
        let userInfo = self.$app.methods.getFromStorage('userInfo');
        let data = {
          MajorToken: userInfo.MajorToken,
          MinorToken: userInfo.MinorToken,
          DateFrom: moment.utc(self.PlaybackFrom, window.COM_TIMEFORMAT2).add(userInfo.UserInfo.TimeZone, 'hours').format(window.COM_TIMEFORMAT),
          DateTo: moment.utc(self.PlaybackTo, window.COM_TIMEFORMAT2).add(userInfo.UserInfo.TimeZone, 'hours').format(window.COM_TIMEFORMAT),
          Imeis: [self.IMEI],
        };

        self.$app.request.post(API_URL.GET_REPORT_TRIP, data, function(result, xhr, status) {
            if(result.MajorCode === '000') {
              if(result.Data && result.Data.length){
                //self.initSummaryList(result.Data[0].Total, result.Data[0].Details);
                self.initTripList(result.Data[0].Details);
              }else{
                //self.initSummaryList();
                //~~~self.initTripList();
				self.getTrips2();
				
              }

            }else{
             
              self.$app.dialog.alert(LANGUAGE.PROMPT_MSG023 + `<br>MajorCode: ${result.MajorCode}<br>MinorCode: ${result.MinorCode}<br>${result.Data}`);
            }
          },
          function(xhr, status) {
            self.$app.dialog.close();
            self.$app.dialog.alert('Error occured at get Trips data');
          },
          'json');
      },
	  getTrips2: function(){
        let self = this;
        let userInfo = self.$app.methods.getFromStorage('userInfo');
        let data = {
          MajorToken: userInfo.MajorToken,
          MinorToken: userInfo.MinorToken,
          DateFrom: moment.utc(self.PlaybackFrom, window.COM_TIMEFORMAT2).add(userInfo.UserInfo.TimeZone, 'hours').format(window.COM_TIMEFORMAT),
          DateTo: moment.utc(self.PlaybackTo, window.COM_TIMEFORMAT2).add(userInfo.UserInfo.TimeZone, 'hours').format(window.COM_TIMEFORMAT),
          Imeis: [self.IMEI],
        };

        self.$app.request.post(API_URL.GET_REPORT_TRIP2, data, function(result, xhr, status) {
            if(result.MajorCode === '000') {
              if(result.Data && result.Data.length){
                //self.initSummaryList(result.Data[0].Total, result.Data[0].Details);
                self.initTripList(result.Data[0].Details);
              }else{
                //self.initSummaryList();
                self.initTripList();
				
              }

            }else{
             
              self.$app.dialog.alert(LANGUAGE.PROMPT_MSG023 + `<br>MajorCode: ${result.MajorCode}<br>MinorCode: ${result.MinorCode}<br>${result.Data}`);
            }
          },
          function(xhr, status) {
            self.$app.dialog.close();
            self.$app.dialog.alert('Error occured at get Trips data');
          },
          'json');
      },
      initTripList: function(tripsDetails=[]){
        let self = this;

        if (tripsDetails && tripsDetails.length){
          let startLatLngs = [];
          let endLatLngs = [];
          let colorLoopIndex = 0
          let userInfo = self.$app.methods.getFromStorage('userInfo');
          let modifiedTripDetails = []

          tripsDetails.forEach(trip=>{
		  //console.log('trip', trip)
            if (trip.StartTime) {
              trip.StartTimeLocal = moment(trip.StartTime, window.COM_TIMEFORMAT3).add(self.$app.data.UTCOFFSET,'minutes').format(window.COM_TIMEFORMAT);
              trip.StartTimeLocalDate = moment(trip.StartTimeLocal, window.COM_TIMEFORMAT).format(window.COM_TIMEFORMAT4);
            }
            if (trip.EndTime) {
              trip.EndTimeLocal = moment(trip.EndTime, window.COM_TIMEFORMAT3).add(self.$app.data.UTCOFFSET,'minutes').format(window.COM_TIMEFORMAT);
            }
            trip.color = self.$app.data.TripCustomization.colorNames[colorLoopIndex];
            trip.colorHEX = self.$app.data.TripCustomization.colors[colorLoopIndex];

            startLatLngs.push([trip.StartLat,trip.StartLng]);
            endLatLngs.push([trip.EndLat,trip.EndLng]);

            if (!modifiedTripDetails.length || modifiedTripDetails[modifiedTripDetails.length-1].StartTimeLocalDate !== trip.StartTimeLocalDate){
              modifiedTripDetails.push({
                Divider: true,
                StartTimeLocalDate: trip.StartTimeLocalDate
              })
            }
            modifiedTripDetails.push(trip)
            colorLoopIndex = colorLoopIndex === 14 ? 0 : ++colorLoopIndex
          })

          let promiseStartAddress = new Promise(function(resolve, reject) {
            self.getAddresses(startLatLngs, resolve, reject);
          });
          let promiseEndAddress = new Promise(function(resolve, reject) {
            self.getAddresses(endLatLngs, resolve, reject);
          });

          Promise.all([
            promiseStartAddress.catch(error => { return error }),
            promiseEndAddress.catch(error => { return error }),
          ]).then(values => {
            if (values[0] && values[1]){
              //for index shifting, which is needed to ignore item divider in trip list and insert correct value of address
              let shift = 0
              for (let i = 0; i < modifiedTripDetails.length; i++) {
                if(modifiedTripDetails[i].Divider){
                  shift = shift - 1
                }else{
                  if (values[0][i+shift] ) {
                    modifiedTripDetails[i].StartCustomAddress = values[0][i+shift];
                  }
                  if (values[1][i+shift] ) {
                    modifiedTripDetails[i].EndCustomAddress = values[1][i+shift];
                  }
                }
              }
              self.$setState({
                TripList: modifiedTripDetails
              });
            }
          }).catch(error => {
            console.log(error)
          });
     
          for (let [tripIndex, trip] of modifiedTripDetails.entries()) {
		        // console.log('&',trip, trip.StartTime)
          
            this.getTripRoute(
              {
                MinorToken: userInfo.MinorToken,
                IsIgnore:  self.$route.params.isIgnore,
                Code: self.Id,
                From: moment(trip.StartTime, window.COM_TIMEFORMAT3).format(window.COM_TIMEFORMAT2),
                To: moment(trip.EndTime, window.COM_TIMEFORMAT3).format(window.COM_TIMEFORMAT2),
              })
              .then( result => {
                //console.log(result)
                let polylinePoints = []
                let prevPoint = {}
                self.TripsDirectionIcons[tripIndex] = L.featureGroup();
                $.each( result, function(index,value){
                  let point = new L.LatLng(value.lat, value.lng);
                  polylinePoints.push(point);

                  //for small optimisation
                  let temp = {lat: Math.floor(value.lat * 10000) / 10000, lng: Math.floor(value.lng * 10000) / 10000}
                  if(index !==0
                    && temp.lat !== prevPoint.lat
                    && temp.lng !== prevPoint.lng
                  ){
                    prevPoint = Object.assign({},temp)
                    L.canvasMarker(point, {
                      radius: 10,
                      prevLatlng: index === 0 ? false : L.latLng(result[index-1].lat, result[index-1].lng),    //previous point
                      img: {
                        url: 'resources/images/direction-arrow.svg',
                        size: [20, 20],
                        rotate: 0,
                      },
                    }).addTo(self.TripsDirectionIcons[tripIndex])
                  }
                });

                let polylineBG = new L.Polyline(polylinePoints, {
                  color: trip.colorHEX,
                  weight: 6,
                  opacity: 0.9,
                });
                let polyline = new L.Polyline(polylinePoints, {
                  color: trip.colorHEX,
                  weight: 3,
                  opacity: 0.9,
                });
                if(self.isLife || self.isQProtect) {
                  polylineBG.options.opacity = 0
                  polyline.options.opacity = 0
                }

                self.TripsRoutes[tripIndex] = L.featureGroup([polylineBG, polyline]);

                if(self.isDirectionIconsOnMap){
                  self.TripsDirectionIcons[tripIndex].addTo(MapTrack);
                }

                if (!self.OptimizedRouteState){
                  self.TripsRoutes[tripIndex].addTo(MapTrack);
                }

                return result
              })
              .then( result => this.getTripRouteOptimized(result) )
              .then( result => {
                if(self.$app.methods.isObjEmpty(result)){
                  return
                }

                let polylines = []
                if (result.polylines && result.polylines.length){
                  polylines = polylines.concat(result.polylines)
                }
                if(result.dropped && result.dropped.length){
                  polylines = polylines.concat(result.dropped)
                }
                if(result.boundaries && result.boundaries.length){
                  polylines = polylines.concat(result.boundaries)
                }

                let polylineOptBg = new L.Polyline(polylines, {
                  color: trip.colorHEX,
                  weight: 6,
                  opacity: 0.7,
                });
                let polylineOpt = new L.Polyline(polylines, {
                  color: trip.colorHEX,
                  weight: 3,
                  opacity: 0.7,
                });
                if(self.isLife || self.isQProtect) {
                  polylineOptBg.options.opacity = 0
                  polylineOpt.options.opacity = 0
                }

                self.TripsRoutesOptimized[tripIndex] = L.featureGroup([polylineOptBg, polylineOpt]);
                if (self.OptimizedRouteState){
                  self.TripsRoutesOptimized[tripIndex].addTo(MapTrack)
                }
              })
          }
        }
        //console.log('here')
        self.$setState({
          isTripsLoaded: true,
          TripList: tripsDetails,
        });
      },
   
      showAddress: function(e) {    
        var parent = $$(e.target) 
        var Lat = e.target.dataset.lat
        var Lng = e.target.dataset.lng

				    parent.html('<p><span class="progressbar-infinite color-red"></span></p>');
						Protocol.Helper.getAddressByGeocoder({ lat: Lat, lng:  Lng }, function (address) {
				 
						 parent.html(address);
						});
      },
      showClickedMarker: function(e){
        let self = this;
        let parent = $$(e.target).closest('li');
        let markerId = parent.data('markerid');

        if (markerId) {
          let marker = self.PlaybackEventsLayerGroup.getLayer(markerId);
          if (marker) {
            self.PlaybackEventsLayerGroup.zoomToShowLayer(marker, function() {
              if (MapTrack.getZoom() < 15) {
                MapTrack.setView(marker.getLatLng(),15)
              }
              marker.openPopup();
            });
          }else{
            let name = parent.data('event-name');
            self.$app.methods.customNotification({title: name ? name : '', text: LANGUAGE.PROMPT_MSG095});
          }
        }


      },
      showClickedHistoryMarker: function(e){
        let self = this;
        let parent = $$(e.target).closest('li');
        let markerId = parent.data('markerid');

        if (markerId) {
          let marker = self.PlaybackHistoryLayerGroup.getLayer(markerId);
          if (marker) {
            self.PlaybackHistoryLayerGroup.zoomToShowLayer(marker, function() {
              if (MapTrack.getZoom() < 15) {
                MapTrack.setView(marker.getLatLng(),15)
              }
              marker.openPopup();
            });
          }else{
            let name = parent.data('event-name');
            self.$app.methods.customNotification({title: name ? name : '', text: LANGUAGE.PROMPT_MSG095});
          }
        }


      },
      initSmartSelectPlaybackHistoryIcon: function() {
        var self = this;
        var smartSelectEl = self.$el.find('.smartSelectPlaybackHistoryIcon');

        self.PlaybackSmartSelectHistoryIcon = app.smartSelect.create({
          el: smartSelectEl,
          openIn: 'popover',
          cssClass: 'smart-select-popover-custom-icons',
          renderItem: function(item, index){
            let ret = `
                        <li class="">
                            <label class="item-checkbox item-content">
                                <input type="checkbox" name="${ item.inputName }" value="${ item.value }" ${ item.selected ? 'checked' : '' }>
                                <div class="item-media">
                                    ${ item.icon }
                                </div>
                                <div class="item-inner">
                                    <div class="item-title">${ item.text }</div>
                                    <div class="item-after">
                                        <i class="icon icon-checkbox"></i>
                                    </div>
                                </div>
                            </label>
                        </li>
                    `;
            return ret;
          },
          on: {
            change: function(select, val){
              for (var i = self.PlaybackFilterHistoryList.length - 1; i >= 0; i--) {
                if (val.indexOf(self.PlaybackFilterHistoryList[i].Value) != -1) {
                  if (!MapTrack.hasLayer(self.PlaybackHistoryLayerSubGroups[self.PlaybackFilterHistoryList[i].Value])) {
                    MapTrack.addLayer(self.PlaybackHistoryLayerSubGroups[self.PlaybackFilterHistoryList[i].Value])
                  }
                }else{
                  MapTrack.removeLayer(self.PlaybackHistoryLayerSubGroups[self.PlaybackFilterHistoryList[i].Value])
                }
              }
            }
          }
        })
      },
      initSmartSelectPlaybackEventsIcon: function(){
        var self = this;
        var smartSelectEl = self.$el.find('.smartSelectPlaybackEventsIcon');

        self.PlaybackSmartSelectEventsIcon = app.smartSelect.create({
          el: smartSelectEl,
          openIn: 'popover',
          cssClass: 'smart-select-popover-custom-icons',
          renderItem: function(item, index){
            let ret = `
                        <li class="">
                            <label class="item-checkbox item-content">
                                <input type="checkbox" name="${ item.inputName }" value="${ item.value }" ${ item.selected ? 'checked' : '' }>
                                <div class="item-media">
                                    ${ item.icon }
                                </div>
                                <div class="item-inner">
                                    <div class="item-title">${ item.text }</div>
                                    <div class="item-after">
                                        <i class="icon icon-checkbox"></i>
                                    </div>
                                </div>
                            </label>
                        </li>
                    `;
            return ret;
          },
          on: {
            change: function(select, val){
              for (var i = self.PlaybackFilterEventsList.length - 1; i >= 0; i--) {
                if (val.indexOf(self.PlaybackFilterEventsList[i].Value) != -1) {
                  if (!MapTrack.hasLayer(self.PlaybackEventsLayerSubGroups[self.PlaybackFilterEventsList[i].Value])) {
                    MapTrack.addLayer(self.PlaybackEventsLayerSubGroups[self.PlaybackFilterEventsList[i].Value])
                  }
                }else{
                  MapTrack.removeLayer(self.PlaybackEventsLayerSubGroups[self.PlaybackFilterEventsList[i].Value])
                }
              }
            }
          }
        })
      },
      getAddresses: function(arr, resolve, reject){
        let data = {
          coordinates: arr
        }
        //console.log(data);
        this.$app.request.postJSON(API_URL.GET_ADDRESSES_FROM_ARRAY, data, function (result, xhr, status) {
            //console.log(result);
            resolve(result)
            //app.progressbar.hide();
          },
          function (xhr, status) {
            //app.progressbar.hide();
            reject(xhr);
            console.log(xhr, status);
          },
          'json');
      },
      mapZoomChanged: function (e){
        if(MapTrack.getZoom() <= 12){
          if(!this.isDirectionIconsOnMap){
            return
          }
          this.isDirectionIconsOnMap = false
          for (let i = 0; i < this.TripList.length; i++) {
            if(this.TripsDirectionIcons[i]){
              MapTrack.removeLayer(this.TripsDirectionIcons[i]);
            }

          }
        }else{
          if(this.isDirectionIconsOnMap){
            return
          }
          this.isDirectionIconsOnMap = true
          for (let i = 0; i < this.TripList.length; i++) {
            if(!this.TripList[i].isHidden && !MapTrack.hasLayer(this.TripsDirectionIcons[i])){
              MapTrack.addLayer(this.TripsDirectionIcons[i]);
            }
          }
        }
      },






      getTripRoute: function (params){
        var self = this;
        return new Promise((resolve, reject) => {
          self.$app.request.get(API_URL.GET_PLAYBACK_ARR_WITHOUTADDRESSES, params, function(result, xhr, status) {
              //console.log(result);
              self.$app.dialog.close();
              if (result.MajorCode == '000' && result.Data) {
                var HistoryArray = self.$app.methods.parsePlaybackHystoryArr(result.Data.HisArry);
                resolve(HistoryArray)
              }else{
                resolve([])
              }
            },
            function(xhr, status) {
              resolve([])
            },
            'json');
        })
      },
      getTripRouteOptimized: function (historyArray){
        var self = this;
        return new Promise((resolve, reject) => {
          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
            ]);
          });
          if(!rawArray.length){
            resolve({})
            return
          }
          $.ajax({
            type: "POST",
            url: API_URL.GET_PLAYBACK_ARR_WITHOUTADDRESSES_OPTIMISED2,  //API_URL.GET_PLAYBACK_ARR_WITHOUTADDRESSES_OPTIMISED,
            dataType: "json",
            data: JSON.stringify(rawArray),
            contentType: 'application/json',
            async: true,
            cache: false,
            timeout: 10000,
            success: function (result) {
              //console.log(result);
              resolve(result)
            },
            error: function (textStatus) {
              resolve({})
              self.$setState({OptimizedRouteState: false, CantBeOptimised: true});
            }
          });
        })

      },
	  
	  getElevationOptions: function() {

        var elevation_options = {

            // Default chart colors: theme lime-theme, magenta-theme, ...
            theme: "lightblue-theme",

            // Chart container outside/inside map container
            detached: true,

            // if (detached), the elevation chart container
            elevationDiv: "#elevation-div",

            // if (!detached) autohide chart profile on chart mouseleave
            autohide: false,

            // if (!detached) initial state of chart profile control
            collapsed: false,

            // if (!detached) control position on one of map corners
            position: "topright",

            // Autoupdate map center on chart mouseover.
            followMarker: true,

            // Autoupdate map bounds on chart update.
            autofitBounds: true,

            // Chart distance/elevation units.
            imperial: false,

            // [Lat, Long] vs [Long, Lat] points. (leaflet default: [Lat, Long])
            reverseCoords: false,

            // Acceleration chart profile: true || "summary" || "disabled" || false
            acceleration: false,

            // Slope chart profile: true || "summary" || "disabled" || false
            slope: false,

            // speed chart profile: true || "summary" || "disabled" || false
            speed: false,

            // Time stamp labels.
            time: false,

            // Summary track info style: "line" || "multiline" || false
            summary: "line",

            // Toggle chart ruler filter.
            ruler: true,

            // Toggle chart legend filter.
            legend: true,

        };

        return elevation_options;
    }

    },

    on: {
      pageInit: function(e, page) {
        var self = this;
        self.$app.dialog.close();

        var assetList = self.$app.methods.getFromStorage('assetList');
        var asset = assetList[self.$route.params.imei];
        var historyArray = self.$app.methods.getFromStorage('historyArray');

        var playbackControllButton = page.$el.find('.playback-controll-button');
        var playbackControllButtonIcon = page.$el.find('.playback-controll-button i');
        var playbackSpeed = page.$el.find('[name="PlaybackSpeed"]');
        var rangeSliderEl = page.$el.find('.range-slider-playback');
        var optimizedSwitcher = page.$el.find('input[name="checkbox-optimized"]');

        var lastQueryPosinfo = {};
		
		
		/*var geojsonFeature = {
			"type": "Feature",
			"properties": {
				"name": "Coors Field",
				"amenity": "Baseball Stadium",
				"popupContent": "This is where the Rockies play!"
			},
			"geometry": {
				"type": "Point",
				"coordinates": [-104.99404, 39.75621]
			}
		};
				
				var myLayer = L.geoJSON().addTo(MapTrack);
		myLayer.addData(geojsonFeature);
		
		  // Instantiate elevation control.
		  var controlElevation = L.control.elevation(self.elevationOptions).addTo(MapTrack);

		  controlElevation.load(myLayer);


		var myStyle = {
		    "color": "#ff7800",
		    "weight": 5,
		};
		var el = L.control.elevation({
  			position: "bottomleft",
            theme: "magenta-theme", //default: lime-theme
            useHeightIndicator: true, //if false a marker is drawn at map position
            interpolation: d3.curveLinear, //see https://github.com/d3/d3/wiki/
            collapsed: false, //collapsed mode, show chart on click or mouseover
            detachedView: true, //if false the chart is drawn within map container
            elevationDiv: "#elevation-div", // (detached) elevation chart container
		});
		el.addTo(MapTrack);
		var geojson = L.geoJson(geojson,{
			style:myStyle,
		    onEachFeature: el.addData.bind(el)
		}).addTo(MapTrack);*/
		
		/*

        var mapElement = $("#mapel");

        var neLat = mapElement.attr('neLat');
        var neLng = mapElement.attr('neLng');
        var swLat = mapElement.attr('swLat');
        var swLng = mapElement.attr('swLng');
		
		var gpx = mapElement.attr('gpx'); // URL to your GPX file or the GPX itself
        new L.GPX(gpx, {
            async: true,
            marker_options: {
                startIconUrl: '/lib/leaflet-gpx/pin-icon-start.png',
                endIconUrl: '/lib/leaflet-gpx/pin-icon-end.png',
                shadowUrl: '/lib/leaflet-gpx/pin-shadow.png'
            }
        }).on('loaded', function(e) {
            map.fitBounds(e.target.getBounds());
        }).addTo(MapTrack);

        // Instantiate elevation control.
        var controlElevation = L.control.elevation(self.getElevationOptions()).addTo(MapTrack);

console.log('gpx',gpx)
        // Load track from url (allowed data types: "*.geojson", "*.gpx")
        controlElevation.load(gpx);*/
		

     

        //self.getOptimizedRoute(historyArray);
        self.getTrips();
        self.initSmartSelectPlaybackEventsIcon();
        self.initSmartSelectPlaybackHistoryIcon()

        var rangeSlider = app.range.create({
          el: rangeSliderEl,
          on: {
            change: function (e, val) {
              self.$setState({
                PlaybackData: self.$app.methods.formatPlaybackData(historyArray[val], asset)
              });
              
              self.PlaybackMarker.setLatLng([historyArray[val].lat, historyArray[val].lng]);
              MapTrack.setView([historyArray[val].lat, historyArray[val].lng]);

              if(lastQueryPosinfo && Math.floor(historyArray[val].lat * 10000) / 10000 === lastQueryPosinfo.lat && Math.floor(historyArray[val].lng * 10000) / 10000 === lastQueryPosinfo.lng ){
                self.$setState({
                  CustomAddress: lastQueryPosinfo.address
                });
              }else{
                Protocol.Helper.getAddressByGeocoder({lat: historyArray[val].lat, lng: historyArray[val].lng},function(address){
                  lastQueryPosinfo = {lat : Math.floor(historyArray[val].lat * 10000) / 10000, lng : Math.floor(historyArray[val].lng * 10000) / 10000, address: address };
                  self.$setState({
                    CustomAddress: address
                  });
                });
              }
            }
          }
        });


        optimizedSwitcher.on('change', function(){
          if (!self.CantBeOptimised) {
            self.$setState({
              OptimizedRouteState: this.checked
            });

            if (this.checked) {
              /*if (self.PlaybackRouteLayerGroupOptimized) {
                MapTrack.removeLayer(self.PlaybackRouteLayerGroup);
                MapTrack.addLayer(self.PlaybackRouteLayerGroupOptimized);
              }*/

              for (let i = 0; i < self.TripList.length; i++) {
                if(!self.TripList[i].isHidden && self.TripsRoutesOptimized[i]){
                  MapTrack.addLayer(self.TripsRoutesOptimized[i]);
                  MapTrack.removeLayer(self.TripsRoutes[i]);
                }
              }
            }else{
              /*if (self.PlaybackRouteLayerGroup) {
                MapTrack.removeLayer(self.PlaybackRouteLayerGroupOptimized);
                MapTrack.addLayer(self.PlaybackRouteLayerGroup);
              }*/

              for (let i = 0; i < self.TripList.length; i++) {
                if(!self.TripList[i].isHidden && self.TripsRoutesOptimized[i]){
                  MapTrack.removeLayer(self.TripsRoutesOptimized[i]);
                  MapTrack.addLayer(self.TripsRoutes[i]);
                }
              }
            }
          }else{
            self.$app.methods.customNotification({
              title: LANGUAGE.ASSET_PLAYBACK_MSG00,
              text: LANGUAGE.PROMPT_MSG041
            });
            this.checked = false;

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

        });

        page.$el.on('change', '[name="checkbox-trip-visibility"]', function (e){
          self.TripList[this.value].isHidden = !this.checked
          if(this.checked){
            MapTrack.addLayer(self.OptimizedRouteState ? self.TripsRoutesOptimized[this.value] : self.TripsRoutes[this.value]);
            if(self.isDirectionIconsOnMap){
              MapTrack.addLayer(self.TripsDirectionIcons[this.value]);
            }
          }else{
            MapTrack.removeLayer(self.OptimizedRouteState ? self.TripsRoutesOptimized[this.value] : self.TripsRoutes[this.value]);
            MapTrack.removeLayer(self.TripsDirectionIcons[this.value]);
          }
        })
        page.$el.on('change', '[name="checkbox-trip-visibility-group"]', function (e){
          e.stopPropagation()
          var elArr = $(this).closest('li').nextUntil('li.item-divider');
          if (elArr && elArr.length) {
            for (var i = elArr.length - 1; i >= 0; i--) {
              $$(elArr[i]).find('input[type="checkbox"]').prop("checked", this.checked).change();
            }
          }
        })
        page.$el.on('click', '.trip-list .item-divider .item-toggle', function (e){
          $$(this).toggleClass('active')
          var elArr = $(this).closest('li').nextUntil('li.item-divider');
          if (elArr && elArr.length) {
            for (var i = elArr.length - 1; i >= 0; i--) {
              $$(elArr[i]).toggleClass('no-max-height')
            }
          }
        })
        /*$$('body').on('click', '.smart-select-page .item-divider', function(){
          var $el = $$(this);
          var elArr = $(this).nextUntil('li.item-divider');
          var state = !$el.data('state');

          if (elArr && elArr.length) {
            for (var i = elArr.length - 1; i >= 0; i--) {
              $$(elArr[i]).find('input[type="checkbox"]').prop("checked", state).change(); //[0].checked = state; //.dispatchEvent(new Event('change', { 'bubbles': true }))
            }
          }
          $el.data('state', state);
        });*/
        playbackControllButton.on('click', function(){
          if (self.PlaybackTimer) {
            self.stopPlaybackPlayer();

          }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 = rangeSlider.getValue();
          if (value != self.PointsCount) {
            value++;
            rangeSlider.setValue(value);
          }else{
            rangeSlider.setValue(0);
            value = 0;
            self.stopPlaybackPlayer();
          }
        }

        MapTrack.on('zoomend', self.mapZoomChanged);
       

      },

      pageBeforeIn: function(e, page){
        var self = this;

        let bottomAssetDetailsWidget = $$('.asset-details-widget');
        bottomAssetDetailsWidget.addClass('display-none')

        var fabViewAll = $$('.fab-viewall');
        if (MapTrack){
          MapTrack.removeLayer(AllMarkersGroup);
          if (fabViewAll && !fabViewAll.hasClass('disabled')) {
            fabViewAll.addClass('disabled');
          }
        }

        if (self.PlaybackData) {

          if (self.PlaybackData.Lat && self.PlaybackData.Lat) {
            Protocol.Helper.getAddressByGeocoder({lat: self.PlaybackData.Lat, lng: self.PlaybackData.Lng},function(address){
              self.$setState({
                CustomAddress: address
              });
            });
          }
        }

        self.showPlaybackRoute();

      },

      pageBeforeOut: function (e, page) {
        var self = this;

        let bottomAssetDetailsWidget = $$('.asset-details-widget');
        bottomAssetDetailsWidget.removeClass('display-none')

        /*if (GroupMarkers) {
            GroupMarkers.clearLayers();
            if (MapTrack) {
                MapTrack.removeLayer(GroupMarkers);
            }
        }*/
        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.PlaybackHistoryLayerGroup) {
          MapTrack.removeLayer(self.PlaybackHistoryLayerGroup);
        }
        if(!self.$app.methods.isObjEmpty(self.TripsRoutes)){
          const keys = Object.keys(self.TripsRoutes)
          for (const key of keys) {
            MapTrack.removeLayer(self.TripsRoutes[key])
            MapTrack.removeLayer(self.TripsDirectionIcons[key])
          }
        }
        if(!self.$app.methods.isObjEmpty(self.TripsRoutesOptimized)){
          const keys = Object.keys(self.TripsRoutesOptimized)
          for (const key of keys) {
            MapTrack.removeLayer(self.TripsRoutesOptimized[key])
          }
        }
        MapTrack.off('zoomend', self.mapZoomChanged);
        //
        self.stopPlaybackPlayer();

        var fabViewAll = $$('.fab-viewall');
        if (MapTrack && !MapTrack.hasLayer(AllMarkersGroup)) {
          if (AllMarkersGroup.getBounds().isValid()) {
            MapTrack.fitBounds(AllMarkersGroup.getBounds(),{padding:[16,16]});
            AllMarkersGroup.addTo(MapTrack);
          }
          if (fabViewAll && fabViewAll.hasClass('disabled')) {
            fabViewAll.removeClass('disabled');
          }
        }

      },

      pageBeforeRemove: function(e, page){
        let self = this;
        app.range.destroy('.range-slider-playback');
        if (self.PlaybackSmartSelectEventsIcon) {
          self.PlaybackSmartSelectEventsIcon.destroy();
        }
        if (self.PlaybackSmartSelectHistoryIcon) {
          self.PlaybackSmartSelectHistoryIcon.destroy();
        }
      },

    }
  };
</script>