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

const
  enabledGetDic = false//百科アイコン習得有効化(タグ個数分通信が発生、「TAG」クリック)
  
  ,F1 = () => {
    const
      popThumb = window.popThumb
      ,data = popThumb.data;
    
    if (popThumb.dic) return;
    var dic = {};
    
    var
      _F = tag => {
        if(tag.dic) dic[tag.text] = 1;
      }
      ,F = i => {
        let tags;
        if (!i.indexOf('obj_')) {
          tags = data[i][1].tags;
        } else if(!i.indexOf('im') && !!data[i][3]) {
          tags = data[i][3];
        } else {
          return;
        }
        return Promise
          .all([for(j of tags) new Promise(r => r(j)).then(_F)])
      }
      ,dataKeys = Object.keys(data);
    
    popThumb.dic = {};
    Promise
      .all([for(i of dataKeys) new Promise(r => r(i)).then(F)])
      .then(() => window.popThumb.dic = dic)
  };

new Promise(F1);

window.popThumb.addDic = {
  enabledGetDic: false,
  
  movie(aElem) {
    if(!aElem.firstElementChild.classList.contains('pop_movie')
      || !aElem.getElementsByClassName('popThumb_FA_desc').length) return;
    
    var
      Tag = aElem.getElementsByClassName('popThumb_FA_desc')[0].previousElementSibling
      ,TagItem = (
        '<li class="TagItem">' +
          (this.enabledGetDic?
            Tag.firstElementChild.outerHTML
              .replace('g>', 'g onclick="window.popThumb.addDic.getDic(this);" style="cursor:pointer;">')
            :Tag.firstElementChild.outerHTML) +
          Tag.firstElementChild.nextSibling.textContent +
        '</li>'
      );
    
    const
      popThumb = window.popThumb
      ,data = popThumb.data
      ,id = aElem.id.split('_')[1];
    var TagItems = [];
    
    for (let nobrs = Tag.getElementsByTagName('nobr'), l = nobrs.length; l--;) {
      let 
        nobr = nobrs[l]
        ,tag = nobr.getElementsByTagName('a')[0]
        ,tagText = tag.getAttribute('href').split('/tag/')[1].replace('/', '%2F')
        ,elem = '<span class="TagType' +
          (nobr.getElementsByTagName('span').length? ' TagLock': '') +
          (nobr.getElementsByTagName('img').length? ' TagCategory': '') +
          '"></span>' + tag.outerHTML;
      
      if (data[`obj_${id}`][1].tags[l].dic || popThumb.dic && popThumb.dic[tagText]) {
        elem += `<a href="http://dic.nicovideo.jp/a/${tagText}" class="TagDic" target="_tab"></a>`;
      } else if(data[`obj_${id}`][1].tags[l].dic === 0) {
        elem += `<a href="http://dic.nicovideo.jp/a/${tagText}" class="TagNoDic" target="_tab"></a>`;
      }
      TagItems.unshift(`<li class="TagItem">${elem}</li>`);
    }
    Tag.outerHTML = `<ul class="TagList font12">${TagItem}${TagItems.join('')}</ul>`;
  },
  
  $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();
    });
  },
  
  getDic(E) {
    var
      TagItems = (Array.from(E.parentNode.parentNode.getElementsByClassName('TagItem'))).slice(1)
      ,E3 = E;
    
    while (!(E3.className && (E3.classList.contains('pop_movie') || E3.classList.contains('pop_seiga_im')))) {
      E3 = E3.parentNode;
    }
    
    var
      id = E3.parentNode.id.split('_')[1]
      ,isMovie = E3.classList.contains('pop_movie')? true: false
      ,gD = ([aTagItem, aId]) => {
          let E3 = aTagItem.getElementsByTagName('a');
          if (E3.length != 1) return null; //すでに百科アイコン付きかどうか
          let
            E4 = E3[0]
            ,tagText = E4.getAttribute('href').split('/tag/')[1].replace(/[/]/g, '%2F');
          
          return window.popThumb.addDic
            .$XHR(`/pr_Redirect_api.nicodic.jp/page.exist/json/a/${tagText}`, [aId, E4, tagText])
            .then(([R, [id, elem, tagText]]) => {
              var res = R.responseText - 0;
              
              elem.insertAdjacentHTML("AfterEnd",`<a href="http://dic.nicovideo.jp/a/${tagText}" class="${res? 'TagDic': 'TagNoDic'}" target="_tab"></a>`);
              
              if (res) window.popThumb.dic[tagText] = 1;
              
              return res;
            })
        };
    
    Promise
      .all([for(i of TagItems) new Promise(r => r([i, id])).then(gD)])
      .then(e => {
        if (isMovie){
          for (let l = e.length; l--;) {
            if(e[l] === null) continue;
            window.popThumb.data[`obj_${id}`][1].tags[l].dic = e[l];
          }
        } else {
          for (let l = e.length; l--;) {
            if(e[l] === null) continue;
            window.popThumb.data[id][3][l].dic = e[l];
          }
        }
        window.popThumb.save();
      })
  },
};

popThumb.addPopThumbEventListener("onPopupMakeElementEnd", function(aElement) { window.popThumb.addDic.movie.call(window.popThumb.addDic, aElement)});

window.popThumb.addDic.enabledGetDic = enabledGetDic;

/*---------------------------------------*/
  var link = document.createElement('link');
  link.setAttribute('href', '/local/popThumb_FA-extension_addDic.css');
  link.setAttribute('type', 'text/css');
  link.setAttribute('charset', 'utf-8');
  link.setAttribute('rel', 'stylesheet');
  document.body.appendChild(link);
/*---------------------------------------*/
});

/*-----------------------------------------------------*/

new Promise(()=>{
//im~のポップアップにタグ追加(returnコメントアウトで有効)
////seiga.nicovideo.jp/ajax/illust/tag/list?id=~に取りに行く
return;//

window.popThumb.addDic.seiga = function(elem) {
  if (!elem.firstElementChild.classList.contains('pop_seiga_im')) return;
  
  const
    popThumb = window.popThumb
    ,data = popThumb.data
    ,id = elem.id.split('_')[1]
    ,F = ([R, [id, elem, flg]]) => {
      var
        tags = flg ?R :JSON.parse(R.responseText).tag_list
        ,A = []
        ,TagItem = (
          '<li class="TagItem">' +
            `<strong${this.enabledGetDic?' onclick="window.popThumb.addDic.getDic(this);" style="cursor:pointer;">': '>'}` +
            `TAG:</strong>[ jp:${tags.length} ]` +
          '</li>')
        ,TagItems = [];
      
      for (let i = tags.length; i--;) {
        let
         tag = tags[i]
         ,tagText = flg? tag.text: tag.name;
        TagItems.unshift(
          '<li class="TagItem">' +
            '<span class="TagType' +
              (tag.is_locked? ' TagLock': '') +
              (tag.is_category? ' TagCategory': '') +
            '"></span>'+
            `<a class="Tag" href="http://seiga.nicovideo.jp/tag/${tagText}"`+
              (/(im\d+)/.exec(tagText)?
                ` onMouseOver="return popThumb2('${RegExp.$1}', 0)" onMouseOut="return nd()"`
                :'') +
            `>${tagText}</a>` +
            ((tag.dic || popThumb.dic && popThumb.dic[tagText]) ?
              `<a href="http://dic.nicovideo.jp/a/${tagText}" class="TagDic" target="_tab"></a>`:
            tag.dic === 0?
              `<a href="http://dic.nicovideo.jp/a/${tagText}" class="TagNoDic" target="_tab"></a>`: '') +
          '</li>');
        /**/
        if(!flg){
          A.unshift({
            "text" : tagText,
            "is_locked" : tag.is_locked? 1: 0,
            "is_category" : tag.is_category? 1: 0,
            "dic" : popThumb.dic[tagText]? 1: undefined,
          });
        }
      }
      if(!flg) data[id][3] = A;
      elem.firstElementChild.firstElementChild.insertAdjacentHTML("BeforeEnd", `<ul class="TagList font12">${TagItem}${TagItems.join('')}</ul>`);
    };
  
  if(!data[id][3]){
    this.$XHR(`/pr_Redirect_seiga.nicovideo.jp/ajax/illust/tag/list?id=${id.substring(2)}`, [id, elem, 0]).then(e => F(e))
  }else{
    F([data[id][3], [id, elem, 1]]);
  }
};

popThumb.addPopThumbEventListener("onPopupMakeElementEnd", function(E){ window.popThumb.addDic.seiga.call(window.popThumb.addDic, E)});

});