(function( $ ) {
	'use strict';

	function normalizeModernAdminNotices() {
		$('.advrf-wrapper.wef-fields-modern, .advrf-wrapper.wef-dashboard-modern, .advrf-wrapper.wef-global-modern, .advrf-wrapper.wef-configure-modern').each(function() {
			var $wrap = $(this);
			var $title = $wrap.children('.advrf-page-title, .wef-page-title').first();

			if (!$title.length) {
				return;
			}

			var $embeddedNotices = $title.children('.notice, .updated, .error');
			if ($embeddedNotices.length) {
				$embeddedNotices.each(function() {
					$(this).insertBefore($wrap);
				});
			}

		});
	}

	function toggleChildTargets($toggle, animate) {
		var targetAttr = String($toggle.attr('data-toggle-target') || '').trim();
		if (!targetAttr) {
			return;
		}

		var targetIds = targetAttr.split(',').map(function(id) {
			return String(id || '').trim();
		}).filter(Boolean);

		if (!targetIds.length) {
			return;
		}

		targetIds.forEach(function(targetId) {
			var $target = $('#' + targetId);
			if (!$target.length) {
				return;
			}

			if ($toggle.is(':checked')) {
				if (animate) {
					$target.stop(true, true).slideDown(500);
				} else {
					$target.show();
				}
			} else if (animate) {
				$target.stop(true, true).slideUp(500);
			} else {
				$target.hide();
			}
		});
	}

	function bindSmartToggleChildren() {
		$(document).on('change', '.advrf_toggle[data-toggle-target]', function() {
			toggleChildTargets($(this), true);
		});

		$('.advrf_toggle[data-toggle-target]').each(function() {
			toggleChildTargets($(this), false);
		});
	}

	function watchModernAdminNotices() {
		if (typeof MutationObserver === 'undefined') {
			return;
		}

		var observer = new MutationObserver(function() {
			normalizeModernAdminNotices();
		});

		$('.advrf-wrapper.wef-fields-modern, .advrf-wrapper.wef-dashboard-modern, .advrf-wrapper.wef-global-modern, .advrf-wrapper.wef-configure-modern').each(function() {
			observer.observe(this, {
				childList: true,
				subtree: true
			});
		});
	}

	$('.wef-popup-close').click(function(e){
            $('.wef-popup').hide();
        });
        $(".wef-insert-fields, .wef-dialog-close, .wef-builder-builder-fields-close").click(function(){
            var $modal = $("#wef-builder-modal");
            if ($modal.is(':visible')) {
                $modal.removeClass('wef-dialog-open').hide();
            } else {
                $modal.addClass('wef-dialog-open').css('display', 'flex');
            }
        });
        
        $(document).ready(function() {    
            normalizeModernAdminNotices();
            window.setTimeout(normalizeModernAdminNotices, 80);
            window.setTimeout(normalizeModernAdminNotices, 220);
            watchModernAdminNotices();
            bindSmartToggleChildren();

            $('#wef-form-tabs a:first').addClass('wef-tab-active');
            $('#wef-form-tabs a:not(:first)').addClass('wef-tab-inactive');
            $('.wef-tab-container').hide();
            $('.wef-tab-container:first').show();

            $('#wef-form-tabs a').click(function()
            {
                var t = $(this).attr('id');
                $('#wef-form-tabs a').removeClass('wef-tab-active'); 
                $('#wef-form-tabs a').addClass('wef-tab-inactive');
                $(this).removeClass('wef-tab-inactive'); 
                $(this).addClass('wef-tab-active');

                $('.wef-tab-container').hide();
                $('#'+ t + 'C').fadeIn('slow');
               
            });

        });   

        $('.wef-color-box').wpColorPicker();
        
        $('.wef_action_button input').addClass('wef_disabled');
        $('.wef_action_button input').attr('disabled','disabled');
        $('input[name="selected[]"]').click(function() {
                var atLeastOneIsChecked = $('input[name="selected[]"]:checked').length > 0;
                if (atLeastOneIsChecked == true) {
                                $('.wef_action_button input').removeClass('wef_disabled');
                    $('.wef_action_button input').removeAttr('disabled');			
                } else {
                                $('.wef_action_button input').addClass('wef_disabled');
                    $('.wef_action_button input').attr('disabled','disabled');
                }
        });
    
   var acc = document.getElementsByClassName("wef_accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    /* Toggle between adding and removing the "active" class,
    to highlight the button that controls the panel */
    this.classList.toggle("active");

    /* Toggle between hiding and showing the active panel */
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
} 
        
})( jQuery );

function efb_show_form()
{
    jQuery("#wef-builder-modal").css('display', 'block');
}


jQuery(function () {
jQuery('.wef_sortable_tabs').sortable({
		axis: 'y',
		opacity: 0.7,
		handle: '.wef-slab-drag-handle',
		update: function (event, ui) {
			var list_sortable = jQuery(this).sortable('toArray').toString();
			var data = {
				'action': 'wef_set_section_order',
				'list_order': list_sortable
			};
			jQuery.post(wpefb_admin_ajax_object.ajax_url, data, function(response) {});		
			// change order in the database using Ajax
		}
	});
});

jQuery(function () {
	jQuery('.wef_sortable_fields').sortable({
		axis: 'y',
		opacity: 0.7,
		handle: '.wef-slab-drag-handle',
		update: function (event, ui) {
				var list_sortable = jQuery(this).sortable('toArray').toString();
				var data = {
				'action': 'wef_set_field_order',
				'list_order': list_sortable
			};
			jQuery.post(wpefb_admin_ajax_object.ajax_url, data, function(response) {});
		}
	});
});


jQuery(function () {
    
	jQuery('#wef_sortable_form_tabs').sortable({
		axis: 'y',
		opacity: 0.7,
		handle: '.wef-slab-drag-handle',
		update: function (event, ui) {
				var list_sortable = jQuery(this).sortable('toArray').toString();
				var data = {
				'action': 'wef_set_form_tabs_order',
				'list_order': list_sortable
			};
			//jQuery.post(wpefb_admin_ajax_object.ajax_url, data, function(response) {});
		}
	});
});



jQuery(document).ready(function(){
    jQuery("#wef-field-selection-popup").click(function(){
        jQuery(".wef-popup").css("visibility", "visible");
        jQuery(".wef-curtains").css("visibility", "visible");
    });
});


jQuery(document).ready(function(){
    jQuery(".wef-popup-close").click(function(){
        jQuery(".wef-popup").css("visibility", "hidden");
        jQuery(".wef-curtains").css("visibility", "hidden");
    });
});

jQuery(function($) {
    $( "#tabs" ).tabs();  
});

jQuery(function($) {
    $( "#sections" ).tabs(); 
 });

jQuery(function($) {
    function applyFieldFilters() {
        var $palette = $('#field-palette');
        var activeCategory = $palette.find('.wef-field-tab.is-active').data('category') || 'all';
        var query = ($('#wef-field-search').val() || '').toLowerCase();

        $palette.find('.field-item').each(function() {
            var $item = $(this);
            var label = ($item.data('label') || '').toLowerCase();
            var desc = ($item.data('desc') || '').toLowerCase();
            var category = ($item.data('category') || '').toLowerCase();

            var matchesCategory = (activeCategory === 'all' || category === activeCategory);
            var matchesQuery = (!query || label.indexOf(query) !== -1 || desc.indexOf(query) !== -1);

            if (matchesCategory && matchesQuery) {
                $item.show();
            } else {
                $item.hide();
            }
        });
    }

    $(document).on('click', '.wef-field-tab', function() {
        var $tab = $(this);
        $tab.closest('.wef-field-tabs').find('.wef-field-tab').removeClass('is-active');
        $tab.addClass('is-active');
        applyFieldFilters();
    });

    $(document).on('input', '#wef-field-search', function() {
        applyFieldFilters();
    });

    applyFieldFilters();

//    $(document).on('click', '.wef-primary-btn', function(e) {
//        e.preventDefault();
//        if (typeof efb_show_form === 'function') {
//            efb_show_form();
//        }
//    });

    function copyShortcode($el) {
        var text = $el.data('shortcode') || $el.val();
        if (!text) {
            return;
        }

        if ($el.is('input') || $el.is('textarea')) {
            $el.trigger('select');
            $el[0].setSelectionRange(0, text.length);
        }

        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(function() {
                showCopyMessage($el);
            }).catch(function() {
                fallbackCopy($el, text);
            });
        } else {
            fallbackCopy($el, text);
        }
    }

    function fallbackCopy($el, text) {
        var success = false;
        try {
            success = document.execCommand('copy');
        } catch (e) {
            success = false;
        }
        if (!success) {
            // leave selected so user can copy manually
        }
        showCopyMessage($el);
    }

    function showCopyMessage($el) {
        var $message = $el.closest('.wef-short-code-wrap, .advrf-short-code-wrap, .wef-short-code-wrap').find('.copy-message').first();
        if ($message.length) {
            $message.stop(true, true).fadeIn(150).delay(1200).fadeOut(200);
        }
    }

    $(document).on('click', '.wef-shortcode, .advrf-shortcode, .wef-shortcode-btn', function() {
        var $el = $(this);
        if ($el.is('button')) {
            var temp = $('<input type="text" />').val($el.data('shortcode')).appendTo('body');
            temp.trigger('select');
            temp[0].setSelectionRange(0, temp.val().length);
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(temp.val()).then(function() {
                    showCopyMessage($el);
                    temp.remove();
                }).catch(function() {
                    document.execCommand('copy');
                    showCopyMessage($el);
                    temp.remove();
                });
                return;
            }
            document.execCommand('copy');
            showCopyMessage($el);
            temp.remove();
            return;
        }
        copyShortcode($el);
    });

    $(document).on('change', 'input[name="meta[wpefb_form_redirect]"]', function() {
        var value = $(this).val();
        if (value === 'page') {
            $('#wpefb_form_redirect_page_html').show(200);
            $('#wpefb_form_redirect_url_html').hide(200);
        } else if (value === 'url') {
            $('#wpefb_form_redirect_url_html').show(200);
            $('#wpefb_form_redirect_page_html').hide(200);
        } else {
            $('#wpefb_form_redirect_page_html').hide(200);
            $('#wpefb_form_redirect_url_html').hide(200);
        }
    });

    var $redirectChecked = $('input[name="meta[wpefb_form_redirect]"]:checked');
    if ($redirectChecked.length) {
        $redirectChecked.trigger('change');
    }

    function wefInsertMergeTag(editorId, tag) {
        if (!tag) {
            return;
        }
        if (typeof tinymce !== 'undefined') {
            var editor = tinymce.get(editorId);
            if (editor) {
                editor.focus();
                editor.execCommand('mceInsertContent', false, tag);
                return;
            }
        }
        var textarea = document.getElementById(editorId);
        if (textarea) {
            var start = textarea.selectionStart || 0;
            var end = textarea.selectionEnd || 0;
            var text = textarea.value || '';
            textarea.value = text.substring(0, start) + tag + text.substring(end);
            textarea.focus();
            textarea.selectionStart = textarea.selectionEnd = start + tag.length;
        }
    }

    $(document).on('click', '.wef-merge-tag-button', function() {
        var editorId = $(this).data('editor');
        var $select = $(this).closest('.wef-merge-tags').find('.wef-merge-tag-select');
        var tag = $select.val();
        wefInsertMergeTag(editorId, tag);
    });
});

jQuery(function($) {
    function getDashboardProModal() {
        var $modal = $('#wefb-dashboard-pro-modal');
        if ($modal.length) {
            return $modal;
        }

        var pro = (window.wpefb_admin_ajax_object && wpefb_admin_ajax_object.pro) ? wpefb_admin_ajax_object.pro : {};
        var logoUrl = String(pro.logo_url || '').trim();
        var logoHtml = logoUrl ? '<div class="wefb-pro-modal-brand"><img class="wefb-pro-modal-logo" src="' + logoUrl + '" alt="Vedrixa Forms"></div>' : '';

        var modalHtml = '' +
            '<div id="wefb-dashboard-pro-modal" class="wefb-pro-modal" role="dialog" aria-modal="true" aria-labelledby="wefb-dashboard-pro-title">' +
                '<div class="wefb-pro-modal-overlay"></div>' +
                '<div class="wefb-pro-modal-dialog">' +
                    '<button type="button" class="wefb-pro-modal-close" aria-label="Close">&times;</button>' +
                    logoHtml +
                    '<h3 id="wefb-dashboard-pro-title" class="wefb-pro-modal-title"></h3>' +
                    '<p class="wefb-pro-modal-message"></p>' +
                    '<div class="wefb-pro-modal-actions">' +
                        '<button type="button" class="button wefb-pro-modal-dismiss">Maybe Later</button>' +
                        '<a class="button button-primary wefb-pro-modal-upgrade" href="#" target="_blank" rel="noopener noreferrer">Upgrade to Pro</a>' +
                    '</div>' +
                '</div>' +
            '</div>';

        $('body').append(modalHtml);
        $modal = $('#wefb-dashboard-pro-modal');

        $modal.on('click', '.wefb-pro-modal-close, .wefb-pro-modal-dismiss, .wefb-pro-modal-overlay', function() {
            $modal.removeClass('is-open');
            $('body').removeClass('wefb-pro-modal-open');
        });

        $(document).on('keydown.wefbDashboardProModal', function(event) {
            if (event.key === 'Escape') {
                $modal.removeClass('is-open');
                $('body').removeClass('wefb-pro-modal-open');
            }
        });

        return $modal;
    }

    $(document).on('click', 'a[data-wpefb-pro-popup="1"]', function(event) {
        event.preventDefault();

        var $trigger = $(this);
        var label = String($trigger.data('feature-label') || 'This feature').trim();
        var upgradeHref = String($trigger.data('upgrade-url') || $trigger.attr('href') || '#').trim();

        var $modal = getDashboardProModal();
        $modal.find('.wefb-pro-modal-title').text(label + ' is available in Pro');
        $modal.find('.wefb-pro-modal-message').text('Unlock ' + label + ' and other advanced capabilities with Vedrixa Forms Pro.');
        $modal.find('.wefb-pro-modal-upgrade').attr('href', upgradeHref || '#');

        $('body').addClass('wefb-pro-modal-open');
        $modal.addClass('is-open');
    });
});
	
function wef_show_hide(obj,primary,secondary,trinary)
{
    a = jQuery(obj).is(':checked');
    if (a == true)
    {
        jQuery('#'+primary).show(500);
        if(secondary!='')
        {
                jQuery('#'+secondary).hide(500);
        }
        if(trinary!='')
        {
                jQuery('#'+trinary).hide(500);
        }
    }
    else 
    {
        jQuery('#'+primary).hide(500);
        if(secondary!='')
        {
                jQuery('#'+secondary).show(500);
        }
        if(trinary!='')
        {
                jQuery('#'+trinary).show(500);
        }
    }
}



function add_form_validation() {
    var $form = jQuery('#wef_add_form');
    if (!$form.length) {
        return true;
    }

    var $name = $form.find('#name');
    var $typeChecked = $form.find('input[name="type"]:checked');

    var $nameError = $name.closest('.wef_required').find('.errortext').first();
    var $typeWrap = $form.find('.wef_radio_required').first();
    var $typeError = $typeWrap.find('.errortext').first();
    if (!$typeError.length) {
        $typeError = jQuery('<div class="errortext"></div>').appendTo($typeWrap);
    }

    $name.removeClass('wef-input-error');
    $typeWrap.find('input[name="type"]').removeClass('wef-input-error');
    $nameError.text('');
    $typeError.text('');

    if (!jQuery.trim($name.val())) {
        $name.addClass('wef-input-error').focus();
        $nameError.text('Form name is required.');
        return false;
    }

    if (!$typeChecked.length) {
        $typeWrap.find('input[name="type"]').addClass('wef-input-error');
        $typeError.text('Please select a form type.');
        return false;
    }

    return true;
}

jQuery(function($) {
    $('#wef_add_form').on('submit', function() {
        return add_form_validation();
    });

    $('.wef-builder-builder-fields-close, .wef-dialog-close').on('click', function() {
        var $form = $('#wef_add_form');
        $form.find('.errortext').text('');
        $form.find('.wef-input-error').removeClass('wef-input-error');
    });
});
