function compareDates(dateStr1, dateStr2) {
  // Parse into Date objects (safe for YYYY-MM-DD format)
  const d1 = new Date(dateStr1);
  const d2 = new Date(dateStr2);

  if (d1.getTime() === d2.getTime()) {
    return 0;   // equal
  } else if (d1.getTime() < d2.getTime()) {
    return -1;  // first is earlier
  } else {
    return 1;   // first is later
  }
}
/**
 * 
 * @param {first date} date1 
 * @param {second date} date2 
 * new Date(...) → safely parses ISO format (YYYY-MM-DD)
 * isNaN(...) to avoid invalid date errors
 * @returns boolean
 */
function isDateGreater(date1, date2) {
  const d1 = new Date(date1);
  const d2 = new Date(date2);

  // Check if both are valid dates
  if (isNaN(d1) || isNaN(d2)) return false;

  return d1 > d2;
}

jQuery(document).ready(function($) {					
	//console.log('wordform_admin_view_page_script loaded...');
	//console.log(wordform_admin_view_page_script_obj);
	
	var wordformPostIDReadyHandler = 0;
	var wordformSelectFormListReadyHandler = 0;

	// Block-Editor: Wait to have Post ID Ready - then insert wordform
	function wordformBlockEditorWaitTohavePostIdReady() {
		let postID = wp.data.select("core/editor").getCurrentPostId();			
		if ( postID ) { 
			//console.log('Block-Editor Post ID ready: '+ postID); 
			clearInterval( wordformPostIDReadyHandler ); 
			// Insert WordForm Block
			let block = wp.blocks.createBlock( 'wordform-block/wordform', { wordformid: wordform_admin_view_page_script_obj.attachto_wordformid } );
			wp.data.dispatch('core/block-editor').insertBlock( block );					
		}			
		else { 
			//console.log('Waiting to have Post Id get Ready...'); 
		}
	}
			
	// Attach to: Attach wordform block with Post | Page Editor - Attach only when users click the Attach to Post | Page from All Forms page
	if ( wordform_admin_view_page_script_obj.attachto_wordformid && wordform_admin_view_page_script_obj.attachto_wordformid.length > 0 ) {
		//console.log('AttachFormID: '+ wordform_admin_view_page_script_obj.attachto_wordformid );			
		wordformPostIDReadyHandler = setInterval( () => wordformBlockEditorWaitTohavePostIdReady() , 1000 );		
	}				
	
	// All Forms: Display all created forms Page
	if ( $('div#wordformAllFormsWrapperTable').length > 0 ) {
		//$('#wordformAllFormsTable').DataTable();								
		$('#wordformAllFormsTable').DataTable({
			order: [[ 2, 'desc' ]]
		});
		$('#wordformAllFormsWrapperTable').fadeIn(300);
		// Fix Show Entries select box UI
		$('body').removeClass('wp-core-ui');

		// Copy Shortcode
		new ClipboardJS('.sc-wordform-shortcode-copy-text');

		$('body').on('mouseenter', '#wordformAllFormsTable tr', function() {
			$(this).find('.sc-wordform-shortcode-copy-text').show();
		});
		$('body').on('mouseleave', '#wordformAllFormsTable tr', function() {
			$(this).find('.sc-wordform-shortcode-copy-text').hide();
		});

		$('body').on('click', '.sc-wordform-shortcode-copy-text', function() {	
			let copyBtnTextEle	= $(this);
			copyBtnTextEle.html( wordform_admin_view_page_script_obj.wordform_copied_text );
			setTimeout(function() { copyBtnTextEle.html( wordform_admin_view_page_script_obj.wordform_copy_shortcode_text );}, 3000);
		});
	}
	
    // Create Form : Create form without save leaving window
	if ( $('div.wordform-draggable-elements-div-wrapper').length > 0 ) {
		$(window).on('beforeunload', function(e) {			 
			 let scWordFormElementDropped  = $('.wordform-dropzone-div-wrapper').children().length;
			 let scWordFormID	= $('.wordform-created-form-id').val();
			 //console.log(scWordFormID.length );
			 // Changes but not saved
			 if ( $.trim( scWordFormID ).length === 0 && scWordFormElementDropped > 0 ) {
				 return 'Please click Save Form button to save your form.';	 
			 }
			 else if ( $.trim( scWordFormID ).length > 0 ) {				
				return '';	 
			 }            

			return '';
		});
	}
	
	// WP Color Picker: Configuration
	var myOptions = {			
		defaultColor: false,
		// a callback to fire whenever the color changes to a valid color
		change: function(event, ui){},
		// a callback to fire when the input is emptied or an invalid color
		clear: function() {},
		// hide the color picker controls on load
		hide: true,
		// show a group of common colors beneath the square
		// or, supply an array of colors to customize further
		palettes: true
	};		
	// Enable Color Picker for selected Element
	var wordFormColorPickerSelectors = '.sc-wordform-form-submit-button-background-color, .sc-wordform-form-submit-button-background-hover-color, .sc-wordform-form-submit-button-font-color, .sc-wordform-upload-progress-bar-color';
	$( wordFormColorPickerSelectors ).wpColorPicker( {
		change: function(event, ui ) {
			// console.log( $(this) );
			// console.log( $(this).val() );
			// console.log( 'Changed Color: '+ ui.color.toString() );									
			// console.log(event);
		}
	});
		
	
	// Tabs : Enable
	if ( $('div#tabs').length > 0 ) {
		$('#tabs').tabs().promise().done(function() {
			$('.sc-wordform-tabs-wrapper-div').fadeIn(300);
		});		
	}
	
	// Submission Data Page: Submission Report - Display all users submission Report total submissions against each form - Ajax Loaded DataTable
	if ($('div#wordformUsersSubmissionReportWrapperTable').length > 0) {
		$('#wordformUsersSubmissionReportDataTable').DataTable({
			processing: true,
			serverSide: true,
			paging: true,
			searching: true,          // global search box
			lengthChange: true,
			pageLength: 10,
			lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
			ajax: {
				type: 'POST',
				url: wordform_admin_view_page_script_obj.adminajax_url,
				data: function(d) {
					d.action   = 'sc_wordform_users_submission_report_load';
					d.security = wordform_admin_view_page_script_obj.nonce;
					// DataTables automatically sends d.search.value for global search
				}
			},
			columns: [
				{ data: 'formName', orderable: true, searchable: true },        // form name searchable
				{ data: 'totalSubmission', orderable: true, searchable: true }, // now searchable
				{ data: 'lastSubmissionDate', orderable: true, searchable: true } // date column searchable
			],
			order: [[2, 'desc']] // default sort: latest submissions first
		});

		$('#wordformUsersSubmissionReportWrapperTable').fadeIn(300);
		$('body').removeClass('wp-core-ui');
	}


	// Submission data Page: Forms Submission data Deatils - Ajax loaded DataTable
	if ($('#wordformUsersFormSubmissionDataWrapperTable').length > 0) {
		const formId = $('#wordformUsersFormSubmissionDataWrapperTable').data('form-id'); // set form-id as data attribute
		$('#wordformUsersFormSubmissionDataTable').DataTable({
			processing: true,
			serverSide: true,
			paging: true,
			searching: true,
			lengthChange: true,
			pageLength: 10,
			lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
			ajax: {
				type: 'POST',
				url: wordform_admin_view_page_script_obj.adminajax_url,
				data: function (d) {
					d.action   = 'sc_wordform_users_submission_data_load';
					d.security = wordform_admin_view_page_script_obj.nonce;
					d.form_id  = formId;
				}
			},
			columns: [
				{ data: 'formName', orderable: true, searchable: true },
				{ data: 'submissionData', orderable: true, searchable: true },
				{ data: 'date', orderable: true, searchable: true }
			],
			order: [[2, 'desc']] // default: latest submissions first
		});
	}

	// ----------------------------------------------------
	// ✅ General Settings Tab: On Change Form Selection Dropdown
	//                          Load general tab settings configuration
	// ---------------------------------------------------
	$('body').on('change', '#scWordformSelectGeneralTabFor', function() {
		let formID = $(this).val();
		let updateInfoEle = $('.sc-wordform-general-tab-update-info').html('Loading...');

		$.ajax({
			type: "POST",
			url: sc_wordform_metabox_script_obj.adminajax_url,
			data: {
				action: 'sc_wordform_get_general_tab_data',
				security: sc_wordform_metabox_script_obj.nonce,
				form_id: formID
			},
			success: function(data) {
				let json = JSON.parse(data);
				if (json.status === 'success' && json.settings) {
					// Refill form fields
					$('.sc-wordform-form-width').val(json.settings.wordform_form_width);
					$('.sc-wordform-form-width-slider').slider('value', json.settings.wordform_form_width)
						.siblings('.slider-value-display').text(json.settings.wordform_form_width + '%');

					$('.sc-wordform-form-submit-button-background-color').val(json.settings.submit_button_background_color)
						.closest('div.wp-picker-container').find('button[type="button"]')
						.css('background-color', json.settings.submit_button_background_color);

					$('.sc-wordform-form-submit-button-background-hover-color').val(json.settings.submit_button_background_hover_color)
						.closest('div.wp-picker-container').find('button[type="button"]')
						.css('background-color', json.settings.submit_button_background_hover_color);

					$('.sc-wordform-form-submit-button-font-color').val(json.settings.submit_button_font_color)
						.closest('div.wp-picker-container').find('button[type="button"]')
						.css('background-color', json.settings.submit_button_font_color);

					$('.sc-wordform-form-submit-button-text-size').val(json.settings.submit_button_font_size);
					$('.sc-wordform-form-submit-button-padding-top-bottom').val(json.settings.submit_button_padding_top_bottom);
					$('.sc-wordform-form-submit-button-padding-left-right').val(json.settings.submit_button_padding_left_right);

					$('input[name="sc-wordform-form-submit-button-font-weight"]').prop('checked', false)
						.filter('[value="' + json.settings.submit_button_font_weight + '"]').prop('checked', true);

					$('.sc-wordform-form-submission-send-email').prop('checked', json.settings.send_email_on_form_submission === 'yes');
					$('.sc-wordform-form-submission-hide-form').prop('checked', json.settings.hide_form_on_form_submission === 'yes');

					updateInfoEle.html(json.message).addClass('text-success');
				} else {
					updateInfoEle.html(json.message || 'Error loading settings').addClass('text-error');
				}
			},
			error: function(xhr, status, error) {
				console.log(error);
				updateInfoEle.html('Failed to load settings.').addClass('text-error');
			}
		});
	});



	// -----------------------------------------
	// ✅ General Tab Slider: Form Width (%)
	// ------------------------------------------
	const formWidth = parseInt($('.sc-wordform-form-width').val()) || 100;
	$('.sc-wordform-form-width-slider').slider({		
		range: "min",
		value: formWidth,
		min: 30,
		max: 100,
		step: 1,
		slide: function (event, ui) {
			$('.sc-wordform-form-width').val(ui.value);
			$(this).next('.slider-value-display').text(ui.value + '%');
		}
	}).next('.slider-value-display').text(formWidth + '%');


	// // -----------------------------------------
	// // ✅ General Tab: Reset Button Action 
	// // ------------------------------------------
	// $('body').on('click', '.sc-wordform-settings-general-tab-reset', function() {
	// 	let backgroundColor			=  '#2271b1';
	// 	let backgroundHoverColor	=  '#006ba1';
	// 	let buttonFontColor			=  '#ffffff';
	// 	let buttonTextSize			=  '16';
	// 	let paddingTopBottom		=  '12';
	// 	let paddingLeftRight		=  '25';
	// 	let wordformFormWidth		=  '100';
		
	// 	const applyGeneralSettingsDefaults = () => {
	// 		// Send Email checkbox
	// 		$('.sc-wordform-form-submission-send-email').removeAttr('checked');

	// 		// Button background color
	// 		$('.sc-wordform-form-submit-button-background-color').val( backgroundColor).promise().done(function() {
	// 			$('.sc-wordform-form-submit-button-background-color').closest('div.wp-picker-container').find('button[type="button"]').css("background-color", backgroundColor).promise().done(function() {
	// 			});
	// 		});

	// 		// Button background color (hover)
	// 		$('.sc-wordform-form-submit-button-background-hover-color').val( backgroundHoverColor ).promise().done(function() {
	// 			$('.sc-wordform-form-submit-button-background-hover-color').closest('div.wp-picker-container').find('button[type="button"]').css("background-color", backgroundHoverColor).promise().done(function() {
	// 			});
	// 		});

	// 		// Button font color
	// 		$('.sc-wordform-form-submit-button-font-color').val( buttonFontColor ).promise().done(function() {
	// 			$('.sc-wordform-form-submit-button-font-color').closest('div.wp-picker-container').find('button[type="button"]').css("background-color", buttonFontColor).promise().done(function() {
	// 			});
	// 		});

	// 		// Wordform Form Width
	// 		$('.sc-wordform-form-width').val( wordformFormWidth );
	// 		// Set Slider Value
	// 		$('.sc-wordform-form-width-slider').slider( "value", wordformFormWidth ).siblings('.slider-value-display').text(wordformFormWidth + '%');			

	// 		// Button font-size 
	// 		$('.sc-wordform-form-submit-button-text-size').val( buttonTextSize );	

	// 		// Padding (Top-Bottom)
	// 		$('.sc-wordform-form-submit-button-padding-top-bottom').val( paddingTopBottom );		

	// 		// Padding (Left-Right)
	// 		$('.sc-wordform-form-submit-button-padding-left-right').val( paddingLeftRight );		


	// 		// Button font-weight
	// 		$('input[name="sc-wordform-form-submit-button-font-weight"]').removeAttr('checked').promise().done(function() {
	// 			$('input[name="sc-wordform-form-submit-button-font-weight"]:first').attr('checked', true ).click();
	// 		});

	// 		// Trigger Submit form
	// 		$('#scWordformSettingsGeneralTabForm').trigger('submit');
	// 	};


	// -----------------------------------------
	// ✅ General Tab: Reset Button Action (Dynamic)
	// ------------------------------------------
		$('body')
			.off('click', '.sc-wordform-settings-general-tab-reset')
			.on('click', '.sc-wordform-settings-general-tab-reset', function(event) {
				event.preventDefault();

				const $resetTrigger = $(this);
				const updateInfoEle = $('.sc-wordform-general-tab-update-info');
				const selectedFormId = $('#scWordformSelectGeneralTabFor').val(); // current selected form

				const applyGeneralSettingsDefaults = () => {
					updateInfoEle
						.html('Resetting to defaults...')
						.removeClass('text-success text-error')
						.addClass('text-info');

					$.ajax({
						type: "POST",
						url: sc_wordform_metabox_script_obj.adminajax_url,
						data: {
							action: 'sc_wordform_get_general_tab_default_data',
							security: sc_wordform_metabox_script_obj.nonce,
							form_id: selectedFormId
						},
						success: function(response) {
							let json = JSON.parse(response);

							if (json.status === 'success' && json.defaults) {
								const d = json.defaults;

								// --- Apply defaults to fields ---
								$('.sc-wordform-form-width').val(d.wordform_form_width);
								$('.sc-wordform-form-width-slider')
									.slider('value', d.wordform_form_width)
									.siblings('.slider-value-display')
									.text(d.wordform_form_width + '%');

								// Button colors
								const colorFields = [
									{ cls: '.sc-wordform-form-submit-button-background-color', val: d.submit_button_background_color },
									{ cls: '.sc-wordform-form-submit-button-background-hover-color', val: d.submit_button_background_hover_color },
									{ cls: '.sc-wordform-form-submit-button-font-color', val: d.submit_button_font_color }
								];
								colorFields.forEach(f => {
									$(f.cls).val(f.val)
										.closest('div.wp-picker-container')
										.find('button[type="button"]').css('background-color', f.val);
								});

								// Font size, padding
								$('.sc-wordform-form-submit-button-text-size').val(d.submit_button_font_size);
								$('.sc-wordform-form-submit-button-padding-top-bottom').val(d.submit_button_padding_top_bottom);
								$('.sc-wordform-form-submit-button-padding-left-right').val(d.submit_button_padding_left_right);

								// Font weight
								$('input[name="sc-wordform-form-submit-button-font-weight"]').prop('checked', false)
									.filter('[value="' + d.submit_button_font_weight + '"]').prop('checked', true);

								// Checkboxes
								$('.sc-wordform-form-submission-send-email').prop('checked', d.send_email_on_form_submission === 'yes');
								$('.sc-wordform-form-submission-hide-form').prop('checked', d.hide_form_on_form_submission === 'yes');

								updateInfoEle.html('Defaults applied. Saving...').removeClass('text-info').addClass('text-success');

								// Trigger form submit to save these defaults for the selected form
								$('#scWordformSettingsGeneralTabForm').trigger('submit');
							} else {
								updateInfoEle.html('Could not fetch default settings.').removeClass('text-info').addClass('text-error');
							}
						},
						error: function(xhr, status, error) {
							console.log(error);
							updateInfoEle.html('Error fetching default settings.').removeClass('text-info').addClass('text-error');
						}
					});
				};

				const dialogId = 'wordform-settings-general-reset-dialog';
				$('#' + dialogId).remove();

				const $dialogContent = $('<div id="' + dialogId + '" title="Reset General Settings">' +
					'<p>Do you want to set default settings?</p>' +
				'</div>').appendTo('body');

				const triggerOffset = $resetTrigger.offset() || { top: 0, left: 0 };
				const triggerHeight = $resetTrigger.outerHeight() || 0;
				const windowHeight = $(window).height();
				const scrollTop = $(window).scrollTop();
				const estimatedDialogHeight = 160;
				const spaceBelowTrigger = scrollTop + windowHeight - (triggerOffset.top + triggerHeight + estimatedDialogHeight + 20);

				const positionOptions = spaceBelowTrigger >= 0
					? { my: 'center top', at: 'center bottom+20', of: $resetTrigger }
					: { my: 'center bottom', at: 'center top-20', of: $resetTrigger };

				$dialogContent.dialog({
					modal: true,
					resizable: false,
					draggable: false,
					width: 420,
					position: positionOptions,
					appendTo: 'body',
					zIndex: 100000,
					buttons: {
						Reset: function() {
							applyGeneralSettingsDefaults();
							$(this).dialog('close');
						},
						Cancel: function() {
							$(this).dialog('close');
						}
					},
					close: function() {
						$(this).remove();
					}
				});
			});
		});


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

	/** ---------------------------------------------------------------
	 * Settings Upload Tab: Save Button Action
	 * --------------------------------------------------------------- */	
	$('#scWordformSettingsUploadTabForm').on('submit', function() {
		let updateInfoEle	= $('.sc-wordform-upload-tab-update-info');
		let postData		= $(this).serialize();
		//console.log(postData);
		let params			= {};
		params.formData		= postData;
		updateInfoEle.html('').removeClass('text-success text-error');
		$.ajax({
		  type:"POST",		  
		  url: sc_wordform_metabox_script_obj.adminajax_url,
		  data : {			    
				action 	    : 'sc_wordform_settings_upload_tab_form',
				security    : sc_wordform_metabox_script_obj.nonce,				
				params 		: params
				},		  
		  success: function(data) { 
			 console.log(data); 
			 let jsonData	= JSON.parse( data );
			  if ( jsonData.status == 'success' ) {		
				  updateInfoEle.html(jsonData.successMsg).addClass('text-success');
			  }
			  else if ( jsonData.status == 'warning' ) {			
				updateInfoEle.html(jsonData.warningMsg).addClass('text-info');
			  }
			  else if ( jsonData.status == 'fail' ) {			
				  updateInfoEle.html(jsonData.failMsg).addClass('text-error');
			  }

			},
		  error: function( xhr, status, error ) { 
			 console.log(xhr); 
			 console.log(status); 
			 console.log(error); 				 

			}
		});			
	
	return false;
	});


	/** ---------------------------------------------------------------
	 * Settings Upload Tab: Initialize Upload Tab Range Sliders on Load
	 * --------------------------------------------------------------- */
	const uploadData = wordform_admin_view_page_script_obj.wordform_upload_config_data || {};
			
	// Max Files Slider
	const maxFiles = parseInt($('.sc-wordform-upload-max-numof-files').val()) || 0;		
	console.log('maxFiles: ', maxFiles);
	$('.sc-wordform-upload-max-numof-files-slider').slider({			
		range: "min",
		value: maxFiles,
		min: 1,
		step: 1,
		max: parseInt(uploadData.server_max_num_files_allowed) || 1000,
		slide: function (event, ui) {				
			$('.sc-wordform-upload-max-numof-files').val(ui.value);
			$(this).next('.slider-value-display').text(ui.value);
		}
	}).next('.slider-value-display').text(maxFiles);

	// Each File Size Slider
	const eachFileSize = parseInt($('.sc-wordform-upload-each-file-max-size').val()) || 0;
	console.log('eachFileSize: ', eachFileSize);
	$('.sc-wordform-upload-each-file-max-size-slider').slider({			
		range: "min",
		value: eachFileSize,
		min: 1,
		step: 1,
		max: parseInt(uploadData.server_each_file_max_size_allowed) || 2000,
		slide: function (event, ui) {
			$('.sc-wordform-upload-each-file-max-size').val(ui.value);
			$(this).next('.slider-value-display').text(ui.value + ' MB');
		}
	}).next('.slider-value-display').text(eachFileSize + ' MB');

	// All Files Size Slider
	const allFilesSize = parseInt($('.sc-wordform-upload-all-files-max-size').val()) || 0;
	console.log('allFilesSize: ', allFilesSize);
	$('.sc-wordform-upload-all-files-max-size-slider').slider({			
		range: "min",
		value: allFilesSize,
		min: 1,
		step: 1,
		max: parseInt(uploadData.server_all_files_max_size_allowed) || 5000,
		slide: function (event, ui) {
			$('.sc-wordform-upload-all-files-max-size').val(ui.value);
			$(this).next('.slider-value-display').text(ui.value + ' MB');
		}
	}).next('.slider-value-display').text(allFilesSize + ' MB');	


	/** ----------------------------------------------------------------
	 * Settings Upload Tab: Reset to Defaults - Reset Button Action
	 * --------------------------------------------------------------- */
/* START: Old Upload Reset (kept for reference)
$('body').on('click', '.sc-wordform-settings-upload-tab-reset', function () {
		if (!confirm('Do you want to reset upload settings to default values?')) return;

		// Default server values
		let defMaxFiles = uploadData.server_max_num_files_allowed;
		let defEachFile = uploadData.server_each_file_max_size_allowed;
		let defAllFiles = uploadData.server_all_files_max_size_allowed;
		let defColor   = '#2271b1';
		let defFormWidth = 100; // General tab default

		// ✅ Reset: Upload - Max Number Of Files
		$('.sc-wordform-upload-max-numof-files').val(defMaxFiles);
		$('.sc-wordform-upload-max-numof-files-slider')
			.slider('value', defMaxFiles)
			.siblings('.slider-value-display').text(defMaxFiles);

		// ✅ Reset: Upload - Each File Max Size
		$('.sc-wordform-upload-each-file-max-size').val(defEachFile);
		$('.sc-wordform-upload-each-file-max-size-slider')
			.slider('value', defEachFile)
			.siblings('.slider-value-display').text(defEachFile + ' MB');

		// ✅ Reset: Upload - All Files Max Size
		$('.sc-wordform-upload-all-files-max-size').val(defAllFiles);
		$('.sc-wordform-upload-all-files-max-size-slider')
			.slider('value', defAllFiles)
			.siblings('.slider-value-display').text(defAllFiles + ' MB');

		// ✅ Reset: General - Form Width
		$('.sc-wordform-form-width').val(defFormWidth);
		$('.sc-wordform-form-width-slider')
			.slider('value', defFormWidth)
			.siblings('.slider-value-display').text(defFormWidth + '%');

		// ✅ Reset: Show / Hide Progress Bar
		$('.sc-wordform-upload-progress-bar-show-hide').prop('checked', true);

		// ✅ Reset: Progress Bar Color
		$('.sc-wordform-upload-progress-bar-color').val(defColor).promise().done(function () {
			$(this).closest('div.wp-picker-container')
				.find('button[type="button"]')
				.css('background-color', defColor);
		});

		// ✅ Trigger form submit
	$('#scWordformSettingsUploadTabForm').trigger('submit');
	});
*/

	});

	jQuery(document).ready(function($) {
    /** ----------------------------------------------------------------
     * Settings Upload Tab: Reset to Defaults - Reset Button Action - 
     * WP jQuery UI Dialog Modal
     * --------------------------------------------------------------- */
    $('body').off('click', '.sc-wordform-settings-upload-tab-reset').on('click', '.sc-wordform-settings-upload-tab-reset', function () {
        /* Old confirm-based logic retained above. This override uses WP jQuery UI dialog for consistency. */

        const applyUploadSettingsDefaults = () => {
            let defMaxFiles  = uploadData.server_max_num_files_allowed;
            let defEachFile  = uploadData.server_each_file_max_size_allowed;
            let defAllFiles  = uploadData.server_all_files_max_size_allowed;
            let defColor     = '#2271b1';
            let defFormWidth = 100;

            $('.sc-wordform-upload-max-numof-files').val(defMaxFiles);
            $('.sc-wordform-upload-max-numof-files-slider')
                .slider('value', defMaxFiles)
                .siblings('.slider-value-display').text(defMaxFiles);

            $('.sc-wordform-upload-each-file-max-size').val(defEachFile);
            $('.sc-wordform-upload-each-file-max-size-slider')
                .slider('value', defEachFile)
                .siblings('.slider-value-display').text(defEachFile + ' MB');

            $('.sc-wordform-upload-all-files-max-size').val(defAllFiles);
            $('.sc-wordform-upload-all-files-max-size-slider')
                .slider('value', defAllFiles)
                .siblings('.slider-value-display').text(defAllFiles + ' MB');

            $('.sc-wordform-form-width').val(defFormWidth);
            $('.sc-wordform-form-width-slider')
                .slider('value', defFormWidth)
                .siblings('.slider-value-display').text(defFormWidth + '%');

            $('.sc-wordform-upload-progress-bar-show-hide').prop('checked', true);

            $('.sc-wordform-upload-progress-bar-color').val(defColor).promise().done(function () {
                $(this).closest('div.wp-picker-container')
                    .find('button[type="button"]')
                    .css('background-color', defColor);
            });

            $('#scWordformSettingsUploadTabForm').trigger('submit');
        };

        const $resetTrigger = $(this);
        const dialogId = 'wordform-settings-upload-reset-dialog';
        $('#' + dialogId).remove();

        const $dialogContent = $('<div id="' + dialogId + '" title="Reset Upload Settings">' +
            '<p>Do you want to reset upload settings to default values?</p>' +
        '</div>').appendTo('body');

        const triggerOffset = $resetTrigger.offset();
        const triggerHeight = $resetTrigger.outerHeight();
        const windowHeight = $(window).height();
        const scrollTop = $(window).scrollTop();
        const estimatedDialogHeight = 160;
        const spaceBelowTrigger = scrollTop + windowHeight - (triggerOffset.top + triggerHeight + estimatedDialogHeight + 20);
        const positionOptions = spaceBelowTrigger >= 0
            ? { my: 'center top', at: 'center bottom+20', of: $resetTrigger }
            : { my: 'center bottom', at: 'center top-20', of: $resetTrigger };

        $dialogContent.dialog({
            modal: true,
            resizable: false,
            draggable: false,
            width: 420,
            position: positionOptions,
            appendTo: 'body',
            zIndex: 100000,
            buttons: {
                Reset: function () { applyUploadSettingsDefaults(); $(this).dialog('close'); },
                Cancel: function () { $(this).dialog('close'); }
            },
            close: function () { $(this).remove(); }
        });
    });


   // Range: Create or Edit Form | Build Form | Range Slider Value Settings 
   $('body').on('change', '.wordform-options-range-settings-values-ul-wrapper input', function(e) {		
		// Class Names: wordform-range-min-value | wordform-range-max-value | wordform-range-default-value | wordform-range-step-value
		let changedElementClass = $(this).prop('class').split('-')[2];
		let changedValue = $(this).val();		
		let sanitizedChangedValue = ! isNaN( parseFloat( changedValue ) ) ? parseFloat( changedValue ) : 0;
		console.log(changedElementClass);
		console.log(changedValue);
		let droppedRangeElement = $('.wordform-dropped-range-name');
		switch( changedElementClass ) {
			case 'min':
				droppedRangeElement.prop('min', sanitizedChangedValue );
			break;
			case 'max':
				droppedRangeElement.prop('max', sanitizedChangedValue );
			break;
			case 'default':
				droppedRangeElement.attr('value', sanitizedChangedValue );
			break;
			case 'step':
				droppedRangeElement.prop('step', sanitizedChangedValue );
			break;
		}
   }); 

   // Date: Create or Edit Form | Build Form | Date Value Settings    
//     let oldDateValue = '';
//    	$('body').on('focus', '.wordform-options-date-settings-values-ul-wrapper input', function(e) {		
// 			oldDateValue = $(this).val();
// 		}).on('change', '.wordform-options-date-settings-values-ul-wrapper input', function(e) {		
// 		// Class Names: wordform-date-min-value | wordform-date-max-value | wordform-date-default-value 
// 		let changingDateElementClassName = $(this).prop('class');
// 		// console.log('Changing Element Class: ' + changingDateElementClassName );
// 		let changedElementClass = $(this).prop('class').split('-')[2];
// 		let changedNewValue = $(this).val();				
// 		let sanitizedChangedValue =  ! isNaN ( Date.parse( changedNewValue ) )? changedNewValue : '0000-00-00';
// 		let droppedDateElement = $('.wordform-dropped-date-name');		

// 		const today = new Date();
// 		let Today = today.toLocaleDateString('en-CA').split('T')[0];
// 		let PreviousYear = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate()).toLocaleDateString('en-CA').split('T')[0];
// 		let NextYear = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate()).toLocaleDateString('en-CA').split('T')[0];			
// 		switch( changedElementClass ) {
// 			case 'min':				
// 			    // Is First date greater then 2nd date param
// 				if ( isDateGreater( changedNewValue, Today ) ) {
// 					// Keep the same date if wrong change					
// 					$(this).val( oldDateValue );
// 					alert('Minimum date must be earlier than today.');		
// 				}
// 				else {
// 					$(this).attr( "value", sanitizedChangedValue );
// 					droppedDateElement.prop('min', sanitizedChangedValue );
// 				}
// 			break;
// 			case 'max':
// 				// Is First date greater then 2nd date param
// 				if (  isDateGreater( Today, changedNewValue ) ) {					
// 					// Keep the same date if wrong change
// 					$(this).val( oldDateValue );
// 					alert('Maximum date must be later than today.');
// 				}
// 				else {
// 					$(this).attr( "value", sanitizedChangedValue );
// 					droppedDateElement.prop('max', sanitizedChangedValue );
// 				}
// 			break;
// 			case 'default':				
// 				$(this).attr( "value", sanitizedChangedValue );
// 				droppedDateElement.attr('value', sanitizedChangedValue );
// 			break;
// 		}
//    }); 


    // Date: On Change default date value in input options & change date display format from dropdown - update dropped element date value //

	// Initialize datepicker when field is focused - clicked
	$('body').on("focus", ".wordform-date-default-value", function(){
		if (!$(this).hasClass("hasDatepicker")) {
			$(this).datepicker({
				dateFormat: "yy-mm-dd", // internal raw format
				onSelect: () => {
					let elementIndex = $(this).closest('.wordform-date-field-options-wrapper')
											.prop("id").split("-")[1];
					let droppedWrapperId = '#wordformElement-' + elementIndex;
					let optionsWrapperId = '#wordformElementOptions-' + elementIndex;
					// On select get the selected date from datepicker		
					var selectedDate = $(this).datepicker("getDate");
					if(selectedDate){
						// Update default date input with YYYY-MM-DD format						
						var $dateInput = $(optionsWrapperId).find(".wordform-date-default-value");
						var rawDate = $.datepicker.formatDate("yy-mm-dd", selectedDate);
						console.log('On Select - Seet into default input field Raw Date ['+ optionsWrapperId +']: '+ rawDate );						
						$dateInput.attr("value", rawDate );
						// Update visible input with formatted date (stays formatted)
						// $(this).val($.datepicker.formatDate(displayFormat, selectedDate));
					}
					updateDroppedDate(droppedWrapperId, optionsWrapperId );
				}
			});
		}
		// Refresh - Redraw DatePicker - If earlier created
		$( this ).datepicker( "refresh" );
	});

	// Date: Function to update displayed date
	function updateDroppedDate( droppedWrapperId, optionsWrapperId ){		
		var $droppedWrapperId = $(droppedWrapperId);		
		var $optionsWrapperId = $(optionsWrapperId);				
		var $dateInput = $optionsWrapperId.find(".wordform-date-default-value");
		var $formatSelect = $optionsWrapperId.find(".wordform-default-date-display-format");
		var $droppedInput = $droppedWrapperId.find(".wordform-dropped-date-name");

		var rawDate = $dateInput.val(); // Get raw ISO value - YYYY-MM-DD 		
		var displayFormat = $formatSelect.val() || "yy-mm-dd";
		console.log('Got default date input Raw Date:'+ rawDate );
		console.log('Got Display Format: '+ displayFormat );

		if (rawDate && /^\d{4}-\d{2}-\d{2}$/.test(rawDate)) {
			var parts = rawDate.split("-");
			var dateObj = new Date(parts[0], parts[1]-1, parts[2]);
			var formatted = $.datepicker.formatDate(displayFormat, dateObj);

			// $droppedInput.val(formatted);
			console.log( 'Dropped Input Element set as Formated date: ' + formatted );
			$droppedInput.attr("value", formatted);
		} else {			
			$droppedInput.attr("value", "");			
			$dateInput.attr("value", "" );			
		}
	}
    
	// Date: On Change Display Date Format - Update Select Drop Down 'selected' attribute & Display date as new format
	$('body').on('change', 'select.wordform-default-date-display-format', function() {
		var $select = $(this);
		// Clear all 'selected' attributes first
		$select.find('option').attr('selected', false);
		// Set the newly chosen option as selected
		$select.find('option:selected').attr('selected', true);		
		console.log("Now selected Format:", $select.val());
      
		// Update display date in dropped input elements as new selected format
		let elementIndex = $(this).closest('.wordform-date-field-options-wrapper').prop("id").split("-")[1];
		let droppedWrapperId = '#wordformElement-' + elementIndex;		
		let optionsWrapperId = '#wordformElementOptions-' + elementIndex;
		updateDroppedDate(droppedWrapperId, optionsWrapperId );				
	});	

	// Connect Page: Accordion
	$("#google-oauth-help, #zapier-webhook-create-help").accordion({
		collapsible: true,
		active: false,
		heightStyle: "content"
	});
});
