/**
 * EverestFormsSaveAndContinue JS
 */
 ( function ($) {
	var EverestFormsCoupons = {
		init: function () {
			var form = $("form.everest-form");

			form.each(function (i, v) {
				$(document).ready(function () {

					// Forms.
					var formTuple = $(v),
						form_id = formTuple.attr( 'data-formid' ),
						btn = formTuple.find( '.evf-coupon-apply' );

					//Validate Coupon.
					btn.on( 'click', function (e) {

						$this = $(this);

						e.preventDefault();

						if( '' === $this.prev( '.evf-payment-coupon' ).val() ) {
							return;
						}

						$this.prop( 'disabled', true );

						// Change the text to user defined property.
						$this.html( 'applying' );

						$this.closest('.everest-forms-coupons' ).find( 'input' ).prop( 'readonly', true );

						$this.closest( '.everest-forms-coupons' ).siblings( '.evf-error' ).remove();
						$this.closest( '.everest-forms-coupons' ).siblings( '.evf-coupon-error' ).remove();

						var data = [];

						// Add action intend for ajax_form_submission endpoint.
						data.push( {
							name: "action",
							value: "everest_forms_coupons_apply",
						} );

						data.push( {
							name: "form_id",
							value: form_id,
						} );

						data.push( {
							name: "coupon_code",
							value: $this.prev( '.everest-forms-coupons-wrapper' ).find( '.evf-payment-coupon' ).val()
						} );

						data.push( {
							name: "coupon_id",
							value: $this.closest( '.evf-field' ).attr( 'data-field-id' )
						} );

						data.push( {
							name: "nonce",
							value: everest_forms_coupons_params.nonce,
						} );

						// Fire the ajax request.
						$.ajax( {
							url: everest_forms_coupons_params.ajax_url,
							type: "POST",
							data: data,
						} )
							.done( function (xhr, textStatus, errorThrown ) {
								if ( true == xhr.success ) {
									var type = xhr.data.discount_type,
										amount = xhr.data.amount;
									if( 'fixed' === type ) {
										var discount_amount_sanitized = amount.match(/\;[\d|.\,]+/)[0].replace(';', '');
										$this.closest('.everest-forms-coupons').find( 'input' ).attr( 'data-discount', discount_amount_sanitized ).addClass('evf-coupon-applied');
									} else {
										if( '' === xhr.data.map_field ) {
											var discount_percent_sanitized = amount.replace( '%', '');
											$this.closest('.everest-forms-coupons').find( 'input' ).attr( 'data-discount', discount_percent_sanitized )
											.attr( 'data-discount_percent', '1' ).addClass('evf-coupon-applied');
										} else {
											var total_product_amount = '0';
											var discount_percent_sanitized = amount.replace( '%', ''),
												map_field =  xhr.data.map_field,
												field = $this.closest( 'form' ).find( 'div[data-field-id="' + map_field + '"] .evf-payment-price:enabled, div[data-field-id="' + map_field + '"] .evf-single-item-price-hidden input[type="hidden"]:enabled');
											if ( 'text' === field.attr( 'type' ) || 'hidden' === field.attr( 'type' ) ) {
												total_product_amount = field.val();
											} else if ( 'radio' === field.attr( 'type' ) && field.is( ':checked' ) ) {
												total_product_amount = field.data('amount');
											} else if( field.closest( '.evf-field' ).is( '.evf-field-payment-checkbox' ) ) {
												total_product_amount = 0;
												field.closest( '.evf-field' ).find( '.evf-payment-price:checked' ).each( function() {
													amount = $( this ).attr( 'data-amount' );
													if ( ! isNaN( parseFloat( amount ) ) ) {
														map_field_amount = parseFloat( amount );
														total_product_amount += map_field_amount;
													}
												} );
												total_product_amount = total_product_amount.toString();
											} else if ( field.is( 'select' ) && field.find( 'option:selected' ).length > 0 ) {
												total_product_amount = field.find( 'option:selected' ).data( 'amount' );
											} else if ( 'number' === field.attr( 'type' ) ) {
												if( field.data( 'enable_payment_slider' ) ) {
													total_product_amount = field.val();
												}
											}
											var total_product_amount_number = total_product_amount.match(/[\d|.\,]+/)[0],
												total_product_amount_sanitized = total_product_amount_number.replace(',', '');
											if ( $this.closest( 'form' ).find( '.evf-payment-quantity' ).length ) {
												$this.closest( 'form' ).find( '.evf-payment-quantity' ).each(function( index, el ) {
													if ( 0 <= $( el).val() ) {
														if( map_field === $( el).attr( 'data-map_field' ) ) {
															total_product_amount_sanitized = total_product_amount_sanitized * $( el ).val();
														}
													}
												} );
											}
											$this.closest('.everest-forms-coupons').find( 'input' ).attr( 'data-discount', discount_percent_sanitized )
											.attr( 'data-discount_percent', '1' ).addClass('evf-coupon-applied')
											.attr( 'data-discount_map_field', map_field );
										}
									}
									$this.closest( 'form' ).find( '.evf-payment-price:first' ).trigger( 'change' );
									$( '<label class="evf-coupon-amount"> '+ xhr.data.message + '</label>' ).insertAfter( $this.closest( '.everest-forms-coupons' ) );
									$this.css( 'display', 'none' );
								} else {
									$( '<label class="evf-coupon-error">' + xhr.data.message + '</label>' ).insertAfter( $this.closest( '.everest-forms-coupons' ) );
								}
							})
							.fail(function () {
								$( '<label class="evf-coupon-error">Something went wrong' ).insertAfter( $this.closest( '.everest-forms-coupons' ) );
							})
							.always(function (xhr) {
								$this.prop( "disabled", false );
								$this.html( $this.attr( 'data-text') );
							});
					});
				});
			});

			$( document ).on( 'click', '.evf-clear-coupon', function() {
				$( this ).closest( '.evf-field' ).removeClass( 'everest-forms-invalid' );
				$( this ).closest( '.evf-field' ).find( 'label.evf-error' ).remove();
				$( this ).closest( '.evf-field' ).find( '.evf-coupon-apply' ).css( 'display', 'block' );
				$( this ).closest( '.evf-field' ).find( '.evf-payment-coupon' ).removeAttr( 'data-discount' ).removeAttr( 'data-discount_percent' ).removeAttr( 'data-discount_map_field' ).removeClass( 'evf-coupon-applied' );
				$( this ).closest( '.evf-field' ).find( '.evf-payment-price' ).trigger("input").trigger( 'change' );
				$( this ).closest( '.evf-field' ).find( '.everest-forms-coupons input' ).prop( 'readonly', false );
				$( this ).closest( '.evf-field' ).find( 'input' ).val( '' ).focus();
				$( this ).closest( '.evf-field' ).find( '.evf-coupon-amount' ).remove();
				$( this ).closest( '.evf-field' ).find( '.evf-coupon-error' ).remove();
				$( this ).closest( 'form' ).find( '.evf-payment-price:first' ).trigger( 'change' );
			});
		},
	};

	// Initialize.
	EverestFormsCoupons.init(jQuery);

	// End of popup modal.
})(jQuery);
