/*<script>*/
(function(){

	  const applicationServerKey = 'BK2Rb4fc07j8D1fW5BAwcSuhdHpZljVvHUdjwP-0yffjLJ1Z-WT72GRobP5sVMEQgZlf0VrNq-q_3gXNl0gCg3k';
  let isPushEnabled = false;



  
  
  
  function allowDetectChange()
  {
		if ('permissions' in navigator) {
		  navigator.permissions.query({ name: 'notifications' }).then(function (notificationPerm) {
		    notificationPerm.onchange = function () {
		      if (notificationPerm.state == 'granted')
		      {
			      push_updateSubscription();
			    }
		    };
		  });
		}
	}
	
	
	
	
	var hackedOnce = false;
	function allowAskHack()
	{
		document.body.addEventListener("click", function(e){
			if (hackedOnce) return;
			try {
				hackedOnce = true;
				checkNotificationPermission();
				e.preventDefault();
				e.stopPropagation();
			}catch(e){}
		});
		
			}
	
	
	var smartInvitationTimeout;
	function showSmartInvitation()
	{
		smartInvitationTimeout = setTimeout(function(){
			try {
					}catch(e){}
		}, 100);
	}
	
	function hideSmartInvitation()
	{
		clearTimeout(smartInvitationTimeout);
		var d = document.getElementById('smartPushInvitationDiv60d68fe28a20585da890ae23e2181fb9');
		if (d)
		{
			d.parentNode.removeChild(d);
		}
	}


  if (!('serviceWorker' in navigator)) {
    console.warn('Service workers are not supported by this browser');
    return;
  }

  if (!('PushManager' in window)) {
    console.warn('Push notifications are not supported by this browser');
    return;
  }

  if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
    console.warn('Notifications are not supported by this browser');
    return;
  }

  // Check the current Notification permission.
  // If its denied, the button should appears as such, until the user changes the permission manually
  if (Notification.permission === 'denied') {
		allowDetectChange();
    console.warn('Notifications are denied by the user');
    return;
  }


  navigator.serviceWorker.register('/serviceworker.js').then(
    () => {
      console.log('[SW] Service worker has been registered');
      push_updateSubscription();
    },
    e => {
      console.error('[SW] Service worker registration failed', e);
    }
  );
  
  

  function changePushButtonState(state) {
    switch (state) {
      case 'enabled':
        //pushButton.disabled = false;
        //pushButton.textContent = 'Disable Push notifications';
        isPushEnabled = true;
        break;
      case 'disabled':
        //pushButton.disabled = false;
        //pushButton.textContent = 'Enable Push notifications';
        isPushEnabled = false;
        break;
    }
  }

  function urlBase64ToUint8Array(base64String) {
    const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
    const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/');

    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
  }




  function checkNotificationPermission() {
    return new Promise((resolve, reject) => {
      if (Notification.permission === 'denied') {
        return reject(new Error('Push messages are blocked.'));
      }

      if (Notification.permission === 'granted') {
        return resolve();
      }

      if (Notification.permission === 'default') {
	      showSmartInvitation();
	      
        return Notification.requestPermission().then(result => {
	        hideSmartInvitation();
	        
          if (result !== 'granted') {
						
						if (result === 'default') allowAskHack();
						
						allowDetectChange();
            reject(new Error('Bad permission result : ' + result));
          }

          resolve();
        });
      }
    });
  }



  function push_subscribe() {

    return checkNotificationPermission()
      .then(() => navigator.serviceWorker.ready)
      .then(serviceWorkerRegistration =>
        serviceWorkerRegistration.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: urlBase64ToUint8Array(applicationServerKey),
        })
      )
      .then(subscription => {
        // Subscription was successful
        // create subscription on your server
        return push_sendSubscriptionToServer(subscription, 'POST');
      })
      .then(subscription => subscription && changePushButtonState('enabled')) // update your UI
      .catch(e => {
        if (Notification.permission === 'denied') {
          // The user denied the notification permission which
          // means we failed to subscribe and the user will need
          // to manually change the notification permission to
          // subscribe to push messages
          console.warn('Notifications are denied by the user.');
        } else {
          // A problem occurred with the subscription; common reasons
          // include network errors or the user skipped the permission
          console.error('Impossible to subscribe to push notifications', e);
          changePushButtonState('disabled');
        }
      });
  }
  
  
  function equalBuffers (buf1, buf2)
{
    if (buf1.byteLength != buf2.byteLength) return false;
    var dv1 = new Int8Array(buf1);
    var dv2 = new Int8Array(buf2);
    for (var i = 0 ; i != buf1.byteLength ; i++)
    {
        if (dv1[i] != dv2[i]) return false;
    }
    return true;
}


  function push_updateSubscription() {
    navigator.serviceWorker.ready
      .then(serviceWorkerRegistration => serviceWorkerRegistration.pushManager.getSubscription())
      .then(subscription => {
        changePushButtonState('disabled');

        if (!subscription) {
	        push_subscribe();
          // We aren't subscribed to push, so set UI to allow the user to enable push
          return;
        }

				if (!equalBuffers(subscription.options.applicationServerKey, urlBase64ToUint8Array(applicationServerKey)))
				{
					subscription.unsubscribe().then(() => {
						//console.log('push subscribe after push unsubscribe...');
		        push_subscribe();
		      });
		      
          // We aren't subscribed to push, so set UI to allow the user to enable push
          return;
				}

        // Keep your server in sync with the latest endpoint
        return push_sendSubscriptionToServer(subscription, 'PUT');
      })
      .then(subscription => subscription && changePushButtonState('enabled')) // Set your UI to show they have subscribed for push messages
      .catch(e => {
        console.error('Error when updating the subscription', e);
      });
  }

/*
  function push_unsubscribe() {

    // To unsubscribe from push messaging, you need to get the subscription object
    navigator.serviceWorker.ready
      .then(serviceWorkerRegistration => serviceWorkerRegistration.pushManager.getSubscription())
      .then(subscription => {
        // Check that we have a subscription to unsubscribe
        if (!subscription) {
          // No subscription object, so set the state
          // to allow the user to subscribe to push
          changePushButtonState('disabled');
          return;
        }

        // We have a subscription, unsubscribe
        // Remove push subscription from server
        return push_sendSubscriptionToServer(subscription, 'DELETE');
      })
      .then(subscription => subscription.unsubscribe())
      .then(() => changePushButtonState('disabled'))
      .catch(e => {
        // We failed to unsubscribe, this can lead to
        // an unusual state, so  it may be best to remove
        // the users data from your data store and
        // inform the user that you have done so
        console.error('Error when unsubscribing the user', e);
        changePushButtonState('disabled');
      });
  }
*/

	var lastPushedSubscription = false;
	
  function push_sendSubscriptionToServer(subscription, method) {
		  
	  setTimeout(function(){
		  
	    const key = subscription.getKey('p256dh');
	    const token = subscription.getKey('auth');
	    const contentEncoding = (PushManager.supportedContentEncodings || ['aesgcm'])[0];
			
		  
			var fs = document.getElementsByTagName("script")[0];
			var s = document.createElement("script");
			s.type = "text/javascript";
			s.defer = true;
			s.async = true;
			s.src = "https://lb.apicit.net/webpush/?json=" + encodeURIComponent(JSON.stringify({
		      more: {
			      method: method,
			      host: 'www.easytrashmail.com',
			      key: 'UV2BDlMMOXS9M_1733217777_fc4a93d20776688b2533cc3a4c78075ade7befb9'
			    },
	        endpoint: subscription.endpoint,
	        publicKey: key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key))) : null,
	        authToken: token ? btoa(String.fromCharCode.apply(null, new Uint8Array(token))) : null,
	        contentEncoding,
	      }));
			fs.parentNode.insertBefore(s, fs);

		}, 1000);
  }

   
   
  
})();



