var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var CompositionBehaviorLoader = (function () {
    function CompositionBehaviorLoader() {
        this.popupBehaviorLoader = new PopupBehaviorLoader();
        this.slideupBehaviorLoader = new SlideupBehaviorLoader();
    }
    CompositionBehaviorLoader.prototype.init = function (config, form) {
        var _this = this;
        window.setTimeout(function () {
            if (document.readyState !== 'loading') {
                return _this.load(config, form);
            }
            else {
                document.addEventListener('DOMContentLoaded', function () { return __awaiter(_this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4, this.load(config, form)];
                            case 1:
                                _a.sent();
                                return [2];
                        }
                    });
                }); });
            }
        }, 1);
    };
    CompositionBehaviorLoader.prototype.load = function (config, form) {
        return __awaiter(this, void 0, void 0, function () {
            var composition;
            return __generator(this, function (_a) {
                composition = config.composition;
                if (composition === 'default') {
                    return [2, new Promise(function (resolve) {
                            resolve();
                        })];
                }
                if (composition === 'popup') {
                    return [2, this.popupBehaviorLoader.load(config, form)];
                }
                if (composition === 'slide-up') {
                    return [2, this.slideupBehaviorLoader.load(config)];
                }
                return [2, new Promise(function (resolve) {
                        console.log('unknown composition: ' + composition);
                        resolve();
                    })];
            });
        });
    };
    return CompositionBehaviorLoader;
}());
var CompositionCssLoader = (function () {
    function CompositionCssLoader() {
    }
    CompositionCssLoader.loadCompositionCss = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            var cssId, link, result;
            return __generator(this, function (_a) {
                cssId = 'se-composition-' + config.composition + '-css';
                if (document.getElementById(cssId)) {
                    return [2, new Promise(function (resolve) {
                            resolve();
                        })];
                }
                link = document.createElement('link');
                link.id = cssId;
                link.rel = 'stylesheet';
                link.type = 'text/css';
                link.href = config.rootUrl + '/web-forms-v2/composition-' + config.composition + '.css';
                link.media = 'all';
                result = new Promise(function (resolve) {
                    link.onload = function () {
                        resolve();
                    };
                });
                document.getElementsByTagName('head')[0].appendChild(link);
                return [2, result];
            });
        });
    };
    return CompositionCssLoader;
}());
var PopupBehaviorLoader = (function () {
    function PopupBehaviorLoader() {
    }
    PopupBehaviorLoader.prototype.load = function (config, form) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (PopupBehaviorLoader.isBlocked(config)) {
                            return [2, new Promise(function (resolve) {
                                    resolve();
                                })];
                        }
                        return [4, CompositionCssLoader.loadCompositionCss(config)];
                    case 1:
                        _a.sent();
                        this.setupToggler(config);
                        if (config.expiration.method === 'submitCookie') {
                            form.addEventListener('submit', function () {
                                PopupBehaviorLoader.setBlockingCookie(config, -1);
                                PopupBehaviorLoader.setBlockingCookie(config, 365);
                                return false;
                            });
                        }
                        return [2, new Promise(function (resolve) {
                                resolve();
                            })];
                }
            });
        });
    };
    PopupBehaviorLoader.prototype.setupToggler = function (config) {
        var containerDivId = '#se-webform-popup-'
            + config.formGuid;
        var modal = document.querySelector(containerDivId + " .se-webform-v2-modal");
        var closeButton = document.querySelector(containerDivId + " .se-webform-v2-close-button");
        var toggler = function () {
            modal.style.display = 'block';
            var displayed = modal.classList.toggle("se-webform-v2-show-modal");
            if (!displayed) {
                return;
            }
            if (config.expiration.method === 'cookie') {
                PopupBehaviorLoader.setBlockingCookie(config, config.expiration.value);
            }
            else {
                PopupBehaviorLoader.setBlockingCookie(config, null);
            }
        };
        var windowModalClose = function (event) {
            if (event.target === modal) {
                toggler();
            }
        };
        if (config.trigger.name === 'none') {
            toggler();
        }
        else if (config.trigger.name === 'delay') {
            window.setTimeout(toggler, Number(config.trigger.value).valueOf() * 1000);
        }
        else if (config.trigger.name === 'scroll') {
            document.addEventListener('scroll', function () {
                if (modal.hasAttribute('data-toggled')) {
                    return;
                }
                if (ScrollDisplayDecider.shouldBeDisplayed(config)) {
                    modal.setAttribute('data-toggled', '1');
                    toggler();
                }
            });
        }
        closeButton.addEventListener("click", toggler);
        window.addEventListener("click", windowModalClose);
    };
    PopupBehaviorLoader.isMobile = function () {
        if (navigator.userAgent.match(/Android/i)
            || navigator.userAgent.match(/webOS/i)
            || navigator.userAgent.match(/iPhone/i)
            || navigator.userAgent.match(/iPad/i)
            || navigator.userAgent.match(/iPod/i)
            || navigator.userAgent.match(/BlackBerry/i)
            || navigator.userAgent.match(/Windows Phone/i)) {
            return true;
        }
        return false;
    };
    PopupBehaviorLoader.hidePopupOnMobile = function (config) {
        return (PopupBehaviorLoader.isMobile() && config.hidePopupOnMobile);
    };
    PopupBehaviorLoader.isBlocked = function (config) {
        if (PopupBehaviorLoader.isPreview(config)) {
            return false;
        }
        if (PopupBehaviorLoader.hidePopupOnMobile(config)) {
            return true;
        }
        var webFormBlockerCookieName = PopupBehaviorLoader.getBlockingCookieName(config);
        var result = new RegExp('(?:^|; )'
            + encodeURIComponent(webFormBlockerCookieName)
            + '=([^;]*)').exec(document.cookie);
        var cookieValue = result ? result[1] : null;
        return cookieValue === 'set';
    };
    PopupBehaviorLoader.isPreview = function (config) {
        return window.location.href.startsWith(config.rootUrl);
    };
    PopupBehaviorLoader.getBlockingCookieName = function (config) {
        return 'se-webform-session-' + config.formGuid;
    };
    PopupBehaviorLoader.setBlockingCookie = function (config, days) {
        if (PopupBehaviorLoader.isPreview(config)) {
            return;
        }
        var expires = '';
        if (days !== null) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie
            = PopupBehaviorLoader.getBlockingCookieName(config)
                + "="
                + 'set'
                + expires
                + '; path=/';
    };
    return PopupBehaviorLoader;
}());
var ScrollDisplayDecider = (function () {
    function ScrollDisplayDecider() {
    }
    ScrollDisplayDecider.shouldBeDisplayed = function (config) {
        var isAbsolute = config.trigger.value.indexOf('%') === -1;
        if (isAbsolute) {
            var scrolledTop = document.documentElement.scrollTop || document.body.scrollTop;
            return scrolledTop >= Number(config.trigger.value).valueOf();
        }
        else {
            var h = document.documentElement;
            var b = document.body;
            var percent = (h.scrollTop || b.scrollTop)
                / ((h.scrollHeight || b.scrollHeight) - h.clientHeight)
                * 100;
            return percent >= Number(config.trigger.value).valueOf();
        }
    };
    return ScrollDisplayDecider;
}());
var SlideupBehaviorLoader = (function () {
    function SlideupBehaviorLoader() {
    }
    SlideupBehaviorLoader.prototype.load = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, CompositionCssLoader.loadCompositionCss(config)];
                    case 1:
                        _a.sent();
                        this.setupToggler(config);
                        return [2, new Promise(function (resolve) {
                                resolve();
                            })];
                }
            });
        });
    };
    SlideupBehaviorLoader.prototype.setupToggler = function (config) {
        var containerDivId = 'se-webform-slideup-'
            + config.formGuid;
        var trigger = document.querySelector('#se-webform-slideup-trigger-' + config.formGuid);
        var container = document.getElementById(containerDivId);
        var availableHeight = screen.availHeight * 0.8;
        if (container.clientHeight >= availableHeight) {
            container.style.height = availableHeight + 'px';
            container.style.overflowY = 'scroll';
        }
        var formCursor = container.clientHeight;
        container.style.bottom = '-' + formCursor + 'px';
        var openId = null;
        function formFrameShow() {
            trigger.classList.toggle('hidden', true);
            formCursor = Math.max(0, formCursor - 20);
            container.style.bottom = '-' + formCursor + 'px';
            if (formCursor <= 0) {
                window.clearInterval(openId);
            }
        }
        trigger.addEventListener('click', function () {
            openId = window.setInterval(formFrameShow, 1);
        });
        if (config.trigger.name === 'delay') {
            var toggler = function () {
                trigger.classList.toggle('hidden', false);
            };
            trigger.classList.toggle('hidden', true);
            window.setTimeout(toggler, Number(config.trigger.value).valueOf() * 1000);
        }
        var closeButton = container.querySelector('.se-webform-v2-slideup-close-button');
        var closeId = null;
        function formFrameHide() {
            formCursor = Math.min(container.clientHeight, formCursor + 20);
            container.style.bottom = '-' + formCursor + 'px';
            if (formCursor >= container.clientHeight) {
                window.clearInterval(closeId);
                trigger.classList.toggle('hidden', false);
            }
        }
        closeButton.addEventListener('click', function () {
            closeId = window.setInterval(formFrameHide, 1);
        });
    };
    return SlideupBehaviorLoader;
}());
var ValidationLoader = (function () {
    function ValidationLoader() {
    }
    ValidationLoader.prototype.init = function (config, form) {
        var _this = this;
        window.setTimeout(function () {
            if (document.readyState !== 'loading') {
                return _this.load(config, form);
            }
            else {
                document.addEventListener('DOMContentLoaded', function () { return __awaiter(_this, void 0, void 0, function () {
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0: return [4, this.load(config, form)];
                            case 1:
                                _a.sent();
                                return [2];
                        }
                    });
                }); });
            }
        }, 1);
    };
    ValidationLoader.prototype.load = function (config, form) {
        return __awaiter(this, void 0, void 0, function () {
            var ready;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        ready = [
                            this.loadFormValidator(config),
                            this.loadEmailCorrectionSuggesterJs(config),
                            this.loadEmailCorrectionSuggesterCss(config)
                        ];
                        return [4, Promise.all(ready)];
                    case 1:
                        _a.sent();
                        Nette.initForm(form);
                        this.initAutoComplete(config, form);
                        return [2];
                }
            });
        });
    };
    ValidationLoader.prototype.initAutoComplete = function (config, form) {
        new autoComplete({
            selector: form.querySelector('input[data-emailaddress="1"]'),
            minChars: 5,
            delay: 500,
            source: function (term, response) {
                return __awaiter(this, void 0, void 0, function () {
                    var xhr;
                    return __generator(this, function (_a) {
                        xhr = new XMLHttpRequest();
                        xhr.open('GET', config.rootUrl
                            + '/api/v3/email-correction-suggester?emailaddress='
                            + term);
                        xhr.onload = function () {
                            if (xhr.status === 200) {
                                var suggestion = JSON.parse(xhr.responseText).data.suggestion;
                                if (suggestion !== '') {
                                    response([suggestion]);
                                }
                            }
                        };
                        xhr.send();
                        return [2];
                    });
                });
            }
        });
    };
    ValidationLoader.prototype.loadEmailCorrectionSuggesterCss = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            var cssId, link, result;
            return __generator(this, function (_a) {
                cssId = 'se-autocomplete-css';
                if (document.getElementById(cssId)) {
                    return [2, new Promise(function (resolve) {
                            resolve();
                        })];
                }
                link = document.createElement('link');
                link.id = cssId;
                link.rel = 'stylesheet';
                link.type = 'text/css';
                link.href = config.rootUrl + '/web-forms-v2/auto-complete.css';
                link.media = 'all';
                result = new Promise(function (resolve) {
                    link.onload = function () {
                        resolve();
                    };
                });
                document.getElementsByTagName('head')[0].appendChild(link);
                return [2, result];
            });
        });
    };
    ValidationLoader.prototype.loadEmailCorrectionSuggesterJs = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            var script, result;
            return __generator(this, function (_a) {
                if (typeof autoComplete !== 'undefined') {
                    return [2, new Promise(function (resolve) {
                            resolve();
                        })];
                }
                script = document.createElement('script');
                script.src = config.rootUrl + '/web-forms-v2/auto-complete.min.js';
                script.async = true;
                script.defer = true;
                result = new Promise(function (resolve) {
                    script.onload = function () {
                        resolve();
                    };
                });
                document.head.appendChild(script);
                return [2, result];
            });
        });
    };
    ValidationLoader.prototype.loadFormValidator = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            var script, result;
            return __generator(this, function (_a) {
                if (typeof Nette !== 'undefined') {
                    return [2, new Promise(function (resolve) {
                            resolve();
                        })];
                }
                Nette = {
                    noInit: true,
                    initForm: function () {
                    }
                };
                script = document.createElement('script');
                script.src = config.rootUrl + '/web-forms-v2/netteForms.min.js';
                script.async = true;
                script.defer = true;
                result = new Promise(function (resolve) {
                    script.onload = function () {
                        resolve();
                    };
                });
                document.head.appendChild(script);
                return [2, result];
            });
        });
    };
    return ValidationLoader;
}());
var WebFormLoader = (function () {
    function WebFormLoader() {
        this.validationLoader = new ValidationLoader();
        this.compositionBehaviorLoader = new CompositionBehaviorLoader();
    }
    WebFormLoader.prototype.run = function (config) {
        var _this = this;
        window.setTimeout(function () {
            var script = document.createElement('script');
            script.onload = function () {
                if (document.readyState !== 'loading') {
                    return _this.render(config);
                }
                else {
                    document.addEventListener('DOMContentLoaded', function () { return __awaiter(_this, void 0, void 0, function () {
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0: return [4, this.render(config)];
                                case 1:
                                    _a.sent();
                                    return [2];
                            }
                        });
                    }); });
                }
            };
            script.src = 'https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?version=3.98.0&features=es6';
            document.head.appendChild(script);
        }, 1);
    };
    WebFormLoader.prototype.loadDefaultValuesFromUrl = function (form) {
        var _a, _b, _c;
        var urlParams = (new URL(document.location.toString())).searchParams;
        var elements = Array.from(form.querySelectorAll('input[name^="fields[df_"], input[name^="fields[cf_"], select[name^="fields[df_"], select[name^="fields[cf_"]'));
        for (var i in elements) {
            var element = elements[i];
            var exec = /fields\[(\w+)\]/i.exec(element.name);
            var fieldName = (_a = exec[1]) !== null && _a !== void 0 ? _a : null;
            var urlParam = urlParams.get('_se_' + fieldName);
            if (urlParam === null) {
                continue;
            }
            var decodedUrlParam = decodeURIComponent(atob(urlParam)
                .split('')
                .map(function (c) {
                return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
            })
                .join(''));
            if (element instanceof HTMLSelectElement) {
                for (var j in element.options) {
                    var option = element.options[j];
                    var optionText = option.innerText;
                    if (optionText !== decodedUrlParam) {
                        continue;
                    }
                    option.setAttribute('selected', '');
                    break;
                }
                continue;
            }
            if (element.type === 'checkbox') {
                var values = decodedUrlParam.split(',');
                for (var j in values) {
                    for (var k in element.labels) {
                        if (((_b = element.labels[k].innerText) === null || _b === void 0 ? void 0 : _b.trim()) !== values[j]) {
                            continue;
                        }
                        element.setAttribute('checked', '');
                        break;
                    }
                }
                continue;
            }
            if (element.type === 'radio') {
                for (var j in element.labels) {
                    if (((_c = element.labels[j].innerText) === null || _c === void 0 ? void 0 : _c.trim()) !== decodedUrlParam) {
                        continue;
                    }
                    element.setAttribute('checked', '');
                    break;
                }
                continue;
            }
            try {
                element.setAttribute('value', decodedUrlParam);
            }
            catch (e) {
                console.log(e);
            }
        }
    };
    WebFormLoader.prototype.render = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            var formHtml, form;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.loadForm(config)];
                    case 1:
                        formHtml = _a.sent();
                        form = WebFormLoader.insertFormToDom(config, formHtml);
                        this.setupTrackingInputsSession();
                        return [4, Promise.all([
                                this.compositionBehaviorLoader.init(config, form),
                                this.validationLoader.init(config, form)
                            ])];
                    case 2:
                        _a.sent();

                        const wtCookieSession = (document.cookie.match(new RegExp('_se20session=([a-z0-9]+)')));
                        if (wtCookieSession) {
                          document.getElementById('se-sessionUid-field').value = wtCookieSession[1];
                        }

                        this.loadDefaultValuesFromUrl(form);
                        return [2];
                }
            });
        });
    };
    WebFormLoader.prototype.setupTrackingInputsSession = function () {
        var w = window;
        w._ssaq = w._ssaq || [];
        w._ssaq.push(['getSessionId', function (sessionId) {
                document.getElementById('se-sessionid-field').value = sessionId;
                document.getElementById('se-sessionUid-field').value = sessionId;
            }]);
    };
    WebFormLoader.insertFormToDom = function (config, formHtml) {
        var node = document.createElement("div");
        node.innerHTML = formHtml;
        if (config.composition === 'slide-up' || config.composition === 'popup') {
            document.body.appendChild(node);
        }
        else {
            var scriptTag = document.getElementById('se-webformScriptLoader-'
                + config.accountId
                + '-'
                + config.formGuid);
            if (scriptTag === null) {
                scriptTag = document.getElementById('se-webformScriptLoader-'
                    + config.formGuid);
            }
            scriptTag.parentNode.insertBefore(node, scriptTag.nextSibling);
        }
        return node.getElementsByTagName('form')[0];
    };
    WebFormLoader.prototype.loadForm = function (config) {
        return __awaiter(this, void 0, void 0, function () {
            var xhr, result;
            return __generator(this, function (_a) {
                xhr = new XMLHttpRequest();
                xhr.open('GET', config.rootUrl
                    + '/public/web-forms-v2/load-form-html-wrapper/'
                    + config.accountId
                    + '-'
                    + config.formGuid);
                result = new Promise(function (resolve) {
                    xhr.onload = function () {
                        if (xhr.status === 200) {
                            resolve(xhr.responseText);
                        }
                        else {
                            resolve('');
                        }
                    };
                });
                xhr.send();
                return [2, result];
            });
        });
    };
    return WebFormLoader;
}());


new WebFormLoader().run(
	{
		rootUrl: "https://se-forms.cz/",
		accountId: 235422,
		hidePopupOnMobile: 1,
		formGuid: "qnpejt1ntjvqnydsl4ddv7cad81ixou0x8tr2jekevy3a5dfbk7xr3fdfx6vkghdh75epojpxo6g3w84fp75taszrog6pxi7y2ql",
		composition: "popup",
		trigger: {
			name: "delay",
			value: "60"
		},
		expiration: {
			method: "cookie",
			value: 1000
		}
	}
);
