var JadaptiveUtils = {
validate: function(form, callback, invalid) {
		
		$('.validation').removeClass('validation border border-5 border-danger');
		
		$('.mceEditor').each(function() {
			var editor = tinymce.get($(this).attr('id'));
			editor.save();
		});		
		
		$.ajax({
		   type: "POST",
		   url: '/app/api/form/json-validate/' + form.data('resourcekey'),
		   cache: false,
		   contentType: false,
		   processData: false,
		   data: JadaptiveUtils.processedFormData(form, true),
		   success: function(data)
		   {
		       if(data.success) {
					if(callback) {
						callback();
					}
	           } else {
				$('#progressModal').modal('hide');
				JadaptiveUtils.error($("#feedback"), data.message);
			     
			     $.each(data.errors, function(idx, obj) {
					
					/* This code mirrors server side based field highlighting found in ObjectRenderer.process */
					 
					var fieldParent = $('[name="' + obj.formVariable + '"]')
						.parents(".field")
						.first();
						
					var field = fieldParent.find(".form-control");
						
					if(field.length > 0) {
				     	field.addClass("validation border border-5 border-danger");
				    } else {
						field = $('textarea[name="' + obj.formVariable + '"]');
						if(field.length > 0) {
							field.siblings('.tox-tinymce').addClass("validation border border-5 border-danger");
						}
					}
					
					/* Add feedback text to the field. If there is a label, add it after the label, otherwise add it before the field. */
					fieldParent.find(".feedback-message").remove();
					var fieldLabel = fieldParent.find(".form-label").first();
					if(fieldLabel.length > 0) {
						fieldLabel.after('<div class="feedback-message text-danger">' + obj.error + '</div>');
					}
					else {
						fieldParent.prepend('<div class="feedback-message text-danger">' + obj.error + '</div>');
					}
						
					
					if(idx == 0) {
				        var parentId = field.parents('.tab-pane').first().attr('id');
						var triggerEl = document.querySelector('a[href="#' + parentId + '"]');
						if(bootstrap.Tab.getInstance(triggerEl)) {
							bootstrap.Tab.getInstance(triggerEl).show();
						}
					}
				  });
			     
			     if(invalid) {
			     	invalid(data);
			     }
			  }
		   }
		 });
	},
startAwesomeSpin : function(el, icon, spinner) {
	
	
		if(!icon) {
			var classList = el.prop('class');
			if(classList) {
				$.each(classList.split(/\s+/), function(index, item) {
				    if (item.startsWith('fa-') && !item.startsWith("fa-spin") && !item.startsWith("fa-spinner")
				    && $('body').data('iconset').indexOf(item) == -1) {
				       icon = item;
					   el.data('faicon', icon);
				    }
				});
			}
		}
		el.parent().attr('disabled', true);
		el.removeClass(icon);
		if(spinner) {
			el.addClass(spinner);
		} else {
			el.addClass('fa-spinner');
		}
		el.addClass('fa-spin');
	},
stopAwesomeSpin : function(el, icon, spinner) {
	    if(!icon) {
			icon = el.data('faicon');
		}
		el.parent().removeAttr('disabled');
		el.removeClass('fa-spin');
		if(spinner) {
			el.removeClass(spinner);
		} else {
			el.removeClass('fa-spinner');
		}
		el.addClass(icon);
	},
error: function(el, message) {
	this.feedback(el, message, 'danger', 'fa-exclamation-square');
},
info: function(el, message) {
	this.feedback(el, message, 'info', 'fa-info-square');
},
success: function(el, message) {
	this.feedback(el, message, 'success', 'fa-thumbs-up');
},	
warning: function(el, message) {
	this.feedback(el, message, 'warning', 'fa-warning');
},
feedback: function(el, message, type, icon) {
    
    var msg = '<div class="d-flex"> \
               <div class="toast-body"> \
                <i class="' + icon + ' me-2 ' + $('body').data('iconset') + '"></i> \
                <span>' + message + '</span> \
               </div> \
               <button class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button> \
           </div>';

    if (el && el.length) {
        el.html('<div class="toast-container position-static text-center w-100">' +
            '<div class="toast align-items-center text-bg-' + type + ' border-0 show w-100" role="alert" aria-live="assertive" aria-atomic="true">' +
            msg + '</div></div>');
    }
    else {
        var mhtml = '<div class="position-relative"><div class="toast-container p-3 top-0 start-50 translate-middle-x">' +
            '<div class="toast align-items-center text-bg-' + type + ' border-0 show" role="alert" aria-live="assertive" aria-atomic="true">' +
            msg + '</div></div></div>';
        var e = $('main.container');
        if (e.length) {
            e.prepend(mhtml);
        }
        else {
            e = $('body').first();
            if (e.length > 0) {
                e.prepend(mhtml);
            }
        }
    }
},
checkBlank: function(elements) {
	var empty = false;
	$.each(elements, function(idx, el) {
		if(el.val().trim() === '') {
			empty = true;
			return true;
		}
	});
	return !empty;
},
toggleDropdown: function(element) {
	var el = element.closest(".dropdown");
		el = el.find('.dropdown-toggle');
		const dropdownToggleEl = el[0];
		const dropdownList = new bootstrap.Dropdown(dropdownToggleEl);
		dropdownList.toggle();	
},
serializeForm: function(form) {
	form.find('.jadaptive-select option').prop('selected', true);
    var results = form.serialize();
	form.find('.jadaptive-select option').prop('selected', false);
    return results;
},

setCookie: function(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
},
getCookie: function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
},
hasCookie: function(name) {
	return this.getCookie(name)!= null;
},
eraseCookie: function(name) {   
    document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 UTC;';
},
processedFormData: function(form, removeFiles) {
	
	var fdata = new FormData(form[0]);
	
	if(removeFiles) {
		form.find('input[type="file"]').each(function() {
			fdata.delete($(this).attr('name'));
		});
	} 
	
	form.find('.mdeEditor').each(function() {
		fdata.delete($(this).attr('id'));
		fdata.append($(this).attr('id'),
			marked.parse($(this).val()));
	});
	
	form.find('.mceEditor').each(function() {
		var editor = tinymce.get($(this).attr('id'));
		editor.save();
	});

	form.find('.processDepends').each(function() {
		var dependsOn = $(this).data('depends-on');
		var dependsValue = $(this).attr('data-depends-value');

		var allInput = $('#' + dependsOn);
		if (!allInput.length) {
			allInput = $('input[name=' + dependsOn + ']');
		}
		var resourceKey = $(this).data('resourcekey');
		if(console)
			console.log('Checking field ' + resourceKey + " against " + dependsOn + " and value " + dependsValue);
		var matchValues = dependsValue.split(',');
		var matches = false;
		allInput.each(function(i, input) {
			input = $(input);
			$.each(matchValues, function(i, obj) {

				var expectedResult = !obj.startsWith("!");
				if (!expectedResult) {
					obj = obj.substring(1);
				}
				var value;
				if (input.attr('type') === 'radio') {
					value = input.is(':checked') ? input.val() : '';
				}
				else if (input.attr('type') === 'checkbox') {
					value = input.is(':checked').toString();
				} else {
					value = input.val();
				}
				if (obj == value) {
					matches = expectedResult;
					return true;
				}
				return false;
			});
			if (matches) {
				return true;
			}
		});
		if (!matches) {
			if(console)
			console.log('Removing field ' + resourceKey);
			fdata.delete(resourceKey);
		}
	});
	
	return fdata;
}
};