/* global jQuery, jpSimplePaymentsStrings, confirm, _ */
/* eslint no-var: 0, quote-props: 0 */
( function ( api, wp, $ ) {
var $document = $( document );
$document.ready( function () {
$document.on( 'widget-added', function ( event, widgetContainer ) {
if ( widgetContainer.is( '[id*="jetpack_simple_payments_widget"]' ) ) {
initWidget( widgetContainer );
}
} );
$document.on( 'widget-synced widget-updated', function ( event, widgetContainer ) {
//this fires for all widgets, this prevent errors for non SP widgets
if ( ! widgetContainer.is( '[id*="jetpack_simple_payments_widget"]' ) ) {
return;
}
event.preventDefault();
syncProductLists();
var widgetForm = widgetContainer.find( '> .widget-inside > .form, > .widget-inside > form' );
enableFormActions( widgetForm );
updateProductImage( widgetForm );
} );
} );
function initWidget( widgetContainer ) {
var widgetForm = widgetContainer.find( '> .widget-inside > .form, > .widget-inside > form' );
//Add New Button
widgetForm
.find( '.jetpack-simple-payments-add-product' )
.on( 'click', showAddNewForm( widgetForm ) );
//Edit Button
widgetForm
.find( '.jetpack-simple-payments-edit-product' )
.on( 'click', showEditForm( widgetForm ) );
//Select an Image
widgetForm
.find(
'.jetpack-simple-payments-image-fieldset .placeholder, .jetpack-simple-payments-image > img'
)
.on( 'click', selectImage( widgetForm ) );
//Remove Image Button
widgetForm
.find( '.jetpack-simple-payments-remove-image' )
.on( 'click', removeImage( widgetForm ) );
//Save Product button
widgetForm
.find( '.jetpack-simple-payments-save-product' )
.on( 'click', saveChanges( widgetForm ) );
//Cancel Button
widgetForm
.find( '.jetpack-simple-payments-cancel-form' )
.on( 'click', clearForm( widgetForm ) );
//Delete Selected Product
widgetForm
.find( '.jetpack-simple-payments-delete-product' )
.on( 'click', deleteProduct( widgetForm ) );
//Input, Select and Checkbox change
widgetForm.find( 'select, input, textarea, checkbox' ).on(
'change input propertychange',
_.debounce( function () {
disableFormActions( widgetForm );
}, 250 )
);
}
function syncProductLists() {
var request = wp.ajax.post( 'customize-jetpack-simple-payments-buttons-get', {
'customize-jetpack-simple-payments-nonce':
api.settings.nonce[ 'customize-jetpack-simple-payments' ],
customize_changeset_uuid: api.settings.changeset.uuid,
} );
request.done( function ( data ) {
var selectedProduct = 0;
$( document )
.find( 'select.jetpack-simple-payments-products' )
.each( function ( index, select ) {
var $select = $( select );
selectedProduct = $select.val();
$select.find( 'option' ).remove();
$select.append(
$.map( data, function ( product ) {
return $( '