(function () {
  function openPopup(url) {
    var w = 1200;
    var h = 900;
    var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
    var dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;

    var width = window.innerWidth || document.documentElement.clientWidth || screen.width;
    var height = window.innerHeight || document.documentElement.clientHeight || screen.height;

    var left = ((width / 2) - (w / 2)) + dualScreenLeft;
    var top = ((height / 2) - (h / 2)) + dualScreenTop;

    var features = 'scrollbars=yes,resizable=yes,width=' + w + ',height=' + h + ',top=' + top + ',left=' + left;
    var win = window.open(url, 'wpsn_sitekit_setup', features);
    if (win && win.focus) {
      win.focus();
    }
    return win;
  }

  document.addEventListener('click', function (e) {
    var a = e.target && e.target.closest ? e.target.closest('a.wpsn-sk-popup[data-wpsn-popup="1"]') : null;
    if (!a) return;

    // If popup is blocked, the browser will just open the link normally.
    e.preventDefault();

    var url = a.getAttribute('href');
    if (!url) return;

    if (window.WPSN_SiteKit && WPSN_SiteKit.strings && WPSN_SiteKit.strings.opening) {
      a.textContent = WPSN_SiteKit.strings.opening;
      setTimeout(function(){ a.textContent = a.textContent; }, 500);
    }

    var win = openPopup(url);
    if (!win) {
      // Popup blocked → fallback.
      window.location.href = url;
    }
  });
})();
