window.googleMapsScriptLoaded=function(){$(window).trigger('googleMapsScriptLoaded');};;(function($,window,document,undefined){'use strict';var $window=$(window),$body=$('body'),windowHeight=$window.height(),windowScrollTop=0,debounce=function(delay,fn){var timer=null;return function(){var context=this,args=arguments;clearTimeout(timer);timer=setTimeout(function(){fn.apply(context,args);},delay);};},throttle=function(delay,fn){var last,deferTimer;return function(){var context=this,args=arguments,now=+new Date;if(last&&now<last+delay){clearTimeout(deferTimer);deferTimer=setTimeout(function(){last=now;fn.apply(context,args);},delay);}
else{last=now;fn.apply(context,args);}};},apiScriptLoaded=false,apiScriptLoading=false,$containers=$([]),init=function(callback){windowScrollTop=$window.scrollTop();$containers.each(function(){var $this=$(this),thisOptions=$this.data('options');if($this.offset().top-windowScrollTop>windowHeight*2)
return true;if(!apiScriptLoaded&&!apiScriptLoading){$body.append('<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&callback=googleMapsScriptLoaded'+(thisOptions.api_key?('&key='+thisOptions.api_key):'')+'"></script>');apiScriptLoading=true;}
if(!apiScriptLoaded)return true;var map=new google.maps.Map(this,{zoom:15});if(thisOptions.callback!==false)
thisOptions.callback(this,map);$containers=$containers.not($this);});};$window.on('googleMapsScriptLoaded',function(){apiScriptLoaded=true;init();}).on('scroll',throttle(500,init)).on('resize',debounce(1000,function(){windowHeight=$window.height();init();}));$.fn.lazyLoadGoogleMaps=function(options){options=$.extend({api_key:false,callback:false,},options);this.each(function(){var $this=$(this);$this.data('options',options);$containers=$containers.add($this);});init();this.debounce=debounce;this.throttle=throttle;return this;};})(jQuery,window,document);!function(t,e){"function"==typeof define&&define.amd?define([],e(t)):"object"==typeof exports?module.exports=e(t):t.iziToast=e(t)}("undefined"!=typeof global?global:window||this.window||this.global,function(t){"use strict";var e={},n="iziToast",o=(document.querySelector("body"),!!/Mobi/.test(navigator.userAgent)),i=/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor),s="undefined"!=typeof InstallTrigger,a="ontouchstart"in document.documentElement,r=["bottomRight","bottomLeft","bottomCenter","topRight","topLeft","topCenter","center"],l={info:{color:"blue",icon:"ico-info"},success:{color:"green",icon:"ico-success"},warning:{color:"orange",icon:"ico-warning"},error:{color:"red",icon:"ico-error"},question:{color:"yellow",icon:"ico-question"}},d=568,c={};e.children={};var u={id:null,"class":"",title:"",titleColor:"",titleSize:"",titleLineHeight:"",message:"",messageColor:"",messageSize:"",messageLineHeight:"",backgroundColor:"",theme:"light",color:"",icon:"",iconText:"",iconColor:"",iconUrl:null,image:"",imageWidth:50,maxWidth:null,zindex:null,layout:1,balloon:!1,close:!0,closeOnEscape:!1,closeOnClick:!1,displayMode:0,position:"bottomRight",target:"",targetFirst:!0,timeout:5e3,rtl:!1,animateInside:!0,drag:!0,pauseOnHover:!0,resetOnHover:!1,progressBar:!0,progressBarColor:"",progressBarEasing:"linear",overlay:!1,overlayClose:!1,overlayColor:"rgba(0, 0, 0, 0.6)",transitionIn:"fadeInUp",transitionOut:"fadeOut",transitionInMobile:"fadeInUp",transitionOutMobile:"fadeOutDown",buttons:{},inputs:{},onOpening:function(){},onOpened:function(){},onClosing:function(){},onClosed:function(){}};if("remove"in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)}),"function"!=typeof window.CustomEvent){var p=function(t,e){e=e||{bubbles:!1,cancelable:!1,detail:void 0};var n=document.createEvent("CustomEvent");return n.initCustomEvent(t,e.bubbles,e.cancelable,e.detail),n};p.prototype=window.Event.prototype,window.CustomEvent=p}var m=function(t,e,n){if("[object Object]"===Object.prototype.toString.call(t))for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.call(n,t[o],o,t);else if(t)for(var i=0,s=t.length;s>i;i++)e.call(n,t[i],i,t)},g=function(t,e){var n={};return m(t,function(e,o){n[o]=t[o]}),m(e,function(t,o){n[o]=e[o]}),n},f=function(t){var e=document.createDocumentFragment(),n=document.createElement("div");for(n.innerHTML=t;n.firstChild;)e.appendChild(n.firstChild);return e},v=function(t){var e=btoa(encodeURIComponent(t));return e.replace(/=/g,"")},y=function(t){return "#"==t.substring(0,1)||"rgb"==t.substring(0,3)||"hsl"==t.substring(0,3)},h=function(t){try{return btoa(atob(t))==t}catch(e){return!1}},b=function(){return{move:function(t,e,o,a){var r,l=.3,d=180;0!==a&&(t.classList.add(n+"-dragged"),t.style.transform="translateX("+a+"px)",a>0?(r=(d-a)/d,l>r&&e.hide(g(o,{transitionOut:"fadeOutRight",transitionOutMobile:"fadeOutRight"}),t,"drag")):(r=(d+a)/d,l>r&&e.hide(g(o,{transitionOut:"fadeOutLeft",transitionOutMobile:"fadeOutLeft"}),t,"drag")),t.style.opacity=r,l>r&&((i||s)&&(t.style.left=a+"px"),t.parentNode.style.opacity=l,this.stopMoving(t,null)))},startMoving:function(t,e,n,o){o=o||window.event;var i=a?o.touches[0].clientX:o.clientX,s=t.style.transform.replace("px)","");s=s.replace("translateX(","");var r=i-s;n.transitionIn&&t.classList.remove(n.transitionIn),n.transitionInMobile&&t.classList.remove(n.transitionInMobile),t.style.transition="",a?document.ontouchmove=function(o){o.preventDefault(),o=o||window.event;var i=o.touches[0].clientX,s=i-r;b.move(t,e,n,s)}:document.onmousemove=function(o){o.preventDefault(),o=o||window.event;var i=o.clientX,s=i-r;b.move(t,e,n,s)}},stopMoving:function(t,e){a?document.ontouchmove=function(){}:document.onmousemove=function(){},t.style.opacity="",t.style.transform="",t.classList.contains(n+"-dragged")&&(t.classList.remove(n+"-dragged"),t.style.transition="transform 0.4s ease, opacity 0.4s ease",setTimeout(function(){t.style.transition=""},400))}}}();return e.setSetting=function(t,n,o){e.children[t][n]=o},e.getSetting=function(t,n){return e.children[t][n]},e.destroy=function(){m(document.querySelectorAll("."+n+"-overlay"),function(t,e){t.remove()}),m(document.querySelectorAll("."+n+"-wrapper"),function(t,e){t.remove()}),m(document.querySelectorAll("."+n),function(t,e){t.remove()}),this.children={},document.removeEventListener(n+"-opened",{},!1),document.removeEventListener(n+"-opening",{},!1),document.removeEventListener(n+"-closing",{},!1),document.removeEventListener(n+"-closed",{},!1),document.removeEventListener("keyup",{},!1),c={}},e.settings=function(t){e.destroy(),c=t,u=g(u,t||{})},m(l,function(t,n){e[n]=function(e){var n=g(c,e||{});n=g(t,n||{}),this.show(n)}}),e.progress=function(t,e,o){var i=this,s=e.getAttribute("data-iziToast-ref"),a=g(this.children[s],t||{}),r=e.querySelector("."+n+"-progressbar div");return{start:function(){"undefined"==typeof a.time.REMAINING&&(e.classList.remove(n+"-reseted"),null!==r&&(r.style.transition="width "+a.timeout+"ms "+a.progressBarEasing,r.style.width="0%"),a.time.START=(new Date).getTime(),a.time.END=a.time.START+a.timeout,a.time.TIMER=setTimeout(function(){clearTimeout(a.time.TIMER),e.classList.contains(n+"-closing")||(i.hide(a,e,"timeout"),"function"==typeof o&&o.apply(i))},a.timeout),i.setSetting(s,"time",a.time))},pause:function(){if("undefined"!=typeof a.time.START&&!e.classList.contains(n+"-paused")&&!e.classList.contains(n+"-reseted")){if(e.classList.add(n+"-paused"),a.time.REMAINING=a.time.END-(new Date).getTime(),clearTimeout(a.time.TIMER),i.setSetting(s,"time",a.time),null!==r){var t=window.getComputedStyle(r),l=t.getPropertyValue("width");r.style.transition="none",r.style.width=l}"function"==typeof o&&setTimeout(function(){o.apply(i)},10)}},resume:function(){"undefined"!=typeof a.time.REMAINING?(e.classList.remove(n+"-paused"),null!==r&&(r.style.transition="width "+a.time.REMAINING+"ms "+a.progressBarEasing,r.style.width="0%"),a.time.END=(new Date).getTime()+a.time.REMAINING,a.time.TIMER=setTimeout(function(){clearTimeout(a.time.TIMER),e.classList.contains(n+"-closing")||(i.hide(a,e,"timeout"),"function"==typeof o&&o.apply(i))},a.time.REMAINING),i.setSetting(s,"time",a.time)):this.start()},reset:function(){clearTimeout(a.time.TIMER),delete a.time.REMAINING,i.setSetting(s,"time",a.time),e.classList.add(n+"-reseted"),e.classList.remove(n+"-paused"),null!==r&&(r.style.transition="none",r.style.width="100%"),"function"==typeof o&&setTimeout(function(){o.apply(i)},10)}}},e.hide=function(t,e,i){"object"!=typeof e&&(e=document.querySelector(e));var s=this,a=g(this.children[e.getAttribute("data-iziToast-ref")],t||{});a.closedBy=i||null,delete a.time.REMAINING,e.classList.add(n+"-closing"),function(){var t=document.querySelector("."+n+"-overlay");if(null!==t){var e=t.getAttribute("data-iziToast-ref");e=e.split(",");var o=e.indexOf(String(a.ref));-1!==o&&e.splice(o,1),t.setAttribute("data-iziToast-ref",e.join()),0===e.length&&(t.classList.remove("fadeIn"),t.classList.add("fadeOut"),setTimeout(function(){t.remove()},700))}}(),a.transitionIn&&e.classList.remove(a.transitionIn),a.transitionInMobile&&e.classList.remove(a.transitionInMobile),o||window.innerWidth<=d?a.transitionOutMobile&&e.classList.add(a.transitionOutMobile):a.transitionOut&&e.classList.add(a.transitionOut);var r=e.parentNode.offsetHeight;e.parentNode.style.height=r+"px",e.style.pointerEvents="none",(!o||window.innerWidth>d)&&(e.parentNode.style.transitionDelay="0.2s");try{var l=new CustomEvent(n+"-closing",{detail:a,bubbles:!0,cancelable:!0});document.dispatchEvent(l)}catch(c){console.warn(c)}setTimeout(function(){e.parentNode.style.height="0px",e.parentNode.style.overflow="",setTimeout(function(){delete s.children[a.ref],e.parentNode.remove();try{var t=new CustomEvent(n+"-closed",{detail:a,bubbles:!0,cancelable:!0});document.dispatchEvent(t)}catch(o){console.warn(o)}"undefined"!=typeof a.onClosed&&a.onClosed.apply(null,[a,e,i])},1e3)},200),"undefined"!=typeof a.onClosing&&a.onClosing.apply(null,[a,e,i])},e.show=function(t){var i=this,s=g(c,t||{});if(s=g(u,s),s.time={},null===s.id&&(s.id=v(s.title+s.message+s.color)),1===s.displayMode||"once"==s.displayMode)try{if(document.querySelectorAll("."+n+"#"+s.id).length>0)return!1}catch(l){console.warn("["+n+"] Could not find an element with this selector: #"+s.id+". Try to set an valid id.")}if(2===s.displayMode||"replace"==s.displayMode)try{m(document.querySelectorAll("."+n+"#"+s.id),function(t,e){i.hide(s,t,"replaced")})}catch(l){console.warn("["+n+"] Could not find an element with this selector: #"+s.id+". Try to set an valid id.")}s.ref=(new Date).getTime()+Math.floor(1e7*Math.random()+1),e.children[s.ref]=s;var p={body:document.querySelector("body"),overlay:document.createElement("div"),toast:document.createElement("div"),toastBody:document.createElement("div"),toastTexts:document.createElement("div"),toastCapsule:document.createElement("div"),cover:document.createElement("div"),buttons:document.createElement("div"),inputs:document.createElement("div"),icon:s.iconUrl?document.createElement("img"):document.createElement("i"),wrapper:null};p.toast.setAttribute("data-iziToast-ref",s.ref),p.toast.appendChild(p.toastBody),p.toastCapsule.appendChild(p.toast),function(){if(p.toast.classList.add(n),p.toast.classList.add(n+"-opening"),p.toastCapsule.classList.add(n+"-capsule"),p.toastBody.classList.add(n+"-body"),p.toastTexts.classList.add(n+"-texts"),o||window.innerWidth<=d?s.transitionInMobile&&p.toast.classList.add(s.transitionInMobile):s.transitionIn&&p.toast.classList.add(s.transitionIn),s["class"]){var t=s["class"].split(" ");m(t,function(t,e){p.toast.classList.add(t)})}s.id&&(p.toast.id=s.id),s.rtl&&(p.toast.classList.add(n+"-rtl"),p.toast.setAttribute("dir","rtl")),s.layout>1&&p.toast.classList.add(n+"-layout"+s.layout),s.balloon&&p.toast.classList.add(n+"-balloon"),s.maxWidth&&(isNaN(s.maxWidth)?p.toast.style.maxWidth=s.maxWidth:p.toast.style.maxWidth=s.maxWidth+"px"),""===s.theme&&"light"===s.theme||p.toast.classList.add(n+"-theme-"+s.theme),s.color&&(y(s.color)?p.toast.style.background=s.color:p.toast.classList.add(n+"-color-"+s.color)),s.backgroundColor&&(p.toast.style.background=s.backgroundColor,s.balloon&&(p.toast.style.borderColor=s.backgroundColor))}(),function(){s.image&&(p.cover.classList.add(n+"-cover"),p.cover.style.width=s.imageWidth+"px",h(s.image.replace(/ /g,""))?p.cover.style.backgroundImage="url(data:image/png;base64,"+s.image.replace(/ /g,"")+")":p.cover.style.backgroundImage="url("+s.image+")",s.rtl?p.toastBody.style.marginRight=s.imageWidth+10+"px":p.toastBody.style.marginLeft=s.imageWidth+10+"px",p.toast.appendChild(p.cover))}(),function(){s.close?(p.buttonClose=document.createElement("button"),p.buttonClose.type="button",p.buttonClose.classList.add(n+"-close"),p.buttonClose.addEventListener("click",function(t){t.target;i.hide(s,p.toast,"button")}),p.toast.appendChild(p.buttonClose)):s.rtl?p.toast.style.paddingLeft="18px":p.toast.style.paddingRight="18px"}(),function(){s.progressBar&&(p.progressBar=document.createElement("div"),p.progressBarDiv=document.createElement("div"),p.progressBar.classList.add(n+"-progressbar"),p.progressBarDiv.style.background=s.progressBarColor,p.progressBar.appendChild(p.progressBarDiv),p.toast.appendChild(p.progressBar)),s.timeout&&(s.pauseOnHover&&!s.resetOnHover&&(p.toast.addEventListener("mouseenter",function(t){i.progress(s,p.toast).pause()}),p.toast.addEventListener("mouseleave",function(t){i.progress(s,p.toast).resume()})),s.resetOnHover&&(p.toast.addEventListener("mouseenter",function(t){i.progress(s,p.toast).reset()}),p.toast.addEventListener("mouseleave",function(t){i.progress(s,p.toast).start()})))}(),function(){s.iconUrl?(p.icon.setAttribute("class",n+"-icon"),p.icon.setAttribute("src",s.iconUrl)):s.icon&&(p.icon.setAttribute("class",n+"-icon "+s.icon),s.iconText&&p.icon.appendChild(document.createTextNode(s.iconText)),s.iconColor&&(p.icon.style.color=s.iconColor)),(s.icon||s.iconUrl)&&(s.rtl?p.toastBody.style.paddingRight="33px":p.toastBody.style.paddingLeft="33px",p.toastBody.appendChild(p.icon))}(),function(){s.title.length>0&&(p.strong=document.createElement("strong"),p.strong.classList.add(n+"-title"),p.strong.appendChild(f(s.title)),p.toastTexts.appendChild(p.strong),s.titleColor&&(p.strong.style.color=s.titleColor),s.titleSize&&(isNaN(s.titleSize)?p.strong.style.fontSize=s.titleSize:p.strong.style.fontSize=s.titleSize+"px"),s.titleLineHeight&&(isNaN(s.titleSize)?p.strong.style.lineHeight=s.titleLineHeight:p.strong.style.lineHeight=s.titleLineHeight+"px")),s.message.length>0&&(p.p=document.createElement("p"),p.p.classList.add(n+"-message"),p.p.appendChild(f(s.message)),p.toastTexts.appendChild(p.p),s.messageColor&&(p.p.style.color=s.messageColor),s.messageSize&&(isNaN(s.titleSize)?p.p.style.fontSize=s.messageSize:p.p.style.fontSize=s.messageSize+"px"),s.messageLineHeight&&(isNaN(s.titleSize)?p.p.style.lineHeight=s.messageLineHeight:p.p.style.lineHeight=s.messageLineHeight+"px")),s.title.length>0&&s.message.length>0&&(s.rtl?p.strong.style.marginLeft="10px":2===s.layout||s.rtl||(p.strong.style.marginRight="10px"))}(),p.toastBody.appendChild(p.toastTexts);var L;!function(){s.inputs.length>0&&(p.inputs.classList.add(n+"-inputs"),m(s.inputs,function(t,e){p.inputs.appendChild(f(t[0])),L=p.inputs.childNodes,L[e].classList.add(n+"-inputs-child"),t[3]&&setTimeout(function(){L[e].focus()},300),L[e].addEventListener(t[1],function(e){var n=t[2];return n(i,p.toast,this,e)})}),p.toastBody.appendChild(p.inputs))}(),function(){s.buttons.length>0&&(p.buttons.classList.add(n+"-buttons"),m(s.buttons,function(t,e){p.buttons.appendChild(f(t[0]));var o=p.buttons.childNodes;o[e].classList.add(n+"-buttons-child"),t[2]&&setTimeout(function(){o[e].focus()},300),o[e].addEventListener("click",function(e){e.preventDefault();var n=t[1];return n(i,p.toast,this,e,L)})})),p.toastBody.appendChild(p.buttons)}(),s.message.length>0&&(s.inputs.length>0||s.buttons.length>0)&&(p.p.style.marginBottom="0"),(s.inputs.length>0||s.buttons.length>0)&&(s.rtl?p.toastTexts.style.marginLeft="10px":p.toastTexts.style.marginRight="10px",s.inputs.length>0&&s.buttons.length>0&&(s.rtl?p.inputs.style.marginLeft="8px":p.inputs.style.marginRight="8px")),function(){p.toastCapsule.style.visibility="hidden",setTimeout(function(){var t=p.toast.offsetHeight,e=p.toast.currentStyle||window.getComputedStyle(p.toast),n=e.marginTop;n=n.split("px"),n=parseInt(n[0]);var o=e.marginBottom;o=o.split("px"),o=parseInt(o[0]),p.toastCapsule.style.visibility="",p.toastCapsule.style.height=t+o+n+"px",setTimeout(function(){p.toastCapsule.style.height="auto",s.target&&(p.toastCapsule.style.overflow="visible")},500),s.timeout&&i.progress(s,p.toast).start()},100)}(),function(){var t=s.position;if(s.target)p.wrapper=document.querySelector(s.target),p.wrapper.classList.add(n+"-target"),s.targetFirst?p.wrapper.insertBefore(p.toastCapsule,p.wrapper.firstChild):p.wrapper.appendChild(p.toastCapsule);else{if(-1==r.indexOf(s.position))return void console.warn("["+n+"] Incorrect position.\nIt can be › "+r);t=o||window.innerWidth<=d?"bottomLeft"==s.position||"bottomRight"==s.position||"bottomCenter"==s.position?n+"-wrapper-bottomCenter":"topLeft"==s.position||"topRight"==s.position||"topCenter"==s.position?n+"-wrapper-topCenter":n+"-wrapper-center":n+"-wrapper-"+t,p.wrapper=document.querySelector("."+n+"-wrapper."+t),p.wrapper||(p.wrapper=document.createElement("div"),p.wrapper.classList.add(n+"-wrapper"),p.wrapper.classList.add(t),document.body.appendChild(p.wrapper)),"topLeft"==s.position||"topCenter"==s.position||"topRight"==s.position?p.wrapper.insertBefore(p.toastCapsule,p.wrapper.firstChild):p.wrapper.appendChild(p.toastCapsule)}isNaN(s.zindex)?console.warn("["+n+"] Invalid zIndex."):p.wrapper.style.zIndex=s.zindex}(),function(){s.overlay&&(null!==document.querySelector("."+n+"-overlay.fadeIn")?(p.overlay=document.querySelector("."+n+"-overlay"),p.overlay.setAttribute("data-iziToast-ref",p.overlay.getAttribute("data-iziToast-ref")+","+s.ref),isNaN(s.zindex)||null===s.zindex||(p.overlay.style.zIndex=s.zindex-1)):(p.overlay.classList.add(n+"-overlay"),p.overlay.classList.add("fadeIn"),p.overlay.style.background=s.overlayColor,p.overlay.setAttribute("data-iziToast-ref",s.ref),isNaN(s.zindex)||null===s.zindex||(p.overlay.style.zIndex=s.zindex-1),document.querySelector("body").appendChild(p.overlay)),s.overlayClose?(p.overlay.removeEventListener("click",{}),p.overlay.addEventListener("click",function(t){i.hide(s,p.toast,"overlay")})):p.overlay.removeEventListener("click",{}))}(),function(){if(s.animateInside){p.toast.classList.add(n+"-animateInside");var t=[200,100,300];"bounceInLeft"!=s.transitionIn&&"bounceInRight"!=s.transitionIn||(t=[400,200,400]),s.title.length>0&&setTimeout(function(){p.strong.classList.add("slideIn")},t[0]),s.message.length>0&&setTimeout(function(){p.p.classList.add("slideIn")},t[1]),(s.icon||s.iconUrl)&&setTimeout(function(){p.icon.classList.add("revealIn")},t[2]);var e=150;s.buttons.length>0&&p.buttons&&setTimeout(function(){m(p.buttons.childNodes,function(t,n){setTimeout(function(){t.classList.add("revealIn")},e),e+=150})},s.inputs.length>0?150:0),s.inputs.length>0&&p.inputs&&(e=150,m(p.inputs.childNodes,function(t,n){setTimeout(function(){t.classList.add("revealIn")},e),e+=150}))}}(),s.onOpening.apply(null,[s,p.toast]);try{var C=new CustomEvent(n+"-opening",{detail:s,bubbles:!0,cancelable:!0});document.dispatchEvent(C)}catch(w){console.warn(w)}setTimeout(function(){p.toast.classList.remove(n+"-opening"),p.toast.classList.add(n+"-opened");try{var t=new CustomEvent(n+"-opened",{detail:s,bubbles:!0,cancelable:!0});document.dispatchEvent(t)}catch(e){console.warn(e)}s.onOpened.apply(null,[s,p.toast])},1e3),s.drag&&(a?(p.toast.addEventListener("touchstart",function(t){b.startMoving(this,i,s,t)},!1),p.toast.addEventListener("touchend",function(t){b.stopMoving(this,t)},!1)):(p.toast.addEventListener("mousedown",function(t){t.preventDefault(),b.startMoving(this,i,s,t)},!1),p.toast.addEventListener("mouseup",function(t){t.preventDefault(),b.stopMoving(this,t)},!1))),s.closeOnEscape&&document.addEventListener("keyup",function(t){t=t||window.event,27==t.keyCode&&i.hide(s,p.toast,"esc")}),s.closeOnClick&&p.toast.addEventListener("click",function(t){i.hide(s,p.toast,"toast")}),i.toast=p.toast},e});!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.moment=t()}(this,function(){"use strict";function e(){return Qe.apply(null,arguments)}function t(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function n(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function s(e){return void 0===e}function i(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function r(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function a(e,t){var n,s=[];for(n=0;n<e.length;++n)s.push(t(e[n],n));return s}function o(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function u(e,t){for(var n in t)o(t,n)&&(e[n]=t[n]);return o(t,"toString")&&(e.toString=t.toString),o(t,"valueOf")&&(e.valueOf=t.valueOf),e}function l(e,t,n,s){return ge(e,t,n,s,!0).utc()}function d(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function h(e){if(null==e._isValid){var t=d(e),n=Xe.call(t.parsedDateParts,function(e){return null!=e}),s=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n);if(e._strict&&(s=s&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return s;e._isValid=s}return e._isValid}function c(e){var t=l(NaN);return null!=e?u(d(t),e):d(t).userInvalidated=!0,t}function f(e,t){var n,i,r;if(s(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),s(t._i)||(e._i=t._i),s(t._f)||(e._f=t._f),s(t._l)||(e._l=t._l),s(t._strict)||(e._strict=t._strict),s(t._tzm)||(e._tzm=t._tzm),s(t._isUTC)||(e._isUTC=t._isUTC),s(t._offset)||(e._offset=t._offset),s(t._pf)||(e._pf=d(t)),s(t._locale)||(e._locale=t._locale),Ke.length>0)for(n=0;n<Ke.length;n++)s(r=t[i=Ke[n]])||(e[i]=r);return e}function m(t){f(this,t),this._d=new Date(null!=t._d?t._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===et&&(et=!0,e.updateOffset(this),et=!1)}function _(e){return e instanceof m||null!=e&&null!=e._isAMomentObject}function y(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function g(e){var t=+e,n=0;return 0!==t&&isFinite(t)&&(n=y(t)),n}function p(e,t,n){var s,i=Math.min(e.length,t.length),r=Math.abs(e.length-t.length),a=0;for(s=0;s<i;s++)(n&&e[s]!==t[s]||!n&&g(e[s])!==g(t[s]))&&a++;return a+r}function w(t){!1===e.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+t)}function v(t,n){var s=!0;return u(function(){if(null!=e.deprecationHandler&&e.deprecationHandler(null,t),s){for(var i,r=[],a=0;a<arguments.length;a++){if(i="","object"==typeof arguments[a]){i+="\n["+a+"] ";for(var o in arguments[0])i+=o+": "+arguments[0][o]+", ";i=i.slice(0,-2)}else i=arguments[a];r.push(i)}w(t+"\nArguments: "+Array.prototype.slice.call(r).join("")+"\n"+(new Error).stack),s=!1}return n.apply(this,arguments)},n)}function M(t,n){null!=e.deprecationHandler&&e.deprecationHandler(t,n),tt[t]||(w(n),tt[t]=!0)}function S(e){return e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function D(e,t){var s,i=u({},e);for(s in t)o(t,s)&&(n(e[s])&&n(t[s])?(i[s]={},u(i[s],e[s]),u(i[s],t[s])):null!=t[s]?i[s]=t[s]:delete i[s]);for(s in e)o(e,s)&&!o(t,s)&&n(e[s])&&(i[s]=u({},i[s]));return i}function k(e){null!=e&&this.set(e)}function Y(e,t){var n=e.toLowerCase();st[n]=st[n+"s"]=st[t]=e}function O(e){return"string"==typeof e?st[e]||st[e.toLowerCase()]:void 0}function T(e){var t,n,s={};for(n in e)o(e,n)&&(t=O(n))&&(s[t]=e[n]);return s}function x(e,t){it[e]=t}function b(e,t,n){var s=""+Math.abs(e),i=t-s.length;return(e>=0?n?"+":"":"-")+Math.pow(10,Math.max(0,i)).toString().substr(1)+s}function P(e,t,n,s){var i=s;"string"==typeof s&&(i=function(){return this[s]()}),e&&(ut[e]=i),t&&(ut[t[0]]=function(){return b(i.apply(this,arguments),t[1],t[2])}),n&&(ut[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function W(e){return e.match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"")}function H(e,t){return e.isValid()?(t=R(t,e.localeData()),ot[t]=ot[t]||function(e){var t,n,s=e.match(rt);for(t=0,n=s.length;t<n;t++)ut[s[t]]?s[t]=ut[s[t]]:s[t]=W(s[t]);return function(t){var i,r="";for(i=0;i<n;i++)r+=S(s[i])?s[i].call(t,e):s[i];return r}}(t),ot[t](e)):e.localeData().invalidDate()}function R(e,t){function n(e){return t.longDateFormat(e)||e}var s=5;for(at.lastIndex=0;s>=0&&at.test(e);)e=e.replace(at,n),at.lastIndex=0,s-=1;return e}function C(e,t,n){Yt[e]=S(t)?t:function(e,s){return e&&n?n:t}}function F(e,t){return o(Yt,e)?Yt[e](t._strict,t._locale):new RegExp(function(e){return U(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,s,i){return t||n||s||i}))}(e))}function U(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function L(e,t){var n,s=t;for("string"==typeof e&&(e=[e]),i(t)&&(s=function(e,n){n[t]=g(e)}),n=0;n<e.length;n++)Ot[e[n]]=s}function N(e,t){L(e,function(e,n,s,i){s._w=s._w||{},t(e,s._w,s,i)})}function G(e,t,n){null!=t&&o(Ot,e)&&Ot[e](t,n._a,n,e)}function V(e){return E(e)?366:365}function E(e){return e%4==0&&e%100!=0||e%400==0}function I(t,n){return function(s){return null!=s?(j(this,t,s),e.updateOffset(this,n),this):A(this,t)}}function A(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function j(e,t,n){e.isValid()&&!isNaN(n)&&("FullYear"===t&&E(e.year())&&1===e.month()&&29===e.date()?e._d["set"+(e._isUTC?"UTC":"")+t](n,e.month(),Z(n,e.month())):e._d["set"+(e._isUTC?"UTC":"")+t](n))}function Z(e,t){if(isNaN(e)||isNaN(t))return NaN;var n=function(e,t){return(e%t+t)%t}(t,12);return e+=(t-n)/12,1===n?E(e)?29:28:31-n%7%2}function z(e,t){var n;if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=g(t);else if(t=e.localeData().monthsParse(t),!i(t))return e;return n=Math.min(e.date(),Z(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n),e}function $(t){return null!=t?(z(this,t),e.updateOffset(this,!0),this):A(this,"Month")}function q(){function e(e,t){return t.length-e.length}var t,n,s=[],i=[],r=[];for(t=0;t<12;t++)n=l([2e3,t]),s.push(this.monthsShort(n,"")),i.push(this.months(n,"")),r.push(this.months(n,"")),r.push(this.monthsShort(n,""));for(s.sort(e),i.sort(e),r.sort(e),t=0;t<12;t++)s[t]=U(s[t]),i[t]=U(i[t]);for(t=0;t<24;t++)r[t]=U(r[t]);this._monthsRegex=new RegExp("^("+r.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function J(e){var t=new Date(Date.UTC.apply(null,arguments));return e<100&&e>=0&&isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e),t}function B(e,t,n){var s=7+t-n;return-((7+J(e,0,s).getUTCDay()-t)%7)+s-1}function Q(e,t,n,s,i){var r,a,o=1+7*(t-1)+(7+n-s)%7+B(e,s,i);return o<=0?a=V(r=e-1)+o:o>V(e)?(r=e+1,a=o-V(e)):(r=e,a=o),{year:r,dayOfYear:a}}function X(e,t,n){var s,i,r=B(e.year(),t,n),a=Math.floor((e.dayOfYear()-r-1)/7)+1;return a<1?s=a+K(i=e.year()-1,t,n):a>K(e.year(),t,n)?(s=a-K(e.year(),t,n),i=e.year()+1):(i=e.year(),s=a),{week:s,year:i}}function K(e,t,n){var s=B(e,t,n),i=B(e+1,t,n);return(V(e)-s+i)/7}function ee(){function e(e,t){return t.length-e.length}var t,n,s,i,r,a=[],o=[],u=[],d=[];for(t=0;t<7;t++)n=l([2e3,1]).day(t),s=this.weekdaysMin(n,""),i=this.weekdaysShort(n,""),r=this.weekdays(n,""),a.push(s),o.push(i),u.push(r),d.push(s),d.push(i),d.push(r);for(a.sort(e),o.sort(e),u.sort(e),d.sort(e),t=0;t<7;t++)o[t]=U(o[t]),u[t]=U(u[t]),d[t]=U(d[t]);this._weekdaysRegex=new RegExp("^("+d.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+u.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+a.join("|")+")","i")}function te(){return this.hours()%12||12}function ne(e,t){P(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function se(e,t){return t._meridiemParse}function ie(e){return e?e.toLowerCase().replace("_","-"):e}function re(e){var t=null;if(!Xt[e]&&"undefined"!=typeof module&&module&&module.exports)try{t=Jt._abbr;require("./locale/"+e),ae(t)}catch(e){}return Xt[e]}function ae(e,t){var n;return e&&(n=s(t)?ue(e):oe(e,t))&&(Jt=n),Jt._abbr}function oe(e,t){if(null!==t){var n=Qt;if(t.abbr=e,null!=Xt[e])M("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),n=Xt[e]._config;else if(null!=t.parentLocale){if(null==Xt[t.parentLocale])return Kt[t.parentLocale]||(Kt[t.parentLocale]=[]),Kt[t.parentLocale].push({name:e,config:t}),null;n=Xt[t.parentLocale]._config}return Xt[e]=new k(D(n,t)),Kt[e]&&Kt[e].forEach(function(e){oe(e.name,e.config)}),ae(e),Xt[e]}return delete Xt[e],null}function ue(e){var n;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return Jt;if(!t(e)){if(n=re(e))return n;e=[e]}return function(e){for(var t,n,s,i,r=0;r<e.length;){for(t=(i=ie(e[r]).split("-")).length,n=(n=ie(e[r+1]))?n.split("-"):null;t>0;){if(s=re(i.slice(0,t).join("-")))return s;if(n&&n.length>=t&&p(i,n,!0)>=t-1)break;t--}r++}return null}(e)}function le(e){var t,n=e._a;return n&&-2===d(e).overflow&&(t=n[xt]<0||n[xt]>11?xt:n[bt]<1||n[bt]>Z(n[Tt],n[xt])?bt:n[Pt]<0||n[Pt]>24||24===n[Pt]&&(0!==n[Wt]||0!==n[Ht]||0!==n[Rt])?Pt:n[Wt]<0||n[Wt]>59?Wt:n[Ht]<0||n[Ht]>59?Ht:n[Rt]<0||n[Rt]>999?Rt:-1,d(e)._overflowDayOfYear&&(t<Tt||t>bt)&&(t=bt),d(e)._overflowWeeks&&-1===t&&(t=Ct),d(e)._overflowWeekday&&-1===t&&(t=Ft),d(e).overflow=t),e}function de(e,t,n){return null!=e?e:null!=t?t:n}function he(t){var n,s,i,r,a,o=[];if(!t._d){for(i=function(t){var n=new Date(e.now());return t._useUTC?[n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()]:[n.getFullYear(),n.getMonth(),n.getDate()]}(t),t._w&&null==t._a[bt]&&null==t._a[xt]&&function(e){var t,n,s,i,r,a,o,u;if(null!=(t=e._w).GG||null!=t.W||null!=t.E)r=1,a=4,n=de(t.GG,e._a[Tt],X(pe(),1,4).year),s=de(t.W,1),((i=de(t.E,1))<1||i>7)&&(u=!0);else{r=e._locale._week.dow,a=e._locale._week.doy;var l=X(pe(),r,a);n=de(t.gg,e._a[Tt],l.year),s=de(t.w,l.week),null!=t.d?((i=t.d)<0||i>6)&&(u=!0):null!=t.e?(i=t.e+r,(t.e<0||t.e>6)&&(u=!0)):i=r}s<1||s>K(n,r,a)?d(e)._overflowWeeks=!0:null!=u?d(e)._overflowWeekday=!0:(o=Q(n,s,i,r,a),e._a[Tt]=o.year,e._dayOfYear=o.dayOfYear)}(t),null!=t._dayOfYear&&(a=de(t._a[Tt],i[Tt]),(t._dayOfYear>V(a)||0===t._dayOfYear)&&(d(t)._overflowDayOfYear=!0),s=J(a,0,t._dayOfYear),t._a[xt]=s.getUTCMonth(),t._a[bt]=s.getUTCDate()),n=0;n<3&&null==t._a[n];++n)t._a[n]=o[n]=i[n];for(;n<7;n++)t._a[n]=o[n]=null==t._a[n]?2===n?1:0:t._a[n];24===t._a[Pt]&&0===t._a[Wt]&&0===t._a[Ht]&&0===t._a[Rt]&&(t._nextDay=!0,t._a[Pt]=0),t._d=(t._useUTC?J:function(e,t,n,s,i,r,a){var o=new Date(e,t,n,s,i,r,a);return e<100&&e>=0&&isFinite(o.getFullYear())&&o.setFullYear(e),o}).apply(null,o),r=t._useUTC?t._d.getUTCDay():t._d.getDay(),null!=t._tzm&&t._d.setUTCMinutes(t._d.getUTCMinutes()-t._tzm),t._nextDay&&(t._a[Pt]=24),t._w&&void 0!==t._w.d&&t._w.d!==r&&(d(t).weekdayMismatch=!0)}}function ce(e){var t,n,s,i,r,a,o=e._i,u=en.exec(o)||tn.exec(o);if(u){for(d(e).iso=!0,t=0,n=sn.length;t<n;t++)if(sn[t][1].exec(u[1])){i=sn[t][0],s=!1!==sn[t][2];break}if(null==i)return void(e._isValid=!1);if(u[3]){for(t=0,n=rn.length;t<n;t++)if(rn[t][1].exec(u[3])){r=(u[2]||" ")+rn[t][0];break}if(null==r)return void(e._isValid=!1)}if(!s&&null!=r)return void(e._isValid=!1);if(u[4]){if(!nn.exec(u[4]))return void(e._isValid=!1);a="Z"}e._f=i+(r||"")+(a||""),_e(e)}else e._isValid=!1}function fe(e,t,n,s,i,r){var a=[function(e){var t=parseInt(e,10);{if(t<=49)return 2e3+t;if(t<=999)return 1900+t}return t}(e),Vt.indexOf(t),parseInt(n,10),parseInt(s,10),parseInt(i,10)];return r&&a.push(parseInt(r,10)),a}function me(e){var t=on.exec(function(e){return e.replace(/\([^)]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}(e._i));if(t){var n=fe(t[4],t[3],t[2],t[5],t[6],t[7]);if(!function(e,t,n){if(e&&jt.indexOf(e)!==new Date(t[0],t[1],t[2]).getDay())return d(n).weekdayMismatch=!0,n._isValid=!1,!1;return!0}(t[1],n,e))return;e._a=n,e._tzm=function(e,t,n){if(e)return un[e];if(t)return 0;var s=parseInt(n,10),i=s%100;return(s-i)/100*60+i}(t[8],t[9],t[10]),e._d=J.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),d(e).rfc2822=!0}else e._isValid=!1}function _e(t){if(t._f!==e.ISO_8601)if(t._f!==e.RFC_2822){t._a=[],d(t).empty=!0;var n,s,i,r,a,o=""+t._i,u=o.length,l=0;for(i=R(t._f,t._locale).match(rt)||[],n=0;n<i.length;n++)r=i[n],(s=(o.match(F(r,t))||[])[0])&&((a=o.substr(0,o.indexOf(s))).length>0&&d(t).unusedInput.push(a),o=o.slice(o.indexOf(s)+s.length),l+=s.length),ut[r]?(s?d(t).empty=!1:d(t).unusedTokens.push(r),G(r,s,t)):t._strict&&!s&&d(t).unusedTokens.push(r);d(t).charsLeftOver=u-l,o.length>0&&d(t).unusedInput.push(o),t._a[Pt]<=12&&!0===d(t).bigHour&&t._a[Pt]>0&&(d(t).bigHour=void 0),d(t).parsedDateParts=t._a.slice(0),d(t).meridiem=t._meridiem,t._a[Pt]=function(e,t,n){var s;if(null==n)return t;return null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?((s=e.isPM(n))&&t<12&&(t+=12),s||12!==t||(t=0),t):t}(t._locale,t._a[Pt],t._meridiem),he(t),le(t)}else me(t);else ce(t)}function ye(o){var l=o._i,y=o._f;return o._locale=o._locale||ue(o._l),null===l||void 0===y&&""===l?c({nullInput:!0}):("string"==typeof l&&(o._i=l=o._locale.preparse(l)),_(l)?new m(le(l)):(r(l)?o._d=l:t(y)?function(e){var t,n,s,i,r;if(0===e._f.length)return d(e).invalidFormat=!0,void(e._d=new Date(NaN));for(i=0;i<e._f.length;i++)r=0,t=f({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],_e(t),h(t)&&(r+=d(t).charsLeftOver,r+=10*d(t).unusedTokens.length,d(t).score=r,(null==s||r<s)&&(s=r,n=t));u(e,n||t)}(o):y?_e(o):function(o){var u=o._i;s(u)?o._d=new Date(e.now()):r(u)?o._d=new Date(u.valueOf()):"string"==typeof u?function(t){var n=an.exec(t._i);null===n?(ce(t),!1===t._isValid&&(delete t._isValid,me(t),!1===t._isValid&&(delete t._isValid,e.createFromInputFallback(t)))):t._d=new Date(+n[1])}(o):t(u)?(o._a=a(u.slice(0),function(e){return parseInt(e,10)}),he(o)):n(u)?function(e){if(!e._d){var t=T(e._i);e._a=a([t.year,t.month,t.day||t.date,t.hour,t.minute,t.second,t.millisecond],function(e){return e&&parseInt(e,10)}),he(e)}}(o):i(u)?o._d=new Date(u):e.createFromInputFallback(o)}(o),h(o)||(o._d=null),o))}function ge(e,s,i,r,a){var o={};return!0!==i&&!1!==i||(r=i,i=void 0),(n(e)&&function(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var t;for(t in e)if(e.hasOwnProperty(t))return!1;return!0}(e)||t(e)&&0===e.length)&&(e=void 0),o._isAMomentObject=!0,o._useUTC=o._isUTC=a,o._l=i,o._i=e,o._f=s,o._strict=r,function(e){var t=new m(le(ye(e)));return t._nextDay&&(t.add(1,"d"),t._nextDay=void 0),t}(o)}function pe(e,t,n,s){return ge(e,t,n,s,!1)}function we(e,n){var s,i;if(1===n.length&&t(n[0])&&(n=n[0]),!n.length)return pe();for(s=n[0],i=1;i<n.length;++i)n[i].isValid()&&!n[i][e](s)||(s=n[i]);return s}function ve(e){var t=T(e),n=t.year||0,s=t.quarter||0,i=t.month||0,r=t.week||0,a=t.day||0,o=t.hour||0,u=t.minute||0,l=t.second||0,d=t.millisecond||0;this._isValid=function(e){for(var t in e)if(-1===Ut.call(hn,t)||null!=e[t]&&isNaN(e[t]))return!1;for(var n=!1,s=0;s<hn.length;++s)if(e[hn[s]]){if(n)return!1;parseFloat(e[hn[s]])!==g(e[hn[s]])&&(n=!0)}return!0}(t),this._milliseconds=+d+1e3*l+6e4*u+1e3*o*60*60,this._days=+a+7*r,this._months=+i+3*s+12*n,this._data={},this._locale=ue(),this._bubble()}function Me(e){return e instanceof ve}function Se(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function De(e,t){P(e,0,0,function(){var e=this.utcOffset(),n="+";return e<0&&(e=-e,n="-"),n+b(~~(e/60),2)+t+b(~~e%60,2)})}function ke(e,t){var n=(t||"").match(e);if(null===n)return null;var s=((n[n.length-1]||[])+"").match(cn)||["-",0,0],i=60*s[1]+g(s[2]);return 0===i?0:"+"===s[0]?i:-i}function Ye(t,n){var s,i;return n._isUTC?(s=n.clone(),i=(_(t)||r(t)?t.valueOf():pe(t).valueOf())-s.valueOf(),s._d.setTime(s._d.valueOf()+i),e.updateOffset(s,!1),s):pe(t).local()}function Oe(e){return 15*-Math.round(e._d.getTimezoneOffset()/15)}function Te(){return!!this.isValid()&&(this._isUTC&&0===this._offset)}function xe(e,t){var n,s,r,a=e,u=null;return Me(e)?a={ms:e._milliseconds,d:e._days,M:e._months}:i(e)?(a={},t?a[t]=e:a.milliseconds=e):(u=fn.exec(e))?(n="-"===u[1]?-1:1,a={y:0,d:g(u[bt])*n,h:g(u[Pt])*n,m:g(u[Wt])*n,s:g(u[Ht])*n,ms:g(Se(1e3*u[Rt]))*n}):(u=mn.exec(e))?(n="-"===u[1]?-1:(u[1],1),a={y:be(u[2],n),M:be(u[3],n),w:be(u[4],n),d:be(u[5],n),h:be(u[6],n),m:be(u[7],n),s:be(u[8],n)}):null==a?a={}:"object"==typeof a&&("from"in a||"to"in a)&&(r=function(e,t){var n;if(!e.isValid()||!t.isValid())return{milliseconds:0,months:0};t=Ye(t,e),e.isBefore(t)?n=Pe(e,t):((n=Pe(t,e)).milliseconds=-n.milliseconds,n.months=-n.months);return n}(pe(a.from),pe(a.to)),(a={}).ms=r.milliseconds,a.M=r.months),s=new ve(a),Me(e)&&o(e,"_locale")&&(s._locale=e._locale),s}function be(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function Pe(e,t){var n={milliseconds:0,months:0};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function We(e,t){return function(n,s){var i,r;return null===s||isNaN(+s)||(M(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),r=n,n=s,s=r),n="string"==typeof n?+n:n,i=xe(n,s),He(this,i,e),this}}function He(t,n,s,i){var r=n._milliseconds,a=Se(n._days),o=Se(n._months);t.isValid()&&(i=null==i||i,o&&z(t,A(t,"Month")+o*s),a&&j(t,"Date",A(t,"Date")+a*s),r&&t._d.setTime(t._d.valueOf()+r*s),i&&e.updateOffset(t,a||o))}function Re(e,t){var n,s=12*(t.year()-e.year())+(t.month()-e.month()),i=e.clone().add(s,"months");return n=t-i<0?(t-i)/(i-e.clone().add(s-1,"months")):(t-i)/(e.clone().add(s+1,"months")-i),-(s+n)||0}function Ce(e){var t;return void 0===e?this._locale._abbr:(null!=(t=ue(e))&&(this._locale=t),this)}function Fe(){return this._locale}function Ue(e,t){P(0,[e,e.length],0,t)}function Le(e,t,n,s,i){var r;return null==e?X(this,s,i).year:(r=K(e,s,i),t>r&&(t=r),function(e,t,n,s,i){var r=Q(e,t,n,s,i),a=J(r.year,0,r.dayOfYear);return this.year(a.getUTCFullYear()),this.month(a.getUTCMonth()),this.date(a.getUTCDate()),this}.call(this,e,t,n,s,i))}function Ne(e,t){t[Rt]=g(1e3*("0."+e))}function Ge(e){return e}function Ve(e,t,n,s){var i=ue(),r=l().set(s,t);return i[n](r,e)}function Ee(e,t,n){if(i(e)&&(t=e,e=void 0),e=e||"",null!=t)return Ve(e,t,n,"month");var s,r=[];for(s=0;s<12;s++)r[s]=Ve(e,s,n,"month");return r}function Ie(e,t,n,s){"boolean"==typeof e?(i(t)&&(n=t,t=void 0),t=t||""):(n=t=e,e=!1,i(t)&&(n=t,t=void 0),t=t||"");var r=ue(),a=e?r._week.dow:0;if(null!=n)return Ve(t,(n+a)%7,s,"day");var o,u=[];for(o=0;o<7;o++)u[o]=Ve(t,(o+a)%7,s,"day");return u}function Ae(e,t,n,s){var i=xe(t,n);return e._milliseconds+=s*i._milliseconds,e._days+=s*i._days,e._months+=s*i._months,e._bubble()}function je(e){return e<0?Math.floor(e):Math.ceil(e)}function Ze(e){return 4800*e/146097}function ze(e){return 146097*e/4800}function $e(e){return function(){return this.as(e)}}function qe(e){return function(){return this.isValid()?this._data[e]:NaN}}function Je(e){return(e>0)-(e<0)||+e}function Be(){if(!this.isValid())return this.localeData().invalidDate();var e,t,n=An(this._milliseconds)/1e3,s=An(this._days),i=An(this._months);t=y((e=y(n/60))/60),n%=60,e%=60;var r=y(i/12),a=i%=12,o=s,u=t,l=e,d=n?n.toFixed(3).replace(/\.?0+$/,""):"",h=this.asSeconds();if(!h)return"P0D";var c=h<0?"-":"",f=Je(this._months)!==Je(h)?"-":"",m=Je(this._days)!==Je(h)?"-":"",_=Je(this._milliseconds)!==Je(h)?"-":"";return c+"P"+(r?f+r+"Y":"")+(a?f+a+"M":"")+(o?m+o+"D":"")+(u||l||d?"T":"")+(u?_+u+"H":"")+(l?_+l+"M":"")+(d?_+d+"S":"")}var Qe,Xe;Xe=Array.prototype.some?Array.prototype.some:function(e){for(var t=Object(this),n=t.length>>>0,s=0;s<n;s++)if(s in t&&e.call(this,t[s],s,t))return!0;return!1};var Ke=e.momentProperties=[],et=!1,tt={};e.suppressDeprecationWarnings=!1,e.deprecationHandler=null;var nt;nt=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)o(e,t)&&n.push(t);return n};var st={},it={},rt=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,at=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,ot={},ut={},lt=/\d/,dt=/\d\d/,ht=/\d{3}/,ct=/\d{4}/,ft=/[+-]?\d{6}/,mt=/\d\d?/,_t=/\d\d\d\d?/,yt=/\d\d\d\d\d\d?/,gt=/\d{1,3}/,pt=/\d{1,4}/,wt=/[+-]?\d{1,6}/,vt=/\d+/,Mt=/[+-]?\d+/,St=/Z|[+-]\d\d:?\d\d/gi,Dt=/Z|[+-]\d\d(?::?\d\d)?/gi,kt=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,Yt={},Ot={},Tt=0,xt=1,bt=2,Pt=3,Wt=4,Ht=5,Rt=6,Ct=7,Ft=8;P("Y",0,0,function(){var e=this.year();return e<=9999?""+e:"+"+e}),P(0,["YY",2],0,function(){return this.year()%100}),P(0,["YYYY",4],0,"year"),P(0,["YYYYY",5],0,"year"),P(0,["YYYYYY",6,!0],0,"year"),Y("year","y"),x("year",1),C("Y",Mt),C("YY",mt,dt),C("YYYY",pt,ct),C("YYYYY",wt,ft),C("YYYYYY",wt,ft),L(["YYYYY","YYYYYY"],Tt),L("YYYY",function(t,n){n[Tt]=2===t.length?e.parseTwoDigitYear(t):g(t)}),L("YY",function(t,n){n[Tt]=e.parseTwoDigitYear(t)}),L("Y",function(e,t){t[Tt]=parseInt(e,10)}),e.parseTwoDigitYear=function(e){return g(e)+(g(e)>68?1900:2e3)};var Ut,Lt=I("FullYear",!0);Ut=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1},P("M",["MM",2],"Mo",function(){return this.month()+1}),P("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),P("MMMM",0,0,function(e){return this.localeData().months(this,e)}),Y("month","M"),x("month",8),C("M",mt),C("MM",mt,dt),C("MMM",function(e,t){return t.monthsShortRegex(e)}),C("MMMM",function(e,t){return t.monthsRegex(e)}),L(["M","MM"],function(e,t){t[xt]=g(e)-1}),L(["MMM","MMMM"],function(e,t,n,s){var i=n._locale.monthsParse(e,s,n._strict);null!=i?t[xt]=i:d(n).invalidMonth=e});var Nt=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Gt="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),Vt="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),Et=kt,It=kt;P("w",["ww",2],"wo","week"),P("W",["WW",2],"Wo","isoWeek"),Y("week","w"),Y("isoWeek","W"),x("week",5),x("isoWeek",5),C("w",mt),C("ww",mt,dt),C("W",mt),C("WW",mt,dt),N(["w","ww","W","WW"],function(e,t,n,s){t[s.substr(0,1)]=g(e)});P("d",0,"do","day"),P("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),P("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),P("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),P("e",0,0,"weekday"),P("E",0,0,"isoWeekday"),Y("day","d"),Y("weekday","e"),Y("isoWeekday","E"),x("day",11),x("weekday",11),x("isoWeekday",11),C("d",mt),C("e",mt),C("E",mt),C("dd",function(e,t){return t.weekdaysMinRegex(e)}),C("ddd",function(e,t){return t.weekdaysShortRegex(e)}),C("dddd",function(e,t){return t.weekdaysRegex(e)}),N(["dd","ddd","dddd"],function(e,t,n,s){var i=n._locale.weekdaysParse(e,s,n._strict);null!=i?t.d=i:d(n).invalidWeekday=e}),N(["d","e","E"],function(e,t,n,s){t[s]=g(e)});var At="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),jt="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Zt="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),zt=kt,$t=kt,qt=kt;P("H",["HH",2],0,"hour"),P("h",["hh",2],0,te),P("k",["kk",2],0,function(){return this.hours()||24}),P("hmm",0,0,function(){return""+te.apply(this)+b(this.minutes(),2)}),P("hmmss",0,0,function(){return""+te.apply(this)+b(this.minutes(),2)+b(this.seconds(),2)}),P("Hmm",0,0,function(){return""+this.hours()+b(this.minutes(),2)}),P("Hmmss",0,0,function(){return""+this.hours()+b(this.minutes(),2)+b(this.seconds(),2)}),ne("a",!0),ne("A",!1),Y("hour","h"),x("hour",13),C("a",se),C("A",se),C("H",mt),C("h",mt),C("k",mt),C("HH",mt,dt),C("hh",mt,dt),C("kk",mt,dt),C("hmm",_t),C("hmmss",yt),C("Hmm",_t),C("Hmmss",yt),L(["H","HH"],Pt),L(["k","kk"],function(e,t,n){var s=g(e);t[Pt]=24===s?0:s}),L(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),L(["h","hh"],function(e,t,n){t[Pt]=g(e),d(n).bigHour=!0}),L("hmm",function(e,t,n){var s=e.length-2;t[Pt]=g(e.substr(0,s)),t[Wt]=g(e.substr(s)),d(n).bigHour=!0}),L("hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[Pt]=g(e.substr(0,s)),t[Wt]=g(e.substr(s,2)),t[Ht]=g(e.substr(i)),d(n).bigHour=!0}),L("Hmm",function(e,t,n){var s=e.length-2;t[Pt]=g(e.substr(0,s)),t[Wt]=g(e.substr(s))}),L("Hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[Pt]=g(e.substr(0,s)),t[Wt]=g(e.substr(s,2)),t[Ht]=g(e.substr(i))});var Jt,Bt=I("Hours",!0),Qt={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Gt,monthsShort:Vt,week:{dow:0,doy:6},weekdays:At,weekdaysMin:Zt,weekdaysShort:jt,meridiemParse:/[ap]\.?m?\.?/i},Xt={},Kt={},en=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,tn=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,nn=/Z|[+-]\d\d(?::?\d\d)?/,sn=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],rn=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],an=/^\/?Date\((\-?\d+)/i,on=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,un={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};e.createFromInputFallback=v("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),e.ISO_8601=function(){},e.RFC_2822=function(){};var ln=v("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=pe.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:c()}),dn=v("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=pe.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:c()}),hn=["year","quarter","month","week","day","hour","minute","second","millisecond"];De("Z",":"),De("ZZ",""),C("Z",Dt),C("ZZ",Dt),L(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=ke(Dt,e)});var cn=/([\+\-]|\d\d)/gi;e.updateOffset=function(){};var fn=/^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,mn=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;xe.fn=ve.prototype,xe.invalid=function(){return xe(NaN)};var _n=We(1,"add"),yn=We(-1,"subtract");e.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",e.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var gn=v("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});P(0,["gg",2],0,function(){return this.weekYear()%100}),P(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Ue("gggg","weekYear"),Ue("ggggg","weekYear"),Ue("GGGG","isoWeekYear"),Ue("GGGGG","isoWeekYear"),Y("weekYear","gg"),Y("isoWeekYear","GG"),x("weekYear",1),x("isoWeekYear",1),C("G",Mt),C("g",Mt),C("GG",mt,dt),C("gg",mt,dt),C("GGGG",pt,ct),C("gggg",pt,ct),C("GGGGG",wt,ft),C("ggggg",wt,ft),N(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,s){t[s.substr(0,2)]=g(e)}),N(["gg","GG"],function(t,n,s,i){n[i]=e.parseTwoDigitYear(t)}),P("Q",0,"Qo","quarter"),Y("quarter","Q"),x("quarter",7),C("Q",lt),L("Q",function(e,t){t[xt]=3*(g(e)-1)}),P("D",["DD",2],"Do","date"),Y("date","D"),x("date",9),C("D",mt),C("DD",mt,dt),C("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),L(["D","DD"],bt),L("Do",function(e,t){t[bt]=g(e.match(mt)[0])});var pn=I("Date",!0);P("DDD",["DDDD",3],"DDDo","dayOfYear"),Y("dayOfYear","DDD"),x("dayOfYear",4),C("DDD",gt),C("DDDD",ht),L(["DDD","DDDD"],function(e,t,n){n._dayOfYear=g(e)}),P("m",["mm",2],0,"minute"),Y("minute","m"),x("minute",14),C("m",mt),C("mm",mt,dt),L(["m","mm"],Wt);var wn=I("Minutes",!1);P("s",["ss",2],0,"second"),Y("second","s"),x("second",15),C("s",mt),C("ss",mt,dt),L(["s","ss"],Ht);var vn=I("Seconds",!1);P("S",0,0,function(){return~~(this.millisecond()/100)}),P(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),P(0,["SSS",3],0,"millisecond"),P(0,["SSSS",4],0,function(){return 10*this.millisecond()}),P(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),P(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),P(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),P(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),P(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),Y("millisecond","ms"),x("millisecond",16),C("S",gt,lt),C("SS",gt,dt),C("SSS",gt,ht);var Mn;for(Mn="SSSS";Mn.length<=9;Mn+="S")C(Mn,vt);for(Mn="S";Mn.length<=9;Mn+="S")L(Mn,Ne);var Sn=I("Milliseconds",!1);P("z",0,0,"zoneAbbr"),P("zz",0,0,"zoneName");var Dn=m.prototype;Dn.add=_n,Dn.calendar=function(t,n){var s=t||pe(),i=Ye(s,this).startOf("day"),r=e.calendarFormat(this,i)||"sameElse",a=n&&(S(n[r])?n[r].call(this,s):n[r]);return this.format(a||this.localeData().calendar(r,this,pe(s)))},Dn.clone=function(){return new m(this)},Dn.diff=function(e,t,n){var s,i,r;if(!this.isValid())return NaN;if(!(s=Ye(e,this)).isValid())return NaN;switch(i=6e4*(s.utcOffset()-this.utcOffset()),t=O(t)){case"year":r=Re(this,s)/12;break;case"month":r=Re(this,s);break;case"quarter":r=Re(this,s)/3;break;case"second":r=(this-s)/1e3;break;case"minute":r=(this-s)/6e4;break;case"hour":r=(this-s)/36e5;break;case"day":r=(this-s-i)/864e5;break;case"week":r=(this-s-i)/6048e5;break;default:r=this-s}return n?r:y(r)},Dn.endOf=function(e){return void 0===(e=O(e))||"millisecond"===e?this:("date"===e&&(e="day"),this.startOf(e).add(1,"isoWeek"===e?"week":e).subtract(1,"ms"))},Dn.format=function(t){t||(t=this.isUtc()?e.defaultFormatUtc:e.defaultFormat);var n=H(this,t);return this.localeData().postformat(n)},Dn.from=function(e,t){return this.isValid()&&(_(e)&&e.isValid()||pe(e).isValid())?xe({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},Dn.fromNow=function(e){return this.from(pe(),e)},Dn.to=function(e,t){return this.isValid()&&(_(e)&&e.isValid()||pe(e).isValid())?xe({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},Dn.toNow=function(e){return this.to(pe(),e)},Dn.get=function(e){return e=O(e),S(this[e])?this[e]():this},Dn.invalidAt=function(){return d(this).overflow},Dn.isAfter=function(e,t){var n=_(e)?e:pe(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=O(s(t)?"millisecond":t))?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())},Dn.isBefore=function(e,t){var n=_(e)?e:pe(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=O(s(t)?"millisecond":t))?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())},Dn.isBetween=function(e,t,n,s){return("("===(s=s||"()")[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===s[1]?this.isBefore(t,n):!this.isAfter(t,n))},Dn.isSame=function(e,t){var n,s=_(e)?e:pe(e);return!(!this.isValid()||!s.isValid())&&("millisecond"===(t=O(t||"millisecond"))?this.valueOf()===s.valueOf():(n=s.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))},Dn.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},Dn.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},Dn.isValid=function(){return h(this)},Dn.lang=gn,Dn.locale=Ce,Dn.localeData=Fe,Dn.max=dn,Dn.min=ln,Dn.parsingFlags=function(){return u({},d(this))},Dn.set=function(e,t){if("object"==typeof e)for(var n=function(e){var t=[];for(var n in e)t.push({unit:n,priority:it[n]});return t.sort(function(e,t){return e.priority-t.priority}),t}(e=T(e)),s=0;s<n.length;s++)this[n[s].unit](e[n[s].unit]);else if(e=O(e),S(this[e]))return this[e](t);return this},Dn.startOf=function(e){switch(e=O(e)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===e&&this.weekday(0),"isoWeek"===e&&this.isoWeekday(1),"quarter"===e&&this.month(3*Math.floor(this.month()/3)),this},Dn.subtract=yn,Dn.toArray=function(){return[this.year(),this.month(),this.date(),this.hour(),this.minute(),this.second(),this.millisecond()]},Dn.toObject=function(){return{years:this.year(),months:this.month(),date:this.date(),hours:this.hours(),minutes:this.minutes(),seconds:this.seconds(),milliseconds:this.milliseconds()}},Dn.toDate=function(){return new Date(this.valueOf())},Dn.toISOString=function(e){if(!this.isValid())return null;var t=!0!==e,n=t?this.clone().utc():this;return n.year()<0||n.year()>9999?H(n,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):S(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this._d.valueOf()).toISOString().replace("Z",H(n,"Z")):H(n,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},Dn.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e="moment",t="";this.isLocal()||(e=0===this.utcOffset()?"moment.utc":"moment.parseZone",t="Z");var n="["+e+'("]',s=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",i=t+'[")]';return this.format(n+s+"-MM-DD[T]HH:mm:ss.SSS"+i)},Dn.toJSON=function(){return this.isValid()?this.toISOString():null},Dn.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},Dn.unix=function(){return Math.floor(this.valueOf()/1e3)},Dn.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},Dn.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},Dn.year=Lt,Dn.isLeapYear=function(){return E(this.year())},Dn.weekYear=function(e){return Le.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},Dn.isoWeekYear=function(e){return Le.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},Dn.quarter=Dn.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},Dn.month=$,Dn.daysInMonth=function(){return Z(this.year(),this.month())},Dn.week=Dn.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},Dn.isoWeek=Dn.isoWeeks=function(e){var t=X(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},Dn.weeksInYear=function(){var e=this.localeData()._week;return K(this.year(),e.dow,e.doy)},Dn.isoWeeksInYear=function(){return K(this.year(),1,4)},Dn.date=pn,Dn.day=Dn.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(e=function(e,t){return"string"!=typeof e?e:isNaN(e)?"number"==typeof(e=t.weekdaysParse(e))?e:null:parseInt(e,10)}(e,this.localeData()),this.add(e-t,"d")):t},Dn.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},Dn.isoWeekday=function(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var t=function(e,t){return"string"==typeof e?t.weekdaysParse(e)%7||7:isNaN(e)?null:e}(e,this.localeData());return this.day(this.day()%7?t:t-7)}return this.day()||7},Dn.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},Dn.hour=Dn.hours=Bt,Dn.minute=Dn.minutes=wn,Dn.second=Dn.seconds=vn,Dn.millisecond=Dn.milliseconds=Sn,Dn.utcOffset=function(t,n,s){var i,r=this._offset||0;if(!this.isValid())return null!=t?this:NaN;if(null!=t){if("string"==typeof t){if(null===(t=ke(Dt,t)))return this}else Math.abs(t)<16&&!s&&(t*=60);return!this._isUTC&&n&&(i=Oe(this)),this._offset=t,this._isUTC=!0,null!=i&&this.add(i,"m"),r!==t&&(!n||this._changeInProgress?He(this,xe(t-r,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,e.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?r:Oe(this)},Dn.utc=function(e){return this.utcOffset(0,e)},Dn.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Oe(this),"m")),this},Dn.parseZone=function(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if("string"==typeof this._i){var e=ke(St,this._i);null!=e?this.utcOffset(e):this.utcOffset(0,!0)}return this},Dn.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?pe(e).utcOffset():0,(this.utcOffset()-e)%60==0)},Dn.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},Dn.isLocal=function(){return!!this.isValid()&&!this._isUTC},Dn.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},Dn.isUtc=Te,Dn.isUTC=Te,Dn.zoneAbbr=function(){return this._isUTC?"UTC":""},Dn.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},Dn.dates=v("dates accessor is deprecated. Use date instead.",pn),Dn.months=v("months accessor is deprecated. Use month instead",$),Dn.years=v("years accessor is deprecated. Use year instead",Lt),Dn.zone=v("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}),Dn.isDSTShifted=v("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){if(!s(this._isDSTShifted))return this._isDSTShifted;var e={};if(f(e,this),(e=ye(e))._a){var t=e._isUTC?l(e._a):pe(e._a);this._isDSTShifted=this.isValid()&&p(e._a,t.toArray())>0}else this._isDSTShifted=!1;return this._isDSTShifted});var kn=k.prototype;kn.calendar=function(e,t,n){var s=this._calendar[e]||this._calendar.sameElse;return S(s)?s.call(t,n):s},kn.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.replace(/MMMM|MM|DD|dddd/g,function(e){return e.slice(1)}),this._longDateFormat[e])},kn.invalidDate=function(){return this._invalidDate},kn.ordinal=function(e){return this._ordinal.replace("%d",e)},kn.preparse=Ge,kn.postformat=Ge,kn.relativeTime=function(e,t,n,s){var i=this._relativeTime[n];return S(i)?i(e,t,n,s):i.replace(/%d/i,e)},kn.pastFuture=function(e,t){var n=this._relativeTime[e>0?"future":"past"];return S(n)?n(t):n.replace(/%s/i,t)},kn.set=function(e){var t,n;for(n in e)S(t=e[n])?this[n]=t:this["_"+n]=t;this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},kn.months=function(e,n){return e?t(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||Nt).test(n)?"format":"standalone"][e.month()]:t(this._months)?this._months:this._months.standalone},kn.monthsShort=function(e,n){return e?t(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[Nt.test(n)?"format":"standalone"][e.month()]:t(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},kn.monthsParse=function(e,t,n){var s,i,r;if(this._monthsParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)r=l([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(r,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(r,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=Ut.call(this._shortMonthsParse,a))?i:null:-1!==(i=Ut.call(this._longMonthsParse,a))?i:null:"MMM"===t?-1!==(i=Ut.call(this._shortMonthsParse,a))?i:-1!==(i=Ut.call(this._longMonthsParse,a))?i:null:-1!==(i=Ut.call(this._longMonthsParse,a))?i:-1!==(i=Ut.call(this._shortMonthsParse,a))?i:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(i=l([2e3,s]),n&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[s]||(r="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[s]=new RegExp(r.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[s].test(e))return s;if(n&&"MMM"===t&&this._shortMonthsParse[s].test(e))return s;if(!n&&this._monthsParse[s].test(e))return s}},kn.monthsRegex=function(e){return this._monthsParseExact?(o(this,"_monthsRegex")||q.call(this),e?this._monthsStrictRegex:this._monthsRegex):(o(this,"_monthsRegex")||(this._monthsRegex=It),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},kn.monthsShortRegex=function(e){return this._monthsParseExact?(o(this,"_monthsRegex")||q.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(o(this,"_monthsShortRegex")||(this._monthsShortRegex=Et),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},kn.week=function(e){return X(e,this._week.dow,this._week.doy).week},kn.firstDayOfYear=function(){return this._week.doy},kn.firstDayOfWeek=function(){return this._week.dow},kn.weekdays=function(e,n){return e?t(this._weekdays)?this._weekdays[e.day()]:this._weekdays[this._weekdays.isFormat.test(n)?"format":"standalone"][e.day()]:t(this._weekdays)?this._weekdays:this._weekdays.standalone},kn.weekdaysMin=function(e){return e?this._weekdaysMin[e.day()]:this._weekdaysMin},kn.weekdaysShort=function(e){return e?this._weekdaysShort[e.day()]:this._weekdaysShort},kn.weekdaysParse=function(e,t,n){var s,i,r;if(this._weekdaysParseExact)return function(e,t,n){var s,i,r,a=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)r=l([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(r,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(r,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(r,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=Ut.call(this._weekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ut.call(this._shortWeekdaysParse,a))?i:null:-1!==(i=Ut.call(this._minWeekdaysParse,a))?i:null:"dddd"===t?-1!==(i=Ut.call(this._weekdaysParse,a))?i:-1!==(i=Ut.call(this._shortWeekdaysParse,a))?i:-1!==(i=Ut.call(this._minWeekdaysParse,a))?i:null:"ddd"===t?-1!==(i=Ut.call(this._shortWeekdaysParse,a))?i:-1!==(i=Ut.call(this._weekdaysParse,a))?i:-1!==(i=Ut.call(this._minWeekdaysParse,a))?i:null:-1!==(i=Ut.call(this._minWeekdaysParse,a))?i:-1!==(i=Ut.call(this._weekdaysParse,a))?i:-1!==(i=Ut.call(this._shortWeekdaysParse,a))?i:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(i=l([2e3,1]).day(s),n&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(i,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(i,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(i,"").replace(".",".?")+"$","i")),this._weekdaysParse[s]||(r="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[s]=new RegExp(r.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[s].test(e))return s;if(n&&"ddd"===t&&this._shortWeekdaysParse[s].test(e))return s;if(n&&"dd"===t&&this._minWeekdaysParse[s].test(e))return s;if(!n&&this._weekdaysParse[s].test(e))return s}},kn.weekdaysRegex=function(e){return this._weekdaysParseExact?(o(this,"_weekdaysRegex")||ee.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(o(this,"_weekdaysRegex")||(this._weekdaysRegex=zt),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},kn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(o(this,"_weekdaysRegex")||ee.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(o(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=$t),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},kn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(o(this,"_weekdaysRegex")||ee.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(o(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=qt),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},kn.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},kn.meridiem=function(e,t,n){return e>11?n?"pm":"PM":n?"am":"AM"},ae("en",{dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===g(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th")}}),e.lang=v("moment.lang is deprecated. Use moment.locale instead.",ae),e.langData=v("moment.langData is deprecated. Use moment.localeData instead.",ue);var Yn=Math.abs,On=$e("ms"),Tn=$e("s"),xn=$e("m"),bn=$e("h"),Pn=$e("d"),Wn=$e("w"),Hn=$e("M"),Rn=$e("y"),Cn=qe("milliseconds"),Fn=qe("seconds"),Un=qe("minutes"),Ln=qe("hours"),Nn=qe("days"),Gn=qe("months"),Vn=qe("years"),En=Math.round,In={ss:44,s:45,m:45,h:22,d:26,M:11},An=Math.abs,jn=ve.prototype;return jn.isValid=function(){return this._isValid},jn.abs=function(){var e=this._data;return this._milliseconds=Yn(this._milliseconds),this._days=Yn(this._days),this._months=Yn(this._months),e.milliseconds=Yn(e.milliseconds),e.seconds=Yn(e.seconds),e.minutes=Yn(e.minutes),e.hours=Yn(e.hours),e.months=Yn(e.months),e.years=Yn(e.years),this},jn.add=function(e,t){return Ae(this,e,t,1)},jn.subtract=function(e,t){return Ae(this,e,t,-1)},jn.as=function(e){if(!this.isValid())return NaN;var t,n,s=this._milliseconds;if("month"===(e=O(e))||"year"===e)return t=this._days+s/864e5,n=this._months+Ze(t),"month"===e?n:n/12;switch(t=this._days+Math.round(ze(this._months)),e){case"week":return t/7+s/6048e5;case"day":return t+s/864e5;case"hour":return 24*t+s/36e5;case"minute":return 1440*t+s/6e4;case"second":return 86400*t+s/1e3;case"millisecond":return Math.floor(864e5*t)+s;default:throw new Error("Unknown unit "+e)}},jn.asMilliseconds=On,jn.asSeconds=Tn,jn.asMinutes=xn,jn.asHours=bn,jn.asDays=Pn,jn.asWeeks=Wn,jn.asMonths=Hn,jn.asYears=Rn,jn.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*g(this._months/12):NaN},jn._bubble=function(){var e,t,n,s,i,r=this._milliseconds,a=this._days,o=this._months,u=this._data;return r>=0&&a>=0&&o>=0||r<=0&&a<=0&&o<=0||(r+=864e5*je(ze(o)+a),a=0,o=0),u.milliseconds=r%1e3,e=y(r/1e3),u.seconds=e%60,t=y(e/60),u.minutes=t%60,n=y(t/60),u.hours=n%24,a+=y(n/24),i=y(Ze(a)),o+=i,a-=je(ze(i)),s=y(o/12),o%=12,u.days=a,u.months=o,u.years=s,this},jn.clone=function(){return xe(this)},jn.get=function(e){return e=O(e),this.isValid()?this[e+"s"]():NaN},jn.milliseconds=Cn,jn.seconds=Fn,jn.minutes=Un,jn.hours=Ln,jn.days=Nn,jn.weeks=function(){return y(this.days()/7)},jn.months=Gn,jn.years=Vn,jn.humanize=function(e){if(!this.isValid())return this.localeData().invalidDate();var t=this.localeData(),n=function(e,t,n){var s=xe(e).abs(),i=En(s.as("s")),r=En(s.as("m")),a=En(s.as("h")),o=En(s.as("d")),u=En(s.as("M")),l=En(s.as("y")),d=i<=In.ss&&["s",i]||i<In.s&&["ss",i]||r<=1&&["m"]||r<In.m&&["mm",r]||a<=1&&["h"]||a<In.h&&["hh",a]||o<=1&&["d"]||o<In.d&&["dd",o]||u<=1&&["M"]||u<In.M&&["MM",u]||l<=1&&["y"]||["yy",l];return d[2]=t,d[3]=+e>0,d[4]=n,function(e,t,n,s,i){return i.relativeTime(t||1,!!n,e,s)}.apply(null,d)}(this,!e,t);return e&&(n=t.pastFuture(+this,n)),t.postformat(n)},jn.toISOString=Be,jn.toString=Be,jn.toJSON=Be,jn.locale=Ce,jn.localeData=Fe,jn.toIsoString=v("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Be),jn.lang=gn,P("X",0,0,"unix"),P("x",0,0,"valueOf"),C("x",Mt),C("X",/[+-]?\d+(\.\d{1,3})?/),L("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e,10))}),L("x",function(e,t,n){n._d=new Date(g(e))}),e.version="2.20.1",function(e){Qe=e}(pe),e.fn=Dn,e.min=function(){return we("isBefore",[].slice.call(arguments,0))},e.max=function(){return we("isAfter",[].slice.call(arguments,0))},e.now=function(){return Date.now?Date.now():+new Date},e.utc=l,e.unix=function(e){return pe(1e3*e)},e.months=function(e,t){return Ee(e,t,"months")},e.isDate=r,e.locale=ae,e.invalid=c,e.duration=xe,e.isMoment=_,e.weekdays=function(e,t,n){return Ie(e,t,n,"weekdays")},e.parseZone=function(){return pe.apply(null,arguments).parseZone()},e.localeData=ue,e.isDuration=Me,e.monthsShort=function(e,t){return Ee(e,t,"monthsShort")},e.weekdaysMin=function(e,t,n){return Ie(e,t,n,"weekdaysMin")},e.defineLocale=oe,e.updateLocale=function(e,t){if(null!=t){var n,s,i=Qt;null!=(s=re(e))&&(i=s._config),(n=new k(t=D(i,t))).parentLocale=Xt[e],Xt[e]=n,ae(e)}else null!=Xt[e]&&(null!=Xt[e].parentLocale?Xt[e]=Xt[e].parentLocale:null!=Xt[e]&&delete Xt[e]);return Xt[e]},e.locales=function(){return nt(Xt)},e.weekdaysShort=function(e,t,n){return Ie(e,t,n,"weekdaysShort")},e.normalizeUnits=O,e.relativeTimeRounding=function(e){return void 0===e?En:"function"==typeof e&&(En=e,!0)},e.relativeTimeThreshold=function(e,t){return void 0!==In[e]&&(void 0===t?In[e]:(In[e]=t,"s"===e&&(In.ss=t-1),!0))},e.calendarFormat=function(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"},e.prototype=Dn,e.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"YYYY-[W]WW",MONTH:"YYYY-MM"},e});var DeviceContext;(function(DeviceContext){DeviceContext[DeviceContext["Mobile"]=0]="Mobile";DeviceContext[DeviceContext["Tablet"]=1]="Tablet";DeviceContext[DeviceContext["Desktop"]=2]="Desktop";})(DeviceContext||(DeviceContext={}));var Shared=(function(){function Shared(){}
Shared.ToggleScrollbar=function(el){if(el!=null){console.log(el.scrollHeight);console.log(Utility.GetWindowHeight());if(el.scrollHeight>Utility.GetWindowHeight()){el.style.overflowY="scroll";document.documentElement.style.overflowY="hidden";}
else{el.style.overflowY="initial";if(el.scrollHeight==Utility.GetWindowHeight()){document.documentElement.style.overflowY="hidden";}
else{document.documentElement.style.overflowY="initial";}}}
else{el.style.overflowY="initial";document.documentElement.style.overflowY="initial";}};Shared.getParameterByName=function(name,url){if(!url)
url=window.location.href;name=name.replace(/[\[\]]/g,"\\$&");var regex=new RegExp("[?&]"+name+"(=([^&#]*)|&|#|$)"),results=regex.exec(url);if(!results)
return null;if(!results[2])
return '';return decodeURIComponent(results[2].replace(/\+/g," "));};Shared.gotoraq=function(url){PageLogger.LogEstPageStep(null,EstablishmentStep.GotoRaq,"raq-start");window.location.href=url;};return Shared;}());sn.app.map=sn.app.map||{Data:[],Markers:[{}],Zoom:10,MapInstances:[],InfoWindow:null,EnableDragSearch:true,SearchFunction:function(){},SearchOnLoad:false,ShowInitialOverlay:false,ShowTools:false,ShowLegend:false,ContentMarkers:[],Service:null,initContentHomePage:function(){var $window=$(window),mapInstances=[],$pluginInstance=$(".map").lazyLoadGoogleMaps({callback:function(container,map){var $container=$(container),center=new google.maps.LatLng(Number($container.attr("data-lat")),Number($container.attr("data-lng")));map.setOptions({zoom:15,center:center,scrollwheel:false,styles:[{featureType:"poi",stylers:[{visibility:"off"}]}]});var marker=new google.maps.Marker({position:center,map:map});$.data(map,"center",center);var infowindow=new google.maps.InfoWindow({maxWidth:300});infowindow.setContent($("#mapInfoWindow").val());infowindow.open(map,marker);map.panBy(0,-80);mapInstances.push(map);var updateCenter=function(){$.data(map,"center",map.getCenter());};google.maps.event.addListener(map,"dragend",updateCenter);google.maps.event.addListener(map,"zoom_changed",updateCenter);google.maps.event.addListenerOnce(map,"idle",function(){$container.addClass("is-loaded");});},api_key:"AIzaSyDRRBhpRkoifqA_Ijr0SYeXp5UrqZqQVV8"});$window.on("resize",$pluginInstance.debounce(1000,function(){$.each(mapInstances,function(){this.setCenter($.data(this,"center"));if(this.getDiv().offsetHeight===300){this.panBy(0,-80);}});}));},initEstablishmentHomePage:function(){var $window=$(window),mapInstances=[],$pluginInstance=$(".map").lazyLoadGoogleMaps({callback:function(container,map){var $container=$(container),center=new google.maps.LatLng(Number($container.attr("data-lat")),Number($container.attr("data-lng")));var poiSetting=$(".nav-staff").length>0?"on":"off";map.setOptions({zoom:17,center:center,mapTypeControl:false,scrollwheel:false,styles:[{featureType:"poi",stylers:[{visibility:poiSetting}]}]});var marker=new google.maps.Marker({position:center,map:map});$.data(map,"center",center);var infowindow=new google.maps.InfoWindow({maxWidth:300});infowindow.setContent($("#mapInfoWindow").val());infowindow.open(map,marker);map.panBy(0,-80);mapInstances.push(map);var updateCenter=function(){$.data(map,"center",map.getCenter());};google.maps.event.addListener(map,"dragend",updateCenter);google.maps.event.addListener(map,"zoom_changed",updateCenter);google.maps.event.addListenerOnce(map,"idle",function(){$container.addClass("is-loaded");setTimeout(function(){if(document.getElementsByClassName('infoWindow').length>0){ko.cleanNode(document.getElementsByClassName('infoWindow')[0]);ko.applyBindings(sn.app.esthomepagev3.ViewModel,document.getElementsByClassName('infoWindow')[0]);}},200);});},api_key:"AIzaSyDRRBhpRkoifqA_Ijr0SYeXp5UrqZqQVV8"});$window.on("resize",$pluginInstance.debounce(1000,function(){$.each(mapInstances,function(){this.setCenter($.data(this,"center"));if(this.getDiv().offsetHeight===300){this.panBy(0,-80);}});}));},initRootLocation:function(){var $window=$(window),mapInstances=[],$pluginInstance=$(".map").lazyLoadGoogleMaps({callback:function(container,map){var $container=$(container),center=new google.maps.LatLng(Number($container.attr("data-lat")),Number($container.attr("data-lng")));map.setOptions({zoom:15,center:center,scrollwheel:false,mapTypeControl:false,styles:[{featureType:"poi",stylers:[{visibility:"off"}]}]});var marker=new google.maps.Marker({position:center,map:map});$.data(map,"center",center);var infowindow=new google.maps.InfoWindow({maxWidth:300});infowindow.setContent($("#mapInfoWindow").val());infowindow.open(map,marker);map.panBy(0,-80);mapInstances.push(map);var updateCenter=function(){$.data(map,"center",map.getCenter());};google.maps.event.addListener(map,"dragend",updateCenter);google.maps.event.addListener(map,"zoom_changed",updateCenter);google.maps.event.addListenerOnce(map,"idle",function(){$container.addClass("is-loaded");});},api_key:"AIzaSyDRRBhpRkoifqA_Ijr0SYeXp5UrqZqQVV8"});$window.on("resize",$pluginInstance.debounce(1000,function(){$.each(mapInstances,function(){this.setCenter($.data(this,"center"));if(this.getDiv().offsetHeight===300){this.panBy(0,-80);}});}));},initListingMap:function(zoomLevel,enableDragSearch,searchOnLoad,showInitialOverlay,showTools,showLegend,showThings,service){this.EnableDragSearch=true;this.SearchOnLoad=searchOnLoad;this.ShowInitialOverlay=showInitialOverlay;this.ShowTools=false;this.ShowLegend=false;this.Service=service;var $window=$(window);var $pluginInstance=$(".map").lazyLoadGoogleMaps({callback:function(container,map){var _this=this;$("body").append("<script src=\"/res/ext/mapmarkerlabel/markerwithlabel.js\"></script>");$("body").append("<script src=\"/res/ext/mapinfobox/infobox.js\"></script>");$("body").append("<script src=\"/res/ext/maptooltip/tooltip.js\"></script>");if(!sn.app.map.ShowLegend){$("#legend").hide();}
var $container=$(container),center=new google.maps.LatLng(Number($container.attr("data-lat")),Number($container.attr("data-lng")));if($container.attr("data-lat")!=null){sn.app.map.Zoom=Number($container.attr("data-zoom"));}
if(!(sn.app.map.Zoom>0)){sn.app.map.Zoom=10;}
map.setOptions({zoom:sn.app.map.Zoom,center:center,scrollwheel:false,panControl:true,mapTypeControl:false,mapTypeId:"roadmap",zoomControlOptions:{style:google.maps.ZoomControlStyle.LARGE,position:google.maps.ControlPosition.RIGHT_CENTER},panControlOptions:{position:google.maps.ControlPosition.LEFT_TOP},styles:[{featureType:"poi",stylers:[{visibility:"off"}]}]});googleMapWidth=$container.css("width");googleMapHeight=$container.css("height");sn.app.map.InfoWindow=new google.maps.InfoWindow({maxWidth:300});var i;for(i=0;i<sn.app.map.Data.length;i++){var item=sn.app.map.Data[i];sn.app.map.createMarker(map,item);}
$.data(map,"center",center);sn.app.map.MapInstances.push(map);google.maps.event.addListener(map,"dragend",function(){sn.app.map.searchAndRefresh(map);});google.maps.event.addListener(map,"zoom_changed",function(){sn.app.map.searchAndRefresh(map);});google.maps.event.addListenerOnce(map,"idle",function(){$container.addClass("is-loaded");if(sn.app.map.SearchOnLoad){$("#mapNorthEastLat").val(map.getBounds().getNorthEast().lat());$("#mapNorthEastLng").val(map.getBounds().getNorthEast().lng());$("#mapSouthWestLat").val(map.getBounds().getSouthWest().lat());$("#mapSouthWestLng").val(map.getBounds().getSouthWest().lng());}});sn.app.map.refreshMap();$("#btn-enter-full-screen").click(function(){$(".map").css({position:"fixed",top:0,left:0,width:"100%",height:"100%",backgroundColor:"white"});$("#map-container").css({height:"100%"});google.maps.event.trigger(map,"resize");$("#btn-enter-full-screen").toggle();$("#btn-exit-full-screen").toggle();return false;});function ThingsToDoControl(controlDiv,map){var controlUI=document.createElement('div');controlUI.style.backgroundColor='#fff';controlUI.style.border='2px solid #fff';controlUI.style.boxShadow='0 2px 6px rgba(0,0,0,.3)';controlUI.style.cursor='pointer';controlUI.style.marginBottom='22px';controlUI.style.textAlign='center';controlUI.style.margin='10px';controlUI.style.width='145px';controlDiv.appendChild(controlUI);var controlText=document.createElement('div');controlText.style.fontSize='16px';controlText.innerHTML='<div class="l-db l-pr check-box">'+
'<input style="margin: 3px" id="checkboxThingsToDo" type="checkbox" class="cb-filter"><label>'+
'<a class="lnk-filter">'+
'Things To Do'+
'</a>'+
'</label>'+
'</div>';controlUI.appendChild(controlText);controlUI.addEventListener('click',function(){var checkBox=document.getElementById("checkboxThingsToDo");;if(checkBox.checked==false){sn.app.map.addThingsToDoMarkers();checkBox.checked=true;}
else{sn.app.map.clearThingsToDoMarkers();checkBox.checked=false;}});}
if(sn.app.map.ShowInitialOverlay&&window.matchMedia&&window.matchMedia("(max-width: 40em)").matches){sn.app.map.toggleControls(map,false);$("#map").prepend($(".map-disable-overlay"));$(".map-disable-overlay").show();$(".enable-map").click(function(){$(".map-disable-overlay").slideToggle("slow",function(){sn.app.map.toggleControls(map,true);});});}
else{if(sn.app.map.ShowTools){$(".map-tools").show();}
else{$(".map-tools").hide();}}
$(".refresh-map").click(function(){event.preventDefault();_this.refreshAndSearch(map);});},api_key:"AIzaSyDRRBhpRkoifqA_Ijr0SYeXp5UrqZqQVV8"});$window.on("resize",$pluginInstance.debounce(1000,function(){$.each(sn.app.map.MapInstances,function(){this.setCenter($.data(this,"center"));if(this.getDiv().offsetHeight===300){this.panBy(0,-85);}});}));},readyToRefresh:function(isReady){if(isReady){$(".refresh-map").addClass("blue");$(".refresh-map .circle-s").fadeToggle("slow",function(){$(this).fadeToggle();});}
else{$(".refresh-map").removeClass("blue");}},toggleControls:function(map,bool){map.setOptions({draggable:bool,zoomControl:bool,scrollwheel:bool,disableDoubleClickZoom:!bool,scaleControl:bool,panControl:bool});if($(".map-tools").length){if(bool&&sn.app.map.ShowTools){$(".map-tools").slideToggle();}
else{$(".map-tools").hide();}}},createContentMarker:function(map,item){var marker=new google.maps.Marker({position:new google.maps.LatLng(item.Latitude,item.Longitude),icon:sn.app.map.getIcon(item.PlaceTypeId),map:map});marker.setMap(map);sn.app.map.createToolTip(marker,item.Name,map);google.maps.event.addListener(marker,"click",function(){sn.app.map.EnableShowLabelHover=false;map.panTo(new google.maps.LatLng(item.Latitude,item.Latitude));$(".infoBox").hide();var infobox=new InfoBox({content:"<div class='infobox-wrapper'><div class='map-infobox info-window-img'><div><a href='"+item.Url+"'>"+item.Name+"</a></div><div><img src='"+item.MainImageUrl+"'/></div></div>",disableAutoPan:false,maxWidth:175,pixelOffset:new google.maps.Size(-140,0),zIndex:null,boxStyle:{background:"url('/res/img/tipbox.gif') no-repeat",opacity:0.95,width:"200px",padding:0,margin:0},closeBoxMargin:"-11px -8px 0px 0px",closeBoxURL:"/res/img/close.png",infoBoxClearance:new google.maps.Size(1,1)});infobox.open(map,this);});sn.app.map.ContentMarkers.push(marker);},getIcon:function(typeid){var iconName;switch(typeid){case 1:case 2:case 4:case 5:case 7:case 8:case 9:case 11:case 24:case 25:case 26:iconName=typeid;break;default:iconName="other";}
return "/images/icons/maps/"+iconName+".png";},createToolTip:function(marker,name,map){var tooltipOptions={marker:marker,content:name,map:map};var tooltip=new Tooltip(tooltipOptions);},createMarker:function(map,item){var markerInfoModel={spid:item.spid,id:item.id,type:item.type,mainimageid:item.mainimageid,mainimageurl:item.mainimageurl,alttext:item.alttext,url:item.url,name:item.name,accomtypes:item.accomtypes,maxoccupancy:item.maxoccupancy,reviewcount:item.reviewcount,latitude:item.latitude,longitude:item.longitude,instantbook:item.instantbook,displayprice:item.displayprice,displaycurrency:item.displayCurrency,markerType:item.markerType,isEnquirable:item.isEnquirable,special:item.special};var marker=new MarkerWithLabel({position:new google.maps.LatLng(item.latitude,item.longitude),icon:item.instantbook?"/images/icons/maps/available.png":"/images/icons/maps/request.png",map:map,infomodel:markerInfoModel});marker.setMap(map);;google.maps.event.addListener(marker,"click",function(){sn.app.map.EnableShowLabelHover=false;map.panTo(new google.maps.LatLng(this.infomodel.latitude,this.infomodel.longitude));$(".infoBox").hide();var infobox=new InfoBox({content:"<div class=\"l-fl map-infobox\" id=\"searchLoaderImage\"><img src=\"/Content/flow/img/loader.gif\" /></div>",disableAutoPan:false,maxWidth:175,pixelOffset:new google.maps.Size(-140,0),zIndex:null,boxStyle:{background:"url('/res/img/tipbox.gif') no-repeat",opacity:0.95,width:"200px",padding:0,margin:0},closeBoxMargin:"-11px -8px 0px 0px",closeBoxURL:"/res/img/close.png",infoBoxClearance:new google.maps.Size(1,1)});infobox.open(map,this);if(item.markerType==="accommodation"){$.ajax({url:"/Listing/GetEstablishmentMapInfoWindowContent/",type:"POST",data:this.infomodel,dataType:"html",success:function(html){infobox.setContent("<div class='infobox-wrapper'><div class='map-infobox info-window-img'>"+html+"</div></div>");$(".info-window-img img[data-remote-url]").dynamicImages(".info-window-img");$("img[src='/res/img/close.png']").css({"z-index":10,"position":"absolute","cursor":"pointer","top":0,"right":0,"margin":"-11px -8px"});$(".addremove-shortlist").click(function(event){sn.app.shortListTriggered(event,event.currentTarget);});$(".addremove-shortlist .icon-heart-1").stop().fadeTo("fast",0.65);}});}
else if(item.markerType==="destination"){this.infomodel.LocationId=this.infomodel.id;$.ajax({url:"/Listing/GetDestinationMapInfoWindowContent/",type:"POST",data:this.infomodel,dataType:"html",success:function(html){infobox.setContent("<div class='infobox-wrapper'><div class='map-infobox'>"+html+"</div></div>");$("img[src='/res/img/close.png']").css({"z-index":10,"position":"absolute","cursor":"pointer","top":0,"right":0,"margin":"-11px -8px"});}});}});sn.app.map.createToolTip(marker,marker.infomodel.name,map);sn.app.map.Markers.push(marker);},EnableShowLabelHover:false,updateMarkerAvailability:function(spid,isavailable){var r=$.grep(sn.app.map.Markers,function(e){return(e!=null);});if(r.length>0){var themarker=r[0];if(themarker.infomodel.spid===spid){if(themarker.infomodel.spid>0){themarker.infomodel.instantbook=isavailable;if(isavailable){themarker.setContent("'<i class=\"icon-location map-marker "+themarker.infomodel.markerType+" available\"></i>");}
else{themarker.setContent("'<i class=\"icon-location map-marker "+themarker.infomodel.markerType+" onrequest\"></i>");}}}}},refresh:function(){var maxItems=30;if(sn.app.map.Data.length<30){maxItems=sn.app.map.Data.length;}
for(var i=0;i<maxItems;i++){var item=sn.app.map.Data[i];sn.app.map.createMarker(sn.app.map.MapInstances[0],item);}},addThingsToDoMarkers:function(){if(typeof contentResults!=="undefined")
for(var i=0;i<contentResults.length;i++){var item=contentResults[i];sn.app.map.createContentMarker(sn.app.map.MapInstances[0],item);}},clearThingsToDoMarkers:function(){for(var i=0;i<sn.app.map.ContentMarkers.length;i++){var marker=sn.app.map.ContentMarkers[i];marker.setMap(null);}
sn.app.map.ContentMarkers.length=0;},clearMarkers:function(){for(var i=0;i<sn.app.map.Markers.length;i++){var marker=sn.app.map.Markers[i];marker.setMap(null);}
sn.app.map.Markers.length=0;},clearMarkersAvailability:function(){for(var i=0;i<sn.app.map.Markers.length;i++){var marker=sn.app.map.Markers[i];marker.setIcon("/res/img/gmaps/marker-blue-drop.png");marker.infomodel.instantbook=false;}},initMap:function(mapZoomLevel,enableDragSearch,fnSearch){if(typeof(results)=="undefined"||results.length===0){sn.app.map.Data=[];}
else{sn.app.map.Data=results;}
sn.app.map.Zoom=mapZoomLevel;sn.app.map.init(mapZoomLevel,enableDragSearch,fnSearch);},refreshMap:function(){if(typeof(results)=="undefined"||results.length===0){sn.app.map.Data=[];}
else{sn.app.map.Data=results;}
sn.app.map.refresh();},searchThingsToDoAndRefresh:function(map){$("#mapNorthEastLat").val(map.getBounds().getNorthEast().lat());$("#mapNorthEastLng").val(map.getBounds().getNorthEast().lng());$("#mapSouthWestLat").val(map.getBounds().getSouthWest().lat());$("#mapSouthWestLng").val(map.getBounds().getSouthWest().lng());sn.app.contentlisting.search(false,true);sn.app.map.clearThingsToDoMarkers();},searchAndRefresh:function(map){$("#mapNorthEastLat").val(map.getBounds().getNorthEast().lat());$("#mapNorthEastLng").val(map.getBounds().getNorthEast().lng());$("#mapSouthWestLat").val(map.getBounds().getSouthWest().lat());$("#mapSouthWestLng").val(map.getBounds().getSouthWest().lng());if(sn.app.map.EnableDragSearch){this.Service.getResults(this.Service);sn.app.map.readyToRefresh(false);}
sn.app.map.readyToRefresh(true);},updateMarkerActivity:function(spid){var theMap=sn.app.map.MapInstances[0];if(theMap){var r=$.grep(sn.app.map.Markers,function(e){return(e!=null);});if(r.length>0){var themarker=r[0];if(themarker.infomodel.spid===spid){if(themarker.infomodel.spid>0){var m=new MarkerWithLabel({position:new google.maps.LatLng(themarker.infomodel.latitude,themarker.infomodel.longitude),icon:{path:google.maps.SymbolPath.CIRCLE,scale:0},map:theMap,draggable:true,labelAnchor:new google.maps.Point(0,10),labelClass:"activity",id:spid,labelContent:"Booked!"});console.log(m);console.log(spid);window.setTimeout(function(){m.setMap(null);},5000);}}}}}};sn.app.facebook=sn.app.facebook||{init:function(){this.InitializeFacebook();},InitializeFacebook:function(){window.fbAsyncInit=function(){FB.init({appId:'175433639141136',xfbml:true,version:'v2.6'});};((function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(d.getElementById(id)){return;}
js=d.createElement(s);js.id=id;js.src="//connect.facebook.net/en_US/sdk.js";fjs.parentNode.insertBefore(js,fjs);})(document,'script','facebook-jssdk'));}};var Utility=(function(){function Utility(){}
Utility.GetWindowHeight=function(){var windowHeight=(window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight);return windowHeight;};Utility.GetWindowWidth=function(){var windowWidth=(window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth);return windowWidth;};Utility.HasClass=function(ele,cls){var classMatch=ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));return classMatch!=null&&classMatch.length>0;};Utility.AddClass=function(ele,cls){if(ele!=null){if(!this.HasClass(ele,cls)){ele.className+=" "+cls;}}};Utility.RemoveClass=function(ele,cls){if(ele!=null){if(this.HasClass(ele,cls)){var reg=new RegExp('(\\s|^)'+cls+'(\\s|$)');ele.className=ele.className.replace(reg,' ');}}};Utility.Offset=function(el){var rect=el.getBoundingClientRect(),scrollLeft=window.pageXOffset||document.documentElement.scrollLeft,scrollTop=window.pageYOffset||document.documentElement.scrollTop;return{top:rect.top+scrollTop,left:rect.left+scrollLeft};};Utility.restrictToPhoneNumber=function(event){var k;document.all?k=event.keyCode:k=event.which;return(k<58||(k>90&&k<106)||k==107);};Utility.showLoader=function(el,message){if(message===void 0){message="";}
Utility.AddClass(document.getElementById("loader-wrapper"),"show");if(message!=""){var messageEl=document.getElementById("loadermessage");if(messageEl!=null){messageEl.innerText=message;}}};Utility.hideLoader=function(el){Utility.RemoveClass(document.getElementById("loader-wrapper"),"show");var messageEl=document.getElementById("loadermessage");if(messageEl!=null){messageEl.innerText="";}};Utility.getDeviceContext=function(){var windowWidth=this.GetWindowWidth();if(windowWidth<768){return DeviceContext.Mobile;}
else{if(windowWidth<1200){return DeviceContext.Tablet;}
else{return DeviceContext.Desktop;}}};Utility.currentYPosition=function(){if(window.pageYOffset)
return window.pageYOffset;if(document.documentElement&&document.documentElement.scrollTop)
return document.documentElement.scrollTop;if(document.body.scrollTop)
return document.body.scrollTop;return 0;};Utility.elmYPosition=function(el){var y=el.offsetTop;return y;};Utility.smoothScroll=function(el,offset){if(offset===void 0){offset=0;}
var startY=Utility.currentYPosition();var stopY=Utility.elmYPosition(el)-offset;var distance=stopY>startY?stopY-startY:startY-stopY;console.log("page offset: "+window.pageYOffset+" startY: "+startY+" stopY: "+stopY+" distance: "+distance);if(distance==0||startY<stopY){return;}
var speed=Math.round(distance/100);if(speed>=20)
speed=20;var step=Math.round(distance/50);var leapY=stopY>startY?startY+step:startY-step;var timer=0;if(stopY>startY){for(var i=startY;i<stopY;i+=step){setTimeout("window.scrollTo(0, "+leapY+")",timer*speed);leapY+=step;if(leapY>stopY)
leapY=stopY;timer++;}
return;}
for(var i=startY;i>stopY;i-=step){setTimeout("window.scrollTo(0, "+leapY+")",timer*speed);leapY-=step;if(leapY<stopY)
leapY=stopY;timer++;}};Utility.getFormattedDate=function(date){var month=date.getMonth()+1<10?"0"+(date.getMonth()+1):date.getMonth()+1;var day=date.getDate()<10?"0"+date.getDate():date.getDate();var year=date.getFullYear();return day+"/"+month+"/"+year;};Utility.getWindowHeight=function(){if(!navigator.userAgent.match(/iphone|ipod|ipad/i)){return window.innerHeight;}
else{var _dims={w:0,h:0};var _axis=void 0;_axis=window.innerHeight>window.innerWidth?0:90;var ruler=document.createElement('div');ruler.style.position='fixed';ruler.style.height='100vh';ruler.style.width="0";ruler.style.top="0";document.documentElement.appendChild(ruler);_dims.w=_axis===90?ruler.offsetHeight:window.innerWidth;_dims.h=_axis===90?window.innerWidth:ruler.offsetHeight;document.documentElement.removeChild(ruler);ruler=null;console.log("window.innerHeight = "+window.innerHeight);if(Math.abs(_axis)!==90){console.log("ios height = "+_dims.h);return _dims.h;}
console.log("ios height = "+_dims.w);return _dims.w;}};Utility.addUrlParam=function(key,value){key=encodeURI(key);value=encodeURI(value);var kvp=document.location.search.substr(1).split('&');var i=kvp.length;var x;while(i--){x=kvp[i].split('=');if(x[0]==key){x[1]=value;kvp[i]=x.join('=');break;}}
if(i<0){kvp[kvp.length]=[key,value].join('=');}
document.location.search=kvp.join('&');};Utility.getUrlParam=function(key,urladdress){if(urladdress===void 0){urladdress="";}
if(urladdress=="")
urladdress=self.location.toString();urladdress=window.location.search.substring(1);var vars=urladdress.split("&");var query_string={};for(var i=0;i<vars.length;i++){var pair=vars[i].split("=");var keypart=decodeURIComponent(pair[0]);var value=decodeURIComponent(pair[1]);if(typeof query_string[keypart]==="undefined"){query_string[keypart]=decodeURIComponent(value);}
else if(typeof query_string[keypart]==="string"){var arr=[query_string[keypart],decodeURIComponent(value)];query_string[keypart]=arr;}
else{query_string[keypart].push(decodeURIComponent(value));}}
return query_string[key];};Utility.getCookie=function(name){var nameLenPlus=(name.length+1);return document.cookie.split(';').map(function(c){return c.trim();}).filter(function(cookie){return cookie.substring(0,nameLenPlus)===name+"=";}).map(function(cookie){return decodeURIComponent(cookie.substring(nameLenPlus));})[0]||null;};Utility.setCookie=function(name,val,days){var date=new Date();var value=val;date.setTime(date.getTime()+(days*24*60*60*1000));document.cookie=name+"="+value+"; expires="+date.toUTCString()+"; path=/";};return Utility;}());var MD5;(function(MD5){function md5cycle(x,k){var a=x[0],b=x[1],c=x[2],d=x[3];a=ff(a,b,c,d,k[0],7,-680876936);d=ff(d,a,b,c,k[1],12,-389564586);c=ff(c,d,a,b,k[2],17,606105819);b=ff(b,c,d,a,k[3],22,-1044525330);a=ff(a,b,c,d,k[4],7,-176418897);d=ff(d,a,b,c,k[5],12,1200080426);c=ff(c,d,a,b,k[6],17,-1473231341);b=ff(b,c,d,a,k[7],22,-45705983);a=ff(a,b,c,d,k[8],7,1770035416);d=ff(d,a,b,c,k[9],12,-1958414417);c=ff(c,d,a,b,k[10],17,-42063);b=ff(b,c,d,a,k[11],22,-1990404162);a=ff(a,b,c,d,k[12],7,1804603682);d=ff(d,a,b,c,k[13],12,-40341101);c=ff(c,d,a,b,k[14],17,-1502002290);b=ff(b,c,d,a,k[15],22,1236535329);a=gg(a,b,c,d,k[1],5,-165796510);d=gg(d,a,b,c,k[6],9,-1069501632);c=gg(c,d,a,b,k[11],14,643717713);b=gg(b,c,d,a,k[0],20,-373897302);a=gg(a,b,c,d,k[5],5,-701558691);d=gg(d,a,b,c,k[10],9,38016083);c=gg(c,d,a,b,k[15],14,-660478335);b=gg(b,c,d,a,k[4],20,-405537848);a=gg(a,b,c,d,k[9],5,568446438);d=gg(d,a,b,c,k[14],9,-1019803690);c=gg(c,d,a,b,k[3],14,-187363961);b=gg(b,c,d,a,k[8],20,1163531501);a=gg(a,b,c,d,k[13],5,-1444681467);d=gg(d,a,b,c,k[2],9,-51403784);c=gg(c,d,a,b,k[7],14,1735328473);b=gg(b,c,d,a,k[12],20,-1926607734);a=hh(a,b,c,d,k[5],4,-378558);d=hh(d,a,b,c,k[8],11,-2022574463);c=hh(c,d,a,b,k[11],16,1839030562);b=hh(b,c,d,a,k[14],23,-35309556);a=hh(a,b,c,d,k[1],4,-1530992060);d=hh(d,a,b,c,k[4],11,1272893353);c=hh(c,d,a,b,k[7],16,-155497632);b=hh(b,c,d,a,k[10],23,-1094730640);a=hh(a,b,c,d,k[13],4,681279174);d=hh(d,a,b,c,k[0],11,-358537222);c=hh(c,d,a,b,k[3],16,-722521979);b=hh(b,c,d,a,k[6],23,76029189);a=hh(a,b,c,d,k[9],4,-640364487);d=hh(d,a,b,c,k[12],11,-421815835);c=hh(c,d,a,b,k[15],16,530742520);b=hh(b,c,d,a,k[2],23,-995338651);a=ii(a,b,c,d,k[0],6,-198630844);d=ii(d,a,b,c,k[7],10,1126891415);c=ii(c,d,a,b,k[14],15,-1416354905);b=ii(b,c,d,a,k[5],21,-57434055);a=ii(a,b,c,d,k[12],6,1700485571);d=ii(d,a,b,c,k[3],10,-1894986606);c=ii(c,d,a,b,k[10],15,-1051523);b=ii(b,c,d,a,k[1],21,-2054922799);a=ii(a,b,c,d,k[8],6,1873313359);d=ii(d,a,b,c,k[15],10,-30611744);c=ii(c,d,a,b,k[6],15,-1560198380);b=ii(b,c,d,a,k[13],21,1309151649);a=ii(a,b,c,d,k[4],6,-145523070);d=ii(d,a,b,c,k[11],10,-1120210379);c=ii(c,d,a,b,k[2],15,718787259);b=ii(b,c,d,a,k[9],21,-343485551);x[0]=add32(a,x[0]);x[1]=add32(b,x[1]);x[2]=add32(c,x[2]);x[3]=add32(d,x[3]);}
function cmn(q,a,b,x,s,t){a=add32(add32(a,q),add32(x,t));return add32((a<<s)|(a>>>(32-s)),b);}
function ff(a,b,c,d,x,s,t){return cmn((b&c)|((~b)&d),a,b,x,s,t);}
function gg(a,b,c,d,x,s,t){return cmn((b&d)|(c&(~d)),a,b,x,s,t);}
function hh(a,b,c,d,x,s,t){return cmn(b^c^d,a,b,x,s,t);}
function ii(a,b,c,d,x,s,t){return cmn(c^(b|(~d)),a,b,x,s,t);}
function md51(s){var txt='';var n=s.length,state=[1732584193,-271733879,-1732584194,271733878],i;for(i=64;i<=s.length;i+=64){md5cycle(state,md5blk(s.substring(i-64,i)));}
s=s.substring(i-64);var tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i=0;i<s.length;i++)
tail[i>>2]|=s.charCodeAt(i)<<((i%4)<<3);tail[i>>2]|=0x80<<((i%4)<<3);if(i>55){md5cycle(state,tail);for(i=0;i<16;i++)
tail[i]=0;}
tail[14]=n*8;md5cycle(state,tail);return state;}
function md5blk(s){var md5blks=[],i;for(i=0;i<64;i+=4){md5blks[i>>2]=s.charCodeAt(i)+(s.charCodeAt(i+1)<<8)+(s.charCodeAt(i+2)<<16)+(s.charCodeAt(i+3)<<24);}
return md5blks;}
var hex_chr='0123456789abcdef'.split('');function rhex(n){var s='',j=0;for(;j<4;j++)
s+=hex_chr[(n>>(j*8+4))&0x0F]+hex_chr[(n>>(j*8))&0x0F];return s;}
function hex(x){for(var i=0;i<x.length;i++)
x[i]=rhex(x[i]);return x.join('');}
function md5(s){return hex(md51(s));}
var add32=function(a,b){return(a+b)&0xFFFFFFFF;};if(md5('hello')!='5d41402abc4b2a76b9719d911017c592'){add32=function(x,y){var lsw=(x&0xFFFF)+(y&0xFFFF),msw=(x>>16)+(y>>16)+(lsw>>16);return(msw<<16)|(lsw&0xFFFF);};}
MD5.encrypt=function(s){return md5(s);};})(MD5||(MD5={}));var ImageSizeEnum;(function(ImageSizeEnum){ImageSizeEnum[ImageSizeEnum["Small"]=0]="Small";ImageSizeEnum[ImageSizeEnum["Medium"]=1]="Medium";ImageSizeEnum[ImageSizeEnum["Large"]=2]="Large";})(ImageSizeEnum||(ImageSizeEnum={}));var ImageSize=(function(){function ImageSize(){}
return ImageSize;}());var GalleryImage=(function(){function GalleryImage(){this.ImageSizes=[];}
return GalleryImage;}());var Gallery=(function(){function Gallery(json){this.activeImagePosition=0;this.galleryImages=[];this.translateX=0;this.preloadQuantity=5;this.galleryOpen=false;this.galleryImages=json;this.prev=document.getElementById("Gallery-Prev");this.next=document.getElementById("Gallery-Next");this.close=document.getElementById("Gallery-Close");this.heroImage=document.getElementById("Gallery-Hero-Image");this.mainImage=document.getElementById("Gallery-Main-Image");this.galleryThumbs=document.getElementById("Gallery-Thumbs");this.galleryFooter=document.getElementById("Gallery-Footer");this.galleryContainer=document.getElementById("Gallery-Container");this.galleryPreload=document.getElementById("Gallery-Preload");this.galleryImageDescription=document.getElementById("Gallery-Image-Description");this.init();}
Gallery.prototype.init=function(){this.galleryThumbs.innerHTML="";for(var i_1=0;i_1<this.galleryImages.length;i_1++){var image=this.galleryImages[i_1];var li=document.createElement("li");if(i_1==0){li.className="active";}
var img=document.createElement("img");img.alt=image.Description;img.id="GalleryImage-"+i_1;img.className="gallery-thumb lazyload";img.setAttribute("sizes","(min-width: 361px) 100vw, (min-width: 481px) 100vw, "+
"(min-width: 769px) 100vw, "+
"(min-width: 1025px) 100vw");img.setAttribute("data-srcset",image.ImageSizes[0].Url+" 360w, "+
image.ImageSizes[1].Url+" 640w, "+
image.ImageSizes[2].Url+" 1024w");img.setAttribute("src","/res/img/placeholder.gif");img.setAttribute("data-src",image.ImageSizes[0].Url);li.appendChild(img);this.galleryThumbs.appendChild(li);}
this.preload();this.configureEventListeners();};Gallery.prototype.tryClose=function(e,gallery){var targetClass=(e.target).className;if(targetClass!==""){var validCloseClasses="modal-container modal-header modal-content modal-footer";if(validCloseClasses.indexOf(targetClass)!==-1){gallery.closeGallery(gallery);}}};Gallery.prototype.configureEventListeners=function(){var _this=this;this.prev["gallery"]=this;this.next["gallery"]=this;this.close["gallery"]=this;this.prev.addEventListener("click",this.onPreviousClick);this.next.addEventListener("click",this.onNextClick);this.close.addEventListener("click",this.onCloseClick);this.heroImage.addEventListener("click",function(e){return _this.onOpenClick();});document.addEventListener("keydown",function(e){return _this.onKeyDown(e,_this);});this.galleryContainer.addEventListener("click",function(e){return _this.tryClose(e,_this);});var thumbnails=document.getElementsByClassName("gallery-thumb");var _loop_1=function(i_2){thumbnails[i_2].addEventListener("click",function(){return _this.onOpenClick(i_2);});};for(var i_2=0;i_2<thumbnails.length;i_2++){_loop_1(i_2);}
var closes=document.getElementsByClassName("gallery-modal-close");for(var i_3=0;i_3<closes.length;i_3++){closes[i_3].addEventListener("click",function(e){return _this.tryClose(e,_this);});}};Gallery.prototype.onKeyDown=function(e,gallery){if(e.keyCode==27){gallery.closeGallery(gallery);}};Gallery.prototype.onOpenClick=function(index){if(index===void 0){index=0;}
this.galleryOpen=true;this.galleryContainer.style.display="block";this.galleryContainer.style.position="fixed";this.activeImagePosition=index;this.handleImageChange();this.preload();this.hideScrollbar();};Gallery.prototype.hideScrollbar=function(){document.body.classList.add("scroll-hide");};Gallery.prototype.showScrollbar=function(){document.body.classList.add("scroll-show");};Gallery.prototype.onPreviousClick=function(e){var gallery=e.currentTarget["gallery"];if(gallery.activeImagePosition>0){gallery.activeImagePosition--;gallery.handleImageChange();}};Gallery.prototype.onNextClick=function(e){var gallery=e.currentTarget["gallery"];if(gallery.activeImagePosition<gallery.galleryThumbs.children.length-1){gallery.activeImagePosition++;gallery.handleImageChange();gallery.preload();}};Gallery.prototype.onCloseClick=function(e){var gallery=e.currentTarget["gallery"];gallery.closeGallery(gallery);};Gallery.prototype.closeGallery=function(gallery){if(!gallery.galleryOpen){return;}
gallery.galleryOpen=false;gallery.galleryContainer.style.display="none";gallery.translateX=0;gallery.galleryThumbs.style.transform="translateX("+this.translateX+"px)";gallery.showScrollbar();if(gallery.onClose){gallery.onClose();}};Gallery.prototype.preload=function(){if(this.activeImagePosition<this.galleryImages.length-this.preloadQuantity){this.galleryPreload.innerHTML="";for(var i_4=this.activeImagePosition;i_4<this.activeImagePosition+this.preloadQuantity;i_4++){var image=this.galleryImages[i_4];var imageId="GalleryImage-"+i_4;var img=document.createElement("img");img.alt=image.Description;img.id="GalleryImage-"+i_4;img.className="lazyload";img.setAttribute("sizes","(min-width: 361px) 100vw, (min-width: 481px) 100vw, "+
"(min-width: 769px) 100vw, "+
"(min-width: 1025px) 100vw");img.setAttribute("data-srcset",image.ImageSizes[0].Url+" 360w, "+
image.ImageSizes[1].Url+" 640w, "+
image.ImageSizes[2].Url+" 1024w");img.setAttribute("src","/res/img/placeholder.gif");this.galleryPreload.appendChild(img);lazySizes.loader.unveil(img);}}};Gallery.prototype.handleImageChange=function(){var isIEOrEdge=/msie\s|trident\/|edge\//i.test(window.navigator.userAgent);var image=this.galleryImages[this.activeImagePosition];var imgTag="<img alt=\""+image.Description+"\" "+
"sizes=\"(min-width: 361px) 100vw, (min-width: 481px) 100vw, (min-width: 769px) 100vw, (min-width: 1025px) 100vw\" "+
"data-srcset=\""+image.ImageSizes[0].Url+" 360w, "+
image.ImageSizes[1].Url+" 640w, "+
image.ImageSizes[2].Url+" 1024w\" "+
"data-src=\""+image.ImageSizes[2].Url+"\" "+
"src=\"/res/img/placeholder.gif\" "+
"class=\"lazyload\" "+
"/>";if(isIEOrEdge){imgTag="<img alt=\""+image.Description+"\" "+
"data-src=\""+image.ImageSizes[2].Url+"\" "+
"src=\"/res/img/placeholder.gif\" "+
"class=\"lazyload\" "+
"/>";}
this.mainImage.innerHTML=imgTag;this.galleryImageDescription.innerText=image.Description;this.scrollThumbnails();};Gallery.prototype.scrollThumbnails=function(){var position=20;var visibleThumbsWidth=this.galleryFooter.offsetWidth;var middle=visibleThumbsWidth/2;var liThumbs=this.galleryThumbs.getElementsByTagName("li");var thumbWidth=liThumbs[0].offsetWidth;var style=window.getComputedStyle?getComputedStyle(liThumbs[0],null):null;var thumbMargin=style?parseInt(style.marginLeft)*2:0;var clickedImageLeftPosition=liThumbs[this.activeImagePosition].offsetLeft;for(var i_5=0;i_5<liThumbs.length;i_5++){liThumbs[i_5].classList.remove("active");}
liThumbs[this.activeImagePosition].classList.add("active");if(clickedImageLeftPosition<middle){this.translateX=0;}
else{this.translateX=clickedImageLeftPosition-middle;}
var maxTranslateX=this.galleryThumbs.offsetWidth-visibleThumbsWidth;if(this.translateX<maxTranslateX){this.galleryThumbs.style.transform="translateX(-"+this.translateX+"px)";}
else{this.galleryThumbs.style.transform="translateX(-"+maxTranslateX+"px)";}};return Gallery;}());var Reviews=(function(){function Reviews(reviewsContainerElementId,showMoreElementId,readMoreClassName){var _this=this;this._itemsToSkip=0;this._reviewsContainer=document.getElementById(reviewsContainerElementId);if(this._reviewsContainer==null)
return;this._showMore=document.getElementById(showMoreElementId);this._readMoreClassName=readMoreClassName;this._itemsPerPage=parseInt(this._reviewsContainer.getAttribute("data-items-per-page"));this._hasMoreReviews=!!(this._reviewsContainer.getAttribute("data-more"));this._spId=parseInt(this._reviewsContainer.getAttribute("data-spId"));if(this._showMore!=null){this._showMore.addEventListener("click",function(e){return _this.onGetReviews(e);});}
this.addReadMoreEventListener();}
Reviews.prototype.onGetReviews=function(e){if(this._reviewsContainer==null)
return;e.preventDefault();this._itemsToSkip+=this._itemsPerPage;var model={ItemsToSkip:this._itemsToSkip,SpId:this._spId};var reviewsContainer=this._reviewsContainer;var showMore=this._showMore;var _thisService=this;$.ajax({type:"POST",url:"/establishment/getmorereviews/",data:model,beforeSend:function(){Utility.showLoader(null);}}).done(function(data){if(!data.hasMoreReviews){Utility.AddClass(showMore,"hide");}
if(data.results!==""){$(data.results).appendTo(reviewsContainer);_thisService.addReadMoreEventListener();}
Utility.hideLoader(null);});};Reviews.prototype.onReadMoreLess=function(el){if(el.innerText.toLowerCase()==="read more"){el.innerText="Read less";Utility.AddClass(el,"read-less");el.previousElementSibling.innerHTML=el.previousElementSibling.getAttribute("data-full-review");}
else{el.innerText="Read more";Utility.RemoveClass(el,"read-less");el.previousElementSibling.innerHTML=el.previousElementSibling.getAttribute("data-truncated-review");}};Reviews.prototype.addReadMoreEventListener=function(){var _this=this;var readMoreLinks=document.getElementsByClassName(this._readMoreClassName);var _loop_1=function(i_1){var readMoreEl=readMoreLinks[i_1];if(!Utility.HasClass(readMoreEl,"clickadded")){Utility.AddClass(readMoreEl,"clickadded");readMoreEl.addEventListener("click",function(){return _this.onReadMoreLess(readMoreEl);});}};for(var i_1=0;i_1<readMoreLinks.length;i_1++){_loop_1(i_1);}};return Reviews;}());/*!lazysizes - v4.0.2*/!function(a,b){var c=function(){b(a.lazySizes),a.removeEventListener("lazyunveilread",c,!0)};b=b.bind(null,a,a.document),"object"==typeof module&&module.exports?b(require("lazysizes"),require("../fix-ios-sizes/fix-ios-sizes")):a.lazySizes?c():a.addEventListener("lazyunveilread",c,!0)}(window,function(a,b,c){"use strict";var d,e=c&&c.cfg||a.lazySizesConfig,f=b.createElement("img"),g="sizes"in f&&"srcset"in f,h=/\s+\d+h/g,i=function(){var a=/\s+(\d+)(w|h)\s+(\d+)(w|h)/,c=Array.prototype.forEach;return function(d){var e=b.createElement("img"),f=function(b){var c,d,e=b.getAttribute(lazySizesConfig.srcsetAttr);e&&((d=e.match(a))&&(c="w"==d[2]?d[1]/d[3]:d[3]/d[1],c&&b.setAttribute("data-aspectratio",c)),b.setAttribute(lazySizesConfig.srcsetAttr,e.replace(h,"")))},g=function(a){var b=a.target.parentNode;b&&"PICTURE"==b.nodeName&&c.call(b.getElementsByTagName("source"),f),f(a.target)},i=function(){e.currentSrc&&b.removeEventListener("lazybeforeunveil",g)};d[1]&&(b.addEventListener("lazybeforeunveil",g),e.onload=i,e.onerror=i,e.srcset="data:,a 1w 1h",e.complete&&i())}}();if(e||(e={},a.lazySizesConfig=e),e.supportsType||(e.supportsType=function(a){return!a}),!a.picturefill&&!e.pf){if(a.HTMLPictureElement&&g)return b.msElementsFromPoint&&i(navigator.userAgent.match(/Edge\/(\d+)/)),void(e.pf=function(){});e.pf=function(b){var c,e;if(!a.picturefill)for(c=0,e=b.elements.length;e>c;c++)d(b.elements[c])},d=function(){var f=function(a,b){return a.w-b.w},i=/^\s*\d+\.*\d*px\s*$/,j=function(a){var b,c,d=a.length,e=a[d-1],f=0;for(f;d>f;f++)if(e=a[f],e.d=e.w/a.w,e.d>=a.d){!e.cached&&(b=a[f-1])&&b.d>a.d-.13*Math.pow(a.d,2.2)&&(c=Math.pow(b.d-.6,1.6),b.cached&&(b.d+=.15*c),b.d+(e.d-a.d)*c>a.d&&(e=b));break}return e},k=function(){var a,b=/(([^,\s].[^\s]+)\s+(\d+)w)/g,c=/\s/,d=function(b,c,d,e){a.push({c:c,u:d,w:1*e})};return function(e){return a=[],e=e.trim(),e.replace(h,"").replace(b,d),a.length||!e||c.test(e)||a.push({c:e,u:e,w:99}),a}}(),l=function(){l.init||(l.init=!0,addEventListener("resize",function(){var a,c=b.getElementsByClassName("lazymatchmedia"),e=function(){var a,b;for(a=0,b=c.length;b>a;a++)d(c[a])};return function(){clearTimeout(a),a=setTimeout(e,66)}}()))},m=function(b,d){var f,g=b.getAttribute("srcset")||b.getAttribute(e.srcsetAttr);!g&&d&&(g=b._lazypolyfill?b._lazypolyfill._set:b.getAttribute(e.srcAttr)||b.getAttribute("src")),b._lazypolyfill&&b._lazypolyfill._set==g||(f=k(g||""),d&&b.parentNode&&(f.isPicture="PICTURE"==b.parentNode.nodeName.toUpperCase(),f.isPicture&&a.matchMedia&&(c.aC(b,"lazymatchmedia"),l())),f._set=g,Object.defineProperty(b,"_lazypolyfill",{value:f,writable:!0}))},n=function(b){var d=a.devicePixelRatio||1,e=c.getX&&c.getX(b);return Math.min(e||d,2.5,d)},o=function(b){return a.matchMedia?(o=function(a){return!a||(matchMedia(a)||{}).matches})(b):!b},p=function(a){var b,d,g,h,k,l,p;if(h=a,m(h,!0),k=h._lazypolyfill,k.isPicture)for(d=0,b=a.parentNode.getElementsByTagName("source"),g=b.length;g>d;d++)if(e.supportsType(b[d].getAttribute("type"),a)&&o(b[d].getAttribute("media"))){h=b[d],m(h),k=h._lazypolyfill;break}return k.length>1?(p=h.getAttribute("sizes")||"",p=i.test(p)&&parseInt(p,10)||c.gW(a,a.parentNode),k.d=n(a),!k.src||!k.w||k.w<p?(k.w=p,l=j(k.sort(f)),k.src=l):l=k.src):l=k[0],l},q=function(a){if(!g||!a.parentNode||"PICTURE"==a.parentNode.nodeName.toUpperCase()){var b=p(a);b&&b.u&&a._lazypolyfill.cur!=b.u&&(a._lazypolyfill.cur=b.u,b.cached=!0,a.setAttribute(e.srcAttr,b.u),a.setAttribute("src",b.u))}};return q.parse=k,q}(),e.loadedClass&&e.loadingClass&&!function(){var a=[];['img[sizes$="px"][srcset].',"picture > img:not([srcset])."].forEach(function(b){a.push(b+e.loadedClass),a.push(b+e.loadingClass)}),e.pf({elements:b.querySelectorAll(a.join(", "))})}()}});/*!lazysizes - v5.1.2*/!function(a,b){var c=b(a,a.document);a.lazySizes=c,"object"==typeof module&&module.exports&&(module.exports=c)}("undefined"!=typeof window?window:{},function(a,b){"use strict";var c,d;if(function(){var b,c={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",errorClass:"lazyerror",autosizesClass:"lazyautosizes",srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:!0,expFactor:1.5,hFac:.8,loadMode:2,loadHidden:!0,ricTimeout:0,throttleDelay:125};d=a.lazySizesConfig||a.lazysizesConfig||{};for(b in c)b in d||(d[b]=c[b])}(),!b||!b.getElementsByClassName)return{init:function(){},cfg:d,noSupport:!0};var e=b.documentElement,f=a.Date,g=a.HTMLPictureElement,h="addEventListener",i="getAttribute",j=a[h],k=a.setTimeout,l=a.requestAnimationFrame||k,m=a.requestIdleCallback,n=/^picture$/i,o=["load","error","lazyincluded","_lazyloaded"],p={},q=Array.prototype.forEach,r=function(a,b){return p[b]||(p[b]=new RegExp("(\\s|^)"+b+"(\\s|$)")),p[b].test(a[i]("class")||"")&&p[b]},s=function(a,b){r(a,b)||a.setAttribute("class",(a[i]("class")||"").trim()+" "+b)},t=function(a,b){var c;(c=r(a,b))&&a.setAttribute("class",(a[i]("class")||"").replace(c," "))},u=function(a,b,c){var d=c?h:"removeEventListener";c&&u(a,b),o.forEach(function(c){a[d](c,b)})},v=function(a,d,e,f,g){var h=b.createEvent("Event");return e||(e={}),e.instance=c,h.initEvent(d,!f,!g),h.detail=e,a.dispatchEvent(h),h},w=function(b,c){var e;!g&&(e=a.picturefill||d.pf)?(c&&c.src&&!b[i]("srcset")&&b.setAttribute("srcset",c.src),e({reevaluate:!0,elements:[b]})):c&&c.src&&(b.src=c.src)},x=function(a,b){return(getComputedStyle(a,null)||{})[b]},y=function(a,b,c){for(c=c||a.offsetWidth;c<d.minSize&&b&&!a._lazysizesWidth;)c=b.offsetWidth,b=b.parentNode;return c},z=function(){var a,c,d=[],e=[],f=d,g=function(){var b=f;for(f=d.length?e:d,a=!0,c=!1;b.length;)b.shift()();a=!1},h=function(d,e){a&&!e?d.apply(this,arguments):(f.push(d),c||(c=!0,(b.hidden?k:l)(g)))};return h._lsFlush=g,h}(),A=function(a,b){return b?function(){z(a)}:function(){var b=this,c=arguments;z(function(){a.apply(b,c)})}},B=function(a){var b,c=0,e=d.throttleDelay,g=d.ricTimeout,h=function(){b=!1,c=f.now(),a()},i=m&&g>49?function(){m(h,{timeout:g}),g!==d.ricTimeout&&(g=d.ricTimeout)}:A(function(){k(h)},!0);return function(a){var d;(a=!0===a)&&(g=33),b||(b=!0,d=e-(f.now()-c),d<0&&(d=0),a||d<9?i():k(i,d))}},C=function(a){var b,c,d=99,e=function(){b=null,a()},g=function(){var a=f.now()-c;a<d?k(g,d-a):(m||e)(e)};return function(){c=f.now(),b||(b=k(g,d))}},D=function(){var g,m,o,p,y,D,F,G,H,I,J,K,L=/^img$/i,M=/^iframe$/i,N="onscroll"in a&&!/(gle|ing)bot/.test(navigator.userAgent),O=0,P=0,Q=0,R=-1,S=function(a){Q--,(!a||Q<0||!a.target)&&(Q=0)},T=function(a){return null==K&&(K="hidden"==x(b.body,"visibility")),K||!("hidden"==x(a.parentNode,"visibility")&&"hidden"==x(a,"visibility"))},U=function(a,c){var d,f=a,g=T(a);for(G-=c,J+=c,H-=c,I+=c;g&&(f=f.offsetParent)&&f!=b.body&&f!=e;)(g=(x(f,"opacity")||1)>0)&&"visible"!=x(f,"overflow")&&(d=f.getBoundingClientRect(),g=I>d.left&&H<d.right&&J>d.top-1&&G<d.bottom+1);return g},V=function(){var a,f,h,j,k,l,n,o,q,r,s,t,u=c.elements;if((p=d.loadMode)&&Q<8&&(a=u.length)){for(f=0,R++;f<a;f++)if(u[f]&&!u[f]._lazyRace)if(!N||c.prematureUnveil&&c.prematureUnveil(u[f]))ba(u[f]);else if((o=u[f][i]("data-expand"))&&(l=1*o)||(l=P),r||(r=!d.expand||d.expand<1?e.clientHeight>500&&e.clientWidth>500?500:370:d.expand,c._defEx=r,s=r*d.expFactor,t=d.hFac,K=null,P<s&&Q<1&&R>2&&p>2&&!b.hidden?(P=s,R=0):P=p>1&&R>1&&Q<6?r:O),q!==l&&(D=innerWidth+l*t,F=innerHeight+l,n=-1*l,q=l),h=u[f].getBoundingClientRect(),(J=h.bottom)>=n&&(G=h.top)<=F&&(I=h.right)>=n*t&&(H=h.left)<=D&&(J||I||H||G)&&(d.loadHidden||T(u[f]))&&(m&&Q<3&&!o&&(p<3||R<4)||U(u[f],l))){if(ba(u[f]),k=!0,Q>9)break}else!k&&m&&!j&&Q<4&&R<4&&p>2&&(g[0]||d.preloadAfterLoad)&&(g[0]||!o&&(J||I||H||G||"auto"!=u[f][i](d.sizesAttr)))&&(j=g[0]||u[f]);j&&!k&&ba(j)}},W=B(V),X=function(a){var b=a.target;if(b._lazyCache)return void delete b._lazyCache;S(a),s(b,d.loadedClass),t(b,d.loadingClass),u(b,Z),v(b,"lazyloaded")},Y=A(X),Z=function(a){Y({target:a.target})},$=function(a,b){try{a.contentWindow.location.replace(b)}catch(c){a.src=b}},_=function(a){var b,c=a[i](d.srcsetAttr);(b=d.customMedia[a[i]("data-media")||a[i]("media")])&&a.setAttribute("media",b),c&&a.setAttribute("srcset",c)},aa=A(function(a,b,c,e,f){var g,h,j,l,m,p;(m=v(a,"lazybeforeunveil",b)).defaultPrevented||(e&&(c?s(a,d.autosizesClass):a.setAttribute("sizes",e)),h=a[i](d.srcsetAttr),g=a[i](d.srcAttr),f&&(j=a.parentNode,l=j&&n.test(j.nodeName||"")),p=b.firesLoad||"src"in a&&(h||g||l),m={target:a},s(a,d.loadingClass),p&&(clearTimeout(o),o=k(S,2500),u(a,Z,!0)),l&&q.call(j.getElementsByTagName("source"),_),h?a.setAttribute("srcset",h):g&&!l&&(M.test(a.nodeName)?$(a,g):a.src=g),f&&(h||l)&&w(a,{src:g})),a._lazyRace&&delete a._lazyRace,t(a,d.lazyClass),z(function(){var b=a.complete&&a.naturalWidth>1;p&&!b||(b&&s(a,"ls-is-cached"),X(m),a._lazyCache=!0,k(function(){"_lazyCache"in a&&delete a._lazyCache},9)),"lazy"==a.loading&&Q--},!0)}),ba=function(a){if(!a._lazyRace){var b,c=L.test(a.nodeName),e=c&&(a[i](d.sizesAttr)||a[i]("sizes")),f="auto"==e;(!f&&m||!c||!a[i]("src")&&!a.srcset||a.complete||r(a,d.errorClass)||!r(a,d.lazyClass))&&(b=v(a,"lazyunveilread").detail,f&&E.updateElem(a,!0,a.offsetWidth),a._lazyRace=!0,Q++,aa(a,b,f,e,c))}},ca=C(function(){d.loadMode=3,W()}),da=function(){3==d.loadMode&&(d.loadMode=2),ca()},ea=function(){if(!m){if(f.now()-y<999)return void k(ea,999);m=!0,d.loadMode=3,W(),j("scroll",da,!0)}};return{_:function(){y=f.now(),c.elements=b.getElementsByClassName(d.lazyClass),g=b.getElementsByClassName(d.lazyClass+" "+d.preloadClass),j("scroll",W,!0),j("resize",W,!0),j("pageshow",function(a){if(a.persisted){var c=b.querySelectorAll("."+d.loadingClass);c.length&&c.forEach&&l(function(){c.forEach(function(a){a.complete&&ba(a)})})}}),a.MutationObserver?new MutationObserver(W).observe(e,{childList:!0,subtree:!0,attributes:!0}):(e[h]("DOMNodeInserted",W,!0),e[h]("DOMAttrModified",W,!0),setInterval(W,999)),j("hashchange",W,!0),["focus","mouseover","click","load","transitionend","animationend"].forEach(function(a){b[h](a,W,!0)}),/d$|^c/.test(b.readyState)?ea():(j("load",ea),b[h]("DOMContentLoaded",W),k(ea,2e4)),c.elements.length?(V(),z._lsFlush()):W()},checkElems:W,unveil:ba,_aLSL:da}}(),E=function(){var a,c=A(function(a,b,c,d){var e,f,g;if(a._lazysizesWidth=d,d+="px",a.setAttribute("sizes",d),n.test(b.nodeName||""))for(e=b.getElementsByTagName("source"),f=0,g=e.length;f<g;f++)e[f].setAttribute("sizes",d);c.detail.dataAttr||w(a,c.detail)}),e=function(a,b,d){var e,f=a.parentNode;f&&(d=y(a,f,d),e=v(a,"lazybeforesizes",{width:d,dataAttr:!!b}),e.defaultPrevented||(d=e.detail.width)&&d!==a._lazysizesWidth&&c(a,f,e,d))},f=function(){var b,c=a.length;if(c)for(b=0;b<c;b++)e(a[b])},g=C(f);return{_:function(){a=b.getElementsByClassName(d.autosizesClass),j("resize",g)},checkElems:g,updateElem:e}}(),F=function(){!F.i&&b.getElementsByClassName&&(F.i=!0,E._(),D._())};return k(function(){d.init&&F()}),c={cfg:d,autoSizer:E,loader:D,init:F,uP:w,aC:s,rC:t,hC:r,fire:v,gW:y,rAF:z}});var BaseViewModel=(function(){function BaseViewModel(){var bvm=this;bvm.currencyCode=ko.observable();bvm.currencySymbol=ko.observable();bvm.isUserLoggedIn=ko.observable();bvm.isStaff=ko.observable();bvm.isCorporateStaff=ko.observable();bvm.isCorporateAgent=ko.observable();bvm.userId=ko.observable();bvm.userName=ko.observable();bvm.userFirstname=ko.observable();bvm.userLastname=ko.observable();bvm.userEmail=ko.observable();bvm.userMobile=ko.observable();bvm.errors=ko.observableArray();bvm.isMobile=ko.observable(true);bvm.isTablet=ko.observable(false);bvm.isDesktop=ko.observable(false);bvm.showErrorCorrectionMessage=ko.observable(false);bvm.setScreenSize();window.onresize=function(){bvm.setScreenSize();};}
BaseViewModel.prototype.consolelog=function(message){if(!this.isLive)
console.log(message);};BaseViewModel.prototype.setScreenSize=function(){var ems=window.innerWidth/parseFloat(getComputedStyle(document.body)["font-size"]);if(ems<=30){this.isMobile(true);this.isTablet(false);this.isDesktop(false);}
else if(ems>30&&ems<=40){this.isMobile(false);this.isTablet(true);this.isDesktop(false);}
else{this.isMobile(false);this.isTablet(false);this.isDesktop(true);}};BaseViewModel.prototype.clearErrors=function(){if(this.errors!==null){this.errors([]);}
this.showErrorCorrectionMessage(false);$('.validationElement').removeClass('validationElement');};BaseViewModel.prototype.addErrors=function(errors){for(var _i=0,errors_1=errors;_i<errors_1.length;_i++){var error=errors_1[_i];if(typeof(error)=="string"){this.errors.push({message:error.toString()});}
else if(error.Description!=null){this.errors.push({message:error.Description});}
else if(error.Message!=null){this.errors.push({message:error.Message});}}};BaseViewModel.prototype.handleLogicErrors=function(data){var serverError="";var serverErrors=[];if(data.Error!=null){serverError=data.Error;}
else if(data.Message!=null){serverError=data.Message;}
else if(data.Errors!=null&&data.Errors instanceof Array){serverErrors=data.Errors;}
else if(data.Errors){serverErrors=data.Errors;}
var vm=null;if(ko.contextFor($("body")[0])!=null){vm=ko.contextFor($("body")[0]).$root;if(vm.errors==null){vm.errors=ko.observableArray();}}
if(vm!=null){if(serverError!=null&&serverError.length>0){vm.errors.push({message:ko.observable(serverError)});}
if(serverErrors!=null&&serverErrors.length>0){if(ko.contextFor($("body")[0])!=null){for(var _i=0,serverErrors_1=serverErrors;_i<serverErrors_1.length;_i++){var error=serverErrors_1[_i];vm.errors.push({message:ko.observable(error.Description)});}}}}};BaseViewModel.prototype.errorNotification=function(error,actionUrl,buttonText){iziToast.show({timeout:false,title:'Error',layout:2,message:error,overlay:true,closeOnEscape:true,maxWidth:500,position:'center',color:'red',progressBar:false,close:false,buttons:[['<button><b>'+buttonText+'</b></button>',function(instance,toast){instance.hide({transitionOut:'fadeOut'},toast,'button');if(actionUrl!=undefined&&actionUrl.length>0){window.location.href=actionUrl;}},true]]});};BaseViewModel.prototype.informationDialog=function(title,message){iziToast.show({timeout:false,title:title,layout:2,message:message,overlay:true,closeOnEscape:true,maxWidth:750,position:'center',color:'rgba(248, 248, 248, 0.95)',progressBar:false,buttons:[['<button>Got it</button>',function(instance,toast){instance.hide({transitionOut:'fadeOutUp'},toast,'buttonName');}]]});};return BaseViewModel;}());var Page;(function(Page){Page[Page["HomePage"]=0]="HomePage";Page[Page["Bookit"]=1]="Bookit";})(Page||(Page={}));sn.app.esthomepagev3=sn.app.esthomepagev3||{RoomRates:null,BookNowAvailableModel:null,DateRange:$([]).add($(".checkin")).add($(".checkout")),UnavailableDates:$([]),FeatureToggle:{AutoAllocate:false},IsRaqOnly:function(){return $("#IsRaqOnly").val()==="True";},IsSingleRoomEstablishment:function(){return $("#IsSingleRoomEstablishment").val()==="True";},AuId:parseInt($('#SingleRoomRaqAuId').val()),BaseCurrencyCode:$('#BaseCurrencyCode').val(),ViewModel:null,Page:null,init:function(page,featureToggles){var _this=this;if(featureToggles===void 0){featureToggles=null;}
this.Page=page;if(window.location.pathname[window.location.pathname.length-1]!=='/'){window.location.pathname+='/';}
if(this.IsSingleRoomEstablishment()){this.ViewModel=new EstablishmentSingleUnit($("#SpId").val(),featureToggles);}
else{this.ViewModel=new EstablishmentMultiUnit($("#SpId").val(),featureToggles);}
this.ViewModel.enableRoomSelection(true);if(Utility.getDeviceContext()===DeviceContext.Mobile&&this.Page===Page.Bookit){this.ViewModel.showBookingSummaryLink(true);}
this.BindEventListeners();this.InitializeShare();this.InitializeStickyStuff();this.InitializeSpecials();this.InitializeDateRange();this.InitializeSimilarAccommodation();setTimeout(function(){PageLogger.LogEstPageStep(_this.ViewModel,EstablishmentStep.PageLoad,"pageload");},250);},initEHome:function(){this.Reset();this.InitializeRoomTypeEvents();this.InitializeRoomAllocations();},setLoading:function(isLoading,elements,message){if(elements===void 0){elements=null;}
if(message===void 0){message="";}
if(elements==null||elements.length===0){elements=new Array();elements=elements.concat($('.booking-summary').toArray());elements=elements.concat($('.est-homepage-slide-out').toArray());}
if(isLoading){$(elements).addClass('loading');}
else{$(elements).removeClass('loading');}},setPageLoading:function(isLoading){if(isLoading){$('#page-loader').addClass('loading');}
else{$('#page-loader').removeClass('loading');}},Reset:function(){$("#SelectedRoomId").val("");},ShowNights:function(){var nights=this.GetNights();var nightsString;if(nights>0){nightsString=this.DateRange.dateRange("getNights","string");$(".nights").text(nightsString);}},GetNights:function(){return this.DateRange.dateRange("getNights");},InitializeAvailabilityCalendar:function(){if(Utility.getDeviceContext()!=DeviceContext.Mobile){setTimeout(function(){$.ajax({url:"/Establishment/GetCalendarView",type:"GET",contentType:"application/html charset=utf-8",dataType:"html",data:{spId:$("#SpId").val(),showRaq:'false'},success:function(result){$("#calendarPartial").html(result);window.loadCalData();$("#datePicker").val($(".checkin").val());window.realtimecalendaryui.init();ko.applyBindings(sn.app.esthomepagev3.ViewModel,$("#calendarPartial")[0]);}});},1000);}},InitializeDateRange:function(){var _this=this;if($("#unavailableDates").length>0){this.UnavailableDates=$("#unavailableDates").val().split(",");}
var range=$([]).add($(".checkin")).add($(".checkout"));if(range.length==0){return;}
var lastValidSeasonDate=new Date($('#lastValidSeasonDate').val());range.dateRange({autoOpenFromDate:false,maxDate:lastValidSeasonDate,showAvailability:true,showClearDates:true,unavailableDates:this.UnavailableDates,onClose:function(fromTo,date,changed,otherDate,toDateClosed){if(date==null)
return;_this.ShowNights();if(fromTo=="from"){$(".checkin").val(moment(date).format("DD MMM YYYY"));}
else{$(".checkout").val(moment(date).format("DD MMM YYYY"));}
if($(".checkin:visible").val()!==""&&$(".checkout:visible").val()!==""){if(toDateClosed){if(!_this.IsRaqOnly()){_this.CheckAvailability();}
else{_this.CheckRaqAvailability();}}}},onSelect:function(name,dateString,changed){if($(this).hasClass("checkin")){$(".checkin:visible").datepicker("setDate",dateString);$(".roomsRatesCalendar .datePicker").datepicker("setDate",dateString);$("#datePicker").change();}
else if($(this).hasClass("checkout")){}},onClear:function(){$(".uiDatePickerFromToFrom.checkin").val("Check-in");$(".uiDatePickerFromToFrom.checkout").val("Check-in");sn.app.esthomepagev3.ViewModel.clearDates(sn.app.esthomepagev3.ViewModel);},beforeShow:function(fromTo){}});},InitializeShare:function(){var _this=this;$("#send-message").click(function(event){var form=$('#frmShareEmail');event.preventDefault();if(!form.valid()){grecaptcha.reset();$("#recap-response").val("");$("#recap-error").show();}
else{var response=$('#recap-response').val();$.ajax({context:_this,url:"/Establishment/VerifyReCaptcha/?recaptchaResponse="+response,type:'POST',success:function(result){var jObject=$.parseJSON(result);if(jObject["success"]){$("#send-message").attr('disabled','disabled').val("processing...");$("#send-message").css({'background-color':'gray','text-shadow':'0 1px 1px gray','border':'solid 1px gray','background-image':'none','cursor':'default'});var token=this.GetToken();var obj={};obj.SpName=$('#SpName').val();obj.SpUrl=$('#SpUrl').val();obj.FriendsEmail=$('#FriendsEmail').val();obj.Name=$('#Name').val();obj.Email=$('#Email').val();obj.Message=$('#Message').val();$.ajax({context:this,url:"/Establishment/ShareEmail",dataType:'html',type:'POST',headers:{"__RequestVerificationToken":token},contentType:'application/json; charset=utf-8',data:JSON.stringify(obj),cache:false,beforeSend:function(){sn.app.showLoader($("#send-message"),$("#snLoaderOverlay"));},success:function(data){if(data==='true'){$('#form-fields').hide();$('#thanks').show();}
else{alert('an unexpected error occured');}},error:function(xhr,textStatus,err){alert('an unexpected error occured');},complete:function(d){sn.app.hideLoader($("#snLoaderOverlay"));}});}
else{$("#recap-error").show();}}});}});$('.share').click(function(event){event.preventDefault();var left=($(window).width()/2)-($("#share-dialog").width()/2);var top=($(window).height()/2)-($("#share-dialog").height()/2);$("#share-dialog").css("left",left);$("#share-dialog").css("top",top);$('#share-dialog').show();$('#screen').css({opacity:0.7,'width':$(document).width(),'height':$(document).height(),'z-index':99});});$('.close-share').click(function(){$('#share-dialog').hide();$('#screen').hide();$('#screen').removeAttr("style");});$('.share-email').click(function(){$('#share-dialog').hide();$('#share-email-dialog').slideDown("fast",function(){});$('#screen').show();$('#screen').css({opacity:0.7,'width':$(document).width(),'height':$(document).height(),'z-index':99});});$('.close-email').click(function(){$('#share-email-dialog').hide();$('#screen').hide();location.reload();});$('.share-facebook').click(function(){FB.ui({method:'share',href:$('#pagePath').val()},function(){$('#share-dialog').hide();});$('#screen').removeAttr("style");});},GetToken:function(){return $('input:hidden[name="__RequestVerificationToken"]').val();},BindEventListeners:function(){var _this=this;$(document).on("change",".CheckAvailability select",function(e){_this.CheckAvailability();});$(document).on("change",".single-unit-children",function(e){if(!_this.IsRaqOnly()){setTimeout(function(){return _this.SubmitAllocation($(".submit-booknow"),false,true);},0);}
else{setTimeout(function(){_this.setLoading(true);_this.CheckRaqGuests().then(function(){return _this.GetRaqRoomRate();}).always(function(){_this.setLoading(false);});});}});$('.modal-book-content').scroll(function(){$(".uiDatePickerFromToFrom").datepicker("hide");});},onListingClick:function(e,service){var processRedirect=true;var target=e.target||e.srcElement;if(Utility.HasClass(target,"icon-heart-1")||Utility.HasClass(target,"icon-heart-empty")||Utility.HasClass(target,"icon-cancel-circled-1")||Utility.HasClass(target,"remove-favourites")||Utility.HasClass(target,"rsSlideClick")||Utility.HasClass(target,"rsArrowIcn")||Utility.HasClass(target,"rsArrow")||Utility.HasClass(target,"icon-right-open")||Utility.HasClass(target,"icon-left-open")||Utility.HasClass(target,"gallery-left")||Utility.HasClass(target,"gallery-right")||Utility.HasClass(target,"rsImg")||Utility.HasClass(target,"royalSlider")||Utility.HasClass(target,"toggle-description")||(!Utility.HasClass(target,"button")&&target.href!=null&&target.href.length>0&&!Utility.HasClass(target,"hub-title"))){processRedirect=false;}
if(processRedirect){if(Utility.HasClass(target,"button")||Utility.HasClass(target,"hub-title")){e.preventDefault();}
var url=e.currentTarget.getAttribute("data-url");var requestId=getParameterByName("r");if(requestId!=null&&requestId.length>0){url=addParameter(url,"r",requestId);}
if(Utility.getDeviceContext()!=DeviceContext.Mobile){if(this._openInNewTab){window.open(url,"_blank");}
else{document.location.href=url;}}
else{document.location.href=url;}}
else{if(Utility.HasClass(target,"toggle-description")){var toggle=target;Utility.RemoveClass(toggle.parentElement.querySelector(".features"),"hide");Utility.RemoveClass(toggle.parentElement.querySelector(".description"),"hide");Utility.RemoveClass(toggle.parentElement.querySelector(".accom-types-mobile"),"hide");Utility.RemoveClass(toggle.parentElement.querySelector(".features"),"show");Utility.RemoveClass(toggle.parentElement.querySelector(".description"),"show");Utility.RemoveClass(toggle.parentElement.querySelector(".accom-types-mobile"),"show");if(Utility.HasClass(toggle,"up")){Utility.RemoveClass(toggle,"up");Utility.AddClass(toggle.parentElement.querySelector(".features"),"show");Utility.AddClass(toggle.parentElement.querySelector(".description"),"hide");Utility.AddClass(toggle.parentElement.querySelector(".accom-types-mobile"),"hide");}
else{Utility.AddClass(toggle,"up");Utility.AddClass(toggle.parentElement.querySelector(".features"),"hide");Utility.AddClass(toggle.parentElement.querySelector(".description"),"show");Utility.AddClass(toggle.parentElement.querySelector(".accom-types-mobile"),"show");}}}},InitializeRooms:function(){$(document).on("click",".room-desc a",function(){var link=$(this);if(link.text()==="see more"){var roomDesc=link.parent();var fullDesc=roomDesc.data("full-desc");$(roomDesc).html(fullDesc);}});$(document).on("click",".room-features a",function(e){var target=e.target||e.srcElement;var selector="span[data-roomfeatureselector="+$(target).attr("data-selector")+"]";$(selector).find("span.is-open").hide();$(selector).find("span.is-closed").show();});},InitializeFacilities:function(){$(document).on("click","#features a",function(e){var target=e.target;var link=$(target),ancestor=link.parent().parent();if(link.text()==="see more"){$(ancestor).find("li.l-dn.toggle").removeClass("l-dn");$(target).text("see less");}
else{$(ancestor).find("li.toggle").addClass("l-dn");$(target).text("see more");}});},InitializeImportantInformation:function(){$(document).on("click","#importantinfo a",function(e){var target=e.target;var link=$(target),ancestor=link.parent().parent();if(link.text()==="see more"){$(ancestor).find("span.shortinfo").addClass("l-dn");$(ancestor).find("span.longinfo").removeClass("l-dn");$(target).text("see less");}
else{$(ancestor).find("span.longinfo").addClass("l-dn");$(ancestor).find("span.shortinfo").removeClass("l-dn");$(target).text("see more");$('html, body').animate({scrollTop:$("#importantinfo").offset().top},500);}});},InitializeLogo:function(){$(".column-img-size").attr("src",$("body").find(".i-logo").next().attr("src"));},InitializeStickyStuff:function(){var _this=this;if($(".sticky").length>0){new Sticky().bind(".sticky",null,0);}
var mobileBtns=document.querySelector(".mobile-booking-card");var sticky=document.querySelector(".est-homepage-sticky-buttons");var stickyTickThrottle=Util.throttle(function(){_this.stickyOnScroll(sticky,mobileBtns,document.querySelector("#footer"));},500);var stickyTick=function(){_this.stickyOnScroll(sticky,mobileBtns,document.querySelector("#footer"));};window.addEventListener("scroll",stickyTickThrottle);window.addEventListener("resize",stickyTickThrottle);window.addEventListener("DOMContentLoaded",stickyTick);window.addEventListener("scroll",function(){});window.addEventListener("resize",function(){});},stickyOnScroll:function(sticky,mobileBtns,footer){if(sticky&&mobileBtns){var bounds=mobileBtns.getBoundingClientRect();var isMobile=Modernizr.mq("(max-width: 767px)");if(bounds.bottom<=0&&isMobile){sticky.classList.add("visible");if(footer){footer.style.paddingBottom="60px";}}
else{sticky.classList.remove("visible");if(footer){footer.style.paddingBottom="";}}}},InitializeSpecials:function(){$(document).on("click",".specialWrapper a.btn-green",function(){$.scrollTo($(".checkin"),600,{offset:-30,onAfter:function(){$(".checkin").focus();}});});},InititalizeTooltips:function(){var tooltipElements=document.querySelectorAll("[data-tooltip]");[].forEach.call(tooltipElements,function(elm){var tooltip=null;var removeTimeout=null;var addTimeout=null;var removeTooltip=function(delay){clearTimeout(addTimeout);removeTimeout=setTimeout(function(){if(tooltip!=null){tooltip.classList.remove("visible");}
setTimeout(function(){if(tooltip!=null){document.body.removeChild(tooltip);tooltip=null;}},delay);},delay);};elm.addEventListener("mouseenter",function(event){if(tooltip==null){addTimeout=setTimeout(function(){var target=event.target;var elmBounds=target.getBoundingClientRect();tooltip=document.createElement("div");tooltip.classList.add("est-homepage-tooltip");tooltip.innerHTML=target.getAttribute("data-tooltip");document.body.appendChild(tooltip);var positionTooltip=function(){if(tooltip!=null){var scrollTop=!window.scrollY?document.documentElement.scrollTop:window.scrollY;tooltip.style.left=(elmBounds.left)-(tooltip.offsetWidth/2)+10+"px";tooltip.style.top=elmBounds.top+scrollTop+25+"px";}};positionTooltip();tooltip.classList.add("visible");tooltip.addEventListener("mouseenter",function(){clearTimeout(removeTimeout);});tooltip.addEventListener("mouseleave",function(){return removeTooltip(100);});window.addEventListener("scroll",function(){return removeTooltip(0);});},50);}
else{clearTimeout(removeTimeout);}});elm.addEventListener("mouseleave",function(){return removeTooltip(100);});});},InitializeRoomTypeEvents:function(){var _this=this;$(document).on("click",".room-desc a",function(e){var link=$(e.target),roomDesc=link.parent(),fullDesc=roomDesc.data("full-desc");if(link.text()==="see more"){roomDesc.text(fullDesc);}});if(this.HasGlobalFilters()){$(document).on("click","input[value='Book']",function(e){var target=e.target||e.srcElement;var selector="div[data-roomselector="+$(target).attr("data-roomselector")+"]";if($(".checkin").val()===""){$.scrollTo($(".checkin"),600,{offset:-30,onAfter:function(){$(".checkin").focus();}});}
else{var roomId=$(target).attr("data-roomid");if(_this.ShowWarningMessages(selector)){}
else{var controlToOverlayLoader=$(target).closest("li");_this.Pay(roomId,controlToOverlayLoader);}}});}
else{$(document).on("click","input[value='Book']",function(e){var target=e.target||e.srcElement;var selector="div[data-roomselector="+$(target).attr("data-roomselector")+"]";$('.validation-summary-warning').hide();if($(".checkin").val()===""){$.scrollTo($(".checkin"),600,{offset:-30,onAfter:function(){$(".checkin").focus();}});}
else{if(!$(selector).is(":visible")){$(selector).show();_this.SubmitAllocation($(selector),true,false);}
$.scrollTo($(target).closest("li"),600,{offset:-5});}});}
$(document).on("click",".room-features a",function(e){var target=e.target||e.srcElement;var selector="span[data-roomfeatureselector="+$(target).attr("data-selector")+"]";$(selector).find("span.is-open").hide();$(selector).find("span.is-closed").show();});},InitializeRoomAllocations:function(){var _this=this;$(document).on("change",".roomQty",function(e){var target=e.target;var mainContainer=$(target).closest(".roomselector");var mainUl=mainContainer.find(".roomallocs");var currentItemCount=mainContainer.find(".roomallocs li").length-1;var newItemCount=$(target).val();var roomPrefix=mainUl.find(".collectionname").val().toLowerCase().replace(".roomallocations","");var roomId=$("input[name='"+roomPrefix+".Id']").val();var paxRows=mainContainer.find('ul li:first span').length;var roomSelectionEnabled=$("#RoomSelectionEnabled").val();if(newItemCount>currentItemCount){var htmlFieldPrefix=roomPrefix+".roomallocations";var obj={};obj.CurrentCount=parseInt(currentItemCount.toString(),10);obj.RequiredCount=newItemCount;obj.RowNumber=i;obj.HtmlFieldPrefix=htmlFieldPrefix;obj.RoomId=roomId;obj.SpId=$("#SpId").val();obj.PaxRows=paxRows;obj.RoomSelectionEnabled=roomSelectionEnabled;$.ajax({context:_this,url:"EmptyRoomAllocation",type:'POST',contentType:'application/json; charset=utf-8',data:JSON.stringify(obj),dataType:'html',cache:false,success:function(html){mainUl.append(html);this.SubmitAllocation(mainContainer,false,false);}});}
else if(currentItemCount>newItemCount){var amountToRemove=currentItemCount-newItemCount;for(var i=0;i<amountToRemove;i++){mainContainer.find(".roomallocs li:last").remove();}
_this.SubmitAllocation(mainContainer,false,false);}
return false;});$(document).on("change",".adults, .children, .meal-plan",function(e){var target=e.target;var roomSelector=$(target).closest(".roomselector");_this.SubmitAllocation(roomSelector,false,false);});$(document).on("change",".roomQty-perUnit",function(e){var target=e.target;var priceselector=$(target).closest(".priceselector");_this.SubmitAllocation(priceselector,false,true);});},CheckAvailability:function(promptRoomChoice){if(promptRoomChoice===void 0){promptRoomChoice=true;}
if($(".checkin").datepicker("getDate")!=null&&$(".checkout").datepicker("getDate")!=null){var viewModel=this.ViewModel;PageLogger.LogEstPageStep(viewModel,EstablishmentStep.DatesEntered,"checkavail");viewModel.clearErrors();$("#RequestType").val(1);$("#BookNowForm").submit();var obj={};obj.CheckIn=$(".checkin").datepicker("getDate");obj.CheckOut=$(".checkout").datepicker("getDate");obj.CheckIn=$(".checkin").datepicker({dateFormat:'yy-mm-dd'}).val();obj.CheckOut=$(".checkout").datepicker({dateFormat:'yy-mm-dd'}).val();if($('#NumberOfRoomsFilter')!=null&&$('#NumberOfRoomsFilter').length>0){obj.NumberOfRoomsFilter=$('#NumberOfRoomsFilter').val();}
if($('#NumberOfAdultsFilter')!=null&&$('#NumberOfAdultsFilter').length>0){obj.NumberOfAdultsFilter=$('#NumberOfAdultsFilter').val();}
if($('#NumberOfChildrenFilter')!=null&&$('#NumberOfChildrenFilter').length>0){obj.NumberOfChildrenFilter=$('#NumberOfChildrenFilter').val();}
if(viewModel.globalRoomsFilter!==null){obj.NumberOfRoomsFilter=viewModel.globalRoomsFilter.TotalRoomsRequested();obj.NumberOfAdultsFilter=viewModel.globalRoomsFilter.TotalAdultsRequested();obj.NumberOfChildrenFilter=viewModel.globalRoomsFilter.TotalKidsRequested();obj.NumberOfChildrenAgesFilter=viewModel.globalRoomsFilter.TotalKidsAgesRequested();}
obj.SpId=$("#SpId").val();$.ajax({context:this,url:"getroomsavailabilityandprice",dataType:'json',type:'POST',contentType:'application/json; charset=utf-8',data:JSON.stringify(obj),cache:false,beforeSend:function(){sn.app.esthomepagev3.setLoading(true);sn.app.esthomepagev3.ViewModel.loading(true);},success:function(data){if(data.Success===false||(data.Errors!=null&&data.Errors.length>0)){sn.app.esthomepagev3.ViewModel.handleLogicErrors(data);}
sn.app.esthomepagev3.ViewModel.updateRoomAvailabilityAndPrice(data);sn.app.esthomepagev3.ViewModel.sortRoomTypeList();if(Utility.getDeviceContext()!==DeviceContext.Mobile){if(promptRoomChoice){sn.app.esthomepagev3.ViewModel.promptRoomChoice();}}
else{if(this.Page===Page.Bookit){if(promptRoomChoice){sn.app.esthomepagev3.ViewModel.promptRoomChoice();}}}},error:function(xhr,textStatus,err){},complete:function(d){sn.app.esthomepagev3.setLoading(false);sn.app.esthomepagev3.ViewModel.loading(false);}});$(".session-timeout").hide();}
sn.app.esthomepagev3.ViewModel.removeAllSelectedRooms();},SubmitAllocation:function(roomSelector,isBookClick,isUnitRate){var obj={};obj.Version=3;obj.Allocations=[];var roomSelectorValue=roomSelector.data("roomselector");var errorMessage=null;var guests=0;if(this.IsSingleRoomEstablishment()){obj.RoomId=parseInt(this.BookNowAvailableModel.BookNowModel.Rooms[0].Id);errorMessage=$(".booknow-availability-error-msg");var allocation={};var sleeps=parseInt($('.sleeps').val());var adults=parseInt($('.single-unit-adults').val());guests=adults;var i=0;allocation.ChildrenAge1=$('.single-unit-children-1').val();allocation.ChildrenAge2=$('.single-unit-children-2').val();allocation.ChildrenAge3=$('.single-unit-children-3').val();guests=[allocation.ChildrenAge1,allocation.ChildrenAge2,allocation.ChildrenAge3].reduce(function(a,b){if(b!==null&&b!==undefined){return parseInt(a)+parseInt(b);}
else{return parseInt(a);}},guests);if(guests>sleeps){errorMessage.html("Too many guests selected");$(".booknow-availability-error").show();$(".booknow-available-indicator").hide();$('.est-homepage-slide-out-booknow-available-msg').hide();return;}
else{errorMessage.html(null);$(".booknow-availability-error").hide();$(".booknow-available-indicator").show();$('.est-homepage-slide-out-booknow-available-msg').show();}
allocation.Adults=adults;allocation.SelectedMealPlanCode=$('.single-unit-mealplan').val();obj.Allocations.push(allocation);}
else{obj.RoomId=roomSelector.data("roomselectorindex");guests=0;var roomCount=0;errorMessage=roomSelector.find(".room-error ul");var payButton=roomSelector.find("input[value='Book Now']");errorMessage.html("");payButton.removeAttr('disabled');payButton.removeClass('btn-disabled');$(roomSelector).find(".room-allocation").each(function(i,element){var room={};var roomguests=0;var sleeps=roomSelector.parent().find('.sleeps').val();room.Adults=$(element).find(".adults").val();guests+=parseInt(room.Adults);roomguests+=parseInt(room.Adults);var i=1;$(element).find(".children").each(function(i,element){if(i===1){room.ChildrenAge1=$(element).val();}
if(i===2){room.ChildrenAge2=$(element).val();}
if(i===3){room.ChildrenAge3=$(element).val();}
guests+=parseInt($(element).val());roomguests+=parseInt($(element).val());i++;});if(roomguests>sleeps){errorMessage.html("<li>There are too many people selected</li>");payButton.attr('disabled','disabled');payButton.addClass('btn-disabled');}
var mealPlan=$(element).find("input[type=radio].meal-plan:checked");if(mealPlan.length===0){mealPlan=$(element).find("input[type=hidden].meal-plan");}
room.RoomId=obj.RoomId;room.SelectedMealPlanCode=mealPlan.val();roomCount++;obj.Allocations.push(room);});}
if(obj.Allocations.length===0){obj.Allocations.push({RoomId:obj.RoomId,Adults:"2",ChildrenAge1:"0",SelectedMealPlanCode:"5"});}
if(errorMessage.html()==null||errorMessage.html().length===0){$.ajax({context:this,url:"GetAllocationRate",dataType:'json',type:'POST',contentType:'application/json; charset=utf-8',data:JSON.stringify(obj),cache:false,beforeSend:function(){this.setLoading(true);if(isBookClick||isUnitRate){sn.app.showLoader(roomSelector,$("#snLoaderOverlay"),"Checking availability...");}
else{var roomPayEl=$(roomSelector).find(".room-pay");sn.app.showLoader(roomPayEl,$("#snLoaderOverlay"),"Retrieving best prices.");}},success:function(data,result){if(data.Error!==""&&data.Error!=null){errorMessage.append("<li>"+data.Error+"</li>");}
else if(data['Price'].length>0){if(this.IsSingleRoomEstablishment()){var desktopPriceHtml='';var mobilePriceHtml='';if(data.HasSpecial){desktopPriceHtml="<span style=\"float: right\" class=\"old-price\">"+data.Price+"</span>\n                                <br>\n                                <span style=\"float: right\" class=\"special-price\">"+data.Special.SpecialAmount+"</span> \n                                <span style=\"float:left\">Total</span>\n                                <div class=\"clearfix\"></div>";mobilePriceHtml="<span style=\"float: right\" class=\"old-price\">"+data.Price+"</span>\n                                <br>\n                                <span style=\"float: right\" class=\"special-price\">"+data.Special.SpecialAmount+"</span> \n                                <span style=\"float:left\">Total</span>\n                                <div class=\"clearfix\"></div>";}
else{desktopPriceHtml="Total <span style=\"float: right\">"+data.Price+"</span>";mobilePriceHtml="Total <span style=\"float: right\">"+data.Price+"</span>";}
if(data.CanUseDeposit){$('.price-due-now.desktop-version').html("Due Now <span style=\"float:right\">"+data.DepositAmount+"</span>");$('.price-due-now.mobile-version').html("Due Now <span style=\"float:right\">"+data.DepositAmount+"</span>");}
$('.price-total.desktop-version').html(desktopPriceHtml);$('.price-total.mobile-version').html(desktopPriceHtml);$('.logoandprice.mobile-version').hide();}
else{if(isBookClick){var elId="span[data-roomselector="+roomSelectorValue+"]";$(elId).find(".room-pay").hide();$(elId).find(".room-button").hide();}
$(roomSelector).find("#rate-"+roomSelectorValue).html(data['Price']);if(data["HasSpecial"]===true){var special=data["Special"];$(roomSelector).find("#specialsummary-"+roomSelectorValue).html(special.SpecialSummary);if(special.IsFreebieOnlySpecial===true){$(roomSelector).find("#freebieInfo-"+roomSelectorValue).removeClass("l-dn").html(special.FreebieDetails);}
else{$(roomSelector).find("#specialamount-"+roomSelectorValue).html(special.SpecialAmount);$(roomSelector).find("#rate-"+roomSelectorValue).addClass("linethrough").addClass("fwn");}}
var nights=this.GetNights();var guestInfo="";if(!isUnitRate){guestInfo=guests===1?"1 guest in ":guests+" guests in ";}
guestInfo+=roomCount===1?"1 room for ":roomCount+" rooms for ";guestInfo+=nights===1?"1 night":nights+" nights";$($(roomSelector).find(".payment-price em")[1]).html(guestInfo);}}
else{$.scrollTo($(".session-timeout"),600,{offset:-5});if($(".checkin").datepicker("getDate")!=null&&$(".checkout").datepicker("getDate")!=null){$(".session-timeout li").html("Your session has timed out.  We are checking availability for your dates.");$(".session-timeout").show();this.CheckAvailability();}
else{$(".session-timeout li").html("Your session has timed out.");$(".session-timeout").show();$(".checkin").focus();}}},error:function(xhr,textStatus,err){},complete:function(d){sn.app.hideLoader($("#snLoaderOverlay"));this.setLoading(false);}});}},Pay:function(roomid,loaderOverlayControl){var _this=this;this.setPageLoading(true);if(this.IsSingleRoomEstablishment()){$("#RequestType").val(2);$("#SelectedRoomId").val(roomid);var form=$("#frmBookNow");var allocation={};var sleeps=parseInt($('.sleeps').val());var adults=parseInt($('.single-unit-adults').val());var guests=adults;var i=0;allocation.ChildrenAge1=$('.single-unit-children-1').val();allocation.ChildrenAge2=$('.single-unit-children-2').val();allocation.ChildrenAge3=$('.single-unit-children-3').val();guests=[allocation.ChildrenAge1,allocation.ChildrenAge2,allocation.ChildrenAge3].reduce(function(a,b){if(b!==null&&b!==undefined){return parseInt(a)+parseInt(b);}
else{return parseInt(a);}},guests);if(guests>sleeps){return;}
allocation.Adults=adults;var mealPlan=$('.single-unit-mealplan').val();allocation.SelectedMealPlanCode=mealPlan;var serialized=form.serializeArray();var roomIndex_1="0";var roomAllocationIndex="0";roomIndex_1=serialized.filter(function(kvp){return kvp.name==="rooms.index";})[0].value;roomAllocationIndex=serialized.filter(function(kvp){return kvp.name==="rooms["+roomIndex_1+"].RoomAllocations.index";})[0].value;var allocationKey=null;serialized.push({name:"rooms["+roomIndex_1+"].RoomAllocations["+roomAllocationIndex+"].Adults",value:allocation.Adults});if(allocation.ChildrenAge1!==undefined&&allocation.ChildrenAge1!==null){serialized.push({name:"rooms["+roomIndex_1+"].RoomAllocations["+roomAllocationIndex+"].ChildrenAge1",value:allocation.ChildrenAge1});}
if(allocation.ChildrenAge2!==undefined&&allocation.ChildrenAge2!==null){serialized.push({name:"rooms["+roomIndex_1+"].RoomAllocations["+roomAllocationIndex+"].ChildrenAge2",value:allocation.ChildrenAge2});}
if(allocation.ChildrenAge3!==undefined&&allocation.ChildrenAge3!==null){serialized.push({name:"rooms["+roomIndex_1+"].RoomAllocations["+roomAllocationIndex+"].ChildrenAge3",value:allocation.ChildrenAge3});}
if(allocation.SelectedMealPlanCode!==undefined&&allocation.SelectedMealPlanCode!==null){serialized.push({name:"rooms["+roomIndex_1+"].RoomAllocations["+roomAllocationIndex+"].SelectedMealPlanCode",value:allocation.SelectedMealPlanCode});}
$.ajax({context:this,type:"POST",url:"BookNow",data:$.param(serialized),cache:false,beforeSend:function(){this.setPageLoading(true);}}).done(function(data){if(data.redirectUrl!==''){document.location.href=data.redirectUrl;}}).fail(function(){_this.setPageLoading(false);});}
else{$("#RequestType").val(2);$("#SelectedRoomId").val(roomid);var form=$("#frmBookNow");$.ajax({context:this,type:"POST",url:"BookNow",data:form.serialize(),cache:false,beforeSend:function(){sn.app.showLoader(loaderOverlayControl,$("#snLoaderOverlay"));}}).done(function(data){if(data.redirectUrl!==''){document.location.href=data.redirectUrl;}
else{$("#bookNowContent").replaceWith(data.view);_this.ShowNights();$.scrollTo($("#frmBookNow"),600,{offset:-5});sn.app.hideLoader($("#snLoaderOverlay"));}}).fail(function(){});}},mimicInput:function(selector){$(document).on("change",selector,function(e){var target=e.target;$(selector).val($(target).val());});},HasGlobalFilters:function(){return $(".CheckAvailability select").length>0;},GetRaqMinimumStay:function(){var deferred=$.Deferred();var req={action:"GetMinimumStay",data:JSON.stringify({SpId:$("#SpId").val(),FromDate:$(".checkin").val(),ToDate:$(".checkout").val(),BaseCurrency:this.BaseCurrencyCode})};$.ajax({context:this,url:"/site/httphandlers/enquiryservice.ashx",type:'POST',contentType:'application/x-www-form-urlencoded; charset=UTF-8',data:req,dataType:'text',cache:false,success:function(html){deferred.resolve(html);},error:function(xhr,textStaus,error){deferred.reject(error);}});return deferred.promise();},CheckRaqGuests:function(){var deferred=$.Deferred();if($('.single-unit-adults').length>0){var adults=parseInt($('.single-unit-adults').val());var guests=adults;var errorMessage=$(".booknow-availability-error-msg");var sleeps=parseInt($('.sleeps').html().split(" ")[$('.sleeps').html().split(" ").length-1]);var childrenAge1=$('.single-unit-children-1').val();var childrenAge2=$('.single-unit-children-2').val();var childrenAge3=$('.single-unit-children-3').val();var children=[];if(childrenAge1){children.push(parseInt(childrenAge1));}
if(childrenAge2){children.push(parseInt(childrenAge2));}
if(childrenAge3){children.push(parseInt(childrenAge3));}
guests=children.reduce(function(a,b){return a+b;},guests);if(guests>sleeps){errorMessage.html("Too many guests selected");$(".booknow-availability-error").show();$(".booknow-available-indicator").hide();$('.est-homepage-slide-out-booknow-available-msg').hide();deferred.reject();}
else{errorMessage.html(null);$(".booknow-availability-error").hide();$(".booknow-available-indicator").show();$('.est-homepage-slide-out-booknow-available-msg').show();deferred.resolve();}}
else{deferred.resolve();}
return deferred.promise();},GetRaqRoomRate:function(){var deferred=$.Deferred();var pax=null;var appendChildPax=function(selector,array){if($(selector).length>0){array.push({Age:$(selector).attr("data-max-age"),Qty:$(selector).val()});}
return array;};if($(".single-unit-adults").length>0&&$(".single-unit-children").length>0){pax={};pax.adults=$(".single-unit-adults").val();pax.children=[];pax.children=appendChildPax(".single-unit-children-1",pax.children);pax.children=appendChildPax(".single-unit-children-2",pax.children);pax.children=appendChildPax(".single-unit-children-3",pax.children);}
var req={action:"GetRoomRates",data:JSON.stringify({SpId:$("#SpId").val(),FromDate:$(".checkin").val(),ToDate:$(".checkout").val(),BaseCurrency:this.BaseCurrencyCode,Adults:pax&&pax.adults?pax.adults:2,Children:pax&&pax.children?pax.children:[]})};$.ajax({context:this,url:"/site/httphandlers/enquiryservice.ashx",type:'POST',contentType:'application/x-www-form-urlencoded; charset=UTF-8',data:req,dataType:'json',cache:false,success:function(rates){deferred.resolve(rates);},error:function(xhr,textStaus,error){deferred.reject(error);}});return deferred.promise();},LoadSingleUnitPaxView:function(){var deferred=$.Deferred();var req={SpId:$("#SpId").val(),};$.ajax({context:this,url:"GetSingleUnitPaxView",dataType:'html',type:'POST',contentType:'application/json; charset=utf-8',data:JSON.stringify(req),cache:false,beforeSend:function(){},success:function(paxView){$(".booknow-pax").html(paxView);setTimeout(function(){var maxAdults=parseInt($('.single-unit-adults').attr('data-max'));if(maxAdults>=2){$('.single-unit-adults').val(2);}
else{$('.single-unit-adults').val(maxAdults);}},0);deferred.resolve();},error:function(xhr,textStatus,err){deferred.reject(err);},complete:function(d){}});return deferred.promise();},SubmitRequestQuote:function(){var deferred=$.Deferred();var sleeps=parseInt($($('.sleeps')[0]).val());var appendChildAgeBand=function(selector,array){if($(selector).length>0){array.push({AgeFrom:parseInt($(selector).attr("data-min-age")),AgeTo:parseInt($(selector).attr("data-max-age")),Qty:parseInt($(selector).val())});}
return array;};var childAgeBands=[];appendChildAgeBand(".single-unit-children-1",childAgeBands);appendChildAgeBand(".single-unit-children-2",childAgeBands);appendChildAgeBand(".single-unit-children-3",childAgeBands);var req={__RequestVerificationToken:this.GetToken(),SpId:$("#SpId").val(),BaseCurrency:this.BaseCurrencyCode,CountryCode:$(".txt-raq-mobile-number-prefix").val(),Checkin:$(".checkin").val(),Checkout:$(".checkout").val(),FirstName:$(".txt-raq-first-name").val(),LastName:$(".txt-raq-last-name").val(),Email:$(".txt-raq-email").val(),PhoneNumber:$(".txt-raq-mobile-number").val(),Adults:$(".single-unit-adults").val(),ChildAgeBands:childAgeBands,Message:$(".txt-raq-message").val(),Sleeps:sleeps,Rooms:[{AuId:parseInt($("#SingleRoomRaqAuId").val()),Quantity:1}],RootLocationId:$("#LocationId").val(),RefererRedirect:true,SellerFirstName:$("#SellerName").val(),ResponseTimeText:$("#ResponseTime").val()};$.ajax({context:this,url:"submitrequestquote",dataType:'html',method:'POST',contentType:'application/json; charset=UTF-8',data:JSON.stringify(req),headers:{"RequestVerificationToken":this.GetToken()},cache:false,beforeSend:function(){},success:function(res){try{var json=JSON.parse(res);deferred.reject({Message:json.Message,StackTrace:json.StackTrace});}
catch(err){location.href=res;}},error:function(xhr,textStatus,err){deferred.reject(err);},complete:function(d){}});return deferred.promise();},ValidateRequestQuoteForm:function(group,field){var _this=this;if(group===void 0){group=null;}
if(field===void 0){field=null;}
var deferred=$.Deferred();var isFormValid=function(field){if(field===void 0){field=null;}
if(field===null&&group===null){return _this.ValidateFormGroup($('.txt-raq-first-name'),$('.form-group-raq-first-name'))&_this.ValidateFormGroup($('.txt-raq-last-name'),$('.form-group-raq-last-name'))&_this.ValidateFormGroup($('.txt-raq-email'),$('.form-group-raq-email'),"Please enter a valid email")&_this.ValidateFormGroup($('.txt-raq-mobile-number'),$('.form-group-raq-mobile'),"Please enter a valid mobile number");}
else{switch(group){case '.form-group-raq-first-name':_this.ValidateFormGroup($('.txt-raq-first-name'),$('.form-group-raq-first-name'));break;case '.form-group-raq-last-name':_this.ValidateFormGroup($('.txt-raq-last-name'),$('.form-group-raq-last-name'));break;case '.form-group-raq-email':_this.ValidateFormGroup($('.txt-raq-email'),$('.form-group-raq-email'),"Please enter a valid email");break;case '.form-group-raq-mobile':_this.ValidateFormGroup($('.txt-raq-mobile-number'),$('.form-group-raq-mobile'),"Please enter a valid mobile number");break;}}};if($('.checkin').val()===''||$('.checkout').val()===''){deferred.reject();}
if(isFormValid()){deferred.resolve();}
else{deferred.reject();}
return deferred.promise();},ValidateFormGroup:function(jqueryInput,formGroup,errorMessage){if(errorMessage===void 0){errorMessage=null;}
var input=jqueryInput[0];var isValid=input.checkValidity();var validationMessage=formGroup.find(".validation-message");if(isValid){formGroup.removeClass("has-error");validationMessage.html(null);return true;}
else{formGroup.addClass("has-error");if(input.validity.patternMismatch){validationMessage.html(errorMessage);}
else{validationMessage.html(input.validationMessage);}
return false;}},CheckRaqAvailability:function(){var _this=this;if(this.IsSingleRoomEstablishment()){$('.booknow-available-indicator').hide();$(".booknow-availability-error").hide();$('.est-homepage-slide-out-booknow-available-msg').hide();$('.booknow-nights-indicator').html(null);this.setLoading(true);this.CheckRaqGuests().then(function(){return _this.GetRaqMinimumStay().then(function(text){text=text.replace("\"","").replace("\"","");if(text!==''){$(".booknow-availability-error-msg").html(text);$(".booknow-availability-error").show();}
else{$(".booknow-availability-error").hide();return _this.GetRaqRoomRate().then(function(rates){var roomRate=rates[0];if(roomRate===null||roomRate===undefined){$(".booknow-availability-error-msg").html("Failed to get room availability");$(".booknow-availability-error").show();}
else{if(roomRate.Available){$('.booknow-nights-indicator').html("&nbsp;("+_this.GetNights()+" nights)");$('.booknow-available-indicator').show();$('.est-homepage-slide-out-booknow-available-msg').show();var desktopPriceHtml='';var mobilePriceHtml='';if(roomRate.HasSpecial){desktopPriceHtml="<span style=\"float: right\" class=\"old-price\">"+roomRate.Price+"</span>\n                                                            <br>\n                                                            <span style=\"float: right\" class=\"special-price\">"+roomRate.Special.SpecialAmount+"</span> \n                                                            <span style=\"float:left\">Total</span>\n                                                            <div class=\"clearfix\"></div>";mobilePriceHtml="<span style=\"float: right\" class=\"old-price\">"+roomRate.Price+"</span>\n                                                            <br>\n                                                            <span style=\"float: right\" class=\"special-price\">"+roomRate.Special.SpecialAmount+"</span> \n                                                            <span style=\"float:left\">Total</span>\n                                                            <div class=\"clearfix\"></div>";}
else{desktopPriceHtml="Total <span style=\"float: right\">"+roomRate.Total+"</span>";mobilePriceHtml="Total <span style=\"float: right\">"+roomRate.Total+"</span>";}
$('.price-total.desktop-version').html(desktopPriceHtml);$('.price-total.mobile-version').html(desktopPriceHtml);$('.logoandprice.mobile-version').hide();return _this.LoadSingleUnitPaxView();}
else{$(".booknow-availability-error-msg").html("Room is unavilable for your dates");$(".booknow-availability-error").show();$('.est-homepage-slide-out-booknow-available-msg').hide();}}});}});}).fail(function(err){$(".booknow-availability-error-msg").html(err);$(".booknow-availability-error").show();}).always(function(){_this.setLoading(false);});}},InitializeShortSelect:function(){var states=[];var elem=$('.short-select');var options=elem.children();options.each(function(index,opt){var state=$(opt).text();states.push({state:state});if($(opt).is(':selected')){var parts=$(opt).text().split(" ");$(opt).text(parts[parts.length-1]);}});elem.on("blur",function(e){var target=e.target;options.each(function(index,opt){if($(opt).is(':selected')){var parts=$(opt).text().split(" ");$(opt).text(parts[parts.length-1]);}});});elem.on("focus",function(e){var target=e.target;options.each(function(index,opt){$(opt).text(states[index].state);});});elem.change(function(e){var target=e.target;options.each(function(index,opt){if($(opt).is(':selected')){var parts=$(opt).text().split(" ");$(opt).text(parts[parts.length-1]);}});$(target).blur();});},InitializeSimilarAccommodation:function(){var _this=this;if($("#similarAccom").length==0){return;}
setTimeout(function(){$.ajax({context:_this,url:"/Establishment/GetSimilarAccommodation?spid="+$("#SpId").val()+"&displayCurrency="+$("#BaseCurrencyCode").val(),type:'GET',beforeSend:function(){sn.app.showLoader($("#similarAccom"),$("#snLoaderOverlay"));},success:function(data){if(data){sn.app.multipartialUpdate(data);$("#similarAccom  img").lazyload({threshold:100,placeholder:"/res/img/no-image-logo.png"});$("#similarAccom .gallery-arrow").hide();$(".listing").on("click",function(e){sn.app.esthomepagev3.onListingClick(e,null);});}},complete:function(){sn.app.hideLoader($("#snLoaderOverlay"));}});},100);},};(function(a){var r=a.fn.domManip,d="_tmplitem",q=/^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,b={},f={},e,p={key:0,data:{}},i=0,c=0,l=[];function g(g,d,h,e){var c={data:e||(e===0||e===false)?e:d?d.data:{},_wrap:d?d._wrap:null,tmpl:null,parent:d||null,nodes:[],calls:u,nest:w,wrap:x,html:v,update:t};g&&a.extend(c,g,{nodes:[],parent:d});if(h){c.tmpl=h;c._ctnt=c._ctnt||c.tmpl(a,c);c.key=++i;(l.length?f:b)[i]=c}return c}a.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(f,d){a.fn[f]=function(n){var g=[],i=a(n),k,h,m,l,j=this.length===1&&this[0].parentNode;e=b||{};if(j&&j.nodeType===11&&j.childNodes.length===1&&i.length===1){i[d](this[0]);g=this}else{for(h=0,m=i.length;h<m;h++){c=h;k=(h>0?this.clone(true):this).get();a(i[h])[d](k);g=g.concat(k)}c=0;g=this.pushStack(g,f,i.selector)}l=e;e=null;a.tmpl.complete(l);return g}});a.fn.extend({tmpl:function(d,c,b){return a.tmpl(this[0],d,c,b)},tmplItem:function(){return a.tmplItem(this[0])},template:function(b){return a.template(b,this[0])},domManip:function(d,m,k){if(d[0]&&a.isArray(d[0])){var g=a.makeArray(arguments),h=d[0],j=h.length,i=0,f;while(i<j&&!(f=a.data(h[i++],"tmplItem")));if(f&&c)g[2]=function(b){a.tmpl.afterManip(this,b,k)};r.apply(this,g)}else r.apply(this,arguments);c=0;!e&&a.tmpl.complete(b);return this}});a.extend({tmpl:function(d,h,e,c){var i,k=!c;if(k){c=p;d=a.template[d]||a.template(null,d);f={}}else if(!d){d=c.tmpl;b[c.key]=c;c.nodes=[];c.wrapped&&n(c,c.wrapped);return a(j(c,null,c.tmpl(a,c)))}if(!d)return[];if(typeof h==="function")h=h.call(c||{});e&&e.wrapped&&n(e,e.wrapped);i=a.isArray(h)?a.map(h,function(a){return a?g(e,c,d,a):null}):[g(e,c,d,h)];return k?a(j(c,null,i)):i},tmplItem:function(b){var c;if(b instanceof a)b=b[0];while(b&&b.nodeType===1&&!(c=a.data(b,"tmplItem"))&&(b=b.parentNode));return c||p},template:function(c,b){if(b){if(typeof b==="string")b=o(b);else if(b instanceof a)b=b[0]||{};if(b.nodeType)b=a.data(b,"tmpl")||a.data(b,"tmpl",o(b.innerHTML));return typeof c==="string"?(a.template[c]=b):b}return c?typeof c!=="string"?a.template(null,c):a.template[c]||a.template(null,q.test(c)?c:a(c)):null},encode:function(a){return(""+a).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;")}});a.extend(a.tmpl,{tag:{tmpl:{_default:{$2:"null"},open:"if($notnull_1){__=__.concat($item.nest($1,$2));}"},wrap:{_default:{$2:"null"},open:"$item.calls(__,$1,$2);__=[];",close:"call=$item.calls();__=call._.concat($item.wrap(call,__));"},each:{_default:{$2:"$index, $value"},open:"if($notnull_1){$.each($1a,function($2){with(this){",close:"}});}"},"if":{open:"if(($notnull_1) && $1a){",close:"}"},"else":{_default:{$1:"true"},open:"}else if(($notnull_1) && $1a){"},html:{open:"if($notnull_1){__.push($1a);}"},"=":{_default:{$1:"$data"},open:"if($notnull_1){__.push($.encode($1a));}"},"!":{open:""}},complete:function(){b={}},afterManip:function(f,b,d){var e=b.nodeType===11?a.makeArray(b.childNodes):b.nodeType===1?[b]:[];d.call(f,b);m(e);c++}});function j(e,g,f){var b,c=f?a.map(f,function(a){return typeof a==="string"?e.key?a.replace(/(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g,"$1 "+d+'="'+e.key+'" $2'):a:j(a,e,a._ctnt)}):e;if(g)return c;c=c.join("");c.replace(/^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/,function(f,c,e,d){b=a(e).get();m(b);if(c)b=k(c).concat(b);if(d)b=b.concat(k(d))});return b?b:k(c)}function k(c){var b=document.createElement("div");b.innerHTML=c;return a.makeArray(b.childNodes)}function o(b){return new Function("jQuery","$item","var $=jQuery,call,__=[],$data=$item.data;with($data){__.push('"+a.trim(b).replace(/([\\'])/g,"\\$1").replace(/[\r\t\n]/g," ").replace(/\$\{([^\}]*)\}/g,"{{= $1}}").replace(/\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,function(m,l,k,g,b,c,d){var j=a.tmpl.tag[k],i,e,f;if(!j)throw"Unknown template tag: "+k;i=j._default||[];if(c&&!/\w$/.test(b)){b+=c;c=""}if(b){b=h(b);d=d?","+h(d)+")":c?")":"";e=c?b.indexOf(".")>-1?b+h(c):"("+b+").call($item"+d:b;f=c?e:"(typeof("+b+")==='function'?("+b+").call($item):("+b+"))"}else f=e=i.$1||"null";g=h(g);return"');"+j[l?"close":"open"].split("$notnull_1").join(b?"typeof("+b+")!=='undefined' && ("+b+")!=null":"true").split("$1a").join(f).split("$1").join(e).split("$2").join(g||i.$2||"")+"__.push('"})+"');}return __;")}function n(c,b){c._wrap=j(c,true,a.isArray(b)?b:[q.test(b)?b:a(b).html()]).join("")}function h(a){return a?a.replace(/\\'/g,"'").replace(/\\\\/g,"\\"):null}function s(b){var a=document.createElement("div");a.appendChild(b.cloneNode(true));return a.innerHTML}function m(o){var n="_"+c,k,j,l={},e,p,h;for(e=0,p=o.length;e<p;e++){if((k=o[e]).nodeType!==1)continue;j=k.getElementsByTagName("*");for(h=j.length-1;h>=0;h--)m(j[h]);m(k)}function m(j){var p,h=j,k,e,m;if(m=j.getAttribute(d)){while(h.parentNode&&(h=h.parentNode).nodeType===1&&!(p=h.getAttribute(d)));if(p!==m){h=h.parentNode?h.nodeType===11?0:h.getAttribute(d)||0:0;if(!(e=b[m])){e=f[m];e=g(e,b[h]||f[h]);e.key=++i;b[i]=e}c&&o(m)}j.removeAttribute(d)}else if(c&&(e=a.data(j,"tmplItem"))){o(e.key);b[e.key]=e;h=a.data(j.parentNode,"tmplItem");h=h?h.key:0}if(e){k=e;while(k&&k.key!=h){k.nodes.push(j);k=k.parent}delete e._ctnt;delete e._wrap;a.data(j,"tmplItem",e)}function o(a){a=a+n;e=l[a]=l[a]||g(e,b[e.parent.key+n]||e.parent)}}}function u(a,d,c,b){if(!a)return l.pop();l.push({_:a,tmpl:d,item:this,data:c,options:b})}function w(d,c,b){return a.tmpl(a.template(d),c,b,this)}function x(b,d){var c=b.options||{};c.wrapped=d;return a.tmpl(a.template(b.tmpl),b.data,c,b.item)}function v(d,c){var b=this._wrap;return a.map(a(a.isArray(b)?b.join(""):b).filter(d||"*"),function(a){return c?a.innerText||a.textContent:a.outerHTML||s(a)})}function t(){var b=this.nodes;a.tmpl(null,null,null,this).insertBefore(b[0]);a(b).remove()}})(jQuery);Array.prototype.containsDate=function(obj){var i=this.length;while(i--){if(this[i].getTime()==obj.getTime()){return true;}}
return false;};Array.prototype.has=function(value){for(var i=0;i<this.length;i++){if(this===value){return true;}}
return false;};if(!Array.indexOf){Array.prototype.indexOf=function(obj,start){for(var i=(start||0);i<this.length;i++){if(this[i]==obj){return i;}}
return-1;};}
function dateExistsInDateRange(date,currentViewStart,currentViewEnd){while(currentViewStart<=currentViewEnd){if(new Date(date).getTime()==currentViewStart.getTime())
return date;currentViewStart.setDate(currentViewStart.getDate()+1);}
return null;}
function dayOfWeek(date){return new Date(date).getDay()==0?7:new Date(date).getDay();}
function abbrDayOfWeek(date){switch(new Date(date).getDay()){case 0:return "Sun"
break;case 1:return "Mon"
break;case 2:return "Tue"
break;case 3:return "Wed"
break;case 4:return "Thu"
break;case 5:return "Fri"
break;case 6:return "Sat"
break;}}
function getDays(firstdate,seconddate){var ONE_DAY=1000*60*60*24;var date1_ms=firstdate.getTime();var date2_ms=seconddate.getTime();var difference_ms=Math.abs(date1_ms-date2_ms);return Math.round(difference_ms/ONE_DAY);}
function firstDayOfMonth(date){return new Date(new Date(date).getFullYear(),new Date(date).getMonth(),1);}
function firstDayOfPreviousMonth(date){var currentMonth=new Date(new Date(date).getFullYear(),new Date(date).getMonth(),1);currentMonth.setDate(currentMonth.getDate()-1);today=new Date(currentMonth.getFullYear(),currentMonth.getMonth(),1);return today;}
function firstDayOfNextMonth(date){var currentMonth=new Date(new Date(date).getFullYear(),new Date(date).getMonth(),28);currentMonth.setDate(currentMonth.getDate()+4);today=new Date(currentMonth.getFullYear(),currentMonth.getMonth(),1);return today;}
function lastDayOfMonth(date){return new Date(new Date(new Date(date).getFullYear(),new Date(date).getMonth()+1,1)-1);}
function formatDateYMD(date){var tempDate=('0'+new Date(date).getDate()).slice(-2)
+('0'+(new Date(date).getMonth()+1)).slice(-2)
+new Date(date).getFullYear();return tempDate;}
function formatDateYYYYMMDD(date){var tempDate=new Date(date).getFullYear()+"/"+
('0'+(new Date(date).getMonth()+1)).slice(-2)+"/"+
('0'+new Date(date).getDate()).slice(-2);return tempDate;}
function formatDateddMMMyyyy(date){var monthNames=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];var tempDate=('0'+new Date(date).getDate()).slice(-2)+" "
+monthNames[new Date(date).getMonth()]+" "
+new Date(date).getFullYear();return tempDate;}
function formatDateMMMMyyyy(date){var monthNames=["January","February","March","April","May","June","July","August","September","October","November","December"];var tempDate=monthNames[new Date(date).getMonth()]+" "+new Date(date).getFullYear();return tempDate;}
function ddMMMyyyyToDate(dateString){var monthNames=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];var d=new Date(dateString.substr(7,4),monthNames.indexOf(dateString.substr(3,3)),dateString.substr(0,2));return d;}
function ddMMMMyyyyToDateString(date){var monthNames=["January","February","March","April","May","June","July","August","September","October","November","December"];var d=date.getDate()+" "+monthNames[date.getMonth()]+" "+date.getFullYear();return d;}
function yyyyMMddToDate(dateString){var d=new Date(dateString.substr(0,4),dateString.substr(5,2)-1,dateString.substr(8,2));return d;}
function cloneDate(d){return new Date(+d);}
function parseJsonDate(jsonDateString){return new Date(parseInt(jsonDateString.replace('/Date(','')));}
function isValidDate(value,userFormat){userFormat=userFormat||'yyyy-mm-dd';var delimiter=/[^ymd]/.exec(userFormat)[0];var theFormat=userFormat.split(delimiter);var theDate=value.split(delimiter);function isDate(date,format){var m,d,y,i=0,len=format.length,f;for(i;i<len;i++){f=format[i];if(/y/.test(f))y=date[i];if(/m/.test(f))m=date[i];if(/d/.test(f))d=date[i];}
return(m>0&&m<13&&y&&y.length===4&&d>0&&d<=(new Date(y,m,0)).getDate());}
return isDate(theDate,theFormat);}
(function(){(function(n,t){var r,u,i;return i="shapeshift",u={selector:"*",enableDrag:!1,enableCrossDrop:!1,enableResize:!1,enableTrash:!1,align:"center",colWidth:null,columns:null,minColumns:1,autoHeight:!0,maxHeight:null,minHeight:100,gutterX:10,gutterY:10,paddingX:0,paddingY:0,animated:!1,animateOnInit:!1,animationSpeed:225,animationThreshold:100,dragClone:!1,deleteClone:!0,dragRate:100,dragWhitelist:"*",crossDropWhitelist:"*",cutoffStart:null,cutoffEnd:null,handle:!1,cloneClass:"ss-cloned-child",activeClass:"ss-active-child",draggedClass:"ss-dragged-child",placeholderClass:"ss-placeholder-child",originalContainerClass:"ss-original-container",currentContainerClass:"ss-current-container",previousContainerClass:"ss-previous-container"},r=function(){function i(t,i){this.element=t;this.options=n.extend({},u,i);this.globals={};this.$container=n(t);this.errorCheck()&&this.init()}return i.prototype.errorCheck=function(){var i,r,n,t;return t=this.options,n=!1,r="Shapeshift ERROR:",t.colWidth===null&&(i=this.$container.children(t.selector),i.length===0&&(n=!0,console.error(""+r+" option colWidth must be specified if Shapeshift is initialized with no active children."))),!n},i.prototype.init=function(){return this.createEvents(),this.setGlobals(),this.setIdentifier(),this.setActiveChildren(),this.enableFeatures(),this.gridInit(),this.render(),this.afterInit()},i.prototype.createEvents=function(){var n,i,t=this;i=this.options;n=this.$container;n.off("ss-arrange").on("ss-arrange",function(n,i){return i==null&&(i=!1),t.render(!1,i)});n.off("ss-rearrange").on("ss-rearrange",function(){return t.render(!0)});n.off("ss-setTargetPosition").on("ss-setTargetPosition",function(){return t.setTargetPosition()});n.off("ss-destroy").on("ss-destroy",function(){return t.destroy()});return n.off("ss-shuffle").on("ss-shuffle",function(){return t.shuffle()})},i.prototype.setGlobals=function(){return this.globals.animated=this.options.animateOnInit,this.globals.dragging=!1},i.prototype.afterInit=function(){return this.globals.animated=this.options.animated},i.prototype.setIdentifier=function(){return this.identifier="shapeshifted_container_"+Math.random().toString(36).substring(7),this.$container.addClass(this.identifier)},i.prototype.enableFeatures=function(){return this.options.enableResize&&this.enableResize(),this.options.enableDrag||this.options.enableCrossDrop?this.enableDragNDrop():void 0},i.prototype.setActiveChildren=function(){var h,c,r,l,t,a,i,u,f,e,o,s;for(i=this.options,h=this.$container.children(i.selector),c=i.activeClass,u=h.length,t=f=0;0<=u?f<u:f>u;t=0<=u?++f:--f)n(h[t]).addClass(c);for(this.setParsedChildren(),l=i.columns,s=[],t=e=0,o=this.parsedChildren.length;0<=o?e<o:e>o;t=0<=o?++e:--e)r=this.parsedChildren[t].colspan,a=i.minColumns,r>l&&r>a?(i.minColumns=r,s.push(console.error("Shapeshift ERROR: There are child elements that have a larger colspan than the minimum columns set through options.\noptions.minColumns has been set to "+r))):s.push(void 0);return s},i.prototype.setParsedChildren=function(){var r,f,o,u,e,t,i;for(f=this.$container.find("."+this.options.activeClass).filter(":visible"),t=f.length,e=[],u=i=0;0<=t?i<t:i>t;u=0<=t?++i:--i)r=n(f[u]),o={i:u,el:r,colspan:parseInt(r.attr("data-ss-colspan"))||1,height:r.outerHeight()},e.push(o);return this.parsedChildren=e},i.prototype.gridInit=function(){var t,r,i,n,u;return n=this.options.gutterX,this.options.colWidth>=1?this.globals.col_width=this.options.colWidth+n:(i=this.parsedChildren[0],r=i.el.outerWidth(),t=i.colspan,u=(r-(t-1)*n)/t,this.globals.col_width=u+n)},i.prototype.render=function(n,t){return n==null&&(n=!1),n&&this.setActiveChildren(),this.setGridColumns(),this.arrange(!1,t)},i.prototype.setGridColumns=function(){var f,y,e,l,n,t,o,s,a,h,c,i,v,r,u;if(t=this.globals,i=this.options,e=t.col_width,s=i.gutterX,v=i.paddingX,h=this.$container.innerWidth()-v*2,c=i.minColumns,n=i.columns||Math.floor((h+s)/e),c&&c>n&&(n=c),t.columns=n,y=this.parsedChildren.length,n>y){for(f=0,a=r=0,u=this.parsedChildren.length;0<=u?r<u:r>u;a=0<=u?++r:--r)l=this.parsedChildren[a].colspan,l+f<=n&&(f+=l);n=f}t.child_offset=v;switch(i.align){case"center":return o=n*e-s,t.child_offset+=(h-o)/2;case"right":return o=n*e-s,t.child_offset+=h-o}},i.prototype.arrange=function(n,t){var r,e,l,a,v,b,u,k,y,s,p,h,c,i,w,d,f,o;for(n&&this.setParsedChildren(),y=this.globals,i=this.options,e=this.$container,b=this.getPositions(),w=this.parsedChildren,f=w.length,l=y.animated&&f<=i.animationThreshold,a=i.animationSpeed,k=i.draggedClass,s=o=0;0<=f?o<f:o>f;s=0<=f?++o:--o)r=w[s].el,v=b[s],p=r.hasClass(k),p&&(d=i.placeholderClass,r=r.siblings("."+d)),l&&!p?r.stop(!0,!1).animate(v,a,function(){}):r.css(v);return t&&(l?setTimeout(function(){return e.trigger("ss-drop-complete")},a):e.trigger("ss-drop-complete")),e.trigger("ss-arranged"),i.autoHeight?(u=y.container_height,h=i.maxHeight,c=i.minHeight,c&&u<c?u=c:h&&u>h&&(u=h),e.height(u)):void 0},i.prototype.getPositions=function(n){var t,h,d,p,i,w,c,r,u,l,a,v,b,y,f,e,o,s,k=this;for(n==null&&(n=!0),i=this.globals,u=this.options,c=u.gutterY,l=u.paddingY,p=u.draggedClass,a=this.parsedChildren,e=a.length,t=[],r=o=0,s=i.columns;0<=s?o<s:o>s;r=0<=s?++o:--o)t.push(l);return y=function(n){var u,r,e,s,h,f,o;if(u=n.col,r=n.colspan,s=n.col*i.col_width+i.child_offset,h=t[u],v[n.i]={left:s,top:h},t[u]+=n.height+c,r>=1){for(o=[],e=f=1;1<=r?f<r:f>r;e=1<=r?++f:--f)o.push(t[u+e]=t[u]);return o}},h=function(n){var o,e,r,l,s,a,h,v,i,c,u,f;for(i=t.length-n.colspan+1,v=t.slice(0).splice(0,i),o=void 0,h=u=0;0<=i?u<i:u>i;h=0<=i?++u:--u){for(e=k.lowestCol(v,h),r=n.colspan,l=t[e],s=!0,c=f=1;1<=r?f<r:f>r;c=1<=r?++f:--f)if(a=t[e+c],l<a){s=!1;break}if(s){o=e;break}}return o},f=[],b=function(){var c,e,n,r,u,t,o,i,l,s;for(u=[],r=t=0,i=f.length;0<=i?t<i:t>i;r=0<=i?++t:--t)n=f[r],n.col=h(n),n.col>=0&&(y(n),u.push(r));for(s=[],e=o=l=u.length-1;o>=0;e=o+=-1)c=u[e],s.push(f.splice(c,1));return s},v=[],(d=function(){var i,u,o;for(o=[],r=u=0;0<=e?u<e:u>e;r=0<=e?++u:--u)i=a[r],!n&&i.el.hasClass(p)?o.push(void 0):(i.col=i.colspan>1?h(i):k.lowestCol(t),i.col===void 0?f.push(i):y(i),o.push(b()));return o})(),u.autoHeight&&(w=t[this.highestCol(t)]-c,i.container_height=w+l),v},i.prototype.enableDragNDrop=function(){var o,l,s,i,d,a,u,v,h,g,c,y,r,f,p,e,w,b,k=this;return r=this.options,l=this.$container,d=r.activeClass,y=r.draggedClass,p=r.placeholderClass,f=r.originalContainerClass,u=r.currentContainerClass,e=r.previousContainerClass,v=r.deleteClone,g=r.dragRate,h=r.dragClone,a=r.cloneClass,i=s=o=b=w=null,c=!1,r.enableDrag&&l.children("."+d).filter(r.dragWhitelist).draggable({addClasses:!1,containment:"document",handle:r.handle,zIndex:9999,start:function(t){var r;return k.globals.dragging=!0,i=n(t.target),h&&(o=i.clone(!1,!1).insertBefore(i).addClass(a)),i.addClass(y),r=i.prop("tagName"),s=n("<"+r+" class='"+p+"' style='height: "+i.height()+"px; width: "+i.width()+"px'><\/"+r+">"),i.parent().addClass(f).addClass(u),b=i.outerHeight()/2,w=i.outerWidth()/2},drag:function(r,e){return c||h&&v&&n("."+u)[0]===n("."+f)[0]||(s.remove().appendTo("."+u),n("."+u).trigger("ss-setTargetPosition"),c=!0,t.setTimeout(function(){return c=!1},g)),e.position.left=r.pageX-i.parent().offset().left-w,e.position.top=r.pageY-i.parent().offset().top-b},stop:function(){var t,r,c;return k.globals.dragging=!1,r=n("."+f),t=n("."+u),c=n("."+e),i.removeClass(y),n("."+p).remove(),h&&(v&&n("."+u)[0]===n("."+f)[0]?(o.remove(),n("."+u).trigger("ss-rearrange")):(o.removeClass(a),r.shapeshift(r.data("plugin_shapeshift").options),t.shapeshift(t.data("plugin_shapeshift").options))),r[0]===t[0]?t.trigger("ss-rearranged",i):(r.trigger("ss-removed",i),t.trigger("ss-added",i)),r.trigger("ss-arrange").removeClass(f),t.trigger("ss-arrange",!0).removeClass(u),c.trigger("ss-arrange").removeClass(e),i=s=null}}),r.enableCrossDrop?l.droppable({accept:r.crossDropWhitelist,tolerance:"intersect",over:function(t){return n("."+e).removeClass(e),n("."+u).removeClass(u).addClass(e),n(t.target).addClass(u)},drop:function(t,r){var o,s,h;if(k.options.enableTrash)return s=n("."+f),o=n("."+u),h=n("."+e),i=n(r.helper),o.trigger("ss-trashed",i),i.remove(),s.trigger("ss-rearrange").removeClass(f),o.trigger("ss-rearrange").removeClass(u),h.trigger("ss-arrange").removeClass(e)}}):void 0},i.prototype.setTargetPosition=function(){var t,l,a,i,v,e,y,b,g,r,o,nt,u,p,k,tt,d,f,s,w,h,c;if(r=this.options,r.enableTrash)return nt=this.options.placeholderClass,n("."+nt).remove();if(g=r.draggedClass,t=n("."+g),l=t.parent(),o=this.parsedChildren,v=this.getPositions(!1),s=v.length,k=t.offset().left-l.offset().left+this.globals.col_width/2,tt=t.offset().top-l.offset().top+t.height()/2,d=9999999,f=0,s>1){for(y=r.cutoffStart+1||0,e=r.cutoffEnd||s,u=c=y;y<=e?c<e:c>e;u=y<=e?++c:--c)i=v[u],i&&(h=k-i.left,w=tt-i.top,h>0&&w>0&&(b=Math.sqrt(w*w+h*h),b<d&&(d=b,f=u,u===s-1&&h>o[u].height/2&&f++)));f===o.length?(a=o[f-1].el,t.insertAfter(a)):(a=o[f].el,t.insertBefore(a))}else s===1?(i=v[0],i.left<k?this.$container.append(t):this.$container.prepend(t)):this.$container.append(t);if(this.arrange(!0),l[0]!==t.parent()[0])return p=r.previousContainerClass,n("."+p).data("plugin_shapeshift").options.enableCrossDrop==!0?n("."+p).trigger("ss-rearrange"):n("."+p)},i.prototype.enableResize=function(){var i,f,r,u=this;i=this.options.animationSpeed;r=!1;f="resize."+this.identifier;return n(t).on(f,function(){if(!r)return r=!0,setTimeout(function(){return u.render()},i/3),setTimeout(function(){return u.render()},i/3),setTimeout(function(){return r=!1,u.render()},i/3)})},i.prototype.shuffle=function(){var n;return n=function(n,t){var i;return i=function(n){var t,i,r;for(i=void 0,r=void 0,t=n.length;t;)i=parseInt(Math.random()*t),r=n[--t],n[t]=n[i],n[i]=r;return n},n.each(function(){var r;return r=n.find("."+t).filter(":visible"),r.length?n.html(i(r)):this})},this.globals.dragging?void 0:(n(this.$container,this.options.activeClass),this.enableFeatures(),this.$container.trigger("ss-rearrange"))},i.prototype.lowestCol=function(n,t){var u,f,i,r;for(t==null&&(t=0),i=n.length,u=[],f=r=0;0<=i?r<i:r>i;f=0<=i?++r:--r)u.push([n[f],f]);return u.sort(function(n,t){var i;return i=n[0]-t[0],i===0&&(i=n[1]-t[1]),i}),u[t][1]},i.prototype.highestCol=function(i){return n.inArray(Math.max.apply(t,i),i)},i.prototype.destroy=function(){var t,n,i;return n=this.$container,n.off("ss-arrange"),n.off("ss-rearrange"),n.off("ss-setTargetPosition"),n.off("ss-destroy"),i=this.options.activeClass,t=n.find("."+i),this.options.enableDrag&&t.draggable("destroy"),this.options.enableCrossDrop&&n.droppable("destroy"),t.removeClass(i),n.removeClass(this.identifier)},i}(),n.fn[i]=function(u){return this.each(function(){var e,f,o,s;return f=(o=n(this).attr("class"))!=null?(s=o.match(/shapeshifted_container_\w+/))!=null?s[0]:void 0:void 0,f&&(e="resize."+f,n(t).off(e),n(this).removeClass(f)),n.data(this,"plugin_"+i,new r(this,u))})}})(jQuery,window,document)}).call(this);/*!
* Knockout JavaScript library v3.4.2
* (c) The Knockout.js team - http://knockoutjs.com/
* License: MIT (http://www.opensource.org/licenses/mit-license.php)
*/(function(){(function(n){var x=this||(0,eval)("this"),t=x.document,M=x.navigator,u=x.jQuery,H=x.JSON;(function(n){"function"===typeof define&&define.amd?define(["exports","require"],n):"object"===typeof exports&&"object"===typeof module?n(module.exports||exports):n(x.ko={})})(function(N,O){function J(a,c){return null===a||typeof a in R?a===c:!1}function S(b,c){var d;return function(){d||(d=a.a.setTimeout(function(){d=n;b()},c))}}function T(b,c){var d;return function(){clearTimeout(d);d=a.a.setTimeout(b,c)}}function U(a,c){c&&c!==E?"beforeChange"===c?this.Ob(a):this.Ja(a,c):this.Pb(a)}function V(a,c){null!==c&&c.k&&c.k()}function W(a,c){var d=this.Mc,e=d[s];e.T||(this.ob&&this.Oa[c]?(d.Sb(c,a,this.Oa[c]),this.Oa[c]=null,--this.ob):e.s[c]||d.Sb(c,a,e.t?{$:a}:d.yc(a)),a.Ha&&a.Hc())}function K(b,c,d,e){a.d[b]={init:function(b,g,h,l,m){var k,r;a.m(function(){var q=g(),p=a.a.c(q),p=!d!==!p,A=!r;if(A||c||p!==k)A&&a.xa.Ca()&&(r=a.a.wa(a.f.childNodes(b),!0)),p?(A||a.f.fa(b,a.a.wa(r)),a.hb(e?e(m,q):m,b)):a.f.za(b),k=p},null,{i:b});return{controlsDescendantBindings:!0}}};a.h.va[b]=!1;a.f.aa[b]=!0}var a="undefined"!==typeof N?N:{};a.b=function(b,c){for(var d=b.split("."),e=a,f=0;f<d.length-1;f++)e=e[d[f]];e[d[d.length-1]]=c};a.H=function(a,c,d){a[c]=d};a.version="3.4.2";a.b("version",a.version);a.options={deferUpdates:!1,useOnlyNativeEvents:!1};a.a=function(){function b(a,b){for(var c in a)a.hasOwnProperty(c)&&b(c,a[c])}function c(a,b){if(b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}function d(a,b){a.__proto__=b;return a}function e(b,c,d,e){var m=b[c].match(r)||[];a.a.r(d.match(r),function(b){a.a.ra(m,b,e)});b[c]=m.join(" ")}var f={__proto__:[]}instanceof Array,g="function"===typeof Symbol,h={},l={};h[M&&/Firefox\/2/i.test(M.userAgent)?"KeyboardEvent":"UIEvents"]=["keyup","keydown","keypress"];h.MouseEvents="click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" ");b(h,function(a,b){if(b.length)for(var c=0,d=b.length;c<d;c++)l[b[c]]=a});var m={propertychange:!0},k=t&&function(){for(var a=3,b=t.createElement("div"),c=b.getElementsByTagName("i");b.innerHTML="\x3c!--[if gt IE "+ ++a+"]><i></i><![endif]--\x3e",c[0];);return 4<a?a:n}(),r=/\S+/g;return{gc:["authenticity_token",/^__RequestVerificationToken(_.*)?$/],r:function(a,b){for(var c=0,d=a.length;c<d;c++)b(a[c],c)},o:function(a,b){if("function"==typeof Array.prototype.indexOf)return Array.prototype.indexOf.call(a,b);for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1},Vb:function(a,b,c){for(var d=0,e=a.length;d<e;d++)if(b.call(c,a[d],d))return a[d];return null},Na:function(b,c){var d=a.a.o(b,c);0<d?b.splice(d,1):0===d&&b.shift()},Wb:function(b){b=b||[];for(var c=[],d=0,e=b.length;d<e;d++)0>a.a.o(c,b[d])&&c.push(b[d]);return c},ib:function(a,b){a=a||[];for(var c=[],d=0,e=a.length;d<e;d++)c.push(b(a[d],d));return c},Ma:function(a,b){a=a||[];for(var c=[],d=0,e=a.length;d<e;d++)b(a[d],d)&&c.push(a[d]);return c},ta:function(a,b){if(b instanceof Array)a.push.apply(a,b);else for(var c=0,d=b.length;c<d;c++)a.push(b[c]);return a},ra:function(b,c,d){var e=a.a.o(a.a.Bb(b),c);0>e?d&&b.push(c):d||b.splice(e,1)},la:f,extend:c,$a:d,ab:f?d:c,D:b,Ea:function(a,b){if(!a)return a;var c={},d;for(d in a)a.hasOwnProperty(d)&&(c[d]=b(a[d],d,a));return c},rb:function(b){for(;b.firstChild;)a.removeNode(b.firstChild)},nc:function(b){b=a.a.W(b);for(var c=(b[0]&&b[0].ownerDocument||t).createElement("div"),d=0,e=b.length;d<e;d++)c.appendChild(a.ba(b[d]));return c},wa:function(b,c){for(var d=0,e=b.length,m=[];d<e;d++){var k=b[d].cloneNode(!0);m.push(c?a.ba(k):k)}return m},fa:function(b,c){a.a.rb(b);if(c)for(var d=0,e=c.length;d<e;d++)b.appendChild(c[d])},uc:function(b,c){var d=b.nodeType?[b]:b;if(0<d.length){for(var e=d[0],m=e.parentNode,k=0,f=c.length;k<f;k++)m.insertBefore(c[k],e);k=0;for(f=d.length;k<f;k++)a.removeNode(d[k])}},Ba:function(a,b){if(a.length){for(b=8===b.nodeType&&b.parentNode||b;a.length&&a[0].parentNode!==b;)a.splice(0,1);for(;1<a.length&&a[a.length-1].parentNode!==b;)a.length--;if(1<a.length){var c=a[0],d=a[a.length-1];for(a.length=0;c!==d;)a.push(c),c=c.nextSibling;a.push(d)}}return a},wc:function(a,b){7>k?a.setAttribute("selected",b):a.selected=b},cb:function(a){return null===a||a===n?"":a.trim?a.trim():a.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")},sd:function(a,b){a=a||"";return b.length>a.length?!1:a.substring(0,b.length)===b},Rc:function(a,b){if(a===b)return!0;if(11===a.nodeType)return!1;if(b.contains)return b.contains(3===a.nodeType?a.parentNode:a);if(b.compareDocumentPosition)return 16==(b.compareDocumentPosition(a)&16);for(;a&&a!=b;)a=a.parentNode;return!!a},qb:function(b){return a.a.Rc(b,b.ownerDocument.documentElement)},Tb:function(b){return!!a.a.Vb(b,a.a.qb)},A:function(a){return a&&a.tagName&&a.tagName.toLowerCase()},Zb:function(b){return a.onError?function(){try{return b.apply(this,arguments)}catch(c){throw a.onError&&a.onError(c),c;}}:b},setTimeout:function(b,c){return setTimeout(a.a.Zb(b),c)},dc:function(b){setTimeout(function(){a.onError&&a.onError(b);throw b;},0)},q:function(b,c,d){var e=a.a.Zb(d);d=k&&m[c];if(a.options.useOnlyNativeEvents||d||!u)if(d||"function"!=typeof b.addEventListener)if("undefined"!=typeof b.attachEvent){var f=function(a){e.call(b,a)},l="on"+c;b.attachEvent(l,f);a.a.G.qa(b,function(){b.detachEvent(l,f)})}else throw Error("Browser doesn't support addEventListener or attachEvent");else b.addEventListener(c,e,!1);else u(b).bind(c,e)},Fa:function(b,c){if(!b||!b.nodeType)throw Error("element must be a DOM node when calling triggerEvent");var d;"input"===a.a.A(b)&&b.type&&"click"==c.toLowerCase()?(d=b.type,d="checkbox"==d||"radio"==d):d=!1;if(a.options.useOnlyNativeEvents||!u||d)if("function"==typeof t.createEvent)if("function"==typeof b.dispatchEvent)d=t.createEvent(l[c]||"HTMLEvents"),d.initEvent(c,!0,!0,x,0,0,0,0,0,!1,!1,!1,!1,0,b),b.dispatchEvent(d);else throw Error("The supplied element doesn't support dispatchEvent");else if(d&&b.click)b.click();else if("undefined"!=typeof b.fireEvent)b.fireEvent("on"+c);else throw Error("Browser doesn't support triggering events");else u(b).trigger(c)},c:function(b){return a.I(b)?b():b},Bb:function(b){return a.I(b)?b.p():b},fb:function(b,c,d){var k;c&&("object"===typeof b.classList?(k=b.classList[d?"add":"remove"],a.a.r(c.match(r),function(a){k.call(b.classList,a)})):"string"===typeof b.className.baseVal?e(b.className,"baseVal",c,d):e(b,"className",c,d))},bb:function(b,c){var d=a.a.c(c);if(null===d||d===n)d="";var e=a.f.firstChild(b);!e||3!=e.nodeType||a.f.nextSibling(e)?a.f.fa(b,[b.ownerDocument.createTextNode(d)]):e.data=d;a.a.Wc(b)},vc:function(a,b){a.name=b;if(7>=k)try{a.mergeAttributes(t.createElement("<input name='"+a.name+"'/>"),!1)}catch(c){}},Wc:function(a){9<=k&&(a=1==a.nodeType?a:a.parentNode,a.style&&(a.style.zoom=a.style.zoom))},Sc:function(a){if(k){var b=a.style.width;a.style.width=0;a.style.width=b}},nd:function(b,c){b=a.a.c(b);c=a.a.c(c);for(var d=[],e=b;e<=c;e++)d.push(e);return d},W:function(a){for(var b=[],c=0,d=a.length;c<d;c++)b.push(a[c]);return b},bc:function(a){return g?Symbol(a):a},xd:6===k,yd:7===k,C:k,ic:function(b,c){for(var d=a.a.W(b.getElementsByTagName("input")).concat(a.a.W(b.getElementsByTagName("textarea"))),e="string"==typeof c?function(a){return a.name===c}:function(a){return c.test(a.name)},k=[],m=d.length-1;0<=m;m--)e(d[m])&&k.push(d[m]);return k},kd:function(b){return"string"==typeof b&&(b=a.a.cb(b))?H&&H.parse?H.parse(b):(new Function("return "+b))():null},Gb:function(b,c,d){if(!H||!H.stringify)throw Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");return H.stringify(a.a.c(b),c,d)},ld:function(c,d,e){e=e||{};var k=e.params||{},m=e.includeFields||this.gc,f=c;if("object"==typeof c&&"form"===a.a.A(c))for(var f=c.action,l=m.length-1;0<=l;l--)for(var g=a.a.ic(c,m[l]),h=g.length-1;0<=h;h--)k[g[h].name]=g[h].value;d=a.a.c(d);var r=t.createElement("form");r.style.display="none";r.action=f;r.method="post";for(var n in d)c=t.createElement("input"),c.type="hidden",c.name=n,c.value=a.a.Gb(a.a.c(d[n])),r.appendChild(c);b(k,function(a,b){var c=t.createElement("input");c.type="hidden";c.name=a;c.value=b;r.appendChild(c)});t.body.appendChild(r);e.submitter?e.submitter(r):r.submit();setTimeout(function(){r.parentNode.removeChild(r)},0)}}}();a.b("utils",a.a);a.b("utils.arrayForEach",a.a.r);a.b("utils.arrayFirst",a.a.Vb);a.b("utils.arrayFilter",a.a.Ma);a.b("utils.arrayGetDistinctValues",a.a.Wb);a.b("utils.arrayIndexOf",a.a.o);a.b("utils.arrayMap",a.a.ib);a.b("utils.arrayPushAll",a.a.ta);a.b("utils.arrayRemoveItem",a.a.Na);a.b("utils.extend",a.a.extend);a.b("utils.fieldsIncludedWithJsonPost",a.a.gc);a.b("utils.getFormFields",a.a.ic);a.b("utils.peekObservable",a.a.Bb);a.b("utils.postJson",a.a.ld);a.b("utils.parseJson",a.a.kd);a.b("utils.registerEventHandler",a.a.q);a.b("utils.stringifyJson",a.a.Gb);a.b("utils.range",a.a.nd);a.b("utils.toggleDomNodeCssClass",a.a.fb);a.b("utils.triggerEvent",a.a.Fa);a.b("utils.unwrapObservable",a.a.c);a.b("utils.objectForEach",a.a.D);a.b("utils.addOrRemoveItem",a.a.ra);a.b("utils.setTextContent",a.a.bb);a.b("unwrap",a.a.c);Function.prototype.bind||(Function.prototype.bind=function(a){var c=this;if(1===arguments.length)return function(){return c.apply(a,arguments)};var d=Array.prototype.slice.call(arguments,1);return function(){var e=d.slice(0);e.push.apply(e,arguments);return c.apply(a,e)}});a.a.e=new function(){function a(b,g){var h=b[d];if(!h||"null"===h||!e[h]){if(!g)return n;h=b[d]="ko"+c++;e[h]={}}return e[h]}var c=0,d="__ko__"+(new Date).getTime(),e={};return{get:function(c,d){var e=a(c,!1);return e===n?n:e[d]},set:function(c,d,e){if(e!==n||a(c,!1)!==n)a(c,!0)[d]=e},clear:function(a){var b=a[d];return b?(delete e[b],a[d]=null,!0):!1},J:function(){return c++ +d}}};a.b("utils.domData",a.a.e);a.b("utils.domData.clear",a.a.e.clear);a.a.G=new function(){function b(b,c){var e=a.a.e.get(b,d);e===n&&c&&(e=[],a.a.e.set(b,d,e));return e}function c(d){var e=b(d,!1);if(e)for(var e=e.slice(0),l=0;l<e.length;l++)e[l](d);a.a.e.clear(d);a.a.G.cleanExternalData(d);if(f[d.nodeType])for(e=d.firstChild;d=e;)e=d.nextSibling,8===d.nodeType&&c(d)}var d=a.a.e.J(),e={1:!0,8:!0,9:!0},f={1:!0,9:!0};return{qa:function(a,c){if("function"!=typeof c)throw Error("Callback must be a function");b(a,!0).push(c)},tc:function(c,e){var f=b(c,!1);f&&(a.a.Na(f,e),0==f.length&&a.a.e.set(c,d,n))},ba:function(b){if(e[b.nodeType]&&(c(b),f[b.nodeType])){var d=[];a.a.ta(d,b.getElementsByTagName("*"));for(var l=0,m=d.length;l<m;l++)c(d[l])}return b},removeNode:function(b){a.ba(b);b.parentNode&&b.parentNode.removeChild(b)},cleanExternalData:function(a){u&&"function"==typeof u.cleanData&&u.cleanData([a])}}};a.ba=a.a.G.ba;a.removeNode=a.a.G.removeNode;a.b("cleanNode",a.ba);a.b("removeNode",a.removeNode);a.b("utils.domNodeDisposal",a.a.G);a.b("utils.domNodeDisposal.addDisposeCallback",a.a.G.qa);a.b("utils.domNodeDisposal.removeDisposeCallback",a.a.G.tc);(function(){var b=[0,"",""],c=[1,"<table>","</table>"],d=[3,"<table><tbody><tr>","</tr></tbody></table>"],e=[1,"<select multiple='multiple'>","</select>"],f={thead:c,tbody:c,tfoot:c,tr:[2,"<table><tbody>","</tbody></table>"],td:d,th:d,option:e,optgroup:e},g=8>=a.a.C;a.a.na=function(c,d){var e;if(u)if(u.parseHTML)e=u.parseHTML(c,d)||[];else{if((e=u.clean([c],d))&&e[0]){for(var k=e[0];k.parentNode&&11!==k.parentNode.nodeType;)k=k.parentNode;k.parentNode&&k.parentNode.removeChild(k)}}else{(e=d)||(e=t);var k=e.parentWindow||e.defaultView||x,r=a.a.cb(c).toLowerCase(),q=e.createElement("div"),p;p=(r=r.match(/^<([a-z]+)[ >]/))&&f[r[1]]||b;r=p[0];p="ignored<div>"+p[1]+c+p[2]+"</div>";"function"==typeof k.innerShiv?q.appendChild(k.innerShiv(p)):(g&&e.appendChild(q),q.innerHTML=p,g&&q.parentNode.removeChild(q));for(;r--;)q=q.lastChild;e=a.a.W(q.lastChild.childNodes)}return e};a.a.Eb=function(b,c){a.a.rb(b);c=a.a.c(c);if(null!==c&&c!==n)if("string"!=typeof c&&(c=c.toString()),u)u(b).html(c);else for(var d=a.a.na(c,b.ownerDocument),e=0;e<d.length;e++)b.appendChild(d[e])}})();a.b("utils.parseHtmlFragment",a.a.na);a.b("utils.setHtml",a.a.Eb);a.N=function(){function b(c,e){if(c)if(8==c.nodeType){var f=a.N.pc(c.nodeValue);null!=f&&e.push({Qc:c,hd:f})}else if(1==c.nodeType)for(var f=0,g=c.childNodes,h=g.length;f<h;f++)b(g[f],e)}var c={};return{yb:function(a){if("function"!=typeof a)throw Error("You can only pass a function to ko.memoization.memoize()");var b=(4294967296*(1+Math.random())|0).toString(16).substring(1)+(4294967296*(1+Math.random())|0).toString(16).substring(1);c[b]=a;return"\x3c!--[ko_memo:"+b+"]--\x3e"},Bc:function(a,b){var f=c[a];if(f===n)throw Error("Couldn't find any memo with ID "+a+". Perhaps it's already been unmemoized.");try{return f.apply(null,b||[]),!0}finally{delete c[a]}},Cc:function(c,e){var f=[];b(c,f);for(var g=0,h=f.length;g<h;g++){var l=f[g].Qc,m=[l];e&&a.a.ta(m,e);a.N.Bc(f[g].hd,m);l.nodeValue="";l.parentNode&&l.parentNode.removeChild(l)}},pc:function(a){return(a=a.match(/^\[ko_memo\:(.*?)\]$/))?a[1]:null}}}();a.b("memoization",a.N);a.b("memoization.memoize",a.N.yb);a.b("memoization.unmemoize",a.N.Bc);a.b("memoization.parseMemoText",a.N.pc);a.b("memoization.unmemoizeDomNodeAndDescendants",a.N.Cc);a.Z=function(){function b(){if(e)for(var b=e,c=0,m;g<e;)if(m=d[g++]){if(g>b){if(5E3<=++c){g=e;a.a.dc(Error("'Too much recursion' after processing "+c+" task groups."));break}b=e}try{m()}catch(k){a.a.dc(k)}}}function c(){b();g=e=d.length=0}var d=[],e=0,f=1,g=0;return{scheduler:x.MutationObserver?function(a){var b=t.createElement("div");(new MutationObserver(a)).observe(b,{attributes:!0});return function(){b.classList.toggle("foo")}}(c):t&&"onreadystatechange"in t.createElement("script")?function(a){var b=t.createElement("script");b.onreadystatechange=function(){b.onreadystatechange=null;t.documentElement.removeChild(b);b=null;a()};t.documentElement.appendChild(b)}:function(a){setTimeout(a,0)},Za:function(b){e||a.Z.scheduler(c);d[e++]=b;return f++},cancel:function(a){a-=f-e;a>=g&&a<e&&(d[a]=null)},resetForTesting:function(){var a=e-g;g=e=d.length=0;return a},rd:b}}();a.b("tasks",a.Z);a.b("tasks.schedule",a.Z.Za);a.b("tasks.runEarly",a.Z.rd);a.Aa={throttle:function(b,c){b.throttleEvaluation=c;var d=null;return a.B({read:b,write:function(e){clearTimeout(d);d=a.a.setTimeout(function(){b(e)},c)}})},rateLimit:function(a,c){var d,e,f;"number"==typeof c?d=c:(d=c.timeout,e=c.method);a.gb=!1;f="notifyWhenChangesStop"==e?T:S;a.Wa(function(a){return f(a,d)})},deferred:function(b,c){if(!0!==c)throw Error("The 'deferred' extender only accepts the value 'true', because it is not supported to turn deferral off once enabled.");b.gb||(b.gb=!0,b.Wa(function(c){var e,f=!1;return function(){if(!f){a.Z.cancel(e);e=a.Z.Za(c);try{f=!0,b.notifySubscribers(n,"dirty")}finally{f=!1}}}}))},notify:function(a,c){a.equalityComparer="always"==c?null:J}};var R={undefined:1,"boolean":1,number:1,string:1};a.b("extenders",a.Aa);a.zc=function(b,c,d){this.$=b;this.jb=c;this.Pc=d;this.T=!1;a.H(this,"dispose",this.k)};a.zc.prototype.k=function(){this.T=!0;this.Pc()};a.K=function(){a.a.ab(this,D);D.ub(this)};var E="change",D={ub:function(a){a.F={change:[]};a.Qb=1},Y:function(b,c,d){var e=this;d=d||E;var f=new a.zc(e,c?b.bind(c):b,function(){a.a.Na(e.F[d],f);e.Ka&&e.Ka(d)});e.ua&&e.ua(d);e.F[d]||(e.F[d]=[]);e.F[d].push(f);return f},notifySubscribers:function(b,c){c=c||E;c===E&&this.Kb();if(this.Ra(c)){var d=c===E&&this.Fc||this.F[c].slice(0);try{a.l.Xb();for(var e=0,f;f=d[e];++e)f.T||f.jb(b)}finally{a.l.end()}}},Pa:function(){return this.Qb},Zc:function(a){return this.Pa()!==a},Kb:function(){++this.Qb},Wa:function(b){var c=this,d=a.I(c),e,f,g,h;c.Ja||(c.Ja=c.notifySubscribers,c.notifySubscribers=U);var l=b(function(){c.Ha=!1;d&&h===c&&(h=c.Mb?c.Mb():c());var a=f||c.Ua(g,h);f=e=!1;a&&c.Ja(g=h)});c.Pb=function(a){c.Fc=c.F[E].slice(0);c.Ha=e=!0;h=a;l()};c.Ob=function(a){e||(g=a,c.Ja(a,"beforeChange"))};c.Hc=function(){c.Ua(g,c.p(!0))&&(f=!0)}},Ra:function(a){return this.F[a]&&this.F[a].length},Xc:function(b){if(b)return this.F[b]&&this.F[b].length||0;var c=0;a.a.D(this.F,function(a,b){"dirty"!==a&&(c+=b.length)});return c},Ua:function(a,c){return!this.equalityComparer||!this.equalityComparer(a,c)},extend:function(b){var c=this;b&&a.a.D(b,function(b,e){var f=a.Aa[b];"function"==typeof f&&(c=f(c,e)||c)});return c}};a.H(D,"subscribe",D.Y);a.H(D,"extend",D.extend);a.H(D,"getSubscriptionsCount",D.Xc);a.a.la&&a.a.$a(D,Function.prototype);a.K.fn=D;a.lc=function(a){return null!=a&&"function"==typeof a.Y&&"function"==typeof a.notifySubscribers};a.b("subscribable",a.K);a.b("isSubscribable",a.lc);a.xa=a.l=function(){function b(a){d.push(e);e=a}function c(){e=d.pop()}var d=[],e,f=0;return{Xb:b,end:c,sc:function(b){if(e){if(!a.lc(b))throw Error("Only subscribable things can act as dependencies");e.jb.call(e.Lc,b,b.Gc||(b.Gc=++f))}},w:function(a,d,e){try{return b(),a.apply(d,e||[])}finally{c()}},Ca:function(){if(e)return e.m.Ca()},Va:function(){if(e)return e.Va}}}();a.b("computedContext",a.xa);a.b("computedContext.getDependenciesCount",a.xa.Ca);a.b("computedContext.isInitial",a.xa.Va);a.b("ignoreDependencies",a.wd=a.l.w);var F=a.a.bc("_latestValue");a.O=function(b){function c(){if(0<arguments.length)return c.Ua(c[F],arguments[0])&&(c.ia(),c[F]=arguments[0],c.ha()),this;a.l.sc(c);return c[F]}
c[F]=b;a.a.la||a.a.extend(c,a.K.fn);a.K.fn.ub(c);a.a.ab(c,B);a.options.deferUpdates&&a.Aa.deferred(c,!0);return c};var B={equalityComparer:J,p:function(){return this[F]},ha:function(){this.notifySubscribers(this[F])},ia:function(){this.notifySubscribers(this[F],"beforeChange")}};a.a.la&&a.a.$a(B,a.K.fn);var I=a.O.md="__ko_proto__";B[I]=a.O;a.Qa=function(b,c){return null===b||b===n||b[I]===n?!1:b[I]===c?!0:a.Qa(b[I],c)};a.I=function(b){return a.Qa(b,a.O)};a.Da=function(b){return"function"==typeof b&&b[I]===a.O||"function"==typeof b&&b[I]===a.B&&b.$c?!0:!1};a.b("observable",a.O);a.b("isObservable",a.I);a.b("isWriteableObservable",a.Da);a.b("isWritableObservable",a.Da);a.b("observable.fn",B);a.H(B,"peek",B.p);a.H(B,"valueHasMutated",B.ha);a.H(B,"valueWillMutate",B.ia);a.ma=function(b){b=b||[];if("object"!=typeof b||!("length"in b))throw Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");b=a.O(b);a.a.ab(b,a.ma.fn);return b.extend({trackArrayChanges:!0})};a.ma.fn={remove:function(b){for(var c=this.p(),d=[],e="function"!=typeof b||a.I(b)?function(a){return a===b}:b,f=0;f<c.length;f++){var g=c[f];e(g)&&(0===d.length&&this.ia(),d.push(g),c.splice(f,1),f--)}d.length&&this.ha();return d},removeAll:function(b){if(b===n){var c=this.p(),d=c.slice(0);this.ia();c.splice(0,c.length);this.ha();return d}return b?this.remove(function(c){return 0<=a.a.o(b,c)}):[]},destroy:function(b){var c=this.p(),d="function"!=typeof b||a.I(b)?function(a){return a===b}:b;this.ia();for(var e=c.length-1;0<=e;e--)d(c[e])&&(c[e]._destroy=!0);this.ha()},destroyAll:function(b){return b===n?this.destroy(function(){return!0}):b?this.destroy(function(c){return 0<=a.a.o(b,c)}):[]},indexOf:function(b){var c=this();return a.a.o(c,b)},replace:function(a,c){var d=this.indexOf(a);0<=d&&(this.ia(),this.p()[d]=c,this.ha())}};a.a.la&&a.a.$a(a.ma.fn,a.O.fn);a.a.r("pop push reverse shift sort splice unshift".split(" "),function(b){a.ma.fn[b]=function(){var a=this.p();this.ia();this.Yb(a,b,arguments);var d=a[b].apply(a,arguments);this.ha();return d===a?this:d}});a.a.r(["slice"],function(b){a.ma.fn[b]=function(){var a=this();return a[b].apply(a,arguments)}});a.b("observableArray",a.ma);a.Aa.trackArrayChanges=function(b,c){function d(){if(!e){e=!0;l=b.notifySubscribers;b.notifySubscribers=function(a,b){b&&b!==E||++h;return l.apply(this,arguments)};var c=[].concat(b.p()||[]);f=null;g=b.Y(function(d){d=[].concat(d||[]);if(b.Ra("arrayChange")){var e;if(!f||1<h)f=a.a.lb(c,d,b.kb);e=f}c=d;f=null;h=0;e&&e.length&&b.notifySubscribers(e,"arrayChange")})}}b.kb={};c&&"object"==typeof c&&a.a.extend(b.kb,c);b.kb.sparse=!0;if(!b.Yb){var e=!1,f=null,g,h=0,l,m=b.ua,k=b.Ka;b.ua=function(a){m&&m.call(b,a);"arrayChange"===a&&d()};b.Ka=function(a){k&&k.call(b,a);"arrayChange"!==a||b.Ra("arrayChange")||(l&&(b.notifySubscribers=l,l=n),g.k(),e=!1)};b.Yb=function(b,c,d){function k(a,b,c){return m[m.length]={status:a,value:b,index:c}}if(e&&!h){var m=[],l=b.length,g=d.length,G=0;switch(c){case "push":G=l;case "unshift":for(c=0;c<g;c++)k("added",d[c],G+c);break;case "pop":G=l-1;case "shift":l&&k("deleted",b[G],G);break;case "splice":c=Math.min(Math.max(0,0>d[0]?l+d[0]:d[0]),l);for(var l=1===g?l:Math.min(c+(d[1]||0),l),g=c+g-2,G=Math.max(l,g),n=[],s=[],w=2;c<G;++c,++w)c<l&&s.push(k("deleted",b[c],c)),c<g&&n.push(k("added",d[w],c));a.a.hc(s,n);break;default:return}f=m}}}};var s=a.a.bc("_state");a.m=a.B=function(b,c,d){function e(){if(0<arguments.length){if("function"===typeof f)f.apply(g.sb,arguments);else throw Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");return this}a.l.sc(e);(g.V||g.t&&e.Sa())&&e.U();return g.M}"object"===typeof b?d=b:(d=d||{},b&&(d.read=b));if("function"!=typeof d.read)throw Error("Pass a function that returns the value of the ko.computed");var f=d.write,g={M:n,da:!0,V:!0,Ta:!1,Hb:!1,T:!1,Ya:!1,t:!1,od:d.read,sb:c||d.owner,i:d.disposeWhenNodeIsRemoved||d.i||null,ya:d.disposeWhen||d.ya,pb:null,s:{},L:0,fc:null};e[s]=g;e.$c="function"===typeof f;a.a.la||a.a.extend(e,a.K.fn);a.K.fn.ub(e);a.a.ab(e,z);d.pure?(g.Ya=!0,g.t=!0,a.a.extend(e,Y)):d.deferEvaluation&&a.a.extend(e,Z);a.options.deferUpdates&&a.Aa.deferred(e,!0);g.i&&(g.Hb=!0,g.i.nodeType||(g.i=null));g.t||d.deferEvaluation||e.U();g.i&&e.ca()&&a.a.G.qa(g.i,g.pb=function(){e.k()});return e};var z={equalityComparer:J,Ca:function(){return this[s].L},Sb:function(a,c,d){if(this[s].Ya&&c===this)throw Error("A 'pure' computed must not be called recursively");this[s].s[a]=d;d.Ia=this[s].L++;d.pa=c.Pa()},Sa:function(){var a,c,d=this[s].s;for(a in d)if(d.hasOwnProperty(a)&&(c=d[a],this.oa&&c.$.Ha||c.$.Zc(c.pa)))return!0},gd:function(){this.oa&&!this[s].Ta&&this.oa(!1)},ca:function(){var a=this[s];return a.V||0<a.L},qd:function(){this.Ha?this[s].V&&(this[s].da=!0):this.ec()},yc:function(a){if(a.gb&&!this[s].i){var c=a.Y(this.gd,this,"dirty"),d=a.Y(this.qd,this);return{$:a,k:function(){c.k();d.k()}}}return a.Y(this.ec,this)},ec:function(){var b=this,c=b.throttleEvaluation;c&&0<=c?(clearTimeout(this[s].fc),this[s].fc=a.a.setTimeout(function(){b.U(!0)},c)):b.oa?b.oa(!0):b.U(!0)},U:function(b){var c=this[s],d=c.ya,e=!1;if(!c.Ta&&!c.T){if(c.i&&!a.a.qb(c.i)||d&&d()){if(!c.Hb){this.k();return}}else c.Hb=!1;c.Ta=!0;try{e=this.Vc(b)}finally{c.Ta=!1}c.L||this.k();return e}},Vc:function(b){var c=this[s],d=!1,e=c.Ya?n:!c.L,f={Mc:this,Oa:c.s,ob:c.L};a.l.Xb({Lc:f,jb:W,m:this,Va:e});c.s={};c.L=0;f=this.Uc(c,f);this.Ua(c.M,f)&&(c.t||this.notifySubscribers(c.M,"beforeChange"),c.M=f,c.t?this.Kb():b&&this.notifySubscribers(c.M),d=!0);e&&this.notifySubscribers(c.M,"awake");return d},Uc:function(b,c){try{var d=b.od;return b.sb?d.call(b.sb):d()}finally{a.l.end(),c.ob&&!b.t&&a.a.D(c.Oa,V),b.da=b.V=!1}},p:function(a){var c=this[s];(c.V&&(a||!c.L)||c.t&&this.Sa())&&this.U();return c.M},Wa:function(b){a.K.fn.Wa.call(this,b);this.Mb=function(){this[s].da?this.U():this[s].V=!1;return this[s].M};this.oa=function(a){this.Ob(this[s].M);this[s].V=!0;a&&(this[s].da=!0);this.Pb(this)}},k:function(){var b=this[s];!b.t&&b.s&&a.a.D(b.s,function(a,b){b.k&&b.k()});b.i&&b.pb&&a.a.G.tc(b.i,b.pb);b.s=null;b.L=0;b.T=!0;b.da=!1;b.V=!1;b.t=!1;b.i=null}},Y={ua:function(b){var c=this,d=c[s];if(!d.T&&d.t&&"change"==b){d.t=!1;if(d.da||c.Sa())d.s=null,d.L=0,c.U()&&c.Kb();else{var e=[];a.a.D(d.s,function(a,b){e[b.Ia]=a});a.a.r(e,function(a,b){var e=d.s[a],l=c.yc(e.$);l.Ia=b;l.pa=e.pa;d.s[a]=l})}d.T||c.notifySubscribers(d.M,"awake")}},Ka:function(b){var c=this[s];c.T||"change"!=b||this.Ra("change")||(a.a.D(c.s,function(a,b){b.k&&(c.s[a]={$:b.$,Ia:b.Ia,pa:b.pa},b.k())}),c.t=!0,this.notifySubscribers(n,"asleep"))},Pa:function(){var b=this[s];b.t&&(b.da||this.Sa())&&this.U();return a.K.fn.Pa.call(this)}},Z={ua:function(a){"change"!=a&&"beforeChange"!=a||this.p()}};a.a.la&&a.a.$a(z,a.K.fn);var P=a.O.md;a.m[P]=a.O;z[P]=a.m;a.bd=function(b){return a.Qa(b,a.m)};a.cd=function(b){return a.Qa(b,a.m)&&b[s]&&b[s].Ya};a.b("computed",a.m);a.b("dependentObservable",a.m);a.b("isComputed",a.bd);a.b("isPureComputed",a.cd);a.b("computed.fn",z);a.H(z,"peek",z.p);a.H(z,"dispose",z.k);a.H(z,"isActive",z.ca);a.H(z,"getDependenciesCount",z.Ca);a.rc=function(b,c){if("function"===typeof b)return a.m(b,c,{pure:!0});b=a.a.extend({},b);b.pure=!0;return a.m(b,c)};a.b("pureComputed",a.rc);(function(){function b(a,f,g){g=g||new d;a=f(a);if("object"!=typeof a||null===a||a===n||a instanceof RegExp||a instanceof Date||a instanceof String||a instanceof Number||a instanceof Boolean)return a;var h=a instanceof Array?[]:{};g.save(a,h);c(a,function(c){var d=f(a[c]);switch(typeof d){case "boolean":case "number":case "string":case "function":h[c]=d;break;case "object":case "undefined":var k=g.get(d);h[c]=k!==n?k:b(d,f,g)}});return h}function c(a,b){if(a instanceof Array){for(var c=0;c<a.length;c++)b(c);"function"==typeof a.toJSON&&b("toJSON")}else for(c in a)b(c)}function d(){this.keys=[];this.Lb=[]}a.Ac=function(c){if(0==arguments.length)throw Error("When calling ko.toJS, pass the object you want to convert.");return b(c,function(b){for(var c=0;a.I(b)&&10>c;c++)b=b();return b})};a.toJSON=function(b,c,d){b=a.Ac(b);return a.a.Gb(b,c,d)};d.prototype={save:function(b,c){var d=a.a.o(this.keys,b);0<=d?this.Lb[d]=c:(this.keys.push(b),this.Lb.push(c))},get:function(b){b=a.a.o(this.keys,b);return 0<=b?this.Lb[b]:n}}})();a.b("toJS",a.Ac);a.b("toJSON",a.toJSON);(function(){a.j={u:function(b){switch(a.a.A(b)){case "option":return!0===b.__ko__hasDomDataOptionValue__?a.a.e.get(b,a.d.options.zb):7>=a.a.C?b.getAttributeNode("value")&&b.getAttributeNode("value").specified?b.value:b.text:b.value;case "select":return 0<=b.selectedIndex?a.j.u(b.options[b.selectedIndex]):n;default:return b.value}},ja:function(b,c,d){switch(a.a.A(b)){case "option":switch(typeof c){case "string":a.a.e.set(b,a.d.options.zb,n);"__ko__hasDomDataOptionValue__"in b&&delete b.__ko__hasDomDataOptionValue__;b.value=c;break;default:a.a.e.set(b,a.d.options.zb,c),b.__ko__hasDomDataOptionValue__=!0,b.value="number"===typeof c?c:""}break;case "select":if(""===c||null===c)c=n;for(var e=-1,f=0,g=b.options.length,h;f<g;++f)if(h=a.j.u(b.options[f]),h==c||""==h&&c===n){e=f;break}if(d||0<=e||c===n&&1<b.size)b.selectedIndex=e;break;default:if(null===c||c===n)c="";b.value=c}}}})();a.b("selectExtensions",a.j);a.b("selectExtensions.readValue",a.j.u);a.b("selectExtensions.writeValue",a.j.ja);a.h=function(){function b(b){b=a.a.cb(b);123===b.charCodeAt(0)&&(b=b.slice(1,-1));var c=[],d=b.match(e),r,h=[],p=0;if(d){d.push(",");for(var A=0,y;y=d[A];++A){var v=y.charCodeAt(0);if(44===v){if(0>=p){c.push(r&&h.length?{key:r,value:h.join("")}:{unknown:r||h.join("")});r=p=0;h=[];continue}}else if(58===v){if(!p&&!r&&1===h.length){r=h.pop();continue}}else 47===v&&A&&1<y.length?(v=d[A-1].match(f))&&!g[v[0]]&&(b=b.substr(b.indexOf(y)+1),d=b.match(e),d.push(","),A=-1,y="/"):40===v||123===v||91===v?++p:41===v||125===v||93===v?--p:r||h.length||34!==v&&39!==v||(y=y.slice(1,-1));h.push(y)}}return c}var c=["true","false","null","undefined"],d=/^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i,e=RegExp("\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|/(?:[^/\\\\]|\\\\.)*/w*|[^\\s:,/][^,\"'{}()/:[\\]]*[^\\s,\"'{}()/:[\\]]|[^\\s]","g"),f=/[\])"'A-Za-z0-9_$]+$/,g={"in":1,"return":1,"typeof":1},h={};return{va:[],ga:h,Ab:b,Xa:function(e,m){function k(b,e){var m;if(!A){var l=a.getBindingHandler(b);if(l&&l.preprocess&&!(e=l.preprocess(e,b,k)))return;if(l=h[b])m=e,0<=a.a.o(c,m)?m=!1:(l=m.match(d),m=null===l?!1:l[1]?"Object("+l[1]+")"+l[2]:m),l=m;l&&g.push("'"+b+"':function(_z){"+m+"=_z}")}p&&(e="function(){return "+e+" }");f.push("'"+b+"':"+e)}m=m||{};var f=[],g=[],p=m.valueAccessors,A=m.bindingParams,y="string"===typeof e?b(e):e;a.a.r(y,function(a){k(a.key||a.unknown,a.value)});g.length&&k("_ko_property_writers","{"+g.join(",")+" }");return f.join(",")},fd:function(a,b){for(var c=0;c<a.length;c++)if(a[c].key==b)return!0;return!1},Ga:function(b,c,d,e,f){if(b&&a.I(b))!a.Da(b)||f&&b.p()===e||b(e);else if((b=c.get("_ko_property_writers"))&&b[d])b[d](e)}}}();a.b("expressionRewriting",a.h);a.b("expressionRewriting.bindingRewriteValidators",a.h.va);a.b("expressionRewriting.parseObjectLiteral",a.h.Ab);a.b("expressionRewriting.preProcessBindings",a.h.Xa);a.b("expressionRewriting._twoWayBindings",a.h.ga);a.b("jsonExpressionRewriting",a.h);a.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson",a.h.Xa);(function(){function b(a){return 8==a.nodeType&&g.test(f?a.text:a.nodeValue)}function c(a){return 8==a.nodeType&&h.test(f?a.text:a.nodeValue)}function d(a,d){for(var e=a,f=1,l=[];e=e.nextSibling;){if(c(e)&&(f--,0===f))return l;l.push(e);b(e)&&f++}if(!d)throw Error("Cannot find closing comment tag to match: "+a.nodeValue);return null}function e(a,b){var c=d(a,b);return c?0<c.length?c[c.length-
1].nextSibling:a.nextSibling:null}var f=t&&"\x3c!--test--\x3e"===t.createComment("test").text,g=f?/^\x3c!--\s*ko(?:\s+([\s\S]+))?\s*--\x3e$/:/^\s*ko(?:\s+([\s\S]+))?\s*$/,h=f?/^\x3c!--\s*\/ko\s*--\x3e$/:/^\s*\/ko\s*$/,l={ul:!0,ol:!0};a.f={aa:{},childNodes:function(a){return b(a)?d(a):a.childNodes},za:function(c){if(b(c)){c=a.f.childNodes(c);for(var d=0,e=c.length;d<e;d++)a.removeNode(c[d])}else a.a.rb(c)},fa:function(c,d){if(b(c)){a.f.za(c);for(var e=c.nextSibling,f=0,l=d.length;f<l;f++)e.parentNode.insertBefore(d[f],e)}else a.a.fa(c,d)},qc:function(a,c){b(a)?a.parentNode.insertBefore(c,a.nextSibling):a.firstChild?a.insertBefore(c,a.firstChild):a.appendChild(c)},kc:function(c,d,e){e?b(c)?c.parentNode.insertBefore(d,e.nextSibling):e.nextSibling?c.insertBefore(d,e.nextSibling):c.appendChild(d):a.f.qc(c,d)},firstChild:function(a){return b(a)?!a.nextSibling||c(a.nextSibling)?null:a.nextSibling:a.firstChild},nextSibling:function(a){b(a)&&(a=e(a));return a.nextSibling&&c(a.nextSibling)?null:a.nextSibling},Yc:b,vd:function(a){return(a=(f?a.text:a.nodeValue).match(g))?a[1]:null},oc:function(d){if(l[a.a.A(d)]){var k=d.firstChild;if(k){do if(1===k.nodeType){var f;f=k.firstChild;var g=null;if(f){do if(g)g.push(f);else if(b(f)){var h=e(f,!0);h?f=h:g=[f]}else c(f)&&(g=[f]);while(f=f.nextSibling)}if(f=g)for(g=k.nextSibling,h=0;h<f.length;h++)g?d.insertBefore(f[h],g):d.appendChild(f[h])}while(k=k.nextSibling)}}}}})();a.b("virtualElements",a.f);a.b("virtualElements.allowedBindings",a.f.aa);a.b("virtualElements.emptyNode",a.f.za);a.b("virtualElements.insertAfter",a.f.kc);a.b("virtualElements.prepend",a.f.qc);a.b("virtualElements.setDomNodeChildren",a.f.fa);(function(){a.S=function(){this.Kc={}};a.a.extend(a.S.prototype,{nodeHasBindings:function(b){switch(b.nodeType){case 1:return null!=b.getAttribute("data-bind")||a.g.getComponentNameForNode(b);case 8:return a.f.Yc(b);default:return!1}},getBindings:function(b,c){var d=this.getBindingsString(b,c),d=d?this.parseBindingsString(d,c,b):null;return a.g.Rb(d,b,c,!1)},getBindingAccessors:function(b,c){var d=this.getBindingsString(b,c),d=d?this.parseBindingsString(d,c,b,{valueAccessors:!0}):null;return a.g.Rb(d,b,c,!0)},getBindingsString:function(b){switch(b.nodeType){case 1:return b.getAttribute("data-bind");case 8:return a.f.vd(b);default:return null}},parseBindingsString:function(b,c,d,e){try{var f=this.Kc,g=b+(e&&e.valueAccessors||""),h;if(!(h=f[g])){var l,m="with($context){with($data||{}){return{"+a.h.Xa(b,e)+"}}}";l=new Function("$context","$element",m);h=f[g]=l}return h(c,d)}catch(k){throw k.message="Unable to parse bindings.\nBindings value: "+
b+"\nMessage: "+k.message,k;}}});a.S.instance=new a.S})();a.b("bindingProvider",a.S);(function(){function b(a){return function(){return a}}function c(a){return a()}function d(b){return a.a.Ea(a.l.w(b),function(a,c){return function(){return b()[c]}})}function e(c,e,k){return"function"===typeof c?d(c.bind(null,e,k)):a.a.Ea(c,b)}function f(a,b){return d(this.getBindings.bind(this,a,b))}function g(b,c,d){var e,k=a.f.firstChild(c),f=a.S.instance,m=f.preprocessNode;if(m){for(;e=k;)k=a.f.nextSibling(e),m.call(f,e);k=a.f.firstChild(c)}for(;e=k;)k=a.f.nextSibling(e),h(b,e,d)}function h(b,c,d){var e=!0,k=1===c.nodeType;k&&a.f.oc(c);if(k&&d||a.S.instance.nodeHasBindings(c))e=m(c,null,b,d).shouldBindDescendants;e&&!r[a.a.A(c)]&&g(b,c,!k)}function l(b){var c=[],d={},e=[];a.a.D(b,function X(k){if(!d[k]){var f=a.getBindingHandler(k);f&&(f.after&&(e.push(k),a.a.r(f.after,function(c){if(b[c]){if(-1!==a.a.o(e,c))throw Error("Cannot combine the following bindings, because they have a cyclic dependency: "+e.join(", "));X(c)}}),e.length--),c.push({key:k,jc:f}));d[k]=!0}});return c}function m(b,d,e,k){var m=a.a.e.get(b,q);if(!d){if(m)throw Error("You cannot apply bindings multiple times to the same element.");a.a.e.set(b,q,!0)}!m&&k&&a.xc(b,e);var g;if(d&&"function"!==typeof d)g=d;else{var h=a.S.instance,r=h.getBindingAccessors||f,p=a.B(function(){(g=d?d(e,b):r.call(h,b,e))&&e.Q&&e.Q();return g},null,{i:b});g&&p.ca()||(p=null)}var s;if(g){var t=p?function(a){return function(){return c(p()[a])}}:function(a){return g[a]},u=function(){return a.a.Ea(p?p():g,c)};u.get=function(a){return g[a]&&c(t(a))};u.has=function(a){return a in g};k=l(g);a.a.r(k,function(c){var d=c.jc.init,k=c.jc.update,f=c.key;if(8===b.nodeType&&!a.f.aa[f])throw Error("The binding '"+f+"' cannot be used with virtual elements");try{"function"==typeof d&&a.l.w(function(){var a=d(b,t(f),u,e.$data,e);if(a&&a.controlsDescendantBindings){if(s!==n)throw Error("Multiple bindings ("+s+" and "+f+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");s=f}}),"function"==typeof k&&a.B(function(){k(b,t(f),u,e.$data,e)},null,{i:b})}catch(m){throw m.message='Unable to process binding "'+f+": "+g[f]+'"\nMessage: '+m.message,m;}})}return{shouldBindDescendants:s===n}}function k(b){return b&&b instanceof a.R?b:new a.R(b)}a.d={};var r={script:!0,textarea:!0,template:!0};a.getBindingHandler=function(b){return a.d[b]};a.R=function(b,c,d,e,k){function f(){var k=g?b():b,m=a.a.c(k);c?(c.Q&&c.Q(),a.a.extend(l,c),l.Q=r):(l.$parents=[],l.$root=m,l.ko=a);l.$rawData=k;l.$data=m;d&&(l[d]=m);e&&e(l,c,m);return l.$data}function m(){return h&&!a.a.Tb(h)}var l=this,g="function"==typeof b&&!a.I(b),h,r;k&&k.exportDependencies?f():(r=a.B(f,null,{ya:m,i:!0}),r.ca()&&(l.Q=r,r.equalityComparer=null,h=[],r.Dc=function(b){h.push(b);a.a.G.qa(b,function(b){a.a.Na(h,b);h.length||(r.k(),l.Q=r=n)})}))};a.R.prototype.createChildContext=function(b,c,d,e){return new a.R(b,this,c,function(a,b){a.$parentContext=b;a.$parent=b.$data;a.$parents=(b.$parents||[]).slice(0);a.$parents.unshift(a.$parent);d&&d(a)},e)};a.R.prototype.extend=function(b){return new a.R(this.Q||this.$data,this,null,function(c,d){c.$rawData=d.$rawData;a.a.extend(c,"function"==typeof b?b():b)})};a.R.prototype.ac=function(a,b){return this.createChildContext(a,b,null,{exportDependencies:!0})};var q=a.a.e.J(),p=a.a.e.J();a.xc=function(b,c){if(2==arguments.length)a.a.e.set(b,p,c),c.Q&&c.Q.Dc(b);else return a.a.e.get(b,p)};a.La=function(b,c,d){1===b.nodeType&&a.f.oc(b);return m(b,c,k(d),!0)};a.Ic=function(b,c,d){d=k(d);return a.La(b,e(c,d,b),d)};a.hb=function(a,b){1!==b.nodeType&&8!==b.nodeType||g(k(a),b,!0)};a.Ub=function(a,b){!u&&x.jQuery&&(u=x.jQuery);if(b&&1!==b.nodeType&&8!==b.nodeType)throw Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");b=b||x.document.body;h(k(a),b,!0)};a.nb=function(b){switch(b.nodeType){case 1:case 8:var c=a.xc(b);if(c)return c;if(b.parentNode)return a.nb(b.parentNode)}return n};a.Oc=function(b){return(b=a.nb(b))?b.$data:n};a.b("bindingHandlers",a.d);a.b("applyBindings",a.Ub);a.b("applyBindingsToDescendants",a.hb);a.b("applyBindingAccessorsToNode",a.La);a.b("applyBindingsToNode",a.Ic);a.b("contextFor",a.nb);a.b("dataFor",a.Oc)})();(function(b){function c(c,e){var m=f.hasOwnProperty(c)?f[c]:b,k;m?m.Y(e):(m=f[c]=new a.K,m.Y(e),d(c,function(b,d){var e=!(!d||!d.synchronous);g[c]={definition:b,dd:e};delete f[c];k||e?m.notifySubscribers(b):a.Z.Za(function(){m.notifySubscribers(b)})}),k=!0)}function d(a,b){e("getConfig",[a],function(c){c?e("loadComponent",[a,c],function(a){b(a,c)}):b(null,null)})}function e(c,d,f,k){k||(k=a.g.loaders.slice(0));var g=k.shift();if(g){var q=g[c];if(q){var p=!1;if(q.apply(g,d.concat(function(a){p?f(null):null!==a?f(a):e(c,d,f,k)}))!==b&&(p=!0,!g.suppressLoaderExceptions))throw Error("Component loaders must supply values by invoking the callback, not by returning values synchronously.");}else e(c,d,f,k)}else f(null)}var f={},g={};a.g={get:function(d,e){var f=g.hasOwnProperty(d)?g[d]:b;f?f.dd?a.l.w(function(){e(f.definition)}):a.Z.Za(function(){e(f.definition)}):c(d,e)},$b:function(a){delete g[a]},Nb:e};a.g.loaders=[];a.b("components",a.g);a.b("components.get",a.g.get);a.b("components.clearCachedDefinition",a.g.$b)})();(function(){function b(b,c,d,e){function g(){0===--y&&e(h)}var h={},y=2,v=d.template;d=d.viewModel;v?f(c,v,function(c){a.g.Nb("loadTemplate",[b,c],function(a){h.template=a;g()})}):g();d?f(c,d,function(c){a.g.Nb("loadViewModel",[b,c],function(a){h[l]=a;g()})}):g()}function c(a,b,d){if("function"===typeof b)d(function(a){return new b(a)});else if("function"===typeof b[l])d(b[l]);else if("instance"in b){var e=b.instance;d(function(){return e})}else"viewModel"in b?c(a,b.viewModel,d):a("Unknown viewModel value: "+b)}function d(b){switch(a.a.A(b)){case "script":return a.a.na(b.text);case "textarea":return a.a.na(b.value);case "template":if(e(b.content))return a.a.wa(b.content.childNodes)}return a.a.wa(b.childNodes)}function e(a){return x.DocumentFragment?a instanceof DocumentFragment:a&&11===a.nodeType}function f(a,b,c){"string"===typeof b.require?O||x.require?(O||x.require)([b.require],c):a("Uses require, but no AMD loader is present"):c(b)}function g(a){return function(b){throw Error("Component '"+a+"': "+b);}}var h={};a.g.register=function(b,c){if(!c)throw Error("Invalid configuration for "+b);if(a.g.wb(b))throw Error("Component "+b+" is already registered");h[b]=c};a.g.wb=function(a){return h.hasOwnProperty(a)};a.g.ud=function(b){delete h[b];a.g.$b(b)};a.g.cc={getConfig:function(a,b){b(h.hasOwnProperty(a)?h[a]:null)},loadComponent:function(a,c,d){var e=g(a);f(e,c,function(c){b(a,e,c,d)})},loadTemplate:function(b,c,f){b=g(b);if("string"===typeof c)f(a.a.na(c));else if(c instanceof Array)f(c);else if(e(c))f(a.a.W(c.childNodes));else if(c.element)if(c=c.element,x.HTMLElement?c instanceof HTMLElement:c&&c.tagName&&1===c.nodeType)f(d(c));else if("string"===typeof c){var l=t.getElementById(c);l?f(d(l)):b("Cannot find element with ID "+c)}else b("Unknown element type: "+c);else b("Unknown template value: "+c)},loadViewModel:function(a,b,d){c(g(a),b,d)}};var l="createViewModel";a.b("components.register",a.g.register);a.b("components.isRegistered",a.g.wb);a.b("components.unregister",a.g.ud);a.b("components.defaultLoader",a.g.cc);a.g.loaders.push(a.g.cc);a.g.Ec=h})();(function(){function b(b,e){var f=b.getAttribute("params");if(f){var f=c.parseBindingsString(f,e,b,{valueAccessors:!0,bindingParams:!0}),f=a.a.Ea(f,function(c){return a.m(c,null,{i:b})}),g=a.a.Ea(f,function(c){var e=c.p();return c.ca()?a.m({read:function(){return a.a.c(c())},write:a.Da(e)&&function(a){c()(a)},i:b}):e});g.hasOwnProperty("$raw")||(g.$raw=f);return g}return{$raw:{}}}a.g.getComponentNameForNode=function(b){var c=a.a.A(b);if(a.g.wb(c)&&(-1!=c.indexOf("-")||"[object HTMLUnknownElement]"==""+b||8>=a.a.C&&b.tagName===c))return c};a.g.Rb=function(c,e,f,g){if(1===e.nodeType){var h=a.g.getComponentNameForNode(e);if(h){c=c||{};if(c.component)throw Error('Cannot use the "component" binding on a custom element matching a component');var l={name:h,params:b(e,f)};c.component=g?function(){return l}:l}}return c};var c=new a.S;9>a.a.C&&(a.g.register=function(a){return function(b){t.createElement(b);return a.apply(this,arguments)}}(a.g.register),t.createDocumentFragment=function(b){return function(){var c=b(),f=a.g.Ec,g;for(g in f)f.hasOwnProperty(g)&&c.createElement(g);return c}}(t.createDocumentFragment))})();(function(b){function c(b,c,d){c=c.template;if(!c)throw Error("Component '"+b+"' has no template");b=a.a.wa(c);a.f.fa(d,b)}function d(a,b,c,d){var e=a.createViewModel;return e?e.call(a,d,{element:b,templateNodes:c}):d}var e=0;a.d.component={init:function(f,g,h,l,m){function k(){var a=r&&r.dispose;"function"===typeof a&&a.call(r);q=r=null}var r,q,p=a.a.W(a.f.childNodes(f));a.a.G.qa(f,k);a.m(function(){var l=a.a.c(g()),h,v;"string"===typeof l?h=l:(h=a.a.c(l.name),v=a.a.c(l.params));if(!h)throw Error("No component name specified");var n=q=++e;a.g.get(h,function(e){if(q===n){k();if(!e)throw Error("Unknown component '"+h+"'");c(h,e,f);var l=d(e,f,p,v);e=m.createChildContext(l,b,function(a){a.$component=l;a.$componentTemplateNodes=p});r=l;a.hb(e,f)}})},null,{i:f});return{controlsDescendantBindings:!0}}};a.f.aa.component=!0})();var Q={"class":"className","for":"htmlFor"};a.d.attr={update:function(b,c){var d=a.a.c(c())||{};a.a.D(d,function(c,d){d=a.a.c(d);var g=!1===d||null===d||d===n;g&&b.removeAttribute(c);8>=a.a.C&&c in Q?(c=Q[c],g?b.removeAttribute(c):b[c]=d):g||b.setAttribute(c,d.toString());"name"===c&&a.a.vc(b,g?"":d.toString())})}};(function(){a.d.checked={after:["value","attr"],init:function(b,c,d){function e(){var e=b.checked,f=p?g():e;if(!a.xa.Va()&&(!l||e)){var h=a.l.w(c);if(k){var m=r?h.p():h;q!==f?(e&&(a.a.ra(m,f,!0),a.a.ra(m,q,!1)),q=f):a.a.ra(m,f,e);r&&a.Da(h)&&h(m)}else a.h.Ga(h,d,"checked",f,!0)}}function f(){var d=a.a.c(c());b.checked=k?0<=a.a.o(d,g()):h?d:g()===d}var g=a.rc(function(){return d.has("checkedValue")?a.a.c(d.get("checkedValue")):d.has("value")?a.a.c(d.get("value")):b.value}),h="checkbox"==b.type,l="radio"==b.type;if(h||l){var m=c(),k=h&&a.a.c(m)instanceof Array,r=!(k&&m.push&&m.splice),q=k?g():n,p=l||k;l&&!b.name&&a.d.uniqueName.init(b,function(){return!0});a.m(e,null,{i:b});a.a.q(b,"click",e);a.m(f,null,{i:b});m=n}}};a.h.ga.checked=!0;a.d.checkedValue={update:function(b,c){b.value=a.a.c(c())}}})();a.d.css={update:function(b,c){var d=a.a.c(c());null!==d&&"object"==typeof d?a.a.D(d,function(c,d){d=a.a.c(d);a.a.fb(b,c,d)}):(d=a.a.cb(String(d||"")),a.a.fb(b,b.__ko__cssValue,!1),b.__ko__cssValue=d,a.a.fb(b,d,!0))}};a.d.enable={update:function(b,c){var d=a.a.c(c());d&&b.disabled?b.removeAttribute("disabled"):d||b.disabled||(b.disabled=!0)}};a.d.disable={update:function(b,c){a.d.enable.update(b,function(){return!a.a.c(c())})}};a.d.event={init:function(b,c,d,e,f){var g=c()||{};a.a.D(g,function(g){"string"==typeof g&&a.a.q(b,g,function(b){var m,k=c()[g];if(k){try{var r=a.a.W(arguments);e=f.$data;r.unshift(e);m=k.apply(e,r)}finally{!0!==m&&(b.preventDefault?b.preventDefault():b.returnValue=!1)}!1===d.get(g+"Bubble")&&(b.cancelBubble=!0,b.stopPropagation&&b.stopPropagation())}})})}};a.d.foreach={mc:function(b){return function(){var c=b(),d=a.a.Bb(c);if(!d||"number"==typeof d.length)return{foreach:c,templateEngine:a.X.vb};a.a.c(c);return{foreach:d.data,as:d.as,includeDestroyed:d.includeDestroyed,afterAdd:d.afterAdd,beforeRemove:d.beforeRemove,afterRender:d.afterRender,beforeMove:d.beforeMove,afterMove:d.afterMove,templateEngine:a.X.vb}}},init:function(b,c){return a.d.template.init(b,a.d.foreach.mc(c))},update:function(b,c,d,e,f){return a.d.template.update(b,a.d.foreach.mc(c),d,e,f)}};a.h.va.foreach=!1;a.f.aa.foreach=!0;a.d.hasfocus={init:function(b,c,d){function e(e){b.__ko_hasfocusUpdating=!0;var f=b.ownerDocument;if("activeElement"in f){var g;try{g=f.activeElement}catch(k){g=f.body}e=g===b}f=c();a.h.Ga(f,d,"hasfocus",e,!0);b.__ko_hasfocusLastValue=e;b.__ko_hasfocusUpdating=!1}var f=e.bind(null,!0),g=e.bind(null,!1);a.a.q(b,"focus",f);a.a.q(b,"focusin",f);a.a.q(b,"blur",g);a.a.q(b,"focusout",g)},update:function(b,c){var d=!!a.a.c(c());b.__ko_hasfocusUpdating||b.__ko_hasfocusLastValue===d||(d?b.focus():b.blur(),!d&&b.__ko_hasfocusLastValue&&b.ownerDocument.body.focus(),a.l.w(a.a.Fa,null,[b,d?"focusin":"focusout"]))}};a.h.ga.hasfocus=!0;a.d.hasFocus=a.d.hasfocus;a.h.ga.hasFocus=!0;a.d.html={init:function(){return{controlsDescendantBindings:!0}},update:function(b,c){a.a.Eb(b,c())}};K("if");K("ifnot",!1,!0);K("with",!0,!1,function(a,c){return a.ac(c)});var L={};a.d.options={init:function(b){if("select"!==a.a.A(b))throw Error("options binding applies only to SELECT elements");for(;0<b.length;)b.remove(0);return{controlsDescendantBindings:!0}},update:function(b,c,d){function e(){return a.a.Ma(b.options,function(a){return a.selected})}function f(a,b,c){var d=typeof b;return"function"==d?b(a):"string"==d?a[b]:c}function g(c,e){if(A&&k)a.j.ja(b,a.a.c(d.get("value")),!0);else if(p.length){var f=0<=a.a.o(p,a.j.u(e[0]));a.a.wc(e[0],f);A&&!f&&a.l.w(a.a.Fa,null,[b,"change"])}}var h=b.multiple,l=0!=b.length&&h?b.scrollTop:null,m=a.a.c(c()),k=d.get("valueAllowUnset")&&d.has("value"),r=d.get("optionsIncludeDestroyed");c={};var q,p=[];k||(h?p=a.a.ib(e(),a.j.u):0<=b.selectedIndex&&p.push(a.j.u(b.options[b.selectedIndex])));m&&("undefined"==typeof m.length&&(m=[m]),q=a.a.Ma(m,function(b){return r||b===n||null===b||!a.a.c(b._destroy)}),d.has("optionsCaption")&&(m=a.a.c(d.get("optionsCaption")),null!==m&&m!==n&&q.unshift(L)));var A=!1;c.beforeRemove=function(a){b.removeChild(a)};m=g;d.has("optionsAfterRender")&&"function"==typeof d.get("optionsAfterRender")&&(m=function(b,c){g(0,c);a.l.w(d.get("optionsAfterRender"),null,[c[0],b!==L?b:n])});a.a.Db(b,q,function(c,e,g){g.length&&(p=!k&&g[0].selected?[a.j.u(g[0])]:[],A=!0);e=b.ownerDocument.createElement("option");c===L?(a.a.bb(e,d.get("optionsCaption")),a.j.ja(e,n)):(g=f(c,d.get("optionsValue"),c),a.j.ja(e,a.a.c(g)),c=f(c,d.get("optionsText"),g),a.a.bb(e,c));return[e]},c,m);a.l.w(function(){k?a.j.ja(b,a.a.c(d.get("value")),!0):(h?p.length&&e().length<p.length:p.length&&0<=b.selectedIndex?a.j.u(b.options[b.selectedIndex])!==p[0]:p.length||0<=b.selectedIndex)&&a.a.Fa(b,"change")});a.a.Sc(b);l&&20<Math.abs(l-b.scrollTop)&&(b.scrollTop=l)}};a.d.options.zb=a.a.e.J();a.d.selectedOptions={after:["options","foreach"],init:function(b,c,d){a.a.q(b,"change",function(){var e=c(),f=[];a.a.r(b.getElementsByTagName("option"),function(b){b.selected&&f.push(a.j.u(b))});a.h.Ga(e,d,"selectedOptions",f)})},update:function(b,c){if("select"!=a.a.A(b))throw Error("values binding applies only to SELECT elements");var d=a.a.c(c()),e=b.scrollTop;d&&"number"==typeof d.length&&a.a.r(b.getElementsByTagName("option"),function(b){var c=0<=a.a.o(d,a.j.u(b));b.selected!=c&&a.a.wc(b,c)});b.scrollTop=e}};a.h.ga.selectedOptions=!0;a.d.style={update:function(b,c){var d=a.a.c(c()||{});a.a.D(d,function(c,d){d=a.a.c(d);if(null===d||d===n||!1===d)d="";b.style[c]=d})}};a.d.submit={init:function(b,c,d,e,f){if("function"!=typeof c())throw Error("The value for a submit binding must be a function");a.a.q(b,"submit",function(a){var d,e=c();try{d=e.call(f.$data,b)}finally{!0!==d&&(a.preventDefault?a.preventDefault():a.returnValue=!1)}})}};a.d.text={init:function(){return{controlsDescendantBindings:!0}},update:function(b,c){a.a.bb(b,c())}};a.f.aa.text=!0;(function(){if(x&&x.navigator)var b=function(a){if(a)return parseFloat(a[1])},c=x.opera&&x.opera.version&&parseInt(x.opera.version()),d=x.navigator.userAgent,e=b(d.match(/^(?:(?!chrome).)*version\/([^ ]*) safari/i)),f=b(d.match(/Firefox\/([^ ]*)/));if(10>a.a.C)var g=a.a.e.J(),h=a.a.e.J(),l=function(b){var c=this.activeElement;(c=c&&a.a.e.get(c,h))&&c(b)},m=function(b,c){var d=b.ownerDocument;a.a.e.get(d,g)||(a.a.e.set(d,g,!0),a.a.q(d,"selectionchange",l));a.a.e.set(b,h,c)};a.d.textInput={init:function(b,d,g){function l(c,d){a.a.q(b,c,d)}function h(){var c=a.a.c(d());if(null===c||c===n)c="";u!==n&&c===u?a.a.setTimeout(h,4):b.value!==c&&(s=c,b.value=c)}function y(){t||(u=b.value,t=a.a.setTimeout(v,4))}function v(){clearTimeout(t);u=t=n;var c=b.value;s!==c&&(s=c,a.h.Ga(d(),g,"textInput",c))}var s=b.value,t,u,x=9==a.a.C?y:v;10>a.a.C?(l("propertychange",function(a){"value"===a.propertyName&&x(a)}),8==a.a.C&&(l("keyup",v),l("keydown",v)),8<=a.a.C&&(m(b,x),l("dragend",y))):(l("input",v),5>e&&"textarea"===a.a.A(b)?(l("keydown",y),l("paste",y),l("cut",y)):11>c?l("keydown",y):4>f&&(l("DOMAutoComplete",v),l("dragdrop",v),l("drop",v)));l("change",v);a.m(h,null,{i:b})}};a.h.ga.textInput=!0;a.d.textinput={preprocess:function(a,b,c){c("textInput",a)}}})();a.d.uniqueName={init:function(b,c){if(c()){var d="ko_unique_"+
++a.d.uniqueName.Nc;a.a.vc(b,d)}}};a.d.uniqueName.Nc=0;a.d.value={after:["options","foreach"],init:function(b,c,d){if("input"!=b.tagName.toLowerCase()||"checkbox"!=b.type&&"radio"!=b.type){var e=["change"],f=d.get("valueUpdate"),g=!1,h=null;f&&("string"==typeof f&&(f=[f]),a.a.ta(e,f),e=a.a.Wb(e));var l=function(){h=null;g=!1;var e=c(),f=a.j.u(b);a.h.Ga(e,d,"value",f)};!a.a.C||"input"!=b.tagName.toLowerCase()||"text"!=b.type||"off"==b.autocomplete||b.form&&"off"==b.form.autocomplete||-1!=a.a.o(e,"propertychange")||(a.a.q(b,"propertychange",function(){g=!0}),a.a.q(b,"focus",function(){g=!1}),a.a.q(b,"blur",function(){g&&l()}));a.a.r(e,function(c){var d=l;a.a.sd(c,"after")&&(d=function(){h=a.j.u(b);a.a.setTimeout(l,0)},c=c.substring(5));a.a.q(b,c,d)});var m=function(){var e=a.a.c(c()),f=a.j.u(b);if(null!==h&&e===h)a.a.setTimeout(m,0);else if(e!==f)if("select"===a.a.A(b)){var g=d.get("valueAllowUnset"),f=function(){a.j.ja(b,e,g)};f();g||e===a.j.u(b)?a.a.setTimeout(f,0):a.l.w(a.a.Fa,null,[b,"change"])}else a.j.ja(b,e)};a.m(m,null,{i:b})}else a.La(b,{checkedValue:c})},update:function(){}};a.h.ga.value=!0;a.d.visible={update:function(b,c){var d=a.a.c(c()),e="none"!=b.style.display;d&&!e?b.style.display="":!d&&e&&(b.style.display="none")}};(function(b){a.d[b]={init:function(c,d,e,f,g){return a.d.event.init.call(this,c,function(){var a={};a[b]=d();return a},e,f,g)}}})("click");a.P=function(){};a.P.prototype.renderTemplateSource=function(){throw Error("Override renderTemplateSource");};a.P.prototype.createJavaScriptEvaluatorBlock=function(){throw Error("Override createJavaScriptEvaluatorBlock");};a.P.prototype.makeTemplateSource=function(b,c){if("string"==typeof b){c=c||t;var d=c.getElementById(b);if(!d)throw Error("Cannot find template with ID "+b);return new a.v.n(d)}if(1==b.nodeType||8==b.nodeType)return new a.v.sa(b);throw Error("Unknown template type: "+b);};a.P.prototype.renderTemplate=function(a,c,d,e){a=this.makeTemplateSource(a,e);return this.renderTemplateSource(a,c,d,e)};a.P.prototype.isTemplateRewritten=function(a,c){return!1===this.allowTemplateRewriting?!0:this.makeTemplateSource(a,c).data("isRewritten")};a.P.prototype.rewriteTemplate=function(a,c,d){a=this.makeTemplateSource(a,d);c=c(a.text());a.text(c);a.data("isRewritten",!0)};a.b("templateEngine",a.P);a.Ib=function(){function b(b,c,d,h){b=a.h.Ab(b);for(var l=a.h.va,m=0;m<b.length;m++){var k=b[m].key;if(l.hasOwnProperty(k)){var r=l[k];if("function"===typeof r){if(k=r(b[m].value))throw Error(k);}else if(!r)throw Error("This template engine does not support the '"+
k+"' binding within its templates");}}d="ko.__tr_ambtns(function($context,$element){return(function(){return{ "+a.h.Xa(b,{valueAccessors:!0})+" } })()},'"+d.toLowerCase()+"')";return h.createJavaScriptEvaluatorBlock(d)+c}var c=/(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'|[^>]*))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi,d=/\x3c!--\s*ko\b\s*([\s\S]*?)\s*--\x3e/g;return{Tc:function(b,c,d){c.isTemplateRewritten(b,d)||c.rewriteTemplate(b,function(b){return a.Ib.jd(b,c)},d)},jd:function(a,f){return a.replace(c,function(a,c,d,e,k){return b(k,c,d,f)}).replace(d,function(a,c){return b(c,"\x3c!-- ko --\x3e","#comment",f)})},Jc:function(b,c){return a.N.yb(function(d,h){var l=d.nextSibling;l&&l.nodeName.toLowerCase()===c&&a.La(l,b,h)})}}}();a.b("__tr_ambtns",a.Ib.Jc);(function(){a.v={};a.v.n=function(b){if(this.n=b){var c=a.a.A(b);this.eb="script"===c?1:"textarea"===c?2:"template"==c&&b.content&&11===b.content.nodeType?3:4}};a.v.n.prototype.text=function(){var b=1===this.eb?"text":2===this.eb?"value":"innerHTML";if(0==arguments.length)return this.n[b];var c=arguments[0];"innerHTML"===b?a.a.Eb(this.n,c):this.n[b]=c};var b=a.a.e.J()+"_";a.v.n.prototype.data=function(c){if(1===arguments.length)return a.a.e.get(this.n,b+c);a.a.e.set(this.n,b+c,arguments[1])};var c=a.a.e.J();a.v.n.prototype.nodes=function(){var b=this.n;if(0==arguments.length)return(a.a.e.get(b,c)||{}).mb||(3===this.eb?b.content:4===this.eb?b:n);a.a.e.set(b,c,{mb:arguments[0]})};a.v.sa=function(a){this.n=a};a.v.sa.prototype=new a.v.n;a.v.sa.prototype.text=function(){if(0==arguments.length){var b=a.a.e.get(this.n,c)||{};b.Jb===n&&b.mb&&(b.Jb=b.mb.innerHTML);return b.Jb}a.a.e.set(this.n,c,{Jb:arguments[0]})};a.b("templateSources",a.v);a.b("templateSources.domElement",a.v.n);a.b("templateSources.anonymousTemplate",a.v.sa)})();(function(){function b(b,c,d){var e;for(c=a.f.nextSibling(c);b&&(e=b)!==c;)b=a.f.nextSibling(e),d(e,b)}function c(c,d){if(c.length){var e=c[0],f=c[c.length-1],g=e.parentNode,h=a.S.instance,n=h.preprocessNode;if(n){b(e,f,function(a,b){var c=a.previousSibling,d=n.call(h,a);d&&(a===e&&(e=d[0]||b),a===f&&(f=d[d.length-1]||c))});c.length=0;if(!e)return;e===f?c.push(e):(c.push(e,f),a.a.Ba(c,g))}b(e,f,function(b){1!==b.nodeType&&8!==b.nodeType||a.Ub(d,b)});b(e,f,function(b){1!==b.nodeType&&8!==b.nodeType||a.N.Cc(b,[d])});a.a.Ba(c,g)}}function d(a){return a.nodeType?a:0<a.length?a[0]:null}function e(b,e,f,h,q){q=q||{};var p=(b&&d(b)||f||{}).ownerDocument,n=q.templateEngine||g;a.Ib.Tc(f,n,p);f=n.renderTemplate(f,h,q,p);if("number"!=typeof f.length||0<f.length&&"number"!=typeof f[0].nodeType)throw Error("Template engine must return an array of DOM nodes");p=!1;switch(e){case "replaceChildren":a.f.fa(b,f);p=!0;break;case "replaceNode":a.a.uc(b,f);p=!0;break;case "ignoreTargetNode":break;default:throw Error("Unknown renderMode: "+e);}p&&(c(f,h),q.afterRender&&a.l.w(q.afterRender,null,[f,h.$data]));return f}function f(b,c,d){return a.I(b)?b():"function"===typeof b?b(c,d):b}
var g;a.Fb=function(b){if(b!=n&&!(b instanceof a.P))throw Error("templateEngine must inherit from ko.templateEngine");g=b};a.Cb=function(b,c,k,h,q){k=k||{};if((k.templateEngine||g)==n)throw Error("Set a template engine before calling renderTemplate");q=q||"replaceChildren";if(h){var p=d(h);return a.B(function(){var g=c&&c instanceof a.R?c:new a.R(c,null,null,null,{exportDependencies:!0}),n=f(b,g.$data,g),g=e(h,q,n,g,k);"replaceNode"==q&&(h=g,p=d(h))},null,{ya:function(){return!p||!a.a.qb(p)},i:p&&"replaceNode"==q?p.parentNode:p})}return a.N.yb(function(d){a.Cb(b,c,k,d,"replaceNode")})};a.pd=function(b,d,g,h,q){function p(a,b){c(b,t);g.afterRender&&g.afterRender(b,a);t=null}function s(a,c){t=q.createChildContext(a,g.as,function(a){a.$index=c});var d=f(b,a,t);return e(null,"ignoreTargetNode",d,t,g)}var t;return a.B(function(){var b=a.a.c(d)||[];"undefined"==typeof b.length&&(b=[b]);b=a.a.Ma(b,function(b){return g.includeDestroyed||b===n||null===b||!a.a.c(b._destroy)});a.l.w(a.a.Db,null,[h,b,s,g,p])},null,{i:h})};var h=a.a.e.J();a.d.template={init:function(b,c){var d=a.a.c(c());if("string"==typeof d||d.name)a.f.za(b);else{if("nodes"in d){if(d=d.nodes||[],a.I(d))throw Error('The "nodes" option must be a plain, non-observable array.');}else d=a.f.childNodes(b);d=a.a.nc(d);(new a.v.sa(b)).nodes(d)}return{controlsDescendantBindings:!0}},update:function(b,c,d,e,f){var g=c();c=a.a.c(g);d=!0;e=null;"string"==typeof c?c={}:(g=c.name,"if"in c&&(d=a.a.c(c["if"])),d&&"ifnot"in c&&(d=!a.a.c(c.ifnot)));"foreach"in c?e=a.pd(g||b,d&&c.foreach||[],c,b,f):d?(f="data"in c?f.ac(c.data,c.as):f,e=a.Cb(g||b,f,c,b)):a.f.za(b);f=e;(c=a.a.e.get(b,h))&&"function"==typeof c.k&&c.k();a.a.e.set(b,h,f&&f.ca()?f:n)}};a.h.va.template=function(b){b=a.h.Ab(b);return 1==b.length&&b[0].unknown||a.h.fd(b,"name")?null:"This template engine does not support anonymous templates nested within its templates"};a.f.aa.template=!0})();a.b("setTemplateEngine",a.Fb);a.b("renderTemplate",a.Cb);a.a.hc=function(a,c,d){if(a.length&&c.length){var e,f,g,h,l;for(e=f=0;(!d||e<d)&&(h=a[f]);++f){for(g=0;l=c[g];++g)if(h.value===l.value){h.moved=l.index;l.moved=h.index;c.splice(g,1);e=g=0;break}e+=g}}};a.a.lb=function(){function b(b,d,e,f,g){var h=Math.min,l=Math.max,m=[],k,n=b.length,q,p=d.length,s=p-n||1,t=n+p+1,v,u,x;for(k=0;k<=n;k++)for(u=v,m.push(v=[]),x=h(p,k+s),q=l(0,k-1);q<=x;q++)v[q]=q?k?b[k-1]===d[q-1]?u[q-1]:h(u[q]||t,v[q-1]||t)+1:q+1:k+1;h=[];l=[];s=[];k=n;for(q=p;k||q;)p=m[k][q]-1,q&&p===m[k][q-1]?l.push(h[h.length]={status:e,value:d[--q],index:q}):k&&p===m[k-1][q]?s.push(h[h.length]={status:f,value:b[--k],index:k}):(--q,--k,g.sparse||h.push({status:"retained",value:d[q]}));a.a.hc(s,l,!g.dontLimitMoves&&10*n);return h.reverse()}return function(a,d,e){e="boolean"===typeof e?{dontLimitMoves:e}:e||{};a=a||[];d=d||[];return a.length<d.length?b(a,d,"added","deleted",e):b(d,a,"deleted","added",e)}}();a.b("utils.compareArrays",a.a.lb);(function(){function b(b,c,d,h,l){var m=[],k=a.B(function(){var k=c(d,l,a.a.Ba(m,b))||[];0<m.length&&(a.a.uc(m,k),h&&a.l.w(h,null,[d,k,l]));m.length=0;a.a.ta(m,k)},null,{i:b,ya:function(){return!a.a.Tb(m)}});return{ea:m,B:k.ca()?k:n}}var c=a.a.e.J(),d=a.a.e.J();a.a.Db=function(e,f,g,h,l){function m(b,c){w=q[c];u!==c&&(D[b]=w);w.tb(u++);a.a.Ba(w.ea,e);t.push(w);z.push(w)}function k(b,c){if(b)for(var d=0,e=c.length;d<e;d++)c[d]&&a.a.r(c[d].ea,function(a){b(a,d,c[d].ka)})}f=f||[];h=h||{};var r=a.a.e.get(e,c)===n,q=a.a.e.get(e,c)||[],p=a.a.ib(q,function(a){return a.ka}),s=a.a.lb(p,f,h.dontLimitMoves),t=[],v=0,u=0,x=[],z=[];f=[];for(var D=[],p=[],w,C=0,B,E;B=s[C];C++)switch(E=B.moved,B.status){case "deleted":E===n&&(w=q[v],w.B&&(w.B.k(),w.B=n),a.a.Ba(w.ea,e).length&&(h.beforeRemove&&(t.push(w),z.push(w),w.ka===d?w=null:f[C]=w),w&&x.push.apply(x,w.ea)));v++;break;case "retained":m(C,v++);break;case "added":E!==n?m(C,E):(w={ka:B.value,tb:a.O(u++)},t.push(w),z.push(w),r||(p[C]=w))}a.a.e.set(e,c,t);k(h.beforeMove,D);a.a.r(x,h.beforeRemove?a.ba:a.removeNode);for(var C=0,r=a.f.firstChild(e),F;w=z[C];C++){w.ea||a.a.extend(w,b(e,g,w.ka,l,w.tb));for(v=0;s=w.ea[v];r=s.nextSibling,F=s,v++)s!==r&&a.f.kc(e,s,F);!w.ad&&l&&(l(w.ka,w.ea,w.tb),w.ad=!0)}k(h.beforeRemove,f);for(C=0;C<f.length;++C)f[C]&&(f[C].ka=d);k(h.afterMove,D);k(h.afterAdd,p)}})();a.b("utils.setDomNodeChildrenFromArrayMapping",a.a.Db);a.X=function(){this.allowTemplateRewriting=!1};a.X.prototype=new a.P;a.X.prototype.renderTemplateSource=function(b,c,d,e){if(c=(9>a.a.C?0:b.nodes)?b.nodes():null)return a.a.W(c.cloneNode(!0).childNodes);b=b.text();return a.a.na(b,e)};a.X.vb=new a.X;a.Fb(a.X.vb);a.b("nativeTemplateEngine",a.X);(function(){a.xb=function(){var a=this.ed=function(){if(!u||!u.tmpl)return 0;try{if(0<=u.tmpl.tag.tmpl.open.toString().indexOf("__"))return 2}catch(a){}return 1}();this.renderTemplateSource=function(b,e,f,g){g=g||t;f=f||{};if(2>a)throw Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");var h=b.data("precompiled");h||(h=b.text()||"",h=u.template(null,"{{ko_with $item.koBindingContext}}"+
h+"{{/ko_with}}"),b.data("precompiled",h));b=[e.$data];e=u.extend({koBindingContext:e},f.templateOptions);e=u.tmpl(h,b,e);e.appendTo(g.createElement("div"));u.fragments={};return e};this.createJavaScriptEvaluatorBlock=function(a){return"{{ko_code ((function() { return "+a+" })()) }}"};this.addTemplate=function(a,b){t.write("<script type='text/html' id='"+a+"'>"+b+"\x3c/script>")};0<a&&(u.tmpl.tag.ko_code={open:"__.push($1 || '');"},u.tmpl.tag.ko_with={open:"with($1) {",close:"} "})};a.xb.prototype=new a.P;var b=new a.xb;0<b.ed&&a.Fb(b);a.b("jqueryTmplTemplateEngine",a.xb)})()})})();})();!function(a){"function"==typeof require&&"object"==typeof exports&&"object"==typeof module?a(require("knockout"),exports):"function"==typeof define&&define.amd?define(["knockout","exports"],a):a(ko,ko.validation={})}(function(a,b){function c(a){var b="max"===a;return function(c,d){if(f.utils.isEmptyVal(c))return!0;var e,g;void 0===d.typeAttr?(g="text",e=d):(g=d.typeAttr,e=d.value),isNaN(e)||e instanceof Date||(g="number");var h,i,j;switch(g.toLowerCase()){case"week":if(h=/^(\d{4})-W(\d{2})$/,i=c.match(h),null===i)throw new Error("Invalid value for "+a+" attribute for week input.  Should look like '2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min");return j=e.match(h),j?b?i[1]<j[1]||i[1]===j[1]&&i[2]<=j[2]:i[1]>j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"month":if(h=/^(\d{4})-(\d{2})$/,i=c.match(h),null===i)throw new Error("Invalid value for "+a+" attribute for month input.  Should look like '2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min");return j=e.match(h),j?b?i[1]<j[1]||i[1]===j[1]&&i[2]<=j[2]:i[1]>j[1]||i[1]===j[1]&&i[2]>=j[2]:!1;case"number":case"range":return b?!isNaN(c)&&parseFloat(c)<=parseFloat(e):!isNaN(c)&&parseFloat(c)>=parseFloat(e);default:return b?e>=c:c>=e}}}function d(a,b,c){return b.validator(a(),void 0===c.params?!0:h(c.params))?!0:(a.setError(f.formatMessage(c.message||b.message,h(c.params),a)),!1)}function e(a,b,c){a.isValidating(!0);var d=function(d){var e=!1,g="";return a.__valid__()?(d.message?(e=d.isValid,g=d.message):e=d,e||(a.error(f.formatMessage(g||c.message||b.message,h(c.params),a)),a.__valid__(e)),void a.isValidating(!1)):void a.isValidating(!1)};b.validator(a(),h(c.params||!0),d)}if("undefined"==typeof a)throw new Error("Knockout is required, please ensure it is loaded before loading this validation plug-in");a.validation=b;var f=a.validation,g=a.utils,h=g.unwrapObservable,i=g.arrayForEach,j=g.extend,k={registerExtenders:!0,messagesOnModified:!0,errorsAsTitle:!0,errorsAsTitleOnModified:!1,messageTemplate:null,insertMessages:!0,parseInputAttributes:!1,writeInputAttributes:!1,decorateInputElement:!1,decorateElementOnModified:!0,errorClass:null,errorElementClass:"validationElement",errorMessageClass:"validationMessage",allowHtmlMessages:!1,grouping:{deep:!1,observable:!0,live:!1},validate:{}},l=j({},k);l.html5Attributes=["required","pattern","min","max","step"],l.html5InputTypes=["email","number","date"],l.reset=function(){j(l,k)},f.configuration=l,f.utils=function(){var a=(new Date).getTime(),b={},c="__ko_validation__";return{isArray:function(a){return a.isArray||"[object Array]"===Object.prototype.toString.call(a)},isObject:function(a){return null!==a&&"object"==typeof a},isNumber:function(a){return!isNaN(a)},isObservableArray:function(a){return!!a&&"function"==typeof a.remove&&"function"==typeof a.removeAll&&"function"==typeof a.destroy&&"function"==typeof a.destroyAll&&"function"==typeof a.indexOf&&"function"==typeof a.replace},values:function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(a[c]);return b},getValue:function(a){return"function"==typeof a?a():a},hasAttribute:function(a,b){return null!==a.getAttribute(b)},getAttribute:function(a,b){return a.getAttribute(b)},setAttribute:function(a,b,c){return a.setAttribute(b,c)},isValidatable:function(a){return!!(a&&a.rules&&a.isValid&&a.isModified)},insertAfter:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},newId:function(){return a+=1},getConfigOptions:function(a){var b=f.utils.contextFor(a);return b||f.configuration},setDomData:function(a,d){var e=a[c];e||(a[c]=e=f.utils.newId()),b[e]=d},getDomData:function(a){var d=a[c];return d?b[d]:void 0},contextFor:function(a){switch(a.nodeType){case 1:case 8:var b=f.utils.getDomData(a);if(b)return b;if(a.parentNode)return f.utils.contextFor(a.parentNode)}return void 0},isEmptyVal:function(a){return void 0===a?!0:null===a?!0:""===a?!0:void 0},getOriginalElementTitle:function(a){var b=f.utils.getAttribute(a,"data-orig-title"),c=a.title,d=f.utils.hasAttribute(a,"data-orig-title");return d?b:c},async:function(a){window.setImmediate?window.setImmediate(a):window.setTimeout(a,0)},forEach:function(a,b){if(f.utils.isArray(a))return i(a,b);for(var c in a)a.hasOwnProperty(c)&&b(a[c],c)}}}();var m=function(){function b(a){i(a.subscriptions,function(a){a.dispose()}),a.subscriptions=[]}function c(a){a.options.deep&&(i(a.flagged,function(a){delete a.__kv_traversed}),a.flagged.length=0),a.options.live||b(a)}function d(a,d){d.validatables=[],b(d),e(a,d),c(d)}function e(b,c,d){var f=[],g=b.peek?b.peek():b;b.__kv_traversed!==!0&&(c.options.deep&&(b.__kv_traversed=!0,c.flagged.push(b)),d=void 0!==d?d:c.options.deep?1:-1,a.isObservable(b)&&(b.errors||n.isValidatable(b)||b.extend({validatable:!0}),c.validatables.push(b),c.options.live&&n.isObservableArray(b)&&c.subscriptions.push(b.subscribe(function(){c.graphMonitor.valueHasMutated()}))),g&&!g._destroy&&(n.isArray(g)?f=g:n.isObject(g)&&(f=n.values(g))),0!==d&&n.forEach(f,function(b){!b||b.nodeType||a.isComputed(b)&&!b.rules||e(b,c,d+1)}))}function k(a){var b=[];return i(a,function(a){n.isValidatable(a)&&!a.isValid()&&b.push(a.error.peek())}),b}var l=0,m=f.configuration,n=f.utils;return{init:function(a,b){l>0&&!b||(a=a||{},a.errorElementClass=a.errorElementClass||a.errorClass||m.errorElementClass,a.errorMessageClass=a.errorMessageClass||a.errorClass||m.errorMessageClass,j(m,a),m.registerExtenders&&f.registerExtenders(),l=1)},reset:f.configuration.reset,group:function(b,c){c=j(j({},m.grouping),c);var e={options:c,graphMonitor:a.observable(),flagged:[],subscriptions:[],validatables:[]},f=null;return f=c.observable?a.computed(function(){return e.graphMonitor(),d(b,e),k(e.validatables)}):function(){return d(b,e),k(e.validatables)},f.showAllMessages=function(a){void 0===a&&(a=!0),f.forEach(function(b){n.isValidatable(b)&&b.isModified(a)})},f.isAnyMessageShown=function(){var a;return a=!!f.find(function(a){return n.isValidatable(a)&&!a.isValid()&&a.isModified()})},f.filter=function(a){return a=a||function(){return!0},f(),g.arrayFilter(e.validatables,a)},f.find=function(a){return a=a||function(){return!0},f(),g.arrayFirst(e.validatables,a)},f.forEach=function(a){a=a||function(){},f(),i(e.validatables,a)},f.map=function(a){return a=a||function(a){return a},f(),g.arrayMap(e.validatables,a)},f._updateState=function(a){if(!n.isObject(a))throw new Error("An object is required.");return b=a,c.observable?void e.graphMonitor.valueHasMutated():(d(a,e),k(e.validatables))},f},formatMessage:function(a,b,c){if(n.isObject(b)&&b.typeAttr&&(b=b.value),"function"==typeof a)return a(b,c);var d=h(b)||[];return n.isArray(d)||(d=[d]),a.replace(/{(\d+)}/gi,function(a,b){return"undefined"!=typeof d[b]?d[b]:a})},addRule:function(a,b){a.extend({validatable:!0});var c=!!g.arrayFirst(a.rules(),function(a){return a.rule&&a.rule===b.rule});return c||a.rules.push(b),a},addAnonymousRule:function(a,b){void 0===b.message&&(b.message="Error"),b.onlyIf&&(b.condition=b.onlyIf),f.addRule(a,b)},addExtender:function(b){a.extenders[b]=function(a,c){return c&&(c.message||c.onlyIf)?f.addRule(a,{rule:b,message:c.message,params:n.isEmptyVal(c.params)?!0:c.params,condition:c.onlyIf}):f.addRule(a,{rule:b,params:c})}},registerExtenders:function(){if(m.registerExtenders)for(var b in f.rules)f.rules.hasOwnProperty(b)&&(a.extenders[b]||f.addExtender(b))},insertValidationMessage:function(a){var b=document.createElement("SPAN");return b.className=n.getConfigOptions(a).errorMessageClass,n.insertAfter(a,b),b},parseInputValidationAttributes:function(a,b){i(f.configuration.html5Attributes,function(c){if(n.hasAttribute(a,c)){var d=a.getAttribute(c)||!0;if("min"===c||"max"===c){var e=a.getAttribute("type");"undefined"!=typeof e&&e||(e="text"),d={typeAttr:e,value:d}}f.addRule(b(),{rule:c,params:d})}});var c=a.getAttribute("type");i(f.configuration.html5InputTypes,function(a){a===c&&f.addRule(b(),{rule:"date"===a?"dateISO":a,params:!0})})},writeInputValidationAttributes:function(b,c){var d=c();if(d&&d.rules){var e=d.rules();i(f.configuration.html5Attributes,function(c){var d=g.arrayFirst(e,function(a){return a.rule&&a.rule.toLowerCase()===c.toLowerCase()});d&&a.computed({read:function(){var e=a.unwrap(d.params);"pattern"===d.rule&&e instanceof RegExp&&(e=e.source),b.setAttribute(c,e)},disposeWhenNodeIsRemoved:b})}),e=null}},makeBindingHandlerValidatable:function(b){var c=a.bindingHandlers[b].init;a.bindingHandlers[b].init=function(b,d,e,f,g){return c(b,d,e,f,g),a.bindingHandlers.validationCore.init(b,d,e,f,g)}},setRules:function(b,c){var d=function(b,c){if(b&&c)for(var e in c)if(c.hasOwnProperty(e)){var g=c[e];if(b[e]){var i=b[e],j=h(i),k={},l={};for(var m in g)g.hasOwnProperty(m)&&(f.rules[m]?k[m]=g[m]:l[m]=g[m]);if(a.isObservable(i)&&i.extend(k),j&&n.isArray(j))for(var o=0;o<j.length;o++)d(j[o],l);else d(j,l)}}};d(b,c)}}}();j(a.validation,m),f.rules={},f.rules.required={validator:function(a,b){var c;return void 0===a||null===a?!b:(c=a,"string"==typeof a&&(c=String.prototype.trim?a.trim():a.replace(/^\s+|\s+$/g,"")),b?(c+"").length>0:!0)},message:"This field is required."},f.rules.min={validator:c("min"),message:"Please enter a value greater than or equal to {0}."},f.rules.max={validator:c("max"),message:"Please enter a value less than or equal to {0}."},f.rules.minLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length>=b},message:"Please enter at least {0} characters."},f.rules.maxLength={validator:function(a,b){if(f.utils.isEmptyVal(a))return!0;var c=f.utils.isNumber(a)?""+a:a;return c.length<=b},message:"Please enter no more than {0} characters."},f.rules.pattern={validator:function(a,b){return f.utils.isEmptyVal(a)||null!==a.toString().match(b)},message:"Please check this value."},f.rules.step={validator:function(a,b){if(f.utils.isEmptyVal(a)||"any"===b)return!0;var c=100*a%(100*b);return Math.abs(c)<1e-5||Math.abs(1-c)<1e-5},message:"The value must increment by {0}."},f.rules.email={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(a):!0},message:"Please enter a proper email address."},f.rules.date={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&!/Invalid|NaN/.test(new Date(a)):!0},message:"Please enter a proper date."},f.rules.dateISO={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(a):!0},message:"Please enter a proper date."},f.rules.number={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a):!0},message:"Please enter a number."},f.rules.digit={validator:function(a,b){return b?f.utils.isEmptyVal(a)||b&&/^\d+$/.test(a):!0},message:"Please enter a digit."},f.rules.phoneUS={validator:function(a,b){return b?f.utils.isEmptyVal(a)?!0:"string"!=typeof a?!1:(a=a.replace(/\s+/g,""),b&&a.length>9&&a.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/)):!0},message:"Please specify a valid phone number."},f.rules.equal={validator:function(a,b){var c=b;return a===f.utils.getValue(c)},message:"Values must equal."},f.rules.notEqual={validator:function(a,b){var c=b;return a!==f.utils.getValue(c)},message:"Please choose another value."},f.rules.unique={validator:function(a,b){var c=f.utils.getValue(b.collection),d=f.utils.getValue(b.externalValue),e=0;return a&&c?(g.arrayFilter(c,function(c){a===(b.valueAccessor?b.valueAccessor(c):c)&&e++}),(d?1:2)>e):!0},message:"Please make sure the value is unique."},function(){f.registerExtenders()}(),a.bindingHandlers.validationCore=function(){return{init:function(b,c){var d=f.utils.getConfigOptions(b),e=c();if(d.parseInputAttributes&&f.utils.async(function(){f.parseInputValidationAttributes(b,c)}),d.insertMessages&&f.utils.isValidatable(e)){var g=f.insertValidationMessage(b);d.messageTemplate?a.renderTemplate(d.messageTemplate,{field:e},null,g,"replaceNode"):a.applyBindingsToNode(g,{validationMessage:e})}d.writeInputAttributes&&f.utils.isValidatable(e)&&f.writeInputValidationAttributes(b,c),d.decorateInputElement&&f.utils.isValidatable(e)&&a.applyBindingsToNode(b,{validationElement:e})}}}(),f.makeBindingHandlerValidatable("value"),f.makeBindingHandlerValidatable("checked"),a.bindingHandlers.textInput&&f.makeBindingHandlerValidatable("textInput"),f.makeBindingHandlerValidatable("selectedOptions"),a.bindingHandlers.validationMessage={update:function(b,c){var d=c(),e=f.utils.getConfigOptions(b),i=(h(d),!1),j=!1;if(null===d||"undefined"==typeof d)throw new Error("Cannot bind validationMessage to undefined value. data-bind expression: "+b.getAttribute("data-bind"));i=d.isModified&&d.isModified(),j=d.isValid&&d.isValid();var k=null;(!e.messagesOnModified||i)&&(k=j?null:d.error);var l=!e.messagesOnModified||i?!j:!1,m="none"!==b.style.display;e.allowHtmlMessages?g.setHtml(b,k):a.bindingHandlers.text.update(b,function(){return k}),m&&!l?b.style.display="none":!m&&l&&(b.style.display="")}},a.bindingHandlers.validationElement={update:function(b,c,d){var e=c(),g=f.utils.getConfigOptions(b),i=(h(e),!1),j=!1;if(null===e||"undefined"==typeof e)throw new Error("Cannot bind validationElement to undefined value. data-bind expression: "+b.getAttribute("data-bind"));i=e.isModified&&e.isModified(),j=e.isValid&&e.isValid();var k=function(){var a={},b=!g.decorateElementOnModified||i?!j:!1;return a[g.errorElementClass]=b,a};a.bindingHandlers.css.update(b,k,d),g.errorsAsTitle&&a.bindingHandlers.attr.update(b,function(){var a=!g.errorsAsTitleOnModified||i,c=f.utils.getOriginalElementTitle(b);return a&&!j?{title:e.error,"data-orig-title":c}:!a||j?{title:c,"data-orig-title":null}:void 0})}},a.bindingHandlers.validationOptions=function(){return{init:function(a,b){var c=h(b());if(c){var d=j({},f.configuration);j(d,c),f.utils.setDomData(a,d)}}}}(),a.extenders.validation=function(a,b){return i(f.utils.isArray(b)?b:[b],function(b){f.addAnonymousRule(a,b)}),a},a.extenders.validatable=function(b,c){if(f.utils.isObject(c)||(c={enable:c}),"enable"in c||(c.enable=!0),c.enable&&!f.utils.isValidatable(b)){var d=f.configuration.validate||{},e={throttleEvaluation:c.throttle||d.throttle};b.error=a.observable(null),b.rules=a.observableArray(),b.isValidating=a.observable(!1),b.__valid__=a.observable(!0),b.isModified=a.observable(!1),b.isValid=a.computed(b.__valid__),b.setError=function(a){var c=b.error.peek(),d=b.__valid__.peek();b.error(a),b.__valid__(!1),c===a||d||b.isValid.notifySubscribers()},b.clearError=function(){return b.error(null),b.__valid__(!0),b};var g=b.subscribe(function(){b.isModified(!0)}),h=a.computed(j({read:function(){b(),b.rules();return f.validateObservable(b),!0}},e));j(h,e),b._disposeValidation=function(){b.isValid.dispose(),b.rules.removeAll(),g.dispose(),h.dispose(),delete b.rules,delete b.error,delete b.isValid,delete b.isValidating,delete b.__valid__,delete b.isModified,delete b.setError,delete b.clearError,delete b._disposeValidation}}else c.enable===!1&&b._disposeValidation&&b._disposeValidation();return b},f.validateObservable=function(a){for(var b,c,g=0,h=a.rules(),i=h.length;i>g;g++)if(c=h[g],!c.condition||c.condition())if(b=c.rule?f.rules[c.rule]:c,b.async||c.async)e(a,b,c);else if(!d(a,b,c))return!1;return a.clearError(),!0};var n,o={};f.defineLocale=function(a,b){return a&&b?(o[a.toLowerCase()]=b,b):null},f.locale=function(a){if(a){if(a=a.toLowerCase(),!o.hasOwnProperty(a))throw new Error("Localization "+a+" has not been loaded.");f.localize(o[a]),n=a}return n},f.localize=function(a){var b=f.rules;for(var c in a)b.hasOwnProperty(c)&&(b[c].message=a[c])},function(){var a={},b=f.rules;for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c].message);f.defineLocale("en-us",a)}(),n="en-us",a.applyBindingsWithValidation=function(b,c,d){var e,g=document.body;c&&c.nodeType?(g=c,e=d):e=c,f.init(),e&&(e=j(j({},f.configuration),e),f.utils.setDomData(g,e)),a.applyBindings(b,g)};var p=a.applyBindings;a.applyBindings=function(a,b){f.init(),p(a,b)},a.validatedObservable=function(b,c){if(!c&&!f.utils.isObject(b))return a.observable(b).extend({validatable:!0});var d=a.observable(b);return d.errors=f.group(f.utils.isObject(b)?b:{},c),d.isValid=a.observable(0===d.errors().length),a.isObservable(d.errors)?d.errors.subscribe(function(a){d.isValid(0===a.length)}):a.computed(d.errors).subscribe(function(a){d.isValid(0===a.length)}),d.subscribe(function(a){f.utils.isObject(a)||(a={}),d.errors._updateState(a),d.isValid(0===d.errors().length)}),d}});sn.app.referrals=sn.app.referrals||{maxEmailsAllowed:5,init:function(maxEmails){if(maxEmails>1){sn.app.referrals.maxEmailsAllowed=maxEmails;}
sn.app.referrals.initSignupClick();$(".tac blue").tooltip();$("#friendsEmailAddressList").tagit({placeholderText:"Add "+sn.app.referrals.maxEmailsAllowed+" friends' email addresses",tagLimit:sn.app.referrals.maxEmailsAllowed,beforeTagAdded:function(event,ui){var result=false;var input=ui.tagLabel;var emails=input.split(/[ ,;]+/);if(emails.length>1){emails.forEach(function(email){$("#friendsEmailAddressList").tagit("createTag",email);});return false;}
if(!sn.app.isValidEmailAddress(ui.tagLabel)){ui.tag.addClass("invalid-tag");$(".sendemail.first").addClass("disabled");}
else{result=true;$(".sendemail.first").removeClass("disabled");ui.tag.removeClass("invalid-tag");sn.app.referrals.hideMessage();}
$(".tagit-new input.ui-autocomplete-input")[0].placeholder="";$(".tagit-new input.ui-autocomplete-input")[0].style.width="100%";$(".tagit-new input.ui-autocomplete-input")[0].style.textAlign="left";$(".tagit-new")[0].style.width="40%";return result;},});$("#friendsEmailAddressList").change(function(){$($("a.sendemail")[0]).data("email-address-list",$(this).val());$("#messageLocator").data("email-address",$(this).val());var currentHeightOfEmailBar=$($(".earn")[0]).position().top+$($(".earn")[0]).outerHeight(true);$("#referralDetail").parent().slideDown(currentHeightOfEmailBar);});$("a.sendemail").click(function(event){event.preventDefault();var sender=$(this);if(sn.app.referrals.isUserLoggedIn()){if(!sender.hasClass("disabled")){var emailAddressList=sender.data("email-address-list");if(emailAddressList===undefined){sn.app.referrals.showError("#messageLocator","Please enter a valid email address");return;}
var isReminder=sender.hasClass("remind");sn.app.referrals.sendEmail(emailAddressList,sender,isReminder);}}
else{sn.app.showLogin(function(e){if(e.status){if(!sender.hasClass("disabled")){var emailAddressList=sender.data("email-address-list");if(emailAddressList===undefined){sn.app.referrals.showError("#messageLocator","Please enter a valid email address");return;}
var isReminder=sender.hasClass("remind");sn.app.referrals.sendEmail(emailAddressList,sender,isReminder);}}},function(e){if(e.status){if(!sender.hasClass("disabled")){var emailAddressList=sender.data("email-address-list");if(emailAddressList===undefined){sn.app.referrals.showError("#messageLocator","Please enter a valid email address");return;}
var isReminder=sender.hasClass("remind");sn.app.referrals.sendEmail(emailAddressList,sender,isReminder);}}});}});$(".login-wallet").on("click",function(event){event.preventDefault();sn.app.showLogin(function(e){if(e.status){window.location.reload(true);}},function(e){if(e.status){window.location.reload(true);}});});},initSignupClick:function(){$("#signUpButton").on("click",function(){sn.app.showRegister(function(e){if(e.status){window.location.reload(true);}},function(e){if(e.status){window.location.reload(true);}});});},isUserLoggedIn:function(){var contactId=-1;if($("#referralContactId").length>0){contactId=$("#referralContactId").first().val();return contactId>0;}
else if($("#hfCustomerId").length>0){contactId=$("#hfCustomerId").first().val();return contactId>0;}
return false;},getReferrerContactId:function(){var contactid=-3;if($("#referralContactId").length>0){var contactId=$("#referralContactId").first().val();return contactId;}
else if($("#hfCustomerId").length>0){contactId=$("#hfCustomerId").first().val();return contactId;}
return-3;},sendEmail:function(emailAddressList,sender,isReminder){var data={"emailAddressList":emailAddressList,"contactId":sn.app.referrals.getReferrerContactId()};var urlString=isReminder?"/referral/processreminders":"/referral/processreferrals";var processJsonData=false;if(document.URL.indexOf("paymentresult.aspx")>=0){urlString="/referral/processpaymentreferrals";processJsonData=true;}
if(!emailAddressList){sn.app.referrals.showError("#messageLocator","No valid email addresses found.");return;}
sn.app.referrals.hideMessage();$.ajax({dataType:"html",type:"POST",contentType:"application/json; charset=utf-8",url:urlString,data:JSON.stringify(data),beforeSend:function(){$($("a.sendemail")["0"]).html("<i class='icon-spin3 animate-spin'> </i> Sending...");}}).done(function(response){if(processJsonData){var jsonResponse=$.parseJSON(response);if(jsonResponse.ValidEmails==="true"){sn.app.referrals.showSuccess("#messageLocator",jsonResponse.Message);}
else{sn.app.referrals.showError("#messageLocator",jsonResponse.Message);}}
sn.app.referrals.reset();}).always(function(response){sn.app.referrals.afterSendSuccess(sender,response);}).fail(function(jqXhr,textStatus,errorThrown){sn.app.referrals.afterSendFail(sender,jqXhr,textStatus,errorThrown);});},afterSendSuccess:function(sender,response){if(response.indexOf("referralDetail")>0){$("#referralDetail").replaceWith(response);$("#newlyAddeddReferralsContainer").show();$("html, body").animate({scrollTop:$("#referralDetail").offset().top},1000);$("#referralDetail").effect("highlight",{},1000);}
else{sn.app.referrals.showSuccess('label[data-email-address="'+sender.data("email-address-list")+'"]',response);}},afterSendFail:function(sender,jqXhr,textStatus,errorThrown){sn.app.referrals.showError('label[data-email-address="'+sender.data("email-address-list")+'"]',errorThrown);},showSuccess:function(selector,message){$(selector).removeClass("red");$(selector).addClass("green larger");sn.app.referrals.showMessage(selector,message,false);},showError:function(selector,message){$(selector).removeClass("blue");$(selector).removeClass("larger");$(selector).addClass("red");sn.app.referrals.showMessage(selector,message,false);},showMessage:function(selector,message,hideAfterShow){if(hideAfterShow===void 0){hideAfterShow=true;}
$(selector).html("");$(selector).append(message);$(selector).show();},hideMessage:function(){$("#messageLocator").hide();},reset:function(){$($("a.sendemail")["0"]).html("Invite friends");$("#friendsEmailAddressList").tagit("removeAll");$(".tagit-new input.ui-autocomplete-input")[0].placeholder="Add "+sn.app.referrals.maxEmailsAllowed+" friends' email addresses";$(".tagit-new input.ui-autocomplete-input")[0].style.width="";$(".tagit-new input.ui-autocomplete-input")[0].style.textAlign="center";$(".tagit-new")[0].style.width="";},initReferralHeaderBanner:function(){$(".referral-notice").hide();$(".closeReferral").on("click",sn.app.referrals.hideReferralHeaderBanner);sn.app.referrals.mustShowReferralHeaderBanner(true);},mustShowReferralHeaderBanner:function(wireAjaxPostBack){var displayNotification=false;var cookie=sn.app.getCookieValue("vc_",true);if(cookie!==undefined){var o=JSON.parse(cookie);var today=new Date();today.setHours(0,0,0,0);var validDate=new Date();validDate.setHours(0,0,0,0);if(o.ExpiryDate!=null){validDate=new Date(o.ExpiryDate);validDate.setHours(0,0,0,0);}
else{validDate=today;}
displayNotification=validDate>=today;if(wireAjaxPostBack){if(displayNotification){$.ajax({method:"get",data:{voucherCode:o.ShortCode},url:"/referral/getvouchercookiemodel",async:true,success:function(model){if(model!==undefined){o=model;var datediff=Math.round((validDate.valueOf()-today.valueOf())/(1000*60*60*24));sn.app.setCookie("vc_"+model.ShortCode,JSON.stringify(model),datediff);displayNotification=datediff>=0;}}});if(displayNotification){sn.app.referrals.showReferralHeaderBanner(o);sn.app.referrals.initializeStickyNotification();}
else{sn.app.referrals.hideReferralHeaderBanner();}}}}},showReferralHeaderBanner:function(model){var notice=$(".referral-notice");var noticeAmount=$(".referral-value-amount");var noticeShortCode=$(".referral-voucher-code");var noticeExpiry=$(".referral-expirydate");noticeAmount.text(model.AmountDisplay);noticeShortCode.text(model.ShortCode);var parseDate=new Date(model.ExpiryDate);noticeExpiry.text(parseDate.toDateString());notice.show();},initializeStickyNotification:function(){sn.app.referrals.stickyNotificationOnScroll();window.addEventListener("scroll",sn.app.referrals.stickyNotificationOnScroll);window.addEventListener("resize",sn.app.referrals.stickyNotificationOnScroll);},stickyNotificationOnScroll:function(){if(sn.app.getCookieValue("vc_",true)){var docViewTop=$(window).scrollTop();if(docViewTop>50){$(".referral-notice").addClass("stickyFixedToTop");$(".referral-notice").fadeIn();}
else{$(".referral-notice").removeClass("stickyFixedToTop");}}},hideReferralHeaderBanner:function(){$(".referral-notice").hide();sn.app.deleteCookie("vc_");}};var Sticky=(function(){function Sticky(){}
Sticky.prototype.bind=function(selector,parentSelector,startStickyAt){this.selector=selector;if(parentSelector!=null)
this.parentSelector=parentSelector;this.startStickyAt=startStickyAt;this.bindEventListeners();};Sticky.prototype.bindEventListeners=function(){var _this=this;var stickyTick=function(){_this.tick();};var stickyTickThrottle=Util.throttle(function(){_this.tick();},50);window.addEventListener("DOMContentLoaded",stickyTick);window.addEventListener("resize",stickyTickThrottle);window.addEventListener("scroll",stickyTickThrottle);};Sticky.prototype.tick=function(){if(Util.isDesktopWidth()){var elements=document.querySelectorAll(this.selector);for(var i=0;i<elements.length;i++){var element=elements.item(i);var isVisible=element.offsetWidth>0||element.offsetHeight>0||element.getClientRects().length>0;if(!isVisible){continue;}
if(element.attributes['data-stickystartat']){this.startStickyAt=element.attributes['data-stickystartat'].value;}
else{this.startStickyAt=0;}
var parent_1=null;if(this.parentSelector===undefined){parent_1=element.parentElement;}
else{parent_1=document.querySelector(this.parentSelector);}
var containerBounds=parent_1.getBoundingClientRect();var computed=window.getComputedStyle(element.parentElement);var width=null;if(element.style.position==="static"||element.style.position==="relative"||element.style.position===""){width=element.offsetWidth;}
else{width=computed.width;}
if(containerBounds.bottom<=element.offsetHeight+parseInt(computed.paddingBottom)){element.style.position="initial";element.style.bottom='0px';element.style.width=width+"px";element.style.top="";}
else if((this.startStickyAt>=0&&containerBounds.top<-this.startStickyAt)||containerBounds.top<-300){element.style.position="fixed";if(element.attributes["data-stickytoppad"]){element.style.top=element.attributes["data-stickytoppad"].value;}
else if(this.startStickyAt==0){element.style.top="0px";}
else{element.style.top="20px";}
element.style.width=width+"px";element.style.height="auto";element.style.bottom="";}
else{element.style.position="relative";element.style.top="";element.style.bottom="";element.style.width="";}
var nextsibling=element.nextElementSibling;if(nextsibling!=null&&element.style.position=="fixed"){nextsibling.style.paddingTop=element.clientHeight+20+'px';}
else if(nextsibling!=null&&element.style.position!="fixed"){nextsibling.style.paddingTop='initial';}}}};return Sticky;}());var Util=(function(){function Util(){}
Util.isMobile=function(){return /iPhone|iPod|Android|Opera Mini|BlackBerry|Nokia|Mobile|PlayBook|KFAPWI/i.test(navigator.userAgent);};Util.isDesktop=function(){return!Util.isMobile();};Util.isMobileWidth=function(){return Modernizr.mq("(max-width: 767px)");};Util.isDesktopWidth=function(){return!Util.isMobileWidth();};Util.formatDate=function(date){var calendarMonths=["Janurary","Feburary","March","April","May","June","July","August","September","October","November","December"];return date.getDate()+" "+calendarMonths[date.getMonth()].substring(0,3)+" "+date.getFullYear();};Util.formatApiDate=function(date){var calendarMonths=["Janurary","Feburary","March","April","May","June","July","August","September","October","November","December"];return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();};Util.throttle=function(fn,threshhold){threshhold||(threshhold=250);var last=null;var deferTimer=null;return function(){var now=new Date(),args=arguments;if(last&&now<last+threshhold){clearTimeout(deferTimer);deferTimer=setTimeout(function(){last=now;fn(args);},threshhold);}
else{last=now;fn(args);}};};Util.guid=function(){return this.s4()+this.s4()+'-'+this.s4()+'-'+this.s4()+'-'+
this.s4()+'-'+this.s4()+this.s4()+this.s4();};Util.s4=function(){return Math.floor((1+Math.random())*0x10000).toString(16).substring(1);};Util.isInViewPort=function(elem){var bounding=elem.getBoundingClientRect();return(bounding.top>=0&&bounding.left>=0&&bounding.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&bounding.right<=(window.innerWidth||document.documentElement.clientWidth));};return Util;}());var StepWizard=(function(){function StepWizard(stepsParam){this.steps=ko.observableArray(stepsParam);}
StepWizard.prototype.activate=function(stepNumbers){for(var _i=0,_a=this.steps();_i<_a.length;_i++){var step=_a[_i];step.stepActivatorObservable(false);}
for(var _b=0,_c=stepNumbers.split(",");_b<_c.length;_b++){var n=_c[_b];for(var _d=0,_e=this.steps();_d<_e.length;_d++){var step=_e[_d];if(step.step().toString()===n){step.stepActivatorObservable(true);}}}};;return StepWizard;}());var Step=(function(){function Step(stepNum,stepText,isStepActive,action){if(isStepActive===void 0){isStepActive=ko.observable(false);}
if(action===void 0){action=null;}
this.step=ko.observable(stepNum);this.text=ko.observable(stepText);this.isActive=ko.computed(function(){return isStepActive();});this.action=action;this.stepActivatorObservable=isStepActive;}
return Step;}());var Money=(function(){function Money(amount,currencySymbol,displaySuffix){var _this=this;if(amount===void 0){amount=0;}
if(currencySymbol===void 0){currencySymbol="R";}
if(displaySuffix===void 0){displaySuffix="";}
this.SetAmount=function(amount,currencySymbol,displaySuffix){if(currencySymbol===void 0){currencySymbol="R";}
if(displaySuffix===void 0){displaySuffix="";}
var vm=this;amount=(parseFloat(amount.toFixed(2)));vm.Amount(amount);vm.CurrencySymbol(currencySymbol);vm.DisplaySuffix=displaySuffix;vm.Display.notifySubscribers();vm.CurrencySymbol.notifySubscribers();};this.CurrencySymbol=ko.observable(currencySymbol);this.DisplaySuffix=displaySuffix;this.Amount=ko.observable(amount);this.Display=ko.computed(function(){_this.Amount(+_this.Amount());if(_this.Amount()<0){return "- "+_this.CurrencySymbol()+(parseFloat(_this.Amount().toFixed(2)))*-1+_this.DisplaySuffix;}
return ""+_this.CurrencySymbol()+(parseFloat(_this.Amount().toFixed(2)))+_this.DisplaySuffix;});}
return Money;}());var InvoiceLineItem=(function(){function InvoiceLineItem(description,amount,special,cssclass){var _this=this;if(special===void 0){special=null;}
if(cssclass===void 0){cssclass="";}
this.Description=description;this.Amount=amount;this.Special=special;this.CssClass=ko.computed(function(){var rclass="";if(cssclass!=""){rclass=cssclass;}
if(_this.Special!=null&&_this.Special.summary!=""){rclass=rclass+" specialineitem";}
return rclass;});}
return InvoiceLineItem;}());var Rate=(function(){function Rate(v,currencysymbol){this.value=v;this.currencySymbol=currencysymbol;this.displayValue=""+currencysymbol+(v).toFixed(2);}
Rate.prototype.hasSpecial=function(){return this.special!=null&&this.special.specialId>0;};return Rate;}());var Special=(function(){function Special(id,freebieOnly,amount,summary,freebieDetails,originalAmount){this.specialId=id;this.isFreebieOnly=freebieOnly;this.amount=amount;this.summary=summary;this.freebieDetails=freebieDetails;this.originalAmount=originalAmount;}
return Special;}());var KoConfig=(function(){function KoConfig(){}
KoConfig.configureKO=function(){if(typeof ko==="undefined"){return;}
ko.options.deferUpdates=true;ko.bindingHandlers.valueWithInit={init:function(element,valueAccessor,allBindingsAccessor,data){var property=valueAccessor(),value=element.value;if(!ko.isWriteableObservable(data[property])){data[property]=ko.observable();}
if(value!=null&&value!==""&&value.toLowerCase()==="true"){value=true;}
else if(value!=null&&value!==""&&value.toLowerCase()==="false"){value=false;}
data[property](value);ko.applyBindingsToNode(element,{value:data[property]});}};ko.bindingHandlers.hidden={init:function(element,valueAccessor,allBindingsAccessor,data){var hidden=ko.unwrap(valueAccessor());$(element).css('visibility',hidden?'hidden':'visible');}};ko.bindingHandlers.numeric={init:function(element,valueAccessor){$(element).on("keydown",function(event){if(event.keyCode==46||event.keyCode==8||event.keyCode==9||event.keyCode==27||event.keyCode==13||(event.keyCode==65&&event.ctrlKey===true)||(event.keyCode==188||event.keyCode==190||event.keyCode==110)||(event.keyCode>=35&&event.keyCode<=39)){return;}
else{if(event.shiftKey||(event.keyCode<48||event.keyCode>57)&&(event.keyCode<96||event.keyCode>105)){event.preventDefault();}}});}};ko.bindingHandlers.backgroundImage={update:function(element,valueAccessor,allBindingsAccessor,data,bindingContext){ko.bindingHandlers.style.update(element,function(){return{backgroundImage:"url('"+valueAccessor()()+"')"};},allBindingsAccessor,data,bindingContext);}};ko.validation.rules.between={validator:function(value,params){var min=params[0];var max=params[1];value=parseInt(value,10);if(!isNaN(value)){return value>=min&&value<=max;}
return false;},message:'Value must be between {0} and {1}'};ko.validation.init({messagesOnModified:true,decorateElementOnModified:true,decorateInputElement:true},true);};;return KoConfig;}());ko.components.register('pax-picker',{viewModel:function(params){var self=this;self.Adults=params.Adults!=null?params.Adults:ko.observable(2);self.Children1=params.Children1!=null?params.Children1:ko.observable(0);self.Children2=params.Children2!=null?params.Children2:ko.observable(0);self.Children3=params.Children3!=null?params.Children3:ko.observable(0);self.MaxPax=params.MaxPax!=null?params.MaxPax:ko.observable(2);self.MaxAdults=params.MaxAdults!=null?params.MaxAdults:ko.observable(2);self.MinAdults=params.MinAdults!=null?params.MinAdults:ko.observable(1);self.MaxChildren=params.MaxChildren!==null?params.MaxChildren:ko.observable(0);self.Child1Min=params.Child1Min!=null?params.Child1Min:ko.observable(0);self.Child1Max=params.Child1Max!=null?params.Child1Max:ko.observable(0);self.Child2Min=params.Child2Min!=null?params.Child2Min:ko.observable(0);self.Child2Max=params.Child2Max!=null?params.Child2Max:ko.observable(0);self.Child3Min=params.Child3Min!=null?params.Child3Min:ko.observable(0);self.Child3Max=params.Child3Max!=null?params.Child3Max:ko.observable(0);self.NeedsDates=params.NeedsDates!=null?params.NeedsDates:false;self.ChildrenList=params.ChildrenList!=null?params.ChildrenList:ko.observableArray([]);self.ChildAges=params.ChildAges!=null?params.ChildAges:ko.observableArray([]);self.ChildrenAgeOptions=params.ChildrenAgeOptions!=null?params.ChildrenAgeOptions:ko.observableArray([]);var maxChildAge=17;self.usingAgeBands=ko.observable(self.Child1Max()>0&&(self.Child2Max()>0||self.Child3Max()>0));if(!self.usingAgeBands()){maxChildAge=self.Child1Max();}
for(var i=1;i<=maxChildAge;i++){self.ChildrenAgeOptions.push(i);}
self.Children=function(){return this.Children1()+this.Children2()+this.Children3();};self.Pax=function(){return this.Children()+this.Adults();};self.RS=function(){return(((1+Math.random())*0x10000)|0).toString(16).substring(1);};self.GUID=function(){return(self.RS()+self.RS()+"-"+self.RS()+"-4"+self.RS().substr(0,3)+"-"+self.RS()+"-"+self.RS()+self.RS()+self.RS()).toLowerCase();};self.ContainerId=ko.observable(self.GUID());self.EnableAdultsDecrement=ko.computed(function(){if(self.Adults()>self.MinAdults())
return true;return false;});self.EnableAdultsIncrement=ko.computed(function(){if(self.Pax()>=self.MaxPax())
return false;if(self.Adults()>=self.MaxAdults())
return false;return true;});self.EnableChildrenIncrement=ko.computed(function(){if(self.Pax()>=self.MaxPax())
return false;if(self.Children()>=self.MaxChildren())
return false;return true;});self.IncrementAdults=function(){self.Adults(self.Adults()+1);};self.DecrementAdults=function(){self.Adults(self.Adults()-1);};self.IncrementChildren1=function(){self.Children1(self.Children1()+1);self.ChildrenList.push({Age:ko.observable(0)});};self.DecrementChildren1=function(){self.Children1(self.Children1()-1);self.ChildrenList.pop();};self.IncrementChildren2=function(){self.Children2(self.Children2()+1);};self.DecrementChildren2=function(){self.Children2(self.Children2()-1);};self.IncrementChildren3=function(){self.Children3(self.Children3()+1);};self.DecrementChildren3=function(){self.Children3(self.Children3()-1);};self.PaxDisplay=ko.computed(function(){var display="";if(self.Adults()>0){if(self.Adults()>1){display=self.Adults()+" Adults";}
else{display=self.Adults()+" Adult";}}
var kids=self.Children1()+self.Children2()+self.Children3();if(kids>0){if(kids>1){display=display+", "+kids+" Children";}
else{display=display+", "+kids+" Child";}}
return display;});self.ShowInputs=ko.observable(false);self.ToggleShow=function(){if(self.NeedsDates){var selector=$('.uiDatePickerFromToFrom.checkin').filter(":visible");if($(selector[0]).is(":visible")){$(selector[0]).datepicker("show");}}
else{self.ShowInputs(!self.ShowInputs());}};self.updateChildAges=function(obj,event){self.ChildAges([]);if(self.ChildrenList()!==null){for(var i=0;i<self.ChildrenList();i++){self.ChildAges.push(self.ChildrenList()[i].Age);}}};$("body").on("click",function(e){if(e.target.id==self.ContainerId())
return;if($(e.target).closest("#"+self.ContainerId()).length)
return;if(self.ShowInputs()){self.ToggleShow();}});},template:"\n\t<div data-bind=\"attr: {'id': ContainerId }\" class=\"PaxPickerContainer\">\n\t\t<div data-bind=\"click: ToggleShow\" class=\"PaxPickerDisplay\">\n\t\t\t<div class=\"PaxPickerDisplayText\">\n\t\t\t\t\t<span data-bind=\"text: PaxDisplay\"></span>\n\t\t\t</div>\n\t\t\t<div class=\"PaxPickerDisplaySymbol icon-down-open\"></div>\n\t\t\t<div class=\"PaxClear\"></div>\n\t\t</div>\n\t\t<div class=\"PaxPickerInputs\">\n            <div data-bind=\"visible: ShowInputs\" class=\"PaxPickerInputsContainer ShowInputs\">\n\t\t\t    <div class=\"PaxPickerInputRow\">\n\t\t\t\t    <div class=\"PaxPickerInputText\">\n                        <div class=\"guest-type\">\n                            Adults\n                        </div>\n                    </div>\n\t\t\t\t    <div class=\"PaxPickerInputControls\">\n                        <div class=\"number-picker\">\n\t\t\t\t\t        <button class=\"l-fl l-pad number-picker-button minus\" data-bind=\"enable: EnableAdultsDecrement, click: DecrementAdults, css: {disabled: !EnableAdultsDecrement()}\"></button>\n\t\t\t\t\t        <div class=\"l-fl l-pad number-picker-text\" data-bind=\"text: Adults\" style=\"width: 48px\"></div>\n\t\t\t\t\t        <button class=\"l-fl l-pad number-picker-button plus\" data-bind=\"enable: EnableAdultsIncrement, click: IncrementAdults, css: {disabled: !EnableAdultsIncrement()}\"></button>\n    \t\t\t\t    </div>\n\t\t\t\t    </div>\n\t\t\t\t    <div class=\"PaxClear\"></div>\n\t\t\t    </div>\n\t\t\t    <div class=\"PaxPickerInputRow\" data-bind=\"visible: Child1Max() > 0\">\n                    <div class=\"PaxPickerInputText\">\n                        <div class=\"guest-type\">\n                            Children\n                        </div>\n                        <div class=\"guest-age\">\n                            Ages <span data-bind=\"text: Child1Min\"></span> to <span data-bind=\"text: Child1Max\"></span>\n                        </div>\n                    </div>\n\t\t\t\t    <div class=\"PaxPickerInputControls\">\n                        <div class=\"number-picker\">\n\t\t\t\t\t        <button class=\"l-fl l-pad number-picker-button minus\" data-bind=\"enable: Children1() > 0, click: DecrementChildren1, css: {disabled: Children1() == 0}\"></button>\n\t\t\t\t\t        <div class=\"l-fl l-pad number-picker-text\" data-bind=\"text: Children1\" style=\"width: 48px\"></div>\n\t\t\t\t\t        <button class=\"l-fl l-pad number-picker-button plus\" data-bind=\"enable: EnableChildrenIncrement, click: IncrementChildren1, css: {disabled: !EnableChildrenIncrement()}\"></button>\n\t\t\t\t        </div>\n\t\t\t\t    </div>\t\t\t\t                        \n                    <div class=\"PaxClear\"></div>\n\t\t\t    </div>\n                <div class=\"PaxPickerInputRow\" data-bind=\"visible: !usingAgeBands()\">\n                    <div class=\"PaxPickerChildAgesRow\">                       \n                        <div data-bind=\"foreach: ChildrenList\">\n                            <div style=\"width:50%; float:left\">\n                                <div class=\"guest-type\">\n                                    Child Age <label data-bind=\"text: ($index() +1)\"></label>\n                                </div>\n                                <select data-bind=\"options: $parent.ChildrenAgeOptions, value: Age, event:{ change : $parent.updateChildAges}\"></select>\n                            </div>\n                        </div>\n                    </div>                    \n                    <div class=\"PaxClear\"></div>\n                </div>\n\t\t\t    <div class=\"PaxPickerInputRow\" data-bind=\"visible: Child2Max() > 0 \">\n\t\t\t\t    <div class=\"PaxPickerInputText\">\n                        <div class=\"guest-type\">\n                            Children\n                        </div>\n                        <div class=\"guest-age\">\n                            Ages <span data-bind=\"text: Child2Min\"></span> to <span data-bind=\"text: Child2Max\"></span>\n                        </div>\n                    </div>\n\t\t\t\t    <div class=\"PaxPickerInputControls\">\n                        <div class=\"number-picker\">\n\t\t\t\t\t        <button class=\"l-fl l-pad number-picker-button minus\" data-bind=\"enable: Children2() > 0, click: DecrementChildren2, css: {disabled: Children2() == 0}\"></button>\n\t\t\t\t\t        <div class=\"l-fl l-pad number-picker-text\" data-bind=\"text: Children2\" style=\"width: 48px\"></div>\n\t\t\t\t\t        <button class=\"l-fl l-pad number-picker-button plus\" data-bind=\"enable: EnableChildrenIncrement, click: IncrementChildren2, css: {disabled: !EnableChildrenIncrement()}\"></button>\n    \t\t\t\t    </div>\n\t\t\t\t    </div>\n\t\t\t\t    <div class=\"PaxClear\"></div>\n\t\t\t    </div>\n\t\t\t    <div class=\"PaxPickerInputRow\" data-bind=\"visible: Child3Max() > 0 \">\n\t\t\t\t    <div class=\"PaxPickerInputText\">\n                        <div class=\"guest-type\">\n                            Children\n                        </div>\n                        <div class=\"guest-age\">\n                            Ages <span data-bind=\"text: Child3Min\"></span> to <span data-bind=\"text: Child3Max\"></span>\n                        </div>\n                    </div>\n\t\t\t\t    <div class=\"PaxPickerInputControls\">\n                        <div class=\"number-picker\">\n\t\t\t\t\t        <button class=\"l-fl l-pad number-picker-button minus\" data-bind=\"enable: Children3() > 0, click: DecrementChildren3, css: {disabled: Children3() == 0}\"></button>\n\t\t\t\t\t        <div class=\"l-fl l-pad number-picker-text\" data-bind=\"text: Children3\" style=\"width: 48px\"></div>\n\t\t\t\t\t        <button class=\"l-fl l-pad number-picker-button plus\" data-bind=\"enable: EnableChildrenIncrement, click: IncrementChildren3, css: {disabled: !EnableChildrenIncrement()}\"></button>\n    \t\t\t\t    </div>\n\t\t\t\t    </div>\n\t\t\t\t    <div class=\"PaxClear\"></div>\n\t\t\t    </div>\n                <div class=\"PaxPickerInputRow\">\n                    <a href=\"javascript::void()\" class=\"PaxPickerClose\" data-bind=\"click: ToggleShow\">Close</a>\n                </div>\n            </div>\n\t\t</div>\n\t</div>\n"});ko.components.register('drop-down',{viewModel:function(params){var self=this;self.Options=params.Options!=null?params.Options:ko.observableArray();self.SelectedOption=params.SelectedOption!=null?params.SelectedOption:ko.observable("");self.DefaultText=params.DefaultText!=null?params.DefaultText:"Please select an option";self.RS=function(){return(((1+Math.random())*0x10000)|0).toString(16).substring(1);};self.GUID=function(){return(self.RS()+self.RS()+"-"+self.RS()+"-4"+self.RS().substr(0,3)+"-"+self.RS()+"-"+self.RS()+self.RS()+self.RS()).toLowerCase();};self.DisplayString=ko.computed(function(){if(self.SelectedOption()==null||self.SelectedOption()===""){return self.DefaultText;}
var item=self.Options().find(function(i){return i.ItemKey===self.SelectedOption();});if(item!=null){return item.TextDisplay;}
return self.DefaultText;});self.ShowHighlight=function(data,event){event.target.className+=" DropDownHighlightItem";};self.HideHighlight=function(data,event){$(event.target).removeClass("DropDownHighlightItem");};self.SetSelectedOption=function(data,event){self.SelectedOption(data.ItemKey);event.target.style.backgroundColor="white";event.target.style.color="black";self.ShowInputs(false);};self.ContainerId=ko.observable(self.GUID());self.ShowInputs=ko.observable(false);self.ToggleShow=function(){self.ShowInputs(!self.ShowInputs());};$("body").on("click",function(e){if(e.target.id==self.ContainerId())
return;if($(e.target).closest("#"+self.ContainerId()).length)
return;if(self.ShowInputs()){self.ToggleShow();}});},template:"\n\t<div data-bind=\"attr: {'id': ContainerId }\" class=\"DropDownContainer\">\n\t\t<div data-bind=\"click: ToggleShow\" class=\"DropDownDisplay\">\n\t\t\t<div class=\"DropDownDisplayText\">\n\t\t\t\t\t<span data-bind=\"text: DisplayString\"></span>\n\t\t\t</div>\n\t\t\t<div class=\"DropDownDisplaySymbol icon-down-open\"></div>\n\t\t\t<div class=\"DropDownClear\"></div>\n\t\t</div>\n\t\t<div style=\"display: none\" data-bind=\"visible: ShowInputs\" class=\"DropDownList\">\n\t\t\t<div data-bind=\"foreach: Options\" class=\"DropDownListItem\">\n\t\t\t\t<div data-bind=\"\n\t\t\t\t\tattr: {'data-key': $data.ItemKey}, \n\t\t\t\t\ttext: $data.TextDisplay, \n\t\t\t\t\tevent: {mouseover: $parents[0].ShowHighlight, mouseout: $parents[0].HideHighlight}, \n\t\t\t\t\tclick: $parents[0].SetSelectedOption,\n\t\t\t\t\tcss: {DropDownSelectedItem: $data.ItemKey == $parents[0].SelectedOption()}\" class=\"DropDownListItemText\"></div>\n\t\t\t</div>\n\t\t</div>\n\t</div>\n"});var DropDownOption=(function(){function DropDownOption(itemKey,textDisplay,initialSelection){if(initialSelection===void 0){initialSelection="";}
var self=this;self.ItemKey=itemKey;self.TextDisplay=textDisplay;self.InitialSelection=initialSelection;}
return DropDownOption;}());var Modalise=(function(){function Modalise(modalContainer,modalhead,modalContentContainer,modalsubject){if(modalContainer===void 0){modalContainer=".modalcontainer";}
if(modalhead===void 0){modalhead=".modalhead";}
if(modalContentContainer===void 0){modalContentContainer=".modalcontentcontainer";}
if(modalsubject===void 0){modalsubject=".modalsubject";}
this.modalcontainer=document.querySelector(modalContainer);this.modalheader=document.querySelector(modalhead);this.modalcontentcontainer=document.querySelector(modalContentContainer);this.modalsubjectcontainer=document.querySelector(modalsubject);var modal=this;this.modalheader.addEventListener("click",function(eve){return modal.close();});this.isOpen=false;this.isModalOpen=ko.observable(this.isOpen);}
Modalise.prototype.modal=function(targetSelector,headerSubject,onClose,containerClass){if(headerSubject===void 0){headerSubject="";}
if(onClose===void 0){onClose=null;}
if(containerClass===void 0){containerClass="";}
try{var target=document.querySelector(targetSelector);var parent_1=null;if(target&&target.parentElement){if(this.modalcontentcontainer.firstChild){this.returnCurrentModalTargetToInitialPosition();}
if(onClose){this.modalCloseEvent=onClose;}
parent_1=target.parentElement;Utility.AddClass(parent_1,"modal-parent-return");Utility.AddClass(this.modalcontainer,"modalise "+containerClass);var contextTargetPlaceHolder=document.createElement('div');var contextPlaceHolderId="modal-targetPlaceHolder_"+targetSelector.replace("#","_").replace(".","");target.setAttribute("data-modal-targetSelector",contextPlaceHolderId);Utility.AddClass(contextTargetPlaceHolder,contextPlaceHolderId);target=parent_1.replaceChild(contextTargetPlaceHolder,target);this.modalsubjectcontainer.innerHTML=headerSubject;this.modalcontainer.style.display="block";this.modalcontentcontainer.appendChild(target);Utility.AddClass(document.body,"noscroll");this.isOpen=true;this.isModalOpen(this.isOpen);return this;}}
catch(exception){}};Modalise.prototype.close=function(){try{if(this.modalcontentcontainer.firstChild){this.returnCurrentModalTargetToInitialPosition();}
this.modalcontainer.style.display="none";Utility.RemoveClass(this.modalcontainer,"modalise");Utility.RemoveClass(document.body,"noscroll");if(this.modalCloseEvent){this.modalCloseEvent();}
this.isOpen=false;this.isModalOpen(this.isOpen);}
catch(exception){}};Modalise.prototype.returnCurrentModalTargetToInitialPosition=function(){try{var target=this.modalcontentcontainer.firstChild;var parent_2=document.querySelector(".modal-parent-return");var contextPlaceHolderId="."+target.attributes["data-modal-targetSelector"].value;var contextTargetPlaceHolder=parent_2.querySelector(contextPlaceHolderId);if(contextTargetPlaceHolder!==null){parent_2.replaceChild(target,contextTargetPlaceHolder);Utility.RemoveClass(parent_2,"modal-parent-return");}}
catch(exception){}};return Modalise;}());var __extends=(this&&this.__extends)||(function(){var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||({__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b;})||function(d,b){for(var p in b)if(b.hasOwnProperty(p))d[p]=b[p];};return extendStatics(d,b);};return function(d,b){extendStatics(d,b);function __(){this.constructor=d;}
d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __());};})();var RoomFeature=(function(){function RoomFeature(name,iconClass){if(iconClass===void 0){iconClass="";}
this.name=name;this.iconClass=iconClass;}
return RoomFeature;}());var FeatureToggle=(function(){function FeatureToggle(options){if(options===void 0){options=null;}
this.ShowRoomCtas=false;this.HideUnavailableRoomsByDefault=false;this.ScrollOpenCheckinOnlyWhenNotIsInViewPort=false;this.ShouldToastPostRoomAdd=false;this.RaqOpenStyle=ko.observable("inline");var featureToggle=this;if(options&&options.RaqOpenStyle){this.RaqOpenStyle=ko.observable(options.RaqOpenStyle);}
this.IsRaqInline=ko.computed(function(){return featureToggle.RaqOpenStyle()==="inline";});this.IsRaqModal=ko.computed(function(){return featureToggle.RaqOpenStyle()==="modal";});this.IsRaqLinkedPage=ko.computed(function(){return featureToggle.RaqOpenStyle()==="linked";});if(options&&options.ShowRoomCtas){this.ShowRoomCtas=options.ShowRoomCtas;}
if(options&&options.HideUnavailableRoomsByDefault){this.ShowRoomCtas=options.HideUnavailableRoomsByDefault;}}
return FeatureToggle;}());var Quote=(function(){function Quote(){var _this=this;this.checkin=ko.observable();this.checkout=ko.observable();this.customerContactId=ko.observable();this.firstname=ko.observable();this.lastname=ko.observable();this.email=ko.observable();this.areacode=ko.observable();this.phoneNumber=ko.observable();this.message=ko.observable();this.validationEnabled=ko.observable(false);this.showErrorCorrectionMessage=ko.observable(false);this.isCorporate=ko.observable(false);this.corporateRequestId=ko.observable();this.corporateGuestName=ko.observable();this.corporateAdults=ko.observable();this.enquireRoomSelection=ko.observable("enquireSpecificRoom");this.addValidationRules();this.checkForCorporateRequestId();this.checkinFormatted=ko.computed(function(){var d=moment(this.checkin(),["DD MMM YYYY"]);if(d.isValid()){return d.format("DD MMM YYYY");}
else
return "";},this);this.checkoutFormatted=ko.computed(function(){var d=moment(this.checkout(),["DD MMM YYYY"]);if(d.isValid()){return d.format("DD MMM YYYY");}
else
return "";},this);if($('.countrychoice').length){var countryCodes=jQuery.parseJSON($("#CountryCodesAsJson").val());this.countryCodeControl=new Choices('.countrychoice',{searchEnabled:true,itemSelectText:'',choices:countryCodes,searchResultLimit:30,shouldSort:true,sortFilter:function(a,b){var labelA=(a.label||a.value).toLowerCase();var labelB=(b.label||b.value).toLowerCase();return labelA.localeCompare(labelB,undefined,{numeric:true,sensitivity:'base'});},fuseOptions:{shouldSort:false,},});this.areacode($(".countrychoice").val());$(".countrychoice").on("change",function(){_this.areacode($(".countrychoice").val());});}
if($('#initQuoteModel').length){var iqm=JSON.parse($('#initQuoteModel').val());if(iqm){if(iqm.Email&&iqm.Email.length>0){this.firstname(iqm.FirstName);this.lastname(iqm.LastName);this.email(iqm.Email);if(iqm.PhoneNumber&&iqm.PhoneNumber.length>0){this.setPhoneNumber(iqm.PhoneNumber);}}}}}
Quote.prototype.checkForCorporateRequestId=function(){var requestId=getParameterByName("r");if(requestId!=null&&requestId!=""){this.corporateRequestId(Number(requestId));}};Quote.prototype.setPhoneNumber=function(newValue){if(newValue.length>4&&newValue.substr(0,2)==="00"){var areacode=newValue.substr(0,4);areacode=areacode.replace("00","");this.areacode(areacode);this.countryCodeControl.setValueByChoice(areacode);this.phoneNumber(newValue.substr(4));}
else{this.areacode("27");this.countryCodeControl.setValueByChoice("27");this.phoneNumber(newValue);}};Quote.prototype.addValidationRules=function(){var quote=this;this.firstname.extend({required:{onlyIf:function(){return quote.validationEnabled();}},minLength:{params:2,onlyIf:function(){return quote.validationEnabled();}}});this.lastname.extend({required:{onlyIf:function(){return quote.validationEnabled();}},minLength:{params:2,onlyIf:function(){return quote.validationEnabled();}}});this.phoneNumber.extend({required:{onlyIf:function(){return quote.validationEnabled()&&!quote.isCorporate();}},minLength:{params:7,onlyIf:function(){return quote.validationEnabled()&&!quote.isCorporate();},message:"Invalid phone number"},number:{onlyIf:function(){return quote.validationEnabled()&&!quote.isCorporate();},message:"Invalid phone number"},maxLength:{params:10,onlyIf:function(){return quote.validationEnabled()&&!quote.isCorporate();},message:"Invalid phone number"}});this.areacode.extend({required:{onlyIf:function(){return quote.validationEnabled()&&!quote.isCorporate();}},minLength:{params:1,onlyIf:function(){return quote.validationEnabled()&&!quote.isCorporate();}},maxLength:{params:4,onlyIf:function(){return quote.validationEnabled()&&!quote.isCorporate();}}});this.email.extend({required:{onlyIf:function(){return quote.validationEnabled();}},email:{onlyIf:function(){return quote.validationEnabled();},message:"Please enter a valid email address"}});quote.errors=ko.validation.group(this);};Quote.prototype.toggleValidation=function(enabled){this.validationEnabled(enabled);};return Quote;}());var RoomType=(function(){function RoomType(root,id,name,nights,currencySymbol){var _this=this;if(currencySymbol===void 0){currencySymbol="R";}
var datacontext=this;datacontext.est=root;datacontext.roomId=id;datacontext.roomName=name;datacontext.roomsSelected=ko.observableArray();datacontext.description="";datacontext.shortDescription="";datacontext.rateBasis="";datacontext.hasAvailability=ko.observable(false);datacontext.initialLeadPriceRate=ko.observable();datacontext.leadPriceRate=ko.observable();datacontext.leadPrice=ko.observable("");datacontext.leadPriceDescription=ko.observable("");datacontext.nights=nights;datacontext.roomTypeAllocationPrice=ko.computed(function(){var totalForAllRooms=0;for(var _i=0,_a=datacontext.roomsSelected();_i<_a.length;_i++){var r=_a[_i];if(r.total()!=null&&r.total().special!=null){totalForAllRooms+=r.total().special.amount.value;}
else{if(r.total().value!=undefined){totalForAllRooms+=r.total().value;}}
currencySymbol=r.total().currencySymbol;}
if(totalForAllRooms===0){return "...";}
return ""+currencySymbol+totalForAllRooms.toFixed(2);});datacontext.roomTypeAllocationStandardPrice=ko.computed(function(){var totalForAllRooms=0;for(var _i=0,_a=datacontext.roomsSelected();_i<_a.length;_i++){var r=_a[_i];if(r.total()!=null&&r.total().value!=undefined){totalForAllRooms+=r.total().value;}
currencySymbol=r.total().currencySymbol;}
if(totalForAllRooms>0){return ""+currencySymbol+totalForAllRooms.toFixed(2);}
else{return "";}});datacontext.showFullDescription=ko.observable(false);datacontext.facilities=ko.observableArray();datacontext.qty=ko.observable(0);datacontext.qtySelected=ko.observable(0);datacontext.sleeps=ko.observable(0);datacontext.image=ko.observable("");datacontext.images=ko.observableArray();datacontext.hasImage=ko.computed(function(){return datacontext.images().length>0&&(datacontext.image()!==null&&datacontext.images().length>0&&datacontext.image().indexOf("no-image-logo.png")<=0);});datacontext.hasNoImage=ko.computed(function(){return!datacontext.hasImage();});datacontext.features=ko.observableArray();datacontext.featuresAsString=ko.observable("");datacontext.mealPlanOptions=ko.observableArray();datacontext.maxAdults=ko.observable(0);datacontext.minAdults=ko.observable(1);datacontext.maxPax=ko.observable(0);datacontext.maxChildren=ko.observable(0);datacontext.child1Min=ko.observable(0);datacontext.child1Max=ko.observable(0);datacontext.child2Min=ko.observable(0);datacontext.child2Max=ko.observable(0);datacontext.child3Min=ko.observable(0);datacontext.child3Max=ko.observable(0);datacontext.hasSpecial=ko.computed(function(){var roomsWithSpecial=0;for(var _i=0,_a=datacontext.roomsSelected();_i<_a.length;_i++){var r=_a[_i];if(r.hasSpecial()){roomsWithSpecial++;}}
return roomsWithSpecial>0;}.bind(this));datacontext.defaultRoom=new Room(datacontext);datacontext.selectedRoomCount=ko.computed(function(){if(this.roomsSelected!=null&&this.roomsSelected().length>0){return this.roomsSelected().length;}
return 0;}.bind(this));datacontext.totalPricePax=ko.computed(function(){var nights=_this.nights();var nightsdescription="";var adultsDefault=", 2 Adults";if(_this.defaultRoom.adults()<=1){adultsDefault=", 1 Adult";}
if(nights==null||nights==0){return "1 room"+adultsDefault+", 1 night";}
if(nights>1){nightsdescription=", for "+nights+" nights";}
if(nights===1){nightsdescription=", for 1 night";}
if(_this.roomsSelected().length===0){return "1 room"+adultsDefault+nightsdescription;}
var totalRoomsSelected=_this.roomsSelected().length;var totalAdults=0;var totalKids=0;for(var _i=0,_a=_this.roomsSelected();_i<_a.length;_i++){var r=_a[_i];totalAdults+=r.adults();totalKids+=r.childBand1()+r.childBand2()+r.childBand3();}
var room=totalRoomsSelected>0?totalRoomsSelected>1?"rooms":"room":"";var kids=totalKids>0?(totalKids>1?", "+totalKids+" Children":", "+totalKids+" Child"):"";var adults=totalAdults>0?(totalAdults>1?", "+totalAdults+" Adults":", 1 Adult"):"";var leadPricePax=totalRoomsSelected+" "+room+adults+kids+nightsdescription;return leadPricePax;},this);datacontext.qtyOptions=ko.computed(function(){var myOptions=[];for(var idx=0;idx<=_this.qty();idx++){myOptions.push(idx);}
return myOptions;},this);datacontext.qtySelected.subscribe(function(newValue){sn.app.esthomepagev3.ViewModel.log(this.roomName+" num rooms selected: "+newValue);while(this.selectedRoomCount()<newValue){this.est.addRoom(new Room(datacontext));}
while(this.selectedRoomCount()>newValue){this.est.removeLastRoomOfType(datacontext.roomId);}}.bind(this));datacontext.show=ko.observable(true);datacontext.canAddRoom=ko.observable(true);}
RoomType.prototype.openRoomGallery=function(roomType){if(!roomType.hasImage()){return;}
roomType.est.gallery.galleryImages=roomType.images();roomType.est.gallery.init();roomType.est.gallery.onClose=function(){roomType.est.gallery.galleryImages=roomType.est.estGallerySource;roomType.est.gallery.init();};roomType.est.gallery.onOpenClick(0);};RoomType.prototype.toggleDescription=function(){this.est.viewRoomContent(this);var roomType=this;roomType.est.modal.modal(".roomContentContainer","Room information",function(){roomType.est.shouldShowRoomContent(false);},"roomContentContainerModal");roomType.est.shouldShowRoomContent(true);};RoomType.prototype.getType=function(){return "RoomType";};return RoomType;}());var Room=(function(){function Room(type,adults,child1,child2,child3,index,mealPlanOptions,mealPlan){var _this=this;if(adults===void 0){adults=2;}
if(child1===void 0){child1=0;}
if(child2===void 0){child2=0;}
if(child3===void 0){child3=0;}
if(index===void 0){index=0;}
if(mealPlanOptions===void 0){mealPlanOptions=ko.observableArray();}
if(mealPlan===void 0){mealPlan="";}
var self=this;self.guid=ko.observable(Util.guid());self.roomType=type;self.roomIndex=index;self.adults=ko.observable(adults);self.childrenList=ko.observableArray([]);self.childAges=ko.observableArray();self.childBand1=ko.observable(child1);self.childBand2=ko.observable(child2);self.childBand3=ko.observable(child3);self.kids=ko.computed(function(){return self.childBand1()+self.childBand2()+self.childBand3();});self.total=ko.observable(new Rate(0,"R"));self.special=ko.observable();self.paxSummary=ko.computed(function(){var kpax=self.kids()>0?(self.kids()>1?", "+self.kids()+" Children":", 1 Child"):"";var kadults=self.adults()>0?(self.adults()>1?self.adults()+" Adults":"1 Adult"):"";var pax=""+kadults+kpax;return pax;});if(mealPlan===""){mealPlan=type.defaultMealPlan;}
self.mealPlan=ko.observable(mealPlan);if(type.mealPlanOptions().length>0){var key=type.mealPlanOptions()[0].ItemKey;self.mealPlan(key);}
self.hasSpecial=ko.computed(function(){return this.special!=null&&this.special()!=null&&this.special().specialId>0;}.bind(this));self.childAges.subscribe(function(c1){sn.app.esthomepagev3.ViewModel.log(this.roomType.roomName+", pax change: child age "+c1);}.bind(this));self.childBand1.subscribe(function(c1){sn.app.esthomepagev3.ViewModel.log(this.roomType.roomName+", pax change: childBand1 "+c1);}.bind(this));self.childBand2.subscribe(function(c2){sn.app.esthomepagev3.ViewModel.log(this.roomType.roomName+", pax change: childBand2 "+c2);}.bind(this));self.childBand3.subscribe(function(c3){sn.app.esthomepagev3.ViewModel.log(this.roomType.roomName+", pax change: childBand3 "+c3);}.bind(this));self.mealPlan.subscribe(function(mp){sn.app.esthomepagev3.ViewModel.log(this.roomType.roomName+", pax change: mealPlan "+mp);}.bind(this));this.adultOptions=ko.computed(function(){var myOptions=[];for(var idx=0;idx<=_this.roomType.maxAdults()&&idx<=(_this.roomType.maxPax()-_this.kids());idx++){myOptions.push(idx);}
return myOptions;},this);this.child1Options=ko.computed(function(){var myOptions=[];for(var idx=0;idx<=_this.roomType.maxChildren()&&idx<=(_this.roomType.maxPax()-_this.adults()-_this.childBand2()-_this.childBand3());idx++){myOptions.push(idx);}
return myOptions;},this);this.child2Options=ko.computed(function(){var myOptions=[];for(var idx=0;idx<=_this.roomType.maxChildren()&&idx<=(_this.roomType.maxPax()-_this.adults()-_this.childBand1()-_this.childBand3());idx++){myOptions.push(idx);}
return myOptions;},this);this.child3Options=ko.computed(function(){var myOptions=[];for(var idx=0;idx<=_this.roomType.maxChildren()&&idx<=(_this.roomType.maxPax()-_this.adults()-_this.childBand1()-_this.childBand2());idx++){myOptions.push(idx);}
return myOptions;},this);};return Room;}());var TotalRatesResult=(function(){function TotalRatesResult(deposit,total,totalExclExtras,nightlyRateExclExtras){this.Deposit=deposit;this.Total=total;this.TotalExclExtras=totalExclExtras;this.NightlyRateExclExtras=nightlyRateExclExtras;}
return TotalRatesResult;}());var RoomKidFilter=(function(){function RoomKidFilter(){this.Age=ko.observable();}
return RoomKidFilter;}());var RoomFilter=(function(){function RoomFilter(parent,minAdults,maxAdults,maxKids){var _this=this;if(minAdults===void 0){minAdults=1;}
if(maxAdults===void 0){maxAdults=20;}
if(maxKids===void 0){maxKids=18;}
this.Parent=parent;this.MinAdults=minAdults;this.MaxAdults=maxAdults;this.MaxKids=maxKids;this.AdultsQuantity=[];for(var i_1=this.MinAdults;i_1<this.MaxAdults;i_1++){this.AdultsQuantity.push(i_1);}
this.KidsQuantity=[];for(var i_2=0;i_2<this.MaxKids;i_2++){this.KidsQuantity.push(i_2);}
this.Adults=ko.observable(2);this.Kids=ko.observableArray([]);this.KidsAges=ko.computed(function(){var kidsages=[];for(var i=0;i<_this.Kids().length;i++){kidsages.push(_this.Kids()[i].Age);}
return kidsages;});}
RoomFilter.prototype.AddAdult=function(){if(this.Adults()<=this.MaxAdults){this.Adults(this.Adults()+1);this.Parent.Summary.notifySubscribers();}};RoomFilter.prototype.RemoveAdult=function(){if(this.Adults()>1){this.Adults(this.Adults()-1);this.Parent.Summary.notifySubscribers();}};RoomFilter.prototype.AddKid=function(){this.Kids.push(new RoomKidFilter());this.KidsAges.notifySubscribers();this.Parent.Summary.notifySubscribers();};RoomFilter.prototype.RemoveKid=function(){this.Kids.pop();this.KidsAges.notifySubscribers();this.Parent.Summary.notifySubscribers();};RoomFilter.prototype.KidsQtyChanged=function(val,eve){};return RoomFilter;}());var RoomFilterModel=(function(){function RoomFilterModel(){var self=this;self.Rooms=ko.observableArray([new RoomFilter(self)]);self.TotalRoomsRequested=ko.observable();self.TotalAdultsRequested=ko.observable();self.TotalKidsRequested=ko.observable();self.TotalKidsAgesRequested=ko.observableArray([]);this.Summary=ko.computed(function(){var rooms=self.Rooms();var s="";var totalAdults=0;var totalKids=0;self.TotalKidsAgesRequested([]);for(var i=0;i<rooms.length;i++){totalAdults+=rooms[i].Adults();totalKids+=rooms[i].Kids().length;for(var k=0;k<rooms[i].Kids().length;k++){var kidsInRoom=rooms[i].Kids()[k];self.TotalKidsAgesRequested.push(kidsInRoom.Age());}}
s=rooms.length==1?rooms.length+" Room":(rooms.length>=2?rooms.length+" Rooms":"");s+=totalAdults==1?", "+totalAdults+" Adult":(totalAdults>=2?", "+totalAdults+" Adults":"");s+=totalKids==1?", "+totalKids+" Child":(totalKids>=2?", "+totalKids+" Kids":"");self.TotalRoomsRequested(rooms.length);self.TotalAdultsRequested(totalAdults);self.TotalKidsRequested(totalKids);return s;},this);}
RoomFilterModel.prototype.RemoveRoom=function(theFilter,theRoom){if(theFilter.Rooms().length>1){theFilter.Rooms.remove(theRoom);theFilter.Summary.notifySubscribers();}};RoomFilterModel.prototype.AddRoom=function(vm){if(vm.globalRoomsFilter.Rooms().length<30){vm.globalRoomsFilter.Rooms.push(new RoomFilter(vm.globalRoomsFilter));vm.globalRoomsFilter.Summary.notifySubscribers();}};return RoomFilterModel;}());var Establishment=(function(_super){__extends(Establishment,_super);function Establishment(spidParam,featureToggles){if(featureToggles===void 0){featureToggles=null;}
var _this=_super.call(this)||this;_this.inlineRaqEnabled=true;_this.addRoomPromptCount=0;_this.allocationPriceCache={};_this.totalsPriceCache={};_this.cacheMinsToLive=8;var vm=_this;_this.modal=new Modalise();_this.featureToggle=new FeatureToggle(featureToggles);_this.isLive=ko.observable(false);_this.showRoomsList=ko.observable(false);_this.loading=ko.observable(true);_this.shouldModaliseBookingCard=ko.observable(false);_this.notBookable=ko.observable(false);_this.spid=ko.observable(spidParam);_this.roomTypeList=ko.observableArray();_this.checkin=ko.observable();_this.checkout=ko.observable();_this.nights=ko.observable();_this.establishmentType=ko.observable("");_this.raqOldRoute=ko.observable(false);_this.raqUrl=ko.observable("");_this.requestingQuoteStarted=0;_this.showMobileExtras=ko.observable(true);_this.isRaqOnly=ko.observable(false);_this.preSpecialTotal=0;_this.appliedRoomSelectionFromUrl=false;_this.viewRoomContent=ko.observable(null);_this.shouldShowRoomContent=ko.observable(false);_this.globalRoomsFilter=new RoomFilterModel();_this.selectedRoomQtyGlobalFilter=ko.observable(1);_this.selectedAdultsGlobalFilter=ko.observable(2);if(Utility.getUrlParam('pax')){var paxAdults=parseInt(Utility.getUrlParam('pax'));var r=_this.globalRoomsFilter.Rooms()[0];r.Adults(paxAdults);_this.selectedAdultsGlobalFilter(paxAdults);}
_this.selectedKidsGlobalFilter=ko.observable(0);_this.roomCount=ko.computed(function(){var count=1;if(_this.roomTypeList==null){count=10;}
else{if(_this.roomTypeList().length<=0){count=10;}
var totalUnits=0;for(var _i=0,_a=_this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];totalUnits+=rt.qty();}
if(totalUnits<=0||_this.roomTypeList().length>1){count=10;}
else{count=totalUnits;}}
if(count>20)
count=20;var roomCounter=Array(count);for(var i=0;i<roomCounter.length;i++){roomCounter[i]=i+1;}
return roomCounter;},_this);_this.maxAdultsGlobalFilter=ko.computed(function(){var count=15;var counter=Array(count);for(var i=0;i<counter.length;i++){counter[i]=i;}
return counter;},_this);_this.maxKidsGlobalFilter=ko.computed(function(){var count=10;var counter=Array(count);for(var i=0;i<counter.length;i++){counter[i]=i;}
return counter;},_this);_this.roomPaxFilterDisplay=ko.computed(function(){var result="1 Room, 2 Adults, 2 Kids";return result;},_this);_this.showGlobalPaxInput=ko.observable(false);_this.loadServerContext();_this.depositPercentage=ko.observable();_this.depositAllInRate=ko.observable();_this.totalAllInRate=ko.observable();_this.totalRateExclExtras=ko.observable();_this.nightlyRateExclExtras=ko.observable();_this.extraCharges=ko.observable();_this.hasExtraCharges=ko.observable(false);_this.totalAllInSpecial=ko.observable();_this.totalExtras=ko.observable(new Rate(0,'R'));_this.showCorporate=ko.observable(true);_this.roomsListText=ko.observable("Rooms");_this.selectedDateRangeText=ko.observable("");_this.roomsListHelp=ko.observable(false);_this.enableRoomSelection=ko.observable(true);_this.showBookingSummaryLink=ko.observable(false);_this.isMultiRoomSelectionEnabled=ko.observable(true);_this.showDeposit=ko.computed(function(){if(_this.depositAllInRate()!=null&&_this.depositAllInRate().value==0){return false;}
if(_this.totalAllInRate()!=null&&_this.depositAllInRate()!=null){if(_this.depositAllInRate().value<_this.totalAllInRate().value){return true;}}
return false;},_this);_this.toggleRoomVisibilityText=ko.observable("Show unavailable rooms");_this.showingAllRooms=ko.observable(true);_this.addRoomPromptCount=0;_this.totalSummary=ko.computed(function(){if(_this.totalAllInRate()==null||_this.totalAllInRate().value===0){return "";}
var specialclass="";var originalAmount="";if(_this.totalAllInSpecial()!=null&&_this.totalAllInSpecial().originalAmount!=null&&_this.totalAllInSpecial().originalAmount.value>0){specialclass="special-price discount-text";originalAmount="<span class='linethrough'> "+_this.totalAllInRate().currencySymbol+(_this.preSpecialTotal+_this.totalExtras().value)+"</span>";}
var r="<div><div class=\"totp white fi l-pad-tb\">Total Price</div> "+originalAmount+"<span data-totalSummary class=\"payment-amount "+specialclass+"\">"+_this.totalAllInRate().displayValue+"</span></div>";return r;},_this);_this.totalSummaryExclExtras=ko.computed(function(){if(_this.totalRateExclExtras()==null||_this.totalRateExclExtras().value===0){return "";}
var r="<div>"+_this.totalRateExclExtras().displayValue+"</span></div>";return r;},_this);_this.nightlyPriceExclExtras=ko.computed(function(){if(_this.nightlyRateExclExtras()==null||_this.nightlyRateExclExtras().value===0){return "";}
return ""+_this.nightlyRateExclExtras().displayValue;},_this);_this.totalDeposit=ko.computed(function(){if(_this.depositAllInRate()==null||_this.depositAllInRate().value===0){return "";}
var r="<span data-depositsummary class=\"payment-amount\">"+_this.depositAllInRate().displayValue+"</span>";_this.deposit=ko.observable(_this.depositAllInRate().value);return r;},_this);_this.hasDates=ko.observable(false);_this.hasSelectedRooms=ko.computed(function(){var hasSelectedRooms=false;for(var _i=0,_a=_this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];hasSelectedRooms=rt.roomsSelected().length>0;if(hasSelectedRooms){return hasSelectedRooms;}}
return hasSelectedRooms;});_this.hasAvailableRooms=ko.computed(function(){var roomsAvailableCount=0;for(var _i=0,_a=_this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];roomsAvailableCount=roomsAvailableCount+rt.qty();}
return roomsAvailableCount>0;},_this);_this.hasUnavailableRooms=ko.computed(function(){for(var _i=0,_a=_this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];if(rt.qty()==0){return true;}}
return false;},_this);_this.showRoomLeadPriceSummary=ko.computed(function(){return false;},_this);_this.roomLeadPriceCheapestRoomDescription=ko.computed(function(){var cheapestRoomType=_this.getCheapestRoomType();if(cheapestRoomType!=null){return cheapestRoomType.roomName;}
return "";},_this);_this.roomLeadPriceCheapestRoomRate=ko.computed(function(){var cheapestRoomType=_this.getCheapestRoomType();if(cheapestRoomType!=null){var nights=_this.nights();if(cheapestRoomType.leadPriceRate().special){return cheapestRoomType.leadPriceRate().currencySymbol+(Math.ceil(cheapestRoomType.leadPriceRate().special.amount.value/nights)).toString();}
return cheapestRoomType.leadPriceRate().currencySymbol+(Math.ceil(cheapestRoomType.leadPriceRate().value/nights)).toString();}
return "";},_this);_this.roomLeadPriceCheapestRoomRateHasSpecial=ko.computed(function(){var cheapestRoomType=_this.getCheapestRoomType();if(cheapestRoomType&&cheapestRoomType.leadPriceRate().special){return true;}
return false;},_this);_this.getApplicableSpecialAmount=ko.computed(function(){var cheapestRoomType=_this.getCheapestRoomType();if(cheapestRoomType&&cheapestRoomType.leadPriceRate().special){var discountPrice=cheapestRoomType.leadPriceRate().special.amount.value;var originalPrice=cheapestRoomType.leadPriceRate().special.originalAmount.value;var difference=originalPrice-discountPrice;return Math.floor((difference/originalPrice)*100)+"% OFF";}
return "";},_this);_this.roomLeadPriceCheapestRoomRatePreSpecial=ko.computed(function(){var cheapestRoomType=_this.getCheapestRoomType();if(cheapestRoomType&&cheapestRoomType.leadPriceRate().special){var nights=_this.nights();return cheapestRoomType.leadPriceRate().currencySymbol+((cheapestRoomType.leadPriceRate().value/nights)).toFixed(2).toString();}
return "";},_this);_this.roomLeadPriceOtherRooms=ko.computed(function(){var availableRoomCount=0;for(var _i=0,_a=_this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];if(rt.qty()>0){availableRoomCount=availableRoomCount+1;}}
if(availableRoomCount-1>=2){return availableRoomCount-1+" other rooms";}
else if(availableRoomCount-1===1){return "1 other room from...";}
return "";},_this);_this.roomLeadPriceOtherRoomsRate=ko.computed(function(){var unsorted=[];for(var _i=0,_a=_this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];if(rt.qty()>0){unsorted.push(rt);}}
unsorted.sort(function(left,right){return left.leadPriceRate().value-right.leadPriceRate().value;});if(unsorted.length>=2){unsorted.shift();for(var _b=0,unsorted_1=unsorted;_b<unsorted_1.length;_b++){var rt=unsorted_1[_b];if(rt.qty()>0){return rt.leadPrice();}}}
return "";},_this);_this.hasOtherAvailableRooms=ko.computed(function(){return _this.roomLeadPriceOtherRooms().length>0;},_this);_this.nightString=ko.computed(function(){if(_this.nights()===0){return "";}
if(_this.nights()===1){return _this.nights()+" night";}
else if(_this.nights()>=2){return _this.nights()+" nights";}
else{return "";}},_this);_this.preCallToAction=ko.computed(function(){if(!_this.hasDates()){return new Step(1,"Submit",ko.observable(false),_this.showBookNowModal);}
if(_this.hasDates()&&!_this.hasSelectedRooms()){return new Step(2,"Submit",ko.observable(false),_this.showBookNowModal);}
if(!_this.hasSelectedRooms()){return new Step(3,"Submit",ko.observable(false),_this.promptRoomChoice);}
if(_this.selectedCallToAction()===0){return new Step(4,"Submit",ko.observable(false),_this.raq);}
if(_this.selectedCallToAction()===1){return new Step(4,"Pay",ko.observable(false),_this.pay);}
return new Step(4,"Unknown",ko.observable(false),null);},_this);_this.selectedCallToAction=ko.observable(-1);_this.bookingSummaryDescription=ko.computed(function(){var nights=_this.nights();var nightsdescription="";var adultsDefault="2 Adults";if($(".checkin").length===0){return "Enter dates";}
var fromDate=moment($($(".checkin")[0]).val(),["DD MMM YYYY","DD MMMM YYYY"]).format("D MMM");var toDate=moment($($(".checkout")[0]).val(),["DD MMM YYYY","DD MMMM YYYY"]).format("D MMM");var checkin=moment($($(".checkin")[0]).val(),["DD MMM YYYY","DD MMMM YYYY"]);var checkout=moment($($(".checkout")[0]).val(),["DD MMM YYYY","DD MMMM YYYY"]);if(checkin.isValid()&&checkout.isValid()){nights=checkout.diff(checkin,'days');if(nights>1){nightsdescription=" for "+nights+" nights";}
if(nights===1){nightsdescription=" for 1 night";}}
var totalRoomsSelected=0;var totalAdults=0;var totalKids=0;for(var _i=0,_a=_this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];for(var _b=0,_c=rt.roomsSelected();_b<_c.length;_b++){var r=_c[_b];totalRoomsSelected++;totalAdults+=r.adults();totalKids+=r.childBand1()+r.childBand2()+r.childBand3();}}
if(totalRoomsSelected===0){return "Select rooms";}
var room=totalRoomsSelected>0?totalRoomsSelected>1?"rooms":"room":"";if(_this.isSingleUnit()){room=totalRoomsSelected>0?totalRoomsSelected>1?"unit":"unit":"";}
var kids=totalKids>0?(totalKids>1?", "+totalKids+" Children":", "+totalKids+" Child"):"";var adults=totalAdults>0?(totalAdults>1?totalAdults+" Adults":"1 Adult"):"";var roomsText=totalRoomsSelected+" "+room;if(_this.isSingleUnit()){roomsText="Entire property";}
var leadPricePax=fromDate+" - "+toDate+", "+roomsText+", "+adults+kids;return leadPricePax;},_this);_this.bookingSummaryPax=ko.computed(function(){var adultsDefault="2 Adults";var totalAdults=0;var totalKids=0;for(var _i=0,_a=_this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];for(var _b=0,_c=rt.roomsSelected();_b<_c.length;_b++){var r=_c[_b];totalAdults+=r.adults();totalKids+=r.childBand1()+r.childBand2()+r.childBand3();}}
var kids=totalKids>0?(totalKids>1?", "+totalKids+" Children":", "+totalKids+" Child"):"";var adults=totalAdults>0?(totalAdults>1?totalAdults+" Adults":"1 Adult"):"";var retVal=""+adults+kids;return retVal;},_this);_this.nights.subscribe(function(){_this.nightString.notifySubscribers();_this.bookingSummaryDescription.notifySubscribers();});_this.canShowRaq=ko.observable(false);_this.canShowInlineRaq=ko.observable(false);_this.shouldShowRAQBookingButton=ko.computed(function(){return this.establishmentType().toLowerCase().indexOf('realtime')!==-1;},_this);_this.isRaq=ko.observable(false);_this.establishmentType.subscribe(function(){var raqAlso=_this.establishmentType().toLowerCase().indexOf('raq')>-1;_this.isRaq(raqAlso);});_this.enquireLink=ko.observable(false);_this.canBookNow=ko.computed(function(){var isRaq=false;if(vm.isRaqOnly!=null)
isRaq=vm.isRaqOnly()===true;return!isRaq&&!vm.quote().isCorporate();},_this);_this.isFlexiQuote=ko.observable(false);_this.canShowBookModal=ko.observable(false);_this.setupCacheExpiry();_this.roomTypeList.subscribe(function(){_this.showingAllRooms(true);if(_this.featureToggle.HideUnavailableRoomsByDefault){_this.toggleRoomVisibility();}});_this.shouldShowModalStickyFooter=ko.observable(false);_this.loading(false);return _this;}
Establishment.prototype.getType=function(){return "Establishment";};Establishment.prototype.getCheapestRoomType=function(){var cheapestRoomType;for(var _i=0,_a=this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];if(rt.qty()>0){if(cheapestRoomType==null){cheapestRoomType=rt;}
else if(rt.leadPriceRate().value<cheapestRoomType.leadPriceRate().value){cheapestRoomType=rt;}}}
return cheapestRoomType;};Establishment.prototype.isSingleUnit=function(){return false;};;Establishment.prototype.toggleMobileExtras=function(){this.showMobileExtras(!this.showMobileExtras());};Establishment.prototype.sortRoomTypeList=function(){this.roomTypeList.sort(function(room1,room2){if(room2.qty()<=0){return-1;}
if(room2.qty()>0&&room1.qty()<=0){return 1;}
if(room2.leadPriceRate().value<room1.leadPriceRate().value){return 1;}
else if(room2.leadPriceRate().value>room1.leadPriceRate().value){return-1;}
else{return 0;}});this.roomTypeList.notifySubscribers();};Establishment.prototype.lowestRoomPriceHasSpecial=function(){return this.roomLeadPriceCheapestRoomRateHasSpecial;};Establishment.prototype.getLowestRoomPricePreSpecial=function(){return this.roomLeadPriceCheapestRoomRatePreSpecial;};Establishment.prototype.getSpecialSummary=function(){if(this.totalAllInSpecial()!=null){return "You score!  "+this.totalAllInSpecial().summary;}};Establishment.prototype.getLowestRoomPrice=function(){if(this.hasSelectedRooms()){return this.nightlyPriceExclExtras();}
return this.roomLeadPriceCheapestRoomRate;};Establishment.prototype.setupCacheExpiry=function(){var _this=this;setTimeout(function(){_this.allocationPriceCache={};_this.totalsPriceCache={};_this.setupCacheExpiry();},this.cacheMinsToLive*60*1000);};Establishment.prototype.verifyUserEmail=function(){var _this=this;this.clearErrors();this.loading(true);$.ajax({context:this,type:"POST",url:"/staff/verifyuseremail",data:{Email:this.quote().email()},cache:false,beforeSend:function(){}}).done(function(data){if(data.Success===true){_this.quote().customerContactId(data.Id);_this.quote().firstname(data.FirstName);_this.quote().lastname(data.LastName);_this.quote().setPhoneNumber(data.MobileNumber);_this.loading(false);}
else{_this.handleLogicErrors(data);_this.loading(false);}}).fail(function(){_this.loading(false);});};Establishment.prototype.toggleCorporateMenu=function(){this.showCorporate(!this.showCorporate());};Establishment.prototype.verifyCorporateRequest=function(){var _this=this;this.quote().message(null);this.quote().corporateGuestName(null);this.quote().corporateAdults(null);this.quote().firstname(null);this.quote().lastname(null);this.quote().setPhoneNumber("");this.quote().email(null);this.loading(true);$.ajax({context:this,type:"POST",url:"/staff/verifycorporaterequest",data:{id:this.quote().corporateRequestId()},cache:false,beforeSend:function(){}}).done(function(data){if(data.Success===true){if(!data.IsEnquirable){alert("Corporate request "+_this.quote().corporateRequestId()+" is not enquirable. It is either in Complete status, or its arrival date is in the past.");}
else{$(".checkin").datepicker("setDate",new Date(data.Arrive));$(".checkout").datepicker("setDate",new Date(data.Depart));_this.quote().isCorporate(true);_this.quote().message(data.Message);_this.quote().corporateGuestName(data.Guest);_this.quote().corporateAdults(data.Adults);_this.quote().firstname(data.FirstName);_this.quote().lastname(data.LastName);_this.quote().setPhoneNumber(data.Mobile);_this.quote().email(data.Email);_this.showRaq();sn.app.esthomepagev3.CheckAvailability();}}
else{alert("Unable to find a corporate request with ID "+_this.quote().corporateRequestId());}
_this.loading(false);}).fail(function(){_this.loading(false);});};Establishment.prototype.openCheckIn=function(){var vm=sn.app.esthomepagev3.ViewModel;var theCheckinElement=null;var selector=$('.uiDatePickerFromToFrom.checkin').filter(":visible");if(selector.length===0){return;}
else if(selector.length>1){if(vm.featureToggle.IsRaqModal()&&vm.canShowRaq()){theCheckinElement=$('.modal-book-content .uiDatePickerFromToFrom.checkin').filter(":visible")[0];}
else{theCheckinElement=selector[0];}}
else{theCheckinElement=selector[0];}
if(!theCheckinElement){return;}
var shouldScroll=sn.app.esthomepagev3.ViewModel.featureToggle.ScrollOpenCheckinOnlyWhenNotIsInViewPort?!Util.isInViewPort(theCheckinElement):true;if(shouldScroll){var scrollPosition=$(theCheckinElement).offset().top-30;var viewableModalRoomListContainer=$(".modal-book:visible").length>0?$(".modal-book")[0]:null;var viewableOnPageRoomListContainer=$(".roomListContainer").length>0?$(".roomListContainer")[0]:null;if(viewableModalRoomListContainer){$(".modal-book-content").animate({scrollTop:0},250,function(){setTimeout(function(){if($(theCheckinElement).is(":visible")){Utility.AddClass(theCheckinElement,'validationElement');$(theCheckinElement).datepicker("show");}},150);});}
else{$("html, body").animate({scrollTop:scrollPosition},250,function(){setTimeout(function(){if($(theCheckinElement).is(":visible")){Utility.AddClass(theCheckinElement,'validationElement');$(theCheckinElement).datepicker("show");}},150);});}}
else{if($(theCheckinElement).is(":visible")){$(theCheckinElement).datepicker("show");Utility.AddClass(theCheckinElement,'validationElement');}}};Establishment.prototype.openModalCheckIn=function(){var selector=$('#ModalBookContent input.uiDatePickerFromToFrom.checkin').filter(":visible");if($(selector[0]).is(":visible")){$(selector[0]).datepicker("show");}};Establishment.prototype.promptRoomChoice=function(){if($(".roomListContainer").length>0){var vm=this;setTimeout(function(){var viewableModalRoomListContainer=$(".modal-book .roomListContainer:visible").length>0?$(".modal-book .roomListContainer")[0]:null;var viewableOnPageRoomListContainer=$(".roomListContainer").length>0?$(".roomListContainer")[0]:null;if(viewableModalRoomListContainer){$(".modal-book-content").animate({scrollTop:0},350,function(){if(!vm.isStaff()&&vm.addRoomPromptCount==3){vm.showAddRoomHelpNotification(vm);}});}
else if(viewableOnPageRoomListContainer){$("html, body").animate({scrollTop:viewableOnPageRoomListContainer.offsetTop},350,function(){if(!vm.isStaff()&&vm.addRoomPromptCount==3){vm.showAddRoomHelpNotification(vm);}});}},150);vm.roomsListText("Choose your rooms below");vm.roomsListHelp(true);$(".number-picker-text").removeClass("number-picker-help");$(".number-picker-text").outerWidth();$(".number-picker-text").addClass("number-picker-help");vm.addRoomPromptCount++;}};Establishment.prototype.loadServerContext=function(){var _this=this;if($("#serverRooms").length>0){var rooms=JSON.parse($("#serverRooms").val());this.addRoomList(rooms);}
else{this.notBookable(true);}
this.currencyCode=$("#BaseCurrencyCode").val();var quote=new Quote();this.quote=ko.observable(quote);this.checkin.subscribe(function(newValue){if(!isNaN(newValue.getDate())){quote.checkin(newValue);}});this.checkout.subscribe(function(newValue){if(!isNaN(newValue.getDate())){quote.checkout(newValue);}});this.userFirstname.subscribe(function(newValue){if(newValue.length>0&&!_this.isStaff){quote.firstname(newValue);}});this.userLastname.subscribe(function(newValue){if(newValue.length>0&&!_this.isStaff){quote.lastname(newValue);}});this.userEmail.subscribe(function(newValue){if(newValue.length>0&&!_this.isStaff){quote.email(newValue);}});this.userMobile.subscribe(function(newValue){if(newValue.length<=0||_this.isStaff){return;}
quote.setPhoneNumber(newValue);});};Establishment.prototype.setLoading=function(isLoading,elements,message){if(elements===void 0){elements=null;}
if(message===void 0){message="";}
if(elements==null||elements.length===0){elements=new Array();elements=elements.concat($('.booking-summary').toArray());elements=elements.concat($('.est-homepage-slide-out').toArray());}
var minLoadingTime=500;var startLoading=moment(Date.now());if(isLoading){startLoading=moment(Date.now());$(elements).addClass('loading');$('.stickytaskbarloader').show();}
else{var finishedLoading=moment(Date.now());var secondsLoading=finishedLoading.diff(startLoading,'milliseconds');if(secondsLoading>minLoadingTime){$(elements).removeClass('loading');$('.stickytaskbarloader').hide();}
else{setTimeout(function(){$(elements).removeClass('loading');$('.stickytaskbarloader').hide();},minLoadingTime-secondsLoading);}}};Establishment.prototype.setCheckinCheckout=function(){var checkin=moment($(".checkin").datepicker("getDate"));if(checkin.isValid()){this.checkin(checkin.toDate());}
var checkout=moment($(".checkout").datepicker("getDate"));if(checkout.isValid()){this.checkout(checkout.toDate());}
this.hasDates(checkin.isValid()&&checkout.isValid());this.nights(checkout.diff(checkin,'days'));};Establishment.prototype.addRoomList=function(serverRooms){for(var _i=0,serverRooms_1=serverRooms;_i<serverRooms_1.length;_i++){var r=serverRooms_1[_i];this.addRoomType(r);}
this.showRoomsList(true);this.roomCount.notifySubscribers();};Establishment.prototype.addRoomType=function(r){var idToUse=r["ThirdPartyUnitId"]!=null&&r["ThirdPartyUnitId"]!==""?r["ThirdPartyUnitId"]:r["Id"];var roomToAdd=new RoomType(this,idToUse,r["Name"],this.nights);roomToAdd.auid=parseInt(r["Id"]);roomToAdd.description=r["Description"];var charcount=440;if(sn.app.ScreenSize.IsXs|sn.app.ScreenSize.IsS|sn.app.ScreenSize.IsM){charcount=40;}
if(sn.app.ScreenSize.IsM){charcount=70;}
if(sn.app.ScreenSize.ems>=sn.app.ScreenSize.L){charcount=150;}
if(roomToAdd.description!=null&&roomToAdd.description.length>charcount){roomToAdd.showFullDescription(false);roomToAdd.shortDescription=roomToAdd.description.substr(0,charcount);}
else{roomToAdd.shortDescription="";}
roomToAdd.rateBasis=r["RateBasis"];roomToAdd.leadPriceRate(new Rate(r["LowestPrice"].Value,r["LowestPrice"].BaseCurrencySymbol));roomToAdd.leadPrice(""+roomToAdd.leadPriceRate().displayValue);roomToAdd.leadPriceDescription(r["LowestPriceRateTypeText"]);roomToAdd.initialLeadPriceRate(roomToAdd.leadPriceRate());roomToAdd.sleeps(r["Sleeps"]);if(r["Facilities"]!==undefined){for(var _i=0,_a=r.Facilities;_i<_a.length;_i++){var f=_a[_i];roomToAdd.facilities.push(f);}}
if(r["Features"]!==undefined){if(r.Features.length>0){for(var _b=0,_c=r.Features;_b<_c.length;_b++){var f=_c[_b];roomToAdd.features.push(new RoomFeature(f.Name,f.IconClass));}
roomToAdd.featuresAsString(roomToAdd.features().map(function(f){return f.name;}).join(", "));}}
if(r["ImageUrls"]){for(var _d=0,_e=r["ImageUrls"];_d<_e.length;_d++){var img=_e[_d];var im={Description:roomToAdd.roomName,Position:0,ImageSizes:[{Url:img,Size:ImageSizeEnum.Small},{Url:img,Size:ImageSizeEnum.Medium},{Url:img,Size:ImageSizeEnum.Large}]};roomToAdd.images.push(im);}
if(roomToAdd.images().length){roomToAdd.image(roomToAdd.images()[0].ImageSizes[0].Url);}}
else if(r["ImageUrl"]){var primImageUrl=r["ImageUrl"];roomToAdd.image(primImageUrl);var primaryImage={Description:roomToAdd.roomName,Position:0,ImageSizes:[{Url:primImageUrl,Size:ImageSizeEnum.Small},{Url:primImageUrl,Size:ImageSizeEnum.Medium},{Url:primImageUrl,Size:ImageSizeEnum.Large}]};roomToAdd.images.push(primaryImage);}
this.roomTypeList.push(roomToAdd);};Establishment.prototype.addRoom=function(room,adults){if(adults===void 0){adults=-1;}
var viewModel=this;if(!this.canShowRaq()){this.setLoading(true);}
if(this.isCorporateStaff()&&this.quote()&&this.quote().corporateAdults()>0){adults=this.quote().corporateAdults();}
else if(this.selectedAdultsGlobalFilter()!=2&&room.adultOptions&&this.selectedAdultsGlobalFilter()<=room.adultOptions().length){adults=this.selectedAdultsGlobalFilter();}
var addedRoom;for(var _i=0,_a=this.roomTypeList();_i<_a.length;_i++){var r=_a[_i];if(r.roomId===room.roomType.roomId){addedRoom=new Room(room.roomType,adults>0?adults:r.defaultRoom.adults(),0,0,0,0,null,r.defaultRoom.mealPlan());r.roomsSelected.push(addedRoom);room=addedRoom;break;}}
if(addedRoom==null){var newRoomType=new RoomType(this,room.roomType.roomId,room.roomType.roomName,this.nights);newRoomType.roomsSelected.push(room);this.roomTypeList.push(newRoomType);addedRoom=room;}
addedRoom.adults.subscribe(function(newAdult){var key=viewModel.getPriceCacheKey(room.roomType.roomId,newAdult,room.childBand1(),room.childBand2(),room.childBand3(),room.childrenList(),room.mealPlan());viewModel.applyPaxChange(key,viewModel,room);}.bind(this));addedRoom.childAges.subscribe(function(childAges){var key=viewModel.getPriceCacheKey(room.roomType.roomId,room.adults(),room.childBand1(),room.childBand2(),room.childBand3(),childAges,room.mealPlan());viewModel.applyPaxChange(key,viewModel,room);}.bind(this));addedRoom.childBand1.subscribe(function(childBand){var key=viewModel.getPriceCacheKey(room.roomType.roomId,room.adults(),childBand,room.childBand2(),room.childBand3(),room.childrenList(),room.mealPlan());viewModel.applyPaxChange(key,viewModel,room);}.bind(this));addedRoom.childBand2.subscribe(function(childBand){var key=viewModel.getPriceCacheKey(room.roomType.roomId,room.adults(),room.childBand1(),childBand,room.childBand3(),room.childrenList(),room.mealPlan());viewModel.applyPaxChange(key,viewModel,room);}.bind(this));addedRoom.childBand3.subscribe(function(childBand){var key=viewModel.getPriceCacheKey(room.roomType.roomId,room.adults(),room.childBand1(),room.childBand2(),childBand,room.childrenList(),room.mealPlan());viewModel.applyPaxChange(key,viewModel,room);}.bind(this));addedRoom.mealPlan.subscribe(function(newMealPlan){var key=viewModel.getPriceCacheKey(room.roomType.roomId,room.adults(),room.childBand1(),room.childBand2(),room.childBand3(),newMealPlan);viewModel.applyPaxChange(key,viewModel,addedRoom);}.bind(this));var rate=this.getPriceCacheResult(this.getPriceCacheKeyFromRoom(room));if(rate!=null){addedRoom.total(rate);if(rate.special!=null){addedRoom.special(rate.special);}}
viewModel.getPriceForRooms();viewModel.postAddRoom(viewModel,room);this.setLoading(false);};Establishment.prototype.postAddRoom=function(vm,room){vm.clearErrors();if(vm.isMobile()||vm.isTablet()){if(!vm.isSingleUnit()&&vm.featureToggle.ShouldToastPostRoomAdd){iziToast.show({id:'show',title:'Add another room or Check out',close:false,displayMode:1,timeout:false,position:'center',backgroundColor:'#61ceff',buttons:[['<button>Add/Edit rooms</button>',function(instance,toast){instance.hide({transitionOut:'fadeOutDown'},toast);if(vm.modal.isOpen){vm.shouldShowModalStickyFooter(true);}}],['<button style="border: solid 1px #81c243;background: #81c243;color: #ffffff !important;font-size: 1.1em;">Next</button>',function(instance,toast){instance.hide({transitionOut:'fadeOutUp'},toast);vm.modal.modal(".mobile-booking-card","Ready to Go!");},true]]});}
else{if(vm.modal.isOpen){vm.shouldShowModalStickyFooter(true);}}}};Establishment.prototype.showAddRoomHelpNotification=function(vm){if(vm.isDesktop()){iziToast.show({id:'showAddRoomHelpNotification',class:'addRoomHelpNotification',title:'',closeOnClick:true,closeOnEscape:true,close:true,displayMode:1,timeout:0,position:'center',image:'https://sncdn.com/res/img/est-homepage/AddRoomHelp.gif',imageWidth:761,});}};Establishment.prototype.applyPaxChange=function(key,viewModel,room){var rate=viewModel.getPriceCacheResult(key);if(rate==null){viewModel.getPriceForRooms();return;}
else{room.total(rate);sn.app.esthomepagev3.ViewModel.log("cache hit: "+key+" "+room.roomType.roomName+", pax change");}
var allocation=JSON.stringify(this.getAllocationRequestModel());var key=MD5.encrypt(allocation);if(this.totalsPriceCache[key]!=null){var totals=this.totalsPriceCache[key];if(totals.Total!=null)
this.totalAllInRate(totals.Total);if(totals.Deposit!=null)
this.depositAllInRate(totals.Deposit);if(totals.NightlyRateExclExtras!=null)
this.nightlyRateExclExtras(totals.NightlyRateExclExtras);if(totals.TotalExclExtras!=null)
this.totalRateExclExtras(totals.TotalExclExtras);}
else{viewModel.getPriceForRooms();return;}};Establishment.prototype.removeRoom=function(guid){for(var _i=0,_a=this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];for(var _b=0,_c=rt.roomsSelected();_b<_c.length;_b++){var r=_c[_b];if(r.guid()===guid){rt.roomsSelected.remove(r);break;}}}
this.getPriceForRooms();this.tryEnableAllRoomPickers();};Establishment.prototype.removeAllSelectedRooms=function(){for(var _i=0,_a=this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];if(rt.roomsSelected().length>0){rt.roomsSelected.removeAll();}}
this.tryEnableAllRoomPickers();};Establishment.prototype.removeAllSelectedRoomsOfType=function(roomTypeId){for(var _i=0,_a=this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];if(rt.roomId===roomTypeId){if(rt.roomsSelected().length>0){rt.roomsSelected.removeAll();}}}
this.tryEnableAllRoomPickers();};Establishment.prototype.tryEnableAllRoomPickers=function(){if(!this.isMultiRoomSelectionEnabled()&&!this.hasSelectedRooms()){for(var _i=0,_a=this.roomTypeList();_i<_a.length;_i++){var r=_a[_i];r.canAddRoom(true);}}};Establishment.prototype.removeLastRoomOfType=function(roomTypeId){for(var _i=0,_a=this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];if(rt.roomId===roomTypeId){if(rt.roomsSelected().length>0){this.removeRoom(rt.roomsSelected()[rt.roomsSelected().length-1].guid());}}}};Establishment.prototype.updateRoomAvailabilityAndPrice=function(data){var rooms=data.Rooms;this.setCheckinCheckout();this.preSpecialTotal=0;var checkin=moment(this.checkin());var checkout=moment(this.checkout());var selectedDates=checkin.format("Do MMM")+" - "+checkout.format("Do MMM")+" "+ +checkout.format("YYYY");this.roomsListText("Rooms - "+selectedDates);this.selectedDateRangeText(selectedDates);if(data.Errors!==null&&data.Errors.length>0){for(var _i=0,_a=data.Errors;_i<_a.length;_i++){var err=_a[_i];this.addErrors([err]);}
for(var _b=0,_c=this.roomTypeList();_b<_c.length;_b++){var rt=_c[_b];this.removeAllSelectedRoomsOfType(rt.roomId);rt.qty(0);}}
else if(rooms==null||rooms.length===0){for(var _d=0,_e=this.roomTypeList();_d<_e.length;_d++){var rt=_e[_d];this.removeAllSelectedRoomsOfType(rt.roomId);rt.qty(0);}}
else{this.isMultiRoomSelectionEnabled(data.RoomSelectionEnabled);if(data.DepositAllIn!=null){this.depositAllInRate(new Rate(data.DepositAllIn.Value,data.DepositAllIn.BaseCurrencySymbol));}
if(data.Total!=null){var totalValue=data.Total.Value;this.totalRateExclExtras(new Rate(totalValue,data.Total.BaseCurrencySymbol));var nights=this.nights();var totalpernight=(totalValue/nights);this.nightlyRateExclExtras(new Rate(totalpernight,data.Total.BaseCurrencySymbol));}
if(data.TotalAllIn!=null){this.totalAllInRate(new Rate(data.TotalAllIn.Value,data.TotalAllIn.BaseCurrencySymbol));}
if(data.TotalAllInSpecial!=null){this.totalAllInSpecial(new Special(data.TotalAllInSpecial.SpecialId,data.TotalAllInSpecial.IsFreebieOnlySpecial,new Rate(data.TotalAllInSpecial.SpecialAmountRate.Value,data.TotalAllInSpecial.SpecialAmountRate.BaseCurrencySymbol),data.TotalAllInSpecial.SpecialSummary,data.TotalAllInSpecial.FreebieDetails,new Rate(data.TotalAllInSpecial.OriginalAmountRate.Value,data.TotalAllInSpecial.OriginalAmountRate.BaseCurrencySymbol)));}
else{this.totalAllInSpecial(null);}
var allocation=JSON.stringify(this.getAllocationRequestModel());var key=MD5.encrypt(allocation);this.totalsPriceCache[key]=new TotalRatesResult(this.depositAllInRate(),this.totalAllInRate(),this.totalRateExclExtras(),this.nightlyRateExclExtras());if(data.ExtraLineItems!=null){var extras="";var extraItems=data.ExtraLineItems.map(function(extra){return "<div class=\"booking-line\"><div class=\"booking-line-text\">"+extra.Item+"</div><div class=\"booking-line-amount\">"+extra.Amount.BaseCurrencySymbol+extra.Amount.Value.toFixed(2)+"</div></div>";});console.log(extras);if(extraItems.length>=1){var extraTotal=0;var extraCurrencySymbol='R';for(var i=0;i<data.ExtraLineItems.length;i++){extraTotal+=data.ExtraLineItems[i].Amount.Value;extraCurrencySymbol=data.ExtraLineItems[i].Amount.BaseCurrencySymbol;}
this.totalExtras(new Rate(extraTotal,extraCurrencySymbol));for(var _f=0,extraItems_1=extraItems;_f<extraItems_1.length;_f++){var extra=extraItems_1[_f];extras+=extra;}
this.extraCharges(""+extras);this.hasExtraCharges(true);}
else{this.extraCharges("");this.hasExtraCharges(false);}}
for(var _g=0,rooms_1=rooms;_g<rooms_1.length;_g++){var sroom=rooms_1[_g];for(var _h=0,_j=this.roomTypeList();_h<_j.length;_h++){var rt=_j[_h];var roomTypeFound=false;if(rt.roomId===sroom.Id){roomTypeFound=true;break;}}
if(!roomTypeFound){this.log("Found a room we should add:");this.log(JSON.stringify(sroom));}}
for(var _k=0,_l=this.roomTypeList();_k<_l.length;_k++){var rt=_l[_k];var roomTypeUpdated=false;for(var _m=0,rooms_2=rooms;_m<rooms_2.length;_m++){var sroom=rooms_2[_m];if(rt.roomId===sroom.Id){roomTypeUpdated=true;if(sroom.Quantity>0){rt.hasAvailability(true);}
rt.qty(sroom.Quantity);rt.maxAdults(sroom.Sleeps);rt.maxChildren(sroom.Sleeps-rt.minAdults());rt.maxPax(sroom.Sleeps);if(sroom.AllowChild1){rt.child1Min(sroom.ChildAge1Lower);rt.child1Max(sroom.ChildAge1Upper);}
if(sroom.AllowChild2){rt.child2Min(sroom.ChildAge2Lower);rt.child2Max(sroom.ChildAge2Upper);}
if(sroom.AllowChild3){rt.child3Min(sroom.ChildAge3Lower);rt.child3Max(sroom.ChildAge3Upper);}
if(sroom.ImageUrl){rt.image(sroom.ImageUrl);}
rt.leadPrice(sroom["LowestPrice"]);rt.leadPriceDescription(sroom["LowestPriceRateTypeText"]);if(this.selectedAdultsGlobalFilter()!=2&&this.selectedAdultsGlobalFilter()<=rt.maxAdults()){rt.defaultRoom.adults(this.selectedAdultsGlobalFilter());}
else{rt.defaultRoom.adults(rt.maxAdults()<2?rt.maxAdults():2);}
rt.defaultMealPlan=sroom.DefaultMealPlan;rt.defaultRoom.mealPlan(sroom.DefaultMealPlan);if(sroom.RoomAllocations!==null&&sroom.RoomAllocations.length>0&&sroom.RoomAllocations[0].ConfirmedAllocationRate!==null){for(var _o=0,_p=sroom.RoomAllocations;_o<_p.length;_o++){var ralloc=_p[_o];rt.maxAdults(ralloc.MaxAdults);rt.maxChildren(ralloc.MaxChildren);if(ralloc.ConfirmedAllocationRate!=null){var roomStayTotal=ralloc.ConfirmedAllocationRate.Value;var roomStayTotalCurrency=ralloc.ConfirmedAllocationRate.BaseCurrencySymbol;var roomStayRate=new Rate(roomStayTotal,roomStayTotalCurrency);var adults=ralloc.Adults;var childAges=ralloc.ChildAges||[];var child1=ralloc.ChildrenAge1||0;var child2=ralloc.ChildrenAge2||0;var child3=ralloc.ChildrenAge3||0;var selectedMealPlan=ralloc.SelectedMealPlanCode||"";rt.leadPrice(""+roomStayRate.displayValue);rt.leadPriceRate(roomStayRate);var special=null;if(ralloc.HasSpecial){this.preSpecialTotal+=ralloc.Special.OriginalAmountRate.Value;special=new Special(ralloc.Special.SpecialId,ralloc.Special.IsFreebieOnlySpecial,new Rate(ralloc.Special.SpecialAmountRate.Value,ralloc.Special.SpecialAmountRate.BaseCurrencySymbol),ralloc.Special.SpecialSummary,ralloc.Special.FreebieDEtails,new Rate(ralloc.Special.OriginalAmountRate.Value,ralloc.Special.OriginalAmountRate.BaseCurrencySymbol));rt.defaultRoom.special(special);roomStayRate.special=special;rt.leadPrice(""+rt.defaultRoom.special().amount.displayValue);rt.leadPriceRate(roomStayRate);}
else{rt.defaultRoom.special(null);}
if(roomStayTotal>0){var key=this.getPriceCacheKey(rt.roomId,adults,child1,child2,child3,childAges,selectedMealPlan);this.addPriceCacheResult(key,roomStayRate);}
if(this.roomTypeList().length>0){for(var _q=0,_r=this.roomTypeList();_q<_r.length;_q++){var srt=_r[_q];if(srt.roomId===sroom.Id){for(var _s=0,_t=srt.roomsSelected();_s<_t.length;_s++){var srtr=_t[_s];if(srtr.adults()==ralloc.Adults&&srtr.childBand1()==ralloc.ChildrenAge1&&srtr.childBand2()==ralloc.ChildrenAge2&&srtr.childBand3()==ralloc.ChildrenAge3){srtr.total(roomStayRate);if(ralloc.HasSpecial){srtr.special(special);}}}}}}
else{rt.leadPriceRate(roomStayRate);rt.defaultRoom.total(roomStayRate);rt.defaultRoom.adults(ralloc.Adults);}
if(ralloc.RoomMealPlans!=null&&ralloc.RoomMealPlans.length>0){rt.mealPlanOptions().length=0;ralloc.RoomMealPlans.sort(function(a,b){return a.IsDefault===false?1:-1;});for(var _u=0,_v=ralloc.RoomMealPlans;_u<_v.length;_u++){var m=_v[_u];if(m.IsDefault){rt.defaultMealPlan=m.Code;rt.defaultRoom.mealPlan(m.Code);}
if(ralloc.RoomMealPlans.length>1){var decoded=$('<textarea/>').html(m["Description"]).text();var dditem=new DropDownOption(m["Code"],decoded);rt.mealPlanOptions.push(dditem);}}}}}}
else{var roomRates=sroom.RoomRates.slice().sort(function(a,b){var comparison=0;if(a.IsDefaultMealPlan&&!b.IsDefaultMealPlan){comparison=-1;}
else if(a.IsDefaultMealPlan===b.IsDefaultMealPlan&&a.RateAmount>=b.RateAmount){comparison=-1;}
else if(a.IsDefaultMealPlan===b.IsDefaultMealPlan&&a.RateAmount<=b.RateAmount){comparison=1;}
return comparison;});if(roomRates.length&&rt.leadPriceRate().value==0){rt.leadPriceRate(new Rate(roomRates[0].RateAmount,rt.initialLeadPriceRate().currencySymbol));}}}}
if(roomTypeUpdated){rt.show(true);}
else{rt.show(!this.featureToggle.HideUnavailableRoomsByDefault);rt.qty(0);rt.hasAvailability(false);rt.defaultRoom.special(null);var rate=new Rate(rt.initialLeadPriceRate().value*rt.nights().valueOf(),rt.initialLeadPriceRate().currencySymbol);rt.leadPriceRate(rate);rt.leadPrice(""+rt.leadPriceRate().currencySymbol+rt.leadPriceRate().value);this.removeAllSelectedRoomsOfType(rt.roomId);}}}
this.setRoomAllocation();this.setLoading(false);this.selectRoomFromUrl();};Establishment.prototype.getPriceCacheKey=function(roomTypeId,adults,c1,c2,c3,cages,plan){if(c1===void 0){c1=0;}
if(c2===void 0){c2=0;}
if(c3===void 0){c3=0;}
if(plan===void 0){plan="";}
var from=moment($(".checkin").datepicker("getDate")).format('DDMMYYYY');var to=moment($(".checkout").datepicker("getDate")).format('DDMMYYYY');var childAges="";if(cages!=null){for(var i=0;i<cages.length;i++){childAges+=cages[i].Age+",";}}
var key=roomTypeId+"_"+from+"_"+to+"_"+adults+"_"+c1+"_"+c2+"_"+c3+"_"+childAges+"_"+plan;return key;};Establishment.prototype.getPriceCacheKeyFromRoom=function(room){var from=moment($(".checkin").datepicker("getDate")).format('DDMMYYYY');var to=moment($(".checkout").datepicker("getDate")).format('DDMMYYYY');var childAges="";for(var i=0;i<room.childrenList().length;i++){childAges+=room.childrenList()[i].Age+",";}
return room.roomType.roomId+"_"+from+"_"+to+"_"+room.adults()+"_"+room.childBand1()+"_"+room.childBand2()+"_"+room.childBand3()+"_"+childAges+"_"+room.mealPlan();};Establishment.prototype.addPriceCacheResult=function(cacheKey,rate){this.allocationPriceCache[""+cacheKey]=rate;sn.app.esthomepagev3.ViewModel.log("rate added to cache: "+cacheKey+" = "+rate.value);};Establishment.prototype.getPriceCacheResult=function(cacheKey){return this.allocationPriceCache[""+cacheKey];};Establishment.prototype.getAllocationRequestModel=function(){var allocationRequest={};allocationRequest.Allocations=[];for(var _i=0,_a=this.roomTypeList();_i<_a.length;_i++){var selectedRoomType=_a[_i];for(var _b=0,_c=selectedRoomType.roomsSelected();_b<_c.length;_b++){var selectedRoom=_c[_b];var room={};room.RoomId=selectedRoomType.roomId;room.Adults=selectedRoom.adults();room.ChildrenAge1=selectedRoom.childBand1();room.ChildrenAge2=selectedRoom.childBand2();room.ChildrenAge3=selectedRoom.childBand3();room.ChildAges=[];for(var i=0;i<selectedRoom.childrenList().length;i++){room.ChildAges.push(selectedRoom.childrenList()[i].Age());}
room.SelectedMealPlanCode=selectedRoom.mealPlan();var key=this.getPriceCacheKeyFromRoom(selectedRoom);if(this.allocationPriceCache[key]!=null){var r=this.allocationPriceCache[key];this.log("cache hit "+key+":"+r.currencySymbol+r.value);selectedRoom.total(r);}
allocationRequest.Allocations.push(room);}}
return allocationRequest;};Establishment.prototype.setRoomAllocation=function(){};Establishment.prototype.getAvailability=function(){};Establishment.prototype.clearDates=function(vm){$.ajax({context:{},type:"GET",url:"/establishment/cleardates",data:{},cache:false,beforeSend:function(){}}).done(function(data){vm.clearErrors();vm.hasDates(false);vm.removeAllSelectedRooms();});};Establishment.prototype.getPriceForRooms=function(){};Establishment.prototype.getGoPageQueryString=function(){var queryString="";if(this.checkin()!=null&&this.checkout()!=null){var checkin=Utility.getFormattedDate(this.checkin());var checkout=Utility.getFormattedDate(this.checkout());queryString="?checkin="+encodeURIComponent(checkin)+"&checkout="+encodeURIComponent(checkout);}
return queryString;};Establishment.prototype.saveGoPageInHistory=function(queryString){var pushState=""+window.location.pathname+queryString;history.pushState(null,"",pushState);};Establishment.prototype.showRaq=function(){var vm=this;PageLogger.LogEstPageStep(this,EstablishmentStep.QuoteRequested,"raq-start");if(this.isCorporateAgent()){var checkinoutparams='';if(this.hasDates()){checkinoutparams='&checkin='+moment(this.checkin()).format("DD-MM-YYYY")+'&checkout='+moment(this.checkout()).format("DD-MM-YYYY");}
window.location.href=this.raqUrl().toString()+checkinoutparams;return;}
if(this.featureToggle.IsRaqInline()){this.showInlineBookingSummaryRaq();return;}
if(this.featureToggle.IsRaqModal()){this.canShowRaq(true);this.selectedCallToAction(0);this.showModal();this.gallery.closeGallery(this.gallery);return;}
else if(this.featureToggle.IsRaqLinkedPage()&&this.raqUrl()!=""){this.saveGoPageInHistory(this.getGoPageQueryString());window.location.href=this.raqUrl().toString();return;}
else{this.saveGoPageInHistory(this.getGoPageQueryString());window.location.href=this.raqUrl().toString();return;}};Establishment.prototype.showInlineBookingSummaryRaq=function(){var vm=this;vm.canShowInlineRaq(true);setTimeout(function(){if(!vm.hasDates()){if(vm.isMobile()||vm.isTablet()){vm.shouldModaliseBookingCard(true);if(vm.isSingleUnit()){vm.modal.modal(".global-avail-filter","Select Dates & Guests");}
else{vm.modal.modal("#booknow","Select Dates, Guests & Room/s");}}
setTimeout(function(){vm.openCheckIn();},100);}
else if(!vm.hasSelectedRooms()){if(!vm.isSingleUnit()){if(vm.isMobile()||vm.isTablet()){vm.modal.modal("#booknow","Select Rooms and Guests");}
setTimeout(function(){vm.promptRoomChoice();},100);}
else{if(vm.isMobile()||vm.isTablet()){$("html, body").animate({scrollTop:$('.mobile-single-booking-card:visible')[0].offsetTop-75},250,function(){});}}}
else{if(vm.isMobile()||vm.isTablet()){if($('.modal-inline-raq-form:visible').length>0){if(vm.modal.isOpen){vm.modal.modalcontentcontainer.animate({scrollTop:$('.modal-inline-raq-form:visible')[0].offsetTop-75},250);}
else{$("html, body").animate({scrollTop:$('.modal-inline-raq-form:visible')[0].offsetTop-75},250,function(){});}}}}},150);};Establishment.prototype.showFlexiQuote=function(){this.isFlexiQuote(true);this.canShowRaq(true);this.selectedCallToAction(0);this.showModal();this.scrollToAvailableRoom(this);};Establishment.prototype.showBookNowModal=function(){this.canShowBookModal(true);this.selectedCallToAction(1);this.showModal();this.scrollToAvailableRoom(this);};Establishment.prototype.showModal=function(){this.setModalHeight();this.showModalOverlay();this.hideWindowScrollbar();this.setModalContentHeight();document.getElementsByClassName("modal-book-content")[0].scrollTop=0;};Establishment.prototype.scrollToAvailableRoom=function(vm,postScrollFunction){if(postScrollFunction===void 0){postScrollFunction=null;}
setTimeout(function(){if(!vm.hasDates()){return;}
var viewableModalRoomListContainer=$(".modal-book .roomListContainer:visible").length>0?$(".modal-book .roomListContainer")[0]:null;var viewableOnPageRoomListContainer=$(".roomListContainer").length>0?$(".roomListContainer")[0]:null;if(viewableModalRoomListContainer){$(".modal-book-content").animate({scrollTop:0},350,function(){if(postScrollFunction&&typeof postScrollFunction==="function"){postScrollFunction();}});}
else if(viewableOnPageRoomListContainer){$("html, body").animate({scrollTop:viewableOnPageRoomListContainer.offsetTop},350,function(){if(postScrollFunction&&typeof postScrollFunction==="function"){postScrollFunction();}});}},250);};Establishment.prototype.mobileCardScrolled=function(data,event){var elem=event.target;if(elem.getBoundingClientRect().bottom>(elem.scrollHeight-elem.offsetHeight)+50){var stickyMobileTaskbar=$(".est-homepage-sticky-buttons")[0];Utility.AddClass(stickyMobileTaskbar,"visible");}};Establishment.prototype.setModalContentHeight=function(){setTimeout(function(){var footerHeight=document.getElementById("ModalBookFooter").offsetHeight;document.getElementById("ModalBookContent").style.bottom=footerHeight+"px";},500);};Establishment.prototype.setModalHeight=function(){var width=window.innerWidth;if(window.innerWidth<1024){var height=Utility.getWindowHeight();var el=document.getElementById("ModalBookContainer");if(el!==null){el.style.height=height+"px";}}};Establishment.prototype.hideModal=function(){var _this=this;$('.modal-book-content').animate({scrollTop:0},50,function(){_this.canShowBookModal(false);_this.canShowRaq(false);_this.isFlexiQuote(false);_this.selectedCallToAction(-1);_this.hideModalOverlay();_this.showWindowScrollbar();});};Establishment.prototype.cancelBookNowModal=function(){this.hideModal();};Establishment.prototype.hideWindowScrollbar=function(){var htmlEl=document.getElementsByTagName('html')[0];Utility.AddClass(htmlEl,"overflow-hidden");};Establishment.prototype.showWindowScrollbar=function(){var htmlEl=document.getElementsByTagName('html')[0];Utility.RemoveClass(htmlEl,"overflow-hidden");};Establishment.prototype.hideModalOverlay=function(){var htmlEl=document.getElementById("ModalOverlayDark");Utility.RemoveClass(htmlEl,"show");};Establishment.prototype.showModalOverlay=function(){var htmlEl=document.getElementById("ModalOverlayDark");Utility.AddClass(htmlEl,"show");};Establishment.prototype.showModalBookingSummary=function(){var vm=this;vm.modal.modal(".mobile-booking-card","Ready to Book!");setTimeout(function(){vm.modal.modalcontentcontainer.animate({scrollTop:0},250);},250);};Establishment.prototype.tryAddRoom=function(selectedRoomCount,roomCount,data){if(!this.hasDates()){this.openCheckIn();}
else{if(selectedRoomCount<roomCount){var roomToAdd=new Room(data);if(roomToAdd.roomType.canAddRoom()){var adults=this.globalRoomsFilter.TotalAdultsRequested();this.addRoom(roomToAdd,adults);}
if(!this.isMultiRoomSelectionEnabled()){for(var _i=0,_a=this.roomTypeList();_i<_a.length;_i++){var r=_a[_i];if(r.roomId!==roomToAdd.roomType.roomId){r.canAddRoom(false);}}}}}};Establishment.prototype.cancelRaq=function(){this.hideModal();};Establishment.prototype.raq=function(){var _this=this;var viewModel=this;this.clearErrors();if(!viewModel.promptAppropriately(viewModel)){return;}
this.loading(true);PageLogger.LogEstPageStep(this,EstablishmentStep.QuoteRequested,"raq-start");this.quote().toggleValidation(true);setTimeout(function(){var checkin=moment(_this.checkin());var checkout=moment(_this.checkout());var quoteRequestModel={};quoteRequestModel.IsStaff=_this.isStaff();quoteRequestModel.Rooms=[];quoteRequestModel.ChildAgeBands=[];quoteRequestModel.Spid=_this.spid();quoteRequestModel.CheckIn=checkin.format("YYYY-MM-DD");quoteRequestModel.CheckOut=checkout.format("YYYY-MM-DD");quoteRequestModel.CustomerContactId=_this.quote().customerContactId();quoteRequestModel.SelectedContactType=_this.quote().customerContactId()>0?"Existing":"New";quoteRequestModel.FirstName=_this.quote().firstname();quoteRequestModel.LastName=_this.quote().lastname();quoteRequestModel.PhoneNumber=_this.quote().phoneNumber();quoteRequestModel.CountryCode=_this.quote().areacode();quoteRequestModel.Email=_this.quote().email();quoteRequestModel.Message=_this.quote().message();quoteRequestModel.Adults=0;quoteRequestModel.BaseCurrency=_this.currencyCode;quoteRequestModel.Sleeps=0;quoteRequestModel.AllowChildren=false;for(var _i=0,_a=_this.roomTypeList();_i<_a.length;_i++){var selectedRoomType=_a[_i];if(selectedRoomType.child1Max()>0||selectedRoomType.child2Max()>0||selectedRoomType.child3Max()>0){quoteRequestModel.AllowChildren=true;}
if(selectedRoomType.roomsSelected()!=null&&selectedRoomType.roomsSelected().length>0){quoteRequestModel.Sleeps+=selectedRoomType.sleeps()*selectedRoomType.qty();var room={};room.Spid=_this.spid();room.AuId=!selectedRoomType.auid?0:selectedRoomType.auid;room.ThirdPartyReferenceId=selectedRoomType.auid?null:selectedRoomType.roomId;room.Name=selectedRoomType.roomName;room.SelectedQuantity=selectedRoomType.roomsSelected().length;room.BedroomSize=selectedRoomType.sleeps();room.adults=0;room.children1=0;room.children2=0;room.children3=0;var ageBand1={};var ageBand2={};var ageBand3={};ageBand1.Quantity=0;ageBand2.Quantity=0;ageBand3.Quantity=0;ageBand1.AgeFrom=selectedRoomType.child1Min();ageBand1.AgeTo=selectedRoomType.child1Max();ageBand2.AgeFrom=selectedRoomType.child2Min();ageBand2.AgeTo=selectedRoomType.child2Max();ageBand3.AgeFrom=selectedRoomType.child3Min();ageBand3.AgeTo=selectedRoomType.child3Max();for(var _b=0,_c=selectedRoomType.roomsSelected();_b<_c.length;_b++){var selectedRoom=_c[_b];quoteRequestModel.Adults+=selectedRoom.adults();ageBand1.Quantity+=selectedRoom.childBand1();ageBand2.Quantity+=selectedRoom.childBand2();ageBand3.Quantity+=selectedRoom.childBand3();room.adults+=selectedRoom.adults();room.children1+=selectedRoom.childBand1();room.children2+=selectedRoom.childBand2();room.children3+=selectedRoom.childBand3();}
if(selectedRoomType.child1Max()>0&&ageBand1.Quantity>0){quoteRequestModel.ChildAgeBands.push(ageBand1);}
if(selectedRoomType.child2Max()>0&&ageBand2.Quantity>0){quoteRequestModel.ChildAgeBands.push(ageBand2);}
if(selectedRoomType.child3Max()>0&&ageBand3.Quantity>0){quoteRequestModel.ChildAgeBands.push(ageBand3);}
quoteRequestModel.Rooms.push(room);}}
if(_this.quote().isCorporate()){quoteRequestModel.CorporateRequestId=_this.quote().corporateRequestId();quoteRequestModel.CorpPartyName=_this.quote().corporateGuestName();quoteRequestModel.Adults=_this.quote().corporateAdults();}
_this.quote().showErrorCorrectionMessage(false);if(quoteRequestModel.Rooms.length<=0){_this.quote().errors().push("No rooms have been selected");}
if(_this.quote().errors().length>0){_this.quote().showErrorCorrectionMessage(true);ko.validation.group(_this.quote()).showAllMessages();_this.setLoading(false);_this.loading(false);setTimeout(function(){var validationElementTop=0;if($(".validationElement:visible").length){validationElementTop=$('.validationElement:visible')[0].offsetTop;}
else if($('.validationLeftBorder:visible').length>0&&$($('.validationLeftBorder:visible')[0]).length>0){validationElementTop=$($('.validationLeftBorder:visible')[0])[0].offsetTop;}
else if($('.error-list:visible').length>0){validationElementTop=$('.error-list:visible')[0].offsetTop;}
$('.modal-book-content').animate({scrollTop:validationElementTop-25},250,function(){});},250);return;}
_this.log("send raq message: \n"+JSON.stringify(quoteRequestModel));if(_this.requestingQuoteStarted==0){_this.requestingQuoteStarted++;$.ajax({context:_this,type:"POST",url:_this.isFlexiQuote()?"/FlexiQuote/Index":"/RequestQuote/RequestQuote",data:quoteRequestModel,cache:false,beforeSend:function(){}}).done(function(data){if(data.ReturnUrl!=null&&data.ReturnUrl!==''&&data.Success===true){PageLogger.LogEstPageStep(viewModel,EstablishmentStep.QuoteRequested,"raq-success-new");document.location.href=data.ReturnUrl;}
else{viewModel.handleLogicErrors(data);_this.setLoading(false);PageLogger.LogEstPageStep(viewModel,EstablishmentStep.QuoteRequested,"raq-failure-new");}}).fail(function(){_this.requestingQuoteStarted=0;_this.setLoading(false);_this.loading(false);});}},250);};Establishment.prototype.book=function(){PageLogger.LogEstPageStep(this,EstablishmentStep.RealtimeBooked,"book-clicked");if(this.hasSelectedRooms()){var queryString=this.getGoPageQueryString();this.saveGoPageInHistory(queryString);window.location.href="book/"+queryString;}};Establishment.prototype.pay=function(context){var vm=null;if(context.getType()=="Establishment"){vm=context;}
else if(context.getType()=="RoomType"){vm=context.est;}
vm.clearErrors();if(!vm.promptAppropriately(vm)){PageLogger.LogEstPageStep(vm,EstablishmentStep.RealtimeBooked,"realtime-engaged");return;}
vm.setLoading(true);PageLogger.LogEstPageStep(vm,EstablishmentStep.RealtimeBooked,"realtime-pay-clicked");var allocationRequest=vm.getAllocationRequestModel();if(allocationRequest.Allocations.length>0){var bookNowRequest={};bookNowRequest.CheckIn=""+Utility.getFormattedDate(vm.checkin());bookNowRequest.CheckOut=""+Utility.getFormattedDate(vm.checkout());bookNowRequest.allocations=[];bookNowRequest.model={};bookNowRequest.model.SpId=vm.spid;bookNowRequest.allocations=allocationRequest.Allocations;$.ajax({context:vm,type:"POST",url:"/booknow/book",data:bookNowRequest,cache:false,beforeSend:function(){}}).done(function(data){PageLogger.LogEstPageStep(vm,EstablishmentStep.RealtimeBooked,"pay-clicked-done");if(data.redirectUrl!==''){var queryString="";if(vm.checkin()!=null&&vm.checkout()!=null){var checkin=Utility.getFormattedDate(vm.checkin());var checkout=Utility.getFormattedDate(vm.checkout());queryString="?checkin="+encodeURIComponent(checkin)+"&checkout="+encodeURIComponent(checkout);}
var pushState=""+window.location.pathname+queryString;history.pushState(null,"",pushState);document.location.href=data.redirectUrl;}
else{if(data.failedBookNowModel=null&&data.failedBookNowModel.Errors!=null){for(var i=0;i<data.failedBookNowModel.Errors.length;i++){vm.addErrors([data.failedBookNowModel.Errors[i]]);}}
else{vm.addErrors(["Unfortunately an error occured on our end. Please contact our customer support to secure your booking."]);}
vm.setLoading(false);}}).fail(function(){vm.log("Errors occurred -- debug here");vm.addErrors(["Unfortunately an error occured on our end. Please contact our customer support to secure your booking."]);vm.setLoading(false);});}};Establishment.prototype.promptAppropriately=function(vm){if(!vm.hasDates()){if(vm.isMobile()||vm.isTablet()){if(vm.featureToggle.IsRaqInline()){vm.shouldModaliseBookingCard(true);if(vm.isSingleUnit()){vm.modal.modal(".global-avail-filter","Select Dates & Guests");}
else{vm.modal.modal("#booknow","Select Dates, Guests & Room/s");}}
setTimeout(function(){vm.openCheckIn();},200);return false;}
vm.addErrors(["Please select dates"]);vm.openCheckIn();return false;}
if(!vm.hasSelectedRooms()){if(vm.isSingleUnit()){if(vm.hasAvailableRooms()){setTimeout(function(){vm.addErrors(["Please select room"]);vm.promptRoomChoice();},100);}
else{vm.addErrors(["There are no rooms available for these dates. Please try alternative dates."]);}
return false;}
else{if(vm.featureToggle.IsRaqInline()&&!vm.canShowRaq()&&(vm.isMobile()||vm.isTablet())){vm.modal.modal("#booknow","Select Rooms and Guests");}
setTimeout(function(){vm.addErrors(["Please select room/s"]);vm.promptRoomChoice();},100);}
return false;}
return true;};Establishment.prototype.log=function(message){if(!this.isLive()){console.log(message);}};Establishment.prototype.scrollToBookingSummary=function(){setTimeout(function(){$("html, body").animate({scrollTop:$('.summary-container')[0].offsetTop-75},500,function(){});},250);};Establishment.prototype.toggleRoomVisibility=function(){var state=!this.showingAllRooms();for(var _i=0,_a=this.roomTypeList();_i<_a.length;_i++){var rt=_a[_i];if(!rt.hasAvailability()){rt.show(state);}}
if(state===false){this.showingAllRooms(false);this.toggleRoomVisibilityText("Show unavailable rooms");}
else{this.showingAllRooms(true);this.toggleRoomVisibilityText("Hide unavailable rooms");}};Establishment.prototype.selectRoomFromUrl=function(){var _this=this;if(!this.appliedRoomSelectionFromUrl){var roomsUrl=Utility.getUrlParam("rooms");if(roomsUrl&&roomsUrl.length>0&&!this.isRaqOnly()&&this.roomTypeList().length>=1){var roomsRequested=JSON.parse(decodeURI(roomsUrl));var _loop_1=function(i_3){var roomRequested=roomsRequested[i_3];var foundRoom=null;this_1.roomTypeList().forEach(function(rt,i,arr){if(rt.roomId===roomRequested.id){foundRoom==rt;var adults=parseInt(roomRequested.a);if(adults>rt.maxAdults()){adults=rt.maxAdults();}
if(adults<0){adults=2;}
if(rt.hasAvailability()){_this.log("auto adding room from url: "+rt.roomName);_this.addRoom(rt.defaultRoom,adults);}
else{_this.log("unable to add room from url - no avail: "+rt.roomName);}}});};var this_1=this;for(var i_3=0;i_3<roomsRequested.length;i_3++){_loop_1(i_3);}}
this.appliedRoomSelectionFromUrl=true;}};Establishment.prototype.galleryActionCheckPrice=function(){this.gallery.closeGallery(this.gallery);if(this.modal.isOpen){this.modal.close();}
this.promptAppropriately(this);};Establishment.prototype.viewFavorites=function(){var win=window.open("/listing/myfavorites",'_blank');win.focus();};return Establishment;}(BaseViewModel));var EstablishmentSingleUnit=(function(_super){__extends(EstablishmentSingleUnit,_super);function EstablishmentSingleUnit(spidParam,featureToggles){var _this=_super.call(this,spidParam,featureToggles)||this;_this.stepwizard=new StepWizard([new Step(1,"Submit",_this.hasDates),new Step(2,"Submit",_this.hasSelectedRooms),new Step(3,"Submit",_this.hasSelectedRooms)]);if(_this.roomTypeList().length===1){_this.singleUnit=ko.observable(_this.roomTypeList()[0].defaultRoom);_this.roomType=ko.observable(_this.roomTypeList()[0]);}
_this.singleUnitComp=ko.computed(function(){if(this.roomTypeList().length>0&&this.roomTypeList()[0].roomsSelected().length>0)
return this.roomTypeList()[0].roomsSelected()[0];else
return this.singleUnit;},_this);return _this;}
EstablishmentSingleUnit.prototype.isSingleUnit=function(){return true;};EstablishmentSingleUnit.prototype.setRoomAllocation=function(){this.log("applying auto room allocation of single unit");if(this.roomTypeList().length===1&&this.roomTypeList()[0].defaultRoom!=null){if(this.roomTypeList()[0].qty()===1){if(this.roomTypeList()[0].roomsSelected().length<1){this.log("auto allocating new room of type "+this.roomTypeList()[0].roomName);this.singleUnit(new Room(this.roomTypeList()[0]));this.singleUnit().mealPlan(this.roomTypeList()[0].defaultMealPlan);var adults=this.globalRoomsFilter.TotalAdultsRequested();this.addRoom(this.singleUnit(),adults);}}}};EstablishmentSingleUnit.prototype.getAvailability=function(){};EstablishmentSingleUnit.prototype.getPriceForRooms=function(){var multiRoomAllocationRateRequest={SpId:this.spid(),AllocationRequest:this.getAllocationRequestModel()};this.log("fetching price for rooms");if(multiRoomAllocationRateRequest.AllocationRequest.Allocations.length>0){$.ajax({context:this,url:"getmultiallocationrate",dataType:'json',type:'POST',contentType:'application/json; charset=utf-8',data:JSON.stringify(multiRoomAllocationRateRequest),cache:false,beforeSend:function(){if(!this.canShowRaq()){this.setLoading(true);}},success:function(data,result){this.log(data);this.updateRoomAvailabilityAndPrice(data);},error:function(xhr,textStatus,err){},complete:function(d){if(!this.canShowRaq()){this.setLoading(false);}}});}};return EstablishmentSingleUnit;}(Establishment));var EstablishmentMultiUnit=(function(_super){__extends(EstablishmentMultiUnit,_super);function EstablishmentMultiUnit(spidParam,featureToggles){if(featureToggles===void 0){featureToggles=null;}
var _this=_super.call(this,spidParam,featureToggles)||this;_this.stepwizard=new StepWizard([new Step(1,"Submit",_this.hasDates),new Step(2,"Submit",_this.hasSelectedRooms),new Step(3,"Submit",_this.hasSelectedRooms)]);return _this;}
EstablishmentMultiUnit.prototype.isSingleUnit=function(){return false;};EstablishmentMultiUnit.prototype.setRoomAllocation=function(){if(!this.isRaqOnly&&this.roomTypeList().length===1&&this.roomTypeList()[0].defaultRoom!=null){this.log("applying auto room allocation of multi unit with only 1 room type");if(this.roomTypeList()[0].qty()>=1){if(this.roomTypeList()[0].roomsSelected().length<1){this.log("auto allocating new room of type "+this.roomTypeList()[0].roomName);this.addRoom(this.roomTypeList()[0].defaultRoom);}}}};EstablishmentMultiUnit.prototype.getAvailability=function(){var vm=this;if(!vm.hasDates()){vm.openCheckIn();return;}
if(vm.addRoomPromptCount<=2){vm.addRoomPromptCount=0;}
sn.app.esthomepagev3.CheckAvailability();};EstablishmentMultiUnit.prototype.getPriceForRooms=function(){var multiRoomAllocationRateRequest={SpId:this.spid(),AllocationRequest:this.getAllocationRequestModel()};if(multiRoomAllocationRateRequest.AllocationRequest.Allocations.length>0){$.ajax({context:this,url:"getmultiallocationrate",dataType:'json',type:'POST',contentType:'application/json; charset=utf-8',data:JSON.stringify(multiRoomAllocationRateRequest),cache:false,beforeSend:function(){this.setLoading(true);},success:function(data,result){this.log(data);this.updateRoomAvailabilityAndPrice(data);},error:function(xhr,textStatus,err){},complete:function(d){this.setLoading(false);}});}};return EstablishmentMultiUnit;}(Establishment));var $cal=null;var $currencyControls=null;var realtimecalendaryui=realtimecalendaryui||{init:function(){if(!$(".roomsRatesCalendar").length)return false;$cal=new RealtimeCalendar();$cal.UnitTooltips=new RealtimeCalendarUnitTT();$cal.RateTooltip=new RealtimeCalendarRateTT();$cal.bindNav();$cal.step=$cal_step<=7&&$cal_step>=1?$cal_step:1;$cal.defaultSpeed=$cal.step==1?200:200+(80*$cal.step);$cal.currency=$cal_currency;$cal.rateTypeItems=$('div.unitRow .pricing .rate-type');$cal.processData($cal_data);$cal.scrollOnInit();$cal.UnitTooltips.monitor();$cal.RateTooltip.init();$cal.RateTooltip.monitor();$("#datePicker").datepicker({beforeShow:function(){setTimeout(function(){$('.ui-datepicker').css('z-index',99999999999999);},0);},minDate:0,showOtherMonths:true,selectOtherMonths:true,regional:"en-za",dateFormat:"d MM yy",});$("#datePicker").change(function(){$cal.onDatePickerDateChanged();});}}
function RealtimeCalendar(){this.index=1;this.motion=1;this.step=1;this.navEnabled=true;this.defaultSpeed=0;this.data=null;this.loadOption=1;this.currency="ZAR";this.settingDatePicker=false;this.selectingDate=false;this.init=true;this.haveEarliest=true;this.itemWidth=51;this.rateTypeItems=null;this.days=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");this.daysShort=new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");this.months=new Array("January","February","March","April","May","June","July","August","September","October","November","December");this.monthsShort=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");this.UnitTooltips=null;this.RateTooltip=null;this.bindNav=function(){$('#rtcNext').closest("a").bind('click',function(){$cal.onNext();});$('#rtcPrev').closest("a").bind('click',function(){$cal.onPrev();});};this.getDatePicker=function(){return _picker();};this.getDatePickerDate=function(utc){var dp=this.getDatePicker();var dt=dp.datepicker("getDate");try{dt=dt!=null?dt:dp.get_focusedDate();}catch(e){var today=new Date();return today;}
return utc?new Date(dt.getUTCFullYear(),dt.getUTCMonth(),dt.getUTCDate()).valueOf():dt.valueOf();};this.setDatePickerDate=function(dt){if(!this.selectingDate){this.settingDatePicker=true;this.getDatePicker().datepicker("setDate",dt);var dtIndex=this.indexOfDate(dt.valueOf());this.setYearMonth(this.data.Dates[dtIndex]);this.settingDatePicker=false;}};this.dateListItems=function(){return $("div.datesRow li");};this.count=function(){return this.dateListItems().size();};this.indexOfUnit=function(auid){var unitIndex=null;for(iUnit=0;iUnit<this.data.Units.length;iUnit++){if(this.data.Units[iUnit].ID==auid){unitIndex=iUnit;break;}};return unitIndex;};this.indexOfDate=function(dt){var dateIndex=-1;for(iDate=0;iDate<this.data.Dates.length;iDate++){if(this.data.Dates[iDate].V==dt){dateIndex=iDate;break;}}
return dateIndex;};this.getUnitRatesXSection=function(unitIndex,itemIndex){var i=0;var q=0;var unit=this.data.Units[unitIndex];var pp=unit.P[itemIndex];var ppRate='&nbsp;';if(pp!=undefined){ppRate=this.getRateValue(pp);}
var pps=unit.S[itemIndex];var ppsRate='&nbsp;';if(pps!=undefined){i=pps.I;q=pps.Q;ppsRate=this.getRateValue(pps);}
var pu=unit.U[itemIndex];var puRate='&nbsp;';if(pu!=undefined){puRate=this.getRateValue(pu);i=pu.I;q=pu.Q;}
var rateType=unit.R[itemIndex];var fixedRate='&nbsp;';var slidingRate='&nbsp;';if(rateType.R!=undefined&&rateType.R=="FR"){var fr=unit.FR[itemIndex];var fixedRate='&nbsp;';if(fr!=undefined){if(fr.R!=null){fixedRate="<ul class='rate-ul'><li>"+this.getRateValue(fr)+"</li></ul>";i=fr.I;q=fr.Q;}}}
if(rateType.R!=undefined&&rateType.R=="SC"){var scRate=unit.SC[itemIndex];var slidingRate='&nbsp;';if(scRate!=undefined){if(scRate.SlidingScaleRates!=null&&scRate.SlidingScaleRates.length>=1){var slidingRatesBreakDown="<ul class='rate-ul'>";$.each(scRate.SlidingScaleRates,function(index,value){slidingRatesBreakDown+="<li>";slidingRatesBreakDown+=value.replace("(s)","");slidingRatesBreakDown+="</li>";});slidingRatesBreakDown+="</ul>";slidingRate=slidingRatesBreakDown;i=scRate.I;q=scRate.Q;}}}
return{P:ppRate,S:ppsRate,U:puRate,FR:fixedRate,SC:slidingRate,I:i,Q:q};};this.setYearMonth=function(calDate){$('#calendarYearMonth').text(calDate.A+' '+$cal.months[calDate.M]+' '+calDate.Y);};this.scrollOnInit=function(){$('div.datesRow').scrollTo(this.dateListItems()[1],200);};this.scrollToDate=function(dt,scrollSpeed){var idx=this.indexOfDate(dt);var count=this.count();if(idx!=-1&&(idx>count-9||idx<1)){return false;}
if(idx!=-1){this.scroll(idx,scrollSpeed);this.index=idx;this.setYearMonth(this.data.Dates[idx]);}
return idx!=-1;};this.scroll=function(toIndex,scrollSpeed){this.navEnabled=false;var dateItems=this.dateListItems();var dateItem=dateItems[toIndex];var speed=scrollSpeed?scrollSpeed:this.defaultSpeed;var rateRows=$('div.ratesRow');var rateItems=rateRows.find('li:nth-child('+toIndex+')');$('div.datesRow').scrollTo(dateItem,speed,{onAfter:$cal.onScrollComplete});rateRows.scrollTo(rateItems,speed);this.setDisplayMonth();};this.onScrollComplete=function(){if($cal.motion==0||$cal.motion==2){var lastIndex=$cal.count()-14;if(($cal.motion==2&&$cal.index>lastIndex)||($cal.motion==0&&!$cal.haveEarliest&&$cal.index<10)){$cal.loadOption=$cal.motion;$cal.showProgress(false);$cal.getData();}else{$cal.navEnabled=true;}}else{$cal.navEnabled=true;}
$cal.setRateTypes();};this.setRateTypes=function(){for(i=0;i<$cal.data.Units.length;i++){var rateTypeInd=$cal.data.Units[i].R[$cal.index].R,rateType=$cal.getRateType(rateTypeInd);$cal.rateTypeItems.eq(i).text(rateType);}};this.onDatePickerDateChanged=function(){if(!this.settingDatePicker){this.loadOption=1;this.selectingDate=true;var dt=this.getDatePickerDate(false);var scrolled=this.scrollToDate(dt);if(!scrolled){this.showProgress(true);this.getData(dt);}}};this.getRateElCss=function(rateInfo,rate){var cls='rb na';if(rate!='&nbsp;'){cls=rateInfo.Q?"rb rq":"rb unav";}
return cls;};this.getRateValue=function(rateInfo){var rate=eval("rateInfo."+this.currency);return rate&&rate.length>0?rate:'&nbsp;';};this.getRateType=function(t){var rt="";switch(t){case "P":rt="per person";break;case "S":rt="p/p sharing";break;case "U":rt="per unit";break;case "FRS":rt="Entire property";break;case "FRM":rt="per unit";break;case "SC":rt="For 2 adults";break;default:rt="n/a";break;}
return rt;};this.createDateEl=function(d){return $('<li>'+this.getDayName("ddd",d.B)+'<br /><span>'+d.A+'<sup>'+d.O+'</sup></span></li>');};this.createRateEl=function(rateInfo,addBorder){var rate=this.getRateValue(rateInfo);var cls=this.getRateElCss(rateInfo,rate);var rateHTML="<li class='"+cls+"'><span>"+rate+"</span></li>";return rateHTML;};this.currencyChanged=function(c){$cal.currency=c;UpdateServerCurrency(c);if($cal.data){$cal.updateRates();}};this.updateRates=function(){$('div.ratesRow ul').each(function(i){$(this).children('li').each(function(ii){var rateInfo=$cal.data.Units[i].R[ii],rate=$cal.getRateValue(rateInfo),css=$cal.getRateElCss(rateInfo,rate);$(this).children("span").html(rate).removeClass().addClass(css);});});};this.showProgress=function(film){var f=film?'div.calendarLoadFull':'div.calendarLoad';$(f).fadeIn('slow');};this.hideProgress=function(){$('div.calendarLoadFull,div.calendarLoad:visible').fadeOut('slow');};this.loadDateData=function(dates,prepend,clear){var datesList=$('div.datesRow ul');if(clear){datesList.empty();}
for(iDt=0;iDt<dates.length;iDt++){var date=dates[iDt];var newDateEl=this.createDateEl(date);if(prepend){datesList.prepend(newDateEl);}else{datesList.append(newDateEl);}};var newWidth=clear?(dates.length*this.itemWidth):datesList.width()+(dates.length*this.itemWidth);datesList.width(newWidth);};this.getReversedArrayCopy=function(arr){var copy=new Array();if(arr){for(iItem=0;iItem<arr.length;iItem++){copy[iItem]=arr[iItem];}
copy.reverse();}
return copy;};this.setDisplayMonth=function(){var currentDate=this.getDatePickerDate(false);if(currentDate!=null&&currentDate!=""){$('.currentMonth').html(MonthNames[new Date(currentDate).getMonth()]+" "+new Date(currentDate).getFullYear())}}
this.processData=function(response){this.RateTooltip.unmonitor();var unit=null;var unitIndex=-1;switch(this.loadOption){case 0:var dates=this.getReversedArrayCopy(response.Dates);this.data.Dates=$.merge(response.Dates,this.data.Dates);this.loadDateData(dates,true,false);var rateRows=$('div.ratesRow');for(iBUnit=0;iBUnit<response.Units.length;iBUnit++){unit=response.Units[iBUnit];unitIndex=this.indexOfUnit(unit.ID);var rates=this.getReversedArrayCopy(response.Units[iBUnit].R);this.data.Units[unitIndex].R=$.merge(unit.R,this.data.Units[unitIndex].R);this.data.Units[unitIndex].P=$.merge(unit.P,this.data.Units[unitIndex].P);this.data.Units[unitIndex].S=$.merge(unit.S,this.data.Units[unitIndex].S);this.data.Units[unitIndex].U=$.merge(unit.U,this.data.Units[unitIndex].U);this.data.Units[unitIndex].FR=$.merge(unit.FR,this.data.Units[unitIndex].FR);this.data.Units[unitIndex].SC=$.merge(unit.SC,this.data.Units[unitIndex].SC);var rateList=rateRows.eq(iBUnit).children('ul');for(iBRate=0;iBRate<rates.length;iBRate++){rateList.prepend(this.createRateEl(rates[iBRate]));}
newWidth=rateList.width()+(rates.length*this.itemWidth);rateList.width(newWidth);}
var dt=this.getDatePickerDate(false);this.index=this.indexOfDate(dt);this.scroll(this.index,1);break;case 1:this.data=response;if(!this.init){this.loadDateData(this.data.Dates,false,true);var rateRows=$('div.ratesRow');for(iSUnit=0;iSUnit<this.data.Units.length;iSUnit++){unit=this.data.Units[iSUnit];unitIndex=this.indexOfUnit(unit.ID);var rates=this.data.Units[unitIndex].R;var rateList=rateRows.eq(iSUnit).children('ul').empty();for(iSRate=0;iSRate<rates.length;iSRate++){rateList.append(this.createRateEl(rates[iSRate]));}
rateList.width(rates.length*this.itemWidth);}
var dt=this.getDatePickerDate(false);this.index=this.indexOfDate(dt);this.scrollToDate(dt);}else{this.setRateTypes();}
this.init=false;break;case 2:$.merge(this.data.Dates,response.Dates);this.loadDateData(response.Dates,false,false);var rateRows=$('div.ratesRow');for(iFUnit=0;iFUnit<response.Units.length;iFUnit++){unit=response.Units[iFUnit];unitIndex=this.indexOfUnit(unit.ID);$.merge(this.data.Units[unitIndex].R,unit.R);$.merge(this.data.Units[unitIndex].P,unit.P);$.merge(this.data.Units[unitIndex].S,unit.S);$.merge(this.data.Units[unitIndex].U,unit.U);$.merge(this.data.Units[unitIndex].FR,unit.FR);$.merge(this.data.Units[unitIndex].SC,unit.SC);var rates=response.Units[unitIndex].R;var rateList=rateRows.eq(iFUnit).children('ul');for(iFRate=0;iFRate<rates.length;iFRate++){rateList.append(this.createRateEl(rates[iFRate]));}
newWidth=rateList.width()+(rates.length*this.itemWidth);rateList.width(newWidth);}
var dt=this.getDatePickerDate(false);this.index=this.indexOfDate(dt);this.scroll(this.index);break;}
this.navEnabled=true;this.hideProgress();this.init=false;this.haveEarliest=this.data.Dates[1].X;this.RateTooltip.monitor();this.RateTooltip.init();};this.getData=function(d){var date=d;if(this.data!=null){switch(this.loadOption){case 0:date=this.data.Dates[0].V;break;case 2:date=this.data.Dates[this.data.Dates.length-1].V;break;}}
$.getJSON('/lib/hbef/realtime/Calendar.ashx',{'SPID':$cal_spid,'DATE':date,'DAYS':$cal_totalDays,"LOADOPTION":this.loadOption}).success(function(d,s,xhr){$cal.processData(d);}).error(function(){$cal.navEnabled=true;$cal.hideProgress();});};this.onNext=function(){this.onMove(this.index+this.step);};this.onPrev=function(){if(this.index>1){var idx=this.index-this.step;idx=this.haveEarliest&&idx<1?1:idx;this.onMove(idx);}};this.onMove=function(toIndex){if(!this.navEnabled){return;}
this.motion=toIndex>this.index?2:0;this.index=toIndex;this.selectingDate=false;this.setDatePickerDate(new Date(this.data.Dates[this.index].V));this.scroll(this.index);};this.getUrlDate=function(dt){var m=dt.getMonth()+1;m=m<10?"0"+m:m;var d=dt.getDate();d=d<10?"0"+d:d;return dt.getFullYear()+"/"+m+"/"+d;};this.getBookNowUrl=function(unit,dt){return "#";};this.getRequestQuoteUrl=function(unit,dt){if($("#FullGoUrl").val()!=undefined&&$("#FullGoUrl").val()!=""){return $("#FullGoUrl").val()+"RequestQuote"+this.getUrlOptions(unit,dt);}
var url=window.location.href;url=url.toLowerCase();var fullGoUrl=$("#FullGoUrl").val();var pathArray=url.split('/');var flag=false;var nextIndex=-1;$.each(pathArray,function(index,value){if(value=="go"){flag=true;nextIndex=index+1;}
if(flag&&index==nextIndex){fullGoUrl=value.replace("/","");flag=false;}});return fullGoUrl+"/"+"RequestQuote"+this.getUrlOptions(unit,dt);};this.getUrlOptions=function(unit,dt){var date=null;var dateIndex=-1;var nights=1;if(dt){date=dt;dateIndex=this.indexOfDate(dt.V);}else{dateIndex=this.indexOfDate(this.getDatePickerDate(false));if(dateIndex==-1){dateIndex=1;}
date=this.data.Dates[dateIndex];}
if(unit){var pps=unit.R[dateIndex];nights=pps.I>0?pps.I:1;}
var opt="?spid="+$cal_spid+"&nights="+nights+"&arrive="+this.getUrlDate(new Date(date.V));if(unit){opt+="&auids="+unit.ID;}
return opt;};this.getDayName=function(format,dayOfWeek){var dayName="";switch(format){case "ddd":dayName=this.daysShort[dayOfWeek];break;case "dddd":dayName=this.days[dayOfWeek];break;}
return dayName;};};function RealtimeCalendarUnitTT(){this.activeUnit=null;this.isHovering=false;this.hideTimer=-1;this.showTimer=-1;this.monitorHover=function(){var calTT=this;this.activeUnit.closest(".unitDiv").find("div.ttContent").hover(function(){calTT.isHovering=true;},function(){calTT.isHovering=false;calTT.startHide();});};this.startShow=function(){var calTT=this;this.showTimer=setTimeout(function(){if(calTT&&calTT.activeUnit&&calTT.activeUnit.isHovering){calTT.show();}},400);};this.show=function(){var unitDiv=this.activeUnit.closest(".unitDiv");var unitIndex=unitDiv.closest("div.unitRow").index();var unit=$cal.data.Units[unitIndex];var bookNowLink=unitDiv.find(".uTTBN");if(bookNowLink){bookNowLink.attr("href",$cal.getBookNowUrl(unit));}
unitDiv.find(".uTTRQ").attr("href",$cal.getRequestQuoteUrl(unit));this.activeUnit.css({backgroundColor:'#E0F3FF'});var tt=unitDiv.children(".unitTT");var position={top:(tt.height()+3)*-1,left:5};tt.css({left:position.left+"px",top:position.top+"px"});tt.fadeIn(400);};this.startHide=function(){var calTT=this;this.hideTimer=setTimeout(function(){calTT.hide();},150);};this.hide=function(){if(!this.isHovering&&this.activeUnit!=null){this.activeUnit.closest(".unitDiv").children(".unitTT").fadeOut(200);this.activeUnit.css({backgroundColor:''});this.activeUnit=null;this.isHovering=false;}};this.monitor=function(){$("div.unitInfo").hover(function(){if($cal_showUnitDesc){var unit=$(this);unit.isHovering=true;if($cal.UnitTooltips.activeUnit!=null){clearTimeout($cal.UnitTooltips.showTimer);clearTimeout($cal.UnitTooltips.hideTimer);$cal.UnitTooltips.hide();}
$cal.UnitTooltips.activeUnit=unit;$cal.UnitTooltips.startShow();$cal.UnitTooltips.monitorHover();}},function(){if($cal_showUnitDesc){$(this).isHovering=false;$cal.UnitTooltips.startHide();}});};};function RealtimeCalendarRateTT(){this.tt=null;this.head=null;this.body=null;this.date=null;this.items=null;this.links=null;this.minStay=null;this.isVisible=false;this.isHovering=false;this.activeRate=null;this.activeUnitIndex=-1;this.activeRateIndex=-1;this.coords={left:0,top:0};this.hideTimer=-1;this.showTimer=-1;this.showLinks=true;this.setPosition=function(){var topPos=this.coords.top-this.tt.height();this.tt.offset({left:this.coords.left-75,top:topPos-8});};this.init=function(){this.tt=$("#rateTT");this.tt.hover(function(){$cal.RateTooltip.isHovering=true;},function(){$cal.RateTooltip.isHovering=false;$cal.RateTooltip.startHide();});this.head=this.tt.find("div.head");this.date=this.tt.find("#rateTTDate");this.items=this.tt.find("#rateTTRates ul");this.links=this.tt.find("div.bnrq");this.body=this.tt.find("#rateTTRates");this.minStay=this.tt.find("ul.minStay");this.minStay.valueEl=this.minStay.children(":nth-child(2)");this.showLinks=$cal_showRTTLinks;};this.startShow=function(){var rTT=this;this.showTimer=setTimeout(function(){if(rTT&&rTT.rateHover()){rTT.show();}},300);};this.show=function(){clearTimeout(this.hideTimer);clearTimeout(this.showTimer);this.activeRateIndex=this.activeRate.closest("li").index();this.activeUnitIndex=this.activeRate.closest("div.unitRow").index();var rateInfo=$cal.getUnitRatesXSection(this.activeUnitIndex,this.activeRateIndex);if(rateInfo.P=="&nbsp;"&&rateInfo.S=="&nbsp;"&&rateInfo.U=="&nbsp;"&&rateInfo.FR=="&nbsp;"&&rateInfo.SC=="&nbsp;")
{this.hideInternal();return;}
if(rateInfo.Q){this.head.html("ON REQUEST");this.head.removeClass("rateHeadUnAv");this.head.addClass("rateHeadRq");if(this.showLinks){this.links.show();}else{this.links.hide();}}else{this.head.html("NOT AVAILABLE");this.head.removeClass("rateHeadRq");this.head.addClass("rateHeadUnAv");this.tt.find("div.bnrq").hide();}
if(rateInfo.I>0){this.minStay.show();var nights=rateInfo.I>1?" Nights":" Night";this.minStay.valueEl.html(rateInfo.I+nights);}else{this.minStay.hide();}
var dt=$cal.data.Dates[this.activeRateIndex];this.date.html($cal.getDayName("dddd",dt.B)+" "+dt.A+dt.O+" "+$cal.months[dt.M]);var unit=$cal.data.Units[this.activeUnitIndex];if(this.showLinks){var bookNowLink=this.tt.find(".uTTBN");if(bookNowLink){bookNowLink.attr("href",$cal.getBookNowUrl(unit,dt));}
this.tt.find(".uTTRQ").attr("href",$cal.getRequestQuoteUrl(unit,dt));}
var rates=new Array("S","P","U","FR","SC");for(i=0;i<=4;i++){var rateVal=eval("rateInfo."+rates[i]);if(rateVal!='&nbsp;'){var rateType=rates[i];this.items.eq(i).children("li:nth-child(2)").html(rateVal);this.items.eq(i).show();}else{this.items.eq(i).hide();}}
if(!this.isVisible){this.isVisible=true;this.tt.fadeIn(300);}
this.setPosition();};this.startHide=function(){var rTT=this;this.hideTimer=setTimeout(function(){rTT.hide();},150);};this.hide=function(){if(!this.isHovering&&!this.rateHover()){this.hideInternal();}};this.hideInternal=function(){clearTimeout(this.hideTimer);clearTimeout(this.showTimer);this.tt.fadeOut(50);this.activeRate=null;this.isVisible=false;};this.rateHover=function(){return this.activeRate!=null&&this.activeRate.data("isHovering")===true;};this.unmonitor=function(){var rates=$("div.ratesRow li span");rates.off("hover");};this.monitor=function(){$("div.ratesRow li span").hover(function(e){var rate=$(this);rate.data("isHovering",true);var ratePos=rate.offset();$cal.RateTooltip.coords.left=ratePos.left;$cal.RateTooltip.coords.top=ratePos.top;$cal.RateTooltip.activeRate=rate;if($cal.RateTooltip.isVisible){$cal.RateTooltip.show();}else{$cal.RateTooltip.startShow();}},function(){var rate=$(this);rate.data("isHovering",false);$cal.RateTooltip.startHide();});};};$(function(){if($(".roomsRatesCalendar").length>0){realtimecalendaryui.init();}});function _picker(){return $("#datePicker");}
var sn=sn||{};sn.ui=sn.ui||{generateUUID:function(){var d=new Date().getTime();if(typeof performance!=='undefined'&&typeof performance.now==='function'){d+=performance.now();}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c){var r=(d+Math.random()*16)%16|0;d=Math.floor(d/16);return(c==='x'?r:(r&0x3|0x8)).toString(16);});}};var PaxPickerData=(function(){function PaxPickerData(){this.adults=2;this.band1min=-1;this.band1max=-1;this.children1=0;this.band2min=-1;this.band2max=-1;this.children2=0;this.band3min=-1;this.band3max=-1;this.children3=0;this.maxPax=0;this.maxAdults=0;this.maxChildren=0;this.baseId="";}
PaxPickerData.prototype.init=function(){if(this.adults>this.maxAdults){this.adults=this.maxAdults;}};PaxPickerData.prototype.loadFromObj=function(object){if(object.adults!=null)
this.adults=object.adults;if(object.band1min!=null)
this.band1min=object.band1min;if(object.band1max!=null)
this.band1max=object.band1max;if(object.children1!=null)
this.children1=object.children1;if(object.band2min!=null)
this.band2min=object.band2min;if(object.band2max!=null)
this.band2max=object.band2max;if(object.children2!=null)
this.children2=object.children2;if(object.band3min!=null)
this.band3min=object.band3min;if(object.band3max!=null)
this.band3max=object.band3max;if(object.children3!=null)
this.children3=object.children3;if(object.maxPax!=null)
this.maxPax=object.maxPax;if(object.maxAdults!=null)
this.maxAdults=object.maxAdults;if(object.maxChildren!=null)
this.maxChildren=object.maxChildren;if(object.baseId!=null)
this.baseId=object.baseId;};PaxPickerData.prototype.applyLimits=function(object){if(object.band1min!=null)
this.band1min=object.band1min;if(object.band1max!=null)
this.band1max=object.band1max;if(object.band2min!=null)
this.band2min=object.band2min;if(object.band2max!=null)
this.band2max=object.band2max;if(object.band3min!=null)
this.band3min=object.band3min;if(object.band3max!=null)
this.band3max=object.band3max;if(object.maxPax!=null)
this.maxPax=object.maxPax;if(object.maxAdults!=null)
this.maxAdults=object.maxAdults;if(object.maxChildren!=null)
this.maxChildren=object.maxChildren;};PaxPickerData.prototype.getDisplayString=function(){var output="";if(this.adults>1){output=output+this.adults+" Adults";}
else{output=output+this.adults+" Adult";}
var kids=+this.children1;kids=kids+ +this.children2;kids=kids+ +this.children3;if(kids>1){output=output+", "+kids+" Children";}
else if(kids>0){output=output+", "+kids+" Child";}
return output;};PaxPickerData.prototype.getValidation=function(){if(this.maxAdults>0&&this.adults>this.maxAdults){return "Too many adults, max is "+this.maxAdults;}
var kids=+this.children1;kids=kids+ +this.children2;kids=kids+ +this.children3;if(this.maxChildren>0&&kids>this.maxChildren){return "Too many children, max is "+this.maxChildren;}
var pax=+kids;pax=pax+ +this.adults;if(this.maxPax>0&&pax>this.maxPax){return "Too many people, max is "+this.maxPax;}
return "";};PaxPickerData.prototype.getContainerControlId=function(){return this.baseId+"_pax_picker_container";};PaxPickerData.prototype.getAdultControlId=function(){return this.baseId+"_pax_picker_adult";};PaxPickerData.prototype.getChild1ControlId=function(){return this.baseId+"_pax_picker_child1";};PaxPickerData.prototype.getChild2ControlId=function(){return this.baseId+"_pax_picker_child2";};PaxPickerData.prototype.getChild3ControlId=function(){return this.baseId+"_pax_picker_child3";};PaxPickerData.prototype.getInputLayerControlId=function(){return this.baseId+"_pax_picker_inputlayer";};PaxPickerData.prototype.getBand1Label=function(){return "Ages "+this.band1min+" - "+this.band1max;};PaxPickerData.prototype.getBand2Label=function(){return "Ages "+this.band2min+" - "+this.band2max;};PaxPickerData.prototype.getBand3Label=function(){return "Ages "+this.band3min+" - "+this.band3max;};return PaxPickerData;}());$.fn.paxpicker=function(options){this.addClass("ui-paxpicker-input");var settings=$.extend({adults:2,band1min:-1,band1max:-1,children1:0,band2min:-1,band2max:-1,children2:0,band3min:-1,band3max:-1,children3:0,maxPax:0,maxAdults:0,maxChildren:0},options);var data=new PaxPickerData();data.loadFromObj(settings);data.baseId=this[0].id;this.val(JSON.stringify(data));var container=$(document.createElement('div'));container.attr("id",data.getContainerControlId());container.addClass("ui-paxpicker-container");this.after(container);var inputctrl=$(this).detach();inputctrl.bind("cancel",function(event){if(options.cancel!=null){options.cancel.call();}});inputctrl.bind("apply",function(event){if(options.apply!=null){options.apply.call();}});container.append(inputctrl);var displaylayer=$(document.createElement('div'));displaylayer.addClass("ui-paxpicker-display-container");displaylayer.width(this.width());displaylayer.height(this.height());var displayspan=$(document.createElement('span'));displayspan.height(displaylayer.height());displayspan.width(displaylayer.width()-displaylayer.height());displayspan.addClass("ui-paxpicker-display");displayspan.html(data.getDisplayString());displaylayer.append(displayspan);var arrowspan=$(document.createElement('span'));arrowspan.addClass("ui-paxpicker-arrow");arrowspan.addClass("icon-down-open");arrowspan.height(displaylayer.height());arrowspan.width(displaylayer.height());arrowspan.html("");displaylayer.append(arrowspan);displaylayer.click(function(){var container=$(this).closest(".ui-paxpicker-container");container.find(".ui-paxpicker-input-container").slideToggle(100);});container.append(displaylayer);var inputlayer=$(document.createElement('div'));inputlayer.attr("id",data.getInputLayerControlId());inputlayer.addClass("ui-paxpicker-input-container");inputlayer.width(270);inputlayer.height(100);inputlayer.css("top",displaylayer.position().top+displaylayer.height()+displaylayer.css("padding-top")+displaylayer.css("padding-bottom"));if(data.maxAdults>0){var adultRow=$(document.createElement('div'));adultRow.addClass("ui-paxpicker-inputrow");adultRow.width(inputlayer.width());adultRow.height(50);var adultLabel=$(document.createElement('span'));adultLabel.addClass("ui-paxpicker-inputmainlabel");adultLabel.html("Adults");adultRow.append(adultLabel);var adultInputSpan=$(document.createElement('span'));adultInputSpan.addClass("ui-paxpicker-inputspan");var adultInput=$(document.createElement('input'));adultInput.addClass("ui-paxpicker-inputspinner");adultInput.attr("readonly","true");adultInput.val(data.adults);adultInput.attr("id",data.getAdultControlId());adultInputSpan.append(adultInput);adultRow.append(adultInputSpan);inputlayer.append(adultRow);}
if(data.band1min>-1&&data.band1max>-1){inputlayer.height(inputlayer.height()+50);var child1Row=$(document.createElement('div'));child1Row.addClass("ui-paxpicker-inputrow");child1Row.width(inputlayer.width());child1Row.height(50);var child1Label=$(document.createElement('span'));child1Label.addClass("ui-paxpicker-inputmainlabel");child1Label.html("Children");child1Row.append(child1Label);var child1InputSpan=$(document.createElement('span'));child1InputSpan.addClass("ui-paxpicker-inputspan");var child1Input=$(document.createElement('input'));child1Input.addClass("ui-paxpicker-inputspinner");child1Input.attr("readonly","true");child1Input.val(data.children1);child1Input.attr("id",data.getChild1ControlId());child1InputSpan.append(child1Input);child1Row.append(child1InputSpan);var child1AgeLabel=$(document.createElement('span'));child1AgeLabel.addClass("ui-paxpicker-inputsublabel");child1AgeLabel.html(data.getBand1Label());child1Row.append(child1AgeLabel);inputlayer.append(child1Row);}
if(data.band2min>-1&&data.band2max>-1){inputlayer.height(inputlayer.height()+50);var child2Row=$(document.createElement('div'));child2Row.addClass("ui-paxpicker-inputrow");child2Row.width(inputlayer.width());child2Row.height(50);var child2Label=$(document.createElement('span'));child2Label.addClass("ui-paxpicker-inputmainlabel");child2Label.html("Children");child2Row.append(child2Label);var child2InputSpan=$(document.createElement('span'));child2InputSpan.addClass("ui-paxpicker-inputspan");var child2Input=$(document.createElement('input'));child2Input.addClass("ui-paxpicker-inputspinner");child2Input.attr("readonly","true");child2Input.val(data.children2);child2Input.attr("id",data.getChild2ControlId());child2InputSpan.append(child2Input);child2Row.append(child2InputSpan);var child2AgeLabel=$(document.createElement('span'));child2AgeLabel.addClass("ui-paxpicker-inputsublabel");child2AgeLabel.html(data.getBand2Label());child2Row.append(child2AgeLabel);inputlayer.append(child2Row);}
if(data.band3min>-1&&data.band3max>-1){inputlayer.height(inputlayer.height()+50);var child3Row=$(document.createElement('div'));child3Row.addClass("ui-paxpicker-inputrow");child3Row.width(inputlayer.width());child3Row.height(50);var child3Label=$(document.createElement('span'));child3Label.addClass("ui-paxpicker-inputmainlabel");child3Label.html("Children");child3Row.append(child3Label);var child3InputSpan=$(document.createElement('span'));child3InputSpan.addClass("ui-paxpicker-inputspan");var child3Input=$(document.createElement('input'));child3Input.addClass("ui-paxpicker-inputspinner");child3Input.attr("readonly","true");child3Input.val(data.children3);child3Input.attr("id",data.getChild3ControlId());child3InputSpan.append(child3Input);child3Row.append(child3InputSpan);var child3AgeLabel=$(document.createElement('span'));child3AgeLabel.addClass("ui-paxpicker-inputsublabel");child3AgeLabel.html(data.getBand3Label());child3Row.append(child3AgeLabel);inputlayer.append(child3Row);}
var validationrow=$(document.createElement('div'));validationrow.addClass("ui-paxpicker-validationrow");validationrow.width(inputlayer.width());validationrow.height(25);var validationspan=$(document.createElement('span'));validationspan.addClass("ui-paxpicker-validation");validationspan.html("&nbsp;");validationrow.append(validationspan);inputlayer.append(validationrow);var actionrow=$(document.createElement('div'));actionrow.addClass("ui-paxpicker-actionrow");actionrow.width(inputlayer.width());actionrow.height(40);var cancellink=$(document.createElement('a'));cancellink.addClass("ui-paxpicker-actionlink");cancellink.addClass("ui-paxpicker-actioncancel");cancellink.html("Cancel");actionrow.append(cancellink);cancellink.on("click",function(){var container=$(this).closest(".ui-paxpicker-container");sn.ui.paxpicker.reset(container);container.find(".ui-paxpicker-input-container").slideToggle(100);inputctrl.trigger("cancel");});var applylink=$(document.createElement('a'));applylink.addClass("ui-paxpicker-actionlink");applylink.addClass("ui-paxpicker-actionapply");applylink.html("Apply");applylink.click(function(){var container=$(this).closest(".ui-paxpicker-container");var inputctrl=container.find(".ui-paxpicker-input");var currentData=JSON.parse(inputctrl.val());var newData=new PaxPickerData();newData.loadFromObj(currentData);newData.adults=$(this).closest(".ui-paxpicker-container").find("#"+newData.getAdultControlId()).val();newData.children1=$(this).closest(".ui-paxpicker-container").find("#"+newData.getChild1ControlId()).val();newData.children2=$(this).closest(".ui-paxpicker-container").find("#"+newData.getChild2ControlId()).val();newData.children3=$(this).closest(".ui-paxpicker-container").find("#"+newData.getChild3ControlId()).val();var validation=newData.getValidation();if(validation.length==0){var jsonData=JSON.stringify(newData);container.find(".ui-paxpicker-input").val(jsonData);container.find(".ui-paxpicker-display").html(newData.getDisplayString());container.find(".ui-paxpicker-input-container").slideToggle(100);inputctrl.trigger("apply");container.find(".ui-paxpicker-validation").html("&nbsp;");}
else{var validspan=container.find(".ui-paxpicker-validation");validspan.html(validation);}});actionrow.append(applylink);inputlayer.append(actionrow);inputlayer.hide();container.append(inputlayer);$('html').click(function(e){if(e.target.id==data.getContainerControlId())
return;if($(e.target).closest("#"+data.getContainerControlId()).length)
return;if($("#"+data.getInputLayerControlId()).is(":visible")){$("#"+data.getInputLayerControlId()).slideToggle(100);}});if(data.maxAdults>0){adultInput.spinner({min:1,max:data.maxAdults});}
if(data.band1min>-1&&data.band1max>-1){child1Input.spinner({min:0,max:data.maxChildren});}
if(data.band2min>-1&&data.band2max>-1){child2Input.spinner({min:0,max:data.maxChildren});}
if(data.band3min>-1&&data.band3max>-1){child3Input.spinner({min:0,max:data.maxChildren});}};sn.ui.paxpicker=sn.ui.paxpicker||{reset:function(container){var inputctrl=container.find(".ui-paxpicker-input");var currentData=JSON.parse(inputctrl.val());var newData=new PaxPickerData();newData.loadFromObj(currentData);container.find("#"+newData.getAdultControlId()).val(currentData.adults);container.find("#"+newData.getChild1ControlId()).val(currentData.children1);container.find("#"+newData.getChild2ControlId()).val(currentData.children2);container.find("#"+newData.getChild3ControlId()).val(currentData.children3);container.find(".ui-paxpicker-validation").html("&nbsp;");},toggle:function(container){$(container.find(".ui-paxpicker-input-container")).slideToggle(100);},show:function(container){var inputctrl=$(container).find(".ui-paxpicker-input-container");if(!inputctrl.is(":visible")){inputctrl.slideToggle(100);}},hide:function(container){var inputctrl=$(container).find(".ui-paxpicker-input-container");if(inputctrl.is(":visible")){inputctrl.slideToggle(100);}}};var RoomPickerData=(function(){function RoomPickerData(){this.roomNumber=0;this.roomName="";this.pax=new PaxPickerData();this.mealPlan="";this.mealPlanOptions={};this.alternateRow=false;this.baseId="";}
RoomPickerData.prototype.loadFromObj=function(object){if(object.roomName!=null)
this.roomName=object.roomName;if(object.roomNumber!=null)
this.roomNumber=object.roomNumber;if(object.pax!=null)
this.pax.loadFromObj(object.pax);if(object.mealPlan!=null)
this.mealPlan=object.mealPlan;if(object.mealPlanOptions!=null)
this.mealPlanOptions=object.mealPlanOptions;if(object.alternateRow!=null)
this.alternateRow=object.alternateRow;if(object.baseId!=null)
this.baseId=object.baseId;};RoomPickerData.prototype.getContainerControlId=function(){return this.baseId+"_room_picker_container";};RoomPickerData.prototype.getInputPaxControlId=function(){return this.baseId+"_room_picker_paxinput";};RoomPickerData.prototype.getInputMealsControlId=function(){return this.baseId+"_room_picker_mealsinput";};return RoomPickerData;}());$.fn.roompicker=function(options){this.addClass("ui-roompicker-input");var settings=$.extend({action:"init",roomName:"",roomNumber:0,pax:{adults:2,band1min:-1,band1max:-1,children1:0,band2min:-1,band2max:-1,children2:0,band3min:-1,band3max:-1,children3:0,maxPax:0,maxAdults:0,maxChildren:0},mealPlan:"",mealPlanOptions:{},alternateRow:false},options);if(settings.action=="init"){var data_1=new RoomPickerData();data_1.roomName=settings.roomName;data_1.roomNumber=settings.roomNumber;data_1.pax.loadFromObj(settings.pax);data_1.mealPlan=settings.mealPlan;data_1.mealPlanOptions=settings.mealPlanOptions;data_1.alternateRow=settings.alternateRow;data_1.baseId=this[0].id;$(this).val(JSON.stringify(data_1));var container=$(document.createElement('div'));container.attr("id",data_1.getContainerControlId());container.addClass("ui-roompicker-container");this.after(container);var inputctrl=$(this).detach();inputctrl.bind("remove",function(){if(options.remove!=null){options.remove.call();}});inputctrl.bind("paxchange",function(){if(options.paxchange!=null){options.paxchange.call();}});inputctrl.bind("mealchange",function(){if(options.mealchange!=null){options.mealchange.call();}});inputctrl.bind("change",function(){if(options.change!=null){options.change.call();}});container.append(inputctrl);var displayarea=$(document.createElement('div'));displayarea.addClass("ui-roompicker-displayarea");displayarea.addClass("ui-roompicker-primary");if(data_1.alternateRow){displayarea.addClass("ui-roompicker-alternative");}
var roomlabel=$(document.createElement('div'));roomlabel.addClass("ui-roompicker-roomlabel");var roomtext=$(document.createElement('span'));roomtext.addClass("ui-roompicker-roomtext");roomtext.html(data_1.roomName);roomlabel.append(roomtext);displayarea.append(roomlabel);var removecontainer=$(document.createElement('div'));removecontainer.addClass("ui-roompicker-removecontainer");var removelink=$(document.createElement('a'));removelink.addClass("ui-roompicker-removelink");removelink.html("Remove this room X");removelink.on("click",function(){var container=$(this).closest(".ui-roompicker-container");var inputctrl=container.find(".ui-roompicker-input");container.slideToggle(100);setTimeout(function(){container.remove();inputctrl.trigger("remove");},100);});removecontainer.append(removelink);displayarea.append(removecontainer);var cleardiv=$(document.createElement('div'));cleardiv.addClass("ui-roompicker-cleardiv");displayarea.append(cleardiv);var guestsandmeals=$(document.createElement('div'));guestsandmeals.addClass("ui-roompicker-guestsmeals");var guestslabel=$(document.createElement('div'));guestslabel.addClass("ui-roompicker-guestslabel");guestslabel.html("Guests");guestsandmeals.append(guestslabel);var inputdiv=$(document.createElement('div'));inputdiv.addClass("ui-roompicker-paxdiv");var inputpax=$(document.createElement('input'));inputpax.width(282);inputpax.attr("id",data_1.getInputPaxControlId());inputdiv.append(inputpax);guestsandmeals.append(inputdiv);if(Object.keys(data_1.mealPlanOptions).length>0){var mealslabel=$(document.createElement('div'));mealslabel.addClass("ui-roompicker-mealslabel");mealslabel.html("Meal Plan");guestsandmeals.append(mealslabel);var mealsdiv=$(document.createElement('div'));mealsdiv.addClass("ui-roompicker-mealsdiv");var mealsdivlabel=$(document.createElement('label'));var mealsinput=$(document.createElement('select'));mealsinput.width(inputpax.width());mealsinput.addClass("ui-roompicker-mealsinput");mealsinput.attr("id",data_1.getInputMealsControlId());for(var key in data_1.mealPlanOptions){var option=document.createElement('option');option.value=key;option.text=data_1.mealPlanOptions[key];if(key==data_1.mealPlan){option.selected=true;}
mealsinput.append(option);}
mealsinput.on("change",function(){var container=$(this).closest(".ui-roompicker-container");var inputctrl=container.find(".ui-roompicker-input");var currentData=JSON.parse(inputctrl.val());var newData=new RoomPickerData();newData.loadFromObj(currentData);newData.mealPlan=$(this).val();inputctrl.val(JSON.stringify(newData));inputctrl.trigger("mealchange");inputctrl.trigger("change");});mealsdivlabel.append(mealsinput);mealsdiv.append(mealsdivlabel);guestsandmeals.append(mealsdiv);}
displayarea.append(guestsandmeals);container.append(displayarea);var paxsettings=$.extend({apply:function(){var container=$("#"+data_1.getContainerControlId());var inputctrl=container.find(".ui-roompicker-input");var currentData=JSON.parse(inputctrl.val());var newData=new RoomPickerData();newData.loadFromObj(currentData);var newPaxData=JSON.parse($("#"+newData.getInputPaxControlId()).val());newData.pax.loadFromObj(newPaxData);newData.mealPlan=$("#"+newData.getInputMealsControlId()).val();inputctrl.val(JSON.stringify(newData));inputctrl.trigger("paxchange");inputctrl.trigger("change");}},settings.pax);inputpax.paxpicker(paxsettings);}
else if(settings.action=="toggle"){var container=$(this).closest(".ui-roompicker-container");var inputctrl=container.find(".ui-roompicker-input");var currentData=JSON.parse(inputctrl.val());var newData=new RoomPickerData();newData.loadFromObj(currentData);if(settings.roomName!=""){newData.roomName=settings.roomName;var roomtext=container.find(".ui-roompicker-roomtext");roomtext.html(settings.roomName);}
if(settings.roomNumber!=0){newData.roomNumber=settings.roomNumber;}
if(newData.alternateRow){newData.alternateRow=!newData.alternateRow;}
inputctrl.val(JSON.stringify(newData));var displayarea=container.find(".ui-roompicker-displayarea");if(displayarea.hasClass("ui-roompicker-alternative")){displayarea.removeClass("ui-roompicker-alternative",100);}
else{displayarea.addClass("ui-roompicker-alternative",100);}}};sn.ui.roompicker=sn.ui.roompicker||{};var RoomTypePickerData=(function(){function RoomTypePickerData(){this.label="How many rooms would you like to book?";this.maxRooms=-1;this.numRooms=0;this.rooms={};this.defaultMealPlan="";this.mealPlanOptions={};this.paxOptions=new PaxPickerData();this.baseId="";}
RoomTypePickerData.prototype.loadFromObj=function(object){if(object.baseId!=null)
this.baseId=object.baseId;if(object.label!=null)
this.label=object.label;if(object.maxRooms!=null)
this.maxRooms=object.maxRooms;if(object.rooms!=null)
this.rooms=object.rooms;this.numRooms=Object.keys(this.rooms).length;if(object.defaultMealPlan!=null)
this.defaultMealPlan=object.defaultMealPlan;if(object.mealPlanOptions!=null)
this.mealPlanOptions=object.mealPlanOptions;if(object.paxOptions!=null)
this.paxOptions=object.paxOptions;};RoomTypePickerData.prototype.getContainerControlId=function(){return this.baseId+"_roomtype_picker_container";};RoomTypePickerData.prototype.getRoomCounterControlId=function(){return this.baseId+"_room_picker_roomcounter";};RoomTypePickerData.prototype.getRoomInputBaseId=function(){return this.baseId+"_room_roompicker_";};return RoomTypePickerData;}());$.fn.roomtypepicker=function(options){$(this).addClass("ui-roomtypepicker-input");var settings=$.extend({label:"How many rooms would you like to book?",maxRooms:-1,rooms:{},mealPlanOptions:{},defaultMealPlan:"",paxOptions:{adults:2,band1min:-1,band1max:-1,children1:0,band2min:-1,band2max:-1,children2:0,band3min:-1,band3max:-1,children3:0,maxPax:0,maxAdults:0,maxChildren:0}},options);var data=new RoomTypePickerData();data.baseId=this[0].id;data.loadFromObj(settings);$(this).val(JSON.stringify(data));var container=$(document.createElement('div'));container.attr("id",data.getContainerControlId());container.addClass("ui-roomtypepicker-container");$(this).after(container);var inputctrl=$(this).detach();inputctrl.bind("change",function(){if(options.change!==undefined){options.change.call();}});inputctrl.on("changeroom",function(event,roomtype,roomkey,roomjson){if(options.changeroom!==undefined&&roomkey){options.changeroom.call(this,roomtype,roomkey,roomjson);}});inputctrl.on("addroom",function(event,roomtype,roomkey,roomjson){if(options.addroom!==undefined&&roomkey){options.addroom.call(this,roomtype,roomkey,roomjson);}});inputctrl.on("removeroom",function(event,roomtype,roomkey){if(options.removeroom!==undefined&&roomkey){options.removeroom.call(this,roomtype,roomkey);}});container.append(inputctrl);var displayarea=$(document.createElement('div'));displayarea.addClass("ui-roomtypepicker-displayarea");var numroomsdiv=$(document.createElement('div'));numroomsdiv.addClass("ui-roomtypepicker-numrooms");if(data.label!=""){var numroomslabel=$(document.createElement('div'));numroomslabel.addClass("ui-roomtypepicker-label");numroomslabel.html(data.label);numroomsdiv.append(numroomslabel);}
var numroomsinput=$(document.createElement('input'));numroomsinput.attr("readonly","true");numroomsinput.attr("id",data.getRoomCounterControlId());numroomsinput.val(data.numRooms);numroomsdiv.append(numroomsinput);displayarea.append(numroomsdiv);var roomsdiv=$(document.createElement('div'));roomsdiv.addClass("ui-roomtypepicker-rooms");if(Object.keys(data.rooms).length>0){var roomIdx=1;for(var key in data.rooms){data.rooms[key].roomNumber=roomIdx;data.rooms[key].roomName="Room "+roomIdx;data.rooms[key].alternateRow=roomIdx%2==0;var roominput=$(document.createElement('input'));roominput.attr("id",data.getRoomInputBaseId()+key);roomsdiv.append(roominput);roomIdx++;}}
displayarea.append(roomsdiv);container.append(displayarea);if(Object.keys(data.rooms).length>0){var _loop_1=function(key){roomSettings=$.extend({mealPlanOptions:data.mealPlanOptions,change:function(){sn.ui.roomtypepicker.handleChange(data.baseId,key);},remove:function(){setTimeout(function(){sn.ui.roomtypepicker.handleRemove(data.baseId);},1);}},data.rooms[key]);paxSettings=new PaxPickerData();paxSettings.loadFromObj(roomSettings.pax);paxSettings.applyLimits(data.paxOptions);roomSettings.pax=paxSettings;$("#"+data.getRoomInputBaseId()+key).roompicker(roomSettings);};var roomSettings,paxSettings;for(var key in data.rooms){_loop_1(key);}}
$(this).val(JSON.stringify(data));if(data.maxRooms>-1){numroomsinput.spinner({min:0,max:data.maxRooms,spin:function(event,ui){if($(event.currentTarget).hasClass("ui-spinner-down")){sn.ui.roomtypepicker.reduceRooms(data.baseId);}
else if($(event.currentTarget).hasClass("ui-spinner-up")){sn.ui.roomtypepicker.increaseRooms(data.baseId);}}});}
else{numroomsinput.spinner({min:0,spin:function(event,ui){if($(event.currentTarget).hasClass("ui-spinner-down")){sn.ui.roomtypepicker.reduceRooms(data.baseId);}
else if($(event.currentTarget).hasClass("ui-spinner-up")){sn.ui.roomtypepicker.increaseRooms(data.baseId);}}});}};sn.ui.roomtypepicker=sn.ui.roomtypepicker||{handleChange:function(baseId,roomkey){var inputctrl=$("#"+baseId);var container=inputctrl.closest(".ui-roomtypepicker-container");var currentData=JSON.parse(inputctrl.val());var data=new RoomTypePickerData();data.loadFromObj(currentData);var roomjson="";if(Object.keys(data.rooms).length>0){for(var key in data.rooms){var roominput=$("#"+data.getRoomInputBaseId()+key);var roomobj=new RoomPickerData();roomobj.loadFromObj(JSON.parse(roominput.val()));data.rooms[key]=roomobj;if(roomkey==key){roomjson=roominput.val();}}}
inputctrl.val(JSON.stringify(data));inputctrl.trigger("change");inputctrl.trigger("changeroom",[baseId,roomkey,roomjson]);},handleRemove:function(baseId){var inputctrl=$("#"+baseId);var container=inputctrl.closest(".ui-roomtypepicker-container");var currentData=JSON.parse(inputctrl.val());var data=new RoomTypePickerData();data.loadFromObj(currentData);var roomkey="";var idx=1;var found=false;if(Object.keys(data.rooms).length>0){for(var key in data.rooms){var roominput=$("#"+data.getRoomInputBaseId()+key);if(roominput.html()==null){found=true;roomkey=key;delete data.rooms[key];}
else{if(found){data.rooms[key].roomNumber=idx;data.rooms[key].roomName="Room "+idx;data.rooms[key].alternateRow=data.rooms[key].roomNumber%2==0;roominput.roompicker({action:"toggle",roomName:data.rooms[key].roomName,roomNumber:data.rooms[key].roomNumber,alternateRow:data.rooms[key].alternateRow});}
idx++;}}}
data.numRooms=Object.keys(data.rooms).length;container.find("#"+data.getRoomCounterControlId()).val(data.numRooms);inputctrl.val(JSON.stringify(data));inputctrl.trigger("change");inputctrl.trigger("removeroom",[baseId,roomkey]);},reduceRooms:function(baseId){var inputctrl=$("#"+baseId);var container=inputctrl.closest(".ui-roomtypepicker-container");var currentData=JSON.parse(inputctrl.val());var data=new RoomTypePickerData();data.loadFromObj(currentData);var currentRoomCount=data.numRooms;var desiredRooms=currentRoomCount-1;var roomkey="";if(Object.keys(data.rooms).length>0){for(var key in data.rooms){if(data.rooms[key].roomNumber>desiredRooms){var roominput=$("#"+data.getRoomInputBaseId()+key);roomkey=key;var roomcontainer=roominput.closest(".ui-roompicker-container");roomcontainer.slideToggle(100);setTimeout(function(){roomcontainer.remove();},100);delete data.rooms[key];}}}
data.numRooms=Object.keys(data.rooms).length;inputctrl.val(JSON.stringify(data));inputctrl.trigger("change");inputctrl.trigger("removeroom",[baseId,roomkey]);},increaseRooms:function(baseId){var inputctrl=$("#"+baseId);var container=inputctrl.closest(".ui-roomtypepicker-container");var currentData=JSON.parse(inputctrl.val());var data=new RoomTypePickerData();data.loadFromObj(currentData);var currentRoomCount=data.numRooms;var desiredRooms=currentRoomCount+1;if(desiredRooms<=data.maxRooms){var roomsctrl=container.find(".ui-roomtypepicker-rooms");var roomdata=new RoomPickerData();roomdata.mealPlan=data.defaultMealPlan;roomdata.mealPlanOptions=data.mealPlanOptions;roomdata.pax=data.paxOptions;roomdata.roomName="Room "+desiredRooms;roomdata.roomNumber=desiredRooms;roomdata.alternateRow=roomdata.roomNumber%2==0;var key=sn.ui.generateUUID();data.rooms[key]=roomdata;var roomSettings=$.extend({change:function(){sn.ui.roomtypepicker.handleChange(data.baseId,key);},remove:function(){setTimeout(function(){sn.ui.roomtypepicker.handleRemove(data.baseId);},1);}},data.rooms[key]);var newroom=$(document.createElement('input'));newroom.attr("id",data.getRoomInputBaseId()+key);roomsctrl.append(newroom);newroom.roompicker(roomSettings);var newcontainer=newroom.closest(".ui-roompicker-container");newcontainer.hide();newcontainer.slideToggle(100);data.numRooms=Object.keys(data.rooms).length;inputctrl.val(JSON.stringify(data));inputctrl.trigger("change");inputctrl.trigger("addroom",[baseId,key,newroom.val()]);}}};/*!choices.js v3.0.4 | (c) 2018 Josh Johnson | https://github.com/jshjohnson/Choices#readme*/(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==='object'&&typeof module==='object')
module.exports=factory();else if(typeof define==='function'&&define.amd)
define([],factory);else if(typeof exports==='object')
exports["Choices"]=factory();else
root["Choices"]=factory();})(this,function(){return(function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])
return installedModules[moduleId].exports;var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.loaded=true;return module.exports;}
__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="/assets/scripts/dist/";return __webpack_require__(0);})
([(function(module,exports,__webpack_require__){module.exports=__webpack_require__(1);}),(function(module,exports,__webpack_require__){'use strict';var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _fuse=__webpack_require__(2);var _fuse2=_interopRequireDefault(_fuse);var _classnames=__webpack_require__(3);var _classnames2=_interopRequireDefault(_classnames);var _index=__webpack_require__(4);var _index2=_interopRequireDefault(_index);var _index3=__webpack_require__(31);var _utils=__webpack_require__(32);__webpack_require__(33);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}
function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}
function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}
function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}
var Choices=function(){function Choices(){var element=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'[data-choice]';var userConfig=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,Choices);if((0,_utils.isType)('String',element)){var elements=document.querySelectorAll(element);if(elements.length>1){for(var i=1;i<elements.length;i++){var el=elements[i];new Choices(el,userConfig);}}}
var defaultConfig={silent:false,items:[],choices:[],renderChoiceLimit:-1,maxItemCount:-1,addItems:true,removeItems:true,removeItemButton:false,editItems:false,duplicateItems:true,delimiter:',',paste:true,searchEnabled:true,searchChoices:true,searchFloor:1,searchResultLimit:4,searchFields:['label','value'],position:'auto',resetScrollPosition:true,regexFilter:null,shouldSort:true,shouldSortItems:false,sortFilter:_utils.sortByAlpha,placeholder:true,placeholderValue:null,searchPlaceholderValue:null,prependValue:null,appendValue:null,renderSelectedChoices:'auto',loadingText:'Loading...',noResultsText:'No results found',noChoicesText:'No choices to choose from',itemSelectText:'Press to select',addItemText:function addItemText(value){return 'Press Enter to add <b>"'+(0,_utils.stripHTML)(value)+'"</b>';},maxItemText:function maxItemText(maxItemCount){return 'Only '+maxItemCount+' values can be added.';},itemComparer:function itemComparer(choice,item){return choice===item;},uniqueItemText:'Only unique values can be added.',classNames:{containerOuter:'choices',containerInner:'choices__inner',input:'choices__input',inputCloned:'choices__input--cloned',list:'choices__list',listItems:'choices__list--multiple',listSingle:'choices__list--single',listDropdown:'choices__list--dropdown',item:'choices__item',itemSelectable:'choices__item--selectable',itemDisabled:'choices__item--disabled',itemChoice:'choices__item--choice',placeholder:'choices__placeholder',group:'choices__group',groupHeading:'choices__heading',button:'choices__button',activeState:'is-active',focusState:'is-focused',openState:'is-open',disabledState:'is-disabled',highlightedState:'is-highlighted',hiddenState:'is-hidden',flippedState:'is-flipped',loadingState:'is-loading',noResults:'has-no-results',noChoices:'has-no-choices'},fuseOptions:{include:'score'},callbackOnInit:null,callbackOnCreateTemplates:null};this.idNames={itemChoice:'item-choice'};this.config=(0,_utils.extend)(defaultConfig,userConfig);if(this.config.renderSelectedChoices!=='auto'&&this.config.renderSelectedChoices!=='always'){if(!this.config.silent){console.warn('renderSelectedChoices: Possible values are \'auto\' and \'always\'. Falling back to \'auto\'.');}
this.config.renderSelectedChoices='auto';}
this.store=new _index2.default(this.render);this.initialised=false;this.currentState={};this.prevState={};this.currentValue='';this.element=element;this.passedElement=(0,_utils.isType)('String',element)?document.querySelector(element):element;if(!this.passedElement){if(!this.config.silent){console.error('Passed element not found');}
return;}
this.isTextElement=this.passedElement.type==='text';this.isSelectOneElement=this.passedElement.type==='select-one';this.isSelectMultipleElement=this.passedElement.type==='select-multiple';this.isSelectElement=this.isSelectOneElement||this.isSelectMultipleElement;this.isValidElementType=this.isTextElement||this.isSelectElement;this.isIe11=!!(navigator.userAgent.match(/Trident/)&&navigator.userAgent.match(/rv[ :]11/));this.isScrollingOnIe=false;if(this.config.shouldSortItems===true&&this.isSelectOneElement){if(!this.config.silent){console.warn('shouldSortElements: Type of passed element is \'select-one\', falling back to false.');}}
this.highlightPosition=0;this.canSearch=this.config.searchEnabled;this.placeholder=false;if(!this.isSelectOneElement){this.placeholder=this.config.placeholder?this.config.placeholderValue||this.passedElement.getAttribute('placeholder'):false;}
this.presetChoices=this.config.choices;this.presetItems=this.config.items;if(this.passedElement.value){this.presetItems=this.presetItems.concat(this.passedElement.value.split(this.config.delimiter));}
this.baseId=(0,_utils.generateId)(this.passedElement,'choices-');this.render=this.render.bind(this);this._onFocus=this._onFocus.bind(this);this._onBlur=this._onBlur.bind(this);this._onKeyUp=this._onKeyUp.bind(this);this._onKeyDown=this._onKeyDown.bind(this);this._onClick=this._onClick.bind(this);this._onTouchMove=this._onTouchMove.bind(this);this._onTouchEnd=this._onTouchEnd.bind(this);this._onMouseDown=this._onMouseDown.bind(this);this._onMouseOver=this._onMouseOver.bind(this);this._onPaste=this._onPaste.bind(this);this._onInput=this._onInput.bind(this);this.wasTap=true;var cuttingTheMustard='classList'in document.documentElement;if(!cuttingTheMustard&&!this.config.silent){console.error('Choices: Your browser doesn\'t support Choices');}
var canInit=(0,_utils.isElement)(this.passedElement)&&this.isValidElementType;if(canInit){if(this.passedElement.getAttribute('data-choice')==='active'){return;}
this.init();}else if(!this.config.silent){console.error('Incompatible input passed');}}
_createClass(Choices,[{key:'init',value:function init(){if(this.initialised===true){return;}
var callback=this.config.callbackOnInit;this.initialised=true;this._createTemplates();this._createInput();this.store.subscribe(this.render);this.render();this._addEventListeners();if(callback){if((0,_utils.isType)('Function',callback)){callback.call(this);}}}},{key:'destroy',value:function destroy(){if(this.initialised===false){return;}
this._removeEventListeners();this.passedElement.classList.remove(this.config.classNames.input,this.config.classNames.hiddenState);this.passedElement.removeAttribute('tabindex');var origStyle=this.passedElement.getAttribute('data-choice-orig-style');if(Boolean(origStyle)){this.passedElement.removeAttribute('data-choice-orig-style');this.passedElement.setAttribute('style',origStyle);}else{this.passedElement.removeAttribute('style');}
this.passedElement.removeAttribute('aria-hidden');this.passedElement.removeAttribute('data-choice');this.passedElement.value=this.passedElement.value;this.containerOuter.parentNode.insertBefore(this.passedElement,this.containerOuter);this.containerOuter.parentNode.removeChild(this.containerOuter);this.clearStore();this.config.templates=null;this.initialised=false;}},{key:'renderGroups',value:function renderGroups(groups,choices,fragment){var _this=this;var groupFragment=fragment||document.createDocumentFragment();var filter=this.config.sortFilter;if(this.config.shouldSort){groups.sort(filter);}
groups.forEach(function(group){var groupChoices=choices.filter(function(choice){if(_this.isSelectOneElement){return choice.groupId===group.id;}
return choice.groupId===group.id&&!choice.selected;});if(groupChoices.length>=1){var dropdownGroup=_this._getTemplate('choiceGroup',group);groupFragment.appendChild(dropdownGroup);_this.renderChoices(groupChoices,groupFragment,true);}});return groupFragment;}},{key:'renderChoices',value:function renderChoices(choices,fragment){var _this2=this;var withinGroup=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var choicesFragment=fragment||document.createDocumentFragment();var _config=this.config,renderSelectedChoices=_config.renderSelectedChoices,searchResultLimit=_config.searchResultLimit,renderChoiceLimit=_config.renderChoiceLimit;var filter=this.isSearching?_utils.sortByScore:this.config.sortFilter;var appendChoice=function appendChoice(choice){var shouldRender=renderSelectedChoices==='auto'?_this2.isSelectOneElement||!choice.selected:true;if(shouldRender){var dropdownItem=_this2._getTemplate('choice',choice);choicesFragment.appendChild(dropdownItem);}};var rendererableChoices=choices;if(renderSelectedChoices==='auto'&&!this.isSelectOneElement){rendererableChoices=choices.filter(function(choice){return!choice.selected;});}
var _rendererableChoices$=rendererableChoices.reduce(function(acc,choice){if(choice.placeholder){acc.placeholderChoices.push(choice);}else{acc.normalChoices.push(choice);}
return acc;},{placeholderChoices:[],normalChoices:[]}),placeholderChoices=_rendererableChoices$.placeholderChoices,normalChoices=_rendererableChoices$.normalChoices;if(this.config.shouldSort||this.isSearching){normalChoices.sort(filter);}
var choiceLimit=rendererableChoices.length;var sortedChoices=[].concat(_toConsumableArray(placeholderChoices),_toConsumableArray(normalChoices));if(this.isSearching){choiceLimit=searchResultLimit;}else if(renderChoiceLimit>0&&!withinGroup){choiceLimit=renderChoiceLimit;}
for(var i=0;i<choiceLimit;i++){if(sortedChoices[i]){appendChoice(sortedChoices[i]);}};return choicesFragment;}},{key:'renderItems',value:function renderItems(items){var _this3=this;var fragment=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var itemListFragment=fragment||document.createDocumentFragment();if(this.config.shouldSortItems&&!this.isSelectOneElement){items.sort(this.config.sortFilter);}
if(this.isTextElement){var itemsFiltered=this.store.getItemsReducedToValues(items);var itemsFilteredString=itemsFiltered.join(this.config.delimiter);this.passedElement.setAttribute('value',itemsFilteredString);this.passedElement.value=itemsFilteredString;}else{var selectedOptionsFragment=document.createDocumentFragment();items.forEach(function(item){var option=_this3._getTemplate('option',item);selectedOptionsFragment.appendChild(option);});this.passedElement.innerHTML='';this.passedElement.appendChild(selectedOptionsFragment);}
items.forEach(function(item){var listItem=_this3._getTemplate('item',item);itemListFragment.appendChild(listItem);});return itemListFragment;}},{key:'render',value:function render(){if(this.store.isLoading()){return;}
this.currentState=this.store.getState();if(this.currentState!==this.prevState){if(this.currentState.choices!==this.prevState.choices||this.currentState.groups!==this.prevState.groups||this.currentState.items!==this.prevState.items){if(this.isSelectElement){var activeGroups=this.store.getGroupsFilteredByActive();var activeChoices=this.store.getChoicesFilteredByActive();var choiceListFragment=document.createDocumentFragment();this.choiceList.innerHTML='';if(this.config.resetScrollPosition){this.choiceList.scrollTop=0;}
if(activeGroups.length>=1&&this.isSearching!==true){choiceListFragment=this.renderGroups(activeGroups,activeChoices,choiceListFragment);}else if(activeChoices.length>=1){choiceListFragment=this.renderChoices(activeChoices,choiceListFragment);}
var activeItems=this.store.getItemsFilteredByActive();var canAddItem=this._canAddItem(activeItems,this.input.value);if(choiceListFragment.childNodes&&choiceListFragment.childNodes.length>0){if(canAddItem.response){this.choiceList.appendChild(choiceListFragment);this._highlightChoice();}else{this.choiceList.appendChild(this._getTemplate('notice',canAddItem.notice));}}else{var dropdownItem=void 0;var notice=void 0;if(this.isSearching){notice=(0,_utils.isType)('Function',this.config.noResultsText)?this.config.noResultsText():this.config.noResultsText;dropdownItem=this._getTemplate('notice',notice,'no-results');}else{notice=(0,_utils.isType)('Function',this.config.noChoicesText)?this.config.noChoicesText():this.config.noChoicesText;dropdownItem=this._getTemplate('notice',notice,'no-choices');}
this.choiceList.appendChild(dropdownItem);}}}
if(this.currentState.items!==this.prevState.items){var _activeItems=this.store.getItemsFilteredByActive();this.itemList.innerHTML='';if(_activeItems&&_activeItems){var itemListFragment=this.renderItems(_activeItems);if(itemListFragment.childNodes){this.itemList.appendChild(itemListFragment);}}}
this.prevState=this.currentState;}}},{key:'highlightItem',value:function highlightItem(item){var runEvent=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;if(!item){return this;}
var id=item.id;var groupId=item.groupId;var group=groupId>=0?this.store.getGroupById(groupId):null;this.store.dispatch((0,_index3.highlightItem)(id,true));if(runEvent){if(group&&group.value){(0,_utils.triggerEvent)(this.passedElement,'highlightItem',{id:id,value:item.value,label:item.label,groupValue:group.value});}else{(0,_utils.triggerEvent)(this.passedElement,'highlightItem',{id:id,value:item.value,label:item.label});}}
return this;}},{key:'unhighlightItem',value:function unhighlightItem(item){if(!item){return this;}
var id=item.id;var groupId=item.groupId;var group=groupId>=0?this.store.getGroupById(groupId):null;this.store.dispatch((0,_index3.highlightItem)(id,false));if(group&&group.value){(0,_utils.triggerEvent)(this.passedElement,'unhighlightItem',{id:id,value:item.value,label:item.label,groupValue:group.value});}else{(0,_utils.triggerEvent)(this.passedElement,'unhighlightItem',{id:id,value:item.value,label:item.label});}
return this;}},{key:'highlightAll',value:function highlightAll(){var _this4=this;var items=this.store.getItems();items.forEach(function(item){_this4.highlightItem(item);});return this;}},{key:'unhighlightAll',value:function unhighlightAll(){var _this5=this;var items=this.store.getItems();items.forEach(function(item){_this5.unhighlightItem(item);});return this;}},{key:'removeItemsByValue',value:function removeItemsByValue(value){var _this6=this;if(!value||!(0,_utils.isType)('String',value)){return this;}
var items=this.store.getItemsFilteredByActive();items.forEach(function(item){if(item.value===value){_this6._removeItem(item);}});return this;}},{key:'removeActiveItems',value:function removeActiveItems(excludedId){var _this7=this;var items=this.store.getItemsFilteredByActive();items.forEach(function(item){if(item.active&&excludedId!==item.id){_this7._removeItem(item);}});return this;}},{key:'removeHighlightedItems',value:function removeHighlightedItems(){var _this8=this;var runEvent=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var items=this.store.getItemsFilteredByActive();items.forEach(function(item){if(item.highlighted&&item.active){_this8._removeItem(item);if(runEvent){_this8._triggerChange(item.value);}}});return this;}},{key:'showDropdown',value:function showDropdown(){var focusInput=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var body=document.body;var html=document.documentElement;var winHeight=Math.max(body.scrollHeight,body.offsetHeight,html.clientHeight,html.scrollHeight,html.offsetHeight);this.containerOuter.classList.add(this.config.classNames.openState);this.containerOuter.setAttribute('aria-expanded','true');this.dropdown.classList.add(this.config.classNames.activeState);this.dropdown.setAttribute('aria-expanded','true');var dimensions=this.dropdown.getBoundingClientRect();var dropdownPos=Math.ceil(dimensions.top+window.scrollY+this.dropdown.offsetHeight);var shouldFlip=false;if(this.config.position==='auto'){shouldFlip=dropdownPos>=winHeight;}else if(this.config.position==='top'){shouldFlip=true;}
if(shouldFlip){this.containerOuter.classList.add(this.config.classNames.flippedState);}
if(focusInput&&this.canSearch&&document.activeElement!==this.input){this.input.focus();}
(0,_utils.triggerEvent)(this.passedElement,'showDropdown',{});return this;}},{key:'hideDropdown',value:function hideDropdown(){var blurInput=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var isFlipped=this.containerOuter.classList.contains(this.config.classNames.flippedState);this.containerOuter.classList.remove(this.config.classNames.openState);this.containerOuter.setAttribute('aria-expanded','false');this.dropdown.classList.remove(this.config.classNames.activeState);this.dropdown.setAttribute('aria-expanded','false');if(isFlipped){this.containerOuter.classList.remove(this.config.classNames.flippedState);}
if(blurInput&&this.canSearch&&document.activeElement===this.input){this.input.blur();}
(0,_utils.triggerEvent)(this.passedElement,'hideDropdown',{});return this;}},{key:'toggleDropdown',value:function toggleDropdown(){var hasActiveDropdown=this.dropdown.classList.contains(this.config.classNames.activeState);if(hasActiveDropdown){this.hideDropdown();}else{this.showDropdown(true);}
return this;}},{key:'getValue',value:function getValue(){var _this9=this;var valueOnly=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var items=this.store.getItemsFilteredByActive();var selectedItems=[];items.forEach(function(item){if(_this9.isTextElement){selectedItems.push(valueOnly?item.value:item);}else if(item.active){selectedItems.push(valueOnly?item.value:item);}});if(this.isSelectOneElement){return selectedItems[0];}
return selectedItems;}},{key:'setValue',value:function setValue(args){var _this10=this;if(this.initialised===true){var values=[].concat(_toConsumableArray(args)),handleValue=function handleValue(item){var itemType=(0,_utils.getType)(item);if(itemType==='Object'){if(!item.value){return;}
if(!_this10.isTextElement){_this10._addChoice(item.value,item.label,true,false,-1,item.customProperties,item.placeholder);}else{_this10._addItem(item.value,item.label,item.id,undefined,item.customProperties,item.placeholder);}}else if(itemType==='String'){if(!_this10.isTextElement){_this10._addChoice(item,item,true,false,-1,null);}else{_this10._addItem(item);}}};if(values.length>1){values.forEach(function(value){handleValue(value);});}else{handleValue(values[0]);}}
return this;}},{key:'setValueByChoice',value:function setValueByChoice(value){var _this11=this;if(!this.isTextElement){var choices=this.store.getChoices();var choiceValue=(0,_utils.isType)('Array',value)?value:[value];choiceValue.forEach(function(val){var foundChoice=choices.find(function(choice){return _this11.config.itemComparer(choice.value,val);});if(foundChoice){if(!foundChoice.selected){_this11._addItem(foundChoice.value,foundChoice.label,foundChoice.id,foundChoice.groupId,foundChoice.customProperties,foundChoice.placeholder,foundChoice.keyCode);}else if(!_this11.config.silent){console.warn('Attempting to select choice already selected');}}else if(!_this11.config.silent){console.warn('Attempting to select choice that does not exist');}});}
return this;}},{key:'setChoices',value:function setChoices(choices,value,label){var _this12=this;var replaceChoices=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;if(this.initialised===true){if(this.isSelectElement){if(!(0,_utils.isType)('Array',choices)||!value){return this;}
if(replaceChoices){this._clearChoices();}
this._setLoading(true);if(choices&&choices.length){this.containerOuter.classList.remove(this.config.classNames.loadingState);choices.forEach(function(result){if(result.choices){_this12._addGroup(result,result.id||null,value,label);}else{_this12._addChoice(result[value],result[label],result.selected,result.disabled,undefined,result.customProperties,result.placeholder);}});}
this._setLoading(false);}}
return this;}},{key:'clearStore',value:function clearStore(){this.store.dispatch((0,_index3.clearAll)());return this;}},{key:'clearInput',value:function clearInput(){if(this.input.value){this.input.value='';}
if(!this.isSelectOneElement){this._setInputWidth();}
if(!this.isTextElement&&this.config.searchEnabled){this.isSearching=false;this.store.dispatch((0,_index3.activateChoices)(true));}
return this;}},{key:'enable',value:function enable(){if(this.initialised){this.passedElement.disabled=false;var isDisabled=this.containerOuter.classList.contains(this.config.classNames.disabledState);if(isDisabled){this._addEventListeners();this.passedElement.removeAttribute('disabled');this.input.removeAttribute('disabled');this.containerOuter.classList.remove(this.config.classNames.disabledState);this.containerOuter.removeAttribute('aria-disabled');if(this.isSelectOneElement){this.containerOuter.setAttribute('tabindex','0');}}}
return this;}},{key:'disable',value:function disable(){if(this.initialised){this.passedElement.disabled=true;var isEnabled=!this.containerOuter.classList.contains(this.config.classNames.disabledState);if(isEnabled){this._removeEventListeners();this.passedElement.setAttribute('disabled','');this.input.setAttribute('disabled','');this.containerOuter.classList.add(this.config.classNames.disabledState);this.containerOuter.setAttribute('aria-disabled','true');if(this.isSelectOneElement){this.containerOuter.setAttribute('tabindex','-1');}}}
return this;}},{key:'ajax',value:function ajax(fn){var _this13=this;if(this.initialised===true){if(this.isSelectElement){requestAnimationFrame(function(){_this13._handleLoadingState(true);});fn(this._ajaxCallback());}}
return this;}},{key:'_triggerChange',value:function _triggerChange(value){if(!value){return;}
(0,_utils.triggerEvent)(this.passedElement,'change',{value:value});}},{key:'_handleButtonAction',value:function _handleButtonAction(activeItems,element){if(!activeItems||!element){return;}
if(this.config.removeItems&&this.config.removeItemButton){var itemId=element.parentNode.getAttribute('data-id');var itemToRemove=activeItems.find(function(item){return item.id===parseInt(itemId,10);});this._removeItem(itemToRemove);this._triggerChange(itemToRemove.value);if(this.isSelectOneElement){this._selectPlaceholderChoice();}}}},{key:'_selectPlaceholderChoice',value:function _selectPlaceholderChoice(){var placeholderChoice=this.store.getPlaceholderChoice();if(placeholderChoice){this._addItem(placeholderChoice.value,placeholderChoice.label,placeholderChoice.id,placeholderChoice.groupId,null,placeholderChoice.placeholder);this._triggerChange(placeholderChoice.value);}}},{key:'_handleItemAction',value:function _handleItemAction(activeItems,element){var _this14=this;var hasShiftKey=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(!activeItems||!element){return;}
if(this.config.removeItems&&!this.isSelectOneElement){var passedId=element.getAttribute('data-id');activeItems.forEach(function(item){if(item.id===parseInt(passedId,10)&&!item.highlighted){_this14.highlightItem(item);}else if(!hasShiftKey){if(item.highlighted){_this14.unhighlightItem(item);}}});if(document.activeElement!==this.input){this.input.focus();}}}},{key:'_handleChoiceAction',value:function _handleChoiceAction(activeItems,element){if(!activeItems||!element){return;}
var id=element.getAttribute('data-id');var choice=this.store.getChoiceById(id);var passedKeyCode=activeItems[0]&&activeItems[0].keyCode?activeItems[0].keyCode:null;var hasActiveDropdown=this.dropdown.classList.contains(this.config.classNames.activeState);choice.keyCode=passedKeyCode;(0,_utils.triggerEvent)(this.passedElement,'choice',{choice:choice});if(choice&&!choice.selected&&!choice.disabled){var canAddItem=this._canAddItem(activeItems,choice.value);if(canAddItem.response){this._addItem(choice.value,choice.label,choice.id,choice.groupId,choice.customProperties,choice.placeholder,choice.keyCode);this._triggerChange(choice.value);}}
this.clearInput();if(hasActiveDropdown&&this.isSelectOneElement){this.hideDropdown();this.containerOuter.focus();}}},{key:'_handleBackspace',value:function _handleBackspace(activeItems){if(this.config.removeItems&&activeItems){var lastItem=activeItems[activeItems.length-1];var hasHighlightedItems=activeItems.some(function(item){return item.highlighted;});if(this.config.editItems&&!hasHighlightedItems&&lastItem){this.input.value=lastItem.value;this._setInputWidth();this._removeItem(lastItem);this._triggerChange(lastItem.value);}else{if(!hasHighlightedItems){this.highlightItem(lastItem,false);}
this.removeHighlightedItems(true);}}}},{key:'_canAddItem',value:function _canAddItem(activeItems,value){var canAddItem=true;var notice=(0,_utils.isType)('Function',this.config.addItemText)?this.config.addItemText(value):this.config.addItemText;if(this.isSelectMultipleElement||this.isTextElement){if(this.config.maxItemCount>0&&this.config.maxItemCount<=activeItems.length){canAddItem=false;notice=(0,_utils.isType)('Function',this.config.maxItemText)?this.config.maxItemText(this.config.maxItemCount):this.config.maxItemText;}}
if(this.isTextElement&&this.config.addItems&&canAddItem){if(this.config.regexFilter){canAddItem=this._regexFilter(value);}}
var isUnique=!activeItems.some(function(item){if((0,_utils.isType)('String',value)){return item.value===value.trim();}
return item.value===value;});if(!isUnique&&!this.config.duplicateItems&&!this.isSelectOneElement&&canAddItem){canAddItem=false;notice=(0,_utils.isType)('Function',this.config.uniqueItemText)?this.config.uniqueItemText(value):this.config.uniqueItemText;}
return{response:canAddItem,notice:notice};}},{key:'_handleLoadingState',value:function _handleLoadingState(){var setLoading=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var placeholderItem=this.itemList.querySelector('.'+this.config.classNames.placeholder);if(setLoading){this.containerOuter.classList.add(this.config.classNames.loadingState);this.containerOuter.setAttribute('aria-busy','true');if(this.isSelectOneElement){if(!placeholderItem){placeholderItem=this._getTemplate('placeholder',this.config.loadingText);this.itemList.appendChild(placeholderItem);}else{placeholderItem.innerHTML=this.config.loadingText;}}else{this.input.placeholder=this.config.loadingText;}}else{this.containerOuter.classList.remove(this.config.classNames.loadingState);if(this.isSelectOneElement){placeholderItem.innerHTML=this.placeholder||'';}else{this.input.placeholder=this.placeholder||'';}}}},{key:'_ajaxCallback',value:function _ajaxCallback(){var _this15=this;return function(results,value,label){if(!results||!value){return;}
var parsedResults=(0,_utils.isType)('Object',results)?[results]:results;if(parsedResults&&(0,_utils.isType)('Array',parsedResults)&&parsedResults.length){_this15._handleLoadingState(false);_this15._setLoading(true);parsedResults.forEach(function(result){if(result.choices){var groupId=result.id||null;_this15._addGroup(result,groupId,value,label);}else{_this15._addChoice(result[value],result[label],result.selected,result.disabled,undefined,result.customProperties,result.placeholder);}});_this15._setLoading(false);if(_this15.isSelectOneElement){_this15._selectPlaceholderChoice();}}else{_this15._handleLoadingState(false);}
_this15.containerOuter.removeAttribute('aria-busy');};}},{key:'_searchChoices',value:function _searchChoices(value){var newValue=(0,_utils.isType)('String',value)?value.trim():value;var currentValue=(0,_utils.isType)('String',this.currentValue)?this.currentValue.trim():this.currentValue;if(newValue.length>=1&&newValue!==currentValue+' '){var haystack=this.store.getSearchableChoices();var needle=newValue;var keys=(0,_utils.isType)('Array',this.config.searchFields)?this.config.searchFields:[this.config.searchFields];var options=Object.assign(this.config.fuseOptions,{keys:keys});var fuse=new _fuse2.default(haystack,options);var results=fuse.search(needle);this.currentValue=newValue;this.highlightPosition=0;this.isSearching=true;this.store.dispatch((0,_index3.filterChoices)(results));return results.length;}
return 0;}},{key:'_handleSearch',value:function _handleSearch(value){if(!value){return;}
var choices=this.store.getChoices();var hasUnactiveChoices=choices.some(function(option){return!option.active;});if(this.input===document.activeElement){if(value&&value.length>=this.config.searchFloor){var resultCount=0;if(this.config.searchChoices){resultCount=this._searchChoices(value);}
(0,_utils.triggerEvent)(this.passedElement,'search',{value:value,resultCount:resultCount});}else if(hasUnactiveChoices){this.isSearching=false;this.store.dispatch((0,_index3.activateChoices)(true));}}}},{key:'_addEventListeners',value:function _addEventListeners(){document.addEventListener('keyup',this._onKeyUp);document.addEventListener('keydown',this._onKeyDown);document.addEventListener('click',this._onClick);document.addEventListener('touchmove',this._onTouchMove);document.addEventListener('touchend',this._onTouchEnd);document.addEventListener('mousedown',this._onMouseDown);document.addEventListener('mouseover',this._onMouseOver);if(this.isSelectOneElement){this.containerOuter.addEventListener('focus',this._onFocus);this.containerOuter.addEventListener('blur',this._onBlur);}
this.input.addEventListener('input',this._onInput);this.input.addEventListener('paste',this._onPaste);this.input.addEventListener('focus',this._onFocus);this.input.addEventListener('blur',this._onBlur);}},{key:'_removeEventListeners',value:function _removeEventListeners(){document.removeEventListener('keyup',this._onKeyUp);document.removeEventListener('keydown',this._onKeyDown);document.removeEventListener('click',this._onClick);document.removeEventListener('touchmove',this._onTouchMove);document.removeEventListener('touchend',this._onTouchEnd);document.removeEventListener('mousedown',this._onMouseDown);document.removeEventListener('mouseover',this._onMouseOver);if(this.isSelectOneElement){this.containerOuter.removeEventListener('focus',this._onFocus);this.containerOuter.removeEventListener('blur',this._onBlur);}
this.input.removeEventListener('input',this._onInput);this.input.removeEventListener('paste',this._onPaste);this.input.removeEventListener('focus',this._onFocus);this.input.removeEventListener('blur',this._onBlur);}},{key:'_setInputWidth',value:function _setInputWidth(){if(this.placeholder){if(this.input.value&&this.input.value.length>=this.placeholder.length/1.25){this.input.style.width=(0,_utils.getWidthOfInput)(this.input);}}else{this.input.style.width=(0,_utils.getWidthOfInput)(this.input);}}},{key:'_onKeyDown',value:function _onKeyDown(e){var _this16=this,_keyDownActions;if(e.target!==this.input&&!this.containerOuter.contains(e.target)){return;}
var target=e.target;var activeItems=this.store.getItemsFilteredByActive();var hasFocusedInput=this.input===document.activeElement;var hasActiveDropdown=this.dropdown.classList.contains(this.config.classNames.activeState);var hasItems=this.itemList&&this.itemList.children;var keyString=String.fromCharCode(e.keyCode);var backKey=46;var deleteKey=8;var enterKey=13;var aKey=65;var escapeKey=27;var upKey=38;var downKey=40;var pageUpKey=33;var pageDownKey=34;var ctrlDownKey=e.ctrlKey||e.metaKey;if(!this.isTextElement&&/[a-zA-Z0-9-_ ]/.test(keyString)&&!hasActiveDropdown){this.showDropdown(true);}
this.canSearch=this.config.searchEnabled;var onAKey=function onAKey(){if(ctrlDownKey&&hasItems){_this16.canSearch=false;if(_this16.config.removeItems&&!_this16.input.value&&_this16.input===document.activeElement){_this16.highlightAll();}}};var onEnterKey=function onEnterKey(){if(_this16.isTextElement&&target.value){var value=_this16.input.value;var canAddItem=_this16._canAddItem(activeItems,value);if(canAddItem.response){if(hasActiveDropdown){_this16.hideDropdown();}
_this16._addItem(value);_this16._triggerChange(value);_this16.clearInput();}}
if(target.hasAttribute('data-button')){_this16._handleButtonAction(activeItems,target);e.preventDefault();}
if(hasActiveDropdown){e.preventDefault();var highlighted=_this16.dropdown.querySelector('.'+_this16.config.classNames.highlightedState);if(highlighted){if(activeItems[0]){activeItems[0].keyCode=enterKey;}
_this16._handleChoiceAction(activeItems,highlighted);}}else if(_this16.isSelectOneElement){if(!hasActiveDropdown){_this16.showDropdown(true);e.preventDefault();}}};var onEscapeKey=function onEscapeKey(){if(hasActiveDropdown){_this16.toggleDropdown();_this16.containerOuter.focus();}};var onDirectionKey=function onDirectionKey(){if(hasActiveDropdown||_this16.isSelectOneElement){if(!hasActiveDropdown){_this16.showDropdown(true);}
_this16.canSearch=false;var directionInt=e.keyCode===downKey||e.keyCode===pageDownKey?1:-1;var skipKey=e.metaKey||e.keyCode===pageDownKey||e.keyCode===pageUpKey;var nextEl=void 0;if(skipKey){if(directionInt>0){nextEl=Array.from(_this16.dropdown.querySelectorAll('[data-choice-selectable]')).pop();}else{nextEl=_this16.dropdown.querySelector('[data-choice-selectable]');}}else{var currentEl=_this16.dropdown.querySelector('.'+_this16.config.classNames.highlightedState);if(currentEl){nextEl=(0,_utils.getAdjacentEl)(currentEl,'[data-choice-selectable]',directionInt);}else{nextEl=_this16.dropdown.querySelector('[data-choice-selectable]');}}
if(nextEl){if(!(0,_utils.isScrolledIntoView)(nextEl,_this16.choiceList,directionInt)){_this16._scrollToChoice(nextEl,directionInt);}
_this16._highlightChoice(nextEl);}
e.preventDefault();}};var onDeleteKey=function onDeleteKey(){if(hasFocusedInput&&!e.target.value&&!_this16.isSelectOneElement){_this16._handleBackspace(activeItems);e.preventDefault();}};var keyDownActions=(_keyDownActions={},_defineProperty(_keyDownActions,aKey,onAKey),_defineProperty(_keyDownActions,enterKey,onEnterKey),_defineProperty(_keyDownActions,escapeKey,onEscapeKey),_defineProperty(_keyDownActions,upKey,onDirectionKey),_defineProperty(_keyDownActions,pageUpKey,onDirectionKey),_defineProperty(_keyDownActions,downKey,onDirectionKey),_defineProperty(_keyDownActions,pageDownKey,onDirectionKey),_defineProperty(_keyDownActions,deleteKey,onDeleteKey),_defineProperty(_keyDownActions,backKey,onDeleteKey),_keyDownActions);if(keyDownActions[e.keyCode]){keyDownActions[e.keyCode]();}}},{key:'_onKeyUp',value:function _onKeyUp(e){if(e.target!==this.input){return;}
var value=this.input.value;var activeItems=this.store.getItemsFilteredByActive();var canAddItem=this._canAddItem(activeItems,value);if(this.isTextElement){var hasActiveDropdown=this.dropdown.classList.contains(this.config.classNames.activeState);if(value){if(canAddItem.notice){var dropdownItem=this._getTemplate('notice',canAddItem.notice);this.dropdown.innerHTML=dropdownItem.outerHTML;}
if(canAddItem.response===true){if(!hasActiveDropdown){this.showDropdown();}}else if(!canAddItem.notice&&hasActiveDropdown){this.hideDropdown();}}else if(hasActiveDropdown){this.hideDropdown();}}else{var backKey=46;var deleteKey=8;if((e.keyCode===backKey||e.keyCode===deleteKey)&&!e.target.value){if(!this.isTextElement&&this.isSearching){this.isSearching=false;this.store.dispatch((0,_index3.activateChoices)(true));}}else if(this.canSearch&&canAddItem.response){this._handleSearch(this.input.value);}}
this.canSearch=this.config.searchEnabled;}},{key:'_onInput',value:function _onInput(){if(!this.isSelectOneElement){this._setInputWidth();}}},{key:'_onTouchMove',value:function _onTouchMove(){if(this.wasTap===true){this.wasTap=false;}}},{key:'_onTouchEnd',value:function _onTouchEnd(e){var target=e.target||e.touches[0].target;var hasActiveDropdown=this.dropdown.classList.contains(this.config.classNames.activeState);if(this.wasTap===true&&this.containerOuter.contains(target)){if((target===this.containerOuter||target===this.containerInner)&&!this.isSelectOneElement){if(this.isTextElement){if(document.activeElement!==this.input){this.input.focus();}}else{if(!hasActiveDropdown){this.showDropdown(true);}}}
e.stopPropagation();}
this.wasTap=true;}},{key:'_onMouseDown',value:function _onMouseDown(e){var target=e.target;if(target===this.choiceList&&this.isIe11){this.isScrollingOnIe=true;}
if(this.containerOuter.contains(target)&&target!==this.input){var foundTarget=void 0;var activeItems=this.store.getItemsFilteredByActive();var hasShiftKey=e.shiftKey;if(foundTarget=(0,_utils.findAncestorByAttrName)(target,'data-button')){this._handleButtonAction(activeItems,foundTarget);}else if(foundTarget=(0,_utils.findAncestorByAttrName)(target,'data-item')){this._handleItemAction(activeItems,foundTarget,hasShiftKey);}else if(foundTarget=(0,_utils.findAncestorByAttrName)(target,'data-choice')){this._handleChoiceAction(activeItems,foundTarget);}
e.preventDefault();}}},{key:'_onClick',value:function _onClick(e){var target=e.target;var hasActiveDropdown=this.dropdown.classList.contains(this.config.classNames.activeState);var activeItems=this.store.getItemsFilteredByActive();if(this.containerOuter.contains(target)){if(target.hasAttribute('data-button')){this._handleButtonAction(activeItems,target);}
if(!hasActiveDropdown){if(this.isTextElement){if(document.activeElement!==this.input){this.input.focus();}}else{if(this.canSearch){this.showDropdown(true);}else{this.showDropdown();this.containerOuter.focus();}}}else if(this.isSelectOneElement&&target!==this.input&&!this.dropdown.contains(target)){this.hideDropdown(true);}}else{var hasHighlightedItems=activeItems.some(function(item){return item.highlighted;});if(hasHighlightedItems){this.unhighlightAll();}
this.containerOuter.classList.remove(this.config.classNames.focusState);if(hasActiveDropdown){this.hideDropdown();}}}},{key:'_onMouseOver',value:function _onMouseOver(e){if(e.target===this.dropdown||this.dropdown.contains(e.target)){if(e.target.hasAttribute('data-choice'))this._highlightChoice(e.target);}}},{key:'_onPaste',value:function _onPaste(e){if(e.target===this.input&&!this.config.paste){e.preventDefault();}}},{key:'_onFocus',value:function _onFocus(e){var _this17=this;var target=e.target;if(this.containerOuter.contains(target)){var hasActiveDropdown=this.dropdown.classList.contains(this.config.classNames.activeState);var focusActions={text:function text(){if(target===_this17.input){_this17.containerOuter.classList.add(_this17.config.classNames.focusState);}},'select-one':function selectOne(){_this17.containerOuter.classList.add(_this17.config.classNames.focusState);if(target===_this17.input){if(!hasActiveDropdown){_this17.showDropdown();}}},'select-multiple':function selectMultiple(){if(target===_this17.input){_this17.containerOuter.classList.add(_this17.config.classNames.focusState);if(!hasActiveDropdown){_this17.showDropdown(true);}}}};focusActions[this.passedElement.type]();}}},{key:'_onBlur',value:function _onBlur(e){var _this18=this;var target=e.target;if(this.containerOuter.contains(target)&&!this.isScrollingOnIe){var activeItems=this.store.getItemsFilteredByActive();var hasActiveDropdown=this.dropdown.classList.contains(this.config.classNames.activeState);var hasHighlightedItems=activeItems.some(function(item){return item.highlighted;});var blurActions={text:function text(){if(target===_this18.input){_this18.containerOuter.classList.remove(_this18.config.classNames.focusState);if(hasHighlightedItems){_this18.unhighlightAll();}
if(hasActiveDropdown){_this18.hideDropdown();}}},'select-one':function selectOne(){_this18.containerOuter.classList.remove(_this18.config.classNames.focusState);if(target===_this18.containerOuter){if(hasActiveDropdown&&!_this18.canSearch){_this18.hideDropdown();}}
if(target===_this18.input&&hasActiveDropdown){_this18.hideDropdown();}},'select-multiple':function selectMultiple(){if(target===_this18.input){_this18.containerOuter.classList.remove(_this18.config.classNames.focusState);if(hasActiveDropdown){_this18.hideDropdown();}
if(hasHighlightedItems){_this18.unhighlightAll();}}}};blurActions[this.passedElement.type]();}else{this.isScrollingOnIe=false;this.input.focus();}}},{key:'_regexFilter',value:function _regexFilter(value){if(!value){return false;}
var regex=this.config.regexFilter;var expression=new RegExp(regex.source,'i');return expression.test(value);}},{key:'_scrollToChoice',value:function _scrollToChoice(choice,direction){var _this19=this;if(!choice){return;}
var dropdownHeight=this.choiceList.offsetHeight;var choiceHeight=choice.offsetHeight;var choicePos=choice.offsetTop+choiceHeight;var containerScrollPos=this.choiceList.scrollTop+dropdownHeight;var endPoint=direction>0?this.choiceList.scrollTop+choicePos-containerScrollPos:choice.offsetTop;var animateScroll=function animateScroll(){var strength=4;var choiceListScrollTop=_this19.choiceList.scrollTop;var continueAnimation=false;var easing=void 0;var distance=void 0;if(direction>0){easing=(endPoint-choiceListScrollTop)/strength;distance=easing>1?easing:1;_this19.choiceList.scrollTop=choiceListScrollTop+distance;if(choiceListScrollTop<endPoint){continueAnimation=true;}}else{easing=(choiceListScrollTop-endPoint)/strength;distance=easing>1?easing:1;_this19.choiceList.scrollTop=choiceListScrollTop-distance;if(choiceListScrollTop>endPoint){continueAnimation=true;}}
if(continueAnimation){requestAnimationFrame(function(time){animateScroll(time,endPoint,direction);});}};requestAnimationFrame(function(time){animateScroll(time,endPoint,direction);});}},{key:'_highlightChoice',value:function _highlightChoice(){var _this20=this;var el=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var choices=Array.from(this.dropdown.querySelectorAll('[data-choice-selectable]'));var passedEl=el;if(choices&&choices.length){var highlightedChoices=Array.from(this.dropdown.querySelectorAll('.'+this.config.classNames.highlightedState));highlightedChoices.forEach(function(choice){choice.classList.remove(_this20.config.classNames.highlightedState);choice.setAttribute('aria-selected','false');});if(passedEl){this.highlightPosition=choices.indexOf(passedEl);}else{if(choices.length>this.highlightPosition){passedEl=choices[this.highlightPosition];}else{passedEl=choices[choices.length-1];}
if(!passedEl){passedEl=choices[0];}}
passedEl.classList.add(this.config.classNames.highlightedState);passedEl.setAttribute('aria-selected','true');this.containerOuter.setAttribute('aria-activedescendant',passedEl.id);}}},{key:'_addItem',value:function _addItem(value){var label=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var choiceId=arguments.length>2&&arguments[2]!==undefined?arguments[2]:-1;var groupId=arguments.length>3&&arguments[3]!==undefined?arguments[3]:-1;var customProperties=arguments.length>4&&arguments[4]!==undefined?arguments[4]:null;var placeholder=arguments.length>5&&arguments[5]!==undefined?arguments[5]:false;var keyCode=arguments.length>6&&arguments[6]!==undefined?arguments[6]:null;var passedValue=(0,_utils.isType)('String',value)?value.trim():value;var passedKeyCode=keyCode;var items=this.store.getItems();var passedLabel=label||passedValue;var passedOptionId=parseInt(choiceId,10)||-1;var group=groupId>=0?this.store.getGroupById(groupId):null;var id=items?items.length+1:1;if(this.config.prependValue){passedValue=this.config.prependValue+passedValue.toString();}
if(this.config.appendValue){passedValue+=this.config.appendValue.toString();}
this.store.dispatch((0,_index3.addItem)(passedValue,passedLabel,id,passedOptionId,groupId,customProperties,placeholder,passedKeyCode));if(this.isSelectOneElement){this.removeActiveItems(id);}
if(group&&group.value){(0,_utils.triggerEvent)(this.passedElement,'addItem',{id:id,value:passedValue,label:passedLabel,groupValue:group.value,keyCode:passedKeyCode});}else{(0,_utils.triggerEvent)(this.passedElement,'addItem',{id:id,value:passedValue,label:passedLabel,keyCode:passedKeyCode});}
return this;}},{key:'_removeItem',value:function _removeItem(item){if(!item||!(0,_utils.isType)('Object',item)){return this;}
var id=item.id;var value=item.value;var label=item.label;var choiceId=item.choiceId;var groupId=item.groupId;var group=groupId>=0?this.store.getGroupById(groupId):null;this.store.dispatch((0,_index3.removeItem)(id,choiceId));if(group&&group.value){(0,_utils.triggerEvent)(this.passedElement,'removeItem',{id:id,value:value,label:label,groupValue:group.value});}else{(0,_utils.triggerEvent)(this.passedElement,'removeItem',{id:id,value:value,label:label});}
return this;}},{key:'_addChoice',value:function _addChoice(value){var label=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var isSelected=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var isDisabled=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;var groupId=arguments.length>4&&arguments[4]!==undefined?arguments[4]:-1;var customProperties=arguments.length>5&&arguments[5]!==undefined?arguments[5]:null;var placeholder=arguments.length>6&&arguments[6]!==undefined?arguments[6]:false;var keyCode=arguments.length>7&&arguments[7]!==undefined?arguments[7]:null;if(typeof value==='undefined'||value===null){return;}
var choices=this.store.getChoices();var choiceLabel=label||value;var choiceId=choices?choices.length+1:1;var choiceElementId=this.baseId+'-'+this.idNames.itemChoice+'-'+choiceId;this.store.dispatch((0,_index3.addChoice)(value,choiceLabel,choiceId,groupId,isDisabled,choiceElementId,customProperties,placeholder,keyCode));if(isSelected){this._addItem(value,choiceLabel,choiceId,undefined,customProperties,placeholder,keyCode);}}},{key:'_clearChoices',value:function _clearChoices(){this.store.dispatch((0,_index3.clearChoices)());}},{key:'_addGroup',value:function _addGroup(group,id){var _this21=this;var valueKey=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'value';var labelKey=arguments.length>3&&arguments[3]!==undefined?arguments[3]:'label';var groupChoices=(0,_utils.isType)('Object',group)?group.choices:Array.from(group.getElementsByTagName('OPTION'));var groupId=id?id:Math.floor(new Date().valueOf()*Math.random());var isDisabled=group.disabled?group.disabled:false;if(groupChoices){this.store.dispatch((0,_index3.addGroup)(group.label,groupId,true,isDisabled));groupChoices.forEach(function(option){var isOptDisabled=option.disabled||option.parentNode&&option.parentNode.disabled;_this21._addChoice(option[valueKey],(0,_utils.isType)('Object',option)?option[labelKey]:option.innerHTML,option.selected,isOptDisabled,groupId,option.customProperties,option.placeholder);});}else{this.store.dispatch((0,_index3.addGroup)(group.label,group.id,false,group.disabled));}}},{key:'_getTemplate',value:function _getTemplate(template){if(!template){return null;}
var templates=this.config.templates;for(var _len=arguments.length,args=Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}
return templates[template].apply(templates,args);}},{key:'_createTemplates',value:function _createTemplates(){var _this22=this;var globalClasses=this.config.classNames;var templates={containerOuter:function containerOuter(direction){return(0,_utils.strToEl)('\n          <div\n            class="'+globalClasses.containerOuter+'"\n            '+(_this22.isSelectElement?_this22.config.searchEnabled?'role="combobox" aria-autocomplete="list"':'role="listbox"':'')+'\n            data-type="'+_this22.passedElement.type+'"\n            '+(_this22.isSelectOneElement?'tabindex="0"':'')+'\n            aria-haspopup="true"\n            aria-expanded="false"\n            dir="'+direction+'"\n            >\n          </div>\n        ');},containerInner:function containerInner(){return(0,_utils.strToEl)('\n          <div class="'+globalClasses.containerInner+'"></div>\n        ');},itemList:function itemList(){var _classNames;var localClasses=(0,_classnames2.default)(globalClasses.list,(_classNames={},_defineProperty(_classNames,globalClasses.listSingle,_this22.isSelectOneElement),_defineProperty(_classNames,globalClasses.listItems,!_this22.isSelectOneElement),_classNames));return(0,_utils.strToEl)('\n          <div class="'+localClasses+'"></div>\n        ');},placeholder:function placeholder(value){return(0,_utils.strToEl)('\n          <div class="'+globalClasses.placeholder+'">\n            '+value+'\n          </div>\n        ');},item:function item(data){var _classNames2;var localClasses=(0,_classnames2.default)(globalClasses.item,(_classNames2={},_defineProperty(_classNames2,globalClasses.highlightedState,data.highlighted),_defineProperty(_classNames2,globalClasses.itemSelectable,!data.highlighted),_defineProperty(_classNames2,globalClasses.placeholder,data.placeholder),_classNames2));if(_this22.config.removeItemButton){var _classNames3;localClasses=(0,_classnames2.default)(globalClasses.item,(_classNames3={},_defineProperty(_classNames3,globalClasses.highlightedState,data.highlighted),_defineProperty(_classNames3,globalClasses.itemSelectable,!data.disabled),_defineProperty(_classNames3,globalClasses.placeholder,data.placeholder),_classNames3));return(0,_utils.strToEl)('\n            <div\n              class="'+localClasses+'"\n              data-item\n              data-id="'+data.id+'"\n              data-value="'+data.value+'"\n              data-deletable\n              '+(data.active?'aria-selected="true"':'')+'\n              '+(data.disabled?'aria-disabled="true"':'')+'\n              >\n              '+data.label+'<!--\n           --><button\n                type="button"\n                class="'+globalClasses.button+'"\n                data-button\n                aria-label="Remove item: \''+data.value+'\'"\n                >\n                Remove item\n              </button>\n            </div>\n          ');}
return(0,_utils.strToEl)('\n          <div\n            class="'+localClasses+'"\n            data-item\n            data-id="'+data.id+'"\n            data-value="'+data.value+'"\n            '+(data.active?'aria-selected="true"':'')+'\n            '+(data.disabled?'aria-disabled="true"':'')+'\n            >\n            '+data.label+'\n          </div>\n        ');},choiceList:function choiceList(){return(0,_utils.strToEl)('\n          <div\n            class="'+globalClasses.list+'"\n            dir="ltr"\n            role="listbox"\n            '+(!_this22.isSelectOneElement?'aria-multiselectable="true"':'')+'\n            >\n          </div>\n        ');},choiceGroup:function choiceGroup(data){var localClasses=(0,_classnames2.default)(globalClasses.group,_defineProperty({},globalClasses.itemDisabled,data.disabled));return(0,_utils.strToEl)('\n          <div\n            class="'+localClasses+'"\n            data-group\n            data-id="'+data.id+'"\n            data-value="'+data.value+'"\n            role="group"\n            '+(data.disabled?'aria-disabled="true"':'')+'\n            >\n            <div class="'+globalClasses.groupHeading+'">'+data.value+'</div>\n          </div>\n        ');},choice:function choice(data){var _classNames5;var localClasses=(0,_classnames2.default)(globalClasses.item,globalClasses.itemChoice,(_classNames5={},_defineProperty(_classNames5,globalClasses.itemDisabled,data.disabled),_defineProperty(_classNames5,globalClasses.itemSelectable,!data.disabled),_defineProperty(_classNames5,globalClasses.placeholder,data.placeholder),_classNames5));return(0,_utils.strToEl)('\n          <div\n            class="'+localClasses+'"\n            data-select-text="'+_this22.config.itemSelectText+'"\n            data-choice\n            data-id="'+data.id+'"\n            data-value="'+data.value+'"\n            '+(data.disabled?'data-choice-disabled aria-disabled="true"':'data-choice-selectable')+'\n            id="'+data.elementId+'"\n            '+(data.groupId>0?'role="treeitem"':'role="option"')+'\n            >\n            '+data.label+'\n          </div>\n        ');},input:function input(){var localClasses=(0,_classnames2.default)(globalClasses.input,globalClasses.inputCloned);return(0,_utils.strToEl)('\n          <input\n            type="text"\n            class="'+localClasses+'"\n            autocomplete="off"\n            autocapitalize="off"\n            spellcheck="false"\n            role="textbox"\n            aria-autocomplete="list"\n            >\n        ');},dropdown:function dropdown(){var localClasses=(0,_classnames2.default)(globalClasses.list,globalClasses.listDropdown);return(0,_utils.strToEl)('\n          <div\n            class="'+localClasses+'"\n            aria-expanded="false"\n            >\n          </div>\n        ');},notice:function notice(label){var _classNames6;var type=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var localClasses=(0,_classnames2.default)(globalClasses.item,globalClasses.itemChoice,(_classNames6={},_defineProperty(_classNames6,globalClasses.noResults,type==='no-results'),_defineProperty(_classNames6,globalClasses.noChoices,type==='no-choices'),_classNames6));return(0,_utils.strToEl)('\n          <div class="'+localClasses+'">\n            '+label+'\n          </div>\n        ');},option:function option(data){return(0,_utils.strToEl)('\n          <option value="'+data.value+'" selected>'+data.label+'</option>\n        ');}};var callbackTemplate=this.config.callbackOnCreateTemplates;var userTemplates={};if(callbackTemplate&&(0,_utils.isType)('Function',callbackTemplate)){userTemplates=callbackTemplate.call(this,_utils.strToEl);}
this.config.templates=(0,_utils.extend)(templates,userTemplates);}},{key:'_setLoading',value:function _setLoading(isLoading){this.store.dispatch((0,_index3.setIsLoading)(isLoading));}},{key:'_createInput',value:function _createInput(){var _this23=this;var direction=this.passedElement.getAttribute('dir')||'ltr';var containerOuter=this._getTemplate('containerOuter',direction);var containerInner=this._getTemplate('containerInner');var itemList=this._getTemplate('itemList');var choiceList=this._getTemplate('choiceList');var input=this._getTemplate('input');var dropdown=this._getTemplate('dropdown');this.containerOuter=containerOuter;this.containerInner=containerInner;this.input=input;this.choiceList=choiceList;this.itemList=itemList;this.dropdown=dropdown;this.passedElement.classList.add(this.config.classNames.input,this.config.classNames.hiddenState);this.passedElement.tabIndex='-1';var origStyle=this.passedElement.getAttribute('style');if(Boolean(origStyle)){this.passedElement.setAttribute('data-choice-orig-style',origStyle);}
this.passedElement.setAttribute('style','display:none;');this.passedElement.setAttribute('aria-hidden','true');this.passedElement.setAttribute('data-choice','active');(0,_utils.wrap)(this.passedElement,containerInner);(0,_utils.wrap)(containerInner,containerOuter);if(this.isSelectOneElement){input.placeholder=this.config.searchPlaceholderValue||'';}else if(this.placeholder){input.placeholder=this.placeholder;input.style.width=(0,_utils.getWidthOfInput)(input);}
if(!this.config.addItems){this.disable();}
containerOuter.appendChild(containerInner);containerOuter.appendChild(dropdown);containerInner.appendChild(itemList);if(!this.isTextElement){dropdown.appendChild(choiceList);}
if(this.isSelectMultipleElement||this.isTextElement){containerInner.appendChild(input);}else if(this.canSearch){dropdown.insertBefore(input,dropdown.firstChild);}
if(this.isSelectElement){var passedGroups=Array.from(this.passedElement.getElementsByTagName('OPTGROUP'));this.highlightPosition=0;this.isSearching=false;this._setLoading(true);if(passedGroups&&passedGroups.length){passedGroups.forEach(function(group){_this23._addGroup(group,group.id||null);});}else{var passedOptions=Array.from(this.passedElement.options);var filter=this.config.sortFilter;var allChoices=this.presetChoices;passedOptions.forEach(function(o){allChoices.push({value:o.value,label:o.innerHTML,selected:o.selected,disabled:o.disabled||o.parentNode.disabled,placeholder:o.hasAttribute('placeholder')});});if(this.config.shouldSort){allChoices.sort(filter);}
var hasSelectedChoice=allChoices.some(function(choice){return choice.selected;});allChoices.forEach(function(choice,index){if(_this23.isSelectOneElement){var shouldPreselect=hasSelectedChoice||!hasSelectedChoice&&index>0;_this23._addChoice(choice.value,choice.label,shouldPreselect?choice.selected:true,shouldPreselect?choice.disabled:false,undefined,choice.customProperties,choice.placeholder);}else{_this23._addChoice(choice.value,choice.label,choice.selected,choice.disabled,undefined,choice.customProperties,choice.placeholder);}});}
this._setLoading(false);}else if(this.isTextElement){this.presetItems.forEach(function(item){var itemType=(0,_utils.getType)(item);if(itemType==='Object'){if(!item.value){return;}
_this23._addItem(item.value,item.label,item.id,undefined,item.customProperties,item.placeholder);}else if(itemType==='String'){_this23._addItem(item);}});}}}]);return Choices;}();module.exports=Choices;}),(function(module,exports,__webpack_require__){;(function(global){'use strict'
function log(){console.log.apply(console,arguments)}
var defaultOptions={id:null,caseSensitive:false,include:[],shouldSort:true,searchFn:BitapSearcher,sortFn:function(a,b){return a.score-b.score},getFn:deepValue,keys:[],verbose:false,tokenize:false,matchAllTokens:false,tokenSeparator:/ +/g,minMatchCharLength:1,findAllMatches:false}
function Fuse(list,options){var key
this.list=list
this.options=options=options||{}
for(key in defaultOptions){if(!defaultOptions.hasOwnProperty(key)){continue;}
if(typeof defaultOptions[key]==='boolean'){this.options[key]=key in options?options[key]:defaultOptions[key];}else{this.options[key]=options[key]||defaultOptions[key]}}}
Fuse.VERSION='2.7.3'
Fuse.prototype.set=function(list){this.list=list
return list}
Fuse.prototype.search=function(pattern){if(this.options.verbose)log('\nSearch term:',pattern,'\n')
this.pattern=pattern
this.results=[]
this.resultMap={}
this._keyMap=null
this._prepareSearchers()
this._startSearch()
this._computeScore()
this._sort()
var output=this._format()
return output}
Fuse.prototype._prepareSearchers=function(){var options=this.options
var pattern=this.pattern
var searchFn=options.searchFn
var tokens=pattern.split(options.tokenSeparator)
var i=0
var len=tokens.length
if(this.options.tokenize){this.tokenSearchers=[]
for(;i<len;i++){this.tokenSearchers.push(new searchFn(tokens[i],options))}}
this.fullSeacher=new searchFn(pattern,options)}
Fuse.prototype._startSearch=function(){var options=this.options
var getFn=options.getFn
var list=this.list
var listLen=list.length
var keys=this.options.keys
var keysLen=keys.length
var key
var weight
var item=null
var i
var j
if(typeof list[0]==='string'){for(i=0;i<listLen;i++){this._analyze('',list[i],i,i)}}else{this._keyMap={}
for(i=0;i<listLen;i++){item=list[i]
for(j=0;j<keysLen;j++){key=keys[j]
if(typeof key!=='string'){weight=(1-key.weight)||1
this._keyMap[key.name]={weight:weight}
if(key.weight<=0||key.weight>1){throw new Error('Key weight has to be > 0 and <= 1')}
key=key.name}else{this._keyMap[key]={weight:1}}
this._analyze(key,getFn(item,key,[]),item,i)}}}}
Fuse.prototype._analyze=function(key,text,entity,index){var options=this.options
var words
var scores
var exists=false
var existingResult
var averageScore
var finalScore
var scoresLen
var mainSearchResult
var tokenSearcher
var termScores
var word
var tokenSearchResult
var hasMatchInText
var checkTextMatches
var i
var j
if(text===undefined||text===null){return}
scores=[]
var numTextMatches=0
if(typeof text==='string'){words=text.split(options.tokenSeparator)
if(options.verbose)log('---------\nKey:',key)
if(this.options.tokenize){for(i=0;i<this.tokenSearchers.length;i++){tokenSearcher=this.tokenSearchers[i]
if(options.verbose)log('Pattern:',tokenSearcher.pattern)
termScores=[]
hasMatchInText=false
for(j=0;j<words.length;j++){word=words[j]
tokenSearchResult=tokenSearcher.search(word)
var obj={}
if(tokenSearchResult.isMatch){obj[word]=tokenSearchResult.score
exists=true
hasMatchInText=true
scores.push(tokenSearchResult.score)}else{obj[word]=1
if(!this.options.matchAllTokens){scores.push(1)}}
termScores.push(obj)}
if(hasMatchInText){numTextMatches++}
if(options.verbose)log('Token scores:',termScores)}
averageScore=scores[0]
scoresLen=scores.length
for(i=1;i<scoresLen;i++){averageScore+=scores[i]}
averageScore=averageScore/scoresLen
if(options.verbose)log('Token score average:',averageScore)}
mainSearchResult=this.fullSeacher.search(text)
if(options.verbose)log('Full text score:',mainSearchResult.score)
finalScore=mainSearchResult.score
if(averageScore!==undefined){finalScore=(finalScore+averageScore)/2}
if(options.verbose)log('Score average:',finalScore)
checkTextMatches=(this.options.tokenize&&this.options.matchAllTokens)?numTextMatches>=this.tokenSearchers.length:true
if(options.verbose)log('Check Matches',checkTextMatches)
if((exists||mainSearchResult.isMatch)&&checkTextMatches){existingResult=this.resultMap[index]
if(existingResult){existingResult.output.push({key:key,score:finalScore,matchedIndices:mainSearchResult.matchedIndices})}else{this.resultMap[index]={item:entity,output:[{key:key,score:finalScore,matchedIndices:mainSearchResult.matchedIndices}]}
this.results.push(this.resultMap[index])}}}else if(isArray(text)){for(i=0;i<text.length;i++){this._analyze(key,text[i],entity,index)}}}
Fuse.prototype._computeScore=function(){var i
var j
var keyMap=this._keyMap
var totalScore
var output
var scoreLen
var score
var weight
var results=this.results
var bestScore
var nScore
if(this.options.verbose)log('\n\nComputing score:\n')
for(i=0;i<results.length;i++){totalScore=0
output=results[i].output
scoreLen=output.length
bestScore=1
for(j=0;j<scoreLen;j++){score=output[j].score
weight=keyMap?keyMap[output[j].key].weight:1
nScore=score*weight
if(weight!==1){bestScore=Math.min(bestScore,nScore)}else{totalScore+=nScore
output[j].nScore=nScore}}
if(bestScore===1){results[i].score=totalScore/scoreLen}else{results[i].score=bestScore}
if(this.options.verbose)log(results[i])}}
Fuse.prototype._sort=function(){var options=this.options
if(options.shouldSort){if(options.verbose)log('\n\nSorting....')
this.results.sort(options.sortFn)}}
Fuse.prototype._format=function(){var options=this.options
var getFn=options.getFn
var finalOutput=[]
var i
var len
var results=this.results
var replaceValue
var getItemAtIndex
var include=options.include
if(options.verbose)log('\n\nOutput:\n\n',results)
replaceValue=options.id?function(index){results[index].item=getFn(results[index].item,options.id,[])[0]}:function(){}
getItemAtIndex=function(index){var record=results[index]
var data
var j
var output
var _item
var _result
if(include.length>0){data={item:record.item}
if(include.indexOf('matches')!==-1){output=record.output
data.matches=[]
for(j=0;j<output.length;j++){_item=output[j]
_result={indices:_item.matchedIndices}
if(_item.key){_result.key=_item.key}
data.matches.push(_result)}}
if(include.indexOf('score')!==-1){data.score=results[index].score}}else{data=record.item}
return data}
for(i=0,len=results.length;i<len;i++){replaceValue(i)
finalOutput.push(getItemAtIndex(i))}
return finalOutput}
function deepValue(obj,path,list){var firstSegment
var remaining
var dotIndex
var value
var i
var len
if(!path){list.push(obj)}else{dotIndex=path.indexOf('.')
if(dotIndex!==-1){firstSegment=path.slice(0,dotIndex)
remaining=path.slice(dotIndex+1)}else{firstSegment=path}
value=obj[firstSegment]
if(value!==null&&value!==undefined){if(!remaining&&(typeof value==='string'||typeof value==='number')){list.push(value)}else if(isArray(value)){for(i=0,len=value.length;i<len;i++){deepValue(value[i],remaining,list)}}else if(remaining){deepValue(value,remaining,list)}}}
return list}
function isArray(obj){return Object.prototype.toString.call(obj)==='[object Array]'}
function BitapSearcher(pattern,options){options=options||{}
this.options=options
this.options.location=options.location||BitapSearcher.defaultOptions.location
this.options.distance='distance'in options?options.distance:BitapSearcher.defaultOptions.distance
this.options.threshold='threshold'in options?options.threshold:BitapSearcher.defaultOptions.threshold
this.options.maxPatternLength=options.maxPatternLength||BitapSearcher.defaultOptions.maxPatternLength
this.pattern=options.caseSensitive?pattern:pattern.toLowerCase()
this.patternLen=pattern.length
if(this.patternLen<=this.options.maxPatternLength){this.matchmask=1<<(this.patternLen-1)
this.patternAlphabet=this._calculatePatternAlphabet()}}
BitapSearcher.defaultOptions={location:0,distance:100,threshold:0.6,maxPatternLength:32}
BitapSearcher.prototype._calculatePatternAlphabet=function(){var mask={},i=0
for(i=0;i<this.patternLen;i++){mask[this.pattern.charAt(i)]=0}
for(i=0;i<this.patternLen;i++){mask[this.pattern.charAt(i)]|=1<<(this.pattern.length-i-1)}
return mask}
BitapSearcher.prototype._bitapScore=function(errors,location){var accuracy=errors/this.patternLen,proximity=Math.abs(this.options.location-location)
if(!this.options.distance){return proximity?1.0:accuracy}
return accuracy+(proximity/this.options.distance)}
BitapSearcher.prototype.search=function(text){var options=this.options
var i
var j
var textLen
var findAllMatches
var location
var threshold
var bestLoc
var binMin
var binMid
var binMax
var start,finish
var bitArr
var lastBitArr
var charMatch
var score
var locations
var matches
var isMatched
var matchMask
var matchedIndices
var matchesLen
var match
text=options.caseSensitive?text:text.toLowerCase()
if(this.pattern===text){return{isMatch:true,score:0,matchedIndices:[[0,text.length-1]]}}
if(this.patternLen>options.maxPatternLength){matches=text.match(new RegExp(this.pattern.replace(options.tokenSeparator,'|')))
isMatched=!!matches
if(isMatched){matchedIndices=[]
for(i=0,matchesLen=matches.length;i<matchesLen;i++){match=matches[i]
matchedIndices.push([text.indexOf(match),match.length-1])}}
return{isMatch:isMatched,score:isMatched?0.5:1,matchedIndices:matchedIndices}}
findAllMatches=options.findAllMatches
location=options.location
textLen=text.length
threshold=options.threshold
bestLoc=text.indexOf(this.pattern,location)
matchMask=[]
for(i=0;i<textLen;i++){matchMask[i]=0}
if(bestLoc!=-1){threshold=Math.min(this._bitapScore(0,bestLoc),threshold)
bestLoc=text.lastIndexOf(this.pattern,location+this.patternLen)
if(bestLoc!=-1){threshold=Math.min(this._bitapScore(0,bestLoc),threshold)}}
bestLoc=-1
score=1
locations=[]
binMax=this.patternLen+textLen
for(i=0;i<this.patternLen;i++){binMin=0
binMid=binMax
while(binMin<binMid){if(this._bitapScore(i,location+binMid)<=threshold){binMin=binMid}else{binMax=binMid}
binMid=Math.floor((binMax-binMin)/2+binMin)}
binMax=binMid
start=Math.max(1,location-binMid+1)
if(findAllMatches){finish=textLen;}else{finish=Math.min(location+binMid,textLen)+this.patternLen}
bitArr=Array(finish+2)
bitArr[finish+1]=(1<<i)-1
for(j=finish;j>=start;j--){charMatch=this.patternAlphabet[text.charAt(j-1)]
if(charMatch){matchMask[j-1]=1}
bitArr[j]=((bitArr[j+1]<<1)|1)&charMatch
if(i!==0){bitArr[j]|=(((lastBitArr[j+1]|lastBitArr[j])<<1)|1)|lastBitArr[j+1]}
if(bitArr[j]&this.matchmask){score=this._bitapScore(i,j-1)
if(score<=threshold){threshold=score
bestLoc=j-1
locations.push(bestLoc)
if(bestLoc<=location){break}
start=Math.max(1,2*location-bestLoc)}}}
if(this._bitapScore(i+1,location)>threshold){break}
lastBitArr=bitArr}
matchedIndices=this._getMatchedIndices(matchMask)
return{isMatch:bestLoc>=0,score:score===0?0.001:score,matchedIndices:matchedIndices}}
BitapSearcher.prototype._getMatchedIndices=function(matchMask){var matchedIndices=[]
var start=-1
var end=-1
var i=0
var match
var len=matchMask.length
for(;i<len;i++){match=matchMask[i]
if(match&&start===-1){start=i}else if(!match&&start!==-1){end=i-1
if((end-start)+1>=this.options.minMatchCharLength){matchedIndices.push([start,end])}
start=-1}}
if(matchMask[i-1]){if((i-1-start)+1>=this.options.minMatchCharLength){matchedIndices.push([start,i-1])}}
return matchedIndices}
if(true){module.exports=Fuse}else if(typeof define==='function'&&define.amd){define(function(){return Fuse})}else{global.Fuse=Fuse}})(this);}),(function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/(function(){'use strict';var hasOwn={}.hasOwnProperty;function classNames(){var classes=[];for(var i=0;i<arguments.length;i++){var arg=arguments[i];if(!arg)continue;var argType=typeof arg;if(argType==='string'||argType==='number'){classes.push(arg);}else if(Array.isArray(arg)){classes.push(classNames.apply(null,arg));}else if(argType==='object'){for(var key in arg){if(hasOwn.call(arg,key)&&arg[key]){classes.push(key);}}}}
return classes.join(' ');}
if(typeof module!=='undefined'&&module.exports){module.exports=classNames;}else if(true){!(__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_RESULT__=function(){return classNames;}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),__WEBPACK_AMD_DEFINE_RESULT__!==undefined&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__));}else{window.classNames=classNames;}}());}),(function(module,exports,__webpack_require__){'use strict';Object.defineProperty(exports,"__esModule",{value:true});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();var _redux=__webpack_require__(5);var _index=__webpack_require__(26);var _index2=_interopRequireDefault(_index);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}
function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}
function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}
var Store=function(){function Store(){_classCallCheck(this,Store);this.store=(0,_redux.createStore)(_index2.default,window.devToolsExtension?window.devToolsExtension():undefined);}
_createClass(Store,[{key:'getState',value:function getState(){return this.store.getState();}},{key:'dispatch',value:function dispatch(action){this.store.dispatch(action);}},{key:'subscribe',value:function subscribe(onChange){this.store.subscribe(onChange);}},{key:'isLoading',value:function isLoading(){var state=this.store.getState();return state.general.loading;}},{key:'getItems',value:function getItems(){var state=this.store.getState();return state.items;}},{key:'getItemsFilteredByActive',value:function getItemsFilteredByActive(){var items=this.getItems();var values=items.filter(function(item){return item.active===true;},[]);return values;}},{key:'getItemsReducedToValues',value:function getItemsReducedToValues(){var items=arguments.length>0&&arguments[0]!==undefined?arguments[0]:this.getItems();var values=items.reduce(function(prev,current){prev.push(current.value);return prev;},[]);return values;}},{key:'getChoices',value:function getChoices(){var state=this.store.getState();return state.choices;}},{key:'getChoicesFilteredByActive',value:function getChoicesFilteredByActive(){var choices=this.getChoices();var values=choices.filter(function(choice){return choice.active===true;});return values;}},{key:'getChoicesFilteredBySelectable',value:function getChoicesFilteredBySelectable(){var choices=this.getChoices();var values=choices.filter(function(choice){return choice.disabled!==true;});return values;}},{key:'getSearchableChoices',value:function getSearchableChoices(){var filtered=this.getChoicesFilteredBySelectable();return filtered.filter(function(choice){return choice.placeholder!==true;});}},{key:'getChoiceById',value:function getChoiceById(id){if(id){var choices=this.getChoicesFilteredByActive();var foundChoice=choices.find(function(choice){return choice.id===parseInt(id,10);});return foundChoice;}
return false;}},{key:'getGroups',value:function getGroups(){var state=this.store.getState();return state.groups;}},{key:'getGroupsFilteredByActive',value:function getGroupsFilteredByActive(){var groups=this.getGroups();var choices=this.getChoices();var values=groups.filter(function(group){var isActive=group.active===true&&group.disabled===false;var hasActiveOptions=choices.some(function(choice){return choice.active===true&&choice.disabled===false;});return isActive&&hasActiveOptions;},[]);return values;}},{key:'getGroupById',value:function getGroupById(id){var groups=this.getGroups();var foundGroup=groups.find(function(group){return group.id===id;});return foundGroup;}},{key:'getPlaceholderChoice',value:function getPlaceholderChoice(){var choices=this.getChoices();var placeholderChoice=[].concat(_toConsumableArray(choices)).reverse().find(function(choice){return choice.placeholder===true;});return placeholderChoice;}}]);return Store;}();exports.default=Store;module.exports=Store;}),(function(module,exports,__webpack_require__){'use strict';exports.__esModule=true;exports.compose=exports.applyMiddleware=exports.bindActionCreators=exports.combineReducers=exports.createStore=undefined;var _createStore=__webpack_require__(6);var _createStore2=_interopRequireDefault(_createStore);var _combineReducers=__webpack_require__(21);var _combineReducers2=_interopRequireDefault(_combineReducers);var _bindActionCreators=__webpack_require__(23);var _bindActionCreators2=_interopRequireDefault(_bindActionCreators);var _applyMiddleware=__webpack_require__(24);var _applyMiddleware2=_interopRequireDefault(_applyMiddleware);var _compose=__webpack_require__(25);var _compose2=_interopRequireDefault(_compose);var _warning=__webpack_require__(22);var _warning2=_interopRequireDefault(_warning);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
function isCrushed(){}
if(false){(0,_warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. '+'This means that you are running a slower development build of Redux. '+'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify '+'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) '+'to ensure you have the correct code for your production build.');}
exports.createStore=_createStore2['default'];exports.combineReducers=_combineReducers2['default'];exports.bindActionCreators=_bindActionCreators2['default'];exports.applyMiddleware=_applyMiddleware2['default'];exports.compose=_compose2['default'];}),(function(module,exports,__webpack_require__){'use strict';exports.__esModule=true;exports.ActionTypes=undefined;exports['default']=createStore;var _isPlainObject=__webpack_require__(7);var _isPlainObject2=_interopRequireDefault(_isPlainObject);var _symbolObservable=__webpack_require__(17);var _symbolObservable2=_interopRequireDefault(_symbolObservable);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var ActionTypes=exports.ActionTypes={INIT:'@@redux/INIT'};function createStore(reducer,preloadedState,enhancer){var _ref2;if(typeof preloadedState==='function'&&typeof enhancer==='undefined'){enhancer=preloadedState;preloadedState=undefined;}
if(typeof enhancer!=='undefined'){if(typeof enhancer!=='function'){throw new Error('Expected the enhancer to be a function.');}
return enhancer(createStore)(reducer,preloadedState);}
if(typeof reducer!=='function'){throw new Error('Expected the reducer to be a function.');}
var currentReducer=reducer;var currentState=preloadedState;var currentListeners=[];var nextListeners=currentListeners;var isDispatching=false;function ensureCanMutateNextListeners(){if(nextListeners===currentListeners){nextListeners=currentListeners.slice();}}
function getState(){return currentState;}
function subscribe(listener){if(typeof listener!=='function'){throw new Error('Expected listener to be a function.');}
var isSubscribed=true;ensureCanMutateNextListeners();nextListeners.push(listener);return function unsubscribe(){if(!isSubscribed){return;}
isSubscribed=false;ensureCanMutateNextListeners();var index=nextListeners.indexOf(listener);nextListeners.splice(index,1);};}
function dispatch(action){if(!(0,_isPlainObject2['default'])(action)){throw new Error('Actions must be plain objects. '+'Use custom middleware for async actions.');}
if(typeof action.type==='undefined'){throw new Error('Actions may not have an undefined "type" property. '+'Have you misspelled a constant?');}
if(isDispatching){throw new Error('Reducers may not dispatch actions.');}
try{isDispatching=true;currentState=currentReducer(currentState,action);}finally{isDispatching=false;}
var listeners=currentListeners=nextListeners;for(var i=0;i<listeners.length;i++){var listener=listeners[i];listener();}
return action;}
function replaceReducer(nextReducer){if(typeof nextReducer!=='function'){throw new Error('Expected the nextReducer to be a function.');}
currentReducer=nextReducer;dispatch({type:ActionTypes.INIT});}
function observable(){var _ref;var outerSubscribe=subscribe;return _ref={subscribe:function subscribe(observer){if(typeof observer!=='object'){throw new TypeError('Expected the observer to be an object.');}
function observeState(){if(observer.next){observer.next(getState());}}
observeState();var unsubscribe=outerSubscribe(observeState);return{unsubscribe:unsubscribe};}},_ref[_symbolObservable2['default']]=function(){return this;},_ref;}
dispatch({type:ActionTypes.INIT});return _ref2={dispatch:dispatch,subscribe:subscribe,getState:getState,replaceReducer:replaceReducer},_ref2[_symbolObservable2['default']]=observable,_ref2;}}),(function(module,exports,__webpack_require__){var baseGetTag=__webpack_require__(8),getPrototype=__webpack_require__(14),isObjectLike=__webpack_require__(16);var objectTag='[object Object]';var funcProto=Function.prototype,objectProto=Object.prototype;var funcToString=funcProto.toString;var hasOwnProperty=objectProto.hasOwnProperty;var objectCtorString=funcToString.call(Object);function isPlainObject(value){if(!isObjectLike(value)||baseGetTag(value)!=objectTag){return false;}
var proto=getPrototype(value);if(proto===null){return true;}
var Ctor=hasOwnProperty.call(proto,'constructor')&&proto.constructor;return typeof Ctor=='function'&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString;}
module.exports=isPlainObject;}),(function(module,exports,__webpack_require__){var Symbol=__webpack_require__(9),getRawTag=__webpack_require__(12),objectToString=__webpack_require__(13);var nullTag='[object Null]',undefinedTag='[object Undefined]';var symToStringTag=Symbol?Symbol.toStringTag:undefined;function baseGetTag(value){if(value==null){return value===undefined?undefinedTag:nullTag;}
return(symToStringTag&&symToStringTag in Object(value))?getRawTag(value):objectToString(value);}
module.exports=baseGetTag;}),(function(module,exports,__webpack_require__){var root=__webpack_require__(10);var Symbol=root.Symbol;module.exports=Symbol;}),(function(module,exports,__webpack_require__){var freeGlobal=__webpack_require__(11);var freeSelf=typeof self=='object'&&self&&self.Object===Object&&self;var root=freeGlobal||freeSelf||Function('return this')();module.exports=root;}),(function(module,exports){(function(global){var freeGlobal=typeof global=='object'&&global&&global.Object===Object&&global;module.exports=freeGlobal;}.call(exports,(function(){return this;}())))}),(function(module,exports,__webpack_require__){var Symbol=__webpack_require__(9);var objectProto=Object.prototype;var hasOwnProperty=objectProto.hasOwnProperty;var nativeObjectToString=objectProto.toString;var symToStringTag=Symbol?Symbol.toStringTag:undefined;function getRawTag(value){var isOwn=hasOwnProperty.call(value,symToStringTag),tag=value[symToStringTag];try{value[symToStringTag]=undefined;var unmasked=true;}catch(e){}
var result=nativeObjectToString.call(value);if(unmasked){if(isOwn){value[symToStringTag]=tag;}else{delete value[symToStringTag];}}
return result;}
module.exports=getRawTag;}),(function(module,exports){var objectProto=Object.prototype;var nativeObjectToString=objectProto.toString;function objectToString(value){return nativeObjectToString.call(value);}
module.exports=objectToString;}),(function(module,exports,__webpack_require__){var overArg=__webpack_require__(15);var getPrototype=overArg(Object.getPrototypeOf,Object);module.exports=getPrototype;}),(function(module,exports){function overArg(func,transform){return function(arg){return func(transform(arg));};}
module.exports=overArg;}),(function(module,exports){function isObjectLike(value){return value!=null&&typeof value=='object';}
module.exports=isObjectLike;}),(function(module,exports,__webpack_require__){module.exports=__webpack_require__(18);}),(function(module,exports,__webpack_require__){(function(global,module){'use strict';Object.defineProperty(exports,"__esModule",{value:true});var _ponyfill=__webpack_require__(20);var _ponyfill2=_interopRequireDefault(_ponyfill);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
var root;if(typeof self!=='undefined'){root=self;}else if(typeof window!=='undefined'){root=window;}else if(typeof global!=='undefined'){root=global;}else if(true){root=module;}else{root=Function('return this')();}
var result=(0,_ponyfill2['default'])(root);exports['default']=result;}.call(exports,(function(){return this;}()),__webpack_require__(19)(module)))}),(function(module,exports){module.exports=function(module){if(!module.webpackPolyfill){module.deprecate=function(){};module.paths=[];module.children=[];module.webpackPolyfill=1;}
return module;}}),(function(module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});exports['default']=symbolObservablePonyfill;function symbolObservablePonyfill(root){var result;var _Symbol=root.Symbol;if(typeof _Symbol==='function'){if(_Symbol.observable){result=_Symbol.observable;}else{result=_Symbol('observable');_Symbol.observable=result;}}else{result='@@observable';}
return result;};}),(function(module,exports,__webpack_require__){'use strict';exports.__esModule=true;exports['default']=combineReducers;var _createStore=__webpack_require__(6);var _isPlainObject=__webpack_require__(7);var _isPlainObject2=_interopRequireDefault(_isPlainObject);var _warning=__webpack_require__(22);var _warning2=_interopRequireDefault(_warning);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
function getUndefinedStateErrorMessage(key,action){var actionType=action&&action.type;var actionName=actionType&&'"'+actionType.toString()+'"'||'an action';return 'Given action '+actionName+', reducer "'+key+'" returned undefined. '+'To ignore an action, you must explicitly return the previous state. '+'If you want this reducer to hold no value, you can return null instead of undefined.';}
function getUnexpectedStateShapeWarningMessage(inputState,reducers,action,unexpectedKeyCache){var reducerKeys=Object.keys(reducers);var argumentName=action&&action.type===_createStore.ActionTypes.INIT?'preloadedState argument passed to createStore':'previous state received by the reducer';if(reducerKeys.length===0){return 'Store does not have a valid reducer. Make sure the argument passed '+'to combineReducers is an object whose values are reducers.';}
if(!(0,_isPlainObject2['default'])(inputState)){return 'The '+argumentName+' has unexpected type of "'+{}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1]+'". Expected argument to be an object with the following '+('keys: "'+reducerKeys.join('", "')+'"');}
var unexpectedKeys=Object.keys(inputState).filter(function(key){return!reducers.hasOwnProperty(key)&&!unexpectedKeyCache[key];});unexpectedKeys.forEach(function(key){unexpectedKeyCache[key]=true;});if(unexpectedKeys.length>0){return 'Unexpected '+(unexpectedKeys.length>1?'keys':'key')+' '+('"'+unexpectedKeys.join('", "')+'" found in '+argumentName+'. ')+'Expected to find one of the known reducer keys instead: '+('"'+reducerKeys.join('", "')+'". Unexpected keys will be ignored.');}}
function assertReducerShape(reducers){Object.keys(reducers).forEach(function(key){var reducer=reducers[key];var initialState=reducer(undefined,{type:_createStore.ActionTypes.INIT});if(typeof initialState==='undefined'){throw new Error('Reducer "'+key+'" returned undefined during initialization. '+'If the state passed to the reducer is undefined, you must '+'explicitly return the initial state. The initial state may '+'not be undefined. If you don\'t want to set a value for this reducer, '+'you can use null instead of undefined.');}
var type='@@redux/PROBE_UNKNOWN_ACTION_'+Math.random().toString(36).substring(7).split('').join('.');if(typeof reducer(undefined,{type:type})==='undefined'){throw new Error('Reducer "'+key+'" returned undefined when probed with a random type. '+('Don\'t try to handle '+_createStore.ActionTypes.INIT+' or other actions in "redux/*" ')+'namespace. They are considered private. Instead, you must return the '+'current state for any unknown actions, unless it is undefined, '+'in which case you must return the initial state, regardless of the '+'action type. The initial state may not be undefined, but can be null.');}});}
function combineReducers(reducers){var reducerKeys=Object.keys(reducers);var finalReducers={};for(var i=0;i<reducerKeys.length;i++){var key=reducerKeys[i];if(false){if(typeof reducers[key]==='undefined'){(0,_warning2['default'])('No reducer provided for key "'+key+'"');}}
if(typeof reducers[key]==='function'){finalReducers[key]=reducers[key];}}
var finalReducerKeys=Object.keys(finalReducers);var unexpectedKeyCache=void 0;if(false){unexpectedKeyCache={};}
var shapeAssertionError=void 0;try{assertReducerShape(finalReducers);}catch(e){shapeAssertionError=e;}
return function combination(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var action=arguments[1];if(shapeAssertionError){throw shapeAssertionError;}
if(false){var warningMessage=getUnexpectedStateShapeWarningMessage(state,finalReducers,action,unexpectedKeyCache);if(warningMessage){(0,_warning2['default'])(warningMessage);}}
var hasChanged=false;var nextState={};for(var _i=0;_i<finalReducerKeys.length;_i++){var _key=finalReducerKeys[_i];var reducer=finalReducers[_key];var previousStateForKey=state[_key];var nextStateForKey=reducer(previousStateForKey,action);if(typeof nextStateForKey==='undefined'){var errorMessage=getUndefinedStateErrorMessage(_key,action);throw new Error(errorMessage);}
nextState[_key]=nextStateForKey;hasChanged=hasChanged||nextStateForKey!==previousStateForKey;}
return hasChanged?nextState:state;};}}),(function(module,exports){'use strict';exports.__esModule=true;exports['default']=warning;function warning(message){if(typeof console!=='undefined'&&typeof console.error==='function'){console.error(message);}
try{throw new Error(message);}catch(e){}}}),(function(module,exports){'use strict';exports.__esModule=true;exports['default']=bindActionCreators;function bindActionCreator(actionCreator,dispatch){return function(){return dispatch(actionCreator.apply(undefined,arguments));};}
function bindActionCreators(actionCreators,dispatch){if(typeof actionCreators==='function'){return bindActionCreator(actionCreators,dispatch);}
if(typeof actionCreators!=='object'||actionCreators===null){throw new Error('bindActionCreators expected an object or a function, instead received '+(actionCreators===null?'null':typeof actionCreators)+'. '+'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');}
var keys=Object.keys(actionCreators);var boundActionCreators={};for(var i=0;i<keys.length;i++){var key=keys[i];var actionCreator=actionCreators[key];if(typeof actionCreator==='function'){boundActionCreators[key]=bindActionCreator(actionCreator,dispatch);}}
return boundActionCreators;}}),(function(module,exports,__webpack_require__){'use strict';exports.__esModule=true;var _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};exports['default']=applyMiddleware;var _compose=__webpack_require__(25);var _compose2=_interopRequireDefault(_compose);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{'default':obj};}
function applyMiddleware(){for(var _len=arguments.length,middlewares=Array(_len),_key=0;_key<_len;_key++){middlewares[_key]=arguments[_key];}
return function(createStore){return function(reducer,preloadedState,enhancer){var store=createStore(reducer,preloadedState,enhancer);var _dispatch=store.dispatch;var chain=[];var middlewareAPI={getState:store.getState,dispatch:function dispatch(action){return _dispatch(action);}};chain=middlewares.map(function(middleware){return middleware(middlewareAPI);});_dispatch=_compose2['default'].apply(undefined,chain)(store.dispatch);return _extends({},store,{dispatch:_dispatch});};};}}),(function(module,exports){"use strict";exports.__esModule=true;exports["default"]=compose;function compose(){for(var _len=arguments.length,funcs=Array(_len),_key=0;_key<_len;_key++){funcs[_key]=arguments[_key];}
if(funcs.length===0){return function(arg){return arg;};}
if(funcs.length===1){return funcs[0];}
return funcs.reduce(function(a,b){return function(){return a(b.apply(undefined,arguments));};});}}),(function(module,exports,__webpack_require__){'use strict';Object.defineProperty(exports,"__esModule",{value:true});var _redux=__webpack_require__(5);var _items=__webpack_require__(27);var _items2=_interopRequireDefault(_items);var _groups=__webpack_require__(28);var _groups2=_interopRequireDefault(_groups);var _choices=__webpack_require__(29);var _choices2=_interopRequireDefault(_choices);var _general=__webpack_require__(30);var _general2=_interopRequireDefault(_general);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}
var appReducer=(0,_redux.combineReducers)({items:_items2.default,groups:_groups2.default,choices:_choices2.default,general:_general2.default});var rootReducer=function rootReducer(passedState,action){var state=passedState;if(action.type==='CLEAR_ALL'){state=undefined;}
return appReducer(state,action);};exports.default=rootReducer;}),(function(module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}
var items=function items(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var action=arguments[1];switch(action.type){case 'ADD_ITEM':{var newState=[].concat(_toConsumableArray(state),[{id:action.id,choiceId:action.choiceId,groupId:action.groupId,value:action.value,label:action.label,active:true,highlighted:false,customProperties:action.customProperties,placeholder:action.placeholder||false,keyCode:null}]);return newState.map(function(item){if(item.highlighted){item.highlighted=false;}
return item;});}
case 'REMOVE_ITEM':{return state.map(function(item){if(item.id===action.id){item.active=false;}
return item;});}
case 'HIGHLIGHT_ITEM':{return state.map(function(item){if(item.id===action.id){item.highlighted=action.highlighted;}
return item;});}
default:{return state;}}};exports.default=items;}),(function(module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}
var groups=function groups(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var action=arguments[1];switch(action.type){case 'ADD_GROUP':{return[].concat(_toConsumableArray(state),[{id:action.id,value:action.value,active:action.active,disabled:action.disabled}]);}
case 'CLEAR_CHOICES':{return state.groups=[];}
default:{return state;}}};exports.default=groups;}),(function(module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++){arr2[i]=arr[i];}return arr2;}else{return Array.from(arr);}}
var choices=function choices(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var action=arguments[1];switch(action.type){case 'ADD_CHOICE':{return[].concat(_toConsumableArray(state),[{id:action.id,elementId:action.elementId,groupId:action.groupId,value:action.value,label:action.label||action.value,disabled:action.disabled||false,selected:false,active:true,score:9999,customProperties:action.customProperties,placeholder:action.placeholder||false,keyCode:null}]);}
case 'ADD_ITEM':{var newState=state;if(action.activateOptions){newState=state.map(function(choice){choice.active=action.active;return choice;});}
if(action.choiceId>-1){newState=state.map(function(choice){if(choice.id===parseInt(action.choiceId,10)){choice.selected=true;}
return choice;});}
return newState;}
case 'REMOVE_ITEM':{if(action.choiceId>-1){return state.map(function(choice){if(choice.id===parseInt(action.choiceId,10)){choice.selected=false;}
return choice;});}
return state;}
case 'FILTER_CHOICES':{var filteredResults=action.results;var filteredState=state.map(function(choice){choice.active=filteredResults.some(function(result){if(result.item.id===choice.id){choice.score=result.score;return true;}
return false;});return choice;});return filteredState;}
case 'ACTIVATE_CHOICES':{return state.map(function(choice){choice.active=action.active;return choice;});}
case 'CLEAR_CHOICES':{return state.choices=[];}
default:{return state;}}};exports.default=choices;}),(function(module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});var general=function general(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{loading:false};var action=arguments[1];switch(action.type){case 'LOADING':{return{loading:action.isLoading};}
default:{return state;}}};exports.default=general;}),(function(module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});var addItem=exports.addItem=function addItem(value,label,id,choiceId,groupId,customProperties,placeholder,keyCode){return{type:'ADD_ITEM',value:value,label:label,id:id,choiceId:choiceId,groupId:groupId,customProperties:customProperties,placeholder:placeholder,keyCode:keyCode};};var removeItem=exports.removeItem=function removeItem(id,choiceId){return{type:'REMOVE_ITEM',id:id,choiceId:choiceId};};var highlightItem=exports.highlightItem=function highlightItem(id,highlighted){return{type:'HIGHLIGHT_ITEM',id:id,highlighted:highlighted};};var addChoice=exports.addChoice=function addChoice(value,label,id,groupId,disabled,elementId,customProperties,placeholder,keyCode){return{type:'ADD_CHOICE',value:value,label:label,id:id,groupId:groupId,disabled:disabled,elementId:elementId,customProperties:customProperties,placeholder:placeholder,keyCode:keyCode};};var filterChoices=exports.filterChoices=function filterChoices(results){return{type:'FILTER_CHOICES',results:results};};var activateChoices=exports.activateChoices=function activateChoices(){var active=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;return{type:'ACTIVATE_CHOICES',active:active};};var clearChoices=exports.clearChoices=function clearChoices(){return{type:'CLEAR_CHOICES'};};var addGroup=exports.addGroup=function addGroup(value,id,active,disabled){return{type:'ADD_GROUP',value:value,id:id,active:active,disabled:disabled};};var clearAll=exports.clearAll=function clearAll(){return{type:'CLEAR_ALL'};};var setIsLoading=exports.setIsLoading=function setIsLoading(isLoading){return{type:'LOADING',isLoading:isLoading};};}),(function(module,exports){'use strict';Object.defineProperty(exports,"__esModule",{value:true});var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj;}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};var capitalise=exports.capitalise=function capitalise(str){return str.replace(/\w\S*/g,function(txt){return txt.charAt(0).toUpperCase()+txt.substr(1).toLowerCase();});};var generateChars=exports.generateChars=function generateChars(length){var chars='';for(var i=0;i<length;i++){var randomChar=getRandomNumber(0,36);chars+=randomChar.toString(36);}
return chars;};var generateId=exports.generateId=function generateId(element,prefix){var id=element.id||element.name&&element.name+'-'+generateChars(2)||generateChars(4);id=id.replace(/(:|\.|\[|\]|,)/g,'');id=prefix+id;return id;};var getType=exports.getType=function getType(obj){return Object.prototype.toString.call(obj).slice(8,-1);};var isType=exports.isType=function isType(type,obj){var clas=getType(obj);return obj!==undefined&&obj!==null&&clas===type;};var isNode=exports.isNode=function isNode(o){return(typeof Node==='undefined'?'undefined':_typeof(Node))==="object"?o instanceof Node:o&&(typeof o==='undefined'?'undefined':_typeof(o))==="object"&&typeof o.nodeType==="number"&&typeof o.nodeName==="string";};var isElement=exports.isElement=function isElement(o){return(typeof HTMLElement==='undefined'?'undefined':_typeof(HTMLElement))==="object"?o instanceof HTMLElement:o&&(typeof o==='undefined'?'undefined':_typeof(o))==="object"&&o!==null&&o.nodeType===1&&typeof o.nodeName==="string";};var extend=exports.extend=function extend(){var extended={};var length=arguments.length;var merge=function merge(obj){for(var prop in obj){if(Object.prototype.hasOwnProperty.call(obj,prop)){if(isType('Object',obj[prop])){extended[prop]=extend(true,extended[prop],obj[prop]);}else{extended[prop]=obj[prop];}}}};for(var i=0;i<length;i++){var obj=arguments[i];if(isType('Object',obj)){merge(obj);}}
return extended;};var whichTransitionEvent=exports.whichTransitionEvent=function whichTransitionEvent(){var t,el=document.createElement('fakeelement');var transitions={'transition':'transitionend','OTransition':'oTransitionEnd','MozTransition':'transitionend','WebkitTransition':'webkitTransitionEnd'};for(t in transitions){if(el.style[t]!==undefined){return transitions[t];}}};var whichAnimationEvent=exports.whichAnimationEvent=function whichAnimationEvent(){var t,el=document.createElement('fakeelement');var animations={'animation':'animationend','OAnimation':'oAnimationEnd','MozAnimation':'animationend','WebkitAnimation':'webkitAnimationEnd'};for(t in animations){if(el.style[t]!==undefined){return animations[t];}}};var getParentsUntil=exports.getParentsUntil=function getParentsUntil(elem,parent,selector){var parents=[];for(;elem&&elem!==document;elem=elem.parentNode){if(parent){var parentType=parent.charAt(0);if(parentType==='.'){if(elem.classList.contains(parent.substr(1))){break;}}
if(parentType==='#'){if(elem.id===parent.substr(1)){break;}}
if(parentType==='['){if(elem.hasAttribute(parent.substr(1,parent.length-1))){break;}}
if(elem.tagName.toLowerCase()===parent){break;}}
if(selector){var selectorType=selector.charAt(0);if(selectorType==='.'){if(elem.classList.contains(selector.substr(1))){parents.push(elem);}}
if(selectorType==='#'){if(elem.id===selector.substr(1)){parents.push(elem);}}
if(selectorType==='['){if(elem.hasAttribute(selector.substr(1,selector.length-1))){parents.push(elem);}}
if(elem.tagName.toLowerCase()===selector){parents.push(elem);}}else{parents.push(elem);}}
if(parents.length===0){return null;}else{return parents;}};var wrap=exports.wrap=function wrap(element,wrapper){wrapper=wrapper||document.createElement('div');if(element.nextSibling){element.parentNode.insertBefore(wrapper,element.nextSibling);}else{element.parentNode.appendChild(wrapper);}
return wrapper.appendChild(element);};var getSiblings=exports.getSiblings=function getSiblings(elem){var siblings=[];var sibling=elem.parentNode.firstChild;for(;sibling;sibling=sibling.nextSibling){if(sibling.nodeType===1&&sibling!==elem){siblings.push(sibling);}}
return siblings;};var findAncestor=exports.findAncestor=function findAncestor(el,cls){while((el=el.parentElement)&&!el.classList.contains(cls)){}
return el;};var findAncestorByAttrName=exports.findAncestorByAttrName=function findAncestorByAttrName(el,attr){var target=el;while(target){if(target.hasAttribute(attr)){return target;}
target=target.parentElement;}
return null;};var debounce=exports.debounce=function debounce(func,wait,immediate){var timeout;return function(){var context=this,args=arguments;var later=function later(){timeout=null;if(!immediate)func.apply(context,args);};var callNow=immediate&&!timeout;clearTimeout(timeout);timeout=setTimeout(later,wait);if(callNow)func.apply(context,args);};};var getElemDistance=exports.getElemDistance=function getElemDistance(el){var location=0;if(el.offsetParent){do{location+=el.offsetTop;el=el.offsetParent;}while(el);}
return location>=0?location:0;};var getElementOffset=exports.getElementOffset=function getElementOffset(el,offset){var elOffset=offset;if(elOffset>1)elOffset=1;if(elOffset>0)elOffset=0;return Math.max(el.offsetHeight*elOffset);};var getAdjacentEl=exports.getAdjacentEl=function getAdjacentEl(startEl,className){var direction=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;if(!startEl||!className)return;var parent=startEl.parentNode.parentNode;var children=Array.from(parent.querySelectorAll(className));var startPos=children.indexOf(startEl);var operatorDirection=direction>0?1:-1;return children[startPos+operatorDirection];};var getScrollPosition=exports.getScrollPosition=function getScrollPosition(position){if(position==='bottom'){return Math.max((window.scrollY||window.pageYOffset)+(window.innerHeight||document.documentElement.clientHeight));}else{return window.scrollY||window.pageYOffset;}};var isInView=exports.isInView=function isInView(el,position,offset){return this.getScrollPosition(position)>this.getElemDistance(el)+this.getElementOffset(el,offset)?true:false;};var isScrolledIntoView=exports.isScrolledIntoView=function isScrolledIntoView(el,parent){var direction=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;if(!el)return;var isVisible=void 0;if(direction>0){isVisible=parent.scrollTop+parent.offsetHeight>=el.offsetTop+el.offsetHeight;}else{isVisible=el.offsetTop>=parent.scrollTop;}
return isVisible;};var stripHTML=exports.stripHTML=function stripHTML(html){return html.replace(/&/g,'&amp;').replace(/>/g,'&rt;').replace(/</g,'&lt;').replace(/"/g,'&quot;');};var addAnimation=exports.addAnimation=function addAnimation(el,animation){var animationEvent=whichAnimationEvent();var removeAnimation=function removeAnimation(){el.classList.remove(animation);el.removeEventListener(animationEvent,removeAnimation,false);};el.classList.add(animation);el.addEventListener(animationEvent,removeAnimation,false);};var getRandomNumber=exports.getRandomNumber=function getRandomNumber(min,max){return Math.floor(Math.random()*(max-min)+min);};var strToEl=exports.strToEl=function(){var tmpEl=document.createElement('div');return function(str){var cleanedInput=str.trim();var r=void 0;tmpEl.innerHTML=cleanedInput;r=tmpEl.children[0];while(tmpEl.firstChild){tmpEl.removeChild(tmpEl.firstChild);}
return r;};}();var getWidthOfInput=exports.getWidthOfInput=function getWidthOfInput(input){var value=input.value||input.placeholder;var width=input.offsetWidth;if(value){var testEl=strToEl('<span>'+stripHTML(value)+'</span>');testEl.style.position='absolute';testEl.style.padding='0';testEl.style.top='-9999px';testEl.style.left='-9999px';testEl.style.width='auto';testEl.style.whiteSpace='pre';if(document.body.contains(input)&&window.getComputedStyle){var inputStyle=window.getComputedStyle(input);if(inputStyle){testEl.style.fontSize=inputStyle.fontSize;testEl.style.fontFamily=inputStyle.fontFamily;testEl.style.fontWeight=inputStyle.fontWeight;testEl.style.fontStyle=inputStyle.fontStyle;testEl.style.letterSpacing=inputStyle.letterSpacing;testEl.style.textTransform=inputStyle.textTransform;testEl.style.padding=inputStyle.padding;}}
document.body.appendChild(testEl);if(value&&testEl.offsetWidth!==input.offsetWidth){width=testEl.offsetWidth+4;}
document.body.removeChild(testEl);}
return width+'px';};var sortByAlpha=exports.sortByAlpha=function sortByAlpha(a,b){var labelA=(a.label||a.value).toLowerCase();var labelB=(b.label||b.value).toLowerCase();if(labelA<labelB)return-1;if(labelA>labelB)return 1;return 0;};var sortByScore=exports.sortByScore=function sortByScore(a,b){return a.score-b.score;};var triggerEvent=exports.triggerEvent=function triggerEvent(element,type){var customArgs=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;var event=new CustomEvent(type,{detail:customArgs,bubbles:true,cancelable:true});return element.dispatchEvent(event);};}),(function(module,exports){'use strict';(function(){if(!Array.from){Array.from=function(){var toStr=Object.prototype.toString;var isCallable=function isCallable(fn){return typeof fn==='function'||toStr.call(fn)==='[object Function]';};var toInteger=function toInteger(value){var number=Number(value);if(isNaN(number)){return 0;}
if(number===0||!isFinite(number)){return number;}
return(number>0?1:-1)*Math.floor(Math.abs(number));};var maxSafeInteger=Math.pow(2,53)-1;var toLength=function toLength(value){var len=toInteger(value);return Math.min(Math.max(len,0),maxSafeInteger);};return function from(arrayLike){var C=this;var items=Object(arrayLike);if(arrayLike==null){throw new TypeError("Array.from requires an array-like object - not null or undefined");}
var mapFn=arguments.length>1?arguments[1]:void undefined;var T;if(typeof mapFn!=='undefined'){if(!isCallable(mapFn)){throw new TypeError('Array.from: when provided, the second argument must be a function');}
if(arguments.length>2){T=arguments[2];}}
var len=toLength(items.length);var A=isCallable(C)?Object(new C(len)):new Array(len);var k=0;var kValue;while(k<len){kValue=items[k];if(mapFn){A[k]=typeof T==='undefined'?mapFn(kValue,k):mapFn.call(T,kValue,k);}else{A[k]=kValue;}
k+=1;}
A.length=len;return A;};}();}
if(!Array.prototype.find){Array.prototype.find=function(predicate){'use strict';if(this==null){throw new TypeError('Array.prototype.find called on null or undefined');}
if(typeof predicate!=='function'){throw new TypeError('predicate must be a function');}
var list=Object(this);var length=list.length>>>0;var thisArg=arguments[1];var value;for(var i=0;i<length;i++){value=list[i];if(predicate.call(thisArg,value,i,list)){return value;}}
return undefined;};}
function CustomEvent(event,params){params=params||{bubbles:false,cancelable:false,detail:undefined};var evt=document.createEvent('CustomEvent');evt.initCustomEvent(event,params.bubbles,params.cancelable,params.detail);return evt;}
CustomEvent.prototype=window.Event.prototype;window.CustomEvent=CustomEvent;})();})])});;var EstablishmentStep;(function(EstablishmentStep){EstablishmentStep[EstablishmentStep["PageLoad"]=0]="PageLoad";EstablishmentStep[EstablishmentStep["LoaderGone"]=1]="LoaderGone";EstablishmentStep[EstablishmentStep["DatesEntered"]=5]="DatesEntered";EstablishmentStep[EstablishmentStep["PaxSelected"]=10]="PaxSelected";EstablishmentStep[EstablishmentStep["SingleRoomSelected"]=30]="SingleRoomSelected";EstablishmentStep[EstablishmentStep["MultipleRoomsSelected"]=40]="MultipleRoomsSelected";EstablishmentStep[EstablishmentStep["GotoRaq"]=50]="GotoRaq";EstablishmentStep[EstablishmentStep["GotoBookNow"]=100]="GotoBookNow";EstablishmentStep[EstablishmentStep["QuoteRequested"]=150]="QuoteRequested";EstablishmentStep[EstablishmentStep["RealtimeBooked"]=200]="RealtimeBooked";})(EstablishmentStep||(EstablishmentStep={}));var PageLogger=(function(){function PageLogger(){}
PageLogger.LogEstPageStep=function(vm,step,option,from,to,guests){var data={};var isRAQButtonVisible=$(".go-main-image-raq-button:visible").length>0;var isRealtimeButtonVisible=$(".seeinstantbook:visible").length>0;if(vm){var fromFormatted="",toFormatted="";if(vm.checkin()&&vm.checkout()){var fromFormatted=moment(vm.checkin()).format("YYYY-MM-DD");var toFormatted=moment(vm.checkout()).format("YYYY-MM-DD");}
data={from:fromFormatted,to:toFormatted,guests:vm.selectedAdultsGlobalFilter()+vm.selectedKidsGlobalFilter(),step:step,option:option,screensize:window.innerWidth,raqVisible:isRAQButtonVisible,realtimeVisible:isRealtimeButtonVisible,spid:vm.spid};}
else{var fromFormatted="",toFormatted="";if($(".checkin").val()&&$(".checkout").val()){var fromFormatted=$(".checkin").val();var toFormatted=$(".checkout").val();}
data={from:fromFormatted,to:toFormatted,guests:guests,step:step,option:option,screensize:window.innerWidth,raqVisible:isRAQButtonVisible,realtimeVisible:isRealtimeButtonVisible};}
var url="/establishment/LogEstStep";$.post(url,data,function(response){});};return PageLogger;}());;