(function($) {
    "use strict";

    $(document).ready(function() {

        // function for compare conditional values 
        function checkFieldLogic(compareFieldValue, conditionOperation, compareValue) {
                    
            conditionOperation = decodeHTMLEntities(conditionOperation);
            compareValue =
          compareValue === null
            ? decodeHTMLEntities(compareValue)
            : decodeHTMLEntities(compareValue).trim();
        compareFieldValue =
          compareFieldValue === null
            ? decodeHTMLEntities(compareFieldValue)
            : compareFieldValue.trim();
            var values = compareFieldValue.split(',');

            var matchFound = values.some(function(value) {
                return value.trim() === compareValue;
            });

            switch (conditionOperation) {
                case "==":
                    return matchFound && '' !== compareFieldValue;
                case "!=":
                    return !matchFound && compareFieldValue !== "";
                case "e":
                    return compareFieldValue == "";
                case "!e":
                    return compareFieldValue != "";
                case "c":
                    return compareFieldValue.includes(compareValue);
                case "!c":
                    return compareFieldValue != "" && !compareFieldValue.includes(compareValue);
                case "^":
                    return compareFieldValue.startsWith(compareValue);
                case "~":
                    return compareFieldValue.endsWith(compareValue);
                case ">":
                    return parseInt(compareFieldValue) > parseInt(compareValue);
                case "<":
                    return parseInt(compareFieldValue) < parseInt(compareValue);
                case ">=":
                    return parseInt(compareFieldValue) >= parseInt(compareValue);
                case "<=":
                    return parseInt(compareFieldValue) <= parseInt(compareValue);
                default:
                    return false;
            }
        }
        function decodeHTMLEntities(text) {
            var textArea = document.createElement('textarea');
            textArea.innerHTML = text;
            return textArea.value;
        }
        // function to add hidden class when form load
        function addHiddenClass(form,formId) {
            var logicData = $(`#cfef_logic_data_${formId}`).html();
            if (logicData && logicData !== "undefined") {
                try {
                    logicData = jQuery.parseJSON(logicData);
                    $.each(logicData, function(logic_key, logic_value) {
                        if ($(".is-field-group-" + logic_key).hasClass("is-field-type-html")) {
                                
                            field = $(".is-field-group-" + logic_key).closest(".is-field-group");
                        
                        } else {
                            var field = getFieldMainDivById(logic_key);
                        }
                        if (!field || field.length === 0) {
                            return; // Skip to the next iteration
                        }
                    
                        var displayMode= logic_value.display_mode;
                        var fireAction = logic_value.fire_action;
                        var conditionPassFail = [];
                        $.each(logic_value.logic_data, function(conditional_logic_key, conditional_logic_values) {
                            if(conditional_logic_values.cfef_logic_field_id)
                            {
                            var value_id = getFieldEnteredValue(conditional_logic_values.cfef_logic_field_id, form);
                  
                            conditionPassFail.push(checkFieldLogic(value_id, conditional_logic_values.cfef_logic_field_is, conditional_logic_values.cfef_logic_compare_value));
                        }
                    }); 
                        var conditionResult = fireAction == "ALL" ? conditionPassFail.every(function(fvalue) { return fvalue === true; }) : conditionPassFail.some(function(fvalue) { return fvalue === true; });
                
                        if (displayMode== "show") {
                            if (conditionResult) {
                            } else {
                                if(field.hasClass('is-field-type-signature')){
                                    setTimeout(()=>{
                                        field.addClass("cfef-hidden");
                                    },100)
                                }else{
                                    field.addClass("cfef-hidden");
                                }
                            }
                        } else if (displayMode== "hide") {
                            if (conditionResult) {
                                if(field.hasClass('is-field-type-signature')){
                                    setTimeout(()=>{
                                        field.addClass("cfef-hidden");
                                    },100)
                                }else{
                                    field.addClass("cfef-hidden");
                                }
                            } else {
                            }
                        }
                    });
                } catch (e) {
                    console.error("Error parsing JSON:", e);
                }
            } else {
            // console.warn("JSON data is empty or undefined");
            }
        }
        
        
        // function to check all the conditions valid or not . and based on that condition show and hide the fields 
        function logicLoad(form, formId) {
            var logicData = $(`#cfef_logic_data_${formId}`).html();
            if (logicData && logicData !== "undefined") {
              try {
                logicData = jQuery.parseJSON(logicData);
                $.each(logicData, function (logic_key, logic_value) {
                  if (
                    $(".is-field-group-" + logic_key, form).hasClass(
                      "is-field-type-html"
                    )
                  ) {
                    field = $(".is-field-group-" + logic_key, form).closest(
                      ".is-field-group"
                    );
                  } else {
                    if (
                      jQuery(".is-field-group-" + logic_key, form).hasClass(
                        "is-field-type-step"
                      )
                    ) {
                      setTimeout(() => {
                        jQuery(".is-field-group-" + logic_key, form)
                          .find(".e-form__buttons")
                          .find(
                            ".elementor-field-type-next, .elementor-field-type-submit"
                          )
                          .find(".elementor-button")
                          .attr("id", "form-field-" + logic_key)
                          .closest(
                            ".elementor-field-type-next, .elementor-field-type-submit"
                          )
                          .addClass("cfef-step-field");
                        var field = getFieldMainDivById(logic_key, form);
                        performFieldLogic(
                          field,
                          logic_value,
                          form,
                          logic_key,
                          formId
                        );
                      }, 500);
                    }
                    var field = getFieldMainDivById(logic_key, form);
                    performFieldLogic(field, logic_value, form, logic_key, formId);
                  }
                  performFieldLogic(field, logic_value, form, logic_key, formId);
                });
              } catch (e) {
                console.error("Error parsing JSON:", e);
              }
            } else {
            
            }
          }    

        function performFieldLogic(field, logic_value, form, logic_key,formId){
            var displayMode= logic_value.display_mode;
            var fireAction = logic_value.fire_action;
            var file_types = logic_value.file_types;
            var conditionPassFail = [];
            $.each(logic_value.logic_data, function(conditional_logic_key, conditional_logic_values) {
                                
                    var dependent_fi = $(".is-field-group-" + conditional_logic_values.cfef_logic_field_id, form);
                    
                    if(dependent_fi.hasClass('is-field-group-acceptance') || dependent_fi.hasClass('is-field-type-acceptance')){
                            dependent_fi.find('.elementor-field-subgroup .elementor-field-option input').click(()=>{
                                if(dependent_fi.find('.elementor-field-subgroup .elementor-field-option input')[0].checked === true){
                                    dependent_fi.find('.elementor-field-subgroup .elementor-field-option input').val('on') 
                                }else{
                                    dependent_fi.find('.elementor-field-subgroup .elementor-field-option input').val('')
                            }
                            })
                    }


                    var hiddenDiv = dependent_fi[0];
                    var	is_field_hidden = hiddenDiv ? hiddenDiv.classList.contains('cfef-hidden') : hiddenDiv;
                    if(conditional_logic_values.cfef_logic_field_id){               
                        var value_id = getFieldEnteredValue(conditional_logic_values.cfef_logic_field_id, form);
                        var value = is_field_hidden ? false : checkFieldLogic(value_id, conditional_logic_values.cfef_logic_field_is, conditional_logic_values.cfef_logic_compare_value);

                        conditionPassFail.push(value);
            }});
            var conditionResult = fireAction == "All" ? conditionPassFail.every(function(fvalue) { return fvalue === true; }) : conditionPassFail.some(function(fvalue) { return fvalue === true; });

            if (displayMode== "show") {
                if (conditionResult) {
                    if (field.hasClass("is-field-type-signature")) {
                        setTimeout(() => {
                            field.removeClass("cfef-hidden");
                        }, 100);
                    }else{
                        field.removeClass("cfef-hidden");
                    }

                    if(field.hasClass('is-field-required')){
                        logicFixedRequiredShow(field,file_types,'visible');
                    }
                } else {
                    if(field.hasClass('is-field-type-signature')){
                        setTimeout(()=>{
                            field.addClass("cfef-hidden");
                        },100)
                    }else{
                        field.addClass("cfef-hidden");
                    }
                    if(field.hasClass('is-field-required')){
                        logicFixedRequiredHidden(field, logic_key,file_types);
                    }
                }
            } else if (displayMode == "hide") {
                if (conditionResult) {
                    if (field.hasClass("cfef-step-field")) {
                      var container = field.closest(".e-form__buttons");
                  
                      // Get the inner text of the button (assuming the "Next" button has a data attribute for direction)
                      var nextButtonText = container
                        .find('button[id^="form-field-"]')
                        .text()
                        .trim();
                  
                      // If the message hasn't been added yet, insert it and replace "Next" with the actual button text
                      if (container.prev(".cfef-step-field-text").length === 0) {
                        container.before(
                          '<p class="cfef-step-field-text">No input is required on this step. Just click "' +
                            nextButtonText +
                            '" to proceed.</p>'
                        );
                      }
                    } else {
                      // Check if field exists before adding the class
                      if (field && field.length > 0) {
                        field.addClass("cfef-hidden");
                        if (field.hasClass("is-field-required")) {
                          logicFixedRequiredHidden(field, logic_key, file_types);
                        }
                      }
                    }
                  } else {
                    // If the field has the "cfef-step-field" class, remove the appended message
                    if (field.hasClass("cfef-step-field")) {
                      var container = field.closest(".e-form__buttons");
                      container.prev(".cfef-step-field-text").remove();
                    }
                    if (field.hasClass("is-field-required")) {
                      logicFixedRequiredShow(field, file_types, "visible");
                    }
                    // Check if field exists before removing the class
                    if (field && field.length > 0) {
                      field.removeClass("cfef-hidden");
                    }
                  }
                  
            } else if (displayMode == "enable") {
                if (conditionResult) {

                    if(field.hasClass('is-field-type-acceptance') || field.hasClass('is-field-type-checkbox') || field.hasClass('is-field-type-radio')){
                        field.find('input').attr('disabled',false)
                        if(field.length > 0){
                            field[0].onclick = ()=>{
                                field.find('input').attr('disabled',false)
                            }
                        }
                    }else{
                        field.find('textarea , input, button, canvas, select').attr('disabled',false).css({"pointer-events": "unset", "opacity": "1.0"})
                        if(field.length > 0){
                            field[0].onclick = ()=>{
                                field.find('textarea , input, button, canvas').attr('disabled',false).css({"pointer-events": "unset", "opacity": "1.0"})
                            }
                        }
                    }

                    if(field.hasClass('is-field-type-select')){
                        field.find('.mdc-select').removeClass('mdc-select--disabled')
                    }

                    if(field.hasClass('is-field-type-recaptcha')){
                        field.find('.ehp-form-recaptcha').css({'pointer-events':'unset','opacity':'1.0'})
                    }

                    if(field.hasClass('is-field-type-slider')){
                        if(jQuery(field[0].children).find('span.irs').length > 0){
                            jQuery(field[0].children).find('span.irs')[0].parentElement.style.pointerEvents = 'unset';
                        }
                    }
                    if(field.hasClass('is-field-type-toggle')){
                        field.find('.toggle-span').css({'opacity':'1.0'})
                    }
                    if(field.hasClass('is-field-type-rating')){
                        field.css({"pointer-events": "unset", "opacity": "1.0"})
                    }
                    if(field.hasClass('is-field-type-WYSIWYG')){
                        if(field.find('.cfkef-wysiwyg-wrapper')){
                         field.css({"pointer-events": "unset", "opacity": "1.0"})
                        };
                     }
                } else {
                    if(field.hasClass('is-field-type-acceptance') || field.hasClass('is-field-type-checkbox') || field.hasClass('is-field-type-radio')){
                        field.find('input').attr('disabled','disabled')
                        if(field.length > 0){
                            field[0].onclick = ()=>{
                                field.find('input').attr('disabled','disabled')
                            }
                        }
                    }else{
                        field.find('textarea , input, button, canvas, select').attr('disabled','disabled').css({"pointer-events": "none", "opacity": "0.3"})
                        if(field.length > 0){
                            field[0].onclick = ()=>{
                                field.find('textarea , input, button, canvas').attr('disabled','disabled').css({"pointer-events": "none", "opacity": "0.3"})
                            }
                        }
                    }


                    if(field.hasClass('is-field-type-select')){
                        field.find('.mdc-select').addClass('mdc-select--disabled')
                    }

                    if(field.hasClass('is-field-type-recaptcha')){
                        field.find('.ehp-form-recaptcha').css({'pointer-events':'none','opacity':'0.3'})
                    }

                    if(field.hasClass('is-field-type-slider')){
                        if(jQuery(field[0].children).find('span.irs').length > 0){
                            jQuery(field[0].children).find('span.irs')[0].parentElement.style.pointerEvents = 'none';
                        }
                    }
                    if(field.hasClass('is-field-type-toggle')){
                        field.find('.toggle-span').css({'opacity':'0.3'})
                    }
                    if(field.hasClass('is-field-type-rating')){
                        field.css({"pointer-events": "none", "opacity": "0.3"})
                    }
                    if(field.hasClass('is-field-type-WYSIWYG')){
                       if(field.find('.cfkef-wysiwyg-wrapper')){
                        field.css({"pointer-events": "none", "opacity": "0.3"})
                       };
                    }
                }
            } else if (displayMode == "disable") {
                if (conditionResult) {

                    if(field.hasClass('is-field-type-acceptance') || field.hasClass('is-field-type-checkbox') || field.hasClass('is-field-type-radio')){
                        field.find('input').attr('disabled','disabled')
                        if(field.length > 0){
                            field[0].onclick = ()=>{
                                field.find('input').attr('disabled','disabled')
                            }
                        }
                    }else{
                        field.find('textarea , input, button, canvas, select').attr('disabled','disabled').css({"pointer-events": "none", "opacity": "0.3"})
                        if(field.length > 0){
                            field[0].onclick = ()=>{
                                field.find('textarea , input, button, canvas').attr('disabled','disabled').css({"pointer-events": "none", "opacity": "0.3"})
                            }
                        }
                    }


                    if(field.hasClass('is-field-type-select')){
                        field.find('.mdc-select').addClass('mdc-select--disabled')
                    }

                    if(field.hasClass('is-field-type-recaptcha')){
                        field.find('.ehp-form-recaptcha').css({'pointer-events':'none','opacity':'0.3'})
                    }

                    if(field.hasClass('is-field-type-slider')){
                        if(jQuery(field[0].children).find('span.irs').length > 0){
                            jQuery(field[0].children).find('span.irs')[0].parentElement.style.pointerEvents = 'none';
                        }
                    }
                    if(field.hasClass('is-field-type-toggle')){
                        field.find('.toggle-span').css({'opacity':'0.3'})
                    }
                    if(field.hasClass('is-field-type-rating')){
                        field.css({"pointer-events": "none", "opacity": "0.3"})
                    }
                    if(field.hasClass('is-field-type-WYSIWYG')){
                        if(field.find('.cfkef-wysiwyg-wrapper')){
                         field.css({"pointer-events": "none", "opacity": "0.3"})
                        };
                     }
                } else {
                    if(field.hasClass('is-field-type-acceptance') || field.hasClass('is-field-type-checkbox') || field.hasClass('is-field-type-radio')){
                        field.find('input').attr('disabled',false)
                        if(field.length > 0){
                            field[0].onclick = ()=>{
                                field.find('input').attr('disabled',false)
                            }
                        }
                    }else{
                        field.find('textarea , input, button, canvas, select').attr('disabled',false).css({"pointer-events": "unset", "opacity": "1.0"})
                        if(field.length > 0){
                            field[0].onclick = ()=>{
                                field.find('textarea , input, button, canvas').attr('disabled',false).css({"pointer-events": "unset", "opacity": "1.0"})
                            }
                        }   
                    }

                    if(field.hasClass('is-field-type-select')){
                        field.find('.mdc-select').removeClass('mdc-select--disabled')
                    }
                    
                    if(field.hasClass('is-field-type-recaptcha')){
                        field.find('.ehp-form-recaptcha').css({'pointer-events':'unset','opacity':'1.0'})
                    }

                    if(field.hasClass('is-field-type-slider')){
                        if(jQuery(field[0].children).find('span.irs').length > 0){
                            jQuery(field[0].children).find('span.irs')[0].parentElement.style.pointerEvents = 'unset';
                        }
                    }
                    if(field.hasClass('is-field-type-toggle')){
                        field.find('.toggle-span').css({'opacity':'1.0'})
                    }
                    if(field.hasClass('is-field-type-rating')){
                        field.css({"pointer-events": "unset", "opacity": "1.0"})
                    }
                    if(field.hasClass('is-field-type-WYSIWYG')){
                        if(field.find('.cfkef-wysiwyg-wrapper')){
                         field.css({"pointer-events": "unset", "opacity": "1.0"})
                        };
                     }
                }      
            }
        }
        
        // remove the default value when formField show
        function logicFixedRequiredShow(formField,file_types,status) {
            if(formField.hasClass('is-field-type-image_radio')){
                formField.find('input').attr('checked',false)
            }
            else if(formField.hasClass('is-field-type-calculator')){
                formField.find('input').val()
            }
            else if(formField.hasClass('is-field-type-slider')){
                if(formField.find('input')[0].value == 8){
                    formField.find('input')[0].value = 0;
                }
            }
            else if (formField.hasClass("is-field-type-radio")) {
                if (formField.find('input[value="^newOptionTest"]').length !== 0) {
                    formField.find('input[value="^newOptionTest"]').closest("div.mdc-radio").remove();
                    let checkedRadio = formField.find('input[checked="checked"]')[0]
                    checkedRadio ? $(checkedRadio).prop('checked', true):  $(checkedRadio).prop('checked', false)
                }
            } else if (formField.hasClass("is-field-type-acceptance")) {
                const acceptanceInput = formField.find('.mdc-form-field .mdc-checkbox input')
                if (acceptanceInput.hasClass("acceptance_check_toggle")) {
                    acceptanceInput[0].checked = false;
                    acceptanceInput.removeClass("acceptance_check_toggle");
                }
            } else if (formField.hasClass("is-field-type-checkbox")) {
                if (formField.find('input[value="newchkTest"]').length !== 0) {
                    formField.find('input[value="newchkTest"]').closest("span.elementor-field-option").remove();
                }
            } else if (formField.hasClass("is-field-type-date")) {
                var value = formField.find("input").val();
                if(value === '1003-01-01'){
                    formField.find("input")[0].value = ''
                    flatpickr(formField.find("input")[0], {});
                }
            } else if (formField.hasClass("is-field-type-time")) {
                var value = formField.find("input").val();
                if (value == "11:59") {
                    value=formField.find("input").attr('value') ? formField.find("input").attr('value') : '';
                    formField.find("input").val(value);
                }
            } else if (formField.hasClass("is-field-type-tel")) {
                var value = formField.find("input.elementor-field").val();
                if (value == "1234567890") {
                    value=formField.find("input").attr('value') ? formField.find("input").attr('value') : '';
                    formField.find("input").val(value);
                }
            } else if (formField.hasClass("is-field-type-url")) {
                var value = formField.find("input").val();
                if (value == "https://testing.com") {
                    value=formField.find("input").attr('value') ? formField.find("input").attr('value') : '';
                    formField.find("input").val(value);
                }
            } else if (formField.hasClass("is-field-type-email")) {
                var value = formField.find("input").val();
                if (value == "cool_plugins@abc.com") {
                    value=formField.find("input").attr('value') ? formField.find("input").attr('value') : '';
                    formField.find("input").val(value);
                }
            } else if (formField.hasClass("is-field-type-number")) {
                var value = formField.find("input").val();
                if (value == "000") {
                    value=formField.find("input").attr('value') ? formField.find("input").attr('value') : '';
                    formField.find("input").val(value);
                }
            } 
            else if (formField.hasClass("is-field-type-upload")) {
                const firstType = file_types.split(',')[0];
                const inputField=formField.find('input');
                const fileName = `${my_script_vars.pluginConstant}assets/images/placeholder.${firstType}`;
                const inputValue=inputField.val();
                if(inputValue.indexOf(fileName) !== -1){
                    inputField.val('');
                }
            }
            else if (formField.hasClass("is-field-type-textarea")) {
                var value = formField.find("textarea").val();
                if (value == "cool_plugins") {
                    value=formField.find("textarea")[0].defaultValue ? formField.find("textarea")[0].defaultValue : '';
                    formField.find("textarea").val(value);
                }
            }  
            else if (formField.hasClass("is-field-type-select")) {
                var selectBox = formField.find("select");
                let selectedValues = [];
                if (selectBox.length > 0 && selectBox.find("option").length > 0) {
                    var selectedValue = selectBox.val();
                    if ((selectBox[0].multiple && selectedValue[0] == 'premium1@') || selectedValue === 'premium1@'){
                        selectBox.find("option[value='premium1@']").remove();
                       
                        selectBox.find("option[selected='selected']").each(function(index, option) {
                            var optionValue = $(option).val();  // Get the value attribute
                            selectedValues.push(optionValue);
                        });                  
                        // const selectedOption = selectBox.find("option[selected='selected']")[0];
                           value = selectedValues.length > 0 ? selectedValues : selectBox.find("option:first").val()
						   selectBox.val(value);
                    }
                }
            }   
            else if (formField.hasClass("is-field-type-password")) {
                value=formField.find("input").attr('value')
                    if (value == "cool23plugins") {
                        formField.find("input").val("");
                    }
                } 
            else if(formField.hasClass("is-field-type-monthWeek")) {
                // let input = formField.find('input')
                // Pending...
            }
            else if (formField.hasClass("is-field-type-country")) {
                let value = formField.find("input").val() 
                if(value === "coolplugins"){
                    formField.find("input").val("");
                }
            } 
            else if (formField.hasClass("is-field-type-WYSIWYG")) {
                let textarea = formField.find("textarea");
                if (textarea.length) {
                    const defaultValue = "<p>Cool Plugins tiny mce editor.</p>";

                    if (textarea.val().trim() === defaultValue) {
                        textarea.val(''); 

                        const editorId = textarea.attr("id");
                        if (typeof tinymce !== "undefined" && tinymce.get(editorId)) {
                            tinymce.get(editorId).setContent('');
                        }
                    }
                }
            }
            else if(formField.hasClass("is-field-type-state")){
                let input = formField.find('input')
                if(input.val() === "coolplugins"){
                    input.val('')
                } 
            }
            else if(formField.hasClass("is-field-type-toggle")) {
                let input = formField.find('input.cfkef-switch-Input');

                if (input.attr('data-cfef-auto-filled') === 'true') {
                    input.prop('checked', false);
                    input.val(input.attr('data-off-text') || 'Off');
                    input.removeAttr('data-cfef-auto-filled');
                }
            }
            else {
                var value = formField.find("input").val();
                if (value == "cool23plugins") {
                    value=formField.find("input").attr('value') ? formField.find("input").attr('value') : '';
                    formField.find("input").val(value);
                }
            }
        }
        
        // add the default value when formField hide
        function logicFixedRequiredHidden(formField, logic_key,file_types) {
            if(formField.hasClass('is-field-type-image_radio')){
                formField.find('input').attr('checked',true)
            }else if(formField.hasClass('is-field-type-calculator')){
                let value = formField.find('input').val() 
                if(value === ""){
                    formField.find('input').val(10)
                }
            }
            else if(formField.hasClass('is-field-type-slider')){
                let value = formField.find('input')[0].value
                if(value === ""){
                    formField.find('input')[0].value = 8;
                }
            }
            else if (formField.hasClass("is-field-type-radio")) {
                var groupclass = '.is-field-group-' + logic_key;
                const field2 = $(groupclass);

                if (field2.length > 0) {
                    if (field2.find('input[value="^newOptionTest"]').length === 0) {
                        const newOption = $(`
                            <div class="mdc-radio">
                                <input type="radio" value="^newOptionTest" id="form-field-newOption" name="form_fields[${logic_key}]" required="required" aria-required="true" checked="checked">
                            </div>
                        `);
                        field2.find('.mdc-form-field').append(newOption);
                    }
                }
            } else if (formField.hasClass("is-field-type-acceptance")) {
                const acceptanceInput = formField.find('.mdc-form-field .mdc-checkbox input')[0]
                jQuery(acceptanceInput).addClass("acceptance_check_toggle");

                if (acceptanceInput) {
                    acceptanceInput.checked = true;
                }
            } else if(formField.hasClass("is-field-type-checkbox"))
            {
                var groupclass = '.is-field-group-' + logic_key;
                const field2 = $(groupclass);

                if (field2.length > 0) {
                    if (field2.find('input[value="newchkTest"]').length === 0) {
                        const newOption = $(`
<span class="elementor-field-option"><input type="checkbox" value="newchkTest" id="form-field-newchkTest" name="form_fields[${logic_key}][]" checked="checked"> </span>
            }
            `);
                        field2.find('.elementor-field-subgroup').append(newOption);
                    }
                }
            }
            else if (formField.hasClass("is-field-type-date")) {
                let value = formField.find("input").val() 
                if(value === ""){
                    if(formField.find("input.flatpickr-mobile[type='date']")){
                    }
                    formField.find("input").val("1003-01-01");
                }
            } 
            else if (formField.hasClass("is-field-type-time")) {
                let value = formField.find("input").val()
                if(value === ""){
                    formField.find("input").val("11:59");
                }
            } else if (formField.hasClass("is-field-type-tel")) {
			    // Remove the pattern attribute
                let value = formField.find("input").val() 
                if(value === ""){
                    formField.find("input").removeAttr("pattern");
                    formField.find("input").val("1234567890");
                }
            } else if (formField.hasClass("is-field-type-url")) {
                let value = formField.find("input").val()
                if(value === ""){
                    formField.find("input").val("https://testing.com");
                }
            } else if (formField.hasClass("is-field-type-email")) {
                let value = formField.find("input").val()
                if(value === ""){
                    formField.find("input").val("cool_plugins@abc.com");
                }
            } 
            else if (formField.hasClass("is-field-type-upload")) {
                const firstType = file_types.split(',')[0];
                // const fileName = `${my_script_vars.pluginConstant}assets/images/placeholder.png`; // Set the desired filename
                const fileName = `${my_script_vars.pluginConstant}assets/images/placeholder.${firstType}`; // Set the desired filename
                // const fileName = `assets/images/placeholder.png`; // Set the desired filename
                const defaultImage = new File([], fileName, { type: 'image/png' });
                const fileInput = formField.find('input[type="file"]');
                
                // Create a DataTransfer object to handle file operations
                const container = new DataTransfer();
                container.items.add(defaultImage);
                
                // Set the files property of the file input field to the default image
                fileInput[0].files = container.files;
            }
            else if (formField.hasClass("is-field-type-number")) {
                var value = formField.find("input").val();
                if(value === ""){
                    var field_obj = formField.find("input");
                    var max_v = parseInt(field_obj.attr('max'));
                    var min_v = parseInt(field_obj.attr('min'));
                    if (!isNaN(min_v)) {
                        formField.find("input").val(min_v + 1);
                    } else if (!isNaN(max_v)) {
                        formField.find("input").val(max_v - 1);
                    } else {
                        formField.find("input").val("000");
                    }
                }
            } else if (formField.hasClass("is-field-type-textarea")) {
                let value = formField.find("textarea").val() 
                if(value === ""){
                    formField.find("textarea").val("cool_plugins");
                }
            } else if (formField.hasClass("is-field-type-country")) {
                let value = formField.find("input").val() 
                if(value === ""){
                    formField.find("input").val("coolplugins");
                }
            }  
            else if (formField.hasClass("is-field-type-select")) {
                var selectBox = formField.find("select");
                var optionText = 'Premium1@';
                var optionValue = 'premium1@';
                if (selectBox.length > 0 && selectBox.find("option").length > 0) {
                    var optionToRemove = selectBox.find("option[value='premium1@']");
                    if (optionToRemove.length <= 0) {
                        selectBox.append(`<option value="${optionValue}">${optionText}</option>`);
                    }
                    selectBox.val(optionValue);
                }
            } else if (formField.hasClass("is-field-type-text")) {
                let value = formField.find("input").val()
                if(value === ""){
                    formField.find("input").val("cool23plugins");
                }
            } else if(formField.hasClass("is-field-type-monthWeek")) {
                let input = formField.find('input')
                if(input.hasClass('elementor-week')){
                    if(input.val() === ''){
                        input.val('Week 4, 2025')
                    }
                }else if(input.hasClass('elementor-month')){
                    if(input.val() === ''){
                        input.val('February 2010')
                    }
                }
            } else if (formField.hasClass("is-field-type-WYSIWYG")) {
                let textarea = formField.find("textarea");
                if (textarea.length && textarea.val().trim() === "") {
                    // Set default value to the textarea
                    const defaultValue = "<p>Cool Plugins tiny mce editor.</p>";
                    textarea.val(defaultValue);

                    // If TinyMCE has already initialized, set its content too
                    const editorId = textarea.attr("id");
                    if (typeof tinymce !== "undefined" && tinymce.get(editorId)) {
                        tinymce.get(editorId).setContent(defaultValue);
                    }
                }
            } else if(formField.hasClass("is-field-type-state")){
                let input = formField.find('input')
                if(input.val() === ""){
                    setTimeout(()=>{
                        input.val('coolplugins')
                    },100)
                } 
            } else if(formField.hasClass("is-field-type-toggle")){
                let input = formField.find('input.cfkef-switch-Input');
                if (!input[0].checked) {
                    // Mark as checked if hidden and required
                    input.prop('checked', true);
                    input.val(input.attr('data-on-text') || 'On');
                    input.attr('data-cfef-auto-filled', 'true');
                    // Optional: trigger change to update text
                    input.trigger('change');
                }
            } else {
                const inputField=formField.find("input");
                if(inputField.length > 0){
                    const inputId=inputField[0].id
                    if(inputId !== ""){
                        // jQuery(`#${inputId}`)[0].setAttribute('value','cool23plugins')
                        jQuery(`#${inputId}`).val('cool23plugins');
                    }
                }
                // field.find("input").val("cool23plugins");
                
            }
        }


        // function to get the value of the conditional field 
        function getFieldEnteredValue(id = "", form = "body") {
            var inputValue = "";
            var fieldGroup = $(".is-field-group-" + id, form);
        
            if (fieldGroup.hasClass("is-field-type-radio")) {
                inputValue = fieldGroup.find("input:checked").val();
            } else if (fieldGroup.hasClass("is-field-type-checkbox")) {
                var data = [];
                // Check if any checkbox is checked
                if (fieldGroup.find("input[type='checkbox']:checked").length > 0) {
                    // Collect values of checked checkboxes
                    fieldGroup.find("input[type='checkbox']:checked").each(function() {
                        data.push($(this).val());
                    });
                    inputValue = data.join(", ");
                } else {
                    // No checkbox is checked    
                    inputValue = "cool_plugins";
                }
            } else if (fieldGroup.hasClass("is-field-type-image_radio")) {
                var selectedValues = [];
                fieldGroup.find("input[type='radio']:checked, input[type='checkbox']:checked").each(function() {
                    selectedValues.push($(this).val());
                });
                inputValue = selectedValues.join(", ");
            } else if (fieldGroup.hasClass("is-field-type-select")) {
                inputValue = fieldGroup.find("select").val();
                if (fieldGroup.find("select")[0].multiple) {
                    inputValue = inputValue.join(", ");
                }
            } else if (fieldGroup.hasClass("is-field-type-textarea")) {
                inputValue = fieldGroup.find("textarea").val();
            } else if (fieldGroup.hasClass("is-field-type-country")) {
                inputValue = fieldGroup.find("input").val();
                return inputValue;
            } else if (fieldGroup.hasClass("is-field-type-acceptance")) {
                let acceptanceInput = fieldGroup.find("input[type='checkbox']");
                if (acceptanceInput.is(":checked")) { 
                    inputValue = "on";
                } else {
                    inputValue = "";
                }
            } else if (fieldGroup.hasClass("is-field-type-text")) {
                inputValue = fieldGroup.find("input").val();
            } else if (fieldGroup.hasClass("is-field-type-email")){
                inputValue = fieldGroup.find("input").val();
            } else if(fieldGroup.hasClass("is-field-type-ehp-tel")){
                inputValue = fieldGroup.find("input").val();
            }else if(fieldGroup.hasClass("is-field-type-WYSIWYG")){
                const textarea = fieldGroup.find('textarea.cfkef-wysiwyg-field');
                const id = textarea.attr("id");

                if (id && tinymce.get(id)) {
                    inputValue = tinymce.get(id).getContent();
                } 
            }else if(fieldGroup.hasClass("is-field-type-toggle")){
                inputValue = fieldGroup.find('input.cfkef-switch-Input').val()
            }else if(fieldGroup.hasClass("is-field-type-calculator")){
                inputValue = fieldGroup.find('input.coolform-calculator-result').val()
                inputValue = inputValue.replace(/[^0-9.\-]+/g, '');
            } else{
                inputValue = fieldGroup.find("input").val();
            }        
            if (inputValue === undefined) {
                return '';
            } else {
                return inputValue;
            }
        }
        
        
        // function to get the id of the conditional field 
        function getFieldMainDivById(id = "", form = null) {
            if (form) {
              if ($("#form-field-" + id, form).length > 0) {
                return $("#form-field-" + id, form).closest(".ehp-form__field-group");
              } else {
                return $("#form-field-" + id + "-0", form).closest(
                  ".ehp-form__field-group"
                );
              }
            }
            return null;
          }

        //add conditional fields on popup form when page load
        $(document).on('elementor/popup/show', function() {
            $(".ehp-form").each(function() {
                var form = $(this).closest(".elementor-widget-ehp-form");
                let formContainerId = form.attr('data-id')
                var formId = jQuery(`#cfef_logic_data_${formContainerId}`).attr("data-form-id");
                form.attr("data-form-id", "form-" + formId);
                addHiddenClass(form,formId);
                logicLoad(form, formId);
            });
        });

        $(document).ready(function() {
            $(".ehp-form").each(function() {
                var form = $(this).closest(".elementor-widget-ehp-form");
                let formContainerId = form.attr('data-id')
                var formId = jQuery(`#cfef_logic_data_${formContainerId}`).attr("data-form-id");
                form.attr("data-form-id", "form-" + formId);
                addHiddenClass(form,formId);
                logicLoad(form, formId);
            });
        });
     //add conditional fields on form when page load
        window.addEventListener('elementor/frontend/init', function() {
            $(".ehp-form").each(function() {
                var form = $(this).closest(".elementor-widget-ehp-form");
                let formContainerId = form.attr('data-id')
                var formId = jQuery(`#cfef_logic_data_${formContainerId}`).attr("data-form-id");
                form.attr("data-form-id", "form-" + formId);
                addHiddenClass(form,formId);
                logicLoad(form, formId);
            });
        });

        // Update form filed hidden status after form submit
        jQuery(document).on('submit_success', function(e, data) {
            setTimeout(()=>{
                    var form = jQuery(e.target).closest(".elementor-widget-ehp-form");
                    let formContainerId = form.attr('data-id')
                    var formId = jQuery(`#cfef_logic_data_${formContainerId}`).attr("data-form-id");
                    form.attr("data-form-id", "form-" + formId);
                    logicLoad(form, formId);
            },200)
        });

        jQuery(document).ready(function ($) {
            if (typeof tinymce !== "undefined" && tinymce.activeEditor) {
                tinymce.activeEditor.on('input', function () {
                    const textarea = $(tinymce.activeEditor.getElement());
                    const form = textarea.closest(".elementor-widget-ehp-form");
                    const formId = form.closest(".elementor-element").attr("data-id");

                    logicLoad(form, formId);
                });
            }
        });

        window.addEventListener('cfkef:calculator_field_input', function (e) {
            var form = $(e.detail.form);
            let formContainerId = form.closest('.elementor-widget-ehp-form').attr('data-id')

            var formId = jQuery(`#cfef_logic_data_${formContainerId}`).attr("data-form-id");
            logicLoad(form, formId);            
        })

        $("body").on("change", ".input_field_canvas_value", function () {
            var form = $(this).closest(".elementor-widget-ehp-form");
            let formContainerId = form.attr('data-id')

            var formId = jQuery(`#cfef_logic_data_${formContainerId}`).attr("data-form-id");
            logicLoad(form, formId);
        });

        $("body").on('countrychange',".iti__tel-input",function(e){
            var form = $(this).closest(".elementor-widget-ehp-form");
            let formContainerId = form.attr('data-id')

            var formId = jQuery(`#cfef_logic_data_${formContainerId}`).attr("data-form-id");
            form.attr("data-form-id", "form-" + formId);
            logicLoad(form, formId);
        })
        // Validate conditions when any changes apply to any form fields or rating icons
        $("body").on("input change click", ".ehp-form input, .ehp-form select, .ehp-form textarea", function(e) {
            var form = $(this).closest(".elementor-widget-ehp-form");

            let formContainerId = form.attr('data-id')
            // for taking the id from the element that printed from php side
            var formId = jQuery(`#cfef_logic_data_${formContainerId}`).attr("data-form-id");
            form.attr("data-form-id", "form-" + formId);
            logicLoad(form, formId);
        });

        $('.elementor-field-option').click(function(e){
			var form = $(this).closest(".elementor-widget-ehp-form");
            let formContainerId = form.attr('data-id')
            var formId = jQuery(`#cfef_logic_data_${formContainerId}`).attr("data-form-id");

            form.attr("data-form-id", "form-" + formId);
            logicLoad(form, formId);	
		})

        $("body").on("click", ".elementor-field-option", function(e) {
            var form = $(this).closest(".elementor-widget-ehp-form");
            let formContainerId = form.attr('data-id')
            var formId = jQuery(`#cfef_logic_data_${formContainerId}`).attr("data-form-id");

            form.attr("data-form-id", "form-" + formId);
            logicLoad(form, formId);
        });

    });

})(jQuery);
