



(function () {
  var initPayPalIntID,
      minMaxAllowed,
      inCompatibleShippingMethods,
      shippingMethodLandRestrictions,
      paymentMethodRegionRestrictions,
      buttonContainer = 'div#paypal-button-container';
      

      try {
        minMaxAllowed = JSON.parse('{"EUR":{"MaxPriceValue":null,"MinPriceValue":null}}');
      } catch (ex) {
      }
      try {
        inCompatibleShippingMethods = JSON.parse('{}');
        shippingMethodLandRestrictions = JSON.parse('{"24284543":{"DE":1},"24750468":{"DE":1},"24435145":{"AT":1}}');
        
        paymentMethodRegionRestrictions = ['DE'];
        
      } catch (ex) {
      }

  var initPayPal = function() {
    var isOk = 1;

    if (window.paypal) {
      try {
        var FUNDING_SOURCES = [
          
            paypal.FUNDING.PAYPAL,
            paypal.FUNDING.PAYLATER
          
        ];

        FUNDING_SOURCES.forEach(function(fundingSource) {
            var button = paypal.Buttons({
              style: {
                layout: 'vertical',
                color: fundingSource === paypal.FUNDING.PAYPAL || fundingSource === paypal.FUNDING.PAYLATER ? 'gold' : 'white',
                shape: 'rect',
                label: 'checkout',
                height: 55,
              },
              fundingSource: fundingSource,
              createOrder: function (data, actions) {
                return xhrRequest();
              },
              onApprove: function (data, actions) {
                xhrRequestApprove(fundingSource);
              },
              onCancel: function (data, actions) {
                console.log("Customer cancelled the PayPal Checkout Flow");
              },
              onError: function () {
                console.log("An Error occurred as part of the PayPal JS SDK");
              },
              onShippingChange: function(data, actions) {
                var selectedShippingOptionId,
                    shippingAddressCountryCode;

                try {
                  selectedShippingOptionId = data.selected_shipping_option.id;
                  shippingAddressCountryCode = data.shipping_address.country_code;
                } catch (ex) {
                  return actions.resolve();
                }

                if ( paymentMethodRegionRestrictions && ! paymentMethodRegionRestrictions.includes(shippingAddressCountryCode) ) {
                  return actions.reject();
                }

                if ( shippingMethodLandRestrictions && shippingMethodLandRestrictions[selectedShippingOptionId] ) {
                  if ( ! shippingMethodLandRestrictions[selectedShippingOptionId][shippingAddressCountryCode] ) {
                    return actions.reject();
                  }
                }

                return actions.resolve();
              }
            });

            if ( button.isEligible() ) {
              button.render(buttonContainer);
            }
        });

        /*  */
        
        if ( cart ) {
            var elem = document.querySelector(buttonContainer);
            if ( elem ) {
              elem.setAttribute('data-pp-amount', cart.grandTotal.amount);
            }
            paypal.Messages({
              style: {
                layout: 'text',
                logo: {
                  type: 'primary'
                },
                text: {
                  align: 'center'
                }
              },
            }).render(buttonContainer);
        }
        

      } catch (e) {
        isOk = 0;
        console.log(e);
      }
    } else {
      isOk = 0;
    }

    if ( typeof initPayPalIntID == 'number' ) {
      clearInterval(initPayPalIntID);
    }
  },

  xhrRequest = function() {
    return new Promise(function(resolve, reject) {
      if (XMLHttpRequest && cart) {
        var xhr = new XMLHttpRequest(),
          targetUrl = 'https://juwelier-wieser.de/epages/Shop052094.sf?ViewAction=JSONViewResponse&ChangeAction=JSONCreatePayPalPPCPOrder',
          data = {
            'BasketGUID': cart.cartId,
          };

        xhr.open('POST', targetUrl, true);
        xhr.setRequestHeader('Content-Type', 'application/json');

        xhr.addEventListener('load', function () {
          if (xhr.status < 200 || xhr.status >= 300) {
            reject(new Error(xhr.responseText + xhr.statusText));
          } else {
            try {
              var response = JSON.parse(xhr.responseText);

              if (response.success) {
                resolve(response.orderID);
              } else {
                reject(new Error(xhr.responseText + xhr.statusText));
              }
            } catch (e) {
              reject(e);
            }
          }
        });

        xhr.send(JSON.stringify(data));
      }
    })
  },

  xhrRequestApprove = function(fundingSource) {
    if (XMLHttpRequest && cart) {
      var xhr = new XMLHttpRequest(),
        targetUrl = 'https://juwelier-wieser.de/epages/Shop052094.sf?ViewAction=JSONViewResponse&ChangeAction=JSONApprovePayPalPPCPOrder',
        data = {
          'PickupToken': 'ZTAzZmFhMzVjNTJkM2QxMGYyMmI3MTkyMTM1M2IxYTI2NWJkOTExNGRiMzBiMGRiOTdmOGZhZGJjMTRlMDcwMV8xNzE3NDQxMDkw',
          'BasketGUID': cart.cartId,
          'FundingSource': fundingSource,
        };

      xhr.open('POST', targetUrl, true);
      xhr.setRequestHeader('Content-Type', 'application/json');

      xhr.addEventListener('load', function () {
        if (xhr.status < 200 || xhr.status >= 300) {
          console.warn(new Error(xhr.responseText + xhr.statusText));
        } else {
          try {
            var response = JSON.parse(xhr.responseText);

            if (response.success) {
              window.location = response.redirect;
            } else {
              console.warn(new Error(xhr.responseText + xhr.statusText));
            }
          } catch (e) {
            console.log(e);
          }
        }
      });

      xhr.send(JSON.stringify(data));
    }
  };

    var cart,
        script,
        shopLocale,
        ppcpUpdateCart = function (e) {
          var container = document.querySelector(buttonContainer),
              timeout = 500,
              compatibleWithCurrentShipping = 1;

          if ( container ) {
            timeout = 0;
          }

          /*  */
          setTimeout(function(){

            if ( ! container ) {
                container = document.querySelector(buttonContainer);
            }
            var cartHasItems = typeof cart.productLineItems === 'object' && cart.productLineItems.length > 0 ? true : false;

            if ( container && cartHasItems ) {
              /*  */
              var cartCurrencyId = cart.grandTotal.currency;

              container.setAttribute('data-pp-amount', cart.grandTotal.amount);

              /*  */
              if ( cart.shippingLineItem.shippingMethod.name ) {
                  try {
                    var shippingNameEncoded = btoa(encodeURIComponent(cart.shippingLineItem.shippingMethod.name));
                    if ( inCompatibleShippingMethods[shippingNameEncoded] ) {
                      compatibleWithCurrentShipping = 0;
                    }
                  } catch (ex) {
                  }
              }

              var regionCompatible = 1;
              
                var shippingAddress = cart.shippingAddress ? cart.shippingAddress : cart.billingAddress;
                if ( shippingAddress && shippingAddress.country ) {
                  if ( ! paymentMethodRegionRestrictions.includes(shippingAddress.country) ) {
                    regionCompatible = 0;
                  }
                }
              

              if ( ! compatibleWithCurrentShipping ) {
                container.style.display = 'none';
              } else if ( typeof minMaxAllowed === 'object' && minMaxAllowed[cartCurrencyId]['MinPriceValue'] && cart.grandTotal.amount < minMaxAllowed[cartCurrencyId]['MinPriceValue'] ) {
                container.style.display = 'none';
              } else if ( typeof minMaxAllowed === 'object' && minMaxAllowed[cartCurrencyId]['MaxPriceValue'] && cart.grandTotal.amount > minMaxAllowed[cartCurrencyId]['MaxPriceValue'] ) {
                container.style.display = 'none';
              } else if ( ! regionCompatible ) {
                container.style.display = 'none';
              } else {
                container.style.display = '';
              }

              if (window.paypal && e.type === 'cart:view') {
                initPayPal();
              }
            }

          }, timeout);
        };

    /*  */
    
      window.eComEventTarget && document.head.insertAdjacentHTML('beforeend', '<style>div.product-button-container span[id*="zoid-paypal-message"]{margin-top:20px;width:100%;}</style>');
      window.eComEventTarget && window.eComEventTarget.addEventListener('product:view', function(event) {
        var product = event.detail.product,
            productSelector = 'div.product-button-container',
            container = document.querySelector(productSelector),
            timeout = 500;

        if ( container ) {
          timeout = 0;
        }

        /*  */
        setTimeout(function(){
            if ( ! container ) {
              container = document.querySelector(productSelector);
            }

            if ( container ) {
              container.setAttribute('data-pp-amount', product.price.amount);

              paypal.Messages({
                  style: {
                    layout: 'text',
                    logo: {
                      type: 'primary'
                    }
                  },
              }).render(productSelector);
            }

        }, timeout);
      });
    

    window.eComEventTarget && window.eComEventTarget.addEventListener('cart:view', function(event) {
      cart = event.detail.cart;
      shopLocale = event.detail.shopLocale;

      ppcpUpdateCart(event);
    });

    window.eComEventTarget && window.eComEventTarget.addEventListener('cart:update', function(event) {
      cart = event.detail.cart;

      ppcpUpdateCart(event);
    });

    
    
      script = document.createElement('script');
      script.src = 'https://www.paypal.com/sdk/js?integration-date=2022-03-24&client-id=AeMIYlbRBhw76OU_vMidMrVhoNXeZE8wwTzgAr2ULAeDBQWoVM7A8RtEvlpUkUEmkdVYNMCbI-SzOcUQ&currency=EUR&intent=capture&components=buttons,funding-eligibility,messages&enable-funding=paylater&commit=false';
      script.setAttribute("defer", true);
      script.setAttribute('data-partner-attribution-id', 'ePages_Diverse_PPCP');
      document.body.appendChild(script);
    

    
    

    /*  */
    window.eComEventTarget && document.head.insertAdjacentHTML('beforeend', '<style>div#paypal-button-container span[id*="zoid-paypal-message"]{display: block;}</style>');
})();



 