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

	// Save autodraft post values
	// when are changes inside the form
	$( document ).on( 'click', '#add-edit-job-form', function( e ) {
		var action_type = getUrlParameter( 'action' ) ? getUrlParameter( 'action' ) : 'new-job';
		var jobid       = getUrlParameter( 'jobid' );

		if ( $( e.target ).parent().hasClass( 'post-new-job-btn' ) === false && $( e.target ).hasClass( 'js-delete-extra' ) === false ) {
			$.ajax({
				type: 'post',
				url : wpj_vars.ajaxurl,
				data: $( this ).serialize() + "&status=autodraft&action=save_job_post_action&aoe_form_submitted=1&action_type=" + action_type + "&jobid=" + jobid,
				success: function( data ) {}
			});
		}
	});

	// Save post values
	// when publosh button is clicked
	$( document ).on( 'click', '.post-new-job-btn', function( e ) {
		wpj_validate_new_job_form();

		if ( $( '#add-edit-job-form' ).form( 'is valid' ) ) {
			e.preventDefault();

			var action_type = getUrlParameter( 'action' ) ? getUrlParameter( 'action' ) : 'new-job';
			var jobid       = getUrlParameter( 'jobid' );

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

			$.ajax({
				type: 'post',
				url : wpj_vars.ajaxurl,
				data: $( '#add-edit-job-form' ).serialize() + "&status=publish&action=save_job_post_action&aoe_form_submitted=1&action_type=" + action_type + "&jobid=" + jobid,
				success: function( data ) {
					if ( data.includes( 'http://' ) || data.includes( 'https://' ) ) changeURL( data );
					else {
						$( '.post-new-job-btn' ).removeClass( 'ui loading disabled button' );
						$( '.ui.error.message' ).html( data ).removeClass( 'hidden' ).show();
						return false;
					}
				}
			});

		}
	});

	// Fill job subcategory by selected categories
	$( document ).on( 'change', '#job_cat', function( e ) {
		if ( $( this ).val().length !== 0 ) {

			$.ajax({
				type: 'post',
				url : wpj_vars.ajaxurl,
				data: {
					'action'               : 'load_subcategories_by_categories_action',
					'taxonomy_name'        : 'job_cat',
					'term_type'            : 'id',
					'include_empty_option' : wpj_vars.select_subcategory,
					'select_name'          : 'subcat',
					'select_id'            : 'subcat',
					'select_category_value': $( this ).val()
				},
				beforeSend: function() {
					if ( e.type == 'change' && e.originalEvent !== undefined ) $( '#job_subcategories' ).html( '<center><img src="' + wpj_vars.theme_path + '/assets/images/loader/loader-green.svg"></center>' );
				},
				success: function( data ) {
					if ( data && data.match( /option/g ).length > 2 ) {
						if ( e.type == 'change' && e.originalEvent !== undefined ) $( '#job_subcategories' ).html( data );
						$( '.ui.dropdown' ).dropdown( { message: { noResults: wpj_vars.nothing_found } } );

						localStorage.setItem( 'validate_subcat', 'yes' );

					} else {
						if ( e.type == 'change' ) $( '#job_subcategories' ).html( '' );
						localStorage.setItem( 'validate_subcat', 'no' );

					}

					if ( $( '#job_subcategories' ).attr( 'data-required' ) != true ) localStorage.setItem( 'validate_subcat', 'no' );
				}
			});

		} else {
			if ( e.type == 'change' ) $( '#job_subcategories' ).html( '' );
			localStorage.setItem( 'validate_subcat', 'no' );
		}
	});

	// Hide instant field
	$( document ).on( 'change', '#max_days', function( e ) {
		if ( $( "#max_days" ).val() == 'instant' ) {
			// for code
			if ( $( '.fields' )[0] ) $( '[data-handler-id="job_instant_delivery"]' ).css({ display: "flex" });

			// for page builder
			if ( $( '.instant-delivery-field-wrapper' )[0] ) $( '.instant-delivery-field-wrapper' ).find( '.kt-inside-inner-col' ).show();

		} else {
			// for code
			if ( $( '.fields' )[0] ) $( '[data-handler-id="job_instant_delivery"]' ).hide();

			// for page builder
			if ( $( '.instant-delivery-field-wrapper' )[0] ) $( '.instant-delivery-field-wrapper' ).find( '.kt-inside-inner-col' ).hide();

		}

		wpj_check_job_delivery_time( 'yes' );
	});

	// Hide fields by price type
	$( document ).on( 'change', 'select[name="price_type"]', function( e ) {
		var this_val = $( this ).val();

		if ( $.inArray( this_val, JSON.parse( wpj_vars.no_days_price_types ) ) != -1 ) {
			// Max delivery days
			if ( $( '.fields' )[0] ) $( '[data-handler-id="job_delivery"]' ).parents( '.fields' ).hide(); // for code
			if ( $( '.wp-block-kadence-rowlayout' )[0] ) $( '[data-handler-id="job_delivery"]' ).parents( '.wp-block-kadence-rowlayout' ).eq( 1 ).hide(); // for page builder

			// Instant delivery
			if ( $( '.fields' )[0] ) jQuery( '[data-handler-id="job_instant_delivery"]' ).hide(); // for code
			if ( $( '.instant-delivery-field-wrapper' )[0] ) $( '.instant-delivery-field-wrapper' ).find( '.kt-inside-inner-col' ).hide(); // for page builder

			// Validation
			wpj_check_job_delivery_time( 'no' );

			// Packages
			if ( this_val == 'package' ) {
				if ( $( '.fields' )[0] ) {
					$( '.packages' ).parents( '.field' ).removeClass( 'hidden' );
					$( '.packages' ).parents( '.fields' ).removeClass( 'hidden' );
				} // for code

				if ( $( '.package-field-wrapper' )[0] ) $( '.package-field-wrapper' ).show(); // for page builder

			} else {
				if ( $( '.fields' )[0] ) {
					$( '.packages' ).parents( '.field' ).addClass( 'hidden' );
					$( '.packages' ).parents( '.fields' ).addClass( 'hidden' );
				} // for code

				if ( $( '.package-field-wrapper' )[0] ) $( '.package-field-wrapper' ).hide(); // for page builder

			}

			if ( this_val == 'package' ) {
				$( 'input[name="job_cost"]' ).prop( 'disabled', true );
				$( 'input[name="job_cost"]' ).attr( 'placeholder', $( 'input[name="job_cost"]' ).attr( 'data-packages' ) );

			} else if ( this_val == 'custom' ) {
				$( 'input[name="job_cost"]' ).prop( 'disabled', true );
				$( 'input[name="job_cost"]' ).attr( 'placeholder', $( 'input[name="job_cost"]' ).attr( 'data-customplaceholder' ) );

			} else {
				$( 'input[name="job_cost"]' ).prop( 'disabled', false );
				$( 'input[name="job_cost"]' ).attr( 'placeholder', $( 'input[name="job_cost"]' ).attr( 'data-placeholder' ) );

			}

		} else {
			// Max delivery days
			if ( $( '.fields' )[0] ) $( '[data-handler-id="job_delivery"]' ).parents( '.fields' ).css({ display: "flex" }); // for code
			if ( $( '.wp-block-kadence-rowlayout' )[0] ) $( '[data-handler-id="job_delivery"]' ).parents( '.wp-block-kadence-rowlayout' ).eq( 1 ).show(); // for page builder

			// Instant delivery
			if ( $( "#max_days" ).val() == 'instant' ) {
				if ( jQuery( '.fields' )[0] ) jQuery( '[data-handler-id="job_instant_delivery"]' ).css({ display: "flex" }); // for code
				if ( jQuery( '.instant-delivery-field-wrapper' )[0] ) jQuery( '.instant-delivery-field-wrapper' ).find( '.kt-inside-inner-col' ).show(); // for page builder
			}

			// Validation
			wpj_check_job_delivery_time( 'yes' );

			// Packages
			if ( $( '.fields' )[0] ) {
				$( '.packages' ).parents( '.field' ).addClass( 'hidden' );
				$( '.packages' ).parents( '.fields' ).addClass( 'hidden' );
			} // for code

			if ( $( '.package-field-wrapper' )[0] ) $( '.package-field-wrapper' ).hide(); // for page builder

			if ( this_val == 'custom' ) {
				$( 'input[name="job_cost"]' ).prop( 'disabled', true );
				$( 'input[name="job_cost"]' ).attr( 'placeholder', $( 'input[name="job_cost"]' ).attr( 'data-customplaceholder' ) );

			} else {
				$( 'input[name="job_cost"]' ).prop( 'disabled', false );
				$( 'input[name="job_cost"]' ).attr( 'placeholder', $( 'input[name="job_cost"]' ).attr( 'data-placeholder' ) );

			}

		}

		wpj_pck_disable_efd_delivery_days();

		Hooks.do_action( 'wpj_after_job_price_type_changed', this_val );
	});

	// Fix width for tags init
	$( document ).on( 'click', '#job_tags_tagsinput', function( e ) {
		if ( $( this ).find( '#job_tags_tag' )[0].style.width == '0px' )
			$( this ).find( '#job_tags_tag' ).removeAttr( 'style' );
	});

	// Add New Video
	$( document ).on( 'click', '.js-add-video', function( e ) {
		$( '.video-wrapper' ).last().clone().find( 'input:text' ).val( '' ).end().insertAfter( '.video-wrapper:last' );
		if ( $( '.video-wrapper' ).length >= wpj_vars.video_multiples ) $( '.js-add-video' ).hide();
	});

	// Delete Video
	$( document ).on( 'click', '.js-delete-video', function( e ) {
		if ( $( '.js-delete-video' ).length > 1 ) $( this ).parents( '.video-wrapper' ).remove();
		else $( '.video-link' ).val( '' );

		if ( $( '.video-wrapper' ).length < wpj_vars.video_multiples ) $( '.js-add-video' ).show();
		else $( '.js-add-video' ).hide();
	});

	// Add New FAQ
	$( document ).on( 'click', '.js-add-faq', function( e ) {
		var last_faq_row = $( '.faq-wrapper' ).last().clone();

		last_faq_row.find( '.title' ).html( wpj_vars.insert_faq + '<i class="angle down icon"></i>');
		last_faq_row.find( 'input, textarea' ).val( '' );

		last_faq_row.insertAfter( '.faq-wrapper:last' );

		$( '.ui.accordion' ).accordion();
	});

	// Delete FAQ
	$( document ).on( 'click', '.js-delete-faq', function( e ) {
		if ( $( '.js-delete-faq' ).length > 1 ) {
			$( this ).parents( '.faq-wrapper' ).remove();

		} else {
			$( this ).siblings( '.faq-item' ).find( '.title' ).html( '<i class="dropdown icon"></i>' + wpj_vars.insert_faq );
			$( this ).siblings( '.faq-item' ).find( 'input, textarea' ).val( '' );
		}
	});

	// Add New Extra
	$( document ).on( 'click', '.js-add-extra', function( e ) {

		$new_extra = $( '.js-extra-wrapper' ).last().clone();
		$id = $new_extra.attr( 'id' ).split( '_' );
		$id = parseInt( $id[1] );

		if ( $id + 1 <= wpj_vars.extra_multiples ) {
			$sep = $( '<div id="field_separator" class="field_separator"><div class="ui section divider"></div></div>' ).insertAfter( $( '.js-extra-wrapper' ).last() );

			$next_id = $id + 1;
			$new_extra.attr( 'id', 'extra_' + $next_id );

			$new_extra.find( 'textarea' ).each( function() {
				$( this ).removeClass( 'charlimit-extradescription-' + $id );
				$( this ).addClass( 'charlimit-extradescription-' + $next_id );
			});

			$new_extra.find( '.charscounter' ).eq( 0 ).remove();

			$new_extra.find( ':input' ).each( function() {
				this.name = this.name.replace( $id, $next_id );
				this.id   = this.id.replace( $id, $next_id );

				if ( e.originalEvent !== undefined ) { // if button is clicked

					if ( this.type == 'number' || this.type == 'textarea' ) {
						$( this ).val( '' );
					}

					$( this ).parents( '.field' ).removeClass( 'error' );
					$( this ).parent().checkbox( 'uncheck' );
					$( this ).parent().children( '.text' ).addClass( 'default' ).html( wpj_vars.lbl_please_select );
					$( this ).parent().children( '.menu' ).children( '.item.active.selected' ).removeClass( 'active' ).removeClass( 'selected' );

				} else { // if button is triggered( for edit job )

					var inc = [];
					$.each( JSON.parse( wpj_vars.extra_enable ), function( key, value ) {
						if ( key != 0 && value == 'yes' ) {
							inc.push( key );
						}
					});

					var content_id = parseInt( $id ) - 1;

					var obj_enable_extra = JSON.parse( wpj_vars.extra_enable );
					if ( this.name == 'enable_extra_' + $next_id ) {
						if ( obj_enable_extra[inc[content_id]] == 'yes' ) {
							$( this ).attr( 'checked', 'checked' );
						} else {
							$( this ).removeAttr( 'checked' );
						}
					}

					var obj_extra_description = JSON.parse( wpj_vars.extra_description );
					if ( this.name == 'extra' + $next_id + '_content' ) {
						$( this ).val( obj_extra_description[inc[content_id]] );

						// job rejected
						var obj_rej_comment = JSON.parse( wpj_vars.rej_comment.replace( /\n/g, "" ).replace( /\r/g, "" ).replace( /\t/g, "" ) );
						if ( obj_rej_comment[inc[content_id]] != "" ) {
							$( this ).addClass( 'rejected-input' );
							$( this ).parent().siblings( '.ui.popup' ).html( obj_rej_comment[inc[content_id]] );
							$( this ).parent().siblings( '.ui.popup' ).addClass( 'rejected-input' );
						}

					}

					var obj_extra_price = JSON.parse( wpj_vars.extra_price );
					if ( this.name == 'extra' + $next_id + '_price' ) {
						$( this ).val( obj_extra_price[inc[content_id]] );
					}

					var obj_extra_max_days = JSON.parse( wpj_vars.extra_max_days );
					if ( this.name == 'max_days_' + $next_id ) {
						$( this ).dropdown( 'set selected', obj_extra_max_days[inc[content_id]] );
					}

					var obj_extra_multiple = JSON.parse( wpj_vars.extra_multiple );
					if ( this.name == 'enable_multiples_' + $next_id ) {
						if ( obj_extra_multiple[inc[content_id]] == 'yes' ) {
							$( this ).attr( 'checked', 'checked' );
						} else {
							$( this ).removeAttr( 'checked' );
						}
					}
				}
			});

			$new_extra.insertAfter( $sep );

			// initialize semantic ui fields
			$.fn.wpjSemanticInit();

			// initialize textarea counter
			$( '.charlimit-extradescription-' + $next_id ).counted( { count: wpj_vars.characters_extradesc_max } );
		}

		if ( $id + 1 >= wpj_vars.extra_multiples ) $( '.js-add-extra' ).hide();
	});

	// Delete a Extra
	$( document ).on( 'click', '.js-delete-extra', function( e ) {
		if ( $( '.js-delete-extra' ).length > 1 ) {
			$( this ).parents( '.js-extra-wrapper' ).next( '.fields' ).remove();
			$( this ).parents( '.js-extra-wrapper' ).remove();

			var count = 1;
			$( '.js-extra-wrapper' ).each( function() {
				$id = $( this ).attr( 'id' ).split( '_' );
				$id = parseInt( $id[1] );

				$( this ).attr( 'id', 'extra_' + count );
				$( this ).find( ':input' ).each( function() {
					this.name = this.name.replace( $id, count );
					this.id = this.id.replace( $id, count );
				});
				count++;
			});
		} else {
			$( this ).parents( '.js-extra-wrapper' ).find( '.price-input' ).val( '' );
			$( this ).parents( '.js-extra-wrapper' ).find( '.charlimit-extradescription' ).val( '' );
			$( this ).parents( '.js-extra-wrapper' ).find( '.ui.checkbox' ).each( function() {
				$( this ).checkbox( 'uncheck' );
			});

			$( this ).parents( '.js-extra-wrapper' ).find( '.max-day-deliver' ).children( '.text' ).addClass( 'default' ).html( wpj_vars.lbl_please_select );
			$( this ).parents( '.js-extra-wrapper' ).find( '.max-day-deliver' ).children( '.menu' ).children( '.item.active.selected' ).removeClass( 'active' ).removeClass( 'selected' );
			$( this ).parents( '.js-extra-wrapper' ).find( '.max-day-deliver' ).prop( 'selectedIndex', 0 );
		}

		$( '.js-add-extra' ).show();
	});

	// Remove Unchecked Extra
	$( document ).on( 'click', '.post-new-job-btn', function( e ) {
		$( function( $ ) {
			$( '.js-extra-wrapper' ).each( function() {
				$id = $( this ).attr( 'id' ).split( '_' );
				$id = parseInt( $id[1] );
				if ( ! $( this ).find( '#enable_extra_' + $id ).is( ':checked' ) ) {
					$( this ).find( '.js-delete-extra' ).trigger( 'click' );
				}
			});
		});
	});

});

// Check Delivery Time
function wpj_check_job_delivery_time() {
	var execute      = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "yes";
	var max_days_val = jQuery( '#max_days' ).val();

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

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

	});

	var price_type = jQuery( 'select[name="price_type"]' ).val();

	execute = Hooks.apply_filters( 'wpj_execute_validation_filter', execute, price_type );

	if ( max_days_val == 'instant' && execute == 'yes' && price_type != 'package' ) {
		jQuery( '#max_days_fast' ).val( 'instant' );
		jQuery( '#enable_extra_fast' ).prop( 'checked', false );
		jQuery( '#enable_extra_fast' ).parent().addClass( 'disabled' );
		jQuery( '#extra_fast_price' ).parent().addClass( 'disabled' );
		jQuery( '#max_days_fast' ).parent().addClass( 'disabled' );

	} else {
		jQuery( '#enable_extra_fast' ).parents().removeClass( 'disabled' );
		jQuery( '#extra_fast_price' ).parents().removeClass( 'disabled' );
		jQuery( '#max_days_fast' ).parents().removeClass( 'disabled' );

	}
}

// Load Extras
function wpj_load_job_extras() {
	if ( jQuery( '.page-id-' + wpj_vars.new_job_page_id )[0] && wpj_vars.extra_enable ) {
		// Add wrapper
		jQuery( '.fields' ).has( '.extra-item' ).wrapAll( '<div id="extra_1" class="extra-wrapper js-extra-wrapper" data-validate="extra_wrapper">' );

		// Add extras dynamically
		jQuery.each( JSON.parse( wpj_vars.extra_enable ), function( key, value ) {
			if ( key != 0 && value == 'yes' ) jQuery( '.js-add-extra' ).trigger( 'click' );
		});

		// Initialize semantic ui fields
		jQuery.fn.wpjSemanticInit();
	}
}