/**
 * Simple and Reliable Form Builder for SPAI Contact Form
 */

(function($) {
    'use strict';

    // Global form builder object
    window.SPAIFormBuilder = {
        fields: [],
        fieldCounter: 0,
        initialized: false,
        
        init: function() {
            if (this.initialized) return;
            this.initialized = true;
            
            console.log('SPAIFormBuilder: Initializing...');
            
            // Load existing fields from PHP
            if (typeof spaiFormFields !== 'undefined' && spaiFormFields) {
                this.fields = JSON.parse(JSON.stringify(spaiFormFields)); // Deep clone
                
                // Normalize required field values from strings to booleans
                this.fields = this.fields.map(function(field) {
                    if (field.hasOwnProperty('required')) {
                        if (field.required === 'true') {
                            field.required = true;
                        } else if (field.required === 'false') {
                            field.required = false;
                        }
                    }
                    // Also normalize hide_label field
                    if (field.hasOwnProperty('hide_label')) {
                        if (field.hide_label === 'true') {
                            field.hide_label = true;
                        } else if (field.hide_label === 'false') {
                            field.hide_label = false;
                        }
                    }
                    return field;
                });
                
                console.log('SPAIFormBuilder: Loaded ' + this.fields.length + ' existing fields');
            }
            
            this.bindEvents();
            this.initImportButton();
            this.renderAllFields();
            this.initSortable();
            
            console.log('SPAIFormBuilder: Initialization complete');
        },
        
        initImportButton: function() {
            var self = this;
            
            $('#import-monday-fields').on('click', function(e) {
                e.preventDefault();
                self.showImportDialog();
            });
        },
        
        showImportDialog: function() {
            var self = this;
            
            // Create dialog HTML
            var dialogHtml = '<div id="monday-import-dialog" style="display:none;">' +
                '<p>Enter your Monday.com settings to import fields:</p>' +
                '<table class="form-table">' +
                '<tr><th><label for="import_api_key">API Key:</label></th>' +
                '<td><input type="password" id="import_api_key" class="regular-text" /></td></tr>' +
                '<tr><th><label for="import_board_id">Board ID:</label></th>' +
                '<td><input type="text" id="import_board_id" class="regular-text" />' +
                '<p class="description">You can find the board ID in the Monday.com URL</p></td></tr>' +
                '</table>' +
                '</div>';
            
            $(dialogHtml).dialog({
                title: 'Import Fields from Monday.com',
                dialogClass: 'wp-dialog',
                autoOpen: true,
                draggable: false,
                width: 500,
                modal: true,
                resizable: false,
                closeOnEscape: true,
                position: {
                    my: "center",
                    at: "center",
                    of: window
                },
                buttons: {
                    "Import": function() {
                        var apiKey = $('#import_api_key').val();
                        var boardId = $('#import_board_id').val();
                        
                        if (!apiKey || !boardId) {
                            alert('Please enter both API key and Board ID');
                            return;
                        }
                        
                        self.importFromMonday(apiKey, boardId);
                        $(this).dialog('close');
                    },
                    "Cancel": function() {
                        $(this).dialog('close');
                    }
                },
                close: function() {
                    $(this).dialog('destroy').remove();
                }
            });
        },
        
        importFromMonday: function(apiKey, boardId) {
            var self = this;
            
            // Show loading
            $('#form-fields-list').html('<p>Importing fields from Monday.com...</p>');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'spai_import_monday_fields',
                    api_key: apiKey,
                    board_id: boardId,
                    nonce: spai_admin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Clear existing fields
                        self.fields = [];
                        
                        // Add imported fields
                        response.data.forEach(function(field) {
                            self.fields.push(field);
                        });
                        
                        // Re-render all fields
                        self.renderAllFields();
                        
                        alert('Fields imported successfully!');
                    } else {
                        alert('Import failed: ' + response.data);
                        self.renderAllFields();
                    }
                },
                error: function() {
                    alert('Failed to import fields. Please try again.');
                    self.renderAllFields();
                }
            });
        },
        
        bindEvents: function() {
            var self = this;
            
            // Add field buttons
            $('.spai-add-field').off('click').on('click', function(e) {
                e.preventDefault();
                self.addField($(this).data('type'));
            });
            
            // Field actions - use delegation
            $(document).off('click', '.spai-field-edit').on('click', '.spai-field-edit', function(e) {
                e.preventDefault();
                self.editField($(this).closest('.spai-field-item').data('field-id'));
            });
            
            $(document).off('click', '.spai-field-delete').on('click', '.spai-field-delete', function(e) {
                e.preventDefault();
                self.deleteField($(this).closest('.spai-field-item').data('field-id'));
            });
            
            $(document).off('click', '.spai-field-duplicate').on('click', '.spai-field-duplicate', function(e) {
                e.preventDefault();
                self.duplicateField($(this).closest('.spai-field-item').data('field-id'));
            });
            
            // Property editor buttons
            $(document).off('click', '#save-field-changes').on('click', '#save-field-changes', function() {
                self.saveFieldChanges();
            });
            
            $(document).off('click', '#cancel-field-changes').on('click', '#cancel-field-changes', function() {
                self.cancelFieldChanges();
            });
        },
        
        initSortable: function() {
            if ($.fn.sortable) {
                $('#form-fields-list').sortable({
                    handle: '.spai-field-move',
                    placeholder: 'spai-field-placeholder',
                    update: function() {
                        SPAIFormBuilder.updateFieldOrder();
                    }
                });
            }
        },
        
        addField: function(type) {
            console.log('Adding field type:', type);
            
            this.fieldCounter++;
            var fieldId = 'field_' + Date.now() + '_' + this.fieldCounter;
            
            var field = {
                id: fieldId,
                type: type,
                name: fieldId,
                label: this.getDefaultLabel(type),
                required: false
            };
            
            // Add type-specific defaults
            switch(type) {
                case 'text':
                case 'email':
                case 'tel':
                case 'textarea':
                    field.placeholder = '';
                    break;
                case 'select':
                case 'radio':
                    field.options = ['Option 1', 'Option 2', 'Option 3'];
                    break;
                case 'multichoice':
                    field.options = ['Option 1', 'Option 2', 'Option 3'];
                    field.default_values = [];
                    break;
                case 'checkbox':
                    field.text = 'Check this box';
                    break;
            case 'consent_checkbox':
                field.label_text = 'By checking this box, you agree to receive text messages. Standard message and data rates may apply. Reply STOP to opt out at any time.';
                field.default_checked = true;
                break;
            }
            
            this.fields.push(field);
            this.renderField(field);
            
            // Auto-edit new field
            this.editField(fieldId);
        },
        
        getDefaultLabel: function(type) {
            var labels = {
                text: 'Text Field',
                email: 'Email Address',
                phone: 'Phone Number',
                textarea: 'Message',
                select: 'Select Option',
                radio: 'Choose One',
                checkbox: 'Checkbox',
                multichoice: 'Multi Choice',
                consent_checkbox: 'Consent Checkbox',
                date: 'Date',
                file: 'File Upload',
                hidden: 'Hidden Field',
                section: 'Section Header'
            };
            return labels[type] || 'New Field';
        },
        
        renderAllFields: function() {
            $('#form-fields-list').empty();
            for (var i = 0; i < this.fields.length; i++) {
                this.renderField(this.fields[i]);
            }
        },
        
        renderField: function(field) {
            var displayLabel = field.type === 'section' && field.heading ? field.heading : field.label;
            
            var html = '<div class="spai-field-item" data-field-id="' + field.id + '">';
            html += '<div class="spai-field-header">';
            html += '<span class="spai-field-move dashicons dashicons-move"></span>';
            html += '<span class="spai-field-label">' + this.escapeHtml(displayLabel) + '</span>';
            html += '<span class="spai-field-type">(' + field.type + ')</span>';
            if ((field.required === true || field.required === 'true') && field.type !== 'section') {
                html += '<span class="spai-field-required">*</span>';
            }
            html += '<div class="spai-field-actions">';
            html += '<button class="spai-field-edit" title="Edit"><span class="dashicons dashicons-edit"></span></button>';
            html += '<button class="spai-field-duplicate" title="Duplicate"><span class="dashicons dashicons-admin-page"></span></button>';
            html += '<button class="spai-field-delete" title="Delete"><span class="dashicons dashicons-trash"></span></button>';
            html += '</div>';
            html += '</div>';
            html += '</div>';
            
            $('#form-fields-list').append(html);
        },
        
        editField: function(fieldId) {
            var field = this.getFieldById(fieldId);
            if (!field) return;
            
            this.editingFieldId = fieldId;
            this.showFieldEditor(field);
        },
        
        showFieldEditor: function(field) {
            var html = '<div class="spai-field-editor">';
            html += '<h3>Edit Field: ' + field.type + '</h3>';
            
            // Basic properties - different for section headers
            if (field.type === 'section') {
                // Skip label field for sections, use heading instead
                html += '<input type="hidden" id="field-label" value="' + this.escapeHtml(field.label) + '">';
                html += '<input type="hidden" id="field-name" value="' + this.escapeHtml(field.name || field.id) + '">';
            } else {
                html += '<div class="spai-field-group">';
                html += '<label for="field-label">Label</label>';
                html += '<input type="text" id="field-label" value="' + this.escapeHtml(field.label) + '">';
                html += '</div>';
                
                html += '<div class="spai-field-group">';
                html += '<label for="field-name">Field Name (no spaces)</label>';
                html += '<input type="text" id="field-name" value="' + this.escapeHtml(field.name) + '">';
                html += '</div>';
            }
            
            // Required checkbox (not for section/hidden)
            if (field.type !== 'section' && field.type !== 'hidden') {
                html += '<div class="spai-field-group">';
                html += '<label><input type="checkbox" id="field-required" ' + (field.required === true || field.required === 'true' ? 'checked' : '') + '> Required Field</label>';
                html += '</div>';
                
                // Hide label checkbox
                html += '<div class="spai-field-group">';
                html += '<label><input type="checkbox" id="field-hide-label" ' + (field.hide_label === true || field.hide_label === 'true' ? 'checked' : '') + '> Hide Label on Form</label>';
                html += '</div>';
                
                // Width setting (half or full width)
                html += '<div class="spai-field-group">';
                html += '<label for="field-width">Field Width</label>';
                html += '<select id="field-width">';
                html += '<option value="full" ' + (field.width !== 'half' ? 'selected' : '') + '>Full Width</option>';
                html += '<option value="half" ' + (field.width === 'half' ? 'selected' : '') + '>Half Width</option>';
                html += '</select>';
                html += '</div>';
            }
            
            // Section header specific properties
            if (field.type === 'section') {
                html += '<div class="spai-field-group">';
                html += '<label for="field-heading">Section Heading</label>';
                html += '<input type="text" id="field-heading" value="' + this.escapeHtml(field.heading || field.label || '') + '">';
                html += '</div>';
                
                html += '<div class="spai-field-group">';
                html += '<label for="field-description">Description (optional)</label>';
                html += '<textarea id="field-description" rows="3">' + this.escapeHtml(field.description || '') + '</textarea>';
                html += '</div>';
            }
            
            // Placeholder (for text inputs, select dropdowns, and multichoice)
            if (['text', 'email', 'phone', 'textarea', 'select', 'multichoice'].includes(field.type)) {
                var placeholderLabel = field.type === 'select' ? 'Dropdown Placeholder (e.g., "Choose an option...")' : 
                                      field.type === 'multichoice' ? 'Search Placeholder (e.g., "Type to search options...")' : 
                                      'Placeholder Text';
                html += '<div class="spai-field-group">';
                html += '<label for="field-placeholder">' + placeholderLabel + '</label>';
                html += '<input type="text" id="field-placeholder" value="' + this.escapeHtml(field.placeholder || '') + '">';
                html += '</div>';
            }
            
            // Default value for text, email, tel, number, date, and hidden fields
            if (['text', 'email', 'phone', 'number', 'date', 'hidden'].includes(field.type)) {
                html += '<div class="spai-field-group">';
                html += '<label for="field-default-value">Default Value</label>';
                html += '<input type="text" id="field-default-value" value="' + this.escapeHtml(field.default_value || '') + '">';
                html += '</div>';
            }
            
            // Phone-specific settings
            if (field.type === 'phone') {
                html += '<div class="spai-field-group">';
                html += '<label for="field-initial-country">Initial Country</label>';
                html += '<select id="field-initial-country">';
                html += '<option value="us" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'us' ? 'selected' : '') + '>United States</option>';
                html += '<option value="ca" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'ca' ? 'selected' : '') + '>Canada</option>';
                html += '<option value="gb" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'gb' ? 'selected' : '') + '>United Kingdom</option>';
                html += '<option value="au" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'au' ? 'selected' : '') + '>Australia</option>';
                html += '<option value="de" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'de' ? 'selected' : '') + '>Germany</option>';
                html += '<option value="fr" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'fr' ? 'selected' : '') + '>France</option>';
                html += '<option value="it" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'it' ? 'selected' : '') + '>Italy</option>';
                html += '<option value="es" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'es' ? 'selected' : '') + '>Spain</option>';
                html += '<option value="mx" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'mx' ? 'selected' : '') + '>Mexico</option>';
                html += '<option value="br" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'br' ? 'selected' : '') + '>Brazil</option>';
                html += '<option value="jp" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'jp' ? 'selected' : '') + '>Japan</option>';
                html += '<option value="cn" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'cn' ? 'selected' : '') + '>China</option>';
                html += '<option value="in" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'in' ? 'selected' : '') + '>India</option>';
                html += '<option value="pl" ' + (field.phoneSettings && field.phoneSettings.initialCountry === 'pl' ? 'selected' : '') + '>Poland</option>';
                html += '</select>';
                html += '</div>';
                
                html += '<div class="spai-field-group">';
                html += '<label><input type="checkbox" id="field-separate-dialcode" ' + (field.phoneSettings && field.phoneSettings.separateDialCode ? 'checked' : '') + '> Show country dial code separately</label>';
                html += '</div>';
                
                html += '<div class="spai-field-group">';
                html += '<label><input type="checkbox" id="field-national-mode" ' + (field.phoneSettings && field.phoneSettings.nationalMode !== false ? 'checked' : '') + '> Use national formatting mode</label>';
                html += '</div>';
            }
            
            // Options (for select/radio/multichoice)
            if (['select', 'radio', 'multichoice'].includes(field.type)) {
                html += '<div class="spai-field-group">';
                html += '<label for="field-options">Options (one per line)</label>';
                html += '<textarea id="field-options" rows="5">' + (field.options || []).join("\n") + '</textarea>';
                html += '</div>';
            }
            
            // Default selected option (for select only)
            if (field.type === 'select') {
                html += '<div class="spai-field-group">';
                html += '<label for="field-default-value">Default Selected Option</label>';
                html += '<input type="text" id="field-default-value" value="' + this.escapeHtml(field.default_value || '') + '" placeholder="e.g., Illinois">';
                html += '</div>';
            }
            
            // Default selected options (for multichoice only)
            if (field.type === 'multichoice') {
                html += '<div class="spai-field-group">';
                html += '<label for="field-default-values">Default Selected Options (one per line, optional)</label>';
                html += '<textarea id="field-default-values" rows="3">' + ((field.default_values || []).join("\n")) + '</textarea>';
                html += '</div>';
            }
            
            // Checkbox text
            if (field.type === 'checkbox') {
                html += '<div class="spai-field-group">';
                html += '<label for="field-text">Checkbox Text</label>';
                html += '<input type="text" id="field-text" value="' + this.escapeHtml(field.text || '') + '">';
                html += '</div>';
            }
            
            // Consent checkbox settings
            if (field.type === 'consent_checkbox') {
                html += '<div class="spai-field-group">';
                html += '<label for="field-label-text">Consent Text</label>';
                html += '<textarea id="field-label-text" rows="3">' + this.escapeHtml(field.label_text || 'By checking this box, you agree to receive text messages. Standard message and data rates may apply. Reply STOP to opt out at any time.') + '</textarea>';
                html += '</div>';
                
                html += '<div class="spai-field-group">';
                html += '<label><input type="checkbox" id="field-default-checked" ' + (field.default_checked !== false ? 'checked' : '') + '> Checked by default</label>';
                html += '</div>';
            }
            
            // Buttons
            html += '<div class="spai-field-editor-buttons">';
            html += '<button id="save-field-changes" class="button button-primary">Save Changes</button>';
            html += '<button id="cancel-field-changes" class="button">Cancel</button>';
            html += '</div>';
            
            html += '</div>';
            
            $('#field-properties').html(html);
            
            // Initialize phone input preview if editing a phone field
            if (field.type === 'phone') {
                setTimeout(function() {
                    var $previewContainer = $('<div class="spai-phone-preview" style="margin-top: 20px;"></div>');
                    $previewContainer.html('<h4>Phone Input Preview:</h4><input type="tel" id="phone-preview" style="width: 100%;">');
                    $('#field-properties').append($previewContainer);
                    
                    if (window.SPAIPhoneInput && window.intlTelInput) {
                        var phoneInstance = SPAIPhoneInput.init('#phone-preview', {
                            initialCountry: $('#field-initial-country').val() || 'us',
                            separateDialCode: $('#field-separate-dialcode').is(':checked'),
                            nationalMode: $('#field-national-mode').is(':checked')
                        });
                        
                        // Update preview when settings change
                        $('#field-initial-country, #field-separate-dialcode, #field-national-mode').on('change', function() {
                            $('.spai-phone-preview').remove();
                            var $newPreview = $('<div class="spai-phone-preview" style="margin-top: 20px;"></div>');
                            $newPreview.html('<h4>Phone Input Preview:</h4><input type="tel" id="phone-preview-new" style="width: 100%;">');
                            $('#field-properties').append($newPreview);
                            
                            SPAIPhoneInput.init('#phone-preview-new', {
                                initialCountry: $('#field-initial-country').val() || 'us',
                                separateDialCode: $('#field-separate-dialcode').is(':checked'),
                                nationalMode: $('#field-national-mode').is(':checked')
                            });
                        });
                    }
                }, 100);
            }
        },
        
        saveFieldChanges: function() {
            if (!this.editingFieldId) return;
            
            var field = this.getFieldById(this.editingFieldId);
            if (!field) return;
            
            // Update field properties
            var labelValue = $('#field-label').val();
            var hideLabel = $('#field-hide-label').is(':checked');
            
            // Allow empty label if hide_label is checked, otherwise default to 'Untitled'
            field.label = (labelValue || (!hideLabel ? 'Untitled' : ''));
            field.name = $('#field-name').val().replace(/\s+/g, '_').toLowerCase() || field.id;
            field.required = $('#field-required').is(':checked');
            field.hide_label = hideLabel;
            field.width = $('#field-width').val() || 'full';
            
            // Section header specific properties
            if (field.type === 'section') {
                field.heading = $('#field-heading').val() || '';
                field.description = $('#field-description').val() || '';
                field.label = field.heading || 'Section Header'; // Update label to match heading
                // Section headers don't need name or required
                delete field.required;
                field.name = field.id; // Use ID as name for sections
            }
            
            if ($('#field-placeholder').length) {
                field.placeholder = $('#field-placeholder').val();
            }
            
            // Save phone-specific settings
            if (field.type === 'phone') {
                field.phoneSettings = {
                    initialCountry: $('#field-initial-country').val() || 'us',
                    separateDialCode: $('#field-separate-dialcode').is(':checked'),
                    nationalMode: $('#field-national-mode').is(':checked')
                };
            }
            
            if ($('#field-options').length) {
                field.options = $('#field-options').val().split("\n").filter(function(o) { return o.trim(); });
            }
            
            if ($('#field-default-value').length) {
                field.default_value = $('#field-default-value').val();
            }
            
            // Multichoice default values
            if (field.type === 'multichoice' && $('#field-default-values').length) {
                field.default_values = $('#field-default-values').val().split("\n").filter(function(v) { return v.trim(); });
            }
            
            if ($('#field-text').length) {
                field.text = $('#field-text').val();
            }
            
            // Consent checkbox specific properties
            if (field.type === 'consent_checkbox') {
                if ($('#field-label-text').length) {
                    field.label_text = $('#field-label-text').val();
                }
                field.default_checked = $('#field-default-checked').is(':checked');
            }
            
            // Update display
            this.updateFieldDisplay(field);
            
            // Clear editor
            this.cancelFieldChanges();
        },
        
        updateFieldDisplay: function(field) {
            var $item = $('[data-field-id="' + field.id + '"]');
            
            // For section headers, display the heading or label
            var displayLabel = field.type === 'section' && field.heading ? field.heading : field.label;
            $item.find('.spai-field-label').text(displayLabel);
            
            if (field.required === true || field.required === 'true') {
                if (!$item.find('.spai-field-required').length) {
                    $item.find('.spai-field-type').after('<span class="spai-field-required">*</span>');
                }
            } else {
                $item.find('.spai-field-required').remove();
            }
        },
        
        cancelFieldChanges: function() {
            $('#field-properties').html('<p class="description">Select a field to edit its properties</p>');
            this.editingFieldId = null;
        },
        
        deleteField: function(fieldId) {
            if (!confirm('Are you sure you want to delete this field?')) return;
            
            // Remove from array
            this.fields = this.fields.filter(function(f) { return f.id !== fieldId; });
            
            // Remove from DOM
            $('[data-field-id="' + fieldId + '"]').remove();
            
            // Clear editor if editing this field
            if (this.editingFieldId === fieldId) {
                this.cancelFieldChanges();
            }
        },
        
        duplicateField: function(fieldId) {
            var field = this.getFieldById(fieldId);
            if (!field) return;
            
            // Create duplicate with new ID
            var duplicate = JSON.parse(JSON.stringify(field));
            duplicate.id = 'field_' + Date.now() + '_' + (++this.fieldCounter);
            duplicate.name = duplicate.name + '_copy';
            duplicate.label = duplicate.label + ' (Copy)';
            
            // Insert after original
            var index = this.fields.findIndex(function(f) { return f.id === fieldId; });
            this.fields.splice(index + 1, 0, duplicate);
            
            // Re-render all fields
            this.renderAllFields();
        },
        
        updateFieldOrder: function() {
            var self = this;
            var newOrder = [];
            
            $('#form-fields-list .spai-field-item').each(function() {
                var fieldId = $(this).data('field-id');
                var field = self.getFieldById(fieldId);
                if (field) {
                    newOrder.push(field);
                }
            });
            
            this.fields = newOrder;
        },
        
        getFieldById: function(fieldId) {
            for (var i = 0; i < this.fields.length; i++) {
                if (this.fields[i].id === fieldId) {
                    return this.fields[i];
                }
            }
            return null;
        },
        
        getFormData: function() {
            console.log('Getting form data, fields:', this.fields);
            
            return {
                form_fields: this.fields,
                form_settings: this.collectFormSettings()
            };
        },
        
        collectFormSettings: function() {
            var settings = {
                submit_text: $('#submit_text').val() || 'Submit',
                redirect_url: $('#redirect_url').val() || '',
                enable_honeypot: $('input[name="enable_honeypot"]').is(':checked'),
                google_ads_conversion_id: $('#google_ads_conversion_id').val() || '',
                google_ads_conversion_label: $('#google_ads_conversion_label').val() || '',
                ga4_event_name: $('#ga4_event_name').val() || 'form_submission'
            };

            // Include email confirmation settings if available
            if (window.SPAIAdmin && typeof window.SPAIAdmin.collectEmailSettings === 'function') {
                settings.email_confirmation = window.SPAIAdmin.collectEmailSettings();
            }

            // Include newsletter settings if available
            if (window.SPAIAdmin && typeof window.SPAIAdmin.collectNewsletterSettings === 'function') {
                settings.newsletter = window.SPAIAdmin.collectNewsletterSettings();
            }

            return settings;
        },
        
        escapeHtml: function(text) {
            var map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return (text || '').toString().replace(/[&<>"']/g, function(m) { return map[m]; });
        }
    };
    
    // Initialize when ready
    $(document).ready(function() {
        if ($('#form-builder-container').length) {
            SPAIFormBuilder.init();
        }
    });

})(jQuery);