1(function($){'use strict';function debugLog(){if(window.CHARITABLE_DEBUG){console.log.apply(console,arguments)}} 2function debugWarn(){if(window.CHARITABLE_DEBUG){console.warn.apply(console,arguments)}} 3function debugError(){if(window.CHARITABLE_DEBUG){console.error.apply(console,arguments)}} 4var CharitableUniversalModal={config:window.CHARITABLE_UNIVERSAL_MODAL||{},isLoading:!1,loadedCss:{},hideCampaignSelector:!1,init:function(){this.bindEvents();this.setupModal();debugLog('[Universal Modal] Initialized successfully')},bindEvents:function(){var self=this;$(document).on('click','.charitable-modal-trigger',function(e){e.preventDefault();var $trigger=$(this);var campaignId=$trigger.data('campaign-id');var modalClass=$trigger.data('modal-class')||'charitable-universal-modal';var amount=$trigger.attr('data-amount');var period=$trigger.attr('data-period')||'once';var campaignName=$trigger.data('campaign-name');var campaignThumbnail=$trigger.data('campaign-thumbnail');var fromShowcase=$trigger.closest('.wp-block-charitable-campaign-showcase').length>0;if(!amount&&$trigger.hasClass('charitable-quick-donate-custom-btn')){amount=$trigger.closest('.campaign-quick-donate--custom').find('.charitable-quick-donate-amount-input').val()} 5self.hideCampaignSelector=!!$trigger.data('hide-campaign-selector');debugLog('[Universal Modal] Trigger clicked - Campaign ID: '+campaignId+', Amount: '+(amount||'none')+', Loading state: '+self.isLoading);if(campaignId){debugLog('[Universal Modal] Opening modal for campaign '+campaignId);self.openModal(campaignId,modalClass,amount,campaignName,campaignThumbnail,fromShowcase,period)}else{debugWarn('[Universal Modal] No campaign ID found on trigger element')}});$(document).on('click','#charitable-universal-modal .modal-close, #lean_overlay',function(e){e.preventDefault();self.closeModal()});$(document).on('keyup',function(e){if(e.key==='Escape'||e.keyCode===27){self.closeModal()}})},setupModal:function(){if($('#lean_overlay').length===0){$('body').append('<div id="lean_overlay"></div>')} 6if($('#charitable-universal-modal').length===0){var modalHtml='<div id="charitable-universal-modal" style="display: none;" class="charitable-modal">'+'<a class="modal-close"></a>'+'<div class="donation-form-wrapper"></div>'+'</div>';$('body').append(modalHtml);debugLog('[Universal Modal] Modal structure created with existing charitable-modal structure')}},openModal:function(campaignId,modalClass,amount,campaignName,campaignThumbnail,fromShowcase,period){var $modal=$('#charitable-universal-modal');var $wrapper=$modal.find('.donation-form-wrapper');var $overlay=$('#lean_overlay');if(this.isLoading){debugLog('[Universal Modal] Already loading, ignoring request');return} 7this.resetModal();this.currentAmount=amount||'';this.currentPeriod=(period&&'once'!==period)?'month':'once';this.currentCampaignName=campaignName||'';if(campaignName){var headerStyle='';var headerClass='charitable-modal-campaign-name';if(campaignThumbnail){headerStyle=' style="background-image: url('+encodeURI(campaignThumbnail)+')"';headerClass+=' has-thumbnail'}else{headerClass+=' no-thumbnail'} 8$wrapper.before('<div class="'+headerClass+'"'+headerStyle+'><span>'+$('<span>').text(campaignName).html()+'</span></div>')} 9this.showLoading($wrapper);$overlay.css({'position':'fixed','z-index':'99999','top':'0px','left':'0px','height':'100%','width':'100%','background':'#000','opacity':'0.5'}).fadeIn(200);$modal.removeClass().addClass('charitable-modal charitable-modal-donation');if(modalClass){$modal.addClass(modalClass)} 10if(fromShowcase){$modal.addClass('charitable-modal-from-showcase')} 11$modal.css({'position':'fixed','top':'100px','left':'50%','transform':'translateX(-50%)','z-index':'100000'}).fadeIn(200);$('body').addClass('charitable-modal-open');this.loadCampaignForm(campaignId,$wrapper)},closeModal:function(){var self=this;var $modal=$('#charitable-universal-modal');var $overlay=$('#lean_overlay');$modal.fadeOut(200);$overlay.fadeOut(200);$('body').removeClass('charitable-modal-open');setTimeout(function(){self.resetModal()},200);debugLog('[Universal Modal] Modal closed with lean-modal behavior')},resetModal:function(){var $modal=$('#charitable-universal-modal');var $wrapper=$modal.find('.donation-form-wrapper');$modal.find('.charitable-modal-campaign-name').remove();$wrapper.empty();$modal.removeClass().addClass('charitable-modal charitable-modal-donation');$modal.removeAttr('style').css('display','none');this.isLoading=!1;this.hideCampaignSelector=!1;this.currentAmount='';this.currentPeriod='';this.currentCampaignName='';debugLog('[Universal Modal] Modal state reset to charitable-modal standards')},showLoading:function($wrapper){var loadingHtml='<div class="charitable-modal-loading">'+'<img src="'+(this.config.loading_gif||'/wp-includes/images/spinner.gif')+'" alt="Loading..." />'+'<p>Loading donation form...</p>'+'</div>';$wrapper.html(loadingHtml);this.isLoading=!0},loadCampaignForm:function(campaignId,$wrapper){var self=this;debugLog('[Universal Modal] AJAX request starting for campaign '+campaignId);$.ajax({type:'POST',url:this.config.ajax_url||(typeof ajaxurl!=='undefined'?ajaxurl:'/wp-admin/admin-ajax.php'),data:{action:'get_donation_form',campaign_id:campaignId,amount:self.currentAmount||'',period:self.currentPeriod||'once'},dataType:'json',xhrFields:{withCredentials:!0},success:function(response){debugLog('[Universal Modal] AJAX success - response.success: '+(response.success?'true':'false'));if(response.success&&response.data){debugLog('[Universal Modal] Response data length: '+response.data.length+' characters');self.replaceForm(response.data,$wrapper,campaignId)}else{debugError('[Universal Modal] AJAX response failed or no data',response);self.showError($wrapper)}},error:function(xhr,status,error){debugError('[Universal Modal] AJAX Error:',error,'Status:',status);debugError('[Universal Modal] XHR Response:',xhr.responseText);self.showError($wrapper)},complete:function(){self.isLoading=!1}})},replaceForm:function(formHtml,$wrapper,campaignId){var self=this;debugLog('[Universal Modal] replaceForm() called for campaign '+campaignId);var inlineStyles=this.extractStyles(formHtml);var safeHtml=this.stripScripts(formHtml);$wrapper[0].innerHTML=safeHtml;debugLog('[Universal Modal] Form HTML replaced in wrapper');var $ajaxVars=$wrapper.find('.charitable-ajax-vars').first();if($ajaxVars.length){window.CHARITABLE_VARS=window.CHARITABLE_VARS||{};var freshMathAnswer=$ajaxVars.attr('data-math-answer');if(typeof freshMathAnswer!=='undefined'&&freshMathAnswer!==''){window.CHARITABLE_VARS.math_answer=parseInt(freshMathAnswer,10);debugLog('[Universal Modal] Refreshed CHARITABLE_VARS.math_answer from AJAX vars: '+window.CHARITABLE_VARS.math_answer)} 12$ajaxVars.remove()} 13if(inlineStyles.length){var $styleContainer=$('<div>');
13inlineStyles.forEach(function(css){$styleContainer.append('<style type="text/css">'+css+'</style>')});$wrapper.prepend($styleContainer.children())} 14this.ensureFormAssets($wrapper);var $newForm=$wrapper.find('#charitable-donation-form, .charitable-donation-form, form[id^="charitable-donation-form"]').first();debugLog('[Universal Modal] Form element found: '+$newForm.length);debugLog('[Universal Modal] CHARITABLE object: '+(typeof CHARITABLE!=='undefined'?'EXISTS':'MISSING'));debugLog('[Universal Modal] Donation_Form class: '+(typeof CHARITABLE!=='undefined'&&typeof CHARITABLE.Donation_Form!=='undefined'?'EXISTS':'MISSING'));if($newForm.length){self.gatewayScopeSeq=(self.gatewayScopeSeq||0)+1;var gatewayScope='modal-'+(campaignId||'0')+'-'+self.gatewayScopeSeq;$newForm.find('input[name="gateway"][id]').each(function(){var $radio=$(this);var oldId=$radio.attr('id');var newId=oldId+'-'+gatewayScope;$newForm.find('label[for="'+oldId+'"]').attr('for',newId);$radio.attr('id',newId)})} 15if($newForm.length&&typeof CHARITABLE!=='undefined'){if(typeof CHARITABLE.Donation_Form!=='undefined'){debugLog('[Universal Modal] Creating new Donation_Form instance');try{var formInstance=new CHARITABLE.Donation_Form($newForm);debugLog('[Universal Modal] Donation_Form instance created successfully',formInstance);var storedInstance=$newForm.data('charitable-donation-form');debugLog('[Universal Modal] Form data stored: '+(storedInstance?'YES':'NO'));if(!storedInstance){debugWarn('[Universal Modal] WARNING: Form instance not stored - storing manually');$newForm.data('charitable-donation-form',formInstance)} 16if(typeof CHARITABLE!=='undefined'&&typeof CHARITABLE.Toggle==='function'){CHARITABLE.Toggle()} 17$('body').trigger('charitable:form:replaced',[formInstance]);debugLog('[Universal Modal] Form initialization complete - matches existing modal behavior');if(self.currentAmount){var amt=parseFloat(self.currentAmount);var $radios=$newForm.find('input[name="donation_amount"]');var matched=!1;$radios.each(function(){if(parseFloat($(this).val())===amt){$(this).prop('checked',!0).trigger('change');matched=!0;debugLog('[Universal Modal] Auto-selected amount: '+amt);return!1}});if(!matched){var $customRadio=$newForm.find('input[name="donation_amount"][value="custom"]');var $customInput=$newForm.find('.custom-donation-input');if($customRadio.length&&$customInput.length){$customRadio.prop('checked',!0).trigger('change');$customInput.val(amt);debugLog('[Universal Modal] Set custom amount: '+amt)}}} 18if(self.currentPeriod&&'once'!==self.currentPeriod){var $recurring=$newForm.find('input[name="recurring_donation"]').filter(function(){return'once'!==$(this).val()}).first();if($recurring.length&&!$recurring.is(':checked')){$recurring.prop('checked',!0).trigger('change');debugLog('[Universal Modal] Auto-selected recurring period: '+self.currentPeriod)}}}catch(e){debugError('[Universal Modal] Error creating Donation_Form instance:',e)}}else{debugWarn('[Universal Modal] CHARITABLE.Donation_Form not available')}}else{debugWarn('[Universal Modal] Form element or CHARITABLE object not found')} 19if($wrapper.find('.charitable-campaign-selector-wrapper').length>0){if(this.hideCampaignSelector){debugLog('[Universal Modal] Hiding campaign selector per trigger override');$wrapper.find('.charitable-campaign-selector-wrapper').hide()}else{debugLog('[Universal Modal] Campaign selector detected - triggering asset loading');$(document).trigger('charitable:campaign:selector:loaded',[$wrapper])}} 20$(document).trigger('charitable:modal:form:loaded',[$wrapper,campaignId])},showError:function($wrapper){var errorHtml='<div class="charitable-modal-error">'+'<p><strong>Error:</strong> Unable to load donation form. Please try again.</p>'+'</div>';$wrapper.html(errorHtml)},stripScripts:function(html){return html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,'')},extractStyles:function(html){var styles=[];var styleRegex=/<style[^>]*>([\s\S]*?)<\/style>/gi;var match;while((match=styleRegex.exec(html))!==null){if(match[1]&&match[1].trim().length>0){styles.push(match[1])}} 21return styles},ensureFormAssets:function($wrapper){var self=this;var $visualForm=$wrapper.find('.charitable-donation-form');if($visualForm.length&&!this.loadedCss['charitable-donation-form']){$(document).trigger('charitable:modal:visual:form:detected',[$wrapper]);this.loadedCss['charitable-donation-form']=!0} 22var $legacyForm=$wrapper.find('#charitable-donation-form');if($legacyForm.length){$(document).trigger('charitable:modal:legacy:form:detected',[$wrapper])}}};$(document).ready(function(){CharitableUniversalModal.init()});window.CharitableUniversalModal=CharitableUniversalModal})(jQuery); 23/*! 24 * accounting.js v0.4.2 25 * Copyright 2014 Open Exchange Rates 26 * 27 * Freely distributable under the MIT license. 28 * Portions of accounting.js are inspired or borrowed from underscore.js 29 * 30 * Full details and documentation: 31 * http://openexchangerates.github.io/accounting.js/ 32 */
33!function(n,r){var e={version:"0.4.1",settings:{currency:{symbol:"$",format:"%s%v",decimal:".",thousand:",",precision:2,grouping:3},number:{precision:0,grouping:3,thousand:",",decimal:"."}}},t=Array.prototype.map,o=Array.isArray,a=Object.prototype.toString;function i(n){return!!(""===n||n&&n.charCodeAt&&n.substr)}function u(n){return o?o(n):"[object Array]"===a.call(n)}function c(n){return n&&"[object Object]"===a.call(n)}function s(n,r){var e;for(e in n=n||{},r=r||{})r.hasOwnProperty(e)&&null==n[e]&&(n[e]=r[e]);return n}function f(n,r,e){var o,a,i=[];if(!n)return i;if(t&&n.map===t)return n.map(r,e);for(o=0,a=n.length;o<a;o++)i[o]=r.call(e,n[o],o,n);return i}function p(n,r){return n=Math.round(Math.abs(n)),isNaN(n)?r:n}function l(n){var r=e.settings.currency.format;return"function"==typeof n&&(n=n()),i(n)&&n.match("%v")?{pos:n,neg:n.replace("-","").replace("%v","-%v"),zero:n}:n&&n.pos&&n.pos.match("%v")?n:i(r)?e.settings.currency.format={pos:r,neg:r.replace("%v","-%v"),zero:r}:r}var m,d=e.unformat=e.parse=function(n,r){if(u(n))return f(n,function(n){return d(n,r)});if("number"==typeof(n=n||0))return n;r=r||e.settings.number.decimal;var t=new RegExp("[^0-9-"+r+"]",["g"]),o=parseFloat((""+n).replace(/\((.*)\)/,"-$1").replace(t,"").replace(r,"."));return isNaN(o)?0:o},g=e.toFixed=function(n,r){r=p(r,e.settings.number.precision);var t=Math.pow(10,r);return(Math.round(e.unformat(n)*t)/t).toFixed(r)},h=e.formatNumber=e.format=function(n,r,t,o){if(u(n))return f(n,function(n){return h(n,r,t,o)});n=d(n);var a=s(c(r)?r:{precision:r,thousand:t,decimal:o},e.settings.number),i=p(a.precision),l=n<0?"-":"",m=parseInt(g(Math.abs(n||0),i),10)+"",y=m.length>3?m.length%3:0;return l+(y?m.substr(0,y)+a.thousand:"")+m.substr(y).replace(/(\d{3})(?=\d)/g,"$1"+a.thousand)+(i?a.decimal+g(Math.abs(n),i).split(".")[1]:"")},y=e.formatMoney=function(n,r,t,o,a,i){if(u(n))return f(n,function(n){return y(n,r,t,o,a,i)});n=d(n);var m=s(c(r)?r:{symbol:r,precision:t,thousand:o,decimal:a,format:i},e.settings.currency),g=l(m.format);return(n>0?g.pos:n<0?g.neg:g.zero).replace("%s",m.symbol).replace("%v",h(Math.abs(n),p(m.precision),m.thousand,m.decimal))};e.formatColumn=function(n,r,t,o,a,m){if(!n)return[];var g=s(c(r)?r:{symbol:r,precision:t,thousand:o,decimal:a,format:m},e.settings.currency),y=l(g.format),b=y.pos.indexOf("%s")<y.pos.indexOf("%v"),v=0;return f(f(n,function(n,r){if(u(n))return e.formatColumn(n,g);var t=((n=d(n))>0?y.pos:n<0?y.neg:y.zero).replace("%s",g.symbol).replace("%v",h(Math.abs(n),p(g.precision),g.thousand,g.decimal));return t.length>v&&(v=t.length),t}),function(n,r){return i(n)&&n.length<v?b?n.replace(g.symbol,g.symbol+new Array(v-n.length+1).join(" ")):new Array(v-n.length+1).join(" ")+n:n})},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=e),exports.accounting=e):"function"==typeof define&&define.amd?define([],function(){return e}):(e.noConflict=(m=n.accounting,function(){return n.accounting=m,e.noConflict=void 0,e}),n.accounting=e)}(this);; 34CHARITABLE=window.CHARITABLE||{};(function(exports,$){var Donation_Form=function(form){this.errors=[];this.pending_processes=[];this.form=form;this.pause_processing=false;this.submit_processing=false;this.current_xhr=null;this.total=0;this.prevent_scroll_to_top=false;var self=this;var $body=$("body");var on_click_terms=function(){self.form.find(".charitable-terms-text").addClass("active");return false};var on_input_custom_amount=function(){var $li=$(this).closest("li");if($li.hasClass("selected")){return}$li.parents(".charitable-donation-form").find(".donation-amount.selected").removeClass("selected");$li.addClass("selected").find("input[name=donation_amount]").prop("checked",true).trigger("change");trigger_amount_change_events()};var trigger_amount_change_events=function(){$body.trigger("charitable:form:amount:changed",self);$body.trigger("charitable:form:total:changed",self)};var on_change_custom_donation_amount=function(){var unformatted=self.unformat_amount($(this).val());if($.trim(unformatted)>0){$(this).val(self.format_amount(unformatted))}trigger_amount_change_events()};var on_select_donation_amount=function(){var $li=$(this).closest("li");if($li.hasClass("selected")){return}$li.parents(".charitable-donation-form").find(".donation-amount.selected").removeClass("selected");$li.addClass("selected").find("[name=donation_amount]").prop("checked",true);if($li.hasClass("custom-donation-amount")){$li.find("input.custom-donation-input").focus()}trigger_amount_change_events()};var on_change_payment_gateway=function(){var selectedGateway=$(this).val();self.hide_inactive_payment_methods();self.show_active_payment_methods(selectedGateway);if(selectedGateway==="square"||selectedGateway==="square_core"){setTimeout(function(){window.dispatchEvent(new Event("resize"))},100)}};var on_click_change_amount_link=function(){$(this).parent().addClass("charitable-hidden");$("#charitable_stripe_express_checkout_field").hide();$(".charitable-payment-divider").hide()};var on_submit=function(event){var helper=event.data.helper;if(helper.form.data("use-ajax")==="1"||helper.form.data("use-ajax")===1){event.preventDefault();event.stopPropagation();event.stopImmediatePropagation()}if(helper.submit_processing){event.preventDefault();event.stopPropagation();event.stopImmediatePropagation();return false}helper.submit_processing=true;helper.show_processing();if(false===helper.validate()){helper.cancel_processing();return false}if(false!==helper.pause_processing){return false}if(1!==helper.form.data("use-ajax")){return true}maybe_process(helper,function(){$body.trigger("charitable:form:process",helper)});return false};var maybe_process=function(helper,callback){if(!helper.waiting()){if(helper.get_errors().length>0){helper.cancel_processing()}else{callback()}return}setTimeout(maybe_process,500,helper,callback)};var process_donation=function(event,helper){var form=helper.form;var data;var processSettings={type:"POST",dataType:"json",url:CHARITABLE_VARS.ajaxurl,timeout:0,xhrFields:{withCredentials:true}};var hasFiles=form.find('input[type="file"]').length>0;if(hasFiles){var formData=new FormData(form[0]);formData.append("action","make_donation");var charitableAction=formData.get("charitable_action");if(charitableAction){formData.append("form_action",charitableAction);formData.delete("charitable_action")}processSettings.data=formData;processSettings.processData=false;processSettings.contentType=false}else{data=helper.get_data();data.action="make_donation";data.form_action=data.charitable_action;delete data.charitable_action;processSettings.data=data}var xhr=$.ajax(processSettings);helper.current_xhr=xhr;xhr.done(function(response){$body.trigger("charitable:form:processed",[response,helper]);if(response.success){$body.trigger("charitable:donation:success",[response,helper]);maybe_process(helper,function(){window.location.href=response.redirect_to})}else{helper.cancel_processing(response.errors);if(response.donation_id){helper.set_donation_id(response.donation_id)}}}).fail(function(response,textStatus,errorThrown){if(window.console&&window.console.log){console.log(response)}helper.cancel_processing([CHARITABLE_VARS.error_unknown])}).always(function(){helper.current_xhr=null});return false};var init=function(){self.form.data("charitable-donation-form",self);self.form.on("click",".donation-amount",on_select_donation_amount);self.form.on("input","input.custom-donation-input",on_input_custom_amount);self.form.on("click",".charitable-terms-link",on_click_terms);self.form.on("blur",".custom-donation-input",on_change_custom_donation_amount);self.ensure_session_amount_selected();
34self.form.find(".donation-amount input:checked").each(function(){$(this).closest("li").addClass("selected")});if(self.get_all_payment_methods().length){self.hide_inactive_payment_methods();var defaultGateway=self.get_payment_method();if(defaultGateway){self.show_active_payment_methods(defaultGateway)}self.form.on("change","#charitable-gateway-selector input[name=gateway]",on_change_payment_gateway);self.form.on("charitable:gateway:changed",function(event,gatewayId){var $radio=self.form.find('input[name=gateway][value="'+gatewayId+'"]');if($radio.length){$radio.prop("checked",true);on_change_payment_gateway.call($radio[0])}})}self.form.on("click",".change-donation",on_click_change_amount_link);self.form.on("submit",{helper:self},on_submit);if(false===CHARITABLE.forms_initialized){$body.on("charitable:form:process",process_donation);$body.trigger("charitable:form:initialize",self);CHARITABLE.forms_initialized=true}$body.trigger("charitable:form:loaded",self)};init()};Donation_Form.prototype.ensure_session_amount_selected=function(){var $sessionAmount=this.form.find(".charitable-your-donation-amount");if($sessionAmount.length){var amountText=$sessionAmount.find("strong").text();var amount=accounting.unformat(amountText,CHARITABLE_VARS.currency_format_decimal_sep);if(amount>0){var $matchingRadio=this.form.find('input[name="donation_amount"][value="'+amount+'"]');if($matchingRadio.length){$matchingRadio.prop("checked",true);$matchingRadio.closest("li").addClass("selected")}else{var $customRadio=this.form.find('input[name="donation_amount"][value="custom"]');var $customInput=this.form.find("input.custom-donation-input");if($customRadio.length&&$customInput.length){$customRadio.prop("checked",true);$customRadio.closest("li").addClass("selected");$customInput.val(amountText)}}}}};Donation_Form.prototype.get_input=function(field){return this.form.find("[name="+field+"]")};Donation_Form.prototype.get_email=function(){return this.form.find("[name=email]").val()};Donation_Form.prototype.is_recurring_donation=function(){var recurring=this.form.find("[name=recurring_donation]:checked, [name=recurring_donation][type=hidden]");return recurring.length&&"once"!==recurring.val()};Donation_Form.prototype.get_suggested_amount=function(){var $recurring_checked=this.form.find("[name=recurring_donation]:checked");var $recurring_hidden=this.form.find("input[type=hidden][name=recurring_donation]");var recurring_donation=$recurring_checked.val()||$recurring_hidden.val()||"once";var value=null;var $checked=null;var debug_enabled=typeof CHARITABLE_VARS!=="undefined"&&CHARITABLE_VARS.debug&&CHARITABLE_VARS.form_debug;if(debug_enabled){console.log("[Charitable Debug] get_suggested_amount() called");console.log("[Charitable Debug] recurring_donation value:",recurring_donation);console.log("[Charitable Debug] $recurring_checked found:",$recurring_checked.length);console.log("[Charitable Debug] $recurring_hidden found:",$recurring_hidden.length,$recurring_hidden.val())}var $session_amount_display=this.form.find(".charitable-your-donation-amount");var is_session_state=$session_amount_display.length>0;if("once"===recurring_donation){if(is_session_state){var $hidden_input=this.form.find("input[type=hidden][name=donation_amount]");if($hidden_input.length>0){var hidden_value=$hidden_input.val();if(hidden_value&&hidden_value!=="custom"&&hidden_value!=="recurring-custom"){value=hidden_value}}}if(!value||value==="custom"||value==="recurring-custom"){var $active_section=this.form.find(".charitable-donation-options.active");if($active_section.length){var $all_in_active=$active_section.find("[name=donation_amount]:checked");$checked=$all_in_active.filter(function(){var $radio=$(this);return"recurring-custom"!==$radio.val()&&!$radio.attr("data-recurring")});if($checked.length>0){value=$checked.first().val()}}if(!value||value==="custom"||value==="recurring-custom"){var $all_checked_radios=this.form.find("[name=donation_amount]:checked");$checked=$all_checked_radios.filter(function(){var $radio=$(this);var $closest_section=$radio.closest(".charitable-donation-options");var is_recurring_section=$closest_section.hasClass("charitable-recurring-donation-options")||$closest_section.hasClass("recurring-donation-options");var is_active_section=$closest_section.hasClass("active");return"recurring-custom"!==$radio.val()&&!$radio.attr("data-recurring")&&(is_active_section||!is_recurring_section)});if($checked.length>0){value=$checked.first().val()}else if(!is_session_state){var $donation_options=this.form.find(".charitable-donation-options");var is_options_hidden=$donation_options.length>0&&$donation_options.hasClass("charitable-hidden");if(is_options_hidden){var $hidden_input_fallback=this.form.find("input[type=hidden][name=donation_amount]");
34if($hidden_input_fallback.length>0){var hidden_value_fallback=$hidden_input_fallback.val();if(hidden_value_fallback&&hidden_value_fallback!=="custom"&&hidden_value_fallback!=="recurring-custom"){value=hidden_value_fallback}}}}}}}else{if(debug_enabled){console.log("[Charitable Debug] In RECURRING branch")}var $all_checked_radios=this.form.find("[name=donation_amount]:checked");if(debug_enabled){console.log("[Charitable Debug] Checked radios found:",$all_checked_radios.length)}if($all_checked_radios.length>0){$checked=$all_checked_radios;value=$checked.first().val();if(debug_enabled){console.log("[Charitable Debug] Using checked radio value:",value)}}else{var $fallback_input=this.form.find("input[type=hidden][name=donation_amount_fallback]");if(debug_enabled){console.log("[Charitable Debug] Fallback input found:",$fallback_input.length)}if($fallback_input.length>0){var fallback_value=$fallback_input.val();if(debug_enabled){console.log("[Charitable Debug] Fallback value:",fallback_value)}if(fallback_value&&fallback_value!=="custom"&&fallback_value!=="recurring-custom"&&parseFloat(fallback_value)>0){value=fallback_value;$checked=$fallback_input;if(debug_enabled){console.log("[Charitable Debug] Using fallback value:",value)}}}if(!value){if(debug_enabled){console.log("[Charitable Debug] No fallback value, checking hidden donation_amount")}var $donation_options=this.form.find(".charitable-donation-options");var is_options_hidden=$donation_options.length>0&&$donation_options.hasClass("charitable-hidden");if(debug_enabled){console.log("[Charitable Debug] Options hidden:",is_options_hidden)}if(is_options_hidden){var $hidden_input=this.form.find("input[type=hidden][name=donation_amount]");if($hidden_input.length>0){var hidden_value=$hidden_input.val();if(hidden_value&&hidden_value!=="custom"&&hidden_value!=="recurring-custom"){value=hidden_value;$checked=$hidden_input}}}}}}if(!value||value==="custom"||value==="recurring-custom"){if(debug_enabled){console.log("[Charitable Debug] No valid value found, returning 0. value was:",value)}return 0}var amount=accounting.unformat(value,CHARITABLE_VARS.currency_format_decimal_sep);if(debug_enabled){console.log("[Charitable Debug] Unformatted amount:",amount,"from value:",value)}if(isNaN(amount)||!isFinite(amount)){if(debug_enabled){console.log("[Charitable Debug] Amount is NaN or not finite, returning 0")}amount=0}if(debug_enabled){console.log("[Charitable Debug] FINAL get_suggested_amount returning:",amount)}return amount||0};Donation_Form.prototype.get_custom_amount=function(){var input=this.form.find(".charitable-donation-options.active input.custom-donation-input,.charitable-donation-options.active input.custom-donation-amount");if(0===input.length){input=this.form.find("input.custom-donation-input")}var $recurring_checked=this.form.find("[name=recurring_donation]:checked");var $recurring_hidden=this.form.find("input[type=hidden][name=recurring_donation]");var recurring_donation=$recurring_checked.val()||$recurring_hidden.val()||"once";if("once"===recurring_donation){input=input.filter(function(){var $input=$(this);return"custom_recurring_donation_amount"!==$input.attr("name")})}var value=input.val();var amount=accounting.unformat(value,CHARITABLE_VARS.currency_format_decimal_sep);if(!(amount>0)&&"once"===recurring_donation){var $session_type=this.form.find('input[type=hidden][name=donation_amount]');if($session_type.length&&"custom"===$session_type.val()){var session_amount=accounting.unformat(this.form.find('input[type=hidden][name=custom_donation_amount]').val(),CHARITABLE_VARS.currency_format_decimal_sep);if(session_amount>0){amount=session_amount}}}return amount};Donation_Form.prototype.get_subtotal=function(){var suggested=this.get_suggested_amount();var custom=this.get_custom_amount();var $custom_radio=this.form.find('[name=donation_amount][value="custom"]:checked');if($custom_radio.length&&custom>0){return custom}var total=suggested||custom;return total||0};Donation_Form.prototype.get_amount=function(){this.total=this.get_subtotal();this.form.trigger("charitable:form:get_amount",this);return this.total};Donation_Form.prototype.add_amount=function(add){this.total+=add};Donation_Form.prototype.remove_amount=function(remove){this.total-=remove};Donation_Form.prototype.get_description=function(){return this.form.find("[name=description]").val()||""};Donation_Form.prototype.get_cc_number=function(){return this.form.find("#charitable_field_cc_number input").val()||""};Donation_Form.prototype.get_cc_cvc=function(){return this.form.find("#charitable_field_cc_cvc input").val()||""};Donation_Form.prototype.get_cc_expiry_month=function(){return this.form.find("#charitable_field_cc_expiration select.month").val()||""};Donation_Form.prototype.get_cc_expiry_year=function(){return this.form.find("#charitable_field_cc_expiration select.year").val()||""};Donation_Form.prototype.clear_cc_fields=function(){this.form.find("#charitable_field_cc_number input, #charitable_field_cc_name input, #charitable_field_cc_cvc input, #charitable_field_cc_expiration select").removeAttr("name")};Donation_Form.prototype.get_payment_method=function(){return this.form.find("[type=hidden][name=gateway], [name=gateway]:checked").val()||""};Donation_Form.prototype.get_all_payment_methods=function(){return this.form.find("#charitable-gateway-selector input[name=gateway]")};Donation_Form.prototype.hide_inactive_payment_methods=function(){var active=this.get_payment_method();var fields=this.form.find(".charitable-gateway-fields[data-gateway!="+active+"]");fields.hide();fields.find("input[required],select[required],textarea[required]").attr("data-required",1).attr("required",fal
34se)};Donation_Form.prototype.show_active_payment_methods=function(active){var active=active||this.get_payment_method();var fields=this.form.find(".charitable-gateway-fields[data-gateway="+active+"]");fields.show();fields.find("[data-required]").attr("required",true)};Donation_Form.prototype.format_amount=function(price,symbol){if(typeof symbol==="undefined")symbol="";return accounting.formatMoney(price,{symbol:symbol,decimal:CHARITABLE_VARS.currency_format_decimal_sep,thousand:CHARITABLE_VARS.currency_format_thousand_sep,precision:CHARITABLE_VARS.currency_format_num_decimals,format:CHARITABLE_VARS.currency_format}).trim()};Donation_Form.prototype.unformat_amount=function(price){return Math.abs(parseFloat(accounting.unformat(price,CHARITABLE_VARS.currency_format_decimal_sep)))};Donation_Form.prototype.add_error=function(message){if(message&&message.trim().length>0){this.errors.push(message)}};Donation_Form.prototype.get_errors=function(){return this.errors};Donation_Form.prototype.get_error_message=function(){return this.errors.join(" ")};Donation_Form.prototype.print_errors=function(errors){var e=errors||this.errors,i=0,count=e.length,output="",error_notice_donation_display=typeof CHARITABLE_VARS.error_notice_donation_display==="undefined"?"top":CHARITABLE_VARS.error_notice_donation_display;e=e.filter(function(error){return error&&error.trim().length>0});count=e.length;if(0===count){return}if(this.form.find(".charitable-form-errors").length){this.form.find(".charitable-form-errors").remove()}output+='<div class="charitable-form-errors charitable-notice"><ul class="errors"><li>';output+=e.join("</li><li>");output+="</li></ul></div>";if(error_notice_donation_display==="bottom"){this.form.append(output)}else{this.form.prepend(output)}};Donation_Form.prototype.clear_errors=function(){this.errors=[];if(this.form.find(".charitable-form-errors").length){this.form.find(".charitable-form-errors").remove()}};Donation_Form.prototype.waiting=function(){return this.pending_processes.length>0};Donation_Form.prototype.add_pending_process=function(process){var index=this.pending_processes.indexOf(process);return-1===index?this.pending_processes.push(process)-1:index};Donation_Form.prototype.remove_pending_process=function(index){this.pending_processes.splice(index,1)};Donation_Form.prototype.remove_pending_process_by_name=function(process){var index=this.pending_processes.indexOf(process);return-1!==index&&this.remove_pending_process(index)};Donation_Form.prototype.show_processing=function(){this.form.find(".charitable-form-processing").show();this.form.find('button[name="donate"]').hide()};Donation_Form.prototype.hide_processing=function(){this.form.find(".charitable-form-processing").hide();this.form.find('button[name="donate"]').show();this.submit_processing=false;this.pause_processing=false;if(this.current_xhr){this.current_xhr.abort();this.current_xhr=null}};Donation_Form.prototype.reset_if_stuck=function(){var $spinner=this.form.find(".charitable-form-processing");var $button=this.form.find('button[name="donate"]');var isStuck=($spinner.is(":visible")||$spinner.css("display")!=="none")&&($button.is(":hidden")||$button.css("display")==="none");if(isStuck){this.hide_processing();return true}return false};Donation_Form.prototype.scroll_to_top=function(){if(this.prevent_scroll_to_top){this.prevent_scroll_to_top=false;return}var $modal=this.form.parents(".charitable-modal");if($modal.length){$modal.scrollTop(0)}else{window.scrollTo(this.form.offset().left,this.form.offset().top)}};Donation_Form.prototype.cancel_processing=function(errors){this.hide_processing();this.print_errors(errors);var error_notice_donation_display=typeof CHARITABLE_VARS.error_notice_donation_display==="undefined"?"top":CHARITABLE_VARS.error_notice_donation_display;if(""===error_notice_donation_display||"top"===error_notice_donation_display){this.scroll_to_top()}this.form.trigger("charitable:form:cancelled",this)};Donation_Form.prototype.set_donation_id=function(donation_id){this.form.find("[name=ID]").val(donation_id)};Donation_Form.prototype.get_data=function(){return this.form.serializeArray().reduce(function(obj,item){if("[]"===item.name.slice(-2)){var name=item.name.slice(0,-2);if(!obj.hasOwnProperty(name)){obj[name]=[]}
34obj[name].push(item.value)}else{obj[item.name]=item.value}return obj},{})};Donation_Form.prototype.get_required_fields=function(){var fields=this.form.find(".charitable-fieldset .required-field").not("#charitable-gateway-fields .required-field"),method=this.get_payment_method();if(""!==method){var gateway_fields=this.form.find("[data-gateway="+method+"] .required-field");if(gateway_fields.length){fields=$.merge(fields,gateway_fields)}}return fields};Donation_Form.prototype.subtotal_exceeds_maximum=function(){var subtotal=this.get_subtotal();var maximum=CHARITABLE_VARS.maximum_donation;if(""===maximum||null===maximum||undefined===maximum){return false}var maximumFloat=parseFloat(maximum);if(isNaN(maximumFloat)||maximumFloat<=0){return false}return subtotal>maximumFloat};Donation_Form.prototype.is_valid_amount=function(){var minimum=parseFloat(CHARITABLE_VARS.minimum_donation);if(this.subtotal_exceeds_maximum()){return false}return minimum>0||CHARITABLE_VARS.permit_0_donation?this.get_subtotal()>=minimum:this.get_subtotal()>minimum};Donation_Form.prototype.validate_amount=function(){var subtotal=this.get_subtotal();var minimum=parseFloat(CHARITABLE_VARS.minimum_donation);var isValid=this.is_valid_amount();if(false===isValid){if(subtotal>0&&this.subtotal_exceeds_maximum()&&CHARITABLE_VARS.error_max_exceeded){this.add_error(CHARITABLE_VARS.error_max_exceeded)}else if(CHARITABLE_VARS.error_invalid_amount){this.add_error(CHARITABLE_VARS.error_invalid_amount)}return false}return true};Donation_Form.prototype.validate_required_fields=function(){var missing_fields=[];var is_visual_form=this.form.hasClass("charitable-visual-donation-form")||this.form.closest(".charitable-visual-donation-form").length>0;this.get_required_fields().each(function(index){var $field=$(this);if(is_visual_form&&!$field.is(":visible")){return true}var $input=$field.find("input, select, textarea");var input_type=$input.attr("type")||"no-type";var input_name=$input.attr("name")||"no-name";var input_value=$input.val()||"";var field_id=$field.attr("id")||"no-id";var field_label="";var $label=$field.find("label");if($label.length>0){field_label=$label.clone().find(".required").remove().end().text().trim()}if($field.find(".iti__tel-input").length>0){var $iti_input=$field.find(".iti__tel-input");$input=$iti_input;input_type=$iti_input.attr("type")||"tel";input_name=$iti_input.attr("name")||"iti-field";input_value=$iti_input.val()||""}var is_empty=false;if(input_type==="radio"&&input_name==="donation_amount"){var checked_radio=$('input[name="donation_amount"]:checked');var checked_value=checked_radio.val()||"";if(checked_radio.length===0||checked_value===""){is_empty=true;missing_fields.push({field_id:field_id,input_name:input_name,input_type:input_type,field_label:field_label||"Donation Amount",category:"donation_amount"})}}else{if(""===input_value){is_empty=true;var category="regular";if(input_type==="email"){category="email"}else if(input_type==="tel"||input_name.indexOf("phone")!==-1){category="phone"}else if(input_name.indexOf("address")!==-1||input_name.indexOf("city")!==-1||input_name.indexOf("state")!==-1||input_name.indexOf("postcode")!==-1){category="address"}else if(is_visual_form&&$field.closest(".charitable-conditional-field").length>0){category="conditional"}missing_fields.push({field_id:field_id,input_name:input_name,input_type:input_type,field_label:field_label||input_name.replace(/_/g," ").replace(/\b\w/g,function(l){return l.toUpperCase()}),category:category})}}});if(missing_fields.length>0){var error_message=this.generate_missing_fields_message(missing_fields);this.add_error(error_message);return false}return true};Donation_Form.prototype.generate_missing_fields_message=function(missing_fields){if(missing_fields.length===0){return CHARITABLE_VARS.error_required_fields}var donation_amount_missing=[];var regular_fields_missing=[];var conditional_fields_missing=[];missing_fields.forEach(function(field){if(field.category==="donation_amount"){donation_amount_missing.push(field)}else if(field.category==="conditional"){conditional_fields_missing.push(field)}else{regular_fields_missing.push(field)}});var message_parts=[];if(donation_amount_missing.length>0){message_parts.push("Please select a donation amount")}if(conditional_fields_missing.length>0){var conditional_labels=conditional_fields_missing.map(function(field){return field.field_label});if(conditional_labels.length===1){message_parts.push("Please complete the required field: "+conditional_labels[0])}else{message_parts.push("Please complete the required fields: "+conditional_labels.join(", "))}}if(regular_fields_missing.length>0){var field_labels=regular_fields_missing.map(function(field){return field.field_label});if(field_labels.length===1){message_parts.push("Please fill out: "+field_labels[0])}else{message_parts.push("Please fill out: "+field_labels.join(", "))}}if(message_parts.length===1){return message_parts[0]+"."}else if(message_parts.length===2){return message_parts.join(" and ")+"."}else{var last_part=message_parts.pop();return message_parts.join(", ")+", and "+last_part+"."}};Donation_Form.prototype.validate=function(){this.clear_errors();this.validate_amount();this.validate_required_fields();this.validate_phone_fields();this.form.trigger("charitable:form:validate",this);return this.errors.length===0};Donation_Form.prototype.validate_phone_fields=function(){var self=this;var isValid=true;this.form.find('input[data-rule-smart-phone-field="true"]').each(function(){if(!CHARITABLE.PhoneField.validateSmart($(this))){isValid=false}});this.form.find('input[data-rule-us-phone-field="true"]').each(function(){if(!CHARITABLE.PhoneField.validateUS($(this))){isValid=false}});if(!isValid){this.add_error("Please correct the phone number errors.")}return isValid};exports.Donation_Form=Donation_Form})(CHARITABLE,jQuery);(function(exports,$){var Toggle=function(){var hide_target=function(){get_target($(this)).addClass("charitable-hidden")};var get_target=function($el){var target=$el.data("charitable-toggle");if(target[0]!=="."&&target[0]!=="#"){target="#"+target}return $(target)};var on_toggle=function(){var $this=$(this),$target=get_target($this);$target.toggleClass("charitable-hidden",function(){if($this.is(":checkbox")){return!$this.is(":checked")}return false===$target.hasClass("charitable-hidden")}());return false};var init=function(){$("[data-charitable-toggle]").each(hide_target)};$("body").on("click","[data-charitable-toggle]",on_toggle);if(exports.content_loading){var timer=setInterval(function(){if(false===exports.content_loading){init();clearInterval(timer)}},500)}return init};exports.Toggle=Toggle()})(CHARITABLE,jQuery);CHARITABLE.VersionCompare=function(version,compare){compare=compare||CHARITABLE_VARS.version;if(typeof version+typeof compare!="stringstring")return false;var a=version.split("."),b=compare.split("."),i=0,len=Math.max(a.length,b.length);for(;i<len;i++){if(a[i]&&!b[i]&&parseInt(a[i])>0||parseInt(a[i])>parseInt(b[i])){return 1}else if(b[i]&&!a[i]&&parseInt(b[i])>0||parseInt(a[i])<parseInt(b[i])){return-1}}return 0};(function(exports,$){CHARITABLE.ResetSuggestedDonations=function(){if($(".charitable-donation-options").length===0){return false}$('ul.donation-amounts input[type="radio"]').each(function(){if($(this).is(":checked")){$(this).closest("li").addClass("selected")}else{$(this).closest("li").removeClass("selected")}});$("input.custom-donation-input").each(function(){var $input=$(this);var $radio=$input.closest(".custom-donation-amount").find('input[type="radio"]');var value=$input.val();if(value&&value.trim()!==""){$radio.prop("checked",true);$radio.closest("li").addClass("selected")}})}})(CHARITABLE,jQuery);(function(exports,$){var CampaignPagination=function(){var self=this;var init=function(){$(document).on("click",".charitable-campaigns-pagination .page-numbers",function(e){if($(this).hasClass("current")){return}e.preventDefault();e.stopPropagation();var $link=$(this);var $container=$link.closest(".charitable-campaigns-shortcode");if($container.hasClass("charitable-loading")){return}$container.addClass("charitable-loading");var shortcodeAtts=$container.data("shortcode-atts");var page=1;if($link.hasClass("next")){var currentPage=parseInt($container.find(".page-numbers.current").text())||1;page=currentPage+1}else if($link.hasClass("prev")){var currentPage=parseInt($container.find(".page-numbers.current").text())||1;page=currentPage-1}else{page=parseInt($link.text())||1}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_load_campaigns_page",nonce:CHARITABLE_VARS.nonce,page:page,shortcode_atts:shortcodeAtts},success:function(response){if(response.success){$container.find(".campaign-loop").html(response.data.campaigns);var $pagination=$(response.data.pagination);$pagination.find("a.page-numbers").each(function(){var $this=$(this);var href=$this.attr("href");var pageNum=href.match(/paged=(\d+)/);if(pageNum){$this.attr("href","#");$this.data("page",pageNum[1])}});$container.find(".charitable-campaigns-pagination").html($pagination);$container.data("current-page",response.data.current_page);$container.find(".page-numbers").removeClass("current");$container.find(".page-numbers").each(function(){var $this=$(this);if($this.text()==response.data.current_page){$this.addClass("current")}})}else{console.error("Error loading campaigns:",response.data.message)}},error:function(xhr,status,error){console.error("AJAX error:",error)},complete:function(){$container.removeClass("charitable-loading")}})})};init()};new CampaignPagination})(window,jQuery);(function(exports,$){var PhoneField={init:function(){this.initSmartFields();this.initUSFields()},initSmartFields:function(){var $smartFields=$('input[data-rule-smart-phone-field="true"]');if($smartFields.length===0){return}if(typeof intlTelInput==="undefined"){var isDebug=function(){return typeof wpchar!=="undefined"&&wpchar.isDebug&&wpchar.isDebug()||window.location.hash&&"#charitabledebug"===window.location.hash};if(isDebug()){if(typeof wpchar!=="undefined"&&wpchar.debug){wpchar.debug("intlTelInput library n
34ot loaded","PhoneField")}else{console.warn("intlTelInput library not loaded")}}return}var utilsScriptUrl=typeof charitable_phone_vars!=="undefined"&&charitable_phone_vars.utils_script_url?charitable_phone_vars.utils_script_url:false;$smartFields.each(function(){var $input=$(this);var initialCountry="us";var $countryField=$("#charitable_field_country_element");if($countryField.length&&$countryField.val()){initialCountry=$countryField.val().toLowerCase()}else if(typeof CHARITABLE_VARS!=="undefined"&&CHARITABLE_VARS.country){initialCountry=CHARITABLE_VARS.country.toLowerCase()}var itiOptions={initialCountry:initialCountry,preferredCountries:["us","ca","gb"],separateDialCode:false};if(utilsScriptUrl){itiOptions.utilsScript=utilsScriptUrl}var iti=intlTelInput($input[0],itiOptions);$input.data("iti",iti)})},initUSFields:function(){var $usFields=$('input[data-rule-us-phone-field="true"]');var isDebug=function(){return typeof wpchar!=="undefined"&&wpchar.isDebug&&wpchar.isDebug()||window.location.hash&&"#charitabledebug"===window.location.hash};if(isDebug()){if(typeof wpchar!=="undefined"&&wpchar.debug){wpchar.debug("[PhoneField] initUSFields called, found fields: "+$usFields.length,"PhoneField")}else{console.log("[PhoneField] initUSFields called, found fields:",$usFields.length)}}if($usFields.length===0){return}if(typeof $.fn.inputmask==="undefined"){if(isDebug()){if(typeof wpchar!=="undefined"&&wpchar.debug){wpchar.debug("[PhoneField] jQuery inputmask library not loaded","PhoneField")}else{console.warn("[PhoneField] jQuery inputmask library not loaded")}}return}if(isDebug()){if(typeof wpchar!=="undefined"&&wpchar.debug){wpchar.debug("[PhoneField] Inputmask library loaded, initializing fields","PhoneField")}else{console.log("[PhoneField] Inputmask library loaded, initializing fields")}}$usFields.each(function(){var $input=$(this);var mask=$input.attr("data-inputmask")||$input.data("inputmask")||"(999) 999-9999";if(isDebug()){if(typeof wpchar!=="undefined"&&wpchar.debug){wpchar.debug("[PhoneField] Initializing inputmask on field: "+$input.attr("id")+" with mask: "+mask,"PhoneField")}else{console.log("[PhoneField] Initializing inputmask on field:",$input.attr("id"),"with mask:",mask)}}if($input[0]&&$input[0].inputmask){if(isDebug()){if(typeof wpchar!=="undefined"&&wpchar.debug){wpchar.debug("[PhoneField] Field already has inputmask instance, skipping","PhoneField")}else{console.log("[PhoneField] Field already has inputmask instance, skipping")}}return}setTimeout(function(){try{if(typeof $.fn.inputmask!=="undefined"){if($input[0]&&$input[0].inputmask){console.log("[PhoneField] Field initialized during delay, skipping");return}$input.removeAttr("data-inputmask");console.log("[PhoneField] Applying mask pattern:",mask);$input.inputmask(mask);console.log("[PhoneField] Inputmask initialized successfully on:",$input.attr("id"))}else{console.error("[PhoneField] Inputmask library not available when trying to initialize")}}catch(e){console.error("[PhoneField] Error initializing inputmask:",e)}},100)})},validateSmart:function($input){var iti=$input.data("iti");if(!iti){return true}if(typeof intlTelInputUtils==="undefined"){return true}var countryCode=iti.getSelectedCountryData().iso2;var isValid=intlTelInputUtils.isValidNumber($input.val(),countryCode);if(!isValid){$input.addClass("charitable-field-error");var errorMsg="Please enter a valid phone number.";if($input.next(".charitable-field-error-message").length===0){$input.after('<span class="charitable-field-error-message">'+errorMsg+"</span>")}return false}else{$input.removeClass("charitable-field-error");$input.next(".charitable-field-error-message").remove();return true}},validateUS:function($input){var value=$input.val().replace(/\D/g,"");var isValid=value.length===10;if(!isValid){$input.addClass("charitable-field-error");var errorMsg="Please enter a valid US phone number (10 digits).";if($input.next(".charitable-field-error-message").length===0){$input.after('<span class="charitable-field-error-message">'+errorMsg+"</span>")}return false}else{$input.removeClass("charitable-field-error");$input.next(".charitable-field-error-message").remove();return true}}};exports.PhoneField=PhoneField})(CHARITABLE,jQuery);(function($){CHARITABLE.forms_initialized=false;CHARITABLE.forms=[];CHARITABLE.reset_stuck_forms=function(){var resetCount=0;
34CHARITABLE.forms.forEach(function(formInstance){if(formInstance&&typeof formInstance.reset_if_stuck==="function"){if(formInstance.reset_if_stuck()){resetCount++}}});$(".charitable-donation-form").each(function(){var $form=$(this);var $spinner=$form.find(".charitable-form-processing");var $button=$form.find('button[name="donate"]');var isStuck=($spinner.is(":visible")||$spinner.css("display")!=="none")&&($button.is(":hidden")||$button.css("display")==="none");if(isStuck){$spinner.hide();$button.show();resetCount++}});return resetCount};$(document).ready(function(){$("html").addClass("js");window.CHARITABLE_FORM_BOOTED=true;var forms=[];$(".charitable-donation-form").each(function(){var formInstance=new CHARITABLE.Donation_Form($(this));forms.push(formInstance);CHARITABLE.forms.push(formInstance)});CHARITABLE.reset_stuck_forms();CHARITABLE.Toggle();CHARITABLE.ResetSuggestedDonations();CHARITABLE.PhoneField.init()});(function(){window.addEventListener("pageshow",function(event){if(event.persisted){setTimeout(function(){CHARITABLE.reset_stuck_forms()},100)}});window.addEventListener("popstate",function(event){setTimeout(function(){CHARITABLE.reset_stuck_forms()},100)});$(document).on("elementor/popup/show",function(){setTimeout(function(){CHARITABLE.reset_stuck_forms()},100)});$(document).on("click",".ue-tab-btn, .r-tabs-anchor, [data-content-id]",function(){setTimeout(function(){CHARITABLE.reset_stuck_forms()},200)})})()})(jQuery);(function($){var GatewayTabHandler=function(){this.initialized=false;this.isModalContext=function(){var $container=$("#charitable-gateway-tabs");if(!$container.length){return false}var donationFormDisplay=typeof CHARITABLE_VARS!=="undefined"&&CHARITABLE_VARS.donation_form_display?CHARITABLE_VARS.donation_form_display:"separate_page";var $modalContainer=$container.closest(".lean-modal, .charitable-modal");if($modalContainer.length>0){return true}var $modalDialog=$container.closest('[role="dialog"]');if($modalDialog.length>0){return true}var currentUrl=window.location.href;if(currentUrl.indexOf("/donate/")!==-1||currentUrl.indexOf("/donate")!==-1){return false}return false};this.init=function(){if(this.initialized){return}this.setupTabs();this.handleOverflow();this.bindEvents();this.setupPaymentMethodErrorDetection();this.initialized=true};this.setupTabs=function(){var $container=$("#charitable-gateway-tabs");if(!$container.length){return}var $tabList=$container.find("#charitable-gateway-selector");var $tabs=$tabList.find(".charitable-gateway-tab");
34if(!$container.find(".charitable-gateway-dropdown-wrapper").length){var $dropdownWrapper=$('<div class="charitable-gateway-dropdown-wrapper" style="display: none;">'+'<button type="button" class="charitable-gateway-dropdown-toggle" aria-expanded="false" aria-label="More payment methods">'+"<span>â¯</span>"+"</button>"+'<ul class="charitable-gateway-dropdown-list" style="display: none;"></ul>'+"</div>");$tabList.after($dropdownWrapper)}};this.handleOverflow=function(){var $container=$("#charitable-gateway-tabs");if(!$container.length){return}var $tabList=$container.find("#charitable-gateway-selector");var $tabs=$tabList.find(".charitable-gateway-tab");var $dropdownWrapper=$container.find(".charitable-gateway-dropdown-wrapper");var $dropdownList=$dropdownWrapper.find(".charitable-gateway-dropdown-list");var dropdownHasTabs=$dropdownList.find(".charitable-gateway-tab").length>0;if(dropdownHasTabs&&$dropdownWrapper.is(":visible")){return}$tabs.each(function(){var $tab=$(this);if($tab.parent().hasClass("charitable-gateway-dropdown-list")){$tabList.append($tab)}});$dropdownWrapper.hide();$dropdownList.hide();var maxVisibleTabs=typeof CHARITABLE_VARS!=="undefined"&&CHARITABLE_VARS.gateway_max_visible_tabs?CHARITABLE_VARS.gateway_max_visible_tabs:4;var isModal=this.isModalContext();var serverModalSetting=typeof CHARITABLE_VARS!=="undefined"&&CHARITABLE_VARS.donation_form_display==="modal";if(isModal&&serverModalSetting){maxVisibleTabs=Math.max(maxVisibleTabs,6)}else if(serverModalSetting&&!isModal){maxVisibleTabs=4}else{}if($tabs.length<=maxVisibleTabs){return}var containerWidth=$tabList.width();if(containerWidth<=10){setTimeout(function(){this.handleOverflow()}.bind(this),100);return}var visibleTabs=[];var overflowTabs=[];$tabs.each(function(index){var $tab=$(this);var tabWidth=$tab.outerWidth(true);var availableWidth=containerWidth-56;var currentWidth=visibleTabs.reduce(function(sum,tab){return sum+tab.width},0);if(visibleTabs.length>=maxVisibleTabs){overflowTabs.push($tab)}else if(currentWidth+tabWidth<=availableWidth){visibleTabs.push({element:$tab,width:tabWidth})}else{overflowTabs.push($tab)}});if(overflowTabs.length>0){if(overflowTabs.length===$tabs.length){var tabsToKeep=Math.min(2,maxVisibleTabs);var tabsToMove=overflowTabs.slice(tabsToKeep);tabsToMove.forEach(function($tab){$dropdownList.append($tab)});if(tabsToMove.length>0){$dropdownWrapper.show()}}else{overflowTabs.forEach(function($tab){$dropdownList.append($tab)});$dropdownWrapper.show()}}else{}};this.bindEvents=function(){var self=this;$(document).on("change",'.charitable-gateway-tab input[type="radio"]',function(){var $radio=$(this);var $tab=$radio.closest(".charitable-gateway-tab");var gatewayId=$radio.val();var $dropdownList=$tab.closest(".charitable-gateway-dropdown-list");var $tabList=$("#charitable-gateway-selector");if($dropdownList.length){var $mainTabs=$tabList.find(".charitable-gateway-tab");var $lastMainTab=$mainTabs.last();$tab.insertAfter($lastMainTab);$dropdownList.append($lastMainTab);$dropdownList.removeClass("show").css("display","none");$dropdownList.parent().find(".charitable-gateway-dropdown-toggle").attr("aria-expanded","false")}$(".charitable-gateway-tab").removeClass("active");$tab.addClass("active");$radio.trigger("charitable:gateway:changed",[gatewayId])});$(document).on("click",".charitable-gateway-dropdown-toggle",function(e){e.preventDefault();var $toggle=$(this);var $dropdownList=$toggle.parent().find(".charitable-gateway-dropdown-list");var isExpanded=$toggle.attr("aria-expanded")==="true";if(isExpanded){$dropdownList.removeClass("show").css("display","none");$toggle.attr("aria-expanded","false")}else{$dropdownList.addClass("show").css("display","block");$toggle.attr("aria-expanded","true")}});$(document).on("click",function(e){if(!$(e.target).closest(".charitable-gateway-dropdown-wrapper").length){$(".charitable-gateway-dropdown-list").hide();$(".charitable-gateway-dropdown-toggle").attr("aria-expanded","false")}});var resizeTimeout;$(window).on("resize",function(){clearTimeout(resizeTimeout);resizeTimeout=setTimeout(function(){self.handleOverflow()},250)});$(document).on("charitable:form:initialize",function(){setTimeout(function(){self.handleOverflow()},100)});$(document).on("leanModal:onOpen",function(){self.handleModalInit()});$(document).on("show.bs.modal shown.bs.modal",function(){self.handleModalInit()});$(document).on("click",'[data-modal], [href*="#modal"], .charitable-modal-trigger',function(){setTimeout(function(){self.handleModalInit()},100)});$(document).on("click",".charitable-donate-button",function(){setTimeout(function(){self.handleModalInit()},100)});$(document).on("charitable:modal:loaded",function(){self.handleModalInit()})};this.refresh=function(){this.handleOverflow()};this.handleModalInit=function(){var $container=$("#charitable-gateway-tabs");if($container.length){var $dropdownWrapper=$container.find(".charitable-gateway-dropdown-wrapper");var $dropdownList=$dropdownWrapper.find(".charitable-gateway-dropdown-list");var $tabList=$container.find("#charitable-gateway-selector");$dropdownList.find(".charitable-gateway-tab").each(function(){$tabList.append($(this))});$dropdownWrapper.hide();$dropdownList.hide()}setTimeout(function(){this.handleOverflow()}.bind(this),400)};this.setupPaymentMethodErrorDetection=function(){var self=this;var errorShown={square_core:false,stripe_ach_direct_debit:false};function isLocalEnvironment(){var hostname=window.location.hostname;var protocol=window.location.protocol;return hostname==="localhost"||hostname==="127.0.0.1"||hostname==="0.0.0.0"||protocol==="file:"||hostname.includes(".local")||hostname.includes(".test")||hostname.includes(".dev")}function isHttpsRequired(){return window.location.protocol!=="https:"&&(window.location.hostname!=="localhost"&&window.location.hostname!=="127.0.0.1")}function checkPaymentMethodAvailability(){var isLocal=isLocalEnvironment();var needsHttps=isHttpsRequired();setTimeout(function(){var $squareContainer=$("#charitable-square-wallet-buttons");var $squareCardContainer=$("#square-card-container");if($squareContainer.length||$squareCardContainer.length){var squareLoaded=$squareContainer.find("button").length>0||$squareCardContainer.find("iframe").length>0||$squareCardContainer.find("div[data-elements-stable-field-name]").length>0;if(!squareLoaded&&!errorShown.square_core){errorShown.square_core=true;self.showPaymentMethodError("square_core",isLocal,needsHttps)}}},2e3);setTimeout(function(){var $achContainer=$("#charitable_stripe_ach_direct_debit_field");var $achGatewayFields=$("#charitable-gateway-fields-stripe_ach_direct_debit");if($achContainer.length){var isGatewayVisible=$achGatewayFields.is(":visible")&&$achGatewayFields.css("display")!=="none";var achLoaded=$achContainer.find("iframe").length>0||$achContainer.find("div[data-elements-stable-field-name]").length>0;var containerHeight=$achContainer.height();var hasHeight=containerHeight>0;var isVisible=$achContainer.is(":visible");var computedDisplay=$achContainer.css("display");var computedVisibility=$achContainer.css("visibility");if(isGatewayVisible){var shouldShowError=false;var errorReason="";if(!achLoaded){shouldShowError=true;errorReason="ACH element not loaded (no iframe found)"}else if(!hasHeight&&!isVisible&&computedDisplay==="none"){shouldShowError=true;errorReason="ACH container hidden and has zero height"}else if(!hasHeight&&isVisible){return}if(shouldShowError&&!errorShown.stripe_ach_direct_debit){errorShown.stripe_ach_direct_debit=true;self.showPaymentMethodError("stripe_ach_direct_debit",isLocal,needsHttps)}}else{}}},3e3)}this.showPaymentMethodError=function(gatewayId,isLocal,needsHttps){var $tab=$('.charitable-gateway-tab[data-gateway-id="'+gatewayId+'"]');var $fields=$("#charitable-gateway-fields-"+gatewayId);if($tab.length&&$fields.length){var errorMessage="";var errorClass="charitable-payment-method-error";if(gatewayId==="square_core"){errorMessage="Square payment is currently unavailable. Please try another payment method."}
34else if(gatewayId==="stripe_ach_direct_debit"){errorMessage="ACH Direct Debit is currently unavailable. Please try another payment method.";$("#charitable_stripe_ach_direct_debit_field").hide()}if(isLocal){errorMessage+="<br><small>Note: This payment method requires HTTPS and may not work in local development environments.</small>";errorClass+=" local-environment"}else if(needsHttps){errorMessage+="<br><small>Note: This payment method requires a secure HTTPS connection.</small>";errorClass+=" https-required"}var $errorDiv=$('<div class="'+errorClass+'">'+errorMessage+"</div>");$fields.prepend($errorDiv);$tab.addClass("payment-method-error");var $dropdownTab=$('.charitable-gateway-dropdown-list .charitable-gateway-tab[data-gateway-id="'+gatewayId+'"]');if($dropdownTab.length){$dropdownTab.addClass("payment-method-error")}}};$(document).on("click",".charitable-gateway-tab",function(){var $tab=$(this);var gatewayId=$tab.data("gateway-id");var $fields=$("#charitable-gateway-fields-"+gatewayId);if($fields.find(".charitable-payment-method-error").length>0){$fields.find(".charitable-payment-method-error").show()}});$(document).on("click",".charitable-gateway-dropdown-list .charitable-gateway-tab",function(){var $tab=$(this);var gatewayId=$tab.data("gateway-id");var $fields=$("#charitable-gateway-fields-"+gatewayId);if($fields.find(".charitable-payment-method-error").length>0){$fields.find(".charitable-payment-method-error").show()}});setTimeout(checkPaymentMethodAvailability,3e3);$(document).on("charitable:form:loaded",function(){setTimeout(checkPaymentMethodAvailability,2e3)});function removeIframeTitles(){$(".charitable-gateway-tab iframe").removeAttr("title");$(".charitable-gateway-tab .StripeElement iframe").removeAttr("title");$(".charitable-gateway-tab #charitable_stripe_ach_direct_debit_field iframe").removeAttr("title")}setInterval(removeIframeTitles,1e3);setInterval(function(){var isLocal=isLocalEnvironment();var needsHttps=isHttpsRequired();var $achContainer=$("#charitable_stripe_ach_direct_debit_field");var $achGatewayFields=$("#charitable-gateway-fields-stripe_ach_direct_debit");if($achContainer.length){var isGatewayVisible=$achGatewayFields.is(":visible")&&$achGatewayFields.css("display")!=="none";if(isGatewayVisible){var containerHeight=$achContainer.height();var hasIframe=$achContainer.find("iframe").length>0;var isVisible=$achContainer.is(":visible");var computedDisplay=$achContainer.css("display");if((containerHeight===0||!hasIframe)&&!errorShown.stripe_ach_direct_debit){if(isVisible===false||computedDisplay==="none"){$achContainer.show();$achContainer[0].offsetHeight;setTimeout(function(){var newHeight=$achContainer.height();var newVisible=$achContainer.is(":visible");if(newHeight===0||!$achContainer.find("iframe").length){errorShown.stripe_ach_direct_debit=true;self.showPaymentMethodError("stripe_ach_direct_debit",isLocal,needsHttps)}},1e3)}else{errorShown.stripe_ach_direct_debit=true;self.showPaymentMethodError("stripe_ach_direct_debit",isLocal,needsHttps)}}}else{}}},5e3);setInterval(function(){var $achContainer=$("#charitable_stripe_ach_direct_debit_field");var $achGatewayFields=$("#charitable-gateway-fields-stripe_ach_direct_debit");if($achContainer.length){var isGatewayVisible=$achGatewayFields.is(":visible")&&$achGatewayFields.css("display")!=="none";if(isGatewayVisible){var isVisible=$achContainer.is(":visible");var computedDisplay=$achContainer.css("display");var hasIframe=$achContainer.find("iframe").length>0;var containerHeight=$achContainer.height();if((!isVisible||computedDisplay==="none")&&hasIframe&&containerHeight>0){$achContainer.show();$achContainer[0].offsetHeight}}else{}}},2e3);function checkACHCSSConflicts(){var $achContainer=$("#charitable_stripe_ach_direct_debit_field");if($achContainer.length){var computedStyles=window.getComputedStyle($achContainer[0]);var $parents=$achContainer.parents();$parents.each(function(index){var $parent=$(this);var parentDisplay=$parent.css("display");var parentVisibility=$parent.css("visibility");var parentOpacity=$parent.css("opacity");if(parentDisplay==="none"||parentVisibility==="hidden"||parentOpacity==="0"){}});var conflictingRules=[];var allStyles=document.styleSheets;for(var i=0;i<allStyles.length;i++){try{var rules=allStyles[i].cssRules||allStyles[i].rules;if(rules){for(var j=0;j<rules.length;j++){var rule=rules[j];if(rule.selectorText&&(rule.selectorText.includes("#charitable_stripe_ach_direct_debit_field")||rule.selectorText.includes(".StripeElement")||rule.selectorText.includes('[id*="ach"]'))){conflictingRules.push({selector:rule.selectorText,display:rule.style.display,visibility:rule.style.visibility,opacity:rule.style.opacity,source:allStyles[i].href||"inline"})}}}}catch(e){continue}}if(conflictingRules.length>0){}}}setTimeout(checkACHCSSConflicts,4e3);function clearACHErrorIfFixed(){var $achContainer=$("#charitable_stripe_ach_direct_debit_field");var $errorMessage=$(".charitable-payment-method-error");var $errorTab=$('.charitable-gateway-tab.payment-method-error[data-gateway-id="stripe_ach_direct_debit"]');
34if($achContainer.length&&$errorMessage.length&&$errorTab.length){var isVisible=$achContainer.is(":visible");var hasIframe=$achContainer.find("iframe").length>0;var containerHeight=$achContainer.height();if(isVisible&&hasIframe&&containerHeight>0){$errorMessage.remove();$errorTab.removeClass("payment-method-error");errorShown.stripe_ach_direct_debit=false}}}setInterval(clearACHErrorIfFixed,3e3);function clearACHErrorOnSelection(){var $achGatewayFields=$("#charitable-gateway-fields-stripe_ach_direct_debit");var $errorMessage=$(".charitable-payment-method-error");var $errorTab=$('.charitable-gateway-tab.payment-method-error[data-gateway-id="stripe_ach_direct_debit"]');if($achGatewayFields.is(":visible")&&$achGatewayFields.css("display")!=="none"){if($errorMessage.length&&$errorTab.length){$errorMessage.remove();$errorTab.removeClass("payment-method-error");errorShown.stripe_ach_direct_debit=false}}}setInterval(clearACHErrorOnSelection,1e3);$(document).on("click",'.charitable-gateway-tab[data-gateway-id="stripe_ach_direct_debit"]',function(){setTimeout(function(){clearACHErrorOnSelection()},100)});function setupACHContainerWatcher(){var $achContainer=$("#charitable_stripe_ach_direct_debit_field");if($achContainer.length){var observer=new MutationObserver(function(mutations){mutations.forEach(function(mutation){if(mutation.type==="attributes"&&mutation.attributeName==="style"){var $target=$(mutation.target);var isVisible=$target.is(":visible");var computedDisplay=$target.css("display");if(!isVisible||computedDisplay==="none"){var hasIframe=$target.find("iframe").length>0;if(hasIframe){$target.show();$target[0].offsetHeight}}}})});observer.observe($achContainer[0],{attributes:true,attributeFilter:["style","class"]})}}setTimeout(setupACHContainerWatcher,5e3);function handleACHCSSEffects(){var $achContainer=$("#charitable_stripe_ach_direct_debit_field");var $achGatewayFields=$("#charitable-gateway-fields-stripe_ach_direct_debit");if($achContainer.length){var isGatewayVisible=$achGatewayFields.is(":visible")&&$achGatewayFields.css("display")!=="none";if(isGatewayVisible){var computedStyles=window.getComputedStyle($achContainer[0]);var transition=computedStyles.transition;var animation=computedStyles.animation;var opacity=computedStyles.opacity;var transform=computedStyles.transform;if(transition!=="none"||animation!=="none"){$achContainer.css({opacity:"1",visibility:"visible"});$achContainer.addClass("ach-transition-protected")}if(opacity==="0"||transform.includes("scale(0)")||transform.includes("translateY(-100%)")){$achContainer.css({opacity:"1",transform:"none"})}}else{}}}setInterval(handleACHCSSEffects,4e3)}};function initMiniWidgetRedirectParams(){var urlParams=new URLSearchParams(window.location.search);var amount=urlParams.get("amount");var period=urlParams.get("period");if(!amount&&!period){return}var $form=$("#charitable-donation-form, .charitable-donation-form").first();if(!$form.length){return}if(amount){var numAmount=parseFloat(amount);if(numAmount>0){var $preset=$form.find('input[type="radio"][name="donation_amount"]').filter(function(){return parseFloat(this.value)===numAmount});if($preset.length){if(!$preset.is(":checked")){$preset.prop("checked",true).trigger("change")}else{$preset.trigger("change")}}else{var $custom=$form.find('#donation-amount-custom, input[name="custom_donation_amount"]').first();if($custom.length){var $otherRadio=$form.find('input[type="radio"][value="custom"]').first();if($otherRadio.length&&!$otherRadio.is(":checked")){$otherRadio.prop("checked",true).trigger("change")}$custom.val(numAmount).trigger("input")}}}}if(period&&"once"!==period){var $recurringRadio=$form.find('input[name="recurring_donation"]').filter(function(){return"once"!==this.value}).first();if($recurringRadio.length&&!$recurringRadio.is(":checked")){$recurringRadio.prop("checked",true).trigger("change")}}}$(document).ready(function(){CHARITABLE.GatewayTabs=new GatewayTabHandler;CHARITABLE.GatewayTabs.init();initMiniWidgetRedirectParams();setInterval(function(){if(CHARITABLE.GatewayTabs&&CHARITABLE.GatewayTabs.isModalContext()){var $container=$("#charitable-gateway-tabs");if($container.length&&$container.find(".charitable-gateway-dropdown-wrapper").is(":visible")){var $dropdownList=$container.find(".charitable-gateway-dropdown-list");var $tabList=$container.find("#charitable-gateway-selector");if($dropdownList.find(".charitable-gateway-tab").length===$tabList.find(".charitable-gateway-tab").length+$dropdownList.find(".charitable-gateway-tab").length){CHARITABLE.GatewayTabs.handleModalInit()}}}},2e3)});$(document).on("charitable:form:loaded",function(){if(CHARITABLE.GatewayTabs){CHARITABLE.GatewayTabs.init()}})})(jQuery);; 35(function(window,document){"use strict";if(window.CharitableGatewayGuard){return}var beaconSent=false;function getDonorMessage(){if(window.CHARITABLE_VARS&&window.CHARITABLE_VARS.gateway_sdk_error_message){return window.CHARITABLE_VARS.gateway_sdk_error_message}return"We cannot process your donation right now. Please try again soon or contact us for assistance."}function showDonorError(formSel){var forms=document.querySelectorAll(formSel);if(!forms.length){forms=document.querySelectorAll(".charitable-donation-form, [data-charitable-form]")}Array.prototype.forEach.call(forms,function(form){if(form.dataset.charitableSdkGuardActive==="true"){return}form.dataset.charitableSdkGuardActive="true";var submits=form.querySelectorAll('input[type="submit"], button[type="submit"], .donate-button, .charitable-button[type="submit"]');
35Array.prototype.forEach.call(submits,function(btn){btn.disabled=true;btn.setAttribute("aria-disabled","true")});var notice=document.createElement("div");notice.className="charitable-notice charitable-form-errors";notice.setAttribute("role","alert");notice.style.marginBottom="1em";notice.textContent=getDonorMessage();form.insertBefore(notice,form.firstChild);if(typeof notice.scrollIntoView==="function"){notice.scrollIntoView({behavior:"smooth",block:"center"})}})}function sendBeacon(gateway,missingGlobal){if(beaconSent){return}beaconSent=true;if(!window.CHARITABLE_VARS||!window.CHARITABLE_VARS.ajaxurl||!window.CHARITABLE_VARS.gateway_sdk_beacon_nonce){return}var payload=new FormData;payload.append("action","charitable_log_gateway_sdk_failure");payload.append("_wpnonce",window.CHARITABLE_VARS.gateway_sdk_beacon_nonce);payload.append("gateway",gateway);payload.append("missing_global",missingGlobal);payload.append("page_url",window.location.href);var url=window.CHARITABLE_VARS.ajaxurl;try{if(navigator.sendBeacon){navigator.sendBeacon(url,payload);return}}catch(e){}try{if(window.fetch){window.fetch(url,{method:"POST",body:payload,credentials:"same-origin",keepalive:true}).catch(function(){});return}}catch(e){}try{var xhr=new XMLHttpRequest;xhr.open("POST",url,true);xhr.send(payload)}catch(e){}}function requireGlobal(opts){if(!opts||typeof opts!=="object"){return}var gateway=opts.gateway||"";var globalName=opts.global||"";var formSel=opts.formSel||"#charitable-donation-form, .charitable-donation-form, [data-charitable-form]";var run=typeof opts.run==="function"?opts.run:null;if(!gateway||!globalName||!run){return}if(typeof window[globalName]!=="undefined"&&window[globalName]!==null){try{run()}catch(runError){if(window.console&&window.console.error){window.console.error("[Charitable] Gateway init failed:",runError)}}return}if(window.console&&window.console.warn){window.console.warn('[Charitable] Required global "'+globalName+'" is not defined for gateway "'+gateway+'". '+"This is usually caused by a caching, JavaScript optimization, or consent plugin "+"blocking or stripping the payment processor script. "+"See https://wpcharitable.com/documentation/")}showDonorError(formSel);sendBeacon(gateway,globalName)}function notifyFailure(gateway,missingGlobal,formSel){if(!gateway||!missingGlobal){return}formSel=formSel||"#charitable-donation-form, .charitable-donation-form, [data-charitable-form]";showDonorError(formSel);sendBeacon(gateway,missingGlobal)}window.CharitableGatewayGuard={requireGlobal:requireGlobal,notifyFailure:notifyFailure,_showDonorError:showDonorError,_sendBeacon:sendBeacon}})(window,document);; 36(function($){if(typeof wpchar==="undefined"){var wpchar={debug:function(msg,type=""){if(!wpchar.isDebug()){return}if(type){type="("+type+")"}console.log("%cCharitable Debug: "+type,"color: #cd6622;",msg)},isDebug:function(){return window.location.hash&&"#charitabledebug"===window.location.hash}}}const style=document.createElement("style");style.textContent=`\n\t\t.charitable-stripe-overlay {\n\t\t\tposition: fixed;\n\t\t\ttop: 0;\n\t\t\tleft: 0;\n\t\t\twidth: 100%;\n\t\t\theight: 100%;\n\t\t\tbackground: rgba(255, 255, 255, 0.5);\n\t\t\tdisplay: flex;\n\t\t\tjustify-content: center;\n\t\t\talign-items: center;\n\t\t\tz-index: 9999;\n\t\t}\n\t\t.charitable-stripe-spinner {\n\t\t\twidth: 50px;\n\t\t\theight: 50px;\n\t\t\tborder: 5px solid #f3f3f3;\n\t\t\tborder-top: 5px solid #3498db;\n\t\t\tborder-radius: 50%;\n\t\t\tanimation: spin 1s linear infinite;\n\t\t}\n\t\t@keyframes spin {\n\t\t\t0% { transform: rotate(0deg); }\n\t\t\t100% { transform: rotate(360deg); }\n\t\t}\n\t`;document.head.appendChild(style);var $body=$("body");var stripe;var stripeElementInstances={card_element:null,expressCheckoutElement:null,ach_direct_debit_payment_element:null,sepa_direct_debit_payment_element:null,becs_debit_payment_element:null,cash_app_payment_element:null,canadian_debit_payment_element:null};var get_stripe_connect_charge_owner=function(helper){var owner=helper.get_input("connect_charge_owner");return owner.length?owner.val():null};var get_stripe_connected_account=function(helper){var account=helper.get_input("connected_account");return account.length?account.val():null};var should_process_payment_on_connected_account=function(helper){return"direct"===get_stripe_connect_charge_owner(helper)||"platform"===get_stripe_connect_charge_owner(helper)&&helper.is_recurring_donation()};var get_stripe_options=function(helper,force){return"direct"===get_stripe_connect_charge_owner(helper)||force?{stripeAccount:get_stripe_connected_account(helper)}:null};var get_stripe_destination=function(helper){return"platform"===get_stripe_connect_charge_owner(helper)?get_stripe_connected_account(helper):null};var Checkout_Handler=function(){stripe=Stripe(CHARITABLE_STRIPE_VARS.key);$body.on("charitable:form:processed",function(event,response,helper){if(!response.success){return}if("make_donation"!==helper.get_input("charitable_action").val()){return}if("stripe"!==helper.get_payment_method()){return}event.preventDefault();helper.add_pending_process("stripe");var formData=helper.get_data();sessionStorage.setItem("charitable_donation_data",JSON.stringify({donation_id:response.donation_id,form_data:formData}));if(should_process_payment_on_connected_account(helper)){new_stripe=Stripe(CHARITABLE_STRIPE_VARS.key,get_stripe_options(helper,true))}else{new_stripe=stripe}new_stripe.redirectToCheckout({sessionId:response.session_id}).then(function(result){if(result.error){helper.add_error(result.error.message);helper.remove_pending_process_by_name("stripe")}})});if(window.location.search.indexOf("payment_intent=")!==-1){var urlParam
36s=new URLSearchParams(window.location.search);var paymentIntent=urlParams.get("payment_intent");var storedData=JSON.parse(sessionStorage.getItem("charitable_donation_data")||"{}");if(paymentIntent&&storedData.donation_id){$.ajax({url:CHARITABLE_STRIPE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_express_checkout_confirmation",payment_intent:paymentIntent,donation_id:storedData.donation_id},success:function(response){if(response.success){sessionStorage.removeItem("charitable_donation_data");window.location.href=response.data.redirect_url}else{alert(response.data.message||"Payment confirmation failed")}},error:function(){alert("Error confirming payment")}})}}};function convertAmountToCents(amount,currency){var zeroDecimalCurrencies=["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"];var currentCurrency=currency||CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency.toUpperCase();var numAmount=parseFloat(amount)||0;if(zeroDecimalCurrencies.indexOf(currentCurrency)!==-1){return Math.abs(Math.round(numAmount))}var amountStr=numAmount.toString();var parts=amountStr.split(".");if(parts.length===1){return Math.abs(parseInt(parts[0])*100)}else{var wholePart=parts[0];var decimalPart=parts[1];while(decimalPart.length<2){decimalPart+="0"}decimalPart=decimalPart.substring(0,2);var cents=parseInt(wholePart)*100+parseInt(decimalPart);return Math.abs(cents)}}function Payment_Intents_Handler(helper){if(!document.getElementById("charitable_stripe_card_field")){return}var resolveVisibleField=function(id){var nodes=document.querySelectorAll("#"+id);for(var i=0;i<nodes.length;i++){if(nodes[i].offsetParent!==null){return nodes[i]}}return nodes[0]||null};stripe=Stripe(CHARITABLE_STRIPE_VARS.key);var processingFlag=false;var elements=stripe.elements();var $card=$("#charitable_stripe_card_field");var $errors=$("#charitable_stripe_card_errors");var $card_name=$(".charitable-donation-form [data-input=cc_name]");var $postcode=$(".charitable-donation-form [name=postcode]");wpchar.debug("Payment_Intents_Handler initialized","stripe");wpchar.debug(CHARITABLE_STRIPE_VARS,"stripe");$(".charitable-payment-divider").hide();amount=helper.get_amount();wpchar.debug("starting amount: "+amount,"stripe");if(amount===0){amount=$("form#charitable-donation-form").find(".charitable-your-donation-amount").find("p strong").text();wpchar.debug("starting amount2: "+amount,"stripe");if(amount===""){const firstSuggestedAmount=$('.donation-amounts.has-suggested-amounts .suggested-donation-amount input[type="radio"]').first();if(firstSuggestedAmount.length){firstSuggestedAmount.prop("checked",true);firstSuggestedAmount.trigger("click");amount=firstSuggestedAmount.val();amount=convertAmountToCents(amount)}else{const customAmountInput=$('input[name="custom_donation_amount"]');const expressCheckoutEnabled=typeof CHARITABLE_STRIPE_VARS.enable_express_checkout!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_express_checkout&&parseInt(CHARITABLE_STRIPE_VARS.enable_express_checkout)!==0;wpchar.debug(customAmountInput,"stripe");wpchar.debug(CHARITABLE_STRIPE_VARS.default_amount,"stripe");if(expressCheckoutEnabled&&customAmountInput.length&&CHARITABLE_STRIPE_VARS.default_amount){customAmountInput.val(CHARITABLE_STRIPE_VARS.default_amount);amount=convertAmountToCents(CHARITABLE_STRIPE_VARS.default_amount)}}}else{amount=amount.replace(/[^0-9.]/g,"");amount=convertAmountToCents(amount)}}else{amount=convertAmountToCents(amount)}wpchar.debug("starting amount10: "+amount,"stripe");var isValidAmount=(typeof amount==="number"||typeof amount==="string")&&!isNaN(parseFloat(amount))&&parseFloat(amount)>0;if(!isValidAmount){if(typeof CHARITABLE_STRIPE_VARS.enable_express_checkout!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_express_checkout&&parseInt(CHARITABLE_STRIPE_VARS.enable_express_checkout)!==0){wpchar.debug("Charitable Note: Payment_Intents_Handler has an invalid amount: "+amount,"stripe")}}if(isValidAmount){const options={mode:"payment",amount:amount,currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"usd"};var elements=stripe.elements(options)}else{var elements=stripe.elements()}cleanupStripeElements();var card_element=elements.create("card");stripeElementInstances.card_element=card_element;let expressCheckoutElement=null;var ach_direct_debit_elements=null,cash_app_elements=null,sepa_direct_debit_elements=null,becs_debit_elements=null;var ach_direct_debit_element=$("#charitable_stripe_ach_direct_debit_field"),ach_direct_debit_payment_element_options={fields:{billingDetails:{name:"never",email:"never"}}},ach_direct_debit_payment_element=false,ach_direct_debit_options={mode:"payment",amount:amount,currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"usd",paymentMethodTypes:["us_bank_account"]};if(typeof CHARITABLE_STRIPE_VARS.enable_ach_direct_debit!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_ach_direct_debit&&CHARITABLE_STRIPE_VARS.enable_ach_direct_debit!==""&&CHARITABLE_STRIPE_VARS.enable_ach_direct_debit!=="0"&&isValidAmount){wpchar.debug("ACH Direct Debit enabled: "+CHARITABLE_STRIPE_VARS.enable_ach_direct_debit,"stripe");wpchar.debug(ach_direct_debit_options,"stripe");setTimeout(function(){if(ach_direct_debit_element.length){wpchar.debug(ach_direct_debit_element,"stripe");wpchar.debug("ACH container before mounting:","stripe");wpchar.debug({display:ach_direct_debit_element.css("display"),visibility:ach_direct_debit_element.css("visibility"),height:ach_direct_debit_element.height(),isVisible:ach_direct_debit_element.is(":visible"),style:ac
36h_direct_debit_element.attr("style")},"stripe");try{ach_direct_debit_elements=stripe.elements(ach_direct_debit_options);wpchar.debug("Stripe elements created successfully","stripe");ach_direct_debit_payment_element=ach_direct_debit_elements.create("payment",ach_direct_debit_payment_element_options);stripeElementInstances.ach_direct_debit_payment_element=ach_direct_debit_payment_element;wpchar.debug("ACH payment element created successfully","stripe");ach_direct_debit_payment_element.mount(resolveVisibleField("charitable_stripe_ach_direct_debit_field"));wpchar.debug("ACH Direct Debit element mounted successfully","stripe");setTimeout(function(){var $mountedElement=$("#charitable_stripe_ach_direct_debit_field");wpchar.debug("Post-mount check:","stripe");wpchar.debug({display:$mountedElement.css("display"),height:$mountedElement.height(),isVisible:$mountedElement.is(":visible"),iframeCount:$mountedElement.find("iframe").length,style:$mountedElement.attr("style")},"stripe");if($mountedElement.is(":hidden")||$mountedElement.css("display")==="none"){wpchar.debug("ACH container was hidden, making it visible","stripe");$mountedElement.show();$mountedElement[0].offsetHeight;wpchar.debug("ACH container after show:","stripe");wpchar.debug({display:$mountedElement.css("display"),height:$mountedElement.height(),isVisible:$mountedElement.is(":visible")},"stripe")}var computedStyles=window.getComputedStyle($mountedElement[0]);wpchar.debug("ACH Container CSS Analysis:","stripe");wpchar.debug({display:computedStyles.display,visibility:computedStyles.visibility,height:computedStyles.height,maxHeight:computedStyles.maxHeight,overflow:computedStyles.overflow,position:computedStyles.position,zIndex:computedStyles.zIndex},"stripe");var $parents=$mountedElement.parents();$parents.each(function(index){var $parent=$(this);var parentDisplay=$parent.css("display");var parentVisibility=$parent.css("visibility");if(parentDisplay==="none"||parentVisibility==="hidden"){wpchar.debug("Parent element hidden:","stripe");wpchar.debug({index:index,tag:this.tagName,id:this.id,class:this.className,display:parentDisplay,visibility:parentVisibility},"stripe")}})},500)}catch(error){wpchar.debug("Error in ACH mounting process: "+error,"stripe");wpchar.debug("Error details:","stripe");wpchar.debug({message:error.message,stack:error.stack,name:error.name},"stripe")}}else{wpchar.debug("ACH Direct Debit element not found in DOM","stripe");wpchar.debug("Looking for: #charitable_stripe_ach_direct_debit_field","stripe");wpchar.debug("Available elements with similar IDs:","stripe");$('[id*="ach"]').each(function(){wpchar.debug("Found element: "+$(this).attr("id"),"stripe")})}},100)}else{wpchar.debug("ACH Direct Debit not enabled or not properly configured or invalid amount","stripe");wpchar.debug("CHARITABLE_STRIPE_VARS.enable_ach_direct_debit: "+CHARITABLE_STRIPE_VARS.enable_ach_direct_debit,"stripe");wpchar.debug("isValidAmount: "+isValidAmount,"stripe");wpchar.debug("amount: "+amount,"stripe")}var sepa_direct_debit_element=$("#charitable_stripe_sepa_direct_debit_field"),sepa_direct_debit_payment_element_options={fields:{billingDetails:{name:"never",email:"never",address:{country:"never",line1:"never",line2:"never",city:"never",state:"never",postalCode:"never"}}}},sepa_direct_debit_payment_element=false,sepa_is_recurring_at_init=function(){var $rd=$('input[name="recurring_donation"]:checked');if($rd.length){var v=$rd.val();if(v&&v!==""&&v!=="once"){return true}}var $hidden=$('input[name="recurring_donation"][type="hidden"]');if($hidden.length){var hv=$hidden.val();if(hv&&hv!==""&&hv!=="once"){return true}}return false}(),sepa_direct_debit_options=sepa_is_recurring_at_init?{mode:"setup",currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"eur",paymentMethodTypes:["sepa_debit"]}:{mode:"payment",amount:amount,currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"eur",paymentMethodTypes:["sepa_debit"]};if(typeof CHARITABLE_STRIPE_VARS.enable_sepa_direct_debit!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_sepa_direct_debit&&parseInt(CHARITABLE_STRIPE_VARS.enable_sepa_direct_debit)!==0&&isValidAmount){if(sepa_direct_debit_element.length){sepa_direct_debit_elements=stripe.elements(sepa_direct_debit_options);sepa_direct_debit_payment_element=sepa_direct_debit_elements.create("payment",sepa_direct_debit_payment_element_options);stripeElementInstances.sepa_direct_debit_payment_element=sepa_direct_debit_payment_element;sepa_direct_debit_payment_element.mount(resolveVisibleField("charitable_stripe_sepa_direct_debit_field"));if(sepa_direct_debit_element.is(":hidden")){sepa_direct_debit_element.show()}}}var becs_debit_element=$("#charitable_stripe_becs_direct_debit_field"),becs_debit_payment_element_options={fields:{billingDetails:{name:"never",email:"never"}}},becs_debit_payment_element=false,becs_debit_options={mode:"payment",amount:amount,currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"usd",paymentMethodTypes:["au_becs_debit"]};if(typeof CHARITABLE_STRIPE_VARS.enable_becs_direct_debit!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_becs_direct_debit&&parseInt(CHARITABLE_STRIPE_VARS.enable_becs_direct_debit)!==0&&isValidAmount){if(becs_debit_element.length){becs_debit_elements=stripe.elements(becs_debit_options);becs_debit_payment_element=becs_debit_elements.create("payment",becs_debit_payment_element_options);stripeElementInstances.becs_debit_payment_element=becs_debit_payment_element;becs_debit_payment_element.mount(resolveVisibleField("charitable_stripe_becs_direct_debit_field"));if(becs_debit_element.is(":hidden")){becs_debit_element.show()}}}var cash_app_element=$("#charitable_stripe_cash_app_field"),cash_app_payment_element_options={},cash_app_payment_element=false,cash_app_options={mode:"payment",amount:amount,currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"usd",paymentMethodTypes:["cash
36app"]};if(typeof CHARITABLE_STRIPE_VARS.enable_cash_app!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_cash_app&&parseInt(CHARITABLE_STRIPE_VARS.enable_cash_app)!==0&&isValidAmount){if(cash_app_element.length){cash_app_elements=stripe.elements(cash_app_options);cash_app_payment_element=cash_app_elements.create("payment",cash_app_payment_element_options);stripeElementInstances.cash_app_payment_element=cash_app_payment_element;cash_app_payment_element.mount(resolveVisibleField("charitable_stripe_cash_app_field"));if(cash_app_element.is(":hidden")){cash_app_element.show()}}}var canadian_debit_element=$("#charitable_stripe_canadian_debit_field"),canadian_debit_payment_element_options={fields:{billingDetails:{name:"never",email:"never"}}},canadian_debit_payment_element=false,canadian_debit_elements=null,canadian_debit_options={mode:"payment",amount:amount,currency:"cad",paymentMethodTypes:["acss_debit"]};function initializeExpressCheckout(amount_in_cents,helper){if(amount_in_cents===0){$(".charitable-payment-divider").hide();$("#charitable_stripe_express_checkout_field").hide();return null}else{$(".charitable-payment-divider").show();if($("#charitable_stripe_express_checkout_field").is(":hidden")){$("#charitable_stripe_express_checkout_field").show()}}const appearance={theme:"stripe",variables:{borderRadius:"0px"}};const expressCheckoutOptions={buttonType:{applePay:"donate",googlePay:"donate",paypal:"buynow",klarna:"pay"},paymentMethods:{applePay:typeof CHARITABLE_STRIPE_VARS.enable_express_checkout!=="undefined"&&typeof CHARITABLE_STRIPE_VARS.enable_apple_pay!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_express_checkout&&CHARITABLE_STRIPE_VARS.enable_apple_pay&&CHARITABLE_STRIPE_VARS.enable_apple_pay!=="0"?"always":"never",googlePay:typeof CHARITABLE_STRIPE_VARS.enable_express_checkout!=="undefined"&&typeof CHARITABLE_STRIPE_VARS.enable_google_pay!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_express_checkout&&CHARITABLE_STRIPE_VARS.enable_google_pay&&CHARITABLE_STRIPE_VARS.enable_google_pay!=="0"?"always":"never",klarna:"auto",paypal:"auto",link:"auto",amazonPay:"auto"}};const elements=stripe.elements({locale:typeof CHARITABLE_STRIPE_VARS!=="undefined"&&CHARITABLE_STRIPE_VARS.locale?CHARITABLE_STRIPE_VARS.locale:"auto",mode:"payment",amount:amount_in_cents,currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"usd",appearance:appearance});if($("#charitable_stripe_express_checkout_field").length){let expressCheckoutElement;try{wpchar.debug("Initializing Express Checkout with options:","stripe");wpchar.debug(expressCheckoutOptions,"stripe");wpchar.debug("Amount in cents: "+amount_in_cents,"stripe");wpchar.debug("Currency: "+(CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"usd"),"stripe");expressCheckoutElement=elements.create("expressCheckout",expressCheckoutOptions);stripeElementInstances.expressCheckoutElement=expressCheckoutElement;wpchar.debug("Express Checkout element created successfully","stripe");expressCheckoutElement.mount(resolveVisibleField("charitable_stripe_express_checkout_field"));wpchar.debug("Express Checkout element mounted successfully","stripe");expressCheckoutElement.on("ready",function({availablePaymentMethods:availablePaymentMethods}){wpchar.debug("Express Checkout element is ready","stripe");if(!availablePaymentMethods||Object.keys(availablePaymentMethods).length===0){$("#charitable_stripe_express_checkout_field").hide();$(".charitable-payment-divider").hide()}});expressCheckoutElement.on("error",function(error){console.error("Express Checkout element error:",error);wpchar.debug("Express Checkout element error: "+JSON.stringify(error),"stripe")})}catch(error){console.error("Error creating/mounting Express Checkout element:",error);wpchar.debug("Error creating/mounting Express Checkout element: "+error.message,"stripe");wpchar.debug("Error stack: "+error.stack,"stripe");return null}const handleError=error=>{const messageContainer=document.querySelector("#charitable-form-errors");messageContainer.textContent=error.message;$("#charitable-form-errors").show()};expressCheckoutElement.on("confirm",async event=>{const{error:submitError}=await elements.submit();if(submitError){handleError(submitError);return}const overlay=document.createElement("div");
36overlay.className="charitable-stripe-overlay";overlay.innerHTML='<div class="charitable-stripe-spinner"></div>';document.body.appendChild(overlay);const formData=$(".charitable-donation-form").serializeArray().reduce(function(obj,item){if("[]"===item.name.slice(-2)){var name=item.name.slice(0,-2);if(!obj.hasOwnProperty(name)){obj[name]=[]}obj[name].push(item.value)}else{obj[item.name]=item.value}return obj},{});$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent",amount_in_cents:amount_in_cents,amount:amount_in_cents/100,nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:formData},success:async function(response){if(!response.success){console.error("response",response);console.error("Failed to create PaymentIntent:",response.data);overlay.remove();return}const{client_secret:clientSecret}=response.data;const{donation_id:donationId}=response.data;const{error:error}=await stripe.confirmPayment({elements:elements,clientSecret:clientSecret,confirmParams:{return_url:CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/"+donationId+"/"}});if(error){handleError(error);overlay.remove()}else{}},error:function(xhr,status,error){console.error("AJAX error:",error);overlay.remove()}})});return expressCheckoutElement}return null}if(typeof CHARITABLE_STRIPE_VARS.enable_express_checkout!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_express_checkout&&parseInt(CHARITABLE_STRIPE_VARS.enable_express_checkout)!==0){wpchar.debug("Express Checkout is enabled, checking amount: "+amount,"stripe");if(!isNaN(amount)&&amount>0){wpchar.debug("Amount is valid ("+amount+"), initializing Express Checkout","stripe");expressCheckoutElement=initializeExpressCheckout(amount,helper);stripeElementInstances.expressCheckoutElement=expressCheckoutElement}else{wpchar.debug("Amount is invalid or zero ("+amount+"), skipping Express Checkout initialization","stripe");if(expressCheckoutElement){expressCheckoutElement.unmount()}$(".charitable-payment-divider").hide()}$body.on("charitable:form:amount:changed",function(event,helper){const amount=convertAmountToCents(helper.get_amount());if(!isNaN(amount)&&amount>0){wpchar.debug("Amount changed: "+amount,"stripe");if(expressCheckoutElement){wpchar.debug("Unmounting existing Express Checkout element","stripe");expressCheckoutElement.unmount()}expressCheckoutElement=initializeExpressCheckout(amount,helper)}});$(".charitable-donation-form").on("input keyup",'input[name="custom_donation_amount"]',function(){const amount=convertAmountToCents($(this).val())||0;if(!isNaN(amount)&&amount>0){wpchar.debug("Custom amount changed: "+amount,"stripe");if(expressCheckoutElement){wpchar.debug("Unmounting existing Express Checkout element","stripe");expressCheckoutElement.unmount()}expressCheckoutElement=initializeExpressCheckout(amount,helper);stripeElementInstances.expressCheckoutElement=expressCheckoutElement}else if(expressCheckoutElement){wpchar.debug("Invalid amount, unmounting Express Checkout element","stripe");expressCheckoutElement.unmount()}})}var $targetElement=$(resolveVisibleField("charitable_stripe_card_field"));try{card_element.mount(resolveVisibleField("charitable_stripe_card_field"));if($("#charitable-form-errors").length===0){$targetElement.closest("form").prepend('<div id="charitable-form-errors" style="display:none;"></div>')}}catch(error){console.error("[STRIPE INIT DEBUG] â Failed to mount card element:",error)}var setup_adaptive_styling=function(){var current_height=$card.height(),new_height=$card_name.innerHeight(),v_padding=(new_height-current_height)/2;$card.css({paddingTop:v_padding,paddingRight:$card_name.css("paddingRight"),paddingBottom:v_padding,paddingLeft:$card_name.css("paddingLeft"),border:$card_name.css("border"),borderRadius:$card_name.css("borderRadius"),background:$card_name.css("background")})}();function adjustStripeCardFieldHeight(){setTimeout(function(){var $cardField=$("#charitable_stripe_card_field");var $stripeElement=$cardField.find(".__PrivateStripeElement");var $ccNameElement=$("#charitable_field_cc_name_element");var isVisualForm=$cardField.closest(".charitable-visual-donation-form").length>0;var isModal=$cardField.closest('.charitable-modal, .lean-modal, [id*="modal"]').length>0;wpchar.debug("adjustStripeCardFieldHeight called - isModal: "+isModal+", isVisualForm: "+isVisualForm,"stripe");if(isVisualForm){wpchar.debug("Visual form detected - matching height to cc_name field","stripe");if($ccNameElement.length){var ccNameHeight=$ccNameElement.outerHeight(true);
36var ccNameOffsetHeight=$ccNameElement[0].offsetHeight;var ccNameWidth=$ccNameElement.outerWidth();var ccNameOffsetWidth=$ccNameElement[0].offsetWidth;wpchar.debug("ccNameHeight (outerHeight with margin): "+ccNameHeight,"stripe");wpchar.debug("ccNameOffsetHeight (offsetHeight): "+ccNameOffsetHeight,"stripe");wpchar.debug("ccNameWidth (outerWidth): "+ccNameWidth,"stripe");wpchar.debug("ccNameOffsetWidth (offsetWidth): "+ccNameOffsetWidth,"stripe");var targetHeight=ccNameOffsetHeight>0?ccNameOffsetHeight:ccNameHeight;var targetWidth=ccNameOffsetWidth>0?ccNameOffsetWidth:ccNameWidth;var MIN_VALID_HEIGHT=40;var MIN_VALID_WIDTH=200;if(targetHeight<MIN_VALID_HEIGHT||targetWidth<MIN_VALID_WIDTH){wpchar.debug("WARNING: Invalid dimensions detected (height: "+targetHeight+"px, width: "+targetWidth+"px). Elements may not be fully rendered yet.","stripe");var $fieldsGrid=$cardField.closest(".charitable-fields-grid");var $parentContainer=$cardField.parent();if(targetWidth<MIN_VALID_WIDTH){var parentWidth=$parentContainer.outerWidth();if(parentWidth>MIN_VALID_WIDTH){wpchar.debug("Using parent container width: "+parentWidth+"px","stripe");targetWidth=parentWidth}else if($fieldsGrid.length){var gridWidth=$fieldsGrid.outerWidth();if(gridWidth>MIN_VALID_WIDTH){wpchar.debug("Using fields grid width: "+gridWidth+"px","stripe");targetWidth=gridWidth}}}if(targetHeight<MIN_VALID_HEIGHT){wpchar.debug("Using fallback height: 42px","stripe");targetHeight=42}if(targetWidth<MIN_VALID_WIDTH){wpchar.debug("Using fallback width: 100% of parent","stripe");targetWidth=null}}if(targetWidth!==null){var $fieldsGrid=$cardField.closest(".charitable-fields-grid");if($fieldsGrid.length){var gridWidth=$fieldsGrid.outerWidth();if(gridWidth>0&&targetWidth>gridWidth){wpchar.debug("Parent .charitable-fields-grid width ("+gridWidth+"px) is smaller than cc_name width ("+targetWidth+"px), constraining to grid width","stripe");targetWidth=gridWidth}else{wpchar.debug("Parent .charitable-fields-grid width: "+gridWidth+"px, cc_name width: "+targetWidth+"px","stripe")}}}var cssProps={height:targetHeight+"px","min-height":targetHeight+"px"};if(targetWidth!==null){cssProps["width"]=targetWidth+"px";cssProps["max-width"]=targetWidth+"px"}else{cssProps["width"]="100%";cssProps["max-width"]="100%"}$cardField.css(cssProps);wpchar.debug("Set Stripe card field height to: "+targetHeight+"px","stripe");if(targetWidth!==null){wpchar.debug("Set Stripe card field width to: "+targetWidth+"px","stripe")}else{wpchar.debug("Set Stripe card field width to: 100%","stripe")}$cardField.css({"padding-top":"10px","padding-bottom":"10px","padding-left":"10px","padding-right":"10px"});if($stripeElement.length){$stripeElement.css("margin-top","0")}}else{wpchar.debug("cc_name element not found in visual form, using standard padding","stripe");$cardField.css({height:"","min-height":"42px","padding-top":"10px","padding-bottom":"10px","padding-left":"10px","padding-right":"10px"});if($stripeElement.length){$stripeElement.css("margin-top","0")}}return}if($ccNameElement.length){var ccNameHeight=$ccNameElement.outerHeight();wpchar.debug("ccNameHeight (with padding): "+ccNameHeight,"stripe");var computedStyle=window.getComputedStyle($ccNameElement[0]);var totalHeight=$ccNameElement[0].offsetHeight;wpchar.debug("totalHeight (offsetHeight): "+totalHeight,"stripe");wpchar.debug("computed padding-top: "+computedStyle.paddingTop,"stripe");wpchar.debug("computed padding-bottom: "+computedStyle.paddingBottom,"stripe");var finalHeight=totalHeight||ccNameHeight;if(isModal&&finalHeight<42){finalHeight=42;wpchar.debug("Modal context detected - setting minimum height to 42px","stripe")}$cardField.height(finalHeight);var cardFieldHeight=$cardField.height();wpchar.debug("cardFieldHeight after setting: "+cardFieldHeight,"stripe");wpchar.debug($stripeElement,"stripe");if($stripeElement.length&&cardFieldHeight>0){var stripeElementHeight=$stripeElement.height();var topPadding=Math.max(0,(cardFieldHeight-stripeElementHeight)/2);if(topPadding>cardFieldHeight*.4){topPadding=Math.max(10,cardFieldHeight*.2)}$stripeElement.css("margin-top",topPadding+"px");wpchar.debug("stripeElementHeight: "+stripeElementHeight,"stripe");wpchar.debug("topPadding: "+topPadding,"stripe");wpchar.debug("cardFieldHeight: "+cardFieldHeight,"stripe")}}else{var cardFieldHeight=$cardField.height();wpchar.debug("ccNameElement not found, using original logic","stripe");wpchar.debug("cardFieldHeight: "+cardFieldHeight,"stripe");wpchar.debug($stripeElement,"stripe");if($stripeElement.length&&cardFieldHeight>0){var topPadding=Math.max(10,Math.floor(cardFieldHeight*.3));$stripeElement.css("margin-top",topPadding+"px")}}},100)}function shouldInitializeStripe(){var $cardField=$("#charitable_stripe_card_field");var $stripeTab=$('.charitable-gateway-tab input[value="stripe"]:checked, input[name="gateway"][value="stripe"]:checked');var $stripeFields=$("#charitable-gateway-fields-stripe");wpchar.debug("Checking if Stripe should be initialized...","stripe");wpchar.debug("Stripe card field exists: "+($cardField.length>0),"stripe");wpchar.debug("Stripe card field visible: "+($cardField.length>0&&$cardField.is(":visible")),"stripe");wpchar.debug("Stripe tab checked: "+($stripeTab.length>0),"stripe");wpchar.debug("Stripe gateway fields container exists: "+($stripeFields.length>0),"stripe");wpchar.debug("Stripe gateway fields visible: "+($stripeFields.length>0&&$stripeFields.is(":visible")),"stripe");if($cardField.length>0&&$cardField.is(":visible")){wpchar.debug("Stripe card field found and visible - should initialize","stripe");return true}if($stripeTab.length>0){wpchar.debug("Stripe tab is checked - should initialize","stripe");return true}if($stripeFields.length>0&&$stripeFields.is(":visible")){wpchar.debug("Stripe gateway fields container visible (likely single gateway) - should initialize","stripe");return true}var $allGatewayTabs=$(".charitable-gateway-tab");var $visibleGatewayTabs=$(".charitable-gateway-tab:visible");if($allGatewayTabs.length===0&&$cardField.length>0){wpchar.debug("No gateway tabs found but Stripe field exists (single gateway scenario) - should initialize","stripe");return true}wpchar.debug("Stripe should NOT be initialized based on current conditions","stripe");return false}adjustStripeCardFieldHeight();setTimeout(function(){wpchar.debug("Additional check after initialization - verifying Stripe should be initialized","stripe");if(shouldInitializeStripe()){wpchar.debug("Stripe should be initialized - performing additional height adjustment","stripe");adjustStripeCardFieldHeight()}else{wpchar.debug("Stripe should NOT be initialized in additional check - skipping","stripe")}},500);$(document).on("charitable:modal:open",function(){wpchar.debug("charitable:modal:open event fired - checking Stripe initialization","stripe");setTimeout(function(){if(shouldInitializeStripe()){wpchar.debug("charitable:modal:open - Stripe should be initialized, calling adjustStripeCardFieldHeight","stripe");adjustStripeCardFieldHeight();setTimeout(function(){var $cardField=$("#charitable_stripe_card_field");var currentWidth=$cardField.outerWidth();var currentHeight=$cardField.outerHeight();if(currentWidth<200||currentHeight<40){wpchar.debug("charitable:modal:open - Retry: Dimensions still invalid (width: "+currentWidth+", height: "+currentHeight+"), retrying adjustStripeCardFieldHeight","stripe");adjustStripeCardFieldHeight()}},500)}else{wpchar.debug("charitable:modal:open - Stripe should NOT be initialized, skipping","stripe")}},600)});$(document).on("shown.bs.modal",function(){wpchar.debug("shown.bs.modal event fired - checking Stripe initialization","stripe");setTimeout(function(){if(shouldInitializeStripe()){wpchar.debug("shown.bs.modal - Stripe should be initialized, calling adjustStripeCardFieldHeight","stripe");adjustStripeCardFieldHeight();setTimeout(function(){var $cardField=$("#charitable_stripe_card_field");var currentWidth=$cardField.outerWidth();var currentHeight=$cardField.outerHeight();if(currentWidth<200||currentHeight<40){wpchar.debug("shown.bs.modal - Retry: Dimensions still invalid (width: "+currentWidth+", height: "+currentHeight+"), retrying adjustStripeCardFieldHeight","stripe");adjustStripeCardFieldHeight()}},500)}else{wpchar.debug("shown.bs.modal - Stripe should NOT be initialized, skipping","stripe")}},600)});$(document).on("charitable:modal:loaded",function(){wpchar.debug("charitable:modal:loaded event fired - checking Stripe initialization","stripe");setTimeout(function(){if(shouldInitializeStripe()){wpchar.debug("charitable:modal:loaded - Stripe should be initialized, calling adjustStripeCardFieldHeight","stripe");adjustStripeCardFieldHeight();setTimeout(function(){var $cardField=$("#charitable_stripe_card_field");var currentWidth=$cardField.outerWidth();var currentHeight=$cardField.outerHeight();if(currentWidth<200||currentHeight<40){wpchar.debug("charitable:modal:loaded - Retry: Dimensions still invalid (width: "+currentWidth+", height: "+currentHeight+"), retrying adjustStripeCardFieldHeight","stripe");adjustStripeCardFieldHeight()}},500)}else{wpchar.debug("charitable:modal:loaded - Stripe should NOT be initialized, skipping","stripe")}},600)});$(document).on("charitable:form:initialize",function(){wpchar.debug("Form initialized - adjusting Stripe card field height","stripe");setTimeout(adjustStripeCardFieldHeight,200)});$(document).on("charitable:form:loaded",function(){wpchar.debug("Form loaded - adjusting Stripe card field height","stripe");var $cardField=$("#charitable_stripe_card_field");var $stripeElement=$cardField.find('.__PrivateStripeElement, iframe[src*="js.stripe.com"]');if($stripeElement.length>0){setTimeout(adjustStripeCardFieldHeight,200)}else{wpchar.debug("Stripe Element not mounted yet, waiting longer for height adjustment","stripe");setTimeout(function(){$stripeElement=$cardField.find('.__PrivateStripeElement, iframe[src*="js.stripe.com"]');if($stripeElement.length>0){adjustStripeCardFieldHeight()}else{setTimeout(function(){adjustStripeCardFieldHeight()},500)}},400)}});$(document).on("charitable:stripe:adjust-height",function(){wpchar.debug("Custom height adjustment event received","stripe");adjustStripeCardFieldHeight()});$(document).on("DOMNodeInserted",".charitable-modal, .lean-modal",function(){setTimeout(function(){var $modal=$(this);if($modal.is(":visible")){wpchar.debug("Modal content inserted and visible - checking Stripe field","stripe");var $stripeTab=$modal.find('.charitable-gateway-tab input[value="stripe"]:checked, input[name="gateway"][value="stripe"]:checked');if($stripeTab.length>0){wpchar.debug("Stripe is active in newly inserted modal - adjusting height","stripe");setTimeout(adjustStripeCardFieldHeight,100)}}}.bind(this),50)});$(document).on("charitable:gateway:changed",function(event,gatewayId){if(gatewayId==="str
36ipe"){wpchar.debug("Stripe gateway selected - adjusting card field height","stripe");setTimeout(adjustStripeCardFieldHeight,200)}});setInterval(function(){var $modal=$('.charitable-modal, .lean-modal, [id*="modal"]');if($modal.length&&$modal.is(":visible")){var $cardField=$("#charitable_stripe_card_field");if($cardField.length&&$cardField.is(":visible")){var $stripeElement=$cardField.find(".__PrivateStripeElement");var $stripeTab=$('.charitable-gateway-tab input[value="stripe"]:checked, input[name="gateway"][value="stripe"]:checked');if($stripeTab.length>0&&$stripeElement.length){var currentHeight=$stripeElement.height();var currentMarginTop=parseInt($stripeElement.css("margin-top"))||0;if(currentHeight===0||currentHeight>0&¤tMarginTop===0){wpchar.debug("Detected Stripe element needing height adjustment in modal - adjusting","stripe");wpchar.debug("Current height: "+currentHeight+" Current margin-top: "+currentMarginTop,"stripe");adjustStripeCardFieldHeight()}}}}},2e3);card_element.on("change",function(event){$errors.text(event.error?event.error.message:"")});if($postcode.length){$postcode.on("change",function(event){card_element.update({value:{postalCode:event.target.value}})}).trigger("change")}wpchar.debug("loading page","stripe");var process_card=function(event,helper){event.preventDefault();if(""!==$errors.text()){if(helper.hasOwnProperty("prevent_scroll_to_top")){helper.prevent_scroll_to_top=true}helper.add_error($errors.text());helper.hide_processing();processingFlag=false;return}wpchar.debug("helper.errors: "+helper.errors,"stripe");if(helper.errors.length===0){helper.add_pending_process("stripe");wpchar.debug("adding pending process with email: "+helper.get_email(),"stripe");var email=helper.get_email(),phone=helper.get_input("phone"),address=function(){var address={},address_fields=[{field:"city",key:"city"},{field:"country",key:"country"},{field:"address",key:"line1"},{field:"address_2",key:"line2"},{field:"postcode",key:"postal_code"},{field:"state",key:"state"}];address_fields.forEach(function(field){var input=helper.get_input(field.field);if(input.length&&input.val().length){address[field.key]=input.val()}});return address}(),data={billing_details:function(){var billing={name:$card_name.val(),email:email,address:address};if(phone.length&&phone.val().length){billing.phone=phone.val()}return billing}()};wpchar.debug("creating payment method with data: "+JSON.stringify(data),"stripe");wpchar.debug(card_element,"stripe");stripe.createPaymentMethod("card",card_element,data).then(function(result){wpchar.debug(result,"stripe");if(result.error){if(helper.hasOwnProperty("prevent_scroll_to_top")){helper.prevent_scroll_to_top=true}else{wpchar.debug("adding error: "+result.error.message,"stripe");helper.add_error(result.error.message)}processingFlag=false}else{wpchar.debug("result.paymentMethod.id: "+result.paymentMethod.id,"stripe");helper.get_input("stripe_payment_method").val(result.paymentMethod.id);processingFlag=false}helper.remove_pending_process_by_name("stripe")}).catch(function(error){wpchar.debug("Stripe createPaymentMethod error: "+error.message,"stripe");helper.add_error("Payment method creation failed: "+error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false})}else{processingFlag=false}};var process_ach_direct_debit=function(event,helper){event.preventDefault();helper.add_pending_process("stripe");ach_direct_debit_elements.submit().then(async function(submitResult){if(submitResult.error){helper.add_error(submitResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent_ach_direct_debit",amount_in_cents:convertAmountToCents(helper.get_amount()),amount:helper.get_amount(),nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:helper.get_data()},success:function(response){wpchar.debug("process_ach_direct_debit AJAX response: "+response,"stripe");if(!response.success){helper.add_error(response.data.message||"Failed to create payment intent");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}var firstName=helper.get_input("first_name").val()||"";var lastName=helper.get_input("last_name").val()||"";var fullName=(firstName+" "+lastName).trim();var email=helper.get_email();stripe.confirmPayment({elements:ach_direct_debit_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:{name:fullName,email:email}},return_url:CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/"+response.data.donation_id+"/"}}).then(function(result){if(result.error){helper.add_error(result.error.message)}helper.remove_pending_process_by_name("stripe");processingFlag=false})},error:function(xhr,status,error){helper.add_error("Failed to process payment: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})})};var process_sepa_direct_debit=function(event,helper){event.preventDefault();helper.add_pending_process("stripe");sepa_direct_debit_elements.submit().then(async function(submitResult){if(submitResult.error){helper.add_error(submitResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent_sepa_direct_debit",amount_in_cents:convertAmountToCents(helper.get_amount()),amount:helper.get_amount(),nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:helper.get_data()},success:function(response){wpchar.debug("process_sepa_direct_debit AJAX response: "+response,"stripe");if(!response.success){helper.add_error(response.data.message||"Failed to create payment intent");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}var firstName=helper.get_input("first_name").val()||"";var lastName=helper.get_input("last_name").val()||"";var fullName=(firstName+" "+lastName).trim();var email=helper.get_email();var city=helper.get_input("city").val()||"";var country=helper.get_input("country").val()||"";var line1=helper.get_input("address").val()||"";var line2=helper.get_input("address_2").val()||"";var postalCode=helper.get_input("postcode").val()||"";var state=helper.get_input("state").val()||"";var billingDetails={name:fullName,email:email,address:{city:city,country:country,line1:line1,line2:line2,postal_code:postalCode,state:state}};var receiptUrl=CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/"+response.data.donation_id+"/";if(response.data.is_recurring){stripe.confirmSetup({elements:sepa_direct_debit_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:billingDetails},return_url:receiptUrl},redirect:"if_required"}).then(function(setupResult){if(setupResult.error){helper.add_error(setupResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_subscription_sepa_direct_debit",nonce:CHARITABLE_STRIPE_VARS.nonce,payment_method:setupResult.setupIntent.payment_method,customer_id:response.data.customer_id,donation_id:response.data.donation_id,donation_plan_id:response.data.donation_plan_id}
36,success:function(subResponse){if(!subResponse.success){helper.add_error(subResponse.data&&subResponse.data.message||"Failed to create subscription");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}window.location.href=receiptUrl},error:function(xhr,status,error){helper.add_error("Failed to create subscription: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})});return}stripe.confirmPayment({elements:sepa_direct_debit_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:billingDetails},return_url:receiptUrl}}).then(function(result){if(result.error){helper.add_error(result.error.message)}helper.remove_pending_process_by_name("stripe");processingFlag=false})},error:function(xhr,status,error){helper.add_error("Failed to process payment: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})})};var process_becs_direct_debit=function(event,helper){event.preventDefault();helper.add_pending_process("stripe");becs_debit_elements.submit().then(async function(submitResult){if(submitResult.error){helper.add_error(submitResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent_becs_direct_debit",amount_in_cents:convertAmountToCents(helper.get_amount()),amount:helper.get_amount(),nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:helper.get_data()},success:function(response){wpchar.debug("process_becs_direct_debit AJAX response: "+response,"stripe");if(!response.success){helper.add_error(response.data.message||"Failed to create payment intent");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}var firstName=helper.get_input("first_name").val()||"";var lastName=helper.get_input("last_name").val()||"";var fullName=(firstName+" "+lastName).trim();var email=helper.get_email();stripe.confirmPayment({elements:becs_debit_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:{name:fullName,email:email}},return_url:CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/"+response.data.donation_id+"/"}}).then(function(result){if(result.error){helper.add_error(result.error.message)}helper.remove_pending_process_by_name("stripe");processingFlag=false})},error:function(xhr,status,error){helper.add_error("Failed to process payment: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})})};var process_cash_app=function(event,helper){event.preventDefault();var originalPageUrl=window.location.href;if(typeof sessionStorage!=="undefined"){sessionStorage.setItem("charitable_cash_app_original_page_url",originalPageUrl)}helper.add_pending_process("stripe");cash_app_elements.submit().then(async function(submitResult){if(submitResult.error){helper.add_error(submitResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent_cash_app",amount_in_cents:convertAmountToCents(helper.get_amount()),amount:helper.get_amount(),nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:helper.get_data(),original_page_url:originalPageUrl},success:function(response){wpchar.debug("process_cash_app AJAX response: "+response,"stripe");if(!response.success){helper.add_error(response.data.message||"Failed to create payment intent");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}var firstName=helper.get_input("first_name").val()||"";var lastName=helper.get_input("last_name").val()||"";var fullName=(firstName+" "+lastName).trim();var email=helper.get_email();var donationId=response.data.donation_id;var returnUrl=window.location.href;stripe.confirmPayment({elements:cash_app_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:{name:fullName,email:email}},return_url:returnUrl}}).then(function(result){if(result.error){helper.add_error(result.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}
36wpchar.debug("Cash App payment confirmation initiated","stripe");if(typeof sessionStorage!=="undefined"){sessionStorage.setItem("charitable_cash_app_donation_id",donationId)}}).catch(function(error){wpchar.debug("Cash App payment error: "+error.message,"stripe");helper.add_error("Payment failed: "+error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false})},error:function(xhr,status,error){helper.add_error("Failed to process payment: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})})};var process_canadian_pre_authorized_debit=function(event,helper){event.preventDefault();helper.add_error("Canadian Pre-Authorized Debit is not yet implemented.");helper.hide_processing();processingFlag=false};var process_ach_direct_debit=function(event,helper){event.preventDefault();helper.add_pending_process("stripe");ach_direct_debit_elements.submit().then(async function(submitResult){if(submitResult.error){helper.add_error(submitResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent_ach_direct_debit",amount_in_cents:convertAmountToCents(helper.get_amount()),amount:helper.get_amount(),nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:helper.get_data()},success:function(response){if(!response.success){helper.add_error(response.data.message||"Failed to create payment intent");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}var firstName=helper.get_input("first_name").val()||"";var lastName=helper.get_input("last_name").val()||"";var fullName=(firstName+" "+lastName).trim();var email=helper.get_email();stripe.confirmPayment({elements:ach_direct_debit_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:{name:fullName,email:email}},return_url:CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/"+response.data.donation_id+"/"}}).then(function(result){if(result.error){helper.add_error(result.error.message)}helper.remove_pending_process_by_name("stripe");processingFlag=false})},error:function(xhr,status,error){helper.add_error("Failed to process payment: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})})};var process_becs_direct_debit=function(event,helper){event.preventDefault();helper.add_pending_process("stripe");becs_debit_elements.submit().then(async function(submitResult){if(submitResult.error){helper.add_error(submitResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent_becs_direct_debit",amount_in_cents:convertAmountToCents(helper.get_amount()),amount:helper.get_amount(),nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:helper.get_data()},success:function(response){if(!response.success){helper.add_error(response.data.message||"Failed to create payment intent");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}var firstName=helper.get_input("first_name").val()||"";var lastName=helper.get_input("last_name").val()||"";var fullName=(firstName+" "+lastName).trim();var email=helper.get_email();stripe.confirmPayment({elements:becs_debit_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:{name:fullName,email:email}},return_url:CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/"+response.data.donation_id+"/"}}).then(function(result){if(result.error){helper.add_error(result.error.message)}helper.remove_pending_process_by_name("stripe");processingFlag=false})},error:function(xhr,status,error){helper.add_error("Failed to process payment: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})})};var process_cash_app=function(event,helper){event.preventDefault();var originalPageUrl=window.location.href;if(typeof sessionStorage!=="undefined"){sessionStorage.setItem("charitable_cash_app_original_page_url",originalPageUrl)}helper.add_pending_process("stripe");cash_app_elements.submit().then(async function(submitResult){if(submitResult.error){helper.add_error(submitResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent_cash_app",amount_in_cents:convertAmountToCents(helper.get_amount()),amount:helper.get_amount(),nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:helper.get_data(),original_page_url:originalPageUrl},success:function(response){if(!response.success){helper.add_error(response.data.message||"Failed to create payment intent");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}var firstName=helper.get_input("first_name").val()||"";var lastName=helper.get_input("last_name").val()||"";var fullName=(firstName+" "+lastName).trim();var email=helper.get_email();var donationId=response.data.donation_id;stripe.confirmPayment({elements:cash_app_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:{name:fullName,email:email}},return_url:window.location.href}}).then(function(result){if(result.error){helper.add_error(result.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}if(typeof sessionStorage!=="undefined"){sessionStorage.setItem("charitable_cash_app_donation_id",donationId)}}).catch(function(error){helper.add_error("Payment failed: "+error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false})},error:function(xhr,status,error){helper.add_error("Failed to process payment: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})})};$body.on("charitable:form:validate.stripe",function(event,helper){wpchar.debug("charitable:form:VALIDATE inside Payment_Intents_Handler","stripe");if("make_donation"!==helper.get_input("charitable_action").val()){return}if(processingFlag){wpchar.debug("Payment already being processed, skipping duplicate","stripe");return}
36wpchar.debug("helper.get_payment_method(): "+helper.get_payment_method(),"stripe");switch(helper.get_payment_method()){case"stripe_ach_direct_debit":processingFlag=true;return process_ach_direct_debit(event,helper);case"stripe_sepa_direct_debit":processingFlag=true;return process_sepa_direct_debit(event,helper);case"stripe":processingFlag=true;return process_card(event,helper);case"stripe_cash_app":processingFlag=true;return process_cash_app(event,helper);case"stripe_becs_direct_debit":processingFlag=true;return process_becs_direct_debit(event,helper);case"stripe_canadian_pre_authorized_debit":processingFlag=true;return process_canadian_pre_authorized_debit(event,helper)}});$body.on("charitable:form:processed.stripe",function(event,response,helper){if(!response.success){return}if(helper.is_recurring_donation()&&!response.requires_action){return}if("make_donation"!==helper.get_input("charitable_action").val()){return}if("stripe"!==helper.get_payment_method()){return}event.preventDefault();if(helper.errors.length===0){var new_stripe;helper.add_pending_process("stripe");if(should_process_payment_on_connected_account(helper)){new_stripe=Stripe(CHARITABLE_STRIPE_VARS.key,get_stripe_options(helper,true))}else{new_stripe=stripe}new_stripe.handleCardPayment(response.secret).then(function(result){if(result.error){$(document).trigger("Charitable_Custom_Event__Handle_Card_Payment_Fail",[event,result,response,CHARITABLE_STRIPE_VARS,helper.get_payment_method()]);helper.add_error(result.error.message)}else{if(response.redirect_to){window.location.href=response.redirect_to}}helper.remove_pending_process_by_name("stripe")})}});function handleCashAppPaymentRedirect(){var urlParams=new URLSearchParams(window.location.search);var paymentIntent=urlParams.get("payment_intent");var redirectStatus=urlParams.get("redirect_status");wpchar.debug("handleCashAppPaymentRedirect called","stripe");wpchar.debug("Current URL: "+window.location.href,"stripe");wpchar.debug("Payment Intent: "+paymentIntent,"stripe");wpchar.debug("Redirect Status: "+redirectStatus,"stripe");if(paymentIntent&&redirectStatus){wpchar.debug("Cash App payment redirect detected - Payment Intent: "+paymentIntent+", Status: "+redirectStatus,"stripe");var donationId=null;if(typeof sessionStorage!=="undefined"){donationId=sessionStorage.getItem("charitable_cash_app_donation_id");wpchar.debug("Donation ID from session: "+donationId,"stripe")}if(redirectStatus==="succeeded"){if(donationId){var receiptUrl=CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/"+donationId+"/";wpchar.debug("Using donation ID from session, redirecting to: "+receiptUrl,"stripe");window.location.href=receiptUrl}else{wpchar.debug("No donation ID in session, making AJAX call to get it","stripe");$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_get_donation_id_by_payment_intent",payment_intent:paymentIntent,nonce:CHARITABLE_STRIPE_VARS.nonce},success:function(response){wpchar.debug("AJAX response for donation ID lookup: "+JSON.stringify(response),"stripe");if(response.success&&response.data.donation_id){var receiptUrl=CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/"+response.data.donation_id+"/";wpchar.debug("Redirecting to receipt URL: "+receiptUrl,"stripe");window.location.href=receiptUrl}else{var receiptUrl=CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/?payment_intent="+paymentIntent;wpchar.debug("AJAX failed, using fallback URL: "+receiptUrl,"stripe");window.location.href=receiptUrl}},error:function(xhr,status,error){wpchar.debug("AJAX error for donation ID lookup: "+error,"stripe");var receiptUrl=CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/?payment_intent="+paymentIntent;wpchar.debug("AJAX error, using fallback URL: "+receiptUrl,"stripe");window.location.href=receiptUrl}})}}else if(redirectStatus==="failed"){var originalPageUrl=null;if(typeof sessionStorage!=="undefined"){originalPageUrl=sessionStorage.getItem("charitable_cash_app_original_page_url")}if(originalPageUrl){var errorUrl=originalPageUrl+(originalPageUrl.includes("?")?"&":"?")+"donation_failed=cash_app";window.location.href=errorUrl}else{handleCashAppPaymentFailure(paymentIntent,donationId)}var cleanUrl=window.location.pathname;window.history.replaceState({},document.title,cleanUrl)}}}function handleCashAppPaymentFailure(paymentIntent,donationId){wpchar.debug("Handling Cash App payment failure","stripe");var errorMessage="Cash App payment was declined. Please try again or use a different payment method.";var $cashAppContainer=$("#charitable_stripe_cash_app_field");var $errorContainer=$cashAppContainer.find(".charitable-cash-app-error");
36if($errorContainer.length){$errorContainer.remove()}var $errorDiv=$('<div class="charitable-cash-app-error charitable-error">'+errorMessage+"</div>");$cashAppContainer.append($errorDiv);resetCashAppPaymentMethod();if(typeof sessionStorage!=="undefined"){sessionStorage.removeItem("charitable_cash_app_donation_id")}$("html, body").animate({scrollTop:$errorDiv.offset().top-100},500)}function resetCashAppPaymentMethod(){wpchar.debug("Resetting Cash App payment method selection","stripe");var $paymentMethodInputs=$('input[name="payment_method"]');if($paymentMethodInputs.length){$paymentMethodInputs.prop("checked",false)}if(typeof cash_app_elements!=="undefined"&&cash_app_elements){try{cash_app_elements.clear()}catch(e){wpchar.debug("Could not clear Cash App elements: "+e.message,"stripe")}}$(".charitable-processing").removeClass("charitable-processing")}function getDonationIdFromPaymentIntent(paymentIntentId){var donationForm=$("form#charitable-donation-form");if(donationForm.length){var donationIdInput=donationForm.find('input[name="donation_id"]');if(donationIdInput.length){return donationIdInput.val()}}return null}$(document).ready(function(){handleCashAppPaymentRedirect();addCashAppErrorStyling()});function addCashAppErrorStyling(){if($("#charitable-cash-app-styles").length){return}var styles=`\n\t\t\t\t<style id="charitable-cash-app-styles">\n\t\t\t\t\t.charitable-cash-app-error {\n\t\t\t\t\t\tmargin-top: 10px;\n\t\t\t\t\t\tpadding: 10px 15px;\n\t\t\t\t\t\tborder: 1px solid #dc3232;\n\t\t\t\t\t\tborder-radius: 4px;\n\t\t\t\t\t\tbackground-color: #fff;\n\t\t\t\t\t\tcolor: #dc3232;\n\t\t\t\t\t\tfont-size: 14px;\n\t\t\t\t\t\tline-height: 1.4;\n\t\t\t\t\t}\n\n\t\t\t\t\t.charitable-cash-app-error:before {\n\t\t\t\t\t\tcontent: "â ï¸ ";\n\t\t\t\t\t\tmargin-right: 5px;\n\t\t\t\t\t}\n\n\t\t\t\t\t#charitable_stripe_cash_app_field .charitable-cash-app-error {\n\t\t\t\t\t\tmargin-top: 15px;\n\t\t\t\t\t}\n\t\t\t\t</style>\n\t\t\t`;$("head").append(styles)}}function Payment_Intents_Handler_Multiple(){var resolveVisibleField=function(id){var nodes=document.querySelectorAll("#"+id);for(var i=0;i<nodes.length;i++){if(nodes[i].offsetParent!==null){return nodes[i]}}return nodes[0]||null};var cardNumberEl=resolveVisibleField("charitable_stripe_card_number_field");if(!cardNumberEl){return}stripe=Stripe(CHARITABLE_STRIPE_VARS.key);var elements=stripe.elements();var $card=$("#charitable_stripe_card_field");var $errors=$("#charitable_stripe_card_errors");var $card_name=$(".charitable-donation-form [data-input=cc_name]");var $postcode=$(".charitable-donation-form [name=postcode]");var $card_field_name=$("#charitable_stripe_card_name_field");var $card_filed_number=$("#charitable_stripe_card_number_field");var $card_field_expiry=$("#charitable_stripe_card_expiration_field");var $card_field_cvc=$("#charitable_stripe_card_cvc_field");var cardNumber=elements.create("cardNumber");cardNumber.mount(cardNumberEl);var cardExpiry=elements.create("cardExpiry");cardExpiry.mount(resolveVisibleField("charitable_stripe_card_expiration_field"));var cardCvc=elements.create("cardCvc");cardCvc.mount(resolveVisibleField("charitable_stripe_card_cvc_field"));cardNumber.on("change",function(event){$errors.text(event.error?event.error.message:"")});cardExpiry.on("change",function(event){$errors.text(event.error?event.error.message:"")});cardCvc.on("change",function(event){$errors.text(event.error?event.error.message:"")});if($postcode.length){$postcode.on("change",function(event){cardNumber.update({value:{postalCode:event.target.value}})}).trigger("change")}var setup_adaptive_styling=function(){var current_height=$card.height(),new_height=$card_name.innerHeight(),v_padding=(new_height-current_height)/2;$card.css({paddingTop:v_padding,paddingRight:$card_name.css("paddingRight"),paddingBottom:v_padding,paddingLeft:$card_name.css("paddingLeft"),border:$card_name.css("border"),borderRadius:$card_name.css("borderRadius"),background:$card_name.css("background")})}();var processingFlag=false;var altAmount=0;var $checkedAmountInput=$('.suggested-donation-amount input[type="radio"]:checked');if($checkedAmountInput.length&&$checkedAmountInput.val()){altAmount=convertAmountToCents($checkedAmountInput.val())}if(!altAmount){var $amountText=$(".charitable-your-donation-amount p strong").text();if($amountText){altAmount=convertAmountToCents($amountText.replace(/[^0-9.]/g,""))}}var isValidAltAmount=altAmount>0;var sepa_direct_debit_elements=null,sepa_direct_debit_payment_element=false,sepa_direct_debit_element=$("#charitable_stripe_sepa_direct_debit_field"),sepa_direct_debit_payment_element_options={fields:{billingDetails:{name:"never",email:"never",address:{country:"never",line1:"never",line2:"never",city:"never",state:"never",postalCode:"never"}}}},sepa_is_recurring_at_init=function(){var $rd=$('input[name="recurring_donation"]:checked');if($rd.length){var v=$rd.val();if(v&&v!==""&&v!=="once"){return true}}var $hidden=$('input[name="recurring_donation"][type="hidden"]');if($hidden.length){var hv=$hidden.val();if(hv&&hv!==""&&hv!=="once"){return true}}return false}(),sepa_direct_debit_options=sepa_is_recurring_at_init?{mode:"setup",currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"eur",paymentMethodTypes:["sepa_debit"]}:{mode:"payment",amount:altAmount,currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"eur",paymentMethodTypes:["sepa_debit"]};if(typeof CHARITABLE_STRIPE_VARS.enable_sepa_direct_debit!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_sepa_direct_debit&&parseInt(CHARITABLE_STRIPE_VARS.enable_sepa_direct_debit)!==0&&isValidAltAmount){if(sepa_direct_debit_element.length){try{
36sepa_direct_debit_elements=stripe.elements(sepa_direct_debit_options);sepa_direct_debit_payment_element=sepa_direct_debit_elements.create("payment",sepa_direct_debit_payment_element_options);stripeElementInstances.sepa_direct_debit_payment_element=sepa_direct_debit_payment_element;sepa_direct_debit_payment_element.mount(resolveVisibleField("charitable_stripe_sepa_direct_debit_field"));if(sepa_direct_debit_element.is(":hidden")){sepa_direct_debit_element.show()}wpchar.debug("SEPA Direct Debit element mounted (Multiple Fields handler)","stripe")}catch(e){wpchar.debug("SEPA init error in Multiple Fields handler: "+e.message,"stripe")}}}var ach_direct_debit_elements=null,ach_direct_debit_payment_element=false,ach_direct_debit_element=$("#charitable_stripe_ach_direct_debit_field"),ach_direct_debit_payment_element_options={fields:{billingDetails:{name:"never",email:"never"}}},ach_direct_debit_options={mode:"payment",amount:altAmount,currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"usd",paymentMethodTypes:["us_bank_account"]};if(typeof CHARITABLE_STRIPE_VARS.enable_ach_direct_debit!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_ach_direct_debit&&CHARITABLE_STRIPE_VARS.enable_ach_direct_debit!==""&&CHARITABLE_STRIPE_VARS.enable_ach_direct_debit!=="0"&&isValidAltAmount){if(ach_direct_debit_element.length){try{ach_direct_debit_elements=stripe.elements(ach_direct_debit_options);ach_direct_debit_payment_element=ach_direct_debit_elements.create("payment",ach_direct_debit_payment_element_options);stripeElementInstances.ach_direct_debit_payment_element=ach_direct_debit_payment_element;ach_direct_debit_payment_element.mount(resolveVisibleField("charitable_stripe_ach_direct_debit_field"));if(ach_direct_debit_element.is(":hidden")){ach_direct_debit_element.show()}wpchar.debug("ACH Direct Debit element mounted (Multiple Fields handler)","stripe")}catch(e){wpchar.debug("ACH init error in Multiple Fields handler: "+e.message,"stripe")}}}var becs_debit_elements=null,becs_debit_payment_element=false,becs_debit_element=$("#charitable_stripe_becs_direct_debit_field"),becs_debit_payment_element_options={fields:{billingDetails:{name:"never",email:"never"}}},becs_debit_options={mode:"payment",amount:altAmount,currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"usd",paymentMethodTypes:["au_becs_debit"]};if(typeof CHARITABLE_STRIPE_VARS.enable_becs_direct_debit!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_becs_direct_debit&&parseInt(CHARITABLE_STRIPE_VARS.enable_becs_direct_debit)!==0&&isValidAltAmount){if(becs_debit_element.length){try{becs_debit_elements=stripe.elements(becs_debit_options);becs_debit_payment_element=becs_debit_elements.create("payment",becs_debit_payment_element_options);stripeElementInstances.becs_debit_payment_element=becs_debit_payment_element;becs_debit_payment_element.mount(resolveVisibleField("charitable_stripe_becs_direct_debit_field"));if(becs_debit_element.is(":hidden")){becs_debit_element.show()}wpchar.debug("BECS Direct Debit element mounted (Multiple Fields handler)","stripe")}catch(e){wpchar.debug("BECS init error in Multiple Fields handler: "+e.message,"stripe")}}}var cash_app_elements=null,cash_app_payment_element=false,cash_app_element=$("#charitable_stripe_cash_app_field"),cash_app_payment_element_options={},cash_app_options={mode:"payment",amount:altAmount,currency:CHARITABLE_STRIPE_VARS.currency&&CHARITABLE_STRIPE_VARS.currency!==""?CHARITABLE_STRIPE_VARS.currency.toLowerCase():"usd",paymentMethodTypes:["cashapp"]};if(typeof CHARITABLE_STRIPE_VARS.enable_cash_app!=="undefined"&&CHARITABLE_STRIPE_VARS.enable_cash_app&&parseInt(CHARITABLE_STRIPE_VARS.enable_cash_app)!==0&&isValidAltAmount){if(cash_app_element.length){try{cash_app_elements=stripe.elements(cash_app_options);cash_app_payment_element=cash_app_elements.create("payment",cash_app_payment_element_options);stripeElementInstances.cash_app_payment_element=cash_app_payment_element;cash_app_payment_element.mount(resolveVisibleField("charitable_stripe_cash_app_field"));if(cash_app_element.is(":hidden")){cash_app_element.show()}
36wpchar.debug("Cash App element mounted (Multiple Fields handler)","stripe")}catch(e){wpchar.debug("Cash App init error in Multiple Fields handler: "+e.message,"stripe")}}}var process_sepa_direct_debit=function(event,helper){event.preventDefault();helper.add_pending_process("stripe");sepa_direct_debit_elements.submit().then(async function(submitResult){if(submitResult.error){helper.add_error(submitResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent_sepa_direct_debit",amount_in_cents:convertAmountToCents(helper.get_amount()),amount:helper.get_amount(),nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:helper.get_data()},success:function(response){if(!response.success){helper.add_error(response.data.message||"Failed to create payment intent");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}var firstName=helper.get_input("first_name").val()||"";var lastName=helper.get_input("last_name").val()||"";var fullName=(firstName+" "+lastName).trim();var email=helper.get_email();var city=helper.get_input("city").val()||"";var country=helper.get_input("country").val()||"";var line1=helper.get_input("address").val()||"";var line2=helper.get_input("address_2").val()||"";var postalCode=helper.get_input("postcode").val()||"";var state=helper.get_input("state").val()||"";var billingDetails={name:fullName,email:email,address:{city:city,country:country,line1:line1,line2:line2,postal_code:postalCode,state:state}};var receiptUrl=CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/"+response.data.donation_id+"/";if(response.data.is_recurring){stripe.confirmSetup({elements:sepa_direct_debit_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:billingDetails},return_url:receiptUrl},redirect:"if_required"}).then(function(setupResult){if(setupResult.error){helper.add_error(setupResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_subscription_sepa_direct_debit",nonce:CHARITABLE_STRIPE_VARS.nonce,payment_method:setupResult.setupIntent.payment_method,customer_id:response.data.customer_id,donation_id:response.data.donation_id,donation_plan_id:response.data.donation_plan_id},success:function(subResponse){if(!subResponse.success){helper.add_error(subResponse.data&&subResponse.data.message||"Failed to create subscription");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}window.location.href=receiptUrl},error:function(xhr,status,error){helper.add_error("Failed to create subscription: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})});return}stripe.confirmPayment({elements:sepa_direct_debit_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:billingDetails}},return_url:receiptUrl}).then(function(result){if(result.error){helper.add_error(result.error.message)}helper.remove_pending_process_by_name("stripe");processingFlag=false})},error:function(xhr,status,error){helper.add_error("Failed to process payment: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})})};var process_ach_direct_debit=function(event,helper){event.preventDefault();helper.add_pending_process("stripe");ach_direct_debit_elements.submit().then(async function(submitResult){if(submitResult.error){helper.add_error(submitResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent_ach_direct_debit",amount_in_cents:convertAmountToCents(helper.get_amount()),amount:helper.get_amount(),nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:helper.get_data()},success:function(response){if(!response.success){helper.add_error(response.data.message||"Failed to create payment intent");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}var firstName=helper.get_input("first_name").val()||"";var lastName=helper.get_input("last_name").val()||"";var fullName=(firstName+" "+lastName).trim();var email=helper.get_email();stripe.confirmPayment({elements:ach_direct_debit_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:{name:fullName,email:email}},return_url:CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/"+response.data.donation_id+"/"}}).then(function(result){if(result.error){helper.add_error(result.error.message)}helper.remove_pending_process_by_name("stripe");processingFlag=false})},error:function(xhr,status,error){helper.add_error("Failed to process payment: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})})};var process_becs_direct_debit=function(event,helper){event.preventDefault();helper.add_pending_process("stripe");becs_debit_elements.submit().then(async function(submitResult){if(submitResult.error){helper.add_error(submitResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent_becs_direct_debit",amount_in_cents:convertAmountToCents(helper.get_amount()),amount:helper.get_amount(),nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:helper.get_data()},success:function(response){if(!response.success){helper.add_error(response.data.message||"Failed to create payment intent");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}var firstName=helper.get_input("first_name").val()||"";var lastName=helper.get_input("last_name").val()||"";var fullName=(firstName+" "+lastName).trim();var email=helper.get_email();stripe.confirmPayment({elements:becs_debit_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:{name:fullName,email:email}},return_url:CHARITABLE_STRIPE_VARS.home_url+"/"+CHARITABLE_STRIPE_VARS.donation_receipt_path+"/"+response.data.donation_id+"/"}}).then(function(result){if(result.error){helper.add_error(result.error.message)}helper.remove_pending_process_by_name("stripe");processingFlag=false})},error:function(xhr,status,error){helper.add_error("Failed to process payment: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})})};var process_cash_app=function(event,helper){event.preventDefault();var originalPageUrl=window.location.href;if(typeof sessionStorage!=="undefined"){sessionStorage.setItem("charitable_cash_app_original_page_url",originalPageUrl)}helper.add_pending_process("stripe");cash_app_elements.submit().then(async function(submitResult){if(submitResult.error){helper.add_error(submitResult.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}$.ajax({url:CHARITABLE_VARS.ajaxurl,type:"POST",data:{action:"charitable_stripe_create_payment_intent_cash_app",amount_in_cents:convertAmountToCents(helper.get_amount()),amount:helper.get_amount(),nonce:CHARITABLE_STRIPE_VARS.nonce,form_data:helper.get_data(),original_page_url:originalPageUrl},success:function(response){if(!response.success){helper.add_error(response.data.message||"Failed to create payment intent");helper.remove_pending_process_by_name("stripe");processingFlag=false;return}var firstName=helper.get_input("first_name").val()||"";var lastName=helper.get_input("last_name").val()||"";var fullName=(firstName+" "+lastName).trim();var email=helper.get_email();var donationId=response.data.donation_id;stripe.confirmPayment({elements:cash_app_elements,clientSecret:response.data.client_secret,confirmParams:{payment_method_data:{billing_details:{name:fullName,email:email}},return_url:window.location.href}}).then(function(result){if(result.error){helper.add_error(result.error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false;return}if(typeof sessionStorage!=="undefined"){sessionStorage.setItem("charitable_cash_app_donation_id",donationId)}}).catch(function(error){helper.add_error("Payment failed: "+error.message);helper.remove_pending_process_by_name("stripe");processingFlag=false})},error:function(xhr,status,error){helper.add_error("Failed to process payment: "+error);helper.remove_pending_process_by_name("stripe");processingFlag=false}})})};$body.on("charitable:form:validate.stripe",function(event,helper){if("make_donation"!==helper.get_input("charitable_action").val()){return}if(processingFlag){return}switch(helper.get_payment_method()){case"stripe_sepa_direct_debit":if(sepa_direct_debit_elements){processingFlag=true;return process_sepa_direct_debit(event,helper)}helper.add_error("SEPA payment method is not available. Please refresh and try again.");return;case"stripe_ach_direct_debit":if(ach_direct_debit_elements){processingFlag=true;return process_ach_direct_debit(event,helper)}helper.add_error("ACH payment method is not available. Please refresh and try again.");return;case"stripe_becs_direct_debit":if(becs_debit_elements){processingFlag=true;return process_becs_direct_debit(event,helper)}helper.add_error("BECS payment method is not available. Please refresh and try again.");return;case"stripe_cash_app":if(cash_app_elements){processingFlag=true;return process_cash_app(event,helper)}helper.add_error("Cash App payment method is not available. Please refresh and try again.");return;case"stripe":break;default:return}if("stripe"!==helper.get_payment_method()){return}event.preventDefault();if(""!==$errors.text()){if(helper.hasOwnProperty("prevent_scroll_to_top")){helper.prevent_scroll_to_top=true}helper.add_error($errors.text());helper.hide_processing();return}if(helper.errors.length===0){helper.add_pending_process("stripe");event.preventDefault();var email=helper.get_email(),phone=helper.get_input("phone"),address={city:helper.get_input("city").val(),country:helper.get_input("country").val(),line1:helper.get_input("address").val(),line2:helper.get_input("address_2").val(),postal_code:helper.get_input("postcode").val(),state:helper.get_input("state").val()},billingDetails={name:$card_name.val(),email:email,address:address};if(phone.length&&phone.val().length){billingDetails.phone=phone.val()}stripe.createPaymentMethod({type:"card",card:cardNumber,billing_details:billingDetails}).then(function(result){if(result.error){helper.add_error(result.error.message)}else{helper.get_input("stripe_payment_method").val(result.paymentMethod.id)}helper.remove_pending_process_by_name("stripe")})}});$body.on("charitable:form:processed.stripe",function(event,response,helper){if(!response.success){return}
36if(helper.is_recurring_donation()&&!response.requires_action){return}if("make_donation"!==helper.get_input("charitable_action").val()){return}if("stripe"!==helper.get_payment_method()){return}event.preventDefault();if(helper.errors.length===0){var new_stripe;helper.add_pending_process("stripe");if(should_process_payment_on_connected_account(helper)){new_stripe=Stripe(CHARITABLE_STRIPE_VARS.key,get_stripe_options(helper,true))}else{new_stripe=stripe}var cardElementToUse;if(typeof CHARITABLE_STRIPE_VARS!=="undefined"&&typeof CHARITABLE_STRIPE_VARS.cc_fields_format!=="undefined"&&"multiple"===CHARITABLE_STRIPE_VARS.cc_fields_format){cardElementToUse=typeof cardNumber!=="undefined"?cardNumber:null}else{cardElementToUse=typeof card_element!=="undefined"?card_element:null}new_stripe.confirmCardPayment(response.secret,{payment_method:{card:cardElementToUse,billing_details:{name:$card_name.val(),email:helper.get_email(),address:{city:helper.get_input("city").val(),country:helper.get_input("country").val(),line1:helper.get_input("address").val(),line2:helper.get_input("address_2").val(),postal_code:helper.get_input("postcode").val(),state:helper.get_input("state").val()}}}}).then(function(result){if(result.error){$(document).trigger("Charitable_Custom_Event__Handle_Card_Payment_Fail",[event,result,response,CHARITABLE_STRIPE_VARS,helper.get_payment_method()]);helper.add_error(result.error.message)}else{if(response.redirect_to){window.location.href=response.redirect_to}}helper.remove_pending_process_by_name("stripe")})}})}function cleanupStripeElements(){console.log("[Stripe] Cleaning up existing Stripe Elements");if(stripeElementInstances.card_element){try{stripeElementInstances.card_element.unmount();console.log("[Stripe] Unmounted card_element")}catch(e){console.error("[Stripe] Error unmounting card_element:",e.message)}stripeElementInstances.card_element=null}if(stripeElementInstances.expressCheckoutElement){try{stripeElementInstances.expressCheckoutElement.unmount();console.log("[Stripe] Unmounted expressCheckoutElement")}catch(e){console.error("[Stripe] Error unmounting expressCheckoutElement:",e.message)}stripeElementInstances.expressCheckoutElement=null}var otherElements=["ach_direct_debit_payment_element","sepa_direct_debit_payment_element","becs_debit_payment_element","cash_app_payment_element","canadian_debit_payment_element"];otherElements.forEach(function(elementName){if(stripeElementInstances[elementName]){try{stripeElementInstances[elementName].unmount();console.log("[Stripe] Unmounted "+elementName)}catch(e){console.error("[Stripe] Error unmounting "+elementName+":",e.message)}stripeElementInstances[elementName]=null}});var $cardField=$("#charitable_stripe_card_field");if($cardField.length){$cardField.empty();console.log("[Stripe] Cleared card field DOM")}}var isReinitializing=false;function reinitializeStripeElements(helper){if(isReinitializing){console.log("[Stripe] Already reinitializing, skipping duplicate call");return}console.log("[Stripe] Reinitializing Stripe Elements after form reload");console.log("[Stripe] Helper passed to reinitializeStripeElements:",helper);var $cardField=$("#charitable_stripe_card_field");var $cardNumberField=$("#charitable_stripe_card_number_field");if(!$cardField.length&&!$cardNumberField.length){console.log("[Stripe] Stripe card field not found, skipping reinitialization");return}var $gatewayRadios=$('input[name="gateway"][type="radio"]');var $stripeSelected=$('.charitable-gateway-tab input[value="stripe"]:checked, input[name="gateway"][value="stripe"]:checked');if($gatewayRadios.length&&!$stripeSelected.length){console.log("[Stripe] Stripe is not the active payment method, skipping reinitialization");return}console.log("[Stripe] All checks passed - proceeding with reinitialization");isReinitializing=true;setTimeout(function(){console.log("[Stripe] Starting cleanup and reinitialization");$body.off("charitable:form:validate.stripe").off("charitable:form:processed.stripe");cleanupStripeElements();if("checkout"===CHARITABLE_STRIPE_VARS.mode){console.log("[Stripe] Reinitializing Checkout_Handler");CharitableGatewayGuard.requireGlobal({gateway:"stripe",global:"Stripe",formSel:"#charitable-donation-form, .charitable-donation-form",run:function(){new Checkout_Handler}})}else{if(typeof CHARITABLE_STRIPE_VARS!=="undefined"&&typeof CHARITABLE_STRIPE_VARS.cc_fields_format!=="undefined"&&"multiple"===CHARITABLE_STRIPE_VARS.cc_fields_format){console.log("[
36Stripe] Reinitializing Payment_Intents_Handler_Multiple");CharitableGatewayGuard.requireGlobal({gateway:"stripe",global:"Stripe",formSel:"#charitable-donation-form, .charitable-donation-form",run:function(){new Payment_Intents_Handler_Multiple}})}else{console.log("[Stripe] Reinitializing Payment_Intents_Handler with helper");CharitableGatewayGuard.requireGlobal({gateway:"stripe",global:"Stripe",formSel:"#charitable-donation-form, .charitable-donation-form",run:function(){new Payment_Intents_Handler(helper)}})}}setTimeout(function(){isReinitializing=false;console.log("[Stripe] Reinitialization complete, flag reset");setTimeout(function(){console.log("[Stripe] Triggering height adjustment after reinitialization");$body.trigger("charitable:stripe:adjust-height")},300)},1e3)},100)}$body.on("charitable:form:initialize",function(event,helper){if("checkout"===CHARITABLE_STRIPE_VARS.mode){CharitableGatewayGuard.requireGlobal({gateway:"stripe",global:"Stripe",formSel:"#charitable-donation-form, .charitable-donation-form",run:function(){new Checkout_Handler}})}else{if(typeof CHARITABLE_STRIPE_VARS!=="undefined"&&typeof CHARITABLE_STRIPE_VARS.cc_fields_format!=="undefined"&&"multiple"===CHARITABLE_STRIPE_VARS.cc_fields_format){CharitableGatewayGuard.requireGlobal({gateway:"stripe",global:"Stripe",formSel:"#charitable-donation-form, .charitable-donation-form",run:function(){new Payment_Intents_Handler_Multiple}})}else{CharitableGatewayGuard.requireGlobal({gateway:"stripe",global:"Stripe",formSel:"#charitable-donation-form, .charitable-donation-form",run:function(){new Payment_Intents_Handler(helper)}})}}});$body.on("charitable:form:loaded",function(event,helper){if(isReinitializing){wpchar.debug("[Stripe] charitable:form:loaded - reinitialization in progress, skipping","stripe");return}if(!helper||!helper.form){wpchar.debug("charitable:form:loaded - no helper, skipping Stripe reinit","stripe");return}var $cardField=$("#charitable_stripe_card_field");var $stripeTab=$('.charitable-gateway-tab input[value="stripe"]:checked, input[name="gateway"][value="stripe"]:checked');if(!$cardField.length||!$stripeTab.length){wpchar.debug("charitable:form:loaded - no Stripe field or Stripe not selected, skipping reinit","stripe");return}var hasMountedElement=$cardField.find('.__PrivateStripeElement, iframe[src*="js.stripe.com"]').length>0;if(hasMountedElement){wpchar.debug("charitable:form:loaded - Stripe Element already mounted (initial load), skipping reinit","stripe");return}console.log("[Stripe] charitable:form:loaded - detected replaced form (empty Stripe field), reinitializing");reinitializeStripeElements(helper)});$body.on("charitable:form:replaced",function(event,helper){if(isReinitializing){wpchar.debug("[Stripe] charitable:form:replaced received but reinitialization in progress, skipping","stripe");return}if(!helper||!helper.form){wpchar.debug("[Stripe] charitable:form:replaced - no helper, skipping","stripe");return}console.log("[Stripe] charitable:form:replaced - reinitializing Stripe Elements");reinitializeStripeElements(helper)})})(jQuery);; 37CHARITABLE_RECURRING=function($){var methods={init:function(){$("html").addClass("js");$(".recurring-donation").find("input:checked").each(function(){$(this).addClass("selected")});$(".recurring-donation-amounts").on("click change","input[name=donation_amount]",function(){var $input=$(this);var $form=$input.closest("form");var $fallback=$form.find('input[name=donation_amount_fallback][data-recurring="true"]');if($fallback.length&&$input.val()&&$input.val()!=="recurring-custom"){$fallback.val($input.val());if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&CHARITABLE_RECURRING_VARS.form_debug&&typeof console!=="undefined"&&console.log){console.log("[Charitable Recurring] Updated fallback to:",$input.val())}}});$(".recurring-donation-options").on("change","input[name=recurring_donation]",function(event){CHARITABLE_RECURRING.toggle_tabs($(this))});$(".charitable-recurring-donation-options .recurring-donation-period [name=recurring_donation_period][value=once]").parent().addClass("one-time-d
37onation-period").hide();$(".recurring-donation-option").on("change","input[name=recurring_donation]",function(event){if($(this).is(":checked")){CHARITABLE_RECURRING.toggle_gateways()}else{CHARITABLE_RECURRING.toggle_gateways(true)}});$(".recurring-donation-options [name=recurring_donation]").change();CHARITABLE_RECURRING.init_stripe_payment_method_filtering()},toggle_tabs:function($radio){var $form=$radio.closest("form");$form.find(".recurring-donation-option").removeClass("selected");$("input[name=recurring_donation]:checked",$form).closest("li").addClass("selected");var val=$("input[name=recurring_donation]:checked",$form).val();if(val=="once"){$form.find(".charitable-recurring-donation-options").hide().removeClass("active");$form.find(".charitable-donation-options:not(.charitable-recurring-donation-options)").show().addClass("active");$form.find(".charitable-recurring-donation-options .recurring-donation-period .one-time-donation-period input").prop("checked",true);CHARITABLE_RECURRING.toggle_gateways(true);CHARITABLE_RECURRING.enable_all_stripe_payment_methods()}else{var $recurring_options=$form.find(".charitable-recurring-donation-options");if($recurring_options.length){$recurring_options.show().addClass("active");$form.find(".charitable-donation-options:not(.charitable-recurring-donation-options)").hide().removeClass("active")}else{$form.find(".charitable-donation-options:not(.charitable-recurring-donation-options)").show().addClass("active")}CHARITABLE_RECURRING.toggle_gateways();CHARITABLE_RECURRING.disable_incompatible_stripe_payment_methods()}},toggle_gateways:function(show_all){var show_all;if(typeof show_all==="undefined"){show_all=false}if(show_all==true){$("#charitable-gateway-selector li").show()}else{$("#charitable-gateway-selector").find("input").each(function(){if($.inArray($(this).val(),Charitable_Recurring.supported_gateways)!==-1){$(this).parent().show()}else{$(this).prop("checked",false).parent().hide()}})}},init_stripe_payment_method_filtering:function(){$(document).on("change","input[name=recurring_donation]",function(){CHARITABLE_RECURRING.handle_recurring_donation_change($(this))});$(document).on("change","input[name=recurring_donation_period]",function(){CHARITABLE_RECURRING.handle_recurring_donation_change($(this))});$(document).on("change",'input[name="gateway"]',function(){CHARITABLE_RECURRING.validate_donate_button_state()});$(document).on("charitable:gateway:changed",function(event,gatewayId){CHARITABLE_RECURRING.validate_donate_button_state()});$(document).on("submit",".charitable-donation-form",function(e){if(CHARITABLE_RECURRING.is_donate_button_disabled()){e.preventDefault();CHARITABLE_RECURRING.show_submission_alert();return false}});$(document).on("click",'button[type="submit"], input[type="submit"], .donate-button',function(e){if(CHARITABLE_RECURRING.is_donate_button_disabled()){e.preventDefault();CHARITABLE_RECURRING.show_submission_alert();return false}});CHARITABLE_RECURRING.check_recurring_donation_state();setTimeout(function(){CHARITABLE_RECURRING.check_recurring_donation_state()},500)},handle_recurring_donation_change:function($input){var $form=$input.closest("form");var is_recurring=CHARITABLE_RECURRING.is_recurring_donation_selected($form);if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Recurring donation change detected");console.log("Input value:",$input.val());console.log("Is recurring:",is_recurring)}if(is_recurring){CHARITABLE_RECURRING.disable_incompatible_stripe_payment_methods();if(CHARITABLE_RECURRING.has_incompatible_gateways_on_form()){CHARITABLE_RECURRING.show_recurring_warning_message()}else{CHARITABLE_RECURRING.hide_recurring_warning_message()}}else{CHARITABLE_RECURRING.enable_all_stripe_payment_methods();CHARITABLE_RECURRING.hide_recurring_warning_message()}CHARITABLE_RECURRING.validate_donate_button_state()},is_recurring_donation_selected:function($form){var $recurring_input=$form.find("input[name=recurring_donation]:checked");if($recurring_input.length===0){return false}var value=$recurring_input.val();if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Recurring donation value:",value)}return value!="once"&&value!=""&&value!=undefined},check_recurring_donation_state:function(){var $form=$(".charitable-donation-form");if($form.length===0){return}var is_recurring=CHARITABLE_RECURRING.is_recurring_donation_selected($form);
37if(is_recurring){CHARITABLE_RECURRING.disable_incompatible_stripe_payment_methods();if(CHARITABLE_RECURRING.has_incompatible_gateways_on_form()){CHARITABLE_RECURRING.show_recurring_warning_message()}else{CHARITABLE_RECURRING.hide_recurring_warning_message()}}else{CHARITABLE_RECURRING.enable_all_stripe_payment_methods();CHARITABLE_RECURRING.hide_recurring_warning_message()}CHARITABLE_RECURRING.validate_donate_button_state()},disable_incompatible_stripe_payment_methods:function(){var incompatible_methods=["stripe_ach_direct_debit","stripe_becs_direct_debit","stripe_cash_app"];if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.disable_offline_for_recurring){incompatible_methods.push("offline")}incompatible_methods.forEach(function(method_id){var $tab=$('.charitable-gateway-tab[data-gateway-id="'+method_id+'"]');var $radio=$('input[value="'+method_id+'"]');if($tab.length>0){$tab.addClass("disabled-for-recurring");$tab.attr("title","This payment method is not available for recurring donations");if($radio.is(":checked")){$radio.prop("checked",false).trigger("change")}}});$("#charitable-gateway-selector li").each(function(){var $li=$(this);var $input=$li.find('input[type="radio"]');var gateway_value=$input.val();if(incompatible_methods.indexOf(gateway_value)!==-1){$li.addClass("disabled-for-recurring");$li.attr("title","This payment method is not available for recurring donations");if($input.is(":checked")){$input.prop("checked",false).trigger("change")}}})},enable_all_stripe_payment_methods:function(){$(".charitable-gateway-tab.disabled-for-recurring").removeClass("disabled-for-recurring").removeAttr("title");$("#charitable-gateway-selector li.disabled-for-recurring").removeClass("disabled-for-recurring").removeAttr("title")},show_recurring_warning_message:function(){if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Showing recurring payment warning message")}var $warning=$(".charitable-recurring-payment-method-warning");if($warning.length===0){var warning_message=CHARITABLE_RECURRING.get_warning_message();$warning=$('<div class="charitable-recurring-payment-method-warning charitable-notice charitable-notice-warning">'+"<p><strong>Note:</strong> "+warning_message+"</p></div>");var $gateway_tabs=$("#charitable-gateway-tabs");if($gateway_tabs.length>0){$gateway_tabs.before($warning)}else{var $gateway_selector=$("#charitable-gateway-selector");if($gateway_selector.length>0){$gateway_selector.before($warning)}else{$("#charitable-gateway-fields").prepend($warning)}}}$warning.show();$warning.css({width:"100%",display:"block","box-sizing":"border-box"})},hide_recurring_warning_message:function(){if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Hiding recurring payment warning message");console.log("Warning elements found:",$(".charitable-recurring-payment-method-warning").length)}$(".charitable-recurring-payment-method-warning").remove()},validate_donate_button_state:function(){var $form=$(".charitable-donation-form");var is_recurring=this.is_recurring_donation_selected($form);var $submit_button=$form.find('button[type="submit"], input[type="submit"], .donate-button');if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("validate_donate_button_state called");console.log("Form found:",$form.length);console.log("Submit button found:",$submit_button.length);console.log("Is recurring:",is_recurring);console.log("Submit button disabled:",$submit_button.prop("disabled"));console.log("Submit button classes:",$submit_button.attr("class"))}if(is_recurring){var selected_gateway=this.get_selected_gateway($form);var incompatible_methods=["stripe_ach_direct_debit","stripe_becs_direct_debit","stripe_cash_app"];if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.disable_offline_for_recurring){incompatible_methods.push("offline")}if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Selected gateway:",selected_gateway);console.log("Incompatible methods:",incompatible_methods);console.log("Is incompatible:",incompatible_methods.indexOf(selected_gateway)!==-1)}if(incompatible_methods.indexOf(selected_gateway)!==-1){$submit_button.prop("disabled",true).addClass("disabled-for-recurring");this.show_donate_button_error();if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Button disabled and error shown")}}
37else{$submit_button.prop("disabled",false).removeClass("disabled-for-recurring");this.hide_donate_button_error();if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Button enabled and error hidden")}}}else{$submit_button.prop("disabled",false).removeClass("disabled-for-recurring");this.hide_donate_button_error();if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Not recurring - button enabled")}}},get_selected_gateway:function($form){if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("=== Gateway Detection Debug ===");console.log("All gateway inputs:",$form.find('input[name="gateway"]').length);console.log("All gateway fields:",$form.find(".charitable-gateway-fields").length);console.log("All gateway tabs:",$form.find(".charitable-gateway-tab").length);console.log("Visible gateway fields:",$form.find(".charitable-gateway-fields:visible").length)}var $gateway_input=$form.find('input[name="gateway"]:checked');if($gateway_input.length){if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log('Gateway found via input[name="gateway"]:',$gateway_input.val())}return $gateway_input.val()}var $gateway_fields=$form.find(".charitable-gateway-fields[data-gateway]");if($gateway_fields.length){var gateway=$gateway_fields.filter(":visible").first().attr("data-gateway");if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Gateway found via data-gateway attribute:",gateway)}return gateway}var $active_tab=$form.find(".charitable-gateway-tab.active, .charitable-gateway-tab.selected");if($active_tab.length){var gateway=$active_tab.attr("data-gateway-id")||$active_tab.attr("id");if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Gateway found via active tab:",gateway)}return gateway}var $visible_fields=$form.find(".charitable-gateway-fields:visible");if($visible_fields.length){var gateway=$visible_fields.first().attr("data-gateway");if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Gateway found via visible fields:",gateway)}return gateway}var $any_gateway_input=$form.find('input[name*="gateway"], input[name*="payment"], input[name*="stripe"]');if($any_gateway_input.length){if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("Found inputs with gateway-related names:",$any_gateway_input.map(function(){return this.name+"="+this.value}).get())}}if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.debug_enabled&&typeof console!=="undefined"&&console.log){console.log("No gateway detected")}return""},is_donate_button_disabled:function(){var $form=$(".charitable-donation-form");var $submit_button=$form.find('button[type="submit"], input[type="submit"], .donate-button');return $submit_button.hasClass("disabled-for-recurring")||$submit_button.prop("disabled")},show_submission_alert:function(){alert("The selected payment method is not available with recurring donations at this time. Please choose a different payment method.")},show_donate_button_error:function(){if($(".charitable-recurring-payment-method-error").length){return}var $error=$('<div class="charitable-recurring-payment-method-error charitable-notice charitable-notice-error">'+"<p>The selected payment method is not available with recurring donations at this time. Please choose a different payment method.</p>"+"</div>");var $form=$(".charitable-donation-form");$form.find('button[type="submit"], input[type="submit"], .donate-button').after($error)},hide_donate_button_error:function(){$(".charitable-recurring-payment-method-error").remove()},has_incompatible_gateways_on_form:function(){var incompatible_methods=["stripe_ach_direct_debit","stripe_becs_direct_debit","stripe_cash_app"];if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.disable_offline_for_recurring){incompatible_methods.push("offline")}var found=false;incompatible_methods.forEach(function(method_id){if($('.charitable-gateway-tab[data-gateway-id="'+method_id+'"]').length>0){found=true}if($('input[name="gateway"][value="'+method_id+'"]').length>0){found=true}if($('#charitable-gateway-selector input[value="'+method_id+'"]').length>0){found=true}});return found},get_warning_message:function(){if(typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.warning_message){return CHARITABLE_RECURRING_VARS.warning_message}var include_offline=typeof CHARITABLE_RECURRING_VARS!=="undefined"&&CHARITABLE_RECURRING_VARS.disable_offline_for_recurring;if(include_offline){return"Some payment methods (ACH, BECS, Cash App, and offline/check payments) are not available for recurring donations only. Please select a different payment method to continue."}else{return"Some payment methods (ACH, BECS, and Cash App) are not available for recurring donations only. Please select a different payment method to continue."}}};return methods}(jQuery);(function($){$("body").on("charitable:form:initialize",function(){CHARITABLE_RECURRING.init(
37)})})(jQuery);; 38CHARITABLE=window.CHARITABLE||{},function(e){var t=function(e){var t=parseInt(CHARITABLE_VARS.fee_relief_display_decimals,10);if(isNaN(t)){var a=parseInt(CHARITABLE_VARS.currency_format_num_decimals,10);t=isNaN(a)?2:Math.max(2,a)}return accounting.formatMoney(e,{symbol:CHARITABLE_VARS.currency_symbol,decimal:CHARITABLE_VARS.currency_format_decimal_sep,thousand:CHARITABLE_VARS.currency_format_thousand_sep,precision:t,format:CHARITABLE_VARS.currency_format}).trim()},a=function(e){this.helper=e,a.prototype.get_gateway_config=function(){var e=this.helper.get_payment_method();return!!CHARITABLE_VARS.fee_relief.hasOwnProperty(e)&&CHARITABLE_VARS.fee_relief[e]},a.prototype.get_subtotal=function(){return this.helper.__proto__.hasOwnProperty("get_subtotal")?this.helper.get_subtotal():this.helper.get_amount()},a.prototype.get_fee=function(e){return void 0===e&&(e=!0),this.apply_fees(e)?this.get_total(e)-this.get_subtotal():0},a.prototype.get_total=function(e){void 0===e&&(e=!0);var t=this.get_subtotal(),a=0;if(!this.apply_fees(e))return t;void 0!==CHARITABLE_VARS.calculate_giftaid&&""!==CHARITABLE_VARS.calculate_giftaid&&this.helper.form.find('input[name="giftaid"]').is(":checked")&&(a=.25*t);var n=this.get_gateway_config(),o=(t+n.fixed)/((100-n.percentage)/100),i=t+parseFloat(n.fixed)+parseFloat(t*(.01*n.percentage));return o+=a,void 0===CHARITABLE_VARS.fee_relief_calculation_type||null===CHARITABLE_VARS.fee_relief_calculation_type||""===CHARITABLE_VARS.fee_relief_calculation_type||1!==CHARITABLE_VARS.fee_relief_calculation_type&&"1"!==CHARITABLE_VARS.fee_relief_calculation_type?0+parseFloat(o.toFixed(2)):0+parseFloat(i.toFixed(2))},a.prototype.apply_fees=function(e){void 0===e&&(e=!0);var t=this.get_gateway_config();return t&&t.enabled&&(!e||this.is_donor_paying_fee())},a.prototype.is_donor_paying_fee=function(){var e=this.helper.form.find('input[name="cover_fees"]');switch(e.attr("type")){case"hidden":return!0;case"checkbox":return e.is(":checked")}}},n=e("body"),o=!1;n.on("charitable:form:get_amount",function(e,t){if(!o){o=!0;var n=new a(t).get_fee();t.add_amount(n),setTimeout(function(){o=!1},100)}}),n.on("charitable:form:loaded",function(o,i){if("make_donation"===i.form.find("[name=charitable_action]").val()){new a(i);var r=i.form.find("[name=cover_fees]").parent(),f=i.form.find(".charitable-donation-amount-custom"),c=i.form.find(".fee-relief .charitable-donation-total");c.length||(c=i.form.find(".charitable-donation-total"));i.form.find("#charitable_field_giftaid_element");var l=function(){r.length&&r.addClass("charitable-hidden")},u=function(){n.trigger("charitable:form:amount:changed",i),n.trigger("charitable:form:total:changed",i)},_=i.form[0];
38e(document).on("charitable:form:amount:changed",function(e,n){n&&n.form&&n.form[0]===_&&function(e,n){setTimeout(function(){var e,o,i,c=new a(n),u=c.get_gateway_config();l(),u&&u.enabled&&0!==(i=c.get_subtotal())&&""!==i&&null!=i&&(e=n.get_payment_method(),n.form.find("label[for=gateway-"+e+"]"),o=n.form.find("label[for=gateway-"+e+"] .charitable-gateway-label").text().trim(),f.length&&(f.find(".gateway").text(o),f.find(".subtotal").html(n.format_amount(i,CHARITABLE_VARS.currency_symbol)),f.find(".fee-amount").html(t(c.get_fee(!1)))),r.find(".gateway").text(o),r.find(".fee-amount").html(t(c.get_fee(!1))),r.removeClass("charitable-hidden"))},500)}(0,n)}),e(document).on("charitable:form:total:changed",function(e,n){n&&n.form&&n.form[0]===_&&function(e,n){setTimeout(function(){var e=new a(n),o=e.get_subtotal();if(0!==o&&""!==o&&null!=o){var i=e.get_total(),r=e.apply_fees()?t(i):n.format_amount(i,CHARITABLE_VARS.currency_symbol);c.find(".total-amount").text(r),c.removeClass("charitable-hidden")}else c.addClass("charitable-hidden")},500)}(0,n)}),i.form.on("change",'input[name="gateway"]',u),i.form.on("change",'input[name="cover_fees"]',u),i.form.on("change",'input[name="giftaid"]',u),CHARITABLE.hasOwnProperty("VersionCompare")&&-1!==CHARITABLE.VersionCompare("1.6.19")||(i.form.on("change",'input[name="donation_amount"]',u),i.form.on("change",'input[name="custom_donation_amount"]',u)),i.form.on("click",".charitable-amount-selector .charitable-amount",function(){setTimeout(function(){u()},100)}),i.form.on("input",'input[name="custom_donation_amount"]',function(){setTimeout(function(){u()},100)}),i.form.on("change",'input[name="donation_amount"]',function(){setTimeout(function(){u()},100)}),i.form.on("change",".charitable-form-field input, .charitable-form-field select",function(){var t=e(this).attr("name");t&&(t.includes("donation")||t.includes("amount")||t.includes("gateway"))&&setTimeout(function(){u()},100)}),l(),c.addClass("charitable-hidden"),setTimeout(function(){u()},1e3)}})}(jQuery);; 39(function($){"use strict";(function(){var search=window.location.search;var isDebug=search.indexOf("visual_debug=true")!==-1||search.indexOf("debug_visual=true")!==-1;if(isDebug){console.log("[ConditionalLogic] Script file loaded and executing");console.log("[ConditionalLogic] Current URL:",window.location.href)}})();var CharitableConditionalLogic={initialized:false,debugMode:false,forms:{},rules:{},debugHistory:[],fieldValueHistory:{},init:function(){if(this.initialized){return}this.debugMode=this.isDebugMode();if(this.debugMode){console.log("[ConditionalLogic] Frontend script loaded");console.log("[ConditionalLogic] Debug mode enabled");console.log("[ConditionalLogic] jQuery available:",typeof $!=="undefined");console.log("[ConditionalLogic] CHARITABLE available:",typeof CHARITABLE!=="undefined")}$(document).ready($.proxy(this.onReady,this))},getUrlParameter:function(name){name=name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");var regex=new RegExp("[\\?&]"+name+"=([^&#]*)");var results=regex.exec(location.search);return results===null?"":decodeURIComponent(results[1].replace(/\+/g," "))},isDebugMode:function(){return this.getUrlParameter("visual_debug")==="true"||this.getUrlParameter("debug_visual")==="true"},onReady:function(){if(this.debugMode){console.log("[ConditionalLogic] DOM ready")}if(typeof charitable_conditional_logic==="undefined"){if(this.debugMode){console.warn("[ConditionalLogic] No conditional logic rules found")}return}this.rules=charitable_conditional_logic;if(this.debugMode){console.log("[ConditionalLogic] Rules loaded:",this.rules);console.log("[ConditionalLogic] Forms with conditionals:",Object.keys(this.rules))}for(var formId in this.rules){if(this.rules.hasOwnProperty(formId)){this.initForm(formId,this.rules[formId])}}$(document.body).on("charitable:form:amount:changed",$.proxy(this.onDonationAmountChanged,this));$(document).on("change",'.charitable-visual-donation-form input[name="donation_amount"]',$.proxy(this.onDonationAmountRadioChange,this));$(document).on("change input",'.charitable-visual-donation-form input.custom-donation-input, .charitable-visual-donation-form input[name="custom_donation_amount"]',$.proxy(this.onCustomAmountChange,this));$(document).on("change input",".charitable-visual-donation-form input, .charitable-visual-donation-form select, .charitable-visual-donation-form textarea",$.proxy(this.onFieldChange,this));if(this.debugMode){this.setupDebugMonitoring()}var self=this;setTimeout(function(){if(self.debugMode){console.log("[ConditionalLogic] Running initial evaluation")}self.readAllFieldValues();if(self.debugMode){self.printFormState("Initial Load")}self.evaluateAll()},200);this.initialized=true;if(this.debugMode){console.log("[ConditionalLogic] Initialization complete")}},initForm:function(formId,formRules){if(this.debugMode){console.log("[ConditionalLogic] Initializing form:",formId,formRules)}this.forms[formId]={rules:formRules,formElement:null};var $form=$(".charitable-visual-donation-form");if($form.length){this.forms[formId].formElement=$form.first()}},getDonationAmount:function(){var amount=0;var $amountInput=$('.charitable-visual-donation-form input[name="donation_amount"]:checked');if($amountInput.length){var amountVal=$amountInput.val();if(amountVal&&amountVal!=="custom"){amount=parseFloat(amountVal)||0}else if(amountVal==="custom"){var $customAmount=$('.charitable-visual-donation-form input.custom-donation-input, .charitable-visual-donation-form input[name="custom_donation_amount"]');
39if($customAmount.length&&$customAmount.val()){var customVal=$customAmount.val().replace(/[^0-9.]/g,"");if(customVal){amount=parseFloat(customVal)||0}}}}else{var $customAmount=$('.charitable-visual-donation-form input.custom-donation-input, .charitable-visual-donation-form input[name="custom_donation_amount"]');if($customAmount.length&&$customAmount.val()){var customVal=$customAmount.val().replace(/[^0-9.]/g,"");if(customVal){amount=parseFloat(customVal)||0}}}return amount},onDonationAmountChanged:function(event,helper){if(this.debugMode){console.log("[ConditionalLogic] Donation amount changed event received")}var amount=0;if(helper&&typeof helper.get_amount==="function"){amount=parseFloat(helper.get_amount())||0}else{amount=this.getDonationAmount()}if(this.debugMode){console.log("[ConditionalLogic] Donation amount:",amount)}this.updateFieldValue("donation_amount",amount);if(this.debugMode){this.logDebugEvent("donation_amount_updated",{amount:amount,source:"charitable:form:amount:changed",timestamp:(new Date).toISOString()})}this.evaluateAll();if(this.debugMode){this.printFormState("After donation amount change event")}},onDonationAmountRadioChange:function(event){if(this.debugMode){console.log("[ConditionalLogic] Donation amount radio changed:",$(event.target).val())}var amount=this.getDonationAmount();if(this.debugMode){console.log("[ConditionalLogic] Donation amount from radio:",amount)}this.updateFieldValue("donation_amount",amount);if(this.debugMode){this.logDebugEvent("donation_amount_updated",{amount:amount,source:"radio_change",timestamp:(new Date).toISOString()})}this.evaluateAll();if(this.debugMode){this.printFormState("After donation amount radio change")}},onCustomAmountChange:function(event){if(this.debugMode){console.log("[ConditionalLogic] Custom donation amount changed")}var $customRadio=$('.charitable-visual-donation-form input[name="donation_amount"][value="custom"]');if($customRadio.length&&$customRadio.is(":checked")){var amount=this.getDonationAmount();if(this.debugMode){console.log("[ConditionalLogic] Custom donation amount:",amount)}this.updateFieldValue("donation_amount",amount);if(this.debugMode){this.logDebugEvent("donation_amount_updated",{amount:amount,source:"custom_input_change",timestamp:(new Date).toISOString()})}this.evaluateAll();if(this.debugMode){this.printFormState("After custom donation amount change")}}},onFieldChange:function(event){var $field=$(event.target);var fieldName=$field.attr("name");var fieldType=$field.attr("type");var fieldValue;var actualFieldName=fieldName;if(fieldType==="checkbox"&&fieldName&&fieldName.indexOf("[]")!==-1){var $allCheckboxes=$('.charitable-visual-donation-form input[type="checkbox"][name="'+fieldName+'"]');var checkedValues=[];$allCheckboxes.each(function(){if($(this).is(":checked")){checkedValues.push($(this).val())}});actualFieldName=fieldName.replace(/\[\]$/,"");fieldValue=checkedValues;if(this.debugMode){console.log("[ConditionalLogic] Checkbox group changed:",actualFieldName,"=",fieldValue)}this.updateFieldValue(actualFieldName,fieldValue)}else{fieldValue=this.getFieldValue($field);if(this.debugMode){console.log("[ConditionalLogic] Field changed:",fieldName,"=",fieldValue)}if(fieldName){this.updateFieldValue(fieldName,fieldValue)}}if(this.debugMode){this.logDebugEvent("field_value_updated",{fieldName:actualFieldName,fieldValue:fieldValue,timestamp:(new Date).toISOString()})}this.evaluateAll();if(this.debugMode){this.printFormState("After field change: "+fieldName)}},getFieldValue:function($field){var type=$field.attr("type");var tagName=$field.prop("tagName").toLowerCase();var fieldName=$field.attr("name");if(tagName==="select"){var val=$field.val();return val||(Array.isArray(val)?[]:"")}else if(tagName==="textarea"){return $field.val()||""}else if(type==="checkbox"){if(fieldName&&fieldName.indexOf("[]")!==-1){var baseName=fieldName.replace(/\[\]$/,"");var $allCheckboxes=$('.charitable-visual-donation-form input[type="checkbox"][name="'+fieldName+'"]');var checkedValues=[];$allCheckboxes.each(function(){if($(this).is(":checked")){checkedValues.push($(this).val())}});return checkedValues}else{return $field.is(":checked")?$field.val():""}}else if(type==="radio"){return $field.is(":checked")?$field.val():""}else{return $field.val()||""}},updateFieldValue:function(fieldName,value){if(typeof this.fieldValues==="undefined"){this.fieldValues={}}this.fieldValues[fieldName]=value;if(this.debugMode){console.log("[ConditionalLogic] Updated field value:",fieldName,"=",value)}},readAllFieldValues:function(){if(this.debugMode){console.log("[ConditionalLogic] Reading all field values from DOM")}if(typeof this.fieldValues==="undefined"){this.fieldValues={}}var donationAmount=this.getDonationAmount();this.updateFieldValue("donation_amount",donationAmount);if(this.debugMode){console.log("[ConditionalLogic] Initial donation amount:",donationAmount);var $allAmounts=$('.charitable-visual-donation-form input[name="donation_amount"]');console.log("[ConditionalLogic] All donation amount inputs:",$allAmounts.length);$allAmounts.each(function(){var $input=$(this);console.log("[ConditionalLogic] - Value:",$input.val(),"Checked:",$input.is(":checked"),"ID:",$input.attr("id"))});var $customAmount=$('.charitable-visual-donation-form input.custom-donation-input, .charitable-visual-donation-form input[name="custom_donation_amount"]');
39if($customAmount.length){console.log("[ConditionalLogic] Custom amount input found, value:",$customAmount.val())}}var $form=$(".charitable-visual-donation-form");if($form.length){if(this.debugMode){console.log("[ConditionalLogic] Form found, scanning fields...")}var processedCheckboxGroups={};$form.find("input, select, textarea").each(function(){var $field=$(this);var fieldName=$field.attr("name");var fieldId=$field.attr("id");var fieldType=$field.attr("type");if(fieldName==="donation_amount"||fieldName==="custom_donation_amount"||fieldName==="charitable_donation_amount"){return}if(fieldType==="hidden"||fieldName==="_charitable_donation_nonce"||fieldName==="_wp_http_referer"||fieldName==="charitable_action"||fieldName==="campaign_id"||fieldName==="description"||fieldName==="ID"||fieldName==="gateway"||fieldName==="stripe_payment_method"){return}if(fieldName){if(fieldType==="checkbox"&&fieldName.indexOf("[]")!==-1){if(processedCheckboxGroups[fieldName]){return}processedCheckboxGroups[fieldName]=true;var $allCheckboxes=$form.find('input[type="checkbox"][name="'+fieldName+'"]');var checkedValues=[];$allCheckboxes.each(function(){if($(this).is(":checked")){checkedValues.push($(this).val())}});var baseName=fieldName.replace(/\[\]$/,"");this.updateFieldValue(baseName,checkedValues);if(this.debugMode){console.log("[ConditionalLogic] Read checkbox group value:",baseName,"=",checkedValues)}}else{var value=this.getFieldValue($field);this.updateFieldValue(fieldName,value);if(this.debugMode){console.log("[ConditionalLogic] Read field value:",fieldName,"=",value,"Type:",fieldType,"ID:",fieldId)}}}}.bind(this))}else{if(this.debugMode){console.warn("[ConditionalLogic] Form not found! Selector: .charitable-visual-donation-form")}}if(this.debugMode){console.log("[ConditionalLogic] Field values read:",Object.keys(this.fieldValues||{}));console.log("[ConditionalLogic] Field values cache:",this.fieldValues)}},getCurrentFieldValue:function(fieldId){var mappedId=this.mapFieldIdToHtml?this.mapFieldIdToHtml(fieldId):fieldId;if(this.debugMode&&mappedId!==fieldId){console.log("[ConditionalLogic] Mapping field ID:",fieldId,"->",mappedId)}if(this.fieldValues){if(mappedId!==fieldId&&this.fieldValues.hasOwnProperty(mappedId)){var mappedValue=this.fieldValues[mappedId];if(Array.isArray(mappedValue)){if(this.debugMode){console.log("[ConditionalLogic] Found array in cache with mapped ID:",mappedId,"=",mappedValue)}return mappedValue}if(mappedValue!==""&&mappedValue!==null&&mappedValue!==undefined){if(this.debugMode){console.log("[ConditionalLogic] Found value in cache with mapped ID:",mappedId,"=",mappedValue)}return mappedValue}}if(this.fieldValues.hasOwnProperty(fieldId)){var originalValue=this.fieldValues[fieldId];if(Array.isArray(originalValue)){if(this.debugMode){console.log("[ConditionalLogic] Found array in cache with original ID:",fieldId,"=",originalValue)}return originalValue}if(this.debugMode){console.log("[ConditionalLogic] Found value in cache with original ID:",fieldId,"=",originalValue)}if(originalValue!==""&&originalValue!==null&&originalValue!==undefined){return originalValue}}if(mappedId!==fieldId&&this.fieldValues.hasOwnProperty(mappedId)){if(this.debugMode){console.log("[ConditionalLogic] Found empty value in cache with mapped ID:",mappedId)}return this.fieldValues[mappedId]}if(this.debugMode){console.log("[ConditionalLogic] Value not found in cache for:",fieldId,"or",mappedId,"Available keys:",Object.keys(this.fieldValues))}}if(fieldId==="donation_amount"||fieldId==="charitable_donation_amount"){return this.getDonationAmount()}var $field=$('.charitable-visual-donation-form [name="'+fieldId+'"], .charitable-visual-donation-form #charitable_field_'+fieldId+'_element, .charitable-visual-donation-form [data-field-id="'+fieldId+'"]');if(!$field.length){$field=$('.charitable-visual-donation-form [name="'+mappedId+'"], .charitable-visual-donation-form #charitable_field_'+mappedId+"_element, .charitable-visual-donation-form #charitable_field_field_"+mappedId.replace("field_","")+"_element")}if($field.length){var value=this.getFieldValue($field.first());this.updateFieldValue(fieldId,value);return value}if(this.debugMode){console.warn("[ConditionalLogic] Field value not found for:",fieldId)}return""},evaluateAll:function(){if(this.debugMode){console.log("[ConditionalLogic] Evaluating all conditionals")}for(var formId in this.rules){if(this.rules.hasOwnProperty(formId)){this.evaluateForm(formId,this.rules[formId])}}},evaluateForm:function(formId,formRules){if(this.debugMode){console.log("[ConditionalLogic] Evaluating form:",formId,"Fields with rules:",Object.keys(formRules))}for(var fieldId in formRules){if(formRules.hasOwnProperty(fieldId)){if(this.debugMode){console.log("[ConditionalLogic] Processing field:",fieldId,"Rules:",formRules[fieldId])}this.evaluateField(fieldId,formRules[fieldId])}}},evaluateField:function(fieldId,fieldRules){if(!fieldRules||!fieldRules.conditionals){if(this.debugMode){console.warn("[ConditionalLogic] Field",fieldId,"has no conditionals or invalid rules:",fieldRules)}return}var conditionalType=fieldRules.conditional_type||"show";var conditionals=fieldRules.conditionals;if(this.debugMode){console.log("[ConditionalLogic] ===== Evaluating field:",fieldId,"=====");console.log("[ConditionalLogic] Conditional type:",conditionalType);console.log("[ConditionalLogic] Conditionals structure:",conditionals);console.log("[ConditionalLogic] Number of groups:",Object.keys(conditionals).length)}var shouldShow=false;var hasValidGroups=false;for(var groupId in conditionals){if(conditionals.hasOwnProperty(groupId)){var group=conditionals[groupId];if(!Array.isArray(group)||group.length===0){continue}hasValidGroups=true;if(this.debugMode){console.log("[ConditionalLogic] Evaluating group",groupId,"with",group.length,"rules")}
39var groupPasses=this.evaluateGroup(group);if(this.debugMode){console.log("[ConditionalLogic] Group",groupId,"passes:",groupPasses)}if(groupPasses){shouldShow=true;if(this.debugMode){console.log("[ConditionalLogic] Group",groupId,"passed, field should be shown (OR logic)")}break}}}if(conditionalType==="hide"){shouldShow=!shouldShow;if(this.debugMode){console.log('[ConditionalLogic] Conditional type is "hide", inverting result:',shouldShow)}}else{if(this.debugMode&&!shouldShow&&hasValidGroups){console.log('[ConditionalLogic] Condition failed with "show" type, field will be hidden')}}if(this.debugMode){console.log("[ConditionalLogic] Final decision for field",fieldId,"- should show:",shouldShow)}this.toggleField(fieldId,shouldShow);if(this.debugMode){this.logDebugEvent("field_visibility_decision",{fieldId:fieldId,shouldShow:shouldShow,conditionalType:conditionalType,fieldValue:this.getCurrentFieldValue(fieldId),timestamp:(new Date).toISOString()})}},evaluateGroup:function(group){if(!Array.isArray(group)||group.length===0){return false}for(var i=0;i<group.length;i++){var rule=group[i];if(!this.evaluateRule(rule)){return false}}return true},evaluateRule:function(rule){if(!rule||!rule.field||!rule.operator){if(this.debugMode){console.warn("[ConditionalLogic] Invalid rule:",rule)}return false}var fieldValue=this.getCurrentFieldValue(rule.field);var operator=rule.operator;var ruleValue=rule.value||"";if(this.debugMode){console.log("[ConditionalLogic] --- Evaluating rule ---");console.log("[ConditionalLogic] Trigger field:",rule.field);console.log("[ConditionalLogic] Operator:",operator);console.log("[ConditionalLogic] Rule value:",ruleValue);console.log("[ConditionalLogic] Actual field value:",fieldValue);console.log("[ConditionalLogic] Value type:",typeof fieldValue);console.log("[ConditionalLogic] Is array?",Array.isArray(fieldValue))}var isArray=Array.isArray(fieldValue);var isNumeric=!isArray&&!isNaN(parseFloat(fieldValue))&&isFinite(fieldValue);var fieldValueNum=isNumeric?parseFloat(fieldValue):0;var ruleValueNum=!isNaN(parseFloat(ruleValue))?parseFloat(ruleValue):0;var fieldValueStr=isArray?"":String(fieldValue).toLowerCase().trim();var ruleValueStr=String(ruleValue).toLowerCase().trim();if(this.debugMode){console.log("[ConditionalLogic] Numeric comparison?",isNumeric);if(isNumeric){console.log("[ConditionalLogic] Numeric values - Field:",fieldValueNum,"Rule:",ruleValueNum)}else{console.log("[ConditionalLogic] String values - Field:",fieldValueStr,"Rule:",ruleValueStr)}}var result=false;switch(operator){case"==":if(isArray){result=fieldValue.indexOf(ruleValue)!==-1||fieldValue.indexOf(ruleValueStr)!==-1}else{result=fieldValueStr===ruleValueStr}break;case"!=":if(isArray){result=fieldValue.indexOf(ruleValue)===-1&&fieldValue.indexOf(ruleValueStr)===-1}else{result=fieldValueStr!==ruleValueStr}break;case">":result=isNumeric&&fieldValueNum>ruleValueNum;break;case">=":result=isNumeric&&fieldValueNum>=ruleValueNum;break;case"<":result=isNumeric&&fieldValueNum<ruleValueNum;break;case"<=":result=isNumeric&&fieldValueNum<=ruleValueNum;break;case"contains":if(isArray){result=fieldValue.some(function(val){return String(val).toLowerCase().indexOf(ruleValueStr)!==-1})}else{result=fieldValueStr.indexOf(ruleValueStr)!==-1}break;case"starts_with":if(isArray){result=fieldValue.some(function(val){return String(val).toLowerCase().indexOf(ruleValueStr)===0})}else{result=fieldValueStr.indexOf(ruleValueStr)===0}break;case"ends_with":if(isArray){result=fieldValue.some(function(val){var valStr=String(val).toLowerCase();return valStr.indexOf(ruleValueStr)===valStr.length-ruleValueStr.length})}else{result=fieldValueStr.indexOf(ruleValueStr)===fieldValueStr.length-ruleValueStr.length}break;case"e":case"empty":if(isArray){result=fieldValue.length===0}else{result=!fieldValue||fieldValueStr===""}break;case"!e":case"!empty":if(isArray){result=fieldValue.length>0}else{result=fieldValue&&fieldValueStr!==""}break;default:if(this.debugMode){console.warn("[ConditionalLogic] Unknown operator:",operator)}result=false}if(this.debugMode){console.log("[ConditionalLogic] Rule result:",result)}return result}
39,mapFieldIdToHtml:function(fieldId){if(typeof fieldId==="string"&&fieldId.indexOf("field_")===0){return fieldId}var numericId=parseInt(fieldId,10);if(!isNaN(numericId)){return"field_"+numericId}return fieldId},toggleField:function(fieldId,show){var mappedFieldId=this.mapFieldIdToHtml(fieldId);var numericId=typeof fieldId==="string"&&fieldId.indexOf("field_")===0?fieldId.replace("field_",""):fieldId;if(this.debugMode){console.log("[ConditionalLogic] Toggling field - Original ID:",fieldId,"Mapped ID:",mappedFieldId,"Numeric ID:",numericId)}var selectors=['[data-field-id="'+fieldId+'"]','[data-field-id="'+mappedFieldId+'"]','[data-field-id="'+numericId+'"]','[data-charitable-field-id="'+fieldId+'"]','[data-charitable-field-id="'+mappedFieldId+'"]','input[name="'+mappedFieldId+'"]','input[name="field_'+numericId+'"]',"#charitable_field_"+mappedFieldId+"_element","#charitable_field_field_"+numericId+"_element","#charitable-form-field-"+numericId,'.charitable-fieldset:has(input[name="'+mappedFieldId+'"])',".charitable-fieldset:has(#charitable_field_"+mappedFieldId+"_element)",".charitable-fieldset:has(#charitable_field_field_"+numericId+"_element)"];var $field=null;for(var i=0;i<selectors.length;i++){try{var $found=$(selectors[i]);if($found.length){if($found.is("input, select, textarea")){$field=$found.closest(".charitable-fieldset");if(!$field.length){$field=$found.closest(".charitable-form-field").closest(".charitable-fieldset");if(!$field.length){$field=$found.closest("fieldset, .charitable-fieldset, .charitable-form-field")}}}else{$field=$found}if($field.length){if(this.debugMode){console.log("[ConditionalLogic] Field found using selector:",selectors[i])}break}}}catch(e){if(this.debugMode){console.warn("[ConditionalLogic] Selector failed:",selectors[i],e)}}}if(!$field||!$field.length){var $allInputs=$('.charitable-visual-donation-form input[name="'+mappedFieldId+'"], .charitable-visual-donation-form #charitable_field_'+mappedFieldId+"_element, .charitable-visual-donation-form #charitable_field_field_"+numericId+"_element");if($allInputs.length){$field=$allInputs.first().closest(".charitable-fieldset");if(!$field.length){$field=$allInputs.first().closest(".charitable-form-field").parent()}}}if(!$field||!$field.length){if(this.debugMode){console.warn("[ConditionalLogic] Field not found:",fieldId,"Mapped:",mappedFieldId,"Selectors tried:",selectors.length);console.warn("[ConditionalLogic] Available fields:",$(".charitable-visual-donation-form .charitable-fieldset").map(function(){var $fs=$(this);var name=$fs.find("input, select, textarea").first().attr("name");var id=$fs.find("input, select, textarea").first().attr("id");return name||id||"unknown"}).get())}return}if(this.debugMode){console.log("[ConditionalLogic] Toggling field:",fieldId,"Show:",show,"Element:",$field,"Element classes:",$field.attr("class"))}var wasPending=$field.hasClass("charitable-conditional-field-pending");$field.removeClass("charitable-conditional-field-pending");if(show){$field.stop(true,true).fadeIn(300);$field.removeClass("charitable-conditional-hidden");$field.find("input, select, textarea").each(function(){var $input=$(this);if($input.attr("data-original-required")==="true"||$input.data("original-required")===true){$input.prop("required",true)}else if($field.hasClass("required-field")){$input.prop("required",true)}})}else{$field.find("input, select, textarea").each(function(){var $input=$(this);if(!$(this).data("original-required-set")){var wasRequired=$input.prop("required")||$input.is("[required]");if(wasRequired){$input.attr("data-original-required","true");$input.data("original-required",true)}else{$input.attr("data-original-required","false");$input.data("original-required",false)}$input.data("original-required-set",true)}});if(wasPending){$field.hide()}else{$field.stop(true,true).fadeOut(300)}$field.addClass("charitable-conditional-hidden");$field.find("input, select, textarea").prop("required",false)}},setupDebugMonitoring:function(){var self=this;$(document).on("click",".charitable-visual-donation-form",function(e){var $target=$(e.target);var tagName=$target.prop("tagName");var type=$target.attr("type");var name=$target.attr("name");var value=$target.attr("value")||$target.val();var id=$target.attr("id");var eventData={event:"click",tag:tagName,type:type,name:name,value:value,id:id,classes:$target.attr("class"),timestamp:(new Date).toISOString()};self.logDebugEvent("user_interaction",eventData);if(name==="donation_amount"){setTimeout(function(){var checked=$('.charitable-visual-donation-form input[name="donation_amount"]:checked');var checkedValue=checked.length?checked.val():"none";var amount=self.getDonationAmount();self.logDebugEvent("donation_amount_selected",{selectedValue:checkedValue,calculatedAmount:amount,timestamp:(new Date).toISOString()});self.printFormState("After donation amount selection")},50)}});$(document).on("change input",".charitable-visual-donation-form *",function(e){var $target=$(e.target);var fieldName=$target.attr("name");var oldValue=self.fieldValueHistory[fieldName]||"";var newValue=$target.val()||"";if(oldValue!==newValue){self.logDebugEvent("field_value_changed",{fieldName:fieldName,oldValue:oldValue,newValue:newValue,type:$target.attr("type"),tag:$target.prop("tagName"),id:$target.attr("id"),timestamp:(new Date).toISOString()});self.fieldValueHistory[fieldName]=newValue}});window.dumpConditionalLogicState=function(){self.printFormState("Manual dump")};window.getConditionalLogicHistory=function(){return self.debugHistory};window.clearConditionalLogicHistory=function(){self.debugHistory=[];
39self.fieldValueHistory={};console.log("[ConditionalLogic] Debug history cleared")}},logDebugEvent:function(eventType,data){if(!this.debugMode){return}var event={type:eventType,data:data,timestamp:(new Date).toISOString()};this.debugHistory.push(event);if(this.debugHistory.length>100){this.debugHistory.shift()}console.log("[ConditionalLogic] ["+eventType+"]",data)},printFormState:function(context){if(!this.debugMode){return}console.group("[ConditionalLogic] ===== FORM STATE: "+(context||"Current")+" =====");console.group("ð Current Field Values:");var fieldValues={};for(var fieldName in this.fieldValues){if(this.fieldValues.hasOwnProperty(fieldName)){fieldValues[fieldName]=this.fieldValues[fieldName]}}fieldValues["donation_amount"]=this.getDonationAmount();console.table(fieldValues);console.groupEnd();console.group("ð Conditional Logic Rules:");for(var formId in this.rules){if(this.rules.hasOwnProperty(formId)){console.group("Form: "+formId);for(var fieldId in this.rules[formId]){if(this.rules[formId].hasOwnProperty(fieldId)){var fieldRules=this.rules[formId][fieldId];console.group("Field "+fieldId+" ("+(fieldRules.conditional_type||"show")+"):");console.log("Rules:",fieldRules);if(fieldRules.conditionals){for(var groupId in fieldRules.conditionals){if(fieldRules.conditionals.hasOwnProperty(groupId)){var group=fieldRules.conditionals[groupId];console.group("Group "+groupId+":");for(var i=0;i<group.length;i++){var rule=group[i];var triggerValue=this.getCurrentFieldValue(rule.field);console.log("Rule "+(i+1)+":",{triggerField:rule.field,triggerValue:triggerValue,operator:rule.operator,compareValue:rule.value,passes:this.evaluateRule(rule)})}console.groupEnd()}}}console.groupEnd()}}console.groupEnd()}}console.groupEnd();console.group("ðï¸ Field Visibility Status:");for(var formId in this.rules){if(this.rules.hasOwnProperty(formId)){for(var fieldId in this.rules[formId]){if(this.rules[formId].hasOwnProperty(fieldId)){var $field=this.findFieldElement(fieldId);var isVisible=$field&&$field.length&&$field.is(":visible");console.log("Field "+fieldId+":",isVisible?"â
VISIBLE":"â HIDDEN")}}}}console.groupEnd();if(this.debugHistory.length>0){console.group("ð Recent Events (last 10):");var recentEvents=this.debugHistory.slice(-10);recentEvents.forEach(function(event,index){console.log("["+(index+1)+"]",event.type,"at",event.timestamp,":",event.data)});console.groupEnd()}console.groupEnd()},findFieldElement:function(fieldId){var mappedFieldId=this.mapFieldIdToHtml(fieldId);var numericId=typeof fieldId==="string"&&fieldId.indexOf("field_")===0?fieldId.replace("field_",""):fieldId;var selectors=['[data-field-id="'+fieldId+'"]','[data-field-id="'+mappedFieldId+'"]','[data-charitable-field-id="'+fieldId+'"]','input[name="'+mappedFieldId+'"]',"#charitable_field_"+mappedFieldId+"_element"];for(var i=0;i<selectors.length;i++){var $found=$(selectors[i]);if($found.length){if($found.is("input, select, textarea")){return $found.closest(".charitable-fieldset")}return $found}}return $()}};CharitableConditionalLogic.init();window.CharitableConditionalLogic=CharitableConditionalLogic})(jQuery);;
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.