jQuery( document ).ready(function( $ ) {

	// Save settings
	$( document ).on( 'click', '.js-save-requests-notifications', function( e ) {

		e.preventDefault();

		var this_form = $( this ).parents( '.ui.form' );

		jQuery.ajax({
			type : "POST",
			url  : wpj_vars.ajaxurl,
			data : "action=save_requests_notifications_action&" + this_form.serialize(),
			beforeSend: function() {
				this_form.addClass( 'loading' );
			},
			success: function( response ) {
				$( '.js-save-requests-notifications' ).notify( wpj_vars.success_saved, { position: 'right', className: 'success' } );
			},
			complete: function() {
				this_form.removeClass( 'loading' );
			}
		});
	});

});

Hooks.add_action( 'wpj_after_form_added_to_page_builder', wpj_sn_add_form_to_requests_notifications_page );
function wpj_sn_add_form_to_requests_notifications_page() {
	if ( jQuery( '.js-requests-notifications-wrapper' )[0] && jQuery( '.kt-inside-inner-col' )[0] )
		jQuery( '.js-requests-notifications-wrapper' ).find( '.kt-inside-inner-col:first > *' ).wrapAll( '<form method="POST" class="ui form"></form>' );
}

Hooks.add_action( 'wpj_after_page_load_without_refresh', wpj_sn_init_scripts );
function wpj_sn_init_scripts() {

	// Enable location
	if ( jQuery( '.js-sn-enable-location' )[0] ) {
		jQuery( '.js-sn-enable-location' ).parent().checkbox({
			onChecked: function () { jQuery( '.js-location-wrapper input' ).prop( 'disabled', false ); },
			onUnchecked: function () { jQuery( '.js-location-wrapper input' ).prop( 'disabled', true ); },
			fireOnInit: true
		});
	}

	// Select all categories
	if ( jQuery( '.js-sn-enable-all-categories' )[0] ) {

		jQuery( '.js-sn-enable-all-categories' ).parent().checkbox({
			onChecked() {
				const options = jQuery( '.js-sn-categories option' ).toArray().map( (obj) => obj.value );
				jQuery( '.js-sn-categories' ).dropdown( 'set selected', options );
			},

			onUnchecked() {
				jQuery( '.js-categories-wrapper .menu .item' ).each( function() {
					jQuery( this ).removeClass( 'selected' ).removeClass( 'active' ).removeClass( 'filtered' );
				});

				jQuery( '.js-categories-wrapper .ui.label' ).each( function() {
					jQuery( this ).remove();
				});

				jQuery( '.js-sn-categories' ).dropdown( 'clear' );
			}

		});

	}
}