PageSourceSearch

https://www.stanleylawteam.com/wp-content/plugins/codemonkeys-hipa…/js/script.js?ver=3.1.4%26time%3D1791470831

js stanleylawteam.com collected 2026-10-08 14:47:44 UTC 240,727 bytes, 3,749 lines download raw bytes

1/**
2 * V3.1.4
3 */
4
5// IE FIX FOR startsWith METHOD
6if (!String.prototype.startsWith) {
7    String.prototype.startsWith = function(searchString, position) {
8        position = position || 0;
9        return this.indexOf(searchString, position) === position;
10    };
11}
12
13jQuery(document).ready(function() {
14    /*** CHECK IF FORMS ON THE PAGE ***/
15    var forms = jQuery('form');
16    var formBuilder = cmHipaaScript.formBuilder;
17
18    var calderaEnabledForms;
19    if(cmHipaaScript.calderaEnabledForms) {
20        calderaEnabledForms = JSON.parse(cmHipaaScript.calderaEnabledForms);
21    }
22
23    var gravityEnabledForms;
24    if(cmHipaaScript.gravityEnabledForms) {
25        gravityEnabledForms = JSON.parse(cmHipaaScript.gravityEnabledForms);
26    }
27
28    var enabledFormsSettings;
29    if(cmHipaaScript.enabledFormsSettings) {
30        enabledFormsSettings = JSON.parse(cmHipaaScript.enabledFormsSettings);
31    }
32
33    formIds = [];
34    // LOOP ENABLED CALDERA FORMS AND PUSH IDS TO ARRAY - DEPRECATED
35    for(var i = 0; i < calderaEnabledForms.length; i++){
36        if(calderaEnabledForms[i]) {
37            formIds.push(calderaEnabledForms[i]);
38        }
39    }
40
41    // LOOP ENABLED GRAVITY FORMS AND PUSH IDS TO ARRAY - DEPRECATED
42    for(var i = 0; i < gravityEnabledForms.length; i++){
43        if(gravityEnabledForms[i]) {
44            formIds.push('gform_' + gravityEnabledForms[i]);
45        }
46    }
47    /*** LOOP FORMS ***/
48    forms.each(function() {
49        var form = jQuery(this);
50        var formMainId = form.attr('id');
51        var formId = form.attr('data-form-id');
52        if(!formId) {
53            formId = formMainId;
54        }
55
56        // SET NEW SUBMIT BUTTON
57        var newSubmitButton;
58        if(formId && formId.startsWith('gform_')) {
59            newSubmitButton = '<div class="cm-hipaa-forms-submit gravity cm-hipaa-forms-button active" role="button" tabindex="0" ><i class="material-icons">lock</i> SUBMIT</div>';
60        } else {
61            newSubmitButton = '<div class="cm-hipaa-forms-submit caldera cm-hipaa-forms-button active" role="button" tabindex="0" ><i class="material-icons">lock</i> SUBMIT</div>';
62        }
63
64        var showSig;
65        if(!enabledFormsSettings) {
66            // IF NEW ENABLED FORMS SETTINGS DOESN'T EXIST SET SIGNATURE TO YES
67            showSig = 'yes';
68        }
69
70        // CHECK IF FORM OBJECT EXISTS IN ARRAY - NEW FORMS SETTINGS JSON OBJECT ARRAY METHOD
71        var formFound;
72        if(cmHipaaScript.enabledFormsSettings) {
73            enabledFormsSettings.some(function (el) {
74                if (el.id === formId && el.enabled === 'yes' || el.form_builder === 'gravity' && 'gform_' + el.id === formId && el.enabled === 'yes') {
75                    formFound = true;
76
77                    // IF SIGNATURE OPTION HAS VALUE SET IT
78                    if(el.show_signature) {
79                        showSig = el.show_signature;
80                    }
81                    // SET SUBMIT BUTTON
82                    if(el.submit_btn_text){
83                        if(el.form_builder === 'gravity' && 'gform_' + el.id === formId){
84                            newSubmitButton = '<div class="cm-hipaa-forms-submit gravity cm-hipaa-forms-button active" role="button" tabindex="0" >' + el.submit_btn_text + '</div>';
85                        } else {
86                            newSubmitButton = '<div class="cm-hipaa-forms-submit caldera cm-hipaa-forms-button active" role="button" tabindex="0" >' + el.submit_btn_text + '</div>';
87                        }
88                    }
89                }
90            });
91        }
92        // IF FORM ID IN DEPRECATED METHOD OR FORM FOUND IN NEW JSON OBJECT ARRAY METHOD
93        if(jQuery.inArray(formId, formIds) !== -1 || formFound) {
94            // CHECK IF SSL ENABLED
95            var protocol = document.location.protocol;
96
97            // ADD CM-HIPAA-FORM-ENABLED CLASS TO FORM
98            jQuery(this).addClass('cm-hipaa-form-enabled');
99
100            // SET INITIAL VALUES
101            var submitButton = jQuery(this).find('input[type="submit"]');
102            var gravityFileUploadEle = jQuery(this).find('.ginput_container_fileupload');
103            var calderaFileUploadEle = jQuery(this).find('.file-prevent-overflow').parent();
104            var calderaMultiFileUploadEle = jQuery(this).find('.cf-uploader-trigger').parent();
105            var calderaAdvancedFileUploadEle = jQuery(this).find('.cf2-field-wrapper'); // EXPERIMENTAL - WILL OTHER NON-FILE UPLOAD FIELDS USE THIS CLASS IN THE FUTURE?
106
107            if(calderaAdvancedFileUploadEle.length > 0) {
108                jQuery.each(calderaAdvancedFileUploadEle,function (){
109                    calderaMultiFileUploadEle.push(this);
110                })
111                //calderaMultiFileUploadEle.push(calderaAdvancedFileUploadEle); // EXPERIMENTAL
112            }
113
114            var gravitySflEle = jQuery(this).find('.gform_save_link');
115            var calderaFormPages;
116            var gravityFormPages;
117            var appendEle;
118
119            calderaFormPages = jQuery(this).find('[data-formpage]');
120            gravityFormPages = jQuery(this).find('.gform_page');
121
122            // CHECK IF MULTI-PAGE FORM
123            if(calderaFormPages.length) {
124                appendEle = calderaFormPages.last();
125            } else if(gravityFormPages.length) {
126                appendEle = gravityFormPages.last();
127
128                // STRIP PREVIOUS & NEXT ONCLICK & ONKEYPRESS METHODS (IE FIX SETS ATTRIBUTE BLANK AS REMOVEATTR DOESN'T PLAY WELL WITH THAT ANTIQUE PIECE OF JUNK)
129                jQuery(this).find('.gform_next_button, .gform_previous_button').prop('onclick', '').prop('onkeypress', '').removeAttr('onclick').removeAttr('onkeypress');
130
131                // LOOP PAGES AND ADD PREVIOUS/NEXT BUTTONS
132                gravityFormPages.each(function(index) {
133                    index = +index+1;
134                    var pageFooter = jQuery(this).find('.gform_page_footer');
135                    var inputIndex = jQuery(this).find('.gform_page_fields input[tabindex]').last().attr('tabindex');
136                    var previousButtonIndex;
137
138                    // PREPEND PREVIOUS BUTTON TO LAST PAGE (NOT SURE WHY ONLY THAT PAGE DOESN'T GET IT)
139                    if(index > 1 && index === gravityFormPages.length) {
140                        previousButtonIndex = +inputIndex+1;
141
142                        pageFooter.prepend('<input type="button" id="gform_previous_button_12" class="gform_previous_button button" value="Previous" tabindex="' + previousButtonIndex + '">');
143                    }
144                });
145            } else {
146                appendEle = form;
147            }
148            // REMOVE FORM ACTION TO ONLY SUBMIT THROUGH AJAX
149            jQuery(this).attr('action','');
150
151            // STOP FORMS FROM USING GENERIC SUBMIT BUTTON
152            jQuery(document).on('click', '#'+ formMainId +' input[type="submit"], #'+ formMainId +' button[type="submit"], #'+ formMainId +' [id^=gform_submit_button], #'+ formMainId +' input[type="submit"], #'+ formMainId +' button[type="submit"] ', function(e) {
153                e.preventDefault();
154                alert('ERROR:  This form submission is being overridden be the HIPAA Forms Plugin and was not submitted!');
155            });
156
157            // SET LOADING ICON
158            appendEle.append('<div class="cm-hipaa-forms-loading"><img src="' + cmHipaaScript.pluginUrl + '/images/loading/loading16.gif" alt="Securing Form" /><br /><br />SECURING FORM</div>');
159
160            // ENSURE SSL ENABLED IF FORM SELECTED AS HIPAA COMPLIANT (checks both Wordpress is_ssl AND document protocol for good measure)
161            if(protocol === 'https:' && cmHipaaScript.ssl === '1') {
162                /*** VALIDATE ACCOUNT ***/
163                jQuery.ajax({
164                    method: 'POST',
165                    type: 'POST',
166                    url: cmHipaaScript.ajax_url,
167                    data: {
168                        'action': 'cm_hipaa_validate_account',
169                        'nononce': '1',
170                        'nonce': cmHipaaScript.nonce
171                    },
172                    success: function (data) {
173                        // REMOVE LOADING ICON
174                        jQuery('.cm-hipaa-forms-loading').remove();
175
176                        //var resultData = JSON.parse(data);
177                        var resultData;
178                        try {
179                            resultData = JSON.parse(data);
180                        } catch (e) {
181                            console.log(data);
182                            appendEle.append('<div class="cm-hipaa-field-error">There was an Ajax Error!</div>');
183                            return false;
184                        }
185
186                        if(resultData.success === 'success') {
187                            // CHECK IF STAGING
188                            var stagingMessage = '';
189                            if(resultData.staging) {
190                                stagingMessage = resultData.staging;
191                            }
192
193                            /*** CHECK IF FILE UPLOAD ENABLED ***/
194                            var validatedAddOns = resultData.add_ons;
195                            var validatedAddOnsArray = '';
196                            if(validatedAddOns && validatedAddOns !== null && validatedAddOns !== 'null' && validatedAddOns !== ''){
197                                if(Array.isArray(validatedAddOns)){
198                                    validatedAddOnsArray = validatedAddOns.split(',');
199                                }else{
200                                    validatedAddOnsArray = validatedAddOns;
201                                }
202
203                            }
204                            var fileUploadEnabled = 'no';
205                            if(Array.isArray(validatedAddOnsArray) && validatedAddOnsArray.indexOf('fileupload') !== -1) {
206                                fileUploadEnabled = 'yes';
207                            } else if(validatedAddOns === 'fileupload') {
208                                fileUploadEnabled = 'yes';
209                            }
210
211                            // SET BASIC PRODUCT BADGE
212                            var basicBadge = '';
213                            if(resultData.product === 'basic' || resultData.license_status === 'expired') {
214                                basicBadge = '<div class="cm-hipaa-powered-by-badge">POWERED BY <a href="https://www.hipaaforms.online" target="_blank">HIPAA FORMS</a> <i>for Wordpress</i></div>';
215                            }
216
217                            // IF BASIC PRODUCT CHECK IF MAX SUBMISSIONS REACHED
218                            var maxSubmissionsMessage;
219                            if(resultData.product === 'basic' && resultData.this_months_submissions >= 25) {
220                                // CHANGING THIS WILL ENABLE YOUR FORM BUT THE SUBMISSIONS WILL STILL BE BLOCKED BY THE API. UPGRADING IS ONLY $50/MO, CODE MONKEYS HAVE BILLS TO PAY TOO ;).
221                                maxSubmissionsMessage = '<div class="cm-hipaa-field-error">The maximum number of forms have been submitted for this month, please try again next month.</div>' + basicBadge;
222                            }
223
224                            if(submitButton.length > 0) {
225                                // DISABLE & REMOVE ORIGINAL SUBMIT BUTTON TO PREVENT ACCIDENTAL GENERAL SUBMISSION
226                                submitButton.attr('disabled', 'disabled').remove();
227                            }
228
229                            // CHECK IF GRAVITY FILE UPLOAD FIELD & FILE UPLOAD URL EXISTS & REPLACE WITH MESSAGE IF NO UPLOAD URL
230                            if(gravityFileUploadEle && fileUploadEnabled !== 'yes') {
231                                gravityFileUploadEle.html('<div class="cm-hipaa-field-error">Default file upload functionality is not HIPAA compliant & has been disabled, please upgrade HIPAA Forms for file upload capability.</div>');
232                            } else if(gravityFileUploadEle && fileUploadEnabled === 'yes') {
233                                // DISABLE GFORM THEME ON FILE UPLOAD ELEMENT (NEEDED SINCE ORBITAL THEME)
234                                gravityFileUploadEle.addClass('gform-theme__disable');
235
236                                // LOOP FILE INPUT FIELDS & REPLACE MULTI-FILE UPLOAD IF EXISTS
237                                jQuery.each(gravityFileUploadEle, function() {
238                                    var gfMultiFile = jQuery(this).find('.gform_fileupload_multifile');
239                                    var fieldId = jQuery(this).parent().attr('id');
240                                    var fileInputId = fieldId.replace('field', 'input');
241                                    var fileInputEnd = fieldId.split('_').pop();
242                                    var fileInputName = 'input_' + fileInputEnd;
243                                    var fileInputDescribed = fieldId.replace('field', 'extensions_message');
244                                    var tabIndex = jQuery(this).find('.gform_button_select_files').attr('tabindex');
245
246                                    var gfAcceptAttr = jQuery(this).find('.gform_fileupload_multifile input[type="file"]').attr('accept');
247                                    var gfMaxFileSize = 0;
248                                    var gfDisallowedExtensions = "php,asp,aspx,cmd,csh,bat,html,htm,hta,jar,exe,com,js,lnk,htaccess,phtml,ps1,ps2,php3,php4,php5,php6,py,rb,tmp";
249                                    var gfFileMimeTypesExtensions = "*";
250                                    var gfMaxFiles = 0;
251
252                                    var gfFileInputSettings = "";
253                                    if(gfMultiFile && gfMultiFile.data('settings')){
254                                        var gfFileDataSettings = gfMultiFile.data('settings');
255                                        if(gfFileDataSettings.filters.max_file_size){
256                                            gfMaxFileSize = gfFileDataSettings.filters.max_file_size
257                                        }
258                                        var gfFileMimeTypesTitle = "";
259                                        if(gfFileDataSettings.filters.mime_types[0]){
260                                            var gfFileMimeTypes = gfFileDataSettings.filters.mime_types[0];
261                                            if(gfFileMimeTypes.title){
262                                                gfFileMimeTypesTitle = gfFileMimeTypes.title
263                                            }
264                                            if(gfFileMimeTypes.extensions){
265                                                gfFileMimeTypesExtensions = gfFileMimeTypes.extensions
266                                            }
267                                        }
268                                        if(gfFileDataSettings.gf_vars.disallowed_extensions){
269                                            gfDisallowedExtensions = gfFileDataSettings.gf_vars.disallowed_extensions
270                                        }
271                                        if(gfFileDataSettings.gf_vars.max_files){
272                                            gfMaxFiles = gfFileDataSettings.gf_vars.max_files
273                                        }
274                                        gfFileInputSettings = '{"maxfilesize":"'+gfMaxFileSize+'","allowedextensions":"'+gfFileMimeTypesExtensions+'","disallowedextensions":"'+gfDisallowedExtensions+'","maxfiles":"'+gfMaxFiles+'"}';
275                                    }else if (gfMultiFile.length === 0){
276                                        gfMaxFileSize = jQuery(this).find("input[type='hidden'][name='MAX_FILE_SIZE']").first().val();
277                                        var uploadRulesTxt = jQuery(this).find(".gform_fileupload_rules").first().text();
278                                        var start = uploadRulesTxt.indexOf("Accepted file types: ");
279                                        var end = uploadRulesTxt.lastIndexOf(',');
280                                        if(start > -1 && end > -1){
281                                            gfFileMimeTypesExtensions = uploadRulesTxt.substring(21, end).replaceAll(' ','').split(',');
282                                        }
283
284
285                                        gfFileInputSettings = '{"maxfilesize":"'+gfMaxFileSize+'","allowedextensions":"'+gfFileMimeTypesExtensions+'","disallowedextensions":"'+gfDisallowedExtensions+'","maxfiles":"'+gfMaxFiles+'"}';
286                                    }
287
288                                    isRequired = jQuery(this).parent().hasClass('gfield_contains_required');
289
290                                    if(gfMultiFile.length > 0 && gfMaxFiles === "1") {
291                                        //maxfiles set to allow only 1 file
292                                        gfMultiFile.replaceWith('<input name="' + fileInputName + '" id="' + fileInputId + '" type="file" class="medium cm-hipaa-multifile-upload-input" aria-describedby="' + fileInputDescribed + '" aria-required="' + isRequired + '" data-settings=' + gfFileInputSettings + ' accept="'+gfAcceptAttr+'"  tabindex="' + tabIndex + '">');
293                                    }else if(gfMultiFile.length > 0 ){
294                                        gfMultiFile.replaceWith('<input name="' + fileInputName + '" id="' + fileInputId + '" type="file" class="medium cm-hipaa-multifile-upload-input" aria-describedby="' + fileInputDescribed + '" aria-required="' + isRequired + '" data-settings=' + gfFileInputSettings + ' accept="'+gfAcceptAttr+'"  tabindex="' + tabIndex + '"><div id="assocd_id_'+ fileInputId +'" class="cm-hipaa-gf-multifile-upload-button">Add Another File</div>');
295                                    }else if(gfMultiFile.length === 0 && gfMaxFiles === 0){
296                                        jQuery('#'+fileInputId).replaceWith('<input name="' + fileInputName + '" id="' + fileInputId + '" type="file" class="medium cm-hipaa-multifile-upload-input" aria-describedby="' + fileInputDescribed + '"  aria-required="' + isRequired + '" data-settings=' + gfFileInputSettings + ' tabindex="' + tabIndex + '">');
297                                    }
298                                });
299                            }
300
301                            // CHECK IF CALDERA FILE UPLOAD FIELD & FILE UPLOAD URL EXISTS & REPLACE WITH MESSAGE IF NO UPLOAD URL
302                            if((calderaFileUploadEle || calderaMultiFileUploadEle) && fileUploadEnabled !== 'yes') {
303                                calderaFileUploadEle.html('<div class="cm-hipaa-field-error">Default file upload functionality is not HIPAA compliant & has been disabled, please upgrade HIPAA Forms for file upload capability.</div>');
304                            } else if(calderaMultiFileUploadEle && fileUploadEnabled === 'yes') {
305                                // LOOP FILE INPUT FIELDS & REPLACE MULTI-FILE UPLOAD IF EXISTS
306                                jQuery.each(calderaMultiFileUploadEle, function() {
307                                    var fieldId = jQuery(this).parent().attr('data-field-wrapper');
308                                    if(!fieldId){
309                                        fieldId = jQuery(this).attr('data-field-id');
310                                    }
311                                    var cfInputField = jQuery("#"+fieldId);
312                                    var cfAcceptAttr = cfInputField.attr('accept');
313                                    var cfMaxFileSize = 0;
314                                    var cfDisallowedExtensions = "php,asp,aspx,cmd,csh,bat,html,htm,hta,jar,exe,com,js,lnk,htaccess,phtml,ps1,ps2,php3,php4,php5,php6,py,rb,tmp";
315                                    var cfFileMimeTypesExtensions = "*";
316                                    var cfMaxFiles = cfInputField.attr('multiple');
317
318                                    var cfFileInputSettings = '{"maxfilesize":"'+cfMaxFileSize+'","allowedextensions":"'+cfFileMimeTypesExtensions+'","disallowedextensions":"'+cfDisallowedExtensions+'","maxfiles":"'+cfMaxFiles+'"}';
319
320                                    if(cfMaxFiles === 'multiple'){
321                                        jQuery(this).replaceWith('<div class="file-prevent-overflow"><div id="' + fieldId + '_1_file_list" class="cf-multi-uploader-list"></div><input type="file" data-settings=' + cfFileInputSettings + ' accept="'+cfAcceptAttr+'" name="' + fieldId + '" value="" data-field="' + fieldId + '" class="" id="' + fieldId + '_1" aria-labelledby="' + fieldId + 'Label"><input type="hidden" name="' + fieldId + '"></div><div id="assocd_id_'+ fieldId +'" class="cm-hipaa-cf-multifile-upload-button">Add Another File</div>');
322                                    }else {
323                                        jQuery(this).replaceWith('<div class="file-prevent-overflow"><div id="' + fieldId + '_1_file_list" class="cf-multi-uploader-list"></div><input type="file" data-settings=' + cfFileInputSettings + ' accept="' + cfAcceptAttr + '" name="' + fieldId + '" value="" data-field="' + fieldId + '" class="" id="' + fieldId + '_1" aria-labelledby="' + fieldId + 'Label"><input type="hidden" name="' + fieldId + '">');
324                                    }
325                                });
326                            }
327
328                            // CHECK IF GRAVITY FORMS "SAVE FOR LATER" LINK EXISTS AND REPLACE WITH NON-COMPLIANT MESSAGE
329                            if(gravitySflEle) {
330                                gravitySflEle.replaceWith('<div class="cm-hipaa-field-error">"Save For Later" has been disabled due to HIPAA non-compliance</div>');
331                            }
332
333                            var sigField = '';
334                            if(showSig === 'yes') {
335                                sigField = '<div class="cm-hipaa-form-signature-wrapper"><div class="cm-hipaa-form-signature-inner"><div class="cm-hipaa-form-signature" style="min-height:150px;"></div><div class="cm-hipaa-form-signature-label"><span class="cm-hipaa-form-signature-label-text">To sign left click and drag mouse or use your finger or stylus if touch screen</span> <span class="cm-hipaa-form-signature-reset cm-ghost-button" class="cm-hipaa-forms-button">RESET</span><span style="clear:both;"></span></div></div></div>';
336                            }
337
338                            // SET HIPAA PRIVACY NOTICE
339                            var cmPrivacyNoticeMethod = cmHipaaScript.privacyNoticeMethod;
340                            var cmPrivacyNoticeLabel = cmHipaaScript.privacyNoticeLabel;
341                            var cmPrivacyNoticeCopy = cmHipaaScript.privacyNoticeCopy;
342                            var cmPrivacyNoticeLink = cmHipaaScript.privacyNoticeLink;
343                            var privacyStatement;
344
345                            if(!cmPrivacyNoticeLabel) {
346                                cmPrivacyNoticeLabel = 'I agree to the HIPAA Privacy Statement';
347                            }
348
349                            if(!cmPrivacyNoticeCopy) {
350                                cmPrivacyNoticeCopy = '<p>\n' +
351                                    'This "Notice of Information/Privacy Practices" is used to inform website visitors regarding our policies with the collection, use, and disclosure of Personal Information if anyone decided to use our Service.\n' +
352                                    '</p>\n' +
353                                    '<p>\n' +
354                                    'If you choose to use our Service, then you agree to the collection and use of information in relation with this policy. The Personal Information that we collect are used for providing and improving the Service. We will not use or share your information with anyone except as de
354scribed in this Privacy Policy.\n' +
355                                    '</p>\n' +
356                                    '<p>\n' +
357                                    '<h3>Information Collection and Use</h3>\n' +
358                                    'For a better experience while using our Service, we may require you to provide us with certain personally identifiable information, including but not limited to your name, phone number, and postal address. The information that we collect will be used to contact or identify you.\n' +
359                                    '</p>\n' +
360                                    '<p>\n' +
361                                    '<h3>Log Data</h3>\n' +
362                                    'We want to inform you that whenever you visit our Service, we collect information that your browser sends to us that is called Log Data. This Log Data may include information such as your computer’s Internet Protocol ("IP") address, browser version, pages of our Service that you visit, the time and date of your visit, the time spent on those pages, and other statistics.\n' +
363                                    '</p>\n' +
364                                    '<p>\n' +
365                                    '<h3>Cookies</h3>\n' +
366                                    'Cookies are files with small amount of data that is commonly used an anonymous unique identifier. These are sent to your browser from the website that you visit and are stored on your computer’s hard drive.\n' +
367                                    '</p>\n' +
368                                    '<p>\n' +
369                                    'Our website uses these "cookies" to collection information and to improve our Service. You have the option to either accept or refuse these cookies, and know when a cookie is being sent to your computer. If you choose to refuse our cookies, you may not be able to use some portions of our Service.\n' +
370                                    '</p>\n' +
371                                    '<p>\n' +
372                                    '<h3>Service Providers</h3>\n' +
373                                    'We may employ third-party companies and individuals due to the following reasons:\n' +
374                                    '<ul>\n' +
375                                    '<li>To facilitate our Service;</li>\n' +
376                                    '<li>To provide the Service on our behalf;</li>\n' +
377                                    '<li>To perform Service-related services; or</li>\n' +
378                                    '<li>To assist us in analyzing how our Service is used.</li>\n' +
379                                    '<p>\n' +
380                                    'We want to inform our Service users that these third parties have access to your Personal Information. The reason is to perform the tasks assigned to them on our behalf. However, they are obligated not to disclose or use the information for any other purpose.\n' +
381                                    '</p>\n' +
382                                    '</p>\n' +
383                                    '<p>\n' +
384                                    '<h3>Security</h3>\n' +
385                                    'We value your trust in providing us your Personal Information, thus we are striving to use commercially acceptable means of protecting it. But remember that no method of transmission over the internet, or method of electronic storage is 100% secure and reliable, and we cannot guarantee its absolute security.\n' +
386                                    '</p>\n' +
387                                    '<p>\n' +
388                                    '<h3>Links to Other Sites</h3>\n' +
389                                    'Our Service may contain links to other sites. If you click on a third-party link, you will be directed to that site. Note that these external sites are not operated by us. Therefore, we strongly advise you to review the Privacy Policy of these websites. We have no control over, and assume no responsibility for the content, privacy policies, or practices of any third-party sites or services.\n' +
390                                    '</p>\n' +
391                                    '<p>\n' +
392                                    '<h3>Changes to This Privacy Policy</h3>\n' +
393                                    'We may update our Privacy Policy from time to time. Thus, we advise you to review this page periodically for any changes. We will notify you of any changes by posting the new Privacy Policy on this page. These 
393changes are effective immediately, after they are posted on this page.\n' +
394                                    '</p>';
395                            }
396
397                            var modalHTML;
398                            if(cmPrivacyNoticeLink && cmPrivacyNoticeMethod === 'link') {
399                                privacyStatement = '<span class="cm-hipaa-privacy-statement-link"><a href="' + cmPrivacyNoticeLink + '" target="_blank" >' + cmPrivacyNoticeLabel + '</a></span>';
400                                modalHTML = '';
401                            } else {
402                                modalHTML = '<div class="cmprivacy-modal closed"><div class="cmprivacy-modal-inner"><div class="cmprivacy-modal-inner-top"><h2 class="cmprivacy-title">Notice of Information/Privacy Practices</h2><i class="cmprivacy-close-btn material-icons">cancel</i></div><div class="cmprivacy-content">'+ cmPrivacyNoticeCopy + '</div></div></div>';
403
404                                privacyStatement = '<span class="cm-hipaa-privacy-statement"><a href="#" >' + cmPrivacyNoticeLabel + '</a></span>';
405                            }
406
407                            // CREATE HONEYPOT INPUT
408                            var honeyPot = '<input type="hidden" class="cm-hipaa-required-extra" value="" />';
409
410                            if(maxSubmissionsMessage) {
411                                // PREPEND MAX FORM SUBMISSIONS MESSAGE
412                                form.prepend('<div class="cm-hipaa-forms-prepend">'+ maxSubmissionsMessage +'</div>');
413
414                                // APPEND MAX FORM SUBMISSIONS MESSAGE
415                                appendEle.append('<div class="cm-hipaa-forms-prepend">'+ maxSubmissionsMessage +'</div>');
416
417                                // DISABLE FORM INPUTS
418                                form.find('input, textarea').attr('readonly', 'readonly');
419                                form.find('select').attr('disabled', 'disabled');
420                                form.find('input[type="checkbox"], input[type="radio"]').prop('disabled', true);
421                            } else {
422                                // APPEND ADDITIONAL FIELDS, SUBMIT BUTTON AND BADGE TO THE FORM
423                                appendEle.append('<div class="cm-hipaa-forms-prepend gform-theme__disable">' + modalHTML + '<div class="cm-hipaa-forms-privacy-statement"><label for="cm-hipaa-forms-privacy-agree" class="sr-only"> ' + cmPrivacyNoticeLabel + '</label><input type="checkbox" id="cm-hipaa-forms-privacy-agree" class="cm-hipaa-forms-privacy-agree" name="cm-hipaa-forms-privacy-agree" aria-label="HIPAA Forms Privacy Statment" value="Yes" /> ' + privacyStatement + '</div><div class="cm-hipaa-forms-prepend-bottom gform-theme__disable"><div class="cm-hipaa-forms-ssl-notice"></div>' + sigField + '<div class="cm-hipaa-forms-submit-wrapper">' + honeyPot + newSubmitButton + '</div><div class="cm-hipaa-notice"></div>' + stagingMessage + '<div class="cm-hipaa-form-badge-wrapper"><img src="' + cmHipaaScript.pluginUrl + '/images/hipaa-compliant-badge.png" alt="HIPAA COMPLIANT FORM" /></div>' + basicBadge + '</div></div>').promise().done(function () {
424                                    if (showSig === 'yes') {
425                                        // INITIALIZE THE FORM SIGNATURE CANVAS FIELD IF VISIBLE
426                                        var signature = appendEle.find(".cm-hipaa-form-signature");
427                                        if (signature.is(':visible')) {
428                                            signature.jSignature({'background-color':'transparent'});
429                                        }
430                                    }
431                                });
432                            }
433                        } else {
434                            // DISABLE & REMOVE ORIGINAL SUBMIT BUTTON TO PREVENT ACCIDENTAL GENERAL SUBMISSION
435                            submitButton.attr('disabled', 'disabled').remove();
436
437                            appendEle.append(resultData.error);
438                        }
439                    },
440                    error: function (errorThrown) {
441                        // REMOVE LOADING ICON
442                        jQuery('.cm-hipaa-forms-loading').remove();
443
444                        console.log(errorThrown);
445                    }
446                });
447            } else {
448                // APPEND NOTICE THAT SSL IS NOT ENABLED
449                form.append('<div class="cm-hipaa-forms-ssl-notice">This form is designated as a HIPAA compliant form however SSL (https) is not enabled so the form has been disabled.<br />Please ask the website administrators to fix this issue.</div>');
450
451                // DISABLE AND REMOVE SUBMIT BUTTON TO ENSURE FORM CAN'T BE SUBMITTED
452                submitButton.attr('disabled', 'disabled').remove();
453            }
454        }
455    });
456
457    /*** REINITIALIZE JSIGNATURE IF MULTI-PAGE FORM - JSIGNATURE DOESN'T INIT PROPERLY WHEN IN A HIDDEN ELEMENT ***/
458    jQuery(document).on('click', '.cm-hipaa-form-enabled .cf-page-btn-next, .cm-hipaa-form-enabled .gform_next_button, .cm-hipaa-form-enabled .gf_step, .caldera_forms_form .breadcrumb a', function() {
459        var signature = jQuery(this).closest('form').find('.cm-hipaa-form-signature');
460
461        // SET TIMEOUT TO WAIT FOR FADEIN
462        setTimeout(function() {
463            if(signature.is(':visible') && signature.find('canvas').length === 0) {
464                signature.jSignature({'background-color':'transparent'});
465            }
466        },500);
467    });
468
469    /*** ADD VALID CLASS TO SIGNATURE FIELD ON CLICK ***/
470    jQuery(document).on('click', '.jSignature', function() {
471        if(!jQuery(this).hasClass('cm-valid-sig')) {
472            jQuery(this).addClass('cm-valid-sig');
473        }
474    });
475
476    /*** TOUCH EVENT VERSION ***/
477    jQuery(document).on('touchstart', '.jSignature', function() {
478        if(!jQuery(this).hasClass('cm-valid-sig')) {
479            jQuery(this).addClass('cm-valid-sig');
480        }
481    });
482
483    /*** REMOVE VALID CLASS FROM SIGNATURE FIELD ON RESET ***/
484    jQuery(document).on('click', '.cm-hipaa-form-signature-reset', function() {
485        jQuery(this).parent().parent().find('.jSignature').removeClass('cm-valid-sig');
486    });
487
488    /*** OVER-RIDE GRAVITY PREVIOUS/NEXT BUTTONS TO SHOW/HIDE INSTEAD OF RELOAD PAGE, DEFAULT FORM SUBMIT TO SELF ISN'T PROTECTED & NOT COMPLIANT! ***/
489    jQuery(document).on('click', '.cm-hipaa-form-enabled .gform_previous_button, .cm-hipaa-form-enabled .gform_next_button', function(e) {
490        var form = jQuery(this).closest('form');
491        var formId = form.attr('id');
492        var thisPage = jQuery(this).parent().parent();
493        var pages = form.find('.gform_page');
494        var pbPercent = Math.floor(100/pages.length);
495        var progressBarTitle = form.find('.gf_progressbar_title');
496        var progressBar = form.find('.gf_progressbar_percentage');
497        var stepsWrapper = form.find('.gf_page_steps');
498        var direction;
499
500        // CLEAR ERRORS
501        form.find('.gfield_error').removeClass('gfield_error');
502        form.find('.validation_error, .validation_message').remove();
503
504        if(jQuery(this).hasClass('gform_previous_button')) {
505            direction = 'previous';
506        } else if(jQuery(this).hasClass('gform_next_button')) {
507            direction = 'next';
508        }
509
510        // LOOP PAGES
511        pages.each(function(index) {
512            index = index+1;
513
514            if(jQuery(this).attr('id') === thisPage.attr('id') && direction === 'next') {
515                // VALIDATE REQUIRED FIELDS ON PAGE
516                var inputs = thisPage.find('input, select, textarea');
517                var errors = [];
518
519                // LOOP INPUTS
520                inputs.each(function() {
521                    var fieldWrapper = jQuery(this).closest('.gfield');
522                    var fieldType = jQuery(this).attr('type');
523                    var value = jQuery(this).val();
524                    var visibleSelect;
525                    var optionText;
526                    var fieldId = jQuery(this).attr('id');
527
528                    if (!fieldType) {
529                        if (jQuery(this).is('select')) {
530                            fieldType = 'select';
531                            visibleSelect = form.find('#' + fieldId);
532                            optionText = visibleSelect.find('option:selected').text();
533                            value = visibleSelect.val();
534                        } else if (jQuery(this).is('textarea')) {
535                            fieldType = 'textarea';
536                            var visibleTextArea = form.find('#' + fieldId);
537                            value = visibleTextArea.attr('value');
538                            // TRY THE VALUE ATTR FIRST AND IF NO VALUE TRY NORMAL JQUERY VAL(), NOT SURE WHY ONE WORKS OVER THE OTHER 
538SOMETIMES
539                            if (!value || value === 'undefined') {
540                                value = visibleTextArea.val();
541                            }
542                        }
543                    }
544                    // IF CHECKBOX OR RADIO SET OPTIONS
545                    var checkOrRadio = false;
546                    var cbOptionChecked;
547                    if(fieldType === 'checkbox' || fieldType === 'radio') {
548                        checkOrRadio = true;
549                        cbOptionChecked = jQuery(this).prop('checked');
550                    }
551
552                    // SET IF FIELD IS HIDDEN OR DISABLED
553                    var isVisible = jQuery(this).is(':visible');
554                    var isDisabled = jQuery(this).prop('disabled');
555
556                    // CHECK IF FIELD IS A NUMBER FIELD WITH MIN AND/OR MAX
557                    if (fieldType === 'number') {
558                        var val = jQuery(this).val();
559                        var num = parseFloat(val);
560                        if (val !== '') {
561                            if (jQuery.isNumeric(num)) {
562                                var min = parseFloat(jQuery(this).attr('min'));
563                                var max = parseFloat(jQuery(this).attr('max'));
564                                if (jQuery.isNumeric(min) && jQuery.isNumeric(max)) {
565                                    if ((Math.round(num * 100000) < Math.round(min * 100000)) || (Math.round(max * 100000) < Math.round(num * 100000))) {
566                                        errors.push(jQuery(this).attr('id'));
567                                    }
568                                } else if (jQuery.isNumeric(max)) {
569                                    if (Math.round(max * 100000) < Math.round(num * 100000)) {
570                                        errors.push(jQuery(this).attr('id'));
571                                    }
572                                } else if (jQuery.isNumeric(min)) {
573                                    if (Math.round(num * 100000) < Math.round(min * 100000)) {
574                                        errors.push(jQuery(this).attr('id'));
575                                    }
576                                }
577                            } else {
578                                errors.push(jQuery(this).attr('id'));
579                            }
580                        }
581
582                    }
583
584                    // CHECK IF FIELD IS AN EMAIL AND FORMATTED CORRECTLY
585                    if (fieldType === 'email'){
586                        var emailVal = jQuery(this).val();
587                        // pattern taken form https://emailregex.com/
588                        var emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
589                        if ( emailVal !== '' ) {
590                            if(!emailReg.test( emailVal ) ){
591                                errors.push(jQuery(this).attr('id'));
592                            }
593                        }
594                    }
595
596                    // SET IF FIELD IS REQUIRED
597                    var required = false;
598                    if(isDisabled !== true && isVisible === true && !jQuery(this).parent().hasClass('name_prefix_select') && !jQuery(this).parent().hasClass('name_suffix') && !jQuery(this).parent().hasClass('ginput_address_line_2') && (jQuery(this).attr('required') === 'true' || jQuery(this).attr('aria-required') === 'true' || fieldWrapper.hasClass('gfield_contains_required') && checkOrRadio !== true && !jQuery(this).parent().hasClass('address_line_2'))) {
599                        required = true;
600                    }
601
602                    // IF REQUIRED FIELD WITH NO VALUE PUSH FIELD TO ERRORS ARRAY
603                    if (required && (!value || value == "") || isDisabled !== true && isVisible === true && checkOrRadio === true && fieldWrapper.hasClass('gfield_contains_required') && cbOptionChecked === false) {
604                        var invalidInputId;
605
606                        // IF CHECKBOX OR RADIO INPUT
607                        if(checkOrRadio === true) {
608                            var cbIsValid = false;
609
610                            // GROUP OPTION INPUTS
611                            var cbInputs = fieldWrapper.find('input');
612
613                            // LOOP OPTIONS
614                            cbInputs.each(function() {
615                                if(jQuery(this).prop('checked') === true) {
616                                    cbIsValid = true;
617                                }
618                            });
619
620                            // PUSH ID TO ERROR ARRAY IF INVALID
621                            if(cbIsValid !== true) {
622                                invalidInputId = fieldWrapper.attr('id');
623                            }
624                        } else if (jQuery(this).attr('id') === undefined){
625                            invalidInputId = fieldWrapper.attr('id');
626                        } else if (fieldType === 'select'){
627                            invalidInputId = fieldWrapper.attr('id');
628                        }else {
629                            invalidInputId = jQuery(this).attr('id');
630                        }
631
632                        if(invalidInputId && errors.indexOf(invalidInputId) === -1) {
633                            errors.push(invalidInputId);
634                        }
635                    }
636                });
637
638                if(errors.length > 0) {
639                    // SET FIRST INVALID FIELD
640                    var firstErrorId = errors[0];
641                    var firstInvalidInput = jQuery('#' + firstErrorId);
642                    var firstInvalidInputWrapper = firstInvalidInput.closest('.gfield');
643
644                    // ADD ERROR MESSAGE TO TOP OF FORM
645                    form.find('.gform_body').before('<div class="validation_error">There was a problem with your submission. Errors have been highlighted below.</div>');
646
647                    // LOOP INVALID INPUT ID'S
648                    for(i=0; i<errors.length; i++) {
649                        var invalidInput = jQuery('#' + errors[i]);
650                        var invalidFieldType = invalidInput.attr('type');
651
652                        // ADD ERROR CLASS & NOTICE MESSAGE
653                        var invalidInputWrapper;
654                        if(invalidFieldType === 'checkbox' || invalidFieldType === 'radio') {
655                            invalidInputWrapper = invalidInput.parent().parent().parent().parent();
656                            invalidInputWrapper.addClass('gfield_error').append('<div class="gfield_description validation_message">This field is required.</div>');
657                        } else {
658                            invalidInputWrapper = invalidInput.closest('.gfield');
659                            invalidInputWrapper.addClass('gfield_error').append('<div class="gfield_description validation_message">This field is required.</div>');
660                        }
661                    }
662
663                    // SCROLL TO FIRST INVALID FIELD
664                    jQuery('html, body').animate({
665                        scrollTop: firstInvalidInputWrapper.offset().top
666                    }, 500, 'linear');
667                } else {
668                    // FADE OUT THIS PAGE
669                    jQuery(this).fadeOut().promise().done(function () {
670                        // FADE IN NEXT PAGE
671                        var nextPageEle = jQuery(this).next('.gform_page');
672                        nextPageEle.fadeIn();
673
674                        var nextIndex = index + 1;
675
676                        // UPDATE PROGRESS BAR IF SET
677                        if(progressBar) {
678                            var nextPercent;
679                            if (index + 1 === pages.length) {
680                                nextPercent = 100;
681                            } else {
682                                nextPercent = (pbPercent * index) + pbPercent;
683                            }
684                            progressBar.css('width', nextPercent + '%').find('span').html(nextPercent + '%');
685                            progressBarTitle.html('Step ' + nextIndex + ' of ' + pages.length);
686                        }
687
688                        // UPDATE STEPS IF SET
689                        if(stepsWrapper) {
690                            var stepLinks = stepsWrapper.find('.gf_step');
691                            var pageId = nextPageEle.attr('id');
692                            var pageIdArr = pageId.split('_');
693
694                            var stepLinkId = 'gf_step_' + pageIdArr[2] + '_' + pageIdArr[3];
695
696                            // LOOP STEP LINK AND SET NEXT STEP ACTIVE
697                            jQuery.each(stepLinks, function() {
698                                if(jQuery(this).attr('id') === stepLinkId) {
699                                    jQuery(this).addClass('gf_step_active gpmpn-step-current');
700                                } else {
701                                    jQuery(this).removeClass('gf_step_active gpmpn-step-current');
702                                }
703                            });
704                        }
705
706                        // SCROLL TO FIRST INVALID FIELD
707                        jQuery('html, body').animate({
708                            scrollTop: form.offset().top
709                        }, 300, 'linear');
710                    });
711                }
712            } else if(jQuery(this).attr('id') === thisPage.attr('id') && direction === 'previous') {
713                // FADE OUT THIS PAGE
714                jQuery(this).fadeOut().promise().done(function() {
715                    // FADE IN PREVIOUS PAGE
716                    var prevPageEle = jQuery(this).prev('.gform_page');
717                    prevPageEle.fadeIn();
718
719                    var previousIndex = index - 1;
720
721                    // UPDATE PROGRESS BAR
722                    if(progressBar) {
723                        prevPercent = (pbPercent * index) - pbPercent;
724                        progressBar.css('width', prevPercent + '%').find('span').html(prevPercent + '%');
725                        progressBarTitle.html('Step ' + previousIndex + ' of ' + pages.length);
726                    }
727
728                    // UPDATE STEPS IF SET
729                    if(stepsWrapper) {
730                        var stepLinks = stepsWrapper.find('.gf_step');
731                        var pageId = prevPageEle.attr('id');
732                        var pageIdArr = pageId.split('_');
733
734                        var stepLinkId = 'gf_step_' + pageIdArr[2] + '_' + pageIdArr[3];
735
736                        // LOOP STEP LINK AND SET NEXT STEP ACTIVE
737                        jQuery.each(stepLinks, function() {
738                            if(jQuery(this).attr('id') === stepLinkId) {
739                                jQuery(this).addClass('gf_step_active gpmpn-step-current');
740                            } else {
741                                jQuery(this).removeClass('gf_step_active gpmpn-step-current');
742                            }
743                        });
744                    }
745
746                    // SCROLL TO FIRST INVALID FIELD
747                    jQuery('html, body').animate({
748                        scrollTop: form.offset().top
749                    }, 300, 'linear');
750                });
751            }
752        });
753    });
754
755    /*** ADD GRAVITY STEP LINK ACTION ***/
756    jQuery(document).on('click', '.cm-hipaa-form-enabled .gf_step', function() {
757        var form = jQuery(this).closest('form');
758        var stepsWrapper = form.find('.gf_page_steps');
759        var stepLinks = stepsWrapper.find('.gf_step');
760        var stepId = jQuery(this).attr('id');
761        var stepIdArr = stepId.split('_');
762        var pageId = 'gform_page_' + stepIdArr[2] + '_' + stepIdArr[3];
763        var curPage = form.find('.gform_page:visible');
764        var curPageIdArr = curPage.attr('id').split('_');
765
766        if(curPage.attr('id') !== pageId) {
767            if(stepIdArr[3] > curPageIdArr[3]) {
768                // CLEAR ERRORS
769                form.find('.gfield_error').removeClass('gfield_error');
770                form.find('.validation_error, .validation_message').remove();
771
772                // VALIDATE REQUIRED FIELDS ON PREVIOUS PAGES
773                var inputs = [];
774                jQuery.each(form.find('.gform_page'), function() {
775                    if(jQuery(this).attr('id').split('_')[3] < stepIdArr[3]) {
776                        var pageInputs = jQuery(this).find('input');
777
778                        pageInputs.each(function() {
779                            inputs.push(jQuery(this).attr('id'));
780                        });
781                    } else {
782                        return false;
783                    }
784                });
785
786                var errors = [];
787                // LOOP INPUTS
788                for(i=0; i<inputs.length; i++) {
789                    var curInput = jQuery('#' + inputs[i]);
790                    var fieldWrapper = curInput.closest('.gfield');
791                    var fieldType = curInput.attr('type');
792                    var value = curInput.val();
793
794                    // IF CHECKBOX OR RADIO SET OPTIONS
795                    var checkOrRadio = false;
796                    var cbOptionChecked;
797                    if(fieldType === 'checkbox' || fieldType === 'radio') {
798                        checkOrRadio = true;
799                        cbOptionChecked = curInput.prop('checked');
800                    }
801
802                    // SET IF FIELD IS HIDDEN OR DISABLED
803                    var isVisible = curInput.is(':visible');
804                    var isDisabled = curInput.prop('disabled');
805
806                    // CHECK IF FIELD IS A NUMBER FIELD WITH MIN AND/OR MAX
807                    if (fieldType === 'number') {
808                        var val = jQuery(this).val();
809                        var num = parseFloat(val);
810                        if (val !== '') {
811                            if (jQuery.isNumeric(num)) {
812                                var min = parseFloat(jQuery(this).attr('min'));
813                                var max = parseFloat(jQuery(this).attr('max'));
814                                if (jQuery.isNumeric(min) && jQuery.isNumeric(max)) {
815                                    if ((Math.round(num * 100000) < Math.round(min * 100000)) || (Math.round(max * 100000) < Math.round(num * 100000))) {
816                                        errors.push(jQuery(this).attr('id'));
817                                    }
818                                } else if (jQuery.isNumeric(max)) {
819                                    if (Math.round(max * 100000) < Math.round(num * 100000)) {
820                                        errors.push(jQuery(this).attr('id'));
821                                    }
822                                } else if (jQuery.isNumeric(min)) {
823                                    if (Math.round(num * 100000) < Math.round(min * 100000)) {
824                                        errors.push(jQuery(this).attr('id'));
825                                    }
826                                }
827                            } else {
828                                errors.push(jQuery(this).attr('id'));
829                            }
830                        }
831                    }
832
833                    // CHECK IF FIELD IS AN EMAIL AND FORMATTED CORRECTLY
834                    if (fieldType === 'email'){
835                        var emailVal = jQuery(this).val();
836                        // pattern taken form https://emailregex.com/
837                        var emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
838                        if ( emailVal !== '' ) {
839                            if(!emailReg.test( emailVal ) ){
840                                errors.push(jQuery(this).attr('id'));
841                            }
842                        }
843                    }
844
845                    // SET IF FIELD IS REQUIRED
846                    var required = false;
847                    if(isDisabled !== true && isVisible === true && (curInput.attr('required') || curInput.attr('aria-required') || fieldWrapper.hasClass('gfield_contains_required') && checkOrRadio !== true && !curInput.parent().hasClass('address_line_2'))) {
848                        required = true;
849                    }
850
851                    if (required === true && !value || isDisabled !== true && isVisible === true && checkOrRadio === true && fieldWrapper.hasClass('gfield_contains_required') && cbOptionChecked === false) {
852                        var invalidInputId;
853
854                        // IF CHECKBOX OR RADIO INPUT
855                        if (fieldType === 'checkbox' || fieldType === 'radio') {
856                            var cbIsValid;
857
858                            // SET INPUT GROUP WRAPPER
859                            var cbInputWrapper = curInput.parent().parent().parent().parent();
860
861                            // GROUP OPTION INPUTS
862                            var cbInputs = cbInputWrapper.find('input');
863
864                            // LOOP OPTIONS
865                            cbInputs.each(function () {
866                                cbIsValid = false;
867
868                                if (jQuery(this).prop('checked') === true) {
869                                    cbIsValid = true;
870
871                                    return false;
872                                }
873                            });
874
875                            // PUSH ID TO ERROR ARRAY IF INVALID
876                            if (cbIsValid !== true) {
877                                invalidInputId = cbInputWrapper.attr('id');
878                            }
879                        } else {
880                            invalidInputId = curInput.attr('id');
881                        }
882                        if (invalidInputId && errors.indexOf(invalidInputId) === -1) {
883                            errors.push(invalidInputId);
884                        }
885                    }
886                }
887
888                if (errors.length > 0) {
889                    // SET FIRST INVALID FIELD
890                    var firstErrorId = errors[0];
891                    var firstInvalidInput = jQuery('#' + firstErrorId);
892                    var errorPage = firstInvalidInput.closest('.gform_page');
893                    var errorPageIdArr = errorPage.attr('id').split('_');
894                    var firstInvalidInputWrapper = firstInvalidInput.closest('.gfield');
895
896                    // ADD ERROR MESSAGE TO TOP OF FORM
897                    form.find('.gform_body').before('<div class="validation_error">There was a problem with your submission. Errors have been highlighted below.</div>');
898
899                    // LOOP INVALID INPUT ID'S
900                    for (i = 0; i < errors.length; i++) {
901                        var invalidInput = jQuery('#' + errors[i]);
902                        var invalidFieldType = invalidInput.attr('type');
903
904                        // ADD ERROR CLASS & NOTICE MESSAGE
905                        var invalidInputWrapper;
906                        if (invalidFieldType === 'checkbox' || invalidFieldType === 'radio') {
907                            invalidInputWrapper = invalidInput.parent().parent().parent().parent();
908                            invalidInputWrapper.addClass('gfield_error').append('<div class="gfield_description validation_message">This field is required.</div>');
909                        } else {
910                            invalidInputWrapper = invalidInput.closest('li');
911                            invalidInputWrapper.addClass('gfield_error').append('<div class="gfield_description validation_message">This field is required.</div>');
912                        }
913                    }
914
915                    if(errorPage.attr('id') !== curPage.attr('id')) {
916                        curPage.fadeOut().promise().done(function() {
917                            errorPage.fadeIn();
918
919                            // UPDATE LINKS
920                            jQuery.each(stepLinks, function () {
921                                if (jQuery(this).attr('id') === 'gf_step_' + errorPageIdArr[2] + '_' + errorPageIdArr[3]) {
922                                    jQuery(this).addClass('gf_step_active gpmpn-step-current');
923                                } else {
924                                    jQuery(this).removeClass('gf_step_active gpmpn-step-current');
925                                }
926                            });
927                        });
928                    }
929
930                    // SCROLL TO FIRST INVALID FIELD
931                    jQuery('html, body').animate({
932                        scrollTop: firstInvalidInputWrapper.offset().top
933                    }, 500, 'linear');
934                } else {
935                    // FADE OUT CURRENT PAGE
936                    curPage.fadeOut().promise().done(function () {
937                        // FADE IN SELECTED PAGE
938                        jQuery('#' + pageId).fadeIn();
939
940                        // UPDATE LINKS
941                        jQuery.each(stepLinks, function () {
942                            if (jQuery(this).attr('id') === stepId) {
943                                jQuery(this).addClass('gf_step_active gpmpn-step-current');
944                            } else {
945                                jQuery(this).removeClass('gf_step_active gpmpn-step-current');
946                            }
947                        });
948                    });
949                }
950            } else {
951                // FADE OUT CURRENT PAGE
952                curPage.fadeOut().promise().done(function () {
953                    // FADE IN SELECTED PAGE
954                    jQuery('#' + pageId).fadeIn();
955                    // UPDATE LINKS
956                    jQuery.each(stepLinks, function () {
957                        if (jQuery(this).attr('id') === stepId) {
958                            jQuery(this).addClass('gf_step_active gpmpn-step-current');
959                        } else {
960                            jQuery(this).removeClass('gf_step_active gpmpn-step-current');
961                        }
962                    });
963                });
964            }
965        }
966    });
967
968    /*** MULTI-FILE UPLOAD ***/
969    jQuery(document).on('change', '.cm-hipaa-multifile-upload-input',function (){
970        jQuery('body .cm-hipaa-multifile-errors').remove();
971        var settings = jQuery(this).data('settings');
972        var uploadPath = jQuery(this).val();
973        var uploadExtension = uploadPath.substring(uploadPath.lastIndexOf(".")+1, uploadPath.length).toLowerCase();  // ADDED TOLOWERCASE
974        //Default values
975        var uploadValidationErrors = [];
976        var maxFileSize = "";
977        var isMaxFileSize = true;
978        var isAllowedExtention = null;
979        var isDisallowedExtention = null;
980
981        if(settings.maxfilesize){
982            maxFileSize = settings.maxfilesize;
983            var fileSize = jQuery(this).prop('files')[0].size;
984            //maxFileSize = maxFileSize.substring(0,maxFileSize.length - 1); //No Longer needed
985            if(fileSize > parseInt(maxFileSize)){
986                 uploadValidationErrors.push("<div class='cm-hipaa-field-error cm-hipaa-multifile-errors'>This file is too large.</div>");
987            }
988        }
989
990        var allowedExtentions = "";
991        if(settings.allowedextensions){
992            allowedExtentions = settings.allowedextensions;
993        }
994
995        var disallowedExtentions = "";
996        if(settings.disallowedextentions){
997            disallowedExtentions = settings.disallowedextentions;
998        }
999
1000        if(allowedExtentions !== "*"){
1001            var allowedExtentionsArray = allowedExtentions.split(',');
1002            //if extention not found in array then error is given
1003            if(!allowedExtentionsArray.includes(uploadExtension)){
1004                uploadValidationErrors.push("<div class='cm-hipaa-field-error cm-hipaa-multifile-errors'>This file type is not allowed.</div>")
1005            }
1006        }else{
1007            var disallowedExtentionsArray = disallowedExtentions.split(',');
1008            //if extention is found in array then error is given
1009            if(disallowedExtentionsArray.includes(uploadExtension)){
1010                uploadValidationErrors.push("<div class='cm-hipaa-field-error cm-hipaa-multifile-errors'>This file type is not allowed.</div>")
1011            }
1012        }
1013
1014        var maxFiles = 0;
1015        if(settings.maxfiles){
1016            maxFiles = settings.maxfiles;
1017        }
1018
1019        if(uploadValidationErrors.length){
1020            jQuery(this).val("");
1021            for (i = 0; i < uploadValidationErrors.length; i++) {
1022                jQuery(this).before(uploadValidationErrors[i]);
1023            }
1024        }
1025    })
1026
1027    /*** GRAVITY MULTI-FILE UPLOAD ADD NEW FIELD ***/
1028    jQuery(document).on('click', '.cm-hipaa-gf-multifile-upload-button', function() {
1029        var fileUploadInputCount = jQuery(this).parent().find('input[type="file"]').length+1;
1030        var fieldId = jQuery(this).parent().parent().attr('id');
1031        var fileInputId = fieldId.replace('field', 'input');
1032        var fileInputEnd = fieldId.split('_').pop();
1033        var fileInputName = 'input_' + fileInputEnd;
1034        var fileInputDescribed = fieldId.replace('field', 'extensions_message');
1035        var gfFileInputSettings = JSON.stringify(jQuery('#'+fileInputId).data('settings'));
1036        var gfAcceptAttr = jQuery('#'+fileInputId).attr('accept');
1037        jQuery(this).before('<div class="multi-file-input-spacer"></div><input name="' + fileInputName + '_' + fileUploadInputCount + '" id="' + fileInputId + '_' + fileUploadInputCount + '" type="file" class="medium cm-hipaa-multifile-upload-input" data-settings=' + gfFileInputSettings + ' accept="'+gfAcceptAttr+'" aria-describedby="' + fileInputDescribed + '"><div class="cm-hipaa-gf-delete-file"><i class="material-icons">delete_forever</i></div>');
1038        gfAddAnotherFileBtn(fileInputId);
1039    });
1040
1041    /*** GRAVITY HANDLE MULTI-FILE ADD ANOTHER FILE BUTTON ***/
1042    function gfAddAnotherFileBtn(assocdInputId){
1043        var fileInputId = jQuery('#'+assocdInputId);
1044        var count = 0;
1045        count = fileInputId.parent().find('input[type="file"]').length;
1046        var fileInputSetting = fileInputId.data('settings');
1047        var max = parseInt(fileInputSetting.maxfiles);
1048        var addAnotherBtn = jQuery('#assocd_id_'+assocdInputId);
1049        var btnFound = false;
1050        if(addAnotherBtn.length > 0){
1051            btnFound = true;
1052        }
1053        if((!btnFound && max === 0) || (!btnFound && max > count)){
1054            fileInputId.parent().find('span.gform_fileupload_rules').before('<div id="assocd_id_'+ assocd
1054InputId +'" class="cm-hipaa-gf-multifile-upload-button">Add Another File</div>')
1055        }else if(btnFound && max <= count && max !== 0){
1056            addAnotherBtn.remove();
1057        }
1058    }
1059
1060    /*** CALDERA MULTI-FILE UPLOAD ADD NEW FIELD ***/
1061    jQuery(document).on('click', '.cm-hipaa-cf-multifile-upload-button', function() {
1062        var fileUploadInputCount = 0;
1063        fileUploadInputCount = jQuery(this).parent().find('input[type="file"]').length+1;
1064
1065        //var fieldId = jQuery(this).parent().attr('data-field-wrapper');
1066        var fieldId = jQuery(this).attr('id').replace('assocd_id_','');
1067        var firstFileUploadInput = jQuery('#'+fieldId+'_1');
1068        var cfFileInputSettings = firstFileUploadInput.data('settings');
1069        var cfAcceptAttr = firstFileUploadInput.attr('accept');
1070
1071        jQuery(this).before('<div class="multi-file-input-spacer"></div><div class="file-prevent-overflow"><div id="' + fieldId + '_' + fileUploadInputCount + '_file_list" class="cf-multi-uploader-list"></div><input type="file" data-settings=' + cfFileInputSettings + ' accept="'+cfAcceptAttr+'" name="' + fieldId + '_' + fileUploadInputCount + '" value="" data-field="' + fieldId + '" class="" id="' + fieldId + '_' + fileUploadInputCount + '" aria-labelledby="' + fieldId + 'Label"><input type="hidden" name="' + fieldId + '"></div><div class="cm-hipaa-cf-delete-file"><i class="material-icons">delete_forever</i></div>');
1072    });
1073
1074    /*** GRAVITY MULTI-FILE DELETE ***/
1075    jQuery(document).on('click', '.cm-hipaa-gf-delete-file', function() {
1076        var fileInputId = jQuery(this).parent().find('input[type="file"]').first().attr('id')
1077        jQuery(this).prev().prev().remove();
1078        jQuery(this).prev().remove();
1079        jQuery(this).remove();
1080        gfAddAnotherFileBtn(fileInputId);
1081    });
1082
1083    /*** CALDERA MULTI-FILE DELETE ***/
1084    jQuery(document).on('click', '.cm-hipaa-cf-delete-file', function() {
1085        jQuery(this).prev().prev().remove();
1086        jQuery(this).prev().remove();
1087        jQuery(this).remove();
1088    });
1089
1090    /*** TRIGGER CLICK EVENT ON ENTER/RETURN KEY CALDERA***/
1091    jQuery(document).on('keydown', 'form .cm-hipaa-forms-submit.caldera.active', function(e){
1092        if(e.keyCode===13){
1093            jQuery('form .cm-hipaa-forms-submit.caldera.active').trigger('click');
1094        }
1095    });
1096
1097    /*** SUBMIT HIPAA ENABLED CALDERA FORM ***/
1098    jQuery(document).on('click', 'form .cm-hipaa-forms-submit.caldera.active', function(e){
1099        var submitButton = jQuery(this);
1100        var form = jQuery(this).parents('form:first');
1101        var formHtml = form.html();
1102        var noticeEle = form.find('.cm-hipaa-notice');
1103        var formMainId = form.attr('id');
1104        var formId = form.attr('data-form-id');
1105        if(!formId) {
1106            formId = formMainId;
1107        }
1108
1109        // REMOVE ACTIVE CLASS FROM SUBMIT BUTTON TO PREVENT RE-SUBMITTING
1110        submitButton.removeClass('active').addClass('inactive');
1111
1112        var calderaEnabledForms = JSON.parse(cmHipaaScript.calderaEnabledForms); // DEPRECATED
1113        formIds = [];
1114
1115        // LOOP CALDERA FORMS AND PUSH IDS TO ARRAY - DEPRECATED
1116        for(var i = 0; i < calderaEnabledForms.length; i++){
1117            if(calderaEnabledForms[i]) {
1118                formIds.push(calderaEnabledForms[i]);
1119            }
1120        }
1121
1122        var enabledFormsSettings;
1123        if(cmHipaaScript.enabledFormsSettings) {
1124            enabledFormsSettings = JSON.parse(cmHipaaScript.enabledFormsSettings); // NEW JSON OBJECT ARRAY
1125        }
1126
1127
1128        // CHECK IF FORM OBJECT EXISTS IN ARRAY - NEW FORMS SETTINGS JSON OBJECT ARRAY METHOD
1129        var formFound = false;
1130        var successHandler;
1131        var successMessage;
1132        var successHideForm;
1133        var successRedirect;
1134        var successCallback;
1135        var successCallbackParams;
1136        var selectedUserSlug = '';
1137        var showSignature;
1138        var notificationOption = '';
1139        //var notificationFromName = '';
1140        //var notificationFromEmail = '';
1141        //var notificationSendTo = '';
1142        //var notificationSubject = '';
1143        //var notificationMessage = '';
1144
1145        if(cmHipaaScript.enabledFormsSettings) {
1146            enabledFormsSettings.some(function (el) {
1147                if (el.id === formId && el.enabled === 'yes') {
1148                    formFound = true;
1149                    successHandler = el.success_handler;
1150                    successMessage = el.success_message;
1151                    successHideForm = el.success_hide_form;
1152                    successRedirect = el.success_redirect;
1153                    successCallback = el.success_callback;
1154                    successCallbackParams = el.success_callback_params;
1155                    selectedUserSlug = el.selected_user_slug;
1156                    showSignature = el.show_signature;
1157                    notificationOption = el.notification_option;
1158                    //notificationFromName = el.notification_from_name;
1159                    //notificationFromEmail = el.notification_from_email;
1160                    //notificationSendTo = el.notification_sendto;
1161                    //notificationSubject = el.notification_subject;
1162                    //notificationMessage = el.notification_message;
1163                }
1164            });
1165        }
1166
1167        // SET SUCCESS MESSAGE IF NOT SET
1168        if(!successMessage) {
1169            successMessage = 'Thank you, your form has been encrypted to protect your privacy and submitted successfully!';
1170        }
1171
1172        // IF FORM ID IS IN ENABLED FORMS PREVENT DEFAULT SUBMIT AND SEND TO CODE MONKEYS
1173        if(jQuery.inArray(formId, formIds) !== -1 || formFound) {
1174            e.preventDefault(); //Prevent the normal submission action
1175            var defaultBorder;
1176
1177            // GET FILE INPUTS
1178            var fileInputs = form.find('input[type=file]');
1179
1180            // CLONE THE FORM AS A HIDDEN VERSION IN ORDER TO REPLACE INPUTS WITH VALUES AND FORMAT TO SAVE
1181            form.after('<div class="cm-hipaa-forms-hidden-form" style="display:none;"></div>');
1182            form.clone().appendTo('.cm-hipaa-forms-hidden-form');
1183            var hiddenForm = jQuery('.cm-hipaa-forms-hidden-form form');
1184            var hiddenFormInputs = jQuery('.cm-hipaa-forms-hidden-form form :input');
1185
1186            // REMOVE THE UNWANTED APPENDED ITEMS AT BOTTOM OF FORM
1187            hiddenForm.find('.cm-hipaa-forms-prepend-bottom, .cmprivacy-modal, .cmprivacy-modal-overlay').remove();
1188
1189            // REMOVE STEP LINK BREADCRUMBS IF EXIST
1190            hiddenForm.find('.breadcrumb').remove();
1191
1192            // LOOP CLONED HIDDEN FORM INPUTS AND GET LABELS => VALUES & FULL HTML VERSION OF FORM
1193            var formFields = [];
1194            var validationErrors = [];
1195
1196            var inputs = jQuery('#' + formMainId + ' :input');
1197            hiddenFormInputs.each(function() {
1198                var label = form.find('label[for="' + jQuery(this).attr('id') + '"]').text().trim();
1199                var value = jQuery(this).val();
1200                var dataField = jQuery(this).attr('data-field');
1201                var fieldId = jQuery(this).attr('id');
1202                var fieldName = jQuery(this).attr('name');
1203                var fieldType = jQuery(this).attr('type');
1204                defaultBorder = jQuery(this).css('border');
1205                var required = jQuery(this).attr('required');
1206                var formGroup = jQuery(this).closest('.form-group');
1207                var checkboxParentLabel = '';
1208                var checkboxLabel = '';
1209                var radioValue = '';
1210                var checkboxValue = '';
1211                var fieldValue = '';
1212                var optionLabel = '';
1213                var optionValue = '';
1214
1215                // IGNORE INITIAL HIDDEN CALDERA FIELDS & NEXT/PREVIOUS BUTTONS
1216                if(fieldName !== '_cf_verify' && fieldName !== '_wp_http_referer' && fieldName !== '_cf_frm_id' && fieldName !== '_cf_frm_ct' && fieldName !== 'cfajax' && fieldName !== '_cf_cr_pst' && fieldType !== 'button' && !jQuery(this).hasClass('button_trigger_1') && !jQuery(this).hasClass('button_trigger_2') && fieldName !== 'pum_form_popup_id') {
1217                    if (!fieldType) {
1218                        if (jQuery(this).is('select')) {
1219                            fieldType = 'select';
1220                            var visibleSelect = form.find('#' + fieldId);
1221                            var optionText = visibleSelect.find('option:selected').text();
1222                            value = visibleSelect.val();
1223                            fieldValue = value;
1224                        } else if (jQuery(this).is('textarea')) {
1225                            fieldType = 'textarea';
1226                            var visibleTextArea = form.find('#' + fieldId);
1227                            value = visibleTextArea.attr('value');
1228                            fieldValue = value;
1229                            // TRY THE VALUE ATTR FIRST AND IF NO VALUE TRY NORMAL JQUERY VAL(), NOT SURE WHY ONE WORKS OVER THE OTHER SOMETIMES
1230                            if(!value || value === 'undefined') {
1231                                value = visibleTextArea.val();
1232                                fieldValue = value;
1233                            }
1234                        }
1235                    }
1236
1237                    // GET REQUIRED FIELDS THAT DO NOT HAVE A VALUE
1238                    if (required && !value && form.find('#' + fieldId).is(':visible') || (fieldType === 'checkbox' || fieldType === 'radio') && (required || jQuery(this).attr('data-parsley-required') === 'true') && jQuery(this).prop('checked') === false && form.find('#' + fieldId).is(':visible')) {
1239                        var errorExists;
1240
1241                        if(fieldType === 'checkbox' || fieldType === 'radio') {
1242                            var optionsGroup;
1243                            var visibleOptionsGroup;
1244                            if(fieldType === 'checkbox') {
1245                                optionsGroup = jQuery(this).data('parsley-group');
1246                                visibleOptionsGroup = form.find('input[data-parsley-group="' + optionsGroup + '"]');
1247                            } else if(fieldType === 'radio') {
1248                                optionsGroup = jQuery(this).data('radio-field');
1249                                visibleOptionsGroup = form.find('input[data-radio-field="' + optionsGroup + '"]');
1250                            }
1251                            var cbIgnore;
1252
1253                            visibleOptionsGroup.each(function() {
1254                                if(jQuery(this).prop('checked') === true) {
1255                                    cbIgnore = true;
1256
1257                                    return false;
1258                                }
1259                            });
1260
1261                            if(validationErrors.length > 0) {
1262                                validationErrors.some(function(el) {
1263                                    if(el.fieldId === fieldId || el.fieldGroup === optionsGroup) {
1264                                        errorExists = true;
1265                                    }
1266                                });
1267                            }
1268
1269                            if(!errorExists && !cbIgnore) {
1270                                validationErrors.push({
1271                                    'fieldId': fieldId,
1272                                    'label': form.find('label[for="' + optionsGroup + '"]').text(),
1273                                    'fieldType': fieldType,
1274                                    'fieldGroup': optionsGroup
1275                                });
1276                            }
1277                        } else {
1278                            validationErrors.push({
1279                                'fieldId': fieldId,
1280                                'label': form.find('label[for="' + jQuery(this).attr('id') + '"]').text(),
1281                                'fieldType': fieldType,
1282                                'fieldGroup': ''
1283                            });
1284                        }
1285                    }
1286
1287                    // SET CHECKBOX OR RADIO FIELD LABEL AND INPUT LABEL
1288                    if (fieldType === 'checkbox' || fieldType === 'radio') {
1289                        if (jQuery(this).prop('checked') === true) {
1290                            checkboxLabel = jQuery(this).parent().text().trim();
1291
1292                            if(jQuery(this).hasClass('cm-hipaa-forms-privacy-agree')) {
1293                                label = 'Privacy Agreement';
1294                            } else {
1295                                label = jQuery(this).parent().parent().parent().find('.control-label').text().trim();
1296
1297                                if(!label) {
1298                                    label = jQuery(this).parent().parent().parent().parent().find('.control-label').text().trim();
1299
1300                                    if(!label) {
1301                                        label = checkboxLabel;
1302                                    }
1303                                }
1304                            }
1305
1306                            checkboxParentLabel = label;
1307                            optionLabel = checkboxLabel;
1308                            optionValue = value;
1309                        }
1310                    }
1311
1312                    // REPLACE HIDDEN HTML VERSION INPUTS WITH VALUES
1313                    if (fieldType === 'select') {
1314                        jQuery(this).replaceWith(optionText);
1315                    } else if (fieldType === 'checkbox') {
1316                        // SET CHECKBOX VALUE IF DIFFERENT THAN LABEL
1317                        if(value !== checkboxLabel) {
1318                            checkboxValue = value;
1319                        }
1320
1321                        if (jQuery(this).prop('checked') === true) {
1322                            // SET CHECKED CHECKBOX IMAGE AND VALUE
1323                            value = '<span class="cm-hipaa-forms-checkbox-value cm-hipaa-forms-checkbox-checked" style="background: #f7f5a091;"><img src="https://www.hipaaforms.online/api-assets/checkbox.png" alt="Checked" style="height: 16px; padding-right: 5px; vertical-align: middle;" />' + checkboxValue + '</span>';
1324                            jQuery(this).parent().addClass('cm-hipaa-forms-checkbox-checked-wrapper');
1325                            if(checkboxParentLabel) {
1326                                fieldValue = 'checked';
1327                            }
1328                        } else {
1329                            // SET UNCHECKED CHECKBOX IMAGE AND VALUE
1330                            value = '<span class="cm-hipaa-forms-checkbox-value  cm-hipaa-forms-checkbox-not-checked"><img src="https://www.hipaaforms.online/api-assets/checkbox-unchecked.png" alt="Not Checked" style="height: 16px; padding-right: 5px; vertical-align: middle;" /></span>';
1331                            jQuery(this).parent().addClass('cm-hipaa-forms-checkbox-not-checked-wrapper');
1332                        }
1333                        jQuery(this).replaceWith(value);
1334                    } else if (fieldType === 'radio') {
1335                        // SET RADIO VALUE IF DIFFERENT THAN LABEL
1336                        if (value !== checkboxLabel) {
1337                            radioValue = value;
1338                        }
1339                        if (jQuery(this).prop('checked') === true) {
1340                            // SET CHECKED RADIO BUTTON IMAGE AND VALUE
1341                            value = '<span class="cm-hipaa-forms-radio-value cm-hipaa-forms-radio-checked" style="background: #f7f5a091;"><img src="https://www.hipaaforms.online/api-assets/radio-checked.png" alt="Selected" style="height: 16px; padding-right: 5px; vertical-align: middle;" />' + radioValue + '</span>';
1342                            jQuery(this).parent().addClass('cm-hipaa-forms-radio-checked-wrapper');
1343                            if (checkboxParentLabel) {
1344                                fieldValue = 'checked';
1345                            }
1346                        } else {
1347                            // SET UNCHECKED RADIO BUTTON IMAGE AND VALUE
1348                            value = '<span class="cm-hipaa-forms-radio-value cm-hipaa-forms-radio-not-checked"><img src="https://www.hipaaforms.online/api-assets/radio-unchecked.png" alt="Not Selected" style="height: 16px; padding-right: 5px; vertical-align: middle;" /></span>';
1349                            jQuery(this).parent().addClass('cm-hipaa-forms-radio-not-checked-wrapper');
1350                        }
1351                        jQuery(this).replaceWith(value);
1352                    } else if(fieldType === 'hidden') {
1353                        // NEED TO CREATE A WRAPPING ELEMENT AND PASS ATTRIBUTES FROM INPUT TO WRAPPER ELE
1354                        jQuery(this).replaceWith('<div data-field="' + jQuery(this).attr('data-field') + '" class="form-group ' + jQuery(this).attr('class') + '" id="' + jQuery(this).attr('id') + '">' + value + '</div>');
1355                    } else {
1356                        fieldValue = value;
1357                        jQuery(this).replaceWith(value);
1358                    }
1359
1360                    // ADD CUSTOM CLASS TO IDENTIFY IF FIELD VALUE IS EMPTY OR NOT
1361                    if(formGroup.hasClass('cm_hipaa_forms_field_not_empty') === false && (!fieldValue || fieldValue.length === 0)) {
1362                        formGroup.addClass('cm_hipaa_forms_field_empty');
1363                    } else {
1364                        formGroup.removeClass('cm_hipaa_forms_field_empty');
1365                        formGroup.addClass('cm_hipaa_forms_field_not_empty');
1366                    }
1367
1368
1369                    if (label && fieldValue) {
1370                        // IF LABEL EXISTS PUSH TO FIELDS ARRAY
1371                        formFields.push({
1372                            'label': label,
1373                            'option_label': optionLabel,
1374                            'option_value': optionValue,
1375                            'value': fieldValue,
1376                            'data_field': dataField,
1377                            'field_id': fieldId,
1378                            'field_type': fieldType,
1379                            'option_text': optionText
1380                        });
1381                    }
1382                }
1383            });
1384
1385            // GET SIGNATURE SVG BASE64 DATA
1386            var signatureEle = form.find('.cm-hipaa-form-signature');
1387            var datapair = signatureEle.jSignature("getData", "svgbase64");
1388            var signature;
1389            if(datapair) {
1390                signature = "data:" + datapair[0] + "," + datapair[1];
1391
1392                formFields.push({
1393                    'label': 'Signature',
1394                    'option_label': 'data:',
1395                    'option_value': datapair[0],
1396                    'value': datapair[1],
1397                    'data_field': '',
1398                    'field_id': '',
1399                    'field_type': 'signature',
1400                    'option_text': ''
1401                });
1402            }
1403
1404            // SET PRIVACY AGREEMENT ELEMENT
1405            var privacyAgreementEle = form.find('.cm-hipaa-forms-privacy-agree');
1406
1407            // RESET ERRORS
1408            //inputs.css('border', defaultBorder);
1409            jQuery('.form-group').removeClass('has-error');
1410            jQuery('input, select, textarea').removeAttr('aria-invalid').removeClass('parsley-error');
1411            jQuery('.caldera_ajax_error_block').remove();
1412            privacyAgreementEle.parent().css('border', '0');
1413            if(signatureEle) {
1414                signatureEle.find('.jSignature').css('border', '0');
1415            }
1416            noticeEle.html('');
1417
1418            // MULTI-PAGE FORM RENDERING
1419            var calderaFormPages = hiddenForm.find('[data-formpage]');
1420            calderaFormPages.each(function(index) {
1421                // MAKE PAGE ELEMENT VISIBLE
1422                jQuery(this).css({
1423                    'visibility': 'visible',
1424                    'display': 'block'
1425                });
1426
1427                // REMOVE BUTTONS
1428                jQuery(this).find('input[type="button"]').closest('.form-group').remove();
1429                jQuery(this).find('button').remove();
1430
1431                // APPEND PAGE BREAK TO END OF PAGE FOR MPDF IF NOT LAST ELEMENT
1432                if(index !== (calderaFormPages.length - 1)) {
1433                    jQuery(this).append('<pagebreak />');
1434                }
1435            });
1436
1437            var nonce = cmHipaaScript.nonce;
1438
1439            if(!jQuery.isEmptyObject(validationErrors) && validationErrors.length > 0) { // ADDED .LENGTH CHECK TO OBJECT TO PREVENT POTENTIAL UNDEFINED OBJ ISSUES
1440                // VALIDATE FIELDS
1441                jQuery.each(validationErrors, function(key, val) {
1442                    var invalidFieldId = val.fieldId;
1443                    var invalidFieldType = val.fieldType;
1444                    var invalidFieldGroup = val.fieldGroup;
1445                    var invalidInput = jQuery('#' + invalidFieldId);
1446                    var invalidFieldWrapper;
1447
1448                    if(invalidFieldGroup) {
1449                        invalidFieldWrapper = jQuery('#' + invalidFieldGroup + '-wrap');
1450                    } else {
1451                        invalidFieldWrapper = jQuery('#' + invalidFieldId + '-wrap');
1452                    }
1453
1454                    // ADD ERROR CLASS TO FIELD GROUP ELEMENT & INPUT
1455                    invalidFieldWrapper.addClass('has-error');
1456                    invalidInput.attr('aria-invalid', 'true').addClass('parsley-error');
1457                    jQuery('label[for="' + invalidFieldId + '"]').addClass('parsley-error');
1458
1459                    // APPEND NOTICE
1460                    invalidFieldWrapper.append('<span class="help-block caldera_ajax_error_block filled" aria-live="polite"><span class="parsley-required">This value is required.</span></span>');
1461
1462                    // UPDATE NOTICE ELEMENT
1463                    noticeEle.append('<p>' + val.label + ' is a required field!</p>');
1464                });
1465
1466                // REMOVE HIDDEN FORM
1467                jQuery('.cm-hipaa-forms-hidden-form').remove();
1468
1469                // SET FIRST INVALID FIELD DEPENDING ON IF CHECKBOX/FIELDGROUP
1470                var scrollTopEle;
1471                if(validationErrors[0].fieldGroup) {
1472                //if(validationErrors[0].hasOwnProperty('fieldGroup')) { // CHANGED TO PREVENT POTENTIAL UNDEFINED ISSUES
1473                    scrollTopEle = '#' + validationErrors[0].fieldGroup + '-wrap';
1474                } else {
1475                    scrollTopEle = '#' + validationErrors[0].fieldId + '-wrap';
1476                }
1477
1478                // SCROLL TO FIRST INVALID FIELD
1479                jQuery('html, body').animate({
1480                    scrollTop: jQuery(scrollTopEle).offset().top
1481                }, 500, 'linear');
1482
1483                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1484                submitButton.removeClass('inactive').addClass('active');
1485            } else if(privacyAgreementEle.prop('checked') !== true) {
1486                // ENSURE THE HIPAA PRIVACY CHECKBOX IS CHECKED
1487                privacyAgreementEle.parent().css('border', '1px solid red');
1488                noticeEle.html('You must agree to the HIPAA Privacy Agreement');
1489
1490                // REMOVE HIDDEN FORM
1491                jQuery('.cm-hipaa-forms-hidden-form').remove();
1492
1493                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1494                submitButton.removeClass('inactive').addClass('active');
1495            } else if(showSignature === 'yes' && !signatureEle.find('.jSignature').hasClass('cm-valid-sig')) {
1496                // ADD RED BORDER TO SIGNATURE FIELD
1497                signatureEle.find('.jSignature').css('border', '1px solid red');
1498
1499                // UPDATE NOTICE ELEMENT
1500                noticeEle.html('You must sign the form');
1501
1502                // REMOVE HIDDEN FORM
1503                jQuery('.cm-hipaa-forms-hidden-form').remove();
1504
1505                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1506                submitButton.removeClass('inactive').addClass('active');
1507            } else {
1508                // VALIDATE ACCOUNT TO GET ENABLED ADD-ONS
1509                jQuery.ajax({
1510                    method: 'POST',
1511                    type: 'POST',
1512                    url: cmHipaaScript.ajax_url,
1513                    data: {
1514                        'action': 'cm_hipaa_validate_account',
1515                        'nononce': '1',
1516                        'nonce': cmHipaaScript.nonce
1517                    },
1518                    success: function (data) {
1519                        // REMOVE LOADING ICON
1520                        jQuery('.cm-hipaa-forms-loading').remove();
1521                        //var resultData = JSON.parse(data);
1522                        var resultData;
1523                        try {
1524                            resultData = JSON.parse(data);
1525                        } catch (e) {
1526                            console.log(data);
1527                            noticeEle.append(data);
1528                            return false;
1529                        }
1530
1531                        if (resultData.success === 'success') {
1532                            // CHECK IF FILE UPLOAD ENABLED
1533                            var validatedAddOns = resultData.add_ons;
1534                            var validatedAddOnsArray;
1535                            if(validatedAddOns) {
1536                                validatedAddOnsArray = validatedAddOns.split(',');
1537                            }
1538                            var fileUploadEnabled = 'no';
1539                            if(Array.isArray(validatedAddOnsArray) && validatedAddOnsArray.indexOf('fileupload') !== -1) {
1540                                fileUploadEnabled = 'yes';
1541                            } else if(validatedAddOns === 'fileupload') {
1542                                fileUploadEnabled = 'yes';
1543                            }
1544
1545                            // IF FILE INPUTS EXIST & FILE UPLOAD ENABLED
1546                            if (fileInputs.length > 0 && fileUploadEnabled === 'yes') {
1547                                // SHOW LOADING BAR
1548                                noticeEle.html('<div class="cm-hipaa-forms-file-upload-status">Uploading Files...</div><div class="cm-hipaa-forms-progress-wrapper"><div class="cm-hipaa-forms-progress"><div class="cm-hipaa-forms-progress-bar"><!--    <div class="cm-hipaa-forms-progress-label">10%</div>--></div></div></div>');
1549                                cmHipaaFormsProgress();
1550                                var fileInputsLength = fileInputs.length;
1551                                var iterations = 0;
1552                                var fileKeys = [];
1553                                fileInputs.each(function (index) {
1554                                    var fileInputParentId = jQuery(this).parent().parent().attr('id');
1555                                    var fileLabel = jQuery(this).parent().parent().find('label').text();
1556                                    fileLabel = fileLabel.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');
1557                                    // GET FILE
1558                                    var theFormFile = jQuery(this).get()[0].files[0];
1559                                    if (theFormFile) {
1560                                        var fileType = theFormFile.type;
1561                                        var fileName = theFormFile.name;
1562                                        // GET PRESIGNED FILE UPLOAD URL
1563                                        jQuery.ajax({
1564                                            method: 'POST',
1565                                            type: 'POST',
1566                                            url: cmHipaaScript.ajax_url,
1567                                            data: {
1568                                                'action': 'cm_hipaa_get_file_upload_url',
1569                                                'file_name': fileName,
1570                                                'nononce': '1',
1571                                                'nonce': cmHipaaScript.
1571nonce
1572                                            },
1573                                            success: function (data) {
1574                                                //var resultData = JSON.parse(data);
1575                                                var resultData;
1576                                                try {
1577                                                    resultData = JSON.parse(data);
1578                                                } catch (e) {
1579                                                    console.log(data);
1580                                                    noticeEle.append(data);
1581                                                    return false;
1582                                                }
1583
1584                                                var fileUploadUrl = resultData.file_upload_url;
1585                                                var fileKey = resultData.file_key;
1586                                                // PUSH FILE KEYS TO ARRAY
1587                                                fileKeys.push(fileKey);
1588                                                // UPLOAD THE FILE
1589                                                jQuery.ajax({
1590                                                    url: fileUploadUrl, // the presigned URL
1591                                                    type: 'PUT',
1592                                                    processData: false,
1593                                                    contentType: fileType,
1594                                                    //headers: {'x-amz-tagging': 'label=' + fileLabel},
1595                                                    data: theFormFile,
1596                                                    success: function () {
1597                                                        var hiddenFileUploadContainer = hiddenForm.find('#' + fileInputParentId);
1598                                                        var existingFiles = hiddenFileUploadContainer.find('.cm_hipaa_file_input'); // GET EXISTING FILES ALREADY UPLOADED IN HIDDEN FORM
1599                                                        hiddenFileUploadContainer.html(''); // CLEAR THE CONTAINER ELEMENT
1600                                                        // PREPEND LABEL TO FILE CONTAINER ELEMENT
1601                                                        hiddenFileUploadContainer.prepend('<label>' + fileLabel + '</label>');
1602                                                        jQuery.each(existingFiles, function () {
1603                                                            // APPEND EXISTING FILES ALREADY UPLOADED BACK INTO CONTAINER ELEMENT
1604                                                            hiddenFileUploadContainer.append(jQuery(this));
1605                                                        });
1606                                                        // APPEND NEW UPLOADED FILE TO CONTAINER ELEMENT
1607                                                        hiddenFileUploadContainer.append('<div class="cm_hipaa_file_input" data-file-key="' + fileKey + '">' + fileKey + '</div>');
1608                                                        iterations = iterations + 1;
1609                                                        if (iterations === fileInputsLength) {
1610                                                            // UPDATE FILE UPLOAD STATUS
1611                                                            jQuery('.cm-hipaa-forms-file-upload-status').html('Submitting Form...');
1612                                                            // SET TIMEOUT TO ENSURE INPUTS OVERWRITTEN
1613                                                            setTimeout(function () {
1614                                                                // SUBMIT FORM
1615                                                                jQuery.ajax({
1616                                                                    method: 'POST',
1617                                                                    type: 'POST',
1618                                                                    url: cmHipaaScript.ajax_url,
1619                                                                    data: {
1620                                                                        'action': 'cm_hipaa_submit_caldera_form',
1621                                                                        'formId': formId,
1622                                                                        'formFields': formFields,
1623                                                                        'formHtml': hiddenForm.html(),
1624                                                                        'signature': signature,
1625                                                                        'nononce': '1',
1626                                                                        'nonce': nonce,
1627                                                                        'selectedUserSlug': selectedUserSlug,
1628                                                                        'notification_option': notificationOption,
1629                                                                        //'notification_from_name': notificationFromName,
1630                                                                        //'notification_from_email': notificationFromEmail,
1631                                                                        //'notification_sendto': notificationSendTo,
1632                                                                        //'notification_subject': notificationSubject,
1633                                                                        //'notification_message': notificationMessage,
1634                                                                        'files': fileKeys.join(','),
1635                                                                        'formFound': formFound
1636                                                                    },
1637                                                                    success: function (data) {
1638                                                                        //var resultData = JSON.parse(data);
1639                                                                        var resultData;
1640                                                                        try {
1641                                                                            resultData = JSON.parse(data);
1642                                                                        } catch (e) {
1643                                                                            console.log(data);
1644                                                                            noticeEle.append(data);
1645                                                                            return false;
1646                                                                        }
1647
1648                                                                        var formError = '';
1649                                                                        if (resultData.error) {
1650                                                                            formError = resultData.error;
1651                                                                        }
1652
1653                                                                        if (resultData.success === 'success') {
1654                                                                            if (successHandler === 'message') {
1655                                                                                if(successHideForm === 'hide') {
1656                                                                                    // HIDE FORM THEN ADD SUCCESS MESSAGE
1657                                                                                    form.fadeOut().promise().done(function() {
1658                                                                                        form.after('<div class="cm-hipaa-notice cm-hidden-form-message">' + successMessage + ' ' + formError + '</div>');
1659                                                                                        jQuery('.cm
1659-hidden-form-message').fadeIn();
1660                                                                                        // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1661                                                                                        submitButton.removeClass('inactive').addClass('active');
1662                                                                                    });
1663                                                                                } else {
1664                                                                                    // DISPLAY THE SUCCESS NOTICE
1665                                                                                    noticeEle.html(successMessage + ' ' + formError);
1666                                                                                    // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1667                                                                                    submitButton.removeClass('inactive').addClass('active');
1668                                                                                }
1669                                                                            } else if (successHandler === 'redirect') {
1670                                                                                // REDIRECT TO SUCCESS PAGE
1671                                                                                window.location = successRedirect;
1672                                                                            } else if (successHandler === 'callback') {
1673                                                                                // MAKE SURE CALLBACK IS AN EXISTING FUNCTION
1674                                                                                fnExists = typeof window[successCallback] === 'function';
1675                                                                                if (fnExists) {
1676                                                                                    if (successCallbackParams) {
1677                                                                                        window[successCallback].apply(null, successCallbackParams.split(','));
1678                                                                                    } else {
1679                                                                                        window[successCallback]();
1680                                                                                    }
1681                                                                                } else {
1682                                                                                    console.log(successCallback + ' is not an existing function!');
1683                                                                                }
1684                                                                                if (successMessage) {
1685                                                                                    noticeEle.html(successMessage + ' ' + formError);
1686                                                                                } else {
1687                                                                                    // DISPLAY THE SUCCESS NOTICE
1688                                                                                    noticeEle.html('Thank y
1688ou, your form has been encrypted to protect your privacy and submitted successfully!');
1689                                                                                }
1690                                                                                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1691                                                                                submitButton.removeClass('inactive').addClass('active');
1692                                                                            } else {
1693                                                                                // DISPLAY THE SUCCESS NOTICE
1694                                                                                noticeEle.html('Thank you, your form has been encrypted to protect your privacy and submitted successfully!');
1695                                                                                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1696                                                                                submitButton.removeClass('inactive').addClass('active');
1697                                                                            }
1698                                                                            // RESET THE FORM
1699                                                                            form[0].reset();
1700                                                                            if (signature) {
1701                                                                                signatureEle.jSignature("reset");
1702                                                                            }
1703                                                                        } else {
1704                                                                            // JUST A FAIL-SAFE JUST IN CASE WE DON'T ACTUALLY GET A SUCCESS MESSAGE
1705                                                                            noticeEle.html(formError);
1706                                                                        }
1707                                                                        hiddenForm.remove();
1708                                                                        jQuery('.cm-hipaa-forms-hidden-form').remove();
1709                                                                    },
1710                                                                    error: function (errorThrown) {
1711                                                                        console.log(errorThrown);
1712                                                                        noticeEle.html(errorThrown);
1713                                                                        hiddenForm.remove();
1714                                                                        jQuery('.cm-hipaa-forms-hidden-form').remove();
1715                                                                    }
1716                                                                });
1717                                                            }, 1000);
1718                                                        }
1719                                                    }
1720                                                });
1721                                            },
1722                                            error: function (errorThrown) {
1723                                                console.log(errorThrown);
1724                                            }
1725                                        });
1726                                    } else {
1727                                        hiddenForm.find('#' + fileInputParentId).find('.file-prevent-overflow').html('<div class="cm_hipaa_file_input" data-file-key="">No File Attached</div>');
1728                                        iterations = iterations + 1;
1729                                        if (iterations === fileInputsLength) {
1730                                            // UPDATE FILE UPLOAD STATUS
1731                                            jQuery('.cm-hipaa-forms-file-upload-status').html('Submitting Form...');
1732                                            // SET TIMEOUT TO ENSURE INPUTS OVERWRITTEN
1733                                            setTimeout(function () {
1734                                                // SUBMIT FORM
1735                                                jQuery.ajax({
1736                                                    method: 'POST',
1737                                                    type: 'POST',
1738                                                    url: cmHipaaScript.ajax_url,
1739                                                    data: {
1740                                                        'action': 'cm_hipaa_submit_caldera_form',
1741                                                        'formId': formId,
1742                                                        'formFields': formFields,
1743                                                        'formHtml': hiddenForm.html(),
1744                                                        'signature': signature,
1745                                                        'nononce': '1',
1746                                                        'nonce': nonce,
1747                                                        'selectedUserSlug': selectedUserSlug,
1748                                                        'notification_option': notificationOption,
1749                                                        //'notification_from_name': notificationFromName,
1750                                                        //'notification_from_email': notificationFromEmail,
1751                                                        //'notification_sendto': notificationSendTo,
1752                                                        //'notification_subject': notificationSubject,
1753                                                        //'notification_message': notificationMessage,
1754                                                        'files': fileKeys.join(','),
1755                                                        'formFound': formFound
1756                                                    },
1757                                                    success: function (data) {
1758                                                        //var resultData = JSON.parse(data);
1759                                                        var resultData;
1760                                                        try {
1761                                                            resultData = JSON.parse(data);
1762                                                        } catch (e) {
1763                                                            console.log(data);
1764                                                            noticeEle.append(data);
1765                                                            return false;
1766                                                        }
1767
1768                                                        var formError = '';
1769                                                        if (resultData.error) {
1770                                                            formError = resultData.error;
1771                                                        }
1772                                                        if (resultData.success === 'success') {
1773                                                            if (successHandler === 'message') {
1774                                                                if(successHideForm === 'hide') {
1775                                                                    // HIDE FORM THEN ADD SUCCESS MESSAGE
1776                                                                    form.fadeOut().promise().done(function() {
1777                                                                        form.after('<div class="cm-hipaa-notice cm-hidden-form-message">' + successMessage + ' ' + formError + '</div>');
1778                                                                        jQuery('.cm
1778-hidden-form-message').fadeIn();
1779                                                                    });
1780                                                                    // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1781                                                                    submitButton.removeClass('inactive').addClass('active');
1782                                                                } else {
1783                                                                    // DISPLAY THE SUCCESS NOTICE
1784                                                                    noticeEle.html(successMessage + ' ' + formError);
1785                                                                    // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1786                                                                    submitButton.removeClass('inactive').addClass('active');
1787                                                                }
1788                                                            } else if (successHandler === 'redirect') {
1789                                                                // REDIRECT TO SUCCESS PAGE
1790                                                                window.location = successRedirect;
1791                                                            } else if (successHandler === 'callback') {
1792                                                                // MAKE SURE CALLBACK IS AN EXISTING FUNCTION
1793                                                                fnExists = typeof window[successCallback] === 'function';
1794                                                                if (fnExists) {
1795                                                                    if (successCallbackParams) {
1796                                                                        window[successCallback].apply(null, successCallbackParams.split(','));
1797                                                                    } else {
1798                                                                        window[successCallback]();
1799                                                                    }
1800                                                                } else {
1801                                                                    console.log(successCallback + ' is not an existing function!');
1802                                                                }
1803                                                                if (successMessage) {
1804                                                                    noticeEle.html(successMessage + ' ' + formError);
1805                                                                } else {
1806                                                                    // DISPLAY THE SUCCESS NOTICE
1807                                                                    noticeEle.html('Thank y
1807ou, your form has been encrypted to protect your privacy and submitted successfully!');
1808                                                                }
1809                                                                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1810                                                                submitButton.removeClass('inactive').addClass('active');
1811                                                            } else {
1812                                                                // DISPLAY THE SUCCESS NOTICE
1813                                                                noticeEle.html('Thank you, your form has been encrypted to protect your privacy and submitted successfully!');
1814                                                                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1815                                                                submitButton.removeClass('inactive').addClass('active');
1816                                                            }
1817                                                            // RESET THE FORM
1818                                                            form[0].reset();
1819                                                            if (signature) {
1820                                                                signatureEle.jSignature("reset");
1821                                                            }
1822                                                        } else {
1823                                                            // JUST A FAIL-SAFE JUST IN CASE WE DON'T ACTUALLY GET A SUCCESS MESSAGE
1824                                                            noticeEle.html(formError);
1825                                                        }
1826                                                        hiddenForm.remove();
1827                                                        jQuery('.cm-hipaa-forms-hidden-form').remove();
1828                                                        // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1829                                                        submitButton.removeClass('inactive').addClass('active');
1830                                                    },
1831                                                    error: function (errorThrown) {
1832                                                        console.log(errorThrown);
1833                                                        noticeEle.html(errorThrown);
1834                                                        hiddenForm.remove();
1835                                                        jQuery('.cm-hipaa-forms-hidden-form').remove();
1836                                                        // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1837                                                        submitButton.removeClass('inactive').addClass('active');
1838                                                    }
1839                                                });
1840                                            }, 1000);
1841                                        }
1842                                    }
1843                                });
1844                            } else {
1845                                // SHOW LOADING BAR
1846                                noticeEle.html('<div class="cm-hipaa-forms-progress-wrapper"><div class="cm-hipaa-forms-progress"><div class="cm-hipaa-forms-progress-bar"><!--    <div class="cm-hipaa-forms-progress-label">10%</div>--></div></div></div>');
1847                                cmHipaaFormsProgress();
1848                                // SUBMIT FORM
1849                                jQuery.ajax({
1850                                    method: 'POST',
1851                                    type: 'POST',
1852                                    url: cmHipaaScript.ajax_url,
1853                                    data: {
1854                                        'action': 'cm_hipaa_submit_caldera_form',
1855                                        'formId': formId,
1856                                        'formFields': formFields,
1857                                        'formHtml': hiddenForm.html(),
1858                                        'signature': signature,
1859                                        'nononce': '1',
1860                                        'nonce': nonce,
1861                                        'selectedUserSlug': selectedUserSlug,
1862                                        'notification_option': notificationOption,
1863                                        //'notification_from_name': notificationFromName,
1864                                        //'notification_from_email': notificationFromEmail,
1865                                        //'notification_sendto': notificationSendTo,
1866                                        //'notification_subject': notificationSubject,
1867                                        //'notification_message': notificationMessage
1868                                        'formFound': formFound
1869                                    },
1870                                    success: function (data) {
1871                                        //var resultData = JSON.parse(data);
1872                                        var resultData;
1873                                        try {
1874                                            resultData = JSON.parse(data);
1875                                        } catch (e) {
1876                                            console.log(data);
1877                                            noticeEle.append(data);
1878                                            return false;
1879                                        }
1880
1881                                        var formError = '';
1882                                        if (resultData.error) {
1883                                            formError = resultData.error;
1884                                        }
1885                                        if (resultData.success === 'success') {
1886                                            if (successHandler === 'message') {
1887                                                if(successHideForm === 'hide') {
1888                                                    // HIDE FORM THEN ADD SUCCESS MESSAGE
1889                                                    form.fadeOut().promise().done(function() {
1890                                                        form.after('<div class="cm-hipaa-notice cm-hidden-form-message">' + successMessage + ' ' + formError + '</div>');
1891                                                        jQuery('.cm
1891-hidden-form-message').fadeIn();
1892                                                    });
1893                                                } else {
1894                                                    // DISPLAY THE SUCCESS NOTICE
1895                                                    noticeEle.html(successMessage + ' ' + formError);
1896                                                }
1897                                            } else if (successHandler === 'redirect') {
1898                                                // REDIRECT TO SUCCESS PAGE
1899                                                window.location = successRedirect;
1900                                            } else if (successHandler === 'callback') {
1901                                                // MAKE SURE CALLBACK IS AN EXISTING FUNCTION
1902                                                fnExists = typeof window[successCallback] === 'function';
1903                                                if (fnExists) {
1904                                                    if (successCallbackParams) {
1905                                                        window[successCallback].apply(null, successCallbackParams.split(','));
1906                                                    } else {
1907                                                        window[successCallback]();
1908                                                    }
1909                                                } else {
1910                                                    console.log(successCallback + ' is not an existing function!');
1911                                                }
1912                                                if (successMessage) {
1913                                                    noticeEle.html(successMessage + ' ' + formError);
1914                                                } else {
1915                                                    // DISPLAY THE SUCCESS NOTICE
1916                                                    noticeEle.html('Thank y
1916ou, your form has been encrypted to protect your privacy and submitted successfully!');
1917                                                }
1918                                                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1919                                                submitButton.removeClass('inactive').addClass('active');
1920                                            } else {
1921                                                // DISPLAY THE SUCCESS NOTICE
1922                                                noticeEle.html('Thank you, your form has been encrypted to protect your privacy and submitted successfully!');
1923                                                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1924                                                submitButton.removeClass('inactive').addClass('active');
1925                                            }
1926                                            // RESET THE FORM
1927                                            form[0].reset();
1928                                            if (signature) {
1929                                                signatureEle.jSignature("reset");
1930                                            }
1931                                        } else {
1932                                            // JUST A FAIL-SAFE JUST IN CASE WE DON'T ACTUALLY GET A SUCCESS MESSAGE
1933                                            noticeEle.html(formError);
1934                                            // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1935                                            submitButton.removeClass('inactive').addClass('active');
1936                                        }
1937                                        hiddenForm.remove();
1938                                        jQuery('.cm-hipaa-forms-hidden-form').remove();
1939                                    },
1940                                    error: function (errorThrown) {
1941                                        console.log(errorThrown);
1942                                        noticeEle.html(errorThrown);
1943                                        hiddenForm.remove();
1944                                        jQuery('.cm-hipaa-forms-hidden-form').remove();
1945                                        // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
1946                                        submitButton.removeClass('inactive').addClass('active');
1947                                    }
1948                                });
1949                            }
1950                        } else {
1951                            console.log('Error validating Account...');
1952                        }
1953                    },
1954                    error: function (errorThrown) {
1955                        console.log(errorThrown);
1956                    }
1957                });
1958            }
1959        }
1960    });
1961
1962    /*** TRIGGER CLICK EVENT ON ENTER/RETURN KEY GRAVITY***/
1963    jQuery(document).on('keyup', 'form .cm-hipaa-forms-submit.gravity.active', function(e){
1964        if(e.keyCode===13){
1965            jQuery('body form .cm-hipaa-forms-submit.gravity.active').trigger('click');
1966        }
1967    });
1968
1969    /*** SUBMIT HIPAA ENABLED GRAVITY FORM ***/
1970    jQuery(document).on('click', 'form .cm-hipaa-forms-submit.gravity.active', function(e){
1971        var gravityVersion = cmHipaaScript.gravityVersion;
1972        var submitButton = jQuery(this);
1973        var form = jQuery(this).parents('form:first');
1974        var noticeEle = form.find('.cm-hipaa-notice');
1975        var formMainId = form.attr('id');
1976        var formId = form.attr('data-form-id');
1977        var newFormat = false;
1978        var legacyMarkup = false;
1979        if(!formId) {
1980            formId = formMainId;
1981        }
1982
1983        // REMOVE ALL TAGS BEFORE CLONING FORM
1984        var rawInputs = form.find('textarea, ' +
1985            'input[type=text], ' +
1986            'input[type=textarea], ' +
1987            'input[type=email], ' +
1988            'input[type=hidden], ' +
1989            'input[type=password], ' +
1990            'input[type=search], ' +
1991            'input[type=url], ' +
1992            'input[type=month], ' +
1993            'input[type=day], ' +
1994            'input[type=year]');
1995        jQuery.each(rawInputs, function(index) {
1996            var rawValue = jQuery(this).val();
1997            if (rawValue) {
1998                var newValue = rawValue
1999                    .replaceAll('onerror', '')
2000                    .replaceAll('img', '')
2001                    .replaceAll('onload','')
2002                    .replaceAll('<','&lt;')
2003                    .replaceAll('>', '&gt;');
2004                //var sanitizedValue = removeTags(newValue);
2005                jQuery(this).val(newValue);
2006            }
2007        });
2008
2009        // CHECK IF NEW FORMAT VERSION (2.5 OR HIGHER)
2010        if(gravityVersion >= 2.5) {
2011            // SET NEW FORMAT TO TRUE
2012            newFormat = true;
2013
2014            // CHECK IF LEGACY MARKUP FORM
2015            if(form.parent().hasClass('gform_legacy_markup_wrapper')) {
2016                legacyMarkup = true;
2017            }
2018        }
2019
2020        // REMOVE ACTIVE CLASS TO PREVENT RE-SUBMITTING
2021        submitButton.removeClass('active').addClass('inactive');
2022
2023        // REMOVE REQUIRED FIELD NOTIFICATION ERROR IF EXISTS
2024        jQuery('.validation_error').remove();
2025
2026        var gravityEnabledForms = JSON.parse(cmHipaaScript.gravityEnabledForms); // DEPRECATED
2027        formIds = [];
2028
2029        // LOOP GRAVITY FORMS AND PUSH IDS TO ARRAY - DEPRECATED
2030        for(var i = 0; i < gravityEnabledForms.length; i++){
2031            if(gravityEnabledForms[i]) {
2032                formIds.push('gform_' + gravityEnabledForms[i]);
2033            }
2034        }
2035
2036        var enabledFormsSettings;
2037        if(cmHipaaScript.enabledFormsSettings) {
2038            enabledFormsSettings = JSON.parse(cmHipaaScript.enabledFormsSettings); // NEW JSON OBJECT ARRAY
2039        }
2040
2041
2042        // CHECK IF FORM OBJECT EXISTS IN ARRAY - NEW FORMS SETTINGS JSON OBJECT ARRAY METHOD
2043        var formFound;
2044        var successHandler;
2045        var successMessage;
2046        var successHideForm;
2047        var successRedirect;
2048        var successCallback;
2049        var successCallbackParams;
2050        var selectedUserSlug = '';
2051        var showSignature;
2052        var notificationOption = '';
2053        //var notificationFromName = '';
2054        //var notificationFromEmail = '';
2055        //var notificationSendTo = '';
2056        //var notificationSubject = '';
2057        //var notificationMessage = '';
2058
2059        if(cmHipaaScript.enabledFormsSettings) {
2060            enabledFormsSettings.some(function (el) {
2061                if (el.form_builder === 'gravity' && 'gform_' + el.id === formId && el.enabled === 'yes') {
2062                    formFound = true;
2063                    successHandler = el.success_handler;
2064                    successMessage = el.success_message;
2065                    successHideForm = el.success_hide_form;
2066                    successRedirect = el.success_redirect;
2067                    successCallback = el.success_callback;
2068                    successCallbackParams = el.success_callback_params;
2069                    selectedUserSlug = el.selected_user_slug;
2070                    showSignature = el.show_signature;
2071                    notificationOption = el.notification_option;
2072                    //notificationFromName = el.notification_from_name;
2073                    //notificationFromEmail = el.notification_from_email;
2074                    //notificationSendTo = el.notification_sendto;
2075                    //notificationSubject = el.notification_subject;
2076                    //notificationMessage = el.notification_message;
2077                }
2078            });
2079        }
2080
2081        // SET SUCCESS MESSAGE IF NOT SET
2082        if(!successMessage) {
2083            successMessage = 'Thank you, your form has been encrypted to protect your privacy and submitted successfully!';
2084        }
2085
2086        // IF FORM ID IS IN ENABLED FORMS PREVENT DEFAULT SUBMIT AND SEND TO CODE MONKEYS
2087        if(jQuery.inArray(formId, formIds) !== -1 || formFound) {
2088            e.preventDefault(); //Prevent the normal submission action
2089
2090            var location;
2091            var locationEmail;
2092            var firstName;
2093            var lastName;
2094            var email;
2095            var phone;
2096            var selectedUser;
2097            var defaultBorder;
2098
2099            // CHECK IF PAGINATED
2100            let isPaginated = false;
2101            if(jQuery('.gform_page')[0]) {
2102                isPaginated = true;
2103            }
2104
2105            // GET FILE INPUTS
2106            var fileInputs = form.find('input[type=file]');
2107
2108            // CLONE THE FORM AS A HIDDEN VERSION IN ORDER TO REPLACE INPUTS WITH VALUES AND FORMAT TO SAVE
2109            form.after('<div class="cm-hipaa-forms-hidden-form" style="display:none;"></div>'); // ADD HIDDEN EMPTY DIV ELEMENT TO CLONE FORM TO
2110            form.clone().appendTo('.cm-hipaa-forms-hidden-form'); // CLONE FORM TO APPENDED HIDDEN EMPTY DIV ELEMENT
2111            var hiddenForm = jQuery('.cm-hipaa-forms-hidden-form form'); // SET HIDDEN FORM VARIABLE
2112            var hiddenFormInputs = jQuery('.cm-hipaa-forms-hidden-form form :input'); // SET INPUTS VARIABLE FROM HIDDEN FORM
2113
2114            // IF GRAVITY 2.5+ ADD GFORM_WRAPPER GRAVITY-THEME CLASS ELEMENT FOR COLUMN STYLES TO WORK
2115            if(newFormat === true && legacyMarkup === false) {
2116                hiddenForm.find('.gform_body').addClass('gform_wrapper gravity-theme');
2117            }
2118
2119            // REMOVE THE UNWANTED APPENDED ITEMS AT BOTTOM OF FORM
2120            hiddenForm.find('.cm-hipaa-forms-prepend-bottom, .cmprivacy-modal, .cmprivacy-modal-overlay').remove();
2121            hiddenForm.find('.gform_footer .gform_hidden').remove();
2122
2123            //add css class by dividing by number of header items
2124            hiddenForm.find('.gfield_list_container').each(function () {
2125                var headerItems = jQuery(this).find('.gfield_header_item');
2126                var headerCount = headerItems.length;
2127                //console.log(headerCount)
2128                if(headerItems.last().hasClass('gfield_header_item--icons')){
2129                    headerCount = headerCount - 1;
2130                }
2131
2132                var widthClass;
2133                switch (headerCount) {
2134                    case 1 :
2135                        widthClass = 'cm-hipaa-gfield--width-1-col';
2136                        break;
2137                    case 2 :
2138                        widthClass = 'cm-hipaa-gfield--width-2-col';
2139                        break;
2140                    case 3 :
2141                        widthClass = 'cm-hipaa-gfield--width-3-col';
2142                        break;
2143                    case 4 :
2144                        widthClass = 'cm-hipaa-gfield--width-4-col';
2145                        break;
2146                    case 5 :
2147                        widthClass = 'cm-hipaa-gfield--width-5-col';
2148                        break;
2149                    case 6 :
2150                        widthClass = 'cm-hipaa-gfield--width-6-col';
2151                        break;
2152                    case 7 :
2153                        widthClass = 'cm-hipaa-gfield--width-7-col';
2154                        break;
2155                    case 8 :
2156                        widthClass = 'cm-hipaa-gfield--width-8-col';
2157                        break;
2158                    case 9 :
2159                        widthClass = 'cm-hipaa-gfield--width-9-col'
2160                        break;
2161                    default:
2162                        widthClass = '';
2163                }
2164                headerItems.each(function () {
2165                    jQuery(this).addClass(widthClass);
2166                });
2167                jQuery(this).find('.gfield_list_group_item').each(function () {
2168                    jQuery(this).removeAttr('data-label');
2169                    jQuery(this).addClass(widthClass);
2170                })
2171            })
2172
2173
2174            // FIND DATE FIELDS
2175            var dateContainers = hiddenForm.find('.ginput_container_date');
2176
2177            // LOOP DATE FIELDS
2178            var dateInputId = '';
2179            dateContainers.each(function() {
2180                // SET MAIN INPUT ID
2181                dateInputId = jQuery(this).find('.datepicker').attr('id');
2182
2183                // REMOVE ICON
2184                jQuery(this).find('.ui-datepicker-trigger').remove();
2185
2186                // REMOVE HIDDEN INPUT WITH ICON PATH
2187                jQuery(this).find('.gform_hidden').remove();
2188            });
2189
2190            // FIND AND REMOVE HIDDEN DATEPICKER ICON INPUT IF EXISTS
2191            hiddenForm.find('.ginput_container_date').next('.gform_hidden').remove();
2192
2193            // REMOVE STEPS LINKS AT TOP OF FORM IF EXIST
2194            hiddenForm.find('.gf_page_steps').remove();
2195
2196            // REMOVE HIDDEN PAGE PROGRESSION INPUT IF EXISTS
2197            hiddenForm.find( "input[name^='gpps_page_progression_']" ).remove();
2198
2199            // REMOVE ADD/DELETE ROW ICONS IF EXIST
2200            hiddenForm.find('.add_list_item').remove();
2201            hiddenForm.find('.delete_list_item').remove();
2202
2203            // REMOVE MULTI-SELECT SELECT OPTIONS ELEMENT
2204            hiddenForm.find('.chosen-drop').remove();
2205
2206            // LOOP CLONED HIDDEN FORM INPUTS AND GET LABELS => VALUES & FULL HTML VERSION OF FORM
2207            var formFields = [];
2208            var validationErrors = [];
2209
2210            var inputs = jQuery('#' + formMainId + ' :input');
2211            hiddenFormInputs.each(function() {
2212                var label = form.find('label[for="' + jQuery(this).attr('id') + '"]').text().trim();
2213                var value = jQuery(this).val();
2214                var fieldId = jQuery(this).attr('id');
2215                var fieldSetId;
2216                var fieldName = jQuery(this).attr('name');
2217                var fieldType = jQuery(this).attr('type');
2218                var gravityClassEle = jQuery(this).closest('.gfield');
2219                var gravityClass = gravityClassEle.attr('class');
2220                defaultBorder = jQuery(this).css('border');
2221
2222                var locationSelect;
2223                var selectedUserSelect;
2224                var visibleSelect;
2225                var optionText = '';
2226                var checkboxParentLabel = '';
2227                var checkboxLabel;
2228                var radioValue = '';
2229                var checkboxValue = '';
2230                var fieldValue = '';
2231                var optionLabel = '';
2232                var optionValue = '';
2233                var checkRadioEmpty = false;
2234                var required = false;
2235
2236                // ENSURE FIELD ID IS SET, SEEMS TO BE AN ISSUE FOR LIST FIELDS - ADDED 9/15/25
2237                if(!fieldId || fieldId === '') {
2238                    const fieldIdFound = jQuery(this).closest('.gfield').attr('id');
2239
2240                    if(fieldIdFound) {
2241                        fieldId = fieldIdFound;
2242                    }
2243                }
2244
2245                // SET IF FIELD IS VISIBLE (TRUE/FALSE)
2246                var visibleFormField = form.find('#' + fieldId);
2247                var isVisible = visibleFormField.is(':visible');
2248                // FOLLOWING IS NEEDED FOR NEW GRAVITY ORBITAL THEME USING CONDITIONAL LOGIC ATTRIBUTE
2249                if(visibleFormField.attr('data-conditional-logic') === 'hidden') {
2250                    console.log('Original = ' + isVisible);
2251                    isVisible = false;
2252                    console.log('Conditional Logic = ' + isVisible);
2253                }
2254
2255                var isDisabled = jQuery(this).prop('disabled');
2256                var message = '';
2257
2258                // SET IF ADVANCED FIELD
2259                var isAdvancedField = false;
2260                var isAdvancedList = false;
2261                if(jQuery(this).closest('.ginput_container').hasClass('ginput_complex') || jQuery(this).closest('.ginput_container').hasClass('ginput_container_list')) {
2262                    isAdvancedField = true;
2263                    // SET FIELDSET ID IF NEW FORMAT & NOT LEGACY MARKUP
2264                    if(newFormat === true && legacyMarkup === false) {
2265                        fieldSetId = jQuery(this).closest('fieldset').attr('id');
2266
2267                        // SET FIELD ID OF EACH INPUT ELEMENT
2268                        let currentItem = jQuery(this);
2269                        jQuery('.gfield_list input').each(function(index) {
2270                            if(jQuery(this).attr('aria-label') === currentItem.attr('aria-label')) {
2271                                fieldId = fieldSetId + '_' + index;
2272                                return false;
2273                            }
2274                        });
2275
2276                        // SET IF ADVANCED FIELD IS VISIBLE
2277                        let visibleFormFieldSet = form.find('#' + fieldSetId);
2278                        isVisible = visibleFormFieldSet.is(':visible');
2279                        // FOLLOWING IS NEEDED FOR NEW GRAVITY ORBITAL THEME USING CONDITIONAL LOGIC ATTRIBUTE
2280                        if(visibleFormFieldSet.attr('data-conditional-logic') === 'hidden') {
2281                            console.log('Original Field Set = ' + isVisible);
2282                            isVisible = false;
2283                            console.log('Field Set Conditional Logic = ' + isVisible);
2284                        }
2285                    }
2286
2287                    // IF ADVANCED LIST ITEM
2288                    if(jQuery(this).closest('.ginput_container').hasClass('ginput_container_list')) {
2289                        isAdvancedList = true;
2290
2291                        // TODO: SET FIELD ID OF EACH INPUT ELEMENT ON LEGACY MARKUP (MAYBE IMPOSSIBLE)
2292                    }
2293
2294
2295                }
2296
2297                // IGNORE GRAVITY SPECIFIC HIDDEN FIELDS NOT NEEDED TO SHOW ON FORM
2298                if(fieldName !== 'is_submit_10' && fieldName !== 'gform_submit' && fieldName !== 'gform_unique_id' && fieldName !== 'state_10' && fieldName !== 'gform_target_page_number_10' && fieldName !== 'gform_source_page_number_10' && fieldName !== 'gform_field_values' && !jQuery(this).hasClass('gforms-pum') && !(jQuery(this).hasClass('gform_hidden') && jQuery(this).parent().hasClass('ginput_container_
2298consent'))) {
2299                    // TODO: ADDING THIS TO THE END OF THE ABOVE IF STATEMENT BREAKS ADVANCED ADDRESS FIELDS ON >2.5  && !jQuery(this).hasClass('gform_hidden')
2300                    // TODO: ABOVE WAS ADDED TO TRY AND REMOVE REDUNDANT LABEL/VALUE FOR "I AGREE" CHECKBOX FIELD, NEED TO TRY AND CHECK PARENT ELE FOR CLASS GINPUT_CONTAINER_CONSENT FIRST
2301
2302                    // GET REQUIRED GRAVITY FIELDS
2303                    if (gravityClassEle.hasClass('hipaa_forms_office_location')) {
2304                        // SET LOCATION VALUES
2305                        locationSelect = form.find('#' + fieldId);
2306                        location = locationSelect.find('option:selected').text();
2307                        locationEmail = locationSelect.val();
2308                    } else if (gravityClassEle.hasClass('hipaa_forms_first_name') && jQuery(this).val()) {
2309                        firstName = jQuery(this).val();
2310                    } else if (gravityClassEle.hasClass('hipaa_forms_last_name') && jQuery(this).val()) {
2311                        lastName = jQuery(this).val();
2312                    } else if (gravityClassEle.hasClass('hipaa_forms_name')) {
2313                        if (jQuery(this).parent().hasClass('name_first') && jQuery(this).val()) {
2314                            firstName = jQuery(this).val();
2315                        } else if (jQuery(this).parent().hasClass('name_last') && jQuery(this).val()) {
2316                            lastName = jQuery(this).val();
2317                        }
2318                    } else if (gravityClassEle.hasClass('hipaa_forms_email')) {
2319                        email = jQuery(this).val();
2320                    } else if (gravityClassEle.hasClass('hipaa_forms_phone')) {
2321                        phone = jQuery(this).val();
2322                    } else if (selectedUserSlug && gravityClassEle.hasClass(selectedUserSlug)) {
2323                        selectedUserSelect = form.find('#' + fieldId);
2324                        selectedUser = selectedUserSelect.val();
2325                    }
2326
2327                    if (!fieldType) {
2328                        if (jQuery(this).is('select')) {
2329                            fieldType = 'select';
2330                            visibleSelect = form.find('#' + fieldId);
2331                            optionText = visibleSelect.find('option:selected').text();
2332                            value = visibleSelect.val();
2333                            fieldValue = value;
2334                        } else if (jQuery(this).is('textarea')) {
2335                            fieldType = 'textarea';
2336                            var visibleTextArea = form.find('#' + fieldId);
2337                            value = visibleTextArea.attr('value');
2338                            fieldValue = value;
2339                            // TRY THE VALUE ATTR FIRST AND IF NO VALUE TRY NORMAL JQUERY VAL(), NOT SURE WHY ONE WORKS OVER THE OTHER SOMETIMES
2340                            if (!value || value === 'undefined') {
2341                                value = visibleTextArea.val();
2342                                fieldValue = value;
2343                            }
2344                        }
2345                    }
2346                    // IF CHECKBOX OR RADIO SET OPTIONS
2347                    var cbOptionsWrapper;
2348                    var checkOrRadio = false;
2349                    var cbOptionChecked;
2350                    if (fieldType === 'checkbox' || fieldType === 'radio') {
2351                        checkOrRadio = true;
2352                        cbOptionsWrapperId = gravityClassEle.attr('id');
2353                        cbOptionsWrapper = form.find('#' + cbOptionsWrapperId);
2354                        cbOptionChecked = form.find('#' + fieldId).prop('checked');
2355                    }
2356
2357                    // CHECK IF FIELD IS FILE UPLOAD & SET AS HIDDEN INPUT VALUE (SAFARI REQUIRED FIELD FIX)
2358                    if (fieldType === 'file') {
2359                        value = form.find('#' + fieldId).val().replace(/C:\\fakepath\\/i, '');
2360                        if (!label) {
2361                            label = 'File Upload';
2362                        }
2363                    }
2364
2365                    // CHECK IF FIELD IS A NUMBER FIELD WITH MIN AND/OR MAX
2366                    if (fieldType === 'number') {
2367                        var val = jQuery(this).val();
2368                        var num = parseFloat(val);
2369                        if (val !== '') {
2370                            if (jQuery.isNumeric(num)) {
2371                                var min = parseFloat(jQuery(this).attr('min'));
2372                                var max = parseFloat(jQuery(this).attr('max'));
2373                                if (jQuery.isNumeric(min) && jQuery.isNumeric(max)) {
2374                                    if ((Math.round(num * 100000) < Math.round(min * 100000)) || (Math.round(max * 100000) < Math.round(num * 100000))) {
2375                                        validationErrors.push({
2376                                            'fieldId': fieldId,
2377                                            'label': label,
2378                                            'name': fieldName,
2379                                            'visible': isVisible,
2380                                            'message': 'The number must be between ' + min + ' and ' + max
2381                                        });
2382                                    }
2383                                } else if (jQuery.isNumeric(max)) {
2384                                    if (Math.round(max * 100000) < Math.round(num * 100000)) {
2385                                        validationErrors.push({
2386                                            'fieldId': fieldId,
2387                                            'label': label,
2388                                            'name': fieldName,
2389                                            'visible': isVisible,
2390                                            'message': 'The number must be less than or equal to ' + max
2391                                        });
2392                                    }
2393                                } else if (jQuery.isNumeric(min)) {
2394                                    if (Math.round(num * 100000) < Math.round(min * 100000)) {
2395                                        validationErrors.push({
2396                                            'fieldId': fieldId,
2397                                            'label': label,
2398                                            'name': fieldName,
2399                                            'visible': isVisible,
2400                                            'message': 'The number must be greater than or equal to ' + min
2401                                        });
2402                                    }
2403                                }
2404                            } else {
2405                                validationErrors.push({
2406                                    'fieldId': fieldId,
2407                                    'label': label,
2408                                    'name': fieldName,
2409                                    'visible': isVisible,
2410                                    'message': 'You must enter a number'
2411                                });
2412                            }
2413                        }
2414
2415                    }
2416
2417                    // CHECK IF FIELD IS AN EMAIL AND FORMATTED CORRECTLY
2418                    if (fieldType === 'email'){
2419                        var emailVal = jQuery(this).val();
2420                        // pattern taken form https://emailregex.com/
2421                        var emailReg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
2422                        if ( emailVal !== '' ) {
2423                            if(!emailReg.test( emailVal ) ){
2424                                validationErrors.push({
2425                                    'fieldId': fieldId,
2426                                    'label': label,
2427                                    'name': fieldName,
2428                                    'visible': isVisible,
2429                                    'message': 'The email address entered is invali
2429d, please check the formatting (e.g. [email protected])',
2430                                });
2431                            }
2432                        }
2433                    }
2434
2435                    // SET IF FIELD IS REQUIRED
2436                    if (isDisabled !== true && isVisible === true && (jQuery(this).attr('required') === 'true' || jQuery(this).attr('aria-required') === 'true' || gravityClassEle.hasClass('gfield_contains_required') === 'true' && checkOrRadio !== true && !jQuery(this).parent().hasClass('address_line_2'))) {
2437                        required = true;
2438                        jQuery(this).attr('required');
2439                    } else if (isAdvancedField) {
2440                        if (isAdvancedList && jQuery(this).attr('aria-required') === 'true' && isVisible === true) {
2441                            required = true;
2442                            jQuery(this).attr('required');
2443                            fieldId = (jQuery(this).closest('fieldset.gfield_contains_required').attr('id'));
2444                            jQuery(this).attr('id', fieldId + '_' + jQuery(this).attr('aria-label'));
2445                        }
2446                    }
2447
2448                    // GET REQUIRED FIELDS THAT DO NOT HAVE A VALUE
2449                    if (required && (!value || value == "") || isDisabled !== true && isVisible === true && checkOrRadio === true && cbOptionsWrapper.hasClass('gfield_contains_required') && cbOptionChecked === false) {
2450                        // MAKE SURE OBJECT DOES NOT ALREADY EXIST, CLEARING ARRAY ABOVE DOESN'T SEEM TO WORK HERE
2451                        var errorFound;
2452                        var cbIgnore;
2453
2454                        // IF CHECKBOX SPLIT NAME AT PERIOD FOR CONSISTENCY
2455                        if (fieldType === 'checkbox' && !jQuery(this).parent().hasClass('gchoice_select_all')) {
2456                            fieldName = fieldName.split('.')[0];
2457                        }
2458
2459                        // IF CHECKBOX OR RADIO, GROUP OPTIONS & ENSURE ONE IS CHECKED
2460                        if (cbOptionsWrapper) {
2461                            var cbOptions = cbOptionsWrapper.find('input');
2462                            cbOptions.each(function () {
2463                                if (jQuery(this).prop('checked')) {
2464                                    cbIgnore = true;
2465
2466                                    return false;
2467                                }
2468                            });
2469                        }
2470
2471                        if (validationErrors.length > 0) {
2472                            validationErrors.some(function (el) {
2473                                // CHECK IF ERROR ALREADY EXISTS IN VALIDATION ERRORS ARRAY
2474                                if (el.fieldId === fieldId || el.name === fieldName) {
2475                                    errorFound = true;
2476                                }
2477                            });
2478                        }
2479
2480                        if (!errorFound && !cbIgnore && !jQuery(this).parent().hasClass('name_prefix_select') && !jQuery(this).parent().hasClass('name_suffix') && !jQuery(this).parent().hasClass('ginput_address_line_2')) {
2481                            validationErrors.push({
2482                                'fieldId': fieldId,
2483                                'label': label,
2484                                'name': fieldName,
2485                                'visible': isVisible,
2486                                'message': message
2487                            });
2488                        }
2489                    }
2490
2491                    // SET CHECKBOX OR RADIO FIELD LABEL AND INPUT LABEL
2492                    if (fieldType === 'checkbox' || fieldType === 'radio') {
2493                        if (jQuery(this).prop('checked') === true) {
2494                            checkboxLabel = jQuery(this).parent().find('label').text().trim();
2495
2496                            if (jQuery(this).hasClass('cm-hipaa-forms-privacy-agree')) {
2497                                label = 'Privacy Agreement';
2498                            } else {
2499                                label = cbOptionsWrapper.find('.gfield_label').text().trim();
2500                            }
2501
2502                            checkboxParentLabel = label;
2503                            optionLabel = checkboxLabel;
2504                            optionValue = value;
2505                        }
2506
2507                        // GET CHECKBOXES OR RADIOS WITHIN GROUP
2508                        //var advancedFields = gravityClassEle.find('input, select');
2509                        //var lastAdvancedFieldId = gravityClassEle.find('input
2509:last', 'select:last').attr('id');
2510                    }
2511
2512                    // REPLACE HIDDEN HTML VERSION INPUTS WITH VALUES
2513                    if (isAdvancedField === true) {
2514                        if (newFormat === true && legacyMarkup === false) {
2515                            /* NEW 2.5+ FORMAT STUFF HERE */
2516                            // GET INPUT AND SELECT ELEMENTS IN FIELD
2517                            var advancedFields = gravityClassEle.find('input, select');
2518                            var lastAdvancedFieldId = '';
2519                            var lastAdvancedListField = '';
2520                            if (isAdvancedList === true) {
2521                                lastAdvancedListField = advancedFields.filter(':last');
2522                            } else {
2523                                lastAdvancedFieldId = advancedFields.filter(':last').attr('id');
2524                            }
2525                            // LOOP FIELDS IF THIS IS THE LAST ADVANCED FIELD
2526                            if (fieldId === lastAdvancedFieldId || isAdvancedList === true && jQuery(this).is(lastAdvancedListField)) {
2527                                // LOOP FIELDS
2528                                var advancedFieldValues = [];
2529                                var advancedFieldHTML = [];
2530                                advancedFields.each(function (index) {
2531                                    var advancedFieldClass = jQuery(this).parent().attr('class');
2532                                    var listGroupsWrapper;
2533                                    var listRows;
2534                                    var listRow;
2535                                    var firstListRow;
2536                                    var lastListRow;
2537                                    var listRowFields;
2538                                    var listCell;
2539                                    var firstListCell;
2540                                    var lastListCell;
2541                                    var listCellLabel;
2542
2543                                    if (isAdvancedList === true) {
2544                                        listGroupsWrapper = jQuery(this).closest('.gfield_list_groups');
2545                                        listRows = listGroupsWrapper.find('.gfield_list_group');
2546                                        listRow = jQuery(this).closest('.gfield_list_group');
2547                                        firstListRow = listRows.filter(':first');
2548                                        lastListRow = listRows.filter(':last');
2549                                        listRowFields = listRow.find('input, select');
2550                                        listCell = jQuery(this).closest('.gfield_list_group_item');
2551                                        firstListCell = listRowFields.filter(':first');
2552                                        lastListCell = listRowFields.filter(':last');
2553                                        //listCellLabel = jQuery(this).parent().attr('data-label');
2554                                        listCellLabel = jQuery(this).attr('aria-label');
2555                                    }
2556
2557                                    if (jQuery(this).is('select') && isAdvancedList !== true) {
2558                                        visibleSelect = form.find('#' + jQuery(this).attr('id'));
2559                                        optionText = visibleSelect.find('option:selected').text();
2560
2561                                        advancedFieldHTML.push('<span class="' + advancedFieldClass + '">' + optionText + '</span> ');
2562                                        advancedFieldValues.push(optionText);
2563                                    } else {
2564                                        if (isAdvancedList === true && jQuery(this).is(firstListCell)) {
2565                                            // if (listRow.is(firstListRow)) {
2566                                            //     //advancedFieldHTML.push('<table class="' + listTable.attr('class') + '">' + listTableHead.html());
2567                                            // }
2568                                            advancedFieldHTML.push('<div class="' + listRow.attr('class') + '"><div class="' + listCell.attr('class') + '">');
2569                                        }
2570
2571                                        if (isAdvancedList === true) {
2572                                            var listVal;
2573                                            if (jQuery(this).is('select')) {
2574                                                var thisListField = jQuery(this);
2575                                                var thisFieldName = thisListField.attr('name');
2576                                                var thisFieldSelects = hiddenForm.find('select[name="' + thisFieldName + '"]');
2577                                                var visibleFieldSelects = form.find('select[name="' + thisFieldName + '"]');
2578                                                var listOptionValue;
2579                                                thisFieldSelects.each(function (index) {
2580                                                    if (jQuery(this).is(thisListField)) {
2581                                                        listOptionValue = visibleFieldSelects.eq(index).val();
2582                                                    }
2583                                                });
2584
2585                                                if (listCell.attr('data-label')) {
2586                                                    listCellLabel = listCell.attr('data-label');
2587                                                }
2588
2589                                                listVal = listOptionValue;
2590                                            } else {
2591                                                listVal = jQuery(this).val();
2592                                            }
2593                                            var inputAttributes = [];
2594                                            jQuery(this).each(function () {
2595                                                jQuery.each(this.attributes, function () {
2596                                                    // this.attributes is not a plain object, but an array
2597                                                    // of attribute nodes, which contain both the name and value
2598                                                    if (this.specified) {
2599                                                        inputAttributes.push(this.name + '="' + this.value + '"');
2600                                                    }
2601                                                });
2602                                            });
2603                                            jQuery(this).replaceWith('<span ' + inputAttributes.join(' ') + '>
2603' + listVal + '</span>');
2604                                            advancedFieldValues.push(listCellLabel +': ' + listVal);
2605                                        } else {
2606                                            advancedFieldHTML.push('<span class="' + advancedFieldClass + '">' + jQuery(this).val() + '</span> ');
2607                                            advancedFieldValues.push(jQuery(this).val());
2608                                        }
2609
2610                                        if (isAdvancedList === true && jQuery(this).is(lastListCell)) {
2611                                            advancedFieldHTML.push('</div>');
2612                                            if (index !== advancedFields.length - 1) {
2613                                                advancedFieldValues.push('|');
2614                                            }
2615                                        } else if (isAdvancedList === true) {
2616                                            advancedFieldValues.push(' - ');
2617                                        }
2618                                    }
2619
2620                                    if (isAdvancedList === true) {
2621                                        value = advancedFieldHTML.join('');
2622                                    } else {
2623                                        value = '<div class="' + jQuery(this).closest('div.ginput_complex').attr('class') + '" id="' + jQuery(this).closest('div.ginput_complex').attr('id') + '">' + advancedFieldHTML.join('') + '</div>';
2624                                    }
2625
2626                                    fieldValue = advancedFieldValues.join(' ');
2627                                    label = gravityClassEle.find('.gfield_label_before_complex').text();
2628                                    // ADD FIX FOR ADVANCED LIST NOT GETTING LABEL
2629                                    if (!label) {
2630                                        label = gravityClassEle.find('.label').text();
2631                                    }
2632                                    if (!label){
2633                                        label = gravityClassEle.find('.gfield_label').text();
2634                                    }
2635                                });
2636                            } else {
2637                                value = '';
2638                                fieldValue = '';
2639                                label = '';
2640                            }
2641
2642                            if (value && isAdvancedList !== true) {
2643                                gravityClassEle.html('<label class="gfield_label gfield_label_before_complex">' + label + '</label>' + value);
2644                                fieldId = gravityClassEle.attr('id');
2645                                fieldType = 'advanced';
2646                            }
2647                        } else {
2648                            /* PRE-2.5 & LEGACY FORMS ADVANCED FIELDS */
2649                            // GET INPUT AND SELECT ELEMENTS IN FIELD
2650                            var advancedFields = gravityClassEle.find('input, select');
2651                            var lastAdvancedFieldId = '';
2652                            var lastAdvancedListField = '';
2653
2654                            if (isAdvancedList === true) {
2655                                lastAdvancedListField = advancedFields.filter(':last');
2656                            } else {
2657                                lastAdvancedFieldId = advancedFields.filter(':last').attr('id');
2658                            }
2659
2660                            // LOOP FIELDS IF THIS IS THE LAST ADVANCED FIELD
2661                            if (fieldId === lastAdvancedFieldId || isAdvancedList === true && jQuery(this).is(lastAdvancedListField)) {
2662                                var listTable;
2663                                var listTableHead;
2664                                if (isAdvancedList === true) {
2665                                    listTable = jQuery(this).closest('table');
2666                                    listTableHead = listTable.find('thead');
2667                                }
2668
2669                                // LOOP FIELDS
2670                                var advancedFieldValues = [];
2671                                var advancedFieldHTML = [];
2672                                advancedFields.each(function (index) {
2673                                    var advancedFieldClass = jQuery(this).parent().attr('class');
2674                                    var listRow;
2675                                    var firstListRow;
2676                                    var lastListRow;
2677                                    var listRowFields;
2678                                    var listCell;
2679                                    var firstListCell;
2680                                    var lastListCell;
2681                                    var listCellLabel;
2682
2683                                    if (isAdvancedList === true) {
2684                                        listRow = jQuery(this).closest('tr');
2685                                        firstListRow = jQuery(this).closest('table').find('tr').filter(':first');
2686                                        lastListRow = jQuery(this).closest('table').find('tr').filter(':last');
2687                                        listRowFields = listRow.find('input, select');
2688                                        listCell = jQuery(this).closest('td');
2689                                        firstListCell = listRowFields.filter(':first');
2690                                        lastListCell = listRowFields.filter(':last');
2691                                        listCellLabel = jQuery(this).attr('aria-label');
2692                                    }
2693
2694                                    if (jQuery(this).is('select') && isAdvancedList !== true) {
2695                                        visibleSelect = form.find('#' + jQuery(this).attr('id'));
2696                                        optionText = visibleSelect.find('option:selected').text();
2697
2698                                        advancedFieldHTML.push('<span class="' + advancedFieldClass + '">
2698' + optionText + '</span> ');
2699                                        advancedFieldValues.push(optionText);
2700                                    } else {
2701                                        if (isAdvancedList === true && jQuery(this).is(firstListCell)) {
2702                                            if (listRow.is(firstListRow)) {
2703                                                //advancedFieldHTML.push('<table class="' + listTable.attr('class') + '">' + listTableHead.html());
2704                                            }
2705
2706                                            advancedFieldHTML.push('<tr class="' + listRow.attr('class') + '">');
2707                                        }
2708
2709                                        if (isAdvancedList === true) {
2710                                            var listVal;
2711                                            if (jQuery(this).is('select')) {
2712                                                var thisListField = jQuery(this);
2713                                                var thisFieldName = thisListField.attr('name');
2714                                                var thisFieldSelects = hiddenForm.find('select[name="' + thisFieldName + '"]');
2715                                                var visibleFieldSelects = form.find('select[name="' + thisFieldName + '"]');
2716                                                var listOptionValue;
2717                                                thisFieldSelects.each(function (index) {
2718                                                    if (jQuery(this).is(thisListField)) {
2719                                                        listOptionValue = visibleFieldSelects.eq(index).val();
2720                                                    }
2721                                                });
2722
2723                                                if (jQuery(this).closest('td').attr('data-label')) {
2724                                                    listCellLabel = jQuery(this).closest('td').attr('data-label');
2725                                                }
2726
2727                                                listVal = listOptionValue;
2728                                            } else {
2729                                                listVal = jQuery(this).val();
2730                                            }
2731
2732                                            advancedFieldHTML.push('<td class="' + listCell.attr('class') + '">' + listVal + '</td>');
2733                                            advancedFieldValues.push(listCellLabel + ': ' + listVal);
2734                                        } else {
2735                                            advancedFieldHTML.push('<span class="' + advancedFieldClass + '">' + jQuery(this).val() + '</span> ');
2736                                            advancedFieldValues.push(jQuery(this).val());
2737                                        }
2738
2739                                        if (isAdvancedList === true && jQuery(this).is(lastListCell)) {
2740                                            advancedFieldHTML.push('</tr>');
2741
2742                                            if (listRow.is(lastListRow)) {
2743                                                //advancedFieldHTML.push('</table>');
2744                                            }
2745
2746                                            if (index !== advancedFields.length - 1) {
2747                                                advancedFieldValues.push('|');
2748                                            }
2749                                        } else if (isAdvancedList === true) {
2750                                            advancedFieldValues.push(' - ');
2751                                        }
2752                                    }
2753
2754                                    if (isAdvancedList === true) {
2755                                        var listTableHeadHtml = '';
2756                                        if (listTableHead.html()) {
2757                                            listTableHeadHtml = listTableHead.html();
2758                                        }
2759
2760                                        value = '<table class="' + jQuery(this).closest('table').attr('class') + '"><thead>' + listTableHeadHtml + '</thead>' + advancedFieldHTML.join('') + '</table>';
2761                                    } else {
2762                                        value = '<div class="' + jQuery(this).closest('div.ginput_complex').attr('class') + '" id="' + jQuery(this).closest('div.ginput_complex').attr('id') + '">' + advancedFieldHTML.join('') + '</div>';
2763                                    }
2764
2765                                    fieldValue = advancedFieldValues.join(' ');
2766                                    label = gravityClassEle.find('.gfield_label_before_complex').text();
2767
2768                                    // ADD FIX FOR ADVANCED LIST NOT GETTING LABEL
2769                                    if (!label) {
2770                                        label = gravityClassEle.find('label').text();
2771                                    }
2772                                    if (!label){
2773                                        label = gravityClassEle.find('.gfield_label').text();
2774                                    }
2775                                });
2776                            } else {
2777                                value = '';
2778                                fieldValue = '';
2779                                label = '';
2780                            }
2781
2782                            if (value) {
2783                                gravityClassEle.html('<label class="gfield_label gfield_label_before_complex">' + label + '</label>' + value);
2784                                fieldId = gravityClassEle.attr('id');
2785                                fieldType = 'advanced';
2786                            }
2787                        }
2788                    } else if (fieldType === 'select') {
2789                        // IF VALUE IS OBJECT ARRAY LIKE FROM MULTISELECT, JOIN VALUES TO STRING
2790                        if (Array.isArray(value)) {
2791                            fieldValue = value.join(';');
2792                            value = value.join('<br />');
2793                            jQuery(this).replaceWith(value);
2794                        } else if (jQuery(this).closest('.ginput_container_date').is('[class*="gfield_date_dropdown"]')){
2795                            var fieldsetElm;
2796                            var parentElm;
2797                            if (newFormat === true && legacyMarkup === false){
2798                                fieldsetElm = jQuery(this).closest('fieldset');
2799                                fieldSetId = fieldsetElm.attr('id');
2800                                parentElm =  jQuery(this).parent();
2801                            }else{
2802                                fieldsetElm = jQuery(this).closest('li.gf
2802ield');
2803                                fieldSetId = fieldsetElm.attr('id');
2804                                parentElm = jQuery(this).parent().parent();
2805                            }
2806
2807                            var dateSelect1 = form.find('#' + fieldSetId).find('select:eq(0)').attr('id');
2808                            var dateSelect2 = form.find('#' + fieldSetId).find('select:eq(1)').attr('id');
2809                            var dateSelect3 = form.find('#' + fieldSetId).find('select:eq(2)').attr('id');
2810                            var dateValue1 = form.find('#'+dateSelect1+' option:selected').text();
2811                            var dateValue2 = form.find('#'+dateSelect2+' option:selected').text();
2812                            var dateValue3 = form.find('#'+dateSelect3+' option:selected').text();
2813
2814                            if (jQuery(this).attr('id') === dateSelect1){
2815                                if (dateValue1 && dateValue1 !== '' && dateValue1 !== 'Month' && dateValue1 !== 'Day' && dateValue1 !== 'Year') {
2816                                    value = dateValue1 + '<span class="dateseparator">\/</span>' + dateValue2 + '<span class="dateseparator">\/</span>' + dateValue3;
2817                                    parentElm.replaceWith(value);
2818                                    fieldId = fieldSetId;
2819                                    fieldValue = dateValue1 + '/' + dateValue2 + '/' + dateValue3;
2820                                    optionText = '';
2821                                    label = fieldsetElm.find('.gfield_label').text();
2822                                }else{
2823                                    label = fieldsetElm.find('.gfield_label').text();
2824                                    jQuery(this).replaceWith('');
2825                                }
2826                            }else{
2827                                label = '';
2828                                jQuery(this).replaceWith('');
2829                            }
2830                        } else {
2831                            jQuery(this).replaceWith(optionText);
2832                        }
2833                    } else if (fieldType === 'checkbox') {
2834                        // SET CHECKBOX VALUE IF DIFFERENT THAN LABEL
2835                        if (value !== checkboxLabel && !jQuery(this).parent().hasClass('ginput_container_consent')) {
2836                            checkboxValue = value;
2837                        }
2838
2839                        if (jQuery(this).prop('checked') === true) {
2840                            // SET CHECKED CHECKBOX IMAGE AND VALUE
2841                            value = '<span class="cm-hipaa-forms-checkbox-value cm-hipaa-forms-checkbox-checked" style="background: #f7f5a091;"><img src="https://www.hipaaforms.online/api-assets/checkbox.png" alt="Checked" style="height: 16px; padding-right: 5px; vertical-align: middle;" />' + checkboxValue + '</span>';
2842                            // ADD CHECKED WRAPPER CLASS TO PARENT ELEMENT
2843                            jQuery(this).parent().addClass('cm-hipaa-forms-checkbox-checked-wrapper');
2844                            if (checkboxParentLabel) {
2845                                fieldValue = 'checked';
2846                            }
2847                        } else {
2848                            // SET UNCHECKED CHECKBOX IMAGE AND VALUE
2849                            value = '<span class="cm-hipaa-forms-checkbox-value  cm-hipaa-forms-checkbox-not-checked"><img src="https://www.hipaaforms.online/api-assets/checkbox-unchecked.png" alt="Not Checked" style="height: 16px; padding-right: 5px; vertical-align: middle;" /></span>';
2850                            jQuery(this).parent().addClass('cm-hipaa-forms-checkbox-not-checked-wrapper');
2851                        }
2852
2853                        // ADD VALUE
2854                        jQuery(this).replaceWith(value);
2855                    } else if (fieldType === 'radio') {
2856                        // SET RADIO VALUE IF DIFFERENT THAN LABEL
2857                        if (value !== checkboxLabel) {
2858                            radioValue = value;
2859                        }
2860
2861                        if (jQuery(this).prop('checked') === true) {
2862                            // SET CHECKED RADIO BUTTON IMAGE AND VALUE
2863                            value = '<span class="cm-hipaa-forms-radio-value cm-hipaa-forms-radio-checked" style="background: #f7f5a091;"><img src="https://www.hipaaforms.online/api-assets/radio-checked.png" alt="Selected" style="height: 16px; padding-right: 5px; vertical-align: middle;" />' + radioValue + '</span>';
2864                            jQuery(this).parent().addClass('cm-hipaa-forms-radio-checked-wrapper');
2865
2866                            if (checkboxParentLabel) {
2867                                fieldValue = 'checked';
2868                            }
2869                        } else {
2870                            // SET UNCHECKED RADIO BUTTON IMAGE AND VALUE
2871                            value = '<span class="cm-hipaa-forms-radio-value cm-hipaa-forms-radio-not-checked"><img src="https://www.hipaaforms.online/api-assets/radio-unchecked.png" alt="Not Selected" style="height: 16px; padding-right: 5px; vertical-align: middle;" /></span>';
2872                            jQuery(this).parent().addClass('cm-hipaa-forms-radio-not-checked-wrapper');
2873                        }
2874                        jQuery(this).replaceWith(value);
2875                    } else if (fieldType === 'url') {
2876                        var rawUrl = jQuery(this).val();
2877                        var formatedUrl = '';
2878
2879                        if (rawUrl.indexOf("http://") === 0){
2880                            formatedUrl = rawUrl.replace('http://','https://');
2881                        }else if(rawUrl.indexOf("https://") === 0){
2882                            formatedUrl = rawUrl;
2883                        }else{
2884                            formatedUrl = 'https://'+rawUrl;
2885                        }
2886                        value = '<span class="cm-hipaa-forms-url-value"><a target="_blank" href="' + formatedUrl + '">' + formatedUrl + '</a></span>';
2887                        fieldValue = formatedUrl;
2888                        jQuery(this).replaceWith(value);
2889                    }else if(jQuery(this).parent().hasClass('ginput_container_time')) {
2890                        if (jQuery(this).parent().hasClass('gfield_time_hour')) {
2891                            var name = jQuery(this).attr('name');
2892                            var hours = jQuery(this).val();
2893                            var minutes = jQuery('.gfield_time_minute input[name="' + name + '"]').val();
2894                            var ampm = jQuery('.gfield_time_ampm select[name="' + name + '"]').val();
2895                            if(hours && hours !== '') {
2896                                if (parseInt(minutes) < 10) {
2897                                    minutes = '0' + minutes;
2898                                }
2899                                if (ampm) {
2900                                    fieldValue = hours + ':' + minutes + ' ' + ampm;
2901                                } else {
2902                                    fieldValue = hours + ':' + minutes;
2903                                }
2904                            }else{
2905                                fieldValue = '';
2906                            }
2907                            label = jQuery(this).closest('fieldset').find('.gfield_label').text();
2908                            fieldId = jQuery(this).closest('.gfield_time_hour').attr('id');
2909                            jQuery(this).closest('.ginput_complex').replaceWith('<div class="ginput_container ginput_container_time" id="' + fieldId + '">' + fieldValue + '</div>');
2910                        } else {
2911                            label = false;
2912                        }
2913                    }else if (jQuery(this).closest('.ginput_container_date').is('[class*="gfield_date"]')) {
2914                        var dateFieldsetElm;
2915                        var dateFieldsetId;
2916                        var parentElm;
2917                        if (newFormat === true && legacyMarkup === false) {
2918                            dateFieldsetElm = jQuery(this).closest('fieldset');
2919                            dateFieldsetId = dateFieldsetElm.attr('id');
2920                            parentElm = jQuery(this).parent();
2921                        } else {
2922                            dateFieldsetElm = jQuery(this).closest('li.gf
2922ield');
2923                            dateFieldsetId = dateFieldsetElm.attr('id');
2924                            parentElm = jQuery(this).parent().parent();
2925                        }
2926                        var dateField1 = form.find('#' + dateFieldsetId).find('.ginput_container_date:eq(0) input');
2927                        var dateField2 = form.find('#' + dateFieldsetId).find('.ginput_container_date:eq(1) input');
2928                        var dateField3 = form.find('#' + dateFieldsetId).find('.ginput_container_date:eq(2) input');
2929                        var dateFieldValue1 = jQuery(dateField1).val();
2930                        var dateFieldValue2 = jQuery(dateField2).val();
2931                        var dateFieldValue3 = jQuery(dateField3).val();
2932
2933                        if (jQuery(this).attr('id') === jQuery(dateField1).attr('id')) {
2934                            if (dateFieldValue1 && dateFieldValue1 !== '' && dateFieldValue1 !== 'Month' && dateFieldValue1 !== 'Day' && dateFieldValue1 !== 'Year') {
2935                                value = dateFieldValue1 + '<span class="dateseparator">\/</span>' + dateFieldValue2 + '<span class="dateseparator">\/</span>' + dateFieldValue3;
2936                                parentElm.replaceWith(value);
2937                                fieldValue = dateFieldValue1 + '/' + dateFieldValue2 + '/' + dateFieldValue3;
2938                                label = dateFieldsetElm.find('.gfield_label').text();
2939                                optionText = '';
2940                            }else {
2941                                label = dateFieldsetElm.find('.gfield_label').text();
2942                                jQuery(this).replaceWith('');
2943                            }
2944                        } else {
2945                            label = '';
2946                            jQuery(this).replaceWith('');
2947                        }
2948                    } else {
2949                        jQuery(this).replaceWith(value);
2950                    }
2951                    // MAKE SURE VALUES ARE TRIMMED
2952                    if(typeof value === 'string' || value instanceof String) {
2953                        value = value.trim();
2954                    }
2955                    if(typeof fieldValue === 'string' || fieldValue instanceof String) {
2956                        fieldValue = fieldValue.trim();
2957                    }
2958
2959                    if(!fieldValue && fieldType !== 'checkbox' && fieldType !== 'radio' && fieldType !== 'advanced' && fieldType !== 'url') {
2960                        fieldValue = value;
2961                    }
2962
2963                    // ADD CUSTOM CLASS TO IDENTIFY IF FIELD VALUE IS EMPTY OR NOT
2964                    if(gravityClassEle.hasClass('cm_hipaa_forms_field_not_empty') === false && (!fieldValue || fieldValue.length === 0)) {
2965                        gravityClassEle.addClass('cm_hipaa_forms_field_empty');
2966                    } else {
2967                        gravityClassEle.removeClass('cm_hipaa_forms_field_empty');
2968                        gravityClassEle.addClass('cm_hipaa_forms_field_not_empty');
2969                    }
2970
2971                    // REMOVED "&& fieldValue" TO START STORING FIELDS WITH EMPTY VALUES 4/2/21
2972                     if (label) {
2973                        // IF LABEL EXISTS PUSH TO FIELDS ARRAY
2974                        formFields.push({
2975                            'label': label,
2976                            'option_label': optionLabel,
2977                            'option_value': optionValue,
2978                            'value': fieldValue,
2979                            'field_id': fieldId,
2980                            'field_type': fieldType,
2981                            'option_text': optionText
2982                        });
2983                    }
2984                }
2985            });
2986
2987            // GET SIGNATURE SVG BASE64 DATA
2988            var signature;
2989            var signatureEle;
2990            var datapair;
2991            if(showSignature === 'yes') {
2992                signatureEle = form.find('.cm-hipaa-form-signature');
2993                datapair = signatureEle.jSignature("getData", "svgbase64");
2994                if(datapair) {
2995                    signature = "data:" + datapair[0] + "," + datapair[1];
2996
2997                    formFields.push({
2998                        'label': 'Signature',
2999                        'option_label': 'data',
3000                        'option_value': datapair[0],
3001                        'value': datapair[1],
3002                        'field_id': '',
3003                        'field_type': 'signature',
3004                        'option_text': 'ELECTRONICALLY SIGNED ' + new Date().toLocaleStr
3004ing()
3005                    });
3006                }
3007            }
3008
3009            // SET PRIVACY AGREEMENT ELEMENT
3010            var privacyAgreementEle = form.find('.cm-hipaa-forms-privacy-agree');
3011
3012            // RESET ERRORS
3013            jQuery('.gfield_error').removeClass('gfield_error');
3014            privacyAgreementEle.parent().css('border', '0');
3015            if(signatureEle) {
3016                signatureEle.find('.jSignature').css('border', '0');
3017            }
3018            noticeEle.html('');
3019            // CLEAR ERRORS
3020            form.find('.gfield_error').removeClass('gfield_error');
3021            form.find('.validation_error, .validation_message').remove();
3022
3023            // MULTI-PAGE FORM RENDERING
3024            var gravityFormPages = hiddenForm.find('.gform_page');
3025            if(gravityFormPages && gravityFormPages.length > 0) {
3026                // REMOVE PROGRESS BAR
3027                hiddenForm.find('.gf_progressbar_wrapper').remove();
3028
3029                gravityFormPages.each(function(index) {
3030                    // MAKE PAGE ELEMENT VISIBLE
3031                    jQuery(this).css({
3032                        'display': 'block'
3033                    });
3034
3035                    // REMOVE BUTTONS
3036                    jQuery(this).find('.gform_page_footer').remove();
3037
3038                    // APPEND PAGE BREAK TO END OF PAGE FOR MPDF IF NOT LAST ELEMENT
3039                    if(index !== (gravityFormPages.length - 1)) {
3040                        jQuery(this).append('<pagebreak />');
3041                    }
3042                });
3043            }
3044
3045            var nonce = cmHipaaScript.nonce;
3046            var honeyPotInput = form.find('.cm-hipaa-required-extra');
3047            var honeyPot;
3048
3049            if(honeyPotInput) {
3050                honeyPot = honeyPotInput.val();
3051            }
3052
3053            if(honeyPot) {
3054                //console.log(honeyPot);
3055                // REMOVE HIDDEN FORM
3056                jQuery('.cm-hipaa-forms-hidden-form').remove();
3057
3058                // ADD NOTICE MESSAGE
3059                noticeEle.html('<div><img src="https://media1.tenor.com/images/4945d2cd26ab7d38a6dce346a9c866e7/tenor.gif?itemid=14825791" alt="Angry Robot Upset GIF - AngryRobot Upset Furious GIFs" style="max-width: 250px;"></div><div>Oops, this appears to be an automated bot submission!  Please contact [email protected] if this is an error.</div>');
3060
3061                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3062                submitButton.removeClass('inactive').addClass('active');
3063            } else if(!jQuery.isEmptyObject(validationErrors) && validationErrors.length > 0) {
3064                // ADD ERROR MESSAGE TO TOP OF FORM
3065                form.find('.gform_body').before('<div class="validation_error">There was a problem with your submission. Errors have been highlighted below.</div>');
3066
3067                // VALIDATE FIELDS
3068                jQuery.each(validationErrors, function(key, val) {
3069                    let invalidFieldId = val.fieldId;
3070                    let invalidFieldInputNumber;
3071                    let invalidField = jQuery('#' + invalidFieldId);
3072
3073                    // IF INVALID FIELD NOT FOUND IT'S PROBABLY A FIELD SET SO SLICE IT DOWN
3074                    if(invalidField.length === 0) {
3075                        invalidFieldId = invalidFieldId.slice(0, -2);
3076
3077                        // FIND FIRST EMPTY INPUT IN FIELD SET
3078                        const invalidFieldSetInputs = jQuery('#' + invalidFieldId + ' input');
3079                        jQuery.each(invalidFieldSetInputs, function(inputKey, inputVal) {
3080                            const invalidValue = jQuery('#' + invalidFieldId + ' input').eq(inputKey).val();
3081                            if(!invalidValue || invalidValue === '') {
3082                                invalidFieldInputNumber = inputKey;
3083                                return false; // BREAK LOOP
3084                            }
3085                        });
3086
3087                        // SET INVALID FIELD
3088                        invalidField = jQuery('#' + invalidFieldId + ' input:eq(' + invalidFieldInputNumber + ')');
3089                    }
3090
3091                    var invalidFieldType = invalidField.attr('type');
3092                    var requiredMessage = val.message;
3093
3094                    if(requiredMessage.length < 1){
3095                        if(invalidField.closest('li').hasClass('hipaa_forms_office_location') && !locationEmail) {
3096                            requiredMessage = 'Location select options must have a value!  This should be an email address for the person at the specific location that should receive the form submission notice.';
3097                        } else {
3098                            requiredMessage = 'This field is required.';
3099                        }
3100                    }
3101
3102
3103                    // ADD ERROR CLASS & NOTICE MESSAGE
3104                    let invalidFieldWrapper;
3105                    if(newFormat === true && legacyMarkup === false) {
3106                        /* NEW FORMAT VALIDATION */
3107                        // SET INVALID FIELD WRAPPER
3108                        if(invalidFieldInputNumber) {
3109                            invalidFieldWrapper = invalidField.parent();
3110                        } else {
3111                            invalidFieldWrapper = invalidField.closest('.gfield');
3112                        }
3113
3114                        // CHECK IF VALIDATION ERROR ALREADY EXISTS
3115                        var existingValidationMessage = invalidFieldWrapper.find('.validation_message');
3116
3117                        if(existingValidationMessage.length === 0) {
3118                            // IF NO VALIDATION MESSAGE EXISTS ADD THE MESSAGE
3119                            invalidFieldWrapper.addClass('gfield_error').append('<div class="gfield_description validation_message">' + requiredMessage + '</div>');
3120                        }
3121                    } else {
3122                        /* PRE-2.5 & LEGACY FORMS */
3123                        if(invalidFieldType === 'checkbox' || invalidFieldType === 'radio') {
3124                            invalidFieldWrapper = invalidField.parent().parent().parent().parent();
3125                            invalidFieldWrapper.addClass('gfield_error').append('<div class="gfield_description validation_message">' + requiredMessage + '</div>');
3126                        } else {
3127                            invalidFieldWrapper = invalidField.closest('li');
3128                            invalidFieldWrapper.addClass('gfield_error').append('<div class="gfield_description validation_message">' + requiredMessage + '</div>');
3129                        }
3130                    }
3131                });
3132
3133                // REMOVE HIDDEN FORM
3134                jQuery('.cm-hipaa-forms-hidden-form').remove();
3135                // SCROLL TO FIRST INVALID FIELD
3136                if (jQuery('#' + validationErrors[0].fieldId).length){
3137                    jQuery('html, body').animate({
3138                        scrollTop: jQuery('#' + validationErrors[0].fieldId).offset().top-125
3139                    }, 500, 'linear');
3140                }else{
3141                    jQuery('html, body').animate({
3142                        scrollTop: jQuery('#' + formId).offset().top-125
3143                    }, 500, 'linear');
3144                }
3145
3146
3147                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3148                submitButton.removeClass('inactive').addClass('active');
3149            } else if(privacyAgreementEle.prop('checked') !== true) {
3150                // ADD RED BORDER TO PRIVACY FIELD
3151                privacyAgreementEle.parent().css('border', '1px solid red');
3152
3153                // UPDATE NOTICE ELEMENT
3154                noticeEle.html('You must agree to the HIPAA Privacy Agreement');
3155
3156                // REMOVE HIDDEN FORM
3157                jQuery('.cm-hipaa-forms-hidden-form').remove();
3158
3159                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3160                submitButton.removeClass('inactive').addClass('active');
3161            } else if(showSignature === 'yes' && !signatureEle.find('.jSignature').hasClass('cm-valid-sig')) {
3162                // ADD RED BORDER TO SIGNATURE FIELD
3163                signatureEle.find('.jSignature').css('border', '1px solid red');
3164
3165                // UPDATE NOTICE ELEMENT
3166                noticeEle.html('You must sign the form');
3167
3168                // REMOVE HIDDEN FORM
3169                jQuery('.cm-hipaa-forms-hidden-form').remove();
3170
3171                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3172                submitButton.removeClass('inactive').addClass('active');
3173            } else {
3174                //console.log(formId);
3175                //console.log(formFields);
3176                //console.log(hiddenForm.html());
3177                /*** VALIDATE ACCOUNT TO GET ENABLED ADD-ONS ***/
3178                jQuery.ajax({
3179                    method: 'POST',
3180                    type: 'POST',
3181                    url: cmHipaaScript.ajax_url,
3182                    data: {
3183                        'action': 'cm_hipaa_validate_account',
3184                        'nononce': '1',
3185                        'nonce': cmHipaaScript.nonce
3186                    },
3187                    success: function (data) {
3188                        // REMOVE LOADING ICON
3189                        jQuery('.cm-hipaa-forms-loading').remove();
3190                        //var resultData = JSON.parse(data);
3191                        var resultData;
3192                        try {
3193                            resultData = JSON.parse(data);
3194                        } catch (e) {
3195                            console.log(data);
3196                            noticeEle.append(data);
3197                            return false;
3198                        }
3199
3200                        if (resultData.success === 'success') {
3201                            // CHECK IF FILE UPLOAD ENABLED
3202                            var validatedAddOns = resultData.add_ons;
3203                            var validatedAddOnsArray;
3204                            if(validatedAddOns) {
3205                                validatedAddOnsArray = validatedAddOns.split(',');
3206                            }
3207                            var fileUploadEnabled = 'no';
3208                            if(Array.isArray(validatedAddOnsArray) && validatedAddOnsArray.indexOf('fileupload') !== -1) {
3209                                fileUploadEnabled = 'yes';
3210                            } else if(validatedAddOns === 'fileupload') {
3211                                fileUploadEnabled = 'yes';
3212                            }
3213
3214                            // IF FILE INPUTS EXIST & FILE UPLOAD ENABLED
3215                            if(fileInputs.length > 0 && fileUploadEnabled === 'yes') {
3216                                // SHOW LOADING BAR
3217                                noticeEle.html('<div class="cm-hipaa-forms-file-upload-status">Uploading Files...</div><div class="cm-hipaa-forms-progress-wrapper"><div class="cm-hipaa-forms-progress"><div class="cm-hipaa-forms-progress-bar"><!--    <div class="cm-hipaa-forms-progress-label">10%</div>--></div></div></div>');
3218                                cmHipaaFormsProgress();
3219
3220                                var fileInputsLength = fileInputs.length;
3221                                var iterations = 0;
3222                                var fileKeys = [];
3223
3224                                fileInputs.each(function(index) {
3225                                    var fileInputParentId = jQuery(this).parent().parent().attr('id');
3226                                    var fileLabel = jQuery(this).parent().parent().find('label').text();
3227                                    fileLabel = fileLabel.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');
3228
3229                                    // GET FILE
3230                                    var theFormFile = jQuery(this).get()[0].files[0];
3231
3232                                    if(theFormFile) {
3233                                        var fileType = theFormFile.type;
3234                                        var fileName = index+'_'+theFormFile.name;
3235
3236                                        // GET PRESIGNED FILE UPLOAD URL
3237                                        jQuery.ajax({
3238                                            method: 'POST',
3239                                            type: 'POST',
3240                                            url: cmHipaaScript.ajax_url,
3241                                            data: {
3242                                                'action': 'cm_hipaa_get_file_upload_url',
3243                                                'file_name': fileName,
3244                                                'nononce': '1',
3245                                                'nonce': cmHipaaScript.nonce
3246                                            },
3247                                            success: function (data) {
3248                                                //var resultData = JSON.parse(data);
3249                                                var resultData;
3250                                                try {
3251                                                    resultData = JSON.parse(data);
3252                                                } catch (e) {
3253                                                    console.log(data);
3254                                                    noticeEle.append(data);
3255                                                    return false;
3256                                                }
3257
3258                                                var fileUploadUrl = resultData.file_upload_url;
3259                                                var fileKey = resultData.file_key;
3260
3261                                                // PUSH FILE KEYS TO ARRAY
3262                                                fileKeys.push(fileKey);
3263
3264                                                // UPLOAD THE FILE
3265                                                jQuery.ajax({
3266                                                    url: fileUploadUrl, // the presigned URL
3267                                                    type: 'PUT',
3268                                                    processData: false,
3269                                                    contentType: fileType,
3270                                                    //headers: {'x-amz-tagging': 'label=' + fileLabel}, //breaks on long text
3271                                                    data: theFormFile,
3272                                                    success: function () {
3273                                                        var hiddenFileUploadContainer = hiddenForm.find('#' + fileInputParentId).find('.ginput_container_fileupload');
3274                                                        var existingFiles = hiddenForm.find('#' + fileInputParentId).find('.cm_hi
3274paa_file_input'); // GET EXISTING FILES ALREADY UPLOADED IN HIDDEN FORM
3275                                                        hiddenFileUploadContainer.html(''); // CLEAR THE CONTAINER ELEMENT
3276
3277                                                        jQuery.each(existingFiles, function() {
3278                                                            // APPEND EXISTING FILES ALREADY UPLOADED BACK INTO CONTAINER ELEMENT
3279                                                            hiddenFileUploadContainer.append(jQuery(this));
3280                                                        });
3281
3282                                                        // APPEND NEW UPLOADED FILE TO CONTAINER ELEMENT
3283                                                        hiddenFileUploadContainer.append('<div class="cm_hipaa_file_input" data-file-key="' + fileKey + '">' + fileKey + '</div>');
3284
3285                                                        iterations = iterations + 1;
3286                                                        if (iterations === fileInputsLength) {
3287                                                            // UPDATE FILE UPLOAD STATUS
3288                                                            jQuery('.cm-hipaa-forms-file-upload-status').html('Submitting Form...');
3289                                                            // SET TIMEOUT TO ENSURE INPUTS OVERWRITTEN
3290                                                            setTimeout(function () {
3291                                                                // SUBMIT FORM
3292                                                                jQuery.ajax({
3293                                                                    method: 'POST',
3294                                                                    type: 'POST',
3295                                                                    url: cmHipaaScript.ajax_url,
3296                                                                    data: {
3297                                                                        'action': 'cm_hipaa_submit_gravity_form',
3298                                                                        'formId': formId,
3299                                                                        'formFields': formFields,
3300                                                                        'formHtml': hiddenForm.html(),
3301                                                                        'signature': signature,
3302                                                                        'nononce': '1',
3303                                                                        'nonce': nonce,
3304                                                                        'selectedUser': selectedUser,
3305                                                                        'location': location,
3306                                                                        'locationEmail': locationEmail,
3307                                                                        'firstName': firstName,
3308                                                                        'lastName': lastName,
3309                                                                        'email': email,
3310                                                                        'phone': phone,
3311                                                                        'notification_option': notificationOption,
3312                                                                        //'notification_from_name': notificationFromName,
3313                                                                        //'notification_from_email': notificationFromEmail,
3314                                                                        //'notification_sendto': notificationSendTo,
3315                                                                        //'notification_subject': notificationSubject,
3316                                                                        //'notification_message': notificationMessage,
3317                                                                        'files': fileKeys.join(','),
3318                                                                        'formFound': formFound
3319                                                                    },
3320                                                                    success: function (data) {
3321                                                                        var resultData = JSON.parse(data);
3322                                                                        var formError = '';
3323                                                                        if(resultData.error) {
3324                                                                            formError = resultData.error;
3325                                                                        }
3326
3327                                                                        if (resultData.success === 'success') {
3328                                                                            if (successHandler === 'message') {
3329                                                                                if(successHideForm === 'hide') {
3330                                                                                    // HIDE FORM THEN ADD SUCCESS MESSAGE
3331                                                                                    form.fadeOut().promise().done(function() {
3332                                                                                        form.after('<div class="cm-hipaa-notice cm-hidden-form-message">' + successMessage + ' ' + formError + '</div>');
3333                                                                                        jQuery('.cm
3333-hidden-form-message').fadeIn();
3334                                                                                    });
3335                                                                                    // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3336                                                                                    submitButton.removeClass('inactive').addClass('active');
3337                                                                                } else {
3338                                                                                    // DISPLAY THE SUCCESS NOTICE
3339                                                                                    noticeEle.html(successMessage + ' ' + formError);
3340                                                                                    // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3341                                                                                    submitButton.removeClass('inactive').addClass('active');
3342                                                                                }
3343                                                                            } else if (successHandler === 'redirect') {
3344                                                                                // REDIRECT TO SUCCESS PAGE
3345                                                                                window.location = successRedirect;
3346                                                                            } else if (successHandler === 'callback') {
3347                                                                                // MAKE SURE CALLBACK IS AN EXISTING FUNCTION
3348                                                                                fnExists = typeof window[successCallback] === 'function';
3349                                                                                if (fnExists) {
3350                                                                                    if (successCallbackParams) {
3351                                                                                        window[successCallback].apply(null, successCallbackParams.split(','));
3352                                                                                    } else {
3353                                                                                        window[successCallback]();
3354                                                                                    }
3355                                                                                } else {
3356                                                                                    console.log(successCallback + ' is not an existing function!');
3357                                                                                }
3358                                                                                if (successMessage) {
3359                                                                                    noticeEle.html(successMessage + ' ' + formError);
3360                                                                                } else {
3361                                                                                    // DISPLAY THE SUCCESS NOTICE
3362                                                                                    noticeEle.html('Thank y
3362ou, your form has been encrypted to protect your privacy and submitted successfully!');
3363                                                                                }
3364                                                                            } else {
3365                                                                                // DISPLAY THE SUCCESS NOTICE
3366                                                                                noticeEle.html('Thank you, your form has been encrypted to protect your privacy and submitted successfully!');
3367                                                                            }
3368                                                                            // RESET THE FORM
3369                                                                            form[0].reset();
3370                                                                            if (signature) {
3371                                                                                signatureEle.jSignature("reset");
3372                                                                            }
3373
3374                                                                            // SHOW PAGE 1 OF FORM IF PAGINATED/STEPPED & NO ERROR
3375                                                                            if(isPaginated === true && !formError) {
3376                                                                                // DEACTIVATE SUBMIT BUTTON AGAIN (DIRTY BUT EASIER)
3377                                                                                submitButton.removeClass('active').addClass('inactive');
3378
3379                                                                                setTimeout(function() {
3380                                                                                    jQuery('.gform_page').fadeOut().promise().done(function() {
3381                                                                                        jQuery('.gform_page:first').fadeIn().promise().done(function() {
3382                                                                                            // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3383                                                                                            submitButton.removeClass('inactive').addClass('active');
3384                                                                                        });
3385                                                                                    });
3386                                                                                }, 5000);
3387                                                                            } else {
3388                                                                                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3389                                                                                submitButton.removeClass('inactive').addClass('active');
3390                                                                            }
3391                                                                        } else {
3392                                                                            // JUST A FAIL-SAFE JUST IN CASE WE DON'T ACTUALLY GET A SUCCESS MESSAGE
3393                                                                            noticeEle.html(formError);
3394
3395                                                                            // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3396                                                                            submitButton.removeClass('inactive').addClass('active');
3397                                                                        }
3398                                                                        hiddenForm.remove();
3399                                                                        jQuery('.cm-hipaa-forms-hidden-form').remove();
3400                                                                    },
3401                                                                    error: function (errorThrown) {
3402                                                                        console.log(errorThrown);
3403                                                                        noticeEle.html(errorThrown);
3404                                                                        hiddenForm.remove();
3405                                                                        jQuery('.cm
3405-hipaa-forms-hidden-form').remove();
3406
3407                                                                        // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3408                                                                        submitButton.removeClass('inactive').addClass('active');
3409                                                                    }
3410                                                                });
3411                                                            }, 500);
3412                                                        }
3413                                                    }
3414                                                });
3415                                            },
3416                                            error: function (errorThrown) {
3417                                                console.log(errorThrown);
3418                                            }
3419                                        });
3420                                    } else {
3421                                        hiddenForm.find('#' + fileInputParentId).find('.ginput_container_fileupload').html('<div class="cm_hipaa_file_input" data-file-key="">No File Attached</div>');
3422
3423                                        iterations = iterations + 1;
3424                                        if (iterations === fileInputsLength) {
3425                                            // UPDATE FILE UPLOAD STATUS
3426                                            jQuery('.cm-hipaa-forms-file-upload-status').html('Submitting Form...');
3427                                            // SET TIMEOUT TO ENSURE INPUTS OVERWRITTEN
3428                                            setTimeout(function () {
3429                                                // SUBMIT FORM
3430                                                jQuery.ajax({
3431                                                    method: 'POST',
3432                                                    type: 'POST',
3433                                                    url: cmHipaaScript.ajax_url,
3434                                                    data: {
3435                                                        'action': 'cm_hipaa_submit_gravity_form',
3436                                                        'formId': formId,
3437                                                        'formFields': formFields,
3438                                                        'formHtml': hiddenForm.html(),
3439                                                        'signature': signature,
3440                                                        'nononce': '1',
3441                                                        'nonce': nonce,
3442                                                        'selectedUser': selectedUser,
3443                                                        'location': location,
3444                                                        'locationEmail': locationEmail,
3445                                                        'firstName': firstName,
3446                                                        'lastName': lastName,
3447                                                        'email': email,
3448                                                        'phone': phone,
3449                                                        'notification_option': notificationOption,
3450                                                        'files': fileKeys.join(','),
3451                                                        'formFound': formFound
3452                                                    },
3453                                                    success: function (data) {
3454                                                        //var resultData = JSON.parse(data);
3455                                                        var resultData;
3456                                                        try {
3457                                                            resultData = JSON.parse(data);
3458                                                        } catch (e) {
3459                                                            console.log(data);
3460                                                            noticeEle.append(data);
3461                                                            return false;
3462                                                        }
3463
3464                                                        var formError = '';
3465                                                        if(resultData.error) {
3466                                                            formError = resultData.error;
3467                                                        }
3468
3469                                                        if (resultData.success === 'success') {
3470                                                            if (successHandler === 'message') {
3471                                                                if(successHideForm === 'hide') {
3472                                                                    // HIDE FORM THEN ADD SUCCESS MESSAGE
3473                                                                    form.fadeOut().promise().done(function() {
3474                                                                        form.after('<div class="cm-hipaa-notice cm-hidden-form-message">' + successMessage + ' ' + formError + '</div>');
3475                                                                        jQuery('.cm
3475-hidden-form-message').fadeIn();
3476                                                                    });
3477
3478                                                                    // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3479                                                                    submitButton.removeClass('inactive').addClass('active');
3480                                                                } else {
3481                                                                    // DISPLAY THE SUCCESS NOTICE
3482                                                                    noticeEle.html(successMessage + ' ' + formError);
3483                                                                    // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3484                                                                    submitButton.removeClass('inactive').addClass('active');
3485                                                                }
3486                                                            } else if (successHandler === 'redirect') {
3487                                                                // REDIRECT TO SUCCESS PAGE
3488                                                                window.location = successRedirect;
3489                                                            } else if (successHandler === 'callback') {
3490                                                                // MAKE SURE CALLBACK IS AN EXISTING FUNCTION
3491                                                                fnExists = typeof window[successCallback] === 'function';
3492                                                                if (fnExists) {
3493                                                                    if (successCallbackParams) {
3494                                                                        window[successCallback].apply(null, successCallbackParams.split(','));
3495                                                                    } else {
3496                                                                        window[successCallback]();
3497                                                                    }
3498                                                                } else {
3499                                                                    console.log(successCallback + ' is not an existing function!');
3500                                                                }
3501                                                                if (successMessage) {
3502                                                                    noticeEle.html(successMessage + ' ' + formError);
3503                                                                } else {
3504                                                                    // DISPLAY THE SUCCESS NOTICE
3505                                                                    noticeEle.html('Thank y
3505ou, your form has been encrypted to protect your privacy and submitted successfully!');
3506                                                                }
3507                                                            } else {
3508                                                                // DISPLAY THE SUCCESS NOTICE
3509                                                                noticeEle.html('Thank you, your form has been encrypted to protect your privacy and submitted successfully!');
3510                                                            }
3511                                                            // RESET THE FORM
3512                                                            form[0].reset();
3513                                                            if (signature) {
3514                                                                signatureEle.jSignature("reset");
3515                                                            }
3516                                                            console.log(isPaginated);
3517
3518                                                            // SHOW PAGE 1 OF FORM IF PAGINATED/STEPPED & NO ERROR
3519                                                            if(isPaginated === true && !formError) {
3520                                                                // DEACTIVATE SUBMIT BUTTON AGAIN (DIRTY BUT EASIER)
3521                                                                submitButton.removeClass('active').addClass('inactive');
3522
3523                                                                setTimeout(function() {
3524                                                                    jQuery('.gform_page').fadeOut().promise().done(function() {
3525                                                                        jQuery('.gform_page:first').fadeIn().promise().done(function() {
3526                                                                            // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3527                                                                            submitButton.removeClass('inactive').addClass('active');
3528                                                                        });
3529                                                                    });
3530                                                                }, 5000);
3531                                                            } else {
3532                                                                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3533                                                                submitButton.removeClass('inactive').addClass('active');
3534                                                            }
3535                                                        } else {
3536                                                            // JUST A FAIL-SAFE JUST IN CASE WE DON'T ACTUALLY GET A SUCCESS MESSAGE
3537                                                            noticeEle.html(formError);
3538                                                            // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3539                                                            submitButton.removeClass('inactive').addClass('active');
3540                                                        }
3541                                                        hiddenForm.remove();
3542                                                        jQuery('.cm-hipaa-forms-hidden-form').remove();
3543                                                    },
3544                                                    error: function (errorThrown) {
3545                                                        console.log(errorThrown);
3546                                                        noticeEle.html(errorThrown);
3547                                                        hiddenForm.remove();
3548                                                        jQuery('.cm-hipaa-forms-hidden-form').remove();
3549
3550                                                        // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3551                                                        submitButton.removeClass('inactive').addClass('active');
3552                                                    }
3553                                                });
3554                                            }, 500);
3555                                        }
3556                                    }
3557                                });
3558                            } else {
3559                                // SHOW LOADING BAR
3560                                noticeEle.html('<div class="cm-hipaa-forms-progress-wrapper"><div class="cm-hipaa-forms-progress"><div class="cm-hipaa-forms-progress-bar"><!--    <div class="cm-hipaa-forms-progress-label">10%</div>--></div></div></div>');
3561                                cmHipaaFormsProgress();
3562                                // SUBMIT FORM
3563                                jQuery.ajax({
3564                                    method: 'POST',
3565                                    type: 'POST',
3566                                    url: cmHipaaScript.ajax_url,
3567                                    data: {
3568                                        'action': 'cm_hipaa_submit_gravity_form',
3569                                        'formId': formId,
3570                                        'formFields': formFields,
3571                                        'formHtml': hiddenForm.html(),
3572                                        'signature': signature,
3573                                        'nononce': '1',
3574                                        'nonce': nonce,
3575                                        'selectedUser': selectedUser,
3576                                        'location': location,
3577                                        'locationEmail': locationEmail,
3578                                        'firstName': firstName,
3579                                        'lastName': lastName,
3580                                        'email': email,
3581                                        'phone': phone,
3582                                        'notification_option': notificationOption,
3583                                        'formFound': formFound
3584                                    },
3585                                    success: function (data) {
3586                                        // var resultData = JSON.parse(data);
3587                                        var resultData;
3588                                        try {
3589                                            resultData = JSON.parse(data);
3590                                        } catch (e) {
3591                                            console.log(data);
3592                                            noticeEle.append(data);
3593                                            return false;
3594                                        }
3595
3596                                        var formError = '';
3597                                        if (resultData.error) {
3598                                            formError = resultData.error;
3599                                        }
3600
3601                                        if (resultData.success === 'success') {
3602                                            if(successHandler === 'message') {
3603                                                if(successHideForm === 'hide') {
3604                                                    // HIDE FORM THEN ADD SUCCESS MESSAGE
3605                                                    form.fadeOut().promise().done(function() {
3606                                                        form.after('<div class="cm-hipaa-notice cm-hidden-form-message">' + successMessage + ' ' + formError + '</div>');
3607                                                        jQuery('.cm-hidden-form-message').fadeIn();
3608                                                    });
3609                                                } else {
3610                                                    // DISPLAY THE SUCCESS NOTICE
3611                                                    noticeEle.html(successMessage + ' ' + formError);
3612                                                }
3613                                            } else if(successHandler === 'redirect') {
3614                                                // REDIRECT TO SUCCESS PAGE
3615                                                window.location = successRedirect;
3616                                            } else if(successHandler === 'callback') {
3617                                                // MAKE SURE CALLBACK IS AN EXISTING FUNCTION
3618                                                fnExists = typeof window[successCallback] === 'function';
3619                                                if(fnExists) {
3620                                                    if(successCallbackParams) {
3621                                                        window[successCallback].apply(null, successCallbackParams.split(','));
3622                                                    } else {
3623                                                        window[successCallback]();
3624                                                    }
3625                                                } else {
3626                                                    console.log(successCallback + ' is not an existing function!');
3627                                                }
3628
3629                                                if(successMessage) {
3630                                                    noticeEle.html(successMessage + ' ' + formError);
3631                                                } else {
3632                                                    // DISPLAY THE SUCCESS NOTICE
3633                                                    noticeEle.html('Thank y
3633ou, your form has been encrypted to protect your privacy and submitted successfully!');
3634                                                }
3635                                            } else {
3636                                                // DISPLAY THE SUCCESS NOTICE
3637                                                noticeEle.html('Thank you, your form has been encrypted to protect your privacy and submitted successfully!');
3638                                            }
3639
3640                                            // RESET THE FORM
3641                                            form[0].reset();
3642
3643                                            if(signature) {
3644                                                signatureEle.jSignature("reset");
3645                                            }
3646
3647                                            // SHOW PAGE 1 OF FORM IF PAGINATED/STEPPED & NO ERROR
3648                                            if(isPaginated === true && !formError) {
3649                                                // DEACTIVATE SUBMIT BUTTON AGAIN (DIRTY BUT EASIER)
3650                                                submitButton.removeClass('active').addClass('inactive');
3651
3652                                                setTimeout(function() {
3653                                                    jQuery('.gform_page').fadeOut().promise().done(function() {
3654                                                        jQuery('.gform_page:first').fadeIn().promise().done(function() {
3655                                                            // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3656                                                            submitButton.removeClass('inactive').addClass('active');
3657                                                        });
3658                                                    });
3659                                                }, 5000);
3660                                            } else {
3661                                                // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3662                                                submitButton.removeClass('inactive').addClass('active');
3663                                            }
3664                                        } else {
3665                                            // JUST A FAIL-SAFE JUST IN CASE WE DON'T ACTUALLY GET A SUCCESS MESSAGE
3666                                            noticeEle.html(formError);
3667                                            // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3668                                            submitButton.removeClass('inactive').addClass('active');
3669                                        }
3670
3671                                        hiddenForm.remove();
3672                                        jQuery('.cm-hipaa-forms-hidden-form').remove();
3673
3674                                    },
3675                                    error: function (errorThrown) {
3676                                        console.log(errorThrown);
3677                                        noticeEle.html(errorThrown);
3678                                        hiddenForm.remove();
3679                                        jQuery('.cm-hipaa-forms-hidden-form').remove();
3680
3681                                        // ADD ACTIVE CLASS BACK TO SUBMIT BUTTON
3682                                        submitButton.removeClass('inactive').addClass('active');
3683                                    }
3684                                });
3685                            }
3686                        } else {
3687                            console.log('Error validating Account...');
3688                        }
3689                    },
3690                    error: function (errorThrown) {
3691                        console.log(errorThrown);
3692                    }
3693                });
3694
3695            }
3696        }
3697    });
3698
3699    /*** RESET SIGNATURE ***/
3700    jQuery(document).on('click', '.cm-hipaa-form-signature-reset', function() {
3701        jQuery(this).parent().parent().find('.cm-hipaa-form-signature').jSignature("reset");
3702    });
3703
3704    /*** PRIVACY MODAL WINDOW ***/
3705    jQuery(document).on('click', '.cmprivacy-modal .cmprivacy-close-btn', function() {
3706        jQuery('.cmprivacy-modal').toggle('closed');
3707        jQuery('.cmprivacy-modal-overlay').toggle('closed');
3708    });
3709    jQuery(document).on('click', '.cm-hipaa-privacy-statement a', function(e) {
3710        e.preventDefault();
3711        jQuery('.cmprivacy-modal').toggle('closed');
3712        jQuery('.cmprivacy-modal-overlay').toggle('closed');
3713    });
3714
3715    //console.log('CM script.js finished');
3716});
3717
3718//Custom progress bar
3719function cmHipaaFormsProgress() {
3720    var elem = jQuery(".cm-hipaa-forms-progress-bar");
3721    var width = 10;
3722    var id = setInterval(frame, 25);
3723    function frame() {
3724        if (width >= 100) {
3725            width = 10;
3726        } else {
3727            width++;
3728            elem.css('width', width + '%');
3729            jQuery(".cm-hipaa-forms-progress-label").html( width + '%');
3730        }
3731    }
3732}
3733
3734//Custom Sanatize inputs
3735function removeTags(str) {
3736    if ((str===null) || (str===''))
3737        return false;
3738    else
3739        str = str.toString();
3740
3741    // Regular expression to identify HTML tags in
3742    // the input string. Replacing the identified
3743    // HTML tag with a null string.
3744    var sanitizedString = str.replace( /(<([^>]+)>)/ig, '');
3745    var sanitizedString2 = sanitizedString.replace(/<img[^>]*?>/g,'');
3746    //console.log(sanitizedString2);
3747
3748    return sanitizedString2;
3749}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.