( function() {
  'use strict';

  var runtimeData = window.pdtCustomMenuRuntimeData || {};
  var map = runtimeData.linkMap || {};
  var newTabLinks = [];

  function openInNewTabFromMenu( event ) {
    var link = event.currentTarget;
    var url = link.getAttribute( 'data-pdt-target-url' ) || link.getAttribute( 'href' );
    if ( ! url ) {
      return;
    }

    event.preventDefault();
    if ( event.stopImmediatePropagation ) {
      event.stopImmediatePropagation();
    }
    event.stopPropagation();
    window.open( url, '_blank', 'noopener,noreferrer' );
  }

  Object.keys( map ).forEach( function( slug ) {
    var item = map[ slug ] || {};
    var link = document.querySelector( '#toplevel_page_' + slug + ' > a' );

    if ( ! link ) {
      link = document.querySelector( 'a[href$="page=' + slug + '"]' );
    }

    if ( ! link || ! item.url ) {
      return;
    }

    link.setAttribute( 'href', item.url );

    if ( item.new_tab ) {
      link.setAttribute( 'target', '_blank' );
      link.setAttribute( 'rel', 'noopener noreferrer' );
      link.setAttribute( 'data-pdt-new-tab', '1' );
      link.setAttribute( 'data-pdt-target-url', item.url );
      newTabLinks.push( link );
    } else {
      link.removeAttribute( 'target' );
      link.removeAttribute( 'rel' );
      link.removeAttribute( 'data-pdt-new-tab' );
      link.removeAttribute( 'data-pdt-target-url' );
    }
  } );

  for ( var i = 0; i < newTabLinks.length; i++ ) {
    newTabLinks[ i ].addEventListener( 'click', openInNewTabFromMenu, true );
  }
}() );
