(function() {
  var closeDropdownTimeout;

  function closeDropdown(event) {
    var dropdowns = document.querySelectorAll('.dropdown');
    for (var i = 0; i < dropdowns.length; i++) {
      var dropdownMenu = dropdowns[i].querySelector('.dropdown-menu');
      if (dropdownMenu.style.display !== 'none' && !dropdowns[i].contains(event.target)) {
        dropdownMenu.style.display = 'none';
      }
    }

    // remove event listener till we have a new dropdown menu open
    if (document.querySelector('.dropdown-menu:not([style*="display: none"])') === null) {
      document.removeEventListener('click', closeDropdown);
    }
  }

  var dropdowns = document.querySelectorAll('.dropdown');
  for (var i = 0; i < dropdowns.length; i++) {
    var dropdownMenu = dropdowns[i].querySelector('.dropdown-menu');
    dropdownMenu.style.display = 'none'; // ensure menu is initially hidden

    dropdowns[i].addEventListener('click', function(e) {
      // show dropdown menu
      var dropdownMenu = this.querySelector('.dropdown-menu');
      dropdownMenu.style.display = 'block';

      // handle clicking away
      clearTimeout(closeDropdownTimeout);
      closeDropdownTimeout = setTimeout(function() {
        document.addEventListener('click', closeDropdown);
      }, 10);
    });
  }
}());
