(function($){
  function disablePlaceOrder(){
    var $btn = $( 'form.checkout #place_order' );
    if(!$btn.length) return;
    $btn.prop('disabled', true).addClass('disabled');
    var orig = $btn.data('orig-text');
    if(!orig){ $btn.data('orig-text', $btn.text()); }
    $btn.text(($btn.data('processing-text') || (window.KNSDD_CheckoutGuard && KNSDD_CheckoutGuard.processingText)) || 'Processing...');
  }
  function enablePlaceOrder(){
    var $btn = $( 'form.checkout #place_order' );
    if(!$btn.length) return;
    $btn.prop('disabled', false).removeClass('disabled');
    var orig = $btn.data('orig-text');
    if(orig){ $btn.text(orig); }
  }

  $(document).on('checkout_place_order', function(){
    disablePlaceOrder();
  });

  // Re-enable on errors returned by AJAX
  $(document.body).on('checkout_error', function(){
    enablePlaceOrder();
  });

  // Also re-enable if fragments refreshed after failure
  $(document.body).on('updated_checkout', function(){
    enablePlaceOrder();
  });

})(jQuery);
