//console.log('LOADED');
var WinorgForm = function (selector, data, token, successPage, surfaceControllerUrl, mainMemberRoleId, familyMemberRoleId, ageRestrictionErrorMessage) {
    console.log("Form data:", JSON.parse(JSON.stringify(data)));
    
    // define element container component
    var ElementContainer = Vue.extend({
        props: ['element', 'test'],
        methods: {
            SwitchElementEditor: function () {
                this.$emit('toggle-element-editor-visibility', this.element);
            }
        },
        template: `
            <div v-if="element.ShowAsCollapsible">
                <p v-if="!this.element.ShowElementEditor">
                    {{element.Label}}:<span class="float-right">
                        <a class="pencil" href="javascript:;" v-on:click="SwitchElementEditor()">{{element.Value}}</a>
                    </span>
                </p>
                <div v-if="element.ShowElementEditor">
                    <slot></slot>
                </div>
            </div>
            <div v-else>
                <slot></slot>
            </div>
        `
    })
    // register element container component
    Vue.component('element-container', ElementContainer)
    new Vue({
        el: selector,
        components: {
            datepicker: vuejsDatepicker,
            orderItem: orderItem,
            datepicker2: DatePicker
        },
        data: {
            autocompleteData: { requestTimer: null, closeTimer: null, results: [], selectedIndex: -1, loading: false, match: true, name: "" },
            autocompleteSelectedItem: 0,
            autocompleteCurrName: "",
            autocompleteBgColor: "#ffffff",
            autocompleteActiveBgColor: "#f0f0f0",
            keys: {
                Backspace: 8,
                Enter: 13,
                Up: 38,
                Down: 40,
                Del: 46
            },
            data: data,
            showFormStepContainer: !data.Steps[0].Collapseable,
            showFormStepContainerArr: [],
            disabledValueCollection: [],
            currentPage: 0,
            showCancelScreen: false,
            privacyPolicyAccepted: false,
            showPrivacyPolicyReminder: false,
            showNextButton: false,
            showPrevButton: false,
            showSubmit: false,
            orderedItems: [],
            invalidFields: [],
            showListOfInvalidFields: false,
            CustomTextInputConstant: '_other_',
            isPosting: false,
            isLoading: false,
            isMaximized: false,
            postSuccess: {
                success: false,
                showSuccess: false,
                winorgResultCode: null
            },
            postFailure: {
                failure: false,
                status: 0,
                winorgResultCode: null
            },
            postComplete: false,
            successPage: successPage,
            surfaceControllerUrl: surfaceControllerUrl,
            stepIsInvalid: false,
            token: token,
            inputTypes: {
                Text: "Text",
                Checkbox: "Checkbox",
                Radio: "Radio",
                Date: "Date",
                Boolean: "Boolean",
                Select: "Select",
                Number: "Number",
                TextArea: "TextArea",
                RadioImage: "RadioImage",
                FormControlButtons: "FormControlButtons",
                SelectWithDialog: "SelectWithDialog",
                LinkList: "LinkList",
                CheckboxSlide: "CheckboxSlide"
            },
            paymentTypes: {
                PaymentType_NETAXEPT: "NETAXEPT_FIRSTPAY_THEN_GIRO",
                PaymentType_VIPPS: "VIPPSRECURRING_FIRSTPAY_AND_SIGN",
                PaymentType_VIPPS_HURTIG: "VIPPS_HURTIG",
            },
            winorgResultCodes: {
                Completed: 0,
                Later: 1,
                Uncompleted: 2
            },
            CustomError: '',
            DMCodeError: '',
            employersLoaded: false,
            showConfirm: false,
            ShowChangeMembershipConfirm: false,
            membership: "active",
            showMembershipCard: false,
            changeMembershipButton: false,

            membershipStatusDate: '',
            membershipStatusReason: null,
            showMembershipStatusConfirm: false,
            changeMembershipStatusConfirm: false,
            membershipStatus: "active",
            showMembershipStatusDateError: false,
            showMembershipStatusReasonError: false,

            popUpUserName: '',
            popUpUserLastName: '',
            popUpUserActorId: '',
            popUpAssociationName: '',
            showInvoiceStat: false,
            showDatepicker: true,
            familyExtraForm: [],
            showFamilyExtraForm: false,
            familyExtraLabel: "Legg til familiemedlemmer",
            showFamilyExtraLabel: true,
            mainMemberLabel: "Husstandsmedlemmer",
            rowFamilyExtraForm: 0,
            personInfoCounter: 1,
            agreementCodes: [700, 801, 803],
            linkList: [],
            linkListVisible: false,
            isClickSubmit: false,
            PaymentType_NETAXEPT: "NETAXEPT_FIRSTPAY_THEN_GIRO",
        },
        methods: {
            toggleElementEditorVisibility: function (element) {
                element.ShowElementEditor = !element.ShowElementEditor;

                //TODO: this is a dirty hack for force myComponent re-render on ShowElementEditor change. 
                //Sorry, didn't have time for that during initial implementation.
                element.Label = element.Label + " ";
            },
            updatePreselectedMembershipFellowship: function () {
                var self = this;
                this.data.Steps.forEach(function (step, stepIndex) {
                    step.Rows.forEach(function (row, rowIndex) {
                        row.Columns.forEach(function (column, columnIndex) {
                            column.Elements.forEach(function (element, elementIndex) {
                                if (element.Values && element.Values.length > 0) {
                                    element.Values.forEach(function (value) {
                                        if (value.IsPreselected && (element.Name === 'Membership¤Fellowship' || element.Name === 'Fellowship')) {
                                            element.Value = "";
                                            self.resetAutocomplete();
                                            self.selectAutocompleteItem(element, '<b></b>' + value.Name);
                                        }
                                    });
                                }
                            });
                        });
                    });
                });
            },
            updatePreselectedStopMembership: function () {
                this.membershipStatusDate = this.getElementByName('Membership¤ToDate')?.Value || '';
            },
            getStopMembershipDateLabel: function () {
                var membershipToDate = this.getElementByName('Membership¤ToDate');
                if (membershipToDate != null) {
                    return membershipToDate.Label;
                }
                return null;
            },
            isStopMembershipDateDisabled: function () {
                var membershipToDate = this.getElementByName('Membership¤ToDate');
                return membershipToDate.Disabled;
            },
            disabledBeforeToday: function (date) {
                const today = new Date();
                today.setHours(0, 0, 0, 0);
                return date.getTime() < today.getTime();
            },
            disabledAfterToday: function (date) {
                const today = new Date();
                today.setHours(0, 0, 0, 0);
                return date.getTime() > today.getTime();
            },
            disableDateFutureOrPast: function (element) {
                if (element.DisableFuture) {
                    return this.disabledAfterToday;
                }
                if (element.DisablePast) {
                    return this.disabledBeforeToday; 
                }
            },
            isEditable: function (element) {
                return !!!element.NonEditable;
            },
            onDateInput: function (newDateValue) {
                // when date is changed
                // there can be other checks too
                var leaveEnd = this.getElementByName('Employment_¤LeaveEnd') || this.getElementByName('LeaveEnd');
                if (leaveEnd) {
                    this.checkLeaveEndAgainstLeaveStart(newDateValue);
                }
            },
            onActorBirthdateInput: function (newBirthdateValue) {
                if (this.data.Method === 'SaveMembershipWithAssociations') {
                    this.CheckPersonMembershipAge(newBirthdateValue);
                }
            },
            CalculatePersonAge: function (personBirthDateString) {
                try {
                    var personBirthDate = new Date(personBirthDateString);
                } catch {
                    return null; // todo: this is DIRTY.
                }

                if (!personBirthDate) {
                    return null;
                }

                var currentDate = new Date();

                var yearsDiff = currentDate.getFullYear() - personBirthDate.getFullYear();
                var monthsDiff = currentDate.getMonth() - personBirthDate.getMonth();

                if (monthsDiff < 0 || (monthsDiff === 0 && currentDate.getDate() < personBirthDate.getDate())) {
                    return yearsDiff - 1;
                }

                return yearsDiff;
            },
            CheckPersonMembershipAge: function () {
                var selectedMembershipValueCode = this.getElementByName('Membership¤RoleID')?.Value;

                var selectedMembershipValue = this.getElementByName('Membership¤RoleID')?.Values
                    .filter(x => x.Value === selectedMembershipValueCode)[0];

                if (!selectedMembershipValue) {
                    return true;
                }

                var checkAge = selectedMembershipValue.AgeRestrictionEnabled;

                if (!checkAge) {
                    return true;
                }

                var minAge = selectedMembershipValue.AgeRestrictionMinAge;
                var maxAge = selectedMembershipValue.AgeRestrictionMaxAge;

                var errorMessage = null;

                ageRestrictionErrorMessage 
                    ? errorMessage = ageRestrictionErrorMessage
                    : errorMessage = 'Dette medlemskapet har aldersbegrensninger. Vennligst velg et annet medlemskap!';

                var personBirthDate = this.getElementByName('Actor¤Birthdate')?.Value;
                var personAge = this.CalculatePersonAge(personBirthDate);

                if ((minAge !== null && minAge !== undefined && personAge !== null && personAge !== undefined && personAge < minAge)
                    || (maxAge !== null && maxAge !== undefined && personAge !== null && personAge !== undefined && personAge > maxAge)) {
                    document.ShowLightbox(errorMessage);
                    return false;
                }
                return true;
            },
            AddPersonMembershipAgeCheck: function () {
                var roleIdElement = document.getElementById('Membership¤RoleID');

                if (!roleIdElement) {
                    return;
                }

                roleIdElement.onchange = (event) => {
                    this.CheckPersonMembershipAge();
                }
            },
            StopMembership: function (e) {
                if (this.membership == "active" && e.Name != "MembershipStatus") {
                    this.showConfirm = false;
                    return;
                }

                this.showMembershipStatusDateError = false;
                this.showMembershipStatusReasonError = false;

                var toDate = this.membershipStatusDate;
                var reason = this.MembershipStatusReason?.SelectValue;

                if (e) {
                    if (e.Name == "MembershipStatus") {
                        if (toDate == "") {
                            this.showMembershipStatusDateError = true;
                        }
                        if (reason == "") {
                            this.showMembershipStatusReasonError = true;
                        }
                        if (this.showMembershipStatusDateError || this.showMembershipStatusReasonError) {
                            return;
                        }
                    }
                }

                this.showConfirm = false;
                this.showMembershipStatusConfirm = false;

                var fromDate = this.getElementByName('Membership¤FromDate');
                var actorId = this.getElementByName('Actor¤ActorID');
                var roleNo = this.getElementByName('Membership¤RoleID');

                var params = {
                    method: "POST",
                    StartPageId: this.data.StartPageId,
                    ActorId: actorId.Value,
                    RoleNo: roleNo.Value,
                    FromDate: fromDate.Value,
                    NodeId: this.data.NodeId,
                    FullUrl: window.location.href,
                    UserAgent: navigator.userAgent,
                    AppVersion: navigator.appVersion,
                    ToDate: toDate,
                    Reason: reason,
                };
                this.$http.post(
                    this.surfaceControllerUrl + '/StopMembership', params).then(function (success) {
                        this.postSuccess.success = true;
                        this.isPosting = false;
                        this.postSuccess.showSuccess = true;

                        var that = this;
                        setTimeout(function () {
                            that.postSuccess.showSuccess = false;
                        }, 5000);

                        if (!this.data.ThankYouPopup && !this.data.SimpleThankYouString) {
                            this.postComplete = true;
                        }

                        if (this.data.ThankYouPopup) {
                            document.ShowLightbox(this.data.SuccessMessage, document.location);
                        }

                    }, function (error) {
                        document.ShowLightbox(this.data.ErrorMessageWinorg);
                    });
            },
            ChangeMembership: function (e) {
                this.ShowChangeMembershipConfirm = false;

                var fromDate = this.getElementByName('Membership¤FromDate');
                var actorId = this.getElementByName('Actor¤ActorID');
                var roleNo = this.getElementByName('Membership¤RoleID');

                var params = {
                    method: "POST",
                    StartPageId: this.data.StartPageId,
                    ActorId: actorId.Value,
                    RoleNo: roleNo.Value,
                    FromDate: fromDate.Value,
                    NodeId: this.data.NodeId,
                    FullUrl: window.location.href,
                    UserAgent: navigator.userAgent,
                    AppVersion: navigator.appVersion,
                };
                this.$http.post(
                    this.surfaceControllerUrl + '/ChangeMembership', params).then(function (success) {
                        this.postSuccess.success = true;
                        this.isPosting = false;
                        this.postSuccess.showSuccess = true;

                        var that = this;
                        setTimeout(function () {
                            that.postSuccess.showSuccess = false;
                        }, 5000);

                        if (!this.data.ThankYouPopup && !this.data.SimpleThankYouString) {
                            this.postComplete = true;
                        }

                        if (this.data.ThankYouPopup) {
                            document.ShowLightbox(this.data.SuccessMessage, document.location);
                        }

                    }, function (error) {
                        document.ShowLightbox(this.data.ErrorMessageWinorg);
                    });
            },
            CloseMembershipCard: function () {
                this.showMembershipCard = false;
            },
            IsShowStatusLink: function (e) {
                if (!e.Text) return false;
                return e.Text.toLowerCase().indexOf("status:") > 0 ? true : false;
            },
            IsFamilyExtraLabel: function (e) {
                return e.Text.toLowerCase().indexOf(this.familyExtraLabel.toLowerCase()) > 0 ? true : false;
            },
            IsFamilyExtraLink: function (e) {
                if (!e.Text) return false;
                var roleId = this.getElementByName('Membership¤RoleID');
                if (roleId != null) {
                    if (roleId.Value == mainMemberRoleId) {
                        return e.Text.toLowerCase().indexOf(this.familyExtraLabel.toLowerCase()) > 0 ? true : false;
                    }
                }
                return false;
            },
            IsMainMemberLabel: function (e) {
                return e.Text.toLowerCase().indexOf(this.mainMemberLabel.toLowerCase()) > 0 ? true : false;
            },
            ShowMainMemberLabel: function (e) {
                if (!e.Text) return false;
                var roleId = this.getElementByName('Membership¤RoleID');
                if (roleId != null) {
                    if (roleId.Value == mainMemberRoleId) {
                        return this.IsMainMemberLabel(e);
                    }
                }
                return false;
            },
            IsShowFamilyFormLink: function (e) {
                if (!e.RTE.value) return false;
                return e.RTE.value.indexOf("[FamilyForm]") > 0 ? true : false;
            },
            IsSystemDatetime: function (e) {
                if (!e.DataType) return false;
                return e.DataType.toLowerCase().indexOf("system.datetime") > 0 ? true : false;
            },
            toDefaultDateFormat: function (value) {
                if (value) {
                    //var date = value.toLocaleString().split(',')[0];
                    //var day = ('0' + (date.split('/')[1])).slice(-2);
                    //var month = ('0' + (date.split('/')[0])).slice(-2);
                    //var year = date.split('/')[2];
                    //return day + '.' + month + '.' + year;
                    var options = { day: '2-digit', month: '2-digit', year: 'numeric' };
                    var date = value.toLocaleDateString("no-NO", options);
                    return date;
                }
                return '';
            },
            ShowConfirmDialog: function () {
                this.showConfirm = true;
            },
            ShowChangeMembershipDialog: function (e) {
                this.ShowChangeMembershipConfirm = true;
                e.SelectValue = e.Value;
            },
            ShowMembershipStatusConfirmDialog: function () {
                this.showMembershipStatusConfirm = true;
            },
            CancelMembershipStatusConfirmDialog: function () {
                this.showMembershipStatusConfirm = false;
            },
            getNameByValue: function (e) {
                var res = "";
                e.Values.forEach(function (item) {
                    if (item.Value == e.Value) {
                        res = item.Name;
                    }
                });
                return res;
            },
            IsShowMembershipCardLink: function (e) {
                if (!e.Text) return false;
                return e.Text.toLowerCase().indexOf("membershipcard:") > 0 ? true : false;
            },
            CancelConfirmDialog: function () {
                this.showConfirm = false;
            },
            CancelChangeMembershipDialog: function () {
                this.ShowChangeMembershipConfirm = false;
            },
            ShowMembershipCardDialog: function () {
                this.showMembershipCard = true;
                this.popUpUserName = this.getElementByName('Actor¤FirstName').Value;
                this.popUpUserLastName = this.getElementByName('Actor¤LastName').Value;
                this.popUpUserActorId = this.getElementByName('Actor¤ActorID').Value;
                this.popUpAssociationName = this.getElementByName('Membership¤AssociationName').Value;
            },
            ViewInvoice: function (e) {
                var params = {
                    InvoiceNo: e.InvoiceNumber,
                    StartPageId: this.data.StartPageId,
                };

                this.$http.post(this.surfaceControllerUrl + '/GetInvoiceAttachment', params, {
                    emulateJSON: true
                }).then(function (response) {
                    var byteCharacters = atob(response.body.AttachmentContent);
                    var byteNumbers = new Array(byteCharacters.length);
                    for (var i = 0; i < byteCharacters.length; i++) {
                        byteNumbers[i] = byteCharacters.charCodeAt(i);
                    }
                    var byteArray = new Uint8Array(byteNumbers);
                    var file = new Blob([byteArray], { type: 'application/pdf;base64' });
                    var fileURL = URL.createObjectURL(file);
                    window.open(fileURL, "_blank");
                }, function (error) {
                    if (error.status == "500") {
                        document.ShowLightbox("Authentication fail... ");
                    }
                });
            },
            ShowInvoiceStat: function () {
                this.showInvoiceStat = true;
            },
            CloseInvoiceStat: function () {
                this.showInvoiceStat = false;
            },
            toggleFormStepContainer: function (e) {
                this.showFormStepContainer = !this.showFormStepContainer;
                this.showFormStepContainerArr[e] = !this.showFormStepContainerArr[e];
            },
            nextStep: function () {
                if (this.currentPage < this.data.Steps.length - 1 && this.stepIsValid()) {
                    this.currentPage++;
                }
                this.checkButtons();
                this.fillEmployerNameFromEmployerActorID();
            },
            prevStep: function () {
                if (this.currentPage > 0) {
                    this.currentPage--;
                }
                this.checkButtons();
                this.fillEmployerNameFromEmployerActorID();
            },
            cancelSubscription: function () {
                this.getElementByName(this.data.CancelConfirmationFieldName).Value = true;
                this.submit(null, true);
            },
            doCourseRegister: function (e) {
                var params = {
                    DepartmentId: e.DepartmentId,
                    CourseId: e.CourseId,
                    StartPageId: this.data.StartPageId,
                };
                this.$http.post(this.surfaceControllerUrl + '/SaveCourseRegister', params, {
                    emulateJSON: true
                }).then(function (response) {
                    if (response.body.Success) {
                        document.ShowLightbox("Din deltakelse er registrert", window.location.href);
                    } else {
                        document.ShowLightbox("Det oppstod en feil...");
                    }
                }, function (error) {
                    if (error.status == "500") {
                        document.ShowLightbox("Authentication fail... ");
                    }
                });
            },
            submit: function (e, skipValidation) {
                if (e) {
                    e.preventDefault();
                }

                if (e.submitter != null) {
                    if (e.submitter.className.indexOf("js-stopmember-cancel-button") !== -1 ||
                        e.submitter.className.indexOf("js-stopmember-confirm-button") !== -1) {
                        return;
                    }
                }

                // when the submit button gets visible in multypage form (with this.showSubmit = true;)
                // Vue.js initiates the uncontrollable form submitting
                // HACK: check this.isClickSubmit if it was manualy pressed the submit button in multypage form
                if (this.data.Steps.length > 1) {
                    if (!this.isClickSubmit)
                        return;
                }

                this.DMCodeError = "";
                this.stepIsInvalid = false;

                // various custom checks
                var errorPresent = false;

                if (!this.CheckPersonMembershipAge()) {
                    errorPresent = true;
                }

                this.fillEmployerNameFromEmployerActorID();

                var fieldsToCheckList = this.selectFieldsAndLinkedErrors();
                for (var i = 0, len = fieldsToCheckList.length; i < len; i++) {
                    var checkObj = fieldsToCheckList[i];
                    var fil = this.findFieldToCheckError(checkObj.FieldToCheckName);
                    if (fil.Value == "") {
                        this.stepIsInvalid = true;
                        if (this.DMCodeError == "")
                            this.DMCodeError = checkObj.ErrorMessage;
                        else
                            this.DMCodeError += "<br>" + checkObj.ErrorMessage
                        errorPresent = true;
                    }
                }

                if (errorPresent)
                    return;

                if (skipValidation || this.stepIsValid()) {
                    this.isPosting = true;
                    this.showListOfInvalidFields = false;
                    this.postFailure.failure = false;
                    this.postSuccess.success = false;
                    this.postSuccess.showSuccess = false;

                    this.$http.post(this.surfaceControllerUrl + '/Post', this.buildPayload(), {
                        emulateJSON: true
                    }).then(function (success) {
                        if (success.body.RedirectUrl) {
                            if (success.body.IsPost) {

                                var postModel = success.body;

                                var _form = document.createElement("form");
                                _form.setAttribute('method', "post");
                                _form.setAttribute('action', postModel.RedirectUrl);
                                _form.setAttribute('style', "display: none");

                                for (var k in postModel.Parameters) {
                                    var _input = document.createElement("input");
                                    _input.setAttribute('type', "hidden");
                                    _input.setAttribute('name', k);
                                    _input.setAttribute('id', k);
                                    _input.setAttribute('value', postModel.Parameters[k]);
                                    _form.appendChild(_input);
                                }

                                var _submit = document.createElement("input");
                                _submit.setAttribute('type', "submit");
                                _submit.setAttribute('style', "display: none");

                                _form.appendChild(_submit);
                                document.getElementsByTagName('body')[0].appendChild(_form);
                                _form.submit();
                            } else {
                                if (!!success.body.RedirectTarget) {
                                    window.open(
                                        success.body.RedirectUrl,
                                        success.body.RedirectTarget
                                    );
                                    this.isPosting = false;
                                } else {
                                    window.location.href = success.body.RedirectUrl;
                                }
                            }
                        } else if (this.successPage) {
                            window.location.href = this.successPage;
                        } else {
                            this.postSuccess.success = true;
                            this.isPosting = false;
                            this.postSuccess.showSuccess = true;
                            this.CustomError = "";

                            var that = this;
                            setTimeout(function () {
                                that.postSuccess.showSuccess = false;
                                that.closePanel();
                            }, 3000);

                            if (!this.data.ThankYouPopup && !this.data.SimpleThankYouString) {
                                this.postComplete = true;
                            }

                            if (this.data.ThankYouPopup) {
                                document.ShowLightbox(this.data.SuccessMessage, redirectUrl);
                            }
                        }
                    }, function (error) {
                        this.postFailure.failure = true;
                        this.postFailure.status = error.status;
                        this.isPosting = false;

                        if (error.status === 400) {
                            this.processServerValidation(error.body);
                        }
                        else if (error.body !== '') {
                            this.CustomError = error.body;
                            console.log("errorstatus", error.body);
                        } else if (this.data.ThankYouPopup) {
                            document.ShowLightbox(this.data.ErrorMessageWinorg);
                        }
                    });
                    this.isClickSubmit = false;
                }
                this.isClickSubmit = false;
            },
            selectFieldsAndLinkedErrors: function () {
                var fieldsToCheckList = [];

                this.data.Steps.forEach(function (step) {
                    step.Rows.forEach(function (row) {
                        row.Columns.forEach(function (column) {
                            column.Elements.forEach(function (element) {
                                var checkedFields = [];
                                if (element.CheckboxValue != null) {
                                    element.CheckboxValue.forEach(function (checkedValue) {
                                        checkedFields.push(checkedValue);
                                    })
                                }

                                if (element.Values != null) {
                                    element.Values.forEach(function (value) {
                                        try {
                                            var fieldToCheck = value.FieldToCheck;
                                            var errorMessage = value.ErrorText;

                                            if (fieldToCheck != undefined && errorMessage != ""
                                                && checkedFields.indexOf(value.Value) > -1) {
                                                //add fields only if they are checked 
                                                var ob = new Object;
                                                ob.DMField = value;
                                                ob.FieldToCheckName = fieldToCheck;
                                                ob.ErrorMessage = errorMessage;
                                                fieldsToCheckList.push(ob);
                                            }

                                        }
                                        catch (er) { };
                                    });
                                }
                            });
                        });
                    });
                });
                return fieldsToCheckList;
            },
            findFieldToCheckError: function (name) {
                var result;
                this.data.Steps.forEach(function (step) {
                    step.Rows.forEach(function (row) {
                        row.Columns.forEach(function (column) {
                            column.Elements.forEach(function (element) {
                                if (element.Name == name) {
                                    result = element;

                                }
                            });
                        });
                    });

                });
                return result;
            },
            processServerValidation: function (form) {
                this.invalidFields = [];
                if (!form.IsValid) {
                    var self = this;
                    form.Elements.forEach(function (e) {
                        if (e.IsInvalid) {
                            formElement = self.getElementByName(e.Name);
                            formElement.IsInvalid = true;
                            self.showListOfInvalidFields = true;
                            self.invalidFields.push(
                                {
                                    label: formElement.Label,
                                    step: self.getStepNumber(formElement)
                                });
                        }
                    });

                    this.currentPage = this.invalidFields[0].step;
                    this.checkButtons();
                }
            },
            isRoleIdCorrect(roleId) {
                var res = true;
                var paymentType = this.getElementByName('Membership_¤PaymentType') || this.getElementByName('PaymentType') || this.getElementByName('Paymenttype');
                if (roleId || paymentType) {
                    if (roleId.Value) {
                        var self = this;
                        roleId.Values.forEach(function (value) {
                            if (value.Value == roleId.Value) {
                                if (value.TermAmount == 0 || value.Price == 0) {
                                    if (paymentType.Value == self.PaymentType_NETAXEPT) {
                                        res = false;
                                    }
                                }
                            }
                        });
                    }
                }
                return res;
            },
            getStepNumber: function (e) {
                var s;
                this.data.Steps.forEach(function (step, i) {
                    step.Rows.forEach(function (row) {
                        row.Columns.forEach(function (column) {
                            column.Elements.forEach(function (element) {
                                if (e.Name === element.Name)
                                    s = i;
                            });
                        });
                    });
                });
                return s;
            },
            getQuerystringParameterByName: function (name) {
                var url = window.location.href;
                name = name.replace(/[\[\]]/g, '\\$&');
                var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
                    results = regex.exec(url);
                if (!results) return null;
                if (!results[2]) return '';
                return decodeURIComponent(results[2].replace(/\+/g, ' '));
            },
            wasRedirectedFromWinorg: function () {
                return this.getQuerystringParameterByName('instanceid') === this.data.InstanceId;
            },
            getWinorgResult: function () {
                this.isLoading = true;
                this.$http.post(
                    this.surfaceControllerUrl + '/WinorgResult', {
                    spid: this.getQuerystringParameterByName('spid'),
                    method: this.getQuerystringParameterByName('method'),
                    winorgtoken: this.getQuerystringParameterByName('winorgtoken'),
                    url: window.location.href
                }).then(function (success) {
                    if (success.body === this.winorgResultCodes.Uncompleted) {
                        this.postFailure.failure = true;
                        this.postFailure.winorgResultCode = success.body;
                    } else {
                        this.postSuccess.success = true;
                        this.postSuccess.winorgResultCode = success.body;
                        if (this.successPage)
                            window.location.href = this.successPage;
                    }
                }, function (error) {

                    this.postFailure.failure = true;
                    this.postFailure.status = error.status;

                    if (error.body !== '') {
                        this.CustomError = error.body;
                    }

                }).finally(function () {
                    this.isLoading = false;
                    this.postComplete = true;
                });
            },
            buildPayload: function () {
                var payload = {};
                var self = this;

                payload.__RequestVerificationToken = this.token;
                payload.StartPageId = this.data.StartPageId;
                payload.WinOrgVersion = this.data.WinOrgVersion;
                payload.Method = this.data.Method;
                payload.NodeId = this.data.NodeId;
                payload.IsLegacyWs = this.data.IsLegacyWs;
                payload.RedirectUrl = window.location.href.split('?')[0];
                payload.InstanceId = this.data.InstanceId;
                payload.FullUrl = window.location.href;
                payload.MainMemberRoleId = mainMemberRoleId;
                payload.FamilyMemberRoleId = familyMemberRoleId;
                payload.UserAgent = navigator.userAgent;
                payload.AppVersion = navigator.appVersion;

                payload.Elements = [];

                this.data.Steps.forEach(function (step) {
                    step.Rows.forEach(function (row) {
                        row.Columns.forEach(function (column) {
                            column.Elements.forEach(function (element) {
                                if (!element.IsTextProperty && !element.IsReadOnly) {

                                    var isRepeatable = !!element.IsRepeatableField;
                                        
                                    var nameSecondary = isRepeatable ? "-SECONDARY-0" : element.NameSecondary;

                                    payload.Elements.push({
                                        Name: element.Name,
                                        NameSecondary: nameSecondary,
                                        Value: self.getElementPayloadValue(element),
                                        SelectValue: element.SelectValue,
                                        DotNetDatatype: element.DotNetDatatype,
                                        Required: element.Required,
                                        ShowAsCollapsible: element.ShowAsCollapsible,
                                        RequiredByCustomer: element.IsRepeatableFieldRequired,
                                        IsVisible: element.IsVisible,
                                    });

                                    // adding the additional parameters to Values
                                    var last = payload.Elements.length - 1;

                                    // Samtykker and Reservasjoner have value ForceCheckboxes = true
                                    if (element.ForceCheckboxes) {
                                        payload.Elements[last].Values = element.Values;
                                    }
                                    else {
                                        payload.Elements[last].Values = [];
                                    }

                                    var selectedItem = self.getSelectedValues(element.Values, element.SelectValue);

                                    if (selectedItem) {
                                        if (selectedItem.FirstPrice) {
                                            payload.Elements[last].Values.push({
                                                Name: "FORSTE_PRIS",
                                                Value: selectedItem.FirstPrice,
                                                FirstPriceDateStart: selectedItem.FirstPriceDateStart,
                                                FirstPriceDateStop: selectedItem.FirstPriceDateStop,
                                            });
                                        }
                                    }
                                }
                            });
                        });
                    });
                });

                this.initializeElementValuesFromPreselectedValues();
                return payload;
            },
            getSelectedValues: function (values, selectedValue) {
                if (values) {
                    for (var i = 0; i < values.length; i++) {
                        if (values[i].Value == selectedValue) {
                            return values[i];
                        }
                    }
                }
                return null;
            },
            summaryFormatDateTime: function (e) {
                return this.toDefaultDateFormat(e.Value);
            },
            summaryElementIsVisible: function (e) {
                if (e.Value)
                    return true;
                return false;
            },
            summaryGetCheckboxValues: function (e) {
                var values = e.Value.split(',');
                if (values[0] === '')
                    return [];
                for (var i = 0; i < values.length; i++) {
                    var index = e.Values.map(function (o) { return o.Value; }).indexOf(values[i]);
                    values[i] = e.Values[index].Name;
                }
                return values;
            },
            initializeSummary: function () {
                if (this.data.AddSummary) {
                    this.data.Steps.push(
                        {
                            Title: 'Oppsummering',
                            IsSummary: true,
                            Rows: []
                        }
                    );
                }
            },
            initializeForm: function () {
                this.initializeSummary();
                this.checkButtons();
                this.initializeElementValuesFromPreselectedValues();
                this.personInfoCounter = this.getCountOfExtraGroup() + 1;

                this.fillEmployerName();
                this.fillAffiliationFellowship();
                this.fillTitles();
            },
            fillEmployerName: function () {
                // initialize employer name values for autocomplete 
                var emploerName = this.getElementByName('Employment_¤EmployerName') || this.getElementByName('EmployerName');
                if (emploerName != null && emploerName.IsAutocompleteFieldNew && emploerName.InputType == this.inputTypes.Text) {

                    var params = {
                        startPageId: this.data.StartPageId,
                        method: emploerName.QueryFilter,
                    };
                    this.$http.post(
                        this.surfaceControllerUrl + '/GetAvailableActiveCompanies', params).then(function (success) {
                            emploerName.Values = [];
                            for (var i = 0; i < success.body.length; i++) {
                                emploerName.Values.push(success.body[i]);
                            }
                            this.employersLoaded = true;
                            this.autocompleteData.results = [];

                            // filling Positions if form contains EmployerName
                            var agreementCode = this.getAgreementCode();
                            if (agreementCode) {
                                this.fillPositions(agreementCode);
                            }
                        });
                }
            },
            fillAffiliationFellowship: function () {
                var affiliationFellowshipName = this.getElementByName('AffiliationFellowshipName');
                if ((affiliationFellowshipName != null && affiliationFellowshipName.IsAutocompleteFieldNew && affiliationFellowshipName.InputType == this.inputTypes.Text))
                {
                    var params2 = {
                        startPageId: this.data.StartPageId,
                        method: affiliationFellowshipName.QueryFilter
                    };
                    this.$http.post(
                        this.surfaceControllerUrl + '/GetAffiliationFellowships', params2).then(function (success) {
                            affiliationFellowshipName.Values = [];
                            for (var i = 0; i < success.body.length; i++) {
                                affiliationFellowshipName.Values.push(success.body[i]);
                            }
                            this.employersLoaded = true;
                        });
                }
            },
            tryToGetDateObject: function (dateString) {
                var res = new Date();
                if (dateString == "" || dateString == null) return null;
                if (typeof dateString == 'object') return dateString;
                if (dateString.substr(0, 4) > 1900) {
                    return new Date(dateString);
                } else {
                    if (dateString.match(/\//ig) != null && dateString.match(/:/ig) != null) {
                        // if date is in format 7/30/1990 12:00:00 PM
                        var dateArr = dateString.split(" ")[0].split("/");
                        var day = dateArr[1];
                        var month = dateArr[0];
                        var year = dateArr[2];
                        res = new Date(year, month - 1, day);
                    } else if (dateString.indexOf(".") > -1 && dateString.match(":") > -1) {
                        // if date is in format 30.07.1990
                        var dateArr = dateString.split(" ")[0].split(".");
                        var day = dateArr[0];
                        var month = dateArr[1];
                        var year = dateArr[2];
                        res = new Date(year, month - 1, day);
                    } else if (dateString.indexOf(".") > -1 && dateString.indexOf(":") > -1) {
                        // if date is in format 30.07.1990 00:00:00
                        var dateArr = dateString.split(" ")[0].split(".");
                        var day = dateArr[0];
                        var month = dateArr[1];
                        var year = dateArr[2];
                        res = new Date(year, month - 1, day);
                    } else if (String(dateString).indexOf("/Date(") != -1) {
                        // if date is in format /Date(1695333600000)/
                        res = new Date(+dateString.replace(/\D/g, ''));
                    } else {
                        // if date has format 'Sun Feb 14 1988 02:00:00 GMT+0300 (Eastern European Standard Time)'
                        res = new Date(dateString);
                    }

                    res = (res.getYear() + 1900) + "-" + ('0' + (res.getMonth() + 1)).slice(-2) + "-" + ('0' + (res.getDate())).slice(-2);

                    return new Date(res);
                }
            },
            convertDateToObject: function (value) {
                try {
                    if (value) {
                        /*Method .toISOString() converts date with considering current user timezone.
                        That is why we have to add/subtract hours depends on timezone.*/

                        if (typeof value === 'string') {
                            value = this.tryToGetDateObject(value);
                        }
                        var offset = parseInt(new Date().getTimezoneOffset() / 60) - 1;
                        if (isNaN(offset))
                            offset = 0;
                        value.setHours(-offset);

                        return value.toISOString();
                    }
                } catch (e) {
                    console.log("Erorr: " + e);
                }
                return null;
            },
            getElementPayloadValue: function (element) {
                if (element.InputType == this.inputTypes.Date || this.IsSystemDatetime(element))
                    element.Value = this.convertDateToObject(element.Value);

                if (!element.IsVisible)
                    return element.Value;

                if (element.Name == "Employment_¤EmployerName" && element.roleIdForReplace != "") {
                    var roleElement = this.getElementByName("Membership_¤Membership¤RoleID");
                    if (roleElement?.Value == element.roleIdForReplace && element.employerActorIdForReplace) {
                        element.Value = element.employerActorIdForReplace;
                    }
                }

                if (element.InputType == this.inputTypes.Boolean || element.InputType == this.inputTypes.CheckboxSlide) {
                    if (element.Value) {
                        return element.CustomValueForBooleanInput ? element.CustomValueForBooleanInput : "true";
                    } else {
                        return "false";
                    }
                } else if (element.InputType == this.inputTypes.Date || this.IsSystemDatetime(element)) {
                    return this.convertDateToObject(element.Value);
                } else if (element.InputType == this.inputTypes.Radio) {
                    return element.Value === "TOM" ? "" : element.Value;
                } else if (element.InputType == this.inputTypes.Select) {
                    return (!element.Value || element.Value === "_NULL_") ? "" : element.Value;
                } else if (element.InputType == this.inputTypes.Checkbox) {
                    // "Hotels" property has SubValues 
                    // and result is placed to element.value
                    if (this.hasSubValues(element)) {
                        return element.Value;
                    } else {
                        var predefinedValues = element.CheckboxValue;
                        var selectedValues = [];
                        element.Values.forEach(function (el) {
                            selectedValues.push(el.Value);
                        });
                        return predefinedValues.filter(x => selectedValues.includes(x)).join(",");
                    }
                } else {
                    return typeof element.Value !== "undefined" ? element.Value : "";
                }
            },
            hasSubValues: function (element) {
                var res = false;
                element.Values.forEach(function (el) {
                    if (!res && el.SubValues != null && el.SubValues.length > 0) {
                        res = true;
                    };
                });
                return res;
            },
            clickSubmit: function ()
            {
                this.isClickSubmit = true;
            },
            checkButtons: function () {
                if (this.currentPage === 0) {
                    this.showPrevButton = false;
                } else {
                    this.showPrevButton = true;
                }

                if (this.currentPage === this.data.Steps.length - 1) {
                    this.showNextButton = false;
                    this.showSubmit = true;
                } else {
                    this.showSubmit = false;
                    this.showNextButton = true;
                }
            },
            stepIsValid: function () {
                this.stepIsInvalid = false;
                var self = this;

                data.Steps[self.currentPage].Rows.forEach(function (row, rowIndex) {
                    row.Columns.forEach(function (column, columnIndex) {
                        column.Elements.forEach(function (element, elementIndex) {
                            var validatedElement = self.getValidatedElement(element);
                            if (validatedElement.IsInvalid) {
                                self.stepIsInvalid = true;
                            }

                            data.Steps[self.currentPage].Rows[rowIndex].Columns[columnIndex].Elements
                                .splice(elementIndex, 1, validatedElement);
                        });
                    });
                });

                if (!this.stepIsInvalid && this.data.IsCoursePage && this.currentPage === this.data.Steps.length - 1 && this.data.PrivacyPolicyUrl && !this.privacyPolicyAccepted) {
                    this.stepIsInvalid = true;
                    this.showPrivacyPolicyReminder = true;
                } else {
                    this.showPrivacyPolicyReminder = false;
                }

                return !this.stepIsInvalid;
            },
            triggerCustomFunction: function (element) {
                var self = this;
                if (element.AnonymousHiddenFields && element.AnonymousHiddenFields.length > 0) {
                    // Check if element should disable or enable other fields
                    element.AnonymousHiddenFields.forEach(function (name) {
                        var affectedElement = self.getElementByName(name);
                        affectedElement ? affectedElement.Disabled = element.Value : null;
                    });
                }
            },
            getElementByName: function (name) {
                var result;
                this.data.Steps.forEach(function (step) {
                    step.Rows.forEach(function (row) {
                        row.Columns.forEach(function (column) {
                            column.Elements.forEach(function (element) {
                                if (element.Name === name) {
                                    result = element;
                                }
                            });
                        });
                    });
                });
                return result;
            },
            lookupField: function (name) {
                var element = this.getElementByName(name);

                var lookupModel = {
                    startPageId: this.data.StartPageId,
                    method: this.data.Method,
                    name: element.Name,
                    sql: element.LookupSQL,
                    isLegacyWs: this.data.IsLegacyWs,
                    params: []
                };

                for (var i = 0; i < element.LookupField.length; i++) {
                    var field = this.getElementByName(element.LookupField[i]);
                    lookupModel.params.push({
                        name: field.Name,
                        value: field.Value
                    });
                }
                
                this.$http.post(
                    this.surfaceControllerUrl + '/LookUp', lookupModel).then(function (success) {
                        if (element.InputType === this.inputTypes.Text) {
                            if (success.body[0]) {
                                element.Value = success.body[0].Name;
                            } else {
                                element.Value = null;
                            }
                        }
                        else if (element.InputType === this.inputTypes.Checkbox || element.InputType === this.inputTypes.Radio) {
                            element.Values = [];
                            for (var i = 0; i < success.body.length; i++) {
                                element.Values.push(success.body[i]);
                            }
                        }
                    }, function (error) {
                        console.log('error lookupField', error);
                    });
            },
            lookupFieldCallers: function (element) {
                if (!element.LookupFieldCallers)
                    return;

                for (var i = 0; i < element.LookupFieldCallers.length; i++) {
                    this.lookupField(element.LookupFieldCallers[i]);
                }
            },
            isAutocompleteField: function(element) {
                return element.AutopopulateFields;
            },
            isAutocompleteFieldNew: function (element) {
                return element.IsAutocompleteFieldNew;
            },
            autocomplete: function (element, mouseHoverIndex) {

                this.autocompleteData.match = true;
                this.autocompleteData.name = element.Name;

                if (element.LookupSQL == "AUTOCOMPLETE_ACTOR_LOOKUP") {
                    this.autocompleteData.loading = true;
                }

                if (this.autocompleteData.closeTimer) {
                    clearTimeout(this.autocompleteData.closeTimer);
                }

                var select = false;
                var delay = 300;
                if (event.keyCode === 27) {
                    this.resetAutocomplete();
                } else if (event.keyCode === 38) {
                    this.autocompleteData.selectedIndex--;
                    if (this.autocompleteData.selectedIndex < -1) {
                        this.autocompleteData.selectedIndex = -1;
                    }
                    return;
                } else if (event.keyCode === 40) {
                    this.autocompleteData.selectedIndex++;
                    if (this.autocompleteData.selectedIndex > this.autocompleteData.results.length - 1) {
                        this.autocompleteData.selectedIndex = this.autocompleteData.results.length - 1;
                    }
                    return;
                } else if (event.keyCode === 13) {
                    select = true;
                }
                else if (event.type === 'mouseover' && !isNaN(mouseHoverIndex)) {
                    this.autocompleteData.selectedIndex = mouseHoverIndex;
                }
                else if (event.type === 'click' && !isNaN(mouseHoverIndex)) {
                    this.autocompleteData.selectedIndex = mouseHoverIndex;
                    select = true;
                } else {
                    this.autocompleteData.selectedIndex = -1;
                }

                var lookupModel = {
                    startPageId: this.data.StartPageId,
                    method: this.data.Method,
                    name: element.Name,
                    value: element.Value,
                    sql: element.LookupSQL,
                    isLegacyWs: this.data.IsLegacyWs,
                    params: []
                };

                if (element.LookupSQL == "AUTOCOMPLETE_ACTOR_LOOKUP") {
                    delay = 0;
                    for (var i = 0; i < element.AutopopulateFields.length; i++) {
                        lookupModel.params.push({
                            name: element.AutopopulateFields[i]
                        });
                    }

                } else if (select) {
                    delay = 0;
                    if (this.autocompleteData.selectedIndex != -1)
                        lookupModel.value = this.autocompleteData.results[this.autocompleteData.selectedIndex].Value;
                    for (var i = 0; i < element.AutopopulateFields.length; i++) {
                        lookupModel.params.push({
                            name: element.AutopopulateFields[i]
                        });
                    }
                }

                if (!element.Value || element.Value.length < 3) {
                    this.resetAutocomplete();
                    for (prop in element.AutopopulateFields) {
                        var elm = this.getElementByName(element.AutopopulateFields[prop]);
                        if (elm && elm.AutocompleteValue && elm.Name !== element.Name) {
                            elm.Value = "";
                        }
                    }
                    return;
                }
                if (element.LookupSQL == "AUTOCOMPLETE_ACTOR_LOOKUP" && !select) {
                    // waits for enter
                    this.resetAutocomplete();
                    for (prop in element.AutopopulateFields) {
                        var elm = this.getElementByName(element.AutopopulateFields[prop]);
                        if (elm && elm.AutocompleteValue && elm.Name !== element.Name) {
                            elm.Value = "";
                        }
                    }
                    return;
                }

                if (this.autocompleteData.requestTimer) {
                    clearTimeout(this.autocompleteData.requestTimer);
                }
                var that = this;
                this.autocompleteData.requestTimer = setTimeout(function () {
                    that.$http.post(
                        that.surfaceControllerUrl + '/LookUp', lookupModel).then(function (success) {
                            
                            if (lookupModel.params.length > 0) {

                                if (success.body.length === 0) {
                                    that.autocompleteData.match = false;
                                    that.resetAutocomplete();
                                }
                                else {
                                    for (prop in success.body) {
                                        var elm = that.getElementByName(success.body[prop].Name);
                                        if (elm && success.body[prop].Value) {
                                            elm.Value = success.body[prop].Value;
                                            elm.AutocompleteValue = true;
                                        }
                                    }
                                    that.resetAutocomplete();
                                }
                            } else {
                                that.autocompleteData.results = success.body;
                                if (success.body.length === 0) {
                                    that.autocompleteData.match = false;
                                }                           
                            }
                        },
                            function (error) {
                                console.log('error autocomplete', error);
                                that.autocompleteData.match = false;
                            }
                        ).bind(that);

                }, delay);
            },
            resetAutocomplete: function () {
                this.autocompleteData.loading = false;
                this.autocompleteData.results = [];
                this.autocompleteData.selectedIndex = -1;
            },
            autocompleteFocus: function (element) {
                var a = element.Value;
            },
            autocompleteKeyup: function (element) {
                var a = element.Value;
            },
            autocompleteFrontend: function (element, event) {
                this.autocompleteData.match = true;
                this.autocompleteData.name = element.Name;
                                           
                if (this.autocompleteData.requestTimer) {
                    clearTimeout(this.autocompleteData.requestTimer);
                }
                this.autocompleteSearch(element, event);
            },
            autocompleteSearch: function (element, event) {
                this.resetAutocomplete();
                if (element.IsAutocompleteFieldNew == true && !this.employersLoaded) {
                    this.autocompleteData.results.push('Loading...');
                    return;
                }

                // Request /GetAvailableActiveCompanies sometimes reset autocompleteData.results
                // That's why we need push('Loading....') again, until finish /ActiveTitles
                if (element.Name == "Employment_¤Title_Text" || element.Name == "Title_Text") {
                    if (element.IsAutocompleteFieldNew == true && element.Values.length == 0) {
                        this.autocompleteData.results.push('Loading....');
                        element.disabled = true;
                        return;
                    }
                }

                element.SelectValue = null;
                var that = this;

                // HACK: we get autocomlete values from $refs if OS is Android or iOS
                var searchStr = element.Value;
                if (navigator.userAgent.toLowerCase().indexOf("android") != -1 ||
                    navigator.userAgent.toLowerCase().indexOf("like mac") != -1) {
                    this.$refs.autocomplete.forEach(function(item) {
                        if(item.id == element.Name) {
                            searchStr = item.value;
                        }
                    });
                }

                element.Values?.forEach(function (elmName) {
                    var itemName = elmName.Name;
                    if (searchStr == null) {// no search letters just show all
                        that.autocompleteData.results.push(itemName);
                    }
                    else {
                        var beginingOfItem = itemName.substring(0, searchStr.length);
                        var indOf = itemName.toUpperCase().indexOf(searchStr.toUpperCase());

                        if (element.Name == "Employment_¤Position_Code_Text" || element.Name == "Position_Code_Text") {
                            if (itemName.toUpperCase().indexOf(searchStr.toUpperCase()) >= 0) {
                                itemName = itemName.substring(0, indOf) + "<b>" + itemName.substring(indOf, indOf + searchStr.length) + "</b>"
                                    + itemName.substring(indOf + searchStr.length, itemName.length);
                                that.autocompleteData.results.push(itemName);
                            }
                        } else {
                            if (beginingOfItem.toUpperCase() == searchStr.toUpperCase()) {
                                itemName = "<b>" + beginingOfItem + "</b>" + itemName.substring(searchStr.length, itemName.length);
                                that.autocompleteData.results.push(itemName);
                            }
                            else if (searchStr.length >= 3 && indOf != -1) {
                                itemName = itemName.substring(0, indOf) + "<b>" + itemName.substring(indOf, indOf + searchStr.length) + "</b>"
                                    + itemName.substring(indOf + searchStr.length, itemName.length);
                                that.autocompleteData.results.push(itemName);
                            }
                        }
                    }
                })

                var indOfIngetTreff = element.Label.indexOf(" - INGEN TREFF");

                if (this.autocompleteData.results.length == 0 && element.ShowNewEmploerFields && this.employersLoaded) {
                    // Show employment adr
                    console.log("Show employer adr");
                    var adr = this.getElementByName('Employment_¤EmployerAdress¤Adr2_S') || this.getElementByName('EmployerAdress¤Adr2_S');
                    if (adr != null) {
                        adr.IsVisible = true;
                        adr.RequiredByCustomer = true;
                    }
                    var postal = this.getElementByName('Employment_¤EmployerAdress¤PostalCode_S') || this.getElementByName('EmployerAdress¤PostalCode_S');
                    if (postal != null) {
                        postal.IsVisible = true;
                        postal.RequiredByCustomer = true;
                    }
                    var street = this.getElementByName('Employment_¤EmployerAdress¤StreetCity_S') || this.getElementByName('EmployerAdress¤StreetCity_S');
                    if (street != null) {
                        street.IsVisible = true;
                        street.RequiredByCustomer = true;
                    }
                    var city = this.getElementByName('Employment_¤EmployerAdress¤CityName_S') || this.getElementByName('EmployerAdress¤CityName_S');
                    if (city != null) {
                        city.IsVisible = true;
                        city.RequiredByCustomer = true;
                    }
                    
                    if (that.data.Method === "UnionToken") {
                        //hide
                        console.log("Union token - hide PositonCodeText and paygrade");
                        var position = this.getElementByName('Employment_¤Position_Code_Text') || this.getElementByName('Position_Code_Text');
                        if (position != null) {
                            position.IsVisible = false;
                        }
                        var payGrade = this.getElementByName('Employment_¤PayGrade') || this.getElementByName('Employment_¤PayGrade');
                        if (payGrade != null) {
                            payGrade.IsVisible = false;
                        }
                    }
                    var employerActorID = this.getElementByName('EmployerActorID') || this.getElementByName('Employment_¤EmployerActorID');
                    if (employerActorID != null) {
                        employerActorID.Value = null;
                    }

                    if (indOfIngetTreff == -1) {
                        element.Label = element.Label + " - INGEN TREFF";
                        if (that.data.Method === "UnionToken") {
                            console.log("Union token - showTitleHidePositionAndPaygrade");
                            this.showTitleHidePositionAndPay();
                        }
                    }
                    this.isPosting = false;
                }
                else if (element.ShowNewEmploerFields) {
                    // hide employer adr
                    console.log("Hide employer adr");
                    var adr = this.getElementByName('Employment_¤EmployerAdress¤Adr2_S') || this.getElementByName('EmployerAdress¤Adr2_S');
                    if (adr != null) {
                        adr.IsVisible = false;
                        adr.Value = null;
                        adr.RequiredByCustomer = false;
                    }
                    var postal = this.getElementByName('Employment_¤EmployerAdress¤PostalCode_S') || this.getElementByName('EmployerAdress¤PostalCode_S');
                    if (postal != null) {
                        postal.IsVisible = false;
                        postal.Value = null;
                        postal.RequiredByCustomer = false;
                    }
                    var street = this.getElementByName('Employment_¤EmployerAdress¤StreetCity_S') || this.getElementByName('EmployerAdress¤StreetCity_S');
                    if (street != null) {
                        street.IsVisible = false;
                        street.Value = null;
                        street.RequiredByCustomer = false;
                    }
                    var city = this.getElementByName('Employment_¤EmployerAdress¤CityName_S') || this.getElementByName('EmployerAdress¤StreetCityName_S');
                    if (city != null) {
                        city.IsVisible = false;
                        city.Value = null;
                        city.RequiredByCustomer = false;
                    }
                    // show
                    if (that.data.Method === "UnionToken") {
                        console.log("Union token - show PositonCodeText and paygrade");
                        var position = this.getElementByName('Employment_¤Position_Code_Text') || this.getElementByName('Position_Code_Text');
                        if (position != null) {
                            position.IsVisible = true;
                        }
                        var payGrade = this.getElementByName('Employment_¤PayGrade') || this.getElementByName('PayGrade');
                        if (payGrade != null) {
                            payGrade.IsVisible = true;
                        }
                    }

                    if (indOfIngetTreff != -1)
                        element.Label = element.Label.substring(0, indOfIngetTreff);
                } else {
                    this.fillTitles();
                }

                this.autocompleteKeys(element, event);
            },
            selectAutocompleteItem: function (element, selectedValue) {
                var start1 = selectedValue.indexOf("<b>");
                var start2 = selectedValue.indexOf("</b>");
                var stringWithoutFormating;
                if (start1 == -1) { // no search just show all list
                    stringWithoutFormating = selectedValue;
                    element.Value = selectedValue;
                }
                else {
                    stringWithoutFormating = selectedValue.substring(0, start1) + selectedValue.substring(start1 + 3, start2)
                        + selectedValue.substring(start2 + 4, selectedValue.length)
                    element.Value = stringWithoutFormating;
                }

                var employerActorID = this.getElementByName('EmployerActorID') || this.getElementByName('Employment_¤EmployerActorID');
                var positions = this.getElementByName('Position_Code') || this.getElementByName('Employment_¤Position_Code');
                var positionsText = this.getElementByName('Position_Code_Text') || this.getElementByName('Employment_¤Position_Code_Text');
                var titles = this.getElementByName('Position_Title') || this.getElementByName('Employment_¤Position_Title');
                var paygrade = this.getElementByName('PayGrade') || this.getElementByName('Employment_¤PayGrade');

                var that = this;
                element.Values.forEach(function (elmName) {
                    if (stringWithoutFormating == elmName.Name) {

                        element.SelectValue = elmName.Value;

                        if (element.Name == 'Employment_¤EmployerName' || element.Name == 'EmployerName') {

                            if (employerActorID) {
                                // fill employerActorID
                                employerActorID.Value = elmName.Value;
                                
                                that.hideShowEmploeyrLinkedFields(element, elmName);
                            }

                            if (that.data.Method === "UnionToken") {
                                if (element.AVTKodes) {

                                    console.log("UnionToken - AVTKODE has value", element.AVTKodes);

                                    if (!(that.agreementCodes.indexOf(parseInt(elmName.AgCod)) > -1)) {
                                        console.log("UnionToken - AGREEMENT_CODE " + elmName.AgCod + " not in agreementCodes [700, 801, 803] - hide PositionCodeText and Paygrade");
                                        if (positionsText) {
                                            positionsText.IsVisible = false;
                                        }
                                        if (paygrade) {
                                            paygrade.IsVisible = false;
                                        }
                                    }
                                    else {
                                        console.log("UnionToken - AGREEMENT_CODE " + elmName.AgCod + " in agreementCodes [700, 801, 803] - fill positions");
                                        that.fillPositions(elmName.AgCod);
                                    }
                                }
                                else {
                                    console.log("UnionToken - AVTKODE is empty - fill positions for AGREEMENT_CODE " + elmName.AgCod);
                                    that.fillPositions(elmName.AgCod);
                                }
                            }

                            // for EmploymentCreate we need to fill positions
                            if (that.data.Method === "EmploymentCreate" || that.data.Method === "Employment") {
                                that.fillPositions(elmName.AgCod);
                            }
                        }

                        if (element.Name == 'Position_Code_Text' || element.Name == 'Employment_¤Position_Code_Text') {
                            if (positions) {
                                positions.Value = element.SelectValue;
                            }
                        }
                        if (element.Name == 'Title_Text' || element.Name == 'Employment_¤Title_Text') {
                            if (titles != null) {
                                titles.Value = element.SelectValue;
                            }
                        }
                    }
                });
                this.resetAutocomplete();
                this.isPosting = false;
                this.setDisablePaymentButtons(false);
            },
            autocompleteInput: function (element, ev) {
                // HACK: substr() was added, because :maxlength="" isn't supported in elder versions of Android Chrome
                if (ev.target.maxLength > 0) {
                    ev.target.value = ev.target.value.substr(0, ev.target.maxLength);
                }
                if (element.Name == "Title_Text" || element.Name == 'Employment_¤Title_Text') {
                    // Title_Text is changed - empty Position_Title (kode) (If a new selection is done, we will get new code)
                    var titles = this.getElementByName('Position_Title') || this.getElementByName('Employment_¤Position_Title');
                    if (titles != null) {
                        titles.Value = null;
                        titles.SelectValue = null;
                    }
                }
                this.Value = ev.target.value;
            },
            autocompleteBlur: function (ev) {
                this.isPosting = false;
            },
            autocompleteKeys: function (element, event) {
                if (event == null) return true;
                if (this.autocompleteCurrName != element.Name)
                {
                    this.autocompleteCurrName = element.Name;
                    this.autocompleteSelectedItem = 0;
                }

                if (element.ShowNewEmploerFields) {
                    this.isPosting = true;
                }

                this.setDisablePaymentButtons(true);

                if (event.keyCode == this.keys.Backspace || event.keyCode == this.keys.Del)
                {
                    this.autocompleteSelectedItem = 0;
                }

                var autocomplete = document.getElementsByClassName('autocomplete-items');
                var count = 0;
                if (autocomplete[0] != null)
                {
                    count = autocomplete[0].childNodes.length;
                }

                if (event.keyCode == this.keys.Enter)
                {
                    if (!element.isChooseFromList || this.autocompleteSelectedItem > 0) {
                        if (autocomplete[0].childNodes[this.autocompleteSelectedItem] != null) {
                            autocomplete[0].childNodes[this.autocompleteSelectedItem].style.backgroundColor = this.autocompleteActiveBgColor;
                        }
                        if (autocomplete[0].childNodes[(this.autocompleteSelectedItem - 1)] != null) {
                            element.Value = autocomplete[0].childNodes[(this.autocompleteSelectedItem - 1)].innerText;
                        }
                        this.resetAutocomplete();
                        if (element.Value.length = 0) {
                            this.isPosting = false;
                        }
                        this.selectAutocompleteItem(element, element.Value);
                    }
                }
                if (event.keyCode == this.keys.Down) {
                    if (this.autocompleteSelectedItem < count) {
                        if (this.autocompleteSelectedItem - 1 >= 0) {
                            autocomplete[0].childNodes[(this.autocompleteSelectedItem - 1)].style.backgroundColor = this.autocompleteBgColor;
                        }
                        this.autocompleteSelectedItem++;
                        autocomplete[0].childNodes[(this.autocompleteSelectedItem - 1)].style.backgroundColor = this.autocompleteActiveBgColor;
                    }
                }
                if (event.keyCode == this.keys.Up) {
                    if (this.autocompleteSelectedItem > 1) {
                        autocomplete[0].childNodes[(this.autocompleteSelectedItem - 1)].style.backgroundColor = this.autocompleteBgColor;
                        this.autocompleteSelectedItem--;
                        autocomplete[0].childNodes[(this.autocompleteSelectedItem - 1)].style.backgroundColor = this.autocompleteActiveBgColor;
                    }
                }
            },
            hideShowEmploeyrLinkedFields: function (element, elmName) {
                var agreementCode = elmName.AgCod;
                var AVTKodes = element.AVTKodes;
                //console.log("AVTKodes", AVTKodes)

                if (AVTKodes) {
                    if (AVTKodes != null && agreementCode && AVTKodes.indexOf(agreementCode) != -1) {
                        console.log("AGREEMENT_CODE ", agreementCode, " is in AVTKODE ", AVTKodes, " - fill positions");
                        this.fillPositions(agreementCode);
                    }
                    else {
                        console.log("AGREEMENT_CODE ", agreementCode, "not in AVTKODE ", AVTKodes);
                        this.showTitleHidePositionAndPay();
                    }
                }
            },
            showTitleHidePositionAndPay: function () {
                console.log("showTitleHidePositionAndPayGrade");
                var position = this.getElementByName('Employment_¤Position_Code_Text') || this.getElementByName('Position_Code_Text');
                if (position != null) {
                    position.IsVisible = false;
                    position.Value = null;
                    position.SelectValue = null;
                }
                var payGrade = this.getElementByName('Employment_¤PayGrade') || this.getElementByName('PayGrade');
                if (payGrade != null)
                    payGrade.Value = null;

                var title = this.getElementByName('Employment_¤Title_Text')  || this.getElementByName('Title_Text');
                if (title != null)
                    title.IsVisible = true;
                    this.fillTitles();
            },
            fillPositions: function (agreementCode) {
                if (!agreementCode)
                    return;
                var positions = this.getElementByName('Employment_¤Position_Code_Text') || this.getElementByName('Position_Code_Text');
                if (positions != null) {
                    var params = {
                        startPageId: this.data.StartPageId,
                        method: agreementCode
                    };
                    this.$http.post(
                        this.surfaceControllerUrl + '/GetAvailablePositions', params).then(function (success) {
                            positions.Values = [];
                            if (success.body.length > 0) {
                                for (var i = 0; i < success.body.length; i++) {
                                    positions.Values.push(success.body[i]);
                                }
                                // we have values - show positions
                                positions.IsVisible = true;
                            }
                            else {
                                console.log("No available positions for AVTALEKODE " + agreementCode);
                            }
                    });
                }
            },     
            fillTitles: function () {
                // the initialization of Title_Text autocomplete if a form contains it
                var titles = this.getElementByName('Employment_¤Title_Text') || this.getElementByName('Title_Text');
                if (titles?.Values.length == 0) {
                    var params = {
                        startPageId: this.data.StartPageId
                    };
                    this.$http.post(
                        this.surfaceControllerUrl + '/ActiveTitles', params).then(function (success) {
                            titles.Values = [];
                            for (var i = 0; i < success.body.length; i++) {
                                titles.Values.push(success.body[i]);
                            }
                            this.autocompleteData.results = [];
                        });
                }
            },  
            clearInput: function (element) {
                element.Value = "";
                this.resetAutocomplete();
                this.isPosting = false;

                var employerActorID = this.getElementByName('EmployerActorID') || this.getElementByName('Employment_¤EmployerActorID');
                var positions = this.getElementByName('Position_Code') || this.getElementByName('Employment_¤Position_Code');
                var positionsText = this.getElementByName('Position_Code_Text') || this.getElementByName('Employment_¤Position_Code_Text');
                var titles = this.getElementByName('Position_Title') || this.getElementByName('Employment_¤Position_Title');

                if ((element.Name == 'Employment_¤EmployerName') || (element.Name == 'EmployerName')) {
                    if (employerActorID != null) {
                        employerActorID.Value = null;
                    }
                    if (positions != null) {
                        positions.Value = null;
                        positions.SelectValue = null;
                    }
                    if (positionsText != null) {
                        positionsText.Value = null;
                        positionsText.SelectValue = null;
                    }
                }
                if ((element.Name == 'Title_Text') || (element.Name == 'Employment_¤Title_Text')) {
                    if (titles != null) {
                        titles.Value = null;
                        titles.SelectValue = null;
                    }
                }
                if ((element.Name == 'Position_Code_Text') || (element.Name == 'Employment_¤Position_Code_Text')) {
                    if (positions != null) {
                        positions.Value = null;
                        positions.SelectValue = null;
                    }
                }
                
                this.setDisablePaymentButtons(false);
            },
            setDisablePaymentButtons: function (status) {
                if (document.getElementsByClassName('payment-type-buttons').length > 0) {
                    var paymentButtons = document.getElementsByClassName('payment-type-buttons')[0].childNodes;
                    if (paymentButtons.length > 0) {
                        paymentButtons.forEach(function (item) {
                            if (item.type == "submit") {
                                item.disabled = status;
                            }
                        });
                    }
                }
            },
            getMaxLength: function (element) {
                if (!element.Validate)
                    return '';
                if (element.Validate === 'SSN')
                    return '11';
                if (element.Validate === 'ZIP')
                    return '4';
                if (element.MaxLength && !isNaN(element.MaxLength)) {
                    return element.MaxLength;
                }
            },
            getMaxLengthTextArea: function (element) {
                return parseInt(element.MaxLengthTextArea);
            },
            getValidatedElement: function (element) {
                this.postSuccess.success = false;
                if (!element.IsVisible)
                    return element;

                if (!element.Value) {
                    element.IsInvalid = element.RequiredByCustomer && !element.Disabled;
                    if (element.IsInvalid) {
                        element.IsInvalidMessage = "Må fylles ut";
                    }
                } else {
                    this.lookupFieldCallers(element);
                    element.IsInvalid = !element.Disabled && !elementIsValid(element, this);
                }

                var that = this;
                this.autocompleteData.closeTimer = setTimeout(function () {
                    that.resetAutocomplete();
                }, 300);

                function elementIsValid(element, self) {
                    switch (element.Validate) {
                        case 'Text':
                        case 'Anonymous':

                            if (element.Name == "Membership_¤Membership¤RoleID") {
                                if (element.IsInvalid) {
                                    return false;
                                } else {
                                    return true;
                                }
                            }

                            if (customTextNumberInputWasEntered(self)) {
                                if (!customTextNumberInputIsValidInt()) {
                                    element.IsInvalidMessage = "Må være et heltall";
                                    return false;
                                }
                                if (!customTextNumberInputIsValidMinValue()) {
                                    element.IsInvalidMessage = "Minste gyldige verdi er " + element.CustomTextInputMinValue;
                                    return false;
                                }
                            }
                            return true;
                        case 'Email':
                            var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
                            if (!re.test(element.Value.toLowerCase())) {
                                element.IsInvalidMessage = "Ikke gyldig e-postadresse";
                                return false;
                            }
                            return true;
                        case 'Phone':
                            if (element.Value == '') {
                                return true;
                            }


                                
                            if (!new RegExp("^(\\+|00)[\\d]{10,11}$|^[\\d]{7,8}$").test(element.Value.replaceAll(" ", ""))) {
                                element.IsInvalidMessage = "Ikke gyldig telefonnummer";
                                return false;
                            }
                            return true;
                        case 'SSN':
                            if (!isValidSSN(element.Value)) {
                                element.IsInvalidMessage = "Ikke gyldig personnummer";
                                return false;
                            }
                            return true;
                        case 'Date':
                            if (element.Name == "Actor¤Birthdate") {
                                element.StringValue = element.Value;
                            }

                            //var s = Object.prototype.toString.call(element.Value);
                            //var ss = typeof self.tryToGetDateObject(element.Value);
                            if (Object.prototype.toString.call(element.Value) !== '[object Date]') {
                                if (typeof self.tryToGetDateObject(element.Value) !== 'object') {
                                    element.IsInvalidMessage = "Ikke gyldig dato";
                                    return false;
                                } else {
                                    element.Value = self.tryToGetDateObject(element.Value);
                                }
                            }

                            if (isNaN(element.Value.getTime())) {
                                element.IsInvalidMessage = "Ikke gyldig dato";
                                return false;
                            }
                            return true;
                        case 'ORGNR':
                            if (!isValidOrganizationNumber(element.Value)) {
                                element.IsInvalidMessage = "Ikke gyldig organisasjonsnummer";
                                return false;
                            }
                            return true;
                        case 'SSNOrORGNR':
                            if (!isValidOrganizationNumber(element.Value) && !isValidSSN(element.Value)) {
                                element.IsInvalidMessage = "Ikke gyldig personnummer eller organisasjonsnummer";
                                return false;
                            }
                            return true;
                        case 'BankAccountNumber':
                            if (!isValidBankAccountNumber(element.Value)) {
                                element.IsInvalidMessage = "Ikke gyldig bankkontonummer";
                                return false;
                            }
                            return true;
                        case 'ZIP':
                            if (new RegExp("^[\\d]{4}$|^[A-Z]{2}$").test(element.Value)) {
                                return true;
                            }
                            element.IsInvalidMessage = "Må være fire siffer eller gyldig landkode";
                            return false;
                        case 'DateString':
                            if (Object.prototype.toString.call(element.Value) !== '[object Date]') {
                                if (typeof self.tryToGetDateObject(element.Value) !== 'object') {
                                    element.IsInvalidMessage = "Ikke gyldig dato";
                                    return false;
                                }
                            }
                            return true;
                        case 'Year':
                            if (new RegExp("^[\\d]{4}$").test(element.Value)) {
                                var year = parseInt(element.Value);
                                if (year >= 1900 && year <= 2100)
                                    return true;
                            }

                            element.IsInvalidMessage = "Ikke gyldig årstall";
                            return false;
                        case 'LettersAndWhitespace':
                            if (new RegExp("^[a-zæøåA-ZÆØÅ\u00c0-\u017e\\s\\-]*$").test(element.Value)) {
                                return true;
                            }
                            element.IsInvalidMessage = "Ikke gyldig verdi";
                            return false;
                        default:
                            return false;
                    }
                }

                function stringContainsRowOfNumbers(length) {
                    // ref: https://stackoverflow.com/questions/4338267/validate-phone-number-with-javascript
                    var res = element.Value.match(/\d/g);

                    return res && res.length === length;
                }

                function isValidOrganizationNumber(value) {

                    var weights = [3,2,7,6,5,4,3,2];

                    var orgNr = value.replace(/\s/g, "");

                    if (orgNr.length !== 9)
                        return false;

                    if (orgNr[0] !== '8' && orgNr[0] !== '9')
                        return false;

                    var sum = 0;
                    for (var i = 0; i < weights.length; i++) {
                        sum += parseInt(orgNr[i]) * weights[i];
                    }

                    var lastDigit = parseInt(orgNr[8]);

                    var control = 11 - sum % 11;
                    if (control === 11)
                        control = 0;

                    return lastDigit === control;
                }

                function isValidBankAccountNumber(bankAccountNumber) {
                    const weights = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2];
                    const bankAccountNumberWithoutSpacesAndPeriods = bankAccountNumber.replace(/[\s.]+/g, '');
                    if (bankAccountNumberWithoutSpacesAndPeriods.length !== 11) {
                        return false;
                    } else {
                        const controlDigit = parseInt(bankAccountNumberWithoutSpacesAndPeriods.charAt(10), 10);
                        const accountNumberWithoutControlDigit = bankAccountNumberWithoutSpacesAndPeriods.substring(0, 10);
                        let sum = 0;
                        for (let index = 0; index < 10; index++) {
                            sum += parseInt(accountNumberWithoutControlDigit.charAt(index), 10) * weights[index];
                        }
                        const remainder = sum % 11;
                        return controlDigit === (remainder === 0 ? 0 : 11 - remainder);
                    }
                }

                function isValidSSN(value) {
                    var regex11Digits = new RegExp("^[\\d]{11}$");
                    if (!regex11Digits.test(value)) {
                        return false;
                    }
                    var d1 = parseInt(value.substring(0, 1));
                    var d2 = parseInt(value.substring(1, 2));
                    var m1 = parseInt(value.substring(2, 3));
                    var m2 = parseInt(value.substring(3, 4));
                    var y1 = parseInt(value.substring(4, 5));
                    var y2 = parseInt(value.substring(5, 6));
                    var i1 = parseInt(value.substring(6, 7));
                    var i2 = parseInt(value.substring(7, 8));
                    var g = parseInt(value.substring(8, 9));
                    var c1 = parseInt(value.substring(9, 10));
                    var c2 = parseInt(value.substring(10, 11));
                    var calculatedC1 = 11 - (3 * d1 + 7 * d2 + 6 * m1 + 1 * m2 + 8 * y1 + 9 * y2 + 4 * i1 + 5 * i2 + 2 * g) % 11;
                    if (calculatedC1 === 11) {
                        calculatedC1 = 0;
                    }
                    var calculatedC2 = 11 - (5 * d1 + 4 * d2 + 3 * m1 + 2 * m2 + 7 * y1 + 6 * y2 + 5 * i1 + 4 * i2 + 3 * g + 2 * c1) % 11;
                    if (calculatedC2 === 11) {
                        calculatedC2 = 0;
                    }
                    // Check that the control numbers are correct
                    if (c1 === calculatedC1 && c2 === calculatedC2) {
                        return true;
                    } else {
                        return false;
                    }
                }

                function customTextNumberInputWasEntered(self) {
                    return (element.InputType === self.inputTypes.Radio || element.InputType === self.inputTypes.Select)
                        && (element.RadioValue === self.CustomTextInputConstant || element.SelectValue === self.CustomTextInputConstant)
                        && element.CustomTextInputIsNumber;
                }

                function customTextNumberInputIsValidInt() {
                    return parseInt(element.Value);
                }
                function customTextNumberInputIsValidMinValue() {
                    return parseInt(element.Value) && element.Value >= element.CustomTextInputMinValue;
                }

                return element;
            },
            processElement: function (stepIndex, rowIndex, columnIndex, elementIndex, value, willReceivePredefinedValuesInFrontend, values, isCheckboxElement, isSelected, uniqueId, disableValues) {
                this.setElementValue(stepIndex, rowIndex, columnIndex, elementIndex, value, null);

                if (willReceivePredefinedValuesInFrontend) {
                    this.addOrRemoveOrderedItems(values.Name, values.Price, isCheckboxElement, isSelected, elementIndex, uniqueId);
                }

                if (disableValues) {
                    if (isSelected) {
                        this.disabledValueCollection.push({k: uniqueId,v: disableValues});
                    } else {
                        var disabledItemIndex = this.disabledValueCollection.map(function (o) { return o.k; }).indexOf(uniqueId);
                        this.disabledValueCollection.splice(disabledItemIndex, 1);
                    }
                }

                this.updateSwithToggleButtonVisibility();
            },
            isValueDisabled: function (curValue, subVaules, CheckboxValues) {
               for (var i = 0; i < subVaules.length; i++) {
                    if (subVaules[i].GeneratedId == curValue.GeneratedId) {
                        //find previous date range
                        var prevValueDateEnd;
                        var prevValueChecked = false;                        
                        if (i - 1 > -1) {
                            prevValueDateEnd = subVaules[i - 1].DateEnd;
                            var prevValueID = subVaules[i - 1].GeneratedId;
                            if (CheckboxValues.indexOf(prevValueID)>-1)
                               prevValueChecked = true;
                        }
                        if (prevValueChecked && prevValueDateEnd > curValue.DateStart)
                            return true;
                        //find next date range
                        var nextValuetDateStart;
                        var nextValueChecked = false;
                        if (i + 2 <= subVaules.length) {
                            nextValuetDateStart = subVaules[i + 1].DateStart;
                            var nextValueID = subVaules[i + 1].GeneratedId;
                            if (CheckboxValues.indexOf(nextValueID) > -1)
                                nextValueChecked = true;
                        }

                        if (nextValueChecked && nextValuetDateStart < curValue.DateEnd)
                            return true;
                    }
                }

                return false;
            },
            addOrRemoveOrderedItems: function (name, price, isCheckboxElement, isSelected, elementIndex, uniqueId) {
                var self = this;

                var addItem = function (name, price, elementIndex, uniqueId) {
                    self.orderedItems.push({
                        name: name,
                        price: parseInt(price),
                        elementIndex: elementIndex,
                        uniqueId: uniqueId
                    });
                };

                if (isCheckboxElement) {
                    var checkboxItemIndex = this.orderedItems.map(function (o) { return o.uniqueId; }).indexOf(uniqueId);

                    if (isSelected) {
                        if (checkboxItemIndex < 0) {
                            addItem(name, price, elementIndex, uniqueId);
                        }
                    } else {
                        this.orderedItems.splice(checkboxItemIndex, 1);
                    }
                } else {
                    var radioItemIndex = this.orderedItems.map(function (o) { return o.elementIndex; }).indexOf(elementIndex);

                    if (radioItemIndex >= 0) {
                        this.orderedItems.splice(radioItemIndex, 1);
                    }

                    addItem(name, price, elementIndex, uniqueId);
                }
            },
            setElementValue: function (stepIndex, rowIndex, columnIndex, elementIndex, value, element) {

                // except Membership¤Fellowship and Fellowship, because they are as autocomplete
                // and Value=SelectValue isn't needed for them
                if (element) {
                    if (element.Name == "Membership¤Fellowship" || element.Name == "Fellowship") {
                        return;
                    }
                }

                if (value !== this.CustomTextInputConstant) {
                    // SelectValue has to be updated for don't reset element to initial value during submitting form
                    this.data.Steps[stepIndex].Rows[rowIndex].Columns[columnIndex].Elements[elementIndex].Value = value;
                    if (element) {
                        this.data.Steps[stepIndex].Rows[rowIndex].Columns[columnIndex].Elements[elementIndex].Value = element.SelectValue;
                    }
                } else {
                    this.data.Steps[stepIndex].Rows[rowIndex].Columns[columnIndex].Elements[elementIndex].Value = '';
                }
                if (element !== null && element.Values !== null) {
                    for (var i = 0; i < element.Values.length; i++) {
                        if (element.Values[i].Value == value) {
                            /*if (element.Values[i].DirectPrice > 0) {
                                this.getElementByName('FORSTE_PRIS').Value = element.Values[i].DirectPrice;
                            }*/
                        }
                    }
                }
                this.postSuccess.success = false;
                this.toggleElement(this.data.Steps[stepIndex].Rows[rowIndex].Columns[columnIndex].Elements[elementIndex]);
                if (element != null && element.Name == "Membership¤RoleID") {
                    this.changeMembershipButton = true;
                }

                this.checkRoleId();
                
                if (element) {
                    if ((element.Name == 'Employment_¤LeaveStart' || element.Name == 'LeaveStart')
                        || (element.Name == 'Employment_¤LeaveEnd' || element.Name == 'LeaveEnd')) {
                        this.checkLeaveEndAgainstLeaveStart();
                    }
                    if (element.Name == 'Employment_¤EmploymentsToAddLeave' || element.Name == 'EmploymentsToAddLeave') {
                        this.onEmploymentsToAddLeaveChange();
                    }
                    if ((element.Name == "Employment_¤EmployerActorID" || element.Name == "EmployerActorID")
                        && (element.InputType == this.inputTypes.Select) && element.IsVisible) {

                        // If only at set of employers is set up as select options and added in umbraco
                        this.fillEmployerNameFromEmployerActorID();
                    }
                }
            },
            checkRoleId() {
                var roleId = this.getElementByName('Membership_¤Membership¤RoleID') || this.getElementByName('Membership¤RoleID');
                if (roleId) {
                    if (!this.isRoleIdCorrect(roleId)) {
                        roleId.IsInvalid = true;
                        roleId.IsInvalidMessage = "Du kan ikke bruke denne rollen med NETAXEPT";
                    } else {
                        roleId.IsInvalid = false;
                        roleId.IsInvalidMessage = "";
                    }
                }
            },
            fillEmployerNameFromEmployerActorID() {
                // If only at set of employers is set up as select options and added in umbraco
                var employerActorID = this.getElementByName('EmployerActorID') || this.getElementByName('Employment_¤EmployerActorID');
                var employerName = this.getElementByName('EmployerName') || this.getElementByName('Employment_¤EmployerName');

                if (employerActorID && employerName && employerActorID.InputType == this.inputTypes.Select && employerActorID.IsVisible) {
                    // fill employerName - Get the title of the select option using summaryGetCheckboxValues
                    employerName.Value = this.summaryGetCheckboxValues(employerActorID)[0];

                    console.log("employerName 2", employerName.Value, "employerActorID", employerActorID.Value);
                }
            },
            onEmploymentsToAddLeaveChange() { 
                var employmentsToAddLeave = this.getElementByName('Employment_¤EmploymentsToAddLeave') || this.getElementByName('EmploymentsToAddLeave');
                if (employmentsToAddLeave && employmentsToAddLeave.Value) {
                    var actorId = this.getElementByName('Actor¤ActorID') || this.getElementByName('Membership_¤Actor¤ActorID');
                    var params = {
                        ActorId: actorId.Value,
                        EmploymentId: employmentsToAddLeave.Value,
                        StartPageId: this.data.StartPageId,
                    };
                    this.$http.post(
                        this.surfaceControllerUrl + '/GetSelectedEmploymentValues', params).then(function (result) {
                            // get data for the selected employment, and fill the fields
                            //console.log("result", result);
                            var that = this;
                            for (prop in result.body) {
                                var elm = that.getElementByName(prop) || that.getElementByName("Employment_¤" + prop);
                                if (elm) {
                                    // we have element in our form // fill with value / or null value
                                    var value = result.body[prop];

                                    //console.log("elm dev", elm.Name, "DontLoadValue", elm.DontLoadValue, "new value", value, "exvalue", elm.Value, elm);
                                    if (!elm.DontLoadValue) { 

                                        elm.Value = value;
                                        
                                        if (elm.InputType === that.inputTypes.Date || that.IsSystemDatetime(elm)) {
                                            //console.log("date", elm.Name, value);
                                            //elm.Value = that.tryToGetDateObject(value);
                                            elm.Value = that.convertDateToObject(value);
                                            //console.log("date 2", elm.Name, elm.Value);
                                        }
                                        if (elm.InputType === that.inputTypes.Select) {
                                            elm.SelectValue = value;
                                        } else {
                                            elm.SelectValue = null;
                                        }
                                        if (elm.InputType === that.inputTypes.Radio) {
                                            elm.RadioValue = value;
                                        } else {
                                            elm.RadioValue = null;
                                        }
                                        if (elm.InputType === that.inputTypes.Checkbox) {
                                            elm.CheckboxValue = [];
                                            elm.CheckboxValue.push(value);
                                        } else {
                                            elm.CheckboxValue = [];
                                        }
                                    }
                                    if ((elm.Name == "Employment_¤LeaveStart" || elm.Name == "LeaveStart") || (elm.Name == "Employment_¤LeaveCode" || elm.Name == "LeaveCode")) {
                                        // When these fields have result data, user can not change - use result data // Delta spesific?
                                        if (value) {
                                            elm.Disabled = true;
                                        }
                                        else {
                                            elm.Disabled = false;
                                        }
                                    }
                                    elm.AutocompleteValue = true; // ??
                                }
                            }
                            // update with preselected and default values (date)
                            this.initializeElementValuesFromPreselectedValues();
                        }
                    );
                }
            },
            checkLeaveEndAgainstLeaveStart() {
                // if LeaveEnd is before LeaveStart, then add invald message
                var leaveStart = this.getElementByName('Employment_¤LeaveStart') || this.getElementByName('LeaveStart');
                var leaveEnd = this.getElementByName('Employment_¤LeaveEnd') || this.getElementByName('LeaveEnd');
                if (leaveStart && leaveEnd && leaveStart.Value && leaveEnd.Value) {
                    var leaveEndDate = new Date(leaveEnd.Value);
                    var leaveStartDate = new Date(leaveStart.Value);

                    if (leaveEndDate <= leaveStartDate) {
                        leaveEnd.IsInvalid = true;
                        leaveEnd.IsInvalidMessage = leaveEnd.Label + " må være større enn " + leaveStart.Label; 
                    } else {
                        leaveEnd.IsInvalid = false;
                        leaveEnd.IsInvalidMessage = "";
                    }
                }
            },
            toggleElement: function (element) {
                if (!element.ControlVisibility)
                    return;

                // hide / show fields added to ControlVisibility
                // standard is VisibleElements - start hidden, if you check, choosen fields are shown
                // for AnonymousDonator it is opposite. The fields starts open, if you check - choosen fields are hidden

                try {
                    if (element.InputType == "Checkbox") {
                        if (element.Value &&  element.CheckboxValue && element.CheckboxValue instanceof Array && element.CheckboxValue.indexOf(element.Value) == -1) {
                            // a removed check value (when you uncheck)
                            element.Value = null;
                        }
                    }
                    var elPreselectedValues = [];
                    if (element.Values) {
                        element.Values.forEach(function (item) {
                            if (item.IsPreselected) {
                                if ((element.CheckboxValue && element.CheckboxValue instanceof Array && element.CheckboxValue.indexOf(item.Value) !== -1)
                                    || (element.RadioValue && element.RadioValue == item.Value)) {
                                    elPreselectedValues.push(item);
                                }
                            }
                        });
                        if (elPreselectedValues && elPreselectedValues.length > 0) {
                            var firstPreselected = elPreselectedValues[0];
                            element.Value = firstPreselected.Value;
                        }
                    }

                    if (element.Value) {
                        var visibleValues = element.Values[element.Values.map(function (o) { return o.Value; }).indexOf(element.Value)].VisibleElements;
                        visibleValues = (typeof visibleValues !== 'undefined' && visibleValues instanceof Array) ? visibleValues : [];
                        // AnonymousDonator - HideElements
                        var valuesToHide = element.Values[element.Values.map(function (o) { return o.Value; }).indexOf(element.Value)].HideElements;
                        valuesToHide = (typeof valuesToHide !== 'undefined' && valuesToHide instanceof Array) ? valuesToHide : [];
                    } else {
                        var visibleValues = [];
                        var valuesToHide = [];
                    }
                    
                    var _that = this;
                    element.ControlVisibility.forEach(function (elmName) {
                        var elementToToggle = _that.getElementByName(elmName);

                        if (element.Name == 'AnonymousDonator') {
                            if (valuesToHide.indexOf(elmName) !== -1) {
                                // if mandatory field is hidden, it has to be submited in a form, add __TOGGLE.HIDDEN__
                                elementToToggle.Value = '__TOGGLE.HIDDEN__';
                                elementToToggle.SelectValue = '';

                                elementToToggle.IsVisible = false;
                                elementToToggle.IsInvalid = false;
                                _that.isPosting = false;
                            } else {
                                elementToToggle.IsVisible = true;
                                elementToToggle.Value = '';
                            }
                        } else {
                            if (visibleValues.indexOf(elmName) !== -1) {

                                if (element.InputType == _that.inputTypes.FormControlButtons
                                    && (elmName == "Paymenttype" || elmName == "PaymentType")) {
                                    _that.showSubmit = true;
                                    if (elementToToggle.InputType == _that.inputTypes.RadioImage) {
                                        _that.showSubmit = false;
                                    }
                                }

                                elementToToggle.IsVisible = true;
                                elementToToggle.Value = '';

                            } else {

                                if (elmName === 'Membership¤Fellowship' || elmName === 'Fellowship') {
                                    //var preselectedValues2 = elementToToggle.Values.filter(x = > x.IsPreselected);
                                    var preselectedValues = [];
                                    elementToToggle.Values.forEach(function (item) {
                                        if (item.IsPreselected) {
                                            preselectedValues.push(item);
                                        }
                                    });

                                    if (preselectedValues && preselectedValues.length > 0) {
                                        var firstPreselected = preselectedValues[0];
                                        elementToToggle.Value = firstPreselected.Name;
                                        elementToToggle.SelectValue = firstPreselected.Value;
                                    }
                                    else {
                                        elementToToggle.Value = '';
                                        elementToToggle.SelectValue = '';
                                    }
                                }
                                else {
                                    // if mandatory field is hidden, it has to be submited in a form, add __TOGGLE.HIDDEN__
                                    elementToToggle.Value = '__TOGGLE.HIDDEN__';
                                    elementToToggle.SelectValue = '';
                                }

                                if (element.InputType == _that.inputTypes.FormControlButtons
                                    && (elmName == "Paymenttype" || elmName == "PaymentType")) {
                                    _that.showSubmit = false;
                                }

                                elementToToggle.IsVisible = false;
                                elementToToggle.IsInvalid = false;
                                _that.isPosting = false;
                            }
                        }
                    })
                }
                catch (er) { }
               ;
            },
            initializeElementValuesFromPreselectedValues: function () {
                var self = this;
                this.data.Steps.forEach(function (step, stepIndex) {
                    step.Rows.forEach(function (row, rowIndex) {
                        row.Columns.forEach(function (column, columnIndex) {
                            column.Elements.forEach(function (element, elementIndex) {

                                if (element.Values && element.Values.length > 0) {
                                    element.Values.forEach(function (value) {
                                        if (value.IsPreselected) {
                                            switch (element.InputType) {
                                                case self.inputTypes.Checkbox:
                                                    if (!element.CheckboxValue) element.CheckboxValue = [];
                                                    if (!element.Value) {
                                                        element.CheckboxValue.push(value.Value);
                                                    } else {
                                                        element.CheckboxValue.push(element.Value);
                                                    }
                                                    
                                                    break;
                                                case self.inputTypes.Radio:
                                                    if (!element.RadioValue) {
                                                        element.RadioValue = [];
                                                    }
                                                    if (!element.Value) {
                                                        element.RadioValue = value.Value;
                                                    } else {
                                                        element.RadioValue = element.Value;
                                                    }
                                                    break;
                                                case self.inputTypes.FormControlButtons:
                                                    if (!element.RadioValue) {
                                                        element.RadioValue = [];
                                                    }
                                                    if (!element.Value) {
                                                        element.RadioValue = value.Value;
                                                    } else {
                                                        element.RadioValue = element.Value;
                                                    }
                                                    break;
                                                case self.inputTypes.Select:
                                                    if (!element.SelectValue) {
                                                        element.SelectValue = value.Value;
                                                        element.Value = value.Name;
                                                    } else {
                                                        if (!element.Value) {
                                                            element.Values.forEach(function (item) {
                                                                if (item.Value == element.SelectValue) {
                                                                    element.Value = item.Name;
                                                                }
                                                            });
                                                        }
                                                    }
                                                    break;
                                            }
                                            if (element.Name !== 'Employment_¤LeaveStart' || element.Name !== 'LeaveStart') {
                                                self.setElementValue(stepIndex, rowIndex, columnIndex, elementIndex, element.SelectValue, element);
                                            }
                                        }
                                    });

                                    if (element.InputType === self.inputTypes.Checkbox
                                        && element.CheckboxValue) {
                                        element.Value = element.CheckboxValue.toString();
                                    } else if (element.InputType === self.inputTypes.Radio
                                        && element.RadioValue
                                        && element.RadioValue !== self.CustomTextInputConstant) {
                                        element.Value = element.RadioValue;
                                    }

                                    self.data.Steps[stepIndex].Rows[rowIndex].Columns[columnIndex].Elements
                                        .splice(elementIndex, 1, element);
                                }

                                if (element.Name === "AllowedPaymentSystems") {
                                    if (element.Name && element.Values.length == 0) {
                                        self.showSubmit = false;
                                        element.IsVisible = false;

                                        self.invalidFields = [];
                                        self.showListOfInvalidFields = true;
                                        self.invalidFields.push(
                                            {
                                                label: "Payment systems have not been defined...",
                                                step: 0
                                            });
                                    } else {
                                        self.showSubmit = true;
                                        element.IsVisible = true;
                                    }
                                }
                                if ((element.Name == "PaymentType" || element.Name == "Paymenttype") && element.InputType == "RadioImage") {
                                    element.ShowLabel = false;
                                    self.showSubmit = false;
                                }
                                if (element.InputType == "FormControlButtons") {
                                    element.ShowLabel = false;
                                    self.showSubmit = false;
                                }
                                if (element.Name === "InvoiceStatTable") {
                                    self.showSubmit = false;
                                }
                                if ((element.InputType === self.inputTypes.Boolean || element.InputType === self.inputTypes.CheckboxSlide)
                                    && element.IsPreselected) {
                                    element.Value = true;
                                }
                                if (element.InputType == self.inputTypes.Date || self.IsSystemDatetime(element)) {
                                    if (!element.Value && element.IsDefaultDateVisible && element.DefaultValue) {
                                        element.Value = element.DefaultValue;
                                    }
                                    element.Value = self.tryToGetDateObject(element.Value);
                                }
                            });
                        });
                    });
                });
                if (this.data.Method === "CourseRegister") {
                    self.showSubmit = false;
                }
            },
            getExtraModel: function (num) {
                var newModel = [];
                newModel.push({ Rows: [] });

                this.data.Steps[this.currentPage].Rows.forEach(function (row, i) {

                    var newRow = newModel[0].Rows;
                    newRow.push({ Columns: [] });
                    var newCol = newRow[i].Columns;

                    row.Columns.forEach(function (column, j) {

                        newCol.push({ Elements: [] });
                        var newElem = newCol[j].Elements;

                        column.Elements.forEach(function (element, k) {

                            if (element.IsRepeatableField) {

                                var isVisible = true;
                                if (element.Name == 'Actor¤ActorID')
                                    isVisible = false;

                                //console.log("element", element.Name, element.InputType, element.Values.length, element);

                                newElem.push({
                                    Name: element.Name,
                                    NameSecondary: "-SECONDARY-" + num,
                                    DataType: element.DataType,
                                    DefaultDateMode: element.DefaultDateMode,
                                    DefaultValue: element.DefaultValue,
                                    //Value: element.DefaultValue,
                                    NonEditable: element.NonEditable,
                                    InputType: element.InputType,
                                    IsDefaultDateVisible: element.IsDefaultDateVisible,
                                    IsVisible: isVisible,
                                    Label: element.Label,
                                    LabelOriginal: element.LabelOriginal,
                                    Placeholder: element.Placeholder,
                                    InputType: element.InputType,
                                    IsReadOnly: element.IsReadOnly,
                                    IsTextProperty: element.IsTextProperty,
                                    Required: element.IsRepeatableFieldRequired,
                                    RequiredByCustomer: element.IsRepeatableFieldRequired,
                                    ShowLabel: element.ShowLabel,
                                    ShowPlaceholder: element.ShowPlaceholder,
                                    Values: element.Values,
                                    Validate: element.Validate,
                                    WoBoksId: element.WoBoksId,
                                    WoModus: element.WoModus,
                                });
                            }
                        });
                    });
                });

                return this.sanityzeExtraModel(newModel);
            },
            sanityzeExtraModel: function (model) {
                var newModel = [{ Rows: [] }];
                model[0].Rows.forEach(function (row, i) {
                    isEmptyRow = true;
                    row.Columns.forEach(function (column, j) {
                        if (column.Elements.length > 0) {
                            if (isEmptyRow) {
                                isEmptyRow = false;
                            }
                        }
                    });
                    if (!isEmptyRow) {
                        newModel[0].Rows.push(row);
                    }
                });

                return newModel;
            },
            openFamilyExtraForm: function (rowIndex) {
                if (!this.showFamilyExtraForm) {
                    this.addFamilyExtraForm(rowIndex);
                }
            },
            addFamilyExtraForm: function (rowIndex) {
                var steps = this.data.Steps[this.currentPage];
                this.familyExtraForm = this.getExtraModel(this.personInfoCounter);
                this.familyExtraForm[0].Rows.forEach(function (row, i) {
                    rowIndex++;
                    steps.Rows.splice(rowIndex + i, 0, row);
                    
                });
                this.$forceUpdate();
                this.personInfoCounter++;
                this.showFamilyExtraForm = true;
                this.rowFamilyExtraForm = rowIndex;
            },
            removeFamilyExtraForm: function (rowIndex, rowIndexToRemove) {
                var steps = this.data.Steps[this.currentPage];

                // remove row
                this.familyExtraForm[0].Rows.forEach(function (row, i) {
                    steps.Rows.splice(rowIndexToRemove, 1);
                    rowIndex--;
                });

                // update numbers
                this.$forceUpdate();
                this.personInfoCounter--;
                this.rowFamilyExtraForm = rowIndex;

                // all family members removed - back to start position
                if (this.personInfoCounter <= 1) {
                    this.showFamilyExtraForm = false;
                } 
            },
            isExtraMember: function (row) {
                var found = false;
                row.Columns.forEach(function (column) {
                    column.Elements.forEach(function (element) {
                        if (!found) {
                            if (element.NameSecondary) {
                                if (element.NameSecondary.indexOf("SECONDARY") > 0) {
                                    found = true;
                                }
                            }
                        }
                    });
                });

                return found;
            },
            getCountExtraFieldInGroup() {
                var countInGroup = 0;
                this.data.Steps[this.currentPage].Rows.forEach(function (row) {
                    row.Columns.forEach(function (column) {
                        column.Elements.forEach(function (element) {
                            if (element.IsRepeatableField) {
                                countInGroup++;
                            }
                        });
                    });
                });

                return countInGroup;
            },
            getCountAllExtraField() {
                var countAllExtra = 0;
                this.data.Steps.forEach(function (step, stepIndex) {
                    step.Rows.forEach(function (row, rowIndex) {
                        row.Columns.forEach(function (column, columnIndex) {
                            column.Elements.forEach(function (element, elementIndex) {
                                if (element.NameSecondary) {
                                    if (element.NameSecondary.indexOf("SECONDARY") > 0) {
                                        countAllExtra++;
                                    }
                                }
                            });
                        });
                    });
                });

                return countAllExtra;
            },
            getCountOfExtraGroup() {
                return ~~(this.getCountAllExtraField() / this.getCountExtraFieldInGroup());
            },
            
            isFirstFamilyFieldInRow(row, e) {
                var found = false;
                var name = "";
                row.Columns.forEach(function (column, columnIndex) {
                    column.Elements.forEach(function (element, elementIndex) {
                        if (element.NameSecondary) {
                            if (element.NameSecondary.indexOf("SECONDARY") > 0 && element.IsVisible == true) {
                                if (!found) {
                                    found = true;
                                    name = element.Name;
                                }
                            }
                        }
                    });
                });
                if (e.Name == name) {
                    return true;
                }

                return false;
            },
            isFirstFamilyFieldInRow_new(e) {
                // not working
                var found = false;
                var name = "";

                var groups = this.getGroupedListAllFamilyMember();

                groups.forEach(function (group) {
                    group.forEach(function (element) {
                        if (element.IsVisible) {
                            if (!found) {
                                found = true;
                                name = element.Name;
                            }
                        }
                    });
                });

                if (e.NameSecondary && e.Name == name) {
                    return true;
                }

                return false;
            },
            getListAllFamilyMember() {
                var list = [];
                var self = this;
                this.data.Steps.forEach(function (step, stepIndex) {
                    step.Rows.forEach(function (row, rowIndex) {
                        row.Columns.forEach(function (column, columnIndex) {
                            column.Elements.forEach(function (element, elementIndex) {
                                if (element.NameSecondary != null) {
                                    if (element.NameSecondary.indexOf("SECONDARY") > 0) {
                                        list.push(element);
                                    }
                                }
                            });
                        });
                        
                    });
                });
                
                return list;
            },
            getGroupedListAllFamilyMember() {
                var groups = [];
                var list = this.getListAllFamilyMember();

                for (var i = 1; i <= this.getCountOfExtraGroup(); i++) {
                    var item = list.filter(x => {
                        if (x.NameSecondary.indexOf("SECONDARY-" + i) > 0) {
                            return x;
                        }
                    });
                    groups.push(item);
                }
                return groups;
            },
            getListFamilyMemberFormated() {
                var res = [];
                var groups = [];
                var list = this.getListAllFamilyMember();

                for (var i = 1; i <= this.getCountOfExtraGroup(); i++) {
                    var item = list.filter(x => {
                        if (x.NameSecondary.indexOf("SECONDARY-" + i) > 0) {
                            return x;
                        }
                    });
                    groups.push(item);
                }
                
                var item = [];
                groups.forEach(function (group) {
                    var firstName, lastName = "";
                    group.forEach(function (element) {
                        if (element.Name == "Actor¤FirstName") {
                            firstName = element.Value;
                        }
                        if (element.Name == "Actor¤LastName") {
                            lastName = element.Value;
                        }
                    });
                    res.push({
                        FirstName: firstName,
                        LastName: lastName,
                    });
                });

                return res;
            },
            submitPayment: function (val) {
                var elem = this.getElementByName("PaymentType")
                    || this.getElementByName("Paymenttype")
                    || this.getElementByName("BETALINGSTYPE")
                    || this.getElementByName("SIGNERING");

                elem.Value = val;     
            },
            isAnyRoomsAvailable: function (items) {
                var res = false;
                if (items.length > 0) {
                    items.forEach(function (item) {
                        if (res == false) {
                            if (item.NumberOfRoomsAvailable == null || item.NumberOfRoomsAvailable > 0) {
                                res = true;
                            }
                        }
                    });
                }
                return res;
            },
            isRoomAvailable: function (value) {
                var res = false;
                if (value == null || value > 0) {
                    res = true;
                }
                return res;
            },
            isShowSubAVTKodes: function (e) {
                var res = true;
                if (e.Name == 'Employment_¤Title_Text' || e.Name == 'Title_Text' || e.Name == 'Employment_¤Position_Code_Text' || e.Name == 'Employment_¤PayGrade') {
                    if (e.SubAVTKodes) {
                        var mainAvtCodes = [];
                        this.data.Steps.forEach(function (step, stepIndex) {
                            step.Rows.forEach(function (row, rowIndex) {
                                row.Columns.forEach(function (column, columnIndex) {
                                    column.Elements.forEach(function (element, elementIndex) {
                                        if (element.Name == "Employment_¤EmployerName" && element.AVTKodes) {
                                            mainAvtCodes = element.AVTKodes.split(',');
                                        }
                                    });
                                });
                            });
                        });

                        var subAvtCodes = e.SubAVTKodes.split(',');
                        var intersecting = this.getArraysIntersection(mainAvtCodes, subAvtCodes);

                        res = intersecting.length > 0 && e.ShowSubAVTKodes;
                    }
                }
                return res;
            },
            getArraysIntersection: function (a1, a2) {
                a2.forEach(function (item, itemIndex) {
                    a2[itemIndex] = item.trim();
                });
                return a1.filter(function (n) { return a2.indexOf(n.trim()) !== -1; });
            },
            isAnyActivitiesAvailable: function (items) {
                var res = false;
                if (items.length > 0) {
                    items.forEach(function (item) {
                        if (res == false) {
                            if (item.NumberOfVacancies == null || item.NumberOfVacancies > 0) {
                                res = true;
                            }
                        }
                    });
                }
                return res;
            },
            isActivityAvailable: function (value) {
                var res = false;
                if (value == null || value > 0) {
                    res = true;
                }
                return res;
            },
            bankAccountFormat: function (event) {
                if (!/^[0-9]+$/.test(event.key) || event.key === '.') return event.preventDefault();
            },
            getLinkList: function (values) {
                var res = [];
                var subRes = [];
                values.forEach(function (item) {
                    if (item.IsLinkGroupTitle === true) {
                        if (subRes.length > 0) {
                            res.push({
                                Name: name,
                                Visible: this.linkListVisible,
                                Values: subRes,
                            });
                        }
                        name = item.Name;
                        subRes = [];
                    } else {
                        subRes.push({
                            Name: item.Name,
                            Value: item.Value,
                        });
                    }
                });
                if (subRes.length > 0) {
                    res.push({
                        Name: name,
                        Visible: this.linkListVisible,
                        Values: subRes,
                    });
                }

                return res;
            },
            toggleLink: function (item) {
                item.Visible = !item.Visible;
            },
            updateSwithToggleButtonVisibility: function () {
                var elements = [];
                var samtykker = this.getElementByName('Samtykker') || this.getElementByName('Membership_¤Samtykker') || this.getElementByName('DmCode_¤Samtykker');
                var reservasjoner = this.getElementByName('Reservasjoner') || this.getElementByName('Membership_¤Reservasjoner') || this.getElementByName('DmCode_¤Reservasjoner');
                if (samtykker) {
                    elements.push(samtykker);
                }
                if (reservasjoner) {
                    elements.push(reservasjoner);
                }
                if (elements.length > 0) {
                    elements.forEach(function (e) {
                        if (e) {
                            var groupHeader = false;
                            e.Values?.forEach(function (v) {
                                if (v.IsSwithToggleButtonGroupHeader == true) {
                                    groupHeader = e.CheckboxValue.includes(v.Value);
                                    v.IsSwithToggleButtonGroupVisible = true;
                                } else {
                                    v.IsSwithToggleButtonGroupVisible = groupHeader;
                                }
                            });
                        }
                    });
                }
            },
            closePanel: function () {
                var myProfileSource = document.querySelector('.my-profile-source');
                if (myProfileSource) {
                    if (myProfileSource.getAttribute("data-source") == "TheFirstEnter") {
                        var myProfile = document.querySelector('.my-profile');
                        if (myProfile) {
                            myProfile.classList.remove('shown');
                            myProfileSource.setAttribute('data-source', '')
                        }
                    }
                }
            },
            getAgreementCode: function () {
                var agreementCode = null;
                var employer = this.getElementByName('EmployerName') || this.getElementByName('Employment_¤EmployerName') || null;
                if (employer) {
                    employer.Values.forEach(item => {
                        if (item.Name == employer.Value && !agreementCode) {
                            agreementCode = item.AgCod;
                        }
                    });

                    return agreementCode;
                }
            }
        },
        computed: {
            isConfirmDisabled: function () {
                return this.membership == "active";
            },
            isMembershipStatusConfirmDisabled: function () {
                return this.membershipStatus == "active";
            },
            isChangeMembershipDisabled: function () {
                return this.changeMembershipButton == false;
            },
            orderedItemsSum: function () {
                var sum = 0;

                if (this.orderedItems.length > 0) {
                    this.orderedItems.forEach(function (item) {
                        sum += item.price;
                    });
                }

                return sum;
            }, 
            stepHasRequiredFields: function () {
                var hasRequiredFields = false;
                this.data.Steps[this.currentPage].Rows.forEach(function (row) {
                    row.Columns.forEach(function (column) {
                        column.Elements.forEach(function (element) {
                            if (element.RequiredByCustomer) {
                                hasRequiredFields = true;
                            }
                        });
                    });
                });

                return hasRequiredFields;
            },
            stepHasAllFieldsHidden: function () {
                var hasVisibleFields = false;
                this.data.Steps[this.currentPage].Rows.forEach(function (row) {
                    row.Columns.forEach(function (column) {
                        column.Elements.forEach(function (element) {
                            if (element.IsVisible && !element.IsTextProperty) {
                                hasVisibleFields = true;
                            }
                        });
                    });
                });

                return !hasVisibleFields;
            },
        },
        created: function () {
            if (this.wasRedirectedFromWinorg()) {
                this.getWinorgResult();
            } else {
                this.initializeForm();
            }

            self = this;
            this.data.Steps.forEach(function () {
                self.showFormStepContainerArr.push(false);
            });

            var links = this.getElementByName("Links");
            if (links != null) {
                this.linkList = this.getLinkList(links.Values);
            }

            this.MembershipStatusReason = this.getElementByName('MembershipStatusReason') || null;
            this.updateSwithToggleButtonVisibility();
        },
        mounted: function () {
            this.updatePreselectedMembershipFellowship();
            this.AddPersonMembershipAgeCheck();
            this.updatePreselectedStopMembership();
            this.updateSwithToggleButtonVisibility();
        }
    });
};

document.addEventListener("DOMContentLoaded", function (d) {
    //console.log("loaded");
    var forms = document.getElementsByClassName('js-woform');
    //console.log("forms", forms.length);
    [].forEach.call(forms, function (form) {
        form.addEventListener('keypress', function (e) {
            if (e.keyCode === 13) {
                // prevent form from submitting when pressing enter
                //console.log("Prevent deafult");
                e.preventDefault();
            }
        });
    });
});

