/*
 * Cookie Overlay JS File
 */

// We assumme that the uoe.js is loaded first, and polyfills for closest.

if (!Element.prototype.matches) {
  Element.prototype.matches = Element.prototype.msMatchesSelector ||
    Element.prototype.webkitMatchesSelector;
}

document.addEventListener('DOMContentLoaded', function () {
  'use strict';

  var iframes = document.getElementsByTagName('IFRAME')
  var i

  for (i = 0; i < iframes.length; i++) {
    if (iframes[i].hasAttribute('data-uoe-cookie-src')) {
      var cookieOverlay = document.createElement('div')
      var style = window.getComputedStyle(iframes[i]);
      var height = iframes[i].offsetHeight;

      var borderWidth = style.getPropertyValue('border-top-width')
      height = height - (borderWidth.indexOf('px') >= 0 ? borderWidth.substring(0, borderWidth.length - 2) : 0)

      borderWidth = style.getPropertyValue('border-bottom-width')
      height = height - (borderWidth.indexOf('px') >= 0 ? borderWidth.substring(0, borderWidth.length - 2) : 0)

      var overlayData = {}
      if (iframes[i].hasAttribute('data-uoe-cookie-link-url')) {
        var url = iframes[i].getAttribute('data-uoe-cookie-link-url')

        if (url !== '') {
          var title
          if (iframes[i].hasAttribute('data-uoe-cookie-link-text')) {
            title = iframes[i].getAttribute('data-uoe-cookie-link-text')
            title = title === '' ? url : title
          }
          else {
            title = url
          }
          overlayData = {
            link: {
              label: title,
              url: url
            }
          }
        }
      }

      cookieOverlay.innerHTML = nunjucks.render('uoe-cookies-overlay.njk', overlayData)
      cookieOverlay.firstChild.setAttribute('style', 'width:' + iframes[i].offsetWidth.toString() + 'px;height:' + height.toString() + 'px' /*style.getPropertyValue('border-top-width')*/)
      iframes[i].parentNode.insertBefore(cookieOverlay.firstChild, iframes[i])
      iframes[i].style.display = 'none'

      var buttons = iframes[i].parentNode.getElementsByTagName('BUTTON')

      for (var j = 0; j < buttons.length; j++) {
        if (buttons[j].matches('.cookie-btn-overlay')) {
          buttons[j].addEventListener('click', function (e) {
            var overlay = e.target.closest('.cookie-overlay')
            var iframe = overlay.nextSibling

            iframe.setAttribute('src', iframe.getAttribute('data-uoe-cookie-src'))
            overlay.style.display = 'none'
            iframe.style.display = ''
          })
        }
      }
    }
  }
});

