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

	// Set checkbox as 'off' if is unchecked
	$( document ).on( "change", ".slider_field", function() {
		var value = $( this ).is( ":checked" ) ? 'on' : 'off';
		$( this ).siblings( "input[type='hidden']" ).val( value );
	});

	// Autocomplete ACF slug from label
	$( document ).on( 'click change', 'div[data-name="label"] input[type=text], div[data-name="slug"] input[type=text]', function( event ) {
		var this_input = $( this ).parents( '.acf-field' ).attr( 'data-name' );

		if ( this_input == 'label' ) {
			var slug = $( this ).val().toLowerCase().replace( / /g,"_" ).replace( /[^\w_]/g, '' );

			if ( ! $( this ).parents( '.acf-fields' ).eq(0).find( 'div[data-name="slug"]' ).find( 'input[type=text]' ).val() )
				$( this ).parents( '.acf-fields' ).eq(0).find( 'div[data-name="slug"]' ).find( 'input[type=text]' ).val( slug );

		} else if ( this_input == 'slug' ) {
			var slug = $( this ).parents( '.acf-fields' ).eq(0).find( 'div[data-name="label"]' ).find( 'input[type=text]' ).val().toLowerCase().replace( / /g,"_" ).replace( /[^\w_]/g, '' );

			if ( ! $( this ).val() ) $( this ).val( slug );

		}
	});

});

// Required field validation
Hooks.add_filter( 'wpj_fields_validation_filter', wpj_validate_cf_fields, 1 );
function wpj_validate_cf_fields( fields_arr, page ) {
	if ( jQuery( '.page-id-' + wpj_vars.new_request_page_id )[0] || jQuery( '.page-id-' + wpj_vars.new_job_page_id )[0] ) {
		jQuery( '.cf-required' ).each( function() {
			var inp_name = jQuery( this ).attr( 'name' );
			var inp_type = jQuery( this ).attr( 'type' ) == 'checkbox' || jQuery( this ).attr( 'type' ) == 'radio' ? 'checked' : 'empty';

			fields_arr[[inp_name]] = {
				identifier: inp_name,
				rules: [{
					type   : inp_type,
					prompt : jQuery( this ).attr( 'data-validation-message' )
				}]
			}

		});
	}

	return fields_arr;
}

// If slug is empty, autocomplete on page load
jQuery( window ).on( 'load', function() {

	if ( jQuery( 'div[data-layout="request_custom_field"]' ).length > 0 )  var cf_class = 'request_custom_field';
	else if ( jQuery( 'div[data-layout="job_custom_field"]' ).length > 0 ) var cf_class = 'job_custom_field';
	else if ( jQuery( 'div[data-layout="up_custom_field"]' ).length > 0 )  var cf_class = 'up_custom_field';
	else var cf_class = '';

	if ( cf_class ) {
		jQuery( 'div[data-layout="' + cf_class + '"]' ).each( function() {
			jQuery( this ).find( 'div[data-name="label"]' ).find( 'input[type="text"]' ).trigger( 'click' );
		});
	}
});