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

	// Add new milestone row
	$( document ).on( 'click', '#add_milestone', function( e ) {
		var new_field = $( '.repeater-row:first' ).clone();

		new_field.find( 'textarea' ).val( '' );
		new_field.find( 'input' ).val( '' );
		new_field.find( '.ui.dropdown.delivery-days' ).dropdown( 'set selected', 1 );

		new_field.appendTo( '.milestone-table tbody' );

		$( '.ui.dropdown.delivery-days' ).dropdown();
		$.fn.wpjTooltipInit();

		// Disable EFD delivery days
		wpj_mlst_disable_efd_delivery_days();
	});

	// Remove milestone row
	$( document ).on( 'click', '.remove-milestone', function( e ) {
		if ( $( '.remove-milestone' ).length > 1 ) {
			$( this ).parents( 'tr' ).remove();

		} else {
			$( this ).parents( 'tr' ).find( 'input, textarea' ).val( '' );
			$( this ).parents( 'tr' ).find( '.ui.dropdown' ).dropdown( 'set selected', 1 );

		}

		// Disable EFD delivery days
		wpj_mlst_disable_efd_delivery_days();
	});

	// Same price for first milestone
	$( document ).on( 'input', '.post-new-price', function() {
		if ( $( 'select[name="price_type"]' ).val() == 'milestone' ) {
			$( '.deposit-amount:first' ).val( $( this ).val() );
		}
	});

	$( document ).on( 'input', '.deposit-amount:first', function() {
		if ( $( 'select[name="price_type"]' ).val() == 'milestone' ) {
			$( '.post-new-price' ).val( $( this ).val() );
		}
	});

	// Mark milestone delivered
	$( document ).on( "click", ".mark_milestone_delivered", function( e ) {
		e.preventDefault();

		var $this = $( this );

		$this.addClass( 'loading' ).addClass( 'disabled' );

		$.ajax({
			type: 'post',
			url : wpj_vars.ajaxurl,
			data: {
				'action': 'mark_milestone_delivered',
				'oid'   : $this.attr( 'data-oid' ),
				'ceid'  : $this.attr( 'data-ceid' )
			},
			success: function( data ) {
				$this.parents( '.custom_extra_chatbox_buttons' ).remove();
				refreshContent( '#order-notification-messages-wrapper' );
			}
		});

	});

	// Mark milestone completed
	$( document ).on( "click", ".mark_milestone_completed", function( e ) {
		e.preventDefault();

		var $this = $( this );

		$this.addClass( 'loading' ).addClass( 'disabled' );

		jQuery.ajax({
			type: 'post',
			url : wpj_vars.ajaxurl,
			data: {
				'action': 'mark_milestone_completed',
				'oid'   : $this.attr( 'data-oid' ),
				'ceid'  : $this.attr( 'data-ceid' )
			},
			success: function( data ) {
				$this.parents( '.custom_extra_chatbox_buttons' ).remove();
				refreshContent( '#order-notification-messages-wrapper' );
				refreshContent( '#order-message-form-wrapper' ); // hide message form
				refreshContent( '#order-feedback-form-wrapper' ); // show review form
			}
		});

	});

	$( document ).on( 'change', 'select[name="delivery_days[]"]', function() {
		wpj_mlst_disable_efd_delivery_days();
	});

});

function wpj_mlst_disable_efd_delivery_days() {
	var total_days = 0;

	if ( jQuery( 'select[name="delivery_days[]"]' )[0] ) {
		var price_type = jQuery( 'select[name="price_type"]' ).val();
		if ( price_type == 'milestone' ) {

			jQuery( 'select[name="delivery_days[]"]' ).each( function() {
				total_days += parseInt( jQuery( this ).val() );
			});

			jQuery( '.max_days_fast.ui.dropdown .menu .item' ).each( function( ind, el ) {
				if ( parseInt( total_days ) && parseInt( jQuery( el ).data( 'value' ) ) >= parseInt( total_days ) )
					jQuery( el ).addClass( 'disabled' );

				else
					jQuery( el ).removeClass( 'disabled' );

			});
		}
	}
}

Hooks.add_action( 'wpj_after_page_load_without_refresh', wpj_mlst_init_scripts );
function wpj_mlst_init_scripts() {
	// Hide multiple row from checkout page
	if ( wpj_vars.is_milestone_type == 'milestone' ) jQuery( '.js-job-quantity-wrapper' ).hide();

	// Same price for first milestone
	jQuery( '.deposit-amount:first' ).val( jQuery( '.post-new-price' ).val() );

	// Fill new milestone row on edit job page
	if ( typeof wpj_vars.job_milestones !== 'undefined' && wpj_vars.job_milestones !== '[]' && wpj_vars.job_milestones != '""' ) {
		jQuery.each( JSON.parse( wpj_vars.job_milestones ), function( key, value ) {
			if ( value ) {
				var new_field = jQuery( '.repeater-row:first' ).clone();

				new_field.find( 'textarea' ).val( value.description );
				new_field.find( '.ui.dropdown' ).dropdown( 'set selected', value.days );
				new_field.find( '.deposit-amount' ).val( value.amount );

				new_field.appendTo( '.milestone-table tbody' );
			}
		});

		jQuery( '.ui.dropdown.delivery-days' ).dropdown();
		jQuery.fn.wpjTooltipInit();

		jQuery( '.repeater-row:first' ).remove();
	}

	// Disable EFD delivery days
	wpj_mlst_disable_efd_delivery_days();
}

// Add milestone label to job price on change and hide fields
Hooks.add_action( 'wpj_after_job_price_type_changed', wpj_mlst_changes_on_price_type_changed, 1 );
function wpj_mlst_changes_on_price_type_changed( val ) {

	if ( jQuery( '[data-handler-id="job_price"]' ).siblings( 'label' )[0] )
		var price_label_el = jQuery( '[data-handler-id="job_price"]' ).siblings( 'label' ); // for code

	else
		var price_label_el = jQuery( '[data-handler-id="job_price"]' ).siblings( '.wp-block-kadence-advancedheading' ); // for page builder

	if ( val == 'milestone' ) {

		// Add 'first milestone' string
		price_label_el.attr( 'data-label', price_label_el.text() ).append( '&nbsp;' + wpj_vars.first_milestone );

		// Show milestone table
		if ( jQuery( '.milestones-wrapper' )[0] ) {
			if ( jQuery( '.fields' )[0] ) {
				jQuery( '.milestones-wrapper' ).parents( '.field' ).removeClass( 'hidden' );
				jQuery( '.milestones-wrapper' ).parents( '.fields' ).removeClass( 'hidden' );
			} // for code

			jQuery( '.milestones-wrapper' ).show(); // for page builder
		}

		// Disable EFD delivery days
		wpj_mlst_disable_efd_delivery_days();

	} else {

		// Remove 'first milestone' string
		if ( price_label_el.attr( 'data-label' ) )
			price_label_el.html( price_label_el.attr( 'data-label' ) );

		// Hide milestone table
		if ( jQuery( '.milestones-wrapper' )[0] ) {
			if ( jQuery( '.fields' )[0] ) {
				jQuery( '.milestones-wrapper' ).parents( '.field' ).addClass( 'hidden' );
				jQuery( '.milestones-wrapper' ).parents( '.fields' ).addClass( 'hidden' );
			} // for code

			jQuery( '.milestones-wrapper' ).hide(); // for page builder
		}

	}
}

// Skip instant validation for milestones
function wpj_mlst_skip_instant_validation( $this, fields_arr ) {
	if ( $this.val() == 'milestone' ) {
		delete fields_arr.max_days;
		wpj_aoe_max_days_validation( $this, fields_arr );
	}
}

Hooks.add_action( 'wpj_before_execute_job_form_validation', wpj_mlst_skip_instant_validation_action, 1 );
function wpj_mlst_skip_instant_validation_action( fields_arr ) {
	wpj_mlst_skip_instant_validation( jQuery( 'select[name="price_type"]' ), fields_arr );

	jQuery( document ).on( 'change', 'select[name="price_type"]', function() {
		wpj_mlst_skip_instant_validation( jQuery( this ), fields_arr );
	});
}

Hooks.add_filter( 'wpj_efd_max_days_validation_filter', wpj_mlst_change_max_days_value );
function wpj_mlst_change_max_days_value( amount_jobefdmaxdays_min ) {
	if ( jQuery( 'select[name="price_type"]' ).val() == 'milestone' ) {
		var total_days = 0;

		jQuery( 'select[name="delivery_days[]"]' ).each( function() {
			total_days += parseInt( jQuery( this ).val() );
		});

		amount_jobefdmaxdays_min = total_days;
	}

	return amount_jobefdmaxdays_min;
}

// Milestone field validation
Hooks.add_filter( 'wpj_fields_validation_filter', wpj_mlst_validate_milestone_field, 1 );
function wpj_mlst_validate_milestone_field( fields_arr, page ) {
	if ( jQuery( 'select[name="price_type"]' ).val() == 'milestone' ) {

		fields_arr.milestone_description = {
			identifier: 'milestone_description[]',
			rules: [{
				type   : 'empty',
				prompt : wpj_vars.empty_description
			}]
		}

		fields_arr.delivery_days = {
			identifier: 'delivery_days[]',
			rules: [{
				type   : 'empty',
				prompt : wpj_vars.empty_days
			}]
		}

		fields_arr.deposit_amount = {
			identifier: 'deposit_amount[]',
			rules: [{
				type   : 'empty',
				prompt : wpj_vars.empty_amount
			}]
		}

	} else {

		delete fields_arr.milestone_description;
		delete fields_arr.delivery_days;
		delete fields_arr.deposit_amount;

	}

	return fields_arr;
}