﻿(function () {
    $(document).ready(function () {
        var mode = coreJS.RWD.getRWDMode();

        Sys.Application.add_load(onEveryLoad);

        for (var i = 0; i < _readyCallback.length; i++) {
            switch (mode) {
                case "mobile":
                    if (_readyCallback[i].mobile) _readyCallback[i].mobile();
                    break;
                case "tablet":
                    if (_readyCallback[i].tablet) _readyCallback[i].tablet();
                    break;
                case "desktop":
                    if (_readyCallback[i].desktop) _readyCallback[i].desktop();
                    break;
            }
        }

        coreJS.initNavSupport();

        initWcagForCheckboxesAndRadiobuttons();

        var setAltText = function (obj, texten) {
            if ($(obj).prop('nodeName') == "IMG") {
                $(obj).attr("alt", texten);
            }
            $(obj).attr("data-caption", texten);
        }
        var getAltText = function (obj, handler) {
            var resultText = "";
            $.ajax({
                type: "POST",
                url: handler,
                contentType: "text/plain",
                dataType: "text",
                success: function (msg) {
                    setAltText($(obj), msg);
                },
                error: function () {
                    setAltText($(obj), "");
                }
            });
        }
        try {
            $("img[src*='DisplayMultimedia.ashx']").each(function () {
                if ($(this).attr("alt").length === 0 && $(this).attr("src").indexOf("DisplayMultimedia.ashx") >= 0 && $(this).attr("src").indexOf("guid=") >= 0) {
                    $(this).attr("alt", $(this).attr("src").replace("DisplayMultimedia.ashx", "DisplayMultimediaDescription.ashx"));
                }
            });
        } catch (e) { console.log("Failed to load alt text") }
        try {
            $("img[alt*='DisplayMultimediaDescription.ashx']").each(function () {
                var textToDisplay = getAltText($(this), $(this).attr("alt"))
            });
        } catch (e) { console.log("Failed to load alt text") }

        try {
            $("a[data-caption*='DisplayMultimediaDescription.ashx']").each(function () {
                var textToDisplay = getAltText($(this), $(this).attr("data-caption"))
            });
        } catch (e) { console.log("Failed to load alt text") }

    });

    $(document).on("rwdResize", function (e, mode) {
        for (var i = 0; i < _resizeCallback.length; i++) {
            switch (mode) {
                case "mobile":
                    if (_resizeCallback[i].mobile) _resizeCallback[i].mobile();
                    break;
                case "tablet":
                    if (_resizeCallback[i].tablet) _resizeCallback[i].tablet();
                    break;
                case "desktop":
                    if (_resizeCallback[i].desktop) _resizeCallback[i].desktop();
                    break;
            }
        }
    });

    var _resizeCallback = new Array();
    var _readyCallback = new Array();

    var coreJS = {
        errorAlertFallback: false,
        moveElementPosition: {
            before: 'before',
            after: 'after',
            replace: 'replace',
            replaceInside: 'replaceInside',
            prepend: 'prepend',
            append: 'append'
        },
        modes: {
            desktop: 'desktop',
            tablet: 'tablet',
            mobile: 'mobile'
        },
        moveElement: function (element, position, target) {
            if (element && position) {
                switch (position) {
                    case 'before':
                        element.insertBefore(target);
                        break;
                    case 'after':
                        element.insertAfter(target);
                        break;
                    case 'replace':
                        target.replaceWith(element);
                        break;
                    case 'replaceInside':
                        target.html(element);
                        break;
                    case 'prepend':
                        target.prepend(element);
                        break;
                    case 'append':
                        target.append(element);
                        break;
                    default:
                        coreJS.throwException('moveElement: Incorrect position');
                        break;
                }
            }
            else {
                coreJS.throwException('moveElement: Incorrect element and/or position');
            }
        },

        throwException: function (iMessage) {
            var message = iMessage;
            if (!message) message = 'Error: (no errormessage)';

            if (console)
                if (console.error)
                    console.error(message);
                else
                    console.log(message);
            else if (coreJS.errorAlertFallback)
                alert(message);
        },

        initNavSupport: function () {
            var htmlString = '<div class="navSupScrollTop"></div>';
            $("body").append(htmlString);

            $(window).on('scroll', function () {
                var scrollTop = $(window).scrollTop();
                var windowHeight = $(window).height();

                if (scrollTop > windowHeight) {
                    if (coreJS.RWD.getRWDMode() == "mobile" || coreJS.RWD.getRWDMode() == "tablet") {
                        $(".navSupScrollTop").addClass("is-active");
                    }
                }
                else {
                    $(".navSupScrollTop").removeClass("is-active");
                }
            });

            $(document).on('click', '.navSupScrollTop', function () {
                $("body, html").animate({ scrollTop: 0 }, 500);
                $(this).removeClass("is-active");
            });
        },



        RWD: {
            getRWDMode: function () {
                var windowWidth = $(window).width();
                var mode;

                if (windowWidth >= window.rwdDesktopBreakpoint) {
                    mode = "desktop";
                }
                else if (windowWidth < window.rwdDesktopBreakpoint && windowWidth >= window.rwdMobileBreakpoint) {
                    mode = "tablet";
                }
                else if (windowWidth < window.rwdMobileBreakpoint) {
                    mode = "mobile";
                }

                return mode;
            },

            isDesktop: function () {
                return this.getRWDMode() == coreJS.modes.desktop;
            },
            isTablet: function () {
                return this.getRWDMode() == coreJS.modes.tablet;
            },
            isMobile: function () {
                return this.getRWDMode() == coreJS.modes.mobile;
            },

            /*
            // This method takes a javascript object as its first parameter. This object can contain three methods,
            // one for each RWD mode. You may omit the ones you do not need. Example "methodCollection":
            // 
            // var methcoll = new Object();
            // methcoll.mobile = function() { Do stuff };
            // methcoll.tablet = function() { Do stuff };
            // methcoll.desktop = function() { Do stuff };
            //
            // coreJS.RWD.addRWDCallback(methcoll, true, true);
            */

            addRWDCallback: function (methodCollection, callAtResize, callAtStart) {
                if (callAtResize) _resizeCallback.push(methodCollection);
                if (callAtStart) _readyCallback.push(methodCollection);
            }
        },

        Cookies: {
            /// <summary>Namespace including support for all things related to cookies</summary>
            getCookieValue: function (cookieName, cookieSetting) {
                /// <summary>Gets the value of a specified cookie and setting in that cookie</summary>
                /// <param name="cookieName">Name of the cookie to get the value for.</param>
                /// <returns type="String">The value</returns>
                var nameEQ = name + "=";
                var ca = document.cookie.split(';');
                for (var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0) == ' ')
                        c = c.substring(1, c.length);
                    
                    if (c.indexOf(nameEQ) >= 0) {
                        var cookieValue = c.substring(c.indexOf(nameEQ) + 1, c.length);
                        var ca2 = cookieValue.split('&');
                        for (var j = 0; j < ca2.length; j++) {

                            if (ca2[j].indexOf(cookieSetting) >= 0)
                            {
                                var setting = ca2[j].split('=');
                                if (setting.length == 2)
                                    return setting[1];
                            }
                        }
                    }
                }
                return null;
            },

            createCookie : function(name, value, daysExpiration, path) {
                /// <summary>Creates a cookie and its value</summary>
                /// <param name="name">Name of the cookie to create.</param>
                /// <param name="value">Value of the cookie</param>
                /// <param name="daysExpiration">Number of days for the cookie to expire</param>
                /// <param name="path">The path the cookie is valid for</param>
                /// <returns type="Boolean">True if the cookie was created.</returns>
                var retVal = false;
                var cookie_string = '';

                var expirationDate = new Date();
                var maxAge = 0;
                if (daysExpiration != null) {
                    expirationDate.setDate(expirationDate.getDate() + daysExpiration);
                    maxAge = daysExpiration * 24 * 60 * 60; // seconds
                }

                cookie_string = name + "=" + value + ((daysExpiration == null) ? "" : "; expires=" + expirationDate.toUTCString()) + ";path=" + path + (maxAge == null ? "" : "; max-age=" + maxAge);
                document.cookie = cookie_string;
                retVal = this.cookieExists(name);

                return retVal;
            },

            cookieExists : function(name) {
                /// <summary>Checks if a given cookie exists</summary>
                /// <param name="name">Name of the cookie to create.</param>
                /// <returns type="Boolean">True if the cookie exists.</returns>
                var retVal = false;

                if (document.cookie != null && document.cookie != undefined)
                    retVal = document.cookie.search(name) != -1;

                return retVal;
            },
            acceptCookieUsage: function (cookieName, errorMessage) {
                try {
                    var currentURL = window.location.href;
                    var cookiePath = '/';
                    
                    var cookieCreated = this.createCookie(cookieName, 'UserAllowsCookies=true', 3650, cookiePath);
                    if (cookieCreated) {
                        coreJS.Cookies.hideCookieHeader();
                    }
                    else {
                        alert(errorMessage);
                    }
                }
                catch (err) {
                    // something fishy happen, dont show the cookie dialog
                    coreJS.Cookies.hideCookieHeader();
                }
            },
            showCookieHeader: function () {
                $('#cookie-header').show();
            },
            hideCookieHeader: function () {
                $('#cookie-header').hide();
            }
        },

        Messages: {
            getConfirmation: function (msg) {
                if (!msg || confirm(msg)) {
                    return true;
                } else {
                    return false;
                }
            }
        },

        Json: {
            isJson: function (jsonString) {
                var retVal = false;
                try {
                    JSON.parse(jsonString);
                    retVal = true;
                }
                catch (e) { }
                return retVal;
            }
        },

        List: {
            addFilterToList: function (inputElement, listElement) {
                $.expr[":"].icontains = $.expr.createPseudo(function (arg) {
                    return function (elem) {
                        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
                    };
                });

                // Adjust even/odd rows and block margin in block list
                window.positioningAdjustment = function (element) {
                    $(window[element.attr("id") + "_blocks"]).filter(":visible").each(function (index) {
                        if ((index + 1) % 3 == 0) {
                            this.style.setProperty("margin-right", "0px", "important");
                        }
                        else {
                            this.style.setProperty("margin-right", "20px");
                        }
                    });
                    $(window[element.attr("id") + "_rows"]).filter(":visible").each(function (index) {
                        if ((index + 1) % 2 == 0)
                            $(this).removeClass('listitem-odd').removeClass('listitem-even').addClass('listitem-even');
                        else {
                            $(this).removeClass('listitem-odd').removeClass('listitem-even').addClass('listitem-odd');
                        }
                    });
                };

                window.filterData = function (filter, element) {
                    window[element.attr("id") + "_rows"] = element.find('.headerrow').siblings();
                    window[element.attr("id") + "_blocks"] = element.find('.templatelist.block.objectlist');
                    window[element.attr("id") + "_isGridList"] = true;
                    
                    if (element.find('table.gridlist:visible').length == 0) {
                        window[element.attr("id") + "_isGridList"] = false;
                    }
                    else {
                        window[element.attr("id") + "_isGridList"] = true;
                    }
                    
                    //Remove whitespaces at start/end
                    filter = $.trim(filter);

                    //Reset rows if search is empty
                    if (filter.length == 0) {
                        window[element.attr("id") + "_rows"].each(function (index) { $(this).show(); });
                        window[element.attr("id") + "_blocks"].each(function (index) { $(this).show(); });
                        window.positioningAdjustment(element);
                    }
                    else {
                        window[element.attr("id") + "_rows"].filter(function (index) {
                            if (filter.length > 0)
                                if ($(window[element.attr("id") + "_rows"][index]).find('*:icontains("' + filter + '")').length <= 0)
                                    $(window[element.attr("id") + "_rows"][index]).hide();
                                else
                                    $(window[element.attr("id") + "_rows"][index]).show();
                        });
                        window[element.attr("id") + "_blocks"].filter(function (index) {
                            if (filter.length > 0)
                                if ($(window[element.attr("id") + "_blocks"][index]).find('span:icontains("' + filter + '")').length <= 0)
                                    $(window[element.attr("id") + "_blocks"][index]).hide();
                                else
                                    $(window[element.attr("id") + "_blocks"][index]).show();
                        });
                        window.positioningAdjustment(element);
                    }
                };
                
                inputElement.on('change keyup paste', function () {
                    setTimeout(window.filterData($(this).val(), listElement), 250);
                });

                inputElement.on('keypress', function (event) {
                    if (event.keyCode == 13) {
                        event.preventDefault();
                        return false;
                    }
                });
            }
        },
        Ajax: {
            performCall: function (url, type, dataType, successCallback, errorCallback, data, cache, antiForgeryToken, contentType) {
                if (cache == undefined || cache == null || cache == true) {
                    cache = true;
                }
                else {
                    cache = false;
                }

                if (contentType === undefined || contentType === null || contentType === "") {
                    contentType = "application/x-www-form-urlencoded; charset=UTF-8";
                }

                var internalErrorCallback = function (jqXHR, textStatus, errorThrown) {
                    var errorMsg = textStatus;
                    if (jqXHR.status)
                        errorMsg += " (" + jqXHR.status + ")";
                    if (errorThrown)
                        errorMsg += " " + errorThrown;

                    if (errorCallback) {
                        errorCallback(jqXHR, textStatus, errorThrown);
                    }
                }

                var options = {
                    url: url,
                    type: type,
                    cache: cache,
                    dataType: dataType,
                    success: successCallback,
                    error: internalErrorCallback,
                    contentType: contentType
                };

                if (antiForgeryToken) {
                    options.headers = {
                        'RequestVerificationToken': antiForgeryToken
                    };
                }

                if (data && type.toUpperCase() == "POST") {
                    options.data = data;
                }

                $.ajax(options);
            },
            getJson: function(url, successCallback, errorCallback, cache, antiForgeryToken) {
                coreJS.Ajax.performCall(url, "GET", "json", successCallback, errorCallback, null, cache, antiForgeryToken, null);
            },
            postJson: function(url, successCallback, errorCallback, data, cache, antiForgeryToken) {
                var jsonString = null;

                if (data != undefined)
                    jsonString = JSON.stringify(data);

                coreJS.Ajax.performCall(url, "POST", "json", successCallback, errorCallback, jsonString, cache, antiForgeryToken, "application/json;charset=utf-8");
            },
            performDelete: function (url, successCallback, antiForgeryToken) {
                coreJS.Ajax.performCall(url, "DELETE", "text", successCallback, null, null, false, antiForgeryToken, null);
            }
        },
        BankId: {
            _formElem: null,
            _loadingElem: null,
            _inputElem: null,
            _buttonElem: null,
            _cancelElem: null,
            _tokenElem: null,
            _statusElem: null,
            _appSSLMessage: "",
            _authCancelled: false,
            _antiForgeryTokenElem: null,
            _swedishLegalId: null,
            _sessionToken: null,
            _qrImageElem: null,
            _thisDevice: null,
            _qrcodeInformation: null,
            showInfo: function(msg) {
                coreJS.BankId.showMessage(msg, "info");
            },
            showSuccess: function(msg) {
                coreJS.BankId.showMessage(msg, "success");
            },
            showWarning: function(msg) {
                coreJS.BankId.showMessage(msg, "warning");
            },
            showError: function(msg) {
                coreJS.BankId.showMessage(msg, "error");
            },
            showMessage: function(msg, type) {
                coreJS.BankId.removeMessage();
                $(coreJS.BankId._statusElem).removeClass(function (index, className) {
                    return (className.match(/(^|\s)alert-\S+/g) || []).join(' ');
                });
                $(coreJS.BankId._statusElem).addClass("alert");
                $(coreJS.BankId._statusElem).addClass("alert-" + type);
                $(coreJS.BankId._statusElem).html(msg);
                $(coreJS.BankId._statusElem).show();
            },
            removeMessage: function () {
                $(coreJS.BankId._statusElem).text('');
                $(coreJS.BankId._statusElem).hide();
            },
            hideLoginButton: function () {
                $(coreJS.BankId._buttonElem).hide();
                $(coreJS.BankId._thisDevice).hide();
            },
            showLoginButton: function () {                
                $(coreJS.BankId._buttonElem).show();
                $(coreJS.BankId._thisDevice).show();
                $(coreJS.BankId._qrImageElem).hide();
                $(coreJS.BankId._cancelElem).hide();
            },
            initposition: function (thisDevice, otherDevice) {

                // on mobile, always put "this device" first
                if (coreJS.RWD.isMobile() === true || coreJS.RWD.isTablet() === true) {
                    $(otherDevice).insertAfter($(thisDevice));
                }
                else {
                    $(thisDevice).insertAfter($(otherDevice));
                }
            },
            authenticate: function (formElem, loadingElem, inputElem, buttonElem, cancelElem, tokenElem, statusElem, antiForgeryTokenElem, appTimeoutMessage, appSSLMessage, sessionToken, swedishLegalId, onlyAuth, qrcodeinformation) {
                coreJS.BankId._formElem = formElem;
                coreJS.BankId._loadingElem = loadingElem;
                coreJS.BankId._inputElem = inputElem;
                coreJS.BankId._buttonElem = buttonElem;
                coreJS.BankId._cancelElem = cancelElem;
                coreJS.BankId._tokenElem = tokenElem;
                coreJS.BankId._statusElem = statusElem;
                coreJS.BankId._antiForgeryTokenElem = antiForgeryTokenElem;
                coreJS.BankId._appSSLMessage = appSSLMessage;
                coreJS.BankId._sessionToken = sessionToken;
                coreJS.BankId._swedishLegalId = swedishLegalId;
                $(coreJS.BankId._cancelElem).off('click').on('click', coreJS.BankId.cancel);
                coreJS.BankId._authCancelled = false;
                coreJS.BankId._qrImageElem = $("*[data-bankid-qrimage]");  
                coreJS.BankId._thisDevice = '#btnBankIdThisDevice';
                coreJS.BankId._qrcodeInformation = qrcodeinformation;
                
                var authenticateErrorCallback = function (authResponse) {
                    if (authResponse.responseJSON.Data != undefined) {
                        var errorData = JSON.parse(authResponse.responseJSON.Data);
                        if (authResponse.responseJSON.Status == "error") {
                            coreJS.BankId.showError(errorData.Message);
                        }
                        else if (authResponse.responseJSON.Status == "warning") {
                            coreJS.BankId.showWarning(errorData.Message);
                        }
                        messageShown = true;
                    }
                    else if (authResponse.status == 403 && authResponse.statusText == "HTTPS Required")
                        coreJS.BankId.showError(coreJS.BankId._appSSLMessage);
                    else
                        coreJS.BankId.showError(authResponse.statusText);

                    coreJS.Animation.removeLoader(coreJS.BankId._loadingElem);
                    if (authResponse.responseJSON.Status == "error") {
                        coreJS.BankId.hideLoginButton();
                    }
                    else if (authResponse.responseJSON.Status == "warning") {
                        coreJS.BankId.showLoginButton();
                    }
                };

                var collectErrorCallback = function (response) {
                    var messageShown = false;

                    if (response != undefined && response.responseJSON != undefined && response.responseJSON.Data != undefined) {
                        var errorData = JSON.parse(response.responseJSON.Data);
                        if (response.responseJSON.Status == "error" && errorData.Message != undefined) {
                            coreJS.BankId.showError(errorData.Message);
                            messageShown = true;
                        }
                        else if (response.responseJSON.Status == "warning" && errorData.Message != undefined) {
                            coreJS.BankId.showWarning(errorData.Message);
                            messageShown = true;
                        }
                    }

                    if (!messageShown)
                        coreJS.BankId.showError("Ett okänt fel inträffade, var vänlig försök igen senare.");
                    
                    if (response.responseJSON.Status == "error")
                        coreJS.BankId.hideLoginButton();
                    else
                        coreJS.BankId.showLoginButton();

                    $(coreJS.BankId._cancelElem).hide();
                    coreJS.Animation.removeLoader(coreJS.BankId._loadingElem);
                };

                var antiForgeryToken = $(antiForgeryTokenElem).val();
                var authRequest = { "sessionid": coreJS.BankId._sessionToken };

                //if (coreJS.BankId._swedishLegalId)
                //    authRequest = { "id": $(inputElem).val() };
                //else {
                //    authRequest = 
                //}

                coreJS.Ajax.postJson(coreJS.App.buildApiUrl("/bankid/"),
                    function (authResponse) {
                    var authData = JSON.parse(authResponse.Data);
                    if (authData.Message != undefined && authData.Message.length > 0 && onlyAuth === false) {
                        coreJS.BankId.showInfo(authData.Message);
                    }
                    else {
                        coreJS.BankId.removeMessage();
                    }

                    coreJS.BankId.hideLoginButton();
                        if (authData.Token != undefined && authData.Token.length > 0) {
                            if (onlyAuth === false) {
                                coreJS.Animation.showLoader(
                                    coreJS.BankId._loadingElem,
                                    0,
                                    coreJS.Animation.loaderAlignment.center,
                                    coreJS.Animation.loaderSize.medium);
                                $(coreJS.BankId._thisDevice).hide();
                            }

                            $(coreJS.BankId._cancelElem).removeAttr("data-token");
                            $(coreJS.BankId._cancelElem).attr("data-token", authData.Token);
                            $(coreJS.BankId._thisDevice).attr("autostart-token", authData.AutoStartToken);
                            var redirectURI = "null";
                            var bankidurl = "bankid:///";
                            let pattern = /iPad|iPhone|iPod/;
                            if (swedishLegalId === false && onlyAuth === false) {
                                if (pattern.test(navigator.userAgent) && !window.MSStream) {
                                    //redirectURI = authData.RedirectUrl;
                                    bankidurl = "https://app.bankid.com/";
                                }
                                url = bankidurl + "?autostarttoken=" + authData.AutoStartToken + "&redirect=" + redirectURI;

                                jQuery('body').remove('a#hiddenlinkLauncher');
                                jQuery('body').append('<a id="hiddenlinkLauncher" href="' + url + '" target="_blank"><&nbsp;</a>');
                                setTimeout(function () {
                                    jQuery('#hiddenlinkLauncher')[0].click();
                                }, 100);
                            }
                        var i = 0;
                        function collectLoop(loopIndex, milliseconds) {
                            setTimeout(function () {
                                $(coreJS.BankId._cancelElem).show();
                                if (coreJS.BankId._authCancelled) {
                                    coreJS.Animation.removeLoader(coreJS.BankId._loadingElem);
                                    coreJS.BankId.removeMessage();
                                    
                                    $(coreJS.BankId._cancelElem).hide();                                    
                                    if (swedishLegalId === false && onlyAuth === false) {
                                        $(coreJS.BankId._thisDevice).show();
                                        $('#btnBankIdLogin').hide();
                                    }
                                    else {
                                        coreJS.BankId.showLoginButton();
                                    }
                                    return;
                                }
                                coreJS.Ajax.getJson(
                                    coreJS.App.buildApiUrl("/bankid/" + authData.Token),
                                    function (collectResponse) {
                                        var collectData = JSON.parse(collectResponse.Data);
                                        var showLoader = !swedishLegalId;

                                        if (loopIndex < 120 && !collectData.Authenticated && !collectData.Terminated) {
                                            coreJS.BankId.showInfo(collectData.Message);
                                            loopIndex++;
                                            // for qr-code ('other device') loop every second, on this every 2s

                                            // only show qr-code for 'other device'
                                            if (swedishLegalId === true) {
                                                coreJS.BankId.showInfo($('#bankidqrcodeInfo').val());
                                                //var qrimage = $('#qrimage');
                                                //$('<img src="data:image/png;base64,' + collectData.QRCode + '" alt="qrcode" id="qrimage" />').insertBefore('#bankIdState');
                                                $(coreJS.BankId._qrImageElem).attr("src", "data:image/png;base64," + collectData.QRCode).show(); 
                                                coreJS.BankId.showInfo(coreJS.BankId._qrcodeInformation);
                                            }

                                            collectLoop(loopIndex, milliseconds);
                                        }
                                        else if (collectData.Authenticated) {
                                            coreJS.BankId.showSuccess(collectData.Message);
                                            //if (swedishLegalId === false && onlyAuth === false) {
                                                $(coreJS.BankId._inputElem).val(collectData.SwedishLegalId);
                                            //}
                                            $(coreJS.BankId._tokenElem).val(collectData.Token);
                                            showLoader = false;
                                            $(coreJS.BankId._cancelElem).hide();
                                            $(coreJS.BankId._qrImageElem).hide();
                                            $(coreJS.BankId._formElem).submit();
                                        }
                                        else {
                                            if (!collectData.Terminated) {
                                                coreJS.BankId.showWarning(appTimeoutMessage);
                                            }
                                            else {
                                                coreJS.BankId.showWarning(collectData.Message);
                                            }
                                            
                                            //coreJS.BankId.showLoginButton();
                                            
                                            //$(coreJS.BankId._cancelElem).hide();
                                            showLoader = false;
                                        }

                                        if (!showLoader) {
                                            coreJS.Animation.removeLoader(coreJS.BankId._loadingElem);
                                        }
                                    },
                                    collectErrorCallback,
                                    false,
                                    antiForgeryToken);
                            }, milliseconds);
                            };
                            
                            collectLoop(i, swedishLegalId === true ? 2000 : 1000);
                            
                    }
                    else if (authData.ServiceAvailable) {
                        coreJS.BankId.showLoginButton();
                        $(coreJS.BankId._cancelElem).hide();
                    }
                },
                authenticateErrorCallback,
                authRequest,
                false,
                antiForgeryToken);
            },
            cancel: function () {
                coreJS.BankId._authCancelled = true;
                var token = $(coreJS.BankId._cancelElem).attr('data-token');
                var antiForgeryToken = $(coreJS.BankId._antiForgeryTokenElem).val();

                if (token != undefined && token.length > 0) {
                    coreJS.Ajax.performDelete(coreJS.App.buildApiUrl("/bankid/" + token), null, antiForgeryToken);
                }
                coreJS.BankId.showLoginButton();
            },
            swapElements : function (siblings, subjectIndex, objectIndex) {                
                
            }
        },
        Animation: {
            loaderSize: {
                "small": 1,
                "medium": 2,
                "large": 3
            },
            loaderAlignment: {
                "left": 1,
                "center": 2,
                "right": 3
            },
            showLoader: function (elem, timeout, alignment, size) {
                if (timeout == undefined)
                    timeout = 2000;
                if (alignment == undefined)
                    alignment = coreJS.Animation.loaderAlignment.left
                if (size == undefined)
                    size = coreJS.Animation.loaderSize.medium

                if ($(elem)) {
                    var sizeClass = "fa-2x"; // medium
                    if (size == coreJS.Animation.loaderSize.small) {
                        sizeClass = "fa-1x";
                    }
                    else if (size == coreJS.Animation.loaderSize.large) {
                        sizeClass = "fa-3x";
                    }
                    var alignmentClass = "text-left";
                    if (alignment == coreJS.Animation.loaderAlignment.center) {
                        alignmentClass = "text-center";
                    }
                    else if (alignment == coreJS.Animation.loaderAlignment.right) {
                        alignmentClass = "text-right";
                    }
                    var loadingElem = $("<div class='loader " + alignmentClass + "'><i class='fa fa-refresh fa-spin " + sizeClass + " fa-fw'></i></div>");
                    $(elem).append(loadingElem);
                    setTimeout(function () {
                        if ($(loadingElem)) {
                            $(loadingElem).show();
                        }
                    }, timeout);
                }
            },
            removeLoader: function (elem) {
                $(elem).children(".loader").remove();
            }
        },
        App: {
            _baseUrl: "",
            _baseApiUrl: "",
            setBaseUrl: function(url) {
                coreJS.App._baseUrl = url;
            },
            getBaseUrl: function() {
                return coreJS.App._baseUrl;
            },
            buildUrl: function(partialUrl) {
                var endsWith = coreJS.App._baseUrl.indexOf("/", this.length - "/".length) >= 0;

                if (partialUrl[0] == "/")
                    partialUrl = partialUrl.slice(1, partialUrl.length);

                var url = coreJS.App._baseUrl + (endsWith ? "" : "/") + partialUrl;

                return url;
            },
            setBaseApiUrl: function(url) {
                coreJS.App._baseApiUrl = url;
            },
            getBaseApiUrl: function() {
                return coreJS.App._baseApiUrl;
            },
            buildApiUrl: function(partialUrl) {
                var endsWith = coreJS.App._baseApiUrl.indexOf("/", this.length - "/".length) >= 0;

                var url = coreJS.App._baseApiUrl + (endsWith ? "" : "/") + partialUrl;
                return url;
            }
        },
        Tabs: {
            _tabList: [],
            initialize: function (elem, activeTab, callback, id) {
                coreJS.Tabs._tabList[id] = elem;
                for (i = 0; i < $(coreJS.Tabs._tabList[id]).children(".tab").length; i++) {
                    $($(coreJS.Tabs._tabList[id]).children(".tab")[i]).on('click', function () {
                        coreJS.Tabs.select(this, id);
                        if (callback)
                            callback(this);
                    });
                    $($(coreJS.Tabs._tabList[id]).children(".tab")[i]).on('keyup keydown', function (e) {
                        var code = e.key; 
                        if (code === "Enter") {
                            e.originalEvent.preventDefault();
                            e.preventDefault ? e.preventDefault() : (e.returnValue = false);
                            coreJS.Tabs.select(this, id);
                            
                            if (callback)
                                callback(this);
                        }
                    });
                }

                $(activeTab).trigger('click');
            },
            select: function (elem, elemId) {
                $(coreJS.Tabs._tabList[elemId]).children(".tab").removeClass("active");
                $(elem).addClass("active");
            }
        },
        formatTextToLowerCase: function (elementId) {
            var element = document.getElementById(elementId);
            var selectionStart = element.selectionStart;
            var selectionEnd = element.selectionEnd;
            
            element.value = element.value.toLowerCase().trim();

            element.setSelectionRange(selectionStart, selectionEnd);

        }
    };

    if (!window.coreJS) { window.coreJS = coreJS; }
})();

function initWcagForCheckboxesAndRadiobuttons() {
    // Make sure structural elements are marked as presentation
    $('.radiobuttonlist').children('TBODY').attr("role", "presentation").children('TR').attr("role", "presentation").children('TD').attr("role", "presentation");
    $('.checkboxlist').children('TBODY').attr("role", "presentation").children('TR').attr("role", "presentation").children('TD').attr("role", "presentation");

    $('.radiobuttonlist, .checkboxlist').each(function (index, element) {
        var labelId = $("[for='" + element.id + "'").id
        $(element).attr("aria-labelledby", labelId)
    });

    // Look for checkboxes and radiobuttons
    $('input[type="checkbox"], input[type="radio"]').each(function (index, element) {
        updateLabelledBy(element);
        updateAriaChecked(element);

        if (element.getAttribute("type") === "checkbox") {
            $(element).on('change', function () {
                updateAriaChecked(element);
            });
        }
        else if (element.getAttribute("type") === "radio") {
            $(element).on('change', function () {
                // Update aria-checked for all radiobuttons in the group
                // First, find the enclosing radiogroup element
                var radiogroupElement = $(element).closest("[role='radiogroup']")
                if (radiogroupElement != null) {
                    // Next, find all radio buttons that are children of the radio group element
                    radiogroupElement.find("input[type='radio']").each(function (index, child) {
                        updateAriaChecked(child);
                    })
                }
            });
        }
    });

    function updateLabelledBy(element) {
        var labels = $(element).siblings("[for='" + element.id + "']").first();
        var label;

        if (labels.length > 0)
            label = labels[0];
        else
            return;

        if (label != null) {
            if (!label.id) {
                label.id = element.id + "_label";
            }

            $(element).attr("aria-labelledby", label.id);
        }
    }
}

function updateAriaChecked(element) {
    if (element.checked) {
        $(element).attr("aria-checked", "true");
    }
    else {
        $(element).attr("aria-checked", "false");
    }
}

function onEveryLoad() {
    initWcagForCheckboxesAndRadiobuttons()
}
