jQuery(document).ready(function() {
    // Handle Form Fields on page load/refresh
    handleFormFields();
});

/**
 * Handles Form Fields
 *
 */
function handleFormFields () {

    // mark disabled fields
    jQuery('.wppb-form-field:not(.login-submit):not(.wppb-two-factor-authentication) input:disabled').parent().addClass('disabled-field');

    // set WYSIWYG to readonly if field is disabled
    jQuery('.wppb-wysiwyg.disabled-field').each(function () {
        let editorId = jQuery(this).find('textarea').attr('id');
        if (typeof tinymce !== 'undefined' && tinymce.get(editorId)) {
            tinymce.get(editorId).setMode('readonly');
        }
    });

    // mark Upload/Avatar Fields on Edit Form, if a file is present
    if ( jQuery('.wppb-avatar').find('.upload-field-details').length > 0 )
        jQuery('.wppb-avatar').addClass('file-selected');
    if ( jQuery('.wppb-upload').find('.upload-field-details').length > 0 )
        jQuery('.wppb-upload').addClass('file-selected');

    // Disable HTML5 validation. It prevents form field error markers to be displayed for required fields.
    jQuery('.wppb-register-user').attr('novalidate', 'novalidate');


    // handle changes for Upload and Avatar Fields
    observeUploadFieldChanges();

    // handle PMS Billing Field Labels
    handleBillingFieldLabels();

}


/**
 * Handles changes for Upload and Avatar Fields
 *
 */
function observeUploadFieldChanges() {

    // mark Upload/Avatar Fields when a file is selected for upload
    const uploadFieldObserver = new MutationObserver(handleUploadFieldChanges);

    jQuery('.wppb-avatar, .wppb-upload').each(function() {
        uploadFieldObserver.observe(this, {
            childList: true,
            subtree: true,
            attributes: true
        });
    });

    function handleUploadFieldChanges(mutationsList) {
        mutationsList.forEach(mutation => {
            if (mutation.type === 'childList' || mutation.type === 'attributes') {
                let uploadField = jQuery(mutation.target);

                if (uploadField.find('.upload-field-details').length > 0) {
                    uploadField.addClass('file-selected');
                } else {
                    uploadField.removeClass('file-selected');
                }
            }
        });
    }

}


/**
 * Handles PMS Billing Fields
 *
 */
function handleBillingFieldLabels() {

    let pmsSelectFields = jQuery('#pms_billing_country, #pms_billing_state');

    if (pmsSelectFields.length > 0) {
        pmsSelectFields.each(function() {
            jQuery(this).on('chosen:ready', function() {
                jQuery('#' + jQuery(this).attr('id') + '_chosen .chosen-single.chosen-default span').html(jQuery('label[for="' + jQuery(this).attr('id') + '"]').html());
            });
        });
    }

}