var userDefinedMessages = new Object(); userDefinedMessages["Validations.DateNotInCorrentFormat"] = "The date is not in the correct format."; userDefinedMessages["SignatureDialog.Save"] = "Save"; userDefinedMessages["SignatureDialog.Cancel"] = "Cancel"; userDefinedMessages["SignatureDialog.Clear"] = "Clear"; userDefinedMessages["SignatureDialog.Title"] = "Please sign in in the field below"; userDefinedMessages["SignatureDialog.UploadExternalImage"] = "Image"; userDefinedMessages["SignatureDialog.ToggleEditingImage"] = "Edit Image"; userDefinedMessages["SignatureDialog.ToggleEditingSignature"] = "Edit Signature"; userDefinedMessages["Validations.SignatureRequiredErrorMessage"] = "There is a signature on the page that is required but not filled in. Please sign in the field and then submit the form again!"; userDefinedMessages["Validations.SignatureRequired"] = "Required"; userDefinedMessages["Information.FormAlreadySubmitted"] = "The form has already been submitted!"; userDefinedMessages["SubmitForm.ServerCommunicationError"] = "Communication with the server failed.\nPlease try again later."; userDefinedMessages["SubmitForm.ResponseErrorDetails"] = "An error occurred!\nDetails:"; userDefinedMessages["PageIsInvalid"] = "Not all fields in the page are filled correctly!"; userDefinedMessages["DatePicker.OK"] = "OK"; userDefinedMessages["BrowserNotSupported"] = "The current browser does not have all the features required to run this form"; userDefinedMessages["FormHasInvalidFields"] = "Form cannot be sumbitted because there are invalid or required fields."; userDefinedMessages["DialogLoading.Message"] = "Sumbitting data to the server. Please wait."; userDefinedMessages["AttachmentBlock.FileNameAlreadyExists"] = "File with name {0} already exists"; userDefinedMessages["PreviewBox.OpewInNewWindow"] = "Open in new window"; userDefinedMessages["Information.RecaptchaV2Fail"] = "Recaptcha is not valid"; userDefinedMessages["OtpWasRecreated"] = "The new otp was submitted"; userDefinedMessages["FieldIsRequired"] = "Field is required"; userDefinedMessages["FieldIsInvalidWithReason"] = "Field is invalid because "; userDefinedMessages["FieldIsInvalid"] = "Field is invalid"; userDefinedMessages["DialogWasOpened"] = "Dialog was opened"; userDefinedMessages["RequiredField"] = "required field"; var userDefinedMessageBoxes = {}; var DialogPositionCallback = null; userDefinedMessageBoxes.Info = '
'; userDefinedMessageBoxes.Warning = userDefinedMessageBoxes["Info"]; userDefinedMessageBoxes.Error = userDefinedMessageBoxes["Info"]; if(typeof(WebSocket) == undefined) { window.onload = function() { document.body.innerHTML = "The browser is not supported"; throw "not supported"; } } //Polyfill for IE: https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach if (window.NodeList && !NodeList.prototype.forEach) { NodeList.prototype.forEach = function (callback, thisArg) { thisArg = thisArg || window; for (var i = 0; i < this.length; i++) { callback.call(thisArg, this[i], i, this); } }; } var __jsErrors__ = []; window.onerror = function (msg, url, lineNo, columnNo, error) { __jsErrors__.push({ msg: msg, url: url, lineNo: lineNo, columnNo: columnNo, error: error }); return false; } var _pages = new Array(); var divStatusTitle = null; var _currentPageIndex = 0; var _currentPage = null; var _buttons = new Object(); var _animations = new Object(); var _fields = new Object(); var _fieldNames = new Array(); var _radioGroups = new Object(); var _signatures = new Object(); var _formSubmitted = false; var _alertCreated = false; var _customValidationFunctions = new Object(); var _globalParameters = new Object(); var _multilineFields = new Array(); var _displayState = new Object(); var NormalImageIndex = 0; var RollOverImageIndex = 1; var DownImageIndex = 2; var UseAjaxOnFormSubmitting = false; var FormID = "_form_"; var g_absoluteLayout = false; var PAGESECTION_VALID = 0; var PAGESECTION_HAS_REQUIREDFIELDS = 1; var PAGESECTION_HAS_INVALIDFIELDS = 2; var PAGESECTION_INVALID = 3; var DialogResult = { Cancel: 0, OK: 1 }; var g_dialogData = null; var g_templateIndex = 0; var g_templateInitializers = new Object(); var g_eventHandlers = new Object(); var g_invalidFieldHandlers = new Object(); var g_invalidFieldsMessageBoxID = "cd_MessageBoxError"; var g_initActions = new Array(); var g_showPageActions = new Array(); var g_hidePageActions = new Array(); var g_addResponseErrorDetails = true; var InvalidFieldsHandlerContext = { GoToNextPage: "a", GoToPreviousPage: "b", Submit: "c" }; var g_dialogLists = new Array(); var g_callServiceInDebug = false; var g_previewData = null; var g_formInitialized = false; var g_scrollIntoOffset = 0; var g_composeDocSystemURL = null; var g_submitFormURL = null; var g_previewBoxCallSystem = false; function translateUserDefinedMessages() { var elementsToTranslate = document.getElementsByClassName("user-defined-message"); for (var i = 0; i < elementsToTranslate.length; i++) { var element = elementsToTranslate.item(i); var messageKey = element.getAttribute("data-user-defined-message-key"); if (!messageKey) { messageKey = element.innerHTML; element.setAttribute("data-user-defined-message-key", messageKey); //store key for next time } if (userDefinedMessages[messageKey] != undefined) { element.innerHTML = userDefinedMessages[messageKey]; } } } var EmptyTemplateID = "__empty__"; g_templateInitializers[EmptyTemplateID] = () => {} function ScrollIntoView(element) { if(g_scrollIntoOffset) { element.scrollIntoView(); if (window.scrollY > g_scrollIntoOffset) { window.scroll(0, window.scrollY - g_scrollIntoOffset); } } else { element.scrollIntoView({block:"center"}); } } function ResizeMultilineField(text) { if (text.value == text.initialValue) { text.style.height = text.initialHeight; } if (text.scrollHeight > 0) { text.style.height = text.scrollHeight + 'px'; } } function InitMultilineField(text) { text.initialValue = text.value; text.initialHeight = text.style.height; var observe; if (window.attachEvent) { observe = function (element, event, handler) { element.attachEvent('on' + event, handler); }; } else { observe = function (element, event, handler) { element.addEventListener(event, handler, false); }; } function resize() { ResizeMultilineField(text); } /* 0-timeout to get the already changed text */ function delayedResize() { window.setTimeout(resize, 0); } observe(text, 'change', resize); observe(text, 'cut', delayedResize); observe(text, 'paste', delayedResize); observe(text, 'drop', delayedResize); observe(text, 'keydown', delayedResize); observe(text, 'keyup', delayedResize); observe(window, 'resize', delayedResize); } function ResizeMultiLineFields(page) { var fieldElements = page.pageElement.querySelectorAll('.multiline-field'); for (var i = 0; i < fieldElements.length; ++i) { ResizeMultilineField(fieldElements[i]); } } function InitMultilineFields(root) { if(root == null) root = document; var fieldElements = root.querySelectorAll('.multiline-field') ; for(var i = 0; i < fieldElements.length; ++i) { InitMultilineField(fieldElements[i]); } } var CoreUtils = { AppendElement: function (parent, elementType, ...styles) { var element = document.createElement(elementType); if(styles) { element.classList.add(...styles); } parent.appendChild(element); return element; }, AppendDiv : function(parent, ...styles) { return this.AppendElement(parent, "div", ...styles); }, AppendText: function (parent, text, ...styles) { var paragraph = this.AppendElement(parent, "p", ...styles); paragraph.innerHTML = text; return paragraph }, AppendSpan : function(parent, text, ...styles) { var span = this.AppendElement(parent, "span", ...styles); span.innerHTML = text; return span; }, SetPixelsProperty : function(element, name, value) { element.style[name] = value + "px"; }, SetMinWidth : function(element, value) { this.SetPixelsProperty(element, "minWidth", value); }, SetMaxWidth : function(element, value) { this.SetPixelsProperty(element, "maxWidth", value); }, SetWidth : function(element, value) { this.SetPixelsProperty(element, "width", value); }, SetMinHeight : function(element, value) { this.SetPixelsProperty(element, "minHeight", value); }, SetMaxHeight : function(element, value) { this.SetPixelsProperty(element, "maxHeight", value); }, SetHeight : function(element, value) { this.SetPixelsProperty(element, "height", value); }, DelayCall : function(handler) { window.setTimeout( handler, 0); } } function InitNumberTextBoxes() { var numberTextBoxes = document.querySelectorAll(".number_tb"); numberTextBoxes.forEach(function (numberTextBox) { let proper = {}; var insertThousandSeparator = (numberTextBox.getAttribute("insertThousandSeparator") === "true"); if (insertThousandSeparator){ proper.decimalCharacter = "."; proper.digitGroupSeparator = ","; var maxlength = numberTextBox.getAttribute("maxlength"); if (maxlength != null) { var maxValue = ""; var len = parseInt(maxlength); while (len-- > 0) { maxValue += "9"; } proper.maximumValue = maxValue; } var minValue = numberTextBox.getAttribute("min-value"); var maxValue = numberTextBox.getAttribute("max-value"); if (minValue != null && maxValue != null) { proper.minimumValue = minValue; proper.maximumValue = maxValue; } numberTextBox.autoNumber = new AutoNumeric(numberTextBox, proper); } else { var platform = window.navigator.platform; var isWindowsDevice = platform.indexOf("Win") != -1; if (isWindowsDevice) { return; } var numberTextBoxes = document.querySelectorAll(".number_tb"); var isIOS = platform == "iPhone" || platform == "iPad"; numberTextBoxes.forEach(function (numberTextBox) { if (isIOS) { numberTextBox.pattern = "[0-9]*"; } else { numberTextBox.type = "number"; } if (numberTextBox.hasAttribute("maxlength")) { var self = numberTextBox; numberTextBox.addEventListener("input", function (event) { if (self.value.length > self.maxLength) { self.value = self.value.substr(0, self.maxLength); } }); } }); } }); } function DataTreeObjectArray(dataTreeObject) { this.dataTreeObject = dataTreeObject; if(this.dataTreeObject) { this.isArray = Array.isArray(dataTreeObject); if(!this.isArray) { this.length = 1; } else { this.length = this.dataTreeObject.length; } } else { this.isArray = false; this.length = 0; this.dataTreeObject = null; } } DataTreeObjectArray.prototype = { GetAt : function(index) { if(this.isArray) { return this.dataTreeObject[index]; } else if(index != 0 || this.length == 0) { return null; } else { return this.dataTreeObject; } }, ToJSArray : function() { if(this.isArray) return this.dataTreeObject; var jsArray = new Array(); if(this.length != 0) { jsArray.push(this.dataTreeObject); } return jsArray; } }; function ExecuteInitActions() { g_initActions.forEach(function (action) { action(); }); } function HandlePreviewData() { if(g_previewData) { if(document.getElementById("__FormData__").value != "") { g_previewData = null; } } } function MoveAttribute(name, source, target) { var attributeValue = source.getAttribute(name); if(!attributeValue) return; source.removeAttribute(name); target.setAttribute(name, attributeValue); } function InitHyperlinksAccessibility() { var hyperlinks = document.querySelectorAll("a"); for(var hyperlink of hyperlinks) { if(!hyperlink.parentElement.classList.contains("fcell")) continue; MoveAttribute("aria-label", hyperlink.parentElement, hyperlink); MoveAttribute("aria-labelledBy", hyperlink.parentElement, hyperlink); MoveAttribute("aria-describedBy", hyperlink.parentElement, hyperlink); } } function InitCore() { g_formInitialized = true; ExecuteInitActions(); InitHyperlinksAccessibility(); InitMultilineFields(); g_showPageActions.push(ResizeMultiLineFields); InitNumberTextBoxes(); HandlePreviewData(); } function SetInvalidFieldsHandler(context, handler) { g_invalidFieldHandlers[context] = handler; } function GetInvalidFieldsHandler(context) { return g_invalidFieldHandlers[context]; } function ValidatePage(pageObject, highlightInvalidFields) { pageObject.Validate(); pageObject.ARIAValidation(); if(!pageObject.isValid) { if(highlightInvalidFields == null || highlightInvalidFields == true) { pageObject.HighlightInvalidFields(); } } return pageObject.isValid } function ValidateCurrentPageEx(highlightInvalidFields, errorMessage, maxInvalidFields) { if(highlightInvalidFields == null) highlightInvalidFields = true; if( ValidatePage(_currentPage, false) ) return true; if(errorMessage == null) { if(highlightInvalidFields) { _currentPage.HighlightInvalidFields(); } return false; } if(errorMessage.indexOf("") != -1) { errorMessage = errorMessage.replace("", _currentPage.GetInvalidFieldsDescription(maxInvalidFields)); } ShowErrorMessageBox(errorMessage, ()=>{ if(highlightInvalidFields) { _currentPage.HighlightInvalidFields(); } }); } function ValidateCurrentPage(highlightInvalidFields) { return ValidatePage(_currentPage, highlightInvalidFields); } SetInvalidFieldsHandler( InvalidFieldsHandlerContext.GoToNextPage, function() { if (!_currentPage.isValid) { if (userDefinedMessages.PageHasInvalidFields) { ShowMessageBox(userDefinedMessages.PageHasInvalidFields, null, g_invalidFieldsMessageBoxID); } _currentPage.HighlightInvalidFields(); return false; } else { return true; } }); SetInvalidFieldsHandler(InvalidFieldsHandlerContext.Submit, function () { _currentPage.Validate(); for (var i = 0; i < _pages.length; ++i) { var page = _pages[i]; if(!page.isValid) { if (userDefinedMessages.FormHasInvalidFields) { ShowMessageBox(userDefinedMessages.FormHasInvalidFields, function () { ShowPage(page.index); page.HighlightInvalidFields(); }, g_invalidFieldsMessageBoxID); } else { ShowPage(page.index); page.HighlightInvalidFields(); } return false; } } return true; }); function EventHandlers(owner) { this.owner = owner; this.handlers = new Array(); this.callIndex = 0; } EventHandlers.prototype = { AddHandler : function(handler) { this.handlers.push(handler); }, RemoveHandler : function(handler) { var removeIndex = -1; for(var i = 0; i < this.handlers.length; ++i) { if(this.handlers[i] == handler) { removeIndex = i; break; } } if(removeIndex == -1) return; for(var i = removeIndex; i < this.handlers.length - 1; ++i) { this.handlers[i] = this.handlers[i + 1]; } if(removeIndex == this.callIndex) { this.callIndex --; } this.handlers.pop(); }, Fire : function(args) { for(var i = 0; i < this.handlers.length; ) { this.callIndex = i; this.handlers[i](this.owner, args); i = this.callIndex + 1; } } } function GetTemplateHandler(templateDataModel, functionName) { if(templateDataModel == null) return null; if(templateDataModel[functionName]) return templateDataModel; else return GetTemplateHandler(templateDataModel.templateHandler, functionName); } function LoadTemplate(templateID, targetElement, templateDataModel, addedDocumentFormFields) { var templateElement = document.getElementById(templateID); if (templateElement == null && templateID != EmptyTemplateID) { console.error("Invalid templateID " + templateID); return false; } if (typeof (targetElement) == 'string') { targetElement = document.getElementById(targetElement); } var idPrefix = "_tmp" + (g_templateIndex++); if(templateElement != null) { var templateContent = templateElement.innerHTML; templateContent = templateContent.replace(/tmpl_/gi, idPrefix); targetElement.innerHTML = templateContent; } var nameResolver = function(fieldName) { var templateHandler = GetTemplateHandler(templateDataModel, "ResolveDocumentFormFieldName"); if(templateHandler) { var newName = templateHandler.ResolveDocumentFormFieldName(fieldName); if(newName != null) return { name :newName, alias : idPrefix + fieldName }; } return { name : idPrefix + fieldName }; } var oldNameResolver = DocumentForm.nameResolver; var oldAddedDocumentFormFields = DocumentForm.addedFields; if (addedDocumentFormFields) { if(oldAddedDocumentFormFields) { oldAddedDocumentFormFields.AddChild(addedDocumentFormFields); } DocumentForm.addedFields = addedDocumentFormFields; } DocumentForm.nameResolver = nameResolver; g_templateInitializers[templateID](idPrefix, templateDataModel, targetElement); var initHandler = GetTemplateHandler(templateDataModel, "InitTemplate"); if(initHandler) { initHandler.InitTemplate(targetElement, idPrefix); } DocumentForm.nameResolver = oldNameResolver; DocumentForm.addedFields = oldAddedDocumentFormFields; InitMultilineFields(targetElement); return true; } function LoadTemplateWithValidation(templateID, targetElement, templateDataModel, addedDocumentFormFields, parentValidation, validationResult) { var validation = new ValidationNode(); DynamicValidation.Push(validation); var result = LoadTemplate(templateID, targetElement, templateDataModel, addedDocumentFormFields); DynamicValidation.Pop(); if(!result) return false; if(validation.IsEmpty()) { return true; } if (parentValidation == null) { parentValidation = DynamicValidation.GetParent(targetElement); } parentValidation.AddChild(validation); if(validationResult) { validationResult.validation = validation; } return true; } function DlgHandleEscape(event) { var key = event.which || event.keyCode; if (key == 27) { if(CloseDialog(null)) { event.stopPropagation(); } } } window.addEventListener("keydown", DlgHandleEscape); function SplashContent(templateID, contentModel) { if (document.getElementById(templateID) == null) return null; var dialogContainer = document.createElement("div"); dialogContainer.classList.add("dialogBox"); document.body.appendChild(dialogContainer); var content = new Object(); content.container = dialogContainer; content.Hide = function() { document.body.removeChild(dialogContainer); } if (!LoadTemplate(templateID, dialogContainer, contentModel)) { content.Hide(); return null; } return content; } var g_busyBoard = { calls : 0, hasMessage : false, busyBoardContainer : null, Show : function() { ++ this.calls; if(this.calls > 1) return; if(this.ShowBoard()) { // for accessibility reasons the message is shown after some time window.setTimeout(() => { this.ShowMessage(); }, 1500); } }, ShowBoard : function() { if(this.busyBoardContainer) return false; this.busyBoardContainer = CoreUtils.AppendDiv(document.body, "dialogBox"); return true; }, ShowMessage : function() { if(this.calls == 0 || this.hasMessage) return; this.busyBoardContainer.classList.remove("transparentBackground"); this.hasMessage = LoadTemplate("cd_loadingDialog", this.busyBoardContainer, { InitTemplate: (templateElement)=> { templateElement.setAttribute("aria-live", "polite"); }}); }, Hide : function() { -- this.calls; if(this.calls > 0) return; if(this.calls < 0) { this.calls = 0; return; } if(this.hasMessage) { window.setTimeout(()=>{ this.DoHide(); }, 2000); } else { this.HideBoard(); } }, HideBoard : function() { document.body.removeChild(this.busyBoardContainer); this.busyBoardContainer = null; this.hasMessage = false; }, DoHide : function() { if(this.calls > 0 || !this.busyBoardContainer) return; this.HideBoard(); } } function ShowBusyBoard() { g_busyBoard.Show(); } function HideBusyBoard() { g_busyBoard.Hide(); } var g_nextDynamicPageContentIndex = 0; function DynamicPageContent(container) { this.contentHolder = container; this.contentContainer = null; } DynamicPageContent.prototype = { Init : function(templateName, templateDataModel) { this.Clean(); var templateElement = document.getElementById(templateName); if (templateElement == null) return false; this.contentContainer = document.createElement("div"); this.contentContainer.id = "dpc" + (g_nextDynamicPageContentIndex ++); this.contentContainer.classList.add("dynamicPageContent"); this.contentContainer.classList.add("validationRoot"); this.contentHolder.appendChild( this.contentContainer ); this.documentFormFields = new DocumentFormFieldsCollection(); if(!LoadTemplateWithValidation(templateName, this.contentContainer, templateDataModel, this.documentFormFields)) { this.contentHolder.removeChild(this.contentContainer); this.contentContainer = null; return; } this.pageObject = new PageObject(this.contentContainer.id, 0); this.pageObject.ValidateFields(); }, Validate : function() { return ValidatePage(this.pageObject) }, Clean : function() { if(this.contentContainer == null) return; ValidationRoots.Remove(this.contentContainer.id) this.contentHolder.removeChild(this.contentContainer); this.documentFormFields.Delete(); this.pageObect = null; } } var g_nextDialogInstance = 0; function ShowDialog(templateID, callback, dialogModel, initDialog, positionCallback) { var activeElement = document.activeElement; if(templateID != EmptyTemplateID && document.getElementById(templateID) == null) { return false; } var dialogID = "dialog" + (g_nextDialogInstance++); var dialogContainer = document.createElement("div"); dialogContainer.id = dialogID; dialogContainer.classList.add("dialogBox"); dialogContainer.classList.add("validationRoot"); document.body.appendChild(dialogContainer); var dialogData = new Object(); dialogData.dialogContainer = dialogContainer; dialogData.callback = callback; dialogData.documentFormFields = new DocumentFormFieldsCollection(); dialogData.id = dialogID; g_dialogLists.push(dialogData); if (LoadTemplateWithValidation(templateID, dialogContainer, dialogModel, dialogData.documentFormFields, null)) { var firstChild = dialogContainer.firstElementChild; firstChild.setAttribute("role", "dialog"); firstChild.setAttribute("aria-modal", "true"); firstChild.setAttribute("aria-label", userDefinedMessages.DialogWasOpened); dialogData.ariaDialog = new aria.Dialog(firstChild, activeElement); } else { CloseDialog(null); return false; } if (initDialog) { initDialog(dialogContainer, dialogModel); } var positionDefault = true; if(positionCallback) { positionDefault = !positionCallback(dialogContainer.firstElementChild); } if(DialogPositionCallback && positionDefault) { DialogPositionCallback(dialogContainer.firstElementChild); } dialogData.pageObject = new PageObject(dialogID, 0); dialogData.pageObject.ValidateFields(); DynamicValidation.Pop(); return true; } function ValidateDialog() { var dialogData = g_dialogLists[ g_dialogLists.length - 1 ]; if(dialogData == null ) return; return ValidatePage(dialogData.pageObject); } function CloseDialog(result) { var dialogData = g_dialogLists.pop(); if (dialogData == null) { return false; } if (dialogData.ariaDialog) { dialogData.ariaDialog.close(); } ValidationRoots.Remove(dialogData.dialogContainer.id); dialogData.documentFormFields.Delete(); document.body.removeChild(dialogData.dialogContainer); if(dialogData.callback) { dialogData.callback(result); } return true; } function InitMessageBox(messageBoxContainer, message) { if (message) { message = message.toString().replaceAll("\n", "
"); } else { message = ""; } SetMessageBoxText(messageBoxContainer, message); } function ShowMessageBox(message, callback, templateID) { if(templateID && templateID != "") { if(ShowDialog(templateID, callback, message, InitMessageBox)) return; } if (!ShowDialog("cd_MessageBoxGeneric", callback, message, InitMessageBox)) { alert(message, callback); } } window.alert = function (error, callback, htmlMessageContent) { if (!htmlMessageContent) { htmlMessageContent = userDefinedMessageBoxes.Info; } var self = this; var message = error.toString(); message = message.replace("\n", "
"); var divAlert = document.getElementById("divAlert"); divAlert.innerHTML = htmlMessageContent; divAlert.style.zIndex = 1000; document.getElementById("divOverlay").style.display = "flex"; divAlert.style.display = "inline-block"; var alertContentElemenets = divAlert.getElementsByClassName("alert-content"); if (alertContentElemenets.length > 0) alertContentElemenets[0].innerHTML = message; /* divAlert.style.marginLeft = -divAlert.offsetWidth / 2 + "px"; divAlert.style.marginTop = -divAlert.offsetHeight / 2 + "px"; */ self.btnAlertOKClicked = function (callback) { document.getElementById("divOverlay").style.display = "none"; document.getElementById("divAlert").style.display = "none"; if (callback) { callback(); } var alertButtonElements = divAlert.getElementsByClassName("alert-button"); for (var i = 0; i < alertButtonElements.length; i++) { var alertButton = alertButtonElements[i]; alertButton.removeEventListener('click', self.clickHandler); } document.removeEventListener('keydown', self.keyDownHandler); }; self.clickHandler = function () { self.btnAlertOKClicked(callback); }; self.keyDownHandler = function (ev) { if (ev.which == 27 || ev.which == 13) { self.btnAlertOKClicked(callback); } }; var alertButtonElements = divAlert.getElementsByClassName("alert-button"); for(var i = 0; i < alertButtonElements.length; i++) { var alertButton = alertButtonElements[i]; alertButton.addEventListener('click', self.clickHandler); } document.addEventListener("keydown", self.keyDownHandler); if(DialogPositionCallback) { DialogPositionCallback(divAlert); } }; function ShowInfoMessageBox(error, callback) { ShowMessageBox(error, callback, "cd_MessageBoxInfo"); } function ShowWarningMessageBox(error, callback) { ShowMessageBox(error, callback, "cd_MessageBoxWarning"); } function ShowErrorMessageBox(error, callback) { ShowMessageBox(error, callback, "cd_MessageBoxError"); } function DisplayElement(objectID, show, setDisplayState) { if (objectID == "") return; if (setDisplayState == undefined || setDisplayState == true) { _displayState[objectID] = show; } ShowObject(document.getElementById(objectID), show); } function ShowElement(objectID) { DisplayElement(objectID, true); } function HideElement(objectID) { DisplayElement(objectID, false); } function UpdateFieldsVisibility(object) { var validationFieldObjects = object.querySelectorAll(".VF"); if (validationFieldObjects.length == 0) return; for(var i = 0; i < validationFieldObjects.length; ++i) { var fieldObject = validationFieldObjects[i]; if (fieldObject.id == "") continue; var field = DocumentForm.GetField(fieldObject.id); if(field != null) { field.UpdateVisibility(); } } if(_currentPage) { _currentPage.CheckForInvalidFields(); } } function ElementShow(element, show) { if(show) element.classList.remove("forceDisplayNone"); else element.classList.add("forceDisplayNone"); } function ShowObject(object, show, disableUpdateVisibility) { if (object == null) return; if (object.dataset.preservespacewhenhidden) { object.style.visibility = show ? "visible" : "hidden"; return; } var displayValue = ""; if(show) { var dvAttribute = object.attributes.dv; if(typeof(dvAttribute) == "undefined") { displayValue = "block"; } else { switch(dvAttribute.value) { case "f": displayValue = "flex"; break; case "c": displayValue = "inline-block"; break; default: displayValue = "block"; } } } else { displayValue = "none"; } if (object.style.display == displayValue) return; object.style.display = displayValue; if(!disableUpdateVisibility) { UpdateFieldsVisibility(object); } } function FindPage(pageName) { for(var i = 0; i < _pages.length; ++i) { var page = _pages[i]; if(page.name === pageName) { return page; } } return null; } function ExecutePageActions(pageActions, page) { pageActions.forEach(function (action) { action(page); }) } function ShowPage(pageIndex) { if(_currentPageIndex == pageIndex) { return; } _currentPage.Hide(); ExecutePageActions(g_hidePageActions, _currentPage); _currentPageIndex = pageIndex; _currentPage = _pages[pageIndex]; document.getElementById(_currentPage.id).setAttribute("aria-hidden", "true"); _currentPage.Show(); setTimeout(function () { document.getElementById(_currentPage.id).setAttribute("aria-hidden", "false"); if (_currentPage.title) { document.title = _currentPage.title; } var contentObjects = _currentPage.pageElement.querySelectorAll(".cell"); var contentObject; for (var i = 0; i < contentObjects.length; ++i) { contentObject = contentObjects[i]; var style = window.getComputedStyle(contentObject); if(style.display != "none" && style.display != "") { break; } } contentObject.tabIndex = 0; contentObject.focus(); }, 1000); if (_currentPage.title) { AddNewDivStatusTitle(_currentPage.title); } ExecutePageActions(g_showPageActions, _currentPage); window.scroll(0, 0); } function GoToPage(pageIndex, invalidFieldsHandler) { if (_currentPageIndex == pageIndex) return true; /* if (!_currentPage.Validate()) { ShowErrorMessageBox(userDefinedMessages["PageIsInvalid"]); return; }*/ if (typeof(invalidFieldsHandler) == "undefined") { invalidFieldsHandler = GetInvalidFieldsHandler(pageIndex > _currentPageIndex ? InvalidFieldsHandlerContext.GoToNextPage : InvalidFieldsHandlerContext.GoToPreviousPage); } _currentPage.Validate(); _currentPage.ARIAValidation(); if (invalidFieldsHandler) { if (!invalidFieldsHandler()) { return false; } } ShowPage(pageIndex); return true; } function GoToPageWithName(pageName, invalidFieldsHandler) { var page = FindPage(pageName); if (page) { return GoToPage(page.index, invalidFieldsHandler); } else { return false; } } function GoToPrevPage(invalidFieldsHandler) { if (_currentPageIndex == 0) return false; return GoToPage(_currentPageIndex - 1, invalidFieldsHandler); } function GoToNextPage(invalidFieldsHandler) { if (_currentPageIndex < _pages.length - 1) { return GoToPage(_currentPageIndex + 1, invalidFieldsHandler); } else { return false; } } function GetPageFieldsToValidate(pageObject) { if (pageObject.pageElement.dataset.validation) { var fieldIDS = pageObject.pageElement.dataset.validation.split(';'); pageObject.fieldsToValidateHead.Add(fieldIDS); } var dynamicFields = DynamicValidation.Get(pageObject.id); if(dynamicFields) { pageObject.fieldsToValidateHead.Add(fieldIDS); } } function InvalidFieldResult() { this.hasInvalidFields = false; this.hasRequiredFields = false; } function PageObject(pageID, pageIndex, inputValdationRoot) { this.index = pageIndex; this.id = pageID; this.pageElement = document.getElementById(pageID); this.name = this.pageElement.dataset.pagename; this.isValid = true; this.hasRequiredFields = false; this.hasInvalidFields = false; this.hasBeenShown = false; this.preventCheckFieldStates = false; this.title = this.pageElement.dataset.title; this.validationRoot = inputValdationRoot ? inputValdationRoot : ValidationRoots.Get(this.id); if (this.pageElement.dataset.validation) { var fieldIDS = this.pageElement.dataset.validation.split(';'); this.validationRoot.node.AddChild(new ValidationNode(fieldIDS)); } this.AttachValidations(this.validationRoot.node); this.validationRoot.page = this; } PageObject.prototype = { AttachValidationFields : function(validationNode) { if(validationNode.data == null) return; var fieldsID = validationNode.data; var validationData = {fields : new Array(), buttons : new Array()}; for (var i = 0; i < fieldsID.length; ++i) { var field = DocumentForm.GetField(fieldsID[i]); field.page = this; if (field.IsButton()) { validationData.buttons.push(field); } else { validationData.fields.push(field); } } validationNode.data = validationData; }, AttachValidations : function(validationNode) { validationNode.root = this.validationRoot; this.AttachValidationFields(validationNode); for(var child = validationNode.firstChild; child != null; child = child.next) { this.AttachValidations(child); } }, AddDynamicValidation : function(validation) { if(validation.data == null) return; this.AttachValidationFields(validation); validation.data.fields.forEach(function(field) { field.UpdateStatus(true); }); if(!this.CheckForInvalidFields()) { this.UpdateValidationState(); } }, RemoveDynamicValidation : function(validation) { if(validation.data == null && validation.firstChild == null) return; this.CheckForInvalidFields(); }, TraverseFieldToValidate : function(node, handler, context) { if(node.data != null) { for(var i = 0; i < node.data.fields.length; ++i) { handler(node.data.fields[i], context); if(context.cancel) { return; } } } for(var child = node.firstChild; child != null; child = child.next) { this.TraverseFieldToValidate(child, handler, context); if(context.cancel) return; } }, ForEachFieldToValidate : function(handler) { var context = {cancel:false}; this.TraverseFieldToValidate(this.validationRoot.node, handler, context); }, ValidateFields : function() { this.isValid = true; this.invalidFieldsCount = 0; this.preventCheckFieldStates = true; this.ForEachFieldToValidate(function (field) { field.UpdateStatus(true); }); this.preventCheckFieldStates = false; if (this.isValid) { this.UpdateValidationState(); } }, ARIAValidation: function () { } , SearchForInvalidField: function () { var result = new InvalidFieldResult(); this.ForEachFieldToValidate(function(field, context){ if (!field.IsValid()) { if (!field.IsVisible()) return; if(field.GetStatus() == STATUS_REQUIRED) { result.hasRequiredFields = true; } else { result.hasInvalidFields = true; } if(result.hasInvalidFields && result.hasRequiredFields) { context.cancel = true; } } }); return result; }, EnableValidationButtons : function(node, enable) { if(node.data != null) { node.data.buttons.forEach(function (button) { if (enable) { button.Enable(); } else { button.Disable(); } }); } for(var child = node.firstChild; child != null; child = child.next) { this.EnableValidationButtons(child, enable); } }, UpdateValidationState : function() { this.EnableValidationButtons(this.validationRoot.node, this.isValid); this.preventCheckFieldStates = true; this.DisplaySections(); this.preventCheckFieldStates = false; }, DisplaySections : function() { var sections = this.pageElement.querySelectorAll(".PageSection"); var self = this; for(var i = 0; i < sections.length; ++i) { var section = sections[i]; var pageSectionType = parseInt( section.dataset.sectiontype ); var show = false; switch(pageSectionType) { case PAGESECTION_VALID: show = self.isValid; break; case PAGESECTION_HAS_INVALIDFIELDS: show = self.hasInvalidFields; break; case PAGESECTION_HAS_REQUIREDFIELDS: show = self.hasRequiredFields; break; case PAGESECTION_INVALID: show = self.hasRequiredFields || self.hasInvalidFields; break; } ShowObject(section, show) } }, ProcessField : function(sourceField) { if (sourceField.IsValid()) { if (this.isValid) return; this.CheckForInvalidFields(); } else { var sourceFieldStatus = sourceField.GetStatus(); if (sourceFieldStatus == STATUS_REQUIRED && this.hasRequiredFields) { return; } else if (this.hasInvalidFields) { return; } if (!sourceField.IsVisible()) return; if (sourceFieldStatus == STATUS_REQUIRED) { this.hasRequiredFields = true; } else { this.hasInvalidFields = true; } this.isValid = false; this.UpdateValidationState(); } }, CheckForInvalidFields : function() { if (this.preventCheckFieldStates) return false; var invalidFieldResult = this.SearchForInvalidField(); if(invalidFieldResult.hasInvalidFields == this.hasInvalidFields && invalidFieldResult.hasRequiredFields == this.hasRequiredFields) { return false; } this.hasInvalidFields = invalidFieldResult.hasInvalidFields; this.hasRequiredFields = invalidFieldResult.hasRequiredFields; this.isValid = !(this.hasInvalidFields || this.hasRequiredFields); this.UpdateValidationState(); return true; }, Validate : function() { this.CheckForInvalidFields(); return this.isValid; }, Show : function() { if (!this.hasBeenShown) { this.preventCheckFieldStates = true; ShowObject(this.pageElement, true); this.preventCheckFieldStates = false; this.hasBeenShown = true; this.ValidateFields(); } else { ShowObject(this.pageElement, true, true); } if(this.pageElement.backgroundColor) { document.body.style.backgroundColor = this.pageElement.backgroundColor; } else { var pageStyle = window.getComputedStyle(this.pageElement); if (pageStyle.backgroundColor) { this.pageElement.backgroundColor = pageStyle.backgroundColor; document.body.style.backgroundColor = pageStyle.backgroundColor; this.pageElement.style.backgroundColor = "transparent"; } } }, Hide : function() { this.preventCheckFieldStates = true; ShowObject(this.pageElement, false, true); this.preventCheckFieldStates = false; }, GetInvalidFieldsDescription : function(maxNumber) { var lines = new Array(); maxNumber = maxNumber || 1000000; var passedFields = {}; var getInvalidMessage = (field, lines)=> { if(field.status == STATUS_INVALID) { var validationMessage = field.validationMessage; if(!validationMessage) { lines.push( userDefinedMessages.FieldIsInvalid.replace("", field.GetUIName()) ); } else { lines.push( userDefinedMessages.FieldIsInvalidWithReason.replace("", field.GetUIName()).replace("", validationMessage) ); } } else if(field.isRequired) { lines.push( userDefinedMessages.FieldIsRequired.replace("", field.GetUIName()) ); } } this.ForEachFieldToValidate((field)=>{ if(field.IsValid()) return; if(lines.length >= maxNumber) return; var fieldName = field.GetUIName(); if(passedFields[fieldName]) return; passedFields[fieldName] = true; //lines.push( getInvalidMessage(field) ); getInvalidMessage(field, lines); }); return lines.join("\n"); }, HighlightInvalidFields : function() { if (this.isValid) return; var firstInvalidField = null; this.ForEachFieldToValidate(function(field){ if (field.IsValid()) return; if(firstInvalidField == null) { firstInvalidField = field; field.Focus(); field.ScrollIntoView(); } field.Highlight(true); }); } }; function AddNewDivStatusTitle(msg) { if (divStatusTitle.lastElementChild) { divStatusTitle.lastElementChild.style.display = "none"; } var newStatus = document.createElement("div"); newStatus.innerHTML = msg; divStatusTitle.appendChild(newStatus); } function InitPages(pagesCount) { if (pagesCount == 0) return; if (!divStatusTitle) { divStatusTitle = document.createElement("div"); divStatusTitle.setAttribute("role", "status"); divStatusTitle.setAttribute("aria-live", "assertive"); divStatusTitle.setAttribute("aria-relevant", "additions"); divStatusTitle.classList.add("ui-helper-hidden-accessible"); document.body.appendChild(divStatusTitle); } for(var i = 0; i < pagesCount; ++i) { _pages.push( new PageObject("_page" + i, i) ); } _currentPage = _pages[0]; if (_currentPage.title) { var titleElem = document.getElementsByTagName("title"); document.title = _currentPage.title; } _currentPage.Show(); ExecutePageActions(g_showPageActions, _currentPage); } function CreateState(name, index) { var state = new Object(); state.images = new Array(); state.images.push( document.getElementById( name + index + "N" ) ); state.images.push( document.getElementById( name + index + "O" ) ); state.images.push( document.getElementById( name + index + "D" ) ); state.index = index; return state; } function CreateStates(name, statesCount) { var states = new Array(); for(var i = 0; i < statesCount; ++i) { states.push( CreateState(name, i) ); } return states; } function ButtonObject(name, statesCount, initialStateIndex, attachToParent) { this.name = name; this.currentState = null; this.states = CreateStates(name, statesCount); this.currentImage = null; this.mouseIsOver = false; this.OnClick = null; this.currentState = this.states[initialStateIndex]; this.initialStateIndex = initialStateIndex; this.currentImageIndex = 0; this.enabled = true; this.owner = null; this.ShowImage(NormalImageIndex); this.mouseDown = false; var uiObject = document.getElementById(name); if (attachToParent) { if(!uiObject.parentElement.parentElement.classList.contains("noUI")) { uiObject = uiObject.parentElement; } } var self = this; uiObject.addEventListener("touchstart", function (e) { e.preventDefault(); self.OnMouseDown(); }); uiObject.addEventListener("touchend", function (e) { e.preventDefault(); self.OnMouseUp(); }); uiObject.addEventListener("mousedown", function (e) { self.OnMouseDown(); }); uiObject.addEventListener("mouseup", function (e) { self.OnMouseUp(); }); /* uiObject.addEventListener("mouseover", function (e) { self.OnMouseOver(); }); uiObject.addEventListener("mouseout", function (e) { self.OnMouseOut(); }); */ this.uiObject = document.getElementById(name); } ButtonObject.prototype.Show = function(doShow) { ShowObject(this.uiObject.parentElement, doShow == null ? true : doshow); } ButtonObject.prototype.Hide = function() { this.Show(false); } ButtonObject.prototype.Reset = function() { this.SetState( this.initialStateIndex ); }; ButtonObject.prototype.Enable = function () { this.enabled = true; if(this.owner != null) { var container = this.owner.GetObject(); container.style.opacity = 1; container.style.cursor = "pointer"; } }; ButtonObject.prototype.GetObject = function () { return this.uiObject; } ButtonObject.prototype.Disable = function () { this.enabled = false; if(this.owner != null) { var container = this.owner.GetObject(); container.style.opacity = 0.5; container.style.cursor = "not-allowed"; } }; ButtonObject.prototype.SetValue = function(value) { if(this.owner != null) { this.owner.SetValue(value); } }; ButtonObject.prototype.GetValue = function() { if(this.owner != null) { return this.owner.GetValue(); } }; ButtonObject.prototype.GetImage = function(imageIndex) { return this.currentState.images[ imageIndex ]; }; ButtonObject.prototype.ShowImage = function(imageIndex) { var image = this.GetImage(imageIndex); if(this.currentImage == image) return; if(this.currentImage != null) { ShowObject(this.currentImage, false); } this.currentImage = image; this.currentImageIndex = imageIndex; ShowObject(this.currentImage, true); }; ButtonObject.prototype.OnMouseDown = function() { if (!this.enabled) return; this.mouseDown = true; //this.ShowImage( DownImageIndex ); }; var g_useTryCatchOnButtonClick = true; ButtonObject.prototype.CallOnClick = function () { if (!this.enabled) return; if (this.OnClick != null) { if (g_useTryCatchOnButtonClick) { try { this.OnClick(this.uiObject); } catch (e) { ShowErrorMessageBox(e); console.error(e); } } else { this.OnClick(this.uiObject); } } } ButtonObject.prototype.OnMouseUp = function() { if (!this.enabled) return; if (!this.mouseDown) return; this.mouseDown = false; this.CallOnClick(); this.ShowImage(this.mouseIsOver ? RollOverImageIndex : NormalImageIndex); }; ButtonObject.prototype.OnMouseOver = function() { if (!this.enabled) return; this.mouseIsOver = true; this.ShowImage( RollOverImageIndex ); }; ButtonObject.prototype.OnMouseOut = function() { if (!this.enabled) return; this.mouseIsOver = false; this.ShowImage( NormalImageIndex ); }; ButtonObject.prototype.SetState = function(stateIndex) { this.currentState = this.states[stateIndex]; this.ShowImage( this.currentImageIndex ); }; function FlowButtonObject(name, disableTouchPreventDefault) { this.name = name; this.mouseIsOver = false; this.OnClick = null; this.enabled = true; this.mouseWasDown = false; var uiObject = typeof(name) == 'string' ? document.getElementById(name) : name; this.uiObject = uiObject; if (uiObject.dataset.controltemplate) { LoadTemplate(uiObject.dataset.controltemplate, uiObject, this); if(uiObject.dataset.controltext) { SetControlText(uiObject, uiObject.dataset.controltext); } } var self = this; var clickArea = uiObject.querySelector(".cdClickArea"); if (clickArea == null) clickArea = uiObject; clickArea.classList.add("buttonClickArea"); clickArea.addEventListener("touchstart", function (e) { if(!disableTouchPreventDefault) { e.preventDefault(); } self.mobile = true; self.OnMouseDown(); }); clickArea.addEventListener("touchend", function (e) { if(!disableTouchPreventDefault) { e.preventDefault(); } self.mobile = true; self.OnMouseUp(); }); clickArea.addEventListener("mousedown", function (e) { if(!self.mobile) self.OnMouseDown(); else self.mobile = false; }); clickArea.addEventListener("mouseup", function (e) { if(!self.mobile) self.OnMouseUp(); else self.mobile = false; }); clickArea.parentElement.addEventListener("keydown", function (e) { if(e.keyCode ==13) { self.OnMouseDown(); self.OnMouseUp(); } }); clickArea.addEventListener("touchmove", function(e) { self.OnTouchMove() }); var parentNodeOfButton = uiObject.parentNode; var parentTabIndex = parentNodeOfButton.getAttribute("tabindex"); if (parentTabIndex) { uiObject.setAttribute("tabindex", parentTabIndex); parentNodeOfButton.removeAttribute("tabindex"); } var parentRole = parentNodeOfButton.getAttribute("role"); if (parentRole) { uiObject.setAttribute("role", parentRole); parentNodeOfButton.removeAttribute("role"); } var parentAriaLabel = parentNodeOfButton.getAttribute("aria-label"); if (parentAriaLabel) { uiObject.setAttribute("aria-label", parentAriaLabel); parentNodeOfButton.removeAttribute("aria-label"); } var parentAriaLabelledBy = parentNodeOfButton.getAttribute("aria-labelledby"); if (parentAriaLabelledBy) { uiObject.setAttribute("aria-labelledby", parentAriaLabelledBy); parentNodeOfButton.removeAttribute("aria-labelledby"); } var parentAriaDescribedBy = parentNodeOfButton.getAttribute("aria-describedby"); if (parentAriaDescribedBy) { uiObject.setAttribute("aria-describedby", parentAriaDescribedBy); parentNodeOfButton.removeAttribute("aria-describedby"); } } FlowButtonObject.prototype.Reset = function () { } FlowButtonObject.prototype.Show = function(doShow) { ShowObject(this.uiObject.parentElement, doShow == null ? true : doshow); } FlowButtonObject.prototype.Hide = function() { this.Show(false); } FlowButtonObject.prototype.Enable = function () { this.enabled = true; var container = this.owner == null ? this.uiObject : this.owner.GetObject(); container.style.opacity = 1; container.style.cursor = "pointer"; } FlowButtonObject.prototype.Disable = function () { this.enabled = false; var container = this.owner == null ? this.uiObject : this.owner.GetObject(); container.style.opacity = 0.5; container.style.cursor = "not-allowed"; } FlowButtonObject.prototype.SetValue = function(value) { if(this.owner != null) { this.owner.SetValue(value); } } FlowButtonObject.prototype.GetValue = function() { if(this.owner != null) { return this.owner.GetValue(); } } FlowButtonObject.prototype.OnMouseDown = function () { if (!this.enabled) return; this.mouseWasDown = true; } FlowButtonObject.prototype.CallOnClick = function () { if (!this.enabled) return; if (this.OnClick != null) { if (g_useTryCatchOnButtonClick) { try { this.OnClick(this.uiObject); } catch (e) { ShowErrorMessageBox(e); console.error(e); } } else { this.OnClick(this.uiObject); } } } FlowButtonObject.prototype.OnMouseUp = function () { if (!this.enabled) return; if (!this.mouseWasDown) return; this.mouseWasDown = false; this.CallOnClick(); } FlowButtonObject.prototype.OnTouchMove = function() { this.mouseWasDown = false; } FlowButtonObject.prototype.GetObject = function () { return this.uiObject; } FlowButtonObject.prototype.OnMouseOver = function () { this.mouseIsOver = true; if (!this.enabled) return; } FlowButtonObject.prototype.OnMouseOut = function () { this.mouseIsOver = false; if (!this.enabled) return; } FlowButtonObject.prototype.SetState = function (stateIndex) { if (this.onStateIndex != undefined && this.onStateIndex == stateIndex) { this.uiObject.classList.add("contextSelected"); } else if(this.offStateIndex != undefined && this.offStateIndex == stateIndex) { this.uiObject.classList.remove("contextSelected"); } } FlowButtonObject.prototype.UpdateState = function() {} FlowButtonObject.prototype.GetFieldKind = function() { return FieldKind.Button; } function CheckBoxOnClick() { if (!this.enabled) return; var divCheckbox = document.getElementById(this.name).parentNode; var newValue; if (this.isOn) { newValue = this.offStateValue; divCheckbox.setAttribute("aria-checked", "false"); } else { newValue = this.onStateValue; divCheckbox.setAttribute("aria-checked", "true"); } this.SetValue(newValue); } function CheckBoxFieldKind() { return FieldKind.CheckBox; } function ControlIsChecked() { return this.isOn; } function CheckBoxUpdateState(value) { if(this.onStateValue == value) { this.required = false; this.isOn = true; this.SetState(this.onStateIndex); } else { this.required = true; this.isOn = false; this.SetState(this.offStateIndex); } } function CheckBoxIsRequired() { return this.required; } function KeyCheckBox(event) { const KEYCODE = { SPACE: 32 } const type = event.type; let next = false; if (type === "keydown") { const divCheckBox = event.currentTarget; const checkBox = divCheckBox.checkBox; switch (event.keyCode) { case KEYCODE.SPACE: next = checkBox; break; } if (next) { next.CallOnClick(); event.preventDefault(); event.stopPropagation(); } } } function CreateButtonObject(name, statesCount, initialStateIndex, attachToParent) { var buttonElement = document.getElementById(name); if (buttonElement.dataset.controltemplate) { return new FlowButtonObject(name); } else { return new ButtonObject(name, statesCount, initialStateIndex, attachToParent); } } function CreateCheckBox(name, fieldID, initialStateIndex, onStateIndex, onStateValue, offStateIndex, offStateValue) { var checkBox = CreateButtonObject(name, 2, initialStateIndex, true); checkBox.onStateIndex = onStateIndex; checkBox.offStateIndex = offStateIndex; checkBox.onStateValue = onStateValue; checkBox.offStateValue = offStateValue; checkBox.OnClick = CheckBoxOnClick; checkBox.UpdateState = CheckBoxUpdateState; checkBox.IsChecked = ControlIsChecked; checkBox.IsRequired = CheckBoxIsRequired; checkBox.required = initialStateIndex == offStateIndex; checkBox.isOn = initialStateIndex == onStateIndex; checkBox.GetFieldKind = CheckBoxFieldKind; _fields[fieldID] = checkBox; const divCheckBox = document.getElementById(checkBox.name).parentNode; const parentParentCheckBox = divCheckBox.parentNode; divCheckBox.parentElement.classList.add("cd-check-box"); divCheckBox.onfocus = ()=>{ divCheckBox.parentElement.classList.add("cd-check-box-focus"); } divCheckBox.onblur = () =>{ divCheckBox.parentElement.classList.remove("cd-check-box-focus"); } if (IsItInAccessibilityMode(parentParentCheckBox, "checkbox")) { divCheckBox.setAttribute("tabindex", parentParentCheckBox.getAttribute("tabindex")); parentParentCheckBox.removeAttribute("tabindex"); divCheckBox.setAttribute("role", parentParentCheckBox.getAttribute("role")); parentParentCheckBox.removeAttribute("role"); var parentAriaDescribedBy = parentParentCheckBox.getAttribute("aria-describedby"); if (parentAriaDescribedBy) { divCheckBox.setAttribute("aria-describedby", parentAriaDescribedBy); parentParentCheckBox.removeAttribute("aria-describedby"); } var parentAriaLabelledBy = parentParentCheckBox.getAttribute("aria-labelledby"); if (parentAriaLabelledBy) { divCheckBox.setAttribute("aria-labelledby", parentAriaLabelledBy); parentParentCheckBox.removeAttribute("aria-labelledby"); } var parentAriaLabel = parentParentCheckBox.getAttribute("aria-label"); if (parentAriaLabel) { divCheckBox.setAttribute("aria-label", parentAriaLabel); parentParentCheckBox.removeAttribute("aria-label"); } var ariaRequired = divCheckBox.getAttribute("aria-required"); if (ariaRequired) { divCheckBox.parentNode.setAttribute("aria-required", ariaRequired); divCheckBox.removeAttribute("aria-required"); } } divCheckBox.setAttribute("aria-checked", checkBox.isOn ? "true" : "false"); divCheckBox.checkBox = checkBox; divCheckBox.addEventListener('keydown', KeyCheckBox); checkBox.SetState(initialStateIndex); checkBox.inType = "checkbox"; return checkBox; } function RadioGroup(fieldID) { this.radioButtons = new Array(); this.selectedRadioButton = null; this.fieldObject = new InputFieldObject(fieldID); this.defaultRadioButton = null; this.eventChanged = new EventHandlers(this); this.updateValueCall = false; this.updateStateCall = false; _fields[fieldID] = this; var self = this; this.eventChanged.AddHandler(function () { self.UpdateButtonFields(); }); } RadioGroup.prototype.GetFieldKind = function() { return FieldKind.RadioGroup; } RadioGroup.prototype.UpdateButtonFields = function() { for (var i = 0; i < this.radioButtons.length; ++i) { this.radioButtons[i].UpdateFieldStatus(); } } RadioGroup.prototype.SetRequired = function(value) { for(let radioButton of this.radioButtons) { radioButton.owner.SetRequired(value); } } RadioGroup.prototype.SelectButton = function(radioButton) { if(this.selectedRadioButton == radioButton) return; if(this.selectedRadioButton != null) { if (radioButton && this.selectedRadioButton.value == radioButton.value) { radioButton.Select(true); return; } this.selectedRadioButton.Select(false); } this.selectedRadioButton = radioButton; if (this.selectedRadioButton != null) { this.selectedRadioButton.Select(true); } else { this.UpdateValue(""); } }; RadioGroup.prototype.Select = function(radioButton) { this.UpdateValue(radioButton.value); this.SelectButton( radioButton ); this.eventChanged.Fire(); }; RadioGroup.prototype.SetValueInternal = function(value) { this.SelectButton(null); for(var i = 0; i < this.radioButtons.length; ++i) { if(this.radioButtons[i].value == value) { this.Select(this.radioButtons[i]); return; } } this.eventChanged.Fire(); } RadioGroup.prototype.SetValue = function(value) { if(this.radioButtons.length == 0) { // buttons are not initialized yet window.setTimeout(()=>{ this.SetValueInternal(value)}, 0); } else { this.SetValueInternal(value); } }; RadioGroup.prototype.UpdateState = function(value) { if(this.updateValueCall) return; this.updateStateCall = true; this.SetValue(value); this.updateStateCall = false; } RadioGroup.prototype.GetValue = function() { return this.fieldObject.GetValue(); }; RadioGroup.prototype.SetDefault = function(radioButton) { this.defaultRadioButton = radioButton; this.SelectButton(radioButton); this.fieldObject.SetValue( radioButton.value ); this.eventChanged.Fire(); }; RadioGroup.prototype.Reset = function() { this.SelectButton( null ); if(this.defaultRadioButton != null) { this.SelectButton(this.defaultRadioButton); } this.fieldObject.SetValue( this.selectedButton == null ? "" : this.selectedButton.value ); this.eventChanged.Fire(); }; RadioGroup.prototype.Enable = function () { for (var i = 0; i < this.radioButtons.length; ++i) { this.radioButtons[i].enabled = true; this.radioButtons[i].UpdateFieldStatus(); } if (this.radioButtons.length > 0) { const fisrtBtnHTMLNode = document.getElementById(this.radioButtons[0].name); fisrtBtnHTMLNode.parentNode.parentNode.parentNode.setAttribute("aria-disabled", "false"); } }; RadioGroup.prototype.Disable = function () { for (var i = 0; i < this.radioButtons.length; ++i) { this.radioButtons[i].enabled = false; this.radioButtons[i].UpdateFieldStatus(); } if (this.radioButtons.length > 0) { const fisrtBtnHTMLNode = document.getElementById(this.radioButtons[0].name); fisrtBtnHTMLNode.parentNode.parentNode.parentNode.setAttribute("aria-disabled", "true"); } }; RadioGroup.prototype.UpdateValue = function(value) { if(this.updateStateCall) return; this.updateValueCall = true; if(this.owner != null) { this.owner.SetValue(value); } else { this.fieldObject.SetValue(value); } this.updateValueCall = false; } function RadioButtonClick() { this.radioGroup.Select(this); } function RadioButtonIsChecked() { return this.isOn; } function RadioButtonFieldKind() { return FieldKind.RadioButton; } function IsItInAccessibilityMode(node, targetRole) { let result = false; if (node.hasAttribute("role") && node.getAttribute("role") === targetRole) { result = true; } return result; } function RadioButtonSelect(on) { const divRadioButton = document.getElementById(this.name); this.selectCall = true; if (on) { this.isOn = true; this.SetValue("on"); if (IsItInAccessibilityMode(divRadioButton.parentNode, "radio")) { for (let idxButton = 0; idxButton < this.radioGroup.radioButtons.length; ++idxButton) { const currButton = this.radioGroup.radioButtons[idxButton]; const currHTMLNode = document.getElementById(currButton.name); if (currButton.name === this.name) { currHTMLNode.parentNode.setAttribute("aria-checked", "true"); currHTMLNode.parentNode.setAttribute("tabindex", "0"); currHTMLNode.parentNode.focus(); } else { currHTMLNode.parentNode.setAttribute("aria-checked", "false"); currHTMLNode.parentNode.setAttribute("tabindex", "-1"); } } } } else { this.isOn = false; this.SetValue("off"); } this.selectCall = false; } function RadioButtonUpdateState(value) { if(value == "on") { this.isOn = true; this.SetState(this.onStateIndex); if(!this.selectCall) { this.radioGroup.SelectButton(this); } } else { this.isOn = false; this.SetState(this.offStateIndex); } } function RadioButtonIsRequired() { return this.radioGroup.GetValue() == "" && this.enabled; } function RadioButtonUpdateFieldStatus() { if(this.owner != null && this.owner.isRequired) { this.owner.UpdateStatus(); } } function KeyDownRadioGroup(event) { const KEYCODE = { DOWN: 40, LEFT: 37, RIGHT: 39, SPACE: 32, UP: 38 } const type = event.type; let next = false; console.log(event); if (type === "keydown") { const divRadioButton = event.currentTarget.htmlRadioButton; const radioButton = divRadioButton.radioButton; const radioGroup = radioButton.radioGroup; const radioButtons = radioButton.radioGroup.radioButtons; switch (event.keyCode) { case KEYCODE.DOWN: case KEYCODE.RIGHT: if (!radioGroup.selectedRadioButton) { next = radioButton; } else if (divRadioButton.grpIdx + 1 === radioButtons.length) { next = radioButtons[0]; } else { next = radioButtons[divRadioButton.grpIdx + 1]; } break; case KEYCODE.UP: case KEYCODE.LEFT: if (!radioGroup.selectedRadioButton) { next = radioButton; } else if (divRadioButton.grpIdx - 1 < 0) { next = radioButtons[radioButtons.length - 1]; } else { next = radioButtons[divRadioButton.grpIdx - 1]; } break; case KEYCODE.SPACE: next = radioButton; break; } if (next) { console.log("call on click"); next.CallOnClick(); event.preventDefault(); event.stopPropagation(); } } } function CreateRadioButton(name, radioGroupID, initialStateIndex, onStateIndex, offStateIndex, value, selected) { var radioButton = CreateButtonObject(name, 2, initialStateIndex, true); radioButton.onStateIndex = onStateIndex; radioButton.offStateIndex = offStateIndex; radioButton.value = value; radioButton.radioGroup = _radioGroups[ radioGroupID ]; radioButton.OnClick = RadioButtonClick; radioButton.radioGroup.radioButtons.push( radioButton ); radioButton.Select = RadioButtonSelect; radioButton.IsChecked = RadioButtonIsChecked; radioButton.UpdateState = RadioButtonUpdateState; radioButton.IsRequired = RadioButtonIsRequired; radioButton.UpdateFieldStatus = RadioButtonUpdateFieldStatus; radioButton.isOn = false; radioButton.GetFieldKind = RadioButtonFieldKind; const divRadioButton = document.getElementById(radioButton.name); const parentParentRadioButton = divRadioButton.parentNode.parentNode; divRadioButton.parentNode.htmlRadioButton = divRadioButton; divRadioButton.parentElement.parentElement.classList.add("cd-radio-button"); divRadioButton.parentElement.onfocus = ()=>{ var radioGroupContainer = divRadioButton.closest("[role='radiogroup']"); if(radioGroupContainer) radioGroupContainer.classList.add("cd-radio-group-focus"); divRadioButton.parentElement.parentElement.classList.add("cd-radio-button-focus"); } divRadioButton.parentElement.onblur = () =>{ var radioGroupContainer = divRadioButton.closest("[role='radiogroup']"); if(radioGroupContainer) radioGroupContainer.classList.remove("cd-radio-group-focus"); divRadioButton.parentElement.parentElement.classList.remove("cd-radio-button-focus"); } if (IsItInAccessibilityMode(parentParentRadioButton, "radio")) { divRadioButton.parentNode.setAttribute("tabindex", parentParentRadioButton.getAttribute("tabindex")); parentParentRadioButton.removeAttribute("tabindex"); divRadioButton.parentNode.setAttribute("role", parentParentRadioButton.getAttribute("role")); parentParentRadioButton.removeAttribute("role"); divRadioButton.parentNode.setAttribute("aria-checked", "false"); var ariaDescribedBy = parentParentRadioButton.getAttribute("aria-describedby"); if (ariaDescribedBy) { divRadioButton.parentNode.setAttribute("aria-describedby", ariaDescribedBy); parentParentRadioButton.removeAttribute("aria-describedby"); } var ariaLabel = parentParentRadioButton.getAttribute("aria-label"); if (ariaLabel) { divRadioButton.parentNode.setAttribute("aria-label", ariaLabel); parentParentRadioButton.removeAttribute("aria-label"); } var ariaLabelledBy = parentParentRadioButton.getAttribute("aria-labelledby"); if (ariaLabelledBy) { divRadioButton.parentNode.setAttribute("aria-labelledby", ariaLabelledBy); parentParentRadioButton.removeAttribute("aria-labelledby"); } var ariaRequired = divRadioButton.getAttribute("aria-required"); if (ariaRequired) { divRadioButton.parentNode.setAttribute("aria-required", ariaRequired); divRadioButton.removeAttribute("aria-required"); } } if (IsItInAccessibilityMode(divRadioButton.parentNode, "radio")) { divRadioButton.radioButton = radioButton; divRadioButton.grpIdx = radioButton.radioGroup.radioButtons.length - 1; divRadioButton.parentNode.addEventListener('keydown', KeyDownRadioGroup); } if (selected) { if (IsItInAccessibilityMode(divRadioButton.parentNode, "radio")) { divRadioButton.parentNode.setAttribute("aria-checked", "true"); divRadioButton.parentNode.setAttribute("tabindex", "0"); } radioButton.radioGroup.SetDefault(radioButton); radioButton.SetState(onStateIndex); } radioButton.inType = "radioButton"; return radioButton; } function AnimationObject(name, framesCount) { this.name = name; this.frames = new Array(); this.currentFrame = 0; for(var i = 0; i < framesCount; ++i) { this.frames.push( document.getElementById(name + "_Frame" + i) ); } this.playParameters = null; } AnimationObject.prototype.ShowFrame = function(frameIndex, show) { ShowObject(this.frames[frameIndex], show); }; AnimationObject.prototype.PlayNextFrame = function() { this.ShowFrame(this.playParameters.currentFrame, false); this.playParameters.currentFrame++; this.ShowFrame(this.playParameters.currentFrame, true); this.currentFrame = this.playParameters.currentFrame; if (this.playParameters.currentFrame == this.frames.length - 1) { window.clearInterval( this.playParameters.interval ); } }; AnimationObject.prototype.Play = function() { this.playParameters = new Object(); this.playParameters.currentFrame = 0; this.ShowFrame(this.currentFrame, false); this.currentFrame = 0; this.ShowFrame(this.currentFrame, true); this.playParameters.interval = window.setInterval(this.PlayFrame , 40 ); }; function DispatchEvent(documentElement, eventName) { if(typeof(CustomEvent) == 'function') { documentElement.dispatchEvent(new CustomEvent(eventName)); return; } var event = document.createEvent("CustomEvent"); event.initEvent(eventName, true, true); documentElement.dispatchEvent(event); } function InputFieldObject(fieldId) { this.fieldId = fieldId; } InputFieldObject.prototype.SetValue = function(value) { var fieldObject = document.getElementById(this.fieldId); fieldObject.value = value; DispatchEvent(fieldObject, "change"); }; InputFieldObject.prototype.GetValue = function() { return document.getElementById(this.fieldId).value; }; InputFieldObject.prototype.Reset = function() {}; function AddMultilineField(fieldID, divID) { var multilineField = new Object(); multilineField.fieldID = fieldID; multilineField.divID = divID; _multilineFields.push(multilineField); } function GetElementText(element) { var textParts = new Array(); var elementChild = element.firstChild; while (elementChild != null) { switch(elementChild.nodeName.toLowerCase()) { case "div": case "br": case "p": textParts.push("\r\n"); break; } textParts.push(elementChild.textContent); elementChild = elementChild.nextSibling; } return textParts.join(""); } function PopulateMultilineFields() { for (var i = 0; i < _multilineFields.length; ++i) { var multilineField = _multilineFields[i]; document.getElementById(multilineField.fieldID).value = GetElementText(document.getElementById(multilineField.divID)); } } function PopulateDisplayState() { var stateArray = new Array(); for(var name in _displayState) { stateArray.push(name); stateArray.push(_displayState[name] == true ? "1" : "0"); } DocumentForm.GetField("_DisplayState_").SetValue(stateArray.join(",")); } function SubmitData(submitID, url) { if(submitID != null && submitID.charAt(0) == '/') { this.url = submitID; this.submitID = "call"; } else { this.url = url; this.submitID = submitID; } this.buildFinal = false; this.closeForm = true; } function GetUrlID() { var locationParts = window.location.href.split("/"); return locationParts[locationParts.length - 1]; } function CompleteForm() { PopulateDisplayState(); PopulateMultilineFields(); document.getElementById("__FieldNames__").value = _fieldNames.join(";"); SetFieldValue("__SubmissionDate__", new Date().toLocaleString('en-GB')); SetFieldValue("__SubmissionDateUTC__", new Date().toISOString()); SetFieldValue("_UrlID_", GetUrlID()); SetFieldValue("__JsErrors__", JSON.stringify(__jsErrors__)); } function SubmitForm(submitData, target, sendWithAjax, reqHandler, opts) { opts = opts || {}; if(typeof(opts) == 'function') { opts = { invalidFieldsHandler : opts }; } if (typeof g_recaptchaV2 !== 'undefined') { if ((submitData.submitID != "saveForm") && (! g_recaptchaV2.IsValid())) { ShowErrorMessageBox(userDefinedMessages["Information.RecaptchaV2Fail"]); return; } } CompleteForm(); var url = null; if (typeof (submitData) == "object") { url = submitData.url; } else { url = submitData; submitData = new SubmitData(); } if (url == null || url == "") { url = g_submitFormURL ? g_submitFormURL : g_IPDFAgentURL +"/SendToService.aspx"; } if (_formSubmitted) { ShowErrorMessageBox(userDefinedMessages["Information.FormAlreadySubmitted"]); return; } if (sendWithAjax == undefined) { sendWithAjax = false; } if(!opts.ignoreValidation) { var invalidFieldsHandler = opts.invalidFieldsHandler; if (typeof (invalidFieldsHandler) == "undefined" || invalidFieldsHandler == null) { invalidFieldsHandler = GetInvalidFieldsHandler(InvalidFieldsHandlerContext.Submit); } _currentPage.Validate(); _currentPage.ARIAValidation(); if (invalidFieldsHandler) { if (!invalidFieldsHandler()) { return; } } } SetFieldValue("__SubmitID__", submitData.submitID); SetFieldValue("__BuildFinal__", submitData.buildFinal ? "1" : "0"); var formObject = document.getElementById( FormID ); if (UseAjaxOnFormSubmitting || sendWithAjax || submitData.resetFormAfterSubmit) { var newUrl = url + window.location.search; SubmitFormWithAjax(formObject, newUrl, reqHandler, submitData.closeForm, opts); } else { formObject.action = url; formObject.method = "POST"; formObject.target = target == null ? "_blank" : target; formObject.submit(); } } function SaveForm(url, closeForm, failMessage, opts) { opts = $.extend(opts || {}, { invalidFieldsHandler: function () { return true; } }); var submitData = new SubmitData("saveForm", url); submitData.closeForm = closeForm; SubmitForm(submitData, null, true, function (success, message) { if (success) { if (closeForm) { window.close(); } } else { if (failMessage && failMessage != "") { message = failMessage + ". (" + message + ")"; } ShowErrorMessageBox(message); } }, opts ); } function SubmitFormWithAjax(formObject, url, reqHandler, closeForm, opts) { opts = opts || {}; var formData = new FormData(formObject); var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 1) { if (!xmlHttp.dialogShown) { ShowBusyBoard(); xmlHttp.dialogShown = true; } } else if (xmlHttp.readyState === 4) { HideBusyBoard(); if (xmlHttp.status === 200) { var result = ParseResult(xmlHttp.responseText); if (opts.onSuccessEventHandler) { opts.onSuccessEventHandler(); } if (reqHandler == undefined) { ShowInfoMessageBox(result); } else { reqHandler(true, result); } if (closeForm) { _formSubmitted = true; } } else if (xmlHttp.status === 0) { var msg = userDefinedMessages["SubmitForm.ServerCommunicationError"]; if (reqHandler == undefined) { ShowErrorMessageBox(msg); } else { reqHandler(false, msg); } if (opts.onFailureEventHandler) { opts.onFailureEventHandler(msg); } } else { var msg = userDefinedMessages["SubmitForm.ResponseErrorDetails"];// + xmlHttp.statusText; if (g_addResponseErrorDetails) { msg += ParseResult(xmlHttp.responseText); } if (reqHandler == undefined) { ShowErrorMessageBox(msg); } else { reqHandler(false, msg); } if (opts.onFailureEventHandler) { opts.onFailureEventHandler(msg); } } } }; xmlHttp.open("post", url); xmlHttp.send(formData); } function ParseResult(html) { var parser = new DOMParser(); var htmlDoc = parser.parseFromString(html, "text/html"); var elementTypes = ["span", "p", "body"]; for (var i = 0; i < elementTypes.length; i++) { var elementType = elementTypes[i]; var elements = htmlDoc.getElementsByTagName(elementType); if (elements.length > 0) { return elements[0].innerHTML; } } return html; } function GetFieldId(fieldIndex) { if(fieldIndex == -1) return null; return "_fd" + fieldIndex; } function GetFieldIndex(fieldName) { for(var i = 0; i < _fieldNames.length; ++i) { if(_fieldNames[i] == fieldName) return i; } return -1; } function GetField(fieldName) { var fieldId = GetFieldId( GetFieldIndex(fieldName) ); if(fieldId == null) return null; var fieldObject = _fields[fieldId]; if(typeof(fieldObject) == "undefined") { fieldObject = new InputFieldObject( fieldId ); _fields[fieldId] = fieldObject; } return fieldObject; } function SetFieldValue(fieldName, value) { GetField(fieldName).SetValue( value ); } function GetFieldValue(fieldName) { return GetField(fieldName).GetValue(); } function ResetForm() { window.location.reload(); } function ValidateForm() { } function ValidateSignatures() { for (var signatureName in _signatures) { var signature = _signatures[signatureName]; if (signature.isRequired && !signature.GetValue()) { ShowErrorMessageBox(userDefinedMessages["Validations.SignatureRequiredErrorMessage"], function() { signature.image.scrollIntoView(); }); return false; } } return true; } function DateUtilsDateAccessor(dateObject, doNotTrimDate) { this.dateObject = doNotTrimDate ? dateObject : new Date(dateObject.getFullYear(), dateObject.getMonth(), dateObject.getDate()); this.month = -1; this.date = -1; this.year = -1; } DateUtilsDateAccessor.prototype = { y : function() { return this.dateObject.getFullYear(); }, Y : function() { return this.dateObject.getFullYear(); }, D : function() { return this.dateObject.getDate(); }, d : function() { return this.dateObject.getDate(); }, M : function() { return this.dateObject.getMonth() + 1; }, m : function() { return this.dateObject.getMonth() + 1; }, s : function() { return this.dateObject.getSeconds(); }, H : function() { return this.dateObject.getHours(); }, h : function() { return this.dateObject.getHours(); }, n : function() { return this.dateObject.getMinutes(); }, N : function() { return this.dateObject.getMinutes(); }, sety : function(value) { if(value < 100) { value += 2000; } this.year = value; //this.dateObject.setFullYear(value) }, setY : function(value) { this.sety(value); }, setd : function(value) { this.setD(value); }, setD: function (value) { //his.dateObject.setDate(value); this.date = value; }, setM : function(value) { this.month = value - 1; }, setm : function(value) { this.setM(value); }, setn : function(value) { this.dateObject.setMinutes(value); }, setN : function(value) { this.setn(value); }, sets : function(value) { this.dateObject.setSeconds(value); }, setH : function(value) { this.dateObject.setHours(value); }, seth : function(value) { this.dateObject.setHours(value); }, update : function() { /* if(this.year != -1) this.dateObject.setFullYear(this.year); if(this.date != -1) this.dateObject.setDate(this.date); // has to be before month because not all months have the same number of days if(this.month != -1) this.dateObject.setMonth(this.month); */ this.dateObject = new Date(this.year == -1 ? this.dateObject.getFullYear() : this.year, this.month == -1 ? this.dateObject.getMonth() : this.month, this.date == -1 ? this.dateObject.getDate() : this.date, this.dateObject.getHours(), this.dateObject.getMinutes(), this.dateObject.getSeconds()); } }; function DateUtilsDateStringAccessor(dateString) { this.dateString = dateString; this.currentSymbolIndex = 0; } DateUtilsDateStringAccessor.prototype = { GetNextSymbol : function() { if(this.currentSymbolIndex < this.dateString.length) { return this.dateString.charAt(this.currentSymbolIndex++); } else { throw ""; } }, GetNumber : function(length) { if(this.currentSymbolIndex + length > this.dateString.length) { throw ""; } var numberString = this.dateString.substr(this.currentSymbolIndex, length); this.currentSymbolIndex += length; var result = parseInt(numberString); if(isNaN(result)) { throw ""; } return result; }, } var StaticDateAccessor = new DateUtilsDateAccessor(new Date()); function DateUtilsClass() { } DateUtilsClass.prototype = { IsDateSymbol : function(symbol) { return StaticDateAccessor[symbol] != null; }, ClearTime : function(date) { return new Date(date.getFullYear(), date.getMonth(), date.getDate()); }, FormatDatePart : function(value, length) { var result = value.toString(); while(length > result.length) { result = "0" + result; } return result; }, SplitDateFormat : function(format) { var formatPart = null; var parts = new Array(); for(var i = 0; i < format.length; ++i) { var charSymbol = format.charAt(i); if(formatPart == null || formatPart.symbol != charSymbol) { formatPart = { symbol : charSymbol, length : 1}; parts.push( formatPart ); } else { ++formatPart.length; } } return parts; }, FormatDate : function(date, format, doNotTrimDate) { var formatParts = this.SplitDateFormat(format); var result = ""; var dateAccessor = new DateUtilsDateAccessor(date, doNotTrimDate); for(var i = 0; i < formatParts.length; ++i) { var formatPart = formatParts[i]; if(dateAccessor[formatPart.symbol] == null) { for(var j = 0; j < formatPart.length; ++j) { result += formatPart.symbol; } } else { result += this.FormatDatePart(dateAccessor[formatPart.symbol](), formatPart.length); } } return result; }, ParseDate : function(dateString, format) { var formatParts = this.SplitDateFormat(format); var dateSymbolIndex = 0; var dateStringAccessor = new DateUtilsDateStringAccessor(dateString); var dateAccessor = new DateUtilsDateAccessor(new Date()); try { for(var i = 0; i < formatParts.length; ++i) { var formatPart = formatParts[i]; if(dateAccessor["set" + formatPart.symbol] == null) { for(var j = 0; j < formatPart.length; ++j) { if(dateStringAccessor.GetNextSymbol() != formatPart.symbol) { return null; } } } else { dateAccessor["set" + formatPart.symbol]( dateStringAccessor.GetNumber(formatPart.length) ); } } dateAccessor.update(); if(this.FormatDate(dateAccessor.dateObject, format) != dateString) { return null; } return dateAccessor.dateObject; } catch(e) { return null; } }, ReformatDate : function(dateString, inputFormat, outputFormat) { return this.FormatDate( this.ParseDate(dateString, inputFormat), outputFormat ); } } var DateUtils = new DateUtilsClass(); function DateManipulatorClass(input) { var date = input || new Date(); this.year = date.getFullYear(); this.month = date.getMonth(); this.date = date.getDate(); } DateManipulatorClass.prototype = { maxMonthDays : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], isManipulator : true, firstWeekDayIsMonday : false, add_y : function(unit) { this.year += unit; }, add_m : function(months) { var years = months < 0 ? Math.ceil(months/12) : Math.floor(months/12); var actualMontsh = months % 12; this.month += months % 12; if(this.month < 0) { this.month = 12 + this.month; --years; } else if(this.month > 11) { this.month = this.month - 12; ++years; } this.add_y(years); }, add_d : function(days) { var ms = days * 86400000; var date = new Date(this.year, this.month, this.date); var newDate = new Date(date.getTime() + ms); this.year = newDate.getFullYear(); this.month = newDate.getMonth(); this.date = newDate.getDate(); }, add_w : function(weeks) { this.add_d(weeks * 7); }, min_y : function() { return new Date(this.year, 0, 1); }, max_y : function() { return new Date(this.year, 11, 31); }, min_m : function() { return new Date(this.year, this.month, 1); }, max_m : function() { var maxDate = this.maxMonthDays[this.month]; if(this.month == 1 && this.isLeapYear()) maxDate = 29; return new Date(this.year, this.month, maxDate); }, call : function(mode, unitKey, defaultResult, unit) { var unitKey = unitKey.toLowerCase().substring(0, 1); if(this[mode + "_" + unitKey]) { return this[mode +"_" + unitKey](unit); } return defaultResult; }, isLeapYear : function() { return new Date(this.year, 1, 29).getDate() == 29; }, add : function(unit, unitKey) { this.call("add", unitKey, null, unit); return this; }, addYears(years) { return this.add(years, 'y'); }, addMonths(months) { return this.add(months, 'm'); }, addDays(days) { return this.add(days, 'd'); }, addWeeks(weeks) { return this.add(weeks, 'w'); }, toDate : function() { return new Date(this.year, this.month, this.date); }, startOf_y : function() { this.month = 0; this.date = 1; }, startOf_m : function() { this.date = 1; }, startOf_w : function() { var currentDate = this.toDate(); var day = currentDate.getDay(); if(this.firstWeekDayIsMonday) { --day; if(day < 0) day = 6; } this.addDays( -currentDate.getDay() ); }, startOf : function(unitKey) { this.call("startOf", unitKey); return this; }, endOf_y : function(unitKey) { this.month = 11; this.date = 31; }, endOf_m : function(unitKey) { this.date = this.maxMonthDays[this.month]; if(this.month == 1 && this.isLeapYear()) this.date = 29; }, endOf_w : function(unitKey) { var currentDate = this.toDate(); var day = currentDate.getDay(); if(this.firstWeekDayIsMonday) { --day; if(day < 0) day = 6; } this.addDays( 6-currentDate.getDay() ); }, endOf : function(unitKey) { this.call("endOf", unitKey); return this; }, toMinDate : function(key) { return this.call("min", key, this.toDate()); }, toMaxDate : function(key) { return this.call("max", key, this.toDate()); } } function DateManipulator(input) { return new DateManipulatorClass(input); } function ValidateDateValue(dateString, format) { var date = DateUtils.ParseDate(dateString, format.replace(/m/g, "M")); return { date: date == null ? new Date() : date, isOk : date != null}; } function ValidateDateField(field) { if(field.originalValidationMessage == null) { field.originalValidationMessage = field.validationMessage; } field.validationMessage = field.originalValidationMessage; var result = field.calendar ? field.calendar.ValidateValue(field.GetValue()) : ValidateDateValue(field.GetValue(), field.GetObject().dataset.dateformat); if(!result.isOk && result.validationMessage) { field.validationMessage = result.validationMessage; } field.currentDate = result.date; return result.isOk; } function OnMediaMatch(mediaMatch) { _viewChangeHandlers.OnViewChanged(); } function MediaView(owner, viewName, mediaQuery) { this.owner = owner; this.mediaMatch = window.matchMedia(mediaQuery); this.viewName = viewName; this.matched = this.mediaMatch.matches; this.mediaMatch.owner = this; this.mediaMatch.addListener(OnMediaMatch); } function ShowForm() { ShowElement("_form_", true); } function HideForm() { HideElement("_form_", false); } function ViewChangeHandlers() { this.handlers = new Array(); this.views = new Array(); this.currentView = ""; } ViewChangeHandlers.prototype.AddHandler = function (id, proc) { var handler = new Object(); handler.id = id; handler.function = proc; this.handlers.push(handler); } ViewChangeHandlers.prototype.OnViewActivated = function (viewName) { this.currentView = viewName; for(var i = 0; i < this.handlers.length; ++i) { var handler = this.handlers[i]; var documentElement = document.getElementById(handler.id); handler.function(documentElement, viewName); } if (_currentPage) { _currentPage.CheckForInvalidFields(); } } ViewChangeHandlers.prototype.AddView = function (viewName, mediaQuery) { this.views.push(new MediaView(this, viewName, mediaQuery)); } ViewChangeHandlers.prototype.OnViewChanged = function() { for (var i = 0; i < this.views.length; ++i) { var view = this.views[i]; if(view.mediaMatch.matches) { this.OnViewActivated(view.viewName); return; } } this.OnViewActivated(null); } function ConvertTextToHTML(text) { return text ? text.replace("\r\n", "
").replace("\n", "
") : ""; } function SetTargetText(container, selector, message) { if(typeof(container) == "string") { container = document.getElementById(container); } var textElement = container.querySelector(selector); if (textElement == null) return; var textRun = textElement.querySelector("p"); if(textRun != null) { textRun.innerHTML = ConvertTextToHTML(message); } } function SetControlText(container, message) { SetTargetText(container, ".cdControlText", message); } function SetMessageBoxText(container, message) { if (typeof (container) == "string") { container = document.getElementById(container); } if(container == null) return; var textElement = container.querySelector(".MessageBoxText"); if (textElement == null) textElement = container; var textRun = textElement.querySelector("p"); if(textRun != null) { textRun.innerHTML = ConvertTextToHTML(message); } } function SetElementText(container, message) { SetMessageBoxText(container, message); } function UpdateMessageBox(display, messageBoxID, message) { if (messageBoxID == "") return; if(!display) { HideElement(messageBoxID); return; } ShowElement(messageBoxID); if (message == "") return; var messageBoxElement = document.getElementById(messageBoxID); SetMessageBoxText(messageBoxElement, message); } function OTPHandler(element) { this.element = element; this.access = false; this.handleEvent = function (event) { if(!g_formInitialized) return; if (this.access) { return; } else { event.preventDefault(); this.owner.AskCredentials(event.target); } } element.addEventListener("click", this, true); element.addEventListener("focus", this, true); element.addEventListener("input", this, true); element.addEventListener("keydown", this, true); element.addEventListener("keypress", this, true); } function OTPInstance(name, matchURL, okResult) { this.name = name; this.matchURL = matchURL; this.handlers = new Array(); this.okResult = okResult; this.canBeRecreated = okResult.charAt(0) == 'R'; if(this.matchURL.charAt(this.matchURL.length - 1) != '/') { this.matchURL += "/"; } } OTPInstance.prototype.GrantAccess = function(value) { var otpInputField = DocumentForm.GetField("__OTPInput__"); var otpInputValue = otpInputField.GetValue(); if(otpInputValue != "") otpInputValue += ";"; otpInputValue += this.name + ":" + value; otpInputField.SetValue(otpInputValue); this.handlers.forEach(function(h) { h.access = true;}); } function OTPDialogHandler(otpInstance, targetElement) { this.otpInstance = otpInstance; this.otpInput = null; this.targetElement = targetElement; this.callInProgress = false; } OTPDialogHandler.prototype = { Init : function(dialogElement) { this.otpInput = dialogElement.querySelector("input[type=text]"); }, OnRecreate : function() { CreateDocumentFormField("__OTPTORECREATE__").SetValue(this.otpInstance.name); var self = this; CallComposeDocSystem("__RecreateOTP__", function(response) { if(response.status == "ok") { self.otpInstance.matchURL = response.value; ShowInfoMessageBox(userDefinedMessages.OtpWasRecreated); } }); }, OnOK : function() { if (this.otpInput == null) return; if(this.callInProgress) return; this.otpInput.readOnly = true; this.callInProgress = true; var otpInputValue = this.otpInput.value; var self = this; CallWebService(this.otpInstance.matchURL + otpInputValue, function() { if (this.status != 200) { this.onerror(); return; } if(this.responseText != self.otpInstance.okResult) { ShowErrorMessageBox("Invalid OTP Service"); self.Close(false); } else { self.otpInstance.GrantAccess(otpInputValue); self.Close(true); } }, function() { var alertMessage = this.statusText; if(this.status == 0) { alertMessage = "Cannot reach the OTP service"; } else if(this.status == 401) { alertMessage = "Value do not match"; } else if(this.status == 404) { alertMessage = "OTP has expired" } ShowErrorMessageBox(alertMessage); self.callInProgress = false; self.otpInput.readOnly = false; }); }, OnCancel: function () { if (this.callInProgress) return; this.Close(); }, OnClose : function() { CloseDialog(); }, Close : function(focusTarget) { if (this.OnClose) { this.OnClose(); } ShowForm(); if (focusTarget) { if (this.targetElement) { this.targetElement.focus(); this.targetElement.scrollIntoView(); } } }, CanRecreate : function() { return this.otpInstance.canBeRecreated; } }; OTPInstance.prototype.AskCredentialsDefault = function(targetElement, otpDialogHandler) { var otpDialog = document.createElement("div"); var titleElement = document.createElement("p"); var otpInput = document.createElement("input"); var buttonOK = document.createElement("button"); var buttonCancel = document.createElement("button"); var elementsHolder = otpDialog; var buttonsPanel = document.createElement("div"); var buttonRecreate = otpDialogHandler.CanRecreate() ? document.createElement("button") : null; elementsHolder.appendChild(titleElement); elementsHolder.appendChild(otpInput); elementsHolder.appendChild(buttonsPanel); buttonsPanel.appendChild(buttonOK); buttonsPanel.appendChild(buttonCancel); otpDialog.classList.add("otpDialog"); otpInput.classList.add("otpInput"); titleElement.classList.add("otpTitle"); buttonsPanel.classList.add("otpDialogButtonsPanel"); buttonOK.classList.add("otpOK"); buttonCancel.classList.add("otpCancel"); buttonOK.innerHTML = "OK"; buttonCancel.innerHTML = "Cancel"; titleElement.innerHTML = "Please enter " + this.name + " OTP:" otpInput.type = "text"; var self = this; otpDialogHandler.OnClose = function() { document.body.removeChild(otpDialog); } otpDialogHandler.otpInput = otpInput; buttonCancel.addEventListener("click", function() { otpDialogHandler.OnCancel(); }); buttonOK.addEventListener("click", function() { otpDialogHandler.OnOK(); }); if (buttonRecreate != null) { buttonsPanel.appendChild(buttonRecreate); buttonRecreate.innerHTML = "Recreate"; buttonRecreate.classList.add("otpRecreate"); buttonRecreate.addEventListener("click", function() { otpDialogHandler.OnRecreate() }); } document.body.appendChild(otpDialog); } OTPInstance.prototype.AskCredentials = function (targetElement) { var otpDialogHandler = new OTPDialogHandler(this, targetElement); if(!ShowDialog("cd_otpDialog", null, otpDialogHandler, function(dialogElement){ otpDialogHandler.Init(dialogElement); })) { this.AskCredentialsDefault(targetElement, otpDialogHandler); } HideForm(); } function OTPManager() { this.otpInstances = new Object(); } OTPManager.prototype.Add = function (name, matchURL, okResult, elementID) { var element = document.getElementById(elementID); var otpInstance = this.otpInstances[name]; if(!otpInstance) { otpInstance = new OTPInstance(name, matchURL, okResult); this.otpInstances[name] = otpInstance; } var handler = new OTPHandler(element); otpInstance.handlers.push(handler); handler.owner = otpInstance; } var _otpManager = new OTPManager(); app = window; function CallWebService(serviceURL, callBackOk, callBackError, data) { var request = new XMLHttpRequest(); request.callBackOk = callBackOk; request.onload = function () { if (this.responseText.indexOf("Error:") == 0) { ShowErrorMessageBox(this.responseText.substr(6)); this.onerror(); } else { this.callBackOk(); } } request.onerror = callBackError; if (data) { request.open("post", serviceURL, true); request.send(data); } else { request.open("get", serviceURL, true); request.send(); } } var g_cachedUserDataServiceResults = new Object(); function CachedUserdataServiceResult() { this.requestCompleted = false; this.requestHandlers = new Array(); this.failed = false; } CachedUserdataServiceResult.prototype = { OnRequestCompleted : function(request) { this.responseText = request.responseText; this.response = request.response; this.statusText = request.statusText; this.statusCode = request.statusCode; this.ProcessRequestHandlers(); }, OnRequestFailed : function(errorMessage) { this.failed = true; this.errorMessage = errorMessage; this.ProcessRequestHandlers(); }, ProcessRequestHandlers : function() { this.requestCompleted = true; for(var i = 0; i < this.requestHandlers.length; ++i) { var handler = this.requestHandlers[i]; this.ProcessHandler( handler.callBackOk, handler.callBackError ); } this.requestHandlers = null; }, ProcessHandler : function(callBackOk, callBackError) { if(!this.failed) { this.callBackOk = callBackOk; this.callBackOk(); this.callBackOk = null; } else if(callBackError) { this.callBackError = callBackError; this.callBackError(this.errorMessage); this.callBackError = null; } else { var timeNow = new Date(); var diff = this.lastErrorMessageCall == null ? 1000000 : timeNow.getTime() - this.lastErrorMessageCall.getTime(); if(diff > 2000) { ShowErrorMessageBox(this.errorMessage); this.lastErrorMessageCall = timeNow; } } }, ProcessCall : function(callBackOk, callBackError) { if(this.requestCompleted) { this.ProcessHandler(callBackOk, callBackError); } else { this.requestHandlers.push( {callBackOk : callBackOk, callBackError : callBackError }); } } } function CallUserDataServiceCached(ipdfAgentURL, requestType, data, callBackOk, callBackError) { var requestKey = requestType + JSON.stringify(data); var cachedResult = g_cachedUserDataServiceResults[requestKey]; if(cachedResult != null) { cachedResult.ProcessCall(callBackOk, callBackError); return; } cachedResult = new CachedUserdataServiceResult(); g_cachedUserDataServiceResults[requestKey] = cachedResult; CallUserDataService(ipdfAgentURL, requestType, data, function (){ cachedResult.OnRequestCompleted(this) }, function (errorMessage){ cachedResult.OnRequestFailed(errorMessage)} ); cachedResult.ProcessCall(callBackOk, callBackError); } function CallUserDataService(ipdfAgentURL, requestType, data, callBackOk, callBackError) { var request = new XMLHttpRequest(); request.isSuccessStatusCode = function () { return this.status >= 200 && this.status <= 299; } request.callBackOk = callBackOk; request.onerror = callBackError; request.onload = function () { if (!this.isSuccessStatusCode() || this.responseText.indexOf("Error:") == 0) { var errorMessage = this.responseText.indexOf("Error:") == 0 ? this.responseText.substr(6) : this.responseText || this.statusText; if (this.onerror != null) { this.onerror(errorMessage); } else { ShowErrorMessageBox(errorMessage); } } else { this.callBackOk(); } } request.open("post", ipdfAgentURL + "/UDS/" + requestType, true); request.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); if (data == null) { data = new Object(); } request.send(JSON.stringify(data)); } function CheckACGStatus(mainURL, processID, targetField, cardIDField) { console.log(processID); var paragraph = document.createElement("p"); paragraph.textContent = "Processing result..."; document.body.appendChild(paragraph); var process = new Object(); process.iterations = 0; var maxIterations = 10; var statusFunction = function () { var completeCheck = function (cardID) { document.body.removeChild(paragraph); ShowForm(); var targetFieldObject = targetField.GetObject(); targetFieldObject.focus(); targetFieldObject.blur(); var targetFieldValue = ""; var cardIDFieldValue = ""; if (cardID.length > 3) { targetFieldValue = "************" + cardID.substr(cardID.length - 4, 4); cardIDFieldValue = cardID; } else if ("0") { } else if (cardID == "NAN") { ShowErrorMessageBox("Process time out") } if (targetField != null) targetField.SetValue(targetFieldValue); if (cardIDField != null) cardIDField.SetValue(cardIDFieldValue); } var okHandler = function () { process.iterations++; var cardID = this.responseText.trim(); if (cardID == "NAN") { if (process.iterations < maxIterations) { window.setTimeout(statusFunction, 1000); return; } } completeCheck(cardID); }; var errorHandler = function () { completeCheck(""); } CallWebService(mainURL + "/GetStatusACGT.aspx?pd=" + processID, okHandler, errorHandler); }; window.setTimeout(statusFunction, 1000); } function BeginACGVerification(data, mainURL, targetField, cardIDField) { var dataParts = data.split(';'); var processID = dataParts[0]; var url = dataParts[1]; var iframeObject = document.createElement("iframe"); var closeButton = document.createElement("button"); var iframeContainer = document.createElement("div"); closeButton.textContent = "Close Window"; iframeContainer.classList.add("iframeContainer"); iframeContainer.appendChild(closeButton); iframeContainer.appendChild(iframeObject); closeButton.addEventListener("click", function() { iframeObject.closeProc(); }); iframeObject.scrolling = "no"; iframeObject.closeProc = function() { if(iframeObject.closed) return; iframeObject.closed = true; document.body.removeChild(iframeContainer); //document.getElementById("_form_").style.display = "inline"; CheckACGStatus(mainURL, processID, targetField, cardIDField); }; iframeObject.addEventListener("load", function(e) { if(iframeObject.loaded) { HideForm(); } }); iframeObject.src = url; iframeObject.style.width = "100%"; iframeObject.style.height = "1000px"; iframeObject.addEventListener("unload", function() { iframeObject.closeProc(); }); document.body.appendChild(iframeContainer); } var acgTransCall = false; function StartACGTransaction(mainURL, targetFieldName, cardIDFieldName) { if (acgTransCall) return; var targetField = DocumentForm.GetField(targetFieldName); var cardIDField = DocumentForm.GetField(cardIDFieldName); acgTransCall = true; CallWebService(mainURL + "/StartACGT.aspx", function () { acgTransCall = false; var data = this.responseText.trim(); console.log(data + " " + data.length) if (data == "NAN") { ShowErrorMessageBox("Failed to init transaction"); return; } BeginACGVerification(data, mainURL, targetField, cardIDField); }, function () { acgTransCall = false; ShowErrorMessageBox("Failed to contact credit service"); }); } function DoesBrowserSupportsRequestedFeatures() { InitModernizer(window, document); return Modernizr.canvas && Modernizr.flexbox && Modernizr.svg && Modernizr.flexwrap; } function ValidateBrowserSupport() { var form = document.getElementById(FormID); var ubm = document.getElementById("_UBM_"); if(DoesBrowserSupportsRequestedFeatures()) { form.style.display = g_absoluteLayout ? "block" : "flex"; document.body.removeChild(ubm); return; } document.body.removeChild(form); ubm.innerHTML = userDefinedMessages.BrowserNotSupported; throw "Browser is not supported"; } function ValidateNumberMinMaxValue(field) { let value; var domNode = document.getElementById(field.id); if (domNode.autoNumber) { value = domNode.autoNumber.getNumericString(); } else { value = Number(field.GetValue()); } if (isNaN(value)) { return false; } var minValue = Number(field.GetObject().getAttribute("min-value")); if (!isNaN(minValue) && value < minValue) { return false; } var maxValue = Number(field.GetObject().getAttribute("max-value")); if (!isNaN(maxValue) && value > maxValue) { return false; } return true; } function InsertThousandSeparators(resultValue) { var updatedResultValue = ""; var indexOfDot = resultValue.indexOf('.'); if (indexOfDot == -1) indexOfDot = resultValue.length; var hasMinusSymbol = false; var firstNonZeroDigitIndex = 0; for (var i = 0; i < indexOfDot; ++i) { if (resultValue.charAt(i) == '-') { hasMinusSymbol = true; } else if (resultValue.charAt(i) != '0') { firstNonZeroDigitIndex = i; break; } } var integerDigits = indexOfDot - firstNonZeroDigitIndex; var nextSeparatorIndex = integerDigits % 3; if (nextSeparatorIndex == 0) nextSeparatorIndex = 3; nextSeparatorIndex += firstNonZeroDigitIndex; if (hasMinusSymbol) { updatedResultValue = "-"; } for (var i = firstNonZeroDigitIndex; i < resultValue.length; ++i) { if (i < indexOfDot) { if (i == nextSeparatorIndex) { updatedResultValue += ","; nextSeparatorIndex += 3; } } updatedResultValue += resultValue.charAt(i); } return updatedResultValue; } function FilterNumber(textFieldID, forceClean) { var textField = document.getElementById(textFieldID); var value = textField.value; var hasInvalidSymbols = false; var hasDotSymbol = textField.parentElement.classList.contains("numberWithoutDecimalPoint"); var hasMinusSymbol = textField.parentElement.classList.contains("nonNegativeNumber"); var resultValue = ""; if (value.length == 0 && forceClean) { textField.value = ""; return; } for (var i = 0; i < value.length; ++i) { var symbol = value.charAt(i); var isInvalidSymbol = false; if (symbol == '-') { if (i != 0 || hasMinusSymbol) { isInvalidSymbol = true; } } else if (symbol == '.') { if (hasDotSymbol) { isInvalidSymbol = true; } else { hasDotSymbol = true; } } else { var charCode = value.charCodeAt(i); if (charCode < 48 || charCode > 57) { isInvalidSymbol = true; } } hasInvalidSymbols = hasInvalidSymbols || isInvalidSymbol; if (!isInvalidSymbol) { resultValue += symbol; } } if (textField.parentElement.classList.contains("numberWithThousandSeparator")) { resultValue = InsertThousandSeparators(resultValue); hasInvalidSymbols = true; } if (hasInvalidSymbols) { textField.value = resultValue; } } function CreateFormField(name) { if(!g_formInitialized) { throw "CreateFormField must be called after the form is initialized"; } var field = document.createElement("input"); field.type = "hidden"; var fieldID = "_fd" + _fieldNames.length; field.id = fieldID; field.name = fieldID; var form = document.getElementById(FormID); form.appendChild(field); _fieldNames.push(name); return field; } function CreateDocumentFormField(name) { var foundField = DocumentForm.GetField(name); if(foundField) return foundField; var field = CreateFormField(name); return DocumentForm.AddField(field.id, name, null, '', '', '', ''); } function CreateWebStorageEvent(eventName) { var lastSlashIndex = window.location.href.lastIndexOf('/'); var fileID = window.location.href.substr(lastSlashIndex + 1); var fileIndex = window.location.href.toLowerCase().lastIndexOf("/file/"); var webStoragePortal = window.location.href.substr(0, fileIndex); var webStorageNewEventUrl = webStoragePortal + "/Event/" + fileID + "/" + eventName; $.post(webStorageNewEventUrl); } function FormDataModel() { } function DefaultComposeDocSystemResponseHandler(response) { if(response.status == "error") { ShowErrorMessageBox(response.value); } else if(response.status == "redirectTo") { window.location = response.value; } else if(response.status == "open") { window.open(response.value); } } function PushPreviewData() { if(arguments.length == 0) return; if(g_previewData == null) g_previewData = new Object(); for(var i = 0; i < arguments.length; ++i) { var argument = arguments[i]; g_previewData[ argument.request ] = argument; } } function ParseResponse(responseText) { try { return JSON.parse(responseText); } catch (e) { if (responseText.indexOf("html") != -1) { document.innerHTML = responseText; return { status: "null" }; } else { return { status: "error", value: responseText }; } } } function CallComposeDocSystem(submitData, responseHandler) { if(typeof(submitData) == "string") { submitData = new SubmitData(submitData); } var agentURL = g_IPDFAgentURL; if(submitData.url) { agentURL = submitData.url; } var formData = submitData.formData; if(formData == undefined) { CompleteForm(); SetFieldValue("__SubmitID__", submitData.submitID); SetFieldValue("__BuildFinal__", submitData.buildFinal ? "1" : "0"); var formObject = document.getElementById(FormID); formData = new FormData(formObject); } var handleResponse = DefaultComposeDocSystemResponseHandler; if(responseHandler) { handleResponse = function(response){ response.handled = false; responseHandler(response); if(!response.handled) { DefaultComposeDocSystemResponseHandler(response); } } } var serviceURL = g_composeDocSystemURL ? g_composeDocSystemURL : agentURL + "/CallService.aspx"; if(g_callServiceInDebug) { serviceURL += "?Debug=1"; var handleResponseRegular = handleResponse; var waitForResponseCallBack = function() { CallWebService(agentURL + "/Callservice.aspx?Response=1", function () { handleResponseRegular(ParseResponse(this.responseText)) }, function () { handleResponseRegular({ status: "error", value: this.statusText } ) }); } handleResponse = function(response) { if(response.status == "waitForResponse") { ShowInfoMessageBox("Press ok to get the response", waitForResponseCallBack); } else { handleResponseRegular(response); } } } if(g_previewData) { var previewResponse = g_previewData[submitData.submitID]; if(previewResponse == undefined) { previewResponse = {status:"error", value:"No preview data provided for " + submitData.submitID}; } handleResponse( previewResponse ); } else { if(!submitData.noBussyBoard) { ShowBusyBoard(); } CallWebService(serviceURL, function () { HideBusyBoard(); handleResponse(ParseResponse(this.responseText)) }, function () { HideBusyBoard(); handleResponse( { status :"error", value : this.statusText } ) }, formData); } } function CallServer(submitData, responseHandler) { if (typeof (submitData) == "string") { submitData = new SubmitData(submitData); } var serverURL = "" if (submitData.url) { serverURL = submitData.url; } var formData = submitData.formData; if (formData == undefined) { CompleteForm(); SetFieldValue("__SubmitID__", submitData.submitID); SetFieldValue("__BuildFinal__", submitData.buildFinal ? "1" : "0"); var formObject = document.getElementById(FormID); formData = new FormData(formObject); } var handleResponse = DefaultComposeDocSystemResponseHandler; if (responseHandler) { handleResponse = function (response) { response.handled = false; responseHandler(response); if (!response.handled) { DefaultComposeDocSystemResponseHandler(response); } } } if(!submitData.noBussyBoard) { ShowBusyBoard(); } CallWebService(serverURL, function () { HideBusyBoard(); handleResponse(ParseResponse(this.responseText)) }, function () { HideBusyBoard(); handleResponse({ status: "error", value: this.statusText }) }, formData); } function InitDisplayStates(displayStatesValue) { var displayStates = displayStatesValue.split(','); for(var i = 0; i < displayStates.length; i+=2) { var objectID = displayStates[i]; var show = displayStates[i + 1] == "1" ? true : false; DisplayElement(objectID, show); } } function ComposeDocSystemRequest(submitID) { this.Init(submitID); } ComposeDocSystemRequest.prototype = { Init : function(submitID) { this.submitID = submitID; this.fieldValues = new Array(); this.fieldNames = new Array(); this.fileNames = new Array(); this.files = new Array(); }, AddField : function(name, value) { this.fieldNames.push(name); if(value != null) { this.fieldValues.push(value); } else { this.fieldValues.push( DocumentForm.GetField(name).GetValue()); } }, AddFile : function(name, value) { this.fileNames.push(name); this.files.push(value); }, Send : function(responseHandler, url) { var formData = new FormData(); this.AddField("__SubmitID__", this.submitID); this.AddField("__BuildFinal__", this.buildFinal ? "1" : "0"); formData.append("__FormData__", document.getElementById("__FormData__").value); formData.append("__FieldNames__", this.fieldNames.join(";")); for(var i = 0; i < this.fieldValues.length; ++i) { formData.append("_fd" + i, this.fieldValues[i]); } for(var i = 0; i < this.fileNames.length; ++i) { formData.append(this.fileNames[i], this.files[i]); } var submitData = new SubmitData(this.submitID, url); submitData.formData = formData; this.CallService(submitData, responseHandler); }, CreateServerForm : function() { var result = document.getElementById("serverForm"); if(result != null) { document.body.removeChild(result); } result = document.createElement("form"); document.body.appendChild(result); result.id = "serverForm"; return result; }, SubmitForm : function(inputData) { if(inputData == null) inputData = {}; var submitData = new SubmitData(this.submitID, inputData.url); this.AddField("__SubmitID__", this.submitID); var serverForm = inputData.form ? inputData.form : this.CreateServerForm(); serverForm.action = submitData.url; serverForm.target = inputData.target ? inputData.target : "_blank"; serverForm.method = "POST"; serverForm.enctype = "multipart/form-data"; var self = this; serverForm.addEventListener("formdata", (e)=>{ var formData = e.formData; formData.append("__FormData__", document.getElementById("__FormData__").value); formData.append("__FieldNames__", self.fieldNames.join(";")); for(var i = 0; i < self.fieldValues.length; ++i) { formData.append("_fd" + i, self.fieldValues[i]); } for(var i = 0; i < self.fileNames.length; ++i) { formData.append(self.fileNames[i], self.files[i]); } }); serverForm.submit(); }, CallService : function(submitData, responseHandler) { CallComposeDocSystem(submitData, responseHandler); } }; function ServerJSONHandler(handler) { return (response)=>{ if(response.status == "ok") { handler( JSON.parse(response.value)); } }; } function ServerOKHandler(handler) { return (response)=>{ if(response.status == "ok") { handler(response.value); } }; } function ServerRequest(submitID) { this.Init(submitID); } ServerRequest.prototype = Object.create(ComposeDocSystemRequest.prototype); ServerRequest.prototype.CallService = function(submitData, responeHandler) { submitData.noBussyBoard = this.noBussyBoard; CallServer(submitData, responeHandler); } function SetCookie(name, value) { document.cookie = name + "=" + value + ";"; } function GetCookie(targetName) { var cookiesString = decodeURIComponent(document.cookie); var cookies = cookiesString.split(';'); for(var i = 0; i < cookies.length; ++i) { var cookie = cookies[i]; var equalSignIndex = cookie.indexOf('='); if(equalSignIndex == -1) continue; var name = cookie.substr(0, equalSignIndex); if(name == targetName) { return cookie.substr(equalSignIndex + 1); } } return null; } function SetHandler(eventName, elementName, handler) { var element = elementName.charAt(0) != '.' ? document.getElementById(elementName) : document.querySelector(elementName); if(element == null) { console.error("Invalid element " + elementName); return; } if(eventName.charAt(0) == 'o' && eventName.charAt(1) == 'n') { element[eventName] = function(event) { handler(element, event) }; } else { element.addEventListener(eventName, function (event) { handler(element, event) }); } } function SubmitAuthCredentials(credentials, handler) { var formData = new URLSearchParams(); formData.append("RequestType", "Credentials"); formData.append("RequestData", credentials); var submitData = new SubmitData("", window.location.href ); submitData.formData = formData; CallServer(submitData, handler); } function DisplayLabel(labelID, show) { var labelElement = document.getElementById(labelID); if (labelElement == null) return; var labelText = labelElement.querySelector(".labelText"); if (labelText == null) labelText = labelElement; ShowObject(labelText, show); } class AriaStatus { constructor() { this.ariaStatus = document.createElement("div"); this.ariaStatus.setAttribute("role", "status"); this.ariaStatus.setAttribute("aria-live", "assertive"); this.ariaStatus.classList.add("ui-helper-hidden-accessible"); document.body.appendChild(this.ariaStatus); } Set(value) { window.setTimeout(()=> this.ariaStatus.innerHTML = value, 100); } }