var Wick = Wick || {};
Wick.CheckoutPaymentDetails = (function() {
  var $modal = $('#modal-terms-and-conditions');

  function preparePage() {
    var modalOpened = $(".modal.show").length;
    if (!modalOpened) {
      return;
    }
    var modalContent = $modal.find('.modal-content').clone();
    $modal.modal("hide");
    modalContent.addClass("print-area");
    $("body")
      .addClass("print-mode")
      .append(modalContent);
  }

  function resetPage() {
    var modalPrintModeActive = $("body.print-mode").length;
    if (!modalPrintModeActive) {
      return;
    }
    $("body").removeClass("print-mode");
    $(".print-area").remove();
    $modal.modal("show");
  }

  function init() {
    $(document).on("change", "[name=payment-method]", function() {
      var checked = $(this).val();
      $('[data-paypal]').toggle(checked === 'paypal');
      $('[data-card]').toggle(checked === 'card');
      if (checked === 'paypal') {
        $('.checkout-payment-details__card-details').addClass('checkout-payment-details__card-details_hidden');
        $('.checkout-payment-details__place-order').addClass('checkout-payment-details__place-order_visible');
      } else {
        $('.checkout-payment-details__place-order').removeClass('checkout-payment-details__place-order_visible');
      }
    });

    $('.btn-new-card').on('click', function() {
      $('[data-new-card]').show();
      $('[data-existing-card]').hide();
      return false;
    });

    $('.btn-back-to-existing-card').on('click', function() {
      $('[data-new-card]').hide();
      $('[data-existing-card]').show();
      return false;
    });

    // do not subscribe if no T&C modal on a current page
    if (!$modal.length) {
      return;
    }

    if (typeof(window.onbeforeprint) !== 'undefined') {
      // subscriptions for browsers
      window.onbeforeprint = preparePage;
      window.onafterprint = resetPage;
    } else if (window.matchMedia) {
      // subscriptions for iOS devices
      var mediaQueryList = window.matchMedia('print');
      mediaQueryList.addListener(function(mql) {
        if (mql.matches) {
          preparePage();
        } else {
          resetPage();
        }
      });
    }
  }

  init();
})();
