jQuery( document ).ready( function( $ ) {
	// Prevent multiple clicks for payment buttons
	var is_button_clicked = false;

	$( document ).one( 'click', '.payment-buttons .text-button', function( e ) {
		if ( ! is_button_clicked && $( this ).attr( 'onclick' ).includes( 'take_to_gateway' ) ) {
			is_button_clicked = true;

			addLoader( $( this ).parents( '.wp-block-kadence-column:first' ) );

			setTimeout(function() { is_button_clicked = false; }, 5000);
		}
	});

	// Cancel topup order
	$( document ).on( 'click', '.js-topup-order-cancel-button', function( e ) {
		e.preventDefault();

		var orderid    = window.location.pathname.split( '/' ).filter( Boolean ).pop();
		var method     = $( '.js-payment-method' ).attr( 'data-method' );
		var package_id = $( '.js-package-id' ).attr( 'data-package-id' );

		take_to_gateway_topup_process( 'cancel', orderid, method, package_id );
	});

	// Process topup order
	$( document ).on( 'click', '.js-topup-order-process-button', function( e ) {
		e.preventDefault();

		var orderid    = window.location.pathname.split( '/' ).filter( Boolean ).pop();
		var method     = $( '.js-payment-method' ).attr( 'data-method' );
		var package_id = $( '.js-package-id' ).attr( 'data-package-id' );

		take_to_gateway_topup_process( 'process', orderid, method, package_id );
	});
});

function take_to_gateway( gateway_name, payment_type ) {
	if ( payment_type == 'job_purchase' )      take_to_gateway_job( gateway_name );
	else if ( payment_type == 'featured' )     take_to_gateway_feature( gateway_name );
	else if ( payment_type == 'custom_extra' ) take_to_gateway_custom_extra( gateway_name );
	else if ( payment_type == 'tips' )         take_to_gateway_tips( gateway_name );
	else if ( payment_type == 'topup' )        take_to_gateway_topup( gateway_name );
	else if ( payment_type == 'badge' )        take_to_gateway_badge( gateway_name );
	else if ( payment_type == 'subscription' ) take_to_gateway_subscription( gateway_name );
}

function take_to_gateway_job( gateway_name ) {
	var amount = jQuery( '.main_value_inp' ).val();

	if ( ! amount ) amount = 1;

	var extras         = '';
	var extras_amounts = '';

	// Extra Fast Delivery
	if ( jQuery( '.chk_extrafast' ).parents( '.ui.checkbox' )[0] && jQuery( '.chk_extrafast' ).parents( '.ui.checkbox' ).checkbox( 'is checked' ) ) {
		var extra_fast_amount = jQuery( '.hid_extrafast' ).val();

		if ( ! extra_fast_amount ) extra_fast_amount = 1;

		extras += 'f|';
		extras_amounts += extra_fast_amount + '|';
	}

	// Additional Revision
	if ( jQuery( '.chk_extrarevision' ).parents( '.ui.checkbox' )[0] && jQuery( '.chk_extrarevision' ).parents( '.ui.checkbox' ).checkbox( 'is checked' ) ) {
		var extra_revision_amount = jQuery( '.hid_extrarevision' ).val();

		if ( ! extra_revision_amount ) extra_revision_amount = 1;

		extras += 'r|';
		extras_amounts += extra_revision_amount + '|';
	}

	// Extras
	for ( var k = 1; k <= 10; k++ ) {
		if ( jQuery( '.chk_extra' + k ).parents( '.ui.checkbox' )[0] && jQuery( '.chk_extra' + k ).parents( '.ui.checkbox' ).checkbox( 'is checked' ) ) {
			var extras_amnt = jQuery( '.hid_extra' + k ).val();

			if ( ! extras_amnt ) extras_amnt = 1;

			extras         += k + '|';
			extras_amounts += extras_amnt + '|';
		}
	}

	// Checkout with extras as text
	if ( ! wpj_vars.extra_prch_page && ! wpj_vars.force_allow ) {
		amount = jQuery( '.payment-main-item' ).attr( 'data-mainamount' );

		if ( ! amount ) amount = 1;

		jQuery( '.extra-item' ).each( function() {
			var extra_name   = jQuery( this ).attr( 'data-extranr' );
			var extra_amount = jQuery( this ).attr( 'data-extraamount' );

			if ( ! extra_amount ) extra_amount = 1;

			if ( extra_name == 'fast' ) {
				extras += 'f|';
				extras_amounts += extra_amount + '|';

			} else if ( extra_name == 'revision' ) {
				extras += 'r|';
				extras_amounts += extra_amount + '|';

			} else if ( extra_name >= 1 && extra_name <= 10 ) {
				extras += extra_name + '|';
				extras_amounts += extra_amount + '|';

			}
		});
	}

	var total_amount = jQuery( '.total' ).attr( 'data-total' );

	var base_url = wpj_vars.site_URL;
	base_url = base_url + '/?pay_for_item=' + gateway_name;
	base_url = base_url + '&payment_type=job_purchase';
	base_url = base_url + '&jobid=' + jQuery( 'input[name="jobid"]' ).val();
	base_url = base_url + '&amount=' + amount;
	base_url = base_url + '&extras=' + extras;
	base_url = base_url + '&extras_amounts=' + extras_amounts;

	if ( jQuery( 'input[name="package_no"]' ).val() )
		base_url = base_url + '&package_no=' + jQuery( 'input[name="package_no"]' ).val();

	if ( jQuery( 'input[name="package_price"]' ).val() )
		base_url = base_url + '&package_price=' + jQuery( 'input[name="package_price"]' ).val();

	if ( jQuery( 'input[name="package_delivery_days"]' ).val() )
		base_url = base_url + '&package_delivery_days=' + jQuery( 'input[name="package_delivery_days"]' ).val();

	var extra_params = {};

	jQuery.map( jQuery( "[name=myFormPurchase]" ).serializeArray(), function( n, i ) { extra_params[n['name']] = n['value']; } );

	if ( extra_params ) {
		jQuery.each( extra_params, function( param_name, param_value ) {
			base_url = base_url + '&' + param_name + '=' + param_value;
		});
	}

	take_to_gateway_window_message( base_url, gateway_name );

	if ( ! ( typeof wpj_vars !== 'undefined' && wpj_vars.is_in_app ) ) {
		window.location = base_url;
	}
}

function take_to_gateway_job_purchase_process( act, order_id, gateway_name ) {
	if ( act == 'process' ) {
		base_url = wpj_vars.site_URL + '/?pay_for_item=' + gateway_name + '&payment_type=job_purchase&oid=' + order_id + '&process_pending=1';

		take_to_gateway_window_message( base_url, gateway_name );

		if ( ! ( typeof wpj_vars !== 'undefined' && wpj_vars.is_in_app ) ) window.location = base_url;

	} else {
		// Remove messages
		jQuery( '.ui.message' ).remove();

		// Add loading class
		if ( jQuery( '.page-id-' + wpj_vars.order_page_id )[0] ) addLoader( '.js-pending-order-wrapper .wp-block-kadence-rowlayout:nth-child(2) .kt-inside-inner-col:first' );
		else addLoader( '.wpj-grid-table' );

		jQuery.ajax({
			type   : "POST",
			url    : wpj_vars.ajaxurl,
			data   : "action=cancel_job_pending_order_action&process=" + act + "&order_id=" + order_id,
			success: function( msg ) {
				if ( jQuery( '.page-id-' + wpj_vars.order_page_id )[0] ) { // order page
					refreshContent( '#main-content' );

				} else { // shopping page
					if ( jQuery( '.user-shopping-wrapper' )[0] ) refreshContent( '.user-shopping-wrapper' ); // for code
					else wpj_refresh_kadence_tab_content(); // for page builder

				}
			}
		});

	}
}

function take_to_gateway_custom_extra( gateway_name ) {
	var oid = jQuery( 'input[name="oid"]' ).val();
	var custom_extra = jQuery( 'input[name="custom_extra"]' ).val();

	var amount = 1;

	var base_url = wpj_vars.site_URL;
	base_url = base_url + '/?pay_for_item=' + gateway_name;
	base_url = base_url + '&payment_type=custom_extra';
	base_url = base_url + '&oid=' + oid;
	base_url = base_url + '&amount=' + amount;
	base_url = base_url + '&custom_extra=' + custom_extra;

	take_to_gateway_window_message( base_url, gateway_name );

	if ( ! ( typeof wpj_vars !== 'undefined' && wpj_vars.is_in_app ) ) {
		window.location = base_url;
	}
}

function take_to_gateway_tips( gateway_name ) {
	var oid = jQuery( 'input[name="oid"]' ).val();
	var tips_id = jQuery( 'input[name="tips"]' ).val();

	var amount = 1;

	var base_url = wpj_vars.site_URL;
	base_url = base_url + '/?pay_for_item=' + gateway_name;
	base_url = base_url + '&payment_type=tips';
	base_url = base_url + '&oid=' + oid;
	base_url = base_url + '&amount=' + amount;
	base_url = base_url + '&tips=' + tips_id;

	take_to_gateway_window_message( base_url, gateway_name );

	if ( ! ( typeof wpj_vars !== 'undefined' && wpj_vars.is_in_app ) ) {
		window.location = base_url;
	}
}

function take_to_gateway_feature( gateway_name ) {
	var pid = jQuery( document ).find( '[data-pid]' ).first().attr( 'data-pid' );

	var h_date_start = jQuery( 'input[name="h_date_start"]' ).val();
	var c_date_start = jQuery( 'input[name="c_date_start"]' ).val();
	var s_date_start = jQuery( 'input[name="s_date_start"]' ).val();

	var current_feature_pages = '';

	jQuery( 'input:checked[name="feature_pages[]"]' ).each( function() {
		if ( jQuery( this ).val() == 'homepage' ) current_feature_pages += "h";
		else if ( jQuery( this ).val() == 'category' ) current_feature_pages += "c";
		else if ( jQuery( this ).val() == 'subcategory' ) current_feature_pages += "s";
	});

	if ( ! current_feature_pages ) {
		jQuery( '#' + gateway_name ).notify( wpj_vars.featured_empty, { position: 'right', className: 'error' } );

		setTimeout( function() {
			jQuery( '.ui.active.inverted.dimmer' ).remove();
		}, 500 );

	} else if ( gateway_name == 'credits' && parseFloat( jQuery( '#showtotal' ).attr( 'data-total' ) ) > parseFloat( wpj_vars.user_credits ) ) {
		jQuery( '#' + gateway_name ).notify( wpj_vars.not_enough_credits, { position: 'right', className: 'error' } );

		setTimeout( function() {
			jQuery( '.ui.active.inverted.dimmer' ).remove();
		}, 500 );

	} else if (
		( wpj_vars.h_date_start != h_date_start && jQuery( '#homepage_featured_chk' ).is( ":checked" ) ) ||
		( wpj_vars.c_date_start != c_date_start && jQuery( '#category_featured_chk' ).is( ":checked" ) ) ||
		( wpj_vars.s_date_start != s_date_start && jQuery( '#subcategory_featured_chk' ).is( ":checked" ) )
	) {
		jQuery( '#' + gateway_name ).notify( wpj_vars.featured_interval, { position: 'right', className: 'error' } );

		setTimeout( function() {
			jQuery( '.ui.active.inverted.dimmer' ).remove();
		}, 500 );

	} else {
		var base_url = wpj_vars.site_URL;
		base_url = base_url + '/?pay_for_item=' + gateway_name;
		base_url = base_url + '&payment_type=feature';
		base_url = base_url + '&jobid=' + pid;
		base_url = base_url + '&h_date_start=' + h_date_start;
		base_url = base_url + '&c_date_start=' + c_date_start;
		base_url = base_url + '&s_date_start=' + s_date_start;
		base_url = base_url + '&feature_pages=' + current_feature_pages;

		take_to_gateway_window_message( base_url, gateway_name );

		if ( ! ( typeof wpj_vars !== 'undefined' && wpj_vars.is_in_app ) ) {
			window.location = base_url;
		}

	}
}

function take_to_gateway_feature_process( act, feature_oid, gateway_name ) {
	if ( act == 'process' ) {

		base_url = wpj_vars.site_URL + '/?pay_for_item=' + gateway_name + '&payment_type=feature&oid=' + feature_oid + '&process_pending=1';

		take_to_gateway_window_message( base_url, gateway_name );

		if ( ! ( typeof wpj_vars !== 'undefined' && wpj_vars.is_in_app ) )
			window.location = base_url;

	} else {

		// Remove messages
		jQuery( '.ui.message' ).remove();

		// Add loading class
		addLoader( '.js-feature-content' );

		jQuery.ajax({
			type: "POST",
			url : wpj_vars.ajaxurl,
			data: {
				action          : 'cancel_featured_order_action',
				order_id        : feature_oid,
				payment_gateway : gateway_name
			},
			success: function( msg ) {
				refreshContent( '.js-feature-content' );
			}
		});

	}
}

function take_to_gateway_topup( gateway_name ) {
	var package_id = jQuery( 'input[name=topup]:checked' ).val();

	if ( package_id >= '0' ) {
		base_url = wpj_vars.site_URL + '/?pay_for_item=' + gateway_name + '&payment_type=topup&package_id=' + package_id;

		take_to_gateway_window_message( base_url, gateway_name );

		if ( ! ( typeof wpj_vars !== 'undefined' && wpj_vars.is_in_app ) ) {
			window.location.href = base_url;
		}

	} else {
		jQuery( '#' + gateway_name ).notify( wpj_vars.topup_package_empty, { position: 'right', className: 'error' } );

		setTimeout( function() {
			jQuery( '.ui.active.inverted.dimmer' ).remove();
		}, 500 );

	}
}

function take_to_gateway_topup_process( act, topup_oid, gateway_name, package_id ) {
	if ( act == 'process' ) {

		base_url = wpj_vars.site_URL + '/?pay_for_item=' + gateway_name + '&payment_type=topup&oid=' + topup_oid + '&package_id=' + package_id + '&process_pending=1';

		take_to_gateway_window_message( base_url, gateway_name );

		if ( ! ( typeof wpj_vars !== 'undefined' && wpj_vars.is_in_app ) )
			window.location = base_url;

	} else {

		// Add loading class
		if ( jQuery( '.page-id-' + wpj_vars.topup_order_page_id )[0] ) addLoader( '.js-pending-order-wrapper' );
		else addLoader( '.wpj-grid-table' );

		jQuery.ajax({
			type : "POST",
			url  : wpj_vars.ajaxurl,
			data : {
				action          : 'cancel_topup_pending_order_action',
				order_id        : topup_oid,
				payment_gateway : gateway_name
			},
			success: function( msg ) {
				if ( jQuery( '.page-id-' + wpj_vars.topup_order_page_id )[0] ) { // order page
					refreshContent( '#main-content' );

				} else { // payments page
					refreshContent( '.wpj-dashboard-topup-pending-table' );

				}
			}
		});

	}
}

function take_to_gateway_badge( gateway_name ) {
	if ( gateway_name == 'credits' && parseFloat( jQuery( '#showtotal' ).attr( 'data-total' ) ) > parseFloat( wpj_vars.user_credits ) ) {
		jQuery( '#' + gateway_name ).notify( wpj_vars.not_enough_credits, { position: 'right', className: 'error' } );

		setTimeout( function() {
			jQuery( '.ui.active.inverted.dimmer' ).remove();
		}, 500 );

	} else {
		if ( ! jQuery( 'input:checked[name="badges"]' ).val() ) {
			jQuery( '#' + gateway_name ).notify( wpj_vars.badge_empty, { position: 'right', className: 'error' } );

			setTimeout( function() {
				jQuery( '.ui.active.inverted.dimmer' ).remove();
			}, 500 );

		} else {
			base_url = wpj_vars.site_URL;
			base_url = base_url + '/?pay_for_item=' + gateway_name;
			base_url = base_url + '&payment_type='  + 'badge';
			base_url = base_url + '&user_id='       + wpj_vars.uid;
			base_url = base_url + '&badge_nr='      + jQuery( 'input:checked[name="badges"]' ).val();
			base_url = base_url + '&price='         + jQuery( 'input:checked[name="badges"]' ).attr( 'data-price' );

			take_to_gateway_window_message( base_url, gateway_name );

			if ( ! ( typeof wpj_vars !== 'undefined' && wpj_vars.is_in_app ) ) {
				window.location = base_url;
			}

		}

	}
}

function take_to_gateway_subscription( gateway_name ) {
	var subscription_details = jQuery( 'input:checked[name="sub_id"]' ).val();

	if ( subscription_details ) {
		var subscr_det_split = subscription_details.split( '-' );

		var sub_type   = subscr_det_split[0];
		var sub_level  = subscr_det_split[1];
		var sub_amount = jQuery( 'input:checked[name="sub_id"]' ).siblings( 'input[name="sub_amt"]' ).val();

		var schedule_only = jQuery( 'input:checked[name="sub_id"]' ).parents( '.subscription-wrapper' ).find( 'input[name="schedule_only"]' ).val();

		if ( gateway_name == 'credits' && parseFloat( sub_amount ) > parseFloat( wpj_vars.user_credits ) ) {
			jQuery( '.js-' + gateway_name ).notify( wpj_vars.not_enough_credits, { position: 'right', className: 'error' } );

			setTimeout( function() {
				jQuery( '.ui.active.inverted.dimmer' ).remove();
			}, 500 );

		} else {
			base_url = wpj_vars.site_URL;
			base_url = base_url + '/?pay_for_item=' + gateway_name;
			base_url = base_url + '&payment_type='  + 'subscription';
			base_url = base_url + '&user_id='       + wpj_vars.uid;
			base_url = base_url + '&sub_amount='    + sub_amount;
			base_url = base_url + '&sub_type='      + sub_type;
			base_url = base_url + '&sub_level='     + sub_level;
			base_url = base_url + '&schedule_only=' + schedule_only;

			take_to_gateway_window_message( base_url, gateway_name );

			if ( ! ( typeof wpj_vars !== 'undefined' && wpj_vars.is_in_app ) ) {
				window.location = base_url;
			}

		}

	} else {
		jQuery( '.js-' + gateway_name ).notify( wpj_vars.subscription_empty, { position: 'right', className: 'error' } );

		setTimeout( function() {
			jQuery( '.ui.active.inverted.dimmer' ).remove();
		}, 500 );

	}
}

function take_to_gateway_subscription_process( act, subscription_oid, gateway_name ) {
	if ( act == 'process' ) {

		base_url = wpj_vars.site_URL + '/?pay_for_item=' + gateway_name + '&payment_type=subscription&oid=' + subscription_oid + '&process_pending=1';

		take_to_gateway_window_message( base_url, gateway_name );

		if ( ! ( typeof wpj_vars !== 'undefined' && wpj_vars.is_in_app ) ) {
			window.location = base_url;
		}

	} else {
		// Remove messages
		jQuery( '.ui.message' ).remove();

		// Add loading class
		jQuery( '.text-button.text-button-negative' ).addClass( 'ui loading button' );
		jQuery( '.ui.mini.buttons' ).find( '.negative' ).addClass( 'loading' );

		jQuery.ajax({
			type: "POST",
			url : wpj_vars.ajaxurl,
			data: {
				action          : 'cancel_subscription_action',
				order_id        : subscription_oid,
				payment_gateway : gateway_name
			},
			success: function( msg ) {
				refreshContent( '#main-content' );
			}
		});

	}
}

function take_to_gateway_window_message( base_url, gateway ) {
	if ( gateway && gateway != 'credits' && gateway != 'cod' && gateway != 'banktransfer' ) {
		window.parent.postMessage( {data: {
			isExternal    : true,
			isTargetBlank : false,
			currentUrl    : window.location.href,
			externalUrl   : base_url
		}}, "*" );

	} else {
		window.parent.postMessage( {data: {
			isExternal    : false,
			isTargetBlank : false,
			currentUrl    : window.location.href,
			nextUrl       : base_url
		}}, "*" );

		window.location = base_url;

	}
}