$ = jQuery;
  IRON.data = {
  
  list: {
    playlist_name: false,
    tracks: false,
    type: false,
    random_order: "",
  },
  currentTrack: 0,
  continuous: false, //if the player has been loaded from cookies.
  favoriteTackList: false,
  playlistID: "",
  showList: false,
  isPlaying: false,
  audioplayerPlaying: null, //Which Audioplayer instance is playing.
  loading: 0,
  minimize: true,
  extendedPlayerOpened: false,
  extendedPlayerOverlayOpened: false,
  audioCtx: false,
  audioElement: false,
  audioSrc: false,
  analyser: false,
  frequencyData: false,
  userPref: {
    pause: false,
    minimize: false,
    autoplay: true,
  },
  storeButtonCount: 0,
  unlock: false,
  playerStatus: "",
  currentTime: "",
  totalTime: "",
  shuffle: false,
  repeatButton: (sonaar_music.option.sticky_show_repeat_bt == 'true') ? true : false,
  repeatStatus: IRON.repeatStatus,
  mute: false,
  volume: null,
  elWidgetId: false, //Only has value when the playlist is built with the elementor widget
  postId: false, //Used by the continous player when the playlist is generated by a elementor widget
  isSmallDevice:( $('body').width() > 768 )? false: true,
  classes: {
    enable: false,
    waveEnable: false,
    continuousPlayer: Boolean(sonaar_music.option.enable_continuous_player === "true"),
    show_nextprevious_bt: (sonaar_music.option.sticky_show_nextprevious_bt != "false") ? true : false,
    show_album_title: (sonaar_music.option.sticky_show_album_title != "false") ? true : false,
    show_speed_bt: Boolean(sonaar_music.option.sticky_show_speed_bt === "true"),
    show_skip_bt: Boolean(sonaar_music.option.sticky_show_skip_bt === "true"),
    show_tracklist_bt: (sonaar_music.option.sticky_show_tracklist_bt != "false") ? true : false,
    show_shuffle_bt: (sonaar_music.option.sticky_show_shuffle_bt != "false") ? true : false,
    show_mobile_next_bt: Boolean(sonaar_music.option.sticky_mobile_show_next === "true"),
    show_mobile_previous_bt: Boolean(sonaar_music.option.sticky_mobile_show_previous === "true"),
    show_mobile_tracklist_bt: Boolean(sonaar_music.option.sticky_mobile_show_tracklist === "true"),
    display_description: (sonaar_music.option.sticky_show_description != "false") ? true : false,
    template: sonaar_music.option.sticky_preset,
    floatpos: sonaar_music.option.float_pos,
    show_controls_hover: sonaar_music.option.show_controls_hover,
    isPlaying: false,
    author: srp_vars.sonaar_music.continuous_artist_name,
    feedUrl: false,
    noLoopTracklist: (srp_vars.sonaar_music.no_loop_tracklist == 'on') ? 'on' : false,
    notrackskip: (srp_vars.sonaar_music.no_track_skip == 'on') ? 'on' : false,
    continued: false, //Player settings come from the cookie (continuous player)
    dontCountContinuous: false, //For statistic. Dont count stats from the continuous player
    emptyPlayer: true,
    skipForward: 30,
    skipBackward: 15,
    speedRate: 1,
    wc_ajax_add_to_cart: (sonaar_music.option.wc_enable_ajax_addtocart == 'true') ? true : false,
    wc_variation_lb: (sonaar_music.option.wc_variation_lb != 'false') ? true : false,
  },
  selectedPlayer: null,
  cookieSetting: {
    mute: false,
    volume: 1,
    isPlaying: false,
    currentTime: 0,
    json: false, //Required for the continuous player with Post Related or "audio_meta_field" shorcode attribute as source
  },
};

var srp_seekTime = false;


Vue.component('control', {
  props: ["player"],
  template: `
  <div class="control" 
     :style="(player.isSmallDevice && (player.classes.show_mobile_previous_bt || player.classes.show_mobile_next_bt || player.classes.show_mobile_tracklist_bt)) 
     ? { 'margin-right': '10px !important', 'column-gap': '15px' } 
     : {}">
    <div aria-label="View Tracklist" 
     :title="sonaar_music.option.tooltip_tracklist_btn" 
     class="list control--item sricon-list" 
     @click="player.setshowList" 
     v-if="player.list.tracks.length > 1 && (!player.isSmallDevice && player.classes.show_tracklist_bt || (player.isSmallDevice && player.classes.show_mobile_tracklist_bt))">
    </div>
    <div aria-label="Rewind 15 seconds" :title="sonaar_music.option.tooltip_rwd_btn" class="sr_skipBackward sricon-15s" @click="sr_audioSkipTo(-1 * player.classes.skipBackward)" v-if="player.classes.show_skip_bt && !player.isSmallDevice"></div>
    <div aria-label="Previous Track" :title="sonaar_music.option.tooltip_prev_btn" class="previous control--item sricon-back" @click="player.previous" v-if="player.list.tracks.length > 1 && (!player.isSmallDevice && player.classes.show_nextprevious_bt || (player.isSmallDevice && player.classes.show_mobile_previous_bt))"></div>
    <div aria-label="Play / Pause" :title="sonaar_music.option.tooltip_play_btn" class="play control--item sricon-play" @click="player.play" :class="{'audio-playing': player.isPlaying }"></div>
    <div aria-label="Next Track" :title="sonaar_music.option.tooltip_next_btn" class="next control--item sricon-forward" @click="player.next" v-if="player.list.tracks.length > 1 && (!player.isSmallDevice && player.classes.show_nextprevious_bt || (player.isSmallDevice && player.classes.show_mobile_next_bt))"></div>
    <div aria-label="Forward 30 seconds" :title="sonaar_music.option.tooltip_fwrd_btn" class="sr_skipForward control--item sricon-30s" @click="sr_audioSkipTo(player.classes.skipForward)" v-if="player.classes.show_skip_bt && !player.isSmallDevice"></div>
    <div aria-label="Speed Rates" :title="sonaar_music.option.tooltip_speed_btn"class="sr_speedRate  control--item " :class="player.classes.speedRate != 1 ? 'active' : '' " @click="sr_setSpeedRate" v-if="player.classes.show_speed_bt && !player.isSmallDevice"><div>{{player.classes.speedRate}}X</div></div>
    <div aria-label="Shuffle Track" :title="sonaar_music.option.tooltip_shuffle_btn"class="shuffle control--item sricon-shuffle" :class="player.shuffle ? 'active' : '' " @click="sr_shuffleToggle" v-if="player.list.tracks.length > 1 && player.classes.show_shuffle_bt && !player.isSmallDevice"></div>
    <div aria-label="Repeat" :title="IRON.repeatToolTipLabel()" class="srp_repeat sricon-repeat control--item" @click="IRON.repeatButtonToggle" :data-repeat-status="player.repeatStatus" v-if="player.repeatButton && !player.isSmallDevice && !player.classes.notrackskip"></div>
    </div>`
})

Vue.component('waveform', {
  props: ["player"],
  template: `
  <div class="sr_progressbar_sticky">
    <div class="timing">
        <div class="time timing_currentTime">{{ player.currentTime }}</div>
        <div class="time timing_totalTime">{{ player.totalTime }}</div>
    </div>
    <div id="sPlayer" class="wave sonaar_fake_wave" :class="{reveal: player.classes.waveEnable, sr_hide: !player.classes.waveEnable}">
      <div class="sonaar_wave_base"><svg></svg>
        <canvas id="splayer-wave-container" :height="player.setWaveHeight" width="2540"></canvas>
      </div>
      <div class="sonaar_wave_cut"><svg></svg>
      <canvas id="splayer-wave-progress" :height="player.setWaveHeight" width="2540"></canvas>
      </div>
    </div>
    </div>`,
  mounted () {
    IRON.audioPlayer.fakeWaveClick('sticky');
  }
})

Vue.component('sonaar-extend-button', {
  props: ["player"],
  template: `
    <div aria-label="Show Call-to-action buttons" class="sonaar-extend-button" @click="player.showCTA" v-if="player.list.tracks.length >= 1 && player.albumStoreList.length >= 1">
      <i class="fas fa-ellipsis-v"></i>
    </div>
  `
});
Vue.component('store', {
  props: ["player"],
  template: `
      <transition name="sonaar-player-storefade">
      <div class="store" v-if="player.list.tracks.length >= 1 && player.albumStoreList.length >= 1">
      
          <ul class="track-store" v-if="player.albumStoreList.length >= 1">
            <li v-for="(store, storeIndex) in player.albumStoreList">
            <cta :player=player :storeid=storeIndex label=true></cta>
            </li>
          </ul>
      </div>
    </transition>
  `
});
Vue.component('cta', {
  props: ["player","storeid","label"],
  computed: {
      store () {
        var index;
        if( typeof this.storeid == 'number'){
          index=  this.storeid;
        }else{
          var storeId = this.storeid;
          index = IRON.sonaar.player.albumStoreList.findIndex(function(element) {
            var storeIdKey = (typeof element['cta-class'] !== "undefined")?'cta-class':'store-icon'; //Some CTA can be identify by using the "cta-class" key and other "store-icon"
            return typeof element[storeIdKey] === "string" && element[storeIdKey].includes(storeId);
          });
        }
        return IRON.sonaar.player.albumStoreList[index];
      },
  },
  template: `
      <span v-if="(typeof store !== 'undefined')">
        <a
            :href="store['link-option'] == 'popup' || (store['has-variation'] == true && player.classes.wc_variation_lb) ? '#!': store['store-link']"
          :target="store['store-target'] || store['link-option'] === 'popup' ? '_self' : '_blank'"
          v-bind:class="[
            {
              'sr_store_round_bt': store['store-type'] === 'wc',
              'srp-make-offer-bt': store['make-offer-bt'],
              'sr_store_ask_email': store['store-link'] === '#srp_ask_email',
              'add_to_cart_button ajax_add_to_cart': !store['make-offer-bt'] && player.classes.wc_ajax_add_to_cart && !store['has-variation'] && store['store-link'] !== '#srp_ask_email', // Prevent add_to_cart_button if store-link is #srp_ask_email
              'sr_store_force_share_bt--sticky': store['cta-class'] === 'sr_store_force_share_bt'
            },
            store['cta-class'] // Bind the store['cta-class'] directly to the class attribute
          ]"
          :download="player.ifDownloadAttribute(store)"
          :data-product_id="store['product-id'] !== undefined ? store['product-id'] : false"
          :data-barba-prevent="['sr_store_force_share_bt', 'srp-fav-bt'].includes(store['cta-class']) ? 'all' : null"
          @click="player.ctaClick(store, $(event.target))"
        >
          <i :class="store['store-icon']"></i>
          <span>{{ store['store-link'] === '#srp_ask_email' ? sonaar_music.option.download_settings_afe_button_label : (label ? store['store-name'] : '') }}</span>
        </a>
      </span>
    `
});

IRON.sonaar = {
  player: new Vue({
    el: "#sonaar-player",
    data: IRON.data,
    methods: {
      play: function () {
        this.userPref.autoplay = true;
        if (this.isPlaying) {
          document.getElementById("sonaar-audio").pause(); // -- Audio MediaElement
        } else {
          this.playAudio();
        }
      },
      playAudio: function () {
        var promise = document.getElementById("sonaar-audio").play();
        if (promise !== undefined) {
          promise
            .then((_) => {
              //console.log('play started! yeah');
              // Autoplay started!
            })
            .catch((error) => {
              console.log("Warning = " + error);
              // Autoplay was prevented.
              // Show a "Play" button so that user can start playback.
            });
        }
        if(typeof sonaar_music.option.sticky_spectro_style !== "undefined" && sonaar_music.option.sticky_spectro_style != "none"){
          startAudioSpectrum( '#sonaar-player' )
        }
      },
      previous: function () {
        if( document.getElementById('sonaar-audio').currentTime > IRON.previousTrackThreshold ){ //Resets the track to the beginning Or go to the previous track.
          document.getElementById('sonaar-audio').currentTime = 0;
          return;
        }
        if (this.shuffle) {
          var i;
          for (i = 0; i < this.list.random_order.length; i++) {
            if (this.list.random_order[i] == this.currentTrack) {
              if (i == 0) {
                this.currentTrack = this.list.random_order[this.list.random_order.length - 1];
              } else {
                this.currentTrack = this.list.random_order[i - 1];
              }
              break;
            }
          }
        } else {
          if (this.currentTrack - 1 < 0) return (this.currentTrack = this.list.tracks.length - 1);

          this.currentTrack--;
        }
      },
      next: function () {
        if (this.playerStatus == "next") return;

        if (this.shuffle) {
          var i;
          for (i = 0; i < this.list.random_order.length; i++) {
            if (this.list.random_order[i] == this.currentTrack) {
              if (i == this.list.random_order.length - 1) {
                if (this.classes.noLoopTracklist == "on"){
                  return;
                }
                this.currentTrack = this.list.random_order[0];
              } else {
                this.currentTrack = this.list.random_order[i + 1];
              }
              break;
            }
          }
        } else {
          if (this.list.tracks.length == 1) { //handleTrackChange() run automaticly when the currentTrack value change. When the playlist has only one track, the currenttrack value never change so we have to trig it here.
            if (this.classes.noLoopTracklist == "on") return; //Do nothing if the "No loop tracklist" is enable"
            this.handleTrackChange();
            return;
          }
          if (this.currentTrack + 1 >= this.list.tracks.length) { //At the end of the playlist
            if (this.classes.noLoopTracklist == "on") return; //Do nothing if the "No loop tracklist" is enable"
            return (this.currentTrack = 0);
          }

          this.currentTrack++;
        }
      },
      skipBackward: function () {
        sr_audioSkipTo(-1 * this.classes.skipBackward);
      },
      skipForward: function () {
        sr_audioSkipTo(this.classes.skipForward);
      },
      start: function () { //Created for custom JS | not used by the plugin code
        document.getElementById("sonaar-audio").play();
      },
      pause: function () { //Created for custom JS | not used by the plugin code
        document.getElementById("sonaar-audio").pause();
      },
      toggleStartPause: function () { //Created for custom JS | not used by the plugin code
        IRON.sonaar.player.play();
      },
 

      setPlaylist: function (audioPlayer, eq, time = 0) {
        if ($(audioPlayer).attr("trackselected") == eq || ($(audioPlayer).attr("trackselected") == null && eq == 0)) {
          $(audioPlayer).attr("duplicating_wave", true);
        }
        $(audioPlayer).attr("trackselected", eq);
        var params = audioPlayer.data("url-playlist").slice(audioPlayer.data("url-playlist").indexOf("title")).split("&");
        let newParams = [];
        params.forEach(function (el) {
          let paramName;
          let paramValue;
          [paramName, paramValue] = el.split('=')
          newParams[paramName] = paramValue;
        });
        if (newParams.feed.length || newParams.audio_meta_field.length) {
          var id = $(audioPlayer).attr("id"); //Use the elementor widget ID as the player ID. This param is only available the FEED option.
        } else {
          var id = newParams.albums;
        }
        this.setPlayer({
          id: id,
          category: newParams.category || '',
          title: newParams.title,
          trackid: eq,
          shuffle: audioPlayer.data("shuffle"),
          audioPlayer: audioPlayer,
          time: time
        });
      },

      preventContinuousUrl: function () {
        var preventURL = false;
        if (typeof sonaar_music.option.sr_prevent_continuous_url !== "undefined") {
          if (sonaar_music.option.sr_prevent_continuous_url.includes(sonaar_music.postID)) {
            preventURL = true;
          }
        }
        return preventURL;
      },

      setPlayerAndPlay: function (args) {
        if (IRON.sonaar.player.playlistID != args.id || this.currentTrack != args.trackid) {
          IRON.audioPlayer.stickyEnable = true;
          this.setPlayer(args);
          this.playAudio();
        } else {
          if (!this.isPlaying) {
            this.playAudio();
          }
          if (args.time) {
            this.seekTime(convertTime(args.time))
          }
          if (args.trackid && this.currentTrack != args.trackid) {
            this.currentTrack = args.trackid;
          }
        }
       
        if(args.nolooptracklist == "on"){
          IRON.sonaar.player.classes.noLoopTracklist = "on";
        }
        if(args.notrackskip == "on"){
          IRON.sonaar.player.classes.notrackskip = "on";
        }
      },

      getPlaylistbyID: function (id, category, title, elwidget, jsonFromCookie = false) {
        var playlistID = id || false;
        var title = title || "";
        var elwidget = elwidget ? elwidget + "&feed=1" : null;
          if (this.selectedPlayer === null && playlistID) {
            if (jsonFromCookie) {
              return jsonFromCookie;
            } else {
              return srp_vars.site_url + "?load=playlist.json&title=" + title + "&albums=" + playlistID + "&category=" + category + "&el_widget_id=" + elwidget + "&posts_per_pages=-1";
            }
          } else {
            json_url = this.selectedPlayer.attr("data-url-playlist");
            return json_url;
          }
      },

      seekTime: function (time) {
        if (time) {
          if (document.getElementById("sonaar-audio").duration !== Infinity) {
            document.getElementById("sonaar-audio").currentTime = convertTime(time);
          }
          srp_seekTime = false;
        }
      },

      setPlayer: function (args) {
        var newTracklistIsFavoriteList = (typeof args.audioPlayer != 'undefined' && args.audioPlayer.hasClass('srp_player_is_favorite'))? true : false;
        IRON.audioPlayer.stickyEnable = true;

        sanitized_id = args.id
        sanitized_id = sanitized_id.toString();
        sanitized_id = sanitized_id.split(" ").join(""); // prevent blank space
        args.id = sanitized_id.replace(/latest/i, srp_vars.sonaar_music.mostRecentId); // if latest string is used, replace it by the most recent id

        if(typeof sonaar_music.option.sticky_spectro_style !== "undefined" && sonaar_music.option.sticky_spectro_style != "none"  && $('#sonaar-audio').length){ // if sticky spectro is enabled
          document.getElementById("sonaar-audio").crossOrigin = "anonymous";
        }

        this.classes.emptyPlayer = false;
        var args = args || {};
        var params = {
          id: args.id,
          category: args.category || '',
          title: args.title || null,
          trackid: args.trackid || 0,
          autoplay: typeof args.autoplay == "boolean" ? args.autoplay : true,
          el_widget_id: args.elwidgetid || false,
          jsonFromCookie: args.json || false // Used to conserved postrelated playlist from single post
        };
        params.id = (params.id == '' && params.category != '') ? srp_vars.sonaar_music.currentPostId : params.id; 
        srp_seekTime = args.time || false;
        this.selectedPlayer = args.audioPlayer || null;

        if( this.continuous ){
          this.playlistID = false;
        }
        if(typeof  args.continuous != 'undefined' &&  args.continuous){
          this.continuous = true;
        }else{
          this.continuous = false;
        }

        this.elWidgetId = params.el_widget_id;
        this.shuffle = args.shuffle == true || args.shuffle == "true" || args.shuffle == "1" || (this.selectedPlayer && this.selectedPlayer.attr('data-shuffle') == 'true') ? true : false;
        var samePlaylist = false;
        if(this.selectedPlayer && this.selectedPlayer.hasClass('sr_selectedPlayer')){ //If the player is already selected
           samePlaylist = true;
        }else{
          $(".sr_selectedPlayer").removeClass("sr_selectedPlayer");
          $(this.selectedPlayer).addClass("sr_selectedPlayer");
        }

        if (!this.classes.wavesurferEnable) {
          IRON.audioPlayer.fakeWaveClick("sticky");
        }
        this.userPref.autoplay = params.autoplay;

        //const samePlaylist = (params.id && params.id === this.playlistID && this.favoriteTackList == newTracklistIsFavoriteList)? true : false;
        
        if (samePlaylist && params.trackid == this.currentTrack) { //If the track is already the current track.
          this.seekTime(srp_seekTime);
          return this.play();
        }
        if ( samePlaylist && params.trackid !== this.currentTrack ) {
          this.currentTrack = params.trackid;
        }

        //Load tracklist from th Json file only if the playlist ID has changed or if the playlist is a favorite playlist.
        if (
            !samePlaylist || 
            newTracklistIsFavoriteList !== this.favoriteTackList || 
            params.category !== this.categoryID
          ) {
          const endingTrack = this.currentTrack;
          $.when($.getJSON(this.getPlaylistbyID(params.id, params.category, params.title, params.el_widget_id, params.jsonFromCookie))).done(
            function (data) {
              if(data.length == 0){ return; } //If the playlist is empty
              if (!$("body").hasClass("artistPlayer-enable")) {
                this.classes.enable = true;
                if (!IRON.sonaar.player.classes.continued) {
                  this.minimize = false;
                }
                this.animatePlayer();
                $("body").addClass("continuousPlayer-enable");
              }
              this.list = data;
              if (IRON.players.length && this.selectedPlayer && this.selectedPlayer.hasClass('srp_reordered')) {
                for (var playerIndex = 0; playerIndex < IRON.players.length && IRON.players[playerIndex].audioPlayer.attr('id') != $(this.selectedPlayer).attr('id'); playerIndex++) { }; //Set playerIndex
                this.reOrderTacklist(playerIndex)
              }

              if (this.shuffle) {
                this.setRandomList();
                if (typeof args.trackid == "undefined") {
                  params.trackid = Math.floor(Math.random() * this.list.tracks.length);
                }
              }

              this.playlistID = params.id;
              this.categoryID = params.category;

              if(typeof sonaar_music.option.general_volume != 'undefined' && this.volume == null){
                sr_setVolume(sonaar_music.option.general_volume/100);
              }        

              if (this.list.type == "podcast") {
                for (var i = 0; i < this.list.tracks.length; i++) {
                  var element = this.list.tracks[i];

                  if (element.id == params.id) {
                    this.currentTrack = i;
                  }
                }
              } else {
                this.currentTrack = params.trackid;
              }

              if (this.currentTrack == 0 || //If the currentTrack still has the default value, execute handleTrackChange. 
                endingTrack == this.currentTrack //HandletrackChange function is automatically triggered when the currentTrack value is changed. Here we execute it if the currentTrack value is the same but the playlist ID has been changed.
              ) {
                this.handleTrackChange();
              }

              if(typeof IRON.sonaar.player.list.tracks === 'object' && typeof IRON.localStorageTrackMemory === 'object'){ //Verify if the track has been completed
                IRON.sonaar.player.list.tracks.forEach((track, index) => {
                    const trackMemoryKey = IRON.getTrackMemoryKeyFormat(track.mp3);
                    if (trackMemoryKey && IRON.localStorageTrackMemory.hasOwnProperty(trackMemoryKey)) {
                        const trackMemoryData = IRON.localStorageTrackMemory[trackMemoryKey];
                        if (Array.isArray(trackMemoryData) && trackMemoryData.length >= 3) {
                           track.hasCompleted = trackMemoryData[2];
                        }
                    }
                });
              }

            }.bind(this)
          );
          this.favoriteTackList = newTracklistIsFavoriteList;
        }

        if (this.selectedPlayer != null) {
          this.classes.feedUrl = this.selectedPlayer.data("feedurl");
          this.classes.noLoopTracklist = this.selectedPlayer.data("no-loop-tracklist");
          this.classes.notrackskip = this.selectedPlayer.data("notrackskip");
          this.cookieSetting.json = this.selectedPlayer.attr('data-url-playlist');
        }
        this.postId = srp_vars.sonaar_music.currentPostId;

        IRON.sonaar.player.selectedTimeStamp = null;
        if (typeof args.ts_id != 'undefined') { //set selected time stamp shortcode
          IRON.sonaar.player.selectedTimeStamp = $('#sonaar_ts-' + args.ts_id);
        } else {
          let selector = '.srmp3_sonaar_ts_shortcode';
          if (this.selectedPlayer != null && typeof this.selectedPlayer.data('ts-sync') != 'undefined') {
            IRON.sonaar.player.selectedTimeStamp = $('#sonaar_ts-' + this.selectedPlayer.data('ts-sync'));
            selector += ':not(#sonaar_ts-' + this.selectedPlayer.data('ts-sync') + ')';
          }
          $(selector).removeClass('sr_selected audio-playing');
        }

        if($('#srmp3_settings_shortcodebuilder').length && $('#adminmenuback').length){ //If we are in the shortcode builder, resize the player to fit the screen
          $('#sonaar-player').css('width', 'calc(100% - ' + $('#adminmenuback').width() + 'px)');
          $('#sonaar-player').css('right', 0);
        }
      },

      setAudio: function () {
        //Set to "audioplayerPlaying" which audioplayer is playing. ( 0 for the first audioplayer)
        var audioplayerPlayingID = null;
        $.each(IRON.players, function (index) {
          if ($(IRON.players[index].audioPlayer).hasClass("sr_selectedPlayer")) {
            audioplayerPlayingID = index;
          }
        });
        this.audioplayerPlaying = audioplayerPlayingID;
        this.setPlayerType();
        //----------------------------------------------------------------------
        
        if (this.list.tracks[this.currentTrack].mp3 === null || this.list.tracks[this.currentTrack].mp3 === "") {
          // feed url is used in the shortcode instead of post id
          this.list.tracks[this.currentTrack].mp3 = $(".iron-audioplayer.sr_selectedPlayer .sr-playlist-item").attr("data-audiopath");
          this.list.tracks[this.currentTrack].track_title = $(".iron-audioplayer.sr_selectedPlayer .sr-playlist-item").attr("data-tracktitle");
          this.list.tracks[this.currentTrack].album_title = $(".iron-audioplayer.sr_selectedPlayer .sr-playlist-item").attr("data-albumtitle");
          this.list.tracks[this.currentTrack].track_artist = $(".iron-audioplayer.sr_selectedPlayer .sr-playlist-item").attr("data-trackartist");
        }
        if(IRON.sonaar.player.hasPlayed == false){ // Register the audio object a first time for iOS to continue to next track on lock mode.
          elementAudio.src = this.list.tracks[this.currentTrack].mp3;
        }
        $("#sonaar-player").attr("data-tracktitle", this.list.tracks[this.currentTrack].track_title);
        $("#sonaar-player").attr("data-albumtitle", this.list.tracks[this.currentTrack].album_title);
        $("#sonaar-player").attr("data-trackartist", this.list.tracks[this.currentTrack].track_artist);
        $("#sonaar-player").attr("data-audiopath", this.list.tracks[this.currentTrack].mp3);
        if (this.list.tracks[this.currentTrack].id != null) {
          $("#sonaar-player").attr("data-trackid", this.list.tracks[this.currentTrack].id);
        }
        currentTrackTitle = this.list.tracks[this.currentTrack].track_title;
        currentAlbumTitle = this.list.tracks[this.currentTrack].album_title;
        currentArtistName = this.list.tracks[this.currentTrack].track_artist;
        currentAlbumArt = this.list.tracks[this.currentTrack].poster;

        IRON.audioPlayer.currentTrackData = {
          trackTitle: currentTrackTitle,
          albumTitle: currentAlbumTitle,
          artistName: currentArtistName,
          albumArt: currentAlbumArt
        }
        IRON.audioPlayer.setMediaSessionAPI(currentTrackTitle, currentAlbumTitle, currentArtistName, currentAlbumArt);     
        
        sr_addTrackToPlaylist(this.list.tracks[this.currentTrack]);
      
        if (!IRON.sonaar.player.selectedPlayer || !IRON.sonaar.player.selectedPlayer.trackMemory) { //if player is not sync with a widget player set with the track memory
          $("#sonaar-player .sonaar_wave_cut, .sr_selectedPlayer .album-player .sonaar_wave_cut, .sr_selectedPlayer .current .sonaar_wave_cut, #sonaar-player .mobileProgressing").width(0);
        }
        var trackHasEnded = document.getElementById("sonaar-audio").ended;
        var isPlaying = !document.getElementById("sonaar-audio").paused;
        $("#sonaar-audio").attr("src", this.list.tracks[this.currentTrack].mp3); //Load Audio MediaElement to the Sticky player
        $("#sonaar-audio").attr("title", currentTrackTitle); //set title for analytics reports (eg: matomo)
        //document.getElementById("sonaar-audio").crossOrigin = "anonymous";
        document.getElementById("sonaar-audio").load();
        if ($(".sr_selectedPlayer").length || isPlaying || trackHasEnded) {
          // if the sticky player is sync with a widget player OR is already playing
          this.playAudio();
          $("#sonaar-player .play").addClass("audio-playing");
        }
        this.classes.waveEnable = true;
        IRON.audioPlayer.checkArtWorkFullBg(this.selectedPlayer, false);
        

        if (IRON.players.length != 0 && this.selectedPlayer != null) { //If Widget Player is selected
          IRON.createFakeWave(this.selectedPlayer);
        }
        IRON.createFakeWave(false, true);
        
        $(document).trigger("sonaarStats", $("#sonaar-player"));
        if (IRON.players.length != 0 && this.classes.feedUrl && !this.elWidgetId && this.audioplayerPlaying != null) {
          //Set "elWidgetId" only when the playlist is built with the elementor widget
          this.elWidgetId = $(IRON.players[this.audioplayerPlaying].audioPlayer).parents(".elementor-widget-music-player").attr("data-id");
        }
        


        if (this.classes.continuousPlayer) {
          sr_setCookieSettings();
        }
 
        
        function ifHaveStoreContent() { //Check if the current player has store-content in the store list
          let value = false;
          $.each(IRON.sonaar.player.list.tracks, function () {
            if (typeof (this.song_store_list) != 'undefined') {
              $.each(this.song_store_list, function () {
                if (typeof (this['store-content']) != 'undefined') {
                  value = true;
                }
              });
            };
          });
          return value;
        }
        if (ifHaveStoreContent()) { //Load Modal reurired for store content popup
          sr_setPopUp();
        }
        
        this.seekTime(srp_seekTime);
        
        IRON.audioPlayer.sr_loadLyricsAjax(this.list.tracks[this.currentTrack].sourcePostID, this.list.tracks[this.currentTrack].track_pos);
        document.getElementById("sonaar-audio").playbackRate = IRON.sonaar.player.classes.speedRate;//set SpeedRate

        //set time from memory
        if(typeof IRON.sonaar.player.selectedPlayer?.find('.sr-playlist-item').eq(this.currentTrack).data('current-time') != 'undefined'){
          sr_setTrackCurrentTime(IRON.sonaar.player.selectedPlayer.find('.sr-playlist-item').eq(this.currentTrack).data('current-time'));
        }
      },
      clickPlayer: function () {
        if (!$('.control:hover').length) {
          this.openMobileControl();
        }
      },
      extendedScrolldown: function () {
        const extendedPlayer = document.querySelector(".srp_extendedPlayer_scrolling_box")
        if(extendedPlayer.scrollTop === 0){
          extendedPlayer.scrollTo({
            top: extendedPlayer.scrollTop + 200,
            behavior: "smooth"
          });
        }  
      },
      clickTrackList: function (index) {
        if(this.currentTrack == index){
          this.play();
        }else{
          this.currentTrack = index; 
          this.playAudio();
        }
      },
      /*Close and Open the sticky mobile control Panel*/
      /* the "cmd" parameter can be use if we only want to "open" or "close" the panel. By default it is toggling between each state.*/
      openMobileControl: function (cmd = false) {
        if ( this.isSmallDevice ) {
          this.extendedPlayerOpened = true;
          $('body').addClass('srp_sticky_ext_opened');
        }
      },
      setshowList: function () {
        if (this.showList == false) {
          $("#pusher-wrap").addClass("sonaar-list-active");
          return (this.showList = true);
        }
        $("#pusher-wrap").removeClass("sonaar-list-active");
        return (this.showList = false);
      },
      setPlayerType: function () {
        this.list.type = sonaar_music.option.player_type; //from plugin settings
        if (this.audioplayerPlaying != null) {
          this.list.type = IRON.players[this.audioplayerPlaying].audioPlayer.playerType; //from widget
        }
        if (srp_vars.sonaar_music.post_player_type != '' && srp_vars.sonaar_music.post_player_type != 'default') {
          this.list.type = srp_vars.sonaar_music.post_player_type //from playlist post settings selected in the page settings
        }
      },
      closePlayer: function () {
        if (this.showList) {
          $("#pusher-wrap").removeClass("sonaar-list-active");
          this.showList = false;
        }
        this.minimize = !this.minimize;
        this.classes.enable = !this.classes.enable;
        this.animatePlayer();
      },
      extendedPlayerClickOutside: function () {
        if($('.srp_extendedPlayer > *:hover').length == 0){
          this.closeExtendedPlayer()
        }
      },
      closeExtendedPlayer: function () {
        this.extendedPlayerOpened = false;
        $('body').removeClass('srp_sticky_ext_opened');
      },
      openExtendedPlayerOverlay: function () {
        this.extendedPlayerOverlayOpened = true;
      },
      closeExtendedPlayerOverlay: function () {    
        this.extendedPlayerOverlayOpened = false;
      },
      getIndexFromStoreList: function (store, inputName, storeList) {
        const valueToSearch = store[inputName];
        var index = -1; //Default
        for (var i = 0; i < storeList.length; i++) {
          if (storeList[i][inputName] === valueToSearch) {
            index = i;
            return index;
          }
        }
        return index;
      },
      

      playlistAfterEnter: function () {
        var ps = new PerfectScrollbar("#sonaar-player .playlist .scroll", {
          wheelSpeed: 0.7,
          swipeEasing: true,
          wheelPropagation: false,
          minScrollbarLength: 20,
          suppressScrollX: true,
        });
        /*$('#sonaar-player .playlist .scroll').perfectScrollbar({
          'suppressScrollX': true
        })*/
      },
      scroll: function (event) {
        var el = event.target;
        var parent = el.offsetParent;

        if (el.offsetWidth > parent.offsetWidth && !el.classList.contains("scrolling")) {
          el.classList.add("scrolling");
          var transformWidth = el.offsetWidth + 10;
          el.insertAdjacentHTML("beforeend", '<span class="duplicate">' + el.innerText + "</span>");
          el.style.transform = "translate( -" + transformWidth + "px )";
          setTimeout(function () {
            el.classList.remove("scrolling");
            el.style.transform = "";
            el.removeChild(el.firstElementChild);
          }, 6000);
        }
      },
      updatePlayers: function () {
        $(".iron-audioplayer").removeClass("audio-playing");
        
        if (IRON.players.length != 0 && this.selectedPlayer != null) { //If Widget Player is selected

          this.selectedPlayer.find("li.current").removeClass("current");

          if (this.isPlaying) {
            var currentTrackPlaying = this.currentTrack;
            //var currentTrackTitle;
            this.selectedPlayer.addClass("audio-playing");
            this.selectedPlayer.find('.currentTime, .totalTime').show();
            this.selectedPlayer.find(".sr-playlist-item").eq(currentTrackPlaying).addClass("current");

            if (this.selectedPlayer.data('hide-artwork') != '1' && this.selectedPlayer.data('hide-artwork') != 'true' && typeof this.selectedPlayer.data('albumart') == 'undefined') {
              if (this.list.tracks[this.currentTrack].poster == '') {
                this.selectedPlayer.addClass('sonaar-no-artwork');
              } else {
                  this.selectedPlayer.removeClass('sonaar-no-artwork');
                  this.selectedPlayer.find('.album-art img').attr("src", this.selectedPlayer.find(".sr-playlist-item").eq(currentTrackPlaying).data('albumart') );
              }
              srp_getColorsFromImage(this.selectedPlayer, this.selectedPlayer.find(".sr-playlist-item").eq(currentTrackPlaying).data('albumart'))
            }
            //currentTrackTitle = this.selectedPlayer.find(".sr-playlist-item").eq(this.currentTrack).attr("data-tracktitle");
            IRON.audioPlayer.updateMiniPlayer(this.selectedPlayer, this.selectedPlayer.find(".sr-playlist-item").eq(this.currentTrack));
           /* if (this.audioplayerPlaying != null) {
              $(IRON.players[this.audioplayerPlaying].audioPlayer).find(".track-title").html(currentTrackTitle);
            }*/
          }
        }
        if (this.selectedTimeStamp != null) { //If Time Stamp shortcode is selected
          $('.srmp3_sonaar_ts_shortcode').removeClass('audio-playing');
          if (this.isPlaying) {
            this.selectedTimeStamp.addClass('audio-playing');
          }
        }

        startAudioSpectrum(this.selectedPlayer);
        IRON.setExtendedPlayerHeightVar();
      },

      scrollingProgressBar: function (event) {
        var progressedAudio = event.target.clientWidth / event.touches[0].clientX;
        document.getElementById("sonaar-audio").currentTime = document.getElementById("sonaar-audio").duration / progressedAudio;
      },

      setSlideVolume: function () {
        sr_initSlider($(this.$el).find(".volume .slide"));
      },

      showCTA: function () {
        if ($("#sonaar-player.enable .store").hasClass("opened")) {
          $("#sonaar-player.enable .store").removeClass("opened");
        } else {
          $("#sonaar-player.enable .store").addClass("opened");
        }
      },

      setRandomList: function () {
        //If the player is selected set the currentTrack to the first track of the random list set firstTrackIndex to the currentTrack value. Otherwise set firstTrackIndex to null.
        firstTrackIndex = (typeof IRON.sonaar.player.selectedPlayer != 'undefined' && IRON.sonaar.player.selectedPlayer != null)? IRON.sonaar.player.selectedPlayer.data('currentTrack') : null;
        this.list.random_order = IRON.audioPlayer.setRandomList(this.list.tracks, firstTrackIndex);
      },

      setIsPlaying: function (value) {
        this.isPlaying = value;
        if (this.classes.continuousPlayer) {
          sr_setCookieSettings();
        }
      },

      handleTrackChange: function () { //This function is automatically triggered when the currentTrack value is changed.
        //console.log('handleTrackChange', this.selectedPlayer.currentTrack, this.currentTrack);

        IRON.favorites.setStickyFavButtons();
        IRON.swiper.update(IRON.sonaar.player.selectedPlayer, IRON.sonaar.player.currentTrack);
        IRON.getIceCastInfo(IRON.sonaar.player.selectedPlayer);
        this.isPlaying = false;
        this.classes.waveEnable = false;


        
       
        if (this.selectedPlayer) {
          this.selectedPlayer.currentTrack = this.currentTrack;
        }
        this.setAudio();



        IRON.init_generatePeaks();

        this.updatePlayers();
      },

      animatePlayer: function () {
        //animation when we click on the close button or when the player is loaded
        if (this.classes.continued) {
          if (this.minimize) {
            $("#sonaar-player").css("bottom", '-' + ($('#sonaar-player').height() + 6) + 'px');
          }else{
            $("#sonaar-player").css("bottom", "0");
          }
          this.classes.continued = false;
        } else {
          if (this.minimize) {
            bottomPosition = '-' + ($('#sonaar-player').height() + 6) + 'px';
          } else {
            bottomPosition = "0";
          }
          // replace #sonaar-player sricon-down-arrow by sricon-up-arrow
      
          $("#sonaar-player").animate({
            bottom: bottomPosition,
          });
        }
      },

      ctaClick: function (store, el) {
        var storeIndex;
        if (store['link-option'] == 'popup') { // Open Popup
          storeIndex = this.getIndexFromStoreList(store, 'store-content', this.list.tracks[this.currentTrack].song_store_list );
          this.storePopUp(this.currentTrack, storeIndex, el)
        } else if (store['has-variation'] == true && this.classes.wc_variation_lb) { // Open variation Lighbox
          srp_variation_button(el, store['product-id']);
        } else if (this.classes.wc_ajax_add_to_cart && store['has-variation'] == false) { // Ajax add to cart
          srp_add_to_cart_loadspinner(el);
        }
        if(store['cta-class'] == 'srp-fav-bt'){
          storeIndex = this.getIndexFromStoreList(store, 'cta-class', this.list.tracks[this.currentTrack].optional_storelist_cta );
          IRON.favorites.clickStickyFavButton( storeIndex );
        }
        if(store['make-offer-bt']){
          el = $(el).closest('a');
          srp_variation_button(el);
        }
        if(store['store-link']=='#srp_ask_email'){
          handleAskEmailClick($(el));
        }
      },

      ifDownloadAttribute: function (store) {
        if( 
          store['store-icon'] === 'fas fa-download' && store['link-option'] !== 'popup' && (typeof store['store-link'] != 'undefined' && !store['store-link']?.startsWith('#') || typeof store['store-link'] == 'undefined' ) &&
          (typeof store['download-attr'] == 'undefined' || typeof store['download-attr'] != 'undefined' && store['download-attr']) //dont set the download attribute if "condition NOT met" and force download CTA redirection is enabled 
        ){
          return '';
        }else{
          return false;
        } 
      },

      storePopUp: function (trackNumber, storeNumber, el) {
        const playlistPostId = this.list.tracks[trackNumber].sourcePostID;
        let postTrackIndex = 0;
        let postTrackCount = 0;
        $.each(this.list.tracks, function (index) {
          if (this.sourcePostID == playlistPostId) {
            if (index == trackNumber) {
              postTrackIndex = postTrackCount;
            }
            postTrackCount++
          }
        });
        const storeId = postTrackIndex + '-' + storeNumber;
        sr_popUp(playlistPostId, storeId, null, null, el)
      },

      /* Re Order the tracklist when the sticky player plays a re-organized(filter/order) playlist by list.js */
      reOrderTacklist: function (playerIndex) {
        if (!IRON.sonaar.player.list.tracks)
          return;

        let newTrackOrder = [];
        $(IRON.players[playerIndex].audioPlayer.find('.sr-playlist-item')).each(function () {
          mp3ToSeek = $(this).data('audiopath');
          titleToSeek = $(this).data('tracktitle');
          postIdToSeek = $(this).data('post-id');
          let trackFound = '';
          IRON.sonaar.player.list.tracks.forEach(function (e, i) {

            e.mp3 = (typeof e.mp3 == 'string') ? e.mp3.replace(/&amp;/g, '&') : e.mp3;
            if (e.mp3 == mp3ToSeek && String(titleToSeek).includes(e.track_title, 0) && postIdToSeek == e.sourcePostID ) {
              trackFound = IRON.sonaar.player.list.tracks[i];
              trackFound['track_index'] = i; //useful for the continuous player.
              newTrackOrder.push(trackFound);
            }
          })
        })
        
        if( newTrackOrder.length ){
         IRON.sonaar.player.list.tracks = newTrackOrder
        }
      },
      unsyncWidgetPlayers: function () {
        IRON.sonaar.player.selectedPlayer = null;
        $('.sr_selectedPlayer').removeClass('sr_selectedPlayer audio-playing');
        IRON.sonaar.player.playlistID = null;
      },
    },

    computed: {
      templateType: function () {
        return "sr-" + this.classes.template;
      },
      setWaveHeight: function () {
        if (this.classes.template == 'mini_fullwidth') {
          return '27';
        } else {
          return '40';
        }
      },
      floatPos: function () {
        return "sr-pos--" + this.classes.floatpos;
      },
      showControlsHover: function () {
        if (this.classes.show_controls_hover === "true") {
          return "sr-show_controls_hover";
        }
      },
      isDraggable: function () {
        if (sonaar_music.option.make_draggable === "true") {
          return "sr-draggable";
        }
      },
      stickyProgressBar: function () {
        if (sonaar_music.option.sticky_hide_progress_bar === "true") {
          return false;
        } else {
          return true;
        }
      },
      classType: function () {
        return "list-type-" + this.list.type;
      },
      playerCallToAction: function () {
        if (this.list.type == "podcast") {
          return this.list.tracks[this.currentTrack].podcast_calltoaction;
        } else {
          return this.list.tracks[this.currentTrack].song_store_list;
        }
      },
      albumStoreList: function () {
        var song_store = this.list.tracks[this.currentTrack].song_store_list;
        var album_store = this.list.tracks[this.currentTrack].album_store_list;
        var optional_cta = this.list.tracks[this.currentTrack].optional_storelist_cta;

        if (this.selectedPlayer) {
          // For dynamic visiblity buttons. Check if optional CTA is available in the current track. If not, remove it from the array, otherwise change the href to reflect the current track button href.
          var $currentTrackfromWidget = this.selectedPlayer.find(".sr-playlist-item").eq(this.currentTrack);
          //check if $currentTrackfromWidget exists
          if ($currentTrackfromWidget.length > 0) {
          
            var storeElements = $currentTrackfromWidget[0].querySelectorAll('.song-store-list-container .song-store');
            var domDataArray = [];
            storeElements.forEach(function(storeElement) {
              // if class is includes srp-fav-bt or sr_store_force_share_bt or sr_store_force_dl_bt or sr_store_force_pl_bt and is not part of optional_cta, maybe its set by the shortcode
              var classAttribute = storeElement.getAttribute('class');
              // Check if class includes any of the specified strings
              var shouldInclude = ['srp-fav-bt', 'sr_store_force_share_bt', 'sr_store_force_dl_bt', 'sr_store_force_pl_bt'].some(str => classAttribute.includes(str));
              // Breakdown classAttribute into individual classes
              var classList = classAttribute.split(' ');
              // Check if any class from classList is part of optional_cta
              var isInOptionalCta = (optional_cta) ? classList.some(cls => optional_cta.some(item => item['cta-class'] === cls)) : '';

              // Only proceed if the class is one of the desired ones and not in optional_cta
              if (shouldInclude && !isInOptionalCta) {
                    // Extract data for each store
                    var storeData = {
                        "store-icon": storeElement.querySelector('i').className,
                        "store-link": storeElement.getAttribute('href'),
                        "store-name": storeElement.getAttribute('title'),
                        "store-target": storeElement.getAttribute('target'),
                        "cta-class": storeElement.getAttribute('class')
                        .replace('song-store', '')  // Remove 'song-store'
                        .replace('sr_store_wc_round_bt', '')  // Remove 'sr_store_wc_round_bt'
                        .replace('srp_hidden', '')  // Remove 'srp_hidden' if it exists
                        .trim(),  // Trim any extra spaces
                        "show-label": storeElement.querySelector('.srp_cta_label') !== null,
                        "download-attr": (storeElement.getAttribute('download') === null)? false : true,
                    };

                    domDataArray.push(storeData);
              };
            });
        
            if (Array.isArray(optional_cta)) {
              optional_cta.forEach(function (ctaItem) {
                $trackButton = $currentTrackfromWidget.find('.' + ctaItem['cta-class']);            
                if( $trackButton.length === 0 ){
                  //remove this item from this array
                  optional_cta.splice(optional_cta.indexOf(ctaItem), 1);
                }
                if( $trackButton.length === 1 ){  
                  // modify the store-link
                  ctaItem['store-link'] = $trackButton.attr('href');  
                }
              });
            }
        }
      };
        var storesObjects = [];
        if (song_store.length < 1 || song_store.length === false) {
          storesObjects = album_store !== undefined ? album_store : [];
        } else {
          storesObjects = album_store === false ? song_store : song_store.concat(album_store);
        } 
              
        if (!Array.isArray(storesObjects)) {
          storesObjects = [];
        }
      
        if (Array.isArray(domDataArray)) { // Only concat if domDataArray is an array
          storesObjects = storesObjects.concat(domDataArray);
        }
        if(typeof optional_cta != 'undefined' && optional_cta !== false){
          if( storesObjects !== false ){
            storesObjects = storesObjects.concat(optional_cta);
          }else{
            storesObjects = optional_cta;
          }
        }
        storeButtonCount = storesObjects.length;

        return storesObjects;
      },
      hasArtwork: function () {
        var strURL = (typeof this.list.tracks[this.currentTrack] != 'undefined')? this.list.tracks[this.currentTrack].poster : false;
        if (strURL != null && strURL != false) {
          return !strURL.endsWith("default.png");
        }else{
          return false;
        }
      },

      playLabelButton: function () {
        return this.isPlaying ? srp_vars.sonaar_music.play_button_label.pause : srp_vars.sonaar_music.play_button_label.play;
      },
      playListTitle: function () {
        if (this.selectedPlayer && this.selectedPlayer.attr("data-playlist_title").length) {
          this.list.playlist_name = this.selectedPlayer.attr("data-playlist_title");
        }
        if (this.list.playlist_name == "") {
          return this.list.tracks[this.currentTrack].album_title;
        } else {
          return this.list.playlist_name;
        }
      },
      outputTrackDescription: function () {
          if(this.classes.display_description){
            return this.list.tracks[this.currentTrack].description;
          }else{
            return false;
          }    
      },
      sr_countUIitems: function () {
        let countItem = 1;
        if (this.list.tracks.length > 1 && this.classes.show_nextprevious_bt) {
          countItem++;
        }
        if (this.list.tracks.length > 1 && this.classes.show_tracklist_bt) {
          countItem++;
        }
        if (this.list.tracks.length >= 1 && this.albumStoreList.length >= 1) {
          countItem++;
        }
        return (countItem);
      },
    },
    mounted: function () {
      this.$nextTick(function () {
        IRON.sonaar.player.hasPlayed = false;
        $("#sonaar-audio").on("ended", function () {
          if(IRON.sonaar.player.selectedPlayer){
            IRON.setTracksTimeMemories(IRON.sonaar.player.selectedPlayer, 0, true); //Reset the track time memory when the track is ended
            IRON.sonaar.player.list.tracks[IRON.sonaar.player.currentTrack].hasCompleted = true
            IRON.sonaar.player.selectedPlayer.list.tracks[IRON.sonaar.player.currentTrack].hasCompleted = true;
          }
          if(IRON.repeatStatus !== false){
            if( IRON.sonaar.player.repeatStatus === 'track' && IRON.sonaar.player.classes.notrackskip !== "on"){
              IRON.sonaar.player.currentTime = 0;
              IRON.sonaar.player.playAudio();
              return;
            }

            if(IRON.sonaar.player.currentTrack + 1 >= IRON.sonaar.player.list.tracks.length && IRON.sonaar.player.repeatStatus !== 'playlist'){
              return;
            }
          }

          if (IRON.sonaar.player.classes.notrackskip !== "on") {
            IRON.sonaar.player.hasPlayed = true;
            IRON.sonaar.player.next();
          }
          
        });

        $("#sonaar-audio").on("timeupdate", function () {
          const duration = (this.duration == 'Infinity')? this.buffered.end(this.buffered.length-1) : this.duration;
          $("#sonaar-player .sonaar_wave_cut, .sr_selectedPlayer .album-player .sonaar_wave_cut, .sr_selectedPlayer .current .sonaar_wave_cut, #sonaar-player .mobileProgressing").width(((this.currentTime + 0.35) / duration) * 100 + "%");
          $("#sonaar-player .progressDot").css("left", (this.currentTime / duration) * 100 + "%");
          var sonaarAudio = document.getElementById("sonaar-audio");
          var currentTime = sonaarAudio.currentTime;
          var time = moment.duration(currentTime, "seconds");
          // Update the Sticky player currentTime
          if (time.hours() >= 12 || time.hours() <= 0) {
            IRON.sonaar.player.currentTime = moment(time.minutes() + ":" + time.seconds(), "m:s").format("mm:ss");
          } else {
            IRON.sonaar.player.currentTime = moment(time.hours() + ":" + time.minutes() + ":" + time.seconds(), "h:m:s").format("h:mm:ss");
          }

          if (sonaarAudio.duration !== Infinity) {
            var timeLeft = moment.duration(sonaarAudio.duration - sonaarAudio.currentTime, "seconds");
            // Update the Sticky player timeLeft
            if(timeLeft.milliseconds() > 0){
              if (  timeLeft.hours() >= 12 || timeLeft.hours() <= 0 ) {
                IRON.sonaar.player.totalTime = "-" + moment(timeLeft.minutes() + ":" + timeLeft.seconds(), "m:s").format("mm:ss");
              } else {
                IRON.sonaar.player.totalTime = "-" + moment(timeLeft.hours() + ":" + timeLeft.minutes() + ":" + timeLeft.seconds(), "h:m:s").format("h:mm:ss");
              }
            }else{
              IRON.sonaar.player.totalTime = ""
            }
          } else {
            IRON.sonaar.player.totalTime = "";
          }
        
          IRON.audioPlayer.karaokeMode($(".sr_selectedPlayer"), this.currentTime);
          $(".sr_selectedPlayer .currentTime").html(IRON.sonaar.player.currentTime); // Update the widget player currentTime
          $(".sr_selectedPlayer .totalTime").html(IRON.sonaar.player.totalTime); // Update the widget player timeLeft
          sr_setCookieTime();
          if(IRON.sonaar.player.selectedPlayer){
            IRON.setTracksTimeMemories(IRON.sonaar.player.selectedPlayer);
          }
        });

        $("#sonaar-audio").on(
          "play",
          function () {
            this.playerStatus = "play";
            this.setIsPlaying(true);
          }.bind(this)
        );

        $("#sonaar-audio").on(
          "pause",
          function () {
            this.setIsPlaying(false);
            this.userPref.pause = true;
          }.bind(this)
        );
        

        this.frequencyData = new Uint8Array(170);
        this.setSlideVolume();
      });
    },
    watch: {
      currentTrack: function () {
        if( typeof this.classes.preventHandleTrackChange != 'undefined' && this.classes.preventHandleTrackChange == true ){
          this.classes.preventHandleTrackChange = false; //set preventHandleTrackChange to true if we dont wanna trigger the handleTrackChange function: used for Favorite feature
          return;
        }

        this.handleTrackChange();
      },
      isPlaying: function () {
        this.updatePlayers();
      },
      minimize: function () {
        if (this.classes.continuousPlayer) {
          sr_setCookieSettings();
        }
        this.userPref.minimize = this.minimize;
        if (this.minimize) {
          $("body").removeClass("continuousPlayer-enable");
        } else {
          $("body").addClass("continuousPlayer-enable");
        }
      },
    },
  }),
};
if (window.matchMedia('(min-width: 861px)').matches) {
  $('#sonaar-player.sr-float .player.sr-draggable').draggable();
  $('#sonaar-player.sr-float .player.sr-draggable').css('cursor', 'grab');
}

/*FLOAT template, extra JQuery*/
$('#sonaar-player.sr-float .player.sr-show_controls_hover').hover(function () {
  let playerWidth = $(this).outerWidth() + $(this).find('.player-row .control').outerWidth() + $(this).find('.volume').outerWidth();
  playerWidth = ($(this).find('.sonaar-extend-button').length) ? playerWidth + $(this).find('.sonaar-extend-button').outerWidth() : playerWidth;
  $(this).width(playerWidth);

}, function () {
  $(this).width(342)
});
