text: 'use strict';
  
  var dom = require('./dom');
  var utilities = require('./utilityFunctions');
  
  var playerUtils = {};
  
  // function .bind를 지원하지 않는 하위 웹브라우져를 위한 호환성 유지 코드
  if(!Function.prototype.bindTo) {
  	Function.prototype.bindTo = function(THIS) {
  		if(typeof this !== 'function') {
  			// closest thing possible to the ECMAScript 5
  			// internal IsCallable function
  			throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
  		}
  
  		var args = Array.prototype.slice.call(arguments, 1),
  			f_to_bind = this,
  			f_nop = function() {},
  			f_bound = function() {
  				return f_to_bind.apply(this instanceof f_nop && THIS ? this : THIS, args.concat(Array.prototype.slice.call(arguments)));
  			};
  
  		f_nop.prototype = this.prototype;
  		f_bound.prototype = new f_nop();
  
  		return f_bound;
  	};
  }
  
  /**
   * Returns an object that captures the portions of player state relevant to
   * video playback. The result of this function can be passed to
   * restorePlayerSnapshot with a player to return the player to the state it
   * was in when this function was invoked.
   * @param {object} player The videojs player object
   */
  playerUtils.getPlayerSnapshot = function getPlayerSnapshot(player) {
    var tech = player.el().querySelector('.vjs-tech');
  
    var snapshot = {
      ended: player.ended(),
      src: player.currentSrc(),
      currentTime: player.currentTime(),
      type: player.currentType(),
      playing: !player.paused(),
      suppressedTracks: getSuppressedTracks(player)
    };
  
    if (tech) {
      snapshot.nativePoster = tech.poster;
      snapshot.style = tech.getAttribute('style');
    }
    return snapshot;
  
    /**** Local Functions ****/
    function getSuppressedTracks(player) {
      var tracks = player.remoteTextTracks ? player.remoteTextTracks() : [];
  
      if (tracks && utilities.isArray(tracks.tracks_)) {
        tracks = tracks.tracks_;
      }
  
      if (!utilities.isArray(tracks)) {
        tracks = [];
      }
  
      var suppressedTracks = [];
      tracks.forEach(function (track) {
        suppressedTracks.push({
          track: track,
          mode: track.mode
        });
        track.mode = 'disabled';
      });
  
      return suppressedTracks;
    }
  };
  
  /**
   * Attempts to modify the specified player so that its state is equivalent to
   * the state of the snapshot.
   * @param {object} snapshot - the player state to apply
   */
  playerUtils.restorePlayerSnapshot = function restorePlayerSnapshot(player, snapshot) {
    var tech = player.el().querySelector('.vjs-tech');
    var attempts = 20; // the number of remaining attempts to restore the snapshot
  
    if (snapshot.nativePoster) {
      tech.poster = snapshot.nativePoster;
    }
  
    if ('style' in snapshot) {
      // overwrite all css style properties to restore state precisely
      tech.setAttribute('style', snapshot.style || '');
    }
  
    if (hasSrcChanged(player, snapshot)) {
  
      // on ios7, fiddling with textTracks too early will cause safari to crash
      player.one('contentloadedmetadata', restoreTracks);
      player.one('loadedmetadata', restoreTracks);
  
      player.one('canplay', tryToResume);
      ensureCanplayEvtGetsFired();
  
      // if the src changed for ad playback, reset it
      player.src({src: snapshot.src, type: snapshot.type});
  
      // safari requires a call to `load` to pick up a changed source
      player.load().play();
  
    } else {
      restoreTracks();
  
      if (snapshot.playing) {
        player.play();
      }
    }
  
    /*** Local Functions ***/
  
    /**
     * Sometimes firefox does not trigger the 'canplay' evt.
     * This code ensure that it always gets triggered triggered.
     */
    function ensureCanplayEvtGetsFired() {
      var timeoutId = setTimeout(function() {
        player.trigger('canplay');
      }, 1000);
  
      player.one('canplay', function(){
        clearTimeout(timeoutId);
      });
    }
  
    /**
     * Determine whether the player needs to be restored to its state
     * before ad playback began. With a custom ad display or burned-in
     * ads, the content player state hasn't been modified and so no
     * restoration is required
     */
    function hasSrcChanged(player, snapshot) {
      if (player.src()) {
        return player.src() !== snapshot.src;
      }
      // the player was configured through source element children
      return player.currentSrc() !== snapshot.src;
    }
  
    function restoreTracks() {
      var suppressedTracks = snapshot.suppressedTracks;
      suppressedTracks.forEach(function (trackSnapshot) {
        trackSnapshot.track.mode = trackSnapshot.mode;
      });
    }
  
    /**
     * Determine if the video element has loaded enough of the snapshot source
     * to be ready to apply the rest of the state
     */
    function tryToResume() {
  
      // if some period of the video is seekable, resume playback
      // otherwise delay a bit and then check again unless we're out of attempts
  
      if (!playerUtils.isReadyToResume(player) && attempts--) {
        setTimeout(tryToResume, 50);
      } else {
        try {
          if(player.currentTime() !== snapshot.currentTime) {
            if (snapshot.playing) { // if needed restore playing status after seek completes
              player.one('seeked', function() {
                player.play();
              });
            }
            player.currentTime(snapshot.currentTime);
  
          } else if (snapshot.playing) {
            // if needed and no seek has been performed, restore playing status immediately
            player.play();
          }
  
        } catch (e) {
          videojs.log.warn('Failed to resume the content after an advertisement', e);
        }
      }
    }
  };
  
  playerUtils.isReadyToResume = function (player) {
  
    if (player.readyState() > 1) {
      // some browsers and media aren't "seekable".
      // readyState greater than 1 allows for seeking without exceptions
      return true;
    }
  
    if (player.seekable() === undefined) {
      // if the player doesn't expose the seekable time ranges, try to
      // resume playback immediately
      return true;
    }
  
    if (player.seekable().length > 0) {
      // if some period of the video is seekable, resume playback
      return true;
    }
  
    return false;
  };
  
  /**
   * This function prepares the player to display ads.
   * Adding convenience events like the 'vast.firsPlay' that gets fired when the video is first played
   * and ads the blackPoster to the player to prevent content from being displayed before the preroll ad.
   *
   * @param player
   */
  playerUtils.prepareForAds = function (player, hasPrerollAd) {
    var blackPoster = null;
    var _firstPlay = true;
    var volumeSnapshot;
  
    if(hasPrerollAd) {
  	  blackPoster = player.addChild('blackPoster');
    }
  
    monkeyPatchPlayerApi();
  
    player.on('play', tryToTriggerFirstPlay);
    player.on('vast.reset', resetFirstPlay);//Every time we change the sources we reset the first play.
    player.on('vast.firstPlay', restoreContentVolume);
    player.on('error', hideBlackPoster);//If there is an error in the player we remove the blackposter to show the err msg
    player.on('vast.adStart', hideBlackPoster);
    player.on('vast.adsCancel', hideBlackPoster);
    player.on('vast.adError', hideBlackPoster);
    player.on('vast.adStart', addStyles);
    player.on('vast.adEnd', removeStyles);
    player.on('vast.adsCancel', removeStyles);
  
    /*** Local Functions ***/
  
    /**
     What this function does is ugly and horrible and I should think twice before calling myself a good developer. With that said,
     it is the best solution I could find to mute the video until the 'play' event happens (on mobile devices) and the plugin can decide whether
     to play the ad or not.
  
     We also need this monkeypatch to be able to pause and resume an ad using the player's API
  
     If you have a better solution please do tell me.
     */
    function monkeyPatchPlayerApi() {
  
      /**
       * Monkey patch needed to handle firstPlay and resume of playing ad.
       *
       * @param callOrigPlay necessary flag to prevent infinite loop when you are restoring a VAST ad.
       * @returns {player}
       */
      var origPlay = player.play;
      player.play = function (callOrigPlay) {
        var that = this;
  
        if (isFirstPlay()) {
          firstPlay();
        } else {
          resume(callOrigPlay);
        }
  
        return this;
  
        /*** local functions ***/
        function firstPlay() {
          if (!utilities.isIPhone()) {
            volumeSnapshot = saveVolumeSnapshot();
            player.muted(true);
          }
  
          origPlay.apply(that, arguments);
        }
  
        function resume(callOrigPlay) {
          if (isAdPlaying() && !callOrigPlay) {
            player.vast.adUnit.resumeAd();
          } else {
            origPlay.apply(that, arguments);
          }
        }
      };
  
  
      /**
       * Needed monkey patch to handle pause of playing ad.
       *
       * @param callOrigPlay necessary flag to prevent infinite loop when you are pausing a VAST ad.
       * @returns {player}
       */
      var origPause = player.pause;
      player.pause = function (callOrigPause) {
        if (isAdPlaying() && !callOrigPause) {
          player.vast.adUnit.pauseAd();
        } else {
          origPause.apply(this, arguments);
        }
        return this;
      };
  
  
      /**
       * Needed monkey patch to handle paused state of the player when ads are playing.
       *
       * @param callOrigPlay necessary flag to prevent infinite loop when you are pausing a VAST ad.
       * @returns {player}
       */
      var origPaused = player.paused;
      player.paused = function (callOrigPaused) {
        if (isAdPlaying() && !callOrigPaused) {
          return player.vast.adUnit.isPaused();
        }
        return origPaused.apply(this, arguments);
      };
    }
  
    function isAdPlaying() {
      return player.vast && player.vast.adUnit;
    }
  
    function tryToTriggerFirstPlay() {
      if (isFirstPlay()) {
        _firstPlay = false;
        player.trigger('vast.firstPlay');
      }
    }
  
    function resetFirstPlay() {
  	  // midroll 재생시 preroll이 함께 나오는 문제로 인해 이 부분을 주석처리함.
      //_firstPlay = true;
      blackPoster.show();
      restoreContentVolume();
    }
  
    function isFirstPlay() {
      return _firstPlay;
    }
  
    function saveVolumeSnapshot() {
      return {
        muted: player.muted(),
        volume: player.volume()
      };
    }
  
    function restoreContentVolume() {
      if (volumeSnapshot) {
        player.currentTime(0);
        restoreVolumeSnapshot(volumeSnapshot);
        volumeSnapshot = null;
      }
    }
  
    function restoreVolumeSnapshot(snapshot) {
      if (utilities.isObject(snapshot)) {
        player.volume(snapshot.volume);
        player.muted(snapshot.muted);
      }
    }
  
  	function showBlackPoster() {
  		if(blackPoster === null) {
  			blackPoster = player.addChild('blackPoster');
  		} else {
  			if(dom.hasClass(blackPoster.el(), 'vjs-hidden')) {
  				blackPoster.show();
  			}
  		}
  	}
  
    function hideBlackPoster() {
      if (blackPoster !== null && !dom.hasClass(blackPoster.el(), 'vjs-hidden')) {
        blackPoster.hide();
      }
    }
  
    function addStyles() {
      dom.addClass(player.el(), 'vjs-ad-playing');
    }
  
    function removeStyles() {
      dom.removeClass(player.el(), 'vjs-ad-playing');
    }
  
  	return {
  		showBlackPoster: function() {
  			showBlackPoster();
  		},
  		hideBlackPoster: function() {
  			hideBlackPoster();
  		}
  	};
  };
  
  /**
   * Remove the poster attribute from the video element tech, if present. When
   * reusing a video element for multiple videos, the poster image will briefly
   * reappear while the new source loads. Removing the attribute ahead of time
   * prevents the poster from showing up between videos.
   * @param {object} player The videojs player object
   */
  playerUtils.removeNativePoster = function (player) {
  	player.el().querySelector('.vjs-poster').style.backgroundImage = '';
  };
  
  /**
   * Helper function to listen to many events until one of them gets fired, then we
   * execute the handler and unsubscribe all the event listeners;
   *
   * @param player specific player from where to listen for the events
   * @param events array of events
   * @param handler function to execute once one of the events fires
   */
  playerUtils.once = function once(player, events, handler) {
    function listener() {
      handler.apply(null, arguments);
  
      events.forEach(function (event) {
        player.off(event, listener);
      });
    }
  
    events.forEach(function (event) {
      player.on(event, listener);
    });
  };
  
  
  module.exports = playerUtils;
  