PageSourceSearch

https://www.speidersport.no/scripts/web-defered-4.0.js?v=j1Urol5H0LJi-4d7o2ysJKmseRNh6y6XkoNtWH9DQoI1

js speidersport.no collected 2026-09-24 13:08:16 UTC 416,054 bytes, 7,581 lines download raw bytes

vendor: 4,554 bytes, lines 1-10
1/* Minification failed. Returning unminified contents.
2(1984,28): run-time error JS1004: Expected ';'
3(1984,38-39): run-time error JS1010: Expected identifier: (
4 */
5/*!
6 * Bootstrap v3.4.1 (https://getbootstrap.com/)
7 * Copyright 2011-2019 Twitter, Inc.
8 * Licensed under the MIT license
9 */
10if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");!function(t){"use strict";var e=jQuery.fn.jquery.split(" ")[0].split(".");if(e[0]<2&&e[1]<9||1==e[0]&&9==e[1]&&e[2]<1||3<e[0])throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(),function(n){"use strict";n.fn.emulateTransitionEnd=function(t){var e=!1,i=this;n(this).one("bsTransitionEnd",function(){e=!0});return setTimeout(function(){e||n(i).trigger(n.support.transition.end)},t),this},n(function(){n.support.transition=function o(){var t=document.createElement("bootstrap"),e={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var i in e)if(t.style[i]!==undefined)return{end:e[i]};return!1}(),n.support.transition&&(n.event.special.bsTransitionEnd={bindType:n.support.transition.end,delegateType:n.support.transition.end,handle:function(t){if(n(t.target).is(this))return t.handleObj.handler.apply(this,arguments)}})})}(jQuery),function(s){"use strict";var e='[data-dismiss="alert"]',a=function(t){s(t).on("click",e,this.close)};a.VERSION="3.4.1",a.TRANSITION_DURATION=150,a.prototype.close=function(t){var e=s(this),i=e.attr("data-target");i||(i=(i=e.attr("href"))&&i.replace(/.*(?=#[^\s]*$)/,"")),i="#"===i?[]:i;var o=s(document).find(i);function n(){o.detach().trigger("closed.bs.alert").remove()}t&&t.preventDefault(),o.length||(o=e.closest(".alert")),o.trigger(t=s.Event("close.bs.alert")),t.isDefaultPrevented()||(o.removeClass("in"),s.support.transition&&o.hasClass("fade")?o.one("bsTransitionEnd",n).emulateTransitionEnd(a.TRANSITION_DURATION):n())};var t=s.fn.alert;s.fn.alert=function o(i){return this.each(function(){var t=s(this),e=t.data("bs.alert");e||t.data("bs.alert",e=new a(this)),"string"==typeof i&&e[i].call(t)})},s.fn.alert.Constructor=a,s.fn.alert.noConflict=function(){return s.fn.alert=t,this},s(document).on("click.bs.alert.data-api",e,a.prototype.close)}(jQuery),function(s){"use strict";var n=function(t,e){this.$element=s(t),this.options=s.extend({},n.DEFAULTS,e),this.isLoading=!1};function i(o){return this.each(function(){var t=s(this),e=t.data("bs.button"),i="object"==typeof o&&o;e||t.data("bs.button",e=new n(this,i)),"toggle"==o?e.toggle():o&&e.setState(o)})}n.VERSION="3.4.1",n.DEFAULTS={loadingText:"loading..."},n.prototype.setState=function(t){var e="disabled",i=this.$element,o=i.is("input")?"val":"html",n=i.data();t+="Text",null==n.resetText&&i.data("resetText",i[o]()),setTimeout(s.proxy(function(){i[o](null==n[t]?this.options[t]:n[t]),"loadingText"==t?(this.isLoading=!0,i.addClass(e).attr(e,e).prop(e,!0)):this.isLoading&&(this.isLoading=!1,i.removeClass(e).removeAttr(e).prop(e,!1))},this),0)},n.prototype.toggle=function(){var t=!0,e=this.$element.closest('[data-toggle="buttons"]');if(e.length){var i=this.$element.find("input");"radio"==i.prop("type")?(i.prop("checked")&&(t=!1),e.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==i.prop("type")&&(i.prop("checked")!==this.$element.hasClass("active")&&(t=!1),this.$element.toggleClass("active")),i.prop("checked",this.$element.hasClass("active")),t&&i.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var t=s.fn.button;s.fn.button=i,s.fn.button.Constructor=n,s.fn.button.noConflict=function(){return s.fn.button=t,this},s(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(t){var e=s(t.target).closest(".btn");i.call(e,"toggle"),s(t.target).is('input[type="radio"], input[type="checkbox"]')||(t.preventDefault(),e.is("input,button")?e.trigger("focus"):e.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(t){s(t.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(t.type))})}(jQuery),function(p){"use strict";var c=function(t,e){this.$element=p(t),this.$indicators=this.$element.find(".carousel-indicators"),this.options=e,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("key
10down.bs.carousel",p.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",p.proxy(this.pause,this)).on("mouseleave.bs.carousel",p.proxy(this.cycle,this))};function r(n){return this.each(function(){var t=p(this),e=t.data("bs.carousel"),i=p.extend({},c.DEFAULTS,t.data(),"object"==typeof n&&n),o="string"==typeof n?n:i.slide;e||t.data("bs.carousel",e=new c(this,i)),"number"==typeof n?e.to(n):o?e[o]():i.interval&&e.pause().cycle()})}c.VERSION="3.4.1",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(t){if(!/input|textarea/i.test(t.target.tagName)){switch(t.which){case 37:this.prev();break;case 39:this.next();break;default:return}t.preventDefault()}},c.prototype.cycle=function(t){return t||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(p.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(t){return this.$items=t.parent().children(".item"),this.$items.index(t||this.$active)},c.prototype.getItemForDirection=function(t,e){var i=this.getItemIndex(e);if(("prev"==t&&0===i||"next"==t&&i==this.$items.length-1)&&!this.options.wrap)return e;var o=(i+("prev"==t?-1:1))%this.$items.length;return this.$items.eq(o)},c.prototype.to=function(t){var e=this,i=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(t>this.$items.length-1||t<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){e.to(t)}):i==t?this.pause().cycle():this.slide(i<t?"next":"prev",this.$items.eq(t))},c.prototype.pause=function(t){return t||(this.paused=!0),this.$element.find(".next, .prev").length&&p.support.transition&&(this.$element.trigger(p.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){if(!this.sliding)return this.slide("next")},c.prototype.prev=function(){if(!this.sliding)return this.slide("prev")},c.prototype.slide=function(t,e){var i=this.$element.find(".item.active"),o=e||this.getItemForDirection(t,i),n=this.interval,s="next"==t?"left":"right",a=this;if(o.hasClass("active"))return this.sliding=!1;var r=o[0],l=p.Event("slide.bs.carousel",{relatedTarget:r,direction:s});if(this.$element.trigger(l),!l.isDefaultPrevented()){if(this.sliding=!0,n&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var h=p(this.$indicators.children()[this.getItemIndex(o)]);h&&h.addClass("active")}var d=p.Event("slid.bs.carousel",{relatedTarget:r,direction:s});return p.support.transition&&this.$element.hasClass("slide")?(o.addClass(t),"object"==typeof o&&o.length&&o[0].offsetWidth,i.addClass(s),o.addClass(s),i.one("bsTransitionEnd",function(){o.removeClass([t,s].join(" ")).addClass("active"),i.removeClass(["active",s].join(" ")),a.sliding=!1,setTimeout(function(){a.$element.trigger(d)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(i.removeClass("active"),o.addClass("active"),this.sliding=!1,this.$element.trigger(d)),n&&this.cycle(),this}};var t=p.fn.carousel;p.fn.carousel=r,p.fn.carousel.Constructor=c,p.fn.carousel.noConflict=function(){return p.fn.carousel=t,this};var e=function(t){var e=p(this),i=e.attr("href");i&&(i=i.replace(/.*(?=#[^\s]+$)/,""));var o=e.attr("data-target")||i,n=p(document).find(o);if(n.hasClass("carousel")){var s=p.extend({},n.data(),e.data()),a=e.attr("data-slide-to");a&&(s.interval=!1),r.call(n,s),a&&n.data("bs.carousel").to(a),t.preventDefault()}};p(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),p(window).on("load",function(){p('[data-ride="carousel"]').each(function(){var t=p(this);r.call(t,t.data())})})}(jQuery),function(a){"use strict";var r=function(t,e){this.$element=a(t),this.options=a.extend({},r.DEFAULTS,e),this.$trigger=a('[data-toggle="collapse"][href="#'+t.id+'"],[data-toggle="collapse"][data-target="#'+t.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};function n(t){var e,i=t.attr("data-target")||(e=t.attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"");return a(document).find(i)}function l(o){return this.each(function(){var t=a(this),e=t.data("bs.collapse"),i=a.extend({},r.DEFAULTS,t.data(),"object"==typeof o&&o);!e&&i.toggle&&/show|hide/.test(o)&&(i.toggle=!1),e||t.data("bs.collapse",e=new r(this,i)),"string"==typeof o&&e[o]()})}r.VERSION="3.4.1",r.TRANSITION_DURATION=350,r.DEFAULTS={toggle:!0},r.prototype.dimension=function(){return this.$element.hasClass("width")?"width":"height"},r.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var t,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(t=e.data("bs.collapse"))&&t.transitioning)){var i=a.Event("show.bs.collapse");if(this.$element.trigger(i),!i.isDefaultPrevented()){e&&e.length&&(l.call(e,"hide"),t||e.data("bs.collapse",null));var o=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[o](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var n=function(){this.$element.removeClass("collapsing").addClass("collapse in")[o](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return n.call(this);
vendor: 4,207 bytes, line 10
10var s=a.camelCase(["scroll",o].join("-"));this.$element.one("bsTransitionEnd",a.proxy(n,this)).emulateTransitionEnd(r.TRANSITION_DURATION)[o](this.$element[0][s])}}}},r.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var t=a.Event("hide.bs.collapse");if(this.$element.trigger(t),!t.isDefaultPrevented()){var e=this.dimension();this.$element[e](this.$element[e]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var i=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};if(!a.support.transition)return i.call(this);this.$element[e](0).one("bsTransitionEnd",a.proxy(i,this)).emulateTransitionEnd(r.TRANSITION_DURATION)}}},r.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},r.prototype.getParent=function(){return a(document).find(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(t,e){var i=a(e);this.addAriaAndCollapsedClass(n(i),i)},this)).end()},r.prototype.addAriaAndCollapsedClass=function(t,e){var i=t.hasClass("in");t.attr("aria-expanded",i),e.toggleClass("collapsed",!i).attr("aria-expanded",i)};var t=a.fn.collapse;a.fn.collapse=l,a.fn.collapse.Constructor=r,a.fn.collapse.noConflict=function(){return a.fn.collapse=t,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(t){var e=a(this);e.attr("data-target")||t.preventDefault();var i=n(e),o=i.data("bs.collapse")?"toggle":e.data();l.call(i,o)})}(jQuery),function(a){"use strict";var r='[data-toggle="dropdown"]',o=function(t){a(t).on("click.bs.dropdown",this.toggle)};function l(t){var e=t.attr("data-target");e||(e=(e=t.attr("href"))&&/#[A-Za-z]/.test(e)&&e.replace(/.*(?=#[^\s]*$)/,""));var i="#"!==e?a(document).find(e):null;return i&&i.length?i:t.parent()}function s(o){o&&3===o.which||(a(".dropdown-backdrop").remove(),a(r).each(function(){var t=a(this),e=l(t),i={relatedTarget:this};e.hasClass("open")&&(o&&"click"==o.type&&/input|textarea/i.test(o.target.tagName)&&a.contains(e[0],o.target)||(e.trigger(o=a.Event("hide.bs.dropdown",i)),o.isDefaultPrevented()||(t.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",i)))))}))}o.VERSION="3.4.1",o.prototype.toggle=function(t){var e=a(this);if(!e.is(".disabled, :disabled")){var i=l(e),o=i.hasClass("open");if(s(),!o){"ontouchstart"in document.documentElement&&!i.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",s);var n={relatedTarget:this};if(i.trigger(t=a.Event("show.bs.dropdown",n)),t.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),i.toggleClass("open").trigger(a.Event("shown.bs.dropdown",n))}return!1}},o.prototype.keydown=function(t){if(/(38|40|27|32)/.test(t.which)&&!/input|textarea/i.test(t.target.tagName)){var e=a(this);if(t.preventDefault(),t.stopPropagation(),!e.is(".disabled, :disabled")){var i=l(e),o=i.hasClass("open");if(!o&&27!=t.which||o&&27==t.which)return 27==t.which&&i.find(r).trigger("focus"),e.trigger("click");var n=i.find(".dropdown-menu li:not(.disabled):visible a");if(n.length){var s=n.index(t.target);38==t.which&&0<s&&s--,40==t.which&&s<n.length-1&&s++,~s||(s=0),n.eq(s).trigger("focus")}}}};var t=a.fn.dropdown;a.fn.dropdown=function e(i){return this.each(function(){var t=a(this),e=t.data("bs.dropdown");e||t.data("bs.dropdown",e=new o(this)),"string"==typeof i&&e[i].call(t)})},a.fn.dropdown.Constructor=o,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=t,this},a(document).on("click.bs.dropdown.data-api",s).on("click.bs.dropdown.data-api",".dropdown form",function(t){t.stopPropagation()}).on("click.bs.dropdown.data-api",r,o.prototype.toggle).on("keydown.bs.dropdown.data-api",r,o.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",o.prototype.keydown)}(jQuery),function(a){"use strict";var s=function(t,e){this.options=e,this.$body=a(document.body),this.$element=a(t),this.$dialog=this.$element.find(".modal
10-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.fixedContent=".navbar-fixed-top, .navbar-fixed-bottom",this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};function r(o,n){return this.each(function(){var t=a(this),e=t.data("bs.modal"),i=a.extend({},s.DEFAULTS,t.data(),"object"==typeof o&&o);e||t.data("bs.modal",e=new s(this,i)),"string"==typeof o?e[o](n):i.show&&e.show(n)})}s.VERSION="3.4.1",s.TRANSITION_DURATION=300,s.BACKDROP_TRANSITION_DURATION=150,s.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},s.prototype.toggle=function(t){return this.isShown?this.hide():this.show(t)},s.prototype.show=function(i){var o=this,t=a.Event("show.bs.modal",{relatedTarget:i});this.$element.trigger(t),this.isShown||t.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){o.$element.one("mouseup.dismiss.bs.modal",function(t){a(t.target).is(o.$element)&&(o.ignoreBackdropClick=!0)})}),this.backdrop(function(){var t=a.support.transition&&o.$element.hasClass("fade");o.$element.parent().length||o.$element.appendTo(o.$body),o.$element.show().scrollTop(0),o.adjustDialog(),t&&o.$element[0].offsetWidth,o.$element.addClass("in"),o.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:i});t?o.$dialog.one("bsTransitionEnd",function(){o.$element.trigger("focus").trigger(e)}).emulateTransitionEnd(s.TRANSITION_DURATION):o.$element.trigger("focus").trigger(e)}))},s.prototype.hide=function(t){t&&t.preventDefault(),t=a.Event("hide.bs.modal"),this.$element.trigger(t),this.isShown&&!t.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(s.TRANSITION_DURATION):this.hideModal())},s.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(t){document===t.target||this.$element[0]===t.target||this.$element.has(t.target).length||this.$element.trigger("focus")},this))},s.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(t){27==t.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},s.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},s.prototype.hideModal=function(){var t=this;this.$element.hide(),this.backdrop(function(){t.$body.removeClass("modal-open"),t.resetAdjustments(),t.resetScrollbar(),t.$element.trigger("hidden.bs.modal")})},s.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},s.prototype.backdrop=function(t){var e=this,i=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var o=a.support.transition&&i;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+i).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(t){this.ignoreBackdropClick?this.ignoreBackdropClick=!1:t.target===t.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide())},this)),o&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!t)return;o?this.$backdrop.one("bsTransitionEnd",t).emulateTransitionEnd(s.BACKDROP_TRANSITION_DURATION):t()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var n=function(){e.removeBackdrop(),t&&t()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",n).emulateTransitionEnd(s.BACKDROP_TRANSITION_DURATION):n()}else t&&t()},s.prototype.handleUpdate=function(){this.adjustDialog()},s.prototype.adjustDialog=function(){var t=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&t?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!t?this.scrollbarWidth:""})},s.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},s.prototype.checkScrollbar=function(){var t=window.innerWidth;if(!t){var e=document.documentElement.getBoundingClientRect();t=e.right-Math.abs(e.left)}this.bodyIsOverflowing=document.body.clientWidth<t,this.scrollbarWidth=this.measureScrollbar()},s.prototype.setScrollbar=function(){var t=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"";var n=this.scrollbarWidth;this.bodyIsOverflowing&&(this.$body.css("padding-right",t+n),a(this.fixedContent).each(function(t,e){var i=e.style.paddingRight,o=a(e).css("padding-right");a(e).data("padding-right",i).css("padding-right",parseFloat(o)+n+"px")}))},s.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad),a(this.fixedContent).each(function(t,e){var i=a(e).data("padding-right");a(e).removeData("padding-right"),e.style.paddingRight=i||""})},s.prototype.measureScrollbar=function(){var t=document.createElement("div");t.className="modal-scrollbar-measure",this.$body.append(t);var e=t.offsetWidth-t.clientWidth;return this.$body[0].removeChild(t),e};var t=a.fn.modal;a.fn.modal=r,a.fn.modal.Constructor=s,a.fn.modal.noConflict=function(){return a.fn.modal=t,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(t){var e=a(this),i=e.attr("href"),o=e.attr("data-target")||i&&i.replace(/.*(?=#[^\s]+$)/,""),n=a(document).find(o),s=n.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(i)&&i},n.data(),e.data());e.is("a")&&t.preventDefault(),n.one("show.bs.modal",function(t){t.isDefaultPrevented()||n.one("hidden.bs.modal",function(){e.is(":visible")&&e.trigger("focus")})}),r.call(n,s,this)})}(jQuery),function(g){"use strict";var o=["sanitize","whiteList","sanitizeFn"],a=["background","cite","href","itemtype","longdesc","poster","src","xlink:href"],t={"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],div:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},r=/^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi,l=/^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i;function u(t,e){var i=t.nodeName.toLowerCase();if(-1!==g.inArray(i,e))return-1===g.inArray(i,a)||Boolean(t.nodeValue.match(r)||t.nodeValue.match(l));for(var o=g(e).filter(function(t,e){return e instanceof RegExp}),n=0,s=o.length;n<s;
vendor: 16,510 bytes, line 10
10n++)if(i.match(o[n]))return!0;return!1}function n(t,e,i){if(0===t.length)return t;if(i&&"function"==typeof i)return i(t);if(!document.implementation||!document.implementation.createHTMLDocument)return t;var o=document.implementation.createHTMLDocument("sanitization");o.body.innerHTML=t;for(var n=g.map(e,function(t,e){return e}),s=g(o.body).find("*"),a=0,r=s.length;a<r;a++){var l=s[a],h=l.nodeName.toLowerCase();if(-1!==g.inArray(h,n))for(var d=g.map(l.attributes,function(t){return t}),p=[].concat(e["*"]||[],e[h]||[]),c=0,f=d.length;c<f;c++)u(d[c],p)||l.removeAttribute(d[c].nodeName);else l.parentNode.removeChild(l)}return o.body.innerHTML}var m=function(t,e){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",t,e)};m.VERSION="3.4.1",m.TRANSITION_DURATION=150,m.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0},sanitize:!0,sanitizeFn:null,whiteList:t},m.prototype.init=function(t,e,i){if(this.enabled=!0,this.type=t,this.$element=g(e),this.options=this.getOptions(i),this.$viewport=this.options.viewport&&g(document).find(g.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var o=this.options.trigger.split(" "),n=o.length;n--;){var s=o[n];if("click"==s)this.$element.on("click."+this.type,this.options.selector,g.proxy(this.toggle,this));else if("manual"!=s){var a="hover"==s?"mouseenter":"focusin",r="hover"==s?"mouseleave":"focusout";this.$element.on(a+"."+this.type,this.options.selector,g.proxy(this.enter,this)),this.$element.on(r+"."+this.type,this.options.selector,g.proxy(this.leave,this))}}this.options.selector?this._options=g.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},m.prototype.getDefaults=function(){return m.DEFAULTS},m.prototype.getOptions=function(t){var e=this.$element.data();for(var i in e)e.hasOwnProperty(i)&&-1!==g.inArray(i,o)&&delete e[i];return(t=g.extend({},this.getDefaults(),e,t)).delay&&"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),t.sanitize&&(t.template=n(t.template,t.whiteList,t.sanitizeFn)),t},m.prototype.getDelegateOptions=function(){var i={},o=this.getDefaults();return this._options&&g.each(this._options,function(t,e){o[t]!=e&&(i[t]=e)}),i},m.prototype.enter=function(t){var e=t instanceof this.constructor?t:g(t.currentTarget).data("bs."+this.type);if(e||(e=new this.constructor(t.currentTarget,this.getDelegateOptions()),g(t.currentTarget).data("bs."+this.type,e)),t instanceof g.Event&&(e.inState["focusin"==t.type?"focus":"hover"]=!0),e.tip().hasClass("in")||"in"==e.hoverState)e.hoverState="in";else{if(clearTimeout(e.timeout),e.hoverState="in",!e.options.delay||!e.options.delay.show)return e.show();e.timeout=setTimeout(function(){"in"==e.hoverState&&e.show()},e.options.delay.show)}},m.prototype.isInStateTrue=function(){for(var t in this.inState)if(this.inState[t])return!0;return!1},m.prototype.leave=function(t){var e=t instanceof this.constructor?t:g(t.currentTarget).data("bs."+this.type);if(e||(e=new this.constructor(t.currentTarget,this.getDelegateOptions()),g(t.currentTarget).data("bs."+this.type,e)),t instanceof g.Event&&(e.inState["focusout"==t.type?"focus":"hover"]=!1),!e.isInStateTrue()){if(clearTimeout(e.timeout),e.hoverState="out",!e.options.delay||!e.options.delay.hide)return e.hide();e.timeout=setTimeout(function(){"out"==e.hoverState&&e.hide()},e.options.delay.hide)}},m.prototype.show=function(){var t=g.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(t);var e=g.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(t.isDefaultPrevented()||!e)return;var i=this,o=this.tip(),n=this.getUID(this.type);this.setContent(),o.attr("id",n),this.$element.attr("aria-describedby",n),this.options.animation&&o.addClass("fade");var s="function"==typeof this.options.placement?this.options.placement.call(this,o[0],this.$element[0]):this.options.placement,a=/\s?auto?\s?/i,r=a.test(s);r&&(s=s.replace(a,"")||"top"),o.detach().css({top:0,left:0,display:"block"}).addClass(s).data("bs."+this.type,this),this.options.container?o.appendTo(g(document).find(this.options.container)):o.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var l=this.getPosition(),h=o[0].offsetWidth,d=o[0].offsetHeight;if(r){var p=s,c=this.getPosition(this.$viewport);s="bottom"==s&&l.bottom+d>c.bottom?"top":"top"==s&&l.top-d<c.top?"bottom":"right"==s&&l.right+h>c.width?"left":"left"==s&&l.left-h<c.left?"right":s,o.removeClass(p).addClass(s)}var f=this.getCalculatedOffset(s,l,h,d);this.applyPlacement(f,s);var u=function(){var t=i.hoverState;i.$element.trigger("shown.bs."+i.type),i.hoverState=null,"out"==t&&i.leave(i)};g.support.transition&&this.$tip.hasClass("fade")?o.one("bsTransitionEnd",u).emulateTransitionEnd(m.TRANSITION_DURATION):u()}},m.prototype.applyPlacement=function(t,e){var i=this.tip(),o=i[0].offsetWidth,n=i[0].offsetHeight,s=parseInt(i.css("margin-top"),10),a=parseInt(i.css("margin-left"),10);isNaN(s)&&(s=0),isNaN(a)&&(a=0),t.top+=s,t.left+=a,g.offset.setOffset(i[0],g.extend({using:function(t){i.css({top:Math.round(t.top),left:Math.round(t.left)})}},t),0),i.addClass("in");var r=i[0].offsetWidth,l=i[0].offsetHeight;"top"==e&&l!=n&&(t.top=t.top+n-l);var h=this.getViewportAdjustedDelta(e,t,r,l);h.left?t.left+=h.left:t.top+=h.top;var d=/top|bottom/.test(e),p=d?2*h.left-o+r:2*h.top-n+l,c=d?"offsetWidth":"offsetHeight";i.offset(t),this.replaceArrow(p,i[0][c],d)},m.prototype.replaceArrow=function(t,e,i){this.arrow().css(i?"left":"top",50*(1-t/e)+"%").css(i?"top":"left","")},m.prototype.setContent=function(){var t=this.tip(),e=this.getTitle();this.options.html?(this.options.sanitize&&(e=n(e,this.options.whiteList,this.options.sanitizeFn)),t.find(".tooltip-inner").html(e)):t.find(".tooltip-inner").text(e),t.removeClass("fade in top bottom left right")},m.prototype.hide=function(t){var e=this,i=g(this.$tip),o=g.Event("hide.bs."+this.type);function n(){"in"!=e.hoverState&&i.detach(),e.$element&&e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),t&&t()}if(this.$element.trigger(o),!o.isDefaultPrevented())return i.removeClass("in"),g.support.transition&&i.hasClass("fade")?i.one("bsTransitionEnd",n).emulateTransitionEnd(m.TRANSITION_DURATION):n(),this.hoverState=null,this},m.prototype.fixTitle=function(){var t=this.$element;(t.attr("title")||"string"!=typeof t.attr("data-original-title"))&&t.attr("data-original-title",t.attr("title")||"").attr("title","")},m.prototype.hasContent=function(){return this.getTitle()},m.prototype.getPosition=function(t){var e=(t=t||this.$element)[0],i="BODY"==e.tagName,o=e.getBoundingClientRect();null==o.width&&(o=g.extend({},o,{width:o.right-o.left,height:o.bottom-o.top}));var n=window.SVGElement&&e instanceof window.SVGElement,s=i?{top:0,left:0}:n?null:t.offset(),a={scroll:i?document.documentElement.scrollTop||document.body.scrollTop:t.scrollTop()},r=i?{width:g(window).width(),height:g(window).height()}:null;return g.extend({},o,a,r,s)},m.prototype.getCalculatedOffset=function(t,e,i,o){return"bottom"==t?{top:e.top+e.height,left:e.left+e.width/2-i/2}:"top"==t?{top:e.top-o,left:e.left+e.width/2-i/2}:"left"==t?{top:e.top+e.height/2-o/2,left:e.left-i}:{top:e.top+e.height/2-o/2,left:e.left+e.width}},m.prototype.getViewportAdjustedDelta=function(t,e,i,o){var n={top:0,left:0};if(!this.$viewport)return n;var s=this.options.viewport&&this.options.viewport.padding||0,a=this.getPosition(this.$viewport);if(/right|left/.test(t)){var r=e.top-s-a.scroll,l=e.top+s-a.scroll+o;r<a.top?n.top=a.top-r:l>a.top+a.height&&(n.top=a.top+a.height-l)}else{var h=e.left-s,d=e.left+s+i;h<a.left?n.left=a.left-h:d>a.right&&(n.left=a.left+a.width-d)}return n},m.prototype.getTitle=function(){var t=this.$element,e=this.options;return t.attr("data-original-title")||("function"==typeof e.title?e.title.call(t[0]):e.title)},m.prototype.getUID=function(t){for(;t+=~~(1e6*Math.random()),document.getElementById(t););return t},m.prototype.tip=function(){if(!this.$tip&&(this.$tip=g(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},m.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},m.prototype.enable=function(){this.enabled=!0},m.prototype.disable=function(){this.enabled=!1},m.prototype.toggleEnabled=function(){this.enabled=!this.enabled},m.prototype.toggle=function(t){var e=this;t&&((e=g(t.currentTarget).data("bs."+this.type))||(e=new this.constructor(t.currentTarget,this.getDelegateOptions()),g(t.currentTarget).data("bs."+this.type,e))),t?(e.inState.click=!e.inState.click,e.isInStateTrue()?e.enter(e):e.leave(e)):e.tip().hasClass("in")?e.leave(e):e.enter(e)},m.prototype.destroy=function(){var t=this;clearTimeout(this.timeout),this.hide(function(){t.$element.off("."+t.type).removeData("bs."+t.type),t.$tip&&t.$tip.detach(),t.$tip=null,t.$arrow=null,t.$viewport=null,t.$element=null})},m.prototype.sanitizeHtml=function(t){return n(t,this.options.whiteList,this.options.sanitizeFn)};var e=g.fn.tooltip;g.fn.tooltip=function i(o){return this.each(function(){var t=g(this),e=t.data("bs.tooltip"),i="object"==typeof o&&o;!e&&/destroy|hide/.test(o)||(e||t.data("bs.tooltip",e=new m(this,i)),"string"==typeof o&&e[o]())})},g.fn.tooltip.Constructor=m,g.fn.tooltip.noConflict=function(){return g.fn.tooltip=e,this}}(jQuery),function(n){"use strict";var s=function(t,e){this.init("popover",t,e)};if(!n.fn.tooltip)throw new Error("Popover requires tooltip.js");s.VERSION="3.4.1",s.DEFAULTS=n.extend({},n.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),((s.prototype=n.extend({},n.fn.tooltip.Constructor.prototype)).constructor=s).prototype.getDefaults=function(){return s.DEFAULTS},s.prototype.setContent=function(){var t=this.tip(),e=this.getTitle(),i=this.getContent();if(this.options.html){var o=typeof i;this.options.sanitize&&(e=this.sanitizeHtml(e),"string"===o&&(i=this.sanitizeHtml(i))),t.find(".popover-title").html(e),t.find(".popover-content").children().detach().end()["string"===o?"html":"append"](i)}else t.find(".popover-title").text(e),t.find(".popover-content").children().detach().end().text(i);t.removeClass("fade top bottom left right in"),t.find(".popover-title").html()||t.find(".popover-title").hide()},s.prototype.hasContent=function(){return this.getTitle()||this.getContent()},s.prototype.getContent=function(){var t=this.$element,e=this.options;return t.attr("data-content")||("function"==typeof e.content?e.content.call(t[0]):e.content)},s.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var t=n.fn.popover;n.fn.popover=function e(o){return this.each(function(){var t=n(this),e=t.data("bs.popover"),i="object"==typeof o&&o;!e&&/destroy|hide/.test(o)||(e||t.data("bs.popover",e=new s(this,i)),"string"==typeof o&&e[o]())})},n.fn.popover.Constructor=s,n.fn.popover.noConflict=function(){return n.fn.popover=t,this}}(jQuery),function(s){"use strict";function n(t,e){this.$body=s(document.body),this.$scrollElement=s(t).is(document.body)?s(window):s(t),this.options=s.extend({},n.DEFAULTS,e),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",s.proxy(this.process,this)),this.refresh(),this.process()}function e(o){return this.each(function(){var t=s(this),e=t.data("bs.scrollspy"),i="object"==typeof o&&o;e||t.data("bs.scrollspy",e=new n(this,i)),"string"==typeof o&&e[o]()})}n.VERSION="3.4.1",n.DEFAULTS={offset:10},n.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},n.prototype.refresh=function(){var t=this,o="offset",n=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),s.isWindow(this.$scrollElement[0])||(o="position",n=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var t=s(this),e=t.data("target")||t.attr("href"),i=/^#./.test(e)&&s(e);return i&&i.length&&i.is(":visible")&&[[i[o]().top+n,e]]||null}).sort(function(t,e){return t[0]-e[0]}).each(function(){t.offsets.push(this[0]),t.targets.push(this[1])})},n.prototype.process=function(){var t,e=this.$scrollElement.scrollTop()+this.options.offset,i=this.getScrollHeight(),o=this.options.offset+i-this.$scrollElement.height(),n=this.offsets,s=this.targets,a=this.activeTarget;if(this.scrollHeight!=i&&this.refresh(),o<=e)return a!=(t=s[s.length-1])&&this.activate(t);if(a&&e<n[0])return this.activeTarget=null,this.clear();for(t=n.length;t--;)a!=s[t]&&e>=n[t]&&(n[t+1]===undefined||e<n[t+1])&&this.activate(s[t])},n.prototype.activate=function(t){this.activeTarget=t,this.clear();var e=this.selector+'[data-target="'+t+'"],'+this.selector+'[href="'+t+'"]',i=s(e).parents("li").addClass("active");i.parent(".dropdown-menu").length&&(i=i.closest("li.dropdown").addClass("active")),i.trigger("activate.bs.scrollspy")},n.prototype.clear=function(){s(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var t=s.fn.scrollspy;s.fn.scrollspy=e,s.fn.scrollspy.Constructor=n,s.fn.scrollspy.noConflict=function(){return s.fn.scrollspy=t,this},s(window).on("load.bs.scrollspy.data-api",function(){s('[data-spy="scroll"]').each(function(){var t=s(this);e.call(t,t.data())})})}(jQuery),function(r){"use strict";var a=function(t){this.element=r(t)};function e(i){return this.each(function(){var t=r(this),e=t.data("bs.tab");e||t.data("bs.tab",e=new a(this)),"string"==typeof i&&e[i]()})}a.VERSION="3.4.1",a.TRANSITION_DURATION=150,a.prototype.show=function(){var t=this.element,e=t.closest("ul:not(.dropdown-menu)"),i=t.data("target");if(i||(i=(i=t.attr("href"))&&i.replace(/.*(?=#[^\s]*$)/,"")),!t.parent("li").hasClass("active")){var o=e.find(".active:last a"),n=r.Event("hide.bs.tab",{relatedTarget:t[0]}),s=r.Event("show.bs.tab",{relatedTarget:o[0]});if(o.trigger(n),t.trigger(s),!s.isDefaultPrevented()&&!n.isDefaultPrevented()){var a=r(document).find(i);this.activate(t.closest("li"),e),this.activate(a,a.parent(),function(){o.trigger({type:"hidden.bs.tab",relatedTarget:t[0]}),t.trigger({type:"shown.bs.tab",relatedTarget:o[0]})})}}},a.prototype.activate=function(t,e,i){var o=e.find("> .active"),n=i&&r.support.transition&&(o.length&&o.hasClass("fade")||!!e.find("> .fade").length);function s(){o.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),t.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),n?(t[0].offsetWidth,t.addClass("in")):t.removeClass("fade"),t.parent(".dropdown-menu").length&&t.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),i&&i()}o.length&&n?o.one("bsTransitionEnd",s).emulateTransitionEnd(a.TRANSITION_DURATION):s(),o.removeClass("in")};var t=r.fn.tab;r.fn.tab=e,r.fn.tab.Constructor=a,r.fn.tab.noConflict=function(){return r.fn.tab=t,this};var i=function(t){t.preventDefault(),e.call(r(this),"show")};r(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',i).on("click.bs.tab.data-api",'[data-toggle="pill"]',i)}(jQuery),function(l){"use strict";var h=function(t,e){this.options=l.extend({},h.DEFAULTS,e);var i=this.options.target===h.DEFAULTS.target?l(this.options.target):l(document).find(this.options.target);this.$target=i.on("scroll.bs.affix.data-api",l.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",l.proxy(this.checkPositionWithEventLoop,this)),this.$element=l(t),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};function i(o){return this.each(function(){var t=l(this),e=t.data("bs.affix"),i="object"==typeof o&&o;
10e||t.data("bs.affix",e=new h(this,i)),"string"==typeof o&&e[o]()})}h.VERSION="3.4.1",h.RESET="affix affix-top affix-bottom",h.DEFAULTS={offset:0,target:window},h.prototype.getState=function(t,e,i,o){var n=this.$target.scrollTop(),s=this.$element.offset(),a=this.$target.height();if(null!=i&&"top"==this.affixed)return n<i&&"top";if("bottom"==this.affixed)return null!=i?!(n+this.unpin<=s.top)&&"bottom":!(n+a<=t-o)&&"bottom";var r=null==this.affixed,l=r?n:s.top;return null!=i&&n<=i?"top":null!=o&&t-o<=l+(r?a:e)&&"bottom"},h.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(h.RESET).addClass("affix");var t=this.$target.scrollTop(),e=this.$element.offset();return this.pinnedOffset=e.top-t},h.prototype.checkPositionWithEventLoop=function(){setTimeout(l.proxy(this.checkPosition,this),1)},h.prototype.checkPosition=function(){if(this.$element.is(":visible")){var t=this.$element.height(),e=this.options.offset,i=e.top,o=e.bottom,n=Math.max(l(document).height(),l(document.body).height());"object"!=typeof e&&(o=i=e),"function"==typeof i&&(i=e.top(this.$element)),"function"==typeof o&&(o=e.bottom(this.$element));var s=this.getState(n,t,i,o);if(this.affixed!=s){null!=this.unpin&&this.$element.css("top","");var a="affix"+(s?"-"+s:""),r=l.Event(a+".bs.affix");if(this.$element.trigger(r),r.isDefaultPrevented())return;this.affixed=s,this.unpin="bottom"==s?this.getPinnedOffset():null,this.$element.removeClass(h.RESET).addClass(a).trigger(a.replace("affix","affixed")+".bs.affix")}"bottom"==s&&this.$element.offset({top:n-t-o})}};var t=l.fn.affix;l.fn.affix=i,l.fn.affix.Constructor=h,l.fn.affix.noConflict=function(){return l.fn.affix=t,this},l(window).on("load",function(){l('[data-spy="affix"]').each(function(){var t=l(this),e=t.data();e.offset=e.offset||{},null!=e.offsetBottom&&(e.offset.bottom=e.offsetBottom),null!=e.offsetTop&&(e.offset.top=e.offsetTop),i.call(t,e)})})}(jQuery);;
11/* qTip2 v2.2.1 | Plugins: tips modal viewport svg imagemap ie6 | Styles: core basic css3 | qtip2.com | Licensed MIT | Sat Sep 06 2014 23:12:07 */
12
13!function(a,b,c){!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery"],a):jQuery&&!jQuery.fn.qtip&&a(jQuery)}(function(d){"use strict";function e(a,b,c,e){this.id=c,this.target=a,this.tooltip=F,this.elements={target:a},this._id=S+"-"+c,this.timers={img:{}},this.options=b,this.plugins={},this.cache={event:{},target:d(),disabled:E,attr:e,onTooltip:E,lastClass:""},this.rendered=this.destroyed=this.disabled=this.waiting=this.hiddenDuringWait=this.positioning=this.triggering=E}function f(a){return a===F||"object"!==d.type(a)}function g(a){return!(d.isFunction(a)||a&&a.attr||a.length||"object"===d.type(a)&&(a.jquery||a.then))}function h(a){var b,c,e,h;return f(a)?E:(f(a.metadata)&&(a.metadata={type:a.metadata}),"content"in a&&(b=a.content,f(b)||b.jquery||b.done?b=a.content={text:c=g(b)?E:b}:c=b.text,"ajax"in b&&(e=b.ajax,h=e&&e.once!==E,delete b.ajax,b.text=function(a,b){var f=c||d(this).attr(b.options.content.attr)||"Loading...",g=d.ajax(d.extend({},e,{context:b})).then(e.success,F,e.error).then(function(a){return a&&h&&b.set("content.text",a),a},function(a,c,d){b.destroyed||0===a.status||b.set("content.text",c+": "+d)});return h?f:(b.set("content.text",f),g)}),"title"in b&&(d.isPlainObject(b.title)&&(b.button=b.title.button,b.title=b.title.text),g(b.title||E)&&(b.title=E))),"position"in a&&f(a.position)&&(a.position={my:a.position,at:a.position}),"show"in a&&f(a.show)&&(a.show=a.show.jquery?{target:a.show}:a.show===D?{ready:D}:{event:a.show}),"hide"in a&&f(a.hide)&&(a.hide=a.hide.jquery?{target:a.hide}:{event:a.hide}),"style"in a&&f(a.style)&&(a.style={classes:a.style}),d.each(R,function(){this.sanitize&&this.sanitize(a)}),a)}function i(a,b){for(var c,d=0,e=a,f=b.split(".");e=e[f[d++]];)d<f.length&&(c=e);return[c||a,f.pop()]}function j(a,b){var c,d,e;for(c in this.checks)for(d in this.checks[c])(e=new RegExp(d,"i").exec(a))&&(b.push(e),("builtin"===c||this.plugins[c])&&this.checks[c][d].apply(this.plugins[c]||this,b))}function k(a){return V.concat("").join(a?"-"+a+" ":" ")}function l(a,b){return b>0?setTimeout(d.proxy(a,this),b):void a.call(this)}function m(a){this.tooltip.hasClass(ab)||(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this.timers.show=l.call(this,function(){this.toggle(D,a)},this.options.show.delay))}function n(a){if(!this.tooltip.hasClass(ab)&&!this.destroyed){var b=d(a.relatedTarget),c=b.closest(W)[0]===this.tooltip[0],e=b[0]===this.options.show.target[0];if(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this!==b[0]&&"mouse"===this.options.position.target&&c||this.options.hide.fixed&&/mouse(out|leave|move)/.test(a.type)&&(c||e))try{a.preventDefault(),a.stopImmediatePropagation()}catch(f){}else this.timers.hide=l.call(this,function(){this.toggle(E,a)},this.options.hide.delay,this)}}function o(a){!this.tooltip.hasClass(ab)&&this.options.hide.inactive&&(clearTimeout(this.timers.inactive),this.timers.inactive=l.call(this,function(){this.hide(a)},this.options.hide.inactive))}function p(a){this.rendered&&this.tooltip[0].offsetWidth>0&&this.reposition(a)}function q(a,c,e){d(b.body).delegate(a,(c.split?c:c.join("."+S+" "))+"."+S,function(){var a=y.api[d.attr(this,U)];a&&!a.disabled&&e.apply(a,arguments)})}function r(a,c,f){var g,i,j,k,l,m=d(b.body),n=a[0]===b?m:a,o=a.metadata?a.metadata(f.metadata):F,p="html5"===f.metadata.type&&o?o[f.metadata.name]:F,q=a.data(f.metadata.name||"qtipopts");try{q="string"==typeof q?d.parseJSON(q):q}catch(r){}if(k=d.extend(D,{},y.defaults,f,"object"==typeof q?h(q):F,h(p||o)),i=k.position,k.id=c,"boolean"==typeof k.content.text){if(j=a.attr(k.content.attr),k.content.attr===E||!j)return E;k.content.text=j}if(i.container.length||(i.container=m),i.target===E&&(i.target=n),k.show.target===E&&(k.show.target=n),k.show.solo===D&&(k.show.solo=i.container.closest("body")),k.hide.target===E&&(k.hide.target=n),k.position.viewport===D&&(k.position.viewport=i.container),i.c
vendor: 4,526 bytes, line 13
13ontainer=i.container.eq(0),i.at=new A(i.at,D),i.my=new A(i.my),a.data(S))if(k.overwrite)a.qtip("destroy",!0);else if(k.overwrite===E)return E;return a.attr(T,c),k.suppress&&(l=a.attr("title"))&&a.removeAttr("title").attr(cb,l).attr("title",""),g=new e(a,k,c,!!j),a.data(S,g),g}function s(a){return a.charAt(0).toUpperCase()+a.slice(1)}function t(a,b){var d,e,f=b.charAt(0).toUpperCase()+b.slice(1),g=(b+" "+rb.join(f+" ")+f).split(" "),h=0;if(qb[b])return a.css(qb[b]);for(;d=g[h++];)if((e=a.css(d))!==c)return qb[b]=d,e}function u(a,b){return Math.ceil(parseFloat(t(a,b)))}function v(a,b){this._ns="tip",this.options=b,this.offset=b.offset,this.size=[b.width,b.height],this.init(this.qtip=a)}function w(a,b){this.options=b,this._ns="-modal",this.init(this.qtip=a)}function x(a){this._ns="ie6",this.init(this.qtip=a)}var y,z,A,B,C,D=!0,E=!1,F=null,G="x",H="y",I="width",J="height",K="top",L="left",M="bottom",N="right",O="center",P="flipinvert",Q="shift",R={},S="qtip",T="data-hasqtip",U="data-qtip-id",V=["ui-widget","ui-tooltip"],W="."+S,X="click dblclick mousedown mouseup mousemove mouseleave mouseenter".split(" "),Y=S+"-fixed",Z=S+"-default",$=S+"-focus",_=S+"-hover",ab=S+"-disabled",bb="_replacedByqTip",cb="oldtitle",db={ie:function(){for(var a=4,c=b.createElement("div");(c.innerHTML="<!--[if gt IE "+a+"]><i></i><![endif]-->")&&c.getElementsByTagName("i")[0];a+=1);return a>4?a:0/0}(),iOS:parseFloat((""+(/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent)||[0,""])[1]).replace("undefined","3_2").replace("_",".").replace("_",""))||E};z=e.prototype,z._when=function(a){return d.when.apply(d,a)},z.render=function(a){if(this.rendered||this.destroyed)return this;var b,c=this,e=this.options,f=this.cache,g=this.elements,h=e.content.text,i=e.content.title,j=e.content.button,k=e.position,l=("."+this._id+" ",[]);return d.attr(this.target[0],"aria-describedby",this._id),f.posClass=this._createPosClass((this.position={my:k.my,at:k.at}).my),this.tooltip=g.tooltip=b=d("<div/>",{id:this._id,"class":[S,Z,e.style.classes,f.posClass].join(" "),width:e.style.width||"",height:e.style.height||"",tracking:"mouse"===k.target&&k.adjust.mouse,role:"alert","aria-live":"polite","aria-atomic":E,"aria-describedby":this._id+"-content","aria-hidden":D}).toggleClass(ab,this.disabled).attr(U,this.id).data(S,this).appendTo(k.container).append(g.content=d("<div />",{"class":S+"-content",id:this._id+"-content","aria-atomic":D})),this.rendered=-1,this.positioning=D,i&&(this._createTitle(),d.isFunction(i)||l.push(this._updateTitle(i,E))),j&&this._createButton(),d.isFunction(h)||l.push(this._updateContent(h,E)),this.rendered=D,this._setWidget(),d.each(R,function(a){var b;"render"===this.initialize&&(b=this(c))&&(c.plugins[a]=b)}),this._unassignEvents(),this._assignEvents(),this._when(l).then(function(){c._trigger("render"),c.positioning=E,c.hiddenDuringWait||!e.show.ready&&!a||c.toggle(D,f.event,E),c.hiddenDuringWait=E}),y.api[this.id]=this,this},z.destroy=function(a){function b(){if(!this.destroyed){this.destroyed=D;var a,b=this.target,c=b.attr(cb);this.rendered&&this.tooltip.stop(1,0).find("*").remove().end().remove(),d.each(this.plugins,function(){this.destroy&&this.destroy()});for(a in this.timers)clearTimeout(this.timers[a]);b.removeData(S).removeAttr(U).removeAttr(T).removeAttr("aria-describedby"),this.options.suppress&&c&&b.attr("title",c).removeAttr(cb),this._unassignEvents(),this.options=this.elements=this.cache=this.timers=this.plugins=this.mouse=F,delete y.api[this.id]}}return this.destroyed?this.target:(a===D&&"hide"!==this.triggering||!this.rendered?b.call(this):(this.tooltip.one("tooltiphidden",d.proxy(b,this)),!this.triggering&&this.hide()),this.target)},B=z.checks={builtin:{"^id$":function(a,b,c,e){var f=c===D?y.nextid:c,g=S+"-"+f;f!==E&&f.length>0&&!d("#"+g).length?(this._id=g,this.rendered&&(this.tooltip[0].id=this._id,this.elements.content[0].id=this._id+"-content",this.elements.title[0].id=this._id+"-title")):a[b]=e},"^prerender":function(a,b,c){c&&!this.rendered&&this.render(this.options.show.ready)},"^content.text$":function(a,b,c){this._updateContent(c)},"^content.attr$":function(a,b,c,d){this.options.content.text===this.target.attr(d)&&this._updateContent(this.target.attr(c))},"^content.title$":function(a,b,c){return c?(c&&!this.elements.title&&this._createTitle(),void this._updateTitle(c)):this._removeTitle()},"^content.button$":function(a,b,c){this._updateButton(c)},"^content.title.(text|button)$":function(a,b,c){this.set("content."+b,c)}
vendor: 15,366 bytes, line 13
13,"^position.(my|at)$":function(a,b,c){"string"==typeof c&&(this.position[b]=a[b]=new A(c,"at"===b))},"^position.container$":function(a,b,c){this.rendered&&this.tooltip.appendTo(c)},"^show.ready$":function(a,b,c){c&&(!this.rendered&&this.render(D)||this.toggle(D))},"^style.classes$":function(a,b,c,d){this.rendered&&this.tooltip.removeClass(d).addClass(c)},"^style.(width|height)":function(a,b,c){this.rendered&&this.tooltip.css(b,c)},"^style.widget|content.title":function(){this.rendered&&this._setWidget()},"^style.def":function(a,b,c){this.rendered&&this.tooltip.toggleClass(Z,!!c)},"^events.(render|show|move|hide|focus|blur)$":function(a,b,c){this.rendered&&this.tooltip[(d.isFunction(c)?"":"un")+"bind"]("tooltip"+b,c)},"^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)":function(){if(this.rendered){var a=this.options.position;this.tooltip.attr("tracking","mouse"===a.target&&a.adjust.mouse),this._unassignEvents(),this._assignEvents()}}}},z.get=function(a){if(this.destroyed)return this;var b=i(this.options,a.toLowerCase()),c=b[0][b[1]];return c.precedance?c.string():c};var eb=/^position\.(my|at|adjust|target|container|viewport)|style|content|show\.ready/i,fb=/^prerender|show\.ready/i;z.set=function(a,b){if(this.destroyed)return this;{var c,e=this.rendered,f=E,g=this.options;this.checks}return"string"==typeof a?(c=a,a={},a[c]=b):a=d.extend({},a),d.each(a,function(b,c){if(e&&fb.test(b))return void delete a[b];var h,j=i(g,b.toLowerCase());h=j[0][j[1]],j[0][j[1]]=c&&c.nodeType?d(c):c,f=eb.test(b)||f,a[b]=[j[0],j[1],c,h]}),h(g),this.positioning=D,d.each(a,d.proxy(j,this)),this.positioning=E,this.rendered&&this.tooltip[0].offsetWidth>0&&f&&this.reposition("mouse"===g.position.target?F:this.cache.event),this},z._update=function(a,b){var c=this,e=this.cache;return this.rendered&&a?(d.isFunction(a)&&(a=a.call(this.elements.target,e.event,this)||""),d.isFunction(a.then)?(e.waiting=D,a.then(function(a){return e.waiting=E,c._update(a,b)},F,function(a){return c._update(a,b)})):a===E||!a&&""!==a?E:(a.jquery&&a.length>0?b.empty().append(a.css({display:"block",visibility:"visible"})):b.html(a),this._waitForContent(b).then(function(a){c.rendered&&c.tooltip[0].offsetWidth>0&&c.reposition(e.event,!a.length)}))):E},z._waitForContent=function(a){var b=this.cache;return b.waiting=D,(d.fn.imagesLoaded?a.imagesLoaded():d.Deferred().resolve([])).done(function(){b.waiting=E}).promise()},z._updateContent=function(a,b){this._update(a,this.elements.content,b)},z._updateTitle=function(a,b){this._update(a,this.elements.title,b)===E&&this._removeTitle(E)},z._createTitle=function(){var a=this.elements,b=this._id+"-title";a.titlebar&&this._removeTitle(),a.titlebar=d("<div />",{"class":S+"-titlebar "+(this.options.style.widget?k("header"):"")}).append(a.title=d("<div />",{id:b,"class":S+"-title","aria-atomic":D})).insertBefore(a.content).delegate(".qtip-close","mousedown keydown mouseup keyup mouseout",function(a){d(this).toggleClass("ui-state-active ui-state-focus","down"===a.type.substr(-4))}).delegate(".qtip-close","mouseover mouseout",function(a){d(this).toggleClass("ui-state-hover","mouseover"===a.type)}),this.options.content.button&&this._createButton()},z._removeTitle=function(a){var b=this.elements;b.title&&(b.titlebar.remove(),b.titlebar=b.title=b.button=F,a!==E&&this.reposition())},z._createPosClass=function(a){return S+"-pos-"+(a||this.options.position.my).abbrev()},z.reposition=function(c,e){if(!this.rendered||this.positioning||this.destroyed)return this;this.positioning=D;var f,g,h,i,j=this.cache,k=this.tooltip,l=this.options.position,m=l.target,n=l.my,o=l.at,p=l.viewport,q=l.container,r=l.adjust,s=r.method.split(" "),t=k.outerWidth(E),u=k.outerHeight(E),v=0,w=0,x=k.css("position"),y={left:0,top:0},z=k[0].offsetWidth>0,A=c&&"scroll"===c.type,B=d(a),C=q[0].ownerDocument,F=this.mouse;if(d.isArray(m)&&2===m.length)o={x:L,y:K},y={left:m[0],top:m[1]};else if("mouse"===m)o={x:L,y:K},(!r.mouse||this.options.hide.distance)&&j.origin&&j.origin.pageX?c=j.origin:!c||c&&("resize"===c.type||"scroll"===c.type)?c=j.event:F&&F.pageX&&(c=F),"static"!==x&&(y=q.offset()),C.body.offsetWidth!==(a.innerWidth||C.documentElement.clientWidth)&&(g=d(b.body).offset()),y={left:c.pageX-y.left+(g&&g.left||0),top:c.pageY-y.top+(g&&g.top||0)},r.mouse&&A&&F&&(y.left-=(F.scrollX||0)-B.scrollLeft(),y.top-=(F.scrollY||0)-B.scrollTop());else{if("event"===m?c&&c.target&&"scroll"!==c.type&&"resize"!==c.type?j.target=d(c.target):c.target||(j.target=this.elements.target):"event"!==m&&(j.target=d(m.jquery?m:this.elements.target)),m=j.target,m=d(m).eq(0),0===m.length)return this;m[0]===b||m[0]===a?(v=db.iOS?a.innerWidth:m.width(),w=db.iOS?a.innerHeight:m.height(),m[0]===a&&(y={top:(p||m).scrollTop(),left:(p||m).scrollLeft()})):R.imagemap&&m.is("area")?f=R.imagemap(this,m,o,R.viewport?s:E):R.svg&&m&&m[0].ownerSVGElement?f=R.svg(this,m,o,R.viewport?s:E):(v=m.outerWidth(E),w=m.outerHeight(E),y=m.offset()),f&&(v=f.width,w=f.height,g=f.offset,y=f.position),y=this.reposition.offset(m,y,q),(db.iOS>3.1&&db.iOS<4.1||db.iOS>=4.3&&db.iOS<4.33||!db.iOS&&"fixed"===x)&&(y.left-=B.scrollLeft(),y.top-=B.scrollTop()),(!f||f&&f.adjustable!==E)&&(y.left+=o.x===N?v:o.x===O?v/2:0,y.top+=o.y===M?w:o.y===O?w/2:0)}return y.left+=r.x+(n.x===N?-t:n.x===O?-t/2:0),y.top+=r.y+(n.y===M?-u:n.y===O?-u/2:0),R.viewport?(h=y.adjusted=R.viewport(this,y,l,v,w,t,u),g&&h.left&&(y.left+=g.left),g&&h.top&&(y.top+=g.top),h.my&&(this.position.my=h.my)):y.adjusted={left:0,top:0},j.posClass!==(i=this._createPosClass(this.position.my))&&k.removeClass(j.posClass).addClass(j.posClass=i),this._trigger("move",[y,p.elem||p],c)?(delete y.adjusted,e===E||!z||isNaN(y.left)||isNaN(y.top)||"mouse"===m||!d.isFunction(l.effect)?k.css(y):d.isFunction(l.effect)&&(l.effect.call(k,this,d.extend({},y)),k.queue(function(a){d(this).css({opacity:"",height:""}),db.ie&&this.style.removeAttribute("filter"),a()})),this.positioning=E,this):this},z.reposition.offset=function(a,c,e){function f(a,b){c.left+=b*a.scrollLeft(),c.top+=b*a.scrollTop()}if(!e[0])return c;var g,h,i,j,k=d(a[0].ownerDocument),l=!!db.ie&&"CSS1Compat"!==b.compatMode,m=e[0];do"static"!==(h=d.css(m,"position"))&&("fixed"===h?(i=m.getBoundingClientRect(),f(k,-1)):(i=d(m).position(),i.left+=parseFloat(d.css(m,"borderLeftWidth"))||0,i.top+=parseFloat(d.css(m,"borderTopWidth"))||0),c.left-=i.left+(parseFloat(d.css(m,"marginLeft"))||0),c.top-=i.top+(parseFloat(d.css(m,"marginTop"))||0),g||"hidden"===(j=d.css(m,"overflow"))||"visible"===j||(g=d(m)));while(m=m.offsetParent);return g&&(g[0]!==k[0]||l)&&f(g,1),c};var gb=(A=z.reposition.Corner=function(a,b){a=(""+a).replace(/([A-Z])/," $1").replace(/middle/gi,O).toLowerCase(),this.x=(a.match(/left|right/i)||a.match(/center/)||["inherit"])[0].toLowerCase(),this.y=(a.match(/top|bottom|center/i)||["inherit"])[0].toLowerCase(),this.forceY=!!b;var c=a.charAt(0);this.precedance="t"===c||"b"===c?H:G}).prototype;gb.invert=function(a,b){this[a]=this[a]===L?N:this[a]===N?L:b||this[a]},gb.string=function(a){var b=this.x,c=this.y,d=b!==c?"center"===b||"center"!==c&&(this.precedance===H||this.forceY)?[c,b]:[b,c]:[b];return a!==!1?d.join(" "):d},gb.abbrev=function(){var a=this.string(!1);return a[0].charAt(0)+(a[1]&&a[1].charAt(0)||"")},gb.clone=function(){return new A(this.string(),this.forceY)},z.toggle=function(a,c){var e=this.cache,f=this.options,g=this.tooltip;if(c){if(/over|enter/.test(c.type)&&e.event&&/out|leave/.test(e.event.type)&&f.show.target.add(c.target).length===f.show.target.length&&g.has(c.relatedTarget).length)return this;e.event=d.event.fix(c)}if(this.waiting&&!a&&(this.hiddenDuringWait=D),!this.rendered)return a?this.render(1):this;if(this.destroyed||this.disabled)return this;var h,i,j,k=a?"show":"hide",l=this.options[k],m=(this.options[a?"hide":"show"],this.options.position),n=this.options.content,o=this.tooltip.css("width"),p=this.tooltip.is(":visible"),q=a||1===l.target.length,r=!c||l.target.length<2||e.target[0]===c.target;return(typeof a).search("boolean|number")&&(a=!p),h=!g.is(":animated")&&p===a&&r,i=h?F:!!this._trigger(k,[90]),this.destroyed?this:(i!==E&&a&&this.focus(c),!i||h?this:(d.attr(g[0],"aria-hidden",!a),a?(this.mouse&&(e.origin=d.event.fix(this.mouse)),d.isFunction(n.text)&&this._updateContent(n.text,E),d.isFunction(n.title)&&this._updateTitle(n.title,E),!C&&"mouse"===m.target&&m.adjust.mouse&&(d(b).bind("mousemove."+S,this._storeMouse),C=D),o||g.css("width",g.outerWidth(E)),this.reposition(c,arguments[2]),o||g.css("width",""),l.solo&&("string"==typeof l.solo?d(l.solo):d(W,l.solo)).not(g).not(l.target).qtip("hide",d.Event("tooltipsolo"))):(clearTimeout(this.timers.show),delete e.origin,C&&!d(W+'[tracking="true"]:visible',l.solo).not(g).length&&(d(b).unbind("mousemove."+S),C=E),this.blur(c)),j=d.proxy(function(){a?(db.ie&&g[0].style.removeAttribute("filter"),g.css("overflow",""),"string"==typeof l.autofocus&&d(this.options.show.autofocus,g).focus(),this.options.show.target.trigger("qtip-"+this.id+"-inactive")):g.css({display:"",visibility:"",opacity:"",left:"",top:""}),this._trigger(a?"visible":"hidden")},this),l.effect===E||q===E?(g[k](),j()):d.isFunction(l.effect)?(g.stop(1,1),l.effect.call(g,this),g.queue("fx",function(a){j(),a()})):g.fadeTo(90,a?1:0,j),a&&l.target.trigger("qtip-"+this.id+"-inactive"),this))},z.show=function(a){return this.toggle(D,a)},z.hide=function(a){return this.toggle(E,a)},z.focus=function(a){if(!this.rendered||this.destroyed)return this;var b=d(W),c=this.tooltip,e=parseInt(c[0].style.zIndex,10),f=y.zindex+b.length;return c.hasClass($)||this._trigger("focus",[f],a)&&(e!==f&&(b.each(function(){this.style.zIndex>e&&(this.style.zIndex=this.style.zIndex-1)}),b.filter("."+$).qtip("blur",a)),c.addClass($)[0].style.zIndex=f),this},z.blur=function(a){return!this.rendered||this.destroyed?this:(this.tooltip.removeClass($),this._trigger("blur",[this.tooltip.css("zIndex")],a),this)},z.disable=function(a){return this.destroyed?this:("toggle"===a?a=!(this.rendered?this.tooltip.hasClass(ab):this.disabled):"boolean"!=typeof a&&(a=D),this.rendered&&this.tooltip.toggleClass(ab,a).attr("aria-disabled",a),this.disabled=!!a,this)},z.enable=function(){return this.disable(E)},z._createButton=function(){var a=this,b=this.elements,c=b.tooltip,e=this.options.content.button,f="string"==typeof e,g=f?e:"Close tooltip";b.button&&b.button.remove(),b.button=e.jquery?e:d("<a />",{"class":"qtip-close "+(this.options.style.widget?"":S+"-icon"),title:g,"aria-label":g}).prepend(d("<span />",{"class":"ui-icon ui-icon-close",html:"&times;"})),b.button.appendTo(b.titlebar||c).attr("role","button").click(function(b){return c.hasClass(ab)||a.hide(b),E})},z._updateButton=function(a){if(!this.rendered)return E;var b=this.elements.button;a?this._createButton():b.remove()},z._setWidget=function(){var a=this.options.style.widget,b=this.elements,c=b.tooltip,d=c.hasClass(ab);c.removeClass(ab),ab=a?"ui-state-disabled":"qtip-disabled",c.toggleClass(ab,d),c.toggleClass("ui-helper-reset "+k(),a).toggleClass(Z,this.options.style.def&&!a),b.content&&b.content.toggleClass(k("content"),a),b.titlebar&&b.titlebar.toggleClass(k("header"),a),b.button&&b.button.toggleClass(S+"-icon",!a)},z._storeMouse=function(a){return(this.mouse=d.event.fix(a)).type="mousemove",this},z._bind=function(a,b,c,e,f){if(a&&c&&b.length){var g="."+this._id+(e?"-"+e:"");return d(a).bind((b.split?b:b.join(g+" "))+g,d.proxy(c,f||this)),this}},z._unbind=function(a,b){return a&&d(a).unbind("."+this._id+(b?"-"+b:"")),this},z._trigger=function(a,b,c){var e=d.Event("tooltip"+a);return e.originalEvent=c&&d.extend({},c)||this.cache.event||F,this.triggering=a,this.tooltip.trigger(e,[this].concat(b||[])),this.triggering=E,!e.isDefaultPrevented()},z._bindEvents=function(a,b,c,e,f,g){var h=c.filter(e).add(e.filter(c)),i=[];h.length&&(d.each(b,function(b,c){var e=d.inArray(c,a);e>-1&&i.push(a.splice(e,1)[0])}),i.length&&(this._bind(h,i,function(a){var b=this.rendered?this.tooltip[0].offsetWidth>0:!1;(b?g:f).call(this,a)}),c=c.not(h),e=e.not(h))),this._bind(c,a,f),this._bind(e,b,g)},z._assignInitialEvents=function(a){function b(a){return this.disabled||this.destroyed?E:(this.cache.event=a&&d.event.fix(a),this.cache.target=a&&d(a.target),clearTimeout(this.timers.show),void(this.timers.show=l.call(this,function(){this.render("object"==typeof a||c.show.ready)},c.prerender?0:c.show.delay)))}var c=this.options,e=c.show.target,f=c.hide.target,g=c.show.event?d.trim(""+c.show.event).split(" "):[],h=c.hide.event?d.trim(""+c.hide.event).split(" "):[];this._bind(this.elements.target,["remove","removeqtip"],function(){this.destroy(!0)},"destroy"),/mouse(over|enter)/i.test(c.show.event)&&!/mouse(out|leave)/i.test(c.hide.event)&&h.push("mouseleave"),this._bind(e,"mousemove",function(a){this._storeMouse(a),this.cache.onTarget=D}),this._bindEvents(g,h,e,f,b,function(){return this.timers?void clearTimeout(this.timers.show):E}),(c.show.ready||c.prerender)&&b.call(this,a)},z._assignEvents=function(){var c=this,e=this.options,f=e.position,g=this.tooltip,h=e.show.target,i=e.hide.target,j=f.container,k=f.viewport,l=d(b),q=(d(b.body),d(a)),r=e.show.event?d.trim(""+e.show.event).split(" "):[],s=e.hide.event?d.trim(""+e.hide.event).split(" "):[];d.each(e.events,function(a,b){c._bind(g,"toggle"===a?["tooltipshow","tooltiphide"]:["tooltip"+a],b,null,g)}),/mouse(out|leave)/i.test(e.hide.event)&&"window"===e.hide.leave&&this._bind(l,["mouseout","blur"],function(a){/select|option/.test(a.target.nodeName)||a.relatedTarget||this.hide(a)}),e.hide.fixed?i=i.add(g.addClass(Y)):/mouse(over|enter)/i.test(e.show.event)&&this._bind(i,"mouseleave",function(){clearTimeout(this.timers.show)}),(""+e.hide.event).indexOf("unfocus")>-1&&this._bind(j.closest("html"),["mousedown","touchstart"],function(a){var b=d(a.target),c=this.rendered&&!this.tooltip.hasClass(ab)&&this.tooltip[0].offsetWidth>0,e=b.parents(W).filter(this.tooltip[0]).length>0;b[0]===this.target[0]||b[0]===this.tooltip[0]||e||this.target.has(b[0]).length||!c||this.hide(a)}),"number"==typeof e.hide.inactive&&(this._bind(h,"qtip-"+this.id+"-inactive",o,"inactive"),this._bind(i.add(g),y.inactiveEvents,o)),this._bindEvents(r,s,h,i,m,n),this._bind(h.add(g),"mousemove",function(a){if("number"==typeof e.hide.distance){var b=this.cache.origin||{},c=this.options.hide.distance,d=Math.abs;(d(a.pageX-b.pageX)>=c||d(a.pageY-b.pageY)>=c)&&this.hide(a)}this._storeMouse(a)}),"mouse"===f.target&&f.adjust.mouse&&(e.hide.event&&this._bind(h,["mouseenter","mouseleave"],function(a){return this.cache?void(this.cache.onTarget="mouseenter"===a.type):E}),this._bind(l,"mousemove",function(a){this.rendered&&this.cache.onTarget&&!this.tooltip.hasClass(ab)&&this.tooltip[0].offsetWidth>0&&this.reposition(a)})),(f.adjust.resize||k.length)&&this._bind(d.event.special.resize?k:q,"resize",p),f.adjust.scroll&&this._bind(q.add(f.container),"scroll",p)},z._unassignEvents=function(){var c=this.options,e=c.show.target,f=c.hide.target,g=d.grep([this.elements.target[0],this.rendered&&this.tooltip[0],c.position.container[0],c.position.viewport[0],c.position.container.closest("html")[0],a,b],function(a){return"object"==typeof a});e&&e.toArray&&(g=g.concat(e.toArray())),f&&f.toArray&&(g=g.concat(f.toArray())),this._unbind(g)._unbind(g,"destroy")._unbind(g,"inactive")},d(function(){q(W,["mouseenter","mouseleave"],function(a){var b="mouseenter"
vendor: 20,380 bytes, lines 13-15
13===a.type,c=d(a.currentTarget),e=d(a.relatedTarget||a.target),f=this.options;b?(this.focus(a),c.hasClass(Y)&&!c.hasClass(ab)&&clearTimeout(this.timers.hide)):"mouse"===f.position.target&&f.position.adjust.mouse&&f.hide.event&&f.show.target&&!e.closest(f.show.target[0]).length&&this.hide(a),c.toggleClass(_,b)}),q("["+U+"]",X,o)}),y=d.fn.qtip=function(a,b,e){var f=(""+a).toLowerCase(),g=F,i=d.makeArray(arguments).slice(1),j=i[i.length-1],k=this[0]?d.data(this[0],S):F;return!arguments.length&&k||"api"===f?k:"string"==typeof a?(this.each(function(){var a=d.data(this,S);if(!a)return D;if(j&&j.timeStamp&&(a.cache.event=j),!b||"option"!==f&&"options"!==f)a[f]&&a[f].apply(a,i);else{if(e===c&&!d.isPlainObject(b))return g=a.get(b),E;a.set(b,e)}}),g!==F?g:this):"object"!=typeof a&&arguments.length?void 0:(k=h(d.extend(D,{},a)),this.each(function(a){var b,c;return c=d.isArray(k.id)?k.id[a]:k.id,c=!c||c===E||c.length<1||y.api[c]?y.nextid++:c,b=r(d(this),c,k),b===E?D:(y.api[c]=b,d.each(R,function(){"initialize"===this.initialize&&this(b)}),void b._assignInitialEvents(j))}))},d.qtip=e,y.api={},d.each({attr:function(a,b){if(this.length){var c=this[0],e="title",f=d.data(c,"qtip");if(a===e&&f&&"object"==typeof f&&f.options.suppress)return arguments.length<2?d.attr(c,cb):(f&&f.options.content.attr===e&&f.cache.attr&&f.set("content.text",b),this.attr(cb,b))}return d.fn["attr"+bb].apply(this,arguments)},clone:function(a){var b=(d([]),d.fn["clone"+bb].apply(this,arguments));return a||b.filter("["+cb+"]").attr("title",function(){return d.attr(this,cb)}).removeAttr(cb),b}},function(a,b){if(!b||d.fn[a+bb])return D;var c=d.fn[a+bb]=d.fn[a];d.fn[a]=function(){return b.apply(this,arguments)||c.apply(this,arguments)}}),d.ui||(d["cleanData"+bb]=d.cleanData,d.cleanData=function(a){for(var b,c=0;(b=d(a[c])).length;c++)if(b.attr(T))try{b.triggerHandler("removeqtip")}catch(e){}d["cleanData"+bb].apply(this,arguments)}),y.version="2.2.1",y.nextid=0,y.inactiveEvents=X,y.zindex=15e3,y.defaults={prerender:E,id:E,overwrite:D,suppress:D,content:{text:D,attr:"title",title:E,button:E},position:{my:"top left",at:"bottom right",target:E,container:E,viewport:E,adjust:{x:0,y:0,mouse:D,scroll:D,resize:D,method:"flipinvert flipinvert"},effect:function(a,b){d(this).animate(b,{duration:200,queue:E})}},show:{target:E,event:"mouseenter",effect:D,delay:90,solo:E,ready:E,autofocus:E},hide:{target:E,event:"mouseleave",effect:D,delay:0,fixed:E,inactive:E,leave:"window",distance:E},style:{classes:"",widget:E,width:E,height:E,def:D},events:{render:F,move:F,show:F,hide:F,toggle:F,visible:F,hidden:F,focus:F,blur:F}};var hb,ib="margin",jb="border",kb="color",lb="background-color",mb="transparent",nb=" !important",ob=!!b.createElement("canvas").getContext,pb=/rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i,qb={},rb=["Webkit","O","Moz","ms"];if(ob)var sb=a.devicePixelRatio||1,tb=function(){var a=b.createElement("canvas").getContext("2d");return a.backingStorePixelRatio||a.webkitBackingStorePixelRatio||a.mozBackingStorePixelRatio||a.msBackingStorePixelRatio||a.oBackingStorePixelRatio||1}(),ub=sb/tb;else var vb=function(a,b,c){return"<qtipvml:"+a+' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" '+(b||"")+' style="behavior: url(#default#VML); '+(c||"")+'" />'};d.extend(v.prototype,{init:function(a){var b,c;c=this.element=a.elements.tip=d("<div />",{"class":S+"-tip"}).prependTo(a.tooltip),ob?(b=d("<canvas />").appendTo(this.element)[0].getContext("2d"),b.lineJoin="miter",b.miterLimit=1e5,b.save()):(b=vb("shape",'coordorigin="0,0"',"position:absolute;"),this.element.html(b+b),a._bind(d("*",c).add(c),["click","mousedown"],function(a){a.stopPropagation()},this._ns)),a._bind(a.tooltip,"tooltipmove",this.reposition,this._ns,this),this.create()},_swapDimensions:function(){this.size[0]=this.options.height,this.size[1]=this.options.width},_resetDimensions:function(){this.size[0]=this.options.width,this.size[1]=this.options.height},_useTitle:function(a){var b=this.qtip.elements.titlebar;return b&&(a.y===K||a.y===O&&this.element.position().top+this.size[1]/2+this.options.offset<b.outerHeight(D))},_parseCorner:function(a){var b=this.qtip.options.position.my;return a===E||b===E?a=E:a===D?a=new A(b.string()):a.string||(a=new A(a),a.fixed=D),a},_parseWidth:function(a,b,c){var d=this.qtip.elements,e=jb+s(b)+"Width";return(c?u(c,e):u(d.content,e)||u(this._useTitle(a)&&d.titlebar||d.content,e)||u(d.tooltip,e))||0},_parseRadius:function(a){var b=this.qtip.elements,c=jb+s(a.y)+s(a.x)+"Radius";return db.ie<9?0:u(this._useTitle(a)&&b.titlebar||b.content,c)||u(b.tooltip,c)||0},_invalidColour:function(a,b,c){var d=a.css(b);return!d||c&&d===a.css(c)||pb.test(d)?E:d},_parseColours:function(a){var b=this.qtip.elements,c=this.element.css("cssText",""),e=jb+s(a[a.precedance])+s(kb),f=this._useTitle(a)&&b.titlebar||b.content,g=this._invalidColour,h=[];return h[0]=g(c,lb)||g(f,lb)||g(b.content,lb)||g(b.tooltip,lb)||c.css(lb),h[1]=g(c,e,kb)||g(f,e,kb)||g(b.content,e,kb)||g(b.tooltip,e,kb)||b.tooltip.css(e),d("*",c).add(c).css("cssText",lb+":"+mb+nb+";"+jb+":0"+nb+";"),h},_calculateSize:function(a){var b,c,d,e=a.precedance===H,f=this.options.width,g=this.options.height,h="c"===a.abbrev(),i=(e?f:g)*(h?.5:1),j=Math.pow,k=Math.round,l=Math.sqrt(j(i,2)+j(g,2)),m=[this.border/i*l,this.border/g*l];return m[2]=Math.sqrt(j(m[0],2)-j(this.border,2)),m[3]=Math.sqrt(j(m[1],2)-j(this.border,2)),b=l+m[2]+m[3]+(h?0:m[0]),c=b/l,d=[k(c*f),k(c*g)],e?d:d.reverse()},_calculateTip:function(a,b,c){c=c||1,b=b||this.size;var d=b[0]*c,e=b[1]*c,f=Math.ceil(d/2),g=Math.ceil(e/2),h={br:[0,0,d,e,d,0],bl:[0,0,d,0,0,e],tr:[0,e,d,0,d,e],tl:[0,0,0,e,d,e],tc:[0,e,f,0,d,e],bc:[0,0,d,0,f,e],rc:[0,0,d,g,0,e],lc:[d,0,d,e,0,g]};return h.lt=h.br,h.rt=h.bl,h.lb=h.tr,h.rb=h.tl,h[a.abbrev()]},_drawCoords:function(a,b){a.beginPath(),a.moveTo(b[0],b[1]),a.lineTo(b[2],b[3]),a.lineTo(b[4],b[5]),a.closePath()},create:function(){var a=this.corner=(ob||db.ie)&&this._parseCorner(this.options.corner);return(this.enabled=!!this.corner&&"c"!==this.corner.abbrev())&&(this.qtip.cache.corner=a.clone(),this.update()),this.element.toggle(this.enabled),this.corner},update:function(b,c){if(!this.enabled)return this;var e,f,g,h,i,j,k,l,m=this.qtip.elements,n=this.element,o=n.children(),p=this.options,q=this.size,r=p.mimic,s=Math.round;b||(b=this.qtip.cache.corner||this.corner),r===E?r=b:(r=new A(r),r.precedance=b.precedance,"inherit"===r.x?r.x=b.x:"inherit"===r.y?r.y=b.y:r.x===r.y&&(r[b.precedance]=b[b.precedance])),f=r.precedance,b.precedance===G?this._swapDimensions():this._resetDimensions(),e=this.color=this._parseColours(b),e[1]!==mb?(l=this.border=this._parseWidth(b,b[b.precedance]),p.border&&1>l&&!pb.test(e[1])&&(e[0]=e[1]),this.border=l=p.border!==D?p.border:l):this.border=l=0,k=this.size=this._calculateSize(b),n.css({width:k[0],height:k[1],lineHeight:k[1]+"px"}),j=b.precedance===H?[s(r.x===L?l:r.x===N?k[0]-q[0]-l:(k[0]-q[0])/2),s(r.y===K?k[1]-q[1]:0)]:[s(r.x===L?k[0]-q[0]:0),s(r.y===K?l:r.y===M?k[1]-q[1]-l:(k[1]-q[1])/2)],ob?(g=o[0].getContext("2d"),g.restore(),g.save(),g.clearRect(0,0,6e3,6e3),h=this._calculateTip(r,q,ub),i=this._calculateTip(r,this.size,ub),o.attr(I,k[0]*ub).attr(J,k[1]*ub),o.css(I,k[0]).css(J,k[1]),this._drawCoords(g,i),g.fillStyle=e[1],g.fill(),g.translate(j[0]*ub,j[1]*ub),this._drawCoords(g,h),g.fillStyle=e[0],g.fill()):(h=this._calculateTip(r),h="m"+h[0]+","+h[1]+" l"+h[2]+","+h[3]+" "+h[4]+","+h[5]+" xe",j[2]=l&&/^(r|b)/i.test(b.string())?8===db.ie?2:1:0,o.css({coordsize:k[0]+l+" "+(k[1]+l),antialias:""+(r.string().indexOf(O)>-1),left:j[0]-j[2]*Number(f===G),top:j[1]-j[2]*Number(f===H),width:k[0]+l,height:k[1]+l}).each(function(a){var b=d(this);b[b.prop?"prop":"attr"]({coordsize:k[0]+l+" "+(k[1]+l),path:h,fillcolor:e[0],filled:!!a,stroked:!a}).toggle(!(!l&&!a)),!a&&b.html(vb("stroke",'weight="'+2*l+'px" color="'+e[1]+'" miterlimit="1000" joinstyle="miter"'))})),a.opera&&setTimeout(function(){m.tip.css({display:"inline-block",visibility:"visible"})},1),c!==E&&this.calculate(b,k)},calculate:function(a,b){if(!this.enabled)return E;var c,e,f=this,g=this.qtip.elements,h=this.element,i=this.options.offset,j=(g.tooltip.hasClass("ui-widget"),{});return a=a||this.corner,c=a.precedance,b=b||this._calculateSize(a),e=[a.x,a.y],c===G&&e.reverse(),d.each(e,function(d,e){var h,k,l;
14e===O?(h=c===H?L:K,j[h]="50%",j[ib+"-"+h]=-Math.round(b[c===H?0:1]/2)+i):(h=f._parseWidth(a,e,g.tooltip),k=f._parseWidth(a,e,g.content),l=f._parseRadius(a),j[e]=Math.max(-f.border,d?k:i+(l>h?l:-h)))}),j[a[c]]-=b[c===G?0:1],h.css({margin:"",top:"",bottom:"",left:"",right:""}).css(j),j},reposition:function(a,b,d){function e(a,b,c,d,e){a===Q&&j.precedance===b&&k[d]&&j[c]!==O?j.precedance=j.precedance===G?H:G:a!==Q&&k[d]&&(j[b]=j[b]===O?k[d]>0?d:e:j[b]===d?e:d)}function f(a,b,e){j[a]===O?p[ib+"-"+b]=o[a]=g[ib+"-"+b]-k[b]:(h=g[e]!==c?[k[b],-g[b]]:[-k[b],g[b]],(o[a]=Math.max(h[0],h[1]))>h[0]&&(d[b]-=k[b],o[b]=E),p[g[e]!==c?e:b]=o[a])}if(this.enabled){var g,h,i=b.cache,j=this.corner.clone(),k=d.adjusted,l=b.options.position.adjust.method.split(" "),m=l[0],n=l[1]||l[0],o={left:E,top:E,x:0,y:0},p={};this.corner.fixed!==D&&(e(m,G,H,L,N),e(n,H,G,K,M),(j.string()!==i.corner.string()||i.cornerTop!==k.top||i.cornerLeft!==k.left)&&this.update(j,E)),g=this.calculate(j),g.right!==c&&(g.left=-g.right),g.bottom!==c&&(g.top=-g.bottom),g.user=this.offset,(o.left=m===Q&&!!k.left)&&f(G,L,N),(o.top=n===Q&&!!k.top)&&f(H,K,M),this.element.css(p).toggle(!(o.x&&o.y||j.x===O&&o.y||j.y===O&&o.x)),d.left-=g.left.charAt?g.user:m!==Q||o.top||!o.left&&!o.top?g.left+this.border:0,d.top-=g.top.charAt?g.user:n!==Q||o.left||!o.left&&!o.top?g.top+this.border:0,i.cornerLeft=k.left,i.cornerTop=k.top,i.corner=j.clone()}},destroy:function(){this.qtip._unbind(this.qtip.tooltip,this._ns),this.qtip.elements.tip&&this.qtip.elements.tip.find("*").remove().end().remove()}}),hb=R.tip=function(a){return new v(a,a.options.style.tip)},hb.initialize="render",hb.sanitize=function(a){if(a.style&&"tip"in a.style){var b=a.style.tip;"object"!=typeof b&&(b=a.style.tip={corner:b}),/string|boolean/i.test(typeof b.corner)||(b.corner=D)}},B.tip={"^position.my|style.tip.(corner|mimic|border)$":function(){this.create(),this.qtip.reposition()},"^style.tip.(height|width)$":function(a){this.size=[a.width,a.height],this.update(),this.qtip.reposition()},"^content.title|style.(classes|widget)$":function(){this.update()}},d.extend(D,y.defaults,{style:{tip:{corner:D,mimic:E,width:6,height:6,border:D,offset:0}}});var wb,xb,yb="qtip-modal",zb="."+yb;xb=function(){function a(a){if(d.expr[":"].focusable)return d.expr[":"].focusable;var b,c,e,f=!isNaN(d.attr(a,"tabindex")),g=a.nodeName&&a.nodeName.toLowerCase();return"area"===g?(b=a.parentNode,c=b.name,a.href&&c&&"map"===b.nodeName.toLowerCase()?(e=d("img[usemap=#"+c+"]")[0],!!e&&e.is(":visible")):!1):/input|select|textarea|button|object/.test(g)?!a.disabled:"a"===g?a.href||f:f}function c(a){k.length<1&&a.length?a.not("body").blur():k.first().focus()}function e(a){if(i.is(":visible")){var b,e=d(a.target),h=f.tooltip,j=e.closest(W);b=j.length<1?E:parseInt(j[0].style.zIndex,10)>parseInt(h[0].style.zIndex,10),b||e.closest(W)[0]===h[0]||c(e),g=a.target===k[k.length-1]}}var f,g,h,i,j=this,k={};d.extend(j,{init:function(){return i=j.elem=d("<div />",{id:"qtip-overlay",html:"<div></div>",mousedown:function(){return E}}).hide(),d(b.body).bind("focusin"+zb,e),d(b).bind("keydown"+zb,function(a){f&&f.options.show.modal.escape&&27===a.keyCode&&f.hide(a)}),i.bind("click"+zb,function(a){f&&f.options.show.modal.blur&&f.hide(a)}),j},update:function(b){f=b,k=b.options.show.modal.stealfocus!==E?b.tooltip.find("*").filter(function(){return a(this)}):[]},toggle:function(a,e,g){var k=(d(b.body),a.tooltip),l=a.options.show.modal,m=l.effect,n=e?"show":"hide",o=i.is(":visible"),p=d(zb).filter(":visible:not(:animated)").not(k);return j.update(a),e&&l.stealfocus!==E&&c(d(":focus")),i.toggleClass("blurs",l.blur),e&&i.appendTo(b.body),i.is(":animated")&&o===e&&h!==E||!e&&p.length?j:(i.stop(D,E),d.isFunction(m)?m.call(i,e):m===E?i[n]():i.fadeTo(parseInt(g,10)||90,e?1:0,function(){e||i.hide()}),e||i.queue(function(a){i.css({left:"",top:""}),d(zb).length||i.detach(),a()}),h=e,f.destroyed&&(f=F),j)}}),j.init()},xb=new xb,d.extend(w.prototype,{init:function(a){var b=a.tooltip;return this.options.on?(a.elements.overlay=xb.elem,b.addClass(yb).css("z-index",y.modal_zindex+d(zb).length),a._bind(b,["tooltipshow","tooltiphide"],function(a,c,e){var f=a.originalEvent;if(a.target===b[0])if(f&&"tooltiphide"===a.type&&/mouse(leave|enter)/.test(f.type)&&d(f.relatedTarget).closest(xb.elem[0]).length)try{a.preventDefault()}catch(g){}else(!f||f&&"tooltipsolo"!==f.type)&&this.toggle(a,"tooltipshow"===a.type,e)},this._ns,this),a._bind(b,"tooltipfocus",function(a,c){if(!a.isDefaultPrevented()&&a.target===b[0]){var e=d(zb),f=y.modal_zindex+e.length,g=parseInt(b[0].style.zIndex,10);xb.elem[0].style.zIndex=f-1,e.each(function(){this.style.zIndex>g&&(this.style.zIndex-=1)}),e.filter("."+$).qtip("blur",a.originalEvent),b.addClass($)[0].style.zIndex=f,xb.update(c);try{a.preventDefault()}catch(h){}}},this._ns,this),void a._bind(b,"tooltiphide",function(a){a.target===b[0]&&d(zb).filter(":visible").not(b).last().qtip("focus",a)},this._ns,this)):this},toggle:function(a,b,c){return a&&a.isDefaultPrevented()?this:void xb.toggle(this.qtip,!!b,c)},destroy:function(){this.qtip.tooltip.removeClass(yb),this.qtip._unbind(this.qtip.tooltip,this._ns),xb.toggle(this.qtip,E),delete this.qtip.elements.overlay}}),wb=R.modal=function(a){return new w(a,a.options.show.modal)},wb.sanitize=function(a){a.show&&("object"!=typeof a.show.modal?a.show.modal={on:!!a.show.modal}:"undefined"==typeof a.show.modal.on&&(a.show.modal.on=D))},y.modal_zindex=y.zindex-200,wb.initialize="render",B.modal={"^show.modal.(on|blur)$":function(){this.destroy(),this.init(),this.qtip.elems.overlay.toggle(this.qtip.tooltip[0].offsetWidth>0)}},d.extend(D,y.defaults,{show:{modal:{on:E,effect:D,blur:D,stealfocus:D,escape:D}}}),R.viewport=function(c,d,e,f,g,h,i){function j(a,b,c,e,f,g,h,i,j){var k=d[f],s=u[a],t=v[a],w=c===Q,x=s===f?j:s===g?-j:-j/2,y=t===f?i:t===g?-i:-i/2,z=q[f]+r[f]-(n?0:m[f]),A=z-k,B=k+j-(h===I?o:p)-z,C=x-(u.precedance===a||s===u[b]?y:0)-(t===O?i/2:0);return w?(C=(s===f?1:-1)*x,d[f]+=A>0?A:B>0?-B:0,d[f]=Math.max(-m[f]+r[f],k-C,Math.min(Math.max(-m[f]+r[f]+(h===I?o:p),k+C),d[f],"center"===s?k-x:1e9))):(e*=c===P?2:0,A>0&&(s!==f||B>0)?(d[f]-=C+e,l.invert(a,f)):B>0&&(s!==g||A>0)&&(d[f]-=(s===O?-C:C)+e,l.invert(a,g)),d[f]<q&&-d[f]>B&&(d[f]=k,l=u.clone())),d[f]-k}var k,l,m,n,o,p,q,r,s=e.target,t=c.elements.tooltip,u=e.my,v=e.at,w=e.adjust,x=w.method.split(" "),y=x[0],z=x[1]||x[0],A=e.viewport,B=e.container,C=(c.cache,{left:0,top:0});return A.jquery&&s[0]!==a&&s[0]!==b.body&&"none"!==w.method?(m=B.offset()||C,n="static"===B.css("position"),k="fixed"===t.css("position"),o=A[0]===a?A.width():A.outerWidth(E),p=A[0]===a?A.height():A.outerHeight(E),q={left:k?0:A.scrollLeft(),top:k?0:A.scrollTop()},r=A.offset()||C,("shift"!==y||"shift"!==z)&&(l=u.clone()),C={left:"none"!==y?j(G,H,y,w.x,L,N,I,f,h):0,top:"none"!==z?j(H,G,z,w.y,K,M,J,g,i):0,my:l}):C},R.polys={polygon:function(a,b){var c,d,e,f={width:0,height:0,position:{top:1e10,right:0,bottom:0,left:1e10},adjustable:E},g=0,h=[],i=1,j=1,k=0,l=0;for(g=a.length;g--;)c=[parseInt(a[--g],10),parseInt(a[g+1],10)],c[0]>f.position.right&&(f.position.right=c[0]),c[0]<f.position.left&&(f.position.left=c[0]),c[1]>f.position.bottom&&(f.position.bottom=c[1]),c[1]<f.position.top&&(f.position.top=c[1]),h.push(c);if(d=f.width=Math.abs(f.position.right-f.position.left),e=f.height=Math.abs(f.position.bottom-f.position.top),"c"===b.abbrev())f.position={left:f.position.left+f.width/2,top:f.position.top+f.height/2};else{for(;d>0&&e>0&&i>0&&j>0;)for(d=Math.floor(d/2),e=Math.floor(e/2),b.x===L?i=d:b.x===N?i=f.width-d:i+=Math.floor(d/2),b.y===K?j=e:b.y===M?j=f.height-e:j+=Math.floor(e/2),g=h.length;g--&&!(h.length<2);)k=h[g][0]-f.position.left,l=h[g][1]-f.position.top,(b.x===L&&k>=i||b.x===N&&i>=k||b.x===O&&(i>k||k>f.width-i)||b.y===K&&l>=j||b.y===M&&j>=l||b.y===O&&(j>l||l>f.height-j))&&h.splice(g,1);f.position={left:h[0][0],top:h[0][1]}}return f},rect:function(a,b,c,d){return{width:Math.abs(c-a),height:Math.abs(d-b),position:{left:Math.min(a,c),top:Math.min(b,d)}}},_angles:{tc:1.5,tr:7/4,tl:5/4,bc:.5,br:.25,bl:.75,rc:2,lc:1,c:0},ellipse:function(a,b,c,d,e){var f=R.polys._angles[e.abbrev()],g=0===f?0:c*Math.cos(f*Math.PI),h=d*Math.sin(f*Math.PI);return{width:2*c-Math.abs(g),height:2*d-Math.abs(h),position:{left:a+g,top:b+h},adjustable:E}},circle:function(a,b,c,d){return R.polys.ellipse(a,b,c,c,d)}},R.svg=function(a,c,e){for(var f,g,h,i,j,k,l,m,n,o=(d(b),c[0]),p=d(o.ownerSVGElement),q=o.ownerDocument,r=(parseInt(c.css("stroke-width"),10)||0)/2;!o.getBBox;)o=o.parentNode;if(!o.getBBox||!o.parentNode)return E;switch(o.nodeName){case"ellipse":case"circle":m=R.polys.ellipse(o.cx.baseVal.value,o.cy.baseVal.value,(o.rx||o.r).baseVal.value+r,(o.ry||o.r).baseVal.value+r,e);break;case"line":case"polygon":case"polyline":for(l=o.points||[{x:o.x1.baseVal.value,y:o.y1.baseVal.value},{x:o.x2.baseVal.value,y:o.y2.baseVal.value}],m=[],k=-1,i=l.numberOfItems||l.length;++k<i;)j=l.getItem?l.getItem(k):l[k],m.push.apply(m,[j.x,j.y]);m=R.polys.polygon(m,e);break;default:m=o.getBBox(),m={width:m.width,height:m.height,position:{left:m.x,top:m.y}}}return n=m.position,p=p[0],p.createSVGPoint&&(g=o.getScreenCTM(),l=p.createSVGPoint(),l.x=n.left,l.y=n.top,h=l.matrixTransform(g),n.left=h.x,n.top=h.y),q!==b&&"mouse"!==a.position.target&&(f=d((q.defaultView||q.parentWindow).frameElement).offset(),f&&(n.left+=f.left,n.top+=f.top)),q=d(q),n.left+=q.scrollLeft(),n.top+=q.scrollTop(),m},R.imagemap=function(a,b,c){b.jquery||(b=d(b));var e,f,g,h,i,j=(b.attr("shape")||"rect").toLowerCase().replace("poly","polygon"),k=d('img[usemap="#'+b.parent("map").attr("name")+'"]'),l=d.trim(b.attr("coords")),m=l.replace(/,$/,"").split(",");if(!k.length)return E;if("polygon"===j)h=R.polys.polygon(m,c);else{if(!R.polys[j])return E;for(g=-1,i=m.length,f=[];++g<i;)f.push(parseInt(m[g],10));h=R.polys[j].apply(this,f.concat(c))}return e=k.offset(),e.left+=Math.ceil((k.outerWidth(E)-k.width())/2),e.top+=Math.ceil((k.outerHeight(E)-k.height())/2),h.position.left+=e.left,h.position.top+=e.top,h};var Ab,Bb='<iframe class="qtip-bgiframe" frameborder="0" tabindex="-1" src="javascript:\'\';"  style="display:block; position:absolute; z-index:-1; filter:alpha(opacity=0); -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";"></iframe>';d.extend(x.prototype,{_scroll:function(){var b=this.qtip.elements.overlay;b&&(b[0].style.top=d(a).scrollTop()+"px")},init:function(c){var e=c.tooltip;d("select, object").length<1&&(this.bgiframe=c.elements.bgiframe=d(Bb).appendTo(e),c._bind(e,"tooltipmove",this.adjustBGIFrame,this._ns,this)),this.redrawContainer=d("<div/>",{id:S+"-rcontainer"}).appendTo(b.body),c.elements.overlay&&c.elements.overlay.addClass("qtipmodal-ie6fix")&&(c._bind(a,["scroll","resize"],this._scroll,this._ns,this),c._bind(e,["tooltipshow"],this._scroll,this._ns,this)),this.redraw()},adjustBGIFrame:function(){var a,b,c=this.qtip.tooltip,d={height:c.outerHeight(E),width:c.outerWidth(E)},e=this.qtip.plugins.tip,f=this.qtip.elements.tip;b=parseInt(c.css("borderLeftWidth"),10)||0,b={left:-b,top:-b},e&&f&&(a="x"===e.corner.precedance?[I,L]:[J,K],b[a[1]]-=f[a[0]]()),this.bgiframe.css(b).css(d)},redraw:function(){if(this.qtip.rendered<1||this.drawing)return this;var a,b,c,d,e=this.qtip.tooltip,f=this.qtip.options.style,g=this.qtip.options.position.container;return this.qtip.drawing=1,f.height&&e.css(J,f.height),f.width?e.css(I,f.width):(e.css(I,"").appendTo(this.redrawContainer),b=e.width(),1>b%2&&(b+=1),c=e.css("maxWidth")||"",d=e.css("minWidth")||"",a=(c+d).indexOf("%")>-1?g.width()/100:0,c=(c.indexOf("%")>-1?a:1)*parseInt(c,10)||b,d=(d.indexOf("%")>-1?a:1)*parseInt(d,10)||0,b=c+d?Math.min(Math.max(b,d),c):b,e.css(I,Math.round(b)).appendTo(g)),this.drawing=0,this},destroy:function(){this.bgiframe&&this.bgiframe.remove(),this.qtip._unbind([a,this.qtip.tooltip],this._ns)}}),Ab=R.ie6=function(a){return 6===db.ie?new x(a):E},Ab.initialize="render",B.ie6={"^content|style$":function(){this.redraw()}}})}(window,document);;
15// jQuery RoyalSlider plugin. Custom build. Copyright 2011-2015 Dmitry Semenov http://dim
15semenov.com 
16// http://dimsemenov.com/private/home.php?build=bullets_thumbnails_tabs_fullscreen_autoplay_video_animated-blocks_auto-height_global-caption_active-class_deeplinking_visible-nearby 
17// jquery.royalslider v9.5.8
18(function(n){function v(b,f){var c,a=this,e=window.navigator,g=e.userAgent.toLowerCase();a.uid=n.rsModules.uid++;a.ns=".rs"+a.uid;var d=document.createElement("div").style,h=["webkit","Moz","ms","O"],k="",l=0,q;for(c=0;c<h.length;c++)q=h[c],!k&&q+"Transform"in d&&(k=q),q=q.toLowerCase(),window.requestAnimationFrame||(window.requestAnimationFrame=window[q+"RequestAnimationFrame"],window.cancelAnimationFrame=window[q+"CancelAnimationFrame"]||window[q+"CancelRequestAnimationFrame"]);window.requestAnimationFrame||
19(window.requestAnimationFrame=function(a,b){var c=(new Date).getTime(),d=Math.max(0,16-(c-l)),e=window.setTimeout(function(){a(c+d)},d);l=c+d;return e});window.cancelAnimationFrame||(window.cancelAnimationFrame=function(a){clearTimeout(a)});a.isIPAD=g.match(/(ipad)/);a.isIOS=a.isIPAD||g.match(/(iphone|ipod)/);c=function(a){a=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||0>a.indexOf("compatible")&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||
20[];return{browser:a[1]||"",version:a[2]||"0"}}(g);h={};c.browser&&(h[c.browser]=!0,h.version=c.version);h.chrome&&(h.webkit=!0);a._a=h;a.isAndroid=-1<g.indexOf("android");a.slider=n(b);a.ev=n(a);a._b=n(document);a.st=n.extend({},n.fn.royalSlider.defaults,f);a._c=a.st.transitionSpeed;a._d=0;!a.st.allowCSS3||h.webkit&&!a.st.allowCSS3OnWebkit||(c=k+(k?"T":"t"),a._e=c+"ransform"in d&&c+"ransition"in d,a._e&&(a._f=k+(k?"P":"p")+"erspective"in d));k=k.toLowerCase();a._g="-"+k+"-";a._h="vertical"===a.st.slidesOrientation?
21!1:!0;a._i=a._h?"left":"top";a._j=a._h?"width":"height";a._k=-1;a._l="fade"===a.st.transitionType?!1:!0;a._l||(a.st.sliderDrag=!1,a._m=10);a._n="z-index:0; display:none; opacity:0;";a._o=0;a._p=0;a._q=0;n.each(n.rsModules,function(b,c){"uid"!==b&&c.call(a)});a.slides=[];a._r=0;(a.st.slides?n(a.st.slides):a.slider.children().detach()).each(function(){a._s(this,!0)});a.st.randomizeSlides&&a.slides.sort(function(){return.5-Math.random()});a.numSlides=a.slides.length;a._t();a.st.startSlideId?a.st.startSlideId>
22a.numSlides-1&&(a.st.startSlideId=a.numSlides-1):a.st.startSlideId=0;a._o=a.staticSlideId=a.currSlideId=a._u=a.st.startSlideId;a.currSlide=a.slides[a.currSlideId];a._v=0;a.pointerMultitouch=!1;a.slider.addClass((a._h?"rsHor":"rsVer")+(a._l?"":" rsFade"));d='<div class="rsOverflow"><div class="rsContainer">';a.slidesSpacing=a.st.slidesSpacing;a._w=(a._h?a.slider.width():a.slider.height())+a.st.slidesSpacing;a._x=Boolean(0<a._y);1>=a.numSlides&&(a._z=!1);a._a1=a._z&&a._l?2===a.numSlides?1:2:0;a._b1=
236>a.numSlides?a.numSlides:6;a._c1=0;a._d1=0;a.slidesJQ=[];for(c=0;c<a.numSlides;c++)a.slidesJQ.push(n('<div style="'+(a._l?"":c!==a.currSlideId?a._n:"z-index:0;")+'" class="rsSlide "></div>'));a._e1=d=n(d+"</div></div>");var m=a.ns,k=function(b,c,d,e,f){a._j1=b+c+m;a._k1=b+d+m;a._l1=b+e+m;f&&(a._m1=b+f+m)};c=e.pointerEnabled;a.pointerEnabled=c||e.msPointerEnabled;a.pointerEnabled?(a.hasTouch=!1,a._n1=.2,a.pointerMultitouch=Boolean(1<e[(c?"m":"msM")+"axTouchPoints"]),c?k("pointer","down","move","up",
24"cancel"):k("MSPointer","Down","Move","Up","Cancel")):(a.isIOS?a._j1=a._k1=a._l1=a._m1="":k("mouse","down","move","up"),"ontouchstart"in window||"createTouch"in document?(a.hasTouch=!0,a._j1+=" touchstart"+m,a._k1+=" touchmove"+m,a._l1+=" touchend"+m,a._m1+=" touchcancel"+m,a._n1=.5,a.st.sliderTouch&&(a._f1=!0)):(a.hasTouch=!1,a._n1=.2));a.st.sliderDrag&&(a._f1=!0,h.msie||h.opera?a._g1=a._h1="move":h.mozilla?(a._g1="-moz-grab",a._h1="-moz-grabbing"):h.webkit&&-1!=e.platform.indexOf("Mac")&&(a._g1=
25"-webkit-grab",a._h1="-webkit-grabbing"),a._i1());a.slider.html(d);a._o1=a.st.controlsInside?a._e1:a.slider;a._p1=a._e1.children(".rsContainer");a.pointerEnabled&&a._p1.css((c?"":"-ms-")+"touch-action",a._h?"pan-y":"pan-x");a._q1=n('<div class="rsPreloader"></div>');e=a._p1.children(".rsSlide");a._r1=a.slidesJQ[a.currSlideId];a._s1=0;a._e?(a._t1="transition-property",a._u1="transition-duration",a._v1="transition-timing-function",a._w1=a._x1=a._g+"transform",a._f?(h.webkit&&!h.chrome&&a.slider.addClass("rsWebkit3d"),
26a._y1="translate3d(",a._z1="px, ",a._a2="px, 0px)"):(a._y1="translate(",a._z1="px, ",a._a2="px)"),a._l?a._p1[a._g+a._t1]=a._g+"transform":(h={},h[a._g+a._t1]="opacity",h[a._g+a._u1]=a.st.transitionSpeed+"ms",h[a._g+a._v1]=a.st.css3easeInOut,e.css(h))):(a._x1="left",a._w1="top");var p;n(window).on("resize"+a.ns,function(){p&&clearTimeout(p);p=setTimeout(function(){a.updateSliderSize()},50)});a.ev.trigger("rsAfterPropsSetup");a.updateSliderSize();a.st.keyboardNavEnabled&&a._b2();a.st.arrowsNavHideOnTouch&&
27(a.hasTouch||a.pointerMultitouch)&&(a.st.arrowsNav=!1);a.st.arrowsNav&&(e=a._o1,n('<div class="rsArrow rsArrowLeft"><div class="rsArrowIcn"></div></div><div class="rsArrow rsArrowRight"><div class="rsArrowIcn"></div></div>').appendTo(e),a._c2=e.children(".rsArrowLeft").click(function(b){b.preventDefault();a.prev()}),a._d2=e.children(".rsArrowRight").click(function(b){b.preventDefault();a.next()}),a.st.arrowsNavAutoHide&&!a.hasTouch&&(a._c2.addClass("rsHidden"),a._d2.addClass("rsHidden"),e.one("mousemove.arrowshover",
28function(){a._c2.removeClass("rsHidden");a._d2.removeClass("rsHidden")}),e.hover(function(){a._e2||(a._c2.removeClass("rsHidden"),a._d2.removeClass("rsHidden"))},function(){a._e2||(a._c2.addClass("rsHidden"),a._d2.addClass("rsHidden"))})),a.ev.on("rsOnUpdateNav",function(){a._f2()}
28),a._f2());if(a.hasTouch&&a.st.sliderTouch||!a.hasTouch&&a.st.sliderDrag)a._p1.on(a._j1,function(b){a._g2(b)});else a.dragSuccess=!1;var r=["rsPlayBtnIcon","rsPlayBtn","rsCloseVideoBtn","rsCloseVideoIcn"];a._p1.click(function(b){if(!a.dragSuccess){var c=
29n(b.target).attr("class");if(-1!==n.inArray(c,r)&&a.toggleVideo())return!1;if(a.st.navigateByClick&&!a._h2){if(n(b.target).closest(".rsNoDrag",a._r1).length)return!0;a._i2(b)}a.ev.trigger("rsSlideClick",b)}}).on("click.rs","a",function(b){if(a.dragSuccess)return!1;a._h2=!0;setTimeout(function(){a._h2=!1},3)});a.ev.trigger("rsAfterInit")}n.rsModules||(n.rsModules={uid:0});v.prototype={constructor:v,_i2:function(b){b=b[this._h?"pageX":"pageY"]-this._j2;b>=this._q?this.next():0>b&&this.prev()},_t:function(){var b;
30b=this.st.numImagesToPreload;if(this._z=this.st.loop)2===this.numSlides?(this._z=!1,this.st.loopRewind=!0):2>this.numSlides&&(this.st.loopRewind=this._z=!1);this._z&&0<b&&(4>=this.numSlides?b=1:this.st.numImagesToPreload>(this.numSlides-1)/2&&(b=Math.floor((this.numSlides-1)/2)));this._y=b},_s:function(b,f){function c(b,c){c?g.images.push(b.attr(c)):g.images.push(b.text());if(h){h=!1;g.caption="src"===c?b.attr("alt"):b.contents();g.image=g.images[0];g.videoURL=b.attr("data-rsVideo");var d=b.attr("data-rsw"),
31e=b.attr("data-rsh");"undefined"!==typeof d&&!1!==d&&"undefined"!==typeof e&&!1!==e?(g.iW=parseInt(d,10),g.iH=parseInt(e,10)):a.st.imgWidth&&a.st.imgHeight&&(g.iW=a.st.imgWidth,g.iH=a.st.imgHeight)}}var a=this,e,g={},d,h=!0;b=n(b);a._k2=b;a.ev.trigger("rsBeforeParseNode",[b,g]);if(!g.stopParsing)return b=a._k2,g.id=a._r,g.contentAdded=!1,a._r++,g.images=[],g.isBig=!1,g.hasCover||(b.hasClass("rsImg")?(d=b,e=!0):(d=b.find(".rsImg"),d.length&&(e=!0)),e?(g.bigImage=d.eq(0).attr("data-rsBigImg"),d.each(function(){var a=
32n(this);a.is("a")?c(a,"href"):a.is("img")?c(a,"src"):c(a)})):b.is("img")&&(b.addClass("rsImg rsMainSlideImage"),c(b,"src"))),d=b.find(".rsCaption"),d.length&&(g.caption=d.remove()),g.content=b,a.ev.trigger("rsAfterParseNode",[b,g]),f&&a.slides.push(g),0===g.images.length&&(g.isLoaded=!0,g.isRendered=!1,g.isLoading=!1,g.images=null),g},_b2:function(){var b=this,f,c,a=function(a){37===a?b.prev():39===a&&b.next()};b._b.on("keydown"+b.ns,function(e){if(!b.st.keyboardNavEnabled)return!0;if(!(b._l2||(c=
33e.keyCode,37!==c&&39!==c||f))){if(document.activeElement&&/(INPUT|SELECT|TEXTAREA)/i.test(document.activeElement.tagName))return!0;b.isFullscreen&&e.preventDefault();a(c);f=setInterval(function(){a(c)},700)}}).on("keyup"+b.ns,function(a){f&&(clearInterval(f),f=null)})},goTo:function(b,f){b!==this.currSlideId&&this._m2(b,this.st.transitionSpeed,!0,!f)},destroy:function(b){this.ev.trigger("rsBeforeDestroy");this._b.off("keydown"+this.ns+" keyup"+this.ns+" "+this._k1+" "+this._l1);this._p1.off(this._j1+
34" click");this.slider.data("royalSlider",null);n.removeData(this.slider,"royalSlider");n(window).off("resize"+this.ns);this.loadingTimeout&&clearTimeout(this.loadingTimeout);b&&this.slider.remove();this.ev=this.slider=this.slides=null},_n2:function(b,f){function c(c,f,g){c.isAdded?(a(f,c),e(f,c)):(g||(g=d.slidesJQ[f]),c.holder?g=c.holder:(g=d.slidesJQ[f]=n(g),c.holder=g),c.appendOnLoaded=!1,e(f,c,g),a(f,c),d._p2(c,g,b),c.isAdded=!0)}function a(a,c){c.contentAdded||(d.setItemHtml(c,b),b||(c.contentAdded=
35!0))}function e(a,b,c){d._l&&(c||(c=d.slidesJQ[a]),c.css(d._i,(a+d._d1+p)*d._w))}function g(a){if(l){if(a>q-1)return g(a-q);if(0>a)return g(q+a)}return a}var d=this,h,k,l=d._z,q=d.numSlides;if(!isNaN(f))return g(f);var m=d.currSlideId,p,r=b?Math.abs(d._o2-d.currSlideId)>=d.numSlides-1?0:1:d._y,t=Math.min(2,r),w=!1,v=!1,u;for(k=m;k<m+1+t;k++)if(u=g(k),(h=d.slides[u])&&(!h.isAdded||!h.positionSet)){w=!0;break}for(k=m-1;k>m-1-t;k--)if(u=g(k),(h=d.slides[u])&&(!h.isAdded||!h.positionSet)){v=!0;break}if(w)for(k=
36m;k<m+r+1;k++)u=g(k),p=Math.floor((d._u-(m-k))/d.numSlides)*d.numSlides,(h=d.slides[u])&&c(h,u);if(v)for(k=m-1;k>m-1-r;k--)u=g(k),p=Math.floor((d._u-(m-k))/q)*q,(h=d.slides[u])&&c(h,u);if(!b)for(t=g(m-r),m=g(m+r),r=t>m?0:t,k=0;k<q;k++)t>m&&k>t-1||!(k<r||k>m)||(h=d.slides[k])&&h.holder&&(h.holder.detach(),h.isAdded=!1)},setItemHtml:function(b,f){var c=this,a=function(){if(!b.images)b.isRendered=!0,b.isLoaded=!0,b.isLoading=!1,d(!0);else if(!b.isLoading){var a,f;b.content.hasClass("rsImg")?(a=b.content,
37f=!0):a=b.content.find(".rsImg:not(img)");a&&!a.is("img")&&a.each(function(){var a=n(this),c='<img class="rsImg" src="'+(a.is("a")?a.attr("href"):a.text())+'" />';f?b.content=n(c):a.replaceWith(c)});a=f?b.content:b.content.find("img.rsImg");k();a.eq(0).addClass("rsMainSlideImage");b.iW&&b.iH&&(b.isLoaded||c._q2(b),d());b.isLoading=!0;if(b.isBig)n("<img />").on("load.rs error.rs",function(a){n(this).off("load.rs error.rs");e([this],!0)}).attr("src",b.image);else{b.loaded=[];b.numStartedLoad=0;a=function(a){n(this).off("load.rs error.rs");
38b.loaded.push(this);b.loaded.length===b.numStartedLoad&&e(b.loaded,!1)};for(var g=0;g<b.images.length;g++){var h=n("<img />");b.numStartedLoad++;h.on("load.rs error.rs",a).attr("src",b.images[g])}}}},e=function(a,c){if(a.length){var d=a[0];if(c!==b.isBig)(d=b.holder.children())&&1<d.length&&l();else if(b.iW&&b.iH)g();else if(b.iW=d.width,b.iH=d.height,b.iW&&b.iH)g();else{var e=new Image;
38e.onload=function(){e.width?(b.iW=e.width,b.iH=e.height,g()):setTimeout(function(){e.width&&(b.iW=e.width,b.iH=
39e.height);g()},1E3)};e.src=d.src}}else g()},g=function(){b.isLoaded=!0;b.isLoading=!1;d();l();h()},d=function(){if(!b.isAppended&&c.ev){var a=c.st.visibleNearby,d=b.id-c._o;f||b.appendOnLoaded||!c.st.fadeinLoadedSlide||0!==d&&(!(a||c._r2||c._l2)||-1!==d&&1!==d)||(a={visibility:"visible",opacity:0},a[c._g+"transition"]="opacity 400ms ease-in-out",b.content.css(a),setTimeout(function(){b.content.css("opacity",1)},16));b.holder.find(".rsPreloader").length?b.holder.append(b.content):b.holder.html(b.content);
40b.isAppended=!0;b.isLoaded&&(c._q2(b),h());b.sizeReady||(b.sizeReady=!0,setTimeout(function(){c.ev.trigger("rsMaybeSizeReady",b)},100))}},h=function(){!b.loadedTriggered&&c.ev&&(b.isLoaded=b.loadedTriggered=!0,b.holder.trigger("rsAfterContentSet"),c.ev.trigger("rsAfterContentSet",b))},k=function(){c.st.usePreloader&&b.holder.html(c._q1.clone())},l=function(a){c.st.usePreloader&&(a=b.holder.find(".rsPreloader"),a.length&&a.remove())};b.isLoaded?d():f?!c._l&&b.images&&b.iW&&b.iH?a():(b.holder.isWaiting=
41!0,k(),b.holder.slideId=-99):a()},_p2:function(b,f,c){this._p1.append(b.holder);b.appendOnLoaded=!1},_g2:function(b,f){var c=this,a,e="touchstart"===b.type;c._s2=e;c.ev.trigger("rsDragStart");if(n(b.target).closest(".rsNoDrag",c._r1).length)return c.dragSuccess=!1,!0;!f&&c._r2&&(c._t2=!0,c._u2());c.dragSuccess=!1;if(c._l2)e&&(c._v2=!0);else{e&&(c._v2=!1);c._w2();if(e){var g=b.originalEvent.touches;if(g&&0<g.length)a=g[0],1<g.length&&(c._v2=!0);else return}else b.preventDefault(),a=b,c.pointerEnabled&&
42(a=a.originalEvent);c._l2=!0;c._b.on(c._k1,function(a){c._x2(a,f)}).on(c._l1,function(a){c._y2(a,f)});c._z2="";c._a3=!1;c._b3=a.pageX;c._c3=a.pageY;c._d3=c._v=(f?c._e3:c._h)?a.pageX:a.pageY;c._f3=0;c._g3=0;c._h3=f?c._i3:c._p;c._j3=(new Date).getTime();if(e)c._e1.on(c._m1,function(a){c._y2(a,f)})}},_k3:function(b,f){if(this._l3){var c=this._m3,a=b.pageX-this._b3,e=b.pageY-this._c3,g=this._h3+a,d=this._h3+e,h=f?this._e3:this._h,g=h?g:d,d=this._z2;this._a3=!0;this._b3=b.pageX;this._c3=b.pageY;"x"===
43d&&0!==a?this._f3=0<a?1:-1:"y"===d&&0!==e&&(this._g3=0<e?1:-1);d=h?this._b3:this._c3;a=h?a:e;f?g>this._n3?g=this._h3+a*this._n1:g<this._o3&&(g=this._h3+a*this._n1):this._z||(0>=this.currSlideId&&0<d-this._d3&&(g=this._h3+a*this._n1),this.currSlideId>=this.numSlides-1&&0>d-this._d3&&(g=this._h3+a*this._n1));this._h3=g;200<c-this._j3&&(this._j3=c,this._v=d);f?this._q3(this._h3):this._l&&this._p3(this._h3)}},_x2:function(b,f){var c=this,a,e="touchmove"===b.type;if(!c._s2||e){if(e){if(c._r3)return;var g=
44b.originalEvent.touches;if(g){if(1<g.length)return;a=g[0]}else return}else a=b,c.pointerEnabled&&(a=a.originalEvent);c._a3||(c._e&&(f?c._s3:c._p1).css(c._g+c._u1,"0s"),function h(){c._l2&&(c._t3=requestAnimationFrame(h),c._u3&&c._k3(c._u3,f))}());if(c._l3)b.preventDefault(),c._m3=(new Date).getTime(),c._u3=a;else if(g=f?c._e3:c._h,a=Math.abs(a.pageX-c._b3)-Math.abs(a.pageY-c._c3)-(g?-7:7),7<a){if(g)b.preventDefault(),c._z2="x";else if(e){c._v3(b);return}c._l3=!0}else if(-7>a){if(!g)b.preventDefault(),
45c._z2="y";else if(e){c._v3(b);return}c._l3=!0}}},_v3:function(b,f){this._r3=!0;this._a3=this._l2=!1;this._y2(b)},_y2:function(b,f){function c(a){return 100>a?100:500<a?500:a}function a(a,b){if(e._l||f)h=(-e._u-e._d1)*e._w,k=Math.abs(e._p-h),e._c=k/b,a&&(e._c+=250),e._c=c(e._c),e._x3(h,!1)}var e=this,g,d,h,k;g=-1<b.type.indexOf("touch");if(!e._s2||g)if(e._s2=!1,e.ev.trigger("rsDragRelease"),e._u3=null,e._l2=!1,e._r3=!1,e._l3=!1,e._m3=0,cancelAnimationFrame(e._t3),e._a3&&(f?e._q3(e._h3):e._l&&e._p3(e._h3)),
46e._b.off(e._k1).off(e._l1),g&&e._e1.off(e._m1),e._i1(),!e._a3&&!e._v2&&f&&e._w3){var l=n(b.target).closest(".rsNavItem");l.length&&e.goTo(l.index())}else{d=f?e._e3:e._h;if(!e._a3||"y"===e._z2&&d||"x"===e._z2&&!d)if(!f&&e._t2){e._t2=!1;if(e.st.navigateByClick){e._i2(e.pointerEnabled?b.originalEvent:b);e.dragSuccess=!0;return}e.dragSuccess=!0}else{e._t2=!1;e.dragSuccess=!1;return}else e.dragSuccess=!0;e._t2=!1;e._z2="";var q=e.st.minSlideOffset;g=g?b.originalEvent.changedTouches[0]:e.pointerEnabled?
47b.originalEvent:b;var m=d?g.pageX:g.pageY,p=e._d3;g=e._v;var r=e.currSlideId,t=e.numSlides,w=d?e._f3:e._g3,v=e._z;Math.abs(m-p);g=m-g;d=(new Date).getTime()-e._j3;d=Math.abs(g)/d;if(0===w||1>=t)a(!0,d);else{if(!v&&!f)if(0>=r){if(0<w){a(!0,d);return}}else if(r>=t-1&&0>w){a(!0,d);return}if(f){h=e._i3;if(h>e._n3)h=e._n3;else if(h<e._o3)h=e._o3;else{m=d*d/.006;l=-e._i3;p=e._y3-e._z3+e._i3;0<g&&m>l?(l+=e._z3/(15/(m/d*.003)),d=d*l/m,m=l):0>g&&m>p&&(p+=e._z3/(15/(m/d*.003)),d=d*p/m,m=p);l=Math.max(Math.round(d/
48.003),50);h+=m*(0>g?-1:1);if(h>e._n3){e._a4(h,l,!0,e._n3,200);return}if(h<e._o3){e._a4(h,l,!0,e._o3,200);return}}e._a4(h,l,!0)}else l=function(a){var b=Math.floor(a/e._w);a-b*e._w>q&&b++;return b},p+q<m?0>w?a(!1,d):(l=l(m-p),e._m2(e.currSlideId-l,c(Math.abs(e._p-(-e._u-e._d1+l)*e._w)/d),!1,!0,!0)):p-q>m?0<w?a(!1,d):(l=l(p-m),e._m2(e.currSlideId+l,c(Math.abs(e._p-(-e._u-e._d1-l)*e._w)/d),!1,!0,!0)):a(!1,d)}}},_p3:function(b){b=this._p=b;this._e?this._p1.css(this._x1,this._y1+(this._h?b+this._z1+0:
490+this._z1+b)+this._a2):this._p1.css(this._h?this._x1:this._w1,b)},updateSliderSize:function(b){var f,c;if(this.slider){if(this.st.autoScaleSlider){var a=this.st.autoScaleSliderWidth,e=this.st.autoScaleSliderHeight;this.st.autoScaleHeight?(f=this.slider.width(),f!=this.width&&(this.slider.css("height",e/a*f),f=this.slider.width()),c=this.slider.height()):(c=this.slider.height(),c!=this.height&&(this.slider.css("width",a/e*c),c=this.slider.height()),f=this.slider.width())}else f=this.slider.width(),
50c=this.slider.height();if(b||f!=this.width||c!=this.height){this.width=f;this.height=c;this._b4=f;this._c4=c;this.ev.trigger("rsBeforeSizeSet");this.ev.trigger("rsAfterSizePropSet");this._e1.css({width:this._b4,height:this._c4});this._w=(this._h?this._b4:this._c4)+this.st.slidesSpacing;this._d4=this.st.imageScalePadding;
50for(f=0;f<this.slides.length;f++)b=this.slides[f],b.positionSet=!1,b&&b.images&&b.isLoaded&&(b.isRendered=!1,this._q2(b));if(this._e4)for(f=0;f<this._e4.length;f++)b=this._e4[f],b.holder.css(this._i,
51(b.id+this._d1)*this._w);this._n2();this._l&&(this._e&&this._p1.css(this._g+"transition-duration","0s"),this._p3((-this._u-this._d1)*this._w));this.ev.trigger("rsOnUpdateNav")}this._j2=this._e1.offset();this._j2=this._j2[this._i]}},appendSlide:function(b,f){var c=this._s(b);if(isNaN(f)||f>this.numSlides)f=this.numSlides;this.slides.splice(f,0,c);this.slidesJQ.splice(f,0,n('<div style="'+(this._l?"position:absolute;":this._n)+'" class="rsSlide"></div>'));f<=this.currSlideId&&this.currSlideId++;this.ev.trigger("rsOnAppendSlide",
52[c,f]);this._f4(f);f===this.currSlideId&&this.ev.trigger("rsAfterSlideChange")},removeSlide:function(b){var f=this.slides[b];f&&(f.holder&&f.holder.remove(),b<this.currSlideId&&this.currSlideId--,this.slides.splice(b,1),this.slidesJQ.splice(b,1),this.ev.trigger("rsOnRemoveSlide",[b]),this._f4(b),b===this.currSlideId&&this.ev.trigger("rsAfterSlideChange"))},_f4:function(b){var f=this;b=f.numSlides;b=0>=f._u?0:Math.floor(f._u/b);f.numSlides=f.slides.length;0===f.numSlides?(f.currSlideId=f._d1=f._u=
530,f.currSlide=f._g4=null):f._u=b*f.numSlides+f.currSlideId;for(b=0;b<f.numSlides;b++)f.slides[b].id=b;f.currSlide=f.slides[f.currSlideId];f._r1=f.slidesJQ[f.currSlideId];f.currSlideId>=f.numSlides?f.goTo(f.numSlides-1):0>f.currSlideId&&f.goTo(0);f._t();f._l&&f._p1.css(f._g+f._u1,"0ms");f._h4&&clearTimeout(f._h4);f._h4=setTimeout(function(){f._l&&f._p3((-f._u-f._d1)*f._w);f._n2();f._l||f._r1.css({display:"block",opacity:1})},14);f.ev.trigger("rsOnUpdateNav")},_i1:function(){this._f1&&this._l&&(this._g1?
54this._e1.css("cursor",this._g1):(this._e1.removeClass("grabbing-cursor"),this._e1.addClass("grab-cursor")))},_w2:function(){this._f1&&this._l&&(this._h1?this._e1.css("cursor",this._h1):(this._e1.removeClass("grab-cursor"),this._e1.addClass("grabbing-cursor")))},next:function(b){this._m2("next",this.st.transitionSpeed,!0,!b)},prev:function(b){this._m2("prev",this.st.transitionSpeed,!0,!b)},_m2:function(b,f,c,a,e){var g=this,d,h,k;g.ev.trigger("rsBeforeMove",[b,a]);k="next"===b?g.currSlideId+1:"prev"===
55b?g.currSlideId-1:b=parseInt(b,10);if(!g._z){if(0>k){g._i4("left",!a);return}if(k>=g.numSlides){g._i4("right",!a);return}}g._r2&&(g._u2(!0),c=!1);h=k-g.currSlideId;k=g._o2=g.currSlideId;var l=g.currSlideId+h;a=g._u;var n;g._z?(l=g._n2(!1,l),a+=h):a=l;g._o=l;g._g4=g.slidesJQ[g.currSlideId];g._u=a;g.currSlideId=g._o;g.currSlide=g.slides[g.currSlideId];g._r1=g.slidesJQ[g.currSlideId];var l=g.st.slidesDiff,m=Boolean(0<h);h=Math.abs(h);var p=Math.floor(k/g._y),r=Math.floor((k+(m?l:-l))/g._y),p=(m?Math.max(p,
56r):Math.min(p,r))*g._y+(m?g._y-1:0);p>g.numSlides-1?p=g.numSlides-1:0>p&&(p=0);k=m?p-k:k-p;k>g._y&&(k=g._y);if(h>k+l)for(g._d1+=(h-(k+l))*(m?-1:1),f*=1.4,k=0;k<g.numSlides;k++)g.slides[k].positionSet=!1;g._c=f;g._n2(!0);e||(n=!0);d=(-a-g._d1)*g._w;n?setTimeout(function(){g._j4=!1;g._x3(d,b,!1,c);g.ev.trigger("rsOnUpdateNav")},0):(g._x3(d,b,!1,c),g.ev.trigger("rsOnUpdateNav"))},_f2:function(){this.st.arrowsNav&&(1>=this.numSlides?(this._c2.css("display","none"),this._d2.css("display","none")):(this._c2.css("display",
57"block"),this._d2.css("display","block"),this._z||this.st.loopRewind||(0===this.currSlideId?this._c2.addClass("rsArrowDisabled"):this._c2.removeClass("rsArrowDisabled"),this.currSlideId===this.numSlides-1?this._d2.addClass("rsArrowDisabled"):this._d2.removeClass("rsArrowDisabled"))))},_x3:function(b,f,c,a,e){function g(){var a;h&&(a=h.data("rsTimeout"))&&(h!==k&&h.css({opacity:0,display:"none",zIndex:0}),clearTimeout(a),h.data("rsTimeout",""));if(a=k.data("rsTimeout"))clearTimeout(a),k.data("rsTimeout",
58"")}var d=this,h,k,l={};isNaN(d._c)&&(d._c=400);d._p=d._h3=b;d.ev.trigger("rsBeforeAnimStart");d._e?d._l?(d._c=parseInt(d._c,10),c=d._g+d._v1,l[d._g+d._u1]=d._c+"ms",l[c]=a?n.rsCSS3Easing[d.st.easeInOut]:n.rsCSS3Easing[d.st.easeOut],d._p1.css(l),a||!d.hasTouch?setTimeout(function(){d._p3(b)},5):d._p3(b)):(d._c=d.st.transitionSpeed,h=d._g4,k=d._r1,k.data("rsTimeout")&&k.css("opacity",0),g(),h&&h.data("rsTimeout",setTimeout(function(){l[d._g+d._u1]="0ms";l.zIndex=0;l.display="none";h.data("rsTimeout",
59"");h.css(l);setTimeout(function(){h.css("opacity",0)},16)},d._c+60)),l.display="block",l.zIndex=d._m,l.opacity=0,l[d._g+d._u1]="0ms",l[d._g+d._v1]=n.rsCSS3Easing[d.st.easeInOut],k.css(l),k.data("rsTimeout",setTimeout(function(){k.css(d._g+d._u1,d._c+"ms");k.data("rsTimeout",setTimeout(function(){k.css("opacity",1);k.data("rsTimeout","")},20))},20))):d._l?(l[d._h?d._x1:d._w1]=b+"px",d._p1.animate(l,d._c,a?d.st.easeInOut:d.st.easeOut)):(h=d._g4,k=d._r1,k.stop(!0,!0).css({opacity:0,display:"block",
60zIndex:d._m}),d._c=d.st.transitionSpeed,k.animate({opacity:1},d._c,d.st.easeInOut),g(),h&&h.data("rsTimeout",setTimeout(function(){h.stop(!0,!0).css({opacity:0,display:"none",zIndex:0})},d._c+60)));d._r2=!0;d.loadingTimeout&&clearTimeout(d.loadingTimeout);d.loadingTimeout=e?setTimeout(function(){d.loadingTimeout=null;e.call()},d._c+60):setTimeout(function(){d.loadingTimeout=null;d._k4(f)},d._c+60)},_u2:function(b){this._r2=!1;clearTimeout(this.loadingTimeout);if(this._l)if(!this._e)this._p1.stop(!0),
61this._p=parseInt(this._p1.css(this._h?this._x1:this._w1),10);else{if(!b){b=this._p;var f=this._h3=this._l4();this._p1.css(this._g+this._u1,"0ms");b!==f&&this._p3(f)}}else 20<this._m?this._m=10:this._m++},_l4:function(){var b=window.getComputedStyle(this._p1.get(0),null).getPropertyValue(this._g+"transform").replace(/^matrix\(/i,"").split(/, |\)$/g),f=0===b[0].indexOf("matrix3d");return parseInt(b[this._h?f?12:4:f?13:5],10)},_m4:function(b,f){return this._e?this._y1+(f?b+this._z1+0:0+this._z1+b)+this._a2:
62b},_k4:function(b){this._l||(this._r1.css("z-index",0),this._m=10);this._r2=!1;this.staticSlideId=this.currSlideId;this._n2();this._n4=!1;this.ev.trigger("rsAfterSlideChange")},_i4:function(b,f){var c=this,a=(-c._u-c._d1)*c._w;if(0!==c.numSlides&&!c._r2)if(c.st.loopRewind)c.goTo("left"===b?c.numSlides-1:0,f);else if(c._l){c._c=200;var e=function(){c._r2=!1};c._x3(a+("left"===b?30:-30),"",!1,!0,function(){c._r2=!1;c._x3(a,"",!1,!0,e)})}}
62,_q2:function(b,f){if(!b.isRendered){var c=b.content,a="rsMainSlideImage",
63e,g=n.isFunction(this.st.imageAlignCenter)?this.st.imageAlignCenter(b):this.st.imageAlignCenter,d=n.isFunction(this.st.imageScaleMode)?this.st.imageScaleMode(b):this.st.imageScaleMode,h;b.videoURL&&(a="rsVideoContainer","fill"!==d?e=!0:(h=c,h.hasClass(a)||(h=h.find("."+a)),h.css({width:"100%",height:"100%"}),a="rsMainSlideImage"));c.hasClass(a)||(c=c.find("."+a));if(c){var k=b.iW,l=b.iH;b.isRendered=!0;if("none"!==d||g){a="fill"!==d?this._d4:0;h=this._b4-2*a;var q=this._c4-2*a,m,p,r={};"fit-if-smaller"===
64d&&(k>h||l>q)&&(d="fit");if("fill"===d||"fit"===d)m=h/k,p=q/l,m="fill"==d?m>p?m:p:"fit"==d?m<p?m:p:1,k=Math.ceil(k*m,10),l=Math.ceil(l*m,10);"none"!==d&&(r.width=k,r.height=l,e&&c.find(".rsImg").css({width:"100%",height:"100%"}));g&&(r.marginLeft=Math.floor((h-k)/2)+a,r.marginTop=Math.floor((q-l)/2)+a);c.css(r)}}}}};n.rsProto=v.prototype;n.fn.royalSlider=function(b){var f=arguments;return this.each(function(){var c=n(this);if("object"!==typeof b&&b){if((c=c.data("royalSlider"))&&c[b])return c[b].apply(c,
65Array.prototype.slice.call(f,1))}else c.data("royalSlider")||c.data("royalSlider",new v(c,b))})};n.fn.royalSlider.defaults={slidesSpacing:8,startSlideId:0,loop:!1,loopRewind:!1,numImagesToPreload:4,fadeinLoadedSlide:!0,slidesOrientation:"horizontal",transitionType:"move",transitionSpeed:600,controlNavigation:"bullets",controlsInside:!0,arrowsNav:!0,arrowsNavAutoHide:!0,navigateByClick:!0,randomizeSlides:!1,sliderDrag:!0,sliderTouch:!0,keyboardNavEnabled:!1,fadeInAfterLoaded:!0,allowCSS3:!0,allowCSS3OnWebkit:!0,
66addActiveClass:!1,autoHeight:!1,easeOut:"easeOutSine",easeInOut:"easeInOutSine",minSlideOffset:10,imageScaleMode:"fit-if-smaller",imageAlignCenter:!0,imageScalePadding:4,usePreloader:!0,autoScaleSlider:!1,autoScaleSliderWidth:800,autoScaleSliderHeight:400,autoScaleHeight:!0,arrowsNavHideOnTouch:!1,globalCaption:!1,slidesDiff:2};n.rsCSS3Easing={easeOutSine:"cubic-bezier(0.390, 0.575, 0.565, 1.000)",easeInOutSine:"cubic-bezier(0.445, 0.050, 0.550, 0.950)"};n.extend(jQuery.easing,{easeInOutSine:function(b,
67f,c,a,e){return-a/2*(Math.cos(Math.PI*f/e)-1)+c},easeOutSine:function(b,f,c,a,e){return a*Math.sin(f/e*(Math.PI/2))+c},easeOutCubic:function(b,f,c,a,e){return a*((f=f/e-1)*f*f+1)+c}})})(jQuery,window);
68// jquery.rs.bullets v1.0.1
69(function(c){c.extend(c.rsProto,{_i5:function(){var a=this;"bullets"===a.st.controlNavigation&&(a.ev.one("rsAfterPropsSetup",function(){a._j5=!0;a.slider.addClass("rsWithBullets");for(var b='<div class="rsNav rsBullets">',e=0;e<a.numSlides;e++)b+='<div class="rsNavItem rsBullet"><span></span></div>';a._k5=b=c(b+"</div>");a._l5=b.appendTo(a.slider).children();a._k5.on("click.rs",".rsNavItem",function(b){a._m5||a.goTo(c(this).index())})}),a.ev.on("rsOnAppendSlide",function(b,c,d){d>=a.numSlides?a._k5.append('<div class="rsNavItem rsBullet"><span></span></div>'):
70a._l5.eq(d).before('<div class="rsNavItem rsBullet"><span></span></div>');a._l5=a._k5.children()}),a.ev.on("rsOnRemoveSlide",function(b,c){var d=a._l5.eq(c);d&&d.length&&(d.remove(),a._l5=a._k5.children())}),a.ev.on("rsOnUpdateNav",function(){var b=a.currSlideId;a._n5&&a._n5.removeClass("rsNavSelected");b=a._l5.eq(b);b.addClass("rsNavSelected");a._n5=b}))}});c.rsModules.bullets=c.rsProto._i5})(jQuery);
71// jquery.rs.thumbnails v1.0.8
72(function(f){f.extend(f.rsProto,{_h6:function(){var a=this;"thumbnails"===a.st.controlNavigation&&(a._i6={drag:!0,touch:!0,orientation:"horizontal",navigation:!0,arrows:!0,arrowLeft:null,arrowRight:null,spacing:4,arrowsAutoHide:!1,appendSpan:!1,transitionSpeed:600,autoCenter:!0,fitInViewport:!0,firstMargin:!0,paddingTop:0,paddingBottom:0},a.st.thumbs=f.extend({},a._i6,a.st.thumbs),a._j6=!0,!1===a.st.thumbs.firstMargin?a.st.thumbs.firstMargin=0:!0===a.st.thumbs.firstMargin&&(a.st.thumbs.firstMargin=
73a.st.thumbs.spacing),a.ev.on("rsBeforeParseNode",function(a,b,c){b=f(b);c.thumbnail=b.find(".rsTmb").remove();c.thumbnail.length?c.thumbnail=f(document.createElement("div")).append(c.thumbnail).html():(c.thumbnail=b.attr("data-rsTmb"),c.thumbnail||(c.thumbnail=b.find(".rsImg").attr("data-rsTmb")),c.thumbnail=c.thumbnail?'<img src="'+c.thumbnail+'"/>':"")}),a.ev.one("rsAfterPropsSetup",function(){a._k6()}),a._n5=null,a.ev.on("rsOnUpdateNav",function(){var e=f(a._l5[a.currSlideId]);e!==a._n5&&(a._n5&&
74(a._n5.removeClass("rsNavSelected"),a._n5=null),a._l6&&a._m6(a.currSlideId),a._n5=e.addClass("rsNavSelected"))}),a.ev.on("rsOnAppendSlide",function(e,b,c){e="<div"+a._n6+' class="rsNavItem rsThumb">'+a._o6+b.thumbnail+"</div>";a._e&&a._s3.css(a._g+"transition-duration","0ms");c>=a.numSlides?a._s3.append(e):a._l5.eq(c).before(e);a._l5=a._s3.children();a.updateThumbsSize(!0)}),a.ev.on("rsOnRemoveSlide",function(e,b){var c=a._l5.eq(b);c&&(a._e&&a._s3.css(a._g+"transition-duration","0ms"),c.remove(),
75a._l5=a._s3.children(),a.updateThumbsSize(!0))}))},_k6:function(){var a=this,e="rsThumbs",b=a.st.thumbs,c="",g,d,h=b.spacing;a._j5=!0;a._e3="vertical"===b.orientation?!1:!0;a._n6=g=h?' style="margin-'+(a._e3?"right":"bottom")+":"+h+'px;"':"";a._i3=0;a._p6=!1;a._m5=!1;a._l6=!1;a._q6=b.arrows&&b.navigation;d=a._e3?"Hor":"Ver";a.slider.addClass("rsWithThumbs rsWithThumbs"+d);c+='<div class="rsNav rsThumbs rsThumbs'+d+'"><div class="'+e+'Container">';a._o6=b.appendSpan?'<span class="thumbIco"></span>':
76"";for(var k=0;k<a.numSlides;k++)d=a.slides[k],c+="<div"+g+' class="rsNavItem rsThumb">'+d.thumbnail+a._o6+"</div>";c=f(c+"</div></div>");g={};b.paddingTop&&(g[a._e3?"paddingTop":"paddingLeft"]=b.paddingTop);b.paddingBottom&&(g[a._e3?"paddingBottom":"paddingRight"]=b.paddingBottom);c.css(g);a._s3=f(c).find("."+e+"Container");
76a._q6&&(e+="Arrow",b.arrowLeft?a._r6=b.arrowLeft:(a._r6=f('<div class="'+e+" "+e+'Left"><div class="'+e+'Icn"></div></div>'),c.append(a._r6)),b.arrowRight?a._s6=b.arrowRight:
77(a._s6=f('<div class="'+e+" "+e+'Right"><div class="'+e+'Icn"></div></div>'),c.append(a._s6)),a._r6.click(function(){var b=(Math.floor(a._i3/a._t6)+a._u6)*a._t6+a.st.thumbs.firstMargin;a._a4(b>a._n3?a._n3:b)}),a._s6.click(function(){var b=(Math.floor(a._i3/a._t6)-a._u6)*a._t6+a.st.thumbs.firstMargin;a._a4(b<a._o3?a._o3:b)}),b.arrowsAutoHide&&!a.hasTouch&&(a._r6.css("opacity",0),a._s6.css("opacity",0),c.one("mousemove.rsarrowshover",function(){a._l6&&(a._r6.css("opacity",1),a._s6.css("opacity",1))}),
78c.hover(function(){a._l6&&(a._r6.css("opacity",1),a._s6.css("opacity",1))},function(){a._l6&&(a._r6.css("opacity",0),a._s6.css("opacity",0))})));a._k5=c;a._l5=a._s3.children();a.msEnabled&&a.st.thumbs.navigation&&a._s3.css("-ms-touch-action",a._e3?"pan-y":"pan-x");a.slider.append(c);a._w3=!0;a._v6=h;b.navigation&&a._e&&a._s3.css(a._g+"transition-property",a._g+"transform");a._k5.on("click.rs",".rsNavItem",function(b){a._m5||a.goTo(f(this).index())});a.ev.off("rsBeforeSizeSet.thumbs").on("rsBeforeSizeSet.thumbs",
79function(){a._w6=a._e3?a._c4:a._b4;a.updateThumbsSize(!0)});a.ev.off("rsAutoHeightChange.thumbs").on("rsAutoHeightChange.thumbs",function(b,c){a.updateThumbsSize(!0,c)})},updateThumbsSize:function(a,e){var b=this,c=b._l5.first(),f={},d=b._l5.length;b._t6=(b._e3?c.outerWidth():c.outerHeight())+b._v6;b._y3=d*b._t6-b._v6;f[b._e3?"width":"height"]=b._y3+b._v6;b._z3=b._e3?b._k5.width():void 0!==e?e:b._k5.height();b._w3&&(b.isFullscreen||b.st.thumbs.fitInViewport)&&(b._e3?b._c4=b._w6-b._k5.outerHeight():
80b._b4=b._w6-b._k5.outerWidth());b._z3&&(b._o3=-(b._y3-b._z3)-b.st.thumbs.firstMargin,b._n3=b.st.thumbs.firstMargin,b._u6=Math.floor(b._z3/b._t6),b._y3<b._z3?(b.st.thumbs.autoCenter?b._q3((b._z3-b._y3)/2):b._q3(b._n3),b.st.thumbs.arrows&&b._r6&&(b._r6.addClass("rsThumbsArrowDisabled"),b._s6.addClass("rsThumbsArrowDisabled")),b._l6=!1,b._m5=!1,b._k5.off(b._j1)):b.st.thumbs.navigation&&!b._l6&&(b._l6=!0,!b.hasTouch&&b.st.thumbs.drag||b.hasTouch&&b.st.thumbs.touch)&&(b._m5=!0,b._k5.on(b._j1,function(a){b._g2(a,
81!0)})),b._s3.css(f),a&&e&&b._m6(b.currSlideId,!0))},setThumbsOrientation:function(a,e){this._w3&&(this.st.thumbs.orientation=a,this._k5.remove(),this.slider.removeClass("rsWithThumbsHor rsWithThumbsVer"),this._k6(),this._k5.off(this._j1),e||this.updateSliderSize(!0))},_q3:function(a){this._i3=a;this._e?this._s3.css(this._x1,this._y1+(this._e3?a+this._z1+0:0+this._z1+a)+this._a2):this._s3.css(this._e3?this._x1:this._w1,a)},_a4:function(a,e,b,c,g){var d=this;if(d._l6){e||(e=d.st.thumbs.transitionSpeed);
82d._i3=a;d._x6&&clearTimeout(d._x6);d._p6&&(d._e||d._s3.stop(),b=!0);var h={};d._p6=!0;d._e?(h[d._g+"transition-duration"]=e+"ms",h[d._g+"transition-timing-function"]=b?f.rsCSS3Easing[d.st.easeOut]:f.rsCSS3Easing[d.st.easeInOut],d._s3.css(h),d._q3(a)):(h[d._e3?d._x1:d._w1]=a+"px",d._s3.animate(h,e,b?"easeOutCubic":d.st.easeInOut));c&&(d._i3=c);d._y6();d._x6=setTimeout(function(){d._p6=!1;g&&(d._a4(c,g,!0),g=null)},e)}},_y6:function(){this._q6&&(this._i3===this._n3?this._r6.addClass("rsThumbsArrowDisabled"):
83this._r6.removeClass("rsThumbsArrowDisabled"),this._i3===this._o3?this._s6.addClass("rsThumbsArrowDisabled"):this._s6.removeClass("rsThumbsArrowDisabled"))},_m6:function(a,e){var b=0,c,f=a*this._t6+2*this._t6-this._v6+this._n3,d=Math.floor(this._i3/this._t6);this._l6&&(this._j6&&(e=!0,this._j6=!1),f+this._i3>this._z3?(a===this.numSlides-1&&(b=1),d=-a+this._u6-2+b,c=d*this._t6+this._z3%this._t6+this._v6-this._n3):0!==a?(a-1)*this._t6<=-this._i3+this._n3&&a-1<=this.numSlides-this._u6&&(c=(-a+1)*this._t6+
84this._n3):c=this._n3,c!==this._i3&&(b=void 0===c?this._i3:c,b>this._n3?this._q3(this._n3):b<this._o3?this._q3(this._o3):void 0!==c&&(e?this._q3(c):this._a4(c))),this._y6())}});f.rsModules.thumbnails=f.rsProto._h6})(jQuery);
85// jquery.rs.tabs v1.0.2
86(function(e){e.extend(e.rsProto,{_f6:function(){var a=this;"tabs"===a.st.controlNavigation&&(a.ev.on("rsBeforeParseNode",function(a,d,b){d=e(d);b.thumbnail=d.find(".rsTmb").remove();b.thumbnail.length?b.thumbnail=e(document.createElement("div")).append(b.thumbnail).html():(b.thumbnail=d.attr("data-rsTmb"),b.thumbnail||(b.thumbnail=d.find(".rsImg").attr("data-rsTmb")),b.thumbnail=b.thumbnail?'<img src="'+b.thumbnail+'"/>':"")}),a.ev.one("rsAfterPropsSetup",function(){a._g6()}),a.ev.on("rsOnAppendSlide",
87function(c,d,b){b>=a.numSlides?a._k5.append('<div class="rsNavItem rsTab">'+d.thumbnail+"</div>"):a._l5.eq(b).before('<div class="rsNavItem rsTab">'+item.thumbnail+"</div>");a._l5=a._k5.children()}
87),a.ev.on("rsOnRemoveSlide",function(c,d){var b=a._l5.eq(d);b&&(b.remove(),a._l5=a._k5.children())}),a.ev.on("rsOnUpdateNav",function(){var c=a.currSlideId;a._n5&&a._n5.removeClass("rsNavSelected");c=a._l5.eq(c);c.addClass("rsNavSelected");a._n5=c}))},_g6:function(){var a=this,c;a._j5=!0;c='<div class="rsNav rsTabs">';
88for(var d=0;d<a.numSlides;d++)c+='<div class="rsNavItem rsTab">'+a.slides[d].thumbnail+"</div>";c=e(c+"</div>");a._k5=c;a._l5=c.children(".rsNavItem");a.slider.append(c);a._k5.click(function(b){b=e(b.target).closest(".rsNavItem");b.length&&a.goTo(b.index())})}});e.rsModules.tabs=e.rsProto._f6})(jQuery);
89// jquery.rs.fullscreen v1.0.6
90(function(c){c.extend(c.rsProto,{_q5:function(){var a=this;a._r5={enabled:!1,keyboardNav:!0,buttonFS:!0,nativeFS:!1,doubleTap:!0};a.st.fullscreen=c.extend({},a._r5,a.st.fullscreen);if(a.st.fullscreen.enabled)a.ev.one("rsBeforeSizeSet",function(){a._s5()})},_s5:function(){var a=this;a._t5=!a.st.keyboardNavEnabled&&a.st.fullscreen.keyboardNav;if(a.st.fullscreen.nativeFS){var b={supp
90ortsFullScreen:!1,isFullScreen:function(){return!1},requestFullScreen:function(){},cancelFullScreen:function(){},fullScreenEventName:"",
91prefix:""},d=["webkit","moz","o","ms","khtml"];if("undefined"!=typeof document.cancelFullScreen)b.supportsFullScreen=!0;else for(var e=0,f=d.length;e<f;e++)if(b.prefix=d[e],"undefined"!=typeof document[b.prefix+"CancelFullScreen"]){b.supportsFullScreen=!0;break}b.supportsFullScreen?(a.nativeFS=!0,b.fullScreenEventName=b.prefix+"fullscreenchange"+a.ns,b.isFullScreen=function(){switch(this.prefix){case "":return document.fullScreen;case "webkit":return document.webkitIsFullScreen;default:return document[this.prefix+
92"FullScreen"]}},b.requestFullScreen=function(a){return""===this.prefix?a.requestFullScreen():a[this.prefix+"RequestFullScreen"]()},b.cancelFullScreen=function(a){return""===this.prefix?document.cancelFullScreen():document[this.prefix+"CancelFullScreen"]()},a._u5=b):a._u5=!1}a.st.fullscreen.buttonFS&&(a._v5=c('<div class="rsFullscreenBtn"><div class="rsFullscreenIcn"></div></div>').appendTo(a._o1).on("click.rs",function(){a.isFullscreen?a.exitFullscreen():a.enterFullscreen()}))},enterFullscreen:function(a){var b=
93this;if(b._u5)if(a)b._u5.requestFullScreen(c("html")[0]);else{b._b.on(b._u5.fullScreenEventName,function(a){b._u5.isFullScreen()?b.enterFullscreen(!0):b.exitFullscreen(!0)});b._u5.requestFullScreen(c("html")[0]);return}if(!b._w5){b._w5=!0;b._b.on("keyup"+b.ns+"fullscreen",function(a){27===a.keyCode&&b.exitFullscreen()});b._t5&&b._b2();a=c(window);b._x5=a.scrollTop();b._y5=a.scrollLeft();b._z5=c("html").attr("style");b._a6=c("body").attr("style");b._b6=b.slider.attr("style");c("body, html").css({overflow:"hidden",
94height:"100%",width:"100%",margin:"0",padding:"0"});b.slider.addClass("rsFullscreen");var d;for(d=0;d<b.numSlides;d++)a=b.slides[d],a.isRendered=!1,a.bigImage&&(a.isBig=!0,a.isMedLoaded=a.isLoaded,a.isMedLoading=a.isLoading,a.medImage=a.image,a.medIW=a.iW,a.medIH=a.iH,a.slideId=-99,a.bigImage!==a.medImage&&(a.sizeType="big"),a.isLoaded=a.isBigLoaded,a.isLoading=!1,a.image=a.bigImage,a.images[0]=a.bigImage,a.iW=a.bigIW,a.iH=a.bigIH,a.isAppended=a.contentAdded=!1,b._c6(a));b.isFullscreen=!0;b._w5=!1;
95b.updateSliderSize();b.ev.trigger("rsEnterFullscreen")}},exitFullscreen:function(a){var b=this;if(b._u5){if(!a){b._u5.cancelFullScreen(c("html")[0]);return}b._b.off(b._u5.fullScreenEventName)}if(!b._w5){b._w5=!0;b._b.off("keyup"+b.ns+"fullscreen");b._t5&&b._b.off("keydown"+b.ns);c("html").attr("style",b._z5||"");c("body").attr("style",b._a6||"");var d;for(d=0;d<b.numSlides;d++)a=b.slides[d],a.isRendered=!1,a.bigImage&&(a.isBig=!1,a.slideId=-99,a.isBigLoaded=a.isLoaded,a.isBigLoading=a.isLoading,a.bigImage=
96a.image,a.bigIW=a.iW,a.bigIH=a.iH,a.isLoaded=a.isMedLoaded,a.isLoading=!1,a.image=a.medImage,a.images[0]=a.medImage,a.iW=a.medIW,a.iH=a.medIH,a.isAppended=a.contentAdded=!1,b._c6(a,!0),a.bigImage!==a.medImage&&(a.sizeType="med"));b.isFullscreen=!1;a=c(window);a.scrollTop(b._x5);a.scrollLeft(b._y5);b._w5=!1;b.slider.removeClass("rsFullscreen");b.updateSliderSize();setTimeout(function(){b.updateSliderSize()},1);b.ev.trigger("rsExitFullscreen")}},_c6:function(a,b){var d=a.isLoaded||a.isLoading?'<img class="rsImg rsMainSlideImage" src="'+
97a.image+'"/>':'<a class="rsImg rsMainSlideImage" href="'+a.image+'"></a>';a.content.hasClass("rsImg")?a.content=c(d):a.content.find(".rsImg").eq(0).replaceWith(d);a.isLoaded||a.isLoading||!a.holder||a.holder.html(a.content)}});c.rsModules.fullscreen=c.rsProto._q5})(jQuery);
98// jquery.rs.autoplay v1.0.5
99(function(b){b.extend(b.rsProto,{_x4:function(){var a=this,d;
99a._y4={enabled:!1,stopAtAction:!0,pauseOnHover:!0,delay:2E3};!a.st.autoPlay&&a.st.autoplay&&(a.st.autoPlay=a.st.autoplay);a.st.autoPlay=b.extend({},a._y4,a.st.autoPlay);a.st.autoPlay.enabled&&(a.ev.on("rsBeforeParseNode",function(a,c,f){c=b(c);if(d=c.attr("data-rsDelay"))f.customDelay=parseInt(d,10)}),a.ev.one("rsAfterInit",function(){a._z4()}),a.ev.on("rsBeforeDestroy",function(){a.stopAutoPlay();a.slider.off("mouseenter mouseleave");b(window).off("blur"+
100a.ns+" focus"+a.ns)}))},_z4:function(){var a=this;a.startAutoPlay();a.ev.on("rsAfterContentSet",function(b,e){a._l2||a._r2||!a._a5||e!==a.currSlide||a._b5()});a.ev.on("rsDragRelease",function(){a._a5&&a._c5&&(a._c5=!1,a._b5())});a.ev.on("rsAfterSlideChange",function(){a._a5&&a._c5&&(a._c5=!1,a.currSlide.isLoaded&&a._b5())});a.ev.on("rsDragStart",function(){a._a5&&(a.st.autoPlay.stopAtAction?a.stopAutoPlay():(a._c5=!0,a._d5()))});a.ev.on("rsBeforeMove",function(b,e,c){a._a5&&(c&&a.st.autoPlay.stopAtAction?
101a.stopAutoPlay():(a._c5=!0,a._d5()))});a._e5=!1;a.ev.on("rsVideoStop",function(){a._a5&&(a._e5=!1,a._b5())});a.ev.on("rsVideoPlay",function(){a._a5&&(a._c5=!1,a._d5(),a._e5=!0)});b(window).on("blur"+a.ns,function(){a._a5&&(a._c5=!0,a._d5())}).on("focus"+a.ns,function(){a._a5&&a._c5&&(a._c5=!1,a._b5())});a.st.autoPlay.pauseOnHover&&(a._f5=!1,a.slider.hover(function(){a._a5&&(a._c5=!1,a._d5(),a._f5=!0)},function(){a._a5&&(a._f5=!1,a._b5())}))},toggleAutoPlay:function(){this._a5?this.stopAutoPlay():
102this.startAutoPlay()},startAutoPlay:function(){this._a5=!0;this.currSlide.isLoaded&&this._b5()},stopAutoPlay:function(){this._e5=this._f5=this._c5=this._a5=!1;this._d5()},_b5:function(){var a=this;a._f5||a._e5||(a._g5=!0,a._h5&&clearTimeout(a._h5),a._h5=setTimeout(function(){var b;a._z||a.st.loopRewind||(b=!0,a.st.loopRewind=!0);a.next(!0);b&&(a.st.loopRewind=!1)},a.currSlide.customDelay?a.currSlide.customDelay:a.st.autoPlay.delay))},_d5:function(){this._f5||this._e5||(this._g5=!1,this._h5&&(clearTimeout(this._h5),
103this._h5=null))}});b.rsModules.autoplay=b.rsProto._x4})(jQuery);
104// jquery.rs.video v1.1.3
105(function(f){f.extend(f.rsProto,{_z6:function(){var a=this;a._a7={autoHideArrows:!0,autoHideControlNav:!1,autoHideBlocks:!1,autoHideCaption:!1,disableCSS3inFF:!0,youTubeCode:'<iframe src="https://www.youtube.com/embed/%id%?rel=1&showinfo=0&autoplay=1&wmode=transparent" frameborder="no"></iframe>',vimeoCode:'<iframe src="https://player.vimeo.com/video/%id%?byline=0&portrait=0&autoplay=1" frameborder="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'};a.st.video=f.extend({},a._a7,
106a.st.video);a.ev.on("rsBeforeSizeSet",function(){a._b7&&setTimeout(function(){var b=a._r1,b=b.hasClass("rsVideoContainer")?b:b.find(".rsVideoContainer");
106a._c7&&a._c7.css({width:b.width(),height:b.height()})},32)});var d=a._a.mozilla;a.ev.on("rsAfterParseNode",function(b,c,e){b=f(c);if(e.videoURL){a.st.video.disableCSS3inFF&&d&&(a._e=a._f=!1);c=f('<div class="rsVideoContainer"></div>');var g=f('<div class="rsBtnCenterer"><div class="rsPlayBtn"><div class="rsPlayBtnIcon"></div></div></div>');b.hasClass("rsImg")?
107e.content=c.append(b).append(g):e.content.find(".rsImg").wrap(c).after(g)}});a.ev.on("rsAfterSlideChange",function(){a.stopVideo()})},toggleVideo:function(){return this._b7?this.stopVideo():this.playVideo()},playVideo:function(){var a=this;if(!a._b7){var d=a.currSlide;if(!d.videoURL)return!1;a._d7=d;var b=a._e7=d.content,d=d.videoURL,c,e;d.match(/youtu\.be/i)||d.match(/youtube\.com/i)?(e=/^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/,(e=d.match(e))&&11==e[2].length&&
108(c=e[2]),void 0!==c&&(a._c7=a.st.video.youTubeCode.replace("%id%",c))):d.match(/vimeo\.com/i)&&(e=/(www\.)?vimeo.com\/(\d+)($|\/)/,(e=d.match(e))&&(c=e[2]),void 0!==c&&(a._c7=a.st.video.vimeoCode.replace("%id%",c)));a.videoObj=f(a._c7);a.ev.trigger("rsOnCreateVideoElement",[d]);a.videoObj.length&&(a._c7=f('<div class="rsVideoFrameHolder"><div class="rsPreloader"></div><div class="rsCloseVideoBtn"><div class="rsCloseVideoIcn"></div></div></div>'),a._c7.find(".rsPreloader").after(a.videoObj),b=b.hasClass("rsVideoContainer")?
109b:b.find(".rsVideoContainer"),a._c7.css({width:b.width(),height:b.height()}).find(".rsCloseVideoBtn").off("click.rsv").on("click.rsv",function(b){a.stopVideo();b.preventDefault();b.stopPropagation();return!1}),b.append(a._c7),a.isIPAD&&b.addClass("rsIOSVideo"),a._f7(!1),setTimeout(function(){a._c7.addClass("rsVideoActive")},10),a.ev.trigger("rsVideoPlay"),a._b7=!0);return!0}return!1},stopVideo:function(){var a=this;return a._b7?(a.isIPAD&&a.slider.find(".rsCloseVideoBtn").remove(),a._f7(!0),setTimeout(function(){a.ev.trigger("rsOnDestroyVideoElement",
110[a.videoObj]);var d=a._c7.find("iframe");if(d.length)try{d.attr("src","")}catch(b){}a._c7.remove();a._c7=null},16),a.ev.trigger("rsVideoStop"),a._b7=!1,!0):!1},_f7:function(a,d){var b=[],c=this.st.video;c.autoHideArrows&&(this._c2&&(b.push(this._c2,this._d2),this._e2=!a),this._v5&&b.push(this._v5));c.autoHideControlNav&&this._k5&&b.push(this._k5);c.autoHideBlocks&&this._d7.animBlocks&&b.push(this._d7.animBlocks);c.autoHideCaption&&this.globalCaption&&b.push(this.globalCaption);this.slider[a?"removeClass":
111"addClass"]("rsVideoPlaying");if(b.length)for(c=0;c<b.length;c++)a?b[c].removeClass("rsHidden"):b[c].addClass("rsHidden")}});f.rsModules.video=f.rsProto._z6})(jQuery);// jquery.rs.animated-blocks v1.0.7
112(function(l){l.extend(l.rsProto,{_p4:function(){function m(){var g=a.currSlide;if(a.currSlide&&a.currSlide.isLoaded&&a._t4!==g){if(0<a._s4.length){for(b=0;b<a._s4.length;b++)clearTimeout(a._s4[b]);a._s4=[]}if(0<a._r4.length){var f;for(b=0;b<a._r4.length;b++)if(f=a._r4[b])a._e?(f.block.css(a._g+a._u1,"0s"),f.block.css(f.css)):f.block.stop(!0).css(f.css),a._t4=null,g.animBlocksDisplayed=!1;a._r4=[]}g.animBlocks&&(g.animBlocksDisplayed=!0,a._t4=g,a._u4(g.animBlocks))}}var a=this,b;a._q4={fadeEffect:!0,
113moveEffect:"top",moveOffset:20,speed:400,easing:"easeOutSine",delay:200};a.st.block=l.extend({},a._q4,a.st.block);a._r4=[];a._s4=[];a.ev.on("rsAfterInit",function(){m()});a.ev.on("rsBeforeParseNode",function(a,b,d){b=l(b);d.animBlocks=b.find(".rsABlock").css("display","none");d.animBlocks.length||(b.hasClass("rsABlock")?d.animBlocks=b.css("display","none"):d.animBlocks=!1)});a.ev.on("rsAfterContentSet",function(b,f){f.id===a.slides[a.currSlideId].id&&setTimeout(function(){m()},a.st.fadeinLoadedSlide?
114300:0)});a.ev.on("rsAfterSlideChange",function(){m()})},_v4:function(l,a){setTimeout(function(){l.css(a)},6)},_u4:function(m){var a=this,b,g,f,d,h,e,n;a._s4=[];m.each(function(m){b=l(this);g={};f={};d=null;var c=b.attr("data-move-offset"),c=c?parseInt(c,10):a.st.block.moveOffset;if(0<c&&((e=b.data("move-effect"))?(e=e.toLowerCase(),"none"===e?e=!1:"left"!==e&&"top"!==e&&"bottom"!==e&&"right"!==e&&(e=a.st.block.moveEffect,"none"===e&&(e=!1))):e=a.st.block.moveEffect,e&&"none"!==e)){var p;p="right"===
115e||"left"===e?!0:!1;var k;n=!1;a._e?(k=0,h=a._x1):(p?isNaN(parseInt(b.css("right"),10))?h="left":(h="right",n=!0):isNaN(parseInt(b.css("bottom"),10))?h="top":(h="bottom",n=!0),h="margin-"+h,n&&(c=-c),a._e?k=parseInt(b.css(h),10):(k=b.data("rs-start-move-prop"),void 0===k&&(k=parseInt(b.css(h),10),isNaN(k)&&(k=0),b.data("rs-start-move-prop",k))));f[h]=a._m4("top"===e||"left"===e?k-c:k+c,p);g[h]=a._m4(k,p)}c=b.attr("data-fade-effect");if(!c)c=a.st.block.fadeEffect;else if("none"===c.toLowerCase()||
116"false"===c.toLowerCase())c=!1;c&&(f.opacity=0,g.opacity=1);if(c||e)d={},d.hasFade=Boolean(c),Boolean(e)&&(d.moveProp=h,d.hasMove=!0),d.speed=b.data("speed"),isNaN(d.speed)&&(d.speed=a.st.block.speed),d.easing=b.data("easing"),d.easing||(d.easing=a.st.block.easing),d.css3Easing=l.rsCSS3Easing[d.easing],d.delay=b.data("delay"),isNaN(d.delay)&&(d.delay=a.st.block.delay*m);c={};a._e&&(c[a._g+a._u1]="0ms");c.moveProp=g.moveProp;c.opacity=g.opacity;c.display="none";a._r4.push({block:b,css:c});a._v4(b,
117f);a._s4.push(setTimeout(function(b,d,c,e){return function(){b.css("display","block");if(c){var g={};if(a._e){var f="";c.hasMove&&(f+=c.moveProp);c.hasFade&&(c.hasMove&&(f+=", "),f+="opacity");g[a._g+a._t1]=f;g[a._g+a._u1]=c.speed+"ms";g[a._g+a._v1]=c.css3Easing;b.css(g);setTimeout(function(){b.css(d)},24)}else setTimeout(function(){b.animate(d,c.speed,c.easing)},16)}delete a._s4[e]}}(b,g,d,m),6>=d.delay?12:d.delay))})}});l.rsModules.animatedBlocks=l.rsProto._p4})(jQuery);
118// jquery.rs.auto-height v1.0.3
119(function(b){b.extend(b.rsProto,{_w4:function(){var a=this;if(a.st.autoHeight){var b,c,e,f=!0,d=function(d){e=a.slides[a.currSlideId];(b=e.holder)&&(c=b.height())&&void 0!==c&&c>(a.st.minAutoHeight||30)&&(a._c4=c,a._e||!d?a._e1.css("height",c):a._e1.stop(!0,!0).animate({height:c},a.st.transitionSpeed),a.ev.trigger("rsAutoHeightChange",c),f&&(a._e&&setTimeout(function(){a._e1.css(a._g+"transition","height "+a.st.transitionSpeed+"ms ease-in-out")},16),f=!1))};a.ev.on("rsMaybeSizeReady.rsAutoHeight",
120function(a,b){e===b&&d()});a.ev.on("rsAfterContentSet.rsAutoHeight",function(a,b){e===b&&d()});a.slider.addClass("rsAutoHeight");a.ev.one("rsAfterInit",function(){setTimeout(function(){d(!1);setTimeout(function(){a.slider.append('<div style="clear:both; float: none;"></div>')},16)},16)});a.ev.on("rsBeforeAnimStart",function(){d(!0)});a.ev.on("rsBeforeSizeSet",function(){setTimeout(function(){d(!1)},16)})}}});b.rsModules.autoHeight=b.rsProto._w4})(jQuery);
121// jquery.rs.global-caption v1.0.1
122(function(b){b.extend(b.rsProto,{_d6:function(){var a=this;a.st.globalCaption&&(a.ev.on("rsAfterInit",function(){a.globalCaption=b('<div class="rsGCaption"></div>').appendTo(a.st.globalCaptionInside?a._e1:a.slider);a.globalCaption.html(a.currSlide.caption||"")}),a.ev.on("rsBeforeAnimStart",function(){a.globalCaption.html(a.currSlide.caption||"")}))}});b.rsModules.globalCaption=b.rsProto._d6})(jQuery);
123// jquery.rs.active-class v1.0.1
124(function(c){c.rsProto._o4=function(){var b,a=this;if(a.st.addActiveClass)a.ev.on("rsOnUpdateNav",function(){b&&clearTimeout(b);b=setTimeout(function(){a._g4&&a._g4.removeClass("rsActiveSlide");a._r1&&a._r1.addClass("rsActiveSlide");b=null},50)})};c.rsModules.activeClass=c.rsProto._o4})(jQuery);
125// jquery.rs.deeplinking v1.0.6 + jQuery hashchange plugin v1.3 Copyright (c) 2010 Ben Alman
126(function(b){b.extend(b.rsProto,{_o5:function(){var a=this,h,d,f;a._p5={enabled:!1,change:!1,prefix:""};a.st.deeplinking=b.extend({},a._p5,a.st.deeplinking);if(a.st.deeplinking.enabled){var g=a.st.deeplinking.change,e=a.st.deeplinking.prefix,c="#"+e,k=function(){var a=window.location.hash;return a&&0<a.indexOf(e)&&(a=parseInt(a.substring(c.length),10),0<=a)?a-1:-1},p=k();-1!==p&&(a.st.startSlideId=p);g&&(b(window).on("hashchange"+a.ns,function(b){h||(b=k(),0>b||(b>a.numSlides-1&&(b=a.numSlides-1),
127a.goTo(b)))}),a.ev.on("rsBeforeAnimStart",function(){d&&clearTimeout(d);f&&clearTimeout(f)}),a.ev.on("rsAfterSlideChange",function(){d&&clearTimeout(d);f&&clearTimeout(f);f=setTimeout(function(){h=!0;window.location.replace((""+window.location).split("#")[0]+c+(a.currSlideId+1));d=setTimeout(function(){h=!1;d=null},60)},400)}));a.ev.on("rsBeforeDestroy",function(){d=f=null;g&&b(window).off("hashchange"+a.ns)})}}});b.rsModules.deeplinking=b.rsProto._o5})(jQuery);
128(function(b,a,h){function d(a){a=a||location.href;return"#"+a.replace(/^[^#]*#?(.*)$/,"$1")}"$:nomunge";var f=document,g,e=b.event.special,c=f.documentMode,k="onhashchange"in a&&(c===h||7<c);b.fn.hashchange=function(a){return a?this.bind("hashchange",a):this.trigger("hashchange")};b.fn.hashchange.delay=50;e.hashchange=b.extend(e.hashchange,{setup:function(){if(k)return!1;b(g.start)},teardown:function(){if(k)return!1;b(g.stop)}});g=function(){function g(){var f=d(),e=q(l);f!==l?(m(l=f,e),b(a).trigger("hashchange")):
129e!==l&&(location.href=location.href.replace(/#.*/,"")+e);c=setTimeout(g,b.fn.hashchange.delay)}var e={},c,l=d(),n=function(a){return a},m=n,q=n;e.start=function(){c||g()};e.stop=function(){c&&clearTimeout(c);c=h};a.attachEvent&&!a.addEventListener&&!k&&function(){var a,c;e.start=function(){a||(c=(c=b.fn.hashchange.src)&&c+d(),a=b('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){c||m(d());g()}).attr("src",c||"javascript:0").insertAfter("body")[0].contentWindow,f.onpropertychange=
130function(){try{"title"===event.propertyName&&(a.document.title=f.title)}catch(b){}})};e.stop=n;q=function(){return d(a.location.href)};m=function(c,e){var d=a.document,g=b.fn.hashchange.domain;c!==e&&(d.title=f.title,d.open(),g&&d.write('<script>document.domain="'+g+'"\x3c/script>'),d.close(),a.location.hash=c)}}();return e}()})(jQuery,this);
131// jquery.rs.visible-nearby v1.0.2
132(function(d){d.rsProto._g7=function(){var a=this;a.st.visibleNearby&&a.st.visibleNearby.enabled&&(a._h7={enabled:!0,centerArea:.6,center:!0,breakpoint:0,breakpointCenterArea:.8,hiddenOverflow:!0,navigateByCenterClick:!1},a.st.visibleNearby=d.extend({},a._h7,a.st.visibleNearby),a.ev.one("rsAfterPropsSetup",function(){a._i7=a._e1.css("overflow","visible").wrap('<div class="rsVisibleNearbyWrap"></div>').parent();a.st.visibleNearby.hiddenOverflow||a._i7.css("overflow","visible");a._o1=a.st.controlsInside?
133a._i7:a.slider}),a.ev.on("rsAfterSizePropSet",function(){var b,c=a.st.visibleNearby;b=c.breakpoint&&a.width<c.breakpoint?c.breakpointCenterArea:c.centerArea;a._h?(a._b4*=b,a._i7.css({height:a._c4,width:a._b4/b}),a._d=a._b4*(1-b)/2/b):(a._c4*=b,a._i7.css({height:a._c4/b,width:a._b4}),a._d=a._c4*(1-b)/2/b);c.navigateByCenterClick||(a._q=a._h?a._b4:a._c4);c.center&&a._e1.css("margin-"+(a._h?"left":"top"),a._d)}))};d.rsModules.visibleNearby=d.rsProto._g7})(jQuery);
134;
135(function (factory) {
136    // Module systems magic dance.
137
138    if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
139        // CommonJS or Node: hard-coded dependency on "knockout"
140        factory(require("knockout"));
141    } else if (typeof define === "function" && define["amd"]) {
142        // AMD anonymous module with hard-coded dependency on "knockout"
143        define(["knockout"], factory);
144    } else {
145        // <script> tag: use the global `ko` object, attaching a `mapping` property
146        factory(ko);
147    }
148}
149(function (ko) {	
150	ko.bindingHandlers.files = {
151		init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
152			var allBindings = allBindingsAccessor();
153			var loadedCallback, progressCallback, errorCallback, hoverClass, allowDrop, fileFilter, readAs, maxFileSize;
154			var filesBinding = allBindings.files;
155			
156			if (typeof(ko.unwrap(filesBinding)) == "function")
157			{ loadedCallback = ko.unwrap(filesBinding); }
158			else
159			{ 
160				loadedCallback = ko.unwrap(filesBinding.onLoaded); 
161				progressCallback = ko.unwrap(filesBinding.onProgress);
162				errorCallback = ko.unwrap(filesBinding.onError);
163				allowDrop = ko.unwrap(filesBinding.allowDrop);
164				hoverClass = ko.unwrap(filesBinding.hoverClass);
165				fileFilter = ko.unwrap(filesBinding.fileFilter);
166				maxFileSize = ko.unwrap(filesBinding.maxFileSize);
167				readAs = ko.unwrap(filesBinding.readAs);
168			}
169			
170			if(typeof(loadedCallback) != "function")
171			{ return; }
172
173			var readFile = function(file) {
174				var reader = new FileReader();
175				reader.onload = function(fileLoadedEvent) {
176					loadedCallback(file, fileLoadedEvent.target.result);
177				};
178				
179				if(typeof(progressCallback) == "function")
180				{
181					reader.onprogress = function(fileProgressEvent) {
182						progressCallback(file, fileProgressEvent.loaded, fileProgressEvent.total);
183					};
184				}
185
186				if(typeof(errorCallback) == "function")
187				{
188					reader.onerror = function(fileErrorEvent) {
189						errorCallback(file, fileErrorEvent.target.error);
190					};
191				}
192
193				if(readAs == "text")
194				{ reader.readAsText(file); }
195				else if(readAs == "array")
196				{ reader.readAsArrayBuffer(file); }
197				else if(readAs == "binary")
198				{ reader.readAsBinaryString(file); }
199				else
200				{ reader.readAsDataURL(file); }
201			};
202
203			var handleFileDrag = function(fileDragEvent) {
204				fileDragEvent.stopPropagation();
205				fileDragEvent.preventDefault();
206				
207				if(fileDragEvent.type == "dragover")
208				{ fileDragEvent.target.classList.add(hoverClass); }
209				else
210				{ fileDragEvent.target.classList.remove(hoverClass); }
211			};
212			
213			var handleDrop = function(fileDropEvent) {
214				handleFileDrag(fileDropEvent);
215				handleFileSelected(fileDropEvent);
216			}
217			
218			var handleFileSelected = function(fileSelectionEvent) {
219				var files = fileSelectionEvent.target.files || fileSelectionEvent.dataTransfer.files;
220				for (var i = 0, f; f = files[i]; i++) { 
221					if (typeof(fileFilter) != "undefined" && !f.type.match(fileFilter)) 
222					{
223						if(typeof(errorCallback) == "function")
224						{ errorCallback(f, "File type does not match filter"); }				
225						continue; 
226					}
227					
228					if(typeof(maxFileSize) != "undefined" && f.size >= maxFileSize)
229					{ 
230						if(typeof(errorCallback) == "function")
231						{ errorCallback(f, "File exceeds file size limit"); }
232						continue; 
233					}
234
235					readFile(f);
236				}
237			};
238
239			if (!document.addEventListener) {
240				return; //IE8 won't work with addEventListener, avoid JS error
241			}
242
243			element.addEventListener('change', handleFileSelected, false);
244
245			if(allowDrop) {
246				element.addEventListener('dragover', handleFileDrag, false);
247				element.addEventListener('dragleave', handleFileDrag, false);
248				element.addEventListener('drop', handleDrop, false);
249			}
250		}
251	};
252}));
253;
254var mcWeb = (mcWeb || {});
255
256mcWeb.responsive = (function ($) {
257    'use strict';
258
259    var screenSize = null;
260
261    function getScreenSize() {
262        if (isLG())
263            return 'lg';
264        else if (isMD())
265            return 'md';
266        else if (isSM())
267            return 'sm';
268        else return 'xs';
269    }
270
271    function getScreenSizePixels() {
272        if (isUHD())
273            return 3840;
274        else if (isQHD())
275            return 2560;
276        else if (isFHD())
277            return 1920;
278        else if (isXL())
279            return 1440;
280        else if (isLG())
281            return 1200;
282        else if (isMD())
283            return 992;
284        else if (isSM())
285            return 768;
286        else return '640';
287    }
288    function useMobileMenu(size) {
289        var screenSize = getScreenSize();
290
291        var result = false;
292        if (size == 'lg')
293            result = (screenSize == 'lg' || screenSize == 'md' || screenSize == 'sm' || screenSize == 'xs');
294        else if (size == 'md')
295            result = (screenSize == 'md' || screenSize == 'sm' || screenSize == 'xs');
296        else if (size == 'sm')
297            result = (screenSize == 'sm' || screenSize == 'xs');
298        else if (size == 'xs')
299            result = (screenSize == 'xs');
300
301        return result;
302    }
303
304    function isXS() {
305        return !isSM() && !isMD() && !isLG() && !isXL() && !isFHD() && !isQHD() && !isUHD();
306    }
307    function isSM() {
308        try {
309            return window.matchMedia("(min-width: 768px)").matches;
310        } catch (e) { }
311        return false;
312    }
313
314    function isMD() {
315        try {
316            return window.matchMedia("(min-width: 992px)").matches;
317        } catch (e) { }
318        return false;
319    }
320
321    function isLG() {
322        try {
323            return window.matchMedia("(min-width: 1200px)").matches;
324        } catch (e) { }
325        return false;
326    }
327
328    function isXL() {
329        try {
330            return window.matchMedia("(min-width: 1400px)").matches;
331        } catch (e) { }
332        return false;
333    }
334
335    function isFHD() {
336        try {
337            return window.matchMedia("(min-width: 1880px)").matches;
338        } catch (e) { }
339        return false;
340    }
341
342    function isQHD() {
343        try {
344            return window.matchMedia("(min-width: 2520px)").matches;
345        } catch (e) { }
346        return false;
347    }
348    function isUHD() {
349        try {
350            return window.matchMedia("(min-width: 3800px)").matches;
351        } catch (e) { }
352        return false;
353    }
354
355    function reloadSize(size) {
356        var productListService = new WebApiService("Responsive");
357        var data = {
358            size: size
359        }
360        var actionName = "SetScreenSize";
361
362        productListService.GetAction(actionName, data)
363            .then(function (result) {
364	            if (result && result.length) {
365	                if (result === "[RELOAD]")
366	                    window.location.reload(true);
367	            } else {
368	                window.location.reload(true);
369	            }
370	        });
371    }
372
373    function setSizeAsSet(correct) {
374        var productListService = new WebApiService("Responsive");
375        var data = { matched: correct };
376        productListService.GetAction("SetScreenSizeMatched", data).
377		then(function (result) {
378		    if (result && result.length && result === "true") {
379		        var el = $('#d-size');
380		        if (el !== undefined) {
381		            el.data('size-set', true);
382		        }
383		    }
384		});
385    }
386
387    function onResize(el, callback) {
388        var newSize = getScreenSize();
389
390        if (newSize !== screenSize) {
391            screenSize = newSize;
392            reloadSize(newSize);
393        }
394    }
395
396    function setupResponsiveDesign() {
397        $(function () {
398            screenSize = getScreenSize();
399
400            var el = $('#d-size');
401            if (el !== undefined) {
402                var size = el.data('size');
403                if (size != undefined && size.length > 0) {
404                    if (size != screenSize) {
405                        reloadSize(screenSize);
406                    } else {
407                        var sizeSet = el.data('size-set');
408                        if (sizeSet === "False") {
409                            //size not stored as "set" yet, but size from session matched actual size, so we update it once as "set"
410                            setSizeAsSet(true);
411                        }
412                    }
413                }
414            }
415        });
416        var resizeTimer;
417        $(window).on('resize', function (el, callback) {
418            if (resizeTimer) {
419                clearTimeout(resizeTimer);
420            }
421            resizeTimer = setTimeout(function () {
422                onResize(el, callback);
423                resizeTimer = null;
424            }, 200);
425        });
426
427    }
428
429    setupResponsiveDesign();
430
431    return {
432        setupResponsiveDesign: setupResponsiveDesign,
433        getScreenSize: getScreenSize,
434        getScreenSizePixels: getScreenSizePixels,
435        isExtraSmall: isXS,
436        isSmall: isSM,
437        isMedium: isMD,
438        isLarge: isLG,
439        useMobileMenu: useMobileMenu
440    };
441
442})(jQuery);
443;
444mcSlide = new function () {
445    var isSwiperActive = false;
446    this.isSwipeTouched = function () {
447        return isSwiperActive;
448    };
449
450    this.removeInnerSlide = function (outerSlide) {
451
452        var rs = outerSlide.find(".royalSlider");
453
454        if (rs.length > 0) { //loop for inner slides
455
456            outerSlide.append("<div class=\"slide-tmp\"> </div>");
457
458            // ReSharper disable once UnknownCssClass
459            var slidetmp = outerSlide.children(".slide-tmp");
460
461            for (var x = 0; x < rs.length; x++) {
462                rs.children().appendTo(slidetmp);
463            }
464
465            var removeItem = outerSlide.children();
466            for (var i = 0; i < removeItem.length; i++) {
467
468                var el = jQuery(removeItem[i]);
469                // ReSharper disable once UnknownCssClass
470                var value = el.hasClass("slide-tmp");
471                var value2 = el.hasClass("rsNav rsBullets");
472
473                if (value == false && value2 == false)
474                    el.remove();
475            }
476
477            // ReSharper disable once UnknownCssClass
478            var temp = outerSlide.children(".slide-tmp").children();
479            temp.unwrap();
480        }
481
482    };
483
484    this.InitSlideshow = function (identifier, play, pause, hoverPause, arrowsNav, generatePagination, arrowsNavAutoHide, fadeSpeed, slideSpeed, effect, crossfade, orientation, scaleType, randomize, css, isMobile, width, height, autostart) {
485
486        var touch = (isMobile == true && orientation == "vertical") ? false : true;
487        effect = (effect == "slide") ? "move" : effect; //Fix for old slider
488        var slideEl = jQuery('#' + identifier);
489        var slide = slideEl.find(".royalSlider").first();
490        if (slide.length < 1)
491            return; //Not found
492
493        var controlNav = (slide.children().length > 1 && generatePagination) ? "bullets" : "none";
494
495        //Remove inner slide
496        this.removeInnerSlide(slide);
497
498        //No change to width og height
499        //Try to calculate width and height		
500        if (isMobile == false && width == 800 && height == 400) {
501
502            var row = slide;
503            var field = row.find(".WebPubFieldRow").first();
504
505            if (field.length > 0) {
506                height = field.height();
507                width = field.width();
508            }
509        } else if (isMobile == true) {
510
511            var minHeight = 0;
512            var tmp = 0;
513            var item = slide.find(".WebPubElement");
514            item.each(function () {
515                tmp = $(this).height();
516                if (minHeight < tmp)
517                    minHeight = tmp;
518            });
519
520            item.each(function () {
521                $(this).height(minHeight);
522            });
523
524            if (minHeight > 0) {
525                height = minHeight;
526                var annonse = slide.find(".sm-jqm");
527                if (annonse.length > 0) {
528                    height += 20;
529                }
530
531                width = Math.abs(window.orientation) === 90 ? $(window).height() : $(window).width();
532            }
533        }
534
535       return runSlide(slide, slideEl, touch, play, pause, hoverPause, arrowsNav, controlNav, arrowsNavAutoHide, fadeSpeed, slideSpeed, effect, crossfade, orientation, scaleType, randomize, css, isMobile, width, height, autostart);
536    }
537
538    var runSlide = function (slide, slideEl, touch, play, pause, hoverPause, arrowsNav, controlNav, arrowsNavAutoHide, fadeSpeed, slideSpeed, effect, crossfade, orientation, scaleType, randomize, css, isMobile, width, height, autostart) {
539
540        //Add css class to slide
541        if (css.length > 0)
542            slide.addClass(css);
543
544        var rs = slide.royalSlider({
545            sliderTouch: touch,
546            sliderDrag: touch,
547
548            autoScaleSlider: true,
549            autoScaleSliderWidth: width,
550            autoScaleSliderHeight: height,
551
552            controlNavigation: controlNav,
553            arrowsNav: arrowsNav,
554            arrowsNavAutoHide: arrowsNavAutoHide,
555            controlNavigationSpacing: 0,
556
557            loop: true,
558            numImagesToPreload: 10,
559            usePreloader: false,
560            keyboardNavEnabled: false,
561            navigateByClick: false,
562
563            transitionType: effect,
564            transitionSpeed: slideSpeed,
565            slidesOrientation: orientation,
566            randomizeSlides: randomize,
567            imageScalePadding: 5,
568
569            autoPlay: {
570                // autoplay options go gere
571                enabled: autostart,
572                pauseOnHover: hoverPause,
573                stopAtAction: false,
574                delay: play//slideSpeed
575            }
576        }).data('royalSlider');
577
578
579
580        setTimeout(function () {
581            var field = slide.find(".WebPubFieldRow").first();
582
583            if (field.length > 0) {
584                rs.width = 0;
585                rs.st.autoScaleSliderHeight = field.height();
586                rs.st.autoScaleSliderWidth = field.width();
587            }
588
589            rs.updateSliderSize(true);
590        }, 1000);
591
592        // mouse/touch drag start
593        rs.ev.on('rsDragStart', function () {
594            isSwiperActive = true;
595        });
596
597        // mouse/touch drag end
598        rs.ev.on('rsDragRelease', function () {
599            setTimeout(function () { isSwiperActive = false; }, 100);
600        });
601
602        rs.ev.on('rsAfterContentSet', function (e, slideObject) {
603            // fires when every time when slide content is loaded and added to DOM
604            var fieldId = jQuery(slideObject.content[0]).find(".WebPubElement").data('fieldid');
605            if (fieldId !== undefined) {
606                PubSub.publish("AjaxRenderingEngine.onPriceRefreshRequested", { Target: "div.ajax-field[data-field-id=" + fieldId+"]" });
607            }
608            else {
609                PubSub.publish("AjaxRenderingEngine.onPriceRefreshRequested", null);
610            }
611            
612            let clientX = 0;
613            const maxMovementToCountAsClicked = 6
614            jQuery(slideObject.content).find('.ArticleWithBackground').each(function (index, element) {
615                if (!!jQuery(element).data('link') && jQuery(element).data('link').length > 0) {
616                    jQuery(element).mousedown(function (e) {
617                        clientX = e.clientX;
618                    })
619                    jQuery(element).mouseup(function (e) {
620                        if (e.which !== 1) return;
621                        const moved = Math.abs(clientX - e.clientX);
622                        if (moved < maxMovementToCountAsClicked) {
623                            document.location = decodeURIComponent(jQuery(element).data('link'));
624                        }
625                    })
626                }
627            });
628        });
629        slideEl.addClass("Show");
630
631        if (isMobile == false) {
632            slide.parent().append(slide.find('.rsNav'));
633        }
634
635        return rs;
636    };
637};;
638/**
639 * Global handler for shop startup state
640 * Handles jQuery.load() calls during shop startup
641 * Note: WebApiService has its own built-in startup handling
642 */
643(function ($) {
644    'use strict';
645
646    // Magic marker for detecting startup page
647    var STARTUP_PAGE_MARKER = 'SHOP_STARTUP_PAGE_MARKER_DO_NOT_REMOVE';
648
649    // Store original jQuery.load
650    var originalLoad = $.fn.load;
651
652    /**
653     * Check if response is the startup page (fast single check)
654     */
655    function isStartupPage(html) {
656        if (!html || typeof html !== 'string') {
657            return false;
658        }
659        // Single fast check for magic marker
660        return html.indexOf(STARTUP_PAGE_MARKER) > -1;
661    }
662
663    /**
664     * Poll startup status until shop is ready
665     */
666    function waitForShopReady() {
667        return new Promise(function (resolve, reject) {
668            var maxAttempts = 100; // 100 * 3 seconds = 5 minutes
669            var attempt = 0;
670
671            function checkStatus() {
672                attempt++;
673
674                if (attempt > maxAttempts) {
675                    reject(new Error('Timeout waiting for shop startup'));
676                    return;
677                }
678
679                $.ajax({
680                    url: '/api-no-session/startup/status',
681                    method: 'GET',
682                    cache: false,
683                    dataType: 'json',
684                    timeout: 5000
685                })
686                    .done(function (data) {
687                        if (data && data.startupSucceeded === true) {
688                            resolve();
689                        } else {
690                            // Not ready yet, try again
691                            setTimeout(checkStatus, 3000);
692                        }
693                    })
694                    .fail(function () {
695                        // API call failed, try again
696                        setTimeout(checkStatus, 3000);
697                    });
698            }
699
700            checkStatus();
701        });
702    }
703
704    // ============================================
705    // Override jQuery.load()
706    // ============================================
707    $.fn.load = function (url, params, callback) {
708        var $this = this;
709        var args = arguments;
710
711        // Separate params and callback (jQuery.load has flexible params)
712        if (typeof params === 'function') {
713            callback = params;
714            params = undefined;
715        }
716
717        // Create wrapper callback that checks for startup page
718        var wrappedCallback = function (responseText, textStatus, jqXHR) {
719            // Check if we got the startup page instead of expected content
720            if (isStartupPage(responseText)) {
721                console.log('Shop is starting, waiting before retrying:', url);
722
723                // Show loading indicator in the target element
724                $this.html(
725                    '<div style="text-align:center;padding:40px;">' +
726                    '<div class="spinner" style="margin:0 auto;border:4px solid #f3f3f3;border-top:4px solid #3498db;border-radius:50%;width:40px;height:40px;animation:spin 1s linear infinite;"></div>' +
727                    '<p style="margin-top:20px;">Butikken starter, vennligst vent...</p>' +
728                    '</div>'
729                );
730
731                // Wait for shop to be ready, then retry
732                waitForShopReady().then(function () {
733                    console.log('Shop ready, retrying load:', url);
734                    // Retry the original load call
735                    originalLoad.apply($this, args);
736                }).catch(function (error) {
737                    console.error('Timeout waiting for shop:', error);
738                    $this.html(
739                        '<div style="text-align:center;padding:40px;color:red;">' +
740                        '<p>Oppstart tok for lang tid. Vennligst oppdater siden.</p>' +
741                        '</div>'
742                    );
743                });
744
745                return; // Don't call original callback
746            }
747
748            // Normal response - call original callback if provided
749            if (callback) {
750                callback.call($this, responseText, textStatus, jqXHR);
751            }
752        };
753
754        // Call original load with our wrapped callback
755        return originalLoad.call(this, url, params, wrappedCallback);
756    };
757
758    // Add global AJAX error handler for startup detection
759    $(document).ajaxComplete(function (event, jqXHR, settings) {
760        // Check if we got HTML when expecting JSON/other content
761        var contentType = jqXHR.getResponseHeader('Content-Type');
762        if (contentType && contentType.indexOf('text/html') > -1) {
763            var responseText = jqXHR.responseText;
764            if (isStartupPage(responseText)) {
765                console.warn('Detected startup page in AJAX response for:', settings.url);
766                $(document).trigger('shop-starting-detected', { url: settings.url });
767            }
768        }
769    });
770
771    // Expose utilities globally for debugging
772    window.startupHandler = {
773        isStartupPage: isStartupPage,
774        waitForShopReady: waitForShopReady
775    };
776
777})(jQuery);;
778mcWeb.hash = new function () {
779    var $ = jQuery;
780    var self = this;
781    self.isLightboxReady = false;
782
783    self.init = function () {
784        $(document).on("lightboxReady", function () {
785            if (self.isLightboxReady) {
786                return;
787            }
788
789            self.isLightboxReady = true;
790
791            $(window).on('hashchange', function () {
792                loadSwitch();
793            });
794            loadSwitch();
795
796        });
797
798        setTimeout(function () {
799            if (!self.isLightboxReady) {
800                $(document).trigger("lightboxReady"); //If not run, extra backup!
801            }
802        }, 400);
803    };
804
805    var loadSwitch = function () {
806
807        switch (window.location.hash.toLowerCase()) {
808
809            case "#login":
810                mcWeb.login.load();
811                break;
812            case "#closedlogin":
813                mcWeb.login.loadClosedLogin();
814                break;
815            case "#logout":
816                mcWeb.login.logout();
817                break;
818            case "#password":
819                mcWeb.loginPassword.load();
820                break;
821            case "#logincontact":
822                mcWeb.loginContacts.load();
823                break;
824            case "#loginagent":
825              mcWeb.loginAgent.load();
826              break;
827            case "#productvariantmatrix":
828                getLibrary("variantmatrix").then(function () {
829                    mcWeb.productVariantMatrix.load();
830                });
831                
832                break;
833            case "#customerregistration":
834                getLibrary("mcWeb.customerRegistration").then(() => {
835                    mcWeb.customerRegistration.LoadView();
836                });
837                break;
838           
839            case "#skiassembly":
840                getLibrary("skiassembly").then(() => { 
841                    mcWeb.SkiAssembly.load();
842                });
843                break;
844            case "#skiattributeassembly":
845                getLibrary("skiattributeassembly").then(() => {
846                    mcWeb.SkiAttributeAssembly.load();
847                });
848                break;            
849
850
851        };// END Switch		
852    };//END LoadSwitch
853
854};
855
856
857;
858var mc = (mc || {});
859
860mc.format = new (function ($) {
861    'use strict';
862
863    var self = this;
864
865    //input value with decimal or dot as Number
866    //If value isNAN uses defaultValue or 1
867    self.asNumber = function (value, desimals, defaultValue) {
868        return Number(convertToDesimal(value, desimals, defaultValue));
869    };
870
871    //A number as Current Culture with decimal or dot
872    self.asCulture = function (value, desimals) {
873        try {
874            value = convertToDesimal(value, desimals).toLocaleStr
874ing();
875            return (whatDecimalSeparator() === '.') ? value.replace(',', '.') : value.replace('.', ',');
876        } catch (e) {
877            return "1";
878        }
879    };
880
881    self.roundToNearest = function (number, multiple, desimals) {
882        var n = Number(convertToDesimal(number, desimals));
883        var m = Number(convertToDesimal(multiple, desimals));
884        var d = Number(convertToDesimal(desimals, 0));
885
886        var r = rToNearest(n, m, d);
887        return r;
888    }
889
890    var convertToDesimal = function (value, desimals, defaultValue) {
891
892        try {
893            if (value != null) {
894                value = value.toString().replace(',', '.');
895            }
896            desimals = Number(desimals);
897            if (isNaN(desimals)) {
898                desimals = 0;
899            }
900            if (isNaN(value) || value.length < 1) {
901                value = (defaultValue != null) ? convertToDesimal(defaultValue, desimals, 1) : convertToDesimal(1, desimals);
902            }
903
904            var r = roundNumber(value, desimals);
905
906            var q = parseFloat(Math.round(r * 100) / 100).toFixed(desimals);
907            if (isNaN(q)) {
908                return self.asNumber(1, desimals);
909            }
910            return q;
911
912        } catch (e) {
913            return 1;
914        }
915    };
916
917    var whatDecimalSeparator = function () {
918        if (_MCDECIMAL_SEP !== undefined)//should be added to each page by McMaster
919            return _MCDECIMAL_SEP;
920
921        var n = 1.1;
922        n = n.toLocaleString().substring(1, 2);
923        return n;
924    }
925
926    var roundNumber = function (num, desimals) {
927        var number = Math.round(num * Math.pow(10, desimals)) / Math.pow(10, desimals);
928        if (num - number > 0) {
929            return (number + Math.floor(2 * Math.round((num - number) * Math.pow(10, (desimals + 1))) / 10) / Math.pow(10, desimals));
930        } else {
931            return number;
932        }
933    }
934
935    var rToNearest = function (number, multiple, desimals) {
936        var x = number * 100;
937        var y = multiple * 100;
938        var r = 1;
939
940        x = roundNumber(x, desimals);
941        y = roundNumber(y, desimals);
942
943        if (x == 0)
944            return 0;
945
946        if (x % y == 0) {
947            r = parseFloat(Math.floor(x / y)) * y;
948        } else {
949            r = (parseFloat(Math.floor(x / y)) * y) + y;
950        }
951
952        r = convertToDesimal((r / 100), desimals);
953        return r;
954    }
955
956
957
958})(jQuery);;
959mcWeb.lightbox = new function () {
960    var $ = jQuery;
961    var self = this;
962
963    self.events = {
964        onShowSpinicon: "mcWeb.lightbox.onShowSpinicon",
965        onHideSpinicon: "mcWeb.lightbox.onHideSpinicon",
966        onShowLightbox: "mcWeb.lightbox.onShowLightbox",
967        onHideLightbox: "mcWeb.lightbox.onHideLightbox",
968        modifyOptions: "mcWeb.lightbox.modifyOptions",
969        contentChanged: "mcWeb.lightbox.contentChanged"
970    };
971
972    var onClickCancelReigstration = false;
973
974    self.init = function () {
975
976        var popupCss = null;
977        PubSub.subscribe(mcWeb.lightbox.events.onShowLightbox, function (message, options) {
978            var popup = $('#center-popup');
979            var hasOptions = !!options;
980            var closeButton = popup.find('.lightbox-close');
981
982            if (hasOptions && options.keyboard === false)
983                closeButton.hide();
984            else
985                closeButton.show();
986
987            if (hasOptions){
988                if(options.css != null) {
989                    popupCss = options.css;
990                    popup.addClass(popupCss);
991                }
992            }
993            
994
995            if (!popup.is(':visible')) {
996                setTimeout(function () {
997                    popup.modal(hasOptions ? options : 'show');
998                    popup.show();
999
1000                    PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
1001
1002                    self.publishUpdateOfPublishedFieldEvent(options);
1003                    
1004
1005                }, 300); //Change from 1 to 300 (bug fix JQM)
1006            } else if (!hasOptions) {
1007                // Reset options to default
1008                var modal = popup.data('bs.modal');
1009                modal.options.backdrop = true;
1010                modal.options.keyboard = true;
1011                self.publishUpdateOfPublishedFieldEvent(options);
1012            }
1013            else if (options != undefined && options != null && options.variantData != undefined) {
1014                self.publishUpdateOfPublishedFieldEvent(options);
1015            }
1016            else if(options != undefined && options != null && options.callback != undefined && options.callback != null){
1017                options.callback();
1018            }
1019        });
1020
1021        PubSub.subscribe(mcWeb.lightbox.events.onHideLightbox, function () {
1022            var popup = $('#center-popup');
1023            if (popupCss !== null) {
1024                popup.removeClass(popupCss);
1025                popupCss = null;
1026                //popup.css("z-index", "");
1027            }
1028            if (popup.is(':visible')) {
1029                popup.modal('hide');
1030                popup.hide();
1031
1032                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
1033            }
1034
1035            if (hasEnableLoginCustReg()) {
1036                location.reload(true);
1037            }
1038            // Remember, event hide.bs.modal is emitted when popup.hide() is called. Theres an eventhandler further down.
1039        });
1040
1041        PubSub.subscribe(mcWeb.lightbox.events.onShowSpinicon, function () {
1042            $('.center-placeholder').addClass('refresh-data');
1043            $('#refresh-center').show();
1044        });
1045
1046        PubSub.subscribe(mcWeb.lightbox.events.onHideSpinicon, function () {
1047            $('.center-placeholder').removeClass('refresh-data');
1048            $('#refresh-center').hide();
1049        });
1050
1051        PubSub.subscribe(mcWeb.lightbox.events.contentChanged, function (message, options) {
1052            $('.modal:visible').each(self.centerLighBox).each(function (index, element) {
1053                
1054            });
1055        });
1056
1057        PubSub.subscribe(mcWeb.lightbox.events.modifyOptions, function (message, options) {
1058            var popup = $('#center-popup');
1059
1060            // Check if the modal is open
1061            if (!(popup.data('bs.modal') || {}).isShown)
1062                return;
1063
1064            var modal = popup.data('bs.modal');
1065
1066            if (options.backdrop) {
1067                if (options.backdrop === 'static')
1068                    modal.options.backdrop = 'static';
1069
1070                if (options.backdrop === true)
1071                    modal.options.backdrop = true;
1072
1073                if (options.backdrop === false)
1074                    modal.options.backdrop = false;
1075            }
1076
1077            if (options.keyboard) {
1078                if (options.keyboard === true)
1079                    modal.options.keyboard = true;
1080
1081                if (options.keyboard === false)
1082                    modal.options.keyboard = false;
1083            }
1084
1085            if (options.clearCss === true) {
1086                if (popupCss !== null) {
1087                    popup.removeClass(popupCss);
1088                    popupCss = null;
1089                    //popup.css("z-index", "");
1090                }
1091            }
1092            if (options.css != null) {
1093                popupCss = options.css;
1094                popup.addClass(popupCss);
1095            }
1096
1097        });
1098
1099        // Reposition when a modal is shown
1100        $('#center-popup').on('show.bs.modal', function () {
1101            $('#center-popup').each(self.centerLighBox);
1102        });
1103
1104        $('#center-popup').on('hide.bs.modal', function () {
1105            if (popupCss != null) {
1106                $(this).removeClass(popupCss);
1107                popupCss = null;
1108            }
1109
1110            if (hasEnableLoginCustReg()) { 
1111                location.reload(true);
1112            }
1113
1114            clearLightbox();
1115            reloadOnCustomerRegistration();
1116            //move all fields back to original positions
1117            var popup = $('#center-popup');
1118            self.movePopupFieldsToOriginalPlaceholder(popup);
1119        });
1120
1121        function hasEnableLoginCustReg() {
1122            if (onClickCancelReigstration === true) {
1123                return true;
1124            }
1125
1126            var el = $(".body-checkout #lightboxCustomerRegistration");
1127            return (el == null || el.length < 1) ? false : true;
1128        }
1129
1130        function reloadOnCustomerRegistration() {
1131            var reg = $('.customer-registration-confirm');
1132            if (reg.length > 0) {
1133                location.reload(true);
1134            }
1135        }
1136
1137        function clearLightbox() {
1138            $('.qtip').remove();
1139            window.location.hash = "";
1140        };
1141
1142        // Reposition when the window is resized
1143        $(window).on('resize', function () {
1144            $('.modal:visible').each(self.centerLighBox);
1145        });
1146    };
1147
1148    self.movePopupFieldsToOriginalPlaceholder = function(popup){
1149         //move all fields back to original positions
1150            var fields = popup.find(".web-pub-field").each(function(index, item){
1151                var clientId = item.id;
1152                var $item = $(item);
1153                //remove content from item before moving it back. It will be filled again when we need it. 
1154                //we just needed in its original location to preserve sortorder and avoid duplication in the DOM
1155                var placeholder = $("div[data-placeholder-id='"+clientId + "']");
1156                var content = $item.find(".ajax-field");
1157                if(content.length > 0){
1158                    content.empty();
1159                }
1160                var detachedItem = $item.detach();
1161                placeholder.after(detachedItem);
1162                placeholder.detach();//
1163            });
1164    };
1165
1166    self.publishUpdateOfPublishedFieldEvent = function(options) {
1167        var publisherOptions = {
1168            variantMatrix: null
1169        };
1170        if (options != undefined &&
1171            options != null) {
1172
1173            if (options.variantData != null && options.variantData != undefined) {
1174                publisherOptions.variantMatrix = options.variantData;
1175
1176                if (mcWeb.ajaxRenderEngine !== undefined) {
1177                    // Only for D4
1178                    PubSub.publish(mcWeb.ajaxRenderEngine.events.onNewAreasShown, publisherOptions);
1179                }
1180            }
1181            else if (options.dataToApply !== undefined && options.dataToApply !== null) {
1182                if (mcWeb.ajaxRenderEngine !== undefined) {
1183                    // Only for D4
1184                    PubSub.publish(mcWeb.ajaxRenderEngine.events.onPopupReady, options);
1185                }
1186            }
1187
1188            if (options.callback != undefined && options.callback != null) {
1189                options.callback();
1190            }
1191        }
1192    };
1193
1194    self.cancelRegistration = function () {
1195        onClickCancelReigstration = true;
1196        mcWeb.login.load();
1197    };
1198
1199    self.centerLighBox = function () {
1200        var gutterConst = 15;
1201        var modal = $(this),
1202            dialog = modal.find('.modal-dialog'),
1203            rhsActivePopup = $("#rhs-popup.d4-popup"),
1204            theBody = $("body"),
1205            topLTEAdminMenu = $("body.fixed-admin-lte nav.navbar-static-top");
1206        // Must be visible to calculate dimensions!
1207        modal.css({ "display": "block" });
1208        var centerConfig = {
1209            left: "50%",
1210            horisontalTranslate: Math.round(dialog.width() / 2),
1211            zIndex: "",
1212            top: "50%"
1213        };
1214        if (rhsActivePopup.length > 0) {
1215            if (dialog.width() + rhsActivePopup.width() >= theBody.width()) {
1216                centerConfig.zIndex = "9001";
1217                dialog.parent().css({ "z-index": 9001 });
1218                var publisherSidebar = $("aside.main-sidebar");
1219                if (publisherSidebar.length > 0) {
1220                    if (publisherSidebar.width() + dialog.width() + gutterConst >= theBody.width())
1221                        centerConfig.left = theBody.width() - dialog.width() -35 + "px";
1222                    else
1223                        centerConfig.left = gutterConst + publisherSidebar.width() + "px";
1224                }
1225                else
1226                    centerConfig.left = gutterConst +"px";
1227                centerConfig.horisontalTranslate = "0";
1228            }
1229            else 
1230                centerConfig.left = "calc(50% - " + Math.round(rhsActivePopup.width() / 2) + "px)";
1231        }
1232
1233        if (topLTEAdminMenu.length > 0) {
1234            centerConfig.top = "calc(50% + " + topLTEAdminMenu.height() +"px)";
1235        }
1236
1237        if(centerConfig.zIndex !== "")
1238            modal.css({ "z-index": centerConfig.zIndex });
1239
1240        var centerCss = {
1241            "position": "absolute",
1242            "top": centerConfig.top,
1243            "left": centerConfig.left,
1244            "transform": "translate(-50%, -50%)",
1245           // "transform": "translate(-" + centerConfig.horisontalTranslate + "px, -" + Math.round(Math.min($(window).height(), dialog.height()) / 2) + "px)",
1246            "margin-top": ""
1247        };
1248        dialog.css(centerCss);        
1249    };
1250     
1251    $(function () {
1252        self.init();
1253
1254        setTimeout(function () {
1255            $(document).trigger("lightboxReady");
1256        }, 1000);
1257    });
1258};;
1259var LanguageService = function () {
1260	var self = this;
1261	this.service = new WebApiService("Language");
1262
1263	this.getValueKo = function (resourceObject, resourceName, value) {
1264		return self.service.GetActionKo('GetValue', { obj: resourceObject, name: resourceName }, value);
1265	};
1266
1267	this.getValue = function (resourceObject, resourceName) {
1268		return self.service.GetAction('GetValue', { obj: resourceObject, name: resourceName });
1269	};
1270};
1271
1272mcWeb.tooltip = {
1273	show: function(sender, text) {
1274		sender.qtip({
1275			content: { text: text },
1276			hide: { event: 'unfocus', fixed: true, effect: function() { $(this).slideUp(); } },
1277			position: { my: 'bottom center', at: 'top center' },
1278			style: { classes: 'qtip-bootstrap' },
1279			show: { ready: true, event: 'contextmenu' }
1280		});
1281	}
1282};;
1283jQuery.support.placeholder = (function () {
1284    var i = document.createElement('input');
1285    return 'placeholder' in i;
1286})();
1287
1288mcWeb.validation = new function () {
1289    var self = this;
1290    var $ = jQuery;
1291    self.service = new WebApiService("Language");
1292    self.registrationService = new WebApiService("CustomerRegistration");
1293
1294    ko.bindingHandlers.validation = {
1295        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
1296            bindingContext.$data.validationRules.push({ element: element, rules: valueAccessor() });
1297            var value = allBindings().value();
1298            self.moveLabel(value, element);
1299        },
1300
1301        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
1302            var value = allBindings().value();
1303            self.moveLabel(value, element);
1304        }
1305    };
1306
1307    ko.bindingHandlers.smartlabel = {
1308        init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
1309            var value = allBindings().value();
1310            self.moveLabel(value, element, true);
1311        },
1312
1313        update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
1314            var value = allBindings().value();
1315            self.moveLabel(value, element, true);
1316        }
1317    };
1318
1319    this.moveLabel = function (value, element, placeholder) {
1320        var valueUnwrapped = ko.unwrap(value);
1321        if (valueUnwrapped !== undefined && valueUnwrapped !== null && valueUnwrapped.length > 0) {
1322            $(element).parent().removeClass('inactive').addClass('active');
1323            $(element).next().fadeIn();
1324        } else {
1325            if (placeholder) {
1326                $(element).attr("placeholder", $(element).next().text());
1327            }
1328
1329            if (!$.support.placeholder) {
1330                $(element).parent().removeClass('inactive').addClass('inactive-old');
1331            } else {
1332                $(element).parent().removeClass('inactive').addClass('inactive');
1333                $(element).next().fadeOut();
1334            }
1335        }
1336    }
1337
1338    this.isNotEmpty = function (element) {
1339        return element.value !== null && element.value !== "" && element.value !== undefined && !self.isAllUnderscore(element.value);
1340    };
1341
1342    self.isAllUnderscore = function (text) {
1343        if (text === null || text === "" || text === undefined)
1344            return false;
1345        var i = 0;
1346        var allUnderscore = true;
1347        for (i = 0; i < text.length; i++) {
1348            var char = text.substring(i, i + 1);
1349            if (char !== '_') {
1350                allUnderscore = false;
1351                break;
1352            }
1353        }
1354        return allUnderscore;
1355
1356    };
1357
1358    this.isEmail = function (element) {
1359        return /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/.test(element.value);
1360    };
1361
1362    this.isDigitsOnly = function (element) {
1363        //allows whitespaces but requires at least one digit
1364        return /^\s*\d[\d\s]*$/.test(element.value);
1365    };
1366    this.isDigitsAndScrableOnly = function (element) {
1367        //allows whitespaces but requires at least one digit
1368        return /^\s*\d[\d\s*?]*$/.test(element.value);
1369    };
1370
1371    this.isLettersDigitsOnly = function (element) {
1372        return /^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9]*$/.test(element.value);
1373    };
1374
1375    this.isValidDate = function (element) {
1376        // Simple check for 6 digits format: (ddmmyy)
1377        return /^\d{6}$/.test(element.value);
1378    };
1379
1380    this.isMinLength = function (element, lenght) {
1381        return element.value.length >= lenght;
1382    };
1383
1384    this.isUsernameNew = function (element) {
1385        if (element.val !== undefined && element.length > 0);
1386        var data = { userName: element.value };
1387        return self.registrationService.PostAction("IsUsernameNew", data);
1388    };
1389
1390    this.isOrgnrNew = function (element) {
1391        if (element.val !== undefined && element.length > 0);
1392        var data = { orgnr: element.value };
1393        return self.registrationService.GetAction("IsOrgnrNew", data);
1394    };
1395
1396    this.isMaxLength = function (element, length) {
1397        return element.value.length <= length;
1398    };
1399
1400    this.isLength = function (element, lenght) {
1401        return element.value.length === lenght;
1402    };
1403
1404    this.addErrorClass = function (element) {
1405        $(element).addClass('validation_error');
1406    };
1407
1408    this.qTipActionShowClickHide = function (element, text) {
1409            $(element).qtip({
1410                content: { text: text },
1411                position: { my: 'bottom center', at: 'top center' },
1412                style: { classes: 'qtip-bootstrap qtip-cust-condition' },
1413                show: true,
1414                hide: {
1415                    event: 'click'
1416                },
1417                prerender: true
1418            });
1419    };
1420
1421    this.qTipActionShow = function (element, text, isWarning) {
1422        if (!isWarning) {
1423            $(element).qtip({
1424                content: { text: text },
1425                position: { my: 'bottom center', at: 'top center' },
1426                style: { classes: 'qtip-bootstrap qtip-cust' },
1427                show: true,
1428                hide: false,
1429                prerender: true
1430            });
1431        } else {
1432            $(element).qtip({
1433                content: { text: text },
1434                position: { my: 'bottom center', at: 'top center' },
1435                show: true,
1436                hide: false,
1437                prerender: true
1438            });
1439        }
1440    };
1441
1442    this.qTipActionShowAndHide = function (element, text, isWarning, myDelay) {
1443        if (!isWarning) {
1444            $(element).qtip({
1445                content: { text: text },
1446                position: { my: 'bottom center', at: 'top center' },
1447                style: { classes: 'qtip-bootstrap qtip-cust' },
1448                show: true,
1449                hide: {
1450                    event: 'unfocus',
1451                    inactive: myDelay
1452                },
1453                prerender: true
1454            });
1455        } else {
1456            $(element).qtip({
1457                content: { text: text },
1458                position: { my: 'bottom center', at: 'top center' },
1459                show: true,
1460                hide: { delay: myDelay },
1461                prerender: true
1462            });
1463        }
1464    };
1465    this.elementIsValid = function (validationObject) {
1466        return validationObject.valid == true;
1467    }
1468
1469    this.validateElement = function (validationRules, element) {
1470        var promise = this.validateModel(validationRules);
1471
1472        return promise.then(function (res) {
1473            var elemValid = true;
1474            var failedRule = '';
1475            var i;
1476            for (i = 0; i < res.length; i++) {
1477                if (res[i].elem === element && !res[i].valid) {
1478                    elemValid = false;
1479                    failedRule = res[i].rule;
1480                }
1481            }
1482            if (elemValid) {
1483                $('.qtip').remove();
1484                return { valid: true, rule: failedRule };
1485            } else {
1486                return { valid: false, rule: failedRule };
1487            }
1488        });
1489    }
1490
1491    this.setValidCss = function (element) {
1492        $(element).parent().addClass('ok');
1493        $(element).removeClass('validation_error');
1494        $(element).prev().addClass('icon-star icon-ok green');
1495    };
1496
1497    this.removeValidCss = function (element) {
1498        $(element).parent().removeClass('ok');
1499        $(element).removeClass('validation_error');
1500        $(element).prev().removeClass('icon-ok green');
1501    };
1502
1503
1504    this.getErrorMessage = function (resource) {
1505        var res = resource.split(',');
1506        var data = { obj: res[0], name: res[1] };
1507        return self.service.GetAction("GetValue", data);
1508    };
1509
1510    this.getErrorMessages = function (validationRules) {
1511        var dataObj = [];
1512        var i;
1513        var j;
1514        for (i = 0; i < validationRules.length; i++) {
1515            for (j = 0; j < validationRules[i].rules.length; j++) {
1516                var languageResource = validationRules[i].rules[j].resource.split(',');
1517                dataObj.push({ Object: languageResource[0], Name: languageResource[1], Value: '' });
1518            }
1519        }
1520        var data = { '': dataObj };
1521        return self.service.PostAction("PostValues", data);//{ 'languageResources': dataObj });
1522    };
1523
1524    this.validateModel = function (validationRules) {
1525        var promises = [];
1526        var i;
1527        var j;
1528        var validationResult = [];
1529        for (i = 0; i < validationRules.length; i++) {
1530            var currEl = validationRules[i].element;
1531            if ($(currEl).is(':visible')) {
1532                for (j = 0; j < validationRules[i].rules.length; j++) {
1533                    var curRuleSet = validationRules[i].rules[j];
1534                    var currRule = curRuleSet.rule;
1535                    switch (currRule) {
1536                        case 'required':
1537                            if (this.isNotEmpty(currEl) || ((ko.isComputed(curRuleSet.active) || ko.isObservable(curRuleSet.active)) ? !curRuleSet.active() : !curRuleSet.active)) {
1538                                validationResult.push({ elem: currEl, rule: currRule, valid: true });
1539                            } else {
1540                                validationResult.push({ elem: currEl, rule: currRule, valid: false });
1541                            }
1542                            break;
1543                        case 'email':
1544                            if (currEl.value === "" || this.isEmail(currEl) || ((ko.isComputed(curRuleSet.active) || ko.isObservable(curRuleSet.active)) ? !curRuleSet.active() : !curRuleSet.active)) {
1545                                validationResult.push({ elem: currEl, rule: currRule, valid: true });
1546                            } else {
1547                                validationResult.push({ elem: currEl, rule: currRule, valid: false });
1548                            }
1549                            break;
1550                        case 'digits':
1551                            if (this.isDigitsOnly(currEl) || !curRuleSet.active) {
1552                                validationResult.push({ elem: currEl, valid: true });
1553                            } else {
1554                                validationResult.push({ elem: currEl, rule: currRule, valid: false });
1555                            }
1556                            break;
1557                        case 'digitsorscramble':
1558                            if (this.isDigitsAndScrableOnly(currEl) || !curRuleSet.active) {
1559                                validationResult.push({ elem: currEl, valid: true });
1560                            } else {
1561                                validationResult.push({ elem: currEl, rule: currRule, valid: false });
1562                            }
1563                            break;
1564
1565                        case 'minlength':
1566                            if (this.isNotEmpty(currEl) || !curRuleSet.active) {
1567                                validationResult.push({ elem: currEl, valid: true });
1568                            } else {
1569                                validationResult.push({ elem: currEl, rule: currRule, valid: false });
1570                            }
1571                            break;
1572                        case 'maxlength':
1573                            if (this.isNotEmpty(currEl) || !curRuleSet.active) {
1574                                validationResult.push({ elem: currEl, valid: true });
1575                            } else {
1576                                validationResult.push({ elem: currEl, rule: currRule, valid: false });
1577                            }
1578                            break;
1579                        case 'length':
1580                            if (this.isLength(currEl, curRuleSet.len) || !curRuleSet.active) {
1581                                validationResult.push({ elem: currEl, valid: true });
1582                            } else {
1583                                validationResult.push({ elem: currEl, rule: currRule, valid: false });
1584                            }
1585                            break;
1586                        case 'usernameUnique':
1587                            if (!curRuleSet.active()) {
1588                                validationResult.push({ elem: currEl, rule: currRule, valid: true });
1589                                break;
1590                            }
1591                            var rule = { elem: currEl, rule: 'usernameUnique', valid: false };
1592                            var usRs = curRuleSet;
1593                            validationResult.push(rule);
1594                            var promise = this.isUsernameNew(currEl).then(function (result) {
1595                                if (result == true || !usRs.active()) {
1596                                    rule.valid = true;
1597                                } else {
1598                                    rule.valid = false;
1599                                }
1600                            });
1601                            promises.push(promise);
1602                            break;
1603                        case 'orgNrUnique':
1604                            var ruleOrg = { elem: currEl, rule: 'orgNrUnique', valid: false };
1605                            validationResult.push(ruleOrg);
1606                            var orgEl = currEl;
1607                            var orgRs = curRuleSet;
1608                            var promiseOrg = this.isOrgnrNew(currEl).then(function (result) {
1609                                if (result == true || !orgRs.active) {
1610                                    ruleOrg.valid = true;
1611                                } else {
1612                                    ruleOrg.valid = false;
1613                                }
1614                            });
1615                            promises.push(promiseOrg);
1616                            break;
1617                        case 'date':
1618                            if (this.isLength(currEl, 0) || this.isValidDate(currEl) || !curRuleSet.active) {
1619                                validationResult.push({ elem: currEl, valid: true });
1620                            } else {
1621                                validationResult.push({ elem: currEl, rule: currRule, valid: false });
1622                            }
1623                            break;
1624                        case 'custom':
1625                            if (curRuleSet.func() || !curRuleSet.active) {
1626                                validationResult.push({ elem: currEl, valid: true });
1627                            } else {
1628                                validationResult.push({ elem: currEl, rule: currRule, valid: false });
1629                            }
1630                            break;
1631                    }
1632                }
1633            }
1634        }
1635
1636        return Promise.allSettled(promises).then(function () {
1637            return validationResult;
1638        });
1639    };
1640};
1641
1642
1643
1644
1645;
1646var mcWeb = (mcWeb || {});
1647
1648
1649mcWeb.variantImage = new function() {
1650	'use strict';
1651	var $ = jQuery;
1652	var self = this;
1653	self.selectImage = function(id, index, array) {
1654		var targetImg = $('#' + id);
1655		var imageArray = targetImg.find("img.lazy");
1656		if (targetImg.length > 0 && imageArray !== undefined) {
1657			imageArray[0].src = array[index].ImageUrl;
1658			imageArray[0].title = array[index].Title;
1659			imageArray[0].alt = array[index].AltTag;
1660			var link = targetImg.find("a[href]");
1661			if (link.length > 0) {
1662				$(link[0]).attr('href',array[index].Href);
1663			}
1664		}
1665	}
1666};;
1667ko.components.register('discount-code', {
1668	viewModel: function (params) {
1669
1670		var $ = jQuery;
1671		var self = this;
1672
1673		this.service = new WebApiService("Cart");
1674		this.languageService = new LanguageService();
1675		this.discountCode = ko.observable('');
1676		this.discountPending = ko.observable(false);
1677		this.discountCodeError = ko.observable(false);
1678		this.isCheckout = ko.observable((($('.body-checkout').length > 0) ? true : false));
1679		this.buttonText = ko.observable();
1680
1681		// Behaviors
1682		this.onClickDiscount = function () {
1683			if (self.discountCode().length === 0)
1684				return;
1685
1686			self.discountCodeError(false);
1687			self.discountPending(true);
1688			self.service.GetAction("AddDiscountCode", { discountCode: self.discountCode(), isCheckout: self.isCheckout() })
1689				.then(function (result) {
1690					if (result === 0) {
1691						self.updateCart(); //Send update cart event
1692						self.discountCode('');
1693                        self.showLanguageTextInTooltip("CUSTOMERCENTER_MYPAGE", "RabattkodeRegistrert");
1694                        setTimeout(PubSub.publish(mcWeb.payments.events.reloadPayments, null), 750); //Reload payment if it changed
1695					} else {
1696						self.discountCodeError(true);
1697
1698						if (result === 3)
1699							self.showLanguageTextInTooltip("CUSTOMERCENTER_MYPAGE", "RabattkodeFinnesIkke");
1700						else if (result === 2)
1701							self.showLanguageTextInTooltip("CUSTOMERCENTER_MYPAGE", "RabattkodeFinnes");
1702						else
1703							self.showLanguageTextInTooltip("CUSTOMERCENTER_MYPAGE", "RabattkodeFeil");
1704					}
1705				})
1706				.fail(function (error) {
1707					console.log(error);
1708					self.discountCodeError(true);
1709					self.showLanguageTextInTooltip("CUSTOMERCENTER_MYPAGE", "RabattkodeFeil");
1710				})
1711				.finally(function () {
1712					self.discountPending(false);
1713				});
1714		};
1715
1716		this.updateCart = function () {
1717			self.service.GetAction("LoadCart", { cartName: null, useVat: null, discountCode: null, vatChange: false, isCheckout: self.isCheckout() }).then(function (result) {
1718				if (result == null)
1719					return;
1720
1721				PubSub.publish(mcWeb.cart.events.onChangedCart, result);
1722			});
1723		};
1724
1725		this.showLanguageTextInTooltip = function (resObj, resName) {
1726			self.languageService.getValue(resObj, resName).then(function (result) {
1727				mcWeb.tooltip.show(jQuery('#discount-code-input'), result);
1728			});
1729		}
1730
1731		this.getButtonText = function () {
1732			self.languageService.getValue("COMMANDS", "Add").then(function (result) {
1733				self.buttonText(result);
1734			}); 
1735		}
1736
1737		self.getButtonText();
1738	},
1739	template:
1740		'<div class="form-group" data-bind="css: { \'has-feedback has-error\': discountCodeError}">\
1741			<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true" data-bind="visible: discountCodeError"></span>\
1742			<input type="text" id="discount-code-input" class="form-control" onclick="return false;" data-bind="value: discountCode, valueUpdate: \'input\', ">\
1743		</div>\
1744		<div class="form-group">\
1745			<button type="button" id="discount-button" class="btn btn-default" data-bind="click: onClickDiscount, disable: discountCode().length == 0 || discountPending()">\
1746				<span class="spinner" data-bind="visible: discountPending"><i class="icon-spinner animate-spin"></i></span>\
1747				<span data-bind="text: buttonText"></span>\
1748			</button>\
1749		</div>'
1750});;
1751mcWeb.instantSearch = new function () {
1752
1753	this.request = null;
1754	this.searchTextBox = null;
1755	this.instantSearch = false;
1756    this.publishMode = false;
1757	var self = this;
1758	self.searchHasFocus = false;
1759	self.clearEntryOnClick = false;
1760	self.imageService = new WebApiService("ImageRenderer");
1761	self.settings = null;
1762	self.ragService = new WebApiService("rag");
1763	self.aiTimeout = null; 
1764
1765	self.vm = new function () {	//Internal - json to array obj.
1766		var view = this;
1767		view.products = ko.observableArray();
1768	    view.brands = ko.observableArray();
1769        view.brandnames = ko.observableArray();
1770	    view.categories = ko.observableArray();
1771	    view.articles = ko.observableArray();
1772		view.TotalHits = ko.observable(0);
1773	    view.TotalArticleHits = ko.observable(0);
1774	    view.ShowBrands = ko.observable(false);
1775        view.ShowBrandNames = ko.observable(false);
1776	    view.ShowCategories = ko.observable(false);
1777	    view.ShowPreview = ko.observable(false);
1778	    view.ShowAccessories = ko.observable(false);
1779	    view.ShowAlternatives = ko.observable(false);
1780        view.ShowArticlesRHS = ko.observable(false);
1781	    view.ShowArticles = ko.observable(false);
1782	    view.CurrentProduct = ko.observable();
1783		view.CurrentPlid = ko.observable(0);
1784		view.OtherSearchesText = ko.observable("");
1785	    if (jQuery("body.mode-publisher").length > 0) {
1786	        self.instantSearch = true;
1787	        self.publishMode = true;
1788	    }
1789
1790		// AI searhch result
1791		view.AIQuestionResponse = ko.observable("");
1792		view.aiProducts = ko.observableArray();
1793
1794        view.loadImages = function (json) {
1795			if (json.Products != null && json.Products.length > 0) {
1796				var items = [];
1797				for (var i = 0; i < json.Products.length; i++) {
1798					var img = json.Products[i];
1799
1800					var item = {                            
1801                            Plid : img.ProduktLagerID
1802                        };
1803					items.push(item);
1804				}
1805				if(items.length > 0){
1806					self.imageService.PostAction("ListInstantSearchImagesAync", { Items : items}).then(function (result){
1807                        if (result !== undefined) {
1808                            for (var j = 0; j < json.Products.length && j < result.items.length; j++) {
1809								var imgInfo = result.items[j];
1810								var me = json.Products[j];
1811								if (me.ProduktLagerID == imgInfo.plid && imgInfo.success) {
1812									me.ImageTag(imgInfo.tag);
1813                                }
1814                            }
1815                        }
1816					})
1817				}
1818			}
1819        };
1820		view.setResult = function (json) {
1821		    view.TotalArticleHits(json.TotalArticleHits);
1822		    view.ShowBrands(json.ShowBrands);
1823            view.ShowBrandNames(json.ShowBrandNames);
1824		    view.ShowCategories(json.ShowCategories);
1825		    view.ShowPreview(json.ShowPreview);
1826		    view.ShowAccessories(json.ShowAccessories);
1827		    view.ShowAlternatives(json.ShowAlternatives);
1828		    view.ShowArticles(json.ShowArticles);
1829            view.ShowArticlesRHS(json.ShowArticlesRHS);
1830			view.TotalHits(json.TotalHits);
1831			view.OtherSearchesText(json.OtherSearchesText);
1832
1833			view.AIQuestionResponse("");
1834			view.aiProducts.removeAll();
1835
1836			if (json.Products != null && json.Products.length > 0) {
1837
1838			    view.CurrentProduct(json.Products[0]);
1839
1840			    for (var i = 0; i < json.Products.length; i++) {
1841			        json.Products[i].ProduktDesc1 = highlightSearchWord(json.SearchWord, json.Products[i].ProduktDesc1);
1842			        json.Products[i].ProduktDesc2 = highlightSearchWord(json.SearchWord, json.Products[i].ProduktDesc2);
1843					json.Products[i].ImageTag = ko.observable(json.Products[i].ImageTag);
1844			    }
1845
1846			    view.products(json.Products);
1847			} else {
1848			    view.products.removeAll();
1849			}
1850		    if (json.Categories != null && json.Categories.length > 0) {
1851		        view.categories(json.Categories);
1852		    } else {
1853		        view.categories.removeAll();
1854		    }
1855
1856		    if (json.BrandList != null && json.BrandList.length > 0) {		  
1857                for(var i = 0; i < json.BrandList.length; i++){
1858                    json.BrandList[i].BrandName = highlightSearchWord(json.SearchWord, json.BrandList[i].BrandName);
1859                }
1860                view.brandnames(json.BrandList);
1861                
1862		    }else {
1863		        view.brandnames.removeAll();
1864		    }
1865
1866            if (json.Brands != null && json.Brands.length > 0) {	
1867                   view.brands(json.Brands);
1868		    }else {
1869		        view.brands.removeAll();
1870		    }
1871
1872		    if (json.Articles != null && json.Articles.length > 0) {		        
1873		        view.articles(json.Articles);
1874		    }else {
1875		        view.articles.removeAll();
1876		    }
1877		};
1878	    view.CurrentProduct.subscribe(function(data) {
1879	        var plid = data.ProduktLagerID;
1880	        view.ShowAccessories(data.ShowAccessories);
1881            view.ShowAlternatives(data.ShowAlternatives);
1882
1883            
1884
1885            if (!!mcWeb.ajaxRenderEngine){
1886                if(view.TotalArticleHits() > 0){
1887                    mcWeb.ajaxRenderEngine.currentSearchKeyword = view.searchKeyWord;
1888                }    
1889                mcWeb.ajaxRenderEngine.reloadInstantSearchPreview(plid);
1890            }
1891	    });
1892	    view.PreviewCurrentProduct = function(data, event) {
1893	        var plid = data.ProduktLagerID;
1894	       
1895	        if (plid != view.CurrentPlid()) {
1896	            
1897	            view.ShowAccessories(data.ShowAccessories);
1898                view.ShowAlternatives(data.ShowAlternatives);
1899
1900	            if (!!mcWeb.ajaxRenderEngine){
1901                    if(view.TotalArticleHits() > 0){
1902                        mcWeb.ajaxRenderEngine.currentSearchKeyword = view.searchKeyWord;
1903                    }
1904                    mcWeb.ajaxRenderEngine.reloadInstantSearchPreview(plid);
1905                }
1906	        }
1907	        view.CurrentPlid(data.ProduktLagerID);
1908	    };
1909
1910        view.searchKeyWord = "";
1911	};
1912
1913	self.load = function (settings) {
1914		self.settings = settings || {};
1915
1916        var searchResultTable = document.getElementById("InstSearchDiv");
1917       
1918		if (searchResultTable) {
1919			ko.applyBindings(self.vm, searchResultTable); //Call viewModal with JSON response
1920		}
1921	};
1922
1923	/*Get JSON from server start*/
1924	this.get = function (search) { //Public
1925
1926		var notfoundMobile = jQuery('.jqm-nosearch');
1927		notfoundMobile.hide();
1928
1929        self.vm.searchKeyWord = search; //share it with the view model
1930		if (showHideMobileMenu(search) == true) {
1931			getAsync(search);
1932		}
1933	};
1934
1935	var showHideMobileMenu = function (search) { //Internal
1936
1937		var searchcontent = jQuery('.content-search');
1938
1939		if (searchcontent != null && searchcontent.length > 0) {
1940
1941			if (search == null || search.length < 1) {
1942				searchcontent.css({ 'display': 'none' });
1943				return false;
1944
1945			} else {
1946				searchcontent.css({ 'display': '' });
1947			}
1948		}
1949
1950		return true;
1951	};
1952
1953	this.search = function (searchboxID, instantSearch) {
1954
1955		self.instantSearch = instantSearch;
1956
1957		jQuery(document).ready(function () {
1958			self.searchTextBox = document.getElementById(searchboxID);
1959
1960			jQuery('#' + searchboxID).on('keypress', function (e) {
1961				if (e.keyCode == 13) {
1962					mcWeb.instantSearch.doSearch();
1963					e.preventDefault();
1964				}
1965			});
1966
1967			if (instantSearch) {
1968				
1969				
1970
1971				jQuery('#' + searchboxID).on('keyup', function (e) {
1972					if (self.searchTextBox.value != null && e.keyCode != 13) {
1973						const rawValue = self.searchTextBox.value.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0')
1974						const searchString = encodeURIComponent(rawValue);
1975						mcWeb.instantSearch.get(searchString);
1976
1977						mcWeb.instantSearch.askAIQuestion(rawValue);
1978					}
1979				});
1980			}
1981
1982			jQuery('#BSrch').on('click', function (e) {
1983				mcWeb.instantSearch.doSearch();
1984			});
1985		});
1986	};
1987
1988	self.askAIQuestion = async function (query) {
1989
1990		if (self.settings.AIQuestionSearchEnabled === false) return;
1991		if (self.aiTimeout) clearTimeout(self.aiTimeout);
1992				
1993		self.aiTimeout = setTimeout(function () {
1994			if (self.vm.products().length > 0 || !query || query.length <= 7) return;
1995
1996			self.vm.AIQuestionResponse("");
1997			self.vm.aiProducts.removeAll();
1998
1999			const restoreSearchIcon = function() {
2000    			jQuery('.icon-search').removeClass('ai-searching');
2001			};
2002
2003			jQuery('.icon-search').addClass('ai-searching');	
2004
2005			self.ragService.GetAction("ask", { q: query }).then(function (result) {
2006				restoreSearchIcon();
2007				if (result == null || result == undefined) return;
2008				if ((result.Answer == null || result.Answer.trim() === "")) return;
2009
2010				self.vm.AIQuestionResponse(result.Answer || "");
2011				self.vm.aiProducts(result.Products || []);
2012
2013				self.vm.CurrentPlid(0);
2014				if (result.Products != null && result.Products.length > 0) {
2015					self.vm.CurrentProduct(result.Products[0]);
2016					self.vm.ShowPreview(true);
2017				}
2018
2019				const searchResultTable = document.getElementById("InstSearchDiv");
2020				jQuery(searchResultTable).slideDown(100);
2021			});
2022        }, 1500);
2023    };
2024
2025	this.clearAndFocus = function (searchBoxID, event) {
2026		event.preventDefault();
2027		jQuery('#InstSearchDiv').slideUp(400);
2028		var searchBox = document.getElementById(searchBoxID);
2029		//focusOnSearch(searchBox);
2030        searchBox.className = "TextBoxSearchEnable";
2031        searchBox.value = "";
2032		jQuery('#CloseSearchButton').hide();
2033		searchBox.focus();
2034	};
2035
2036	//Sends the browser to the search page with the appropriate search query string
2037	this.doSearch = function () {
2038		jQuery('#InstSearchDiv').hide();
2039
2040		if (jQuery(self.searchTextBox).val().length == 0)
2041			return;
2042
2043		var searchUrlelement = document.getElementById("hidden-search-url");
2044		var searchpath = '/search?q=';
2045
2046		if (searchUrlelement !== undefined)
2047			searchpath = searchUrlelement.textContent + '?q=';
2048
2049		var searchString = encodeURIComponent(jQuery(self.searchTextBox).val());
2050		var link = searchpath + searchString;
2051
2052		if (self.request)
2053			self.request.abort();
2054
2055		document.location = link;
2056	};
2057    this.onFocusOut = function() {
2058        self.searchHasFocus = false;
2059        self.clearEntryOnClick = true;
2060    };
2061
2062    this.focusOnSearch = function (event, sender) {
2063        try {//clear content only when clicking at end of the string
2064            if (self.clearEntryOnClick && sender.selectionStart >= sender.value.length) {
2065                sender.className = "TextBoxSearchEnable";
2066                sender.value = "";
2067                self.clearEntryOnClick = false;
2068                jQuery('#InstSearchDiv').removeClass("stop-ajax-rendering");//class used to stop publisher rendering before we show the instant search
2069                jQuery('#InstSearchDiv').slideUp(400);
2070            }
2071        } catch (e) {
2072
2073        }
2074    };
2075	this.setSearchBoxCoord = function (event, sender) {
2076		//On focus, "activate" the ajax-rendering.
2077		jQuery('#InstSearchDiv').removeClass("stop-ajax-rendering");//class used to stop publisher rendering before we show the instant search
2078
2079	    if (!self.searchHasFocus)
2080	        self.clearEntryOnClick = true;
2081	    self.searchHasFocus = true;
2082	    
2083		if (!self.instantSearch)
2084			return;
2085
2086		var extendedPanel = jQuery('#InstSearchDiv');
2087		if (!extendedPanel)
2088			return;
2089
2090		var mobileSearchResult = jQuery('#search-result');
2091
2092		//Check if not mobile
2093		if (mobileSearchResult == null || mobileSearchResult.length < 1) {
2094
2095			var target = sender;
2096			var dimensionTarget = sender;
2097			if (jQuery("body.layoutver4").length > 0) {
2098				dimensionTarget = "#SubMenuArea";
2099			}
2100
2101			var targetRect = target.getBoundingClientRect();
2102			var dimensionTargetRect = jQuery(dimensionTarget)[0].getBoundingClientRect();
2103
2104			extendedPanel.clonePosition(target);
2105
2106			if (jQuery('.use-sticky-header').length > 0) {
2107				extendedPanel.css({
2108					'left': dimensionTargetRect.left + 'px',
2109					'top': targetRect.bottom + 'px',
2110					'position': 'fixed',
2111					'z-index': '121'
2112				});
2113			} else {
2114				extendedPanel.css({
2115					'left': dimensionTargetRect.left + 'px',
2116					'top': targetRect.bottom + 'px',
2117					'position': 'absolute',
2118					'z-index': '121'
2119				});
2120			}
2121
2122			var heightOffset = jQuery(target).outerHeight();
2123
2124			var width = extendedPanel.width();
2125			var widthOfBox = jQuery(dimensionTarget).outerWidth();
2126
2127
2128			if (width < widthOfBox) {
2129				//Make the panel at least as wide as the search box
2130				extendedPanel.css('width', widthOfBox + 'px');
2131				width = widthOfBox;
2132			}
2133			if (width < 300) {
2134				//make it at least 250px wide
2135				extendedPanel.css('width', '300px');
2136			}
2137
2138			var widthOfTable = jQuery('.InstantSearch table').outerWidth();
2139			if (width < widthOfTable) {
2140				//make width no less than that of the table contained within it
2141				extendedPanel.css('width', widthOfTable + 'px');
2142			}
2143		}
2144	};
2145
2146	this.setSearchBoxCoordFixed = function (event, sender) {
2147
2148		var extendedPanel = jQuery('#InstSearchDiv');
2149		if (extendedPanel == null)
2150			return;
2151
2152		var mobileSearchResult = jQuery('#search-result');
2153
2154		//Check if not mobile
2155		if (mobileSearchResult == null || mobileSearchResult.length < 1) {
2156			extendedPanel.clonePosition(sender);
2157			extendedPanel.css('left', jQuery(sender).offset().left + 'px');
2158			var heightOfBox = jQuery(sender).outerHeight();
2159
2160			extendedPanel.offset({ top: extendedPanel.offset().top + heightOfBox, left: extendedPanel.offset().left });
2161			var width = extendedPanel.width();
2162
2163			var widthOfBox = jQuery(sender).outerWidth();
2164			if (width < widthOfBox) {
2165				//Make the panel at least as wide as the search box
2166				extendedPanel.css('width', widthOfBox + 'px');
2167				width = widthOfBox;
2168			}
2169			if (width < 300) {
2170				//make it at least 250px wide
2171				extendedPanel.css('width', '300px');
2172			}
2173			extendedPanel.css('top', '92px');
2174			extendedPanel.css('position', 'fixed');
2175			extendedPanel.css('z-index', '121');
2176		}
2177
2178
2179	};
2180
2181	var getAsync = function (search) {	//Internal - Ajax post
2182		var params = { search: search }; //Ajax params
2183
2184		if (self.request)
2185			self.request.abort();
2186
2187		self.request = ReqAjaxGet("InstantSearchKnockout", "GetInstantSearchResult", params, getCallBack,null,true);
2188	};
2189
2190	var getCallBack = function (response) {	//Internal - Ajax response
2191		self.request = null;
2192
2193		try {
2194			var searchResultTable = document.getElementById("InstSearchDiv");
2195			var oldDisplayType = jQuery(searchResultTable).css('display');
2196
2197			if (response != null && (response.Products != null && response.Products.length > 0 || response.TotalArticleHits > 0)) {
2198			    var productCount = 1; //we need this to have height set for when only article count is returned
2199			    if (response.Products != null && response.Products.length > 0)
2200			        productCount = response.Products.length;
2201                
2202				if (oldDisplayType != 'block') {
2203					jQuery(searchResultTable).height(52 * productCount);
2204					
2205					jQuery('#CloseSearchButton').show();
2206					jQuery(searchResultTable).slideDown(100);
2207				} else {
2208				    var minHeightProducts = 52 * productCount;
2209				    var minHeight = jQuery('#InstSearchDiv > div.InstantSearch').height();
2210                    if(minHeight > minHeightProducts)
2211                        jQuery(searchResultTable).height(minHeight);
2212                    else
2213						jQuery(searchResultTable).height(minHeightProducts);
2214				} 
2215				
2216			} else {
2217
2218				if (oldDisplayType == 'block') {
2219					jQuery('#CloseSearchButton').hide();
2220					jQuery(searchResultTable).slideUp(400);
2221				}
2222			}
2223            self.vm.setResult(response);
2224            if (jQuery("body.layoutver4").length > 0) {
2225				self.vm.loadImages(response);
2226            }
2227			
2228			return true;
2229		}
2230		catch (e) {
2231			alert('InstantSearch getCallback Error : InstantSearch.js : ' + e);
2232			return true;
2233		}
2234	};
2235
2236
2237	
2238
2239	var highlightSearchWord = function(searchWord, produktDesc) {
2240
2241		try {
2242			var pos = 0, startPos = 0;
2243			var length = searchWord.length;
2244			searchWord = searchWord.toLowerCase();
2245			var sp = '<span class="search-key">';
2246			var esp = '</span>';
2247
2248			while (pos > -1) {
2249				pos = produktDesc.substring(startPos).toLowerCase().indexOf(searchWord);
2250				if (pos > -1) {
2251					pos += startPos;
2252					var first = produktDesc.substring(0, pos) + sp;
2253					var word = produktDesc.substring(pos, pos + length) + esp;				
2254					var second = produktDesc.substring(pos + length, produktDesc.length);
2255
2256					produktDesc = first + word + second;
2257					startPos = first.length + word.length;
2258
2259					if (startPos >= produktDesc.length) {					
2260						return produktDesc;
2261					}
2262				}
2263			}
2264		} catch (e) {
2265
2266		}
2267
2268		return produktDesc;
2269	};
2270
2271	/*Get JSON from server end*/
2272};
2273
2274/**
2275* Copyright (c) 2009 Gary Haran => [email protected]
2276* Released under MIT license [...]
2277*/
2278(function ($) {
2279    $.fn.clonePosition = function(element, options) {
2280        var options = $.extend({
2281            cloneWidth: true,
2282            cloneHeight: true,
2283            offsetLeft: 0,
2284            offsetTop: 0
2285        }, (options || { }));
2286
2287		//var offsets = $(element).offset();
2288		var getBoundingRect = $(element)[0].getBoundingClientRect();
2289
2290        $(this).css({
2291            position: 'fixed',
2292            top: (getBoundingRect.top + options.offsetTop) + 'px',
2293            left: (getBoundingRect.left + options.offsetLeft) + 'px'
2294        });
2295
2296        if (options.cloneWidth) $(this).width($(element).width());
2297        if (options.cloneHeight) $(this).height($(element).height());
2298
2299        return this;
2300    };
2301})(jQuery);
2302
2303jQuery(document).mouseup(function(e) {
2304	var container = jQuery('#InstSearchDiv');
2305
2306    if(jQuery("body.publish-mode").length > 0 || jQuery("#EDMMasterActive").length > 0)
2307        return;//not active in publish-mode
2308
2309	if (!container.is(e.target) && container.has(e.target).length === 0) {
2310		container.hide();
2311	}
2312});
2313;
2314mcWeb.conditions = (new function ($) {
2315    var conditionsThis = this;
2316    this.events = {
2317        onAcceptChange: "mcWeb.conditions.events.onAcceptChange",
2318        onConditionsBound: "mcWeb.conditions.events.onConditionsBound"
2319    };
2320
2321    this.conditionGetLanguageText = function (key) {
2322        if ($("." + key).length > 0)
2323            return $("." + key)[0].innerText;
2324    };
2325
2326    this.vm = function (id) {
2327        var self = this;
2328        self.settings = null;
2329        self.userEditMode = ko.observable(false);
2330
2331        this.refConditionsStatus = {
2332            isFunctionalConditionAccepted: ko.observable(false),
2333            acceptDocuments: ko.observableArray([]),
2334            usageArea: null
2335        };
2336        self.setSettings = function (settings) {
2337            if (!settings)
2338                return;
2339            self.settings = {
2340                usageArea: 0,
2341                usageFunction: '',
2342                forUnknownUser: true,
2343                isInLightbox: false,
2344                accordionstyleCollapse: true,
2345                emailAddress: null,
2346                useSessionDocumentAcceptance: false
2347            };
2348            self.settings.usageArea = (settings.usageArea) ? settings.usageArea : 0;
2349            self.settings.usageFunction = (settings.functionName) ? settings.functionName : '';
2350            self.settings.forUnknownUser = (settings.forUnknownUser === null) ? true : settings.forUnknownUser;
2351            self.settings.isInLightbox = (settings.isInLightbox === null) ? false : settings.isInLightbox;
2352            self.settings.accordionstyleCollapse = (settings.accordionstyleCollapse === null) ? true : settings.accordionstyleCollapse;
2353            self.settings.emailAddress = settings.emailAddress;
2354            self.settings.useSessionDocumentAcceptance = (settings.useSessionDocumentAcceptance != null) ? settings.useSessionDocumentAcceptance : false;
2355
2356            if (self.settings.usageArea == 4) {
2357                //EDM
2358                self.isRegisterForEDM = ko.observable(true);
2359                self.isVisible(false);
2360                // EDM Subscribe / unsubscribe :
2361                PubSub.subscribe(mcWeb.EdmRegistration.events.onInOutChange, function (evt, evtData) {
2362                    if ("#" + self.id !== evtData.parentDomId)
2363                        return;
2364                    self.isRegisterForEDM(evtData.isIn);
2365                    self.isVisible(evtData.isIn);
2366                    if (!evtData.isIn)
2367                        self.resetResponses();
2368                });
2369                // EDM successfully subscribed:
2370                PubSub.subscribe(mcWeb.EdmRegistration.events.onEdmRegistrationSuccess, function (evt, successStatus) {
2371                    if ("#" + self.id !== successStatus.parentDomId)
2372                        return;
2373                    self.isVisible(!successStatus.isSuccess);
2374                    if (successStatus.isSuccess)
2375                        self.resetResponses();
2376
2377                });
2378
2379                // EDM Email-textfield gets focus
2380                PubSub.subscribe(mcWeb.EdmRegistration.events.onEdmRegistrationTBFocus, function (evt, focusStatus) {
2381                    if ("#" + self.id !== focusStatus.parentDomId)
2382                        return;
2383                    if (focusStatus.hasFocus);
2384                    {
2385                        self.isRegisterForEDM(focusStatus.isIn);
2386                        if ((!self.isVisible()) && (self.isRegisterForEDM())) {
2387                            self.isVisible(true);
2388                            self.resetResponses();
2389                        }
2390                    }
2391                });
2392            }
2393            else if (self.settings.usageArea == 2) {
2394                // Customer registration
2395                self.isVisible(false);
2396            }
2397            else {
2398                self.isVisible(true);
2399            }
2400
2401        }
2402
2403        self.conditions = ko.observableArray([]);
2404
2405        self.AcceptDoc = function (dc, isKundesenterUsage) {
2406            var acDoc = this;
2407            this.Term = ko.observable(dc);
2408
2409            this.userEditMode = ko.observable(false); // only used in kundeservice
2410
2411            this.Accepted = ko.observable(
2412                (dc.Accepted === null) ? false
2413                    : (dc.Accepted) ?
2414                        (dc.RepeatMode == 1) ?
2415                            (isKundesenterUsage) ? true : false
2416                            : true
2417                        : false);
2418            this.Accepted.subscribe(function (newValue) {
2419                self.acceptanceChanged.notifySubscribers();
2420            });
2421            this.storedAcceptanceStatus = ko.observable((dc.Accepted === null) ? "0" : (dc.Accepted) ? (dc.RepeatMode == "1") ? "1" : "1" : "-1");
2422            this.newAcceptanceStatus = ko.observable(this.storedAcceptanceStatus());
2423            this.newAcceptanceStatus.subscribe(function (newValue) {
2424                self.acceptanceChanged.notifySubscribers();
2425            });
2426
2427
2428            this.isFullview = ko.observable(false);
2429            this.isExpanded = ko.observable(false);
2430
2431
2432            this.cancelEdit = function () {
2433                acDoc.userEditMode(false);
2434                acDoc.newAcceptanceStatus(acDoc.storedAcceptanceStatus());
2435                // reset changes
2436                return false;
2437            };
2438            this.goEditMode = function () {
2439                if (acDoc.Term().CurrRev > acDoc.Term().AcceptedRevision)
2440                    acDoc.newAcceptanceStatus(0);
2441
2442                acDoc.userEditMode(true);
2443                return false;
2444            };
2445            this.save = function (data) {
2446                self.saveCondition(data);
2447                return true;
2448            }
2449
2450        }
2451
2452        self.id = (id) ? (id[0] == '#') ? id.substring(1) : id : null;
2453        self.service = new WebApiService("Conditions");
2454
2455        self.highlightRequired = function (containerName) {
2456            var highlightThis;
2457            if ((containerName === undefined) || (containerName == null))
2458                highlightThis = $("#" + self.id + " .isRequired label:not(.active)");
2459            else
2460                highlightThis = $("#" + containerName + " .isRequired label:not(.active)");
2461            if (highlightThis.length > 0)
2462                mcWeb.validation.qTipActionShowClickHide(highlightThis[0], conditionsThis.conditionGetLanguageText("langtext-conditions-required"));
2463            return highlightThis.length > 0;
2464        };
2465
2466        self.isLoggedIn = ko.observable();
2467        self.selectedDocument = ko.observable(null);
2468
2469        self.isVisible = ko.observable(false);
2470        self.usageArea = 0;
2471        self.usageFunction = 0;
2472
2473        self.acceptanceChanged = ko.computed(function () {
2474            return false;
2475        }, this);
2476        self.acceptanceChanged.extend({ notify: 'always', rateLimit: 50 });
2477        self.acceptanceChanged.subscribe(function (newValue) {
2478            var evtArgs = { functionalConditionIsAccepted: null, acceptDocuments: [], usageArea: self.settings.usageArea, instanceId: self.id };
2479
2480            var needsFunctionAcceptance = false;
2481            var acceptedRequiredTerm = true;
2482
2483            ko.utils.arrayForEach(self.conditions(), function (doc) {
2484                if (self.settings.usageArea == 0)
2485                    doc.Term().Accepted = (doc.newAcceptanceStatus() > 0) ? true : (doc.newAcceptanceStatus() == 0) ? null : false;
2486                else
2487                    doc.Term().Accepted = doc.Accepted();
2488                evtArgs.acceptDocuments.push(doc.Term());
2489                if (doc.Term().TermRequiredForFunction) {
2490                    needsFunctionAcceptance = true;
2491                    if (!doc.Accepted())
2492                        acceptedRequiredTerm = false;
2493                }
2494            });
2495            self.acceptDocuments = evtArgs.acceptDocuments;
2496            if (!needsFunctionAcceptance)
2497                evtArgs.functionalConditionIsAccepted = null;
2498            else
2499                evtArgs.functionalConditionIsAccepted = acceptedRequiredTerm;
2500
2501            evtArgs.vm = self;
2502
2503            PubSub.publish(mcWeb.conditions.events.onAcceptChange, evtArgs);
2504
2505        });
2506        self.expandDoc = function (currentDoc) {
2507            self.collapseAllBut(currentDoc);
2508            currentDoc.isExpanded(!currentDoc.isExpanded());
2509        }
2510        self.goFullViewDoc = function (currentDoc) {
2511            $('.qtip').remove();
2512            self.collapseAllBut(currentDoc);
2513            currentDoc.isFullview(true);
2514            self.selectedDocument(currentDoc);
2515
2516            self.moveDocToLightbox();
2517        }
2518        self.removeFullViewDoc = function (currentDoc) {
2519            self.collapseAllBut(currentDoc);
2520            currentDoc.isFullview(false);
2521            self.selectedDocument(null);
2522            // Run only when not in lightbox-mode already
2523            if (!self.settings.isInLightbox)
2524                PubSub.publish(mcWeb.lightbox.events.onHideLightbox);
2525            else
2526                self.moveDocBackToPlaceholder();
2527        }
2528
2529        self.moveDocToLightbox = function () {
2530            $("#lightbox-placeholder").children().hide();
2531            if ($("#lightbox-placeholder > .FullAcceptDocument-UsageArea" + self.settings.usageArea).length == 0) {
2532                var elementToMove = $(".FullAcceptDocument-UsageArea" + self.settings.usageArea).detach();
2533                $("#lightbox-placeholder").append(elementToMove);
2534            }
2535
2536
2537            $("#lightbox-placeholder .FullAcceptDocument-UsageArea" + self.settings.usageArea).show();
2538            // Run only when not in lightbox-mode already
2539            if (!self.settings.isInLightbox)
2540                PubSub.publish(mcWeb.lightbox.events.onShowLightbox);
2541
2542        }
2543
2544        self.moveDocBackToPlaceholder = function () {
2545            $("#lightbox-placeholder").children().show();
2546            $("#lightbox-placeholder .conditionDocumentFull").hide();
2547
2548            if ($("#lightbox-placeholder > .FullAcceptDocument-UsageArea" + self.settings.usageArea).length == 1) {
2549                var elementToMove = $(".FullAcceptDocument-UsageArea" + self.settings.usageArea).detach();
2550                $(".FullDocPlaceholder-UsageArea" + self.settings.usageArea).append(elementToMove);
2551            }
2552        }
2553
2554        self.collapseAllBut = function (currentDoc) {
2555            if (self.settings.accordionstyleCollapse) {
2556                ko.utils.arrayForEach(self.conditions(), function (doc) {
2557                    if (currentDoc != doc) {
2558                        doc.isFullview(false);
2559                        doc.isExpanded(false);
2560                    }
2561                });
2562            }
2563        }
2564
2565        self.expandAll = function () {
2566            if (!self.settings.accordionstyleCollapse) {
2567                ko.utils.arrayForEach(self.conditions(), function (doc) {
2568                    doc.isFullview(false);
2569                    doc.isExpanded(true);
2570                });
2571            }
2572        }
2573
2574
2575        self.resetResponses = function () {
2576            ko.utils.arrayForEach(self.conditions(), function (doc) {
2577                doc.Accepted(false);
2578                doc.isFullview(false);
2579                doc.isExpanded(false);
2580                doc.newAcceptanceStatus(doc.storedAcceptanceStatus());
2581            });
2582        }
2583        self.load = function (data, settings) {
2584            $(".conditionDocumentFull").hide();
2585            if (!self.settings) {
2586                var initialSettings;
2587                if (settings) {
2588                    initialSettings = settings;
2589                }
2590
2591
2592                self.setSettings(initialSettings);
2593                if (initialSettings.status) {
2594                    self.refConditionsStatus = initialSettings.status;
2595                    PubSub.subscribe(mcWeb.conditions.events.onAcceptChange, function (evt, conditionStatus) {
2596                        if (self.id == conditionStatus.instanceId) {
2597                            if (conditionStatus.functionalConditionIsAccepted === null) {
2598                                self.refConditionsStatus.isFunctionalConditionAccepted(true);
2599                            }
2600                            else {
2601                                self.refConditionsStatus.isFunctionalConditionAccepted(conditionStatus.functionalConditionIsAccepted);
2602                            }
2603                            self.refConditionsStatus.acceptDocuments(conditionStatus.acceptDocuments);
2604                            $('.qtip').remove();
2605                            if (self.settings.useSessionDocumentAcceptance)
2606                                self.updateSessionCondition();
2607                        }
2608                    });
2609                }
2610                PubSub.subscribe(mcWeb.lightbox.events.onHideLightbox, function () {
2611                    self.moveDocBackToPlaceholder();
2612                });
2613            }
2614
2615
2616            if (data == null) {
2617                self.fetchConditions();
2618                return;
2619            } else
2620                self.bindConditions(data);
2621        }
2622        self.fetchConditions = function () {
2623            var selfFetch = this;
2624            var email = (self.settings.emailAddress == null) ? mcWeb.currentUser.getUser() : null;
2625
2626            if (!!self.settings && self.settings.emailAddress != null && self.settings.emailAddress.length > 0) {
2627                email = self.settings.emailAddress;
2628            }
2629
2630            var param = {
2631                UsageArea: (self.settings.usageArea == 0) ? null : self.settings.usageArea,
2632                SpraakId: null,
2633                AvsAdresseId: null,
2634                KndKontaktId: null,
2635                DomainId: null,
2636                FunctionName: self.settings.usageFunction,
2637                ForUnknownUser: self.settings.forUnknownUser
2638            };
2639            self.service.PostAction(
2640                (param.UsageArea != null) ? "ListAcceptDocumentsNotAcceptedOrIsRepeatable" : "ListAcceptDocuments"
2641                , param).then(function (result) {
2642                    if (result != null) {
2643                        if ((self.settings.usageArea === 3 || self.settings.usageArea === 1)) {
2644                            // Customerregistration and checkout
2645                            var paramCustReg = param;
2646                            paramCustReg.UsageArea = 2;
2647                            paramCustReg.FunctionName = "CUSTOMERREGISTRATION";
2648                            var checkoutResult = result;
2649                            self.service.PostAction("ListAcceptDocumentsNotAcceptedOrIsRepeatable", paramCustReg).then(function (customerRegistrationResult) {
2650                                var accumulatedResult = new Array();
2651
2652                                for (var i = 0; i < checkoutResult.length; i++) {
2653                                    var currentResult = checkoutResult[i];
2654                                    currentResult.storedAcceptanceStatus = currentResult.Accepted;
2655                                    accumulatedResult.push(currentResult);
2656                                }
2657
2658                                for (var i = 0; i < customerRegistrationResult.length; i++) {
2659                                    var currentResult = customerRegistrationResult[i];
2660                                    currentResult.storedAcceptanceStatus = currentResult.Accepted;
2661                                    if (self.settings.usageArea !== 1)
2662                                        accumulatedResult.push(currentResult);
2663                                    else {
2664                                        if (currentResult.TermRequiredForFunction) {
2665                                            accumulatedResult.push(currentResult);
2666                                        }
2667                                    }
2668                                }
2669                                //accumulatedResult = customerRegistrationResult.concat(checkoutResult);
2670                                if ((checkoutResult.length != 0) && (customerRegistrationResult.length != 0)) {
2671                                    var keyCb = function (val) { return val.DocumentID; }
2672                                    var seen = {};
2673                                    var uniqueArray = accumulatedResult.filter(function (item) {
2674                                        var k = keyCb(item);
2675                                        return seen.hasOwnProperty(k) ? false : (seen[k] = true);
2676                                    });
2677                                    // Don't miss any RequiredForFunction
2678                                    for (var accuIndex = 0; accuIndex < accumulatedResult.length; accuIndex++) {
2679                                        for (var uniqueIndex = 0; uniqueIndex < uniqueArray.length; uniqueIndex++) {
2680                                            if (uniqueArray[uniqueIndex].DocumentID == accumulatedResult[accuIndex].DocumentID) {
2681                                                if (uniqueArray[uniqueIndex].TermRequiredForFunction == null && accumulatedResult[accuIndex].TermRequiredForFunction != null) {
2682                                                    uniqueArray[uniqueIndex].TermRequiredForFunction = accumulatedResult[accuIndex].TermRequiredForFunction;
2683                                                }
2684                                            }
2685                                        }
2686                                    }
2687                                    accumulatedResult = uniqueArray.sort(function (a, b) {
2688                                        return a.TermRequiredForFunction < b.TermRequiredForFunction;
2689                                    });
2690                                }
2691
2692                                self.bindConditions(accumulatedResult);
2693                            });
2694
2695                        } else
2696                            self.bindConditions(result);
2697                    } else
2698                        self.bindConditions(null);
2699                });
2700        }
2701        self.bindConditions = function (data) {
2702            if (data != null) {
2703                if (data.length > 0) {
2704                    var isKundesenterUsageArea = false;
2705                    if (self.settings) {
2706                        if (self.settings.usageArea == 0)
2707                            isKundesenterUsageArea = true;
2708                    }
2709
2710                    if (self.conditions().length == 0) {
2711                        // Add all
2712                        for (index = 0; index < data.length; ++index) {
2713                            self.conditions.push(new self.AcceptDoc(data[index], isKundesenterUsageArea));
2714                        }
2715                    } else {
2716                        // Add any new
2717                        for (index = 0; index < data.length; ++index) {
2718                            var docAlreadyBound = false;
2719                            ko.utils.arrayForEach(self.conditions(),
2720                                function (doc) {
2721                                    if (doc.Term().DocumentID == data[index].DocumentID)
2722                                        docAlreadyBound = true;
2723                                });
2724                            if (!docAlreadyBound)
2725                                self.conditions.push(new self.AcceptDoc(data[index], isKundesenterUsageArea));
2726                        }
2727                        // Remove any in self.conditions that's not in new resultset
2728                        // First, find which to remove
2729                        var removeTheseIndexes = [];
2730                        for (var condIndex = 0; condIndex < self.conditions().length; ++condIndex) {
2731                            var docInNewResultset = false;
2732                            for (var index = 0; index < data.length; ++index) {
2733                                if (self.conditions()[condIndex].Term().DocumentID == data[index].DocumentID)
2734                                    docInNewResultset = true;
2735                            }
2736                            if (!docInNewResultset)
2737                                removeTheseIndexes.push(condIndex);
2738                        }
2739                        console.log("conditions().length before =" + self.conditions().length);
2740                        // Second, perform removal (if needed)
2741                        console.log("to be removed:" + removeTheseIndexes.length);
2742                        if (removeTheseIndexes.length > 0) {
2743                            // IMPORTANT: MUST loop through in "reverse" order, be
2743cause reomval from back of array won't mess up indexes.
2744                            for (var removeIndex = removeTheseIndexes.length - 1; removeIndex >= 0; removeIndex--) {
2745                                self.conditions.splice(removeTheseIndexes[removeIndex], 1);
2746                            }
2747                        }
2748                        console.log("conditions().length after =" + self.conditions().length);
2749                    }
2750                } else
2751                    self.conditions([]);
2752            } else
2753                self.conditions([]);
2754
2755            self.acceptanceChanged.notifySubscribers();
2756            PubSub.publish(mcWeb.conditions.events.onConditionsBound, self.settings.usageArea);
2757        };
2758
2759        self.saveCondition = function (term) {
2760
2761            var userEmail = mcWeb.currentUser.getUser();
2762
2763            var doc = term.Term();
2764            var acceptStatus = term.Accepted();
2765
2766            var myParams = {
2767                Accept: acceptStatus,
2768                DocUsageId: doc.DocUsageID,
2769                RevDataId: doc.RevDataID,
2770                AvsAdresseID: null,
2771                DomainId: null,
2772                EmailAddress: userEmail,
2773                ReferenceString: doc.FunctionReferenceString
2774            };
2775            if (myParams.Accept != null) {
2776                self.service.PostAction("RegisterTermAcceptance", myParams).then(function (result) {
2777                    if (result) {
2778                        if (result.RetCode === 0) {
2779                            term.storedAcceptanceStatus((myParams.Accept === null) ? "0" : (myParams.Accept) ? "1" : "0");
2780                            term.newAcceptanceStatus(term.storedAcceptanceStatus());
2781                        }
2782                        else
2783                            console.log("RetCode:" + result.RetCode);
2784
2785                    }
2786                });
2787            }
2788        }
2789        self.updateSessionCondition = function () {
2790            var ConditionDocuments = [];
2791            ko.utils.arrayForEach(self.conditions(), function (doc) {
2792                ConditionDocuments.push(
2793                    {
2794                        Accepted: doc.Accepted(),
2795                        DocUsageID: doc.Term().DocUsageID,
2796                        DocumentID: doc.Term().DocumentID,
2797                        RevDataID: doc.Term().RevDataID
2798                    }
2799                );
2800            });
2801
2802            if (ConditionDocuments.length > 0) {
2803                self.service.PostAction("UpdateCurrentSessionAcceptDocuments", { '': ConditionDocuments }).then(function () {
2804                    console.log("Sesssion updated");
2805                });
2806            }
2807        }
2808
2809    };
2810}(jQuery));
2811
2812
2813;
2814mcWeb.userConditions = new function () {
2815
2816    this.events = {
2817    }
2818
2819    this.vm = function (id) {
2820        var self = this;
2821        this.id = "#" + id;
2822        this.conditionVM = new mcWeb.conditions.vm(self.id);
2823        this.conditionsStatus = {
2824            isFunctionalConditionAccepted: ko.observable(false),
2825            acceptDocuments: ko.observableArray([]),
2826            usageArea: null
2827        };
2828        this.isLoading = ko.observable(true);
2829        this.initialAcceptChange = true;
2830        this.conditionsStored = ko.observable(true); //true because initial is fetched from server
2831        this.conditionsStoringSuccessfull = ko.observable(false);
2832        this.responseCounter = 0;
2833        this.expectedResponses = 0;
2834
2835        this.conditions = ko.observableArray([]);
2836
2837        self.doBind = function () {
2838            PubSub.subscribe(mcWeb.conditions.events.onAcceptChange, function (evt, conditionStatus) {
2839                if (self.conditionsStatus.usageArea == conditionStatus.usageArea) {
2840                    if (self.initialAcceptChange) {
2841                        self.conditionsStored(true);
2842                        self.initialAcceptChange = false;
2843                    } else
2844                        self.conditionsStored(false);
2845                    self.conditionsStoringSuccessfull(false);
2846                }
2847            });
2848            self.conditionVM.load(ko.toJS(self.conditions), { usageArea: self.conditionsStatus.usageArea, forUnknownUser: false, isInLightbox: false, status: self.conditionsStatus });
2849            self.conditionVM.isVisible(true);
2850            self.isLoading(false);
2851
2852        };
2853
2854        self.service = new WebApiService("Conditions");
2855
2856
2857        this.load = function (data, settings) {
2858            self.isLoading(true);
2859
2860            var userEmail = mcWeb.currentUser.getUser();
2861            
2862            self.conditions([]);
2863
2864            var param = {
2865                UsageArea: this.conditionsStatus.usageArea,
2866                SpraakId: null,
2867                AvsAdresseId: null,
2868                KndKontaktId: null,
2869                EmailAddress: userEmail,
2870                DomainId: null,
2871                FunctionName: null,
2872                ForUnknownUser:false
2873            };
2874
2875            self.service.PostAction("ListAcceptDocuments", param).then(function (result) {
2876                if (result != null) {
2877                    for (index = 0; index < result.length; ++index) {
2878                        self.conditions.push(result[index]);
2879                    }
2880                }
2881                self.doBind();
2882            });
2883
2884         
2885        };
2886    };
2887};
2888;
2889mcWeb.countrySelector = new function () {
2890    var $ = jQuery;
2891    var self = this;
2892
2893    self.events = {
2894        onStartRefresh : "mcWeb.countrySelector.onStartRefresh"
2895            };
2896    
2897    self.changedCountryValues = {
2898        CountryId: -1,
2899        LanguageId: -1,
2900        PricesExVat: false,
2901        CultureCode: null,
2902        ValutaHistoryId: -1,
2903        ValutaId: -1,
2904        ValutaTabellId: -1,
2905        Valuta: null
2906        };
2907    self.service = new WebApiService("Login");
2908
2909    PubSub.subscribe("mcWeb.countrySelector.onStartRefresh", function (message, options) {
2910        self.service.PostAction("GetCountryLangCurrencySelector").then(function (result) {
2911            if (result && result.Success) {
2912                $(".content-countrylangcurrency-selector").replaceWith(result.Content);
2913            }
2914        });
2915    });
2916
2917    self.saveCountryLang = function () {
2918        $('#UpdateIcon').show();
2919        self.service.PostAction("ChangeCountryLangCurrency", self.changedCountryValues).then(function (result) {
2920            if (result) {
2921                if (result.OldLangPrefix == result.LangPrefix || $("body.body-product-info").length === 0) {
2922                    window.location.reload();
2923                }
2924                else {
2925                    var newPath = document.location.pathname.replace(result.OldLangPrefix, result.LangPrefix);//use this ONLY when we're on a productpage
2926                    document.location.pathname = newPath;
2927                }
2928            }
2929            else {
2930                PubSub.publish(mcWeb.lightbox.events.onHideLightbox);
2931                $('#UpdateIcon').hide();
2932            }
2933        });
2934    };
2935    self.cancel = function () {
2936        self.changedCountryValues = {
2937            CountryId: -1,
2938            LanguageId: -1,
2939            PricesExVat: false,
2940            CultureCode: null,
2941            ValutaHistoryId: -1,
2942            ValutaId: -1,
2943            ValutaTabellId: -1,
2944            Valuta: null
2945        };
2946
2947        PubSub.publish(mcWeb.lightbox.events.onHideLightbox);
2948
2949    };
2950    self.setActiveCountry = function (item) {
2951        self.changedCountryValues.CountryId = jQuery(item).data("c
2951ountry-id");
2952        var changed = $(item).data("title") !=$("#country-selector-dropdown").data("orig-name") ;
2953        var newTitle = $(item).data("title");
2954        if (changed) 
2955            newTitle += " *";
2956
2957        var param = {
2958            countryId: self.changedCountryValues.CountryId
2959            };
2960        self.service.GetAction("GetDefaultCurrencyForCountry", param).then(function (result) {
2961            if (result != undefined && result != null && result.Success) {
2962                jQuery("#content-currency-selector li a").filter("[data-valuta='" + result.CurrencyCode + "']").trigger("click");
2963            }
2964            self.service.GetAction("GetDefaultLanguageFromCountry", param).then(function (result2) {
2965                if (result2 != undefined && result2 != null && result2.Success) {
2966                    jQuery("#content-language-selector li img").filter("[data-language-id=" + result2.LanguageId + "]").trigger("click");
2967                }
2968            });
2969        });
2970        
2971        $("#country-selector-dropdown").text(newTitle);    
2972    }
2973
2974    self.selectCountry = function (item){
2975        var param = {
2976            CountryId : jQuery(item).data("country-id")
2977        };
2978
2979        self.service.PostAction("SelectCountry", param).then(function(res){
2980            if(res){
2981                document.location.reload(true);
2982            }
2983        });
2984    };
2985
2986    self.selectedCountryByIdNoPageReload = function (countryId) {
2987        var param = {
2988            CountryId : countryId
2989        };
2990
2991        self.service.PostAction("SelectCountryById", param).then(function(res){
2992            if(res){
2993                PubSub.publish("mcWeb.countrySelector.onStartRefresh",null);
2994                PubSub.publish( mcWeb.cart.events.onChangedCart);
2995                //Reload shipments if it changed
2996                PubSub.publish(mcWeb.shipment.events.reloadShipment, null);
2997            }
2998        });
2999    }
3000
3001    self.setActiveLanguage = function (item) {
3002        self.changedCountryValues.LanguageId = $(item).data("language-id");
3003        self.changedCountryValues.PricesExVat = $(item).data("prices-ex-vat");
3004        self.changedCountryValues.CultureCode = $(item).data("culture-code");
3005        $("#content-language-selector li").removeClass("active");
3006        $(item).parent("li").addClass("active");
3007    };
3008    self.setLanguage = function (item) {
3009        var param = {
3010            LanguageId : $(item).data("language-id"),
3011            PricesExVat : $(item).data("prices-ex-vat"),
3012            CultureCode : $(item).data("culture-code")
3013        };
3014
3015        self.service.PostAction("SelectCulture", param).then(function(res){
3016            if(res){
3017                document.location.reload(true);
3018            }
3019        });
3020    };
3021
3022    self.loadSelectors = function (me) {
3023        $('#UpdateIcon').show();
3024        if ($("body.device-size-xs").length > 0) {
3025            jQuery('button.mmenu_close').click()
3026        }
3027        
3028        $("#lightbox-placeholder").load("/Webpages/Kunde/CountryLangCurrencyView.aspx", function () {
3029            //$(me).removeClass("animate-spin");
3030            if (!!mcWeb.inlineEditor)
3031                mcWeb.inlineEditor.init(true);
3032
3033            if ($("#content-countrylangcurrency").length > 0) {
3034                PubSub.publish(mcWeb.lightbox.events.onShowLightbox, {
3035                    css: 'country-selector-popup',
3036                    callback: function () {
3037                        $('#UpdateIcon').hide();
3038                    }
3039                });
3040            }
3041            else {
3042                $('#UpdateIcon').show();
3043            }
3044            
3045        });
3046    };
3047
3048    self.setActiveCurrency = function (item) {
3049        self.changedCountryValues.ValutaHistoryId = jQuery(item).data("valuta-history-id");
3050        self.changedCountryValues.ValutaId = jQuery(item).data("valuta-id");
3051        self.changedCountryValues.ValutaTabellId = jQuery(item).data("valuta-tabell-id");
3052        self.changedCountryValues.Valuta = $(item).data("valuta");
3053        var changed = $(item).data("title") != $("#currency-selector-dropdown").data("orig-name");
3054        var newTitle = $(item).data("title");
3055        if(changed )
3056            newTitle += " *";
3057        $("#currency-selector-dropdown").text(newTitle);
3058    };
3059
3060    self.selectCurrency = function (item) {
3061        var param = {
3062            ValutaHistoryId: jQuery(item).data("valuta-history-id"),
3063            ValutaId: jQuery(item).data("valuta-id"),
3064            ValutaTabellId: jQuery(item).data("valuta-tabell-id"),
3065            Valuta: $(item).data("valuta")
3066        }
3067
3068        self.service.PostAction("SelectCurrency", param).then(function(res){
3069            if(res){
3070                document.location.reload(true);
3071            }
3072        });
3073    };
3074};;
3075mcWeb.login2FAReg = new (function ($) {
3076    'use strict';
3077    //mcWeb.loginAgent = new function () {
3078    var self = this;
3079    self.service = new WebApiService("Login");
3080    self.isClosedShop = false;
3081    self.lightboxOptions = null;
3082    self.registrationPath = "/webpages/kunde/login2faregview.aspx";
3083    self.verifyCodePath = "/webpages/kunde/login2favalidationview.aspx";
3084    var loadInitReg = function (placeholderId, binElementId, twoFactorStatus) {
3085
3086        if (window.location.pathname.toLowerCase().indexOf("loginlukketshop") !== -1)
3087            self.isClosedShop = true;
3088
3089        PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3090        $("#" + placeholderId).load(self.registrationPath, function () {
3091            if ($("#" + placeholderId).length < 1) {
3092                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3093                return;
3094            }//Module not active
3095
3096            mcWeb.login2FAReg.activateView(twoFactorStatus, binElementId);
3097
3098            PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3099
3100            if (!!mcWeb.inlineEditor)
3101                mcWeb.inlineEditor.init(true);
3102        });
3103    };
3104
3105    var loadInitVerifyCode = function (placeholderId, binElementId, twoFactorStatus) {
3106
3107        if (window.location.pathname.toLowerCase().indexOf("loginlukketshop") !== -1)
3108            self.isClosedShop = true;
3109
3110        PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3111        $("#" + placeholderId).load(self.verifyCodePath, function () {
3112            if ($("#" + placeholderId).length < 1) {
3113                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3114                return;
3115            }//Module not active
3116
3117            mcWeb.login2FAReg.activateVerifyView(twoFactorStatus, binElementId);
3118            PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3119
3120            if (!!mcWeb.inlineEditor)
3121                mcWeb.inlineEditor.init(true);
3122        });
3123    };
3124    
3125
3126    self.load = function (twoFactorStatus, loginView) {
3127        self.loginView = loginView;
3128        self.loginData = loginView.data;
3129        if (twoFactorStatus.Show2FACodeInput)           
3130            loadInitVerifyCode("lightbox-placeholder", "login-2fa-verify", twoFactorStatus);
3131        else loadInitReg("lightbox-placeholder", "login-2fa-reg", twoFactorStatus);
3132    };
3133
3134
3135    self.activateView = function (twoFactorStatus, binElementId) {
3136        self.viewModelReg = new viewModel2FAReg(twoFactorStatus);
3137        ko.applyBindings(self.viewModelReg, document.getElementById(binElementId));
3138
3139    };
3140
3141    self.activateVerifyView = function (twoFactorStatus, binElementId) {
3142        self.viewModelVerify = new viewModel2FAVerify(twoFactorStatus);
3143        ko.applyBindings(self.viewModelVerify, document.getElementById(binElementId));
3144
3145    };
3146    self.validateCode = function (evt) {
3147        self.viewModelVerify.validateCode();
3148        evt.preventDefault();
3149    };
3150
3151    var viewModel2FAReg = function (data) { //Internal
3152        var view = this;
3153        view.ManualEntryKey = ko.observable(data.ManualEntryKey);
3154        view.QrCodeSetupImageUrl = ko.observable(data.QrCodeSetupImageUrl);
3155        view.ContactId = data.ContactId;
3156        view.CodeFromApp = ko.observable('');
3157        view.ShopName = ko.observable(data.ShopName);
3158        view.Require2FA = ko.observable(data.Required);
3159        view.ShowCodeNotValidError = ko.observable(false);
3160        view.TwoFAClockAppearsIncorrect = ko.observable(false);
3161        view.RegisterAccountNameText = ko.observable(data.RegisterAccountNameText);
3162        PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3163
3164        if (($('.body-checkout').length > 0)) {
3165            //publish event here!
3166            if ($("body.layoutver4").length > 0 && self.lightboxOptions === null) {
3167                self.lightboxOptions = { keyboard: true, show: true, variantData: {}, deferred: false, css: 'two-factor-modal' };
3168            }
3169
3170            //publish event here!
3171            if (self.lightboxOptions === null)
3172                PubSub.publish(mcWeb.lightbox.events.onShowLightbox);
3173            else
3174                PubSub.publish(mcWeb.lightbox.events.onShowLightbox, self.lightboxOptions);
3175        }
3176
3177        //Link event
3178        view.registerCode = function (viewmodel, event) {
3179            event.preventDefault();
3180            PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3181            view.ShowCodeNotValidError(false);
3182            view.TwoFAClockAppearsIncorrect(false);
3183            var params = {
3184                CodeFromApp: view.CodeFromApp(),
3185                ContactId: view.ContactId,
3186                Data: self.loginData
3187            }
3188            self.service.PostAction("RegisterSecurityCode", params).then(function (result) {
3189                if (result.Success) {
3190                    PubSub.unsubscribe(view.resetLoginBox);//must be removed before onHideLightbox to avoid calling logic only meant for when we cancel 
3191                    PubSub.publish(mcWeb.lightbox.events.modifyOptions, { clearCss: true });                    
3192                    self.loginView.loginResult(result);
3193                }
3194                else {
3195                    view.ShowCodeNotValidError(true);
3196                    if (result.TwoFactorStatus !== null) {
3197                        view.TwoFAClockAppearsIncorrect(result.TwoFactorStatus.TwoFAClockAppearsIncorrect);
3198                        view.ShowCodeNotValidError(!result.TwoFactorStatus.TwoFAClockAppearsIncorrect);
3199                    }
3200
3201                }
3202                
3203                
3204                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3205            });
3206
3207        };// END Link event
3208
3209        view.cancel = function () {            
3210            self.loginView.load();
3211            PubSub.publish(mcWeb.lightbox.events.modifyOptions, { clearCss: true });
3212            PubSub.publish(mcWeb.lightbox.events.contentChanged);   
3213
3214            if (self.loginView.isCheckout()) {
3215                PubSub.publish(mcWeb.lightbox.events.onHideLightbox);
3216            }
3217        }
3218
3219        view.skipTwoFactor = function () {
3220            PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3221            view.ShowCodeNotValidError(false);
3222            view.TwoFAClockAppearsIncorrect(false);
3223            var params = {                
3224                ContactId: view.ContactId,
3225                Data: self.loginData
3226            }
3227            self.service.PostAction("TurnOff2FactorAndLogIn", params).then(function (result) {
3228                PubSub.publish(mcWeb.lightbox.events.modifyOptions, { clearCss: true });
3229                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3230                self.loginView.loginResult(result);
3231            });
3232        }
3233
3234        PubSub.publish(mcWeb.lightbox.events.modifyOptions, { css: 'two-factor-modal' });
3235        PubSub.publish(mcWeb.lightbox.events.contentChanged);       
3236        PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3237
3238        view.resetLoginBox = function () {
3239            self.loginView.load();
3240            PubSub.unsubscribe(view.resetLoginBox);
3241        };
3242
3243        PubSub.subscribe(mcWeb.lightbox.events.onHideLightbox, view.resetLoginBox);
3244
3245    };
3245 /*END viewModel2FAReg*/
3246
3247
3248    var viewModel2FAVerify = function (data) { //Internal
3249        PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3250        var view = this;        
3251        view.ContactId = data.ContactId;
3252        view.CodeFromApp = ko.observable('');
3253        view.ShopName = ko.observable(data.ShopName);
3254        view.ShowShopName = ko.observable(data.ShowShopName);
3255        view.ShowInvalidCodeMsg = ko.observable(false);
3256        view.ShowEmailCodeSent = ko.observable(false);
3257        view.TwoFAClockAppearsIncorrect = ko.observable(false);
3258        if (($('.body-checkout').length > 0)) {
3259            //publish event here!
3260            if ($("body.layoutver4").length > 0 && self.lightboxOptions === null) {
3261                self.lightboxOptions = { keyboard: true, show: true, variantData: {}, deferred: false, css: 'two-factor-modal' };
3262            }
3263
3264            //publish event here!
3265            if (self.lightboxOptions === null)
3266                PubSub.publish(mcWeb.lightbox.events.onShowLightbox);
3267            else
3268                PubSub.publish(mcWeb.lightbox.events.onShowLightbox, self.lightboxOptions);
3269        }
3270        //Link event
3271        view.validateCode = function (viewmodel,event) {
3272            event.preventDefault();
3273            PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3274            view.TwoFAClockAppearsIncorrect(false);
3275            var params = {
3276                CodeFromApp: view.CodeFromApp(),                
3277                ContactId: view.ContactId,
3278                Data: self.loginData
3279            }
3280            self.service.PostAction("VerifySecurityCode", params).then(function (result) {
3281                if (result.Success) {
3282                    PubSub.unsubscribe(view.resetLoginBox);//must be removed before onHideLightbox to avoid calling logic only meant for when we cancel 
3283                    PubSub.publish(mcWeb.lightbox.events.modifyOptions, { clearCss: true });
3284                    self.loginView.loginResult(result);
3285                    if (self.loginView.isCheckout()) {
3286                        PubSub.publish(mcWeb.lightbox.events.onHideLightbox);
3287                    }
3288                    
3289                }
3290                else {
3291                    view.ShowInvalidCodeMsg(true);
3292                    view.ShowEmailCodeSent(false);
3293                    if (result.TwoFactorStatus !== null) {
3294                        view.TwoFAClockAppearsIncorrect(result.TwoFactorStatus.TwoFAClockAppearsIncorrect);
3295                        view.ShowInvalidCodeMsg(!result.TwoFactorStatus.TwoFAClockAppearsIncorrect);
3296                    }
3297                }
3298                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3299
3300            });
3301
3302        };// END validateCode
3303         
3304        view.cancel = function () {                
3305            self.loginView.load();
3306            PubSub.publish(mcWeb.lightbox.events.modifyOptions, { clearCss: true });
3307            PubSub.publish(mcWeb.lightbox.events.contentChanged);   
3308            if (self.loginView.isCheckout()) {
3309                PubSub.publish(mcWeb.lightbox.events.onHideLightbox);
3310            }
3311        };
3312
3313        view.sendCodeByMail = function () {
3314            view.TwoFAClockAppearsIncorrect(false);
3315            view.ShowInvalidCodeMsg(false);
3316            PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3317            var params = {
3318                ContactId: view.ContactId,
3319                Data: self.loginData
3320            };
3321            self.service.PostAction("SendCodeByMail", params).then(function (result) {
3322                if (result.Success) {
3323                    view.ShowEmailCodeSent(true);
3324                }                
3325                else {
3326                    view.ShowInvalidCodeMsg(true);
3327                }
3328                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3329            });
3330        };
3331        PubSub.publish(mcWeb.lightbox.events.contentChanged);
3332        PubSub.publish(mcWeb.lightbox.events.modifyOptions, { css: 'two-factor-modal' });
3333        PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3334
3335        
3336
3337        view.resetLoginBox = function(){
3338            self.loginView.load();
3339            PubSub.unsubscribe(view.resetLoginBox);
3340        };
3341
3342        PubSub.subscribe(mcWeb.lightbox.events.onHideLightbox, view.resetLoginBox);
3343
3344    };
3344 /*END viewModel2FAReg*/
3345
3346    this.logout = function () {
3347        try {
3348            window.StorageService.localStorage.removeItem('id');
3349            window.StorageService.localStorage.removeItem('user');
3350            window.StorageService.localStorage.removeItem('remember');
3351            window.StorageService.localStorage.removeItem('authenticatedGuid');
3352            window.StorageService.localStorage.removeItem('remember');
3353        } catch (e) {
3354            console.error('LoginAgentView.logout - ex: ' + e);
3355        }
3356        mcWeb.login.logout();
3357    };
3358
3359    self.sendCodeByMail = function (showUponSuccess, showUponError) {
3360        self.service.PostAction("SendCodeByMailLoggedIn").then(function (result) {
3361            if (result.Success) {
3362                if (showUponSuccess != undefined && showUponSuccess != null) {
3363                    $(showUponSuccess).removeClass("hidden");
3364                    setTimeout(function () {
3365                        $(showUponSuccess).addClass("hidden")
3366                    }, 5000);
3367                }
3368            }
3369            else {
3370                if (showUponError != undefined && showUponError != null) {
3371                    $(showUponError).removeClass("hidden");
3372                    setTimeout(function () {
3373                        $(showUponError).addClass("hidden")
3374                    }, 5000);
3375                }
3376            }
3377        });
3378
3379    };
3380
3381})(jQuery);
3382;
3383mcWeb.loginAgent = new (function ($) {
3384  'use strict';
3385  //mcWeb.loginAgent = new function () {
3386  var self = this;
3387  self.service = new WebApiService("Login");
3388  self.isClosedShop = false;
3389
3390  var loadInit = function (agent, placeholderId, binElementId) {
3391
3392    if (window.location.pathname.toLowerCase().indexOf("loginlukketshop") !== -1)
3393      self.isClosedShop = true;
3394
3395    PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3396    $(placeholderId).load("/Webpages/Kunde/LoginAgentView.aspx", function () {
3397      if ($("#login-agent").length < 1) {
3398        PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3399        return;
3400      }//Module not active
3401
3402      mcWeb.loginAgent.activateView(agent, binElementId);
3403
3404      PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3405
3406      if (!!mcWeb.inlineEditor)
3407        mcWeb.inlineEditor.init(true);
3408    });
3409    };
3410
3411    var loadLastSearch = function () {
3412        PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3413
3414        self.service.GetAction("LoadAgentLastSearch").then(function (result) {
3415            PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3416
3417            if (result !== null) {
3418                loadInit(result, "#lightbox-placeholder", "login-agent");                
3419            } else {
3420                mcWeb.login.load();
3421            }
3422        });
3423    };//End Load Contacts
3424
3425  self.load = function (loginView,agent) {
3426      self.loginView = loginView;
3427    if (agent == null) {
3428        loadLastSearch();
3429        return;
3430    }
3431        loadInit(agent, "#lightbox-placeholder", "login-agent");
3432    };
3433    
3434
3435  self.activateView = function (agent, binElementId) {
3436    var isLogin = (binElementId === "login-agent") ? true : false;
3437    ko.applyBindings(new viewModelAgent(agent, isLogin), document.getElementById(binElementId));
3438    if (isLogin) {
3439      PubSub.publish(mcWeb.lightbox.events.onShowLightbox, { show: true, css: 'login-agent-dialog' });
3440      setTimeout(function () {
3441        $('#agent-search-input').focus();
3442      }, 1000);
3443    }
3444
3445  };
3446
3447    var viewModelAgent = function (data) { //Internal
3448        var view = this;
3449        view.searchKey = '';
3450        view.showSearch = ko.observable(true);
3451        view.contactName = ko.observable(data.ContactName);
3452        if (data.SearchKey != null) {
3453            view.query = ko.observable(data.SearchKey);
3454            view.Customers = ko.observableArray(data.SearchResults);
3455        } else {
3456            view.query = ko.observable("");
3457            view.Customers = ko.observableArray();
3458            view.Customers(null);
3459        }
3460    
3461        //Link event
3462        view.loginContact = function (contact) {
3463            PubSub.publish(mcWeb.hamburgerMenu.events.onMenuNeedsRefresh);
3464            PubSub.publish(mcWeb.MegaMenuResponsive.events.onMenuNeedsRefresh);
3465            PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3466            var obj = {
3467                loginAsMe: (contact.CustomerNo == null && contact.ContactId == null) ? true : false,
3468                customerNo: (contact.CustomerNo == null) ? null : contact.CustomerNo,
3469                contactId: (contact.ContactId == null) ? null : contact.ContactId,
3470                loginType: 4
3471            };
3472
3473            self.service.PostAction("LoginContact", obj).then(function (result) {
3474
3475                if (result != null && result.Success === true) {
3476                    if (self.loginView !== undefined && self.loginView !== null) {
3477                        self.loginView.loginResult(result);
3478                    }
3479                    else if (self.isClosedShop) {
3480                        window.location.href = "/";
3481                    }
3482                    else if (result.HrefLangLookupKey) {
3483                        let targetUrls = $("head link[rel='alternate'][hreflang='" + result.HrefLangLookupKey + "']");
3484                        if (targetUrls !== undefined && targetUrls.length > 0) {
3485                            window.location.href = targetUrls[0].href;
3486                        }
3487                        else window.location.href = document.location.href.replace(location.hash, "");
3488                    }                    
3489                } else {
3490                    PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3491                    mcWeb.login.load();
3492                }
3493            });//End Web Api: LoginContact
3494
3495        };// END Link event
3496
3497        view.onAgentSearchKeyPress = function (event) {
3498            if (event.keyCode === 13) {
3499                event.preventDefault();
3500                if (view.Customers() && view.Customers().length === 1) { //If only one result, login
3501                    const customer = view.Customers()[0];
3502                    view.loginContact(customer);
3503                }
3504            }
3505        }
3506
3507        view.search = function(value) {
3508
3509            if (value != null && value.length < 2) {
3510                view.Customers(null);
3511                return;
3512            }
3513
3514            view.searchKey = value;
3515
3516            setTimeout(function() {
3517
3518                if (view.searchKey === value) {
3519                    PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3520
3521                    self.service.PostAction("AgentSearch", { Search: value }).then(function(result) {
3522                        view.Customers((result != null && result.length) ? result : null);
3523                        PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3524                    });
3525                }
3526            }, 1000);
3527
3528            
3529        };
3530
3531        view.query.subscribe(view.search);
3532
3533    };
3533 /*END viewModelAgent*/
3534
3535    this.logout = function () {
3536        try {
3537            window.StorageService.localStorage.removeItem('id');
3538            window.StorageService.localStorage.removeItem('user');
3539            window.StorageService.localStorage.removeItem('remember');
3540            window.StorageService.localStorage.removeItem('authenticatedGuid');
3541            window.StorageService.localStorage.removeItem('remember');
3542        } catch (e) {
3543            console.error('LoginAgentView.logout - ex: ' + e);
3544        }
3545        mcWeb.login.logout();
3546    };
3547
3548})(jQuery);
3549;
3550mcWeb.loginAvsAdresse = new function () {
3551	var $ = jQuery;
3552	var self = this;
3553	self.service = new WebApiService("Login");
3554    self.isClosedShop = false;
3555    self.data = {};
3556
3557   var loadInit = function(avsenders, placeholderId, binElementId) {
3558
3559		if (window.location.pathname.toLowerCase().indexOf("loginlukketshop") !== -1)
3560			self.isClosedShop = true;
3561
3562		PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3563        $(placeholderId).load("/Webpages/Kunde/LoginAvsAdresseView.aspx", function () {
3564            if ($("#login-avs-adresse").length < 1) {
3565				PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3566				return;
3567			}//Module not active
3568
3569            mcWeb.loginAvsAdresse.activateView(avsenders, binElementId);
3570
3571			PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3572
3573            if (mcWeb.inlineEditor !== undefined)
3574				mcWeb.inlineEditor.init(true);
3575		});
3576    };
3577
3578    self.load = function (loginView, data, avsenders) {
3579        self.loginView = loginView;
3580        if (data === null || avsenders === null) {
3581            return;
3582        }
3583
3584        self.data = data;
3585        loadInit(avsenders, "#lightbox-placeholder", "login-avs-adresse");
3586    };
3587
3588    var ViewModelavsenders = function (avsenders) { //Internal
3589		var view = this;
3590        view.avsenders = ko.observableArray(avsenders);
3591		
3592		//Link event
3593		view.loginSender = function (sender) {
3594
3595			PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3596            self.data.avsAdresseId = sender.AvsAdresseId;
3597
3598            self.service.PostAction("Login", self.data).then(function (result) {
3599				
3600                if (result != null && result.Success === true) {
3601                    if (self.loginView !== undefined && self.loginView !== null)
3602                        self.loginView.loginResult(result);
3603                    else mcWeb.login.loginResult(result);
3604				} else {
3605                    PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3606                    if (self.loginView !== undefined && self.loginView !== null)
3607                        self.loginView.load();
3608                    else mcWeb.login.load();
3609				}
3610			});//End Web Api: LoginSender
3611		};// END Link event
3612
3613    }; /*END viewModelavsenders*/ 
3614
3615	self.activateView = function (avsenders, binElementId) {
3616		ko.applyBindings(new ViewModelavsenders(avsenders), document.getElementById(binElementId));
3617		PubSub.publish(mcWeb.lightbox.events.onShowLightbox);		
3618    };
3619
3620    this.logout = function () {
3621        try {
3622            window.StorageService.localStorage.removeItem('id');
3623            window.StorageService.localStorage.removeItem('user');
3624            window.StorageService.localStorage.removeItem('remember');
3625            window.StorageService.localStorage.removeItem('authenticatedGuid');
3626            window.StorageService.localStorage.removeItem('remember');
3627        } catch (e) {
3628            console.error('LoginAvsAdresseView.logout - ex: ' + e);
3629        }
3630        mcWeb.login.logout();
3631    };
3632};;
3633mcWeb.loginContacts = new function () {
3634	var $ = jQuery;
3635	var self = this;
3636	self.service = new WebApiService("Login");
3637	self.isClosedShop = false;
3638
3639	self.load = function (contacts) {
3640
3641        if (contacts == null) {
3642			loadContacts();
3643			return;
3644		}
3645
3646		loadInit(contacts, "#lightbox-placeholder", "login-club");
3647	};
3648
3649	self.loadInfo = function (contacts) {
3650
3651        if (contacts != null) {
3652            loadInit(contacts, "#placeholder-club", "club-bindings");
3653        }
3654	}
3655
3656	var loadInit = function(contacts, placeholderId, binElementId) {
3657
3658		if (window.location.pathname.toLowerCase().indexOf("loginlukketshop") !== -1)
3659			self.isClosedShop = true;
3660
3661		PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3662		$(placeholderId).load("/Webpages/Kunde/LoginContactView.aspx", function () {
3663			if ($("#login-club").length < 1) {
3664				PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3665				return;
3666			}//Module not active
3667
3668			mcWeb.loginContacts.activateView(contacts, binElementId);
3669
3670			PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3671
3672			if (!!mcWeb.inlineEditor)
3673				mcWeb.inlineEditor.init(true);
3674		});
3675	};
3676    
3677	var loadContacts = function () {
3678		PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3679
3680		self.service.GetAction("LoadContacts").then(function(result) {
3681			PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3682
3683			if (result !== null) {
3684				mcWeb.loginContacts.load(result);
3685			} else {
3686				mcWeb.login.load();
3687			}			
3688		});
3689	};//End Load Contacts
3690
3691	self.activateView = function (contacts, binElementId) {
3692		var isLogin = (binElementId === "login-club") ? true : false;
3693		ko.applyBindings(new viewModelContacts(contacts, isLogin), document.getElementById(binElementId));
3694		if (isLogin) {
3695			PubSub.publish(mcWeb.lightbox.events.onShowLightbox);
3696		}
3697		
3698	};
3699
3700	var viewModelContacts = function (json, isLogin) { //Internal
3701		var view = this;        
3702        view.contactName = ko.observable(json.ContactName);
3703		view.Contacts = ko.observableArray(json.Contacts);
3704		
3705		//Link event
3706		view.loginContact = function (contact) {
3707
3708			if (isLogin === false)
3709				return false;
3710
3711            PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3712
3713			var obj = {
3714                loginAsMe: (contact.CustomerNo == null) ? true : false,
3715                customerNo: (contact.CustomerNo == null) ? null : contact.CustomerNo,
3716                loginType: 3
3717                //clubDealId: (contact.CustomerId == null) ? '-99' : contact.ClubDealId,
3718                //clubRemaining: (contact.CustomerId == null) ? '0' : contact.RemainingAmou
3718nt,
3719			};
3720			
3721			self.service.PostAction("LoginContact", obj).then(function (result) {
3722				
3723				if (result != null && result.Success == true) {
3724					if(self.isClosedShop)
3725						window.location.href = "/";
3726					else
3727						window.location.href = document.location.href.replace(location.hash, "");
3728				} else {
3729					PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3730					mcWeb.login.load();
3731				}
3732			});//End Web Api: LoginContact
3733		};// END Link event
3734
3735	}; /*END viewModelContacts*/ 
3736	
3737    this.logout = function () {
3738        try {
3739            window.StorageService.localStorage.removeItem('id');
3740            window.StorageService.localStorage.removeItem('user');
3741            window.StorageService.localStorage.removeItem('remember');
3742            window.StorageService.localStorage.removeItem('authenticatedGuid');
3743            window.StorageService.localStorage.removeItem('remember');
3744        } catch (e) {
3745            console.error('LoginContactsView.logout - ex: ' + e);
3746        }
3747        mcWeb.login.logout();
3748    };
3749};;
3750mcWeb.loginPassword = new function () {
3751    var $ = jQuery;
3752    var self = this;
3753    self.service = new WebApiService("Login");
3754
3755    self.closeOnCancel = false;    
3756
3757    self.load = function (closeOnCancel, lightboxOptions) {
3758
3759        self.closeOnCancel = closeOnCancel;
3760        
3761        var placeholder = $("#lightbox-placeholder");
3762        if (placeholder.length < 1)
3763            return;
3764
3765        placeholder.load("/Webpages/Kunde/LoginForgottenPasswordView.aspx", function () {
3766
3767            var forgottenPsw = $("#forgotten-password");
3768            if (forgottenPsw.length < 1)
3769                return;
3770
3771            forgottenPsw.on("keydown", function () {
3772                if (event.keyCode === 13) {
3773                    event.preventDefault();
3774                }
3775            });
3776
3777            forgottenPsw.on("keyup", function () {
3778                if (event.keyCode === 13) {
3779                    mcWeb.loginPassword.sendPasswordToken();                    
3780                }
3781            });
3782
3783            $("#forgottenPassordEmail").focus();
3784           
3785            $('#send-password').on("click", function () {
3786                mcWeb.loginPassword.sendPassword();
3787            });
3788
3789            $('#send-password-token').on("click", function () {
3790                mcWeb.loginPassword.sendPasswordToken();
3791            });
3792            
3793            if (!lightboxOptions)
3794                PubSub.publish(mcWeb.lightbox.events.onShowLightbox);
3795            else
3796                PubSub.publish(mcWeb.lightbox.events.onShowLightbox, lightboxOptions);
3797
3798            if (mcWeb.inlineEditor != null)
3799                mcWeb.inlineEditor.init(true);
3800
3801        }); //End Load view
3802    };//End Load
3803
3804    self.close = function() {
3805        if (self.closeOnCancel !== null && self.closeOnCancel === true) {
3806            PubSub.publish(mcWeb.lightbox.events.onHideLightbox);
3807            return false;
3808        }
3809
3810        mcWeb.login.load();
3811        return true;
3812    };
3813
3814    self.setTabIndex = function(useAvsender) {
3815        if (useAvsender) {
3816            $('#avs-select').attr('tabindex', 1);
3817            $('#password').attr('tabindex', 2);
3818            $('#password2').attr('tabindex', 3);
3819            $('#change-psw').attr('tabindex', 4);
3820        } else {
3821            $('#avs-select').removeAttr('tabindex');
3822            $('#password').attr('tabindex', 1);
3823            $('#password2').attr('tabindex', 2);
3824            $('#change-psw').attr('tabindex', 3);
3825        }
3826    };
3827
3828    self.clearAvsenders = function () {
3829        $("#avs-form option:not([value='-1'])").remove();
3830    }
3831   
3832    self.loadAvsenders = function(element) {
3833
3834        var avs = $("#avs-form");
3835        var username = element.value;
3836        if (username == null || username.trim().length < 3) {            
3837            if (!avs.hasClass("hidden")) {
3838                avs.AddClass("hidden");                
3839            }
3840            mcWeb.loginPassword.setTabIndex(false);
3841            return;
3842        }
3843
3844        var tok = self.getPasswordTokenFromURI("ptk");
3845        var data = {
3846            username: username,
3847            passwordToken: tok
3848        };
3849
3850        PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3851
3852        try {
3853            self.service.PostAction("PasswordTokenSenders", data).then(function (result) {
3854                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3855                if (result != null) {
3856                    var el = document.getElementById("avs-select");
3857                    if (el != null && result.length > 0) {
3858                        self.clearAvsenders();
3859                        for (var i = 0; i < result.length; i++) {
3860                            var option = document.createElement("option");
3861                            option.setAttribute('value', result[i].AvsAdresseId);
3862                            option.appendChild(document.createTextNode(result[i].DisplayName));
3863                            el.appendChild(option);
3864                        }
3865                        $('#avs-select').attr('tabindex', 1);                 
3866                        avs.removeClass("hidden");
3867                        mcWeb.loginPassword.setTabIndex(true);
3868                        return;
3869                    }
3870                }
3871                avs.addClass("hidden");
3872                mcWeb.loginPassword.setTabIndex(false);
3873            });
3874        } catch (e) {
3875            PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3876        } 
3877    };
3878
3879    self.sendPassword = function () {
3880        var data = {
3881            username: encodeURIComponent($("#forgottenPassordEmail").val()),
3882        };
3883
3884        $('#send-password').attr('disabled', 'disabled');
3885        PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3886
3887        try {
3888
3889            self.service.PostAction("SendPassword", data).then(function (result) {
3890                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3891                var msg = $("#error-msg-password");
3892
3893                if (result !== null && result !== undefined) {
3894
3895                    if (result.Success === true) {
3896                        var ok = $('#psw-sendt');
3897                        ok.html(result.Message);
3898                        $("#fp-primary").hide();
3899                        $("#fp-secondary").show();
3900                        return;
3901                    } else {
3902                        msg.html(result.Message);
3903                        $("#forgottenPassordEmail").focus();
3904                    }
3905                }
3906                msg.show();
3907
3908                $('#send-password').removeAttr('disabled');
3909            });
3910
3911        } catch (e) {
3912            PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3913        } 
3914
3915       
3916    };//End Login
3917
3918
3919    self.sendPasswordToken = function () {
3920        var data = {
3921            username: $("#forgottenPassordEmail").val()
3922        };
3923
3924        $('#send-password-token').attr('disabled', 'disabled');
3925        PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
3926
3927        try {
3928            self.service.PostAction("SendPasswordToken", data).then(function (result) {
3929                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3930
3931                var msg = $("#error-msg-password");
3932
3933                if (result !== null && result !== undefined) {
3934
3935                    if (result.Success === true) {
3936                        var ok = $('#psw-sendt');
3937                        ok.html(result.Message);
3938                        $("#fp-primary").hide();
3939                        $("#fp-secondary").show();
3940                        return;
3941                    } else {
3942                        msg.html(result.Message);
3943                        $("#forgottenPassordEmail").focus();
3944                    }
3945                }
3946                msg.show();
3947
3948                $('#send-password-token').removeAttr('disabled');
3949            });
3950        } catch (e) {
3951            PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
3952        } 
3953    };
3954    
3955    self.getPasswordTokenFromURI = function (name) {
3956        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
3957    };
3958
3959    self.validateResetPasswordInput = function () {
3960        $("#password2").on("keypress", function (e) {
3961            var keyCode = e.keyCode || e.which;
3962            if (keyCode === 13) {
3963                e.preventDefault();
3964                return false;
3965            }
3966        });
3967        var isvalid = $("#password").val() === $("#password2").val() && $("#password").val().length >= 6;
3968        return isvalid;
3969    };
3970
3971    self.setPasswordOnKeypress = function () {
3972        $("#password").on("keypress", function (event) {
3973            if (event.which === 13) { //key Code 13 is Enter
3974                event.preventDefault();
3975                self.setNewUserPassword();
3976            }
3977        });
3978    };
3979
3980    self.setNewUserPassword = function () {
3981        try {
3982            var psw = $("#password").val();
3983            var btn = $("#psw_save_btn");
3984
3985            if (btn.hasClass("disabled"))
3986                return false;
3987
3988            if (psw.trim().length < 1) {
3989                PubSub.publish(mcWeb.lightbox.events.onHideLightbox);
3990                return false;
3991            }
3992            psw = psw.trim();
3993            btn.addClass("disabled");
3994
3995            var data = {
3996                password: psw
3997            };
3998
3999            //$("#passWordSaveOk").hide();
4000            $("#passWordSaveError1").hide();
4001            $("#passWordSaveError2").hide();
4002
4003            var usePswVerification = $("#password2").length > 0;
4004
4005            var isValid = false;
4006            if (usePswVerification) {
4007                isValid = self.validateResetPasswordInput();
4008            } else {
4009                isValid = (psw.length >= 6);
4010            } 
4011
4012            if (isValid) {
4013                PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
4014
4015                try {
4016                    self.service.PostAction("ChangeCurrentUserPassword", data).then(function (result) {
4017                        PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
4018
4019                        if (result) {
4020                            var okTxt = $("#passWordSaveOk").text();
4021                            PubSub.publish(mcWeb.cartsmall.events.onShowNewItemInCartText, { status: true, msg: okTxt, css: 'popup-new-psw', popupTime: 3000 });
4022                            btn.text(okTxt);
4023                            setTimeout(function () {
4024                                PubSub.publish(mcWeb.lightbox.events.onHideLightbox, {});
4025                            }, 3500);
4026                        } else {
4027                            var err1 = $("#passWordSaveError1");
4028                            PubSub.publish(mcWeb.cartsmall.events.onShowNewItemInCartText, { status: false, msg: err1.text(), popupTime: 4000 });
4029                            err1.show();
4030                            btn.removeClass("disabled");
4031                        }
4032                    });
4033                } catch (e) {
4034                    PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
4035                } 
4036                
4037            } else {
4038                var errMsg = usePswVerification ? $("#passWordSaveError2") : $("#passWordSaveError3");
4039                PubSub.publish(mcWeb.cartsmall.events.onShowNewItemInCartText, { status: false, msg: errMsg.text(), popupTime: 4000 });
4040                errMsg.show();
4041                btn.removeClass("disabled");
4042            }
4043
4044        } catch (e) {
4045            console.log("LoginForgottenPasswordView - Error: " + e);
4046        }
4047        return false;
4048    };
4049
4050    self.sendPasswordResetRequest = function () {
4051        var tok = self.getPasswordTokenFromURI("ptk");
4052        $("#reset-result-success").hide();
4053        $("#reset-result-error").hide();
4054        $("#reset-result-validation-error").hide();
4055        $("#reset-result-avs-not-selected").hide();
4056        $("#avs-select").removeClass("reset-error");
4057
4058        if (tok == null)
4059            tok = '_missing_';//this should cause an error to become visible rather than the updateicon just showing constantly
4060
4061        var avsender = -1;
4062        var avsenderForm = $("#avs-form");
4063
4064        if (avsenderForm.length > 0 && !avsenderForm.hasClass('hidden')) {
4065            avsender =  parseFloat(jQuery('#avs-select').find(":selected").val());
4066            if (isNaN(avsender)) {
4067                avsender = -1;
4068            }
4069            
4070            if (avsender < 0) {
4071                $("#reset-result-avs-not-selected").show();
4072                $("#avs-select").addClass("reset-error");
4073                return;
4074            }
4075        }
4076
4077        var data = {
4078            username: $("#username").val(),
4079            passwordToken: tok,
4080            password: $("#password").val(),
4081            avsender: avsender
4082        };
4083
4084        if (self.validateResetPasswordInput()) {
4085            
4086            PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
4087            try {
4088                self.service.PostAction("SendPasswordResetRequest", data).then(function (result) {
4089                    PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
4090                    if (result && result.Success) {
4091                        //todo: set authguid i localstorage til AuthGuid fra result
4092                        $("#reset-result-success").show();
4093                        mcWeb.login.loginAfterPasswordReset();
4094                    } else {
4095                        $("#reset-result-error").show();
4096                    }
4097                });
4098            } catch (e) {
4099                PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
4100            } 
4101            
4102        } else {
4103            $("#reset-result-validation-error").show();
4104        };
4105    };
4106
4107
4108    $("#forgottenPassordEmail").keyup(function (event) {
4109        if (event.keyCode === 13) {
4110            mcWeb.login.sendPassword();
4111        }
4112    });
4113
4114};;
4115mcWeb.login = new function () {
4116    var $ = jQuery;
4117    var self = this;
4118
4119    self.events = {
4120        onSetLogin: "mcWeb.login.onSetLogin",
4121        onIsloggedIn: "mcWeb.login.onIsloggedIn"
4122    };
4123
4124    self.service = new WebApiService("Login");
4125    self.cartService = new WebApiService("Cart");
4126    self.isMobile = false;
4127    self.isLoggedIn = false;
4128    self.isClosedShop = false;
4129    self.lightboxOptions = null;
4130    self.isCheckout = ko.observable(false);
4131    self.loadClosedLogin = function () {
4132        self.lightboxOptions = { backdrop: 'static', keyboard: false, show: true, variantData: {}, deferred: false };
4133        self.load();
4134    };
4135
4136    self.conditionVM = new mcWeb.conditions.vm("login");
4137    self.conditionsStatus = {
4138        isFunctionalConditionAccepted: ko.observable(false),
4139        acceptDocuments: ko.observableArray([]),
4140        usageArea: 1
4141    };
4142
4143    self.acceptChangesubscriptionToken = null;
4144
4145    self.load = function () {
4146
4147        if (!self.isMobile) {
4148            $('#UpdateIcon').show();
4149        }
4150
4151        if (window.location.pathname.toLowerCase().indexOf("loginlukketshop") !== -1)
4152            self.isClosedShop = true;
4153
4154        $("#lightbox-placeholder").load("/Webpages/Kunde/LoginView.aspx", function () {
4155            if (!self.isMobile) {
4156                $('#UpdateIcon').hide();
4157            }
4158
4159            if ($("#login").length < 1) {
4160                return; //Module not active
4161            }
4162
4163            removeQtip();
4164            onClick();
4165            setLocalStorage();
4166
4167            if($("body.layoutver4").length > 0 && self.lightboxOptions === null){
4168                self.lightboxOptions =  { keyboard: true, show: true , variantData:{}, deferred: false};
4169            }
4170
4171            //publish event here!
4172            if (!self.isMobile) {
4173                if (self.lightboxOptions === null)
4174                    PubSub.publish(mcWeb.lightbox.events.onShowLightbox);
4175                else
4176                    PubSub.publish(mcWeb.lightbox.events.onShowLightbox, self.lightboxOptions);
4177            }
4178
4179            if (!!mcWeb.inlineEditor)
4180                mcWeb.inlineEditor.init(true);
4181
4182            setTimeout(function () { $("#username").focus(); }, 1000);
4183        }); //End Load view
4184    }; //End Load
4185
4186
4187    $(document).ready(function () {
4188        PubSub.subscribe(mcWeb.login.events.onSetLogin, function (message, isLoggedIn) {
4189            self.isLoggedIn = isLoggedIn;
4190            PubSub.publish(mcWeb.login.events.onIsloggedIn, self.isLoggedIn);            
4191        });
4192    });
4193
4194
4195    self.loadMobile = function () {
4196        self.isMobile = true;
4197        onClick();
4198        setLocalStorage();
4199    };
4200
4201    function removeQtip() {
4202        var qtip2 = $('.qtip');
4203        if (qtip2.length > 0)
4204            qtip2.remove();
4205    };
4206
4207
4208    function onClick() {
4209        $("#password").on("keypress", function (event) {
4210            if (event.keyCode == 13) {
4211                mcWeb.login.login();
4212                event.preventDefault();
4213            }
4214        });
4215
4216        $("#username").on("keypress", function (event) {
4217            if (event.keyCode == 13) {
4218                mcWeb.login.login();
4219                event.preventDefault();
4220            }
4221        });
4222        
4223        $("#username").on("blur", function (event) {
4224            diplayNormalMode();
4225        });
4226
4227        //OnClick checkbox
4228        $('#remember_me').on("click", function () {
4229
4230            var chk = $(this).is(':checked');
4231            if (chk) {
4232                window.StorageService.localStorage.setItem('remember', chk);
4233            }
4234        });        
4235    }
4236
4237    function diplayNormalMode() {
4238        var mode = $(".login-mode");
4239        if (mode != null && mode.length > 0) {
4240            var username = $("#username").val();
4241            if (username != null &&
4242                username.indexOf('@multicase.no') > 0) {
4243                mode.show();
4244            } else {
4245                mode.hide();
4246            }
4247        }        
4248    }
4249
4250
4251    var pswt = "********************";
4252    function setLocalStorage() {
4253
4254        //Load username and password
4255        var remember = window.StorageService.localStorage.getItem('remember');
4256        var user = mcWeb.currentUser.getUser();
4257        
4258        if (remember !== null && remember === "true" && user !== null && user.indexOf('@') > 0) {
4259            $('#remember_me').prop('checked', true);
4260            $('#username').val(user);
4261            $('#password').val(pswt);
4262            diplayNormalMode();
4263        } else {
4264            $('#remember_me').removeAttr('checked');
4265            $('#login_mode').removeAttr('checked');
4266            window.StorageService.localStorage.removeItem('user');
4267            window.StorageService.localStorage.removeItem('id');
4268            window.StorageService.localStorage.removeItem('remember');
4269        }
4270
4271    }
4272
4273    self.data = { username: '', password: '', localstorge: false, allowasynclogin: false, avsAdresseId: null, isNormalMode: true };
4274
4275    function validateInput(value, pswEl) {
4276        var pswParent = pswEl.parent();
4277
4278        if (pswParent.hasClass("has-error")) {
4279            pswParent.removeClass("has-error");
4280        }
4281
4282        if (value == null || value.trim().toLowerCase() === "null" || value.trim().length < 4) {
4283
4284            $('#remember_me').removeAttr('checked');
4285            clearStorage();
4286            pswParent.addClass("has-error");
4287            pswEl.val('');
4288            pswEl.focus();
4289
4290            return false;
4291        }
4292        return true;
4293    }
4294
4295    self.vippsLogin = function () {
4296        var data = { isCart: false };
4297        self.service.GetAction("VippsGetAuthorizationEndpoint", data).then(function (result) {
4298            if (result && result.length) {
4299                document.location.href = result
4300            } else {
4301                console.log("Vipps Login feilet");
4302            }
4303        });
4304    };
4305
4306    self.login = function () {
4307        try {
4308            PubSub.publish(mcWeb.hamburgerMenu.events.onMenuNeedsRefresh);
4309            PubSub.publish(mcWeb.MegaMenuResponsive.events.onMenuNeedsRefresh);
4310
4311            var pswEl = $("#password");
4312            var psw = pswEl.val();
4313            var localstorge = (psw === pswt);
4314            var id = window.StorageService.localStorage.getItem('id');
4315
4316            var pass = (id !== null && localstorge) ? id : psw;
4317            if (validateInput(pass, pswEl) === false) {
4318                return;
4319            }
4320
4321            if (self.isMobile == false) {
4322                PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
4323            }
4324
4325            self.data.username = $("#username").val();
4326            self.data.password = pass;
4327            self.data.localstorge = localstorge;
4328            self.data.allowasynclogin = true;
4329            self.data.avsAdresseId = null;
4330            self.data.isNormalMode = $('#login_mode').is(':checked');                
4331            
4332            self.service.PostAction("Login", self.data).then(function (result) {
4333
4334                if (self.isMobile == false) {
4335                    PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
4336                }
4337
4338                if (result.Success === true) {
4339                    clearStorage();
4340                    if (result.User !== mcWeb.currentUser.getUser())
4341                        mcWeb.currentUser.setUser(result.User);
4342
4343                    self.successLoginResult = result;
4344
4345                    if ((result.IsAgent === true) || (result.IsClub === true) || result.Token != null || result.TwoFactorStatus !== null) {
4346                        self.postViewingConditions();
4347                    } else {
4348                        var nextReminderDate = window.StorageService.localStorage.getItem('nextPostLoginConditionReminder');
4349                        if (nextReminderDate !== null) {
4350                            var reminderDateMS = Date.parse(nextReminderDate);
4351                            if (!isNaN(reminderDateMS)) {
4352                                if (Date.now() <= reminderDateMS) {
4353                                    self.postViewingConditions();
4354                                    return;
4355                                }                            }
4356                        }
4357
4358                        self.conditionVM.load(null, { usageArea: self.conditionsStatus.usageArea, forUnknownUser: false, isInLightbox: true, status: self.conditionsStatus });
4359
4360                        self.acceptChangesubscriptionToken = PubSub.subscribe(mcWeb.conditions.events.onAcceptChange, function (evt, conditionStatus) {
4361                            if (self.conditionsStatus.usageArea == conditionStatus.usageArea) {
4362                                if (conditionStatus.acceptDocuments.length > 0)
4363                                    self.postLoginShowConditions(conditionStatus.acceptDocuments);
4364                                else
4365                                    self.postViewingConditions();
4366                            }
4367                        });
4368                    }
4369
4370                } else {
4371                    clearStorage();
4372                    if (pass === pswt) {
4373                        $('#remember_me').removeAttr('checked');
4374                        pswEl.parent().addClass("has-error");
4375                        pswEl.val('');
4376                        pswEl.focus();
4377                        return false;
4378                    }
4379                    if (result.Blocked) {
4380                        $("#blocked-msg-login").show();
4381                        $("#error-msg-login").hide();
4382                        $("#error-preorder-login").hide();
4383                        return false;
4384                    }
4385
4386                    $("blocked-msg-login").hide();
4387                    
4388                    if (result.PreOrderClosed) {
4389                        $("#error-msg-login").hide();
4390                        $("#error-preorder-login").show();
4391                    } else {
4392                        $("#error-msg-login").show();
4393                        $("#error-preorder-login").hide();
4394                    }
4395                }
4396
4397                return false;
4398            });
4399        } catch (e) {
4400            if (self.isMobile == true) {
4401                $.mobile.loading("hide");
4402            }
4403        }
4404    }; //End Login
4405
4406    self.successLoginResult = null;
4407
4408    self.postLoginShowConditions = function(acceptDocuments) {
4409        PubSub.unsubscribe(self.acceptChangesubscriptionToken);
4410        PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
4411        var settings = { successLoginResult: self.successLoginResult };
4412        $("#lightbox-placeholder").load("/Webpages/ViewProvider.aspx?view=postlogin",
4413            function () {
4414                getLibrary("mcWeb.customerRegistration").then(() => {
4415                    getLibrary("mcWeb.postlogin").then(() => { 
4416                        loadModule(mcWeb.postlogin,
4417                            'PostloginCondtions',
4418                            'postloginConditions',
4419                            self.conditionsStatus.acceptDocuments(),
4420                            settings);
4421                    });
4422                });
4423            }); //End Load view
4424    };
4425
4426    self.postViewingConditions = function(successResult) {
4427        var result = (successResult) ? successResult : self.successLoginResult;
4428        if (!result) {
4429            console.log("No successfull login. Starting over.");
4430            self.load();
4431        }
4432
4433        self.loginResult(result);
4434    };
4435
4436    self.loginResult = function (result) {
4437
4438        if (result.Token != null) {
4439            getLibrary("mcWeb.customerRegistration").then(() => {
4440                mcWeb.customerRegistration.LoadView(result.Token);
4441            });
4442        } else if (result.TwoFactorStatus !== null && result.TwoFactorStatus.Show2FARegistration) {
4443            mcWeb.login2FAReg.load(result.TwoFactorStatus, self);
4444        }
4445        else if (result.TwoFactorStatus !== null && result.TwoFactorStatus.Show2FACodeInput) {
4446            mcWeb.login2FAReg.load(result.TwoFactorStatus, self);
4447        }
4448        else if (result.Avsenders != null) {
4449            mcWeb.loginAvsAdresse.load(self, self.data, result.Avsenders);
4450        } else if (result.IsAgent == true) {
4451            mcWeb.loginAgent.load(self,result);
4452        } else if (result.Club != null) { //&& self.isMobile == false) {
4453            mcWeb.loginContacts.load(result.Club);
4454        } else {
4455
4456            var nextUrl;
4457            var doReload;
4458
4459            nextUrl = window.location.href;
4460
4461            if (self.isMobile) {
4462                nextUrl = $('#url-ref').text();
4463            } else if (self.isClosedShop) {
4464                if (result.RefUrlLukketShop && result.RefUrlLukketShop.length > 0)
4465                    nextUrl = result.RefUrlLukketShop;
4466                else
4467                    nextUrl = "/";
4468            } else {
4469                if (location.hash == null || location.hash.length < 1) {
4470                    doReload = true;
4471
4472                } 
4473                else if (result.HrefLangLookupKey) {
4474                    let targetUrls = $("head link[rel='alternate'][hreflang='" + result.HrefLangLookupKey + "']");
4475                    if (targetUrls !== undefined && targetUrls.length > 0) {
4476                        nextUrl = targetUrls[0].href;
4477                    }
4478                    else nextUrl = document.location.href.replace(location.hash, "");
4479                    
4480                }
4481            }
4482
4483            window.StorageService.localStorage.setItem('ReadyForPostLoginPopup', 'true');
4484
4485            if (!result.RedirectDomain) {
4486                if (doReload) {
4487                    location.reload(true);
4488                } else {
4489                    window.location.href = nextUrl;
4490                }
4491            } else {
4492                var arr = nextUrl.split("/");
4493                var newUrl = arr[0] + "//" + result.RedirectDomain;
4494                window.location.href = newUrl;
4495                return true;
4496            }
4497        }
4498        return false;
4499    };
4500
4501    self.loginAfterPasswordReset = function () {
4502        try {
4503            var psw = $("#password").val();
4504            var localstorge = psw === pswt;
4505            var id = window.StorageService.localStorage.getItem('id');
4506            var pass = (id !== null && localstorge) ? id : psw;
4507
4508            var data = {
4509                username: $("#username").val(),
4510                password: pass,
4511                localstorge: localstorge,
4512                allowasynclogin: true
4513            };
4514
4515            self.service.PostAction("Login", data).then(function (result) {
4516                if (result.Success === true) {
4517                    if(location.protocol === "https:")
4518                        window.location.href = "https://" + location.hostname;
4519                    else
4520                        window.location.href = "http://" + location.hostname;
4521                }
4522
4523                return false;
4524            });
4525        } catch (e) {
4526            if (self.isMobile == true) {
4527                $.mobile.loading("hide");
4528            }
4529        }
4530    };
4531
4532    //Removes remember me
4533    function clearStorage() {
4534        window.StorageService.localStorage.removeItem('user');
4535        window.StorageService.localStorage.removeItem('id');
4536        window.StorageService.localStorage.removeItem('remember');
4537        window.StorageService.localStorage.removeItem('authenticatedGuid');
4538    }
4539
4540    this.logout = function (forceReload) {
4541        PubSub.publish(mcWeb.hamburgerMenu.events.onMenuNeedsRefresh);
4542        PubSub.publish(mcWeb.MegaMenuResponsive.events.onMenuNeedsRefresh);
4543
4544        var forceReloadPage = "";
4545        if (forceReload != undefined) {
4546            forceReloadPage = forceReload;
4547        }
4548
4549        self.service.GetAction("Logout", forceReloadPage).then(function (result) {
4550            //window.StorageService.localStorage.removeItem('authenticatedGuid');
4551            var rember = window.StorageService.localStorage.getItem('remember');
4552            if (rember == null || rember !== "true") {
4553                window.StorageService.localStorage.removeItem('user');
4554                window.StorageService.localStorage.removeItem('id');
4555                window.StorageService.localStorage.removeItem('remember');
4556                window.StorageService.localStorage.removeItem('authenticatedGuid');
4557            }
4558
4559            if (result !== null) {
4560                if (result.Success === null
4561                    && result.AgentloginURL !== null
4562                    && result.AgentloginURL.length > 0) {
4563                        window.location.href = result.AgentloginURL;
4564                } else {
4565                    var mcCookiename = result.Cookiename;
4566                    var cookieContent = self.getCookieContent(mcCookiename);
4567                    var deviceSize = self.getDeviceSizeInfo(cookieContent);
4568                    self.resetCookie(mcCookiename, result.Domain, deviceSize);
4569
4570                    if (!result.Success)
4571                        console.log('Error logg ut');
4572
4573                    if (location.protocol === "https:")
4574                        window.location.href = "https://" + location.hostname;
4575                    else
4576                        window.location.href = "http://" + location.hostname;
4577                }
4578            }
4579        });
4580    };
4581    this.getCookieContent = function (cookieName) {
4582        var nameEqual = cookieName + "=";
4583        var cookieArray = document.cookie.split(';');
4584        for (var i = 0; i < cookieArray.length; i++) {
4585            var cookie = cookieArray[i];
4586            while (cookie.charAt(0) === ' ')
4587                cookie = cookie.substring(1, cookie.length);
4588            if (cookie.indexOf(nameEqual) === 0)
4589                return cookie.substring(nameEqual.length, cookie.length);
4590        }
4591        return null;
4592    };
4593
4594    this.getDeviceSizeInfo = function (cookieContent) {
4595        if (!cookieContent) return null;
4596        var keyValueArray = cookieContent.split("&");
4597        for (var i = 0; i < keyValueArray.length; i++) {
4598            var keyValue = keyValueArray[i];
4599            while (keyValue.charAt(0) === ' ') keyValue = keyValue.substring(1, keyValue.length);
4600            if (keyValue.indexOf("DeviceSize=") === 0)
4601                return keyValue;
4602        }
4603        return null;
4604    };
4605
4606    this.resetCookie = function (cookieName, cookieDomain, deviceSizeInfo) {
4607        var cookieString = cookieName + '=';
4608        var expireDate = new Date();
4609        expireDate.setMonth(expireDate.getMonth() + 12);
4610        if (deviceSizeInfo)
4611            cookieString += deviceSizeInfo;
4612        if (cookieDomain)
4613            cookieString += ";domain=" + cookieDomain;
4614        document.cookie = cookieString + ';path=/;expires=' + expireDate;
4615    };
4616    //Log in out btn
4617    this.getLoginStatus = function () {
4618
4619        self.service.GetAction("GetLoginStatus", "").then(function (result) {
4620            if (result == null)
4621                return;
4622
4623            var lg = $("#loginout");
4624            lg.text(result.LoginText);
4625            var ct = $("#loginout-content");
4626
4627            if (result.IsLogedin === true) {
4628                lg.attr('href', (result.ShowClubLogin ? '#logincontact' : '#logout'));
4629                ct.removeClass("LogInButtonContainer");
4630                ct.addClass("LogUtButtonContainer");
4631            } else {
4632                lg.attr('href', (result.ShowClubLogin ? '#logincontact' : '#login'));
4633                ct.removeClass("LogUtButtonContainer");
4634                ct.addClass("LogInButtonContainer");
4635            }
4636
4637            $("#loginuser").text(result.LoginUser);
4638        });
4639    };
4640
4641    this.showForgottenPassword = function () {
4642        if (self.lightboxOptions === null)
4643            mcWeb.loginPassword.load();
4644        else
4645            mcWeb.loginPassword.load(false, self.lightboxOptions);
4646    };
4647
4648    this.onClickGoToCart = function () {
4649        try {
4650            $('#UpdateIcon').show();
4651
4652            self.cartService.GetAction("GoToCart", "").then(function (result) {
4653                $('#UpdateIcon').hide();
4654                if (result === null)
4655                    return;
4656                window.location.href = result;
4657            });
4658        } catch (e) {
4659            $('#UpdateIcon').hide();
4660        }
4661    };
4662    
4663
4664    this.LoadRegistrationLightbox = function (doLogout, settings) {
4665        if (doLogout) {
4666
4667            try {
4668                self.service.GetAction("Logout", { forceReloadPage: false }).then(function (result) {
4669                    window.StorageService.localStorage.removeItem('authenticatedGuid');
4670                    window.StorageService.localStorage.removeItem('user');
4671                    window.StorageService.localStorage.removeItem('id');
4672                    window.StorageService.localStorage.removeItem('remember');
4673
4674                    if (result === "false") {
4675                        alert('Error logg ut');
4676                    } else {
4677                        settings.ReadOnly = false;//we just logged out, need to reset this param
4678                        getLibrary("mcWeb.customerRegistration").then(() => {
4679                            mcWeb.customerRegistration.lightbox.load(settings);
4680                        });
4681                    }
4682                });
4683            } catch (e) {
4684                // IOS/etc. Private Mode
4685                console.log('LoginView.LoadRegistrationLightbox - ex: ' + e);
4686            }
4687        } else {
4688            getLibrary("mcWeb.customerRegistration").then(() => {
4689                mcWeb.customerRegistration.lightbox.load(settings);
4690            });
4691        }
4692    };
4693
4694    this.ThatsNotMe = function () {
4695        window.StorageService.localStorage.removeItem('user');
4696        window.StorageService.localStorage.removeItem('id');
4697        window.StorageService.localStorage.removeItem('remember');
4698        window.StorageService.localStorage.removeItem('authenticatedGuid');
4699        this.logout(false);
4700    };
4701
4702};;
4703mcWeb.customerReview = (new function ($) {
4704    'use strict';
4705
4706    var obj = this;
4707    //obj.productinfo; 
4708
4709    this.vm = function (product) {
4710        var self = this;
4711        obj.productinfo = product;
4712        //self.id = "#" + id;
4713        self.service = obj.productinfo.service;
4714        self.imageService = new WebApiService("ImageRenderer");
4715        self.customerName = ko.observable();
4716
4717        self.rating = ko.observable(0);
4718        self.setRating = function (rate) { self.rating(rate); }
4719        self.star = ko.pureComputed(function () { return self.rating(); }, self);
4720
4721        self.review = ko.observable();
4722        self.kundeId = ko.observable();
4723        self.kndKontaktId = ko.observable();
4724        self.plid = ko.observable();
4725        self.loggedIn = ko.observable();       
4726        self.reviewReply = ko.observable();
4727        self.desc1 = ko.observable();
4728        self.desc2 = ko.observable();
4729        self.webPubElementId = 0;
4730        self.replyMode = ko.observable(false);
4731        self.reloadUponClose = true;
4732        this.login = function () {
4733            mcWeb.login.load();
4734        }
4735
4736        this.openReviewWindow = function () {
4737
4738            $("#customerReviewModal").modal("show");
4739        }
4740
4741        this.closeReviewWindow = function () {
4742            $("#customerReviewModal").modal("hide");
4743            if(self.reloadUponClose)
4744                window.location = window.location.pathname + window.location.hash;
4745            else self.reloadUponClose = false;
4746
4747            var element = $("div.WebPubElement[data-elementid=" + self.webPubElementId + "]");
4748            var targetWebPubFieldId = $(element).data("fieldid");
4749            mcWeb.ajaxRenderEngine.updateFields(
4750                "div .ajax-field[data-field-id='" + targetWebPubFieldId + "']",
4751                "#AttributeListBox",
4752                false,
4753                false,
4754                false, 0);
4755        };
4756
4757        this.openReviewReplyWindow = function(webPubElementId) {
4758            self.webPubElementId = webPubElementId;
4759            self.replyMode(true);
4760            self.loadReply(webPubElementId);
4761            $("#customerReviewModal").modal("show");
4762        };
4763
4764        this.openReviewReplyWindow2 = function(me) {
4765            var webPubElementId = $(me).data('elementid');
4766            self.webPubElementId = webPubElementId;
4767            self.replyMode(true);
4768            self.loadReply(webPubElementId);            
4769            self.reloadUponClose = false;
4770            var zindex = self.findHighestZIndex("div");
4771
4772            $("#customerReviewModal").css("z-index", zindex + 1);
4773            $("#customerReviewModal").modal("show");
4774        };
4775
4776        this.openReviewReplyWindowFromReviewsList = function(me) {
4777            var webPubElementId = $(me).data('elementid');
4778            self.webPubElementId = webPubElementId;
4779            self.replyMode(true);
4780            self.loadReply(webPubElementId);            
4781            self.reloadUponClose = false;
4782            var zindex = self.findHighestZIndex("div");
4783            
4784            $("#customerReviewModal").css("z-index", zindex+1);
4785            $("#customerReviewModal").modal("show");
4786            
4787        };
4788
4789        this.findHighestZIndex = function (elem)
4790        {
4791          var elems = document.getElementsByTagName(elem);
4792          var highest = Number.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);
4793          for (var i = 0; i < elems.length; i++)
4794          {
4795            var zindex = Number.parseInt(
4796              document.defaultView.getComputedStyle(elems[i], null).getPropertyValue("z-index"),
4797              10
4798            );
4799            if (zindex > highest)
4800            {
4801              highest = zindex;
4802            }
4803          }
4804          return highest;
4805        };
4806
4807        this.closeReviewReplyRemoveWindow = function () {
4808            $("#customerReviewReplyRemove").modal("hide");
4809            window.location = window.location.pathname + window.location.hash;
4810        };
4811
4812        self.submitReview = function () {
4813            var nickname = $("#nickname");
4814            if (nickname.val() !== "" && self.rating() > 0) {
4815                var data = { CustomerName: (self.customerName()), Rating: self.rating(), Review: self.review(), KndKontaktId: self.kndKontaktId(), KundeId: self.kundeId(), plid: self.plid() };
4816                self.service.PostAction("PostReview", data).then(function (result) {
4817                    self.closeReviewWindow();
4818                    if(result > 0){
4819                        if(jQuery("body.layoutver4").length > 0){
4820                            window.mcWeb.ajaxRenderEngineMenus.refreshField(result);
4821                        }
4822                    }
4823                });
4824            } else {
4825                if (nickname.val() === "") {
4826                    nickname.addClass("rev-error");
4827                }
4828                if (self.rating() === 0) {
4829                    $("#scoreFieldset").addClass("rev-error");
4830                }
4831            }
4832        };
4833
4834        self.submitReviewReply = function () {
4835            if (self.reviewReply() !== "") {
4836                var data = { ReviewReply: self.reviewReply(), plid: self.plid(), WebPubElementId: self.webPubElementId };
4837                self.service.PostAction("PostReviewReply", data).then(function () {
4838                    self.closeReviewWindow();
4839                });
4840            } else {
4841                $('.review-reply').addClass("rev-error");
4842            }
4843        };
4844
4845        var custJson = $("div[id*='revqsdiv']").html();
4846        var pld = $("div[id*='revpliddiv']").html();
4847        var logged = $("div[id*='revpliddiv']").data("loggedin");
4848        self.loggedIn(logged === "True");
4849        self.plid(pld);
4850
4851        if (custJson) {
4852            custJson = JSON.parse(custJson);
4853            self.desc1(custJson.Desc1);
4854            self.desc2(custJson.Desc2);
4855            self.kundeId(custJson.KundeId);
4856            self.kndKontaktId(custJson.KndKontaktId);
4857            self.rating(parseInt(custJson.Score));
4858            self.customerName(custJson.Kundenavn);
4859            if (self.rating() !== 0)
4860                self.openReviewWindow();
4861        }
4862
4863        $("#nickname").on("keypress", function (e) {
4864            var keyCode = e.keyCode || e.which;
4865            if (keyCode === 13) {
4866                e.preventDefault();
4867                return false;
4868            }
4869          return true;
4870        });
4871
4872        //this.load = function (data, settings) { };
4873
4874        self.loadReply = function (webPubElementId) {
4875            self.service.GetAction("GetReviewReply", { webPubElementId: webPubElementId }).then(function (result) {
4876                if (result != null) {
4877                    self.reviewReply(result.ReviewReply);
4878                    self.plid(result.plid);
4879                    self.rating(parseInt(result.Score.toString()));
4880                    self.review(result.Review);
4881                    self.customerName(result.CustomerName);
4882                    self.desc1(result.ProductDesc1);
4883                    self.desc2(result.ProductDesc2);
4884                    self.refreshImage(result.plid);   
4885                }
4886            });
4887
4888        };
4889        self.refreshImage = function (plid) {
4890            var images = jQuery("#customerReviewModal img.ReviewAddImg");
4891            if (images.length <= 0)
4892                return;
4893
4894            var items = self.getImageParam(images[0],plid);
4895            if (items == null)
4896                return;
4897
4898            self.imageService.PostAction("ListImageTagsAsync", { Items: items }).then(function (result) {
4899                if (result && result.items && result.items.length > 0) {
4900                    var items = result.items;
4901                    for (var i = 0; i < items.length; i++) {
4902                        var item = items[i];
4903                        if (item.success) {                            
4904                            jQuery('#' + item.targetId).replaceWith(item.tag);
4905                        }
4906                    }
4907                }
4908            });
4909        };
4910
4911        self.editReviewReply = function (webPubElementId) {
4912            self.webPubElementId = webPubElementId;
4913            self.loadReply(webPubElementId);
4914
4915            $("#customerReviewReplyModal").modal("show");
4916        };
4917
4918        self.openReviewReplyRemove = function (webPubElementId) {
4919            self.webPubElementId = webPubElementId;
4920            $("#customerReviewReplyRemove").modal("show");
4921        };
4922
4923        self.openReviewReplyRemove2 = function (me) {
4924            var webPubElementId = $(me).data('elementid');
4925
4926            self.webPubElementId = webPubElementId;
4927            $("#customerReviewReplyRemove").modal("show");
4928        };
4929
4930        self.submitRemoveReviewReply = function () {
4931            var data = { ReviewReply: "", plid: self.plid(), WebPubElementId: self.webPubElementId };
4932            self.service.PostAction("PostReviewReply", data).then(function () {
4933                self.closeReviewWindow();
4934                $("#customerReviewReplyRemove").modal("hide");
4935            });
4936        };
4937
4938        self.getImageParam = function(image, plid){
4939            var img = jQuery(image);
4940            var parent = img.parent();
4941            if (parent === null || parent === undefined || parent.length <= 0)
4942                return null;
4943
4944            var containerTagType = parent[0].tagName.toLowerCase();
4945            var includeLink = containerTagType === "a";
4946            var parentWidth = parent.width();
4947            var parentHeight = parent.height();
4948            var myWidth = img.data("width");
4949            var myHeight = img.data("height");
4950            var elementId = img.data("elementid");
4951            var css = img.attr('class');            
4952            
4953            if (parentWidth <= 0)
4954                parentWidth = myWidth;
4955            if (parentHeight <= 0)
4956                parentHeight = myHeight;
4957                
4958            var aspect = parentWidth / parentHeight;
4959            if (aspect < 0.1 || aspect > 2) {
4960                //lazy loading in use, must use different aspect calculation
4961                aspect = myWidth / myHeight;
4962            }
4963            var myId = img[0].id;
4964            if (myId === "")
4965                myId = parent[0].id;
4966
4967            var item = {
4968                TargetId: myId,
4969                Plid: plid,
4970                Index: img.data("imageIndex"),
4971                Width: parentWidth,
4972                Aspect: aspect,
4973                IncludeLink: includeLink,
4974                UseSecondaryImage: img.data("hassecondaryimg") === 1,
4975                IncludeNotFound: true,
4976                ElementId: 0,
4977                Css: css,
4978                AutoScale: false
4979            };
4980            if (elementId !== undefined && elementId !== null)
4981                item.ElementId = elementId;
4982            if (css !== undefined && css !== null)
4983                item.Css = css;
4984
4985            var list = [];
4986            list.push(item);
4987            return list;
4988        };
4989
4990    }; //End vm
4991
4992}(jQuery));;
4993mcWeb.productlistquantity = new (function ($) {
4994    'use strict';
4995
4996    var obj = this;
4997    obj.productlist;
4998
4999    this.vm = function (product) {
5000        obj.productlist = product;
5001
5002        var self = this;
5003        self.service = obj.productlist.service;
5004        self.updatePrice = true;
5005
5006        self.change = function (sender, plid, minQuan, incQuan, maxQuan, desimals) {
5007
5008            var el = $(sender);
5009            var value = mc.format.asNumber(sender.value, desimals);
5010            var minValue = mc.format.asNumber(minQuan, desimals);
5011            var incQuan = mc.format.asNumber(incQuan, desimals)
5012            var maxValue = mc.format.asNumber(maxQuan, desimals);
5013
5014            if (value > maxValue) {
5015                changeQuantityPopup(sender, maxValue, value);
5016                value = maxValue;
5017            }
5018
5019            if (minValue < -0.0001) {
5020                minValue = Number(0);
5021            }
5022
5023            if (incQuan < 0.0001) {
5024                incQuan = Number(1);
5025            }
5026
5027            var quan = value;
5028            var round = mc.format.roundToNearest(value, incQuan, desimals);
5029
5030            if (round < minValue) {
5031                sender.value = mc.format.asCulture(minValue, desimals);
5032                return;
5033            }
5034
5035            if (round != quan) {
5036                changeQuantityPopup(sender, round, quan, desimals);
5037            }
5038            sender.value = mc.format.asCulture(round, desimals);
5039
5040            //Check for new price
5041            if (obj.productlist.price != null && el.data("updateprice") == true) {
5042                var useVat = $("#price-inc-ex-vat").is(':checked') ? 1 : 0;
5043                obj.productlist.price.updatePrice(plid, round, useVat);
5044            }
5045        }
5046
5047        var changeQuantityPopup = function (sender, newQuantity, oldQuantity, desimals) {
5048            var value = mc.format.asNumber((newQuantity - oldQuantity), desimals);
5049            var changeQua = mc.format.asCulture(value, desimals);
5050            var text = ' ' + ((changeQua > 0) ? '+' : '') + changeQua;
5051            self.quantityQtip($(sender), '', text);
5052        }
5053        this.quantityQtip = function (sender, text, quantity) {
5054            var textQua = (quantity) ? ('<span class="bold">' + quantity + '</span>') : '';
5055            sender.qtip({
5056                content: { text: text + textQua },
5057                hide: {
5058                    inactive: 5000,
5059                    event: 'click mouseleave mouseover',
5060                    effect: function () { $(this).slideUp(); }
5061                },
5062                position: { my: 'bottom center', at: 'top center' },
5063                style: { classes: 'qtip-bootstrap qtip-cart' },
5064                show: { ready: true },
5065            });
5066        };
5067
5068
5069        self.keyPressed = function (sender, keyCode) {
5070
5071            if (keyCode === 38 || keyCode === 107 || keyCode === 40 || keyCode === 109) {
5072
5073                var increase = (keyCode === 38 || keyCode === 107) ? true : false;
5074
5075                var el = $(sender);
5076                var des = el.data("des");
5077                var min = mc.format.asNumber(el.data("min"), des);
5078                var inc = mc.format.asNumber(el.data("inc"), des);
5079                var max = mc.format.asNumber(el.data("max"), des);
5080                var value = mc.format.asNumber(sender.value, des);
5081
5082                if (isNaN(value)) {
5083                    sender.value = mc.format.asCulture(min, des);
5084                    return true;
5085                }
5086
5087                if (increase == true) {
5088                    if ((value + inc) > max) {
5089                        sender.value = mc.format.asCulture(max, des);
5090                        return false;
5091                    }
5092                    sender.value = mc.format.asCulture(mc.format.asNumber((value + inc), des), des);
5093                } else {
5094                    if ((value - inc) < min) {
5095                        sender.value = mc.format.asCulture(min, des);
5096                        return false;
5097                    }
5098                    sender.value = mc.format.asCulture(mc.format.asNumber((value - inc), des), des);
5099                }
5100
5101                mcWeb.productlist.qt.change(sender, el.data("plid"), min, inc, max, des);
5102                return false;
5103            } else if (keyCode === 13) {
5104                document.activeElement.blur();
5105                return true;
5106            }
5107        };
5108    }
5109
5110})(jQuery);;
5111mcWeb.productlist = new (function ($) {
5112    'use strict';
5113
5114    this.vm = function (id) {
5115        var self = this;
5116        self.id = "#" + id;
5117        self.service = new WebApiService("ProductInfo");
5118
5119        //vm for product quantity
5120        self.qt = new mcWeb.productlistquantity.vm(self);
5121
5122        //vm for product buy
5123        getLibrary("mcWeb.productlistbuy").then(() => {
5124            self.buy = new mcWeb.productlistbuy.vm(self);
5125        });
5126
5127        //vm for product price
5128        getLibrary("mcWeb.productlistprice").then(() => {
5129            self.price = new mcWeb.productlistprice.vm(self);
5130        });
5131        //vm for product favorites
5132        getLibrary("mcWeb.productlistfavorites").then(() => {
5133            self.fav = new mcWeb.productlistfavorites.vm(self);
5134        });
5135
5136        //vm for product filter
5137        getLibrary("mcWeb.productlistfilter").then(() => {
5138            self.filter = new mcWeb.productlistfilter.vm(self);
5139        });
5140    };//End vm
5141
5142})(jQuery);
5143
5144mcWeb.productlist.vm();;
5145mcWeb.productVariant = new function () {
5146	var self = this;
5147	self.showQtipWarning = function (target) {
5148		var textContainerId = 'variant-visual-warning';
5149		var titleId = 'variant-visual-warning-title';
5150		var text = jQuery('#' + textContainerId).html();
5151		var title = jQuery('#' + titleId).html();
5152		jQuery('#' + target).qtip({
5153			content: { text: text, title: title},
5154			position: { my: 'right center', at: 'center left' },
5155			style: { classes: 'qtip-dark' },
5156			show: { ready: true, event: 'contextmenu' },
5157			hide: {event: false, inactive: 4000, fixed:true}
5158		});
5159	};
5160};;
5161mcWeb.elementGrouping = new (function () {
5162
5163    'use strict';
5164    var self = this;
5165    var defaultToggleSpeed = 400;
5166    const variantLevel = 100;
5167    const maxLevels = 4;
5168
5169    self.toggle = function (clickedElm, speed, accordion) {
5170        
5171        if (clickedElm.getAttribute("aria-expanded") == "true")
5172            self.collapseFromThis(clickedElm, speed);
5173        else {
5174            self.expandFromThis(clickedElm, speed, accordion);
5175        }
5176    };
5177
5178    self.getParentSeparator = function (domElement) {
5179        var parentCollection = jQuery(domElement).parents(".separator-element");
5180        return parentCollection;
5181    };
5182
5183    self.collapseFromThis = function (clickedElement, speed) {
5184        
5185        var collapseSpeed = speed ? speed : defaultToggleSpeed;
5186        var separatorElement = self.getParentSeparator(clickedElement);
5187        if (separatorElement == null) {
5188            console.log("Could not find separator");
5189            return;
5190        }
5191
5192        clickedElement.setAttribute("aria-expanded", "false");
5193        self.doCollapse(separatorElement, collapseSpeed);
5194    };
5195
5196    self.expandFromThis = function (clickedElement, speed, accordion) {
5197        var expandSpeed = speed ? speed : defaultToggleSpeed;
5198        var doAccordion = accordion ? true : false;
5199        
5200        var separatorElement = self.getParentSeparator(clickedElement);
5201        if (separatorElement == null) {
5202            console.log("Could not find separator");
5203            return;
5204        }
5205        clickedElement.setAttribute("aria-expanded", "true");
5206        
5207        if (doAccordion) {
5208            var sameLevel = parseInt(separatorElement.data("separator-level"), 10);
5209            var thisLevel;
5210            separatorElement.prevAll(".separator-element").each(function (prevIndex) {
5211                thisLevel = parseInt(jQuery(this).data("separator-level"), 10);
5212                if (thisLevel == sameLevel) {
5213                    self.collapseFromThis(jQuery(this).find(".exp-toggler")[0]);
5214                }
5215                else
5216                    if (thisLevel < sameLevel)
5217                        return false;
5218            });
5219
5220            separatorElement.nextAll(".separator-element").each(function (nextIndex) {
5221                thisLevel = parseInt(jQuery(this).data("separator-level"), 10);
5222
5223                if (thisLevel == sameLevel)
5224                    self.collapseFromThis(jQuery(this).find(".exp-toggler")[0]);
5225                else
5226                    if (thisLevel < sameLevel)
5227                        return false;
5228            });
5229        }
5230        self.doExpand(separatorElement, expandSpeed);
5231        
5232    };
5233
5234    self.accordionPrevSiblings = function (elm) {
5235
5236    };
5237
5238    self.doExpand = function (separatorElement, speed) {
5239        separatorElement.removeClass("isColl");
5240
5241        var expandLevel = parseInt(separatorElement.attr("data-separator-level"));
5242        var collapsedState = this.newCollapseState(expandLevel);
5243        var siblingsFromParent = jQuery(".separator-element[data-elementid='" + separatorElement.attr("data-elementid") + "'][data-separator-level='" + expandLevel + "'] ~ *");
5244        
5245        siblingsFromParent.each(function () {
5246            if (jQuery(this).hasClass("separator-element")) {
5247                //Separator-element
5248                collapsedState.setCurrentSeparatorCollapseStatus(
5249                    parseInt(jQuery(this).attr("data-separator-level"))
5250                    , jQuery(this).hasClass("isColl"));                
5251
5252                if (collapsedState.isSameOrHigherThanStartLevel())
5253                    return false; //Exit, dont' expand any more.
5254                else if (collapsedState.separatorVisibility())
5255                    jQuery(this).show(speed);
5256                
5257            } else {
5258                //PublisedElement
5259                if (collapsedState.elementVisibility())
5260                    jQuery(this).show(speed);
5261            }
5262        });
5263    };
5264
5265    self.doCollapse = function (separatorElement, speed) {
5266        separatorElement.addClass("isColl");
5267
5268        var currentLevel = parseInt(separatorElement.attr("data-separator-level"));
5269        var siblingsFromParent = jQuery(".separator-element[data-elementid='" + separatorElement.attr("data-elementid") + "'][data-separator-level='" + currentLevel + "'] ~ *");
5270        siblingsFromParent.each(function () {
5271            if (jQuery(this).hasClass("separator-element")) {
5272                if (currentLevel >= parseInt(jQuery(this).attr("data-separator-level")))
5273                    return false;
5274            }
5275
5276            jQuery(this).hide(speed);
5277        }
5278        );
5279    };
5280
5281    self.expandAll = function (fromLevel, toLevel, options, evtElm) {
5282
5283        var groupedField = self.getGroupedField(options, evtElm);
5284        var levelIndex = fromLevel;
5285        while (levelIndex <= toLevel) {
5286            groupedField.find(".separator-element[data-separator-level=" + levelIndex +"] .exp-toggler").each(function (index) {
5287                self.expandFromThis(this, (options && options.speed) ? options.speed : null, false);
5288            });
5289
5290            (levelIndex == maxLevels) ? levelIndex = variantLevel : levelIndex++;
5291        }
5292    };
5293
5294    self.collapseAll = function (fromLevel, toLevel, options, evtElm) {
5295        var groupedField = self.getGroupedField(options, evtElm);
5296        var levelIndex = fromLevel;
5297        while (levelIndex <= toLevel) {
5298            groupedField.find(".separator-element[data-separator-level="+ levelIndex +"] .exp-toggler").each(function (index) {
5299                self.collapseFromThis(this, (options || options.speed) ? options.speed : null);
5300            });
5301
5302            (levelIndex == maxLevels) ? levelIndex = variantLevel : levelIndex++;
5303        }
5304    };
5305
5306    self.getGroupedField = function (groupedFieldOrOptionsObject, evtElm) {
5307        //Backwards compatibility:
5308        
5309        if (groupedFieldOrOptionsObject && groupedFieldOrOptionsObject.constructor.name!='Object')
5310            return jQuery(groupedFieldOrOptionsObject);
5311
5312        return (groupedFieldOrOptionsObject || groupedFieldOrOptionsObject.field) ? jQuery(groupedFieldOrOptionsObject.field) : jQuery(evtElm.target).parent(".web-pub-field + .web-pub-field.grouped");
5313    };
5314
5315    self.newCollapseState = function (expandFromLevel) {
5316        return {
5317            //State-engine uses zero-based levels, the DOM uses 1-based, with 100 being variant and lowest level
5318            expandFromLevel: expandFromLevel - 1,
5319            currentLevel: expandFromLevel - 1,
5320            collapseLevels: new Array(false, false, false, false, false),
5321            setCurrentSeparatorCollapseStatus: function (level, state) {
5322                this.currentLevel = (level == 100) ? 4 : level - 1;
5323                this.collapseLevels[this.currentLevel] = state;
5324            },
5325            separatorVisibility: function (text) {
5326                //Visible if no levels are collapsed or if collapsed levels are deeper or same as current.
5327                return (this.collapseLevels.indexOf(true) < 0) || this.collapseLevels.indexOf(true) >= this.currentLevel;
5328            },
5329            elementVisibility: function () {
5330                //Visible if no levels are collapsed or if collapsed levels are deeper than current.
5331                return (this.collapseLevels.indexOf(true) < 0) || this.collapseLevels.indexOf(true) > this.currentLevel;
5332            },
5333            isSameOrHigherThanStartLevel: function () {
5334                return this.expandFromLevel >= this.currentLevel;
5335            }
5336        };
5337
5338    };
5339
5340});
5341;
5342mcWeb.warning = new function () {
5343	var self = this;
5344	self.service = new WebApiService("Login");
5345
5346	var isMobile = false;
5347
5348	self.load = function (path) {
5349		PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
5350		jQuery("#lightbox-placeholder").load(path, function () {
5351
5352			if (jQuery("#warningView").length < 1) {
5353				PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
5354				return; //Module not active
5355			}
5356
5357			PubSub.publish(mcWeb.lightbox.events.onShowLightbox);
5358			PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
5359
5360		}); //End Load view
5361	};//End Load
5362
5363	self.loadMobile = function () {
5364		isMobile = true;
5365		onClick();
5366	};
5367
5368	var onClick = function () {
5369		jQuery("#password").on("keypress", function (event) {
5370			if (event.keyCode == 13) {
5371				mcWeb.login.login();
5372				event.preventDefault();
5373			}
5374		});
5375
5376		jQuery("#username").on("keypress", function (event) {
5377			if (event.keyCode == 13) {
5378				mcWeb.login.login();
5379				event.preventDefault();
5380			}
5381		});
5382
5383
5384		//OnClick checkbox
5385		jQuery('#remember_me').on("click", function () {
5386
5387			var chk = jQuery(this).is(':checked');
5388			if (chk) {
5389				window.StorageService.localStorage.setItem('remember', chk);
5390			}
5391		});
5392	};
5393
5394
5395
5396	var pswt = "********************";
5397	self.login = function () {
5398		try {
5399
5400			jQuery('#UpdateIcon').show();
5401
5402			var psw = jQuery("#password").val();
5403
5404			var data = {
5405				username: encodeURIComponent(jQuery("#username").val()),
5406				password: encodeURIComponent((psw === pswt) ? window.StorageService.localStorage.getItem('id') : psw),
5407				localstorge: (psw === pswt) ? true : false,
5408				allowasynclogin: true
5409			};
5410
5411			self.service.PostAction("Login", data).then(function (result) {
5412				PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
5413
5414				if (result.Success === true) {
5415                    clearStorage();
5416
5417					if (result.LoginContacts != null && isMobile == false) {
5418						mcWeb.loginContacts.load(result.LoginContacts);
5419					} else {
5420						if (isMobile) {
5421							window.location.href = jQuery('#url-ref').text();
5422						} else {
5423							window.location.href = document.location.href.replace(location.hash, "");
5424						}
5425					}
5426				} else {
5427					clearStorage();
5428					jQuery("#error-msg-login").show();
5429				}
5430
5431				return false;
5432			});
5433		} catch (e) {
5434			if (isMobile == true) {
5435				jQuery.mobile.loading("hide");
5436			}
5437		}
5438	};//End Login
5439
5440	self.loginAfterPasswordReset = function () {
5441		try {
5442			var psw = jQuery("#password").val();
5443
5444			var data = {
5445				username: encodeURIComponent(jQuery("#username").val()),
5446				password: encodeURIComponent((psw === pswt) ? window.StorageService.localStorage.getItem('id') : psw),
5447				localstorge: (psw === pswt) ? true : false,
5448				allowasynclogin: true
5449			};
5450
5451			self.service.PostAction("Login", data).then(function (result) {
5452				if (result.Success === true) {
5453					window.location.href = "http://" + location.hostname;
5454				}
5455
5456				return false;
5457			});
5458		} catch (e) {
5459			if (isMobile == true) {
5460				jQuery.mobile.loading("hide");
5461			}
5462		}
5463	};
5464
5465	var clearStorage = function () {
5466        try {
5467            window.StorageService.localStorage.removeItem('id');
5468            window.StorageService.localStorage.removeItem('user');
5469            window.StorageService.localStorage.removeItem('remember');
5470        } catch (e) {
5471            console.log('WarningView - ex: ' + e);
5472        }
5473	};
5474
5475	this.logout = function (mobile) {
5476		PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
5477
5478		isMobile = mobile;
5479        self.service.GetAction("Logout", "").then(function (result) {
5480            //window.StorageService.sessionStorage.removeItem('authenticatedGuid');
5481			if (result === true) {
5482                window.location.href = (isMobile) ? ("http://" + location.hostname) : document.location.href.replace(location.hash, "");
5483				PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
5484			} else {
5485				alert('Error logg ut');
5486			}
5487		});
5488	};
5489
5490	//Log in out btn
5491	this.LoginOut = function () {
5492
5493		self.service.GetAction("Loginout", "").then(function (result) {
5494			if (result == null)
5495				return;
5496
5497			var lg = jQuery("#loginout");
5498			lg.text(result.LoginText);
5499			var ct = jQuery("#loginout-content");
5500
5501			if (result.IsLogedin === true) {
5502				lg.attr('href', (result.ShowClubLogin ? '#logincontact' : '#logout'));
5503				ct.removeClass("LogInButtonContainer");
5504				ct.addClass("LogUtButtonContainer");
5505			} else {
5506				lg.attr('href', (result.ShowClubLogin ? '#logincontact' : '#login'));
5507				ct.removeClass("LogUtButtonContainer");
5508				ct.addClass("LogInButtonContainer");
5509			}
5510
5511			jQuery("#loginuser").text(result.LoginUser);
5512		});
5513	};
5514
5515
5516};;
5517mcWeb.hamburgerMenu = new function () {
5518
5519    var self = this;
5520    self.events = {
5521        onMenuNeedsRefresh: "mcWeb.hamburgerMenu.onMenuNeedsRefresh"
5522    };
5523
5524    self.menuData = ko.observableArray([]);
5525    self.service = new WebApiService("Menu");
5526    //var self.theVm = null;
5527    self.MenuVm = null;
5528    self.stickybar = null;
5529    self.language = jQuery("html").attr("lang");
5530    self.cacheKeySuffix = "";
5531    if (!!self.language && self.language.length > 0)
5532        self.cacheKeySuffix = "_" + self.language;
5533
5534    self.vm = function () {
5535        var me = this;
5536        me.menuDataItems = ko.observableArray();
5537        me.firstlevelNodes = ko.observableArray();
5538        me.firstSelectedNodeId = ko.observable(0);
5539        me.firstSelectedNode = ko.observable(null);
5540        me.firstSelectedNodeCssClass = ko.observable('');
5541        me.rootNodeId = ko.observable();
5542        me.selectedNodes = ko.observableArray([]);
5543        me.delayTimer = null;        
5544
5545        me.triggerSubMenu = function (data, evt) {
5546            var doHoverDelay = (evt.type === "mouseover");
5547            if (data.Level === "0" || !doHoverDelay) {
5548                if (null !== me.delayTimer) {
5549                    clearTimeout(me.delayTimer);
5550                    me.delayTimer = null;
5551                }
5552                me.showSubMenu(data, evt);
5553            } else {
5554                clearTimeout(me.delayTimer);
5555                me.delayTimer = null;
5556                me.delayTimer = setTimeout(function () {
5557                    me.showSubMenu(data, evt);
5558                }, 300);
5559            }
5560        };
5561
5562        me.showSubMenu = function (data, evt) {
5563
5564            if (data.Level === "0" && (data.WebSiteMapNodeID === parseInt(me.firstSelectedNodeId()))) {
5565                me.resetMenu();
5566                return;
5567            }
5568
5569            while (parseInt(data.Level) < me.selectedNodes().length) {
5570                me.selectedNodes.pop();
5571            }
5572
5573            var node = me.getNodes(data.WebSiteMapNodeID);
5574            if (node === null || node === undefined)
5575                return;
5576
5577            var childNode = node.Children;
5578
5579
5580            var subNode = {
5581                level: ko.observable(parseInt(data.Level) + 1),
5582                nodeId: ko.observable(data.WebSiteMapNodeID),
5583                Children: ko.observableArray(JSON.parse(JSON.stringify(childNode))),
5584                selectedId: ko.observable(0)
5585            };
5586
5587            if (subNode.Children().length === 0)
5588                return;
5589
5590            ko.utils.arrayForEach(subNode.Children(), function (child) {
5591                var childTree = me.getNodes(child.WebSiteMapNodeID);
5592                if (childTree) {
5593                    child.HasChildren = (childTree.Children.length !== 0);
5594                    child.CssClass += (childTree.Children.length !== 0) ? " has-children" : "";
5595                } else {
5596                    child.HasChildren = false;
5597                }
5598            });
5599            me.addLevel(subNode);
5600            if (data.Level == 0) {
5601                document.querySelector("#burger-menus").style.cssText = "left: " + evt.target.offsetLeft + "px; top: " + evt.target.offsetTop +"px";
5602                me.firstSelectedNodeId(data.WebSiteMapNodeID);
5603                me.firstSelectedNode(data);
5604                me.firstSelectedNodeCssClass(data.CssClass);
5605                me.setOverlay(true);
5606            }
5607
5608        };
5609
5610        me.addLevel = function (subNodes) {
5611            me.selectedNodes.push(subNodes);
5612            var level = subNodes.level() - 2;
5613            if (level >= 0)
5614                me.selectedNodes()[level].selectedId(subNodes.nodeId());
5615        };
5616
5617        me.SubMenuOut = function (data, evt) {
5618
5619        }
5620
5621        me.load = function (data) {
5622            me.rootNodeId(data.RootNodeId);
5623            me.menuDataItems(data.Items);
5624            me.firstlevelNodes(me.getNodes(data.RootNodeId).Children);
5625            ko.utils.arrayForEach(me.firstlevelNodes(), function (child) {
5626                var childTree = me.getNodes(child.WebSiteMapNodeID);
5627                if (childTree) {
5628                    child.HasChildren = (childTree.Children.length !== 0);
5629                } else {
5630                    child.HasChildren = false;
5631                }
5632            });
5633            document.querySelector('body').classList.add('mc-ham-menu');
5634            var useStickyMenu = document.querySelector('.use-sticky-header');
5635            if (useStickyMenu !== null) {
5636                if (self.stickybar == null) {
5637                    var topm = document.querySelector('.use-sticky-smallcart .m-header-dock .top-menu');
5638                    var offsetTop = (topm !== null) ? topm.offsetHeight : 0;
5639                    offsetTop = (offsetTop > 0) ? offsetTop * (-1) : offsetTop;
5640
5641                    if (topm !== null) {
5642                        var stickySearch = new Stickybar(jQuery, '.m-header-dock', 0, offsetTop);
5643                    }
5644                    self.stickybar = new Stickybar(jQuery, '.menu-container', 0, offsetTop);
5645                }
5646            }
5647            var evenHeaderReady = document.createEvent("Event");
5648            evenHeaderReady.initEvent("header-menu-ready", false, false);
5649            evenHeaderReady.target = document;
5650            document.dispatchEvent(evenHeaderReady);
5651        };
5652
5653        me.getNodes = function (parentNode) {
5654            return me.menuDataItems()[parentNode];
5655        }
5656
5657        me.setOverlay = function (show) {
5658
5659            var body = document.querySelector('body');
5660
5661            if (show === true) {
5662                body.classList.add('mc-menu-overlay');
5663            } else {
5664                body.classList.remove('mc-menu-overlay');
5665            }
5666        }
5667
5668        me.titleTrigger = function () {
5669            if (me.selectedNodes().length === 0)
5670                return;
5671
5672            me.selectedNodes()[0].selectedId(0);
5673            clearTimeout(me.delayTimer);
5674            while (me.selectedNodes().length > 1)
5675                me.selectedNodes.pop();
5676        };
5677
5678        me.resetMenu = function () {
5679            while (me.selectedNodes().length > 0)
5680                me.selectedNodes.pop();
5681            me.firstSelectedNodeId(0);
5682            me.firstSelectedNode(null);
5683            me.firstSelectedNodeCssClass('');
5684            me.setOverlay(false);
5685        };
5686    };
5687
5688    self.load = function () {
5689        var menuData = self.getMenuCache();
5690        if (menuData !== null) {
5691            self.initVm(menuData);
5692
5693        } else {
5694            self.service.GetAction("GetMenuData", null).then(function (result) {
5695                if (result !== null) {
5696                    self.setMenuCache(result);
5697                    self.initVm(result);
5698                }
5699
5700            });
5701        }
5702        document.querySelector(".mc-overlay").addEventListener("click",
5703            function (e) {
5704                return mcWeb.hamburgerMenu.resetMenu();
5705            }
5706        );
5707
5708        PubSub.subscribe(mcWeb.hamburgerMenu.events.onMenuNeedsRefresh, function (evt) {
5709            self.resetMenuCache();
5710        });
5711
5712    };
5713
5714    self.resetMenu = function () {
5715        self.MenuVm.resetMenu();
5716    };
5717
5718    self.initVm = function (menuData) {
5719        self.MenuVm = new self.vm();
5720        self.MenuVm.load(menuData);
5721        var hamburgerMenuPlaceholder = document.getElementById("hamburgerMenu");
5722        if (hamburgerMenuPlaceholder)
5723            ko.applyBindings(self.MenuVm, hamburgerMenuPlaceholder);
5724        else
5725            console.log("No node to bind menu");
5726    };
5727
5728    self.getMenuCache = function () {
5729        var nextMenuDataRefresh = window.StorageService.sessionStorage.getItem("hamburgercachetime" + self.cacheKeySuffix);
5730        if (nextMenuDataRefresh !== "" && nextMenuDataRefresh !== null && nextMenuDataRefresh !== undefined) {
5731            nextMenuDataRefresh = new Date(nextMenuDataRefresh);
5732        } else {
5733            nextMenuDataRefresh = new Date(Date.now() + 5 * 60000);
5734            window.StorageService.sessionStorage.setItem("hamburgercachetime" + self.cacheKeySuffix, nextMenuDataRefresh);
5735        }
5736
5737        if (nextMenuDataRefresh < Date.now())
5738            return null;
5739
5740        try {
5741            var menuCache = window.StorageService.sessionStorage.getItem("hamburgercache" + self.cacheKeySuffix);
5742            return (menuCache === "") ? null : JSON.parse(menuCache);
5743        } catch (e) {
5744            //No Web Storage support
5745        }
5746        return null;
5747    };
5748
5749    self.resetMenuCache = function () {
5750        window.StorageService.sessionStorage.setItem("hamburgercachetime" + self.cacheKeySuffix , null);
5751        self.setMenuCache(null);
5752    };
5753
5754    self.setMenuCache = function (menuData) {
5755        try {
5756            if (menuData === null) {
5757                window.StorageService.sessionStorage.setItem("hamburgercache" + self.cacheKeySuffix, "");
5758            } else {
5759                var textMenuData = JSON.stringify(menuData);
5760                window.StorageService.sessionStorage.setItem("hamburgercache" + self.cacheKeySuffix, textMenuData);
5761            }
5762        } catch (e) {
5763            //No Web Storage support
5764        }
5765    };
5766
5767};;
5768mcWeb.magamenu = new (function ($) {
5769    'use strict';
5770
5771    this.init = function () {
5772        var self = this;
5773        //self.service = new WebApiService("ProductInfo");
5774
5775    };//End int
5776
5777    this.toggle = function (sender, id) {
5778        var element = $(sender).next('.nav-content-' + id);
5779        var body = $('body');
5780        if (element.is(":hidden")) {
5781            $('.nav-content-1').removeClass('active');
5782            body.addClass('mc-menu-overlay');
5783            element.addClass('active');
5784        } else {
5785            element.removeClass('active');
5786            body.removeClass('mc-menu-overlay');
5787        }
5788
5789        return false;
5790    }
5791
5792    this.show = function (sender, id) {
5793        var list = $('.nav-content-1.active').find('div.active');
5794        if (list.length > 0) {
5795            list.removeClass('active');
5796        }
5797
5798        var element = $(sender).next('.nav-content-' + id);
5799        element.addClass('active');
5800        return false;
5801    }
5802
5803    this.hide = function () {
5804        $('.nav-content-1').removeClass('active');
5805        return false;
5806    }
5807
5808})(jQuery);;
5809mcWeb.MegaMenuResponsive = new function () {
5810    var $ = jQuery;
5811    var self = this;
5812    self.service = new WebApiService("Menu");
5813    self.hasCacheData = false;
5814    self.stickybar = null;
5815    self._showMobileMenuCollapsed = false;
5816    self._useMobileMenu = false;
5817    self.events = {
5818        onClose: "mcWeb.MegaMenuResponsive.events.onClose",
5819        onOpen: "mcWeb.MegaMenuResponsive.events.onOpen",
5820        onAddNewFilterButton: "mcWeb.MegaMenuResponsive.events.onAddNewFilterButton",
5821        onMenuNeedsRefresh: "mcWeb.MegaMenuResponsive.events.onMenuNeedsRefresh"
5822    }
5823
5824    self.load = function (showMobileMenuCollapsed, nodeId, collapsedSize, disableMegaMenu, enableClickForDesktop, useHamburgerMenu) {
5825        self.language = $("html").attr("lang");
5826        self.country = document.querySelector("html").getAttribute("country");
5827        self.cacheKeySuffix = "";
5828        const loginType = $("body").data("login-type");
5829        if (loginType !== null && loginType !== undefined && loginType.length > 0)
5830            self.cacheKeySuffix = "_" + loginType;
5831
5832        if (!!self.language && self.language.length > 0)
5833            self.cacheKeySuffix = "_" + self.language;
5834
5835        if (!!self.country && self.country.length > 0)
5836            self.cacheKeySuffix += "_" + self.country;
5837
5838        self.hideSubmenu();
5839
5840        PubSub.subscribe(mcWeb.MegaMenuResponsive.events.onMenuNeedsRefresh, function (evt) {
5841            self.resetMenuCache();
5842        });
5843
5844        const useMobileMenu = mcWeb.responsive.useMobileMenu(collapsedSize);
5845        self._useMobileMenu = useMobileMenu;
5846        if (!useMobileMenu && useHamburgerMenu) {
5847            mcWeb.hamburgerMenu.load();
5848            return;
5849        }
5850
5851        const menu = (useMobileMenu) ? $('#smenu') : $("#SubMenuArea");
5852        if (menu.length < 1) {
5853            alert('Error loading menu, please reload page!');
5854            return;
5855        }
5856
5857        showMobileMenuCollapsed = ((showMobileMenuCollapsed == null) ? false : showMobileMenuCollapsed);
5858        self._showMobileMenuCollapsed = showMobileMenuCollapsed;
5859        const cache = getCache(showMobileMenuCollapsed, useMobileMenu);
5860        if (cache !== null && !disableMegaMenu) {
5861            run(useMobileMenu, false, enableClickForDesktop, true, menu, cache);
5862            if (!self.isCachedMenuOld())
5863                return;//
5864        }
5865        loadMenu((cache !== null), menu, nodeId, showMobileMenuCollapsed, useMobileMenu, disableMegaMenu, enableClickForDesktop);
5866       
5867
5868    }; //End Load
5869
5870    const loadMenu = function (isCached, menu, nodeId, showMobileMenuCollapsed, useMobileMenu, disableMegaMenu, enableClickForDesktop) {
5871        try {
5872
5873            if (!isCached)
5874                PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
5875
5876            const ratio = window.devicePixelRatio || 1;
5877            const w = Math.floor(screen.width * ratio);
5878            const h = Math.floor(screen.height * ratio);
5879
5880            const data = {
5881                nodeId: nodeId,
5882                screensize: mcWeb.responsive.getScreenSize(),
5883                screensizePixels: mcWeb.responsive.getScreenSizePixels(),
5884                width: Math.abs(window.orientation) === 90 ? h : w,
5885                height: Math.abs(window.orientation) === 90 ? w : h,
5886                showMobileMenuCollapsed: showMobileMenuCollapsed
5887            }
5888            self.service.GetHTML("GetHtmlMenu", data).then(function (result) {
5889                if (result != null && isValidMenuResponse(result)) {
5890                    //Update cache
5891                    setCache(result, showMobileMenuCollapsed, useMobileMenu);
5892                    var nextMenuDataRefresh = new Date(Date.now() + 5 * 60000);
5893                    window.StorageService.sessionStorage.setItem("megamenucachetime", nextMenuDataRefresh);
5894                    run(useMobileMenu, disableMegaMenu, enableClickForDesktop,false,menu,result);
5895
5896                    if (!isCached) {
5897                        PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
5898                        
5899                    }
5900                } else {
5901                    // Invalid response received - clear cache and reload page
5902                    console.error('Invalid menu response received. Clearing cache and reloading.');
5903                    self.resetMenuCache();
5904                    if (!isCached) {
5905                        PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
5906                    }
5907                }
5908
5909            });
5910        } catch (e) {
5911            PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
5912        }
5913    }
5914
5915    const isValidMenuResponse = function(response) {
5916        // Check if response is a string
5917        if (typeof response !== 'string') {
5918            return false;
5919        }
5920        
5921        // Check for common redirect patterns in the response
5922        // A redirect page typically contains doctype, html, head, body tags
5923        const redirectPatterns = [
5924            /<!DOCTYPE/i,
5925            /<html/i,
5926            /<head/i,
5927            /window\.location/i,
5928            /meta.*http-equiv.*refresh/i
5929        ];
5930        
5931        for (let i = 0; i < redirectPatterns.length; i++) {
5932            if (redirectPatterns[i].test(response)) {
5933                console.warn('Detected redirect/full HTML page in menu response');
5934                return false;
5935            }
5936        }
5937        
5938        // Optionally: Check for expected menu content markers
5939        // For example, if your menu always contains certain classes or elements:
5940        // var hasExpectedContent = response.indexOf('SubMenuArea') > -1 || 
5941        //                         response.indexOf('navbar') > -1 ||
5942        //                         response.indexOf('mmenu') > -1;
5943        // return hasExpectedContent;
5944        
5945        return true;
5946    }
5947
5948    self.isCachedMenuOld = function () {
5949        let nextMenuDataRefresh = window.StorageService.sessionStorage.getItem("megamenucachetime");
5950        if (nextMenuDataRefresh !== "" && nextMenuDataRefresh !== null && nextMenuDataRefresh !== undefined) {
5951            nextMenuDataRefresh = new Date(nextMenuDataRefresh);
5952        } else {
5953            nextMenuDataRefresh = new Date(Date.now() + 5 * 60000);
5954            window.StorageService.sessionStorage.setItem("megamenucachetime", nextMenuDataRefresh);
5955        }
5956
5957        return (nextMenuDataRefresh < Date.now());
5958    };
5959
5960    const getCache = function (collapsed, useMobileMenu) {
5961        try {
5962            let item;
5963            if (collapsed === true && useMobileMenu) {
5964                item = window.StorageService.sessionStorage.getItem("menucache_collapsed" + self.cacheKeySuffix);
5965            } else {
5966                item = window.StorageService.sessionStorage.getItem("menucache" + self.cacheKeySuffix);
5967            }
5968
5969            if (item != null && item.length > 10) {
5970                if (useMobileMenu.toString() === window.StorageService.sessionStorage.getItem("menucache_ismob")) {
5971                    return item;
5972                }
5973            }
5974        } catch (e) {
5975            //No Web Storage support
5976        }
5977
5978        return null;
5979    };
5980
5981    var setCache = function (menu, collapsed, useMobileMenu) {
5982        try {
5983            if (collapsed === true && useMobileMenu) {
5984                window.StorageService.sessionStorage.setItem("menucache_collapsed" + self.cacheKeySuffix, menu);
5985            } else {
5986                window.StorageService.sessionStorage.setItem("menucache" + self.cacheKeySuffix, menu);
5987            }
5988
5989            window.StorageService.sessionStorage.setItem("menucache_ismob", (useMobileMenu));
5990        } catch (e) {
5991            //No Web Storage support
5992        }
5993    };
5994
5995    self.resetMenuCache = function () {
5996        var nextMenuDataRefresh = new Date(Date.now() - 60000);
5997        if (jQuery("body.user-is-admin")) {
5998            window.StorageService.sessionStorage.setItem("menucache_collapsed" + self.cacheKeySuffix, null);
5999            window.StorageService.sessionStorage.setItem("menucache" + self.cacheKeySuffix, null);
6000        }
6001        window.StorageService.sessionStorage.setItem("megamenucachetime", nextMenuDataRefresh);
6002    };
6003    const getFilterStatus = function () {
6004        try {
6005            var value = window.StorageService.sessionStorage.getItem("filter_active");
6006            return (value !== null && value === 'true') ? true : false;
6007        } catch (e) {
6008            //No Web Storage support
6009            return false;
6010        }
6011    }
6012
6013    const setFilterStatus = function (status) {
6014        try {
6015            window.StorageService.sessionStorage.setItem("filter_active", status);
6016        } catch (e) {
6017            //No Web Storage support
6018        }
6019    }
6020
6021    const getScrollPos = function () {
6022        try {
6023            const value = window.StorageService.sessionStorage.getItem("filter_scrollx");
6024            return (value !== null) ? parseInt(value) : -1;
6025        } catch (e) {
6026            //No Web Storage support
6027            return -1;
6028        }
6029    }
6030
6031    const setScrollPos = function (top) {
6032        try {
6033            //var doc = document.documentElement;
6034            ////var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
6035            //var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
6036            //$('.c-menu__close').html(top);
6037            window.StorageService.sessionStorage.setItem("filter_scrollx", top);
6038        } catch (e) {
6039            //No Web Storage support
6040        }
6041    }
6042
6043
6044
6045    const closePanel = function () {
6046        document.querySelector('.mmenu_close').click();
6047    }
6048
6049    self.Login = function () {
6050        closePanel();
6051        setTimeout(function () {
6052            window.location.hash = '#login';
6053        }, 400);
6054    }
6055
6056    self.Logout = function (isAgent) {
6057        closePanel();
6058        setTimeout(function () {
6059            window.location.hash = (isAgent === true) ? '#loginagent' : '#logout';
6060        }, 400);
6061    }
6062
6063    self.RegisterCust = function () {
6064        closePanel();
6065        setTimeout(function () {
6066            window.location.hash = '#customerregistration';
6067        }, 400);
6068    }
6069
6070    self.hideSubmenu = function () {
6071
6072        var openEl = $('.SubMenuArea .navbar li.dropdown.open');
6073        openEl.removeClass('open');
6074        openEl.find('a[aria-expanded="true"]').attr('aria-expanded', false);
6075
6076        $('body').removeClass('mc-menu-overlay');
6077    }
6078
6079    let leftMenu = null;
6080    let pushRight = null;
6081    const mobileNavMenu = function (useMobileMenu, menuElement, menuHtml) {
6082        let menuPromise = null;
6083
6084        if (useMobileMenu) {
6085
6086            //Move Kundesender info to right menu mobil if not already exists (2xu.no)!
6087            const infoMenu = document.querySelector('.mmenu-push-right .mmenu-iInfoMenu');
6088            if (infoMenu == null) {
6089
6090                ///Move info meny to mobile sidebar menu
6091                const oldParent = document.getElementsByClassName('top-menu')[0];
6092                if (oldParent == null)
6093                    return;
6094
6095                const newParent = document.querySelector('#mmenu-push-right');
6096                if (newParent == null)
6097                    return;
6098
6099                for (let i = 0; i < oldParent.children.length; i++) {
6100                    newParent.appendChild(oldParent.children[i]);
6101                }
6102            }
6103            
6104            if (pushRight === null) {
6105                menuPromise = getLibrary("nav-bar-mobile")
6106                    .then(() => { return getLibrary("slinky"); })
6107                        .then(() => {
6108                            $(".header-main .container-top-menu").on("click", () => {
6109                            menuElement.html(menuHtml);
6110                            $(".header-main .container-top-menu").prop("onclick", null).off("click"); //remove this onclick, sinc we only want this to run once.
6111                            pushRight = new Menu({
6112                                wrapper: '#o-wrapper',
6113                                type: 'push-right',
6114                                menuOpenerClass: '.container-top-menu',
6115                                maskId: '#m-mask',
6116                                btn: '.container-top-menu',
6117                                menuStartId: '#mmenu-',
6118                                closeClass: '.mmenu_close'
6119                            });
6120                            const backText = document.getElementById('mback').innerHTML;
6121                            pushRight.slinkyMenu = jQuery('#mmenu').slinky({
6122                                label: backText
6123                                , title: true
6124                            });
6125                            pushRight.open();
6126                        });
6127                    });
6128            }
6129            
6130        }
6131        else {
6132            menuElement.html(menuHtml);
6133        }
6134        if (menuPromise === null) {
6135            //we need not wait for the menuPromise, but we must return a promise...
6136            menuPromise = Promise.resolve();
6137        }
6138
6139        const filterToMove = $('#PageColumnLeft');
6140
6141        if (filterToMove.find('.ProductMenu ul li').length < 1) {
6142            const b = $('body');
6143            if (b.length > 0 && !b.hasClass('empty-product-menu')) {
6144                b.addClass('empty-product-menu');
6145            }
6146        }
6147        if (filterToMove.find('.has-filters').length < 1) {
6148            const b = $('body');
6149            if (b.length > 0 && !b.hasClass('has-no-filter')) {
6150                b.addClass('has-no-filter');
6151            }
6152        }
6153
6154        const useBredcrumb = ($('.breadcrumb-container').height() > 0);
6155        const b = $('body');
6156        if (useBredcrumb) {
6157            if (b.length > 0 && !b.hasClass('has-breadcrumb')) {
6158                b.addClass('has-breadcrumb');
6159            }
6160        } else {
6161            if (b.length > 0 && !b.hasClass('no-breadcrumb')) {
6162                b.addClass('no-breadcrumb');
6163            }
6164        }
6165
6166        const size = mcWeb.responsive.getScreenSize();
6167        //Check if left attribute filter already exists
6168        // Dont use filter toolbare if size > sm
6169        if (leftMenu != null || (size == 'md' || size == 'lg'))
6170            return menuPromise;
6171
6172        var slideLeft = null;
6173        var menuOpenerClass = '.container-filter-menu';
6174        var filterButton = jQuery('.container-filter-menu');
6175        if (filterButton.length < 1) {
6176            filterButton = jQuery('.container-filter-menu-cells');
6177            menuOpenerClass = '.container-filter-menu-cells';
6178        }
6179
6180        if (filterButton.length > 0) {
6181            /* Attribute filter */
6182            getLibrary("nav-bar-mobile").then(() => {
6183                slideLeft = new Menu({
6184                    wrapper: '#o-wrapper',
6185                    type: 'slide-left',
6186                    menuOpenerClass: menuOpenerClass,
6187                    maskId: '#m-mask',
6188                    btn: menuOpenerClass
6189                });
6190
6191                leftMenu = slideLeft;
6192            });
6193        }
6194
6195        /* Move Attribute filter in to Left Menu */
6196        if (filterButton.length > 0 && filterToMove.length > 0 && filterToMove.find('.attribute-left-box .has-filters').length > 0) { //Do filter exist on this page
6197
6198            filterToMove.removeClass("hidden-xs");
6199
6200            var filter = $('#mmenu-left');
6201            filter.on("scroll", function (event) {
6202                setScrollPos(this.scrollTop);
6203            });
6204
6205            filter.append(filterToMove);
6206
6207            var items = $('.filter-selection .SelectedAttribute').length;
6208            var btn = $('#filter-btn');
6209            var filterCount = btn.find('.filters-count');
6210            if (items < 1) {
6211                filterCount.addClass('hidden');
6212            } else {
6213                filterCount.removeClass('hidden').html(items);
6214            }
6215
6216            btn.show();
6217
6218            //Is filter active (gaia is reloading the page)
6219            if (getFilterStatus() == true) {
6220                slideLeft.notransition();
6221                slideLeft.open();
6222                var scrollx = getScrollPos();
6223                if (scrollx > -1) {
6224                    filter.scrollTop(scrollx);
6225                }
6226                PubSub.publish("AjaxRenderingEngine.onFilterLoadRequested", null);
6227                setTimeout(function () { slideLeft.transition(); }, 300);
6228
6229            }
6230        }
6231
6232        return menuPromise;
6233    }
6234
6235    PubSub.subscribe(self.events.onAddNewFilterButton, function(message, id){
6236          if($("body.device-size-xs").length <= 0 && $("body.device-size-sm").length <=0)
6237           return;//only do this for phones and tablets
6238
6239        var filter = $('#mmenu-left');
6240       
6241        var slideLeft = null;
6242        var menuOpenerClass = '.container-filter-menu';
6243        var filterButton = jQuery('.container-filter-menu');
6244        if (filterButton.length < 1) {
6245            filterButton = jQuery('.container-filter-menu-cells');
6246            menuOpenerClass = '.container-filter-menu-cells';
6247        }
6248
6249        if (filterButton.length > 0) {
6250            /* Attribute filter */
6251            getLibrary("nav-bar-mobile").then(() => {
6252
6253                slideLeft = new Menu({
6254                    wrapper: '#o-wrapper',
6255                    type: 'slide-left',
6256                    menuOpenerClass: menuOpenerClass,
6257                    maskId: '#m-mask',
6258                    btn: menuOpenerClass
6259                });
6260
6261                leftMenu = slideLeft;
6262                if (filter.find("#PageColumnLeft").length <= 0) {
6263                    //PageColumnLeft should be moved into the aside when on mobile or tablet
6264                    var filterToMove = $('#PageColumnLeft');
6265                    filterToMove.removeClass("hidden-xs");
6266                    filter.append(filterToMove);
6267                }
6268                if (getFilterStatus() == true) { //Is filter active (gaia is reloading the page)
6269                    slideLeft.notransition();
6270                    slideLeft.open();
6271                    var scrollx = getScrollPos();
6272                    if (scrollx > -1) {
6273                        filter.scrollTop(scrollx);
6274                    }
6275                    setTimeout(function () { slideLeft.transition(); }, 300);
6276                }
6277            });
6278        }
6279        var btn = $('#filter-btn');
6280        btn.show();
6281    });
6282
6283    PubSub.subscribe(self.events.onOpen, function (message, id) {
6284        PubSub.publish("AjaxRenderingEngine.onFilterLoadRequested", null);
6285        if (id === "c-menu--slide-left") {
6286            setFilterStatus(true);
6287        }
6288    });
6289    PubSub.subscribe(self.events.onClose, function (message, id) {
6290        if (id === "c-menu--slide-left") {
6291            setFilterStatus(false);
6292        }
6293    });
6294
6295    var toggleSearch = function () {
6296        var content = document.querySelector(".HeaderSearch");
6297        content.classList.toggle('show-search');
6298        if (content.classList.contains('show-search')) {
6299            document.querySelector(".main-search-a input").focus();
6300        } else {
6301            document.activeElement.blur();
6302        }
6303    }
6304
6305    self.setOverlay = function (show) {
6306
6307        var body = $('body');
6308
6309        if (show === true) {
6310            body.addClass('mc-menu-overlay');
6311        } else {
6312            body.removeClass('mc-menu-overlay');
6313        }
6314    }
6315
6316    var getMegaMenuIdentifierClass = function (target) {
6317
6318        var menuIndex = target.data("menu-index");
6319        return ".mc-menu .dropdown.mcm-fw[data-menu-index=" + menuIndex + "] .NoSlide.web-pub-field div.ajax-field";
6320    };
6321    var run = function (useMobileMenu, disableMegaMenu, enableClickForDesktop, isCacheMenu, menuElement, menuHtml) {
6322
6323        mobileNavMenu(useMobileMenu, menuElement, menuHtml).then(() => { 
6324
6325        var toggle = document.getElementById("m-search");
6326        var toggle2 = document.getElementById("CloseSearchButton");
6327
6328        if (toggle)
6329            toggle.addEventListener("click", toggleSearch, false);
6330        if (toggle2)
6331            toggle2.addEventListener("click", toggleSearch, false);
6332
6333            if (!useMobileMenu) {
6334
6335                if (!disableMegaMenu && !enableClickForDesktop) {
6336                    $('.SubMenuArea .navbar .dropdown').hover(function () {
6337                        $(this).find('.dropdown-menu').first().stop(true, true).show();
6338                        if (mcWeb.ajaxRenderEngine !== undefined) {
6339                            mcWeb.ajaxRenderEngine.updateContentForSpecificFields(getMegaMenuIdentifierClass($(this)));
6340                        }
6341                    }, function () {
6342                        $(this).find('.dropdown-menu').first().stop(true, true).hide(); //.delay(100).slideUp();
6343                    }
6344                    );
6345
6346                    $('.SubMenuArea .navbar .dropdown-menu').hover(function () {
6347                        $(this).parent().addClass('open');
6348                        if (mcWeb.ajaxRenderEngine !== undefined) {
6349                            mcWeb.ajaxRenderEngine.updateContentForSpecificFields(getMegaMenuIdentifierClass($(this)));
6350                        }
6351
6352                    }, function () {
6353                        $(this).parent().removeClass('open');
6354
6355                    });
6356                }
6357
6358                var isTap = enableClickForDesktop;
6359                $('.SubMenuArea .navbar .dropdown > a').on("touchstart", function () {
6360                    isTap = true;
6361                });
6362
6363                $('.MegaMenuNotPublished').click(function (e) {
6364                    e.stopPropagation();
6365                })
6366
6367                $('.SubMenuArea .navbar .dropdown > a').click(function (event) {
6368                    var parent = $(this).parent();
6369                    var dropMenu = parent.find('.dropdown-menu');
6370
6371                    if (!isTap || dropMenu.length < 1 || disableMegaMenu) {
6372
6373                        var searchStr = "http";
6374                        if (this.href.substr(0, searchStr.length) === searchStr) {
6375                            window.open(this.href, this.target);
6376                            return false;
6377                        }
6378                        location.href = this.href;
6379                        return;
6380                    }
6381
6382                    isTap = enableClickForDesktop;
6383
6384                    var showhide = dropMenu.children('ul').stop(true, true);
6385                    if (parent.hasClass('open') === true) {
6386                        showhide.hide();
6387                        self.setOverlay(false);
6388                    } else {
6389                        showhide.show();
6390                        self.setOverlay(true);
6391                        if (mcWeb.ajaxRenderEngine !== undefined) {
6392                            mcWeb.ajaxRenderEngine.updateContentForSpecificFields(getMegaMenuIdentifierClass(dropMenu.parent()));
6393                        }
6394                    }
6395                });
6396
6397                if (isCacheMenu == undefined) {
6398
6399                    $("document").ready(function ($) {
6400                        var useStickyMenu = $('.use-sticky-header');
6401                        if (useStickyMenu.length > 0) {
6402                            if (self.stickybar == null) {
6403                                var topm = $('.use-sticky-smallcart .m-header-dock .top-menu');
6404                                var offsetTop = (topm.length > 0) ? topm.height() : 0;
6405                                offsetTop = (offsetTop > 0) ? offsetTop * (-1) : offsetTop;
6406
6407                                if (topm.length > 0) {
6408                                    var stickySearch = new Stickybar(jQuery, '.m-header-dock', 0, offsetTop);
6409                                }
6410                                self.stickybar = new Stickybar(jQuery, '.menu-container', 0, offsetTop);
6411                                $(document).trigger("header-menu-ready");
6412                            }
6413                        } else {
6414                            $(document).trigger("header-menu-ready");
6415                        }
6416                    });
6417                }
6418
6419
6420            }
6421            else {
6422
6423                if (mcWeb.responsive.getScreenSize() === 'xs') {
6424                    setHeadRoom(); // Global function in General_scripts.js (D2016) or mcweb4-standard.js (D4)
6425                }
6426            }
6427        });
6428    }
6429};;
6430mcWeb.partStream = new function() {
6431
6432  var self = this;
6433  self.service = new WebApiService("ProductInfo");
6434
6435  this.getAllIndexes = function(array, value) {
6436    var indexes = [], i;
6437    for (i = 0; i < array.length; i++)
6438      if (array[i].indexOf(value) > -1 )
6439        indexes.push(i);
6440    return indexes;
6441  };
6442
6443  this.getListOfVareNr = function (data) {
6444    var dat = data.split("&");
6445    var varnr = [];
6446    var indexes = self.getAllIndexes(dat, "arisku");
6447
6448    for (var i = 0; i < indexes.length; i++) {
6449      var nr = dat[indexes[i]];
6450      varnr.push(nr.substring(7));
6451    }
6452    return varnr;
6453  };
6454
6455  this.getListOfQuantities = function(data) {
6456    var dat = data.split("&");
6457    var quantity = [];
6458    var indexes = self.getAllIndexes(dat, "ariqty");
6459
6460    for (var i = 0; i < indexes.length; i++) {
6461      var qty = dat[indexes[i]];
6462      quantity.push(qty.substring(7));
6463    }
6464    return quantity;
6465  };
6466
6467  this.getListOfBrand = function (data) {
6468    var dat = data.split("&");
6469    var brand = [];
6470    var indexes = self.getAllIndexes(dat, "aribrand");
6471
6472    for (var i = 0; i < indexes.length; i++) {
6473      var bName = dat[indexes[i]];
6474      brand.push(bName.substring(9));
6475    }
6476    return brand[0];
6477  };
6478
6479  this.parseProducts = function(data) {
6480    var dat = data.split("&");
6481    console.log(dat);
6482
6483    var parsedProducts = [];
6484
6485
6486  };
6487
6488  this.addToCart = function (data) {
6489    var varenr = self.getListOfVareNr(data);
6490    var amount = self.getListOfQuantities(data);
6491    var brand = self.getListOfBrand(data);
6492
6493    var dat = { varenr: varenr, amount: amount, brand: brand, isCheckout: false };
6494    PubSub.publish(mcWeb.lightbox.events.onShowSpinicon);
6495      self.service.GetAction("AddToCartVareNr", dat).then(function (result) {
6496      if (result != null && result.Success == true) {
6497        PubSub.publish(mcWeb.cartsmall.events.onShowNewItemInCartText, { status: true, msg: result.PopupText });
6498        PubSub.publish(mcWeb.cartsmall.events.onUpdateCart);
6499        PubSub.publish(mcWeb.events.freeShippingTxt.onUpdateFreeShipping);
6500        if (result.Redirect != null && result.Redirect === "[REFRESH]") {
6501          location.reload();
6502        }
6503      } else {
6504        alert('Beklager produktet er ikke tilgjengelig for salg!');
6505      }
6506      PubSub.publish(mcWeb.lightbox.events.onHideSpinicon);
6507    });
6508  }
6509};
6510mcWeb.EdmRegistration = new (function ($) {
6511    var me = this;
6512    this.events = {
6513        onInOutChange: "mcWeb.EdmRegistration.events.onInOutChange",
6514        onEdmRegistrationSuccess: "mcWeb.EdmRegistration.events.onEdmRegistrationSuccess",
6515        onEdmRegistrationTBFocus: "mcWeb.EdmRegistration.events.onEdmRegistrationTBFocus"
6516    };
6517
6518  
6519    this.vm = function (id) {
6520        var $ = jQuery;
6521        var self = this;
6522        self.langService = new LanguageService();
6523        this.id = "#" + id;
6524        this.isInnmelding = ko.observable(true);
6525        self.emailAddress = ko.observable();
6526
6527        this.service = new WebApiService("EdmRegistration");
6528        this.conditionsService = new WebApiService("Conditions");
6529        //vm for GDPR conditions
6530        this.conditionVM = new mcWeb.conditions.vm(self.id);
6531        this.conditionsStatus = {
6532            isFunctionalConditionAccepted: ko.observable(false),
6533            acceptDocuments: ko.observableArray([]),
6534            usageArea: 4
6535        };   
6536        this.load = function (data, settings) {
6537            self.conditionVM.load(null, { usageArea: 4, forUnknownUser: true, functionName: 'EDM', status: self.conditionsStatus  });
6538        };
6539
6540        this.onEDMChange = function (data, evt, isIn) {
6541            this.isInnmelding(isIn);
6542            PubSub.publish(mcWeb.EdmRegistration.events.onInOutChange, {
6543                isIn: isIn,
6544                parentDomId: self.id
6545            });
6546            var errorLabel = $(self.id +' .ErrorInfo').find("[id*='LabelInfo']");
6547            if (errorLabel != null)
6548                errorLabel.text('');
6549        }
6550
6551        this.onEmailFocus = function() {
6552            PubSub.publish(mcWeb.EdmRegistration.events.onEdmRegistrationTBFocus, { hasFocus: true, isIn: self.isInnmelding(), parentDomId: self.id } );
6553            var errorLabel = $(self.id +' .ErrorInfo').find("[id*='LabelInfo']");
6554            if (errorLabel != null)
6555                errorLabel.text('');
6556        }
6557
6558        //Enable or disable InlineEditor
6559        this.onClickRegisterEmail = function () {
6560
6561            var unregister = $(self.id +" [id*='RadioButtonUt']").is(':checked');
6562            if (!unregister && !self.conditionsStatus.isFunctionalConditionAccepted()) {
6563                console.log("Required terms not accepted");
6564                self.langService.getValue('NEWS_SUBSCRIPTION', 'EmailTermsNotAccepted').then(function (value) {
6565                    var errorLabel = $(self.id +' .ErrorInfo').find("[id*='LabelInfo']");
6566                    if(errorLabel != null)
6567                        errorLabel.text(value);
6568                });
6569                return;
6570            }
6571            else {
6572                console.log("Required terms accepted");
6573            }
6574
6575            var email = $(self.id +" [id*='TextBoxEmail']").val();
6576
6577            if (self.conditionsStatus.acceptDocuments !== undefined && self.conditionsStatus.acceptDocuments != null && self.conditionsStatus.acceptDocuments().length > 0) {
6578                //fetch value from self.acceptDocuments and use Accepted() as value to set.
6579                var responseCounter = 0;
6580                var docs = self.conditionsStatus.acceptDocuments();
6581                var expectedResponses = docs.length;
6582                var emailWillBeRegisteredByTermAcceptance = false;
6583                var edmBlockedByTerm = false;
6584                var edmTermWasRegistered = false;
6585                for (i = 0; i < expectedResponses; i++) {
6586                    var doc = docs[i];
6587                    if (doc !== null) {
6588                        var acceptStatus = doc.Accepted;
6589
6590                        if (!acceptStatus && !doc.TermRequiredForFunction)
6591                            continue;
6592
6593                        if (unregister) {
6594                            acceptStatus = false;
6595                        }
6596                        var myParams = {
6597                            Accept: acceptStatus,
6598                            DocUsageId: doc.DocUsageID,
6599                            RevDataId: doc.RevDataID,
6600                            AvsAdresseID: null,
6601                            KndKontaktId: null,
6602                            DomainId: null,
6603                            EmailAddress: email,
6604                            ReferenceString: doc.FunctionReferenceString
6605                        };
6606                        if (unregister && doc.FunctionReferenceString != "EDM")
6607                            continue;
6608                        else if (unregister && doc.FunctionReferenceString == "EDM") {
6609                            myParams.Accept = false;
6610                        }
6611                        emailWillBeRegisteredByTermAcceptance = emailWillBeRegisteredByTermAcceptance ||
6612                            (!unregister && doc.FunctionReferenceString == "EDM" && doc.Accepted);
6613                        //|| (unregister && doc.FunctionReferenceString == "EDM" && !doc.Accepted);
6614
6615                        if (doc.FunctionReferenceString == "EDM")
6616                            edmTermWasRegistered = true;
6617
6618                        self.conditionsService.PostAction("RegisterTermAcceptance", myParams).then(function (result) {
6619                            if (result) {
6620                                responseCounter++;
6621                            }
6622
6623                            if (result.DoRegisterEdm == true ) {
6624                                self.ShowEmailRegresult(result.Accept, result.EdmRegistrationResult);
6625                            }
6626                        });
6627                    }
6628                }
6629                if (!edmTermWasRegistered) {
6630                    self.RegisterEmail(email, unregister);
6631                }
6632
6633            } else {
6634                self.RegisterEmail(email, unregister);
6635            }
6636
6637        };
6638        this.ShowEmailRegresult = function(accept, result) {
6639            var obj = jQuery.parseJSON(result);
6640            var errorLabel = $(self.id +' .ErrorInfo').find("[id*='LabelInfo']");
6641            if (obj.ok === "True" || obj.ok === "true") {
6642                if (accept) {
6643                    if (obj.confirmMail === "True") {
6644                        self.langService.getValue('NEWS_SUBSCRIPTION', 'EdmMailSubscribeValidationSendt').then(function (value) {
6645                            errorLabel.text(value);
6646                        });
6647                    } else {
6648                        self.langService.getValue('NEWS_SUBSCRIPTION', 'EmailSubscribe').then(function (value) {
6649                            errorLabel.text(value);
6650                        });
6651                    }
6652                    PubSub.publish(mcWeb.EdmRegistration.events.onEdmRegistrationSuccess, { isSuccess: true, parentDomId: self.id});
6653                } else {
6654                    if (obj.foundAddress === 'true' || obj.foundAddress === 'True') {
6655                        if (obj.confirmMail === "True") {
6656                            self.langService.getValue('NEWS_SUBSCRIPTION', 'EdmMailUnubscribeValidationSendt').then(function (value) {
6657                                errorLabel.text(value);
6658                            });
6659                        } else {
6660                            self.langService.getValue('NEWS_SUBSCRIPTION', 'EmailCancel').then(function (value) {
6661                                errorLabel.text(value);
6662                            });
6663                        }
6664                        
6665                    } else {
6666                        self.langService.getValue('NEWS_SUBSCRIPTION', 'EmailNotFound').then(function (value) {
6667                            errorLabel.text(value);
6668                        });
6669                    }
6670
6671                }
6672            } else {
6673                if (obj.confirmMail === "True") {
6674                    self.langService.getValue('NEWS_SUBSCRIPTION', 'EdmMailSubscriptionError').then(function (value) {
6675                        errorLabel.text(value);
6676                    });
6677                } else {
6678                    if (accept) {
6679                        self.langService.getValue('NEWS_SUBSCRIPTION', 'EmailFailedToSubscribe').then(function (value) {
6680                            errorLabel.text(value);
6681                        });
6682                    } else {
6683                        self.langService.getValue('NEWS_SUBSCRIPTION', 'EmailFailedToCancel').then(function (value) {
6684                            errorLabel.text(value);
6685                        });
6686                    }
6687                }
6688            }
6689
6690            if (obj.ok === "False" && obj.foundAddress === "False") {
6691                self.langService.getValue('NEWS_SUBSCRIPTION', 'EmailNotValid').then(function (value) {
6692                    errorLabel.text(value);
6693                });
6694            }
6695        };
6696        this.RegisterEmail = function(email, unregister) {
6697            self.isRegistering = !unregister;
6698            self.service.GetAction("RegisterEmail", { email: email, unregister: unregister }).then(function(result) {
6699                //var res = result.substring(1, result.length - 1);
6700                self.ShowEmailRegresult(self.isRegistering,result);
6701            });
6702        };
6703
6704    };
6705})(jQuery);
6706
6707
6708;
6709var mc = (mc || {});
6710
6711//Shortcuts...
6712mc.s = new (function ($) {
6713    'use strict';
6714    var self = this;
6715
6716    //Add to cart
6717    self.buy = function (sender, plid, qua) {
6718        mcWeb.productlist.buy.buy(sender, plid, qua);
6719    };
6720
6721    self.buyNordea = function (sender, plid, qua) {
6722        mcWeb.productlist.buy.buyNordea(sender, plid, qua);
6723    };
6724
6725    //Add to cart, get Quantity from input tag: #qu12345
6726    self.buy_l = function (sender, plid) {
6727        mcWeb.productlist.buy.buy(sender, plid, self.buy_l_min($('#qu' + plid)), false);
6728    };
6729
6730    self.buy_l_min = function (quantityElement) {
6731        var min_quantity = quantityElement.val();
6732        if (min_quantity <= 0 && quantityElement.data("min") >0) {
6733            min_quantity = quantityElement.data("min");
6734        }
6735        return min_quantity;
6736    };
6737
6738    self.buy_l_qua = function (sender, plid, qua) {
6739        var min_quantity = self.buy_l_min($('#qu' + plid));
6740        var checkQuantity = min_quantity.replace(",", ".");
6741        var quantity = (checkQuantity > 0) ? min_quantity : qua;
6742        mcWeb.productlist.buy.buy(sender, plid, quantity, false);
6743    }
6744
6745    self.buy_all = function (sender, selector, allowRedirect) {
6746        mcWeb.productlist.buy.buyAll(sender, selector, allowRedirect);
6747    };
6748
6749    //Change Quantity input
6750    self.qu = function (sender) {
6751        var el = $(sender);
6752        mcWeb.productlist.qt.change(sender, el.data("plid"), el.data("min"), el.data('inc'), el.data("max"), el.data("des"));
6753    };
6754
6755    self.qsu = function (sender) {
6756        var el = $(sender);
6757        mcWeb.productlist.qt.change(sender, el.data("plid"), el.data("min"), el.data('inc'), el.data("max"), el.data("des"));
6758        mcWeb.productVariantMatrix.updateQuantitySum(el);
6759    };
6760
6761    self.qu_key = function (sender, e) {
6762        var key = (typeof e.which === "number") ? e.which : e.keyCode;
6763        if (mcWeb.productlist.qt.keyPressed(sender, key) == false) {
6764            e.preventDefault();
6765        }
6766    };
6767    self.qu_minus = function (event, clickedElement) {
6768        if (clickedElement.nextElementSibling !== null)
6769            self.qu_less(null, event, clickedElement.nextElementSibling);
6770    }
6771    self.qu_plus = function (event, clickedElement) {
6772        if (clickedElement.previousElementSibling !== null)
6773            self.qu_more(null, event, clickedElement.previousElementSibling);
6774    }
6775
6776    self.qu_less = function (sender, e, id) {
6777        var qu = $(id)[0];
6778        qu.oldValue = qu.value;
6779        if (mcWeb.productlist.qt.keyPressed(qu, 40) == false) {
6780            e.preventDefault();
6781        }
6782    };
6783    self.qu_more = function (sender, e, id) {
6784        var qu = $(id)[0];
6785        qu.oldValue = qu.value;
6786        if (mcWeb.productlist.qt.keyPressed(qu, 38) == false) {
6787            e.preventDefault();
6788        }
6789    };
6790
6791    //Add to favorite cart
6792    self.fav = function (sender, plid, qua) {
6793        //$(sender).find('.heart-empty').hide();
6794        //$(sender).find('.heart-full').show();
6795        if (mcWeb.productlist.fav.addUsingPopup != undefined)
6796            mcWeb.productlist.fav.addUsingPopup(sender, plid, qua, false, false, false);
6797        else {
6798            $(sender).find('.heart-empty').hide();
6799            $(sender).find('.heart-full').show();
6800            mcWeb.productlist.fav.add(sender, plid, qua);
6801        }
6802    };
6803
6804
6805    //Remove from favorite cart
6806    self.fav_r = function (sender, plid) {
6807        mcWeb.productlist.fav.remove(sender, plid, false, true);
6808    };
6809
6810    //Select all text inn input (sender)
6811    self.selectAll = function (sender) {
6812        sender.setSelectionRange(0, sender.value.length);
6813    }
6814
6815    //On enter key, then blur input 
6816    self.onEnterBlur = function (sender) {
6817        var charCode = (sender.which) ? sender.which : sender.keyCode;
6818        if (charCode == 13) {
6819            document.activeElement.blur();
6820            return false;
6821        }
6822        return true;
6823    };
6824})(jQuery);
6825
6826
6827;
6828mcWeb.currentUser = new function () {
6829    var $ = jQuery;
6830    var self = this;
6831
6832    this.StorageService = window.StorageService;
6833
6834    this.service = new WebApiService("Login");
6835
6836    this.doSecuritySofteningLogin = function (email) {
6837        if ((email === undefined || email === null) && self.getHasTriedSecSoftLogin())
6838            return;
6839
6840        self.setHasTriedSecSoftLogin(true);
6841        var username = self.getUser();
6842        if (email !== undefined && email !== null && email.length > 0) {
6843            username = email;
6844        }
6845        var loginData = {
6846            WebBrukerId: username,
6847            AuthenticationGUID: self.getAuthenticationGUID()
6848        };
6849        self.service.PostAction("SecuritySofteningLogin", loginData).then(function (result) {
6850            
6851            if (result.Success) {
6852                if (window.location.href.indexOf('#') >= 0) {
6853                    var newUrl = window.location.href.substr(0, window.location.href.indexOf('#'));
6854                    window.location.href = newUrl;
6855                }
6856                else {
6857                    window.location.reload(true);
6858                }
6859            }
6860        });
6861    };
6862
6863
6864    this.getAuthenticationGUID = function () {
6865        return self.StorageService.localStorage.getItem('authenticatedGuid');
6866    };
6867
6868    this.setHasTriedSecSoftLogin = function (value) {
6869        return self.StorageService.sessionStorage.setItem("hasTriedSecSoftLogin", value);
6870    };
6871
6872    this.getHasTriedSecSoftLogin = function () {
6873        return self.StorageService.sessionStorage.getItem("hasTriedSecSoftLogin");
6874    };
6875
6876    this.getUser = function () {
6877        return self.StorageService.localStorage.getItem('user');
6878    };
6879
6880    this.setUser = function (value) {
6881        if ($("#CurrentUserData").length > 0) {
6882            $("#CurrentUserData").attr("data-WebBrukerID", value);
6883        }
6884    };
6885
6886    this.setAuthenticationGUID = function (value) {
6887        if ($("#CurrentUserData").length > 0) {
6888            $("#CurrentUserData").attr("data-authGUID", value);
6889        }
6890    };
6891
6892};
6893;
6894
6895mcWeb.attributeFilte = new (function ($) {
6896    'use strict';
6897
6898    var self = this;
6899    self.showMoreText = 'none';
6900    self.hideMoreText = 'none';
6901
6902    var showHideFilter = function (nodeId, level, filterContent, levelFilter, body, index) {
6903
6904        //Run once
6905        if (index === 0) {
6906            var result = $('#filteroptions .AttributeBox .selected');
6907            if (result != null && result.length > 0) {
6908                $('.filter-toggle-hide').show();
6909                filterContent.css('display', "");
6910                PubSub.publish("AjaxRenderingEngine.onFilterLoadRequested");//the filter may not have been loaded yet
6911                return true;
6912            }
6913        }
6914
6915        if (nodeId === '*' || body.hasClass("department-id-" + nodeId.trim())) {
6916            var show = parseInt(level) <= levelFilter;
6917            $((show) ? '.filter-toggle-hide' : '.filter-toggle-show').show();
6918            filterContent.css('display', show ? "" : "none");
6919            if (show) {
6920                PubSub.publish("AjaxRenderingEngine.onFilterLoadRequested");//the filter may not have been loaded yet
6921                return true;
6922            }
6923        }
6924        return false; //Department not found
6925    };
6926
6927    self.unhideProductMenu = function () {
6928        var menu = jQuery("div.ProductMenu");
6929        if (menu.length > 0) {
6930            menu.removeClass("hidden");
6931        }
6932    };
6933
6934    var initFilter = function (expandlevel, filterContent, excludeList) {
6935        if (expandlevel.trim().length < 1) {
6936            filterContent.css('display', "");
6937        }
6938
6939        var arrayDepartments = expandlevel.split(';');
6940        
6941        var body = $("body");
6942        var skipLevelCheck = false;
6943
6944        if (excludeList != null) {
6945            for (var y = 0; y < excludeList.length; y++) {
6946                var css = excludeList[y];
6947                if (body.hasClass(css)) {
6948                    skipLevelCheck = true;
6949                    break;
6950                }
6951            }
6952        }
6953        
6954        var cssList = body.attr("class").split(' ');
6955        var levelFilter = skipLevelCheck ? 100 : -1;
6956
6957        if (!skipLevelCheck) {
6958            for (var x = 0; x < cssList.length; x++) {
6959                if (cssList[x].indexOf("body-menu-level-") > -1) {
6960                    levelFilter = parseInt(cssList[x].replace("body-menu-level-", ""));
6961                    break;
6962                }
6963            }
6964        }
6965        
6966        if (levelFilter === -1) {
6967            filterContent.css('display', "");
6968            return;
6969        }
6970
6971        var showFilter = false;
6972        for (var i = 0; i < arrayDepartments.length; i++) {
6973            var item = arrayDepartments[i].split(',');
6974            if (showHideFilter(item[0], item[1], filterContent, levelFilter, body, i)) {
6975                showFilter = true;
6976                break;
6977            }
6978        }
6979
6980        if (showFilter === false) {
6981            $('.filter-toggle-show').show();
6982            self.unhideProductMenu();
6983        }
6984        else {
6985            $('.filter-toggle-show').hide();
6986        }
6987    };
6988
6989    
6990
6991    self.init = function (showFilterToggle, excludeList) {
6992
6993        if (showFilterToggle) {
6994            var filtertoggle = $("#filter-toggle");
6995            var toggleText = $('.filter-toggle-text');
6996            if (filtertoggle.css('display') !== 'none') {
6997
6998                var filterContent = $("#filter-content");
6999
7000                if (jQuery("aside.c-menu #filter-toggle").length > 0 ||
7001                    (jQuery("body.layoutver4").length > 0 &&
7002                        (jQuery("body.device-size-xs").length > 0 
7003                    || jQuery("body.device-size-sm").length > 0
7004                        ))
7005                    ) {
7006
7007                    filtertoggle.hide();
7008                    filterContent.show();
7009                    return;
7010                }
7011
7012                filtertoggle.on('click',
7013                    function () {
7014                        PubSub.publish("AjaxRenderingEngine.onFilterLoadRequested");
7015
7016                        filterContent.slideToggle(200, function () {
7017                            toggleText.toggle();
7018                        });
7019
7020                    });
7021
7022                if(filtertoggle.length > 0)
7023                    initFilter(filtertoggle.data('expandlevel'), filterContent, excludeList);
7024            }
7025        }
7026
7027        var clearFilter = $("[ID*='LBClearFilter']");
7028        if (document.location.href.indexOf('Filter=') >= 0) {
7029            clearFilter.on('click', RemoveFilter);
7030        } else {
7031            clearFilter.attr('disabled', 'disabled');
7032            clearFilter.toggleClass('disabled');
7033        }
7034
7035        var buttons = $("[ID*='LBCloseFilter'], [ID*='LBShowFilter']");
7036        buttons.on('click', function () {
7037            buttons.toggle();
7038            $('#AttributeListBox').slideToggle(200);
7039        });
7040
7041        var toggleAdvancedButton = $("[ID*='LinkButtonShowAllAttributes']");
7042        var listOfAttributes = $('.AttributeHide');
7043        toggleAdvancedButton.on('click', function () {
7044            if (listOfAttributes.is(":visible")) {
7045                toggleAdvancedButton.text(self.showMoreText);
7046            } else {
7047                toggleAdvancedButton.text(self.hideMoreText);
7048            }
7049            listOfAttributes.slideToggle(100);
7050        });
7051
7052        //Show/hide attribute filters depedning on the existence of the Keep parameter.
7053        if (window.location.href.indexOf(keepFilterOpen) >= 0) {
7054            listOfAttributes.slideToggle(100);
7055            if (listOfAttributes.is(":visible")) {
7056                toggleAdvancedButton.text(self.hideMoreText);
7057            } else {
7058                toggleAdvancedButton.text(self.showMoreText);
7059            }
7060        }
7061    };
7062})(jQuery);;
7063var mcWeb = (mcWeb || {});
7064
7065mcWeb.productImageRenderV2 = new function() {
7066	var self = this;
7067	self.load = function() {
7068		var eq = jQuery('.equalize');
7069		if (eq != null)
7070			eq.equalHeights();
7071
7072		var container = jQuery('#MainImgContainer');
7073		var mainImg = jQuery('#MainProdImg');
7074		if (container != null && mainImg != null) {
7075			mainImg.width(container.width());
7076		}
7077	}
7078
7079	self.updateMainImageDimensions = function(e) {
7080		var container = jQuery('#MainImgContainer');
7081		var mainImg = jQuery('#MainProdImg');
7082
7083		self.adjustImageToContainerDimensions(mainImg[0],container[0]);
7084	}
7085
7086	self.updateDimensions = function (e) {
7087		
7088		var mainImg = jQuery(this);
7089		var container = jQuery(mainImg.parentNode);
7090		self.adjustImageToContainerDimensions(mainImg[0], container[0]);
7091	}
7092
7093	/**
7094  * Conserve aspect ratio of the orignal region. Useful when shrinking/enlarging
7095  * images to fit into a certain area.
7096  *
7097  * @param {Number} srcWidth Source area width
7098  * @param {Number} srcHeight Source area height
7099  * @param {Number} maxWidth Fittable area maximum available width
7100  * @param {Number} maxHeight Fittable area maximum available height
7101  * @return {Object} { width, heigth }
7102  */
7103	self.calculateAspectRatioFit = function (srcWidth, srcHeight, maxWidth, maxHeight) {
7104
7105		var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
7106
7107		return { width: srcWidth * ratio, height: srcHeight * ratio };
7108	}
7109
7110	self.adjustImageToContainerDimensions = function (obj, container) {
7111		
7112		var frameHeight = jQuery(container).height();
7113		var frameWidth = jQuery(container).width();
7114
7115		var height = obj.naturalHeight;
7116		var width = obj.naturalWidth;
7117
7118		if (frameHeight == undefined || frameWidth == undefined || height == undefined || width == undefined)
7119			alert('Some data was undefine: frameWidth = ' + frameWidth + '; frameHeight = ' + frameHeight + '; height = ' + height + '; width = ' + width);
7120
7121		var newSize = self.calculateAspectRatioFit(width, height, frameWidth, frameHeight);
7122		jQuery(obj).css("width", newSize.width + "px");
7123		jQuery(obj).css("height", newSize.height + "px");
7124
7125		return;
7126
7127		var aspect = obj.naturalWidth / obj.naturalHeight;
7128		var heightScale = height / frameHeight;
7129		var widthScale = width / frameWidth;
7130
7131		if (height > frameHeight || width > frameWidth) {
7132
7133
7134			if (widthScale > heightScale) {
7135
7136				jQuery(obj).css("width", frameWidth + "px");
7137				jQuery(obj).css("height", "auto");
7138				jQuery(obj.parentNode).css("width", "auto");
7139			} else {
7140				jQuery(obj).css("height", frameHeight + "px");
7141				var newWidth = width / heightScale;
7142				jQuery(obj).css("width", newWidth + "px");
7143
7144			}
7145		}
7146		else if (height < frameHeight && width < frameWidth) {
7147			jQuery(obj).css("width", "auto");
7148		}
7149	}
7150};
7151mcWeb.popupAttributeFilter = new (function($) {
7152    'user strict';
7153    var self = this;
7154
7155    self.clearStoredValueUponInit = false;
7156    var myStoragePrefix = "CData.PopupFilter.";
7157    this.storeAttributeFilter = function(storagePrefix, attribute, attributeValue) {
7158        var myCurrentFilter = JSON.parse(window.StorageService.sessionStorage.getItem(myStoragePrefix+storagePrefix));
7159        if (myCurrentFilter == null || myCurrentFilter == undefined) {
7160            myCurrentFilter = {
7161            };
7162
7163        }
7164        myCurrentFilter[attribute] = attributeValue;
7165
7166        window.StorageService.sessionStorage.setItem(myStoragePrefix+storagePrefix,JSON.stringify( myCurrentFilter));
7167    };
7168
7169    this.loadAttributeFilter = function(storagePrefix,attribute) {
7170        var myCurrentFilter = JSON.parse(window.StorageService.sessionStorage.getItem(myStoragePrefix+storagePrefix));
7171        if (myCurrentFilter != null && myCurrentFilter != undefined) {
7172            var myAttributeValue = myCurrentFilter[attribute];
7173            if (myAttributeValue !== undefined && myAttributeValue !== null) {
7174                return myAttributeValue;
7175            } else return null;
7176        }
7177    };
7178
7179    this.storeDDAttributeValue = function(e) {
7180        var myValue = e.options[e.selectedIndex].value;
7181        var myAttribute = $(e).data("attributeid");
7182        var myModelId = $(e).data("model-id");
7183        self.clearStoredValueUponInit = false;
7184        self.storeAttributeFilter(myModelId, myAttribute, myValue);
7185        PubSub.publish(mcWeb.ajaxRenderEngine.events.onPopupFilterChanged,
7186            { AttributeId: myAttribute, AttributeValue: myValue, Sender: e, FullFilter: JSON.parse(window.StorageService.sessionStorage.getItem(myStoragePrefix+myModelId)) });
7187    };
7188
7189    PubSub.subscribe("AjaxRenderingEngine.onClearFieldFilter",function(data){
7190                self.clearStoredValueUponInit = true;                
7191            }
7192        );
7193
7194    this.initialiseDDAttributeValue = function(e) {
7195        var myAttribute = $(e).data("attributeid");
7196        self.myId = $(e).attr("id");
7197        if (myAttribute !== undefined && myAttribute !== null) {
7198            var myModelId = $(e).data("model-id");
7199            if(! self.clearStoredValueUponInit){//init of filter from model register cannot initialise content from stored filter, so we must clear it now
7200                var storedString = self.loadAttributeFilter(myModelId, myAttribute);
7201                var currentVal = $(e).val();
7202                if (storedString != undefined && storedString !== null && currentVal !== storedString) {
7203                    $(e).val(storedString);//update dropdown
7204
7205                }
7206            }
7207            else{
7208                self.storeAttributeFilter(myModelId, myAttribute, -1);
7209            }
7210        }
7211    };
7212})(jQuery);;
7213mcWeb.ajaxPopup = new (function ($) {
7214   
7215    'use strict';
7216    var self = this;
7217    self.events = {
7218        onFieldShowPopup: "mcWeb.ajaxPopup.onFieldShowPopup_"
7219    };
7220
7221
7222    self.load = function() {
7223        var targetKey = "div.ajax-field.not-loaded[data-popup='7']";
7224        var fieldsToSubscribeTo = $(targetKey);
7225
7226        for (var i = 0; i < fieldsToSubscribeTo.length; i++) {
7227            var current = $(fieldsToSubscribeTo[i]);
7228
7229            var fieldId = jQuery(current).data("field-id");
7230
7231            PubSub.unsubscribe(self.events.onFieldShowPopup + fieldId);
7232            PubSub.subscribe(self.events.onFieldShowPopup + fieldId,
7233                function(message,data) {
7234                    var fieldId = data.FieldId;
7235                    var fieldRecognizer = "div.ajax-field.not-loaded";
7236                    var recognizer = fieldRecognizer + "[data-field-id='" + fieldId + "']";
7237
7238                    if (data.FieldIds != undefined && data.FieldIds.length > 0) {
7239                        var extraFieldIds = data.FieldIds.split(',');
7240                        for (var i = 0; i < extraFieldIds.length; i++) {
7241                            recognizer += "," + fieldRecognizer + "[data-field-id=" + extraFieldIds[i] + "]";
7242                        }
7243                    }
7244
7245                    var field = jQuery(recognizer);
7246                    jQuery(field).data("plid", data.Plid);
7247                    var param = {
7248                        targetKey: recognizer,
7249                        filterTargetKey: "#AttributeListBox",
7250                        onlyUpdateProductList: false,
7251                        doNotRenderFilter: false,
7252                        useDummyData: false,
7253                        popupFilter: 7,
7254                        nextPageNumber: 0
7255                    };
7256                   mcWeb.ajaxRenderEngine.updateFields(param.targetKey,
7257                        param.filterTargetKey,
7258                        param.onlyUpdateProductList,
7259                        param.doNotRenderFilter,
7260                        param.useDummyData,
7261                        param.popupFilter,
7262                        param.nextPageNumber);
7263                });
7264        }
7265    };
7266
7267    self.openFieldPopup = function(plid,caller) {
7268        //check if the given field is found, if not, we probably havent specified the fields correctly in the template. 
7269        //if we find the field for variant-listing for a popup, then we can use that
7270
7271        var opensFromCenter = jQuery(caller).parents("#center-popup").length > 0;
7272
7273        if (opensFromCenter) {
7274            PubSub.publish("mcWeb.slideOverBox.onHideLightbox");
7275        }
7276        else {
7277            PubSub.publish("mcWeb.lightBox.onHideLightbox");
7278        }
7279
7280        var fields = jQuery("div.ajax-field.not-loaded[data-popup=7][data-area-id='PopupProductAndDepartmentPageAllProducts']");
7281        var fieldId =0;
7282        var fieldIds = [];
7283        if(fields.length > 0){
7284            fieldId = jQuery(fields[0]).data("field-id");
7285            for(var i = 1; i < fields.length; i++){
7286                var id = jQuery(fields[i]).data("field-id");
7287                fieldIds.push(id);
7288            }
7289
7290            PubSub.publish(self.events.onFieldShowPopup + fieldId, {FieldId: fieldId, FieldIds: fieldIds, Plid: plid});
7291        }
7292        else{
7293            fields = jQuery("div.ajax-field.not-loaded[data-popup=7][data-listing-type=59]");
7294            if(fields.length > 0){
7295                fieldId = jQuery(fields[0]).data("field-id");
7296                 for(var i = 1; i < fields.length; i++){
7297                    var id = jQuery(fields[i]).data("field-id");
7298                    fieldIds.push(id);
7299                }
7300                PubSub.publish(self.events.onFieldShowPopup + fieldId, {FieldId: fieldId, FieldIds: fieldIds, Plid: plid});
7301            }
7302        }
7303    }
7304})(jQuery);;
7305mcWeb.slideOverBox = new function () {
7306    var $ = jQuery;
7307    var self = this;
7308
7309    self.service = new WebApiService("SlideOverBox","/api-ro-session");//only use a readonly session
7310
7311    self.events = {
7312        onShowSpinicon: "mcWeb.slideOverBox.onShowSpinicon",
7313        onHideSpinicon: "mcWeb.slideOverBox.onHideSpinicon",
7314        onShowLightbox: "mcWeb.slideOverBox.onShowLightbox",
7315        onHideLightbox: "mcWeb.slideOverBox.onHideLightbox",
7316        onMinimizeLightbox:"mcWeb.slideOverBox.onMinimizeLightbox",
7317        onMaximizeLightbox:"mcWeb.slideOverBox.onMaximizeLightbox",
7318        modifyOptions: "mcWeb.slideOverBox.modifyOptions"
7319    }
7320
7321    var onClickCancelReigstration = false;
7322    self.load = function() {
7323        var slideOverBox = $("#rhs-popup");
7324        if (slideOverBox == undefined || slideOverBox == null || slideOverBox.length == 0) {
7325            self.loadSlideOverBox();
7326        }
7327    };
7328    self.loadSlideOverBox = function() {
7329        var param = {
7330            Reset: false
7331        };
7332        self.service.PostAction("RenderSlideOverBox", param).then(function(result) {
7333            if (result != null && result.Success) {
7334                var target = jQuery("#rhs-popup-sidebar");
7335                if (target.length > 0) {
7336                    $(target).hide();//ensure the container is hidden when we load the "lightbox"
7337                    target.html(result.Response);
7338                }
7339            }
7340        });
7341    };
7342    self.init = function () {
7343        self.load();
7344        var popupCss = null;
7345        PubSub.subscribe(mcWeb.slideOverBox.events.onShowLightbox, function (message, options) {
7346            var popup = $('#rhs-popup');
7347            var hasOptions = !!options;
7348           
7349            var closeButton = popup.find('.lightbox-close');
7350            var target = jQuery("#rhs-popup-sidebar");
7351            target.show();//show the div around the "lightbox" in case  it is still hidden 
7352            
7353            popup.removeClass("shrinking-box");
7354            if (popup.width() > 0 && popup.width() < 50) {
7355                var popupWidth = popup.css("width");
7356                if (popupWidth != "") {                    
7357                    jQuery(popup).animateAuto("width",null,"", 400);
7358                }
7359                self.setCloseButtonEvent(closeButton, true);
7360            }
7361            if (hasOptions && options.keyboard === false)
7362                closeButton.hide();
7363            else
7364                closeButton.show();
7365
7366            if (hasOptions){
7367                if(options.css != null) {
7368                    popupCss = options.css;
7369                    popup.addClass(popupCss);
7370                }
7371            }
7372            
7373
7374            if (!popup.is(':visible')) {
7375                setTimeout(function () {
7376                   //popup.show();
7377                    
7378                    popup.animate({ width: "toggle" }, 200);
7379                    PubSub.publish(mcWeb.slideOverBox.events.onHideSpinicon);
7380                    setTimeout(function(){ 
7381                        //used to get RoyalSlider (re)started, but only after the slideover is finished
7382                        if(options.callback !== undefined){
7383                            options.callback();
7384                        }
7385                    },210);
7386
7387                }, 300); //Change from 1 to 300 (bug fix JQM)
7388            } else if (!hasOptions) {
7389                // Reset options to default
7390                var modal = popup.data('bs.modal');
7391                modal.options.backdrop = true;
7392                modal.options.keyboard = true;
7393            }
7394            else{//used to get RoyalSlider (re)started
7395                  if(options.callback !== undefined){
7396                    options.callback();
7397                }
7398            }
7399        });
7400
7401        PubSub.subscribe(mcWeb.slideOverBox.events.onHideLightbox, function () {
7402            var popup = $('#rhs-popup');
7403            if (popupCss != null) {
7404                popup.removeClass(popupCss);
7405                popupCss = null;
7406            }
7407
7408            if (popup.is(':visible')) {
7409                popup.modal('hide');
7410                popup.hide();
7411
7412                PubSub.publish(mcWeb.slideOverBox.events.onHideSpinicon);
7413            }
7414            self.movePopupFieldsToOriginalPlaceholder(popup);
7415        });
7416
7417        PubSub.subscribe(mcWeb.slideOverBox.events.onMinimizeLightbox, function () {
7418            var popup = $('#rhs-popup');
7419            if (popupCss != null) {
7420                popup.removeClass(popupCss);
7421                popupCss = null;
7422            }
7423
7424            if (popup.is(':visible')) {
7425                popup.addClass("shrinking-box");
7426
7427                var closeButton = popup.find('.lightbox-close');
7428                closeButton.removeClass("lightbox-close");
7429                closeButton.addClass("lightbox-open");
7430
7431                jQuery(popup).animate({ width: '25', right: '0' }, 400, 'swing');
7432
7433                self.setCloseButtonEvent(closeButton, false);
7434
7435                PubSub.publish(mcWeb.slideOverBox.events.onHideSpinicon);
7436            }
7437
7438        });
7439
7440        PubSub.subscribe(mcWeb.slideOverBox.events.onMaximizeLightbox, function () {
7441            var popup = $('#rhs-popup');
7442            if (popupCss != null) {
7443                popup.removeClass(popupCss);
7444                popupCss = null;
7445            }
7446
7447            if (popup.is(':visible')) {
7448                popup.removeClass("shrinking-box");
7449
7450                var closeButton = popup.find('.lightbox-open');
7451                closeButton.addClass("lightbox-close");
7452                closeButton.removeClass("lightbox-open");
7453
7454                if (popup.width() > 0 && popup.width() < 50) {
7455                    var popupWidth = popup.css("width");
7456                    if (popupWidth != "") {                    
7457                        jQuery(popup).animateAuto("width",null,"", 400);
7458                    }
7459                }
7460                
7461
7462                PubSub.publish(mcWeb.slideOverBox.events.onHideSpinicon);
7463            }
7464
7465        });
7466
7467
7468
7469        
7470
7471        PubSub.subscribe(mcWeb.slideOverBox.events.onShowSpinicon, function () {
7472            $('.center-placeholder').addClass('refresh-data');
7473            $('#rhs-refresh-center').show();
7474        });
7475
7476        PubSub.subscribe(mcWeb.slideOverBox.events.onHideSpinicon, function () {
7477            $('.center-placeholder').removeClass('refresh-data');
7478            $('#rhs-refresh-center').hide();
7479        });
7480
7481        PubSub.subscribe(mcWeb.slideOverBox.events.modifyOptions, function (message, options) {
7482            var popup = $('#rhs-popup');
7483
7484            // Check if the modal is open
7485            if (!(popup.data('bs.modal') || {}).isShown)
7486                return;
7487
7488            var modal = popup.data('bs.modal');
7489
7490            if (options.backdrop) {
7491                if (options.backdrop === 'static')
7492                    modal.options.backdrop = 'static';
7493
7494                if (options.backdrop === true)
7495                    modal.options.backdrop = true;
7496
7497                if (options.backdrop === false)
7498                    modal.options.backdrop = false;
7499            }
7500
7501            if (options.keyboard) {
7502                if (options.keyboard === true)
7503                    modal.options.keyboard = true;
7504
7505                if (options.keyboard === false)
7506                    modal.options.keyboard = false;
7507            }
7508        });
7509
7510        // Reposition when a modal is shown
7511        $('#rhs-popup').on('show.bs.modal', function () {
7512            $('#rhs-popup').each(self.centerLighBox);
7513        });
7514
7515        $('#rhs-popup').on('hide.bs.modal', function () {
7516            if (popupCss != null) {
7517                $(this).removeClass(popupCss);
7518                popupCss = null;
7519            }
7520            
7521        });
7522        
7523    };
7524
7525     self.movePopupFieldsToOriginalPlaceholder = function(popup){
7526         //move all fields back to original positions
7527            var fields = popup.find(".web-pub-field").each(function(index, item){
7528                var clientId = item.id;
7529                var $item = $(item);
7530                //remove content from item before moving it back. It will be filled again when we need it. 
7531                //we just needed in its original location to preserve sortorder and avoid duplication in the DOM
7532                var placeholder = $("div[data-placeholder-id='"+clientId + "']");
7533                var content = $item.find(".ajax-field");
7534                if(content.length > 0){
7535                    content.empty();
7536                }
7537                var detachedItem = $item.detach();
7538                placeholder.after(detachedItem);
7539                placeholder.detach();//
7540            });
7541    };
7542
7543    self.setCloseButtonEvent = function(mybutton, close) {
7544        if (close) {
7545            mybutton.click(function() {
7546                PubSub.publish(mcWeb.slideOverBox.events.onMinimizeLightbox);
7547            });
7548        }
7549        else {
7550            mybutton.click(function() {
7551                PubSub.publish(mcWeb.slideOverBox.events.onMaximizeLightbox);
7552            });
7553        }
7554    };
7555
7556    $(function () {
7557        self.init();
7558    });
7559};
7560
7561jQuery.fn.animateAuto = function(prop,heightSize, widthSize, speed, callback){
7562    var elem, height, width;
7563    return this.each(function(i, el) {
7564        if (heightSize == null || heightSize == undefined)
7565            heightSize = "auto";
7566        if (widthSize == null || widthSize == undefined)
7567            widthSize = "auto";
7568
7569        el = jQuery(el), elem = el.clone().css({"height":heightSize,"width":widthSize}).appendTo("body");
7570        height = elem.css("height"),
7571            width = elem.css("width"),
7572            elem.remove();
7573        
7574        if(prop === "height")
7575            el.animate({"height":height}, speed, callback);
7576        else if(prop === "width")
7577            el.animate({"width":width}, speed, callback);  
7578        else if(prop === "both")
7579            el.animate({"width":width,"height":height}, speed, callback);
7580    });  
7581};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.