function onFocusAdded(node) {
  if(['input', 'textarea'].indexOf(node.nodeName.toLowerCase()) === -1) {
    return;
  }
  node.parentNode.className += ' active';
}

function onFocusLose(node) {
  if(!node.parentNode) { return; }
  let currentClass = node.parentNode.className;
  node.parentNode.className = currentClass.replace(/\sactive/gi, '').replace(/\sfilled/gi, '');
  if(node.value) {
    node.parentNode.className += ' filled';
  }
}

function syncFields(root) {
  if(!root.querySelectorAll) { return; }
  root.querySelectorAll('input').forEach(elm => onFocusLose(elm));
  root.querySelectorAll('textarea').forEach(elm => onFocusLose(elm));
}

window.addEventListener('focus', e => onFocusAdded(document.activeElement), true);
window.addEventListener('blur', e => onFocusLose(e.target), true);
window.addEventListener('DOMNodeInserted', e => syncFields(e.target), false);
window.addEventListener('DOMContentLoaded', e => syncFields(document), false);

module.exports = {
  syncFields,
  onFocusLose
};
