Spaces:
No application file
No application file
File size: 43,538 Bytes
d2897cd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 |
(function( window ) {
'use strict';
function define_library(){
//Core library
var Core = {};
//Mautic Modal
var Modal = {
closeButton: null,
modal: null,
overlay: null,
defaults: {
className: 'fade-and-drop',
closeButton: true,
content: "",
width: '600px',
height: '480px',
overlay: true
}
};
//Mautic Form
var Form = {
clickEvents: [],
clonedNodes: {},
};
//Mautic Profiler
var Profiler = {};
//global configuration
var config = {devmode: false, debug: false};
Profiler.startTime = function() {
this._startTime = performance.now();
};
Profiler.runTime = function() {
this._endTime = performance.now();
this._runtime = this._endTime - this._startTime;
if (Core.debug()) console.log('Execution time: ' + this._runtime + ' ms.');
};
Form.initialize = function(){
var re = /{mauticform([^}]+)}/g, text;
while(text = re.exec(document.body.innerHTML)) {
var replaceText = text[0];
var replaceArgs = {data: {}, params: ''};
var tmpParams = [];
text[1].trim().split(/\s+/).forEach(function (strAttribute){
var tmpAtr = strAttribute.split('=');
replaceArgs.data[tmpAtr[0]] = tmpAtr[1];
if (tmpAtr[0] != 'id')
tmpParams.push(tmpAtr[0]+'='+encodeURIComponent(tmpAtr[1]));
});
tmpParams.push('html=1');
replaceArgs.params = tmpParams.join('&');
replaceArgs.data['replace'] = replaceText;
replaceArgs.data['style'] = typeof(replaceArgs.data['style']) == 'undefined' ? 'embed' : replaceArgs.data['style'] ;
if (Core.debug()) console.log(replaceArgs.data['style']+' Mautic Form: '+replaceText);
//display form according with style
switch (replaceArgs.data['style'])
{
case 'modal':
document.body.innerHTML = document.body.innerHTML.replace(replaceText,'');
Form.clickEvents.push(replaceArgs);
break;
case 'embed':
default:
document.body.innerHTML = document.body.innerHTML.replace(replaceText,this.createIframe(replaceArgs).outerHTML);
break;
}
}
this.bindClickEvents();
Profiler.runTime();
};
Form.bindClickEvents = function() {
if (Core.debug()) console.log('binding modal click events');
for(var index in Form.clickEvents) {
var current = Form.clickEvents[index];
document.querySelector(current.data.element).setAttribute("_mautic_form_index", index);
document.querySelector(current.data.element).addEventListener("click", function(){
if (Core.debug()) console.log('add event to '+current.data.element);
Form.openModal(Form.clickEvents[this.getAttribute('_mautic_form_index')]);
});
}
};
Form.openModal = function(options){
Core.openModal({
content: Form.createIframe(options, true).outerHTML,
width: typeof(options.data['width']) != 'undefined' ? options.data['width'] : '600px',
height: typeof(options.data['height']) != 'undefined' ? options.data['height'] : '480px'
});
};
Form.getFormLink = function(options) {
return Core.getMauticBaseUrl() + 'index.php/form/' + options.data['id'] + '?' + options.params;
};
Form.createIframe = function(options, embed) {
var embed = (typeof(embed) == 'undefined') ? false : true ;
var iframe = document.createElement('iframe');
//iframe config properties
iframe.frameBorder = typeof(options.data['border']) != 'undefined' ? parseInt(options.data['border']) : '0' ;
iframe.width = (embed) ? '100%' : typeof(options.data['width']) != 'undefined' ? options.data['width'] : '600px' ;
iframe.height = (embed) ? '100%' : typeof(options.data['height']) != 'undefined' ? options.data['height'] : '400px' ;
iframe.className = (typeof(options.data['class']) == 'string') ? options.data['class'] : '' ;
iframe.src = this.getFormLink(options);
return iframe;
};
Form.customCallbackHandler = function(formId, event, data) {
if (typeof MauticFormCallback !== 'undefined' &&
typeof MauticFormCallback[formId] !== 'undefined' &&
typeof MauticFormCallback[formId][event] == 'function'
) {
if (typeof data == 'undefined') {
data = null;
}
return MauticFormCallback[formId][event](data);
}
return null;
};
Form.prepareForms = function() {
if (Core.debug()) console.log('Preparing forms found on the page');
var forms = document.getElementsByTagName('form');
for (var i = 0, n = forms.length; i < n; i++) {
var formId = forms[i].getAttribute('data-mautic-form');
if (formId !== null) {
Form.prepareMessengerForm(formId);
Form.prepareValidation(formId);
Form.prepareShowOn(formId);
Form.preparePagination(formId);
Form.populateValuesWithGetParameters();
}
}
};
Form.prepareMessengerForm = function(formId) {
var theForm = document.getElementById('mauticform_' + formId);
// Check for an onsubmit attribute
if (!theForm.getAttribute('onsubmit')) {
theForm.onsubmit = function (event) {
event.preventDefault();
Core.validateForm(formId, true);
}
}
// Check to see if the iframe exists
if (!document.getElementById('mauticiframe_' + formId)) {
// Likely an editor has stripped out the iframe so let's dynamically create it
var ifrm = document.createElement("IFRAME");
ifrm.style.display = "none";
ifrm.style.margin = 0;
ifrm.style.padding = 0;
ifrm.style.border = "none";
ifrm.style.width = 0;
ifrm.style.heigh = 0;
ifrm.setAttribute( 'id', 'mauticiframe_' + formId);
ifrm.setAttribute('name', 'mauticiframe_' + formId);
document.body.appendChild(ifrm);
theForm.target = 'mauticiframe_' + formId;
}
if (!document.getElementById('mauticform_' + formId + '_messenger')) {
var messengerInput = document.createElement('INPUT');
messengerInput.type = 'hidden';
messengerInput.setAttribute('name', 'mauticform[messenger]');
messengerInput.setAttribute('id', 'mauticform_' + formId + '_messenger');
messengerInput.value = 1;
theForm.appendChild(messengerInput);
}
};
Form.prepareValidation = function(formId) {
if (typeof window.MauticFormValidations[formId] == 'undefined') {
window.MauticFormValidations[formId] = {};
var theForm = document.getElementById('mauticform_' + formId);
// Find validations via data-attributes
var validations = theForm.querySelectorAll('[data-validate]');
[].forEach.call(validations, function (container) {
var alias = container.getAttribute('data-validate');
window.MauticFormValidations[formId][alias] = {
type: container.getAttribute('data-validation-type'),
name: alias,
multiple: container.getAttribute('data-validate-multiple'),
}
});
}
};
Form.prepareShowOn = function (formId) {
var theForm = document.getElementById('mauticform_' + formId);
var showOnDataAttribute = 'data-mautic-form-show-on';
var parents = {};
var showOn = theForm.querySelectorAll('['+showOnDataAttribute+']');
[].forEach.call(showOn, function (container) {
var condition = container.getAttribute(showOnDataAttribute);
var returnArray = condition.split(':');
var idOnChangeElem = "mauticform_" + formId+"_"+returnArray[0];
var elemToShow = container.getAttribute('id');
var elemShowOnValues = (returnArray[1]).split('|');
if(!parents[idOnChangeElem]){
parents[idOnChangeElem] = {};
}
parents[idOnChangeElem][elemToShow] = elemShowOnValues;
});
Object.keys(parents).forEach(function(key) {
var containerElement = document.getElementById(key);
Form.doShowOn(parents, key, Form.getSelectedValues(containerElement));
containerElement.onchange = function (evt) {
var selectElement = evt.target;
Form.doShowOn(parents, key, Form.getSelectedValues(evt.currentTarget));
}
});
};
Form.doShowOn = function (parents, key, selectedValues) {
Object.keys((parents[key])).forEach(function(key2) {
Form.hideField(document.getElementById(key2));
});
Object.keys((parents[key])).forEach(function(key2) {
[].forEach.call(selectedValues, function (selectedValue) {
var el = document.getElementById(key2);
if (selectedValue) {
if (el.getAttribute('data-mautic-form-expr') == 'notIn') {
if (!(parents[key][key2]).includes(selectedValue)) {
Form.showField(el, selectedValue);
}
}
else if ((parents[key][key2]).includes(selectedValue) || ((parents[key][key2]).includes('*'))) {
Form.showField(el, selectedValue);
}
}
})
});
};
Form.hideField = function(element) {
element.style.display = 'none';
element.setAttribute('data-validate-disable', 1);
}
Form.showField = function(element, selectedValue) {
element.style.display = 'block';
element.removeAttribute('data-validate-disable');
Form.filterOptGroups(element, selectedValue);
}
Form.getSelectedValues = function(containerElement) {
if (containerElement.querySelectorAll('input[type=checkbox], input[type=radio]').length) {
return Array.from(containerElement.querySelectorAll('input:checked'))
.map(option => option.value);
}else if(containerElement.querySelectorAll('select').length){
return Array.from(containerElement.querySelectorAll('option:checked'))
.map(option => option.value);
}
}
Form.filterOptGroups = function(selectElement, optGroupValue) {
// safari doesn't support hiding optgroup, so we need to restore the select before filtering
selectElement.querySelectorAll('select').forEach(function (select) {
if (typeof Form.clonedNodes[select.id] === 'undefined') {
Form.clonedNodes[select.id] = select.cloneNode(true);
}
select.innerHTML = Form.clonedNodes[select.id].innerHTML;
});
const matchingOptionGroups = selectElement.querySelectorAll('optgroup[label="' + optGroupValue + '"]');
const notMatchingOptionGroups = selectElement.querySelectorAll('optgroup:not([label="' + optGroupValue + '"])');
// hide if all option groups don't match
if (!matchingOptionGroups.length && notMatchingOptionGroups.length) {
Form.hideField(selectElement);
return;
}
[].forEach.call(notMatchingOptionGroups, function (notMatchingOptionGroup) {
notMatchingOptionGroup.remove();
});
};
Form.preparePagination = function(formId) {
var theForm = document.getElementById('mauticform_'+formId);
var pages = theForm.querySelectorAll('[data-mautic-form-page]');
var lastPageNumber = pages.length;
[].forEach.call(pages, function (page) {
var pageNumber = parseInt(page.getAttribute('data-mautic-form-page'));
var pageBreak = theForm.querySelector('[data-mautic-form-pagebreak="'+pageNumber+'"]');
if (pageNumber > 1) {
// Hide other pages by default
page.style.display = 'none';
}
if (pageBreak) {
var prevPageNumber = pageNumber - 1;
var nextPageNumber = pageNumber + 1;
var prevButton = pageBreak.querySelector('[data-mautic-form-pagebreak-button="prev"]');
var nextButton = pageBreak.querySelector('[data-mautic-form-pagebreak-button="next"]');
// Add button handlers
prevButton.onclick = function(formId, theForm, showPageNumber) {
return function() {
Form.customCallbackHandler(formId, 'onShowPreviousPage', showPageNumber);
Form.switchPage(theForm, showPageNumber);
}
} (formId, theForm, prevPageNumber);
nextButton.onclick = function(formId, theForm, hidePageNumber, showPageNumber) {
return function () {
// Validate fields first
var validations = theForm.querySelector('[data-mautic-form-page="' + hidePageNumber + '"]').querySelectorAll('[data-validate]');
var isValid = true;
[].forEach.call(validations, function (container) {
var fieldKey = container.getAttribute('data-validate');
if (!Core.getValidator(formId).validateField(theForm, fieldKey)) {
isValid = false;
}
});
if (!isValid) {
return;
}
Form.customCallbackHandler(formId, 'onShowNextPage', showPageNumber);
Form.switchPage(theForm, showPageNumber);
}
} (formId, theForm, pageNumber, nextPageNumber);
if (1 === pageNumber) {
prevButton.setAttribute('disabled', 'disabled');
pageBreak.style.display = 'block';
} else {
if (lastPageNumber === pageNumber) {
var theSubmit = theForm.querySelector('button[type="submit"]').parentNode;
nextButton.parentNode.appendChild(theSubmit);
nextButton.remove();
}
}
}
});
};
Form.switchPage = function(theForm, showPageNumber) {
var pages = theForm.querySelectorAll('[data-mautic-form-page]');
[].forEach.call(pages, function (page) {
// Hide all pages
page.style.display = 'none';
var pageNumber = parseInt(page.getAttribute('data-mautic-form-page'));
var pageBreak = theForm.querySelector('[data-mautic-form-pagebreak="'+pageNumber+'"]');
if (pageBreak) {
pageBreak.style.display = 'none';
}
});
// Show the wanted page
var thePage = theForm.querySelector('[data-mautic-form-page="' + showPageNumber + '"]');
if (thePage) {
thePage.style.display = 'block'
}
var showPageBreak = theForm.querySelector('[data-mautic-form-pagebreak="' + showPageNumber + '"]');
if (showPageBreak) {
showPageBreak.style.display = 'block';
}
};
Form.getPageForField = function (formId, fieldId, switchPage) {
if (typeof switchPage === 'undefined') {
switchPage = true;
}
var containerId = Form.getFieldContainerId(formId, fieldId);
var container = document.getElementById(containerId);
if (!container) {
return;
}
// If within a page break - go back to the page that includes this field
var pageBreak = Form.findAncestor(container, 'mauticform-page-wrapper');
if (pageBreak) {
var page = pageBreak.getAttribute('data-mautic-form-page');
if (switchPage) {
Form.switchPage(document.getElementById('mauticform_' + formId), page);
}
return page;
}
};
Form.findAncestor = function (el, cls) {
var ancestor = false;
while (true) {
var parent = el.parentElement;
if (!parent || Form.hasClass(parent, 'mauticform-innerform')) {
break;
} else if (Form.hasClass(parent, cls)) {
ancestor = parent;
break;
} else {
el = parent;
}
}
return ancestor;
};
Form.hasClass = function (el, cls) {
return (' ' + el.className + ' ').indexOf(' ' + cls + ' ') > -1;
};
Form.validator = function(formId) {
var validator = {
validateForm: function (submitForm) {
if (!submitForm) {
Form.prepareMessengerForm(formId);
}
var elId = 'mauticform_' + formId;
var theForm = document.getElementById(elId);
var formValid = Form.customCallbackHandler(formId, 'onValidate');
var firstInvalidField = false;
validator.disableSubmitButton();
// If true or false, then a callback handled it
if (formValid === null) {
Form.customCallbackHandler(formId, 'onValidateStart');
// Remove success class if applicable
var formContainer = document.getElementById('mauticform_wrapper_' + formId);
if (formContainer) {
formContainer.className = formContainer.className.replace(" mauticform-post-success", "");
}
validator.setMessage('', 'message');
validator.setMessage('', 'error');
var formValid = true;
// Find each required element
for (var fieldKey in MauticFormValidations[formId]) {
if (!validator.validateField(theForm, fieldKey)) {
formValid = false;
if (!firstInvalidField) {
firstInvalidField = fieldKey;
}
}
}
if (formValid) {
document.getElementById(elId + '_return').value = document.URL;
}
}
if (Form.customCallbackHandler(formId, 'onValidateEnd', formValid) === false) {
// A custom validation failed
formValid = false;
}
if (formValid && submitForm) {
theForm.submit();
} else {
// Activate the page with the first validation error
Form.getPageForField(formId, firstInvalidField);
// Enable submit button after response is handled
validator.enableSubmitButton();
// Focus on the first invalid field
if (MauticFormValidations[formId] && MauticFormValidations[formId][firstInvalidField]) {
const invalidField = MauticFormValidations[formId][firstInvalidField];
const invalidElement = document.getElementsByName('mauticform[' + invalidField.name + ']')[0];
if (invalidElement) {
invalidElement.focus();
}
}
}
return formValid;
},
validateField: function(theForm, fieldKey) {
var field = MauticFormValidations[formId][fieldKey];
var containerId = Form.getFieldContainerId(formId, fieldKey);
// Skip conditonal hidden field
if (document.getElementById(containerId).getAttribute('data-validate-disable')) {
return true;
}
var valid = Form.customCallbackHandler(formId, 'onValidateField', {fieldKey: fieldKey, field: field});
// If true, then a callback handled it
if (valid === null) {
var name = 'mauticform[' + field.name + ']';
if (field.multiple == 'true' || field.type == 'checkboxgrp') {
name = name + '[]';
}
var valid = true;
if (typeof theForm.elements[name] != 'undefined') {
switch (field.type) {
case 'radiogrp':
var elOptions = theForm.elements[name];
valid = validator.validateOptions(elOptions);
break;
case 'checkboxgrp':
var elOptions = theForm.elements[name];
valid = validator.validateOptions(elOptions);
break;
case 'email':
valid = validator.validateEmail(theForm.elements[name].value);
break;
default:
valid = (theForm.elements[name].value != '')
break;
}
}
if (!valid) {
validator.markError(containerId, valid);
} else {
validator.clearError(containerId);
}
}
return valid;
},
validateOptions: function(elOptions) {
if (typeof elOptions === 'undefined') {
return;
}
var optionsValid = false;
if (elOptions.length == undefined) {
elOptions = [elOptions];
}
for (var i = 0; i < elOptions.length; i++) {
if (elOptions[i].checked) {
optionsValid = true;
break;
}
}
return optionsValid;
},
validateEmail: function(email) {
var atpos = email.indexOf("@");
var dotpos = email.lastIndexOf(".");
var valid = (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) ? false : true;
return valid;
},
markError: function(containerId, valid, validationMessage) {
var elErrorSpan = false;
var callbackValidationMessage = validationMessage;
var elContainer = document.getElementById(containerId);
if (elContainer) {
elErrorSpan = elContainer.querySelector('.mauticform-errormsg');
if (typeof validationMessage == 'undefined' && elErrorSpan) {
callbackValidationMessage = elErrorSpan.innerHTML;
}
}
var callbackData = {
containerId: containerId,
valid: valid,
validationMessage: callbackValidationMessage
};
// If true, a callback handled it
if (!Form.customCallbackHandler(formId, 'onErrorMark', callbackData)) {
if (elErrorSpan) {
if (typeof validationMessage !== 'undefined') {
elErrorSpan.innerHTML = validationMessage;
}
elErrorSpan.style.display = (valid) ? 'none' : '';
elContainer.className = elContainer.className + " mauticform-has-error";
}
}
},
clearErrors: function() {
var theForm = document.getElementById('mauticform_' + formId);
var hasErrors = theForm.querySelectorAll('.mauticform-has-error');
var that = this;
[].forEach.call(hasErrors, function(container) {
that.clearError(container.id);
});
},
clearError: function(containerId) {
// If true, a callback handled it
if (!Form.customCallbackHandler(formId, 'onErrorClear', containerId)) {
var elContainer = document.getElementById(containerId);
if (elContainer) {
var elErrorSpan = elContainer.querySelector('.mauticform-errormsg');
if (elErrorSpan) {
elErrorSpan.style.display = 'none';
elContainer.className = elContainer.className.replace(" mauticform-has-error", "");
}
}
}
},
parseFormResponse: function (response) {
// Reset the iframe so that back doesn't repost for some browsers
var ifrm = document.getElementById('mauticiframe_' + formId);
if (ifrm) {
ifrm.src = 'about:blank';
}
// If true, a callback handled response parsing
if (!Form.customCallbackHandler(formId, 'onResponse', response)) {
Form.customCallbackHandler(formId, 'onResponseStart', response);
if (response.download) {
// Hit the download in the iframe
document.getElementById('mauticiframe_' + formId).src = response.download;
// Register a callback for a redirect
if (response.redirect) {
setTimeout(function () {
window.top.location = response.redirect;
}, 2000);
}
} else if (response.redirect) {
window.top.location = response.redirect;
} else if (response.validationErrors) {
var firstPage = false;
for (var field in response.validationErrors) {
var elPage = Form.getPageForField(formId, field, false);
if (elPage) {
elPage = parseInt(elPage);
if (firstPage) {
firstPage = (firstPage < elPage) ? firstPage : elPage;
} else {
firstPage = elPage;
}
}
this.markError('mauticform_' + formId + '_' + field, false, response.validationErrors[field]);
}
if (firstPage) {
Form.switchPage(document.getElementById('mauticform_' + formId), firstPage);
}
} else if (response.errorMessage) {
this.setMessage(response.errorMessage, 'error');
}
if (response.success) {
if (response.successMessage) {
this.setMessage(response.successMessage, 'message');
}
// Add a post success class
var formContainer = document.getElementById('mauticform_wrapper_' + formId);
if (formContainer) {
formContainer.className = formContainer.className + " mauticform-post-success";
}
// Reset the form
this.resetForm();
}
validator.enableSubmitButton();
Form.customCallbackHandler(formId, 'onResponseEnd', response);
}
},
setMessage: function (message, type) {
// If true, a callback handled it
if (!Form.customCallbackHandler(formId, 'onMessageSet', {message: message, type: type})) {
var container = document.getElementById('mauticform_' + formId + '_' + type);
if (container) {
container.innerHTML = message;
} else if (message) {
alert(message);
}
}
},
resetForm: function () {
this.clearErrors();
Form.switchPage(document.getElementById('mauticform_' + formId), 1);
document.getElementById('mauticform_' + formId).reset();
Form.prepareShowOn(formId); // Hides conditional fields again.
},
disableSubmitButton: function() {
// If true, then a callback handled it
if (!Form.customCallbackHandler(formId, 'onSubmitButtonDisable')) {
var submitButton = document.getElementById('mauticform_' + formId).querySelector('.mauticform-button');
if (submitButton) {
MauticLang.submitMessage = submitButton.innerHTML;
submitButton.innerHTML = MauticLang.submittingMessage;
submitButton.disabled = 'disabled';
}
}
},
enableSubmitButton: function() {
// If true, then a callback handled it
if (!Form.customCallbackHandler(formId, 'onSubmitButtonEnable')) {
var submitButton = document.getElementById('mauticform_' + formId).querySelector('.mauticform-button');
if (submitButton) {
submitButton.innerHTML = MauticLang.submitMessage;
submitButton.disabled = '';
}
}
}
};
return validator;
};
Form.registerFormMessenger = function() {
window.addEventListener('message', function(event) {
if (Core.debug()) console.log(event);
if (MauticDomain.indexOf(event.origin) !== 0) return;
try {
var response = JSON.parse(event.data);
if (response && response.formName) {
Core.getValidator(response.formName).parseFormResponse(response);
}
} catch (err) {
if (Core.debug()) console.log(err);
}
}, false);
if (Core.debug()) console.log('Messenger listener started.');
};
Form.getFieldContainerId = function(formId, fieldKey) {
var containerId = 'mauticform_' + formId + '_' + fieldKey;
if (!document.getElementById(containerId)) {
containerId = 'mauticform_' + fieldKey;
}
return containerId;
};
Form.populateValuesWithGetParameters = function() {
if (document.forms.length !== 0 && window.location.search) {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const entries = urlParams.entries();
for (const entry of entries) {
const inputs = document.getElementsByName(`mauticform[${entry[0]}]`);
inputs.forEach(function (input) {
if (input.type !== 'hidden' && input.value === '') {
input.value = entry[1].replace(/<[^>]*>?/gm, '');
}
});
}
}
};
Core.getValidator = function(formId) {
return Form.validator(formId);
};
Core.validateForm = function(formId, submit) {
if (typeof submit == 'undefined') {
submit = false;
}
return Core.getValidator(formId).validateForm(submit);
};
Core.prepareForm = function(formId) {
return Form.prepareForm(formId);
}
Modal.loadStyle = function() {
if (typeof(config.modal_css) != 'undefined' && parseInt(config.modal_css) != 'Nan' && config.modal_css == 0) {
if (Core.debug()) console.log('custom modal css style');
return;
}
var s = document.createElement('link');
s.rel = "stylesheet"
s.type = "text/css"
s.href = Core.debug() ? Core.getMauticBaseUrl() + 'app/assets/css/modal.css' : Core.getMauticBaseUrl() + 'media/css/modal.min.css';
document.head.appendChild(s);
if (Core.debug()) console.log(s);
};
Modal.open = function() {
if (arguments[0] && typeof arguments[0] === "object") {
this.options = this.extendDefaults(this.defaults, arguments[0]);
}
this.buildOut();
this.initializeEvents();
window.getComputedStyle(this.modal).height;
this.modal.className = this.modal.className + (this.modal.offsetHeight > window.innerHeight ? " mauticForm-open mauticForm-anchored" : " mauticForm-open");
this.overlay.className = this.overlay.className + " mauticForm-open";
};
Modal.buildOut = function() {
var content, contentHolder, docFrag;
content = typeof(this.options.content) == 'string' ? this.options.content : this.options.content.innerHTML;
// Create a DocumentFragment to build with
docFrag = document.createDocumentFragment();
// Create modal element
this.modal = document.createElement("div");
this.modal.className = "mauticForm-modal " + this.options.className;
this.modal.style.width = this.options.width;
this.modal.style.height = this.options.height;
// If closeButton option is true, add a close button
if (this.options.closeButton === true) {
this.closeButton = document.createElement("button");
this.closeButton.className = "mauticForm-close close-button";
this.closeButton.innerHTML = "×";
this.modal.appendChild(this.closeButton);
}
// If overlay is true, add one
if (this.options.overlay === true) {
this.overlay = document.createElement("div");
this.overlay.className = "mauticForm-overlay " + this.options.className;
docFrag.appendChild(this.overlay);
}
// Create content area and append to modal
contentHolder = document.createElement("div");
contentHolder.className = "mauticForm-content";
contentHolder.innerHTML = content;
this.modal.appendChild(contentHolder);
// Append modal to DocumentFragment
docFrag.appendChild(this.modal);
// Append DocumentFragment to body
document.body.appendChild(docFrag);
};
Modal.extendDefaults = function(source, properties) {
for (var property in properties) {
if (properties.hasOwnProperty(property)) source[property] = properties[property];
}
return source;
};
Modal.initializeEvents = function() {
if (this.closeButton) this.closeButton.addEventListener('click', this.close.bind(this));
if (this.overlay) this.overlay.addEventListener('click', this.close.bind(this));
};
Modal.transitionSelect = function() {
var el = document.createElement("div");
return (el.style.WebkitTransition) ? "webkitTransitionEnd" : (el.style.WebkitTransition) ? "webkitTransitionEnd" : "oTransitionEnd" ;
};
Modal.close = function() {
var _ = this;
this.modal.className = this.modal.className.replace(" mauticForm-open", "");
this.overlay.className = this.overlay.className.replace(" mauticForm-open", "");
this.modal.addEventListener(this.transitionSelect(), function() {
_.modal.parentNode.removeChild(_.modal);
});
this.overlay.addEventListener(this.transitionSelect(), function() {
if(_.overlay.parentNode) _.overlay.parentNode.removeChild(_.overlay);
});
//remove modal and overlay
this.overlay.parentNode.removeChild(this.overlay);
this.modal.parentNode.removeChild(this.modal);
};
Core.parseToObject = function(params) {
return params.split('&')
.reduce((params, param) => {
const item = param.split('=');
const key = decodeURIComponent(item[0] || '');
const value = decodeURIComponent(item[1] || '');
if (key) {
params[key] = value;
}
return params;
}, {});
};
Core.setConfig = function (options) {
config = options;
};
Core.getConfig = function() {
return config;
};
Core.debug = function() {
return (typeof(config.debug) != 'undefined' && parseInt(config.debug) != 'Nan' && config.debug == 1) ? true : false ;
};
Core.devMode = function() {
return (typeof(config.devmode) != 'undefined' && parseInt(config.devmode) != 'Nan' && config.devmode == 1) ? true : false ;
};
Core.setMauticBaseUrl = function(base_url) {
config.mautic_base_url = base_url.split('/').slice(0,-3).join('/')+'/';
};
Core.getMauticBaseUrl = function() {
return config.mautic_base_url;
};
Core.initialize = function(base_url) {
Profiler.startTime();
if (Core.debug()) console.log('SDK initialized');
if (typeof(config.mautic_base_url) == 'undefined') Core.setMauticBaseUrl(base_url);
if (Core.debug()) console.log('Automatic setup mautic_base_url as: ' + config.mautic_base_url);
Modal.loadStyle();
document.addEventListener("DOMContentLoaded", function(e){
if (Core.debug()) console.log('DOMContentLoaded dispatched as DOM is ready');
Form.initialize();
});
};
Core.openModal = function(options){
Modal.open(options);
};
Core.onLoad = function() {
if (Core.debug()) console.log('Object onLoad called');
Core.setupForms();
};
Core.setupForms = function() {
if (Core.debug()) console.log('DOM ready state is ' + document.readyState);
// Landing pages and form "previews" cannot process till the DOM is fully loaded
if ("complete" !== document.readyState) {
setTimeout(function () { Core.setupForms(); }, 1);
return;
}
Form.prepareForms();
Form.registerFormMessenger();
};
return Core;
}
if (typeof(MauticSDK) === 'undefined') {
window.MauticSDK = define_library();
var sjs = document.getElementsByTagName('script'), tjs = sjs.length;
for (var i = 0; i < sjs.length; i++) {
if (!sjs[i].hasAttribute('src') || sjs[i].getAttribute("src").indexOf('mautic-form-src.js') == -1) continue;
var sParts = sjs[i].getAttribute("src").split("?");
if (sParts[1]) MauticSDK.setConfig(MauticSDK.parseToObject(sParts[1]));
MauticSDK.initialize(sParts[0]);
break;
}
}
if (typeof window.MauticFormValidations == 'undefined') {
window.MauticFormValidations = {};
}
})( window );
|