/*! lazysizes - v2.0.0 */
!function () {
    "use strict";
    if (window.addEventListener) {
        var a = /\s+/g, b = /\s*\|\s+|\s+\|\s*/g, c = /^(.+?)(?:\s+\[\s*(.+?)\s*\])?$/, d = {contain: 1, cover: 1},
            e = function (a) {
                var b = lazySizes.gW(a, a.parentNode);
                return (!a._lazysizesWidth || b > a._lazysizesWidth) && (a._lazysizesWidth = b), a._lazysizesWidth
            }, f = function (a) {
                var b;
                return b = (getComputedStyle(a) || {
                    getPropertyValue: function () {
                    }
                }).getPropertyValue("background-size"), !d[b] && d[a.style.backgroundSize] && (b = a.style.backgroundSize), b
            }, g = function (d, e, f) {
                var g = document.createElement("picture"), h = e.getAttribute(lazySizesConfig.sizesAttr),
                    i = e.getAttribute("data-ratio"), j = e.getAttribute("data-optimumx");
                e._lazybgset && e._lazybgset.parentNode == e && e.removeChild(e._lazybgset), Object.defineProperty(f, "_lazybgset", {
                    value: e,
                    writable: !0
                }), Object.defineProperty(e, "_lazybgset", {
                    value: g,
                    writable: !0
                }), d = d.replace(a, " ").split(b), g.style.display = "none", f.className = lazySizesConfig.lazyClass, 1 != d.length || h || (h = "auto"), d.forEach(function (a) {
                    var b = document.createElement("source");
                    h && "auto" != h && b.setAttribute("sizes", h), a.match(c) && (b.setAttribute(lazySizesConfig.srcsetAttr, RegExp.$1), RegExp.$2 && b.setAttribute("media", lazySizesConfig.customMedia[RegExp.$2] || RegExp.$2)), g.appendChild(b)
                }), h && (f.setAttribute(lazySizesConfig.sizesAttr, h), e.removeAttribute(lazySizesConfig.sizesAttr), e.removeAttribute("sizes")), j && f.setAttribute("data-optimumx", j), i && f.setAttribute("data-ratio", i), g.appendChild(f), e.appendChild(g)
            }, h = function (a) {
                if (a.target._lazybgset) {
                    var b = a.target, c = b._lazybgset, d = b.currentSrc || b.src;
                    d && (c.style.backgroundImage = "url(" + d + ")"), b._lazybgsetLoading && (lazySizes.fire(c, "_lazyloaded", {}, !1, !0), delete b._lazybgsetLoading)
                }
            };
        addEventListener("lazybeforeunveil", function (a) {
            var b, c, d;
            !a.defaultPrevented && (b = a.target.getAttribute("data-bgset")) && (d = a.target, c = document.createElement("img"), c.alt = "", c._lazybgsetLoading = !0, a.detail.firesLoad = !0, g(b, d, c), setTimeout(function () {
                lazySizes.loader.unveil(c), lazySizes.rAF(function () {
                    lazySizes.fire(c, "_lazyloaded", {}, !0, !0), c.complete && h({target: c})
                })
            }))
        }), document.addEventListener("load", h, !0), window.addEventListener("lazybeforesizes", function (a) {
            if (a.target._lazybgset && a.detail.dataAttr) {
                var b = a.target._lazybgset, c = f(b);
                d[c] && (a.target._lazysizesParentFit = c, lazySizes.rAF(function () {
                    a.target.setAttribute("data-parent-fit", c), a.target._lazysizesParentFit && delete a.target._lazysizesParentFit
                }))
            }
        }, !0), document.documentElement.addEventListener("lazybeforesizes", function (a) {
            !a.defaultPrevented && a.target._lazybgset && (a.detail.width = e(a.target._lazybgset))
        })
    }
}();
/*! lazysizes - v2.0.0 */
!function(a,b){var c=b(a,a.document);a.lazySizes=c,"object"==typeof module&&module.exports&&(module.exports=c)}(window,function(a,b){"use strict";if(b.getElementsByClassName){var c,d=b.documentElement,e=a.Date,f=a.HTMLPictureElement,g="addEventListener",h="getAttribute",i=a[g],j=a.setTimeout,k=a.requestAnimationFrame||j,l=a.requestIdleCallback,m=/^picture$/i,n=["load","error","lazyincluded","_lazyloaded"],o={},p=Array.prototype.forEach,q=function(a,b){return o[b]||(o[b]=new RegExp("(\\s|^)"+b+"(\\s|$)")),o[b].test(a[h]("class")||"")&&o[b]},r=function(a,b){q(a,b)||a.setAttribute("class",(a[h]("class")||"").trim()+" "+b)},s=function(a,b){var c;(c=q(a,b))&&a.setAttribute("class",(a[h]("class")||"").replace(c," "))},t=function(a,b,c){var d=c?g:"removeEventListener";c&&t(a,b),n.forEach(function(c){a[d](c,b)})},u=function(a,c,d,e,f){var g=b.createEvent("CustomEvent");return g.initCustomEvent(c,!e,!f,d||{}),a.dispatchEvent(g),g},v=function(b,d){var e;!f&&(e=a.picturefill||c.pf)?e({reevaluate:!0,elements:[b]}):d&&d.src&&(b.src=d.src)},w=function(a,b){return(getComputedStyle(a,null)||{})[b]},x=function(a,b,d){for(d=d||a.offsetWidth;d<c.minSize&&b&&!a._lazysizesWidth;)d=b.offsetWidth,b=b.parentNode;return d},y=function(){var a,c,d=[],e=function(){var b;for(a=!0,c=!1;d.length;)b=d.shift(),b[0].apply(b[1],b[2]);a=!1};return function(f){a?f.apply(this,arguments):(d.push([f,this,arguments]),c||(c=!0,(b.hidden?j:k)(e)))}}(),z=function(a,b){return b?function(){y(a)}:function(){var b=this,c=arguments;y(function(){a.apply(b,c)})}},A=function(a){var b,c=0,d=125,f=999,g=f,h=function(){b=!1,c=e.now(),a()},i=l?function(){l(h,{timeout:g}),g!==f&&(g=f)}:z(function(){j(h)},!0);return function(a){var f;(a=a===!0)&&(g=66),b||(b=!0,f=d-(e.now()-c),0>f&&(f=0),a||9>f&&l?i():j(i,f))}},B=function(a){var b,c,d=99,f=function(){b=null,a()},g=function(){var a=e.now()-c;d>a?j(g,d-a):(l||f)(f)};return function(){c=e.now(),b||(b=j(g,d))}},C=function(){var f,k,l,n,o,x,C,E,F,G,H,I,J,K,L,M=/^img$/i,N=/^iframe$/i,O="onscroll"in a&&!/glebot/.test(navigator.userAgent),P=0,Q=0,R=0,S=0,T=function(a){R--,a&&a.target&&t(a.target,T),(!a||0>R||!a.target)&&(R=0)},U=function(a,c){var e,f=a,g="hidden"==w(b.body,"visibility")||"hidden"!=w(a,"visibility");for(F-=c,I+=c,G-=c,H+=c;g&&(f=f.offsetParent)&&f!=b.body&&f!=d;)g=(w(f,"opacity")||1)>0,g&&"visible"!=w(f,"overflow")&&(e=f.getBoundingClientRect(),g=H>e.left&&G<e.right&&I>e.top-1&&F<e.bottom+1);return g},V=function(){var a,b,e,g,i,j,m,n,p;if((o=c.loadMode)&&8>R&&(a=f.length)){b=0,S++,null==K&&("expand"in c||(c.expand=d.clientHeight>500?500:400),J=c.expand,K=J*c.expFactor),K>Q&&1>R&&S>3&&o>2?(Q=K,S=0):Q=o>1&&S>2&&6>R?J:P;for(;a>b;b++)if(f[b]&&!f[b]._lazyRace)if(O)if((n=f[b][h]("data-expand"))&&(j=1*n)||(j=Q),p!==j&&(C=innerWidth+j*L,E=innerHeight+j,m=-1*j,p=j),e=f[b].getBoundingClientRect(),(I=e.bottom)>=m&&(F=e.top)<=E&&(H=e.right)>=m*L&&(G=e.left)<=C&&(I||H||G||F)&&(l&&3>R&&!n&&(3>o||4>S)||U(f[b],j))){if(ba(f[b]),i=!0,R>9)break}else!i&&l&&!g&&4>R&&4>S&&o>2&&(k[0]||c.preloadAfterLoad)&&(k[0]||!n&&(I||H||G||F||"auto"!=f[b][h](c.sizesAttr)))&&(g=k[0]||f[b]);else ba(f[b]);g&&!i&&ba(g)}},W=A(V),X=function(a){r(a.target,c.loadedClass),s(a.target,c.loadingClass),t(a.target,Z)},Y=z(X),Z=function(a){Y({target:a.target})},$=function(a,b){try{a.contentWindow.location.replace(b)}catch(c){a.src=b}},_=function(a){var b,d,e=a[h](c.srcsetAttr);(b=c.customMedia[a[h]("data-media")||a[h]("media")])&&a.setAttribute("media",b),e&&a.setAttribute("srcset",e),b&&(d=a.parentNode,d.insertBefore(a.cloneNode(),a),d.removeChild(a))},aa=z(function(a,b,d,e,f){var g,i,k,l,o,q;(o=u(a,"lazybeforeunveil",b)).defaultPrevented||(e&&(d?r(a,c.autosizesClass):a.setAttribute("sizes",e)),i=a[h](c.srcsetAttr),g=a[h](c.srcAttr),f&&(k=a.parentNode,l=k&&m.test(k.nodeName||"")),q=b.firesLoad||"src"in a&&(i||g||l),o={target:a},q&&(t(a,T,!0),clearTimeout(n),n=j(T,2500),r(a,c.loadingClass),t(a,Z,!0)),l&&p.call(k.getElementsByTagName("source"),_),i?a.setAttribute("srcset",i):g&&!l&&(N.test(a.nodeName)?$(a,g):a.src=g),(i||l)&&v(a,{src:g})),y(function(){a._lazyRace&&delete a._lazyRace,s(a,c.lazyClass),(!q||a.complete)&&(q?T(o):R--,X(o))})}),ba=function(a){var b,d=M.test(a.nodeName),e=d&&(a[h](c.sizesAttr)||a[h]("sizes")),f="auto"==e;(!f&&l||!d||!a.src&&!a.srcset||a.complete||q(a,c.errorClass))&&(b=u(a,"lazyunveilread").detail,f&&D.updateElem(a,!0,a.offsetWidth),a._lazyRace=!0,R++,aa(a,b,f,e,d))},ca=function(){if(!l){if(e.now()-x<999)return void j(ca,999);var a=B(function(){c.loadMode=3,W()});l=!0,c.loadMode=3,W(),i("scroll",function(){3==c.loadMode&&(c.loadMode=2),a()},!0)}};return{_:function(){x=e.now(),f=b.getElementsByClassName(c.lazyClass),k=b.getElementsByClassName(c.lazyClass+" "+c.preloadClass),L=c.hFac,i("scroll",W,!0),i("resize",W,!0),a.MutationObserver?new MutationObserver(W).observe(d,{childList:!0,subtree:!0,attributes:!0}):(d[g]("DOMNodeInserted",W,!0),d[g]("DOMAttrModified",W,!0),setInterval(W,999)),i("hashchange",W,!0),["focus","mouseover","click","load","transitionend","animationend","webkitAnimationEnd"].forEach(function(a){b[g](a,W,!0)}),/d$|^c/.test(b.readyState)?ca():(i("load",ca),b[g]("DOMContentLoaded",W),j(ca,2e4)),W(f.length>0)},checkElems:W,unveil:ba}}(),D=function(){var a,d=z(function(a,b,c,d){var e,f,g;if(a._lazysizesWidth=d,d+="px",a.setAttribute("sizes",d),m.test(b.nodeName||""))for(e=b.getElementsByTagName("source"),f=0,g=e.length;g>f;f++)e[f].setAttribute("sizes",d);c.detail.dataAttr||v(a,c.detail)}),e=function(a,b,c){var e,f=a.parentNode;f&&(c=x(a,f,c),e=u(a,"lazybeforesizes",{width:c,dataAttr:!!b}),e.defaultPrevented||(c=e.detail.width,c&&c!==a._lazysizesWidth&&d(a,f,e,c)))},f=function(){var b,c=a.length;if(c)for(b=0;c>b;b++)e(a[b])},g=B(f);return{_:function(){a=b.getElementsByClassName(c.autosizesClass),i("resize",g)},checkElems:g,updateElem:e}}(),E=function(){E.i||(E.i=!0,D._(),C._())};return function(){var b,d={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",errorClass:"lazyerror",autosizesClass:"lazyautosizes",srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:!0,expFactor:1.5,hFac:.8,loadMode:2};c=a.lazySizesConfig||a.lazysizesConfig||{};for(b in d)b in c||(c[b]=d[b]);a.lazySizesConfig=c,j(function(){c.init&&E()})}(),{cfg:c,autoSizer:D,loader:C,init:E,uP:v,aC:r,rC:s,hC:q,fire:u,gW:x,rAF:y}}});
'use strict';

$(function () {
    window.monnerNavBar.init();
});

function anyCallToAction() {
    if (sessionStorage.getItem("reKYC") !== null) {
       $("#callToAction").show();
        $("#toReKYCBtn").show();
        $(document).ready(function() {
            $('#toReKYCBtn').hover(
                function() {
                    $(this).css('cursor', 'pointer');
                },
                function() {
                    $(this).css('cursor', 'default');
                }
            );
        });
    } else {
        $("#toReKYCBtn").hide();
    }
    if (sessionStorage.getItem("newAgreement") !== null) {
        $("#callToAction").show();
        $("#toNewAgreementBtn").show();
        $(document).ready(function() {
            $('#toNewAgreementBtn').hover(
                function() {
                    $(this).css('cursor', 'pointer');
                },
                function() {
                    $(this).css('cursor', 'default');
                }
            );
        });
    } else {
        $("#toNewAgreementBtn").hide();
    }
    if(sessionStorage.getItem("reKYC") === null && sessionStorage.getItem("newAgreement") === null){
        $("#callToAction").hide();
    }
}
window.addEventListener('load', function() {
    // Your function to run last
    anyCallToAction();
});
window.monnerNavBar = {
    init: function () {
        $('.logoText').click(()=>{
            window.location.href="/";
        });

        $('#toNewAgreementBtn').click(()=>{
            window.location.href="/aksepternyavtale";
        });
        $('#toReKYCBtn').click(()=>{
            window.location.href="/reonboarding";
        });

    },

};


window.onstorage = function (event) {
    if (event.key === 'sessionStorage' && !sessionStorage.monnersessiontoken) {
        sessionStorage.monnersessiontoken = event.newValue;
    }
    if (event.key === 'getSessionStorage') {
        if (sessionStorage.monnersessiontoken) {
            localStorage.sessionStorage = sessionStorage.monnersessiontoken;
            localStorage.removeItem('sessionStorage');
        }
    }
    if (event.key === 'clearSessionStorage') {
        if (sessionStorage.monnersessiontoken) {
            localStorage.removeItem('monnersessiontoken');
            sessionStorage.removeItem('monnersessiontoken');
        }
    }
};

if (!sessionStorage.monnersessiontoken) {
    localStorage.getSessionStorage = Date.now();
}

window.ServerApi = {


    handleErrorFromServer(fromServer, doOnDisplayableError) {
        if (fromServer.errorcode && doOnDisplayableError) {
            doOnDisplayableError(fromServer.errormessage, fromServer.errorcode);
        } else {
            console.log("Error at:");
            console.trace();
            Notification.error(fromServer.errormessage);
        }
    },

    getFromServer(url, doWithReturnData, doOnDisplayableError) {
        window.ServerApi.ajax({
            url,
            data: {},
            success(fromServer) {
                if (fromServer.status === 'error') {
                    window.ServerApi.handleErrorFromServer(fromServer, doOnDisplayableError);
                } else {
                    if (fromServer.trackEvent) {
                        //MonnerTracking.track(fromServer.trackEvent.name, fromServer.trackEvent.payload);
                    }
                    doWithReturnData(fromServer);
                }
            },
            error(jqXHR, textStatus, errorThrown) {
                console.log("Error at:");
                console.trace();
                Notification.error('Teknisk feil');
            },
        });
    },

    postToServer(url, jsonToServer, onSuccsess, doOnDisplayableError, onTechnicalError) {
        window.ServerApi.ajax({
            url,
            method: 'POST',
            data: JSON.stringify(jsonToServer),
            success(fromServer) {
                if (fromServer.status === 'error') {
                    window.ServerApi.handleErrorFromServer(fromServer, doOnDisplayableError);
                } else if (onSuccsess == null) {
                    window.location.reload();
                } else {
                    onSuccsess(fromServer);
                }
            },
            error(jqXHR, textStatus, errorThrown) {
                console.log("Error at:");
                console.trace();
                Notification.error('Teknisk feil');
                if (onTechnicalError) {
                    onTechnicalError();
                }
            },
        });
    },

    ajax(settings) {
        let self = window.ServerApi;
        const settingsCopy = settings;

        const accesstoken = localStorage.getItem('monnersessiontoken') || sessionStorage.getItem('monnersessiontoken');
        if (accesstoken) {
            settingsCopy.headers = {
                monnersessiontoken: accesstoken,
            };
        }
        if (settings.contentType !== false && settings.headers) {
            settingsCopy.headers['Content-Type'] = 'application/json';
        } else if ((!settings.headers || !settings.headers['Content-Type']) && settings.contentType !== false) {
            settingsCopy.headers = {
                'Content-Type': 'application/json',
            };
        }
        return $.ajax(settingsCopy);

    },

    updateToken(data) {

        if (data.callToActionItems) {
            if(data.callToActionItems.includes('newAgreement')){
                sessionStorage.setItem('newAgreement', "1")
            } else {
                sessionStorage.removeItem("newAgreement")
            }
            if(data.callToActionItems.includes('reKYC')){
                sessionStorage.setItem('reKYC', "1")
            } else {
                sessionStorage.removeItem("reKYC")
            }
        }

        if (data !== null && typeof (data) === 'object' && data.status === 'ok') {

            window.ServerApi.removeTokens();


            sessionStorage.setItem('monnersessiontoken', data.monnersessiontoken);
            if(data.isBackofficeUser){
                // Internal users get the session token persisted to localstorage in addition to localstorage,
                // to make it possible to have multiple tabs open at the same time in Backoffice etc
                localStorage.setItem('monnersessiontoken', data.monnersessiontoken);

                // Also sharing this token via a cookie, to make it possible to use the same session in the react localhost:3000 port
                // (localStorage is bound to a specific port, while cookies are shared for same domain across all ports )
                this.setMonioSharedDevSessionToken(data.monnersessiontoken, 1);
            }

            localStorage.sessionStorage = sessionStorage.monnersessiontoken;
            localStorage.removeItem('sessionStorage');
        }
    },


    setMonioSharedDevSessionToken(value, expiry) {
        let key = "monioDevSharedSessionToken";
        let expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + '; samesite=strict; expires=' + expires.toUTCString();
    },

    removeTokens() {
        sessionStorage.removeItem('monnersessiontoken');
        localStorage.removeItem('monnersessiontoken');
        localStorage.clearSessionStorage = Date.now();
    },

    dooingServerCall: false,

    monoPostToServer(url, payload, onSuccess, onDisplayableErrorError, doOnLongRequestsToServer, doWhenLongRequestDone) {
        const self = window.ServerApi;
        if (self.dooingServerCall) {
            console.log('User is impatient');
            return;
        }

        self.dooingServerCall = true;


        let hasWaitedForALongTime = null;
        if (doOnLongRequestsToServer) {
            Common.sleepThen(500, () => {
                if (hasWaitedForALongTime == null) {
                    hasWaitedForALongTime = true;
                    doOnLongRequestsToServer();
                }
            });
        }

        function handleWaintingLongTime() {
            if (hasWaitedForALongTime) {
                doWhenLongRequestDone();
            } else {
                hasWaitedForALongTime = false;
            }
        }

        self.postToServer(url, payload,
            (fromServer) => {
                self.dooingServerCall = false;
                handleWaintingLongTime();
                onSuccess(fromServer);
            },
            (errormessage, errorcode) => {
                self.dooingServerCall = false;
                if (onDisplayableErrorError) {
                    onDisplayableErrorError(errormessage, errorcode);
                }
                handleWaintingLongTime();
            },
            () => {
                handleWaintingLongTime();
            });
    },
};

/* global User, SocialMedia */


window.Common = {

  init() {
    this.initPasswordFields();
    this.removeFocusOutlinesOnClick();
    this.checkForIOS();
    this.checkForChromeAndroid();
    this.initExpandable();
    this.checkActiveStates();
    this.checkDataIfs();

    if (typeof(User) !== "undefined") {
      User._construct();
    }
    if (typeof(SocialMedia) !== "undefined") {
      SocialMedia._construct();
    }
  },


  /**
   * Initialize bindings needed for expandable content
   */
  initExpandable() {
    $('body').on('click', '.expandable', function () {
      const $el = $(this);

      if ($el.is('.expanded')) {
        $el.removeClass('expanded');
        $el.find('.expandable-content').stop().slideUp(300);
      } else {
        $el.addClass('expanded');
        $el.find('.expandable-content').stop().slideDown(300);
      }
    });
  },

  /**
   * Makes it possible to toggle character visibility on password fields
   */
  initPasswordFields() {
    $(document).on('click', '.input-with-icon .micon-eye-inactive, .input-with-icon .micon-eye-active', function () {
      const $input = $(this).prev();

      if ($input.attr('type') === 'password') {
        $('.hideablePassword').attr('type', 'text');
        $(this).removeClass('micon-eye-inactive').addClass('micon-eye-active');
      } else {
        $('.hideablePassword').attr('type', 'password');
        $(this).removeClass('micon-eye-active').addClass('micon-eye-inactive');
      }
    });
  },

  /**
   * Will make sure you only get element outlines on focus when
   * you are using TAB, and not clicking elements with the mouse
   */
  removeFocusOutlinesOnClick() {
    $('body').addClass('no-outlines');

    $(document).on('keydown', (e) => {
      if (e.keyCode === 9) {
        $('body').removeClass('no-outlines');
      }
    });

    $(document).on('click', () => {
      $('body').addClass('no-outlines');
    });
  },

  /**
   * Get URL parameter by URL
   *
   * @param name
   * @param url
   * @returns {*}
   */
  getUrlParameter(name, url) {
    url = url || window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');

    const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`);


    const results = regex.exec(url);

    if (!results) return null;
    if (!results[2]) return '';

    return decodeURIComponent(results[2].replace(/\+/g, ' '));
  },

  urlWithParameters(coreUrl, parameterToPassOn, possibleSecondParameter) {
    const parameterFromPageUrl = Common.getUrlParameter(parameterToPassOn);
    let returnValue = coreUrl;
    let seperator = '?';
    if (returnValue.includes('?')) {
      seperator = '&';
    }

    if (parameterToPassOn) {
      returnValue = `${returnValue + seperator + parameterToPassOn}=${parameterFromPageUrl}`;
    }
    if (possibleSecondParameter && Common.getUrlParameter(possibleSecondParameter)) {
      returnValue = `${returnValue}&${possibleSecondParameter}=${Common.getUrlParameter(possibleSecondParameter)}`;
    }

    return returnValue;
  },

  getPageInfo() {
    const addr = window.location.href;
    const ind = addr.lastIndexOf('/');

    return addr.substr(ind + 1);
  },

  /**
   * Check if we're running on iOS as we need some iOS specific styling
   */
  checkForIOS() {
    const isIOS = /iP(ad|hone|od).+Version\/[\d\.]+.*Safari/i.test(navigator.userAgent);

    if (isIOS) {
      $('body').addClass('ios');

      // Check to check for iPhone X, we need to check for this because Apple don't care about web standards
      if (screen.availHeight === 812 && screen.availWidth === 375) {
        $('body').addClass('iphonex');
      }
    }
  },

  /**
   * Check if we're running on Chrome on Android
   */
  checkForChromeAndroid() {
    const userAgent = navigator.userAgent;

    if (/Android/i.test(navigator.userAgent) && /Chrome/i.test(navigator.userAgent)) {
      $('body').addClass('android-chrome');
    }
  },


  /**
   * Will check all elements with the data-check-active attribute if the elements href value is the same as current URL
   */
  checkActiveStates() {
    $(`[data-check-active][href$="${window.location.pathname}"]`).each(function () {
      $(this).addClass('active');
    });
  },

  checkDataIfs() {
    const self = this;

    $('[data-if]').hide().each(function () {
      const $el = $(this);
      const parameter = $el.attr('data-if');

      if (self.getUrlParameter(parameter)) {
        $el.show();
      }
    });
  },

  ready(fn) {
    if (document.attachEvent ? document.readyState === 'complete' : document.readyState !== 'loading') {
      fn();
    } else {
      document.addEventListener('DOMContentLoaded', fn);
    }
  },

  validateEmail(email) {
    const 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,}))$/;
    return re.test(email);
  },

  /**
   * @param {String} html representing a single element
   * @return {Element}
   */
  htmlToElement(html) {
    const template = document.createElement('template');
    template.innerHTML = html.trim();
    return template.content.firstChild;
  },

  formatMoney(amount, decimalCount = 0, decimal = ',', thousands = ' ') {
    let checkDecimalCount = Math.abs(decimalCount);
    checkDecimalCount = Number.isNaN(checkDecimalCount) ? 2 : checkDecimalCount;
    const negativeSign = amount < 0 ? '-' : '';
    const i = Number.parseInt(amount = Math.abs(Number(amount) || 0)
      .toFixed(checkDecimalCount), 10).toString();
    const j = (i.length > 3) ? i.length % 3 : 0;

    return negativeSign + (j ? i.substr(0, j) + thousands : '')
      + i.substr(j).replace(/(\d{3})(?=\d)/g, `$1${thousands}`)
      + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : '');
  },

  makeFundingCaseUrl(type, idOrAlias) {
    if (type === 'EQUITY') {
      return `/aksje/${idOrAlias}`;
    }
    return `/laan/${idOrAlias}`;
  },

  fileUploader($uploadButton, $hiddenFilePicker, toUrl, additionalParamenters, errorHandlerFunction, succsessFunction) {
    if (succsessFunction == null) {
      succsessFunction = function () {
        window.location.reload();
      };
    }

    $uploadButton.click(() => {
      $hiddenFilePicker.click();
    });

    $hiddenFilePicker.on('change', (event) => {
      const formData = new FormData();
      const theFile = event.target.files[0];
      if (theFile && theFile.size > 8 * 1024 * 1024) {
        if (_.isFunction(errorHandlerFunction)) {
          errorHandlerFunction('Filen kan ikke være større enn 8MB');
        } else {
          alert('Filen kan ikke være større enn 8MB');
        }
        return;
      }
      formData.append('fileupl', theFile);

      if (_.isFunction(additionalParamenters)) {
        additionalParamenters = additionalParamenters();
      }
      $.each(additionalParamenters, (index, oneParam) => {
        formData.append(oneParam.id, oneParam.value);
      });
      formData.append('filename', theFile.name);
      formData.append('type', theFile.type);
      window.ServerApi.ajax({
        url: toUrl,
        method: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        success: succsessFunction,
      });
    });
  },

  templateFromCurrentPage(quaryString) {
    return $($(quaryString).html());
  },

  compare(a, b) {
    if (a > b) {
      return 1;
    }
    if (a === b) {
      return 0;
    }
    return -1;
  },

  randomBase64: function(size) {
    return btoa(String.fromCharCode.apply(null, window.crypto.getRandomValues(new Uint8Array(size))));
  },

  base64UrlEncodeString(str) {
    let b64 = btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
        function toSolidBytes(match, p1) {
          return String.fromCharCode('0x' + p1);
        }))
        .replace(/\//g,'_')
        .replace(/\+/g,'-')
        .replace(/\=/g,'')
    return b64
  },

  base64UrlDecodeString(b64) {
    if (!b64)
      return null
    let str = b64.replace(/_/g,'/').replace(/-/g,'+')
    return decodeURIComponent(atob(str).split('').map(function(c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
  },

  sleepThen(time, thenDo) {
    new Promise(resolve => setTimeout(thenDo, time));
  },

  showLoader() {
    $('.loadIconWrapper').append(Common.loaderElement);
  },

  hideLoader() {
    $('.loadIconWrapper').hide();
  },

  loaderElement: `
      <!-- monnerinclude /crowd/html/reusables/loadingWindow.html -->
    `,
};

$(() => {
  window.Common.init();
});

'use strict';

window.User = {

    data: null,

    loading: false,

    waitingCallbacks: [],

    _construct: function () {
        this.getUserFromServer();
        window.addEventListener('storage', (event) => {
            if (event.key == 'removeAllLocalCredentialsEvent' && event.newValue) {
                this._removeAllLocalCredentials(false)
                window.location.href = "/";
            }
        })
    },

    get: function (callback) {
        let self = this;

        if (typeof callback !== 'function') {
            throw 'Callback needs to be a function';
        }

        // If no data exist, get it from the server, the data should probably invalidate after a certain amount of time
        if (self.data === null) {
            return self.getUserFromServer(callback);
        }

        callback(self.data);
    },

    logout: function (reloadPage) {
        let self = this

        window.ServerApi.ajax({
            method: "POST",
            url: "/api/logout",
            data: JSON.stringify({}),
            success: function () {
                self._removeAllLocalCredentials(true)
                if(reloadPage){
                    window.location.href = "/";
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
            }
        });

    },

    // Private function. Do not call this unless the server has been notified through logout()
    _removeAllLocalCredentials: function (notifyOtherWindows) {
        window.ServerApi.removeTokens();
        if (this.data) {
            this.data.user = null;
        }
        window.sessionStorage.removeItem("onboardingStartedOn");
        window.sessionStorage.removeItem("onboardingType");
        window.sessionStorage.removeItem("newAgreement");
        window.sessionStorage.removeItem("reKYC");

        if (notifyOtherWindows) {
            // Triggers a storage event to all browsers.
            localStorage.setItem("removeAllLocalCredentialsEvent", Date.now());
            localStorage.removeItem("removeAllLocalCredentialsEvent");
        }
    },

    timerVar: null,
    timeoutmillis: null,
    startTimerFunction: function (self) {
        if (!self.timeoutmillis) {
            return;
        }
        self.stopTimerFunction(self);
        self.timerVar = window.setInterval(function () {
            self.logout(false);
            window.location.href = "/logg_inn?timeout=true";
        }, self.timeoutmillis);
    },
    stopTimerFunction: function (self) {
        if (self.timerVar) {
            window.clearInterval(self.timerVar);
            self.timerVar = null;
        }
    },

    isLogedIn: function () {
        return sessionStorage.monnersessiontoken !== null;

    },

    getUserFromServer: function (callback) {
        let self = this;
        // Loading a user without monnersession token will fail, and will block potentially successful loading of users
        // if they are initiated before this load is finished.
        if (!self.isLogedIn() ) {
            if (typeof callback === 'function') {
                if (self.data)
                    callback(self.data)
                else
                    callback({})
            }
            return
        }

        if (typeof callback === 'function') {
            self.waitingCallbacks.push(callback);
        }

        if (self.loading) return;


        self.loading = true;

        window.ServerApi.ajax({
            method: "GET",
            url: "/api/currentUser",
            success: function (data) {
                self.data = data;
                if (data.user) {
                    if(window.ga){
                        window.ga(function(tracker) {
                            /*
                            MonnerTracking.identify(data.user.userid, {
                                clientId: tracker.get('clientId'),
                                userId: data.user.userid
                            })

                             */
                        })
                    }
                }

                if (self.data && self.data.user) {
                    self.timeoutmillis = data.timeoutmillis;
                    self.startTimerFunction(self);
                } else {
                    self.stopTimerFunction(self);
                }

                self.loading = false;

                self._runWaitingCallbacks(data);
            }
        });
    },

    _runWaitingCallbacks: function (data) {
        var self = this;

        _.each(self.waitingCallbacks, function (callback) {
            callback(data);
        });

        self.waitingCallbacks = [];
    },

    registerWhereToGoBackToAfterLogin: function () {
        window.sessionStorage.setItem("loginFrom", window.location.href);
    },
};
'use strict';

window.SocialMedia = {

    sites: {},

    /**
     * Constructor
     */
    _construct: function() {
        var url = window.location.href,
            title = $('h1').text(),
            summary = '';

        this.sites.facebook = {
            title: 'Facebook',
            url: 'https://www.facebook.com/sharer/sharer.php?u=' + url
        };

        this.sites.linkedin = {
            title: 'LinkedIn',
            url: 'http://www.linkedin.com/shareArticle?mini=true&url=' + url + (title ? '&title=' + title : '') + (summary ? '&summary=' + summary : '')
        };

        this.sites.twitter = {
            title: 'Twitter',
            url: 'https://twitter.com/intent/tweet?text=' + (summary ? summary : '') + '%20' + url
        };

        this.registerBindings();
    },

    /**
     * Register bindings
     */
    registerBindings: function() {
        var self = this;

        $('body').on('click', '[data-share]', function(e) {
            e.preventDefault();
            self.share($(this).attr('data-share'));
        });
    },

    /**
     * Open the share popup
     *
     * @param site
     */
    share: function(site) {
        var trackingEvent;
        if (window.User.data.user) {
            trackingEvent = "Customer - Shared";
        } else {
            trackingEvent = "Visitor - Shared";
        }
        var trackingPayload = {};
        trackingPayload.company_name = $("#businessName").text();
        trackingPayload.headline = $("#loanTitle").text();
        trackingPayload.amount = $("#investedValue").text();
        trackingPayload.invested = $("#loanAmount").text();

        //MonnerTracking.track(trackingEvent, trackingPayload);


        this.popupCenter(this.sites[site].url, this.sites[site].title, 580, 470)
    },

    /**
     * Open a popup on the middle of the screen
     *
     * @param url
     * @param title
     * @param w
     * @param h
     */
    popupCenter: function(url, title, w, h) {
        var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
        var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;

        var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
        var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

        var left = ((width / 2) - (w / 2)) + dualScreenLeft;
        var top = ((height / 3) - (h / 3)) + dualScreenTop;

        var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

        // Puts focus on the newWindow
        if (newWindow && newWindow.focus) {
            newWindow.focus();
        }
    },

};

$(function () {
    window.Newsletter.init();
});

window.Newsletter = {
    init:function(){
        $('#wantNewsletterButton').click(Newsletter.onNewsletterAbo);
    },

    onNewsletterAbo: function() {
        let trackingpayload = {email: $('#emailForNewsletter').val()};


        $('#newsletterError').html('');
        $('#emailForNewsletter').removeClass('error');
        $('#newsLetter').removeClass('error');

        if (!trackingpayload.email.length) {
            $('#newsletterError').html('<div class="error"><span>Vennligst fyll inn en e-postadresse</span></div>');
            $('#emailForNewsletter').addClass('error');
            return;
        }

        if (!Common.validateEmail(trackingpayload.email)) {
            $('#newsletterError').html('<div class="error"><span>E-postadressen er ugyldig, vennligst fyll inn en gyldig e-postadresse.</span></div>');
            $('#emailForNewsletter').addClass('error');
            return;
        }

        $('#wantNewsletterButton').text('Sender..');

        window.ServerApi.ajax({
            url: "/openapi/subscribeNewsletter",
            method: "POST",
            data: JSON.stringify(trackingpayload),
            success: function( fromServer ) {
                if (fromServer.status !== "ok") {
                    $('#newsletterError').html('<div class="error"><span>' + fromServer.errormessage + '</span></div>');
                    $('#emailForNewsletter').addClass('error');
                    return;
                }
                $('#newsletterButtonAnimator').fadeOut(250, function() {
                    $('#newsletterSuccess').fadeIn(250);
                });

            }
        });
    }

};
'use strict';

$(function (){
    window.crowdHome.init();
})

    let isSmall;
window.crowdHome = {

    init: function () {

        try {
            // Attempt to use InvestmentSuggestions
            if (InvestmentSuggestions) {
                InvestmentSuggestions.$el = $('#investmentCards');
                InvestmentSuggestions.registerSlider();
                InvestmentSuggestions.populateList();
            }
        } catch (error) {
            // DO nothing
        }

        $('.statisticMessageBox-footer').hide();

        User.get(function(data) {
            if(data.user) {
                if (data.user.roles.length > 0) {
                    $('#investButton').text("Invester nå");
                    $('#investButton')[0].onclick = null
                    $('#investButton').click(()=>{
                        location.href = "/invester"
                    })
                }
            }
        });
    },
};
$(function () {
    window.TechnicalDifficultiesBanner.init();
});

window.TechnicalDifficultiesBanner = {
    init: function () {
        let self = window.TechnicalDifficultiesBanner;
        self.technicalDifficultiesBanner(self)
    },
    technicalDifficultiesBanner: function(self){
        ServerApi.getFromServer("/api/technicalDifficulties", function(data){
            if(data.currentStatus.isActive){
                $('.technicalDifficultiesBanner').show();
                $('#technicalDifficultiesBannerText').text(data.currentStatus.message);
            }
        });
    }
}
'use strict';



window.Menu = {

    $el: null,
    haveRemovedWhiteClassFromPageHeader: false,

    init: function($el) {
        this.$el = $('#headMenu');

        window.addEventListener('storage', (event) => {
            if (event.key == 'sessionStorage' && this.monnersessiontokenChecked != sessionStorage.monnersessiontoken) {
                this.monnersessiontokenChecked = sessionStorage.monnersessiontoken
                this.checkUserState();
            }
        })

        this.checkUserState();
        this.registerBindings();
        //this.populateStatistics();
        this.showInvestWarning();
    },

    showInvestWarning() {
        window.User.get(function(data) {
            if (!data.minutesLeftForSigningPledge) {
                return;
            }
            $("#investMinutesLeftSpan").append(data.minutesLeftForSigningPledge);
            $("#investSignLink").attr("href",data.linkToPledgeToSign);
            $(".investReminderBanner").show();
        });
    },
    populateStatistics: function () {
        window.ServerApi.getFromServer("/api/statistics",function (fromServer) {
            $(".statAmountInvested").append(fromServer.amountPledged);
            $(".statNumCampains").append(fromServer.numCampains);
            $(".statNumberOfPledges").append(fromServer.numberOfPledges);
            $(".statAmountAvailble").append(fromServer.amountAvailble);
            if (fromServer.note) {
                var $section = $(".statisticMessageBox");
                $section.append($('<div class="statItem statSeperator">|</div>'));
                $section.append($('<div class="statItem">' + fromServer.note + '</div>'));
            }
        });
    },

    /**
     * Register bindings
     */
    registerBindings: function() {
        var self = this;

        self.$el.find('#logoutButton').on('click', function() {
            User.logout(true);
        });

        self.$el.find("#menuLoginButton").click(User.registerWhereToGoBackToAfterLogin);

        self.$el.find('#customerNavigationToggle').on('click', function() {
            if ($(this).parent().is('.open')) {
                self.closeCustomerNavigation();
            } else {
                self.openCustomerNavigation();
            }
        });

        self.$el.find('#customerNavigationToggleSplit').on('click', function() {
            if ($(this).parent().is('.open')) {
                self.closeCustomerNavigation();
            } else {
                self.openCustomerNavigation();
            }
        });

        $(document).on('click', function(e) {
            if (!$(e.target).closest('.customer-navigation-container').length) {
                self.closeCustomerNavigation();
            }
        });

        $(document).on('keyup',function(e) {
            if (e.keyCode === 27) { // ESC key
                self.closeCustomerNavigation();
            }
        });

        $(window).on('focusin', function(e) {
            if (!$('body').hasClass('customer-navigation-open')) {
                return;
            }

            if (!$(e.target).closest('header.page-header').length) {
                $('header.page-header .logo').focus();
            }
        });

        var debounce = _.debounce(function() {
            self.adjustOnMobileDesktopSwitch();
        }, 100);

        $(window).on('resize', debounce);

    },

    /**
     * Check the user state and update the navigation
     */
    checkUserState: function() {
        var self = this;

        User.get(function(data) {
            self.showFirstNavigation();
            self.showSecondNavigation();
            if (!data.user) {
                self.enableNotLoggedInState();
                return;
            }


            self.$el.find('#menuUserName').text(data.user.username);
            self.$el.find('[data-not-logged-in]').hide();

            self.$el.find('[data-logged-in]').show();
            self.showLoggedInItems(data.menuItems);

/*            if (data.user.roles.length === 0) {
                self.$el.find('[data-line-height-pending]').addClass("lineHeight");
                self.$el.find("#micon-profil").hide();
                self.$el.find("#micon-pending").show();
                self.$el.find('#customerNavigationToggle').unbind("click");
                self.$el.find("#customerNavigationToggle").click(function(ev) {
                    window.location.href = data.landingPage;
                });
                return;
            }
*/
            if (data.customerList && data.activeCustomerId){
                self.showCustomerList(data.customerList, data.activeCustomerId);
            }

            if (_.contains(data.user.roles, 'INVESTOR')) {
                self.enableInvestorState();
            }
            if (_.contains(data.user.roles, 'LOAN_CUSTOMER')) {
                self.enableBusinessState();
            }

        });
    },

    /**
     * Open customer navigation
     */
    openCustomerNavigation: function() {
        var self = this;

        if (self.isMobileView()) {
            $('header.page-header').addClass('mobileNavDarkModeOverride');
            $('header.page-header .customer-navigation-container').addClass('mobileNavDarkModeOverride');
            $('header.page-header .customer-navigation-container .customer-navigation nav ul li a').addClass('mobileNavDarkModeOverride');
            $('header.page-header .logo').addClass('mobileLogoDarkModeOverride');
            $('#hamburger-not-logged-in').addClass('mobileNavDarkModeOverride');


            self.haveRemovedWhiteClassFromPageHeader = true;
        }

        $('body').addClass('customer-navigation-open');
        self.$el.find('.customer-navigation-container').addClass('open');
    },

    /**
     * Close customer navigation
     */
    closeCustomerNavigation: function() {
        var self = this;

        var $pageHeader = $('header.page-header');

        if (self.haveRemovedWhiteClassFromPageHeader === true) {
            $pageHeader.addClass('white');
        }

        $('body').removeClass('customer-navigation-open');
        $('header.page-header').removeClass('mobileNavDarkModeOverride');
        $('header.page-header .customer-navigation-container').removeClass('mobileNavDarkModeOverride');
        $('header.page-header .customer-navigation-container .customer-navigation nav ul li a').removeClass('mobileNavDarkModeOverride');
        $('header.page-header .logo').removeClass('mobileLogoDarkModeOverride');
        $('#hamburger-not-logged-in').removeClass('mobileNavDarkModeOverride');

        self.$el.find('.customer-navigation-container')
            .on('transitionend', function() {
                $(this).removeClass('fadeout');
                $(this).off('transitionend');
            })
            .removeClass('open');
    },

    /**
     * Enable the navigation state for unauthorized users
     */
    enableNotLoggedInState: function() {
        var self = this;
        window.sessionStorage.removeItem("newAgreement");
        window.sessionStorage.removeItem("reKYC");
        self.$el.find('#anonymousItems').show();
        self.$el.find('faededItems').show();
        self.$el.addClass('not-logged-in');
        self.$el.find('[data-logged-in]').hide();
        self.$el.find('[data-not-logged-in]').show();
        self.$el.find('[data-line-height-pending]').removeClass("lineHeight");

        self.$el.removeClass('logged-in');
        self.$el.find('#loggedinItems').hide();
    },

    /**
     * Enable the navigation state for investors
     */
    enableInvestorState: function() {
        var self = this;

        self.$el.find('#investorItems').show();
        self.$el.addClass('logged-in');


    },

    /**
     * Enable the navigation state for businesses
     */
    enableBusinessState: function() {
        var self = this;

        self.$el.find('.icon-circle .micon-profile')
            .removeClass('micon-profile')
            .addClass('micon-briefcase');

        //self.$el.find('#businessItems').show();
        self.$el.addClass('logged-in');


    },


    showLoggedInItems: function(menuItems) {
        var self = this;
        self.$el.find('#loggedinItems').show();
        $.each(menuItems, function (idex,id) {
            self.$el.find("#"+id).removeAttr("style");
        });
        self.$el.find('#anonymousItems').hide();
        self.$el.removeClass('not-logged-in');
    },

    customerTemplateRow: '<a id="customerSwitch" href="#"></a>',

    showCustomerList: function(customerList, activeCustomerId) {
        const self = window.Menu;
        let parsedCustomerList;
        if (_.isArray(customerList)) {
            parsedCustomerList = customerList;
        } else {
            parsedCustomerList = JSON.parse(customerList);
        }
        $.each(parsedCustomerList, function (index, row) {
            if (row.customerId === activeCustomerId){
                self.$el.find("#menuCurrentCustomer").text(row.customerName);
                self.$el.find("#currentCustomerLabel").show()
            } else {
                const $thisLine = $(self.customerTemplateRow);
                $thisLine.append(row.customerName);
                $thisLine.click(() => self.switchUser(row.customerId));
                self.$el.find("#customerList").append($thisLine);
            }
        });
    },

    switchUser(customerId){

        const payload = {
            customerid: customerId
        };

        window.ServerApi.ajax({
            url: "/api/changeActiveCustomer",
            method: "POST",
            data: JSON.stringify(payload),
            success: function (fromServer) {
                if (fromServer.status === 'ok'){
                    document.location.href = "/bedrift/dine_finansieringer"
                }
            }
        });
    },

    /**
     * Show the right part of the navigation
     */
    showFirstNavigation: function() {
        var self = this;

        self.$el.find('.first-navigation').css('display', 'block');
    },

    /**
     * Show the right part of the navigation
     */
    showSecondNavigation: function() {
        var self = this;

        self.$el.find('.second-navigation').show();
    },



    /**
     * If the mobile view is active or not
     *
     * @returns {boolean}
     */
    isMobileView: function() {
        return (window.innerWidth <= 885);
    },

    /**
     * Adjust some things when we switch from mobile to desktop view and visa versa
     */
    adjustOnMobileDesktopSwitch: function() {
        var self = this;

        if (self.isMobileView()) {
            if ( (self.haveRemovedWhiteClassFromPageHeader || $('header.page-header').is('.white')) && ($('.customer-navigation-container').is('.open'))) {
                $('header.page-header').removeClass('white');
                self.haveRemovedWhiteClassFromPageHeader = true;
            }
        } else {
            if (self.haveRemovedWhiteClassFromPageHeader) {
                $('header.page-header').addClass('white');
            }
        }
    }

};

$(document).ready(function () {
    window.Menu.init();
});
'use strict';

window.Tabs = {

    $el: null,

    init: function($el, forceShowAllContent) {
        this.$el = $el;

        if (forceShowAllContent) {
            this.unwrapAllTabContent();
        } else {
            this.initStickyTabs();
            this.setInitialActiveTab();
            this.registerBindings();
        }
    },

    // Flattens page: all tab divs shown at once & remove the tab header
    unwrapAllTabContent: function (){
        $('.tab[data-tab]').addClass('active');
        $('.tabs-header').hide();
    },

    registerBindings: function() {
        var self = this;

        self.$el.find('.tabs-header .tab[data-tab], a[data-tab]').on('click', function(e) {
            e.preventDefault();

            if ($(this).is('.active')) {
                return;
            }

            self.setActiveTab($(this).attr('data-tab'));
        });

        self.$el.find('[data-tab-next]').on('click', function() {
            self.nextTab();
        });

        self.$el.find('[data-tab-previous]').on('click', function() {
            self.previousTab();
        });

    },

    /**
     * Set the first tab as active unless some other tab is manually set as active
     */
    setInitialActiveTab: function() {
        var self = this;

        if (self.$el.find('.tab[data-tab]').is('.active')) {
            self.setActiveTab(self.$el.find('.tab[data-tab].active').attr('data-tab'));
            return;
        }

        self.$el.find('.tab:first-child').addClass('active');
    },

    initStickyTabs: function() {
        if (!this.$el.is('.sticky')) {
            return;
        }


        $('.sticky .tabs-header-wrapper').sticky();

    },

    setActiveTab: function(tab) {
        var self = this;

        var $currentActiveTabContent = self.$el.find('.tabs-content .tab.active');
        var $newActiveTabContent = self.$el.find('.tabs-content .tab[data-tab="' + tab + '"]');

        if ($newActiveTabContent.is('.active')) {
            return;
        }

        self.$el.find('.tabs-header .tab[data-tab]').removeClass('active');
        self.$el.find('.tabs-header .tab[data-tab="' + tab + '"]').addClass('active');

        $currentActiveTabContent
            .on('transitionend', function() {
                $(this)
                    .removeClass('active')
                    .off('transitionend')
                    .removeClass('fadeout');

                $newActiveTabContent.addClass('active');

                if (self.$el.find('.sticky-wrapper').is('.is-sticky')) {
                    $('html, body').stop().animate({
                        scrollTop: $('.tabs-container.sticky').offset().top + 1
                    }, 0);
                }
            })
            .addClass('fadeout');
    },

    nextTab: function() {
        var self = this;

        var $currentActiveTabContent = self.$el.find('.tabs-content .tab.active');
        var $nextTab = $currentActiveTabContent.next();
        
        if ($nextTab.length && $nextTab.attr('data-tab').length) {
            self.setActiveTab($nextTab.attr('data-tab'));
        }
    },

    previousTab: function() {
        var self = this;

        var $currentActiveTabContent = self.$el.find('.tabs-content .tab.active');
        var $previousTab = $currentActiveTabContent.prev();

        if ($previousTab.length && $previousTab.attr('data-tab').length) {
            self.setActiveTab($previousTab.attr('data-tab'));
        }
    },
};
'use strict';

window.Notification = {

    error: function(message) {

        $('.notification').remove();

        var html = '<div class="notification error hidden"><div class="message">' + message + '</div></div>';

        $('body').append(html);

        setTimeout(function() {
            $('.notification').removeClass('hidden');
        }, 20);

        setTimeout(function() {
            $('.notification').addClass('hidden');
        }, 20000);
    }

};
'use strict';

window.Template = {

  get(template, callback) {
    $.get('/templates/' + template + '.html', function (html) {
      callback(html);
    });
  },

  getWithFullUrl(templateUrl, callback) {

    var request = new XMLHttpRequest();
    request.open("GET", templateUrl, true);
    request.send(null);
    request.onreadystatechange = function() {
      if (request.readyState == 4)
        callback(request.responseText);
    };
  },

  fromTextToElement(htmlFromTemplate) {
    const returnValue= document.createElement('div');
    returnValue.innerHTML= htmlFromTemplate;
    return returnValue.firstElementChild;
  }

};

'use strict';

// Call from footer everywhere, so that the adtraction tracking ref is pulled from url params to localstorage at every
// opportunity
window.AdTractionTracking = {
    init: function () {
        let code = window.Common.getUrlParameter(this.ADTRACTION_KEY);
        this.cacheTrackingCode(code);
    },

    ADTRACTION_KEY: "at_gd",

    cacheTrackingCode: function (code) {
        if (code) {
            window.localStorage.setItem(this.ADTRACTION_KEY, code);
        }
    },

    // Get url param is present, fall back to cached value if not
    getAdTractionCode: function () {
        let code = window.Common.getUrlParameter("at_gd");
        if (!code) {
            code = window.localStorage.getItem(this.ADTRACTION_KEY);
        }
        return code;
    },

    clearCachedAdTractionCode: function () {
        window.localStorage.removeItem(this.ADTRACTION_KEY);
    }
};

window.AdTractionTracking.init();
'use strict';

window.ReferrerTracking = {
    init: function () {

        let referrer = window.localStorage.getItem("referrerId")
        let utmValues = window.localStorage.getItem("utmValues")

        if(!utmValues){
            const urlParam = new URLSearchParams(window.location.search)
            utmValues = {
                source: urlParam.get("utm_source"),
                medium: urlParam.get("utm_medium"),
                campaign: urlParam.get("utm_campaign"),
                term: urlParam.get("utm_term"),
                content: urlParam.get("utm_content")
            }
        }

        if(!referrer){
            referrer = document.referrer
            if(referrer.includes("https://folkeinvestformidling.no") || referrer.includes("https://www.folkeinvestformidling.no")){
                return
            }
            let payload = {
                referrer: referrer,
            }
            window.ServerApi.postToServer("api/newUserReferrer", payload, function(fromServer){
                window.localStorage.setItem("referrerId", fromServer.referrerId)
                window.localStorage.setItem("utmValues", JSON.stringify(utmValues))
            })
        }
    },

    getReferrerId: function(){
        let referrerId = window.localStorage.getItem("referrerId")
        let utmValues = JSON.parse(window.localStorage.getItem("utmValues"))
        let returnValue = {
            referrerId: referrerId,
            source: utmValues.source,
            medium: utmValues.medium,
            campaign: utmValues.campaign,
            term: utmValues.term,
            content: utmValues.content
        }
        if(referrerId || referrerId===""){ return returnValue }else{ return null }
    },
};

window.ReferrerTracking.init();
"use strict";

/* global _ */

window.Uxlibrary = {
    makeDropdownFilter: function (values, selectorId, onChoiceDo) {
        var defaultText = 'Velg verdi';
        if (values.length > 0) {
            defaultText = values[0].second;
        }

        var $selectedValue = $('<div class="select-filter-selected">' + defaultText + '</div>');
        var $returnValue = $('<div class="select-filter"></div>');
        var $selector = $('<select id="' + selectorId + '"></select>');
        var $displayableList = $('<div class="select-filter-items" style="display: none"></div>');
        $selector.append($('<option value=""></option>'));
        $.each(values, function (index, val) {
            $selector.append($('<option value="' + val.first + '">' + val.second + '</option>'));
            let $oneOption = $('<div>' + val.second + '</div>');
            $oneOption.click(function () {
                $selectedValue.html(val.second);
                $selector.val(val.first);
                if (onChoiceDo){
                    onChoiceDo();
                }
            });
            $displayableList.append($oneOption);
        });
        $returnValue.append($selector);
        $returnValue.append($selectedValue);
        $returnValue.append($displayableList);
        let isOpen = false;
        $returnValue.click(function () {
            if (isOpen) {
                $displayableList.hide();
                isOpen = false;
            } else {
                $displayableList.show();
                isOpen = true;
            }
        });
        return $returnValue;
    },


    makeDropdownWithSearchField: function (values, selectorId, currentValue, defaultText = 'Søk...') {
        let $selectedValue = $('<div class="select-dropdown-selected" tabindex="0">' + defaultText + '</div>');
        let $selectorInputField = $('<input class="select-dropdown-input" type="text" style="display: none" placeholder="' + defaultText + '">');
        let $returnValue = $('<div class="select-dropdown"></div>');
        let $selector = $('<select id="' + selectorId + '"></select>');
        let $displayableList = $('<div class="select-dropdown-items" placeholder="' + defaultText + '" style="display: none"></div>');
        let isOpen = false;
        $selector.append($('<option value=""></option>'));
        $.each(values, function (index, val) {
            $selector.append($('<option value="' + val.first + '">' + val.second + '</option>'));
            let $oneOption = $('<div class="select-dropdown-item-displayname" tabindex="0">' + val.second + '</div>');
            $oneOption.click(function () {
                $selectedValue.html(val.second);
                $selector.val(val.first);
            });
            $oneOption.keydown(function (event){
                if(event.code === "Enter") {
                    $selectedValue.html(val.second);
                    $selector.val(val.first);
                    isOpen = isDropDownShowing(isOpen);
                }
            });
            $displayableList.append($oneOption);
        });

        if (currentValue) {
            let selecteeditem = _.findWhere(values, {first: currentValue});
            if (selecteeditem) {
                $selectedValue.html(selecteeditem.second);
                $selector.val(selecteeditem.first);
                $selectedValue.addClass("withValue");
            }
        }


        $selectorInputField.on("input", function () {
            let filter = $selectorInputField.val().toLowerCase();
            $displayableList.find("div").each(function (index, $element) {
                if (filter === "" || $(this).text().toLowerCase().startsWith(filter)) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        });

        $returnValue.append($selector);
        $returnValue.append($selectedValue);
        $returnValue.append($selectorInputField);
        $returnValue.append($displayableList);

        $returnValue.click(function () {
            isOpen = isDropDownShowing(isOpen);
        });

        $selectedValue.keydown(function(event){
            if(event.code === "Enter"){
                isOpen = isDropDownShowing(isOpen);
            }
        });

        let isDropDownShowing = function(isOpen){
            if (isOpen) {
                $returnValue.addClass("isOpen");
                $returnValue.removeClass("isNotOpen");
                $displayableList.hide();
                $selectorInputField.hide();
                $selectedValue.show();
                return false;
            } else {
                $selectedValue.addClass("withValue");
                $returnValue.removeClass("isOpen");
                $returnValue.addClass("isNotOpen");
                $displayableList.show();
                $selectorInputField.show();
                $selectedValue.hide();
                $selectorInputField.focus();
                return true;
            }
        };

        return $returnValue;
    }
};
window.onstorage = function (event) {
    if (event.key === 'sessionStorage' && !sessionStorage.monnersessiontoken) {
        sessionStorage.monnersessiontoken = event.newValue;
    }
    if (event.key === 'getSessionStorage') {
        if (sessionStorage.monnersessiontoken) {
            localStorage.sessionStorage = sessionStorage.monnersessiontoken;
            localStorage.removeItem('sessionStorage');
        }
    }
    if (event.key === 'clearSessionStorage') {
        if (sessionStorage.monnersessiontoken) {
            localStorage.removeItem('monnersessiontoken');
            sessionStorage.removeItem('monnersessiontoken');
        }
    }
};

if (!sessionStorage.monnersessiontoken) {
    localStorage.getSessionStorage = Date.now();
}

window.ServerApi = {


    handleErrorFromServer(fromServer, doOnDisplayableError) {
        if (fromServer.errorcode && doOnDisplayableError) {
            doOnDisplayableError(fromServer.errormessage, fromServer.errorcode);
        } else {
            console.log("Error at:");
            console.trace();
            Notification.error(fromServer.errormessage);
        }
    },

    getFromServer(url, doWithReturnData, doOnDisplayableError) {
        window.ServerApi.ajax({
            url,
            data: {},
            success(fromServer) {
                if (fromServer.status === 'error') {
                    window.ServerApi.handleErrorFromServer(fromServer, doOnDisplayableError);
                } else {
                    if (fromServer.trackEvent) {
                        //MonnerTracking.track(fromServer.trackEvent.name, fromServer.trackEvent.payload);
                    }
                    doWithReturnData(fromServer);
                }
            },
            error(jqXHR, textStatus, errorThrown) {
                console.log("Error at:");
                console.trace();
                Notification.error('Teknisk feil');
            },
        });
    },

    postToServer(url, jsonToServer, onSuccsess, doOnDisplayableError, onTechnicalError) {
        window.ServerApi.ajax({
            url,
            method: 'POST',
            data: JSON.stringify(jsonToServer),
            success(fromServer) {
                if (fromServer.status === 'error') {
                    window.ServerApi.handleErrorFromServer(fromServer, doOnDisplayableError);
                } else if (onSuccsess == null) {
                    window.location.reload();
                } else {
                    onSuccsess(fromServer);
                }
            },
            error(jqXHR, textStatus, errorThrown) {
                console.log("Error at:");
                console.trace();
                Notification.error('Teknisk feil');
                if (onTechnicalError) {
                    onTechnicalError();
                }
            },
        });
    },

    ajax(settings) {
        let self = window.ServerApi;
        const settingsCopy = settings;

        const accesstoken = localStorage.getItem('monnersessiontoken') || sessionStorage.getItem('monnersessiontoken');
        if (accesstoken) {
            settingsCopy.headers = {
                monnersessiontoken: accesstoken,
            };
        }
        if (settings.contentType !== false && settings.headers) {
            settingsCopy.headers['Content-Type'] = 'application/json';
        } else if ((!settings.headers || !settings.headers['Content-Type']) && settings.contentType !== false) {
            settingsCopy.headers = {
                'Content-Type': 'application/json',
            };
        }
        return $.ajax(settingsCopy);

    },

    updateToken(data) {

        if (data.callToActionItems) {
            if(data.callToActionItems.includes('newAgreement')){
                sessionStorage.setItem('newAgreement', "1")
            } else {
                sessionStorage.removeItem("newAgreement")
            }
            if(data.callToActionItems.includes('reKYC')){
                sessionStorage.setItem('reKYC', "1")
            } else {
                sessionStorage.removeItem("reKYC")
            }
        }

        if (data !== null && typeof (data) === 'object' && data.status === 'ok') {

            window.ServerApi.removeTokens();


            sessionStorage.setItem('monnersessiontoken', data.monnersessiontoken);
            if(data.isBackofficeUser){
                // Internal users get the session token persisted to localstorage in addition to localstorage,
                // to make it possible to have multiple tabs open at the same time in Backoffice etc
                localStorage.setItem('monnersessiontoken', data.monnersessiontoken);

                // Also sharing this token via a cookie, to make it possible to use the same session in the react localhost:3000 port
                // (localStorage is bound to a specific port, while cookies are shared for same domain across all ports )
                this.setMonioSharedDevSessionToken(data.monnersessiontoken, 1);
            }

            localStorage.sessionStorage = sessionStorage.monnersessiontoken;
            localStorage.removeItem('sessionStorage');
        }
    },


    setMonioSharedDevSessionToken(value, expiry) {
        let key = "monioDevSharedSessionToken";
        let expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + '; samesite=strict; expires=' + expires.toUTCString();
    },

    removeTokens() {
        sessionStorage.removeItem('monnersessiontoken');
        localStorage.removeItem('monnersessiontoken');
        localStorage.clearSessionStorage = Date.now();
    },

    dooingServerCall: false,

    monoPostToServer(url, payload, onSuccess, onDisplayableErrorError, doOnLongRequestsToServer, doWhenLongRequestDone) {
        const self = window.ServerApi;
        if (self.dooingServerCall) {
            console.log('User is impatient');
            return;
        }

        self.dooingServerCall = true;


        let hasWaitedForALongTime = null;
        if (doOnLongRequestsToServer) {
            Common.sleepThen(500, () => {
                if (hasWaitedForALongTime == null) {
                    hasWaitedForALongTime = true;
                    doOnLongRequestsToServer();
                }
            });
        }

        function handleWaintingLongTime() {
            if (hasWaitedForALongTime) {
                doWhenLongRequestDone();
            } else {
                hasWaitedForALongTime = false;
            }
        }

        self.postToServer(url, payload,
            (fromServer) => {
                self.dooingServerCall = false;
                handleWaintingLongTime();
                onSuccess(fromServer);
            },
            (errormessage, errorcode) => {
                self.dooingServerCall = false;
                if (onDisplayableErrorError) {
                    onDisplayableErrorError(errormessage, errorcode);
                }
                handleWaintingLongTime();
            },
            () => {
                handleWaintingLongTime();
            });
    },
};

