//========================================================
// アニメーション
//========================================================
$(function() {
    setTimeout(function() {
        $('.first-view').addClass('is-animation');
    }, 1000);
});

$(window).on('load scroll', function() {
    isAnimation();
});

function isAnimation() {
    $('.js-animation').each(function() {
        var win_scroll = $(window).scrollTop();
        var win_height = $(window).height();
        var scroll_pos = win_scroll + win_height;
        if ($(this).offset().top < scroll_pos) {
            $(this).addClass('is-animation');
        }
    });
}


//========================================================
// modal
//========================================================

// YouTubeのコードを生成
const getYouTubeVideoCode = url => {
  let inicio = url.indexOf('?') + 3,
      final = url.indexOf('&', inicio),
      code = final !== -1 ? url.slice(inicio, final) : url.slice(inicio),
      params = url.slice(final);
  return final !== -1 ? `${code}?${params}&` : `${code}?`;
};

// タグを出力してオブジェクトを作る
const printYouTubeModal = videoCode => {
  let modal = document.createElement('div');
  modal.id = "modalYouTube";
  modal.classList.add('ed-modal');
  modal.innerHTML = `
  <div id="modalOverlay">
  <div class="modalContent">
    <div id="closeModal" class="ed-closeModal"></div>
      <div class="video">
        <iframe src="https://www.youtube.com/embed/${videoCode}autoplay=1" frameborder="0" allowfullscreen> </iframe>
      <div>
  </div>
  </div>`;
  document.body.appendChild(modal);
  closeModal(modal);
};

// モーダルを閉じる場合
const closeModal = modal => {
  document.getElementById('closeModal').addEventListener('click', () => {
    document.body.removeChild(modal);
  });
  document.getElementById('modalOverlay').addEventListener('click', () => {
    document.body.removeChild(modal);
  });  
  window.addEventListener('keyup', e => {
    if (e.key === 'Escape') {
      document.getElementById('closeModal').click();
    }
  });
};

// モーダルを開く
const openYouTubeModal = selector => {
  let linksElements = [...document.querySelectorAll(selector)],
      links = linksElements.map(link => link.href);
  linksElements.forEach((el, i) => {
    el.addEventListener('click', e => {
      e.preventDefault();
      printYouTubeModal(getYouTubeVideoCode(links[i]));
    });
  });
};

openYouTubeModal('.modal-youtube');