
var wordformOnloadgreCaptchaCallback = function() {
	console.log('grecaptcha is ready');	
  };	
var wordformreCaptchaErrorCallback = function(err) { console.err('reCAPTCHA Error:', err) }

jQuery(document).ready(function($) {	
	// console.log('SC-WORDFORM-FRONTEND-OBJECT');
	// console.log(sc_wordform_frontend_misc_script_obj);				
		
		// Front-end Users Form Submission - Single Page Multiple Form Support
		$('.sc-wordform-built-created-form-frontend-display-form').on("submit", function(e) {
			e.preventDefault();		
			// console.log(e);		
			let scWordformWrapperID				= $(this).prop('id');		
			let scWordformWrapper				= $('#'+scWordformWrapperID);
			let scWordFormLoadedElement         = scWordformWrapper.find('.wordform-users-form-submit-loading-icon');
			let gCapcthaTokenInputElementName   = scWordformWrapper.find('.wordform-gcaptcha-token-value').prop("name");
			let gCapcthaActionInputElementName  = scWordformWrapper.find('.wordform-gcaptcha-action-value').prop("name");
			let token                           = '';

			let wordformProgressBarEle          = $(".progress-bar");

			// Keep disabled submit button
			scWordformWrapper.find('button[type="submit"]').attr('disabled', true );
			
			let scWordFormOuterMostDivWrapper	= scWordformWrapper.parent();
			let scWordFormID					= scWordformWrapperID;				
			let gCaptchaActionValue             = scWordFormID.replace(/-/g, '_');
			let scWordFormName					= scWordformWrapper.data('scwordform-form-name');					
			let wordform_form_element 			= document.getElementById( scWordformWrapperID );
			let wordform_formdata 				= new FormData( wordform_form_element );	
			let wordform_total_files_uploading  = 0;		
			
			// console.log('wordform_selected_tmp_files');
			// console.log(wordform_selected_tmp_files);		

			// Append Selected files into FormData to upload to server - index is the each input type file element Id attribute
			$.each(wordform_selected_tmp_files, function( index, files ) {
			// Find the name attribute to assign upload file data	
			let inputTypeFileElementName = scWordformWrapper.find('#'+index).prop('name');
			// console.log(inputTypeFileElementName );
			wordform_formdata.delete( inputTypeFileElementName ); // Delete / Clear same name of FormData varriable before adding to avoid duplicate files uploading		   
			$.each( files, function(index, file) { 
					// console.log(file) 				     
					wordform_formdata.append( inputTypeFileElementName, file);				
					wordform_total_files_uploading += 1;
				});
			});

			// console.log('Total File Uploading: '+ wordform_total_files_uploading );

			wordform_formdata.append('action', 'sc_wordform_created_form_submission');
			wordform_formdata.append('security', sc_wordform_frontend_misc_script_obj.nonce);
			wordform_formdata.append('WordFormName', scWordFormName );
			wordform_formdata.append('WordFormID', scWordFormID );

			// console.log('wordform_formdata');
			// console.log(wordform_formdata);

			// Remove form submission report messages if exist
			scWordformWrapper.find('.sc-wordform-submission-success-msg-div-wrapper,.sc-wordform-submisson-fail-msg-div-wrapper').remove();
			scWordFormLoadedElement.show();
			scWordformWrapper.prev('.sc-wordform-submission-success-msg-div-wrapper').remove();
			scWordformWrapper.find('.sc-wordform-error-msg').text('');

			// When greCaptcha Key Available && greCaptcha integrated with form!
			if ( sc_wordform_frontend_misc_script_obj.gcaptcha_site_key.length > 0 
				        && sc_wordform_frontend_misc_script_obj.gcaptcha_version === 'v3' 
							&&  parseInt( sc_wordform_frontend_misc_script_obj?.gcaptcha_form_element_exist ) === 1 ) {

						// console.log('gCaptcha Site Key: '+ sc_wordform_frontend_misc_script_obj.gcaptcha_site_key );

						// greCaptcha Render
						// grecaptcha.render('testV3reCaptcha', {
						// 	'sitekey' : sc_wordform_frontend_misc_script_obj.gcaptcha_site_key,
						// 	'callback' : function(response) { 
						// 		console.log('render Callback');
						// 		console.log(response); 
						// 	},
						// 	// 'size': 'invisible',
						// 	// 'error-callback': errorHandling,
						// });								

						// Execute grecaptcha
					grecaptcha.ready( function() {
				 		grecaptcha.execute( sc_wordform_frontend_misc_script_obj.gcaptcha_site_key, {action: gCaptchaActionValue } ).then(function(token) {
				 		 // grecaptcha.enterprise.execute( sc_wordform_frontend_misc_script_obj.gcaptcha_site_key, {action: gCaptchaActionValue } ).then(function(token) {	
							// console.log('grecaptcha.execute Token: '+ token );
				 		 	// wordform_formdata.append('token', token );
				 		 	wordform_formdata.append( gCapcthaTokenInputElementName, token );				
				 		 	wordform_formdata.append( gCapcthaActionInputElementName, gCaptchaActionValue );

							//   console.log('reCAPTCHA( V3 ) FORM SUBMISSION');
							  $.ajax({
								xhr: function() {
										var xhr = new window.XMLHttpRequest();
										xhr.upload.addEventListener("progress", function(evt) {
											if (evt.lengthComputable) {						
												var percentComplete = ((evt.loaded / evt.total) * 100);
												// If Files are available to upload then show progress bar
												if ( wordform_total_files_uploading > 0 && sc_wordform_frontend_misc_script_obj.wordform_upload_config_data?.wordform_upload_show_hide_progress_bar == 'yes' ) {
													wordformProgressBarEle.width(percentComplete + '%').css( {'background-color' : sc_wordform_frontend_misc_script_obj.wordform_upload_config_data?.wordform_upload_progress_bar_color });
													wordformProgressBarEle.html(percentComplete+'%');
												}
											}
										}, false );
										return xhr;
								},			
					
								type : "POST",		  
								url  : sc_wordform_frontend_misc_script_obj.ajax_url,		  
								processData: false,
								contentType: false,
								data : wordform_formdata,		  				
					
								beforeSend: function() {
									wordformProgressBarEle.width('0%');					
								},
					
								success: function(data) { 
									wordformProgressBarEle.width('0%');
									// console.log(data); 
									jsonData	= JSON.parse( data );			 
									// console.log(jsonData ); 
									// Fail
									if ( jsonData.status == 'fail' ) {
										scWordFormLoadedElement.hide();
										if ( jsonData.validationErrorData ) {
											$.each( jsonData.validationErrorData, function( key, val ) {
												// console.log(val.validationMsgClass );
												// Show the error found on the element if certain class found for that element based on elementKey
												if ( typeof val.validationMsgClass !== 'undefined' ) {
													$('.'+val.validationMsgClass).text(val.validationMsg);
												}
												// If not found certain class to show error then show as general error at top of Form
												else {
													scWordFormOuterMostDivWrapper.prepend('<br/>' + val.validationMsg);
												}
											});
											scWordFormOuterMostDivWrapper[0].scrollIntoView();	 
										}
										else {
											scWordFormOuterMostDivWrapper.prepend('<br/>' + jsonData.failMsg);
											scWordFormOuterMostDivWrapper[0].scrollIntoView();
										}
										scWordformWrapper.find('button[type="submit"]').removeAttr('disabled');
									} 
									// Success
									else {
										scWordFormLoadedElement.hide();
										$(this).slideUp(500).promise().done(function() {
											if (  sc_wordform_frontend_misc_script_obj.hide_form_on_submission && sc_wordform_frontend_misc_script_obj.hide_form_on_submission == 1 ) {
												scWordFormOuterMostDivWrapper.html(jsonData.successMsg);
											}
											else {
												scWordFormOuterMostDivWrapper.prepend(jsonData.successMsg); 
											}
											//scWordformWrapper[0].scrollIntoView();
											scWordFormOuterMostDivWrapper[0].scrollIntoView();
											scWordformWrapper.find('button[type="submit"]').removeAttr('disabled');
										});
									} 
									},
								error: function( xhr, status, error ) { 
									wordformProgressBarEle.width('0%');
									scWordFormLoadedElement.hide(); 
									console.log(xhr); 
									console.log(status); 
									console.log(error); 				 
									}
								}); // $.ajax												
				 		 }); // grecaptcha.execute
					}); // grecaptcha.ready()			
			}		
			// When G-reCaptcha key not available || G-recaptcha not integrated || G-reCaptcha integrated as V2 || normal submit form 		
			else {											
				// Execute Submit: Uploading selected files if available including others form data values		
				console.log('NORMAL FORM SUBMISSION OR reCaptcha V2');							
				if ( typeof grecaptcha !== 'undefined' ) {
					try {
						// console.log('grecaptcha.getResponse(): ');
						token = grecaptcha.getResponse();		
						wordform_formdata.append( gCapcthaTokenInputElementName, token );								
						// console.log( token );
					}
					catch(error) {
						console.log( error.message );
					}
				}				
				// wordform_formdata.append('token', token );				
				// wordform_formdata.append( gCapcthaTokenInputElementName, token );				
				wordform_formdata.append( gCapcthaActionInputElementName, gCaptchaActionValue );								

				$.ajax({
				xhr: function() {
						var xhr = new window.XMLHttpRequest();
						xhr.upload.addEventListener("progress", function(evt) {
							if (evt.lengthComputable) {						
								var percentComplete = ((evt.loaded / evt.total) * 100);
								// If Files are available to upload then show progress bar
								if ( wordform_total_files_uploading > 0 && sc_wordform_frontend_misc_script_obj.wordform_upload_config_data?.wordform_upload_show_hide_progress_bar == 'yes' ) {
									wordformProgressBarEle.width(percentComplete + '%').css( {'background-color' : sc_wordform_frontend_misc_script_obj.wordform_upload_config_data?.wordform_upload_progress_bar_color });
									wordformProgressBarEle.html(percentComplete+'%');
								}
							}
						}, false );
						return xhr;
				},			

				type : "POST",		  
				url  : sc_wordform_frontend_misc_script_obj.ajax_url,		  
				processData: false,
				contentType: false,
				data : wordform_formdata,		  				

				beforeSend: function() {
					wordformProgressBarEle.width('0%');					
				},

				success: function(data) { 
					wordformProgressBarEle.width('0%');
					// console.log(data); 
					jsonData	= JSON.parse( data );			 
					// console.log(jsonData ); 
					// Fail
					if ( jsonData.status == 'fail' ) {
						scWordFormLoadedElement.hide();
						if ( jsonData.validationErrorData ) {
							$.each( jsonData.validationErrorData, function( key, val ) {
								// console.log(val.validationMsgClass );
								// Show the error on the element it occured if certain class found for that element based on elementKey
								if ( typeof val.validationMsgClass !== 'undefined' ) {
									$('.'+val.validationMsgClass).text(val.validationMsg);
								}
								// If not found certain class to show error then show as general error at top of Form
								else {
									scWordFormOuterMostDivWrapper.prepend('<br/>' + val.validationMsg);
								}
							});
							scWordFormOuterMostDivWrapper[0].scrollIntoView();	 
						}
						else {
							scWordFormOuterMostDivWrapper.prepend('<br/>' + jsonData.failMsg);
							scWordFormOuterMostDivWrapper[0].scrollIntoView();
						}
						scWordformWrapper.find('button[type="submit"]').removeAttr('disabled');
					} 
					// Success
					else {
						scWordFormLoadedElement.hide();
						$(this).slideUp(500).promise().done(function() {
							if (  sc_wordform_frontend_misc_script_obj.hide_form_on_submission && sc_wordform_frontend_misc_script_obj.hide_form_on_submission == 1 ) {
								scWordFormOuterMostDivWrapper.html(jsonData.successMsg);
							}
							else {
								scWordFormOuterMostDivWrapper.prepend(jsonData.successMsg); 
							}
							//scWordformWrapper[0].scrollIntoView();
							scWordFormOuterMostDivWrapper[0].scrollIntoView();
							scWordformWrapper.find('button[type="submit"]').removeAttr('disabled');
						});
					} 
					},
				error: function( xhr, status, error ) { 
					wordformProgressBarEle.width('0%');
					scWordFormLoadedElement.hide(); 
					console.log(xhr); 
					console.log(status); 
					console.log(error); 				 
					}
				}); // $.ajax
			} // else
			
		}); // $('.sc-wordform-built-created-form-frontend-display-form').on("submit", function(e)	
	

	
	// When Selecting files - Supporting multiple input type file elements of same Form
	  var wordform_selected_tmp_files = {}; 	
	  var wordform_selected_total_file_numbers = 0;  
	  $(".sc-wordform-built-upload-element").on("change", function(e) {
			let inputTypeElementkey   = $(this).data('input-typefile-element-key');
		    let UploadErrorMsgWrapper = $('#wordformUploadTempError-' + inputTypeElementkey );
			let uploadMultipleFiles   = $(this).prop('multiple');
			let scWordformWrapperID   = $(this).closest('form').prop('id');			
			let inputTypeFileId       = $(this).prop('id');
			let acceptFileExtensions  = $(this).prop('accept');
			let selectedFileListULId  = $(this).parent().next().prop('id');	
			let scWordFormID 		  = $(this).closest('.sc-wordform-built-created-form-frontend-display-form').prop('id');		
			let validationMessagesJsonStr = $('#'+scWordFormID+'-validationMsg').val().replace( '-', '_');	
			validationMessages        = JSON.parse( validationMessagesJsonStr );
			// console.log('Validation Messages:');
			// console.log(validationMessages);

			// console.log('Upload Multiple');
			// console.log(uploadMultipleFiles);
	
			UploadErrorMsgWrapper.html('');

			// console.log('WordForm ID: '+ scWordformWrapperID );
			// console.log(acceptFileExtensions);

			// console.log('Upload Config data');
			// console.log( sc_wordform_frontend_misc_script_obj.wordform_upload_config_data );
			// console.log('UPLOAD_MAX_SIZE: '+ sc_wordform_frontend_misc_script_obj.wordform_upload_config_data?.each_file_max_size_allowed );
			// console.log('POST_MAX_SIZE: '+ sc_wordform_frontend_misc_script_obj.wordform_upload_config_data?.all_files_max_size_allowed );
			// console.log('MAX_FILE_UPLOADS: '+ sc_wordform_frontend_misc_script_obj.wordform_upload_config_data?.max_num_files_allowed );				

			// Total Selected Files Number						
			if ( ( wordform_selected_total_file_numbers + e.target.files.length )  > sc_wordform_frontend_misc_script_obj.wordform_upload_config_data?.max_num_files_allowed ) {				
				// console.log('Total Selected Files:'+ ( wordform_selected_total_file_numbers + e.target.files.length ) );
				UploadErrorMsgWrapper.html( sc_wordform_frontend_misc_script_obj.info_file_icon + validationMessages.upload_maxinput_msg );						
			}
			else if ( wordformSelectedFilesSize( e.target.files ).singleFileSizeExceed === true ) {
				UploadErrorMsgWrapper.html( sc_wordform_frontend_misc_script_obj.info_file_icon + validationMessages.upload_size_msg );
			}
			else if ( wordformSelectedFilesSize( e.target.files ).multipleFileSizeExceed === true ) {
				UploadErrorMsgWrapper.html( sc_wordform_frontend_misc_script_obj.info_file_icon + validationMessages.upload_allsize_msg );
			}
			// Finally count selected file
			else {
				// Input Type File Element attribute Id as index
				wordform_selected_tmp_files[ inputTypeFileId ] ||= [];	
				// console.log( acceptFileExtensions.split(',') );
				for ( const file of e.target.files ) {		
					// console.log(file);										
					if ( is_file_selected_once( file.name ) >= 0 ) {
						UploadErrorMsgWrapper.append( sc_wordform_frontend_misc_script_obj.info_file_icon +  file.name +' - '+ validationMessages.upload_filealready_added_msg );			
					}
					// If File Type Accepted | Consider File as uploadable | Multiple Upload - True
					else if ( acceptFileExtensions.split(',').includes( file.type ) && uploadMultipleFiles === true ) {			
						wordform_selected_total_file_numbers += 1;
						wordform_selected_tmp_files[ inputTypeFileId ].push( file );				
						$('#'+selectedFileListULId).append( '<li>' + file.name.trim() + sc_wordform_frontend_misc_script_obj.remove_file_icon + '</li>' );			
					}
					// If File Type Accepted | Consider File as uploadable | Multiple Upload - False															
					else if ( acceptFileExtensions.split(',').includes( file.type ) && uploadMultipleFiles === false ) {			
						// Adding first time for single file upload
						if ( typeof wordform_selected_tmp_files[ inputTypeFileId ][0] === 'undefined') {							
							wordform_selected_total_file_numbers += 1;						
							wordform_selected_tmp_files[ inputTypeFileId ].push( file );					
						}
						// Overwrite old one with new one
						else {							
							wordform_selected_tmp_files[ inputTypeFileId ][0] =  file;
						}
						$('#'+selectedFileListULId).html( '<li>' + file.name.trim() + sc_wordform_frontend_misc_script_obj.remove_file_icon + '</li>' );			
					}
					// If File Type Not Accepted
					else {
						UploadErrorMsgWrapper.append( '<br/>' + sc_wordform_frontend_misc_script_obj.info_file_icon + file.name + ' - ' + validationMessages.upload_allow_msg );
					}
				} // for							
				console.log('Total Selected Files:'+ wordform_selected_total_file_numbers );
		   }
		//    console.log(wordform_selected_tmp_files );
	  });

	  // Remove selected file
	  $('body').on('click', '.wordform-remove-selected-file', function(e) {				
		let removeFileName = $(this).parent().text();
		// let inputTypeElementkey = $(this).closest('.wordform-selected-file-names-list').prop('id').split('-')[1];		
		// let UploadErrorMsgWrapper = $('#wordformUploadTempError-' + inputTypeElementkey );		
		// console.log( 'Remove File Name:'+ removeFileName );				
		$.each( wordform_selected_tmp_files, function(index, files) {			
			let removeItemIndex = files.findIndex( function(file) { return file?.name?.trim() == removeFileName.trim(); });			
			// Remove or Delete
			if ( removeItemIndex !== -1 ) { files.splice( removeItemIndex, 1 );	}
		});	
		//  console.log( wordform_selected_tmp_files );
		 $(this).closest('li').remove();
		 // Update Total File Numbers on Remove
		 wordform_selected_total_file_numbers--;
		//  console.log('Total Selected Files:'+ wordform_selected_total_file_numbers );
	  });
	
	  // Check selected Individual | Multiple file | files size
	  function wordformSelectedFilesSize( selectedFiles ) {
		let fileSizeInfo = {};
		let total_size_in_bytes = 0;
		// Check each selected file size exceeded
		$.each( selectedFiles, function( index, file ) {
			total_size_in_bytes += file.size ||=0;
			// console.log('Converted file.size into MB: '+ wordform_bytes_to_mb( file.size ) );
			// console.log('Each File Size Allowed: '+ parseFloat( sc_wordform_frontend_misc_script_obj.wordform_upload_config_data?.each_file_max_size_allowed ) );
			if ( wordform_bytes_to_mb( file.size ) > parseFloat( sc_wordform_frontend_misc_script_obj.wordform_upload_config_data?.each_file_max_size_allowed ) ) {
				// console.log( file.name + ' File Size '+ wordform_bytes_to_mb( file.size ) + ' Exceeded.' );
				fileSizeInfo.singleFileSizeExceed = true;
				return; // Break the loop
			}
		});
		// Merge Earlier file | files size if available with current selected file | files size		
		$.each( wordform_selected_tmp_files, function(index, files ) {
			$.each( files, function( index, file ) {
				total_size_in_bytes += file.size ||=0;
			});			
		});
		// Check all files total sizes exceeded
		if ( wordform_bytes_to_mb( total_size_in_bytes ) > parseFloat( sc_wordform_frontend_misc_script_obj.wordform_upload_config_data?.all_files_max_size_allowed ) ) {
			fileSizeInfo.multipleFileSizeExceed = true;
		}
		// console.log('All selected files total size:'+ wordform_bytes_to_mb( total_size_in_bytes ) );
		return fileSizeInfo;
	  }

	  // Is same file selected once
	  function is_file_selected_once( filename ) {
		let addedFileIndex = -1;		
		$.each( wordform_selected_tmp_files, function( index, files ) {
			addedFileIndex = files.findIndex( function(file) { return file.name == filename; } );
			//  console.log('FileIndex: '+ addedFileIndex );
			// If Found - Break the Loop
			if ( addedFileIndex !== -1 ) return;			 
		});
		return addedFileIndex;
	  }

	  // Convert Bytes into MB
	//   function wordform_bytes_to_mb( bytes, decimals = 2) {
	// 	if (!+bytes) return 0;	
	// 	const k = 1024;
	// 	const dm = decimals < 0 ? 0 : decimals;
	// 	// const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
	// 	// Convert always into MB
	//     const sizes = ['MiB'];
	// 	const i = Math.floor(Math.log(bytes) / Math.log(k))	
	// 	// return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
	// 	return parseFloat( (bytes / Math.pow(k, i) ).toFixed(dm) );
	// }	  
	  function wordform_bytes_to_mb( wordformBytes = 0 ) {
		if ( wordformBytes === 0 ) return 0;
		return parseFloat( ( wordformBytes / ( 1024 ** 2 ) ).toFixed(2) );
	  }



	  // Range Slider - Mousemove
	  $('body').on('mousemove click change', '.sc-wordform-built-range-element', function(e) {		
		let wordformRangeValueDisplayEle = $('.wordform-range-element-selected-value');
		let offset = $(this).offset();
		let selectedValue = $(this).val();
		// console.log( selectedValue );

		wordformRangeValueDisplayEle.text( selectedValue );		
		wordformRangeValueDisplayEle.css({"left" : (e.pageX - offset.left), "top" : ( e.pageY - offset.top ) });
	  });

	  // Range Slider - Mouseout
	  $('body').on('mouseout', '.sc-wordform-built-range-element', function(e) {
		let wordformRangeValueDisplayEle = $('.wordform-range-element-selected-value');
		let selectedValue = $(this).val();
		// console.log( selectedValue );
		let rangeElementWidth = ($(this).width() + 5 ) + 'px';
		wordformRangeValueDisplayEle.css({"left" : rangeElementWidth, "top" : '45%' });
	  });

	

			
}); // $(document)