if (typeof window.waitEvent == 'function') {
  window.waitEvent('scripts_window', function() {
    window.blockSelectReadonly();
  });
} else {
  if (document.readyState === 'complete') {
    window.blockSelectReadonly();
  } else {
    document.addEventListener('DOMContentLoaded', function() {
      window.blockSelectReadonly();
    });
  }
}

function preventKeydown(e) {
  e.preventDefault();
}

function blockSelect(element) {
  element.classList.add('js-select-readonly');
  element.setAttribute('tabindex', '-1');
  element.setAttribute('aria-disabled', true);

  element.removeEventListener('keydown', preventKeydown, false);
  element.addEventListener('keydown', preventKeydown, false);
}

function unlockSelect(element) {
  element.removeAttribute('tabindex', '-1');
  element.removeAttribute('aria-disabled', true);

  element.removeEventListener('keydown', preventKeydown, false);
  element.classList.remove('js-select-readonly');
}

window.blockSelectReadonly = function(context) {
  context = context || document;
  let blockField = context.querySelectorAll('select[readonly]'),
    unlockField = context.querySelectorAll('select.js-select-readonly:not([readonly])');

  for (let index = 0; index < unlockField.length; index++) {
    unlockSelect(unlockField[index]);
  }

  for (let i = 0; i < blockField.length; i++) {
    blockSelect(blockField[i]);
  }
};
