new Promise(()=>{
 "use strict";

const F1 = function() {
  const
    ArrS = [
      "/local/nl_watch-nlTree.js",
      "/local/nl_watch-nlMediaInfo.js",
      "/local/nl_watch-nlItab.js",
    ]
    ,ArrC = [
      "/local/nl_watch-nlTree.css",
      "/local/nl_watch-nlMediaInfo.css",
      "/local/nl_watch-nlItab.css",
      "/local/nl_watch.css",
    ]
    ,script = document.createElement('script')
    ,link = document.createElement('link')
    ,fragment = document.createDocumentFragment();
  
  for (let S of ArrS) {
    let clone = script.cloneNode(true);
    clone.setAttribute('charset', 'utf-8');
    clone.setAttribute('type', 'text/javascript');
    clone.setAttribute('src', `//${location.host}${S}`);
    fragment.appendChild(clone);
  }
  for (let C of ArrC) {
    let clone = link.cloneNode(true);
    clone.setAttribute('charset', 'utf-8');
    clone.setAttribute('type', 'text/css');
    clone.setAttribute('rel', 'stylesheet');
    clone.setAttribute('href', `//${location.host}${C}`);
    fragment.appendChild(clone);
  }
  document.body.appendChild(fragment);
  
  window.nl_watch.init();
  //window.WatchJsApi.video.onVideoChanged(window.nl_watch.loadWatchData);
};

window.nl_watch = {
  "apiData": {},
  "environment": {},
  "eventListenerMap": new Set(),

  $XHR(aUrl, aParam) {
    return new Promise((resolve, reject) => {
      var httpObj = new XMLHttpRequest();
      httpObj.open('GET', aUrl, true);
      httpObj.onload = () => resolve((aParam === undefined)? httpObj: [httpObj, aParam]);
      httpObj.onerror = () => reject(httpObj.error);
      httpObj.send();
    });
  },

  init() {
    const observer = new MutationObserver(mutations => {
      for (let mutation of mutations) {
        if (mutation.type !== "attributes") break;
        //console.log(`body: ${mutation.target.getAttribute(mutation.attributeName)}`);
        //console.log(`body: oldValue_${mutation.oldValue}`);
        if (mutation.oldValue.split(' ').includes('is-page-changing')
            && !mutation.target.classList.contains('is-page-changing')) {
          this.loadWatchData();
        }
      };
    });
    
    observer.observe(
      document.body
      ,{attributes:true, attributeOldValue:true, attributeFilter:['class'],}
    );
  },

  loadWatchData() {
    //if (!window.WatchJsApi) return requestAnimationFrame(this.loadWatchData.bind(this));
    
    const
      vid = window.WatchJsApi.video.getVideoID()
      ,loadEventListenerMap = () => {
        const eventListenerMap = window.nl_watch.eventListenerMap;
        if (!eventListenerMap.size) return;
        eventListenerMap.forEach(aValue => Promise.resolve(aValue()));
      }
    
    
    if (!this.apiData.video) {
      console.log(`nl_watch.apiData: none`);
      window.nl_watch.apiData = JSON.parse(document.getElementById('js-initial-watch-data').getAttribute('data-api-data'));
      window.nl_watch.environment = JSON.parse(document.getElementById('js-initial-watch-data').getAttribute('data-environment'));
      loadEventListenerMap();
    } else if (this.apiData.video.id !== vid) {
      const playlistToken = this.environment.playlistToken;
      console.log(`vid: ${vid}, playlistToken: ${playlistToken}`);
      
      window.nl_watch
        .$XHR(`/watch/${vid}?mode=pc_html5&eco=0&playlist_token=${playlistToken}`)
        .then(r => window.nl_watch.apiData = JSON.parse(r.responseText))
        .then(loadEventListenerMap);
    }
  },
};

document.addEventListener("DOMContentLoaded", F1, false);

});