/* An error occurred during minification, see Trace log for more details - returning concatenated content unminified.
 */
///#source 1 1 /Assets/scripts/libs/codehouse-js/boot.min.js
/*
 * ---------------------------------------- *
 * Name:    Codehouse Boot                  *
 * Version: 3.0.0                           *
 * Author:  Matt O'Neill | Joseph Moore     *
 * Status:  Release                         *
 * ---------------------------------------- *
 */

window.boot || (window.boot = {}), window.boot = new function () { return this.config = {}, this.config.global = "/Assets/scripts/libs/", this.config.local = "/Assets/scripts/libs/codehouse-js/", this.config.cdn = "", this.loadScript = function (t, n, e) { function o(t, n) { ("loaded" === t.readyState || "complete" === t.readyState) && n() } var i = -1 != navigator.appVersion.indexOf("MSIE 10"), a = document.createElement("script"), s = n ? this.config[n] : this.config.local; a.type = "text/javascript", a.src = s + t, document.body.appendChild(a), a.addEventListener && !i ? e && a.addEventListener("load", function (t) { e() }, !1) : a.attachEvent && e && a.attachEvent("onreadystatechange", function () { a.onload = a.onreadystatechange = null, o(a, e) }) }, this };
///#source 1 1 /Assets/scripts/libs/bootstrap-bundle-5.3.3.min.js
/*!
  * Bootstrap v5.3.3 (https://getbootstrap.com/)
  * Copyright 2011-2024 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
  * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
  */
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).bootstrap=e()}(this,(function(){"use strict";const t=new Map,e={set(e,i,n){t.has(e)||t.set(e,new Map);const s=t.get(e);s.has(i)||0===s.size?s.set(i,n):console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(s.keys())[0]}.`)},get:(e,i)=>t.has(e)&&t.get(e).get(i)||null,remove(e,i){if(!t.has(e))return;const n=t.get(e);n.delete(i),0===n.size&&t.delete(e)}},i="transitionend",n=t=>(t&&window.CSS&&window.CSS.escape&&(t=t.replace(/#([^\s"#']+)/g,((t,e)=>`#${CSS.escape(e)}`))),t),s=t=>{t.dispatchEvent(new Event(i))},o=t=>!(!t||"object"!=typeof t)&&(void 0!==t.jquery&&(t=t[0]),void 0!==t.nodeType),r=t=>o(t)?t.jquery?t[0]:t:"string"==typeof t&&t.length>0?document.querySelector(n(t)):null,a=t=>{if(!o(t)||0===t.getClientRects().length)return!1;const e="visible"===getComputedStyle(t).getPropertyValue("visibility"),i=t.closest("details:not([open])");if(!i)return e;if(i!==t){const e=t.closest("summary");if(e&&e.parentNode!==i)return!1;if(null===e)return!1}return e},l=t=>!t||t.nodeType!==Node.ELEMENT_NODE||!!t.classList.contains("disabled")||(void 0!==t.disabled?t.disabled:t.hasAttribute("disabled")&&"false"!==t.getAttribute("disabled")),c=t=>{if(!document.documentElement.attachShadow)return null;if("function"==typeof t.getRootNode){const e=t.getRootNode();return e instanceof ShadowRoot?e:null}return t instanceof ShadowRoot?t:t.parentNode?c(t.parentNode):null},h=()=>{},d=t=>{t.offsetHeight},u=()=>window.jQuery&&!document.body.hasAttribute("data-bs-no-jquery")?window.jQuery:null,f=[],p=()=>"rtl"===document.documentElement.dir,m=t=>{var e;e=()=>{const e=u();if(e){const i=t.NAME,n=e.fn[i];e.fn[i]=t.jQueryInterface,e.fn[i].Constructor=t,e.fn[i].noConflict=()=>(e.fn[i]=n,t.jQueryInterface)}},"loading"===document.readyState?(f.length||document.addEventListener("DOMContentLoaded",(()=>{for(const t of f)t()})),f.push(e)):e()},g=(t,e=[],i=t)=>"function"==typeof t?t(...e):i,_=(t,e,n=!0)=>{if(!n)return void g(t);const o=(t=>{if(!t)return 0;let{transitionDuration:e,transitionDelay:i}=window.getComputedStyle(t);const n=Number.parseFloat(e),s=Number.parseFloat(i);return n||s?(e=e.split(",")[0],i=i.split(",")[0],1e3*(Number.parseFloat(e)+Number.parseFloat(i))):0})(e)+5;let r=!1;const a=({target:n})=>{n===e&&(r=!0,e.removeEventListener(i,a),g(t))};e.addEventListener(i,a),setTimeout((()=>{r||s(e)}),o)},b=(t,e,i,n)=>{const s=t.length;let o=t.indexOf(e);return-1===o?!i&&n?t[s-1]:t[0]:(o+=i?1:-1,n&&(o=(o+s)%s),t[Math.max(0,Math.min(o,s-1))])},v=/[^.]*(?=\..*)\.|.*/,y=/\..*/,w=/::\d+$/,A={};let E=1;const T={mouseenter:"mouseover",mouseleave:"mouseout"},C=new Set(["click","dblclick","mouseup","mousedown","contextmenu","mousewheel","DOMMouseScroll","mouseover","mouseout","mousemove","selectstart","selectend","keydown","keypress","keyup","orientationchange","touchstart","touchmove","touchend","touchcancel","pointerdown","pointermove","pointerup","pointerleave","pointercancel","gesturestart","gesturechange","gestureend","focus","blur","change","reset","select","submit","focusin","focusout","load","unload","beforeunload","resize","move","DOMContentLoaded","readystatechange","error","abort","scroll"]);function O(t,e){return e&&`${e}::${E++}`||t.uidEvent||E++}function x(t){const e=O(t);return t.uidEvent=e,A[e]=A[e]||{},A[e]}function k(t,e,i=null){return Object.values(t).find((t=>t.callable===e&&t.delegationSelector===i))}function L(t,e,i){const n="string"==typeof e,s=n?i:e||i;let o=I(t);return C.has(o)||(o=t),[n,s,o]}function S(t,e,i,n,s){if("string"!=typeof e||!t)return;let[o,r,a]=L(e,i,n);if(e in T){const t=t=>function(e){if(!e.relatedTarget||e.relatedTarget!==e.delegateTarget&&!e.delegateTarget.contains(e.relatedTarget))return t.call(this,e)};r=t(r)}const l=x(t),c=l[a]||(l[a]={}),h=k(c,r,o?i:null);if(h)return void(h.oneOff=h.oneOff&&s);const d=O(r,e.replace(v,"")),u=o?function(t,e,i){return function n(s){const o=t.querySelectorAll(e);for(let{target:r}=s;r&&r!==this;r=r.parentNode)for(const a of o)if(a===r)return P(s,{delegateTarget:r}),n.oneOff&&N.off(t,s.type,e,i),i.apply(r,[s])}}(t,i,r):function(t,e){return function i(n){return P(n,{delegateTarget:t}),i.oneOff&&N.off(t,n.type,e),e.apply(t,[n])}}(t,r);u.delegationSelector=o?i:null,u.callable=r,u.oneOff=s,u.uidEvent=d,c[d]=u,t.addEventListener(a,u,o)}function D(t,e,i,n,s){const o=k(e[i],n,s);o&&(t.removeEventListener(i,o,Boolean(s)),delete e[i][o.uidEvent])}function $(t,e,i,n){const s=e[i]||{};for(const[o,r]of Object.entries(s))o.includes(n)&&D(t,e,i,r.callable,r.delegationSelector)}function I(t){return t=t.replace(y,""),T[t]||t}const N={on(t,e,i,n){S(t,e,i,n,!1)},one(t,e,i,n){S(t,e,i,n,!0)},off(t,e,i,n){if("string"!=typeof e||!t)return;const[s,o,r]=L(e,i,n),a=r!==e,l=x(t),c=l[r]||{},h=e.startsWith(".");if(void 0===o){if(h)for(const i of Object.keys(l))$(t,l,i,e.slice(1));for(const[i,n]of Object.entries(c)){const s=i.replace(w,"");a&&!e.includes(s)||D(t,l,r,n.callable,n.delegationSelector)}}else{if(!Object.keys(c).length)return;D(t,l,r,o,s?i:null)}},trigger(t,e,i){if("string"!=typeof e||!t)return null;const n=u();let s=null,o=!0,r=!0,a=!1;e!==I(e)&&n&&(s=n.Event(e,i),n(t).trigger(s),o=!s.isPropagationStopped(),r=!s.isImmediatePropagationStopped(),a=s.isDefaultPrevented());const l=P(new Event(e,{bubbles:o,cancelable:!0}),i);return a&&l.preventDefault(),r&&t.dispatchEvent(l),l.defaultPrevented&&s&&s.preventDefault(),l}};function P(t,e={}){for(const[i,n]of Object.entries(e))try{t[i]=n}catch(e){Object.defineProperty(t,i,{configurable:!0,get:()=>n})}return t}function j(t){if("true"===t)return!0;if("false"===t)return!1;if(t===Number(t).toString())return Number(t);if(""===t||"null"===t)return null;if("string"!=typeof t)return t;try{return JSON.parse(decodeURIComponent(t))}catch(e){return t}}function M(t){return t.replace(/[A-Z]/g,(t=>`-${t.toLowerCase()}`))}const F={setDataAttribute(t,e,i){t.setAttribute(`data-bs-${M(e)}`,i)},removeDataAttribute(t,e){t.removeAttribute(`data-bs-${M(e)}`)},getDataAttributes(t){if(!t)return{};const e={},i=Object.keys(t.dataset).filter((t=>t.startsWith("bs")&&!t.startsWith("bsConfig")));for(const n of i){let i=n.replace(/^bs/,"");i=i.charAt(0).toLowerCase()+i.slice(1,i.length),e[i]=j(t.dataset[n])}return e},getDataAttribute:(t,e)=>j(t.getAttribute(`data-bs-${M(e)}`))};class H{static get Default(){return{}}static get DefaultType(){return{}}static get NAME(){throw new Error('You have to implement the static method "NAME", for each component!')}_getConfig(t){return t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t}_mergeConfigObj(t,e){const i=o(e)?F.getDataAttribute(e,"config"):{};return{...this.constructor.Default,..."object"==typeof i?i:{},...o(e)?F.getDataAttributes(e):{},..."object"==typeof t?t:{}}}_typeCheckConfig(t,e=this.constructor.DefaultType){for(const[n,s]of Object.entries(e)){const e=t[n],r=o(e)?"element":null==(i=e)?`${i}`:Object.prototype.toString.call(i).match(/\s([a-z]+)/i)[1].toLowerCase();if(!new RegExp(s).test(r))throw new TypeError(`${this.constructor.NAME.toUpperCase()}: Option "${n}" provided type "${r}" but expected type "${s}".`)}var i}}class W extends H{constructor(t,i){super(),(t=r(t))&&(this._element=t,this._config=this._getConfig(i),e.set(this._element,this.constructor.DATA_KEY,this))}dispose(){e.remove(this._element,this.constructor.DATA_KEY),N.off(this._element,this.constructor.EVENT_KEY);for(const t of Object.getOwnPropertyNames(this))this[t]=null}_queueCallback(t,e,i=!0){_(t,e,i)}_getConfig(t){return t=this._mergeConfigObj(t,this._element),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}static getInstance(t){return e.get(r(t),this.DATA_KEY)}static getOrCreateInstance(t,e={}){return this.getInstance(t)||new this(t,"object"==typeof e?e:null)}static get VERSION(){return"5.3.3"}static get DATA_KEY(){return`bs.${this.NAME}`}static get EVENT_KEY(){return`.${this.DATA_KEY}`}static eventName(t){return`${t}${this.EVENT_KEY}`}}const B=t=>{let e=t.getAttribute("data-bs-target");if(!e||"#"===e){let i=t.getAttribute("href");if(!i||!i.includes("#")&&!i.startsWith("."))return null;i.includes("#")&&!i.startsWith("#")&&(i=`#${i.split("#")[1]}`),e=i&&"#"!==i?i.trim():null}return e?e.split(",").map((t=>n(t))).join(","):null},z={find:(t,e=document.documentElement)=>[].concat(...Element.prototype.querySelectorAll.call(e,t)),findOne:(t,e=document.documentElement)=>Element.prototype.querySelector.call(e,t),children:(t,e)=>[].concat(...t.children).filter((t=>t.matches(e))),parents(t,e){const i=[];let n=t.parentNode.closest(e);for(;n;)i.push(n),n=n.parentNode.closest(e);return i},prev(t,e){let i=t.previousElementSibling;for(;i;){if(i.matches(e))return[i];i=i.previousElementSibling}return[]},next(t,e){let i=t.nextElementSibling;for(;i;){if(i.matches(e))return[i];i=i.nextElementSibling}return[]},focusableChildren(t){const e=["a","button","input","textarea","select","details","[tabindex]",'[contenteditable="true"]'].map((t=>`${t}:not([tabindex^="-"])`)).join(",");return this.find(e,t).filter((t=>!l(t)&&a(t)))},getSelectorFromElement(t){const e=B(t);return e&&z.findOne(e)?e:null},getElementFromSelector(t){const e=B(t);return e?z.findOne(e):null},getMultipleElementsFromSelector(t){const e=B(t);return e?z.find(e):[]}},R=(t,e="hide")=>{const i=`click.dismiss${t.EVENT_KEY}`,n=t.NAME;N.on(document,i,`[data-bs-dismiss="${n}"]`,(function(i){if(["A","AREA"].includes(this.tagName)&&i.preventDefault(),l(this))return;const s=z.getElementFromSelector(this)||this.closest(`.${n}`);t.getOrCreateInstance(s)[e]()}))},q=".bs.alert",V=`close${q}`,K=`closed${q}`;class Q extends W{static get NAME(){return"alert"}close(){if(N.trigger(this._element,V).defaultPrevented)return;this._element.classList.remove("show");const t=this._element.classList.contains("fade");this._queueCallback((()=>this._destroyElement()),this._element,t)}_destroyElement(){this._element.remove(),N.trigger(this._element,K),this.dispose()}static jQueryInterface(t){return this.each((function(){const e=Q.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}R(Q,"close"),m(Q);const X='[data-bs-toggle="button"]';class Y extends W{static get NAME(){return"button"}toggle(){this._element.setAttribute("aria-pressed",this._element.classList.toggle("active"))}static jQueryInterface(t){return this.each((function(){const e=Y.getOrCreateInstance(this);"toggle"===t&&e[t]()}))}}N.on(document,"click.bs.button.data-api",X,(t=>{t.preventDefault();const e=t.target.closest(X);Y.getOrCreateInstance(e).toggle()})),m(Y);const U=".bs.swipe",G=`touchstart${U}`,J=`touchmove${U}`,Z=`touchend${U}`,tt=`pointerdown${U}`,et=`pointerup${U}`,it={endCallback:null,leftCallback:null,rightCallback:null},nt={endCallback:"(function|null)",leftCallback:"(function|null)",rightCallback:"(function|null)"};class st extends H{constructor(t,e){super(),this._element=t,t&&st.isSupported()&&(this._config=this._getConfig(e),this._deltaX=0,this._supportPointerEvents=Boolean(window.PointerEvent),this._initEvents())}static get Default(){return it}static get DefaultType(){return nt}static get NAME(){return"swipe"}dispose(){N.off(this._element,U)}_start(t){this._supportPointerEvents?this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX):this._deltaX=t.touches[0].clientX}_end(t){this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX-this._deltaX),this._handleSwipe(),g(this._config.endCallback)}_move(t){this._deltaX=t.touches&&t.touches.length>1?0:t.touches[0].clientX-this._deltaX}_handleSwipe(){const t=Math.abs(this._deltaX);if(t<=40)return;const e=t/this._deltaX;this._deltaX=0,e&&g(e>0?this._config.rightCallback:this._config.leftCallback)}_initEvents(){this._supportPointerEvents?(N.on(this._element,tt,(t=>this._start(t))),N.on(this._element,et,(t=>this._end(t))),this._element.classList.add("pointer-event")):(N.on(this._element,G,(t=>this._start(t))),N.on(this._element,J,(t=>this._move(t))),N.on(this._element,Z,(t=>this._end(t))))}_eventIsPointerPenTouch(t){return this._supportPointerEvents&&("pen"===t.pointerType||"touch"===t.pointerType)}static isSupported(){return"ontouchstart"in document.documentElement||navigator.maxTouchPoints>0}}const ot=".bs.carousel",rt=".data-api",at="next",lt="prev",ct="left",ht="right",dt=`slide${ot}`,ut=`slid${ot}`,ft=`keydown${ot}`,pt=`mouseenter${ot}`,mt=`mouseleave${ot}`,gt=`dragstart${ot}`,_t=`load${ot}${rt}`,bt=`click${ot}${rt}`,vt="carousel",yt="active",wt=".active",At=".carousel-item",Et=wt+At,Tt={ArrowLeft:ht,ArrowRight:ct},Ct={interval:5e3,keyboard:!0,pause:"hover",ride:!1,touch:!0,wrap:!0},Ot={interval:"(number|boolean)",keyboard:"boolean",pause:"(string|boolean)",ride:"(boolean|string)",touch:"boolean",wrap:"boolean"};class xt extends W{constructor(t,e){super(t,e),this._interval=null,this._activeElement=null,this._isSliding=!1,this.touchTimeout=null,this._swipeHelper=null,this._indicatorsElement=z.findOne(".carousel-indicators",this._element),this._addEventListeners(),this._config.ride===vt&&this.cycle()}static get Default(){return Ct}static get DefaultType(){return Ot}static get NAME(){return"carousel"}next(){this._slide(at)}nextWhenVisible(){!document.hidden&&a(this._element)&&this.next()}prev(){this._slide(lt)}pause(){this._isSliding&&s(this._element),this._clearInterval()}cycle(){this._clearInterval(),this._updateInterval(),this._interval=setInterval((()=>this.nextWhenVisible()),this._config.interval)}_maybeEnableCycle(){this._config.ride&&(this._isSliding?N.one(this._element,ut,(()=>this.cycle())):this.cycle())}to(t){const e=this._getItems();if(t>e.length-1||t<0)return;if(this._isSliding)return void N.one(this._element,ut,(()=>this.to(t)));const i=this._getItemIndex(this._getActive());if(i===t)return;const n=t>i?at:lt;this._slide(n,e[t])}dispose(){this._swipeHelper&&this._swipeHelper.dispose(),super.dispose()}_configAfterMerge(t){return t.defaultInterval=t.interval,t}_addEventListeners(){this._config.keyboard&&N.on(this._element,ft,(t=>this._keydown(t))),"hover"===this._config.pause&&(N.on(this._element,pt,(()=>this.pause())),N.on(this._element,mt,(()=>this._maybeEnableCycle()))),this._config.touch&&st.isSupported()&&this._addTouchEventListeners()}_addTouchEventListeners(){for(const t of z.find(".carousel-item img",this._element))N.on(t,gt,(t=>t.preventDefault()));const t={leftCallback:()=>this._slide(this._directionToOrder(ct)),rightCallback:()=>this._slide(this._directionToOrder(ht)),endCallback:()=>{"hover"===this._config.pause&&(this.pause(),this.touchTimeout&&clearTimeout(this.touchTimeout),this.touchTimeout=setTimeout((()=>this._maybeEnableCycle()),500+this._config.interval))}};this._swipeHelper=new st(this._element,t)}_keydown(t){if(/input|textarea/i.test(t.target.tagName))return;const e=Tt[t.key];e&&(t.preventDefault(),this._slide(this._directionToOrder(e)))}_getItemIndex(t){return this._getItems().indexOf(t)}_setActiveIndicatorElement(t){if(!this._indicatorsElement)return;const e=z.findOne(wt,this._indicatorsElement);e.classList.remove(yt),e.removeAttribute("aria-current");const i=z.findOne(`[data-bs-slide-to="${t}"]`,this._indicatorsElement);i&&(i.classList.add(yt),i.setAttribute("aria-current","true"))}_updateInterval(){const t=this._activeElement||this._getActive();if(!t)return;const e=Number.parseInt(t.getAttribute("data-bs-interval"),10);this._config.interval=e||this._config.defaultInterval}_slide(t,e=null){if(this._isSliding)return;const i=this._getActive(),n=t===at,s=e||b(this._getItems(),i,n,this._config.wrap);if(s===i)return;const o=this._getItemIndex(s),r=e=>N.trigger(this._element,e,{relatedTarget:s,direction:this._orderToDirection(t),from:this._getItemIndex(i),to:o});if(r(dt).defaultPrevented)return;if(!i||!s)return;const a=Boolean(this._interval);this.pause(),this._isSliding=!0,this._setActiveIndicatorElement(o),this._activeElement=s;const l=n?"carousel-item-start":"carousel-item-end",c=n?"carousel-item-next":"carousel-item-prev";s.classList.add(c),d(s),i.classList.add(l),s.classList.add(l),this._queueCallback((()=>{s.classList.remove(l,c),s.classList.add(yt),i.classList.remove(yt,c,l),this._isSliding=!1,r(ut)}),i,this._isAnimated()),a&&this.cycle()}_isAnimated(){return this._element.classList.contains("slide")}_getActive(){return z.findOne(Et,this._element)}_getItems(){return z.find(At,this._element)}_clearInterval(){this._interval&&(clearInterval(this._interval),this._interval=null)}_directionToOrder(t){return p()?t===ct?lt:at:t===ct?at:lt}_orderToDirection(t){return p()?t===lt?ct:ht:t===lt?ht:ct}static jQueryInterface(t){return this.each((function(){const e=xt.getOrCreateInstance(this,t);if("number"!=typeof t){if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}else e.to(t)}))}}N.on(document,bt,"[data-bs-slide], [data-bs-slide-to]",(function(t){const e=z.getElementFromSelector(this);if(!e||!e.classList.contains(vt))return;t.preventDefault();const i=xt.getOrCreateInstance(e),n=this.getAttribute("data-bs-slide-to");return n?(i.to(n),void i._maybeEnableCycle()):"next"===F.getDataAttribute(this,"slide")?(i.next(),void i._maybeEnableCycle()):(i.prev(),void i._maybeEnableCycle())})),N.on(window,_t,(()=>{const t=z.find('[data-bs-ride="carousel"]');for(const e of t)xt.getOrCreateInstance(e)})),m(xt);const kt=".bs.collapse",Lt=`show${kt}`,St=`shown${kt}`,Dt=`hide${kt}`,$t=`hidden${kt}`,It=`click${kt}.data-api`,Nt="show",Pt="collapse",jt="collapsing",Mt=`:scope .${Pt} .${Pt}`,Ft='[data-bs-toggle="collapse"]',Ht={parent:null,toggle:!0},Wt={parent:"(null|element)",toggle:"boolean"};class Bt extends W{constructor(t,e){super(t,e),this._isTransitioning=!1,this._triggerArray=[];const i=z.find(Ft);for(const t of i){const e=z.getSelectorFromElement(t),i=z.find(e).filter((t=>t===this._element));null!==e&&i.length&&this._triggerArray.push(t)}this._initializeChildren(),this._config.parent||this._addAriaAndCollapsedClass(this._triggerArray,this._isShown()),this._config.toggle&&this.toggle()}static get Default(){return Ht}static get DefaultType(){return Wt}static get NAME(){return"collapse"}toggle(){this._isShown()?this.hide():this.show()}show(){if(this._isTransitioning||this._isShown())return;let t=[];if(this._config.parent&&(t=this._getFirstLevelChildren(".collapse.show, .collapse.collapsing").filter((t=>t!==this._element)).map((t=>Bt.getOrCreateInstance(t,{toggle:!1})))),t.length&&t[0]._isTransitioning)return;if(N.trigger(this._element,Lt).defaultPrevented)return;for(const e of t)e.hide();const e=this._getDimension();this._element.classList.remove(Pt),this._element.classList.add(jt),this._element.style[e]=0,this._addAriaAndCollapsedClass(this._triggerArray,!0),this._isTransitioning=!0;const i=`scroll${e[0].toUpperCase()+e.slice(1)}`;this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(jt),this._element.classList.add(Pt,Nt),this._element.style[e]="",N.trigger(this._element,St)}),this._element,!0),this._element.style[e]=`${this._element[i]}px`}hide(){if(this._isTransitioning||!this._isShown())return;if(N.trigger(this._element,Dt).defaultPrevented)return;const t=this._getDimension();this._element.style[t]=`${this._element.getBoundingClientRect()[t]}px`,d(this._element),this._element.classList.add(jt),this._element.classList.remove(Pt,Nt);for(const t of this._triggerArray){const e=z.getElementFromSelector(t);e&&!this._isShown(e)&&this._addAriaAndCollapsedClass([t],!1)}this._isTransitioning=!0,this._element.style[t]="",this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(jt),this._element.classList.add(Pt),N.trigger(this._element,$t)}),this._element,!0)}_isShown(t=this._element){return t.classList.contains(Nt)}_configAfterMerge(t){return t.toggle=Boolean(t.toggle),t.parent=r(t.parent),t}_getDimension(){return this._element.classList.contains("collapse-horizontal")?"width":"height"}_initializeChildren(){if(!this._config.parent)return;const t=this._getFirstLevelChildren(Ft);for(const e of t){const t=z.getElementFromSelector(e);t&&this._addAriaAndCollapsedClass([e],this._isShown(t))}}_getFirstLevelChildren(t){const e=z.find(Mt,this._config.parent);return z.find(t,this._config.parent).filter((t=>!e.includes(t)))}_addAriaAndCollapsedClass(t,e){if(t.length)for(const i of t)i.classList.toggle("collapsed",!e),i.setAttribute("aria-expanded",e)}static jQueryInterface(t){const e={};return"string"==typeof t&&/show|hide/.test(t)&&(e.toggle=!1),this.each((function(){const i=Bt.getOrCreateInstance(this,e);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t]()}}))}}N.on(document,It,Ft,(function(t){("A"===t.target.tagName||t.delegateTarget&&"A"===t.delegateTarget.tagName)&&t.preventDefault();for(const t of z.getMultipleElementsFromSelector(this))Bt.getOrCreateInstance(t,{toggle:!1}).toggle()})),m(Bt);var zt="top",Rt="bottom",qt="right",Vt="left",Kt="auto",Qt=[zt,Rt,qt,Vt],Xt="start",Yt="end",Ut="clippingParents",Gt="viewport",Jt="popper",Zt="reference",te=Qt.reduce((function(t,e){return t.concat([e+"-"+Xt,e+"-"+Yt])}),[]),ee=[].concat(Qt,[Kt]).reduce((function(t,e){return t.concat([e,e+"-"+Xt,e+"-"+Yt])}),[]),ie="beforeRead",ne="read",se="afterRead",oe="beforeMain",re="main",ae="afterMain",le="beforeWrite",ce="write",he="afterWrite",de=[ie,ne,se,oe,re,ae,le,ce,he];function ue(t){return t?(t.nodeName||"").toLowerCase():null}function fe(t){if(null==t)return window;if("[object Window]"!==t.toString()){var e=t.ownerDocument;return e&&e.defaultView||window}return t}function pe(t){return t instanceof fe(t).Element||t instanceof Element}function me(t){return t instanceof fe(t).HTMLElement||t instanceof HTMLElement}function ge(t){return"undefined"!=typeof ShadowRoot&&(t instanceof fe(t).ShadowRoot||t instanceof ShadowRoot)}const _e={name:"applyStyles",enabled:!0,phase:"write",fn:function(t){var e=t.state;Object.keys(e.elements).forEach((function(t){var i=e.styles[t]||{},n=e.attributes[t]||{},s=e.elements[t];me(s)&&ue(s)&&(Object.assign(s.style,i),Object.keys(n).forEach((function(t){var e=n[t];!1===e?s.removeAttribute(t):s.setAttribute(t,!0===e?"":e)})))}))},effect:function(t){var e=t.state,i={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,i.popper),e.styles=i,e.elements.arrow&&Object.assign(e.elements.arrow.style,i.arrow),function(){Object.keys(e.elements).forEach((function(t){var n=e.elements[t],s=e.attributes[t]||{},o=Object.keys(e.styles.hasOwnProperty(t)?e.styles[t]:i[t]).reduce((function(t,e){return t[e]="",t}),{});me(n)&&ue(n)&&(Object.assign(n.style,o),Object.keys(s).forEach((function(t){n.removeAttribute(t)})))}))}},requires:["computeStyles"]};function be(t){return t.split("-")[0]}var ve=Math.max,ye=Math.min,we=Math.round;function Ae(){var t=navigator.userAgentData;return null!=t&&t.brands&&Array.isArray(t.brands)?t.brands.map((function(t){return t.brand+"/"+t.version})).join(" "):navigator.userAgent}function Ee(){return!/^((?!chrome|android).)*safari/i.test(Ae())}function Te(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!1);var n=t.getBoundingClientRect(),s=1,o=1;e&&me(t)&&(s=t.offsetWidth>0&&we(n.width)/t.offsetWidth||1,o=t.offsetHeight>0&&we(n.height)/t.offsetHeight||1);var r=(pe(t)?fe(t):window).visualViewport,a=!Ee()&&i,l=(n.left+(a&&r?r.offsetLeft:0))/s,c=(n.top+(a&&r?r.offsetTop:0))/o,h=n.width/s,d=n.height/o;return{width:h,height:d,top:c,right:l+h,bottom:c+d,left:l,x:l,y:c}}function Ce(t){var e=Te(t),i=t.offsetWidth,n=t.offsetHeight;return Math.abs(e.width-i)<=1&&(i=e.width),Math.abs(e.height-n)<=1&&(n=e.height),{x:t.offsetLeft,y:t.offsetTop,width:i,height:n}}function Oe(t,e){var i=e.getRootNode&&e.getRootNode();if(t.contains(e))return!0;if(i&&ge(i)){var n=e;do{if(n&&t.isSameNode(n))return!0;n=n.parentNode||n.host}while(n)}return!1}function xe(t){return fe(t).getComputedStyle(t)}function ke(t){return["table","td","th"].indexOf(ue(t))>=0}function Le(t){return((pe(t)?t.ownerDocument:t.document)||window.document).documentElement}function Se(t){return"html"===ue(t)?t:t.assignedSlot||t.parentNode||(ge(t)?t.host:null)||Le(t)}function De(t){return me(t)&&"fixed"!==xe(t).position?t.offsetParent:null}function $e(t){for(var e=fe(t),i=De(t);i&&ke(i)&&"static"===xe(i).position;)i=De(i);return i&&("html"===ue(i)||"body"===ue(i)&&"static"===xe(i).position)?e:i||function(t){var e=/firefox/i.test(Ae());if(/Trident/i.test(Ae())&&me(t)&&"fixed"===xe(t).position)return null;var i=Se(t);for(ge(i)&&(i=i.host);me(i)&&["html","body"].indexOf(ue(i))<0;){var n=xe(i);if("none"!==n.transform||"none"!==n.perspective||"paint"===n.contain||-1!==["transform","perspective"].indexOf(n.willChange)||e&&"filter"===n.willChange||e&&n.filter&&"none"!==n.filter)return i;i=i.parentNode}return null}(t)||e}function Ie(t){return["top","bottom"].indexOf(t)>=0?"x":"y"}function Ne(t,e,i){return ve(t,ye(e,i))}function Pe(t){return Object.assign({},{top:0,right:0,bottom:0,left:0},t)}function je(t,e){return e.reduce((function(e,i){return e[i]=t,e}),{})}const Me={name:"arrow",enabled:!0,phase:"main",fn:function(t){var e,i=t.state,n=t.name,s=t.options,o=i.elements.arrow,r=i.modifiersData.popperOffsets,a=be(i.placement),l=Ie(a),c=[Vt,qt].indexOf(a)>=0?"height":"width";if(o&&r){var h=function(t,e){return Pe("number"!=typeof(t="function"==typeof t?t(Object.assign({},e.rects,{placement:e.placement})):t)?t:je(t,Qt))}(s.padding,i),d=Ce(o),u="y"===l?zt:Vt,f="y"===l?Rt:qt,p=i.rects.reference[c]+i.rects.reference[l]-r[l]-i.rects.popper[c],m=r[l]-i.rects.reference[l],g=$e(o),_=g?"y"===l?g.clientHeight||0:g.clientWidth||0:0,b=p/2-m/2,v=h[u],y=_-d[c]-h[f],w=_/2-d[c]/2+b,A=Ne(v,w,y),E=l;i.modifiersData[n]=((e={})[E]=A,e.centerOffset=A-w,e)}},effect:function(t){var e=t.state,i=t.options.element,n=void 0===i?"[data-popper-arrow]":i;null!=n&&("string"!=typeof n||(n=e.elements.popper.querySelector(n)))&&Oe(e.elements.popper,n)&&(e.elements.arrow=n)},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]};function Fe(t){return t.split("-")[1]}var He={top:"auto",right:"auto",bottom:"auto",left:"auto"};function We(t){var e,i=t.popper,n=t.popperRect,s=t.placement,o=t.variation,r=t.offsets,a=t.position,l=t.gpuAcceleration,c=t.adaptive,h=t.roundOffsets,d=t.isFixed,u=r.x,f=void 0===u?0:u,p=r.y,m=void 0===p?0:p,g="function"==typeof h?h({x:f,y:m}):{x:f,y:m};f=g.x,m=g.y;var _=r.hasOwnProperty("x"),b=r.hasOwnProperty("y"),v=Vt,y=zt,w=window;if(c){var A=$e(i),E="clientHeight",T="clientWidth";A===fe(i)&&"static"!==xe(A=Le(i)).position&&"absolute"===a&&(E="scrollHeight",T="scrollWidth"),(s===zt||(s===Vt||s===qt)&&o===Yt)&&(y=Rt,m-=(d&&A===w&&w.visualViewport?w.visualViewport.height:A[E])-n.height,m*=l?1:-1),s!==Vt&&(s!==zt&&s!==Rt||o!==Yt)||(v=qt,f-=(d&&A===w&&w.visualViewport?w.visualViewport.width:A[T])-n.width,f*=l?1:-1)}var C,O=Object.assign({position:a},c&&He),x=!0===h?function(t,e){var i=t.x,n=t.y,s=e.devicePixelRatio||1;return{x:we(i*s)/s||0,y:we(n*s)/s||0}}({x:f,y:m},fe(i)):{x:f,y:m};return f=x.x,m=x.y,l?Object.assign({},O,((C={})[y]=b?"0":"",C[v]=_?"0":"",C.transform=(w.devicePixelRatio||1)<=1?"translate("+f+"px, "+m+"px)":"translate3d("+f+"px, "+m+"px, 0)",C)):Object.assign({},O,((e={})[y]=b?m+"px":"",e[v]=_?f+"px":"",e.transform="",e))}const Be={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function(t){var e=t.state,i=t.options,n=i.gpuAcceleration,s=void 0===n||n,o=i.adaptive,r=void 0===o||o,a=i.roundOffsets,l=void 0===a||a,c={placement:be(e.placement),variation:Fe(e.placement),popper:e.elements.popper,popperRect:e.rects.popper,gpuAcceleration:s,isFixed:"fixed"===e.options.strategy};null!=e.modifiersData.popperOffsets&&(e.styles.popper=Object.assign({},e.styles.popper,We(Object.assign({},c,{offsets:e.modifiersData.popperOffsets,position:e.options.strategy,adaptive:r,roundOffsets:l})))),null!=e.modifiersData.arrow&&(e.styles.arrow=Object.assign({},e.styles.arrow,We(Object.assign({},c,{offsets:e.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:l})))),e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-placement":e.placement})},data:{}};var ze={passive:!0};const Re={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:function(t){var e=t.state,i=t.instance,n=t.options,s=n.scroll,o=void 0===s||s,r=n.resize,a=void 0===r||r,l=fe(e.elements.popper),c=[].concat(e.scrollParents.reference,e.scrollParents.popper);return o&&c.forEach((function(t){t.addEventListener("scroll",i.update,ze)})),a&&l.addEventListener("resize",i.update,ze),function(){o&&c.forEach((function(t){t.removeEventListener("scroll",i.update,ze)})),a&&l.removeEventListener("resize",i.update,ze)}},data:{}};var qe={left:"right",right:"left",bottom:"top",top:"bottom"};function Ve(t){return t.replace(/left|right|bottom|top/g,(function(t){return qe[t]}))}var Ke={start:"end",end:"start"};function Qe(t){return t.replace(/start|end/g,(function(t){return Ke[t]}))}function Xe(t){var e=fe(t);return{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function Ye(t){return Te(Le(t)).left+Xe(t).scrollLeft}function Ue(t){var e=xe(t),i=e.overflow,n=e.overflowX,s=e.overflowY;return/auto|scroll|overlay|hidden/.test(i+s+n)}function Ge(t){return["html","body","#document"].indexOf(ue(t))>=0?t.ownerDocument.body:me(t)&&Ue(t)?t:Ge(Se(t))}function Je(t,e){var i;void 0===e&&(e=[]);var n=Ge(t),s=n===(null==(i=t.ownerDocument)?void 0:i.body),o=fe(n),r=s?[o].concat(o.visualViewport||[],Ue(n)?n:[]):n,a=e.concat(r);return s?a:a.concat(Je(Se(r)))}function Ze(t){return Object.assign({},t,{left:t.x,top:t.y,right:t.x+t.width,bottom:t.y+t.height})}function ti(t,e,i){return e===Gt?Ze(function(t,e){var i=fe(t),n=Le(t),s=i.visualViewport,o=n.clientWidth,r=n.clientHeight,a=0,l=0;if(s){o=s.width,r=s.height;var c=Ee();(c||!c&&"fixed"===e)&&(a=s.offsetLeft,l=s.offsetTop)}return{width:o,height:r,x:a+Ye(t),y:l}}(t,i)):pe(e)?function(t,e){var i=Te(t,!1,"fixed"===e);return i.top=i.top+t.clientTop,i.left=i.left+t.clientLeft,i.bottom=i.top+t.clientHeight,i.right=i.left+t.clientWidth,i.width=t.clientWidth,i.height=t.clientHeight,i.x=i.left,i.y=i.top,i}(e,i):Ze(function(t){var e,i=Le(t),n=Xe(t),s=null==(e=t.ownerDocument)?void 0:e.body,o=ve(i.scrollWidth,i.clientWidth,s?s.scrollWidth:0,s?s.clientWidth:0),r=ve(i.scrollHeight,i.clientHeight,s?s.scrollHeight:0,s?s.clientHeight:0),a=-n.scrollLeft+Ye(t),l=-n.scrollTop;return"rtl"===xe(s||i).direction&&(a+=ve(i.clientWidth,s?s.clientWidth:0)-o),{width:o,height:r,x:a,y:l}}(Le(t)))}function ei(t){var e,i=t.reference,n=t.element,s=t.placement,o=s?be(s):null,r=s?Fe(s):null,a=i.x+i.width/2-n.width/2,l=i.y+i.height/2-n.height/2;switch(o){case zt:e={x:a,y:i.y-n.height};break;case Rt:e={x:a,y:i.y+i.height};break;case qt:e={x:i.x+i.width,y:l};break;case Vt:e={x:i.x-n.width,y:l};break;default:e={x:i.x,y:i.y}}var c=o?Ie(o):null;if(null!=c){var h="y"===c?"height":"width";switch(r){case Xt:e[c]=e[c]-(i[h]/2-n[h]/2);break;case Yt:e[c]=e[c]+(i[h]/2-n[h]/2)}}return e}function ii(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=void 0===n?t.placement:n,o=i.strategy,r=void 0===o?t.strategy:o,a=i.boundary,l=void 0===a?Ut:a,c=i.rootBoundary,h=void 0===c?Gt:c,d=i.elementContext,u=void 0===d?Jt:d,f=i.altBoundary,p=void 0!==f&&f,m=i.padding,g=void 0===m?0:m,_=Pe("number"!=typeof g?g:je(g,Qt)),b=u===Jt?Zt:Jt,v=t.rects.popper,y=t.elements[p?b:u],w=function(t,e,i,n){var s="clippingParents"===e?function(t){var e=Je(Se(t)),i=["absolute","fixed"].indexOf(xe(t).position)>=0&&me(t)?$e(t):t;return pe(i)?e.filter((function(t){return pe(t)&&Oe(t,i)&&"body"!==ue(t)})):[]}(t):[].concat(e),o=[].concat(s,[i]),r=o[0],a=o.reduce((function(e,i){var s=ti(t,i,n);return e.top=ve(s.top,e.top),e.right=ye(s.right,e.right),e.bottom=ye(s.bottom,e.bottom),e.left=ve(s.left,e.left),e}),ti(t,r,n));return a.width=a.right-a.left,a.height=a.bottom-a.top,a.x=a.left,a.y=a.top,a}(pe(y)?y:y.contextElement||Le(t.elements.popper),l,h,r),A=Te(t.elements.reference),E=ei({reference:A,element:v,strategy:"absolute",placement:s}),T=Ze(Object.assign({},v,E)),C=u===Jt?T:A,O={top:w.top-C.top+_.top,bottom:C.bottom-w.bottom+_.bottom,left:w.left-C.left+_.left,right:C.right-w.right+_.right},x=t.modifiersData.offset;if(u===Jt&&x){var k=x[s];Object.keys(O).forEach((function(t){var e=[qt,Rt].indexOf(t)>=0?1:-1,i=[zt,Rt].indexOf(t)>=0?"y":"x";O[t]+=k[i]*e}))}return O}function ni(t,e){void 0===e&&(e={});var i=e,n=i.placement,s=i.boundary,o=i.rootBoundary,r=i.padding,a=i.flipVariations,l=i.allowedAutoPlacements,c=void 0===l?ee:l,h=Fe(n),d=h?a?te:te.filter((function(t){return Fe(t)===h})):Qt,u=d.filter((function(t){return c.indexOf(t)>=0}));0===u.length&&(u=d);var f=u.reduce((function(e,i){return e[i]=ii(t,{placement:i,boundary:s,rootBoundary:o,padding:r})[be(i)],e}),{});return Object.keys(f).sort((function(t,e){return f[t]-f[e]}))}const si={name:"flip",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,n=t.name;if(!e.modifiersData[n]._skip){for(var s=i.mainAxis,o=void 0===s||s,r=i.altAxis,a=void 0===r||r,l=i.fallbackPlacements,c=i.padding,h=i.boundary,d=i.rootBoundary,u=i.altBoundary,f=i.flipVariations,p=void 0===f||f,m=i.allowedAutoPlacements,g=e.options.placement,_=be(g),b=l||(_!==g&&p?function(t){if(be(t)===Kt)return[];var e=Ve(t);return[Qe(t),e,Qe(e)]}(g):[Ve(g)]),v=[g].concat(b).reduce((function(t,i){return t.concat(be(i)===Kt?ni(e,{placement:i,boundary:h,rootBoundary:d,padding:c,flipVariations:p,allowedAutoPlacements:m}):i)}),[]),y=e.rects.reference,w=e.rects.popper,A=new Map,E=!0,T=v[0],C=0;C<v.length;C++){var O=v[C],x=be(O),k=Fe(O)===Xt,L=[zt,Rt].indexOf(x)>=0,S=L?"width":"height",D=ii(e,{placement:O,boundary:h,rootBoundary:d,altBoundary:u,padding:c}),$=L?k?qt:Vt:k?Rt:zt;y[S]>w[S]&&($=Ve($));var I=Ve($),N=[];if(o&&N.push(D[x]<=0),a&&N.push(D[$]<=0,D[I]<=0),N.every((function(t){return t}))){T=O,E=!1;break}A.set(O,N)}if(E)for(var P=function(t){var e=v.find((function(e){var i=A.get(e);if(i)return i.slice(0,t).every((function(t){return t}))}));if(e)return T=e,"break"},j=p?3:1;j>0&&"break"!==P(j);j--);e.placement!==T&&(e.modifiersData[n]._skip=!0,e.placement=T,e.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}};function oi(t,e,i){return void 0===i&&(i={x:0,y:0}),{top:t.top-e.height-i.y,right:t.right-e.width+i.x,bottom:t.bottom-e.height+i.y,left:t.left-e.width-i.x}}function ri(t){return[zt,qt,Rt,Vt].some((function(e){return t[e]>=0}))}const ai={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function(t){var e=t.state,i=t.name,n=e.rects.reference,s=e.rects.popper,o=e.modifiersData.preventOverflow,r=ii(e,{elementContext:"reference"}),a=ii(e,{altBoundary:!0}),l=oi(r,n),c=oi(a,s,o),h=ri(l),d=ri(c);e.modifiersData[i]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:h,hasPopperEscaped:d},e.attributes.popper=Object.assign({},e.attributes.popper,{"data-popper-reference-hidden":h,"data-popper-escaped":d})}},li={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function(t){var e=t.state,i=t.options,n=t.name,s=i.offset,o=void 0===s?[0,0]:s,r=ee.reduce((function(t,i){return t[i]=function(t,e,i){var n=be(t),s=[Vt,zt].indexOf(n)>=0?-1:1,o="function"==typeof i?i(Object.assign({},e,{placement:t})):i,r=o[0],a=o[1];return r=r||0,a=(a||0)*s,[Vt,qt].indexOf(n)>=0?{x:a,y:r}:{x:r,y:a}}(i,e.rects,o),t}),{}),a=r[e.placement],l=a.x,c=a.y;null!=e.modifiersData.popperOffsets&&(e.modifiersData.popperOffsets.x+=l,e.modifiersData.popperOffsets.y+=c),e.modifiersData[n]=r}},ci={name:"popperOffsets",enabled:!0,phase:"read",fn:function(t){var e=t.state,i=t.name;e.modifiersData[i]=ei({reference:e.rects.reference,element:e.rects.popper,strategy:"absolute",placement:e.placement})},data:{}},hi={name:"preventOverflow",enabled:!0,phase:"main",fn:function(t){var e=t.state,i=t.options,n=t.name,s=i.mainAxis,o=void 0===s||s,r=i.altAxis,a=void 0!==r&&r,l=i.boundary,c=i.rootBoundary,h=i.altBoundary,d=i.padding,u=i.tether,f=void 0===u||u,p=i.tetherOffset,m=void 0===p?0:p,g=ii(e,{boundary:l,rootBoundary:c,padding:d,altBoundary:h}),_=be(e.placement),b=Fe(e.placement),v=!b,y=Ie(_),w="x"===y?"y":"x",A=e.modifiersData.popperOffsets,E=e.rects.reference,T=e.rects.popper,C="function"==typeof m?m(Object.assign({},e.rects,{placement:e.placement})):m,O="number"==typeof C?{mainAxis:C,altAxis:C}:Object.assign({mainAxis:0,altAxis:0},C),x=e.modifiersData.offset?e.modifiersData.offset[e.placement]:null,k={x:0,y:0};if(A){if(o){var L,S="y"===y?zt:Vt,D="y"===y?Rt:qt,$="y"===y?"height":"width",I=A[y],N=I+g[S],P=I-g[D],j=f?-T[$]/2:0,M=b===Xt?E[$]:T[$],F=b===Xt?-T[$]:-E[$],H=e.elements.arrow,W=f&&H?Ce(H):{width:0,height:0},B=e.modifiersData["arrow#persistent"]?e.modifiersData["arrow#persistent"].padding:{top:0,right:0,bottom:0,left:0},z=B[S],R=B[D],q=Ne(0,E[$],W[$]),V=v?E[$]/2-j-q-z-O.mainAxis:M-q-z-O.mainAxis,K=v?-E[$]/2+j+q+R+O.mainAxis:F+q+R+O.mainAxis,Q=e.elements.arrow&&$e(e.elements.arrow),X=Q?"y"===y?Q.clientTop||0:Q.clientLeft||0:0,Y=null!=(L=null==x?void 0:x[y])?L:0,U=I+K-Y,G=Ne(f?ye(N,I+V-Y-X):N,I,f?ve(P,U):P);A[y]=G,k[y]=G-I}if(a){var J,Z="x"===y?zt:Vt,tt="x"===y?Rt:qt,et=A[w],it="y"===w?"height":"width",nt=et+g[Z],st=et-g[tt],ot=-1!==[zt,Vt].indexOf(_),rt=null!=(J=null==x?void 0:x[w])?J:0,at=ot?nt:et-E[it]-T[it]-rt+O.altAxis,lt=ot?et+E[it]+T[it]-rt-O.altAxis:st,ct=f&&ot?function(t,e,i){var n=Ne(t,e,i);return n>i?i:n}(at,et,lt):Ne(f?at:nt,et,f?lt:st);A[w]=ct,k[w]=ct-et}e.modifiersData[n]=k}},requiresIfExists:["offset"]};function di(t,e,i){void 0===i&&(i=!1);var n,s,o=me(e),r=me(e)&&function(t){var e=t.getBoundingClientRect(),i=we(e.width)/t.offsetWidth||1,n=we(e.height)/t.offsetHeight||1;return 1!==i||1!==n}(e),a=Le(e),l=Te(t,r,i),c={scrollLeft:0,scrollTop:0},h={x:0,y:0};return(o||!o&&!i)&&(("body"!==ue(e)||Ue(a))&&(c=(n=e)!==fe(n)&&me(n)?{scrollLeft:(s=n).scrollLeft,scrollTop:s.scrollTop}:Xe(n)),me(e)?((h=Te(e,!0)).x+=e.clientLeft,h.y+=e.clientTop):a&&(h.x=Ye(a))),{x:l.left+c.scrollLeft-h.x,y:l.top+c.scrollTop-h.y,width:l.width,height:l.height}}function ui(t){var e=new Map,i=new Set,n=[];function s(t){i.add(t.name),[].concat(t.requires||[],t.requiresIfExists||[]).forEach((function(t){if(!i.has(t)){var n=e.get(t);n&&s(n)}})),n.push(t)}return t.forEach((function(t){e.set(t.name,t)})),t.forEach((function(t){i.has(t.name)||s(t)})),n}var fi={placement:"bottom",modifiers:[],strategy:"absolute"};function pi(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];return!e.some((function(t){return!(t&&"function"==typeof t.getBoundingClientRect)}))}function mi(t){void 0===t&&(t={});var e=t,i=e.defaultModifiers,n=void 0===i?[]:i,s=e.defaultOptions,o=void 0===s?fi:s;return function(t,e,i){void 0===i&&(i=o);var s,r,a={placement:"bottom",orderedModifiers:[],options:Object.assign({},fi,o),modifiersData:{},elements:{reference:t,popper:e},attributes:{},styles:{}},l=[],c=!1,h={state:a,setOptions:function(i){var s="function"==typeof i?i(a.options):i;d(),a.options=Object.assign({},o,a.options,s),a.scrollParents={reference:pe(t)?Je(t):t.contextElement?Je(t.contextElement):[],popper:Je(e)};var r,c,u=function(t){var e=ui(t);return de.reduce((function(t,i){return t.concat(e.filter((function(t){return t.phase===i})))}),[])}((r=[].concat(n,a.options.modifiers),c=r.reduce((function(t,e){var i=t[e.name];return t[e.name]=i?Object.assign({},i,e,{options:Object.assign({},i.options,e.options),data:Object.assign({},i.data,e.data)}):e,t}),{}),Object.keys(c).map((function(t){return c[t]}))));return a.orderedModifiers=u.filter((function(t){return t.enabled})),a.orderedModifiers.forEach((function(t){var e=t.name,i=t.options,n=void 0===i?{}:i,s=t.effect;if("function"==typeof s){var o=s({state:a,name:e,instance:h,options:n});l.push(o||function(){})}})),h.update()},forceUpdate:function(){if(!c){var t=a.elements,e=t.reference,i=t.popper;if(pi(e,i)){a.rects={reference:di(e,$e(i),"fixed"===a.options.strategy),popper:Ce(i)},a.reset=!1,a.placement=a.options.placement,a.orderedModifiers.forEach((function(t){return a.modifiersData[t.name]=Object.assign({},t.data)}));for(var n=0;n<a.orderedModifiers.length;n++)if(!0!==a.reset){var s=a.orderedModifiers[n],o=s.fn,r=s.options,l=void 0===r?{}:r,d=s.name;"function"==typeof o&&(a=o({state:a,options:l,name:d,instance:h})||a)}else a.reset=!1,n=-1}}},update:(s=function(){return new Promise((function(t){h.forceUpdate(),t(a)}))},function(){return r||(r=new Promise((function(t){Promise.resolve().then((function(){r=void 0,t(s())}))}))),r}),destroy:function(){d(),c=!0}};if(!pi(t,e))return h;function d(){l.forEach((function(t){return t()})),l=[]}return h.setOptions(i).then((function(t){!c&&i.onFirstUpdate&&i.onFirstUpdate(t)})),h}}var gi=mi(),_i=mi({defaultModifiers:[Re,ci,Be,_e]}),bi=mi({defaultModifiers:[Re,ci,Be,_e,li,si,hi,Me,ai]});const vi=Object.freeze(Object.defineProperty({__proto__:null,afterMain:ae,afterRead:se,afterWrite:he,applyStyles:_e,arrow:Me,auto:Kt,basePlacements:Qt,beforeMain:oe,beforeRead:ie,beforeWrite:le,bottom:Rt,clippingParents:Ut,computeStyles:Be,createPopper:bi,createPopperBase:gi,createPopperLite:_i,detectOverflow:ii,end:Yt,eventListeners:Re,flip:si,hide:ai,left:Vt,main:re,modifierPhases:de,offset:li,placements:ee,popper:Jt,popperGenerator:mi,popperOffsets:ci,preventOverflow:hi,read:ne,reference:Zt,right:qt,start:Xt,top:zt,variationPlacements:te,viewport:Gt,write:ce},Symbol.toStringTag,{value:"Module"})),yi="dropdown",wi=".bs.dropdown",Ai=".data-api",Ei="ArrowUp",Ti="ArrowDown",Ci=`hide${wi}`,Oi=`hidden${wi}`,xi=`show${wi}`,ki=`shown${wi}`,Li=`click${wi}${Ai}`,Si=`keydown${wi}${Ai}`,Di=`keyup${wi}${Ai}`,$i="show",Ii='[data-bs-toggle="dropdown"]:not(.disabled):not(:disabled)',Ni=`${Ii}.${$i}`,Pi=".dropdown-menu",ji=p()?"top-end":"top-start",Mi=p()?"top-start":"top-end",Fi=p()?"bottom-end":"bottom-start",Hi=p()?"bottom-start":"bottom-end",Wi=p()?"left-start":"right-start",Bi=p()?"right-start":"left-start",zi={autoClose:!0,boundary:"clippingParents",display:"dynamic",offset:[0,2],popperConfig:null,reference:"toggle"},Ri={autoClose:"(boolean|string)",boundary:"(string|element)",display:"string",offset:"(array|string|function)",popperConfig:"(null|object|function)",reference:"(string|element|object)"};class qi extends W{constructor(t,e){super(t,e),this._popper=null,this._parent=this._element.parentNode,this._menu=z.next(this._element,Pi)[0]||z.prev(this._element,Pi)[0]||z.findOne(Pi,this._parent),this._inNavbar=this._detectNavbar()}static get Default(){return zi}static get DefaultType(){return Ri}static get NAME(){return yi}toggle(){return this._isShown()?this.hide():this.show()}show(){if(l(this._element)||this._isShown())return;const t={relatedTarget:this._element};if(!N.trigger(this._element,xi,t).defaultPrevented){if(this._createPopper(),"ontouchstart"in document.documentElement&&!this._parent.closest(".navbar-nav"))for(const t of[].concat(...document.body.children))N.on(t,"mouseover",h);this._element.focus(),this._element.setAttribute("aria-expanded",!0),this._menu.classList.add($i),this._element.classList.add($i),N.trigger(this._element,ki,t)}}hide(){if(l(this._element)||!this._isShown())return;const t={relatedTarget:this._element};this._completeHide(t)}dispose(){this._popper&&this._popper.destroy(),super.dispose()}update(){this._inNavbar=this._detectNavbar(),this._popper&&this._popper.update()}_completeHide(t){if(!N.trigger(this._element,Ci,t).defaultPrevented){if("ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))N.off(t,"mouseover",h);this._popper&&this._popper.destroy(),this._menu.classList.remove($i),this._element.classList.remove($i),this._element.setAttribute("aria-expanded","false"),F.removeDataAttribute(this._menu,"popper"),N.trigger(this._element,Oi,t)}}_getConfig(t){if("object"==typeof(t=super._getConfig(t)).reference&&!o(t.reference)&&"function"!=typeof t.reference.getBoundingClientRect)throw new TypeError(`${yi.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`);return t}_createPopper(){if(void 0===vi)throw new TypeError("Bootstrap's dropdowns require Popper (https://popper.js.org)");let t=this._element;"parent"===this._config.reference?t=this._parent:o(this._config.reference)?t=r(this._config.reference):"object"==typeof this._config.reference&&(t=this._config.reference);const e=this._getPopperConfig();this._popper=bi(t,this._menu,e)}_isShown(){return this._menu.classList.contains($i)}_getPlacement(){const t=this._parent;if(t.classList.contains("dropend"))return Wi;if(t.classList.contains("dropstart"))return Bi;if(t.classList.contains("dropup-center"))return"top";if(t.classList.contains("dropdown-center"))return"bottom";const e="end"===getComputedStyle(this._menu).getPropertyValue("--bs-position").trim();return t.classList.contains("dropup")?e?Mi:ji:e?Hi:Fi}_detectNavbar(){return null!==this._element.closest(".navbar")}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map((t=>Number.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_getPopperConfig(){const t={placement:this._getPlacement(),modifiers:[{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"offset",options:{offset:this._getOffset()}}]};return(this._inNavbar||"static"===this._config.display)&&(F.setDataAttribute(this._menu,"popper","static"),t.modifiers=[{name:"applyStyles",enabled:!1}]),{...t,...g(this._config.popperConfig,[t])}}_selectMenuItem({key:t,target:e}){const i=z.find(".dropdown-menu .dropdown-item:not(.disabled):not(:disabled)",this._menu).filter((t=>a(t)));i.length&&b(i,e,t===Ti,!i.includes(e)).focus()}static jQueryInterface(t){return this.each((function(){const e=qi.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}static clearMenus(t){if(2===t.button||"keyup"===t.type&&"Tab"!==t.key)return;const e=z.find(Ni);for(const i of e){const e=qi.getInstance(i);if(!e||!1===e._config.autoClose)continue;const n=t.composedPath(),s=n.includes(e._menu);if(n.includes(e._element)||"inside"===e._config.autoClose&&!s||"outside"===e._config.autoClose&&s)continue;if(e._menu.contains(t.target)&&("keyup"===t.type&&"Tab"===t.key||/input|select|option|textarea|form/i.test(t.target.tagName)))continue;const o={relatedTarget:e._element};"click"===t.type&&(o.clickEvent=t),e._completeHide(o)}}static dataApiKeydownHandler(t){const e=/input|textarea/i.test(t.target.tagName),i="Escape"===t.key,n=[Ei,Ti].includes(t.key);if(!n&&!i)return;if(e&&!i)return;t.preventDefault();const s=this.matches(Ii)?this:z.prev(this,Ii)[0]||z.next(this,Ii)[0]||z.findOne(Ii,t.delegateTarget.parentNode),o=qi.getOrCreateInstance(s);if(n)return t.stopPropagation(),o.show(),void o._selectMenuItem(t);o._isShown()&&(t.stopPropagation(),o.hide(),s.focus())}}N.on(document,Si,Ii,qi.dataApiKeydownHandler),N.on(document,Si,Pi,qi.dataApiKeydownHandler),N.on(document,Li,qi.clearMenus),N.on(document,Di,qi.clearMenus),N.on(document,Li,Ii,(function(t){t.preventDefault(),qi.getOrCreateInstance(this).toggle()})),m(qi);const Vi="backdrop",Ki="show",Qi=`mousedown.bs.${Vi}`,Xi={className:"modal-backdrop",clickCallback:null,isAnimated:!1,isVisible:!0,rootElement:"body"},Yi={className:"string",clickCallback:"(function|null)",isAnimated:"boolean",isVisible:"boolean",rootElement:"(element|string)"};class Ui extends H{constructor(t){super(),this._config=this._getConfig(t),this._isAppended=!1,this._element=null}static get Default(){return Xi}static get DefaultType(){return Yi}static get NAME(){return Vi}show(t){if(!this._config.isVisible)return void g(t);this._append();const e=this._getElement();this._config.isAnimated&&d(e),e.classList.add(Ki),this._emulateAnimation((()=>{g(t)}))}hide(t){this._config.isVisible?(this._getElement().classList.remove(Ki),this._emulateAnimation((()=>{this.dispose(),g(t)}))):g(t)}dispose(){this._isAppended&&(N.off(this._element,Qi),this._element.remove(),this._isAppended=!1)}_getElement(){if(!this._element){const t=document.createElement("div");t.className=this._config.className,this._config.isAnimated&&t.classList.add("fade"),this._element=t}return this._element}_configAfterMerge(t){return t.rootElement=r(t.rootElement),t}_append(){if(this._isAppended)return;const t=this._getElement();this._config.rootElement.append(t),N.on(t,Qi,(()=>{g(this._config.clickCallback)})),this._isAppended=!0}_emulateAnimation(t){_(t,this._getElement(),this._config.isAnimated)}}const Gi=".bs.focustrap",Ji=`focusin${Gi}`,Zi=`keydown.tab${Gi}`,tn="backward",en={autofocus:!0,trapElement:null},nn={autofocus:"boolean",trapElement:"element"};class sn extends H{constructor(t){super(),this._config=this._getConfig(t),this._isActive=!1,this._lastTabNavDirection=null}static get Default(){return en}static get DefaultType(){return nn}static get NAME(){return"focustrap"}activate(){this._isActive||(this._config.autofocus&&this._config.trapElement.focus(),N.off(document,Gi),N.on(document,Ji,(t=>this._handleFocusin(t))),N.on(document,Zi,(t=>this._handleKeydown(t))),this._isActive=!0)}deactivate(){this._isActive&&(this._isActive=!1,N.off(document,Gi))}_handleFocusin(t){const{trapElement:e}=this._config;if(t.target===document||t.target===e||e.contains(t.target))return;const i=z.focusableChildren(e);0===i.length?e.focus():this._lastTabNavDirection===tn?i[i.length-1].focus():i[0].focus()}_handleKeydown(t){"Tab"===t.key&&(this._lastTabNavDirection=t.shiftKey?tn:"forward")}}const on=".fixed-top, .fixed-bottom, .is-fixed, .sticky-top",rn=".sticky-top",an="padding-right",ln="margin-right";class cn{constructor(){this._element=document.body}getWidth(){const t=document.documentElement.clientWidth;return Math.abs(window.innerWidth-t)}hide(){const t=this.getWidth();this._disableOverFlow(),this._setElementAttributes(this._element,an,(e=>e+t)),this._setElementAttributes(on,an,(e=>e+t)),this._setElementAttributes(rn,ln,(e=>e-t))}reset(){this._resetElementAttributes(this._element,"overflow"),this._resetElementAttributes(this._element,an),this._resetElementAttributes(on,an),this._resetElementAttributes(rn,ln)}isOverflowing(){return this.getWidth()>0}_disableOverFlow(){this._saveInitialAttribute(this._element,"overflow"),this._element.style.overflow="hidden"}_setElementAttributes(t,e,i){const n=this.getWidth();this._applyManipulationCallback(t,(t=>{if(t!==this._element&&window.innerWidth>t.clientWidth+n)return;this._saveInitialAttribute(t,e);const s=window.getComputedStyle(t).getPropertyValue(e);t.style.setProperty(e,`${i(Number.parseFloat(s))}px`)}))}_saveInitialAttribute(t,e){const i=t.style.getPropertyValue(e);i&&F.setDataAttribute(t,e,i)}_resetElementAttributes(t,e){this._applyManipulationCallback(t,(t=>{const i=F.getDataAttribute(t,e);null!==i?(F.removeDataAttribute(t,e),t.style.setProperty(e,i)):t.style.removeProperty(e)}))}_applyManipulationCallback(t,e){if(o(t))e(t);else for(const i of z.find(t,this._element))e(i)}}const hn=".bs.modal",dn=`hide${hn}`,un=`hidePrevented${hn}`,fn=`hidden${hn}`,pn=`show${hn}`,mn=`shown${hn}`,gn=`resize${hn}`,_n=`click.dismiss${hn}`,bn=`mousedown.dismiss${hn}`,vn=`keydown.dismiss${hn}`,yn=`click${hn}.data-api`,wn="modal-open",An="show",En="modal-static",Tn={backdrop:!0,focus:!0,keyboard:!0},Cn={backdrop:"(boolean|string)",focus:"boolean",keyboard:"boolean"};class On extends W{constructor(t,e){super(t,e),this._dialog=z.findOne(".modal-dialog",this._element),this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._isShown=!1,this._isTransitioning=!1,this._scrollBar=new cn,this._addEventListeners()}static get Default(){return Tn}static get DefaultType(){return Cn}static get NAME(){return"modal"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||this._isTransitioning||N.trigger(this._element,pn,{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._isTransitioning=!0,this._scrollBar.hide(),document.body.classList.add(wn),this._adjustDialog(),this._backdrop.show((()=>this._showElement(t))))}hide(){this._isShown&&!this._isTransitioning&&(N.trigger(this._element,dn).defaultPrevented||(this._isShown=!1,this._isTransitioning=!0,this._focustrap.deactivate(),this._element.classList.remove(An),this._queueCallback((()=>this._hideModal()),this._element,this._isAnimated())))}dispose(){N.off(window,hn),N.off(this._dialog,hn),this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}handleUpdate(){this._adjustDialog()}_initializeBackDrop(){return new Ui({isVisible:Boolean(this._config.backdrop),isAnimated:this._isAnimated()})}_initializeFocusTrap(){return new sn({trapElement:this._element})}_showElement(t){document.body.contains(this._element)||document.body.append(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.scrollTop=0;const e=z.findOne(".modal-body",this._dialog);e&&(e.scrollTop=0),d(this._element),this._element.classList.add(An),this._queueCallback((()=>{this._config.focus&&this._focustrap.activate(),this._isTransitioning=!1,N.trigger(this._element,mn,{relatedTarget:t})}),this._dialog,this._isAnimated())}_addEventListeners(){N.on(this._element,vn,(t=>{"Escape"===t.key&&(this._config.keyboard?this.hide():this._triggerBackdropTransition())})),N.on(window,gn,(()=>{this._isShown&&!this._isTransitioning&&this._adjustDialog()})),N.on(this._element,bn,(t=>{N.one(this._element,_n,(e=>{this._element===t.target&&this._element===e.target&&("static"!==this._config.backdrop?this._config.backdrop&&this.hide():this._triggerBackdropTransition())}))}))}_hideModal(){this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._isTransitioning=!1,this._backdrop.hide((()=>{document.body.classList.remove(wn),this._resetAdjustments(),this._scrollBar.reset(),N.trigger(this._element,fn)}))}_isAnimated(){return this._element.classList.contains("fade")}_triggerBackdropTransition(){if(N.trigger(this._element,un).defaultPrevented)return;const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._element.style.overflowY;"hidden"===e||this._element.classList.contains(En)||(t||(this._element.style.overflowY="hidden"),this._element.classList.add(En),this._queueCallback((()=>{this._element.classList.remove(En),this._queueCallback((()=>{this._element.style.overflowY=e}),this._dialog)}),this._dialog),this._element.focus())}_adjustDialog(){const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._scrollBar.getWidth(),i=e>0;if(i&&!t){const t=p()?"paddingLeft":"paddingRight";this._element.style[t]=`${e}px`}if(!i&&t){const t=p()?"paddingRight":"paddingLeft";this._element.style[t]=`${e}px`}}_resetAdjustments(){this._element.style.paddingLeft="",this._element.style.paddingRight=""}static jQueryInterface(t,e){return this.each((function(){const i=On.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t](e)}}))}}N.on(document,yn,'[data-bs-toggle="modal"]',(function(t){const e=z.getElementFromSelector(this);["A","AREA"].includes(this.tagName)&&t.preventDefault(),N.one(e,pn,(t=>{t.defaultPrevented||N.one(e,fn,(()=>{a(this)&&this.focus()}))}));const i=z.findOne(".modal.show");i&&On.getInstance(i).hide(),On.getOrCreateInstance(e).toggle(this)})),R(On),m(On);const xn=".bs.offcanvas",kn=".data-api",Ln=`load${xn}${kn}`,Sn="show",Dn="showing",$n="hiding",In=".offcanvas.show",Nn=`show${xn}`,Pn=`shown${xn}`,jn=`hide${xn}`,Mn=`hidePrevented${xn}`,Fn=`hidden${xn}`,Hn=`resize${xn}`,Wn=`click${xn}${kn}`,Bn=`keydown.dismiss${xn}`,zn={backdrop:!0,keyboard:!0,scroll:!1},Rn={backdrop:"(boolean|string)",keyboard:"boolean",scroll:"boolean"};class qn extends W{constructor(t,e){super(t,e),this._isShown=!1,this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._addEventListeners()}static get Default(){return zn}static get DefaultType(){return Rn}static get NAME(){return"offcanvas"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||N.trigger(this._element,Nn,{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._backdrop.show(),this._config.scroll||(new cn).hide(),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.classList.add(Dn),this._queueCallback((()=>{this._config.scroll&&!this._config.backdrop||this._focustrap.activate(),this._element.classList.add(Sn),this._element.classList.remove(Dn),N.trigger(this._element,Pn,{relatedTarget:t})}),this._element,!0))}hide(){this._isShown&&(N.trigger(this._element,jn).defaultPrevented||(this._focustrap.deactivate(),this._element.blur(),this._isShown=!1,this._element.classList.add($n),this._backdrop.hide(),this._queueCallback((()=>{this._element.classList.remove(Sn,$n),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._config.scroll||(new cn).reset(),N.trigger(this._element,Fn)}),this._element,!0)))}dispose(){this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}_initializeBackDrop(){const t=Boolean(this._config.backdrop);return new Ui({className:"offcanvas-backdrop",isVisible:t,isAnimated:!0,rootElement:this._element.parentNode,clickCallback:t?()=>{"static"!==this._config.backdrop?this.hide():N.trigger(this._element,Mn)}:null})}_initializeFocusTrap(){return new sn({trapElement:this._element})}_addEventListeners(){N.on(this._element,Bn,(t=>{"Escape"===t.key&&(this._config.keyboard?this.hide():N.trigger(this._element,Mn))}))}static jQueryInterface(t){return this.each((function(){const e=qn.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}N.on(document,Wn,'[data-bs-toggle="offcanvas"]',(function(t){const e=z.getElementFromSelector(this);if(["A","AREA"].includes(this.tagName)&&t.preventDefault(),l(this))return;N.one(e,Fn,(()=>{a(this)&&this.focus()}));const i=z.findOne(In);i&&i!==e&&qn.getInstance(i).hide(),qn.getOrCreateInstance(e).toggle(this)})),N.on(window,Ln,(()=>{for(const t of z.find(In))qn.getOrCreateInstance(t).show()})),N.on(window,Hn,(()=>{for(const t of z.find("[aria-modal][class*=show][class*=offcanvas-]"))"fixed"!==getComputedStyle(t).position&&qn.getOrCreateInstance(t).hide()})),R(qn),m(qn);const Vn={"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],dd:[],div:[],dl:[],dt:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","srcset","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},Kn=new Set(["background","cite","href","itemtype","longdesc","poster","src","xlink:href"]),Qn=/^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i,Xn=(t,e)=>{const i=t.nodeName.toLowerCase();return e.includes(i)?!Kn.has(i)||Boolean(Qn.test(t.nodeValue)):e.filter((t=>t instanceof RegExp)).some((t=>t.test(i)))},Yn={allowList:Vn,content:{},extraClass:"",html:!1,sanitize:!0,sanitizeFn:null,template:"<div></div>"},Un={allowList:"object",content:"object",extraClass:"(string|function)",html:"boolean",sanitize:"boolean",sanitizeFn:"(null|function)",template:"string"},Gn={entry:"(string|element|function|null)",selector:"(string|element)"};class Jn extends H{constructor(t){super(),this._config=this._getConfig(t)}static get Default(){return Yn}static get DefaultType(){return Un}static get NAME(){return"TemplateFactory"}getContent(){return Object.values(this._config.content).map((t=>this._resolvePossibleFunction(t))).filter(Boolean)}hasContent(){return this.getContent().length>0}changeContent(t){return this._checkContent(t),this._config.content={...this._config.content,...t},this}toHtml(){const t=document.createElement("div");t.innerHTML=this._maybeSanitize(this._config.template);for(const[e,i]of Object.entries(this._config.content))this._setContent(t,i,e);const e=t.children[0],i=this._resolvePossibleFunction(this._config.extraClass);return i&&e.classList.add(...i.split(" ")),e}_typeCheckConfig(t){super._typeCheckConfig(t),this._checkContent(t.content)}_checkContent(t){for(const[e,i]of Object.entries(t))super._typeCheckConfig({selector:e,entry:i},Gn)}_setContent(t,e,i){const n=z.findOne(i,t);n&&((e=this._resolvePossibleFunction(e))?o(e)?this._putElementInTemplate(r(e),n):this._config.html?n.innerHTML=this._maybeSanitize(e):n.textContent=e:n.remove())}_maybeSanitize(t){return this._config.sanitize?function(t,e,i){if(!t.length)return t;if(i&&"function"==typeof i)return i(t);const n=(new window.DOMParser).parseFromString(t,"text/html"),s=[].concat(...n.body.querySelectorAll("*"));for(const t of s){const i=t.nodeName.toLowerCase();if(!Object.keys(e).includes(i)){t.remove();continue}const n=[].concat(...t.attributes),s=[].concat(e["*"]||[],e[i]||[]);for(const e of n)Xn(e,s)||t.removeAttribute(e.nodeName)}return n.body.innerHTML}(t,this._config.allowList,this._config.sanitizeFn):t}_resolvePossibleFunction(t){return g(t,[this])}_putElementInTemplate(t,e){if(this._config.html)return e.innerHTML="",void e.append(t);e.textContent=t.textContent}}const Zn=new Set(["sanitize","allowList","sanitizeFn"]),ts="fade",es="show",is=".modal",ns="hide.bs.modal",ss="hover",os="focus",rs={AUTO:"auto",TOP:"top",RIGHT:p()?"left":"right",BOTTOM:"bottom",LEFT:p()?"right":"left"},as={allowList:Vn,animation:!0,boundary:"clippingParents",container:!1,customClass:"",delay:0,fallbackPlacements:["top","right","bottom","left"],html:!1,offset:[0,6],placement:"top",popperConfig:null,sanitize:!0,sanitizeFn:null,selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',title:"",trigger:"hover focus"},ls={allowList:"object",animation:"boolean",boundary:"(string|element)",container:"(string|element|boolean)",customClass:"(string|function)",delay:"(number|object)",fallbackPlacements:"array",html:"boolean",offset:"(array|string|function)",placement:"(string|function)",popperConfig:"(null|object|function)",sanitize:"boolean",sanitizeFn:"(null|function)",selector:"(string|boolean)",template:"string",title:"(string|element|function)",trigger:"string"};class cs extends W{constructor(t,e){if(void 0===vi)throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");super(t,e),this._isEnabled=!0,this._timeout=0,this._isHovered=null,this._activeTrigger={},this._popper=null,this._templateFactory=null,this._newContent=null,this.tip=null,this._setListeners(),this._config.selector||this._fixTitle()}static get Default(){return as}static get DefaultType(){return ls}static get NAME(){return"tooltip"}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}toggleEnabled(){this._isEnabled=!this._isEnabled}toggle(){this._isEnabled&&(this._activeTrigger.click=!this._activeTrigger.click,this._isShown()?this._leave():this._enter())}dispose(){clearTimeout(this._timeout),N.off(this._element.closest(is),ns,this._hideModalHandler),this._element.getAttribute("data-bs-original-title")&&this._element.setAttribute("title",this._element.getAttribute("data-bs-original-title")),this._disposePopper(),super.dispose()}show(){if("none"===this._element.style.display)throw new Error("Please use show on visible elements");if(!this._isWithContent()||!this._isEnabled)return;const t=N.trigger(this._element,this.constructor.eventName("show")),e=(c(this._element)||this._element.ownerDocument.documentElement).contains(this._element);if(t.defaultPrevented||!e)return;this._disposePopper();const i=this._getTipElement();this._element.setAttribute("aria-describedby",i.getAttribute("id"));const{container:n}=this._config;if(this._element.ownerDocument.documentElement.contains(this.tip)||(n.append(i),N.trigger(this._element,this.constructor.eventName("inserted"))),this._popper=this._createPopper(i),i.classList.add(es),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))N.on(t,"mouseover",h);this._queueCallback((()=>{N.trigger(this._element,this.constructor.eventName("shown")),!1===this._isHovered&&this._leave(),this._isHovered=!1}),this.tip,this._isAnimated())}hide(){if(this._isShown()&&!N.trigger(this._element,this.constructor.eventName("hide")).defaultPrevented){if(this._getTipElement().classList.remove(es),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))N.off(t,"mouseover",h);this._activeTrigger.click=!1,this._activeTrigger[os]=!1,this._activeTrigger[ss]=!1,this._isHovered=null,this._queueCallback((()=>{this._isWithActiveTrigger()||(this._isHovered||this._disposePopper(),this._element.removeAttribute("aria-describedby"),N.trigger(this._element,this.constructor.eventName("hidden")))}),this.tip,this._isAnimated())}}update(){this._popper&&this._popper.update()}_isWithContent(){return Boolean(this._getTitle())}_getTipElement(){return this.tip||(this.tip=this._createTipElement(this._newContent||this._getContentForTemplate())),this.tip}_createTipElement(t){const e=this._getTemplateFactory(t).toHtml();if(!e)return null;e.classList.remove(ts,es),e.classList.add(`bs-${this.constructor.NAME}-auto`);const i=(t=>{do{t+=Math.floor(1e6*Math.random())}while(document.getElementById(t));return t})(this.constructor.NAME).toString();return e.setAttribute("id",i),this._isAnimated()&&e.classList.add(ts),e}setContent(t){this._newContent=t,this._isShown()&&(this._disposePopper(),this.show())}_getTemplateFactory(t){return this._templateFactory?this._templateFactory.changeContent(t):this._templateFactory=new Jn({...this._config,content:t,extraClass:this._resolvePossibleFunction(this._config.customClass)}),this._templateFactory}_getContentForTemplate(){return{".tooltip-inner":this._getTitle()}}_getTitle(){return this._resolvePossibleFunction(this._config.title)||this._element.getAttribute("data-bs-original-title")}_initializeOnDelegatedTarget(t){return this.constructor.getOrCreateInstance(t.delegateTarget,this._getDelegateConfig())}_isAnimated(){return this._config.animation||this.tip&&this.tip.classList.contains(ts)}_isShown(){return this.tip&&this.tip.classList.contains(es)}_createPopper(t){const e=g(this._config.placement,[this,t,this._element]),i=rs[e.toUpperCase()];return bi(this._element,t,this._getPopperConfig(i))}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map((t=>Number.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_resolvePossibleFunction(t){return g(t,[this._element])}_getPopperConfig(t){const e={placement:t,modifiers:[{name:"flip",options:{fallbackPlacements:this._config.fallbackPlacements}},{name:"offset",options:{offset:this._getOffset()}},{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"arrow",options:{element:`.${this.constructor.NAME}-arrow`}},{name:"preSetPlacement",enabled:!0,phase:"beforeMain",fn:t=>{this._getTipElement().setAttribute("data-popper-placement",t.state.placement)}}]};return{...e,...g(this._config.popperConfig,[e])}}_setListeners(){const t=this._config.trigger.split(" ");for(const e of t)if("click"===e)N.on(this._element,this.constructor.eventName("click"),this._config.selector,(t=>{this._initializeOnDelegatedTarget(t).toggle()}));else if("manual"!==e){const t=e===ss?this.constructor.eventName("mouseenter"):this.constructor.eventName("focusin"),i=e===ss?this.constructor.eventName("mouseleave"):this.constructor.eventName("focusout");N.on(this._element,t,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusin"===t.type?os:ss]=!0,e._enter()})),N.on(this._element,i,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusout"===t.type?os:ss]=e._element.contains(t.relatedTarget),e._leave()}))}this._hideModalHandler=()=>{this._element&&this.hide()},N.on(this._element.closest(is),ns,this._hideModalHandler)}_fixTitle(){const t=this._element.getAttribute("title");t&&(this._element.getAttribute("aria-label")||this._element.textContent.trim()||this._element.setAttribute("aria-label",t),this._element.setAttribute("data-bs-original-title",t),this._element.removeAttribute("title"))}_enter(){this._isShown()||this._isHovered?this._isHovered=!0:(this._isHovered=!0,this._setTimeout((()=>{this._isHovered&&this.show()}),this._config.delay.show))}_leave(){this._isWithActiveTrigger()||(this._isHovered=!1,this._setTimeout((()=>{this._isHovered||this.hide()}),this._config.delay.hide))}_setTimeout(t,e){clearTimeout(this._timeout),this._timeout=setTimeout(t,e)}_isWithActiveTrigger(){return Object.values(this._activeTrigger).includes(!0)}_getConfig(t){const e=F.getDataAttributes(this._element);for(const t of Object.keys(e))Zn.has(t)&&delete e[t];return t={...e,..."object"==typeof t&&t?t:{}},t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t.container=!1===t.container?document.body:r(t.container),"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),"number"==typeof t.title&&(t.title=t.title.toString()),"number"==typeof t.content&&(t.content=t.content.toString()),t}_getDelegateConfig(){const t={};for(const[e,i]of Object.entries(this._config))this.constructor.Default[e]!==i&&(t[e]=i);return t.selector=!1,t.trigger="manual",t}_disposePopper(){this._popper&&(this._popper.destroy(),this._popper=null),this.tip&&(this.tip.remove(),this.tip=null)}static jQueryInterface(t){return this.each((function(){const e=cs.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}m(cs);const hs={...cs.Default,content:"",offset:[0,8],placement:"right",template:'<div class="popover" role="tooltip"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>',trigger:"click"},ds={...cs.DefaultType,content:"(null|string|element|function)"};class us extends cs{static get Default(){return hs}static get DefaultType(){return ds}static get NAME(){return"popover"}_isWithContent(){return this._getTitle()||this._getContent()}_getContentForTemplate(){return{".popover-header":this._getTitle(),".popover-body":this._getContent()}}_getContent(){return this._resolvePossibleFunction(this._config.content)}static jQueryInterface(t){return this.each((function(){const e=us.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}m(us);const fs=".bs.scrollspy",ps=`activate${fs}`,ms=`click${fs}`,gs=`load${fs}.data-api`,_s="active",bs="[href]",vs=".nav-link",ys=`${vs}, .nav-item > ${vs}, .list-group-item`,ws={offset:null,rootMargin:"0px 0px -25%",smoothScroll:!1,target:null,threshold:[.1,.5,1]},As={offset:"(number|null)",rootMargin:"string",smoothScroll:"boolean",target:"element",threshold:"array"};class Es extends W{constructor(t,e){super(t,e),this._targetLinks=new Map,this._observableSections=new Map,this._rootElement="visible"===getComputedStyle(this._element).overflowY?null:this._element,this._activeTarget=null,this._observer=null,this._previousScrollData={visibleEntryTop:0,parentScrollTop:0},this.refresh()}static get Default(){return ws}static get DefaultType(){return As}static get NAME(){return"scrollspy"}refresh(){this._initializeTargetsAndObservables(),this._maybeEnableSmoothScroll(),this._observer?this._observer.disconnect():this._observer=this._getNewObserver();for(const t of this._observableSections.values())this._observer.observe(t)}dispose(){this._observer.disconnect(),super.dispose()}_configAfterMerge(t){return t.target=r(t.target)||document.body,t.rootMargin=t.offset?`${t.offset}px 0px -30%`:t.rootMargin,"string"==typeof t.threshold&&(t.threshold=t.threshold.split(",").map((t=>Number.parseFloat(t)))),t}_maybeEnableSmoothScroll(){this._config.smoothScroll&&(N.off(this._config.target,ms),N.on(this._config.target,ms,bs,(t=>{const e=this._observableSections.get(t.target.hash);if(e){t.preventDefault();const i=this._rootElement||window,n=e.offsetTop-this._element.offsetTop;if(i.scrollTo)return void i.scrollTo({top:n,behavior:"smooth"});i.scrollTop=n}})))}_getNewObserver(){const t={root:this._rootElement,threshold:this._config.threshold,rootMargin:this._config.rootMargin};return new IntersectionObserver((t=>this._observerCallback(t)),t)}_observerCallback(t){const e=t=>this._targetLinks.get(`#${t.target.id}`),i=t=>{this._previousScrollData.visibleEntryTop=t.target.offsetTop,this._process(e(t))},n=(this._rootElement||document.documentElement).scrollTop,s=n>=this._previousScrollData.parentScrollTop;this._previousScrollData.parentScrollTop=n;for(const o of t){if(!o.isIntersecting){this._activeTarget=null,this._clearActiveClass(e(o));continue}const t=o.target.offsetTop>=this._previousScrollData.visibleEntryTop;if(s&&t){if(i(o),!n)return}else s||t||i(o)}}_initializeTargetsAndObservables(){this._targetLinks=new Map,this._observableSections=new Map;const t=z.find(bs,this._config.target);for(const e of t){if(!e.hash||l(e))continue;const t=z.findOne(decodeURI(e.hash),this._element);a(t)&&(this._targetLinks.set(decodeURI(e.hash),e),this._observableSections.set(e.hash,t))}}_process(t){this._activeTarget!==t&&(this._clearActiveClass(this._config.target),this._activeTarget=t,t.classList.add(_s),this._activateParents(t),N.trigger(this._element,ps,{relatedTarget:t}))}_activateParents(t){if(t.classList.contains("dropdown-item"))z.findOne(".dropdown-toggle",t.closest(".dropdown")).classList.add(_s);else for(const e of z.parents(t,".nav, .list-group"))for(const t of z.prev(e,ys))t.classList.add(_s)}_clearActiveClass(t){t.classList.remove(_s);const e=z.find(`${bs}.${_s}`,t);for(const t of e)t.classList.remove(_s)}static jQueryInterface(t){return this.each((function(){const e=Es.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}N.on(window,gs,(()=>{for(const t of z.find('[data-bs-spy="scroll"]'))Es.getOrCreateInstance(t)})),m(Es);const Ts=".bs.tab",Cs=`hide${Ts}`,Os=`hidden${Ts}`,xs=`show${Ts}`,ks=`shown${Ts}`,Ls=`click${Ts}`,Ss=`keydown${Ts}`,Ds=`load${Ts}`,$s="ArrowLeft",Is="ArrowRight",Ns="ArrowUp",Ps="ArrowDown",js="Home",Ms="End",Fs="active",Hs="fade",Ws="show",Bs=".dropdown-toggle",zs=`:not(${Bs})`,Rs='[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]',qs=`.nav-link${zs}, .list-group-item${zs}, [role="tab"]${zs}, ${Rs}`,Vs=`.${Fs}[data-bs-toggle="tab"], .${Fs}[data-bs-toggle="pill"], .${Fs}[data-bs-toggle="list"]`;class Ks extends W{constructor(t){super(t),this._parent=this._element.closest('.list-group, .nav, [role="tablist"]'),this._parent&&(this._setInitialAttributes(this._parent,this._getChildren()),N.on(this._element,Ss,(t=>this._keydown(t))))}static get NAME(){return"tab"}show(){const t=this._element;if(this._elemIsActive(t))return;const e=this._getActiveElem(),i=e?N.trigger(e,Cs,{relatedTarget:t}):null;N.trigger(t,xs,{relatedTarget:e}).defaultPrevented||i&&i.defaultPrevented||(this._deactivate(e,t),this._activate(t,e))}_activate(t,e){t&&(t.classList.add(Fs),this._activate(z.getElementFromSelector(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.removeAttribute("tabindex"),t.setAttribute("aria-selected",!0),this._toggleDropDown(t,!0),N.trigger(t,ks,{relatedTarget:e})):t.classList.add(Ws)}),t,t.classList.contains(Hs)))}_deactivate(t,e){t&&(t.classList.remove(Fs),t.blur(),this._deactivate(z.getElementFromSelector(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.setAttribute("aria-selected",!1),t.setAttribute("tabindex","-1"),this._toggleDropDown(t,!1),N.trigger(t,Os,{relatedTarget:e})):t.classList.remove(Ws)}),t,t.classList.contains(Hs)))}_keydown(t){if(![$s,Is,Ns,Ps,js,Ms].includes(t.key))return;t.stopPropagation(),t.preventDefault();const e=this._getChildren().filter((t=>!l(t)));let i;if([js,Ms].includes(t.key))i=e[t.key===js?0:e.length-1];else{const n=[Is,Ps].includes(t.key);i=b(e,t.target,n,!0)}i&&(i.focus({preventScroll:!0}),Ks.getOrCreateInstance(i).show())}_getChildren(){return z.find(qs,this._parent)}_getActiveElem(){return this._getChildren().find((t=>this._elemIsActive(t)))||null}_setInitialAttributes(t,e){this._setAttributeIfNotExists(t,"role","tablist");for(const t of e)this._setInitialAttributesOnChild(t)}_setInitialAttributesOnChild(t){t=this._getInnerElement(t);const e=this._elemIsActive(t),i=this._getOuterElement(t);t.setAttribute("aria-selected",e),i!==t&&this._setAttributeIfNotExists(i,"role","presentation"),e||t.setAttribute("tabindex","-1"),this._setAttributeIfNotExists(t,"role","tab"),this._setInitialAttributesOnTargetPanel(t)}_setInitialAttributesOnTargetPanel(t){const e=z.getElementFromSelector(t);e&&(this._setAttributeIfNotExists(e,"role","tabpanel"),t.id&&this._setAttributeIfNotExists(e,"aria-labelledby",`${t.id}`))}_toggleDropDown(t,e){const i=this._getOuterElement(t);if(!i.classList.contains("dropdown"))return;const n=(t,n)=>{const s=z.findOne(t,i);s&&s.classList.toggle(n,e)};n(Bs,Fs),n(".dropdown-menu",Ws),i.setAttribute("aria-expanded",e)}_setAttributeIfNotExists(t,e,i){t.hasAttribute(e)||t.setAttribute(e,i)}_elemIsActive(t){return t.classList.contains(Fs)}_getInnerElement(t){return t.matches(qs)?t:z.findOne(qs,t)}_getOuterElement(t){return t.closest(".nav-item, .list-group-item")||t}static jQueryInterface(t){return this.each((function(){const e=Ks.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}N.on(document,Ls,Rs,(function(t){["A","AREA"].includes(this.tagName)&&t.preventDefault(),l(this)||Ks.getOrCreateInstance(this).show()})),N.on(window,Ds,(()=>{for(const t of z.find(Vs))Ks.getOrCreateInstance(t)})),m(Ks);const Qs=".bs.toast",Xs=`mouseover${Qs}`,Ys=`mouseout${Qs}`,Us=`focusin${Qs}`,Gs=`focusout${Qs}`,Js=`hide${Qs}`,Zs=`hidden${Qs}`,to=`show${Qs}`,eo=`shown${Qs}`,io="hide",no="show",so="showing",oo={animation:"boolean",autohide:"boolean",delay:"number"},ro={animation:!0,autohide:!0,delay:5e3};class ao extends W{constructor(t,e){super(t,e),this._timeout=null,this._hasMouseInteraction=!1,this._hasKeyboardInteraction=!1,this._setListeners()}static get Default(){return ro}static get DefaultType(){return oo}static get NAME(){return"toast"}show(){N.trigger(this._element,to).defaultPrevented||(this._clearTimeout(),this._config.animation&&this._element.classList.add("fade"),this._element.classList.remove(io),d(this._element),this._element.classList.add(no,so),this._queueCallback((()=>{this._element.classList.remove(so),N.trigger(this._element,eo),this._maybeScheduleHide()}),this._element,this._config.animation))}hide(){this.isShown()&&(N.trigger(this._element,Js).defaultPrevented||(this._element.classList.add(so),this._queueCallback((()=>{this._element.classList.add(io),this._element.classList.remove(so,no),N.trigger(this._element,Zs)}),this._element,this._config.animation)))}dispose(){this._clearTimeout(),this.isShown()&&this._element.classList.remove(no),super.dispose()}isShown(){return this._element.classList.contains(no)}_maybeScheduleHide(){this._config.autohide&&(this._hasMouseInteraction||this._hasKeyboardInteraction||(this._timeout=setTimeout((()=>{this.hide()}),this._config.delay)))}_onInteraction(t,e){switch(t.type){case"mouseover":case"mouseout":this._hasMouseInteraction=e;break;case"focusin":case"focusout":this._hasKeyboardInteraction=e}if(e)return void this._clearTimeout();const i=t.relatedTarget;this._element===i||this._element.contains(i)||this._maybeScheduleHide()}_setListeners(){N.on(this._element,Xs,(t=>this._onInteraction(t,!0))),N.on(this._element,Ys,(t=>this._onInteraction(t,!1))),N.on(this._element,Us,(t=>this._onInteraction(t,!0))),N.on(this._element,Gs,(t=>this._onInteraction(t,!1)))}_clearTimeout(){clearTimeout(this._timeout),this._timeout=null}static jQueryInterface(t){return this.each((function(){const e=ao.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}return R(ao),m(ao),{Alert:Q,Button:Y,Carousel:xt,Collapse:Bt,Dropdown:qi,Modal:On,Offcanvas:qn,Popover:us,ScrollSpy:Es,Tab:Ks,Toast:ao,Tooltip:cs}}));
//# sourceMappingURL=bootstrap.bundle.min.js.map
///#source 1 1 /Assets/scripts/libs/codehouse-js/client.min.js
/*
 * ---------------------------------------- *
 * Name:     Codehouse Detection            *
 * Type:     JavaScript Class               *
 * Version:  1.3.0                          *
 * Author:   Codehouse LTD                  *
 * Status:   Development                    *
 * ---------------------------------------- *
 */

window.client||(window.client={}),window.client=new function(){var e=navigator.userAgent.toLowerCase(),i=document.createElement("div"),o={iPad:"ipad",iPhone:"iphone",iOS:"iphone|ipad|ipod",Mac:"intel mac",Chrome:"chrome",Firefox:"firefox",IE:"msie|rv:11",IE7:"msie 7.0",IE8:"msie 8.0",IE9:"msie 9.0",IE10:"msie 10.0",IE11:"rv:11.0",OldIE:"msie 7.0|msie 8.0",Opera:"opera|opr",Android:"android",Mobile:"android|webos|iphone|ipad|ipod|blackberry|windows phone|iemobile",WindowsPhone:"windows phone"},n=["WebkitPerspective","MozPerspective","OPerspective","msPerspective"],r=function(){function r(e,i){var o=i.charAt(0).toUpperCase();return e["webkit"+o]||e[i]||e["moz"+o]||e["ms"+o]||function(e){setTimeout(e,60)}}var t={},a="";for(var s in o){var d=new RegExp(o[s],["i"]);t[s]=d.test(e)}for(var c in n)if(void 0!==i.style[n[c]]){t.Perspective=n[c],t.CSSVendorPrefix="-"+n[c].replace("Perspective","").toLowerCase()+"-";break}t.Safari=e.indexOf("chrome")>-1?!1:e.indexOf("safari")>-1,t.HighDef=window.devicePixelRatio>1,t.RequestAnimationId=r(window,"requestAnimationFrame"),t.CancelAnimationId=r(window,"cancelAnimationFrame"),t.iOSVersion=t.iOS?parseFloat(e.split(" os ")[1].split(" ")[0].replace("_",".")):void 0;for(var m in t)t[m]&&(a+=" "+m.toLowerCase());return t.domApply=function(){document.documentElement.className+=a},t};return new r};

///#source 1 1 /Assets/scripts/libs/codehouse-js/cookie.min.js
/* 
 * ---------------------------------------- *
 * Name: 	Cookie                          *
 * Type: 	JavaScript Class                *
 * Version: v2.0.2                          *
 * Author:	Matt O'Neill                    *
 * Status:	Release Candidate               *
 * ---------------------------------------- *
 */


var Cookie = function () { this.read = function () { if (!document.cookie) { return false } var t = [], n = document.cookie.split(/; */); for (var r = 0; r < n.length; r++) { var i = n[r].split("="); var s = new e(i[0], i[1]); t.push(s) } return t }; this.write = function (e, t, n) { if (n != undefined) { var r = new Date; r.setDate(r.getDate() + n); var i = "; expires=" + r.toUTCString() } document.cookie = n !== undefined ? e + "=" + t + i + ";path=/" : e + "=" + t + ";path=/" }; this.check = function (e) { var t = this.read(); for (var n in t) { if (t[n].name === e) { return t[n].value } } return undefined }; this.erase = function (e) { if (e !== undefined) { this.write(e, "", -1) } else { var t = this.read(); for (var n in t) { this.write(t[n].name, "", -1) } } }; var e = function (e, t) { this.name = e; this.value = t } }

///#source 1 1 /Assets/scripts/libs/codehouse-js/codehouse-placeholders.min.js
/* 
 * ---------------------------------------- *
 * Name:    Placeholder Polyfill            *
 * Version: 1.0.0                           *
 * Author:  Codehouse                       * 
 * Requisites: >= jquery 1.9.1              *
 *             stylish-forms(opt)           *
 *             client.js(opt)               *
 * ---------------------------------------- *
 */

window.chPlaceholders = window.chPlaceholders || new function (a) { var b = this, c = a('input[type="url"], input[type="text"], input[type="tel"], input[type="email"], input[type="password"], textarea'), d = { setSpans: function (b, c) { var d = b.parent('[class^="stylish-"]').length ? b.parent() : b; d.wrap('<span class="placeholder-wrapper"></span>'), a('<span class="placeholder">' + c + "</span>").insertAfter(d).on("click", function () { a(this).closest(".placeholder-wrapper").find("input, textarea").trigger("focus") }) }, checkValue: function (a) { "" === a.val() ? a.parents(".placeholder-wrapper").find(".placeholder").show() : a.parents(".placeholder-wrapper").find(".placeholder").hide() }, inputCheck: function (c) { var e = c.type; if (b.hideOnFocus === !1) { if ("focus" === e) return } else if ("focus" === e && a(this).parents(".placeholder-wrapper").find(".placeholder").hide(), /input|keyup|focus/i.test(e)) return; d.checkValue(a(this)) }, run: function () { var b = a(this), c = b.data("placeholder-text"); "undefined" == typeof c && (c = b.attr("placeholder") || "", b.data("placeholder-text", c)), "" !== c && (b.attr("placeholder", ""), d.setSpans(b, c), b.on("blur focus input keyup", d.inputCheck), d.checkValue(b)) } }; b.hideOnFocus = !0, this.apply = function (a) { a = a || c, a.each(d.run) } }(jQuery);
///#source 1 1 /Assets/scripts/libs/codehouse-js/form-validation.min.js
/* Form Validation 4.2.5 */
window.FormValidation || (window.FormValidation = {}), window.FormValidation.Application = function () { "use strict"; function e() { this.submit = !1, this.valid = !0 } String.prototype.toBool = function () { return !/^(false|0)$/i.test(this) }; var n = function (n, t) { var r = !1, o = n, a = null, s = null, d = null, u = null, l = null, f = null, c = { form: new e, segs: [], activeSeg: 0, id: "modForm_" + t, customRules: {}, disabledSegs: 0 }, m = { data: [] }, v = null, h = void 0, p = void 0, g = void 0, b = !0, w = {}, y = void 0, x = [], _ = 0, V = 0, F = !1, E = {}, S = function () { for (var e = FormValidation.Manifest.Externals.manifest, n = 0; n < e.length; n += 1) { var t = e[n]; "undefined" == typeof FormValidation.Manifest[t.className] && i.handle(i.fact.loadRuleExtensionFile + ": " + t.className), i.safe(M.extensions.registerRule, [t.className], { msg: "ruleExtension", param: t.filename }) } M.set(), M._dom(), C() }, M = { inline: void 0, summary: void 0, instantFeedback: void 0, serverErrorMessage: void 0, extensions: { registerRule: function (e) { var n = new window.FormValidation.Manifest[e]; for (var t in n) "function" == typeof n[t] && (A.rules[t] = n[t]) } }, set: function () { M.inline = o.attr("data-inline-errors"), M.summary = o.attr("data-error-summary").toBool(), M.instantFeedback = o.attr("data-instant-feedback").toBool(), M.serverErrorMessage = o.attr("data-server-error-message"), a = o.find(".form-section"), s = a.find(".form-field"), d = s.find("input, select, textarea"), l = o.find("[data-custom-regex]"), f = o.find(".error-summary"); for (var t = 0; t < a.length; t += 1) c.segs.push(new e); w = {}, w.full = new Function, o.attr("data-id", c.id), n.find(".form-section").each(function (e) { var n = "batch_" + (e + 1); $(this).attr("data-id", n), w[n] = new Function }) }, _status: { get: function (e, n) { return c.segs[e][n] }, set: function (e, n, t) { if ("undefined" != typeof t) return void (c.segs[t][e] = n); for (var i in c.segs) c.segs[i][e] = n }, setSubmitted: function (e, n) { this.set("submit", e, n) }, setValidity: function (e, n) { this.set("valid", e, n) } }, _dom: function () { l.each(function (e) { var n = $(this), t = new RegExp(n.data("custom-regex")), i = (e + 1 + (new Date).getTime()).toString().split("").sort(function () { return .5 - Math.random() }).join(""); c.customRules[i] = t, n.data("custom-regex", i) }), a.each(function () { $(this).attr("data-section-id", arguments[0]) }) } }, k = { complexObject: function (e) { function n(e, t) { for (var i in t) try { t[i].constructor == Object ? e[i] = n(e[i], t[i]) : e[i] = t[i] } catch (r) { e[i] = t[i] } return e } function t(e, n) { for (var t = {}, i = {}, r = 0; r < e.length; r += 1) t[e[r]] = r === e.length - 1 ? n : {}, t = t[e[r]]; return i } var i = {}; for (var r in e) -1 !== r.indexOf(".") ? i = n(i, t(r.split("."), e[r])) : i[r] = e[r]; return i } }, C = function () { function e() { s = !0, setTimeout(function () { s = !1 }, 100) } function n(e) { s || (u = e, h = "blur", c.disabledSegs = 0, B.formSection(e.closest(".form-section"))) } function t(n) { h = "partial", e(), M._status.setSubmitted(!0, n.data("section-id")), c.disabledSegs = 0, B.formSection(n) } function i() { h = "full", _ = 0, c.disabledSegs = a.filter(".disabled").length, M._status.setSubmitted(!0), B._formValid() } var r, s = !1; d.on({ change: function () { n($(this)) }, focus: function () { c.activeSeg = $(this).closest(".form-section").data("section-id"), r = $(this) }, blur: function () { r = void 0 } }), o.find(".partial-submit").on({ click: function (e) { e.preventDefault(), t($(this).closest(".form-section")) }, mousedown: function (e) { e.preventDefault(), "undefined" != typeof r && r.blur(), t($(this).closest(".form-section")) } }), o.find(".full-submit").on({ click: function (e) { e.preventDefault(), i() }, mousedown: function (e) { e.preventDefault(), "undefined" != typeof r && r.blur(), i() }, focus: function (e) { c.activeSeg = "complete" } }), o.find(".form-clear").click(function (e) { e.preventDefault(), j() }), o.keydown(function (e) { var n = $(e.target); if (n.is('a[href="#"]')); else if ("undefined" == typeof r || r.is("textarea")) return; 13 !== e.which || n.hasClass("form-clear") || n.closest(".actions").length || (e.preventDefault(), n.closest(".form-section").find(".full-submit, .partial-submit").click()) }) }, B = { _formValid: function () { o.find(".form-section").each(function () { B.formSection($(this)) }) }, formSection: function (e) { var n; y = e || y, y.hasClass("disabled") ? H(y) : (n = y.data(), V = 0, x = [], v = null, p = n.batchValidation, g = n.sectionId, y.find(".form-field").each(function () { B._formField($(this), n, !1, y.find(".form-field").length) }), null === v && (B.endPointer(), _ += 1)) }, _formField: function (e, n, t, i) { R._run(e, e.parents(".form-section"), i, n) }, endPointer: function () { b ? O._finalFormCheck(y) : O._finalActions() } }, R = { _run: function (e, n, t, i) { var r = V === t - 1, o = e.find("input, select, textarea").is(":disabled"); if (o || (R._rules(e), R._clientResultHandler(m.data, e), m = { data: [] }), V += 1, !o) { if (x.length > 0 || "blur" === h) return void (v = null); if (r && null !== v && n.data("batch-validation") === !0) return R._serverValidate(i.endpoint, v, n), V = 0, void (M.summary && O._summaryErrorMessageHandler()) } }, _rules: function (e) { var n, t, r = "undefined" == typeof e.data("required") ? !0 : e.data("required"), o = ("object" == typeof e.data("validation") ? JSON.stringify(e.data("validation")) : e.data("validation")) || "", a = e.data("type"), s = e.find(".field"); if ("undefined" != typeof a) if (n = i.safe(A.dataValue[a], [s], { msg: "dataType", param: a }), (A.rules.required(n) || r) && "" != o) { t = o.split("|"); for (var d = 0; d < t.length; d += 1) "server" !== t[d] ? m.data.push(i.safe(R._clientValidate, [t[d], n, e], { msg: "ruleConfig", param: t[d] })) : (null === v && (v = {}), v[e.attr("data-field-id")] = n) } else -1 !== o.indexOf("server") && (null === v && (v = {}), v[e.attr("data-field-id")] = n) }, _clientValidate: function (e, n, t) { var i, r = {}, o = t.data(); return "{" === e.charAt(0) && (r = $.parseJSON(e), e = r.rule, r = r.val), o.customRegex && "regex" === e && (r = o.customRegex), !o["for"] || "confirm" !== e && "confirmStrict" !== e && "different" !== e && "differentStrict" !== e || (r.target = y.find("#" + o["for"]).val()), i = A.rules[e](n, r, t), { state: i, rule: e } }, _serverValidate: function (e, n, t) { var o, a = t.attr("data-batch-name"); return "undefined" == typeof a ? (i.log(i.fact.Batchname), void R._serverResultHandler({ Errors: [] }, t)) : (n = k.complexObject(n), o = "undefined" != typeof FormValidation.Manifest.OutBound && "undefined" != typeof FormValidation.Manifest.OutBound[a] ? FormValidation.Manifest.OutBound[a](n) : n, "" === e || "undefined" == typeof e ? (i.log(i.fact.Endpoint), void R._serverResultHandler({ Errors: [] }, t)) : void (F || (F = !0, t.addClass("pending"), $.ajax({ url: e, data: JSON.stringify(o), cache: !1, type: "POST", contentType: "application/json" }).done(function (e) { var n; F = !1, E = e, r && window.console && console.log("server response:", E), t.removeClass("pending"), "undefined" != typeof FormValidation.Manifest.InBound && (n = "undefined" != typeof FormValidation.Manifest.InBound[a] ? FormValidation.Manifest.InBound[a](e) : e, R._serverResultHandler(n, t), v = null) }).fail(function () { F = !1, t.removeClass("pending"), "undefined" == typeof M.serverErrorMessage ? i.handle(i.fact.Server) : R._serverResultHandler({ Errors: [M.serverErrorMessage] }, t) })))) }, _clientResultHandler: function (e, n) { var t = !0, i = 0; if (0 === e.length) return void O._clientErrorMessageHandler(n, !0); this.resultRulesEngine(); do 0 == e[i].state && (x.push(e[i].rule), t = !1), O._clientErrorMessageHandler(n, e[i].state, e[i].rule), i += 1; while (i < e.length && t === !0) }, _serverResultHandler: function (e, n) { var t = n.find(".form-section-errors"); if (this.resultRulesEngine(), t.empty(), e.Errors.length > 0) { for (var i = 0; i < e.Errors.length; i += 1) O._serverErrorMessageHandler(e.Errors[i], t), x.push("server"); b && t.addClass("errors") } else b && t.removeClass("errors"); B.endPointer() }, resultRulesEngine: function () { p && "blur" === h && !c.segs[g].submit ? (r && I("action result factors:", "batch, blur, not submitted"), b = !1) : (r && !p && "blur" === h && c.segs[g].submit && I("action result factors:", "not batch && isBlur, has submitted"), b = !0) } }, O = { _clientErrorMessageHandler: function (e, n, t) { (b || M.instantFeedback === !0 && "blur" === h && u.closest(".form-field")[0] === e[0]) && (e.removeClass("error"), "true" === M.inline && (e.find(".err-msgs").children("div").hide(), n || (e.addClass("error"), "undefined" != typeof t && e.find(".err-msgs").children('div[data-validation="' + t + '"]').show()))) }, _serverErrorMessageHandler: function (e, n) { b && n.append("<div>" + e + "</div>") }, _summaryErrorMessageHandler: function () { }, _finalFormCheck: function (e) { var n = 0 === x.length; M._status.setValidity(n, e.data("section-id")), e.toggleClass("errors", !n), c.form.valid = !0; for (var t = 0; t < c.segs.length; t += 1) if (c.segs[t].valid === !1) { c.form.valid = !1; break } o.toggleClass("errors", !c.form.valid), this._finalActions() }, _finalActions: function () { var e = 0 === x.length, n = "full" === h, t = _ === a.length - 1 - c.disabledSegs; return e || "blur" === h || o.find('input[type="password"], [data-sensitive="true"] input').val(void 0), r && I("section: " + (y.data("section-id") + 1) + ", submit: ", h + ", fails: " + x.length), n && e && t && (x = [], r && I("form passed")), (!n || n && t) && (x = []), n || "blur" === h ? void (n && t && w.full(c.form.valid, o, E)) : void w["batch_" + (g + 1)](e, y, E) } }, H = function (e) { M._status.setValidity(!0, e.data("section-id")), e.removeClass("errors"), O._clientErrorMessageHandler(e.find(".form-field.error"), !0) }, j = function () { M._status.setSubmitted(!1), s.removeClass("error"), a.removeClass("errors valid"), o.removeClass("errors"), O._clientErrorMessageHandler(s, !0), d.val(void 0), d.filter("select").each(function () { var e = !1; $(this).find("option").each(function () { return this.defaultSelected ? (this.selected = !0, e = !0, !1) : void 0 }), e || ($(this)[0].options[0].selected = !0), $(this).change() }) }, A = { dataValue: { hidden: function (e) { return e.find("input").val() }, number: function (e) { return e.find("input").val() }, text: function (e) { return e.find("input").val() }, multiline: function (e) { return e.find("textarea").val() }, email: function (e) { return e.find("input").val() }, radio: function (e) { return e.find('input[type="radio"]:checked').index('input[type="radio"]') + 1 }, select: function (e) { return e.find("select").children("option:selected").data("value") }, selectGroup: function (e) { return e.find("select").find("option:selected").parent().data("group-id") }, checkbox: function (e) { return e.find('input[type="checkbox"]:checked').length }, multi: function (e) { var n = ""; return e.find("input").each(function () { n += $(this).val() }), n } }, dataValueFriendly: { number: function (e) { return e.find("input").val() }, text: function (e) { return e.find("input").val() }, multiline: function (e) { return e.find("textarea").val() }, email: function (e) { return e.find("input").val() }, radio: function (e) { return e.find('input[type="radio"]:checked').length > 0 || "" }, select: function (e) { return e.find("select").children("option:selected").text() }, selectGroup: function (e) { return e.find("select").find("option:selected").val() }, checkbox: function (e) { return e.find('input[type="checkbox"]:checked').length > 0 || "" }, multi: function (e) { var n = ""; return e.find("input").each(function () { n += $(this).val() }), n } }, rules: { number: function (e) { return "string" == typeof e && -1 != e.indexOf(",") && (e = e.replace(",", ".")), !isNaN(parseFloat(e)) && isFinite(e) }, minLength: function (e, n) { return e.length >= n }, maxLength: function (e, n) { return e.length <= n }, min: function (e, n) { return e >= n }, max: function (e, n) { return n >= e }, required: function (e) { return "" != e && -1 != e && null != e }, alpha: function (e) { return /^[a-zA-Z\s]+$/.test(e) }, range: function (e, n) { return e >= n.min && e <= n.max }, email: function (e) { return /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e) }, match: function (e, n) { return e == n }, checked: function (e) { return e > 0 }, unchecked: function (e) { return 0 === e }, confirm: function (e, n) { return e.toLowerCase() == n.target.toLowerCase() }, confirmStrict: function (e, n) { return e == n.target }, different: function (e, n) { return e.toLowerCase() != n.target.toLowerCase() }, differentStrict: function (e, n) { return e != n.target }, regex: function (e, n) { return c.customRules[n].test(e) } } }, I = function () { var e = []; for (var n in arguments) e.push(arguments[n]); window.console && console.log(e.join("")) }; S(), this.id = c.id, this.api = { events: w, validateBatch: function (e) { return h = "partial", B.formSection(e) }, validateForm: function () { return h = "submit", B._formValid() }, clearForm: j, clearSeg: H, debug: function (e) { "boolean" == typeof e && (r = e) } } }, t = function (e) { var t = {}; $(".mod-form").each(function (e) { var i = new n($(this), e += 1); t[i.id] = i.api }), window.FormValidation.Application.prototype.api = t }, i = { fact: { bootDependency: "FormValidation requires boot.js version 3.0.0 +", dataType: "data type does not exist for field", ruleConfig: "Validation rule configuration contains errors for field", Server: "Service error", Endpoint: "Invalid endpoint", Batchname: "Invalid batch-name", ruleExtension: "Invalid rule extension configuration in ", loadRuleExtensionFile: "FormValidation requires to load rules extension file", outBound: "OutBound Object Literal has property missing for batch name", inBound: "InBound Object Literal has property missing for batch name" }, safe: function (e, n, t) { try { return e.apply(this, n) } catch (i) { this.handle(this.fact[t.msg] + ": '" + (t.param || "") + "'") } }, log: function (e) { window.console && console.info(e) }, handle: function (e) { throw new Error(e) } }; this.init = function () { var e; return window.boot || window.toolkit.boot ? (e = window.boot || window.toolkit.boot, e.config.FormValidation = FormValidation.Manifest.ExtensionPath, window.FormValidation.Manifest.OutBound === !0 && e.loadScript("extensions-outbound.js", "FormValidation"), window.FormValidation.Manifest.InBound === !0 && e.loadScript("extensions-inbound.js", "FormValidation"), void t(this)) : void i.handle(i.fact.bootDependency) } }, window.FormValidation.Manifest = function (e) { function n() { this.manifest = [], this.register = function (e, n) { this.manifest.push({ className: e, filename: n }) } } return window.formValidation = window.formValidation || new window.FormValidation.Application, e.init = window.formValidation.init, { Externals: new n, ExtensionPath: "", OutBound: !1, InBound: !1 } }(window.FormValidation);
///#source 1 1 /Assets/scripts/libs/codehouse-js/responsive.min.js
/* 
 * ---------------------------------------- *
 * Name: 	Codehouse Responsive            *
 * Type: 	JavaScript Class                *
 * Version: 2.0.0                           *
 * Author:	Matt O'Neill                    *
 * Status:	Development                     *
 * ---------------------------------------- *
 */

window.Responsive || (window.Responsive = {}), window.Responsive = function e() { "use strict"; function n() { var e = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, n = [], i = [], t = this; t.mode = 0; var r = function (e) { for (var n = 0; n < e.methods.length; n++) "function" == typeof e.methods[n] && e.methods[n].call(this, e.event) }, o = function (o) { e = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var a = 0; for (var s in i) { if (s >= e || a === i.length - 1) { "undefined" != typeof i[s] && (n[s] || r({ methods: i[s], event: o }), c(s)), t.mode = s; break } a++ } }, a = function () { function e() { o("resize") } var n; window.onresize = function (i) { o("resize"), clearTimeout(n), n = setTimeout(function () { e() }, 100) } }, c = function (e) { for (var i in n) n[i] = !1; n[e] = !0 }, s = function () { function e(e) { for (var n = 0; n < e.length; n++) i[r].push(e[n]) } var t = arguments[0]; for (var r in t) { var o = t[r]; "function" == typeof o && (o = [o]), "undefined" != typeof i[r] ? e(o) : (i[r] = o, n.push(r)) } }; return a(), { register: s, trigger: a } } function i() { var e = [], n = "undefined" != typeof window.document.createElement("div").style.objectFit, i = { container: function () { for (var e, n = this.parentNode; 9 !== n.nodeType;) { if ((" " + n.className + " ").indexOf(" image-fit-container ") > -1) { e = n; break } n = n.parentNode } return e }, objectFit: !0, useMargins: !1, resize: !0, checkOnResize: !1, onPreLoad: function () { }, onCheck: function () { }, onSet: function () { } }, t = { handleElems: function (e) { var n = []; if ("undefined" != typeof e && null !== e) if ("undefined" == typeof e.length) n.push(e); else if (e.length) for (var i = 0; i < e.length; i += 1) n.push(e[i]); return n }, checkCallback: function (e, n) { "function" == typeof e && e.call(n) }, merge: function () { for (var e, n = {}, i = 0; i < arguments.length; i += 1) { e = arguments[i]; for (var t in e) e.hasOwnProperty(t) && (n[t] = e[t]) } return n }, addClass: function (e, n) { var i = " " + e.className + " ", t = n.split(" "), r = "", o = 0; for (o; o < t.length; o += 1) -1 === i.indexOf(" " + t[o] + " ") && "" !== t[o] && (r += " " + t[o]); e.className += r }, removeClass: function (e, n) { var i = " " + e.className + " ", t = n.split(" "), r = 0; for (r; r < t.length; r += 1) i = i.replace(" " + t[r] + " ", " "); e.className = i.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "") } }, r = { resize: { timer: void 0, bind: function (n, i) { n.resize && i && e.push(n) }, check: function (e) { e.checkOnResize ? r.run(e, !1) : r.checkAndSet(e) }, run: function () { e.length && (r.resize.timer && clearTimeout(r.resize.timer), r.resize.timer = setTimeout(function () { var n = 0; for (n; n < e.length; n += 1) r.resize.check(e[n]) }, 100)) } }, checkAndSet: function (e) { t.removeClass(e.img, "fitted-tall fitted-wide"), t.checkCallback(e.onCheck, e.img); var n = e.img.clientHeight / e.img.clientWidth * 100, i = e.container.clientHeight / e.container.clientWidth * 100, r = i > n ? "fitted-tall" : "fitted-wide"; t.addClass(e.img, "fitted " + r), e.useMargins && (t.addClass(e.img, "fitted-margins"), "fitted-tall" === r ? (e.img.style.marginLeft = -(e.img.clientWidth / 2) + "px", e.img.style.marginTop = "") : (e.img.style.marginLeft = "", e.img.style.marginTop = -(e.img.clientHeight / 2) + "px")), t.checkCallback(e.onSet, e.img) }, run: function (e, i) { var o = new Image; return t.checkCallback(e.onPreLoad, e.img), e.objectFit && n ? (t.addClass(e.img, "fitted fitted-object-fit"), void (e.checkOnResize && r.resize.bind(e, i))) : (o.onload = function () { r.checkAndSet(e), r.resize.bind(e, i) }, o.onerror = function () { t.addClass(e.img, "fitted-error") }, void (o.src = e.img.currentSrc || e.img.src)) }, prep: function (e) { "function" == typeof e.container && (e.container = e.container.call(e.img)), e.container = t.handleElems(e.container), e.container.length && (e.container = e.container[0], e.img.imageFitData = e, r.run(e, !0)) }, init: function (e, n) { var o = "string" == typeof n && "update" === n; e = t.handleElems(e); for (var a = 0; a < e.length; a += 1) o && "undefined" != typeof e[a].imageFitData ? r.run(e[a].imageFitData, !1) : r.prep(t.merge(i, n, { img: e[a] })) } }; return "undefined" != typeof window.addEventListener ? window.addEventListener("resize", r.resize.run) : window.attachEvent("onresize", r.resize.run), "undefined" != typeof $ && null !== $ && ($.fn.fluidImages = function (e) { return r.init(this, e), this }), this.init = r.init, this } var t = new n, r = new i; return e.prototype.api = { register: t.register, trigger: t.trigger, enableFluidImages: r.init }, this };
///#source 1 1 /Assets/scripts/libs/codehouse-js/serialise.min.js
/* Serialise 2.2.4 */
!function(e){window.serialise||(window.serialise={}),window.serialise=new function(){var n=function(){},t=function(e){var n=[];for(var t in e)e.hasOwnProperty(t)&&n.push(encodeURIComponent(t)+"="+encodeURIComponent(e[t]));return n.join("&")},r=function(e){for(var n={},t=-1!=e.indexOf("#")?e.split("#")[1].split("&"):e.split("?")[1].split("&"),r=0;r<t.length;r+=1){var a=t[r].split("=");n[decodeURIComponent(a[0])]=decodeURIComponent(a[1])}return n},a=function(e){function n(e,t){for(var r in t)try{t[r].constructor==Object?e[r]=n(e[r],t[r]):e[r]=t[r]}catch(a){e[r]=t[r]}return e}function t(e,n){for(var t,r=t={},a=0;a<e.length;a+=1)t=t[e[a]]=a===e.length-1?n:{};return r}var r={};for(var a in e)if(-1!==a.indexOf(".")){var i=a.split("."),o=t(i,e[a]);r=n(r,o)}else r[a]=e[a];return r};if("undefined"!=typeof jQuery)var i=function(){var e={},n=arguments[0].serializeArray();for(var t in n)void 0!==e[n[t].name]?(e[n[t].name].push||(e[n[t].name]=[e[n[t].name]]),e[n[t].name].push(n[t].value||"")):e[n[t].name]=n[t].value||"";return e},o=function(n,t){function r(n){return e.map(n.split("-"),function(e,n){return(n?e.charAt(0).toUpperCase():e.charAt(0))+e.slice(1).toLowerCase()}).join("")}function a(e,n){return""!==e&&void 0!==e&&null!==e||!n||(e=n),e}var i=this,o=r(t);return n.find("[data-"+t+"]").each(function(){var n=e(this),t=n.data();n.is("select")&&1==t.rawValue?i[t[o]]=n.children("option:selected").text():n.is(":checkbox")?i[t[o]]=n.is(":checked"):i[t[o]]=a(n.val(),n.data().sentinel),"number"===t.format&&(i[t[o]]=parseFloat(i[t[o]].replace(/,/g,"")))}),n.find("[data-"+t+"-group]").each(function(){var n=e(this),a=n.data(),o=[];n.children().each(function(){var t=e(this).find('input[type="checkbox"]:checked, input[type="radio"]:checked'),r=a.rawValue?t.attr("data-id"):t.attr("name");""!==r&&void 0!==r&&(t.is('input[type="radio"]')&&n.data("single-value")===!0?o=r:o.push(r))}),o.length>0&&(i[a[r(t+"-group")]]=o)}),i},u=function(e,n){var t={},r=new o(e,n);for(var i in r)t[i]=r[i];return t=a(t)};return"undefined"!=typeof jQuery&&(n.prototype.jQueryObj=i,n.prototype.jQueryData=u),n.prototype.obj=t,n.prototype.url=r,n.prototype.complex=a,new n}}(jQuery);
///#source 1 1 /Assets/scripts/libs/codehouse-js/stylish-forms.min.js
/* Stylish Forms 3.1.4 */
!function (e) { window.stylishForms || (window.stylishForms = {}), window.stylishForms = new function () { var t = !1, s = function (s) { var i = function () { s.find('input[type="text"], input[type="number"], input[type="password"], input[type="email"], input[type="tel"], textarea').each(function () { e(this).attr("tabindex", 0).wrap('<div class="stylish-' + this.type + '" data-type="' + this.type + '" tabindex="-1" />').before("<span></span>"), p.setFocusClass(e(this)), p.disableField(e(this)) }), s.find("input.date").each(function () { e(this).parent().addClass("multidate").children("span").addClass("date"), p.setFocusClass(e(this)) }) }, o = function () { s.find("select").each(function () { e(this).wrap('<div class="stylish-select" data-type="' + this.type + '" tabindex="-1" />').css({ opacity: 0, position: "absolute", left: "-9999px" }).after('<span class="selected"><span class="text">' + e(this).find("option:selected").text() + '</span><span class="ico"></span></span><div class="dropdown-list" role="listbox"><div></div></div>'), n(e(this)), p.setFocusClass(e(this)), p.disableField(e(this)) }) }, n = function (t) { var s, i = 0, o = ""; return t.children().each(function () { e(this).is("optgroup") ? (o += '<div class="dropdown-option group">', o += "<span>" + e(this).attr("label") + "</span>", o += "<ul>", e(this).children().each(function () { e(this).data("index", i), o += '<li class="dropdown-option" role="option" data-index="' + i + '" ' + (e(this).is(":disabled") ? 'class="disabled"' : "") + (e(this).is(":selected") ? " option-selected" : "") + ">" + e(this).text() + "</li>", i += 1 }), o += "</ul>", o += "</div>") : (e(this).data("index", i), o += '<div class="dropdown-option' + (e(this).is(":disabled") ? " disabled" : "") + (e(this).is(":selected") ? " option-selected" : "") + '" role="option" data-index="' + i + '">' + e(this).text() + "</div>", i += 1) }), s = t.closest(".stylish-select").find(".dropdown-list > div"), s.append(o), s.find(".dropdown-option").add(s.find(".dropdown-option")).not(".disabled, .group").attr("tabindex", 0), o }, a = function () { s.find('.dropdown-list[data-stylish-group="checkbox-dropdown"]').each(function () { e(this).wrap('<div class="stylish-select checkbox-dropdown" data-type="' + this.type + '" tabindex="-1" />').before('<span class="selected"></span>'), d(e(this)), p.setFocusClass(e(this)) }) }, d = function (e) { e.siblings(".selected").html('<span class="text">' + e.data("default-option-text") + '</span><span class="ico"></span>'), e.find(".dropdown-option").attr("tabindex", 0) }, l = function () { s.find('input[type="checkbox"], input[type="radio"]').each(function () { p.dualStatesHelper(e(this), e(this).attr("type")), p.setFocusClass(e(this)) }) }, c = function () { s.find('[data-type="range"]').each(function () { var t = e(this), s = t.data(), i = s.updateValue, o = s.inputfor, n = t.parent().find('[data-input-from="' + o + '"]'), a = t.parent().find('[data-input-to="' + o + '"]'), d = [n.val(), a.val()].filter(function (e) { return void 0 !== e }); t.slider({ range: d.length > 1, values: d, step: s.precision, min: s.min, max: s.max, slide: function (e, t) { var s = t.values[0], o = t.values[1]; i && (n && n.val(s), a && a.val(o)) }, start: p.hideDropdowns }) }) }, p = { checkboxDdSelected: function (t) { var s = t.find('input[type="checkbox"]:checked, input[type="radio"]:checked'), i = t.find(".selected > span.text"), o = [], n = ""; 0 === s.length ? i.html(t.find(".dropdown-list").data("default-option-text")) : (s.each(function () { o.push(e('label[for="' + e(this).attr("id") + '"]').text()) }), n = o.join(", "), i.html(n), i.attr("title", n)) }, setDropdownHeight: function (t) { var s = t.offset(), i = e(window).scrollTop(), o = s.top + t.outerHeight(), n = e(window).height() + i, a = s.top - i, d = n - s.top; o > n ? a > d ? (t.css("max-height", .8 * a), t.addClass("show-above")) : (t.css("max-height", .8 * (n - s.top)), t.removeClass("show-above")) : (t.removeClass("show-above"), t.css("max-height", "")) }, hideDropdowns: function (t) { 0 === e(t.target).closest(".stylish-select").length && e("[data-stylish-form]").find(".stylish-select").removeClass("active").find(".dropdown-list").hide().css("max-height", "").removeClass("show-above") }, setFocusClass: function (e) { e.on({ focus: function () { e.parent().addClass("focus") }, blur: function () { e.parent().removeClass("focus") } }) }, returnDefaultSelected: function (e) { var t = e.find("option").filter(function () { return this.defaultSelected }), s = e.closest(".stylish-select").find(".dropdown-list .dropdown-option"); return 0 === t.length ? (s.eq(0).addClass("option-selected"), s.eq(0)) : (s.eq(t.index()).addClass("option-selected"), t) }, returnDefaultChecked: function (e) { var t = e.closest(".stylish-form").find('input:radio[name="' + e.attr("name") + '"]').filter(function () { return this.defaultChecked }); t.prop("checked", !0).siblings("span").addClass("checked") }, disableField: function (e) { e.parent().toggleClass("disabled", e.is(":disabled")) }, checkField: function (t) { "radio" === t.attr("type") && (t.closest(".stylish-form").find("input:radio").not(":checked").each(function () { e(this).attr("name") === t.attr("name") && e(this).siblings("span").removeClass("checked") }), e('input:radio[name="' + t.attr("name") + '"]:checked').val() || p.returnDefaultChecked(t)), t.siblings("span").toggleClass("checked", t.is(":checked")) }, dualStatesHelper: function (e, t) { e.wrap('<div class="stylish-ds" data-type="' + t + '" />').css({ opacity: 0, position: "absolute" }).before('<span class="' + (e.is(":checked") ? "checked" : "") + '"><span class="ico"></span></span>') }, updateCheckboxSelected: function (e) { e.closest(".stylish-select.checkbox-dropdown").length && (p.checkboxDdSelected(e.closest(".stylish-select.checkbox-dropdown")), e.closest("li").toggleClass("checked")) } }, r = function () { var i, o = "", n = !1; s.on("change", '.stylish-ds input[type="checkbox"]', function () { e(this).siblings("span").toggleClass("checked"), p.updateCheckboxSelected(e(this)) }), s.on("change", ".stylish-ds input[type=radio]", function () { s.find('input[type="radio"][name="' + e(this).attr("name") + '"]').each(function () { e(this).siblings("span").removeClass("checked") }), e(this).siblings("span").addClass("checked") }), s.on("click", ".stylish-select > .selected", function (t) { var s = e(this).closest(".stylish-select").find(".dropdown-list"), i = e(this).closest(".stylish-select").siblings("select"); t.stopPropagation(), i.is(":disabled") || (e(".stylish-select .dropdown-list").not(s).hide().closest(".stylish-select").removeClass("active"), s.toggle(), s.is(":visible") ? (s.closest(".stylish-select").addClass("active"), p.setDropdownHeight(s)) : s.closest(".stylish-select").removeClass("active"), 0 === s.find(".option-selected").length && p.returnDefaultSelected(i)) }), s.on("mouseover", ".stylish-select:not(.checkbox-dropdown) .dropdown-option", function (t) { e(this).not(".disabled").addClass("option-selected").siblings(".option-selected").removeClass("option-selected") }), s.on("click", ".stylish-select:not(.checkbox-dropdown) .dropdown-option", function (t) { var s = e(this); t.stopPropagation(), s.is(":not(.group, .disabled)") && (s.closest(".stylish-select").find(".dropdown-list").hide(), s.closest(".stylish-select").find("select").prop("selectedIndex", s.data("index")).change()) }), s.on("change", ".stylish-select select", function () { var t = e(this), s = t.find("option:selected"), i = t.closest(".stylish-select").find(".dropdown-list"); t.parent().find("span.selected > span.text").html(s.text()), i.find(".dropdown-option[data-index]").removeClass("option-selected").eq(t.prop("selectedIndex")).addClass("option-selected") }), s.on("keypress, keyup, keydown", ".stylish-select select", function (t) { var s = e(this), i = s.closest(".stylish-select"), o = i.find(".dropdown-list"); switch (t.which) { case 13: case 32: t.preventDefault(), t.stopPropagation(), i.hasClass("active") ? p.hideDropdowns(s) : (i.addClass("active"), o.show(), p.setDropdownHeight(o)), s.blur(), i.focus(), s.trigger("change"); break; case 27: case 9: s.trigger("change"), p.hideDropdowns(s); break; case 38: case 40: s.trigger("change") } }), s.on("keypress, keyup, keydown", ".stylish-select.active", function (t) { function s(t) { return o === e(this).text().trim().substring(0, o.length).toLowerCase() ? (r.removeClass("option-selected"), e(this).addClass("option-selected"), h = !0, !1) : void 0 } var a = e(this), d = a.find("select"), l = a.find(".dropdown-list"), c = l.find(".dropdown-option:not(.disabled)"), r = c.filter(".option-selected"), h = !1; switch (t.which) { case 13: case 32: case 27: case 9: t.preventDefault(), d.find("option").eq(r.data("index")).prop("selected", !0), d.focus(), a.blur().removeClass("active"), d.trigger("change"), p.hideDropdowns(d); break; case 38: t.preventDefault(), r.length ? r.index() && (r.removeClass("option-selected").prevAll(".dropdown-option:not(.disabled)").first().addClass("option-selected"), l.scrollTop(c.filter(".option-selected").position().top)) : c.last().addClass("option-selected"); break; case 40: t.preventDefault(), r.length ? r.index() + 1 < c.length && (r.removeClass("option-selected").nextAll(".dropdown-option:not(.disabled)").first().addClass("option-selected"), l.scrollTop(c.filter(".option-selected").position().top)) : c.first().addClass("option-selected"); break; default: (t.which >= 48 && t.which <= 57 || t.which >= 65 && t.which <= 90) && r.length && (n ? (clearTimeout(i), o += String.fromCharCode(t.which).toLowerCase()) : o = String.fromCharCode(t.which).toLowerCase(), n = !0, i = setTimeout(function () { n = !1 }, 1e3), c.slice(r.index() + 1).each(s), h || c.slice(0, r.index()).each(s), l.scrollTop(c.filter(".option-selected").position().top)) } }), t === !1 && (e(document).on("click touchend", p.hideDropdowns), t = !0) }; s.off(), void function () { s.addClass("stylish-form").attr("data-stylish-form", "set"), i(), o(), l(), a(), jQuery.ui && c(), r() }() }; this.apply = function () { e('[data-stylish-form="true"]').each(function () { s(e(this)) }) }, this.update = function () { this.apply() }, this.refresh = function (e) { _refresh(e) } } }(jQuery);
///#source 1 1 /Assets/scripts/libs/codehouse-js/touch.min.js
/*
 * ---------------------------------------- *
 * Name:    Codehouse Touch                 *
 * Version: 1.1.0                           *
 * Author:  Leon Slater | Matt O'Neill      *
 * Status:  Release                         *
 * ---------------------------------------- *
 */

window.touch || (window.touch = {}); var chTouch = function (e, t) { var n = { threshold: 20, swipeDirection: "horizontal", start: function () { }, beforeEnd: function () { }, right: function () { }, left: function () { }, up: function () { }, down: function () { }, moving: function () { }, reached: function () { }, notReached: function () { }, end: function () { }, reset: function () { } }, o = document.documentElement, i = 0; this.browserTouchSupport = "ontouchstart" in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; var r = window.navigator.pointerEnabled, c = window.navigator.msPointerEnabled, a = this.browserTouchSupport ? r || c : !1, u = { start: { IEedge: "pointerdown", IE10: "MSPointerDown", webkit: "touchstart" }, move: { IEedge: "pointermove", IE10: "MSPointerMove", webkit: "touchmove" }, end: { IEedge: "pointerup", IE10: "MSPointerUp", webkit: "touchend" }, cancel: { IEedge: "pointercancel", IE10: "MSPointerCancel", webkit: "touchcancel" } }, d = a ? r ? "IEedge" : "IE10" : "webkit", h = u.cancel[d], s = u.start[d], l = u.move[d], v = u.end[d]; this.touchDevice = !("undefined" == typeof o.ontouchstart) || a || !1; var f = function (e, t) { function r() { return { horizontal: I.x > n.threshold ? "right" : I.x < -n.threshold ? "left" : "notReached", vertical: I.y > n.threshold ? "down" : I.y < -n.threshold ? "up" : "notReached", all: null }[n.swipeDirection] } function c(e) { var t = !0; if ("function" == typeof e) { if (L) return; t = e(I), t === !1 && u() } } function u() { i--, m = 0, y = 0, b = g, T = -1, x = !1, I.x = 0, I.y = 0, a ? (o.removeEventListener(l, w), o.removeEventListener(v, p)) : (e.removeEventListener(l, w), e.removeEventListener(v, p)), 0 === i && e !== o && (o.style.msTouchAction = "", o.style.touchAction = ""), c(n.reset, "reset"), L = !0 } function d(e, t) { var n = a ? "touch" === e.pointerType || 2 === e.pointerType : !0; if (n) switch (t) { case "start": n = -1 === T; break; case "move": n = a ? T === e.pointerId : T === e.targetTouches[0].identifier; break; case "end": n = a ? T === e.pointerId : T === e.changedTouches[0].identifier } return n } function f(t) { if (d(t, "start")) { var r = a ? t : t.targetTouches[0]; L = !1, m = r.clientX, y = r.clientY, a ? (o.addEventListener(l, w), o.addEventListener(v, p)) : (e.addEventListener(l, w), e.addEventListener(v, p)), T = a ? r.pointerId : r.identifier, 0 === i && e !== o && (o.style.msTouchAction = "none", o.style.touchAction = "none"), i++, c(n.start, "start") } } function w(e) { if (d(e, "move")) { var t = a ? e : e.targetTouches[0], o = Math.abs; I.x = t.clientX - m, I.y = t.clientY - y, (o(I.x) > n.threshold || o(I.y) > n.threshold) && (x || (x = !0, c(n.reached, "reached"))), b && (b = { horizontal: o(I.y) > o(I.x), vertical: o(I.y) < o(I.x), all: !1 }[n.swipeDirection]), b ? u() : (e.preventDefault(), c(n.moving, "moving")) } } function p(e) { if (d(e, "end")) { if (!b) { var t = r(); c(n.beforeEnd, "beforeEnd"), c(n[t], t), c(n.end, "end") } u() } } for (var E in t) n.hasOwnProperty(E) && (n[E] = t[E]); var m = 0, y = 0, g = "all" !== n.swipeDirection, b = g, T = -1, I = { el: e, x: 0, y: 0 }, x = !1, L = !1, D = { horizontal: "pan-y", vertical: "pan-x", all: "none" }[n.swipeDirection]; e.style.msTouchAction = D, e.style.touchAction = D, e.addEventListener && (e.addEventListener(s, f), e.addEventListener(h, u)) }; this.bind = function (e) { if (e.length) for (var t = 0; t < e.length; t++) f(e[t], arguments[1]); else f(e, arguments[1]) }, void 0 !== e && this.bind(e, t) }; window.touch = new chTouch, window.jQuery && (jQuery.fn.touch = function (e) { var t = new chTouch; return t.bind(jQuery(this), e) });

///#source 1 1 /Assets/scripts/libs/codehouse-js/toolkit.min.js
/*! toolkit 1.3.0 */
"use strict"; window.toolkit || (window.toolkit = {}), window.toolkit.boot || (window.toolkit.boot = {}), window.toolkit.boot = new function () { return this.config = {}, this.config.global = "/Assets/scripts/libs/", this.config.local = "/Assets/scripts/libs/mod-js/", this.config.cdn = "", this.loadScript = function (a, b, c) { var d = navigator.appVersion.indexOf("MSIE 10") != -1, e = document.createElement("script"), f = b ? this.config[b] : this.config.local; e.type = "text/javascript", e.src = f + a, document.body.appendChild(e), c && (e.addEventListener && !d ? c && e.addEventListener("load", function (a) { c() }, !1) : e.attachEvent && e.attachEvent("onreadystatechange", function () { e.onload = e.onreadystatechange = null, "loaded" !== e.readyState && "complete" !== e.readyState || c() })) }, this }, window.toolkit.cache || (window.toolkit.cache = {}), "undefined" != typeof jQuery && jQuery(document).ready(function () { window.toolkit.cache = new function () { var a = { $window: jQuery(window), $document: jQuery(document), $html: jQuery("html"), $body: jQuery("body") }; return a } }), window.toolkit.client || (window.toolkit.client = {}), window.toolkit.client = new function () { var a = navigator.userAgent.toLowerCase(), b = document.createElement("div"), c = { iPad: "ipad", iPhone: "iphone", iOS: "iphone|ipad|ipod", Mac: "intel mac", Chrome: "chrome", Firefox: "firefox", IE: "msie|rv:11", IE7: "msie 7.0", IE8: "msie 8.0", IE9: "msie 9.0", IE10: "msie 10.0", IE11: "rv:11.0", OldIE: "msie 7.0|msie 8.0", Opera: "opera|opr", Android: "android", Mobile: "android|webos|iphone|ipad|ipod|blackberry|windows phone|iemobile", WindowsPhone: "windows phone" }, d = ["WebkitPerspective", "MozPerspective", "OPerspective", "msPerspective"], e = function () { function e(a, b) { var c = b.charAt(0).toUpperCase(); return a["webkit" + c] || a[b] || a["moz" + c] || a["ms" + c] || function (a) { setTimeout(a, 60) } } var f = {}, g = "", h = document.getElementsByTagName("html")[0]; for (var i in c) { var j = new RegExp(c[i], ["i"]); f[i] = j.test(a) } for (var k in d) if (void 0 !== b.style[d[k]]) { f.Perspective = d[k], f.CSSVendorPrefix = "-" + d[k].replace("Perspective", "").toLowerCase() + "-"; break } f.Safari = !(a.indexOf("chrome") > -1) && a.indexOf("safari") > -1, f.HighDef = window.devicePixelRatio > 1, f.RequestAnimationId = e(window, "requestAnimationFrame"), f.CancelAnimationId = e(window, "cancelAnimationFrame"), f.iOSVersion = f.iOS ? parseFloat(a.split(" os ")[1].split(" ")[0].replace("_", ".")) : void 0; for (var l in f) f[l] && (g += " " + l.toLowerCase()); return f.dir = h.getAttribute("dir"), f.lang = h.getAttribute("lang"), f.domApply = function () { document.documentElement.className += g }, f }; return new e }, window.toolkit.config || (window.toolkit.config = {}), window.toolkit.config = new function () { var a = { breakpoint: { MOBILE: 768, TABLET: 1200 } }; return a }, window.toolkit.cookie || (window.toolkit.cookie = {}), window.toolkit.cookie = new function a() { this.read = function () { var b, c = []; if (!document.cookie) return !1; b = document.cookie.split(/; */); for (var d = 0; d < b.length; d += 1) { var e = b[d].split("="), f = new a(e[0], e[1]); c.push(f) } return c }, this.write = function (a, b, c) { if (void 0 != c) { var d = new Date; d.setDate(d.getDate() + c), d.toUTCString() } document.cookie = void 0 !== c ? a + "=" + b + "; expires=" + d + ";path=/" : a + "=" + b + ";path=/" }, this.check = function (a) { var b = this.read(); for (var c in b) if (b[c].name === a) return b[c].value }, this.erase = function (a) { if (void 0 !== a) this.write(a, "", -1); else { var b = this.read(); for (var c in b) this.write(b[c].name, "", -1) } }; var a = function (a, b) { this.name = a, this.value = b } }, window.toolkit.equalHeight || (window.toolkit.equalHeight = {}), window.toolkit.equalHeight = function () { for (var a = this.children, b = [], c = 0; c < a.length; c += 1) a[c].style.height = ""; if (a.length > 1) { for (var c = 0; c < a.length; c += 1) b.push(a[c].clientHeight); for (var c = 0; c < a.length; c += 1) a[c].style.height = Math.max.apply(Math, b) + "px" } }, window.toolkit.resizeTimer || (window.toolkit.resizeTimer = []), function () { var a, b = function () { clearTimeout(a), a = setTimeout(function () { for (var a = 0; a < window.toolkit.resizeTimer.length; a += 1) window.toolkit.resizeTimer[a]() }, 100) }; "undefined" != typeof window.addEventListener ? window.addEventListener("resize", b, !0) : "undefined" != typeof window.attachEvent ? window.attachEvent("onresize", b) : window.onresize = b }(), window.toolkit.scrollTimer || (window.toolkit.scrollTimer = []), function () { var a, b = function () { clearTimeout(a), a = setTimeout(function () { for (var a = 0; a < window.toolkit.scrollTimer.length; a += 1) window.toolkit.scrollTimer[a]() }, 100) }; "undefined" != typeof window.addEventListener ? window.addEventListener("scroll", b, !0) : "undefined" != typeof window.attachEvent ? window.attachEvent("onscroll", b) : window.onscroll = b }(), window.toolkit.serialise || (window.toolkit.serialise = {}), window.toolkit.serialise = new function () { var a = function () { }, b = function (a) { var b = []; for (var c in a) a.hasOwnProperty(c) && b.push(encodeURIComponent(c) + "=" + encodeURIComponent(a[c])); return b.join("&") }, c = function (a) { for (var b = {}, c = a.indexOf("#") != -1 ? a.split("#")[1].split("&") : a.split("?")[1].split("&"), d = 0; d < c.length; d += 1) { var e = c[d].split("="); b[decodeURIComponent(e[0])] = decodeURIComponent(e[1]) } return b }, d = function (a) { function b(a, c) { for (var d in c) try { c[d].constructor == Object ? a[d] = b(a[d], c[d]) : a[d] = c[d] } catch (b) { a[d] = c[d] } return a } function c(a, b) { for (var c, d = c = {}, e = 0; e < a.length; e += 1) c = c[a[e]] = e === a.length - 1 ? b : {}; return d } var d = {}; for (var e in a) if (e.indexOf(".") !== -1) { var f = e.split("."), g = c(f, a[e]); d = b(d, g) } else d[e] = a[e]; return d }; if ("undefined" != typeof jQuery) var e = function () { var a = {}, b = arguments[0].serializeArray(); for (var c in b) void 0 !== a[b[c].name] ? (a[b[c].name].push || (a[b[c].name] = [a[b[c].name]]), a[b[c].name].push(b[c].value || "")) : a[b[c].name] = b[c].value || ""; return a }, f = function (a, b) { function c(a) { return jQuery.map(a.split("-"), function (a, b) { return (b ? a.charAt(0).toUpperCase() : a.charAt(0)) + a.slice(1).toLowerCase() }).join("") } function d(a, b) { return "" !== a && void 0 !== a && null !== a || !b || (a = b), a } var e = this, f = c(b); return a.find("[data-" + b + "]").each(function () { var a = $(this), b = a.data(); a.is("select") && 1 == b.rawValue ? e[b[f]] = a.children("option:selected").text() : a.is(":checkbox") ? e[b[f]] = a.is(":checked") : e[b[f]] = d(a.val(), a.data().sentinel), "number" === b.format && (e[b[f]] = parseFloat(e[b[f]].replace(/,/g, ""))) }), a.find("[data-" + b + "-group]").each(function () { var a = jQuery(this), d = a.data(), f = []; a.children().each(function () { var b = jQuery(this).find('input[type="checkbox"]:checked, input[type="radio"]:checked'), c = d.rawValue ? b.attr("data-id") : b.attr("name"); "" !== c && void 0 !== c && (b.is('input[type="radio"]') && a.data("single-value") === !0 ? f = c : f.push(c)) }), f.length > 0 && (e[d[c(b + "-group")]] = f) }), e }, g = function (a, b) { var c = {}, e = new f(a, b); for (var g in e) c[g] = e[g]; return c = d(c) }; return "undefined" != typeof jQuery && (a.prototype.jQueryObj = e, a.prototype.jQueryData = g), a.prototype.obj = b, a.prototype.url = c, a.prototype.complex = d, new a };
///#source 1 1 /Assets/scripts/initJquery.js
var jQ = jQuery;
///#source 1 1 /Assets/scripts/libs/mustache.min.js
(function defineMustache(global,factory){if(typeof exports==="object"&&exports&&typeof exports.nodeName!=="string"){factory(exports)}else if(typeof define==="function"&&define.amd){define(["exports"],factory)}else{global.Mustache={};factory(global.Mustache)}})(this,function mustacheFactory(mustache){var objectToString=Object.prototype.toString;var isArray=Array.isArray||function isArrayPolyfill(object){return objectToString.call(object)==="[object Array]"};function isFunction(object){return typeof object==="function"}function typeStr(obj){return isArray(obj)?"array":typeof obj}function escapeRegExp(string){return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function hasProperty(obj,propName){return obj!=null&&typeof obj==="object"&&propName in obj}var regExpTest=RegExp.prototype.test;function testRegExp(re,string){return regExpTest.call(re,string)}var nonSpaceRe=/\S/;function isWhitespace(string){return!testRegExp(nonSpaceRe,string)}var entityMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function escapeHtml(string){return String(string).replace(/[&<>"'`=\/]/g,function fromEntityMap(s){return entityMap[s]})}var whiteRe=/\s*/;var spaceRe=/\s+/;var equalsRe=/\s*=/;var curlyRe=/\s*\}/;var tagRe=/#|\^|\/|>|\{|&|=|!/;function parseTemplate(template,tags){if(!template)return[];var sections=[];var tokens=[];var spaces=[];var hasTag=false;var nonSpace=false;function stripSpace(){if(hasTag&&!nonSpace){while(spaces.length)delete tokens[spaces.pop()]}else{spaces=[]}hasTag=false;nonSpace=false}var openingTagRe,closingTagRe,closingCurlyRe;function compileTags(tagsToCompile){if(typeof tagsToCompile==="string")tagsToCompile=tagsToCompile.split(spaceRe,2);if(!isArray(tagsToCompile)||tagsToCompile.length!==2)throw new Error("Invalid tags: "+tagsToCompile);openingTagRe=new RegExp(escapeRegExp(tagsToCompile[0])+"\\s*");closingTagRe=new RegExp("\\s*"+escapeRegExp(tagsToCompile[1]));closingCurlyRe=new RegExp("\\s*"+escapeRegExp("}"+tagsToCompile[1]))}compileTags(tags||mustache.tags);var scanner=new Scanner(template);var start,type,value,chr,token,openSection;while(!scanner.eos()){start=scanner.pos;value=scanner.scanUntil(openingTagRe);if(value){for(var i=0,valueLength=value.length;i<valueLength;++i){chr=value.charAt(i);if(isWhitespace(chr)){spaces.push(tokens.length)}else{nonSpace=true}tokens.push(["text",chr,start,start+1]);start+=1;if(chr==="\n")stripSpace()}}if(!scanner.scan(openingTagRe))break;hasTag=true;type=scanner.scan(tagRe)||"name";scanner.scan(whiteRe);if(type==="="){value=scanner.scanUntil(equalsRe);scanner.scan(equalsRe);scanner.scanUntil(closingTagRe)}else if(type==="{"){value=scanner.scanUntil(closingCurlyRe);scanner.scan(curlyRe);scanner.scanUntil(closingTagRe);type="&"}else{value=scanner.scanUntil(closingTagRe)}if(!scanner.scan(closingTagRe))throw new Error("Unclosed tag at "+scanner.pos);token=[type,value,start,scanner.pos];tokens.push(token);if(type==="#"||type==="^"){sections.push(token)}else if(type==="/"){openSection=sections.pop();if(!openSection)throw new Error('Unopened section "'+value+'" at '+start);if(openSection[1]!==value)throw new Error('Unclosed section "'+openSection[1]+'" at '+start)}else if(type==="name"||type==="{"||type==="&"){nonSpace=true}else if(type==="="){compileTags(value)}}openSection=sections.pop();if(openSection)throw new Error('Unclosed section "'+openSection[1]+'" at '+scanner.pos);return nestTokens(squashTokens(tokens))}function squashTokens(tokens){var squashedTokens=[];var token,lastToken;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];if(token){if(token[0]==="text"&&lastToken&&lastToken[0]==="text"){lastToken[1]+=token[1];lastToken[3]=token[3]}else{squashedTokens.push(token);lastToken=token}}}return squashedTokens}function nestTokens(tokens){var nestedTokens=[];var collector=nestedTokens;var sections=[];var token,section;for(var i=0,numTokens=tokens.length;i<numTokens;++i){token=tokens[i];switch(token[0]){case"#":case"^":collector.push(token);sections.push(token);collector=token[4]=[];break;case"/":section=sections.pop();section[5]=token[2];collector=sections.length>0?sections[sections.length-1][4]:nestedTokens;break;default:collector.push(token)}}return nestedTokens}function Scanner(string){this.string=string;this.tail=string;this.pos=0}Scanner.prototype.eos=function eos(){return this.tail===""};Scanner.prototype.scan=function scan(re){var match=this.tail.match(re);if(!match||match.index!==0)return"";var string=match[0];this.tail=this.tail.substring(string.length);this.pos+=string.length;return string};Scanner.prototype.scanUntil=function scanUntil(re){var index=this.tail.search(re),match;switch(index){case-1:match=this.tail;this.tail="";break;case 0:match="";break;default:match=this.tail.substring(0,index);this.tail=this.tail.substring(index)}this.pos+=match.length;return match};function Context(view,parentContext){this.view=view;this.cache={".":this.view};this.parent=parentContext}Context.prototype.push=function push(view){return new Context(view,this)};Context.prototype.lookup=function lookup(name){var cache=this.cache;var value;if(cache.hasOwnProperty(name)){value=cache[name]}else{var context=this,names,index,lookupHit=false;while(context){if(name.indexOf(".")>0){value=context.view;names=name.split(".");index=0;while(value!=null&&index<names.length){if(index===names.length-1)lookupHit=hasProperty(value,names[index]);value=value[names[index++]]}}else{value=context.view[name];lookupHit=hasProperty(context.view,name)}if(lookupHit)break;context=context.parent}cache[name]=value}if(isFunction(value))value=value.call(this.view);return value};function Writer(){this.cache={}}Writer.prototype.clearCache=function clearCache(){this.cache={}};Writer.prototype.parse=function parse(template,tags){var cache=this.cache;var tokens=cache[template];if(tokens==null)tokens=cache[template]=parseTemplate(template,tags);return tokens};Writer.prototype.render=function render(template,view,partials){var tokens=this.parse(template);var context=view instanceof Context?view:new Context(view);return this.renderTokens(tokens,context,partials,template)};Writer.prototype.renderTokens=function renderTokens(tokens,context,partials,originalTemplate){var buffer="";var token,symbol,value;for(var i=0,numTokens=tokens.length;i<numTokens;++i){value=undefined;token=tokens[i];symbol=token[0];if(symbol==="#")value=this.renderSection(token,context,partials,originalTemplate);else if(symbol==="^")value=this.renderInverted(token,context,partials,originalTemplate);else if(symbol===">")value=this.renderPartial(token,context,partials,originalTemplate);else if(symbol==="&")value=this.unescapedValue(token,context);else if(symbol==="name")value=this.escapedValue(token,context);else if(symbol==="text")value=this.rawValue(token);if(value!==undefined)buffer+=value}return buffer};Writer.prototype.renderSection=function renderSection(token,context,partials,originalTemplate){var self=this;var buffer="";var value=context.lookup(token[1]);function subRender(template){return self.render(template,context,partials)}if(!value)return;if(isArray(value)){for(var j=0,valueLength=value.length;j<valueLength;++j){buffer+=this.renderTokens(token[4],context.push(value[j]),partials,originalTemplate)}}else if(typeof value==="object"||typeof value==="string"||typeof value==="number"){buffer+=this.renderTokens(token[4],context.push(value),partials,originalTemplate)}else if(isFunction(value)){if(typeof originalTemplate!=="string")throw new Error("Cannot use higher-order sections without the original template");value=value.call(context.view,originalTemplate.slice(token[3],token[5]),subRender);if(value!=null)buffer+=value}else{buffer+=this.renderTokens(token[4],context,partials,originalTemplate)}return buffer};Writer.prototype.renderInverted=function renderInverted(token,context,partials,originalTemplate){var value=context.lookup(token[1]);if(!value||isArray(value)&&value.length===0)return this.renderTokens(token[4],context,partials,originalTemplate)};Writer.prototype.renderPartial=function renderPartial(token,context,partials){if(!partials)return;var value=isFunction(partials)?partials(token[1]):partials[token[1]];if(value!=null)return this.renderTokens(this.parse(value),context,partials,value)};Writer.prototype.unescapedValue=function unescapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return value};Writer.prototype.escapedValue=function escapedValue(token,context){var value=context.lookup(token[1]);if(value!=null)return mustache.escape(value)};Writer.prototype.rawValue=function rawValue(token){return token[1]};mustache.name="mustache.js";mustache.version="2.2.1";mustache.tags=["{{","}}"];var defaultWriter=new Writer;mustache.clearCache=function clearCache(){return defaultWriter.clearCache()};mustache.parse=function parse(template,tags){return defaultWriter.parse(template,tags)};mustache.render=function render(template,view,partials){if(typeof template!=="string"){throw new TypeError('Invalid template! Template should be a "string" '+'but "'+typeStr(template)+'" was given as the first '+"argument for mustache#render(template, view, partials)")}return defaultWriter.render(template,view,partials)};mustache.to_html=function to_html(template,view,partials,send){var result=mustache.render(template,view,partials);if(isFunction(send)){send(result)}else{return result}};mustache.escape=escapeHtml;mustache.Scanner=Scanner;mustache.Context=Context;mustache.Writer=Writer});

///#source 1 1 /Assets/scripts/global/helpers.js
/* 
 * ---------------------------------------- *
 * Name: 	AA Helpers JavaScripts          *
 * Type: 	JavaScript                      *
 * Version: Not Versioned                   *
 * Author:  Codehouse                       *
 * ---------------------------------------- *
 */

/*
 * site helper methods
 */

window.aa || (window.aa = {});
window.aa.helpers = {
    cache: {
        cachedElements: (new function () {
            this.$window = $(window);
            this.$document = $(document);
            this.$html = $('html');
            this.$body = $('body');
            this.$main = $('#main');
            this.$footer = $('#site-footer');
            this.isExperienceEditor = this.$body.hasClass('experience-editor');
            this.url = window.location.pathname;
        }()),
        constants: {
            TABLET_LANDSCAPE: 1024,
            TABLET_BREAKPOINT: 880,
            MOBILE_BREAKPOINT: 737
        },
        registerCookie: new Cookie()
    },

    // truncate text with no option to reveal the rest or "read more/less"
    truncateText: function (text, nr) {
        var truncatedText = text.trim().substring(0, nr).split(' ').slice(0, -1).join(' ');

        if (text.length > nr) {
            return truncatedText;
        } else {
            return false;
        }
    },

    // load search results
    showResults: function ($resultsContainer, $loadingElem) {
        $resultsContainer.stop().fadeIn(100, function () { // fade in container
            $loadingElem.removeClass('loading'); // remove loading class
        });
    },

    // hide search results
    hideResults: function ($resultsContainer, $loadingElem, empty) {
        $resultsContainer.stop().fadeOut(100, function () { // fade out container
            $loadingElem.removeClass('loading'); // remove loading class
            // empty results container by default, unless false passed in for "empty" argument
            if (empty === true) {
                $resultsContainer.empty();
            }
        });
    },

    // autocomplete
    autoComplete: function (args) {
        var hasUrl = typeof args.url !== 'undefined',
            numKeyCodes = new RegExp(/ 13 | 27 | 38 | 40 /i),
            isUsingResults,
            blurTimer,
            ajaxTimer,
            ajaxCall,
            previousKeyword,
            keyword,
            keyUpEvents = {
                upAndDown: function (isUpKey) {
                    if (!args.preventArrowBehaviour) {
                        window.aa.helpers.autoCompleteArrowKeyHelper(args.$resultsContainer.find('li').not('.hide'), isUpKey);
                        window.aa.helpers.placeItemInViewHelper(args.$resultsContainer.find('.focus'), args.$resultsContainer.children('ul'));
                    }
                },
                13: args.onEnter,
                27: function () { // esc
                    args.$input.trigger('blur');
                },
                38: function () { // arrow up
                    keyUpEvents.upAndDown(true);
                },
                40: function () { // arrow down
                    keyUpEvents.upAndDown(false);
                }
            };

        function initAjax() {

            var url = args.url.replace('{value}', keyword);

            ajaxCall = $.ajax({
                url: url,
                type: 'GET',
                success: args.onSuccess,
                error: function () {
                    window.aa.helpers.hideResults(args.$resultsContainer, args.$loadingElem);
                }
            });
        }

        function getResults() {
            if (hasUrl) {
                initAjax();
            } else {
                args.onSuccess();
            }
        }

        function clearRequest() {
            if (ajaxCall) {
                ajaxCall.abort();
            }
            if (ajaxTimer) {
                clearTimeout(ajaxTimer);
            }
        }

        /*
         * clean string of special characters
         * @param str {string}
         * @return {string}
         */
        function cleanString(str) {
            return $.trim(str.replace(/[*|&;$%@"<>()+,]/g, ''));
        }

        args.$input.on({
            keypress: function (e) {
                if (numKeyCodes.test(' ' + e.keyCode + ' ') || (/^[a-zA-Z0-9- ]*$/.test($(this).val()) === false)) {
                    e.preventDefault();
                } else {
                    clearRequest();
                }
            },
            keyup: function (e) {
                var keyCode = e.keyCode;

                keyword = cleanString(args.$input.val());
                previousKeyword = keyword; // store keyword as previous keyword

                if (numKeyCodes.test(' ' + keyCode + ' ')) {
                    // check for " {num} " instead of "num" so that numbers such as "138" don't pass regex 
                    keyUpEvents[keyCode]();
                    return;
                }

                clearRequest();

                if (keyword.length >= args.characterCount) {
                    args.$loadingElem.addClass('loading');
                    ajaxTimer = setTimeout(function () {
                        getResults(keyword);
                    }, 150);
                } else {
                    window.aa.helpers.hideResults(args.$resultsContainer, args.$loadingElem);
                }
            },
            blur: function () {
                if (isUsingResults) {
                    return;
                }

                // use timer to ensure click events on spans fire before input blur
                blurTimer = setTimeout(function () {
                    clearRequest(); // abort any active ajax call
                    window.aa.helpers.hideResults(args.$resultsContainer, args.$loadingElem, false); // hide results container
                    if (typeof args.onBlur === 'function') {
                        args.onBlur();
                    }
                }, 100);
            },
            focus: function () {
                keyword = cleanString(args.$input.val());

                if (blurTimer) {
                    clearTimeout(blurTimer);
                }

                // show results when focussing only if input has a keyword in it and there are results to show
                if (keyword.length >= args.characterCount && args.$resultsContainer[0].innerHTML !== '') {
                    // check keyword on focus with keyword on blur, in case the keyword has been updated externally
                    if (keyword === previousKeyword) {
                        window.aa.helpers.showResults(args.$resultsContainer, args.$loadingElem);
                    } else {
                        getResults(keyword);
                    }
                }

                if (typeof args.onFocus === 'function') {
                    args.onFocus();
                }
            }
        });

        // prevent the mousedown on results container from triggering a blur
        args.$resultsContainer.on({
            // use mousedown to detect if user clicks on container, or scrollbar inside
            mousedown: function () {
                isUsingResults = true;
            },
            mouseup: function () {
                args.$input.trigger('focus');
                isUsingResults = false;
            }
        });
    },

    /*
     * up and down arrow key helper for autocompletes (search results)
     * adds "focus" class to next item
     * @param $items {jQuery elements}: items to cycle through
     * @param cycleUp {boolean}: if true, go up the list of items instead of down (default)
     */
    autoCompleteArrowKeyHelper: function ($items, cycleUp) {
        var focusedItemIndex = -1;

        // check if any have the focus class, and if so, store the item index based on $items (as not all items will be siblings)
        for (var i = 0; i < $items.length; i += 1) {
            if ($($items[i]).hasClass('focus')) {
                focusedItemIndex = i;
                break;
            }
        }

        if (focusedItemIndex !== -1) { // if there is a currently focused one
            $items.removeClass('focus');
            if (cycleUp) {
                if (focusedItemIndex !== 0) { // if not on first one, focus on previous item
                    $items.eq(focusedItemIndex - 1).addClass('focus');
                }
                return;
            }
            if (focusedItemIndex !== $items.length - 1) { // if not currently on last one, focus on next item
                $items.eq(focusedItemIndex + 1).addClass('focus');
            }
        } else { // if none are currently focused
            if (cycleUp) {
                $items.last().addClass('focus');
                return;
            }
            $items.first().addClass('focus');
        }
    },

    /*
     * Check if item is in visible area, if not, scroll $searchArea to it
     * @param $item {jQuery element}: item to check position of - if multiple, takes first one
     * @param $holder {jQuery element} optional: element to check $item position within, and to force scroll to
     * if none passed in, will use $item's offsetParent
     */
    placeItemInViewHelper: function ($item, $searchArea) {

        var holderHeight,
            itemPos,
            itemHeight,
            itemIsBelowView,
            itemIsBeyondView,
            holderScrollPos;

        if (!$item.length) {
            return;
        }
        if ($item.length > 1) {
            $item = $item.first();
        }

        $searchArea = $searchArea || $($item[0].offsetParent);
        holderHeight = $searchArea.outerHeight(),
            itemPos = $item.position().top,
            itemHeight = $item.outerHeight(),
            itemIsBelowView = itemPos < 0, // if item is below view
            itemIsBeyondView = itemPos + itemHeight > holderHeight; // if item (and its height) is past current scroll view

        if (itemIsBelowView || itemIsBeyondView) {

            holderScrollPos = $searchArea.scrollTop();

            if (itemIsBelowView) {
                // scroll to item: uses + in calculation as itemPos will be a negative value
                $searchArea.stop().animate({ scrollTop: holderScrollPos + itemPos }, 100);
            } else {
                // scroll to item: ensure item is at the bottom of the viewable area
                $searchArea.stop().animate({ scrollTop: holderScrollPos + (itemPos - holderHeight + itemHeight) }, 100);
            }
        }
    },

    // retrieve the tallest height in a $ collection
    getTallestHeightHelper: function ($panels) {
        return Math.max.apply(Math, $panels.map(function () {
            return $(this).outerHeight();
        }));
    },

    // product detail panel heights
    panelHeight: function () {
        var $panel = $(this),
            $outerPanel;

        // set equal heights of columns based on tallest
        function setHeights($panels) {
            $panels.height(''); // remove inline height
            $panels.height(function () {
                return Math.max.apply(Math, $panels.map(function () {
                    return $(this).height();
                }));
            });
        }

        if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT || window.aa.helpers.cache.cachedElements.isExperienceEditor) {
            return;
        }

        $outerPanel = $panel.closest('.two-column');

        setHeights($outerPanel.find('.beam'));
        setHeights($outerPanel.find('.info'));
        setHeights($outerPanel.find('.features'));
    },

    // global accordions
    accordions: function () {
        var $accordion = $(this),
            $accordionItem = $accordion.find('.accordion-item'),
            data = $accordion.data();
            
        window.aa.pageContentCache = null;

        window.aa.helpers.registerAccordionContentDownloadHandlers();   // CD-529
            
        function accordionList() {
            var $accordions = $(this),
                $accordionHeader = $accordions.find('.accordion-header'),
                $accordionContent = $accordions.find('.accordion-content'),
                $accordionSummary = $accordions.find('.accordion-summary');

            function hideSummaryShowContent() {
                $accordionSummary.stop().slideUp(function () {
                    $accordionContent.stop().addClass('open').slideDown(250);
                });
            }

            function hideContentShowSummary() {
                $accordionContent.stop().removeClass('open').slideUp(function () {
                    $accordionSummary.stop().slideDown(250);
                });
            }

            function hideSiblingContent() {
                $accordions.siblings().children('.accordion-content').stop().removeClass('open').slideUp(function () {
                    $accordions.siblings().children('.accordion-summary').slideDown(250);
                });
            }

            // set active state
            function activeAccordion() {
                if ($accordions.hasClass('active')) {
                    if (data.animating === true) {
                        if ($accordionSummary.length) {
                            hideSummaryShowContent();
                        } else {
                            $accordionContent.stop().addClass('open').slideDown(250);
                        }
                    } else {
                        if ($accordionSummary.length) {
                            hideContentShowSummary();
                        } else {
                            $accordionContent.stop().removeClass('open').hide();
                        }
                    }
                } else {
                    if ($accordionSummary.length) {
                        hideContentShowSummary();
                    } else {
                        $accordionContent.stop().removeClass('open').slideUp(250);
                    }
                }
            }

            function toggleAccordions(event) {
                event.preventDefault();
                $accordions.toggleClass('active');
                activeAccordion();
            }

            // NW-2964 Starts
            function fetchAccordionData(event, cb) {
                event.preventDefault(); // stop page from navigating to link
                
                var $accordionLink;
                if(!$(event.target).is('a')) {
                    $accordionLink = $(event.target).parents('a');
                } else {
                    $accordionLink = $(event.target)
                }


                if(!$accordionLink.length) {
                    cb(event);
                    return;
                }

                var selectedAccordionContentId = $accordionLink.attr('id').replace('accordionTitle_', 'accordionText_');

                var accordionContentParent = $(document).find('#' + selectedAccordionContentId);

                // if .inner CSSClass exists in content box, check if it has full data, else check parent for full data
                var accordionContentBox =
                    accordionContentParent.find('.inner').length ? accordionContentParent.find('.inner') : accordionContentParent;

                var accordionContentExists = accordionContentBox.html().trim().length;

                if(!accordionContentExists) { // if content in accordion content box doesnt exists make a call to get data
                    
                    var fullPageUrl = $accordionLink.attr('href');
    
                    if(!window.aa.pageContentCache) {
                        $.get(fullPageUrl, function(data) {
                            var parsedPage = $.parseHTML(data);                    
                            
                            // save to cache so as to not make the call again
                            window.aa.pageContentCache = $(parsedPage);
                            
                            setAccordionData(selectedAccordionContentId);
                            cb(event);
                        
                        });
                    } else {
                        setAccordionData(selectedAccordionContentId);
                        cb(event);
                    }

                } else {    // default functionality of toggling accordions
                    cb(event);
                }

            }
           

            function setAccordionData(selectedAccordionContentId) {
                
                var accordionContent = 
                $(window.aa.pageContentCache).find('#' + selectedAccordionContentId);
                
                var accordionContentHolder = $(document).find('#' + selectedAccordionContentId);

                accordionContentHolder.html($(accordionContent).html());
                
                accordionContentDownloadFinished(accordionContentHolder);   // CD-529

            }
            // NW-2964 Ends

            function accordionContentDownloadFinished(accordionContentHolder) { // CD-529
                var handlers = window.aa.salesJourneyApp.accordionContentDownloadHandlers || [];
                
                for(var h = 0; h < handlers.length; h++) {
                    var shouldCallPerformAction = false;

                    if(handlers[h].isHandler && (typeof handlers[h].isHandler == 'function')) {
                        shouldCallPerformAction = handlers[h].isHandler(accordionContentHolder);
                    }
                    if(shouldCallPerformAction && handlers[h].performAction && (typeof handlers[h].performAction == 'function')) {
                        handlers[h].performAction(accordionContentHolder);
                    }
                }
            }

            
            // show accordion content as open to not affect animation
            if ($accordionContent.hasClass('open')) {
                $accordionContent.show();
                $accordionSummary.hide();
            }

            // all accordions open by default in experience editor
            if (window.aa.helpers.cache.cachedElements.isExperienceEditor) {
                $accordionItem.addClass('active');
                $accordionContent.stop().addClass('open').show();
                $accordionSummary.show();
            }

            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {

                $accordionHeader.click(function (event) {
                    
                    event.preventDefault();

                    fetchAccordionData(event, function() {
                       
                        $accordions.toggleClass('active').siblings().removeClass('active');

                        if ($accordionSummary.length) {
                            hideSiblingContent();
                        } else {
                            $accordions.siblings().children('.accordion-content').removeClass('open').slideUp(250);
                        }

                        activeAccordion();
                    })

                });
                return;
            }

            $accordionHeader.on({
                click: function(event) {
                    fetchAccordionData(event, toggleAccordions)
                },  // NW-2964, can be changed back to toggleAccordions without any other changes
                keypress: function (e) {
                    if (e.keyCode === 13 || e.which === 13) {
                        fetchAccordionData(e, toggleAccordions);   // NW-2964, can be changed back to toggleAccordions() without any other changes
                    }
                }
            });

        }

        $accordionItem.each(accordionList);
    },

    // CD-529
    registerAccordionContentDownloadHandlers: function() {  // handlers for accordions which do not have a dedicated JS file can be added here
        window.aa.salesJourneyApp.accordionContentDownloadHandlers = [];

        var accordionMethods = {
            isHandler: function (accordionContentHolder) {
                var callMeBackForm = accordionContentHolder.find('.call-me-back-form');
                return ((callMeBackForm && callMeBackForm.length) && !callMeBackForm.attr('data-id'))
            },
            performAction: function (accordionContentHolder) {
                var callMeBackForm = accordionContentHolder.find('.call-me-back-form');
                try {
                    formValidation.init();
                    callMeBackForm.each(initFormElements);  // initFormElements is a global function from Assets\scripts\forms.js
                } catch(ex) {
                    console.log(ex);
                }

            }
        };

        window.aa.salesJourneyApp.accordionContentDownloadHandlers.push(accordionMethods);  // more objects with methods can be similarly pushed from other pages/scripts

    },

    // mobile only accordions within modules
    moduleAccordion: function () {

        var $moduleAccordion = $(this),
            $moduleAccordionContent = $moduleAccordion.find('.module-accordion-content'),
            $moduleAccordionSummary = $moduleAccordion.find('.module-accordion-summary');

        if ((window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) || ($('.desktop-enabled').length)) {

            if ($moduleAccordionSummary.length) {
                if ($moduleAccordion.hasClass('active')) {
                    $moduleAccordionContent.show();
                    $moduleAccordionSummary.hide();
                } else {
                    $moduleAccordionSummary.show();
                    $moduleAccordionContent.hide();
                }
            }
            //Start sublink changes			
            openbydefaultlinkvalue = $moduleAccordion.hasClass("openbydefault");
            if (openbydefaultlinkvalue) {
                $moduleAccordionContent.css("display", "block").slideDown(300);
                $moduleAccordionSummary.slideUp(300);
                $moduleAccordion.toggleClass('active').siblings().removeClass('active');
            }
			//End sublink changes
            $moduleAccordion.find('.module-accordion-header').on('click', function () {

                $moduleAccordion.toggleClass('active').siblings().removeClass('active');

                // close content of other accordions and show summary
                $moduleAccordion.siblings().find('.module-accordion-content').stop().slideUp(300, function () {
                    $moduleAccordion.siblings().find('.module-accordion-summary').stop().slideDown(300);
                });

                if ($moduleAccordion.hasClass('active')) {
                    if ($moduleAccordionSummary.length) {
                        $moduleAccordionSummary.stop().slideUp(300, function () {
                            $moduleAccordionContent.stop().slideDown(300);
                        });
                    } else {
                        $moduleAccordionContent.stop().slideDown(300);
                    }
                } else {
                    if ($moduleAccordionSummary.length) {
                        $moduleAccordionContent.stop().slideUp(300, function () {
                            $moduleAccordionSummary.stop().slideDown(300);
                        });
                    } else {
                        $moduleAccordionContent.stop().slideUp(300);
                    }
                }

            });
            //Start sublink changes
            $moduleAccordion.find('.module-accordion-header-sublink').on('click', function () {

                $moduleAccordion.toggleClass('active').siblings().removeClass('active');

                // close content of other accordions and show summary
                $moduleAccordion.siblings().find('.module-accordion-content').stop().slideUp(300, function () {
                    $moduleAccordion.siblings().find('.module-accordion-summary').stop().slideDown(300);
                });

                if ($moduleAccordion.hasClass('active')) {
                    if ($moduleAccordionSummary.length) {
                        $moduleAccordionSummary.stop().slideUp(300, function () {
                            $moduleAccordionContent.stop().slideDown(300);
                        });
                    } else {
                        $moduleAccordionContent.stop().slideDown(300);
                    }
                } else {
                    if ($moduleAccordionSummary.length) {
                        $moduleAccordionContent.stop().slideUp(300, function () {
                            $moduleAccordionSummary.stop().slideDown(300);
                        });
                    } else {
                        $moduleAccordionContent.stop().slideUp(300);
                    }
                }

            });
			//End sublink changes
        }
    },

    // save form data
    saveAccountForm: function (url, $form, dto, $serviceErrorMessageContainer, $serviceFailedMessageContainer, $submit) {

        var messageTimeout;

        // message playback
        function responseMessages(response) {

            var $theResult = $form.find('.success-result');

            // successful messages
            if (response.IsOkay) {
                $theResult.show().find('.result-msg').html('<span class="info-check"></span>' + response.Message);

                // after successMessageExpiry redirect to respective page
                messageTimeout = setTimeout(function () {
                    $form.find('.success-result').hide();
                    window.location.href = response.SuccessRedirect;
                }, (response.SuccessMessageExpiry * 1000));

            } else {
                $form.find('.service-error-message').text(response.Message).show();
                $form.find('.service-error-failed').hide();
            }

            $submit.prop('disabled', false).removeClass('disabled processing');
        }

        // service failure messages
        function serviceFailure(data) {
            $submit.prop('disabled', false).removeClass('disabled processing');

            if (typeof data.responseJSON !== 'undefined' && (typeof data.responseJSON.IsOkay !== 'undefined' && !data.responseJSON.IsOkay)) {
                $form.find('.service-error-message').text(data.responseJSON.Message).show();
                $form.find('.service-error-failed').hide();
            } else {
                $form.find('.service-error-failed').show();
            }
        }

        $.ajax({
            type: 'POST',
            url: url,
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify(dto)
        }).done(responseMessages).fail(serviceFailure);
    },

    // open lightbox and autoplay youtube video
    youtubeLightbox: function () {

        var $lightBox = window.aa.helpers.cache.cachedElements.$main.find('#youtube-lightbox'),
            $videoModule = $lightBox.find('.youtube-video'),
            $videoContainer = $videoModule.find('.video-container'),
            $play = window.aa.helpers.cache.cachedElements.$main.find('.cinemagraph-container button.play-media'),
            $close = $lightBox.find('button.close-media'),
            $iframe = $lightBox.find('iframe'),
            fadeTimer;

        $play.on({
            click: function (e) {

                var videoUrl = $iframe.prop('src');

                e.preventDefault();

                // pop up lightbox and autoplay video
                if (window.aa.salesJourneyApp.helpers.isDefined(videoUrl)) {

                    videoUrl += '&autoplay=1';

                    clearTimeout(fadeTimer);

                    if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                        $videoModule.stop().animate({ scrollTop: 250 });
                    }

                    window.aa.helpers.cache.cachedElements.$body.addClass('youtube-hero-on');
                    $iframe.stop().fadeIn(250).prop('src', videoUrl);
                    $videoContainer.animate({ 'opacity': 1 }, 800);

                    fadeTimer = setTimeout(function () {
                        $lightBox.stop().fadeIn(250).attr('aria-hidden', false).addClass('active');
                    }, 150);
                }
            }
        });

        $close.on({
            click: function (e) {

                var videoUrl = $iframe.prop('src');

                e.preventDefault();

                clearTimeout(fadeTimer);

                // close lightbox and pause video
                if (window.aa.salesJourneyApp.helpers.isDefined(videoUrl)) {

                    videoUrl = videoUrl.replace('&autoplay=1', '');

                    $iframe.prop('src', videoUrl);
                    $lightBox.stop().fadeOut(400).attr('aria-hidden', true).removeClass('active');
                    window.aa.helpers.cache.cachedElements.$body.removeClass('youtube-hero-on');

                    fadeTimer = setTimeout(function () {
                        $iframe.hide();
                    }, 150);
                }
            }
        });

        window.aa.helpers.cache.cachedElements.$document.on('keyup', function (e) {

            // open youtube lightbox when pressing return
            if ($play.is(e.target && e.which === 13)) {
                $play.trigger('click');
            }

            // close youtube lightbox when pressing escape
            if (window.aa.helpers.cache.cachedElements.$body.is('.youtube-hero-on') && e.which === 27) {
                $close.trigger('click');
            }
        });
    },

    // input thousands formatting
    initThousandsFormatting: function (inputsSelector, regex) {
        $(inputsSelector).each(function () {
            var $input = $(this),
                inputValue;

            function formatValue() {
                inputValue = $input.val().split(',').join('');

                $input.removeClass('masked');

                if (inputValue === '' || !regex.test(inputValue)) {
                    $input.addClass('masked');
                    $input.val($input.val().slice(0, -1)).removeClass('masked').focus();

                } else if ($input.is('.thousands-format') && regex.test(inputValue)) {

                    if (inputValue.length > 3) {
                        $input.val(function (index, value) {
                            return value.replace(/\D/g, '').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                        });
                    } else {
                        $input.val(inputValue);
                    }
                }
            }

            formatValue();

            $input.on({
                input: function (e) {

                    // if keys (arrows, tab, return, shift, delete, spacebar, backspace, ctrl + v, ctrl + a)  are pressed, return
                    if (e.which === 37 || e.which === 38 || e.which === 39 || e.which === 40 || e.which === 9 || e.which === 13 || e.which === 16 || e.which === 46 || e.which === 32 || e.which === 8 || (e.which === 17 && e.which === 86) || (e.which === 17 && e.which === 65)) {
                        return;
                    }

                    formatValue();
                }
            });
        });
    }
};

///#source 1 1 /Assets/scripts/app-banner.js
/* 
 * ---------------------------------------- *
 * Name: 	Android App Banner              *
 * Type: 	JavaScript                      *
 * Version: Not Versioned                   *
 * Author:	Joseph Moore | Thomas Dale      *
 * Requisites: chg.Client                   *
 *             chg.Cookie                   *
 * ---------------------------------------- *
 */

(function ($) {

    /* android app banner
       ---------------------------- */

    function androidAppBanner() {
        var $appBanner = $(this),
            appId = $appBanner.data('app-id');

        // show the banner
        function revealBanner() {
            $appBanner.stop().slideDown();
        }

        // hide the banner
        function hideBanner() {
            $appBanner.stop().slideUp();
        }

        // only on android mobile/tablet device
        if (client.Mobile && client.Android) {

            // no AppInstalled cookie, display banner 
            if (!window.aa.helpers.cache.registerCookie.check('AppInstalled')) {
                revealBanner();
            } else {
                // check if app ID doesn't exist in the cookie's value
                if ($.inArray(appId, window.aa.helpers.cache.registerCookie.check('AppInstalled').split(',')) === -1) {
                    revealBanner();
                }
            }

            // click event
            $appBanner.find('.close').on('click', function () {
                var cookieValue = window.aa.helpers.cache.registerCookie.check('AppInstalled');

                /* 
                    get the cookie value, if it's not null, 
                    split it into an array, 
                    otherwise set its value to an empty array
                */
                if (cookieValue) {
                    cookieValue = cookieValue.split(',');
                } else {
                    cookieValue = [];
                }

                // if non-existent value push it to array 
                if ($.inArray(appId, cookieValue) === -1) {
                    cookieValue.push(appId);
                }

                // write the cookie with new value(s)
                window.aa.helpers.cache.registerCookie.write('AppInstalled', cookieValue.join(','), 14);

                hideBanner();

            });

        }

    }

    // initialise
    $('.app-banner').each(androidAppBanner);

})(jQ);
///#source 1 1 /Assets/scripts/forms.js
/*
 * ---------------------------------------- *
 * Name: 	Form Elements                   *
 * Type: 	JavaScript                      *
 * Version: Not Versioned                   *
 * Author:	Codehouse | Thomas Dale         *
 * Requisites: chg.Client,                  *
 *             chg.FormValidation,          *
 *             chg.StylishForms             *
 * ---------------------------------------- *
 */

/* forms and form validation
---------------------------- */
boot.config.libs = '/Assets/scripts/libs/';

function initFormElements() {

    var $formElements = $(this);

    // form inputs and labels
    function inputLabels() {

        var $fields = $(this),
            $inputs = $fields.find('input, textarea'),
            $textArea = $inputs.filter('textarea'),
            $fullnameFields = $fields.find('.first-name,.last-name'),
            $dobGroup = $fields.find('.dob-input'),
            $dobday = $fields.find('.dob-group.day input'),
            $dobmonth = $fields.find('.dob-group.month input'),
            $dobyear = $fields.find('.dob-group.year input'),
            $characterCounter = $fields.find('.counter'),
            $submitBtn = $formElements.find('input[type="submit"]'),
            characterLimit = $textArea.data('character-limit'),
            $postCodeField = $inputs.filter('input.postCode'),
            $telephoneField = $inputs.filter('input.tel-mobile'),
            $loanAgreeNumberField = $inputs.filter('input.loan-number'),
            $membshipNumber = $inputs.filter('input.member-number'),
            $sortCode = $inputs.filter('input.uasort-code'),
            $accountNumber = $inputs.filter('input.account-number'),
            $loanAgreeNumberField = $inputs.filter('input.loan-number'),
            $payAmountField = $inputs.filter('input.pay-amount'),
            $dobField = $inputs.filter('input.dob-input');
            

        $characterCounter.text(characterLimit);

        // show/hide information about the field
        function informationToggle() {
            $formElements.on('click', '.ico', function () {
                $fields.find('.more-information').stop().slideToggle();
            });
        }

        $formElements.on('keyup', $inputs, function (e) {

            // if tab or shift keys are pressed or if input exists inside a calculator tool, return
            if (e.which === 16 || e.which === 9 || e.which === 13 || $formElements.closest('.calculator-tool').length) {
                return;
            }

            // count down character count
            if ($characterCounter.length) {
                $characterCounter.text(characterLimit - $textArea.val().length);
            }

            // remove input label text if input is empty
            if ($inputs.val() === '') {
                $inputs.removeClass('typing');
                $submitBtn.prop('disabled', true).addClass('disabled');
            } else {
                // display input label text above typed value
                $inputs.addClass('typing');
                $submitBtn.prop('disabled', false).removeClass('disabled');
            }

            window.aa.salesJourneyApp.helpers.initInputMasking($inputs.filter('#day-number').add($inputs.filter('#month-number')), window.aa.salesJourneyApp.constants.regex.days);

        });

        //loan agreement number FS-639
        $loanAgreeNumberField.on({
            blur: function (e) {
                var $input = $(this);
                var inputVal = $input.val();
                var res = inputVal.substring(0, 4);
                if (inputVal != "") {
                    if (res != "0007" || inputVal.length != 19) {
                        $('#mcc6012AccountNumber').parent().parent().parent('.form-field').addClass('error');
                        $('#mcc6012AccountNumber').parent().parent().parent('.form-field').find('.err-msgs div[data-validation="minLength"]').show();
                    } else {
                        $('#mcc6012AccountNumber').parent().parent().parent('.form-field').find('.err-msgs div[data-validation="minLength"]').hide();
                    }
                }


            }
        });

        //amount to pay FS-639
        $payAmountField.on({
            keypress: function (e) {
                var e = e || window.event;
                var k = e.which || e.keyCode;
                var s = String.fromCharCode(k);
                var $input = $(this),
                    key = window.event ? e.keyCode : e.which;

                // remove any invalid characters but allow use of arrow keys
                if (key === 37 || key === 38 || key === 39 || key === 40) {
                    return true;
                }
                // format input value to add commas in thousands
                $input.autoNumeric('init', { mDec: '2', vMin: '0', vMax: '5000' });
            },
            paste: function (e) {
                // allow backspace in firefox
                var $input = $(this),
                    key = window.event ? e.keyCode : e.which;

                // remove any invalid characters but allow use of arrow keys
                if (key === 37 || key === 38 || key === 39 || key === 40) {
                    return true;
                }
                // format input value to add commas in thousands
                $input.autoNumeric('init', { mDec: '2', vMin: '0', vMax: '5000' });
            }
        });

        //MB-447 : input masking for postcode
        $postCodeField.on({
            keydown: function (e) {

                window.aa.salesJourneyApp.helpers.initInputMasking($postCodeField, window.aa.salesJourneyApp.constants.regex.postcodeRegister);
            },
            paste: function (e) {
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }
                return /^(?!\s)[0-9a-zA-Z0-9]*$/.test(e.originalEvent.clipboardData.getData('text'));
            }
        });
        //for telephone validation
        $telephoneField.on({
            keydown: function (e) {
                window.aa.salesJourneyApp.helpers.initInputMasking($telephoneField, window.aa.salesJourneyApp.constants.regex.telephoneNumberRegister);
            },
            paste: function (e) {
                var filter = /^(?!\s)[0-9+]*$/;
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }
                return filter.test(e.originalEvent.clipboardData.getData('text'));
            }
        });

        $membshipNumber.on({
            keydown: function (e) {
                window.aa.salesJourneyApp.helpers.initInputMasking($membshipNumber, window.aa.salesJourneyApp.constants.regex.numeric);
            },
            paste: function (e) {
                var filter = /^[0-9]*$/;
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }
                return filter.test(e.originalEvent.clipboardData.getData('text'));
            }
        });

        $sortCode.on({
            keydown: function (e) {
                window.aa.salesJourneyApp.helpers.initInputMasking($sortCode, window.aa.salesJourneyApp.constants.regex.numeric);
            },
            paste: function (e) {
                var filter = /^[0-9]*$/;
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }
                return filter.test(e.originalEvent.clipboardData.getData('text'));
            }
        });

        $accountNumber.on({
            keydown: function (e) {
                window.aa.salesJourneyApp.helpers.initInputMasking($accountNumber, window.aa.salesJourneyApp.constants.regex.numeric);
            },
            paste: function (e) {
                var filter = /^[0-9]*$/;
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }
                return filter.test(e.originalEvent.clipboardData.getData('text'));
            }
        });

        //UIDA-780 DOB
        $dobday.on({
            keydown: function (e) {

                window.aa.salesJourneyApp.helpers.initInputMasking($dobday, window.aa.salesJourneyApp.constants.regex.days);

            },
            paste: function (e) {
                var filter = /^[0-9]*$/;
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }
                return filter.test(e.originalEvent.clipboardData.getData('text'));
            }
        });
        $dobmonth.on({
            keydown: function (e) {

                window.aa.salesJourneyApp.helpers.initInputMasking($dobmonth, window.aa.salesJourneyApp.constants.regex.months);

            },
            paste: function (e) {
                var filter = /^[0-9]*$/;
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }
                return filter.test(e.originalEvent.clipboardData.getData('text'));
            }
        });
        $dobyear.on({
            keydown: function (e) {

                window.aa.salesJourneyApp.helpers.initInputMasking($dobyear, window.aa.salesJourneyApp.constants.regex.numeric);
            },
            paste: function (e) {
                var filter = /^[0-9]*$/;
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }
                return filter.test(e.originalEvent.clipboardData.getData('text'));
            }
        });

        //firstname and lastname
        $fullnameFields.on({
            input: function (e) {
                $input = $(this);
                var inputValue = $input.val();
                var regex = /^[a-zA-Z#~`_+=?><:!@”$%&.’()* '"+\-,\/;\[\\\]\^_`{|}~\xC0-\xD6\xD8-\xF6\xF8-\xFF]*$/;

                hasInvalidCharacter = regex.test($input.val());

                // replace invalid characters
                if (!hasInvalidCharacter) {
                    $input.addClass('masked');
                    $input.val($input.val().replace($input, ''));
                    $input.val(inputValue.slice(0, -1)).removeClass('masked').focus();
                    return;
                }
            },
            paste: function (e) {
                // allow backspace in firefox
                var filter = /^[a-zA-Z#~`_+=?><:!@”$%&.’() *'"+\-,\/;\[\\\]\^_`{|}~\xC0-\xD6\xD8-\xF6\xF8-\xFF]*$/;
                if (e.which === 8) {
                    return true;
                }
                if (filter.test(e.originalEvent.clipboardData.getData('text'))) {
                    return true;
                } else {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                }
            }
        });

        // prevent script tags and other special characters in textareas
        $textArea.on({
            keypress: function (e) {
                var $thisTextarea = $(this);
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }

                return !$thisTextarea.data('disable-characters') ? /^[a-zA-Z0-9-',.\n ]*$/.test($(this).val()) : true;
            },
            keyup: function (e) {
                var $thisTextarea = $(this),
                    regex = /[^a-zA-Z0-9-',.\n ]+/g,
                    hasInvalidCharacter = regex.test($thisTextarea.val());

                // replace invalid characters
                if (hasInvalidCharacter && $thisTextarea.data('disable-characters')) {
                    $thisTextarea.val($thisTextarea.val().replace(regex, ''));
                }
            },
            paste: function (e) {
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }
                return /^[a-zA-Z0-9-',. ]*$/.test(e.originalEvent.clipboardData.getData('text'));
            }
        });

        $formElements.on('change', 'select', function () {
            $submitBtn.prop('disabled', false).removeClass('disabled');
        });

        $formElements.on('click', '[type="radio"], [type="checkbox"]', function () {

            var $checkBoxRadio = $(this),
                $radioinputsGroup = $checkBoxRadio.closest('.radio-inputs');

            $submitBtn.prop('disabled', !$checkBoxRadio.is(':checked')).removeClass('disabled');
            $checkBoxRadio.parent('.stylish-ds').siblings('label').toggleClass('checked');
            $checkBoxRadio.filter('[type="radio"]').parent().siblings('label').addClass('checked');
            $checkBoxRadio.closest('.stylish-ds').siblings().children('label').removeClass('checked');
            $checkBoxRadio.filter('[type="radio"]').closest('.radio-field, .radio').siblings().children('label').removeClass('checked');

            if ($radioinputsGroup.length) {
                $radioinputsGroup.find('label').removeClass('checked');
                $checkBoxRadio.closest('.radio-input-group').children('label').addClass('checked');
            }
        });

        if ($inputs.hasClass('hidden')) {
            $inputs.parent('.stylish-ds').hide();
            stylishForms.update();
        } else {
            $inputs.parent('.stylish-ds').show();
            stylishForms.update();
        }

        informationToggle();

    }

    // battery form
    function batteryForm() {

        var $batteryForm = $(this),
            $theForm = $batteryForm.find('form'),
            $theResults = $batteryForm.find('.results'),
            $registration = $theForm.find('input[type="text"].registration'),
            $registrationErrorMessage = $registration.parents('.form-field').find('.error-message'),
            registrationErrorMessageDefaultText = $registrationErrorMessage.data('defaultmessage'),
            $havingTrouble = $batteryForm.find('.having-trouble'),
            $submit = $batteryForm.find('input[type="submit"]');

        // replace form elements with results
        function getBatteryInfo() {
            var inputValue = $registration.val(),
                isMember = $theForm.find('input[type="radio"]#Yes').is(':checked');

            if (inputValue.length >= 2) {
                $submit.addClass('disabled processing');

                $.ajax({
                    url: '/cms/ajax/api/battery/getbatteryresults/' + inputValue,
                    type: 'GET'
                }).done(function (batteryApiViewModel) {
                    if (batteryApiViewModel.IsValidVrm && batteryApiViewModel.BatteryCount > 0) {
                        $('<div>').load('/cms/ajax/fragment/batteryform/GetBatteryComponent', {
                            id: inputValue,
                            isMember: isMember
                        },
                            function (response) {
                                $theForm.hide();
                                $theResults.html(response);
                                $submit.removeClass('disabled processing');
                            });
                    } else {
                        $registrationErrorMessage.text(batteryApiViewModel.ValidationError).show();
                        $havingTrouble.show();
                        $submit.removeClass('disabled processing');
                    }
                });
            } else {
                $registrationErrorMessage.text(registrationErrorMessageDefaultText).show();
            }
        }

        $submit.on('click', function (e) {
            e.preventDefault();
            getBatteryInfo();
        });

        $batteryForm.on('click', '.reset-form', function (e) {
            e.preventDefault();
            $theForm.show();
            $registration.val('');
            $registrationErrorMessage.text(registrationErrorMessageDefaultText).hide();
            $theResults.html('');
            $havingTrouble.hide();
        });
    }

    // call me back form
    function callMeBackForm() {
        var $callMeBackForm = $(this),
            $theForm = $callMeBackForm.find('form'),
            $theResults = $callMeBackForm.find('.results'),
            $submit = $theForm.find('.full-submit');
        var submitCalled = false;
        formValidation.api[$callMeBackForm.data('id')].events.full = function (valid) {
            if (submitCalled) return;

            if (valid) {
                $submit.addClass('disabled processing');
                submitCalled = true;
                $.ajax({
                    type: 'POST',
                    url: '/cms/ajax/fragment/CallMeBackForm/RequestCallBack',
                    dataType: 'json',
                    data: $theForm.serialize().replace(/%0D%0A/g, '%2C+'), // remove line breaks causing server errors
                    success: function (data) {
                        if (data.ShowError) {
                            $theForm.find('.service-error-message').text(data.ErrorMessage).show();
                            $theForm.find('.service-error-failed').hide();
                        } else {
                            $theForm.hide();
                            $theResults.show();
                        }
                        $submit.removeClass('disabled processing');
                        submitCalled = false;
                    },
                    error: function () {
                        $theForm.find('.service-error-failed').show();
                        $theForm.find('.service-error-message').hide();
                        $submit.removeClass('disabled processing');
                        submitCalled = false;
                    }
                });
            }
        }

        $theForm.on('submit', function (e) {
            e.preventDefault();
        });

        $callMeBackForm.on('click', '.reset-form', function (e) {
            e.preventDefault();
            $theForm.show();
            $theResults.hide();
        });
    }
    //FS-639-Starts
    // loan repayment form
    function loanPaymentForm() {
        var $loanPaymentForm = $(this),
            $theForm = $loanPaymentForm.find('form'),
            $submit = $loanPaymentForm.find('.full-submit');

        formValidation.api[$loanPaymentForm.data('id')].events.full = function (valid) {
            document.getElementById("chargetotal").value = document.getElementById("chargetotal").value.split(",").join("");
            var day = document.getElementById("dob_day").value.length === 1 ?
                "0" + document.getElementById("dob_day").value :
                document.getElementById("dob_day").value;
            var month = document.getElementById("dob_month").value.length === 1 ?
                "0" + document.getElementById("dob_month").value :
                document.getElementById("dob_month").value;
            document.getElementById("mcc6012BirthDay").value =
                day + "." +
                month + "." +
                document.getElementById("dob_year").value;
            if (valid) {
                if (typeof GenerateHash == 'function') {
                    GenerateHash(function (response) {
                        document.getElementById("frmPaymentGateway").submit();
                    });
                } else {
                    console.log("GenerateHash not found");
                }

            }
        }

        $theForm.on('submit', function (e) {
            e.preventDefault();
        });

    }

    //FS-639-Ends
    //MB-406 - Registration 
    function registerUserForm() {
        $("#sortcode").on({
            keydown: function (e) {
                if (e.which === 32)
                    return false;
            },
            change: function () {
                this.value = this.value.replace(/\s/g, "");
            }
        });

        $("#accountnumber").on({
            keydown: function (e) {
                if (e.which === 32)
                    return false;
            },
            change: function () {
                this.value = this.value.replace(/\s/g, "");
            }
        });

        $("#insurancepolicy").on({
            keydown: function (e) {
                if (e.which === 32)
                    return false;
            },
            change: function () {
                this.value = this.value.replace(/\s/g, "");
            }
        });

        var $registerUserForm = $(this),
            $theForm = $registerUserForm.find('#register-user'),
            $submit = $theForm.find('.full-submit'),
            $password,
            $confirmPassword,
            opt_chosen = 1,
            opt_value;

        /*CD-9798 Part1 Value capturing from inputs*/
        $('#password1').on('input', function () {
            $password = $('#password1').val();
        });
        $('#password2').on('input', function () {
            $confirmPassword = $('#password2').val();
        });

        /* LBG Create Account Options CD-11091 Start*/
        $('.AAMembership').hide();
        $('.radio-field:first-child > .AAMembership ').show();
        $("#options1").find('input[type="text"]').removeAttr('disabled');

        $("input[name$='Fields.MembershipSelection.Value']").click(function () {

            opt_chosen = $(this).val();

            $(".AAMembership").hide();
            $("#options" + opt_chosen).show();
            $("#options" + opt_chosen).parent('.radio-card').addClass('selected').siblings().removeClass('selected');
            $("#options" + opt_chosen).find('input[type="text"]').prop('disabled', false);
            $("#options" + opt_chosen).parent().siblings().find('input[type="text"]').prop('disabled', true);
            /* CD-26072 */
            if ($("#options" + opt_chosen).parent().siblings().find('.AAMembership .form-field').hasClass('error')) {
                $("#options" + opt_chosen).parent().siblings().find('.AAMembership .form-field').removeClass('error');
            }
        });
        /* LBG Create Account Options CD-11091 End */

        formValidation.api[$registerUserForm.data('id')].events.full = function (valid) {
            if (formValidation.api[$registerUserForm.data('id')].events.formPost) return;

            if (valid) {
                $submit.addClass('disabled processing');

                /*LLOYDS Create Account Analytics  */
                if (opt_chosen == 1) {
                    opt_value = "AAPersonal";
                } else if (opt_chosen == 2) {
                    opt_value = "Bank";
                } else if (opt_chosen == 3) {
                    opt_value = "Insurance";
                } else {
                    opt_value = "null";
                }
                /*LLOYDS Create Account Analytics  */

                var email = $('#Email').val();

                var hiddenEmail = $('#Fields_Email_Value').val();
                if (email === null && hiddenEmail !== null) //added if field is set to hidden
                {
                    email = hiddenEmail;
                }

                formValidation.api[$registerUserForm.data('id')].events.formPost =
                    $.ajax({
                        type: 'POST',
                        url: '/cms/ajax/fragment/UniversalAccount/RegisterUser',
                        dataType: 'json',
                        data: $theForm.serialize().replace(/%0D%0A/g, '%2C+'), // remove line breaks causing server errors
                        success: function (data) {
                            var v = grecaptcha.getResponse();
                            var given_name = $('.fc-err-msg.givenName'),
                                sur_name = $('.fc-err-msg.SurName'),
                                Password_fc = $('.fc-err-msg.Password'),
                                user_email = $('.fc-err-msg.UserName');

                            if (v.length !== 0) {
                                if (data.Token === null && data.ErrorMessage !== "AA_UNIQUE") {
                                    $('#dvMain').show();
                                    $('#dvAlreadyRegisteredsMessage').hide();
                                    $('#dvSuccessMessage').hide();
                                    $('#dvErrorsMessage').hide();
                                    //window.location.href = window.location.href + "#fail";

                                } else if (data.ErrorMessage === "AA_UNIQUE") {
                                    $('#dvMain').hide();
                                    $('#dvSuccessMessage').hide();
                                    $('#dvErrorsMessage').hide();
                                    $('#dvAlreadyRegisteredsMessage').show();
                                    utag.view({ "site_section": "Your account", "page_name": "/account/#register/email_already_registered", "error_message": "email already registered", "forgerockID": "", "userType": opt_value });
                                    window.location.href = window.location.href + "#alreadyaccount";

                                } else if (data.Token === null && data.IsOkay === false) {
                                    $('#dvMain').show();
                                    $('#dvAlreadyRegisteredsMessage').hide();
                                    $('#dvSuccessMessage').hide();
                                    $('#dvErrorsMessage').hide();
                                } else {
                                    $(".check-inbox .userEmail").text(email);
                                    $('#dvMain').hide();
                                    $('#dvErrorsMessage').hide();
                                    $('#dvAlreadyRegisteredsMessage').hide();
                                    $('#dvSuccessMessage').show();
                                    utag.view({ "site_section": "Your account", "page_name": "/account/#register/check_your_inbox", "forgerockID": "", "userType": opt_value });
                                    window.location.href = window.location.href + "#success";

                                }
                            }
                            console.log(data.ErrorMessage);
                            if (data.ErrorMessage !== null) {
                                //console.log($(given_name).data('fieldname'));

                                if ($(given_name).data('fieldname') === data.Fieldname) {
                                    $(given_name).show();
                                } else {
                                    $(given_name).hide();
                                }
                                if ($(sur_name).data('fieldname') === data.Fieldname) {
                                    $(sur_name).show();
                                } else {
                                    $(sur_name).hide();
                                }
                                if ($(Password_fc).data('fieldname') === data.Fieldname) {
                                    $(Password_fc).show();
                                } else {
                                    $(Password_fc).hide();
                                }
                                if ($(user_email).data('fieldname') === data.Fieldname) {
                                    $(user_email).show();
                                } else {
                                    $(user_email).hide();
                                }
                                window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                                    scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                                }, 100);
                                $submit.removeClass('disabled processing');
                                formValidation.api[$registerUserForm.data('id')].events.formPost = null;
                                return false;
                            }
                            window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                                scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                            }, 100);
                            $submit.removeClass('disabled processing');
                            formValidation.api[$registerUserForm.data('id')].events.formPost = null;

                        },
                        error: function () {
                            $('#dvMain').hide();
                            $('#dvAlreadyRegisteredsMessage').hide();
                            $('#dvSuccessMessage').hide();
                            $('#dvErrorsMessage').show();
                            window.location.href = window.location.href + "#fail";
                            $submit.removeClass('disabled processing');
                            formValidation.api[$registerUserForm.data('id')].events.formPost = null;
                            window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                                scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                            }, 100);

                        }
                    });
            } else {
                //CD-9798 Part 2 for retaining the values in the create-account registration form
                if ($password != null) {
                    $('#password1').val($password);
                }
                if ($confirmPassword != null) {
                    $('#password2').val($confirmPassword);
                }

                //CD-9263
                if (typeof $('.errors .error').first().offset() !== 'undefined') {
                    $('html, body').animate({
                        scrollTop: $('.errors .error').first().offset().top - (75)
                    }, 150);

                    var scrollUp = 0;
                    if ($('.errors .error').first().hasClass('year') || $('.errors .error').first().hasClass('month') || $('.errors .error').first().hasClass('day')) {
                        $('html, body').animate({
                            scrollTop: $('.errors .error').first().offset().top - (140)
                        }, 150);
                    }
                }
                // Start-CD-2549
                //CD-26072 Slightly Modified for meeting acceptance criteria
                var arr = [];
                $('div.form-field.cf.error').each(function (i, elem) {
                    if ($(elem).find('label').text()) {
                        if ($(elem).find('input[type="text"],input[type="password"]').val())
                            arr.push($(elem).find('label').text() + "-invalid");
                        else
                            arr.push($(elem).find('label').text() + "-missing");
                    }
                });
                // End-CD-2549
                if ($('div.form-field.cf.captchRel.error').length) {
                    arr.push($('.form-field.cf.Recaptcha-group .field >label').text() + "-missing");
                }
                //CD-26072 Slightly Modified for meeting acceptance criteria
                if ($('.form-field.cf.date-of-birth-group .error').length) {
                    if ($('.form-field.cf.date-of-birth-group .error').find('input[type="text"]').val() && $('.form-field.cf.date-of-birth-group .error').hasClass('error'))
                        arr.push($('.form-field.cf.date-of-birth-group fieldset legend').text() + "-invalid");
                    else
                        arr.push($('.form-field.cf.date-of-birth-group fieldset legend').text() + "-missing");
                }
                utag.link({ "event_category": "ua - enter details", "event_name": "registration form - incomplete fields", "event_label": arr.join(',') });
            }
        }

        $theForm.on('submit', function (e) {
            e.preventDefault();
        });
    }

    function registerEmailForm() {
        var $registerEmailForm = $(this),
            $theForm = $registerEmailForm.find('#register-email'),
            $submit = $theForm.find('.full-submit');

        formValidation.api[$registerEmailForm.data('id')].events.full = function (valid) {
            if (formValidation.api[$registerEmailForm.data('id')].events.formPost) return;

            if (valid) {
                utag.link({ "event_category": "create account", "event_name": "email check", "event_label": "submit email" });

                $submit.addClass('disabled processing');
                var email = $('#Email').val();
                var hiddenEmail = $('#Fields_Email_Value').val();
                if (email === null && hiddenEmail !== null) //added if field is set to hidden
                {
                    email = hiddenEmail;
                }

                formValidation.api[$registerEmailForm.data('id')].events.formPost =
                    $.ajax({
                        type: 'POST',
                        url: '/cms/ajax/fragment/UniversalAccount/RegisterEmailvalidation',
                        dataType: 'json',
                        data: $theForm.serialize().replace(/%0D%0A/g, '%2C+'), // remove line breaks causing server errors
                        success: function (data) {

                            var user_email = $('.fc-err-msg.UserName');
                            if (data.IsOkay === false && data.ErrorMessage !== "AA_UNIQUE") {
                                $submit.addClass('disabled processing');
                                $('#dvMain').show();
                            }
                            if (data.ErrorMessage === "AA_UNIQUE" && data.IsOkay === false) {
                                $submit.addClass('disabled processing');
                                $('#dvMain').show();
                                window.location.href = window.location.origin + "/create-account/already-registered";
                            } else if (data.RecaptchaFail) {
                                window.location.href = window.location.origin + "/create-account/error";
                            } else {
                                $('#dvMain').show();
                                //window.location.href = window.location.origin + "/create-account/register";
                                function weightedRandom(min, max) {
                                    return (Math.round(max / (Math.random() * max + min)));
                                }

                                function isOdd(num) { return (num % 2); }

                                let oddcount = 0
                                let evencount = 0
                                let variant = sessionStorage.getItem("variant");
                                let number = 0
                                for (let i = 0; i < 1; i++) {
                                    number = weightedRandom(1, 3)
                                    if (isOdd(number) || variant === "b") {
                                        oddcount++;
                                        location.href = window.location.origin + "/create-account/register";
                                    } else {
                                        evencount++;
                                        location.href = window.location.origin + "/create-account/details";
                                    }
                                }

                                $submit.addClass('disabled processing');
                            }


                            console.log(data.ErrorMessage);
                            if (data.ErrorMessage !== null) {
                                //console.log($(given_name).data('fieldname'));

                                if ($(given_name).data('fieldname') === data.Fieldname) {
                                    $(given_name).show();
                                } else {
                                    $(given_name).hide();
                                }
                                if ($(sur_name).data('fieldname') === data.Fieldname) {
                                    $(sur_name).show();
                                } else {
                                    $(sur_name).hide();
                                }
                                if ($(Password_fc).data('fieldname') === data.Fieldname) {
                                    $(Password_fc).show();
                                } else {
                                    $(Password_fc).hide();
                                }
                                if ($(user_email).data('fieldname') === data.Fieldname) {
                                    $(user_email).show();
                                } else {
                                    $(user_email).hide();
                                }
                                window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                                    scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                                }, 100);
                                $submit.removeClass('disabled processing');
                                formValidation.api[$registerEmailForm.data('id')].events.formPost = null;
                                return false;
                            }
                            window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                                scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                            }, 100);
                            $submit.removeClass('disabled processing');
                            formValidation.api[$registerEmailForm.data('id')].events.formPost = null;

                        },
                        error: function () {
                            $('#dvMain').hide();
                            $('#dvAlreadyRegisteredsMessage').hide();
                            $('#dvSuccessMessage').hide();
                            $('#dvErrorsMessage').show();
                            window.location.href = window.location.href + "#fail";
                            $submit.removeClass('disabled processing');
                            formValidation.api[$registerEmailForm.data('id')].events.formPost = null;
                            window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                                scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                            }, 100);

                        }
                    });
            } else {
                //CD-9798 Part 2 for retaining the values in the create-account registration form
                if ($password != null) {
                    $('#password1').val($password);
                }
                if ($confirmPassword != null) {
                    $('#password2').val($confirmPassword);
                }

                //CD-9263
                if (typeof $('.errors .error').first().offset() !== 'undefined') {
                    $('html, body').animate({
                        scrollTop: $('.errors .error').first().offset().top - (75)
                    }, 150);

                    var scrollUp = 0;
                    if ($('.errors .error').first().hasClass('year') || $('.errors .error').first().hasClass('month') || $('.errors .error').first().hasClass('day')) {
                        $('html, body').animate({
                            scrollTop: $('.errors .error').first().offset().top - (140)
                        }, 150);
                    }
                }
                // Start-CD-2549
                var arr = [];
                $('div.form-field.cf.error').each(function (i, elem) {
                    if ($(elem).find('label').text()) {
                        arr.push($(elem).find('label').text());
                    }
                });
                utag.link({ "event_category": "create account", "event_name": "email check", "event_label": arr.join(',') });
            }
        }

        $theForm.on('submit', function (e) {
            e.preventDefault();
        });
    }

    function registerUserDetailsForm() {

        $("#sortcode").on({
            keydown: function (e) {
                if (e.which === 32)
                    return false;
            },
            change: function () {
                this.value = this.value.replace(/\s/g, "");
            }
        });

        $("#accountnumber").on({
            keydown: function (e) {
                if (e.which === 32)
                    return false;
            },
            change: function () {
                this.value = this.value.replace(/\s/g, "");
            }
        });

        $("#insurancepolicy").on({
            keydown: function (e) {
                if (e.which === 32)
                    return false;
            },
            change: function () {
                this.value = this.value.replace(/\s/g, "");
            }
        });

        var variant_value = "";
        var $registerUserDetailsForm = $(this),
            $theForm = $registerUserDetailsForm.find('#register-user'),
            $submit = $theForm.find('.full-submit'),
            $password,
            $confirmPassword,
            opt_chosen = 1,
            opt_value;


        /*CD-9798 Part1 Value capturing from inputs*/
        $('#password1').on('input', function () {
            $password = $('#password1').val();
        });
        $('#password2').on('input', function () {
            $confirmPassword = $('#password2').val();
        });

        /* LBG Create Account Options CD-11091 Start*/
        $('.AAMembership').hide();
        $('.radio-field:first-child > .AAMembership ').show();
        $("#options1").find('input[type="text"]').removeAttr('disabled');
        $("input[name$='Fields.MembershipSelection.Value']").click(function () {

            opt_chosen = $(this).val();

            $(".AAMembership").hide();
            $("#options" + opt_chosen).show();
            $("#options" + opt_chosen).parent('.radio-card').addClass('selected').siblings().removeClass('selected');
            $("#options" + opt_chosen).find('input[type="text"]').prop('disabled', false);
            $("#options" + opt_chosen).parent().siblings().find('input[type="text"]').prop('disabled', true);
        });
        /* LBG Create Account Options CD-11091 End */

        formValidation.api[$registerUserDetailsForm.data('id')].events.full = function (valid) {
            if (formValidation.api[$registerUserDetailsForm.data('id')].events.formPost) return;

            if (valid) {
                $submit.addClass('disabled processing');

                /*LLOYDS Create Account Analytics  */
                if (opt_chosen == 1) {
                    opt_value = "AAPersonal";
                    variant_value = "Variant A";
                } else if (opt_chosen == 2) {
                    opt_value = "Bank";
                    variant_value = "Variant A";
                } else if (opt_chosen == 3) {
                    opt_value = "Insurance";
                    variant_value = "Variant A";
                } else {
                    opt_value = "null";
                    variant_value = "Variant B";
                }
                /*LLOYDS Create Account Analytics  */

                /*Email from cookies from create-account/landing */
                function getCookie(name) {
                    var value = "; " + document.cookie;
                    var parts = value.split("; " + name + "=");
                    if (parts.length == 2) return parts.pop().split(";").shift();
                }

                var userName = getCookie('aa-state');
                var splitUsername = userName.split("&");
                var userEmail = splitUsername[0].split("=");
                var email = userEmail[1];

                var hiddenEmail = $('#Fields_Email_Value').val();
                if (email === null && hiddenEmail !== null) //added if field is set to hidden
                {
                    email = hiddenEmail;
                }

                formValidation.api[$registerUserDetailsForm.data('id')].events.formPost =
                    $.ajax({
                        type: 'POST',
                        url: '/cms/ajax/fragment/UniversalAccount/RegisterUserDetails',
                        dataType: 'json',
                        data: $theForm.serialize().replace(/%0D%0A/g, '%2C+'), // remove line breaks causing server errors
                        success: function (data) {
                            var given_name = $('.fc-err-msg.givenName'),
                                sur_name = $('.fc-err-msg.SurName'),
                                Password_fc = $('.fc-err-msg.Password');

                            if (data.Token === null && data.IsOkay === false) {
                                $('#dvMain').show();
                                $('#dvAlreadyRegisteredsMessage').hide();
                                $('#dvSuccessMessage').hide();
                                $('#dvErrorsMessage').hide();
                            } else {
                                utag.link({ "event_category": "create account", "event_action": "Check Inbox", "userType": opt_value, "test_variant": variant_value });
                                window.location.href = window.location.origin + "/create-account/check-inbox";
                            }
                            console.log(data.ErrorMessage);
                            if (data.ErrorMessage !== null) {
                                if ($(given_name).data('fieldname') === data.Fieldname) {
                                    $(given_name).show();
                                } else {
                                    $(given_name).hide();
                                }
                                if ($(sur_name).data('fieldname') === data.Fieldname) {
                                    $(sur_name).show();
                                } else {
                                    $(sur_name).hide();
                                }
                                if ($(Password_fc).data('fieldname') === data.Fieldname) {
                                    $(Password_fc).show();
                                } else {
                                    $(Password_fc).hide();
                                }
                                if ($(user_email).data('fieldname') === data.Fieldname) {
                                    $(user_email).show();
                                } else {
                                    $(user_email).hide();
                                }
                                window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                                    scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                                }, 100);
                                $submit.removeClass('disabled processing');
                                formValidation.api[$registerUserDetailsForm.data('id')].events.formPost = null;
                                return false;
                            }
                            window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                                scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                            }, 100);
                            $submit.removeClass('disabled processing');
                            formValidation.api[$registerUserDetailsForm.data('id')].events.formPost = null;

                        },
                        error: function () {
                            $('#dvMain').hide();
                            $('#dvAlreadyRegisteredsMessage').hide();
                            $('#dvSuccessMessage').hide();
                            $('#dvErrorsMessage').show();
                            window.location.href = window.location.href + "#fail";
                            $submit.removeClass('disabled processing');
                            formValidation.api[$registerUserDetailsForm.data('id')].events.formPost = null;
                            window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                                scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                            }, 100);

                        }
                    });
            } else {
                //CD-9798 Part 2 for retaining the values in the create-account registration form
                if ($password != null) {
                    $('#password1').val($password);
                }
                if ($confirmPassword != null) {
                    $('#password2').val($confirmPassword);
                }

                //CD-9263
                if (typeof $('.errors .error').first().offset() !== 'undefined') {
                    $('html, body').animate({
                        scrollTop: $('.errors .error').first().offset().top - (75)
                    }, 150);

                    var scrollUp = 0;
                    if ($('.errors .error').first().hasClass('year') || $('.errors .error').first().hasClass('month') || $('.errors .error').first().hasClass('day')) {
                        $('html, body').animate({
                            scrollTop: $('.errors .error').first().offset().top - (140)
                        }, 150);
                    }
                }
                // Start-CD-2549
                var arr = [];
                $('div.form-field.cf.error').each(function (i, elem) {
                    if ($(elem).find('label').text()) {
                        arr.push($(elem).find('label').text());
                    }
                });
                // End-CD-2549
                utag.link({ "event_category": "create account", "event_name": "email check", "event_label": arr.join(',') });
            }
        }

        $theForm.on('submit', function (e) {
            e.preventDefault();
        });
    }


    //new account association
    function accountAssociationForm() {

        var $accountAssociationForm = $(this),
            $theAssociationForm = $accountAssociationForm.find('#account-association'),
            $submit = $theAssociationForm.find('.full-submit');

        $('.AAMembership').hide();
        $("#options1").find('input[type="text"]').removeAttr('disabled');
        $(".radio-card").find('span').removeClass('checked');
        $(".radio-card").find('label').removeClass('checked');

        if ($('#membership').val() != "") {
            $(".AAMembership").hide();
            $("#options1").parent().find('span').addClass('checked');
            $("#options1").parent().find('label').addClass('checked');
            $("#options" + 1).show();
            $("#options" + 1).parent('.radio-card').addClass('selected').siblings().removeClass('selected');
            $("#options" + 1).find('input[type="text"]').prop('disabled', false);
            $("#options" + 1).parent().siblings().find('input[type="text"]').prop('disabled', true);
        }

        if ($('#sortcode').val() != "") {
            $(".AAMembership").hide();
            $("#options2").parent().find('span').addClass('checked');
            $("#options2").parent().find('label').addClass('checked');
            $("#options" + 2).show();
            $("#options" + 2).parent('.radio-card').addClass('selected').siblings().removeClass('selected');
            $("#options" + 2).find('input[type="text"]').prop('disabled', false);
            $("#options" + 2).parent().siblings().find('input[type="text"]').prop('disabled', true);
        }

        if ($('#insurancepolicy').val() != "") {
            $(".AAMembership").hide();
            $("#options3").parent().find('span').addClass('checked');
            $("#options3").parent().find('label').addClass('checked');
            $("#options" + 3).show();
            $("#options" + 3).parent('.radio-card').addClass('selected').siblings().removeClass('selected');
            $("#options" + 3).find('input[type="text"]').prop('disabled', false);
            $("#options" + 3).parent().siblings().find('input[type="text"]').prop('disabled', true);
        }
        $("input[data-type-radio='membership']").click(function () {
            opt_chosen = $(this).val();
            if (opt_chosen == 1) {
                $("#options1").parent().find('span').addClass('checked');
            }
            $(".AAMembership").hide();
            $("#options" + opt_chosen).show();
            $("#options" + opt_chosen).parent('.radio-card').addClass('selected').siblings().removeClass('selected');
            $("#options" + opt_chosen).find('input[type="text"]').prop('disabled', false);
            $("#options" + opt_chosen).parent().siblings().find('input[type="text"]').prop('disabled', true);
        });

        var pnumber;
        var forgerockId;
        $.ajax({
            type: 'POST',
            url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
            dataType: 'JSON',
            success: function (data) {
                if (data !== null) {
                    pnumber = $('.member-number').val();
                    forgerockId = data;
                }
            }
        });

        formValidation.api[$accountAssociationForm.data('id')].events.full = function (valid) {
            if (formValidation.api[$accountAssociationForm.data('id')].events.formPost) return;
            var policyNumberEdit = $('#dvMain #membership').val();
            var policyNumberOld = $('#dvMainOld #membership').val();
            if (policyNumberOld !== policyNumberEdit && policyNumberEdit === "") {
                $('#hiddenPolicyNumberAfterEdit').val(policyNumberOld);
            } else {
                $('#hiddenPolicyNumberAfterEdit').val(policyNumberEdit);
            }

            if (valid) {
                //debugger;
                $submit.addClass('disabled processing');
                //UIDA-721
                $("#loader").stop().fadeIn(300);
                window.aa.salesJourneyApp.cache.$main.addClass('loading');
                formValidation.api[$accountAssociationForm.data('id')].events.formPost =
                    $.ajax({
                        type: 'POST',
                        url: '/cms/ajax/fragment/AssociateAccount/GetAssociateAccountViewModel',
                        dataType: 'html',
                        data: $theAssociationForm.serialize().replace(/%0D%0A/g, '%2C+'), // remove line breaks causing server errors
                        success: function (data) {
                            $submit.removeClass('disabled processing');
                            setTimeout(function () {
                                if ($("#loader")) {
                                    $("#loader").stop().fadeOut(300);
                                    window.aa.salesJourneyApp.cache.$main.removeClass('loading');
                                }
                            }, 700);
                            window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                                scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                            }, 150);

                            formValidation.api[$accountAssociationForm.data('id')].events.formPost = null;
                            var hostname = window.location.origin;

                            if (data.indexOf('flagIsVehiclePolicy') >= 0) {
                                window.location.href = hostname + '/create-account/your-vehicle';
                            }
                            else if (data.indexOf('flagAlreadyAssociated') <= 0 && data.indexOf('flagEditAssociation') <= 0 && data.indexOf('flagVrnEntry') <= 0 && data.indexOf('flagPushToCall') <= 0) {
                                utag.link({ "event_category": "universal access", "event_action ": "association status", "event_label": "successful", "interaction_name": "/association : association status - success" });
                                window.location.href = hostname + '/products/' + '#successassoc';
                            } else if (data.indexOf('flagAlreadyAssociated') >= 0 && data.indexOf('flagEditAssociation') <= 0 && data.indexOf('flagVrnEntry') <= 0 && data.indexOf('flagPushToCall') <= 0) {
                                setAssociationUrlBack();

                                //hide UI for mobile apps
                                var queryString = window.location.search;
                                const urlParams = new URLSearchParams(queryString);
                                const mobileapps = urlParams.get('mobileapps');
                                window.location.href = hostname + '/create-account/your-products' + '#alreadyassociated';
                                $('#dvMain').hide();
                                $('#dvMainOld').hide();
                                if (mobileapps == 'true') {
                                    $('#dvAlreadyAssociated').hide();
                                }
                                else {
                                    $('#dvAlreadyAssociated').show();
                                }

                                $('#dvAlreadyAssociated').html(data);
                                utag.view({ "site_section": "Your account", "page_name": "/associateaccount/customer_already_registered", "error_message": "customer already registered, forgerock_ID:" + forgerockId, "forgerock_ID": forgerockId, "user_ID": pnumber });

                            } else if (data.indexOf('flagVrnEntry') >= 0 && data.indexOf('flagAlreadyAssociated') <= 0 && data.indexOf('flagEditAssociation') <= 0 && data.indexOf('flagPushToCall') <= 0) {
                                window.location.href = hostname + '/create-account/your-products';

                                $('#dvMain').hide();
                                $('#dvMainOld').hide();
                                $('#dvAlreadyAssociated').hide();
                                $('#dvDetails').hide();
                                $('#dvVrnEntry').show();
                                utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/enter_number_plate, forgerockId:" + forgerockId, "forgerockID": forgerockId, "user_ID": pnumber });
                            } else if (data.indexOf('flagVrnEntry') <= 0 && data.indexOf('flagAlreadyAssociated') <= 0 && data.indexOf('flagEditAssociation') <= 0 && data.indexOf('flagPushToCall') >= 0) {
                                window.location.href = hostname + '/create-account/your-products';
                                $('#dvMain').hide();
                                $('#dvMainOld').hide();
                                $('#dvAlreadyAssociated').hide();
                                $('#dvDetails').hide();
                                $('#dvVrnEntry').hide();
                                $('#dvPushTocall').show();
                                utag.view({ "site_section": "Your account", "page_name": "/account/details_not_found", "error_message": "customer details not found - no details, forgerock_ID:" + forgerockId, "forgerock_ID": forgerockId, "user_ID": pnumber });
                                window.location.href = window.location.href + '#associationfail';
                            } else {
                                $('#dvDetails').hide();
                                $('#dvAlreadyAssociated').hide();
                                $('#dvMainOld').hide();
                                $('#dvMain').show();
                                $(".needMoreInfo").hide();
                                $(".editDetails").show();
                                var insuranceNumber = $('.member-number1').val();
                                var opt_chosen = $("input[data-type-radio='membership']").val();
                                //opt_chosen 1 is for aa membership radio button selection
                                if (opt_chosen == 1) {
                                    $(".aaMembershipError").show();
                                    $(".aaBankError").hide();
                                    $(".aaInsuranceError").hide();
                                    $(".cdlInsuranceError").hide();
                                    $(".chaseBankInsuranceError").hide();
                                }
                                //opt_chosen 2 is for bank account radio button selection
                                if (opt_chosen == 2) {
                                    $(".aaMembershipError").hide();
                                    $(".aaBankError").show();
                                    $(".aaInsuranceError").hide();
                                    $(".cdlInsuranceError").hide();
                                    $(".chaseBankInsuranceError").hide();
                                }
                                //opt_chosen 3 is for insurance selection, XPC, HC is for CDL policies radio button selection
                                if (opt_chosen == 3 && insuranceNumber != "") {
                                    $(".aaMembershipError").hide();
                                    $(".aaBankError").hide();
                                    $(".aaInsuranceError").hide();
                                    $(".cdlInsuranceError").hide();
                                    $(".chaseBankInsuranceError").hide();

                                    if (insuranceNumber.slice(0, 3) === "XPC" || insuranceNumber.slice(0, 2) === "HC") {
                                        $(".cdlInsuranceError").show();
                                    }
                                    if (insuranceNumber.slice(0, 2).toLowerCase() === "ch") {
                                        $(".chaseBankInsuranceError").show();
                                    }
                                    else {
                                        $(".aaInsuranceError").show();
                                    }
                                }

                                utag.view({ "site_section": "Your account", "page_name": "/associateaccount/edit_details", "error_message": "customer details not found – edit_details, forgerock_ID:" + forgerockId, "forgerock_ID": forgerockId, "user_ID": pnumber });
                                window.location.href = hostname + '/create-account/your-products';
                            }
                        },
                        error: function () {
                            $submit.removeClass('disabled processing');
                            formValidation.api[$accountAssociationForm.data('id')].events.formPost = null;
                            //UIDA-721
                            setTimeout(function () {
                                if ($("#loader")) {
                                    $("#loader").stop().fadeOut(300);
                                    window.aa.salesJourneyApp.cache.$main.removeClass('loading');
                                }
                            }, 700);
                            window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                                scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                            }, 150);
                        }
                    });
            } else {

                //CD-9263
                if (typeof $('.errors .error').first().offset() !== 'undefined') {
                    $('html, body').animate({
                        scrollTop: $('.errors .error').first().offset().top - (75)
                    }, 150);

                    var scrollUp = 0;
                    if ($('.errors .error').first().hasClass('year') || $('.errors .error').first().hasClass('month') || $('.errors .error').first().hasClass('day')) {
                        $('html, body').animate({
                            scrollTop: $('.errors .error').first().offset().top - (140)
                        }, 150);
                    }
                }
                //CD-11003 Setting error forEdit Details old
                if ($('.setError').css('display') == 'block') {
                    // true
                    $('.month').addClass("error");
                    $('.day').addClass("error");
                }
                //Cd-11003 Setting error for Edit Details new
                if ($('.setError1').css('display') == 'block') {
                    // true
                    $('.month').addClass("error");
                    $('.day').addClass("error");
                }
            }
        };

        $theAssociationForm.on('submit', function (e) {
            e.preventDefault();
        });
    }
    //end

    //VRN Check
    function vrnCheckForm() {

        var vrnCheckForm = $(this),
            $thevrnCheckForm = vrnCheckForm.find('#vrn-check'),
            $submit = $thevrnCheckForm.find('.full-submit');

        formValidation.api[vrnCheckForm.data('id')].events.full = function (valid) {
            if (formValidation.api[vrnCheckForm.data('id')].events.formPost) return;

            if (valid) {
                $submit.addClass('disabled processing');
                var vehicleNumber = $('#txtVehicleNumber').val();
                formValidation.api[vrnCheckForm.data('id')].events.formPost =
                    $.ajax({
                        type: 'POST',
                        url: '/cms/ajax/fragment/AssociateAccount/GetVehicleDetails',
                        dataType: 'JSON',
                        data: { VehicleNumber: vehicleNumber },
                        success: function (result) {
                            if (result.isVehicledetailsFound) {
                                $('#dvVrnEntry').hide();
                                $('#dvVehicleDetails').show();
                                $('#vehicleColor').text(result.Vehicle.Color);
                                $('#vehcileMake').text(result.Vehicle.Make);
                                $('#vehicleModel').text(result.Vehicle.Model);
                                $('#hiddenVehicleNumber').val(result.VehicleNumber);
                                $('#hiddenIsVehicleMatching').val(result.IsVehicleMatchingInRes);
                                $.ajax({
                                    type: 'POST',
                                    url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
                                    dataType: 'JSON',
                                    success: function (data) {
                                        if (data !== null) {
                                            var pnumber = $('.member-number').val();
                                            utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/validate_car_details, forgerock_ID:" + data, "forgerock_ID": data, "user_ID": pnumber });
                                        }
                                    }
                                });
                            } else if (!result.isVehicledetailsFound && result.IsVehicleMatchingInRes) {
                                $('#dvHaveMembership').show();
                                utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/mph_question" });
                                $('#dvVrnEntry').hide();
                                $('#dvVehicleNotFound').hide();
                                $('#dvVehicleDetails').hide();
                            } else {
                                $('#dvVrnEntry').hide();
                                $('#dvVehicleNotFound').show();
                                $.ajax({
                                    type: 'POST',
                                    url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
                                    dataType: 'JSON',
                                    success: function (data) {
                                        if (data !== null) {
                                            var pnumber = $('.member-number').val();
                                            utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/validate_plate_details, forgerock_ID:" + data, "forgerock_ID": data, "user_ID": pnumber });
                                        }
                                    }
                                });
                                $('#vehicleNumber').text(result.VehicleNumber);
                                $('#hiddenVehicleNumber').val(result.VehicleNumber);
                            }
                            $submit.removeClass('disabled processing');
                            formValidation.api[vrnCheckForm.data('id')].events.formPost = null;

                        },
                        error: function () {
                            $submit.removeClass('disabled processing');
                            formValidation.api[vrnCheckForm.data('id')].events.formPost = null;

                        }
                    });
            }
        };

        $thevrnCheckForm.on('submit', function (e) {
            e.preventDefault();
        });

        $("#txtVehicleNumber").keypress(function (e, evt) {
            e.stopImmediatePropagation();
            var key = document.all ? key = e.keyCode : key = e.which;
            if (e.which === 8 || e.which === 0) {
                return true;
            }
            if (key === 32) {
                return false;
            }
            return ((key > 64 && key < 91) || (key > 96 && key < 123) || (key >= 48 && key <= 57));

        });
    }
    //end

    // mancon form
    function manconForm() {

        var $manconForm = $(this),
            $theForm = $manconForm.find('form'),
            $manNumberInput = $manconForm.find('.form-field.info-field input[type="text"]');

        $manNumberInput.focus(function () {
            if ($(this).val() === '') {
                $(this).val('MAN');
            }
        });

        formValidation.api[$manconForm.data('id')].events.full = function (valid) {
            var manufacturerName,
                manNumber,
                postcode;

            if (valid === true) {
                manufacturerName = $manconForm.find('input[name="manufacturer"]').val();
                manNumber = $manNumberInput.val();
                postcode = $manconForm.find('.form-field.postcode input[type="text"]').val();

                $theForm.find('.full-submit').addClass('disabled processing');

                $.ajax({
                    type: 'GET',
                    url: '/cms/ajax/api/mancon/validate?manufacturer=' + manufacturerName + '&manNumber=' + manNumber + '&postcode=' + postcode,
                    success: function (data) {
                        if (data.ServiceResponse === 'Success') {
                            window.location = data.JourneyUri;
                        } else {
                            $theForm.find('.service-error-message').text(data.ValidationError).show();
                            $theForm.find('.service-error-failed').hide();
                            $theForm.find('.full-submit').removeClass('disabled processing');
                        }
                    },
                    error: function () {
                        $theForm.find('.service-error-failed').show();
                        $theForm.find('.service-error-message').hide();
                        $theForm.find('.full-submit').removeClass('disabled processing');
                    }
                });
            }
        }

        $theForm.on('submit', function (e) {
            e.preventDefault();
        });
    }

    // eligibility check
    function eligibilityCheck() {

        var $eligibilityForm = $(this),
            $inputs = $eligibilityForm.find('input,textarea'),
            $checkbox = $eligibilityForm.find('input[type="checkbox"]'),
            $submitBtn = $eligibilityForm.find('input[type="submit"]'),
            $membershipInputField = $eligibilityForm.find('input[type="text"]'),
            $membershipInputFieldValue = $membershipInputField.val().replace(/\s/g, ''),
            $errorMessage = $eligibilityForm.find('.error-message'),
            $memEmptyErrMsg = $eligibilityForm.find('#errorMessageEmpty'),
            $memInvalidErrMsg = $eligibilityForm.find('#errorMessageInvalid'),
            $membershipDiv = $eligibilityForm.find('.field.information'),
            $memberformField = $eligibilityForm.find(".form-field"),
            $membPrepopulation = document.getElementById('prePolutionForm'),
            $membershipTc = $eligibilityForm.find('#fs-terms-cond'),
            $memberShipRegex = /^(((635601)\d{10})|((6356 01)\d{2}\s\d{4}\s\d{4})\d{16})$/,
            linkValue = $eligibilityForm.find('.link').val(),
            $aggMembershipDiv = $eligibilityForm.find('.membership-toggle');

        $eligibilityForm.on('click', '[type="radio"], [type="checkbox"]', function () {
            $submitBtn.prop('disabled', false);
            if ($checkbox.is(':not(:checked)')) {
                $membershipTc.css("display", 'block');
            } else {
                $membershipTc.css("display", 'none');
            }
        });

        //Remove padding for checkbox div when input field is hidden
        if ($memberformField.hasClass("hidden"))
            $('.fs-checkbox').css('padding-top', '0');

        //Loans Eligibility Prepopulation Flow (HDD Token)
        $('#membershipButtonPost').click(function (event) {
            event.preventDefault();
            fsMembershipCheck();
        });

        //On Input Focus remove error messages
        $membershipInputField.focusin(function () {
            $membershipInputField.removeClass('errorInput');
            $membershipDiv.removeClass('errorDiv-input');
            $memInvalidErrMsg.css("display", "none");
            $memEmptyErrMsg.css("display", "none");
            $membershipTc.css("display", "none");
        });

        //Loans Eligibility Default Flow
        $submitBtn.on('click', function (e) {
            e.preventDefault();
            fsMembershipCheck(); //Validate Membership Number

            var dataToSend = serialise.jQueryData($eligibilityForm, 'input');
            dataToSend.membershipNumber = dataToSend.membershipNumber.replace(/\s/g, '');
            if ($('.loans-calculator.newVersion').length > 0 && (!!$aggMembershipDiv.attr('style') == true ? $aggMembershipDiv.attr('style').indexOf('none') > 0 : false)) {
                dataToSend.variant = '2';
            }
            if (aa.helpers.cache.cachedElements.$main.find('.user-feedback-form').hasClass('active')) {
                return;
            }
            $.ajax({
                type: 'POST',
                url: '/cms/ajax/api/eligibility/validate?' + serialise.obj(dataToSend) + '',
                dataType: 'json'
            }).done(function (response) {

                var validationPassed = response.IsValidationPassed,
                    checkboxChecked = response.IsCheckboxChecked,
                    membershipCorrect = response.IsMembershipNumberCorrect,
                    variant = dataToSend.variant,
                    valid = true;

                switch (variant) {
                    case '1':
                        valid = validationPassed === true && checkboxChecked === false && (membershipCorrect === false || membershipCorrect === null);
                        break;
                    case '2':
                        valid = validationPassed === true && checkboxChecked === true && (membershipCorrect === false || membershipCorrect === null);
                        break;
                    case '3':
                        valid = validationPassed === true && checkboxChecked === true && membershipCorrect === true;
                        break;
                    default:
                        valid = validationPassed === false && checkboxChecked === false && membershipCorrect === false;
                        break;
                }

                if (valid) {
                    $errorMessage.hide();
                    if ($('.loans-calculator.newVersion').length > 0) {
                        var newLLinkVal = $(".link").val();
                        window.location = decodeURIComponent(newLLinkVal);
                    }
                    else {
                        window.location = decodeURIComponent(linkValue);
                    }
                } else {
                    $errorMessage.show();
                    $submitBtn.removeClass('processing');
                }

            }).fail(function () {
                $eligibilityForm.find('.wrapper').html('<h5>' + $errorMessage.data('defaultmessage') + '</h5>');
            });
        });

        //Check Membership Validation for eligiblity check (Loans)
        function fsMembershipCheck() {
            $membershipValue = $membershipInputField.val().replace(/\s/g, '');
            if ($membershipValue != "") {
                $membershipInputField.removeClass('errorInput');
                $membershipDiv.removeClass('errorDiv-input');
                $membershipValueTestResult = $memberShipRegex.test($membershipValue);
                if ($membershipValueTestResult) {

                    // prepFunction();
                    $checkbox.removeAttr('name');
                    if ($membPrepopulation && $checkbox.is(':checked'))
                        $membPrepopulation.submit();

                } else {
                    $membershipInputField.addClass('errorInput');
                    $membershipDiv.addClass('errorDiv-input');
                    $memInvalidErrMsg.css("display", "block");
                }
            } else {
                MembershipRegexResult = false;
                $membershipInputField.addClass('errorInput');
                $membershipDiv.addClass('errorDiv-input');
                $memEmptyErrMsg.css("display", "block");

                var hiddenMemFormFieldCheck = $memberformField.hasClass("hidden");
                if ($aggMembershipDiv.length > 0) {
                    if (!!$aggMembershipDiv.attr('style') == true ? $aggMembershipDiv.attr('style').indexOf('none') > 0 : false) {
                        hiddenMemFormFieldCheck = true;
                    } else {
                        hiddenMemFormFieldCheck = false;
                    }
                }

                if (hiddenMemFormFieldCheck && $checkbox.is(':checked') && $membPrepopulation)
                    $membPrepopulation.submit();
            }
            if ($checkbox.is(':not(:checked)')) {
                $membershipTc.css("display", 'block');
            } else {
                $membershipTc.css("display", 'none');
            }
        }
    }

    //CD-31864
    function loaneligibilityCheck() {

        var $loaneligibilityForm = $(this),
            $inputs = $loaneligibilityForm.find('input,textarea'),
            $checkbox = $loaneligibilityForm.find('input[type="checkbox"]'),
            $submitBtn = $loaneligibilityForm.find('input[type="submit"]'),
            $membershipInputField = $loaneligibilityForm.find('input[type="text"]'),
            $membershipInputFieldValue = $membershipInputField.val().replace(/\s/g, ''),
            $errorMessage = $loaneligibilityForm.find('.error-message'),
            $memEmptyErrMsg = $loaneligibilityForm.find('#loanErrorMessageEmpty'),
            $memInvalidErrMsg = $loaneligibilityForm.find('#loanErrorMessageInvalid'),
            $membershipDiv = $loaneligibilityForm.find('.field.information'),
            $memberformField = $loaneligibilityForm.find(".form-field"),
            $membPrepopulation = document.getElementById('prePopulationForm'),
            $membershipTc = $loaneligibilityForm.find('#fs-terms-condn'),
            $memberShipRegex = /^(((635601)\d{10})|((6356 01)\d{2}\s\d{4}\s\d{4})\d{16})$/,
            linkValue = $loaneligibilityForm.find('.link').val();

        $loaneligibilityForm.on('click', '[type="radio"], [type="checkbox"]', function () {
            $submitBtn.prop('disabled', false);
            if ($checkbox.is(':not(:checked)')) {
                $membershipTc.css("display", 'block');
            } else {
                $membershipTc.css("display", 'none');
            }
        });

        //Remove padding for checkbox div when input field is hidden
        if ($memberformField.hasClass("hidden"))
            $('.fs-checkbox').css('padding-top', '0');

        //Loans Eligibility Prepopulation Flow (HDD Token)
        $('#loanmembershipButtonPost').click(function (event) {
            event.preventDefault();
            fsMembershipCheck();
        });

        //On Input Focus remove error messages
        $membershipInputField.focusin(function () {
            $membershipInputField.removeClass('errorInput');
            $membershipDiv.removeClass('errorDiv-input');
            $memInvalidErrMsg.css("display", "none");
            $memEmptyErrMsg.css("display", "none");
            $membershipTc.css("display", "none");
        });

        //Loans Eligibility Default Flow
        $submitBtn.on('click', function (e) {
            e.preventDefault();
            fsMembershipCheck(); //Validate Membership Number

            var dataToSend = serialise.jQueryData($loaneligibilityForm, 'input');
            dataToSend.membershipNumber = dataToSend.membershipNumber.replace(/\s/g, '');
            if (aa.helpers.cache.cachedElements.$main.find('.user-feedback-form').hasClass('active')) {
                return;
            }
            $.ajax({
                type: 'POST',
                url: '/cms/ajax/api/eligibility/validate?' + serialise.obj(dataToSend) + '',
                dataType: 'json'
            }).done(function (response) {

                var validationPassed = response.IsValidationPassed,
                    checkboxChecked = response.IsCheckboxChecked,
                    membershipCorrect = response.IsMembershipNumberCorrect,
                    variant = dataToSend.variant,
                    valid = true;

                switch (variant) {
                    case '1':
                        valid = validationPassed === true && checkboxChecked === false && (membershipCorrect === false || membershipCorrect === null);
                        break;
                    case '2':
                        valid = validationPassed === true && checkboxChecked === true && (membershipCorrect === false || membershipCorrect === null);
                        break;
                    case '3':
                        valid = validationPassed === true && checkboxChecked === true && membershipCorrect === true;
                        break;
                    default:
                        valid = validationPassed === false && checkboxChecked === false && membershipCorrect === false;
                        break;
                }

                if (valid) {
                    $errorMessage.hide();
                    window.location = decodeURIComponent(linkValue);
                } else {
                    //$errorMessage.show();
                    $submitBtn.removeClass('processing');
                }

            }).fail(function () {
                $loaneligibilityForm.find('.wrapper').html('<h5>' + $errorMessage.data('defaultmessage') + '</h5>');
            });
        });

        //Check Membership Validation for eligiblity check (Loans)
        function fsMembershipCheck() {

            $membershipValue = $membershipInputField.val().replace(/\s/g, '');

            if ($membershipValue != "") {
                $membershipInputField.removeClass('errorInput');
                $membershipDiv.removeClass('errorDiv-input');
                $membershipValueTestResult = $memberShipRegex.test($membershipValue);

                if ($membershipValueTestResult) {

                    // prepFunction();
                    $checkbox.removeAttr('name');
                    if ($membPrepopulation && $checkbox.is(':checked'))
                        $membPrepopulation.submit();

                } else {
                    $membershipInputField.addClass('errorInput');
                    $membershipDiv.addClass('errorDiv-input');
                    $memInvalidErrMsg.css("display", "block");
                }
            } else {
                MembershipRegexResult = false;
                $membershipInputField.addClass('errorInput');
                $membershipDiv.addClass('errorDiv-input');
                $memEmptyErrMsg.css("display", "block");
                if ($('.sectionTwo').hasClass('hidden') && $checkbox.is(':checked') && $membPrepopulation)
                    $membPrepopulation.submit();
            }
            if ($checkbox.is(':not(:checked)')) {
                $membershipTc.css("display", 'block');
            } else {
                $membershipTc.css("display", 'none');
            }
        }
    }

    // Date of birth constructor function
    function DateOfBirth($form) {
        var day = parseInt($form.find('#day-number').val(), 10),
            month = parseInt($form.find('#month-number').val(), 10),
            year = parseInt($form.find('#year-number').val(), 10),
            date = new Date(year, month - 1, day),
            currentDate = new Date();

        this.fullDateOfBirth = $form.find('input[name="DateOfBirth"]').map(function () { return this.value; }).get().join('/');
        this.isValid = function () {
            return date.getFullYear() === year && date.getMonth() + 1 === month && date.getDate() === day && date <= currentDate;
        };
        this.isFutureDate = function () {
            return date > currentDate;
        };
        this.isLeapYear = function () {
            return date.getFullYear() === year && date.getMonth() + 1 === month && date.getDate() === day;
        };
    }

    // Date of birth validation rules
    function dateOfBirthEvents() {

        var $form = $(this),
            $dateofBirthField = $form.find('.dob-input'),
            $formField = $dateofBirthField.closest('.form-field'),
            $futureDateValidationText = $formField.find('[data-custom-validation="future"]'),
            $leapDateValidationText = $formField.find('[data-custom-validation="leapYear"]'),
            $dateOfBirthGroup = $form.find('.date-of-birth-group'),
            dob = new DateOfBirth($form);

        $dateofBirthField.on('change', function () {
            if ($dateofBirthField.closest('.dob-group').hasClass('error')) {
                $dateOfBirthGroup.addClass('error');

            } else {
                $dateOfBirthGroup.removeClass('error future-date-error leap-year-error');
            }
        });

        if (dob.isFutureDate()) {
            $futureDateValidationText.show();
            $dateOfBirthGroup.addClass('future-date-error');
            $form.submit(function (e) {
                e.preventDefault();
            });

        } else {
            $futureDateValidationText.hide();
            $dateOfBirthGroup.removeClass('future-date-error');
        }

        if (dob.isLeapYear()) {
            $leapDateValidationText.hide();
            $dateOfBirthGroup.removeClass('leap-year-error');

        } else {
            $leapDateValidationText.show();
            $dateOfBirthGroup.addClass('leap-year-error');
            $form.submit(function (e) {
                e.preventDefault();
            });
        }
    }

    // my aa account management
    function accountManagement() {

        var $accountManagementForm = $(this),
            $updatePasswordForm = window.aa.helpers.cache.cachedElements.$body.find('#update-password'),
            $associateAccountForm = window.aa.helpers.cache.cachedElements.$body.find('#associate-account'),
            $updateEmailAddressForm = window.aa.helpers.cache.cachedElements.$body.find('#update-email-address'),
            $strengthMetterContainer = $accountManagementForm.find('.strength-meter'),
            $newPasswordInput = $accountManagementForm.find('#new-password'),
            verdictWeak = $strengthMetterContainer.find('#strength-weak').val(),
            verdictGood = $strengthMetterContainer.find('#strength-good').val(),
            verdictStrong = $strengthMetterContainer.find('#strength-strong').val(),
            $firstName,
            $lastName;

        if ($('#update-password').length) {

            boot.loadScript('strength-meter.min.js', 'libs', function () {

                $newPasswordInput.strength({
                    mainTemplate: '<div class="password-checker-container" data-stylish-form="true">{input}<span class="meter-container">{meter}</span></div>',
                    containerClass: 'password-meter',
                    showMeter: true,
                    showToggle: false,
                    meterClass: 'score-meter',
                    scoreBarClass: 'scorebar',
                    verdictTitles: [verdictWeak, verdictWeak, verdictWeak, verdictGood, verdictGood, verdictStrong],
                    verdictClasses: ['weak', 'weak', 'weak', 'good', 'good', 'strong']
                });

                $('.meter-container').appendTo($strengthMetterContainer);
                stylishForms.update();
            });

            $updatePasswordForm.find('input[type="submit"]').off('click').on('click', function (e) {

                var $submitButton = $(this),
                    $serviceFailedMessage = $updatePasswordForm.find('.service-error-failed'),
                    $serviceErrorMessage = $updatePasswordForm.find('.service-error-message'),
                    dto = serialise.jQueryData($updatePasswordForm, 'serialise-form');

                var queryString = window.location.search;

                e.preventDefault();
                $serviceFailedMessage.add($serviceErrorMessage).hide();
                formValidation.api[$updatePasswordForm.data('id')].validateForm();

                if ($updatePasswordForm.hasClass('errors') && $newPasswordInput.strength('verdict') < 3) {
                    return;

                } else {
                    $submitButton.prop('disabled', true).addClass('disabled processing');
                    window.aa.helpers.saveAccountForm('/cms/ajax/api/accountsettings/updatepassword' + queryString, $updatePasswordForm, dto, $serviceErrorMessage, $serviceFailedMessage, $submitButton);
                }
            });
        }

        if ($('#update-email-address').length) {

            $updateEmailAddressForm.find('input[type="submit"]').off('click').on('click', function (e) {

                var $submitButton = $(this),
                    $serviceFailedMessage = $updateEmailAddressForm.find('.service-error-failed'),
                    $serviceErrorMessage = $updateEmailAddressForm.find('.service-error-message'),
                    dto = serialise.jQueryData($updateEmailAddressForm, 'serialise-form');

                var queryString = window.location.search;

                e.preventDefault();
                $serviceErrorMessage.add($serviceFailedMessage).hide();
                formValidation.api[$updateEmailAddressForm.data('id')].validateForm();
                
                if ($updateEmailAddressForm.hasClass('errors')) {
                    return;

                } else {
                    $submitButton.prop('disabled', true).addClass('disabled processing');
                    window.aa.helpers.saveAccountForm('/cms/ajax/api/AccountSettings/UpdateEmail' + queryString, $updateEmailAddressForm, dto, $serviceErrorMessage, $serviceFailedMessage, $submitButton);
                }
            });
        }

        if ($('#associate-account').length) {
            $firstName = $associateAccountForm.find('[name="FirstName"]');
            $lastName = $associateAccountForm.find('[name="LastName"]');

            // clear user name field values
            function clearField($input) {
                $input.val('');
            }

            function excapeFields() {
                var $input = $(this);

                $input.val($input.val().replace('&#39;', "'"));
            }

            $firstName.add($lastName).each(excapeFields);

            $associateAccountForm.find('input[type="submit"]').off('click').on('click', function (e) {

                var $submitButton = $associateAccountForm.find('input[type="submit"]'),
                    $serviceFailedMessage = $associateAccountForm.find('.service-error-failed'),
                    $serviceErrorMessage = $associateAccountForm.find('.service-error-message'),
                    dob = new DateOfBirth($accountManagementForm),
                    dataTransferObject;

                e.preventDefault();
                $serviceErrorMessage.add($serviceFailedMessage).hide();
                formValidation.api[$associateAccountForm.data('id')].validateForm();
                $accountManagementForm.each(dateOfBirthEvents);

                // valid date check
                if ($associateAccountForm.hasClass('errors') || !dob.isValid()) {
                    return;

                } else {
                    dataTransferObject = serialise.jQueryData($associateAccountForm, 'serialise-form');
                    dataTransferObject.DateOfBirth = dob.fullDateOfBirth;

                    $submitButton.prop('disabled', true).addClass('disabled processing');
                    window.aa.helpers.saveAccountForm('/cms/ajax/api/Registration/AssociateFrUserInCmd', $associateAccountForm, dataTransferObject, $serviceErrorMessage, $serviceFailedMessage, $submitButton);
                }
            });

            $firstName.add($lastName).off('click').on('click', function () {
                clearField($(this));
            });

            window.aa.helpers.cache.cachedElements.$document.on({
                keyup: function (e) {
                    if (e.which === 9 & (!$firstName.is(e.target) || !$lastName.is(e.target)) && ($firstName.has(e.target).length === 0 || $lastName.has(e.target).length === 0)) {
                        clearField($(e.target));
                    }
                }
            });
        }
    }

    // hospitality feedback form
    function sendFeedbackForm() {

        var $thisForm = $(this),
            $submit = $thisForm.find('.full-submit'),
            $results = $thisForm.closest('.accordion-content').find('.results'),
            $errorResult = $thisForm.find('.service-error-failed');

        function sendFeedback() {

            var formData = {
                Name: $thisForm.find('#Name').val(),
                Email: $thisForm.find('#Email').val(),
                CustomerMessage: $thisForm.find('#customer-message').val(),
                __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
            };

            $.ajax({
                method: 'POST',
                url: '/cms/ajax/api/hospitality/sendfeedback',
                data: formData
            }).done(function () {
                $thisForm.find('form').hide();
                $submit.removeClass('disabled processing');
                $results.show();
            }).fail(function () {
                $submit.removeClass('disabled processing');
                $errorResult.show();
            });
        }

        $submit.on('click', function (e) {
            e.preventDefault();
            $submit.addClass('disabled processing');
            $errorResult.hide();
            sendFeedback();
        });
    }

    // hospitality feedback form
    function sendFeedbackForm() {

        var $thisForm = $(this),
            $submit = $thisForm.find('.full-submit'),
            $results = $thisForm.closest('.accordion-content').find('.results'),
            $errorResult = $thisForm.find('.service-error-failed');

        function sendFeedback() {

            var formData = {
                Name: $thisForm.find('#Name').val(),
                Email: $thisForm.find('#Email').val(),
                CustomerMessage: $thisForm.find('#customer-message').val(),
                __RequestVerificationToken: $('input[name=__RequestVerificationToken]').val()
            };

            $.ajax({
                method: 'POST',
                url: '/cms/ajax/api/hospitality/sendfeedback',
                data: formData
            }).done(function () {
                $thisForm.find('form').hide();
                $submit.removeClass('disabled processing');
                $results.show();
            }).fail(function () {
                $submit.removeClass('disabled processing');
                $errorResult.show();
            });
        }

        $submit.on('click', function (e) {
            e.preventDefault();
            $submit.addClass('disabled processing');
            $errorResult.hide();
            sendFeedback();
        });
    }

    // user feedback form
    function userFeedbackForm() {

        var $form = $(this),
            $overlay = $('#nav-overlay'),
            formTimeout,
            formShown = false;

        // overwrite aria attribute
        $form.add($overlay).attr('aria-hidden', 'true');

        // reveal the form
        function revealForm() {
            if (!aa.helpers.cache.registerCookie.check('userFeedbackForm')) {
                formShown = true;
                aa.helpers.cache.cachedElements.$main.children().attr('aria-hidden', 'true');
                $form.add($overlay).attr('aria-hidden', 'false').addClass('active');
                aa.helpers.cache.registerCookie.write('userFeedbackForm', formShown, $form.data('expiry'));
            } else {
                hideForm();
            }
        }

        // hide the form
        function hideForm() {
            formShown = false;
            aa.helpers.cache.cachedElements.$main.children().attr('aria-hidden', 'false');
            $form.add($overlay).attr('aria-hidden', 'true').removeClass('active');
            aa.helpers.cache.cachedElements.$main.find('.user-feedback-view').add(aa.helpers.cache.cachedElements.$footer.find('.user-feedback-view')).removeClass('user-feedback-view');
        }

        // collect form data
        function sendFormData() {
            var dto = serialise.jQueryData($form, 'serialise-form');

            dto.QualitativeFeedbackQuestion = $form.find('.form-field.character-limit').find('label').text();

            $.ajax({
                method: 'POST',
                contentType: 'application/json',
                url: '/cms/ajax/api/UserFeedbackForm/SendFeedBack',
                data: JSON.stringify(dto)
            }).done(hideForm);
        }

        // add class to body if form exists on page
        aa.helpers.cache.cachedElements.$body.addClass('feedback-form');

        // display form after certain amount of time
        if ($form.data('on-time-has-elapsed')) {
            formTimeout = setTimeout(revealForm, ($form.data('delayed-time') * 1000));
        }

        // push data to browser history
        if (!aa.helpers.cache.registerCookie.check('userFeedbackForm') && $form.data('on-page-exit')) {
            aa.salesJourneyApp.helpers.pushDataToHistory('formShown', formShown);

            // if page-on-exit is selected, add relevant class to all anchors
            aa.helpers.cache.cachedElements.$main.find('a').add(aa.helpers.cache.cachedElements.$footer.find('a')).addClass('user-feedback-view');

            $(window).on('popstate', function () {

                clearTimeout(formTimeout);
                revealForm();
            });
        }

        // if a button with user-feedback-view class is found
        aa.helpers.cache.cachedElements.$main.find('.user-feedback-view').add(aa.helpers.cache.cachedElements.$footer.find('.user-feedback-view')).on('click', function (e) {
            // prevent redirect on first click
            if ($(this).hasClass('user-feedback-view')) {
                e.preventDefault();
            }

            clearTimeout(formTimeout);
            revealForm();
            formShown = false; // falsey to allow user to click browser back button
        });

        $form.find('.close').add($overlay).add($form.find('.text-button')).on('click', function (e) {
            e.preventDefault();
            clearTimeout(formTimeout);
            hideForm();
            if (formShown) {
                history.back(); // return to previous page
            }
        });

        // submit feedback form
        $form.find('.cta').find('input[type="submit"]').on('click', function (e) {
            e.preventDefault();
            sendFormData();
        });

    }


    //EBC Destination Checker
    function destinationCheckerEBC() {

        let $destinationCheckerForm = $(this),
            $destinationCheckerInput = $destinationCheckerForm.find('input[type="text"]#countryName'),
            $submitBtn = $destinationCheckerForm.find('input[type="submit"]'),
            $ebcCountrySearch = $destinationCheckerForm.parents('.ebc-coutry-search'),
            $ebcCountrySearchDiv = $ebcCountrySearch.find('#search'),
            $ebcCheckAnotherCountryLink = $ebcCountrySearch.find('.check-another-country'),
            $ebcSearchSuccessDiv = $ebcCountrySearch.find('#SearchPass'),
            $ebcSearchNotFoundDiv = $ebcCountrySearch.find('#SearchFail'),
            $ebcTabGroupCountryZones = $ebcSearchSuccessDiv.find('.tab-group-country ul.tabs-list'),
            $ebcTabCountryMapList = $ebcSearchSuccessDiv.find('.tab-coutry-map ul'),
            countryList,
            countryName;

        // Generic function to make text bold if name entered uppercase / lowercase using :contains selector
        $.expr[":"].contains = $.expr.createPseudo(function (arg) {
            return function (elem) {
                return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
            };
        });

        // Get list of countries for auto-complete on ready
        $.ajax({
            type: 'GET',
            url: '/cms/ajax/fragment/DestinationChecker/DestinationCheckerUniqueList',
            dataType: 'JSON',
        }).done(function (response) {
            countryList = response;
            $destinationCheckerInput.autocomplete({
                source: countryList,
                minLength: 2,
                autoFocus: true,
                appendTo: ".ebc-destination-checker .field"
            });
        }).fail(function (response) {
            console.log(response);
        });

        // Reset validations on focus-in event

        $destinationCheckerInput.on({
            focusin: function (e) {
                $(this).parents('.form-field').removeClass('hasError');
                $(this).parents('.form-field').find('.error-msges div').hide();
            },
            keyup: function (e) {
                $(this).trigger('click');
            },

        });

        let func = function () {
            $destinationCheckerInput.val($destinationCheckerInput.val().replace(/^[^a-zA-ZÜü]*/, ''));
        }
        $destinationCheckerInput.keyup(func).blur(func);

        //Search country and return if it is covered / not covered
        $submitBtn.on('click', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();

            countryName = $destinationCheckerInput.val().trimEnd();
            if (countryName == "") {
                $(this).parents('.form-field').addClass('hasError');
                $(this).parents('.form-field').find('.error-msges div').show();
                return;
            }
            $(this).addClass("disabled processing").attr('disabled', true);
            $.ajax({
                type: 'POST',
                url: '/cms/ajax/fragment/DestinationChecker/DestinationCheckerDisplayResult',
                dataType: 'json',
                data: { countryName: countryName }
            }).done(function (response) {
                if (response.Covered) {
                    let zonesList = "",
                        zones = response.Zone,
                        zoneIndex;

                    $ebcTabGroupCountryZones.find('li').hide();
                    for (let i = 0; i < zones.length; i++) {

                        if ((zones.length - i) === 1) {
                            if (zones.length === 1)
                                zonesList += response.Zone[i];
                            else {
                                zonesList = zonesList.replace(/,\s*$/, "");
                                zonesList += ' and ' + response.Zone[i];
                            }
                        }
                        else {
                            zonesList += response.Zone[i] + ', ';
                        }

                        $ebcTabGroupCountryZones.find("li[id='" + response.Zone[i] + "']").show();
                    }

                    $ebcSearchSuccessDiv.find('p:first span#country').empty();
                    $ebcSearchSuccessDiv.find('p:first span#zones').empty();
                    $ebcSearchSuccessDiv.find('p:first span#country').append(response.CountryName);
                    $ebcSearchSuccessDiv.find('p:first span#zones').append(zonesList);

                    zoneIndex = zones[0].split(" ");

                    $ebcCountrySearchDiv.hide();
                    $ebcTabGroupCountryZones.find('li').removeClass('active');
                    $ebcTabGroupCountryZones.find('li:nth-child(' + zoneIndex[1] + ')').addClass('active');

                    $ebcTabCountryMapList.find('li').removeClass('active');
                    $ebcTabCountryMapList.find('li:nth-child(' + zoneIndex[1] + ')').addClass('active');
                    $ebcTabCountryMapList.find('li ul li:contains(' + countryName + ')').addClass('highlighted');
                    $ebcSearchSuccessDiv.show();

                }
                else {
                    $ebcSearchNotFoundDiv.find('p:first span#country-uncovered').empty();
                    $ebcSearchNotFoundDiv.find('p:first span#country-uncovered').append(countryName);
                    $ebcSearchNotFoundDiv.show();
                    $ebcCountrySearchDiv.hide();

                }
                $destinationCheckerInput.val('');
                $submitBtn.removeClass("disabled processing").attr('disabled', false);

            }).fail(function () {
                $submitBtn.removeClass("disabled processing").attr('disabled', false);
            });
        });

        // Toggle Search box and Success / Unsuccess Search
        $ebcCheckAnotherCountryLink.on('click', function (e) {
            e.preventDefault();
            $ebcSearchSuccessDiv.hide();
            $ebcSearchNotFoundDiv.hide();
            $ebcTabCountryMapList.find('li ul li:contains(' + countryName + ')').removeClass('highlighted');
            $(this).parents($ebcCountrySearch).find($ebcCountrySearchDiv).show();
            window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                scrollTop: $ebcCountrySearch.first().offset().top - (75)
            }, 1000);
        });

    }

    // initialise each form field
    $formElements.find('.form-field').each(inputLabels);

    // initialise each form type
    $formElements.filter('.battery-form').each(batteryForm);
    $formElements.filter('.call-me-back-form').each(callMeBackForm);
    $formElements.filter('.mancon-form').each(manconForm);
    $formElements.filter('.account-management').each(accountManagement);
    $formElements.filter('.feedback-form').each(sendFeedbackForm);
    $('.terms-and-conditions').find($formElements).each(eligibilityCheck);
    $('.loan-eligibility-check').find($formElements).each(loaneligibilityCheck);    //CD-31864
    $formElements.filter('.user-feedback-form').each(userFeedbackForm);
    $formElements.filter('.registration-form').each(registerUserForm); //MB-406
    $formElements.filter('.registration-email').each(registerEmailForm);
    $formElements.filter('.registration-Userdetail').each(registerUserDetailsForm);
    $formElements.filter('.loan-payment-form').each(loanPaymentForm);

    $formElements.filter('.account-association').each(accountAssociationForm); //UIDA-561
    $formElements.filter('.account-association-details').each(accountAssociationDetailsForm);
    $formElements.filter('.vrn-check').each(vrnCheckForm); //UIDA-412
    $('.ebc-coutry-search').find($formElements).each(destinationCheckerEBC);

    $formElements.filter('.account-association-vehicle-details').each(accountAssociationVehicleDetailsForm);
}

function initWffmFormElements() {

    var $formElements = $(this),
        $inputs = $formElements.find('input, textarea'),
        $selectBox = $formElements.find('select'),
        $infoHelpBlock = $formElements.find('.help-block').not('.field-validation-error, .field-validation-valid');

    $infoHelpBlock.each(function () {
        $(this).hide().siblings('label.control-label').addClass('info-block');
    });

    $formElements.find('.info-block').on({
        click: function (e) {
            e.preventDefault();
            $(this).siblings('.help-block').not('.field-validation-error, .field-validation-valid').slideToggle();
        }
    });

    $inputs.on('keyup', function (e) {
        // if tab or shift keys are pressed, return
        if (e.which === 16 || e.which === 9 || e.which === 13) {
            return;
        }
    });

    $selectBox.on('click', function () {
        $(this).toggleClass('selected');
    });

    $inputs.filter('[type="checkbox"]').add($inputs.filter('[type="radio"]')).on('click', function () {

        var $checkBoxRadio = $(this);
        $checkBoxRadio.closest('label').parent('.checkbox').add($checkBoxRadio.closest('label')).toggleClass('checked');
        $checkBoxRadio.filter('[type="radio"]').closest('label').parent('.radio').addClass('checked');
        $checkBoxRadio.filter('[type="radio"]').closest('.radio').siblings().children('label').parent().removeClass('checked');
    });

    window.aa.helpers.cache.cachedElements.$document.on({
        click: function (e) {
            if (!$selectBox.is(e.target) && $selectBox.has(e.target).length === 0) {
                $selectBox.removeClass('selected');
            }
        }
    });
}

window.aa.helpers.cache.cachedElements.$document.ready(function () {
    if (typeof FormValidation !== 'undefined') {
        FormValidation.Manifest.ExtensionPath = '/Assets/scripts/roads/';
        FormValidation.Manifest.Externals.register('CustomValidationRules', 'custom-validation-rules.js');
        formValidation.init();
        $('.form-module, .form-section').each(initFormElements);
    }

    $('.wffm-form-module').each(initWffmFormElements);

    setUrlBack();
});
$(document).find('#vehicleDetailsYes').on('click', function () {
    $('#dvVehicleDetails').hide();
    $('#dvVrnEntry').hide();
    if ($('#hiddenIsVehicleMatching').val() === "true") {
        $('#dvHaveMembership').show();
        $.ajax({
            type: 'POST',
            url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
            dataType: 'JSON',
            success: function (data) {
                if (data !== null) {
                    utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/policyholder_question, forgerock_ID:" + data });
                }
            }
        });
    }
    else {
        $('#dvVehicleNotCovered').show();
        window.location.href = window.location.href + '#vrnfail';
    }
});
$(document).find('#vehicleDetailsNo').on('click', function () {
    $('#dvVehicleDetails').hide();
    $('#dvVehicleNotFound').show();
    $.ajax({
        type: 'POST',
        url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
        dataType: 'JSON',
        success: function (data) {
            if (data !== null) {
                utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/validate_plate_details, forgerock_ID:" + data });
            }
        }
    });
    $('#vehicleNumber').text($('#hiddenVehicleNumber').val());
});
$(document).find('#vehicleNotFoundNo').on('click', function () {
    $('#dvVrnEntry').show();
    $.ajax({
        type: 'POST',
        url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
        dataType: 'JSON',
        success: function (data) {
            if (data !== null) {
                utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/enter_number_plate, forgerock_ID:" + data });
            }
        }
    });
    $('#dvVehicleNotFound').hide();
});
$(document).find('#vehicleNotFoundYes').on('click', function () {
    $('#dvVrnEntry').hide();
    $('#dvVehicleNotFound').hide();
    $('#dvVehicleNotCovered').show();
    $.ajax({
        type: 'POST',
        url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
        dataType: 'JSON',
        success: function (data) {
            if (data !== null) {
                utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/vehicle_not_covered", "error_message": "vehicle not covered, forgerock_ID:" + data });
            }
        }
    });
    window.location.href = window.location.href + '#vrnfail';
});

//CD-58182
$(document).find('.logout').on('click', function (e) {
    e.preventDefault();
    sessionStorage.clear();
    localStorage.removeItem("nonce");
    localStorage.removeItem("PKCE_verifier");
    window.location.href = e.target.getAttribute("href");
});

//CD-60406
if (location.search.indexOf("sc_trk=Logout") > -1) {
    sessionStorage.clear();
    localStorage.removeItem("nonce");
    localStorage.removeItem("PKCE_verifier");
}

//CD-21982
//Combined Function after Continue button Vehicle Beneficiary
$(document).find('.continue-yes-no').on('click', function () {
    if ($('#haveMembershipYes').is(':checked')) {
        $('#dvVrnEntry').hide();
        $('#dvHaveMembership').hide();
        $('#dvMain').show();
        $.ajax({
            type: 'POST',
            url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
            dataType: 'JSON',
            success: function (data) {
                if (data !== null) {
                    utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/vehicle_policyholder_not_found", "error_message": "vehicle policyholder not found, forgerock_ID:" + data, "event_category": "Vehicle Beneficiary", "event_name": "Policyholder check - continue button clicked", "event_label": "Yes" });
                }
            }
        });
    }
    if ($('#haveMembershipNo').is(':checked')) {
        $('#dvVrnEntry').hide();
        $('#dvHaveMembership').hide();
        $('#dvHaveMembershipNo').hide();
        $('#dvPostcodeEntry').show();
        utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/enter_postcode"});
        var tb1 = document.getElementById('HomePostcode1');
        var tb2 = document.getElementById('txtPostcode');
        tb2.value = tb1.value;
        $.ajax({
            type: 'POST',
            url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
            dataType: 'JSON',
            success: function (data) {
                if (data !== null) {
                    utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/create_vehicle_beneficiary, forgerock_ID:" + data, "event_category": "Vehicle Beneficiary", "event_name": "Policyholder check - continue button clicked", "event_label": "No" });
                }
            }
        });
    }
});

$('#btnFindYourAddress').on('click', function (e) {

    $('#btnFindYourAddress').addClass('disabled processing');
    $('#address-errmsgs').css('display', 'none');

    $('#dvVehicleDetails').hide();
    e.stopImmediatePropagation();

    var firstline = $(document).find('#txtFirstLineOfAddress').val();
    var postcode = $(document).find('#txtPostcode').val();
    var postcodeInitials = postcode.slice(0, 2);

    if (postcode === "") {
        $('#btnFindYourAddress').removeClass('disabled processing');
        $('#address-errmsgs').css('display', 'block');
        return false;
    }

    if (postcodeInitials.toLowerCase() === "im" || postcodeInitials.toLowerCase() === "je" || postcodeInitials.toLowerCase() === "gy") {
        $('#btnFindYourAddress').removeClass('disabled processing');
        $('#address-errmsgs').css('display', 'block');
        return false;
    }

    $.ajax({
        type: 'POST',
        url: '/cms/ajax/fragment/AssociateAccount/GetAddress',
        dataType: 'JSON',
        data: { Firstline: firstline, Postcode: postcode },
        success: function (data) {
            if (data.ViewModelData !== null) {
                $('#dvVrnEntry').hide();
                $('#dvHaveMembership').hide();
                $('#dvMain').hide();
                $('#dvHaveMembershipNo').hide();
                $('#dvPostcodeEntry').hide();
                $('#dvContactDetails').show();
                utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/select_address" });

                var addressList = data.ViewModelData.Addresses;
                if (addressList.Length == 0) {
                    $('#dvPostcodeEntry').show();
                    return false;
                }

                if (addressList.length > 1) {

                    var addresses = [];
                    var addressList = data.ViewModelData.Addresses;
                    if (addressList.length > 1) {
                        $('#single-address').hide();
                        $.each(addressList, function (key, address) {
                            if ((address.Line1.indexOf("FLAT ") != -1) || (address.Line1.indexOf("APARTMENT ") != -1))
                                dropDownOption = address.Line1 + ", " + address.Line2 + ", " + address.Town + ", " + address.PostCode;
                            else
                                dropDownOption = address.Line1 + ", " + address.Line2 + ", " + address.Town + ", " + address.PostCode;
                            addresses.push(' <option value="' + address.Line1 + ";" + address.Line2 + ";" + address.Town + ";" + address.County + ";" + address.PostCode + '">' + dropDownOption) + '</option>';

                        });
                        var multipleaddressvariable = $('#multiple-address');
                        var vbaddressvariable = $('#vbaddress');
                        renderOptions(multipleaddressvariable, vbaddressvariable, addresses);

                        function renderOptions($selectGroup, $select, array) {

                            selectDropdown = $selectGroup.find('.stylish-select');

                            if (selectDropdown.length) {
                                $selectGroup.find('.dropdown-list').remove();
                                $selectGroup.attr('data-stylish-form', 'true');
                                $selectGroup.find('.selected').remove();
                                $select.unwrap();
                            }

                            $selectGroup.attr('data-stylish-form', 'true');
                            $select.find('option.default').nextAll('option').remove();
                            $select.find('option.default').after(array);
                            stylishForms.update(); // update stylishForms
                            $selectGroup.show();
                        }

                        $("#vbaddress").change(function () {
                            var select = document.getElementById('vbaddress');
                            var selectedAddress = select.options[select.selectedIndex].text;
                            if (selectedAddress === "Choose") {
                                return false;
                            }
                            $('#multi-address').text(selectedAddress);
                            var date = new Date();
                            date.setTime(date.getTime() + (600000));
                            expires = "; expires=" + date.toGMTString();
                            document.cookie = "vbaddress=" + selectedAddress + expires + "; path=/";
                        });
                    }
                }
                else {
                    $('#multiple-address').hide();
                    $('#addressline1').text(addressList[0].Line1);
                    $('#addressline2').text(addressList[0].Line2);
                    $('#addressline3').text(addressList[0].Line3);
                    $('#town').text(addressList[0].Town);
                    $('#postcode').text(addressList[0].PostCode);
                    var addressForCookie = addressList[0].Line1 + ", " + addressList[0].Line2 + ", " + addressList[0].Town + ", " + addressList[0].PostCode;
                    var date = new Date();
                    date.setTime(date.getTime() + (600000));
                    expires = "; expires=" + date.toGMTString();
                    document.cookie = "vbaddress=" + addressForCookie + expires + "; path=/";
                }
            }
            else {
                $('#btnFindYourAddress').removeClass('disabled processing');
                $('#address-errmsgs').css('display', 'block');
                return false;
            }
        }
    });
});

$('#btnUseNewEmailAddress').on('click', function () {
    $('#btnUseNewEmailAddress').addClass('disabled processing');
    $.ajax({
        type: 'POST',
        url: '/cms/ajax/fragment/AssociateAccount/OverrideForgerockId',
        dataType: 'html',
        success: function (data) {
            if (data !== null) {
                $('#btnUseNewEmailAddress').removeClass('disabled processing');
                utag.link({ "event_category": "universal access", "event_action ": "association status", "event_label": "successful", "interaction_name": "/association : association status - success" });
                window.location.replace("\/products/");
            }
        }
    });
});

function accountAssociationDetailsForm() {
    var accountAssociationDetailsForm = $(this),
        $theForm = accountAssociationDetailsForm.find('#account-association-details'),
        $submit = $theForm.find('.full-submit');

    formValidation.api[accountAssociationDetailsForm.data('id')].events.full = function (valid) {
        if (formValidation.api[accountAssociationDetailsForm.data('id')].events.formPost) return;

        if (valid) {
            var hostname = window.location.origin;
            $submit.addClass('disabled processing');
            formValidation.api[accountAssociationDetailsForm.data('id')].events.formPost =
                $.ajax({
                    type: 'POST',
                    url: '/cms/ajax/fragment/AssociateAccount/AssociateAccountDetailsCapture',
                    dataType: 'html',
                    data: $theForm.serialize().replace(/%0D%0A/g, '%2C+'), // remove line breaks causing server errors
                    success: function (data) {
                        if (JSON.parse(data).IsOkay) {
                            utag.link({ "event_category": "universal access", "event_action ": "association status", "event_label": "successful", "interaction_name": "/association : association status - success" });
                            window.location.href = hostname + '/products/' + '#successassoc';
                        } else {
                            $submit.removeClass('disabled processing').attr('disabled', false);
                            window.location.href = hostname + "/create-account/your-policy";
                        }

                        window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                            scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                        }, 100);
                        $submit.removeClass('disabled processing');
                        formValidation.api[accountAssociationDetailsForm.data('id')].events.formPost = null;

                    }
                });
        }
    }
    $theForm.on('submit', function (e) {
        e.preventDefault();
    });
}

$('#btnAddressNext').on('click', function (e) {

    function getCookie(name) {
        var value = "; " + document.cookie;
        var parts = value.split("; " + name + "=");
        if (parts.length == 2) return parts.pop().split(";").shift();
    }

    var address = getCookie('vbaddress');
    if (address === null || address === "Choose" || address === undefined) {
        $('#dvPostcodeEntry').show();
        utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/enter_postcode" });
        $('#dvContactDetails').hide();
        $('#btnFindYourAddress').removeClass('disabled processing');
        $('#address-errmsgs').css('display', 'block');
        return false;
    }

    $('#dvVehicleDetails').hide();
    e.stopImmediatePropagation();
    $('#dvVrnEntry').hide();
    $('#dvHaveMembership').hide();
    $('#dvMain').hide();
    $('#dvPostcodeEntry').hide();
    $('#dvContactDetails').hide();
    $('#dvHaveMembershipNo').show();
    utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/create_vb" });
    $.ajax({
        type: 'POST',
        url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
        dataType: 'JSON',
        success: function (data) {
            if (data !== null) {
                utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/create_vehicle_beneficiary, forgerock_ID:" + data, "event_category": "Vehicle Beneficiary", "event_name": "Policyholder check - continue button clicked", "event_label": "No" });
            }
        }
    });
});

$(document).on('click', '.toggle-pass', function (e) {
    e.preventDefault();
    if ($(this).parent().parent().find(".pass").val()) {
        if ($(this).parent().parent().find(".pass").attr("type") === "password") {
            $(this).parent().parent().find(".pass").attr("type", "text");
            $(this).text("Hide");
        } else {
            $(this).parent().parent().find(".pass").attr("type", "password");
            $(this).text("Show");
        }
    }
});

function AssociateVehicleBeneficiary(forgerockAssociationModel) {
    if (forgerockAssociationModel === undefined) {
        var policyNumber = $("#hdnPolicySession").data('value');
        var policyNumberAfterEdit = $('#hiddenPolicyNumberAfterEdit').val();
        var titleMainOld = $("#dvMainOld input[name='AssociationViewModel.Title']:checked").val();
        var titleMain = $("#dvMain input[name='AssociationViewModel.Title']:checked").val();
        if (titleMainOld !== titleMain && titleMain === undefined) {
            var title = titleMainOld;
        } else {
            title = titleMain;
        }
        var firstName = $('.first-name').val();
        var lastName = $('.last-name').val();
        if ($('#dvMainOld #number-day').val() !== $('#dvMain #number-day1').val() && $('#dvMain #number-day1').val() === "") {
            var dayOfBirth = $('#dvMainOld #number-day').val();
        } else {
            dayOfBirth = $('#dvMain #number-day1').val();
        }
        if ($('#dvMainOld #number-month').val() !== $('#dvMain #number-month1').val() && $('#dvMain #number-month1').val() === "") {
            var monthOfBirth = $('#dvMainOld #number-month').val();
        } else {
            monthOfBirth = $('#dvMain #number-month1').val();
        }
        if ($('#dvMainOld #number-year').val() !== $('#dvMain #number-year1').val() && $('#dvMain #number-year1').val() === "") {
            var yearOfBirth = $('#dvMainOld #number-year').val();
        } else {
            yearOfBirth = $('#dvMain #number-year1').val();
        }
        if ($('#dvMainOld #Telephone').val() !== $('#dvMain #Telephone1').val() && $('#dvMain #Telephone1').val() === "") {
            var phoneNumber = $('#dvMainOld #Telephone').val();
        } else {
            phoneNumber = $('#dvMain #Telephone1').val();
        }
        if ($('#dvMainOld #HomePostcode').val() !== $('#dvMain #HomePostcode1').val() && $('#dvMain #HomePostcode1').val() === "") {
            var postCode = $('#dvMainOld #HomePostcode').val();
        } else {
            postCode = $('#dvMain #HomePostcode1').val();
        }
        if ($('#dvMainOld #membership').val() !== $('#dvMain #membership1').val() && $('#dvMain #membership1').val() === "") {
            var policyNumber2 = $('#dvMainOld #membership').val();
        } else {
            policyNumber2 = $('#dvMain #membership1').val();
        }

        if (policyNumber !== policyNumberAfterEdit && policyNumberAfterEdit !== "") {
            policyNumber = policyNumberAfterEdit;
        }
        //if (policyNumber === null || policyNumber !== "") {
        //    policyNumber = policyNumber2;
        //}

        var forgerockCmdAssociationViewModel = {
            Title: title,
            FirstName: firstName,
            LastName: lastName,
            Postcode: postCode,
            PolicyNumber: policyNumber,
            DayOfBirth: dayOfBirth,
            MonthOfBirth: monthOfBirth,
            YearOfBirth: yearOfBirth,
            PhoneNumber: phoneNumber
        };
    } else {
        forgerockCmdAssociationViewModel = forgerockAssociationModel;
    }

    $("#loader").show();
    $.ajax({
        type: 'POST',
        url: '/cms/ajax/fragment/AssociateAccount/AssociateVehicleBeneficiary',
        dataType: 'json',
        data: forgerockCmdAssociationViewModel,
        success: function (result) {
            if (result.IsOkay) {
                var hostname = window.location.origin;
                utag.link({ "event_category": "universal access", "event_action ": "association status", "event_label": "successful", "interaction_name": "/association : association status - success" });
                window.location.href = hostname + '/products/' + '#successassoc';
            } else {
                $('#dvHaveMembershipNo').hide();
                $('#dvPushTocallVB').parent().parent('.row').css('display', 'block');
                $('#dvPushTocallVB').show();
                $.ajax({
                    type: 'POST',
                    url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
                    dataType: 'JSON',
                    success: function (data) {
                        if (data !== null) {
                            utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/vehicle_policyholder_not_found", "error_message": "vehicle policyholder not found, forgerock_ID:" + data });
                        }
                    }
                });
                $("#loader").hide();
                window.location.href = window.location.href + '#notvb';
            }

        },
        error: function () {
            $('#dvHaveMembershipNo').hide();
            $('#dvPushTocallVB').parent().parent('.row').css('display', 'block');
            $('#dvPushTocallVB').show();
            $.ajax({
                type: 'POST',
                url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
                dataType: 'JSON',
                success: function (data) {
                    if (data !== null) {
                        utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/vehicle_policyholder_not_found", "error_message": "vehicle policyholder not found, forgerock_ID:" + data });
                    }
                }
            });
            $("#loader").hide();
            window.location.href = window.location.href + '#notvb';
        }
    });
}

formatter = {
    number_format: function (t, e, n, i) {
        "use strict";
        t = (t + "").replace(/[^0-9+\-Ee.]/g, "");
        var a = isFinite(+t) ? +t : 0,
            o = isFinite(+e) ? Math.abs(e) : 0,
            r = "undefined" == typeof i ? "," : i,
            l = "undefined" == typeof n ? "." : n,
            s = function (t, e) {
                var n = Math.pow(10, e);
                return "" + (Math.round(t * n) / n).toFixed(e)
            },
            u = (o ? s(a, o) : "" + Math.round(a)).split(".");
        return u[0].length > 3 && (u[0] = u[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, r)), (u[1] || "").length < o && (u[1] = u[1] || "", u[1] += new Array(o - u[1].length + 1).join("0")), u.join(l)
    }
};

function setUrlBack() {
    var url = window.location.href;
    var urlParams = new Array(2);
    urlParams = url.split("#", 2);
    if (urlParams[1] === "fail" || urlParams[1] === "success" || urlParams[1] === "alreadyaccount" || urlParams[1] === "vrnfail" || urlParams[1] === "notvb" || urlParams[1] === "successassoc" || urlParams[1] === "alreadyassociated" || urlParams[1] === "associationfail") {
        url = url.split("#", 1);
        history.pushState(null, null, url);
    }
}

function setAssociationUrlBack() {
    var url = window.location.href;
    var urlParams = new Array(2);
    urlParams = url.split("#", 2);
    if (urlParams[1] === "fail" || urlParams[1] === "alreadyassociated") {
        url = url.split("#", 1);
        history.pushState(null, null, url);
    }
}

function ValidationSummaryMover() {

    var placeholderClassName = 'validation-summary-placeholder'

    function findValidationSummaryPlaceholder() {
        var placeholder = document.getElementsByClassName(placeholderClassName);
        if (placeholder == null || placeholder.length === 0) {
            console.info('No matching div was found to move the validation summary.');
            return null;
        }

        return placeholder[0];
    }

    function findValidationSummary() {
        var matches = document.getElementsByClassName('validation-summary-valid');
        if (!matches || matches.length === 0) {
            console.info('No validation summary was found.');
            return null;
        }

        return matches[0];
    }

    function moveValidationSummary() {
        var validationSummary = findValidationSummary();
        if (!validationSummary) {
            return;
        }

        var nextDiv = findValidationSummaryPlaceholder();
        if (!nextDiv) {
            return;
        }

        validationSummary.remove();
        nextDiv.append(validationSummary);
        console.info('Validation summary moved to placeholder.');
    }

    this.init = function () {
        if (document.getElementsByClassName(placeholderClassName) &&
            document.getElementsByClassName(placeholderClassName).length > 0) {
            moveValidationSummary();
            return;
        }

        console.info("No validation summary placeholder found.");
    }
}

function accountAssociationVehicleDetailsForm() {

    var $associationVehicleDetailsForm = $(document).find('.account-association-vehicle-details');
    var $theForm = $associationVehicleDetailsForm.find('#account-association-vehicle-details');

    formValidation.api[$associationVehicleDetailsForm.data('id')].events.full = function (valid) {
        if (formValidation.api[$associationVehicleDetailsForm.data('id')].events.formPost) return;

        if (valid) {
            associateAccount(false);
        }
    }
    $theForm.on('submit', function (e) {
        e.preventDefault();
    });
}


function associateAccount(isVehicleRegSkip) {
    var $associationVehicleDetailsForm = $(document).find('.account-association-vehicle-details');
    var $theForm = $associationVehicleDetailsForm.find('#account-association-vehicle-details');
    var $submit = $theForm.find('.full-submit');
    $submit.addClass('disabled processing');
    
    var pnumber;
    var forgerockId;


    $.ajax({
        type: 'POST',
        url: '/cms/ajax/fragment/AssociateAccount/GetForgerockId',
        dataType: 'JSON',
        success: function (data) {
            if (data !== null) {
                pnumber = $('.member-number').val();
                forgerockId = data;
            }
        }
    });

    formValidation.api[$associationVehicleDetailsForm.data('id')].events.formPost =
        $.ajax({
            type: 'POST',
            url: '/cms/ajax/fragment/AssociateAccount/GetAssociateAccountViewModel',
            dataType: 'html',
            data: isVehicleRegSkip ? $theForm.serialize().replace(/%0D%0A/g, '%2C+').replace("AssociationViewModel.VehicleRegSkip=False", "AssociationViewModel.VehicleRegSkip=True") : $theForm.serialize().replace(/%0D%0A/g, '%2C+'), // remove line breaks causing server errors
            success: function (data) {
                $submit.removeClass('disabled processing');
                setTimeout(function () {
                    if ($("#loader")) {
                        $("#loader").stop().fadeOut(300);
                        window.aa.salesJourneyApp.cache.$main.removeClass('loading');
                    }
                }, 700);

                window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                    scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                }, 150);

                formValidation.api[$associationVehicleDetailsForm.data('id')].events.formPost = null;

                var hostname = window.location.origin;

                if (data.indexOf('flagAlreadyAssociated') <= 0 &&
                    data.indexOf('flagEditAssociation') <= 0 && data.indexOf('flagVrnEntry') <= 0
                    && data.indexOf('flagPushToCall') <= 0) {
                    utag.link({ "event_category": "universal access", "event_action ": "association status", "event_label": "successful", "interaction_name": "/association : association status - success" });
                    window.location.href = hostname + '/products/' + '#successassoc';
                }
                else if (data.indexOf('flagAlreadyAssociated') >= 0
                    && data.indexOf('flagEditAssociation') <= 0 &&
                    data.indexOf('flagVrnEntry') <= 0 && data.indexOf('flagPushToCall') <= 0) {
                    setAssociationUrlBack();

                    //hide UI for mobile apps
                    var queryString = window.location.search;
                    const urlParams = new URLSearchParams(queryString);
                    const mobileapps = urlParams.get('mobileapps');
                    window.location.href = hostname + '/create-account/your-products' + '#alreadyassociated';
                    $('#dvMain').hide();
                    $('#dvMainOld').hide();
                    if (mobileapps == 'true') {
                        $('#dvAlreadyAssociated').hide();
                    }
                    else {
                        $('#dvAlreadyAssociated').show();
                    }

                    $('#dvAlreadyAssociated').html(data);
                    tag.view({ "site_section": "Your account", "page_name": "/associateaccount/customer_already_registered", "error_message": "customer already registered, forgerock_ID:" + forgerockId, "forgerock_ID": forgerockId, "user_ID": pnumber });

                }
                else if (data.indexOf('flagVrnEntry') >= 0 && data.indexOf('flagAlreadyAssociated') <= 0
                    && data.indexOf('flagEditAssociation') <= 0 && data.indexOf('flagPushToCall') <= 0) {
                    window.location.href = hostname + '/create-account/your-products';
                    $('#dvMain').hide();
                    $('#dvMainOld').hide();
                    $('#dvAlreadyAssociated').hide();
                    $('#dvDetails').hide();
                    $('#dvVrnEntry').show();
                    utag.view({ "site_section": "Your account", "page_name": "/associateaccount/vehicle/enter_number_plate, forgerockId:" + forgerockId, "forgerockID": forgerockId, "user_ID": pnumber });
                }
                else if (data.indexOf('flagVrnEntry') <= 0 && data.indexOf('flagAlreadyAssociated') <= 0 && data.indexOf('flagEditAssociation') <= 0 && data.indexOf('flagPushToCall') >= 0) {
                    window.location.href = hostname + '/create-account/your-products';
                    $('#dvMain').hide();
                    $('#dvMainOld').hide();
                    $('#dvAlreadyAssociated').hide();
                    $('#dvDetails').hide();
                    $('#dvVrnEntry').hide();
                    $('#dvPushTocall').show();
                    utag.view({ "site_section": "Your account", "page_name": "/account/details_not_found", "error_message": "customer details not found - no details, forgerock_ID:" + forgerockId, "forgerock_ID": forgerockId, "user_ID": pnumber });
                    window.location.href = window.location.href + '#associationfail';
                }
                else {
                    $('#dvDetails').hide();
                    $('#dvAlreadyAssociated').hide();
                    $('#dvMainOld').hide();
                    $('#dvMain').show();
                    $(".needMoreInfo").hide();
                    $(".editDetails").show();


                    utag.view({ "site_section": "Your account", "page_name": "/associateaccount/edit_details", "error_message": "customer details not found – edit_details, forgerock_ID:" + forgerockId, "forgerock_ID": forgerockId, "user_ID": pnumber });
                    window.location.href = hostname + '/create-account/your-products';
                }
            },
            error: function () {
                $submit.removeClass('disabled processing');
                formValidation.api[$associationVehicleDetailsForm.data('id')].events.formPost = null;

                setTimeout(function () {
                    if ($("#loader")) {
                        $("#loader").stop().fadeOut(300);
                        window.aa.salesJourneyApp.cache.$main.removeClass('loading');
                    }
                }, 700);
                window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).animate({
                    scrollTop: window.aa.helpers.cache.cachedElements.$body.offset().top
                }, 150);
            }
        });

}

$(document).find('#skipVehicleNumber').on('click', function (e) {
    e.preventDefault();
    associateAccount(true);
});

var validationSummaryMover = new ValidationSummaryMover();
validationSummaryMover.init();

///#source 1 1 /Assets/scripts/header-3.5.js
/* 
 * ---------------------------------------- *
 * Name:    Header JavaScripts              *
 * Type: 	JavaScript                      *
 * Version: Not Versioned                   *
 * Author:	Thomas Dale | Codehouse         *
 * ---------------------------------------- *
 */

(function ($) {

    var $header = $('#site-header, #sales-journey-header'),
        $primaryNavigation = $header.find('#primary-navigation'),
        $aaRoutePlannerContainer = window.aa.helpers.cache.cachedElements.$body.find('.aa-route-planner-container'),
        $aaRoutePlannerTakeover = window.aa.helpers.cache.cachedElements.$body.find('#aa-route-planner-takeover'),
        $megaMenuContainer = $primaryNavigation.find('.mega-menu'),
        $secondLevelNavigation,
        headerHeight = $header.outerHeight(),
        resizeTimer,
        navDelayTimer;

    // check cookie & dropdown if non-existent
    function cookieLaw() {

        var $cookieLawBar = $('#cookie-bar'),
            $cookieAccept = $cookieLawBar.find('.accept');

        function hideCookieBar() {
            $cookieLawBar.find('.text').removeClass('fade-in').stop().fadeOut(550);
            $cookieLawBar.stop().slideUp(550);
        }

        function writeCookie() {
            window.aa.helpers.cache.registerCookie.write('aaCookie', 'aaCookiebar', $cookieLawBar.data('expiry'));
            hideCookieBar();
        }

        if (!window.aa.helpers.cache.registerCookie.check('aaCookie')) {
            $cookieLawBar.stop().slideDown(550);
        }

        // write cookie on acceptance and hide bar
        $cookieAccept.on({
            click: writeCookie,
            keypress: function (e) {
                if (e.keyCode === 13 || e.which === 13) {
                    writeCookie();
                }
            }
        });
    }

    // apply class to allow header to be fixed
    function stickyHeader() {

        // disable sticky header on mobile only
        if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
            return;
        }

        if (window.aa.helpers.cache.cachedElements.$window.scrollTop() >= headerHeight) {
            $header.addClass('sticky');
            $aaRoutePlannerTakeover.addClass('hidden');
            window.aa.helpers.cache.cachedElements.$main.css({ paddingTop: headerHeight });

        } else {
            $header.removeClass('sticky');
            $aaRoutePlannerTakeover.removeClass('hidden');

            if (client.Mobile) {
                setTimeout(function () {
                    window.aa.helpers.cache.cachedElements.$main.css({ paddingTop: 0 });
                });

            } else {
                window.aa.helpers.cache.cachedElements.$main.css({ paddingTop: 0 });
            }
        }

        $('.my-account').removeClass('active');

    }

    // header takeover forms
    function headerTakeovers() {

        var $takeovers = $(this),
            $closeTakeover = $takeovers.find('.close-takeover'),
            $routePlannerTakeover = $takeovers.filter('#route-planner-takeover'),
            $closeAaTakeover = $aaRoutePlannerTakeover.find('.aa-takeover-btn'),
            $searchTakeover = $takeovers.filter('#search-takeover'),
            $bothTakeovers = $searchTakeover.add($routePlannerTakeover),
            $headerLinks = $('#helpful-links').add('#top-level-nav'),
            transitionTimer,
            routePlannerHeight,
            activePlace = -1;

        // route planner toggle
        function toggleRoutePlanner() {

            var $firstInput = $routePlannerTakeover.find('input').filter(':first');

            if (client.oldIE || client.IE9) {
                $headerLinks.stop().fadeOut(250);
                $routePlannerTakeover.stop().fadeIn(500);
                $firstInput.focus();
                return;
            }

            $headerLinks.addClass('animated blur-out');
            $routePlannerTakeover.stop().toggleClass('animated zoom-in');
            $firstInput.focus();
            hideNavigation();
        }

        // aa route planner animating 
        function routePlannerAnimating() {

            window.aa.helpers.cache.cachedElements.$body.removeClass('transition-off').addClass('transition-on');

            clearTimeout(transitionTimer);

            transitionTimer = setTimeout(function () {
                window.aa.helpers.cache.cachedElements.$body.removeClass('transition-on').addClass('transition-off');
            }, 550);
        }

        // aa route planner toggle
        function toggleAaRoutePlanner() {

            var $firstInput = $aaRoutePlannerTakeover.find('input').filter(':first');

            if ($aaRoutePlannerTakeover.hasClass('active')) {
                routePlannerHeight = $aaRoutePlannerTakeover.css({ maxHeight: '' }).outerHeight();

                $aaRoutePlannerTakeover.add($aaRoutePlannerContainer).css({ overflow: 'hidden' });
                routePlannerAnimating();
                $aaRoutePlannerTakeover.css({ maxHeight: routePlannerHeight }).stop().animate({ maxHeight: 0 }, 550, function () {
                    $aaRoutePlannerTakeover.add($aaRoutePlannerTakeover.parent()).removeClass('active');
                });

            } else {

                window.aa.helpers.cache.cachedElements.$window.scrollTop(0);
                $aaRoutePlannerTakeover.add($aaRoutePlannerTakeover.parent()).addClass('active');

                if (!routePlannerHeight) {
                    routePlannerHeight = $aaRoutePlannerTakeover.outerHeight();
                }

                hideNavigation();
                routePlannerAnimating();
                $aaRoutePlannerTakeover.stop().animate({ maxHeight: routePlannerHeight }, 550, function () {
                    $firstInput.focus();
                    $aaRoutePlannerTakeover.add($aaRoutePlannerContainer).css({ overflow: 'visible' });
                });
            }
        }

        // navigate through suggested places list
        function navigateSuggestedPlaces(placeIndex) {

            var $places = window.aa.helpers.cache.cachedElements.$body.find('.location-suggestions .place');

            activePlace += placeIndex;

            if (activePlace >= $places.length) {
                activePlace = 0;

            } else if (activePlace < 0) {
                activePlace = $places.length;
            }

            window.aa.helpers.cache.cachedElements.$body.addClass('no-overflow');
            window.aa.helpers.cache.cachedElements.$body.find('#chosen-location').blur();
            $places.removeClass('place-active').eq(activePlace).addClass('place-active');
        }

        // hide location suggestions
        function hideLocationSuggestions() {
            window.aa.helpers.cache.cachedElements.$body.removeClass('no-overflow');
            window.aa.helpers.cache.cachedElements.$main.find('.chosen-location').removeClass('active-search');
            window.aa.helpers.cache.cachedElements.$main.find('.location-suggestions').hide().empty();
        }

        // traffic news events
        function initTrafficNews() {

            var $trafficInfoContainer = $(this),
                $locationInputContainer = $trafficInfoContainer.find('.chosen-location'),
                $locationInput = $locationInputContainer.find('#chosen-location'),
                $locationSuggestionsList = $trafficInfoContainer.find('.location-suggestions'),
                $trafficReport = $trafficInfoContainer.find('.traffic-report'),
                $trafficNews = $trafficInfoContainer.find('.traffic-news'),
                $setLocation = $trafficInfoContainer.find('.set-location'),
                $setLat = $trafficInfoContainer.find('.set-lat'),
                $setLong = $trafficInfoContainer.find('.set-long'),
                defaultLocation = $locationInputContainer.data('default-location'),
                defaultLat = $locationInputContainer.data('default-lat'),
                defaultLong = $locationInputContainer.data('default-long'),
                suggestionsViewTemplate = $locationSuggestionsList.html(),
                trafficReportViewTemplate = $trafficReport.html(),
                loadSuggestionsTimer;

            // set location preferences
            function populateFields(lat, long, location) {
                $setLat.val(lat);
                $setLong.val(long);

                if (window.aa.salesJourneyApp.helpers.isDefined(location)) {
                    $locationInput.val(location);
                    $locationInput.data('chosen-location', location);
                }
            }

            // get my location using geolocation api
            function getLocation() {
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(setPosition, showError);
                } else {
                    populateFields(defaultLat, defaultLong, defaultLocation);
                }
            }

            // set my location using geolocation api
            function setPosition(position) {

                var lat = position.coords.latitude,
                    long = position.coords.longitude;

                $.ajax({
                    method: 'GET',
                    url: 'https://maps.googleapis.com/maps/api/geocode/json',
                    data: { latlng: lat + ',' + long }
                }).done(function (response) {

                    if (window.aa.salesJourneyApp.helpers.isDefined(response.results)) {
                        populateFields(lat, long, response.results[0].address_components[2].long_name);

                    } else {
                        populateFields(defaultLat, defaultLong, defaultLocation);
                    }
                }).fail(window.aa.salesJourneyApp.helpers.serviceErrorModal);
            }

            // geolocation error handling
            function showError(error) {
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        $('[data-location-off]').show();
                        updateRoutePlannerHeight();
                        break;
                    case error.POSITION_UNAVAILABLE:
                    case error.TIMEOUT:
                    case error.UNKNOWN_ERROR:
                        populateFields(defaultLat, defaultLong, defaultLocation);
                        break;
                }
            }

            // load location suggestions
            function loadSuggestedLocations($input, location) {

                var $inputLoader = $trafficInfoContainer.find('.input-loader');

                $inputLoader.stop().fadeIn(250);
                $input.blur();

                $.ajax({
                    method: 'GET',
                    url: '/cms/ajax/api/RoutePlannerTrafficNews/GetSuggestedAddresses',
                    data: { searchText: location }
                }).done(function (response) {

                    $inputLoader.stop().fadeOut(250);
                    hideLocationSuggestions();
                    activePlace = -1;

                    if (window.aa.salesJourneyApp.helpers.isDefined(response.Result)) {

                        for (var i = 0; i < response.Result.length; i += 1) {

                            $locationSuggestionsList.append(Mustache.render(suggestionsViewTemplate, response.Result[i])).show();
                            $locationInputContainer.addClass('active-search');
                        }

                        $input.removeClass('typing').focus();
                    } else {
                        populateFields(defaultLat, defaultLong, defaultLocation);
                    }
                }).fail(window.aa.salesJourneyApp.helpers.serviceErrorModal);
            }

            // get location coordinates
            function getLocationCoordinates(callback) {

                $setLocation.prop('disabled', true).addClass('disabled');

                $.ajax({
                    method: 'GET',
                    url: '/cms/ajax/api/RoutePlannerTrafficNews/GetPlace',
                    data: { address: $locationInput.data('chosen-location') }
                }).done(function (response) {

                    $setLocation.prop('disabled', false).removeClass('disabled');

                    if (window.aa.salesJourneyApp.helpers.isDefined(response.Result)) {
                        populateFields(response.Result.Latitude, response.Result.Longitude);

                    } else {
                        populateFields(defaultLat, defaultLong, defaultLocation);
                    }

                    if (typeof callback === 'function') {
                        callback();
                    }

                }).fail(window.aa.salesJourneyApp.helpers.serviceErrorModal);

            }

            // set am/pm time
            function hourAmPm(date) {

                var setDate = new Date(date),
                    hours = setDate.getHours(),
                    ampm = (hours >= 12) ? 'PM' : 'AM',
                    minutes = (setDate.getMinutes() < 10) ? '0' + setDate.getMinutes() : setDate.getMinutes();

                return hours + ':' + minutes + ampm;
            }

            // format incident occurrence time
            function formatIncidentDate(incidentDate) {

                var monthNames = ['Jan', 'Febr', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'],
                    date = new Date(incidentDate),
                    day = date.getDate(),
                    year = date.getFullYear(),
                    month = monthNames[date.getMonth()];

                return (day + ' ' + month + ' ' + year + ', ' + hourAmPm(incidentDate));
            }

            // get news traffic data
            function getTrafficNews() {

                var $sectionLoader = $trafficInfoContainer.find('.section-loader');

                $setLocation.prop('disabled', true).addClass('disabled');
                $sectionLoader.stop().fadeIn(250);

                if (!$aaRoutePlannerTakeover.is('.active')) {
                    window.aa.salesJourneyApp.cache.$main.find('#aa-route-planner').prop('disabled', true);
                }

                $.ajax({
                    method: 'GET',
                    url: '/cms/ajax/api/RoutePlannerTrafficNews/GetIncidentsInRadius',
                    data: { coordinates: $setLat.val() + '|' + $setLong.val() }
                }).done(function (response) {

                    var $incidentTime,
                        $incidentDescription,
                        view = Mustache.render(trafficReportViewTemplate, response);

                    $setLocation.prop('disabled', false).removeClass('disabled');
                    $sectionLoader.hide();

                    if (window.aa.salesJourneyApp.helpers.isDefined(response)) {

                        $trafficReport.hide().empty();
                        $trafficNews.hide();
                        $trafficReport.append(view).show();

                        // cache dynamic generated selectors
                        $incidentTime = $trafficReport.find('.incident-time');
                        $incidentDescription = $trafficReport.find('.incident-description');

                        if (window.aa.salesJourneyApp.helpers.isDefined(response.Description) && window.aa.salesJourneyApp.helpers.isDefined(response.IncidentSeverity)) {

                            $incidentDescription.empty().html(response.Description.split(': ')[1]);
                            $incidentTime.html(formatIncidentDate(response.StartDate) + ' (' + $incidentTime.data('label') + ')');

                        } else {
                            $trafficReport.find('.incident-title').remove();

                            if (response.StartDate !== $trafficInfoContainer.data('time-undefined') || window.aa.salesJourneyApp.helpers.isDefined(response.UpdatedDateTime)) {
                                $incidentTime.html($trafficReport.find('.report-details').data('last-update').replace('{time}', formatIncidentDate(response.UpdatedDateTime)));
                            }

                            $trafficReport.find('.road-icon').remove();
                            $trafficReport.find('.report-details').addClass('report-not-available');
                            $incidentDescription.html($incidentDescription.data('no-incidents'));
                        }

                        $trafficReport.find('.current-location p').html($locationInput.data('chosen-location').split(',', 1));
                        updateRoutePlannerHeight();

                    } else {
                        window.aa.salesJourneyApp.helpers.serviceErrorModal();
                    }

                    window.aa.salesJourneyApp.cache.$main.find('#aa-route-planner').prop('disabled', false);

                }).fail(window.aa.salesJourneyApp.helpers.serviceErrorModal);
            }

            // on load set traffic news for London by default
            populateFields(defaultLat, defaultLong, defaultLocation);
            getTrafficNews();

            // show location suggestions on keyup
            $locationInput.off('keyup').on('keyup', function (e) {

                var $target = $(this),
                    targetValue = $target.val();

                if (e.which === 40 && $locationSuggestionsList.find('.place').length) {
                    navigateSuggestedPlaces(0);
                    return;
                }

                clearTimeout(loadSuggestionsTimer);

                if ($target.hasClass('typing') && targetValue.length >= 3 && e.which !== 27) {
                    loadSuggestionsTimer = setTimeout(function () {
                        loadSuggestedLocations($target, targetValue);
                    }, 350);

                } else {
                    hideLocationSuggestions();
                    $target.data('chosen-location', '');
                }
            });

            // set chosen location
            $locationSuggestionsList.off('click').on('click', '.place', function () {

                var location = $(this).data('location-to-send');

                $locationInput.data('chosen-location', location);
                $locationInput.val(location.split(',', 1));
                hideLocationSuggestions();
            });

            // edit location and reset traffic info
            $trafficReport.off('click').on('click', '.edit-location', function (e) {
                e.preventDefault();
                $trafficReport.hide().empty();
                $trafficNews.show();
                $locationInput.focus();
                updateRoutePlannerHeight();
            });

            // switch route inputed values
            $aaRoutePlannerContainer.find('.field-separator').off('click').on('click', function () {

                var $from = $aaRoutePlannerContainer.find('#fromPlace-1'),
                    $to = $aaRoutePlannerContainer.find('#toPlace-1'),
                    fromValue = $from.val(),
                    toValue = $to.val();

                $from.val(toValue);
                $to.val(fromValue);
            });

            // hide and clear location suggestions list when not in focus
            window.aa.helpers.cache.cachedElements.$document.on('mouseup touchend', function (e) {
                if (!$locationSuggestionsList.is(e.target) && $locationSuggestionsList.has(e.target).length === 0) {
                    hideLocationSuggestions();
                }
            });

            // set current location
            $trafficInfoContainer.find('.my-location').off('click').on('click', function (e) {
                e.preventDefault();
                getLocation();
            });

            // send location coordinates to server
            $setLocation.off('click').on('click', function (e) {

                e.preventDefault();

                // trigger validation on the form
                formValidation.api[$trafficInfoContainer.data('id')].validateForm();

                if ($trafficInfoContainer.hasClass('errors')) {
                    updateRoutePlannerHeight();
                    $trafficInfoContainer.find('.error').eq(0).find('input:first').focus();
                    return;
                }

                // set default location if chosen location is empty
                if ($locationInput.data('chosen-location') === '') {
                    populateFields(defaultLat, defaultLong, defaultLocation);
                    getTrafficNews();
                    return;
                }

                getLocationCoordinates(getTrafficNews);
            });
        }

        // search takeover toggle
        function toggleSearchTakeover() {

            var $searchInput = $searchTakeover.find('input').first();

            hideNavigation();

            if (client.oldIE || client.IE9) {
                $headerLinks.stop().fadeOut(250);
                $searchTakeover.stop().fadeIn(500);
                $searchInput.focus();
                return;
            }

            $searchInput.focus();
            $searchTakeover.stop().toggleClass('animated zoom-in');

            // slide down on mobile
            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                // hide navicon close text when search icon is clicked
                if ($primaryNavigation.is(':visible')) {
                    $('#navicon-close').addClass('hidden');
                    $('#navicon').removeClass('hidden');
                }

                window.aa.helpers.cache.cachedElements.$html.removeClass('no-overflow');

                hideNavigation();

                return;
            }

            // fade and zoom in
            $headerLinks.addClass('animated blur-out');
        }

        // close takeovers
        function closeTakeovers() {
            if (client.oldIE || client.IE9) {
                $bothTakeovers.stop().fadeOut(250);
                $headerLinks.stop().fadeIn(500);
                return;
            }

            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                if ($searchTakeover.hasClass('zoom-in')) {
                    $bothTakeovers.removeClass('zoom-in').addClass('zoom-out');
                }

                if ($bothTakeovers.hasClass('zoom-out')) {
                    setTimeout(function () {
                        $bothTakeovers.removeClass('animated zoom-out');
                    }, 250);
                }

                return;
            }

            // fade and zoom out
            $bothTakeovers.removeClass('zoom-in').addClass('zoom-out');

            if ($bothTakeovers.hasClass('zoom-out')) {
                setTimeout(function () {
                    $headerLinks.removeClass('blur-out').addClass('blur-in');
                    $bothTakeovers.removeClass('animated zoom-out');
                }, 250);
            }
        }

        $('#search-icon').on({
            click: toggleSearchTakeover
        });

        // route planner takeover
        $('#route-planner').on({
            click: toggleRoutePlanner
        });

        // aa route planner takeover
        $('#aa-route-planner').off('click').on({
            click: toggleAaRoutePlanner
        });

        // init traffic news
        $('.traffic-info').each(initTrafficNews);

        // prevent symbols from being entered into search input
        $('#search-takeover').find('input[type="text"]').on('keypress', function () {
            return /^[a-zA-Z0-9- ]*$/.test($(this).val());
        });

        // close takeovers
        $closeTakeover.on({
            click: closeTakeovers,
            keypress: function (e) {
                if (e.which === 13 || e.keyCode === 13) {
                    closeTakeovers();
                }
            }
        });

        // close aa route planner
        $closeAaTakeover.on({
            click: toggleAaRoutePlanner,
            keypress: function (e) {
                if (e.which === 13 || e.keyCode === 13) {
                    toggleAaRoutePlanner();
                }
            }
        });

        // close active takeover if esc key is pressed
        window.aa.helpers.cache.cachedElements.$document.on('keyup keypress', function (e) {

            if (e.which === 27) {

                if ($bothTakeovers.hasClass('zoom-in')) {
                    closeTakeovers();
                }

                if ($aaRoutePlannerTakeover.hasClass('active')) {
                    toggleAaRoutePlanner();
                }

                hideLocationSuggestions();
            }

            if (window.aa.helpers.cache.cachedElements.$body.find('.location-suggestions').children().length) {

                e.preventDefault();

                switch (e.which) {
                    case 13:
                    case 32:
                        window.aa.helpers.cache.cachedElements.$body.find('.location-suggestions').find('.place-active').trigger('click');
                        break;
                    case 40:
                    case 9:
                        navigateSuggestedPlaces(1);
                        break;
                    case 38:
                        navigateSuggestedPlaces(-1);
                        break;
                }
            }
        });

        // remove route planner on window resize
        window.aa.helpers.cache.cachedElements.$window.on('resize', function () {
            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                $routePlannerTakeover.addClass('hidden');

                if ($aaRoutePlannerTakeover.hasClass('active')) {
                    toggleAaRoutePlanner();
                }
            }
        });
    }

    // mobile navigation exists
    function detectMobileNavigation() {

        if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
            $primaryNavigation.removeClass('desktop-nav').addClass('mobile-nav');

        } else {
            $primaryNavigation.removeClass('mobile-nav').addClass('desktop-nav');
            $primaryNavigation.find('.primary-item').removeClass('menu-item-clicked');

        }
    }

    // update route planner height on resize
    function updateRoutePlannerHeight() {

        if ($aaRoutePlannerTakeover.hasClass('active')) {

            var routePlannerHeight = $aaRoutePlannerTakeover.css({ maxHeight: '100%' }).outerHeight();

            $aaRoutePlannerTakeover.css({ maxHeight: routePlannerHeight });
        }
    }

    // hide navigation events
    function hideNavigation() {
        $primaryNavigation.find('.active').removeClass('active');
        window.aa.helpers.cache.cachedElements.$body.add($primaryNavigation).removeClass('nav-open account-details-active');
        $('#navicon-close').addClass('hidden');
        $('#navicon').removeClass('hidden');
        $megaMenuContainer.parent('li').removeClass('active');

        if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
            $primaryNavigation.stop().slideUp(250);
        }

    }

    // mega menu dropdown
    function megaMenu() {

        var $primaryNavigationItem = $(this),
            $secondaryNavItem = $primaryNavigationItem.find('.secondary-item'),
            $secondaryItemsOverlay = $primaryNavigation.find('.second-level-nav-overlay'),
            $primaryNavigationItems = window.aa.helpers.cache.cachedElements.$body.find('.primary-item'),
            $megaMenu = $primaryNavigationItem.find('.mega-menu'),
            $navPanels = $primaryNavigationItem.find('.nav-panels'),
            $subComponents = $navPanels.find('.sub-component'),
            $myAccount = $header.find('#component-my-account');

        $megaMenu.css({ maxWidth: window.aa.helpers.cache.cachedElements.$window.width() });

        if ($myAccount.length) {
            $myAccount.closest('.primary-item').addClass('account-link');
        }

        function revealMegaMenu() {

            var $secondaryItem = $megaMenu.find('.secondary-item'),
                $secondaryNavPanels = $megaMenu.find('.nav-panels');

            if ($primaryNavigationItem.hasClass('has-children') && !$primaryNavigationItem.hasClass('active')) {

                if ($primaryNavigationItem.find('.my-aa-account').length) {
                    $navPanels.addClass('open');
                }

                if ($primaryNavigationItem.hasClass('account-link')) {
                    window.aa.helpers.cache.cachedElements.$body.addClass('account-details-active');
                }

                window.aa.helpers.cache.cachedElements.$body.addClass('nav-open');
                $primaryNavigationItems.removeClass('active');
                $primaryNavigationItem.addClass('active');

                if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    $secondaryItem.removeClass('active');
                    $secondaryItem.filter(':first').addClass('active');
                    $secondaryNavPanels.removeClass('open');
                    $secondaryNavPanels.filter(':first-of-type').addClass('open');
                    if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.TABLET_BREAKPOINT) {
                        $secondaryItemsOverlay.show();
                    }
                }
            } else {
                window.aa.helpers.cache.cachedElements.$body.removeClass('nav-open account-details-active');
                $primaryNavigationItems.removeClass('active');
            }
        }

        function hideMegamenu() {
            clearTimeout(navDelayTimer);
            window.aa.helpers.cache.cachedElements.$body.removeClass('nav-open account-details-active');
            $primaryNavigationItems.add($secondaryNavItem).removeClass('active');
            $navPanels.removeClass('open');
        }

        function resetMegamenu() {
            hideMegamenu();
            $megaMenu.css({ height: 'auto' });
        }

        if ($megaMenu.length) {
            $primaryNavigationItem.addClass('has-children');
        }

        $('.editorial-panel').each(function () {
            $(this).closest('.nav-panels').addClass('editorial');
        });

        detectMobileNavigation();

        $primaryNavigationItem.on({
            click: function (e) {

                var $target = $(this),
                    isActive = $target.filter('.active');

                if ($primaryNavigationItem.hasClass('active')) {
                    if (!isActive.is(e.target) && isActive.has(e.target).length === 0) {
                        resetMegamenu();
                    }

                    return true;
                } else {

                    if (!$target.hasClass('has-children') || $target.hasClass('menu-item-clicked')) {
                        return true;
                    }
                    revealMegaMenu();
                    $megaMenu.css({ height: $target.find('.second-level-navigation').height() });
                }

                $(this).siblings('.primary-item').find('.nav-panels').removeClass('open');

                return false;
            }
        });

        $secondaryNavItem.on('mouseover click', function (e) {

            e.stopPropagation();

            var $element = $(this),
                targetId = $element.data('secondary'),
                $subComponent = $('#' + targetId).find('.sub-component');

            if ($('#' + targetId).hasClass('open') && window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                $subComponent.css({ minHeight: window.aa.helpers.getTallestHeightHelper($subComponent) });
            }

            if ($element.hasClass('active')) {
                if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.TABLET_BREAKPOINT) {
                    $secondaryItemsOverlay.show();
                }
                return true;

            } else {
                // momentary delay before revealing mega menu
                $secondaryNavItem.removeClass('active');
                $navPanels.removeClass('open');
                $element.addClass('active');
                $('#' + targetId).addClass('open');
            }
            return false;
        });

        // re-enable second level navigation events
        $secondaryItemsOverlay.off('mouseover').on('mouseover', function () {
            if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.TABLET_BREAKPOINT) {
                clearTimeout(navDelayTimer);

                navDelayTimer = setTimeout(function () {
                    $secondaryItemsOverlay.hide();
                }, 250);
            }
        });

        // disable second level navigation
        $navPanels.on('mouseover', function () {
            if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.TABLET_BREAKPOINT) {
                $secondaryItemsOverlay.show();
            }
        });

        // use nav item toggle icon to open/close mega menu
        $megaMenu.siblings('.toggle').on('click', function (e) {
            e.stopPropagation();

            if ($(this).parent('li').hasClass('active')) {
                hideMegamenu();
                $primaryNavigationItems.find('.nav-panels').removeClass('open');
            } else {
                revealMegaMenu();
            }
        });

        window.aa.helpers.cache.cachedElements.$document.on({
            click: function (e) {

                var $targetArea = $megaMenu.add($header);

                if (!$targetArea.is(e.target) && $targetArea.has(e.target).length === 0) {
                    hideMegamenu();
                    $primaryNavigationItems.find('.nav-panels').removeClass('open');
                }

            }
        });
    }

    // mobile mega menu dropdown
    function megaMenuMobile() {

        var $navicon = $('#navicon, #navicon-close'),
            $primaryItem = $primaryNavigation.find('.primary-item'),
            $secondaryItem = $primaryItem.find('.secondary-item'),
            $secondaryLevelNavigation = $primaryItem.find('.second-level-navigation'),
            $tertiaryLevelNavigation = $primaryItem.find('.nav-panels'),
            $backToPrimary = $primaryItem.find('.back-to-primary-link'),
            $backToSecondary = $primaryItem.find('.back-to-secondary-link'),
            $goToSecondary = $primaryItem.find('.mobile-toggle');

        function navToggle() {
            if ($primaryNavigation.hasClass('nav-open')) {
                navOpen();
            } else {
                navClose();
            }
        }

        function navOpen() {
            if ($tertiaryLevelNavigation.hasClass('active')) {
                $tertiaryLevelNavigation.stop().slideDown(250);
            } else if ($secondaryLevelNavigation.hasClass('active')) {
                $secondaryLevelNavigation.stop().slideDown(250);
            }
            $primaryNavigation.stop().slideDown(250);
        }

        function navClose() {
            if ($tertiaryLevelNavigation.hasClass('active')) {
                $tertiaryLevelNavigation.stop().slideUp(250, function () {
                    $primaryNavigation.stop().slideUp(250, function () {
                        $primaryItem.add($secondaryItem).add($secondaryLevelNavigation).add($tertiaryLevelNavigation).removeClass('active');
                        $(this).css({ left: '0' });
                    });
                });
            } else if ($secondaryLevelNavigation.hasClass('active')) {
                $secondaryLevelNavigation.stop().slideUp(250, function () {
                    $primaryNavigation.stop().slideUp(250, function () {
                        $primaryItem.add($secondaryItem).add($secondaryLevelNavigation).add($tertiaryLevelNavigation).removeClass('active');
                        $(this).css({ left: '0' });
                    });
                });
            } else {
                $primaryNavigation.stop().slideUp(250, function () {
                    $primaryItem.add($secondaryItem).add($secondaryLevelNavigation).add($tertiaryLevelNavigation).removeClass('active');
                    $(this).css({ left: '0' });
                });
            }

            window.aa.helpers.cache.cachedElements.$body.removeClass('account-details-active');
        }

        function slideMenuLevels($selector) {
            $secondaryLevelNavigation.add($tertiaryLevelNavigation).removeClass('active');

            if ($selector.hasClass('has-children') && $selector.hasClass('primary-item')) {
                $primaryNavigation.stop().animate({ left: '-100vw' }, 250);

                if ($selector.find('.my-aa-account').length) {
                    $selector.find('.nav-panels').addClass('open').show();
                    $primaryNavigation.stop().animate({ left: '-200vw' }, 250);

                } else {
                    $secondaryLevelNavigation.addClass('active').show();
                    $selector.addClass('menu-item-clicked').siblings().addClass('hide-items');
                    $primaryNavigation.animate({ left: '-100vw' }, 250);
                }
            } else if ($selector.hasClass('back-to-primary-link')) {

                $primaryNavigation.stop().animate({ left: '0' }, 250, function () {

                    window.aa.helpers.cache.cachedElements.$body.removeClass('account-details-active');

                    if ($selector.find('.my-aa-account').length) {
                        $selector.find('.nav-panels').removeClass('open').hide();

                    } else {
                        $secondaryLevelNavigation.removeClass('active').hide();
                    }

                });
            } else if ($selector.hasClass('secondary-item')) {
                $primaryNavigation.animate({ left: '-200vw' }, 250, function () {
                    $secondaryLevelNavigation.removeClass('active').hide();
                });
                $tertiaryLevelNavigation.addClass('active').show();
            } else if ($selector.hasClass('back-to-secondary-link')) {
                $primaryNavigation.stop().animate({ left: '-100vw' }, 250, function () {
                    $tertiaryLevelNavigation.removeClass('open').hide();
                });
                $secondaryLevelNavigation.addClass('active').show();
            }
        }

        $navicon.on('click', function (e) {
            e.stopImmediatePropagation();
            $navicon.toggleClass('hidden');
            window.aa.helpers.cache.cachedElements.$body.add($primaryNavigation).toggleClass('nav-open');
            $primaryItem.removeClass('menu-item-clicked').siblings().removeClass('hide-items');
            navToggle();
        });

        $goToSecondary.on('click', function () {
            $(this).parent().removeClass('menu-item-clicked').siblings().removeClass('hide-items');
        });

        $primaryItem.on('click', function () {
            slideMenuLevels($(this));
        });

        $backToPrimary.on('click', function (e) {
            e.stopPropagation();
            $primaryItem.removeClass('active menu-item-clicked').siblings().removeClass('hide-items');
            slideMenuLevels($(this));
        });

        $secondaryItem.on('click', function () {
            slideMenuLevels($(this));
        });

        $backToSecondary.on('click', function (e) {
            e.stopPropagation();
            $secondaryItem.removeClass('active');
            slideMenuLevels($(this));
        });

        window.aa.helpers.cache.cachedElements.$document.on({
            click: function (e) {

                if (!$header.is(e.target) && $header.has(e.target).length === 0 && window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    if ($primaryNavigation.is(':visible')) {
                        $navicon.toggleClass('hidden');
                        window.aa.helpers.cache.cachedElements.$body.add($primaryNavigation).removeClass('nav-open account-details-active');
                        navToggle();
                    }
                }
            }
        });

    }

    // my account login
    function myAccountLogin() {

        var $myAccount = $(this),
            $myAccountBtn = $myAccount.find('.button'),
            $myAccountMegaMenu = $myAccount.find('.account-nav'),
            $secondaryNavItem = $myAccountMegaMenu.find('h5'),
            $lastColumn = $myAccountMegaMenu.find('.col').last();

        function revealAccountMegaMenu() {
            $myAccount.addClass('active');

            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                $myAccountMegaMenu.stop().slideDown(500, function () {
                    $lastColumn.find('ul').stop().slideDown(250);
                });
            }

            if (client.IE9) {
                $myAccountMegaMenu.stop().fadeIn(200);
            }

        }

        function hideAccountMegaMenu() {
            $myAccount.add($myAccount.find('h5')).removeClass('active');

            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                $myAccountMegaMenu.add($myAccountMegaMenu.find('ul')).stop().slideUp(500, function () {
                    $lastColumn.find('ul').stop().slideUp(250);
                });
            }

            if (client.IE9) {
                $myAccountMegaMenu.stop().fadeOut(200);
            }

        }

        // close active navigation item
        function closeAccordionNav() {
            var $close = $(this);

            $close.on('click', function () {
                $close.parent().removeClass('active').siblings('ul').stop().slideUp(200);

                if (!$myAccount.hasClass('active')) {
                    $myAccountMegaMenu.stop().slideUp(250);
                }

            });
        }

        // hide mega menu when item is clicked
        $myAccountMegaMenu.find('li').click(hideAccountMegaMenu);

        // clicking (tapping) elsewhere on a page hides mega menu
        window.aa.helpers.cache.cachedElements.$document.on('mouseup touchend', function (e) {
            if (!$myAccount.is(e.target) && $myAccount.has(e.target).length === 0) {
                hideAccountMegaMenu();
            }
        });

        if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {

            // apply class if mega menu is found
            if ($secondaryNavItem.siblings('ul').length) {
                $secondaryNavItem.addClass('has-children');
            }

            // activate and open my account mega menu
            $myAccountBtn.on('click', function () {
                $myAccount.toggleClass('active');

                if ($myAccount.hasClass('active')) {
                    revealAccountMegaMenu();
                } else {
                    hideAccountMegaMenu();
                }

            });

            // activate and open mega menu
            $secondaryNavItem.children('a').on('click', function (e) {

                var $anchorParent = $(this).parent(),
                    $anchorParentSiblings = $anchorParent.parent().siblings().children('h5');

                // prevent first click going to link
                if (!$anchorParent.hasClass('active')) {
                    e.preventDefault();
                }

                $anchorParent.toggleClass('active').siblings('ul').stop().slideDown(250, function () {
                    $anchorParentSiblings.removeClass('active').siblings().stop().slideUp(250);
                });

            });

            $myAccount.find('.close').each(closeAccordionNav);

            $lastColumn.prependTo($myAccountMegaMenu).find('h5').remove();

            return;
        }

        // reveal mega menu on hover
        $myAccount.hover(revealAccountMegaMenu, hideAccountMegaMenu);

        // use the tab key to focus on navigation items
        window.aa.helpers.cache.cachedElements.$document.on({
            keyup: function (e) {
                if (e.which === 9 || e.keyCode === 9) {
                    if ($myAccountBtn.is(e.target)) {
                        revealAccountMegaMenu();
                    } else {
                        hideAccountMegaMenu();
                    }
                }
            }
        });

    }

    // sign in panel overlay
    function signInPanel() {

        var $signInPanel = $('#sign-in-panel'),
            $signInPanelOverlay = $('#sign-in-overlay'),
            $main = $signInPanel.closest('#main'),
            $mainAndFooter = $main.add($main.siblings('#site-footer'));

        // panel toggle reveal/hide
        function toggleSignInPanel() {

            $signInPanel.add($signInPanelOverlay).toggleClass('active');

            // fade fallback for IE9
            if (client.IE9) {
                $signInPanel.add($signInPanelOverlay).stop().fadeToggle(250);
                return;
            }

            $header.find('.active').removeClass('active');
            window.aa.helpers.cache.cachedElements.$body.removeClass('nav-open account-details-active');
            $mainAndFooter.removeClass('blur-in-half').toggleClass('blur-out-half');
            $mainAndFooter.add($mainAndFooter.children().not($signInPanel, $signInPanelOverlay)).attr('aria-hidden', 'true');

        }

        // hide panel
        function hideSignInPanel() {

            $signInPanel.add($signInPanelOverlay).removeClass('active');

            // fade fallback for IE9
            if (client.IE9) {
                $signInPanel.stop().fadeOut(250);
                $signInPanelOverlay.stop().fadeOut(250);
                return;
            }

            $mainAndFooter.removeClass('blur-out-half').addClass('blur-in-half');
            $mainAndFooter.add($mainAndFooter.children().not($signInPanel, $signInPanelOverlay)).attr('aria-hidden', 'false');

        }

        $('#close-panel, .sign-in').on({
            click: function (e) {
                e.preventDefault();

                toggleSignInPanel();
            }

        });

        window.aa.helpers.cache.cachedElements.$document.on({
            mouseup: function (e) {
                // if the target of the click isn't the panel, nor a descendant of the panel, nor the scrollbar
                if (!$signInPanel.is(e.target) && ($signInPanel.has(e.target).length === 0) && (e.target !== window.aa.helpers.cache.cachedElements.$html.get(0))) {
                    hideSignInPanel();
                }
            },
            keyup: function (e) {
                if (e.which === 27 || e.keyCode === 27) {
                    hideSignInPanel();
                }
            }
        });
    }

    // PP Jquery upgrade
    //    window.aa.helpers.cache.cachedElements.$document.on({
    //        ready: function () {
    window.aa.helpers.cache.cachedElements.$document.ready(
        function () {
            //console.log('Jquery upgrade of document.on( ready');
            if ($('#cookie-bar').length) {
                cookieLaw();
            }

            $('.takeover, .aa-route-planner-container').each(headerTakeovers);

            $('#primary-navigation .container > ul').children('.primary-item').each(megaMenu);

            if ($('#navicon').length && $primaryNavigation.length && window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                megaMenuMobile();
            }

            if ($('.sign-in').length) {
                signInPanel();
            }

            $('.my-account').each(myAccountLogin);
            //}
        });

    window.aa.helpers.cache.cachedElements.$window.on({
        resize: function () {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function () {

                $secondLevelNavigation = $primaryNavigation.find('.primary-item.active .second-level-navigation');

                if ($primaryNavigation.length) {
                    detectMobileNavigation();
                }

                if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    megaMenuMobile();
                }

                updateRoutePlannerHeight();

                $megaMenuContainer.css({ maxWidth: window.aa.helpers.cache.cachedElements.$window.width(), height: $secondLevelNavigation.height() });
            }, 100); // call on resize end
        },
        scroll: function () {
            if ($header.length) {

                stickyHeader();
                if (($('#sales-journey-header').hasClass("sticky")) && ($("#contact-cta").hasClass('dsf-view-none'))) {
                    $('#CancelSalesLabel').css('margin-right', '13rem');
                    $("#BackToDashboard").css({ "margin-right": "13rem", "margin-left": "-30px" });
                }
                else {
                    $('#CancelSalesLabel').css('margin-right', '2.5rem');
                    $("#BackToDashboard").css({ 'margin-right': '2.5rem', 'margin-left': '0px' });
                }


            }

        }
    });
})(jQ);
///#source 1 1 /Assets/scripts/libs/jquery.mCustomScrollbar.concat.min.js
/* == jquery mousewheel plugin == Version: 3.1.13, License: MIT License (MIT) */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})});!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})});
/* == malihu jquery custom scrollbar plugin == Version: 3.1.5, License: MIT License (MIT) */
!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"undefined"!=typeof module&&module.exports?module.exports=e:e(jQuery,window,document)}(function(e){!function(t){var o="function"==typeof define&&define.amd,a="undefined"!=typeof module&&module.exports,n="https:"==document.location.protocol?"https:":"http:",i="cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js";o||(a?require("jquery-mousewheel")(e):e.event.special.mousewheel||e("head").append(decodeURI("%3Cscript src="+n+"//"+i+"%3E%3C/script%3E"))),t()}(function(){var t,o="mCustomScrollbar",a="mCS",n=".mCustomScrollbar",i={setTop:0,setLeft:0,axis:"y",scrollbarPosition:"inside",scrollInertia:950,autoDraggerLength:!0,alwaysShowScrollbar:0,snapOffset:0,mouseWheel:{enable:!0,scrollAmount:"auto",axis:"y",deltaFactor:"auto",disableOver:["select","option","keygen","datalist","textarea"]},scrollButtons:{scrollType:"stepless",scrollAmount:"auto"},keyboard:{enable:!0,scrollType:"stepless",scrollAmount:"auto"},contentTouchScroll:25,documentTouchScroll:!0,advanced:{autoScrollOnFocus:"input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']",updateOnContentResize:!0,updateOnImageLoad:"auto",autoUpdateTimeout:60},theme:"light",callbacks:{onTotalScrollOffset:0,onTotalScrollBackOffset:0,alwaysTriggerOffsets:!0}},r=0,l={},s=window.attachEvent&&!window.addEventListener?1:0,c=!1,d=["mCSB_dragger_onDrag","mCSB_scrollTools_onDrag","mCS_img_loaded","mCS_disabled","mCS_destroyed","mCS_no_scrollbar","mCS-autoHide","mCS-dir-rtl","mCS_no_scrollbar_y","mCS_no_scrollbar_x","mCS_y_hidden","mCS_x_hidden","mCSB_draggerContainer","mCSB_buttonUp","mCSB_buttonDown","mCSB_buttonLeft","mCSB_buttonRight"],u={init:function(t){var t=e.extend(!0,{},i,t),o=f.call(this);if(t.live){var s=t.liveSelector||this.selector||n,c=e(s);if("off"===t.live)return void m(s);l[s]=setTimeout(function(){c.mCustomScrollbar(t),"once"===t.live&&c.length&&m(s)},500)}else m(s);return t.setWidth=t.set_width?t.set_width:t.setWidth,t.setHeight=t.set_height?t.set_height:t.setHeight,t.axis=t.horizontalScroll?"x":p(t.axis),t.scrollInertia=t.scrollInertia>0&&t.scrollInertia<17?17:t.scrollInertia,"object"!=typeof t.mouseWheel&&1==t.mouseWheel&&(t.mouseWheel={enable:!0,scrollAmount:"auto",axis:"y",preventDefault:!1,deltaFactor:"auto",normalizeDelta:!1,invert:!1}),t.mouseWheel.scrollAmount=t.mouseWheelPixels?t.mouseWheelPixels:t.mouseWheel.scrollAmount,t.mouseWheel.normalizeDelta=t.advanced.normalizeMouseWheelDelta?t.advanced.normalizeMouseWheelDelta:t.mouseWheel.normalizeDelta,t.scrollButtons.scrollType=g(t.scrollButtons.scrollType),h(t),e(o).each(function(){var o=e(this);if(!o.data(a)){o.data(a,{idx:++r,opt:t,scrollRatio:{y:null,x:null},overflowed:null,contentReset:{y:null,x:null},bindEvents:!1,tweenRunning:!1,sequential:{},langDir:o.css("direction"),cbOffsets:null,trigger:null,poll:{size:{o:0,n:0},img:{o:0,n:0},change:{o:0,n:0}}});var n=o.data(a),i=n.opt,l=o.data("mcs-axis"),s=o.data("mcs-scrollbar-position"),c=o.data("mcs-theme");l&&(i.axis=l),s&&(i.scrollbarPosition=s),c&&(i.theme=c,h(i)),v.call(this),n&&i.callbacks.onCreate&&"function"==typeof i.callbacks.onCreate&&i.callbacks.onCreate.call(this),e("#mCSB_"+n.idx+"_container img:not(."+d[2]+")").addClass(d[2]),u.update.call(null,o)}})},update:function(t,o){var n=t||f.call(this);return e(n).each(function(){var t=e(this);if(t.data(a)){var n=t.data(a),i=n.opt,r=e("#mCSB_"+n.idx+"_container"),l=e("#mCSB_"+n.idx),s=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")];if(!r.length)return;n.tweenRunning&&Q(t),o&&n&&i.callbacks.onBeforeUpdate&&"function"==typeof i.callbacks.onBeforeUpdate&&i.callbacks.onBeforeUpdate.call(this),t.hasClass(d[3])&&t.removeClass(d[3]),t.hasClass(d[4])&&t.removeClass(d[4]),l.css("max-height","none"),l.height()!==t.height()&&l.css("max-height",t.height()),_.call(this),"y"===i.axis||i.advanced.autoExpandHorizontalScroll||r.css("width",x(r)),n.overflowed=y.call(this),M.call(this),i.autoDraggerLength&&S.call(this),b.call(this),T.call(this);var c=[Math.abs(r[0].offsetTop),Math.abs(r[0].offsetLeft)];"x"!==i.axis&&(n.overflowed[0]?s[0].height()>s[0].parent().height()?B.call(this):(G(t,c[0].toString(),{dir:"y",dur:0,overwrite:"none"}),n.contentReset.y=null):(B.call(this),"y"===i.axis?k.call(this):"yx"===i.axis&&n.overflowed[1]&&G(t,c[1].toString(),{dir:"x",dur:0,overwrite:"none"}))),"y"!==i.axis&&(n.overflowed[1]?s[1].width()>s[1].parent().width()?B.call(this):(G(t,c[1].toString(),{dir:"x",dur:0,overwrite:"none"}),n.contentReset.x=null):(B.call(this),"x"===i.axis?k.call(this):"yx"===i.axis&&n.overflowed[0]&&G(t,c[0].toString(),{dir:"y",dur:0,overwrite:"none"}))),o&&n&&(2===o&&i.callbacks.onImageLoad&&"function"==typeof i.callbacks.onImageLoad?i.callbacks.onImageLoad.call(this):3===o&&i.callbacks.onSelectorChange&&"function"==typeof i.callbacks.onSelectorChange?i.callbacks.onSelectorChange.call(this):i.callbacks.onUpdate&&"function"==typeof i.callbacks.onUpdate&&i.callbacks.onUpdate.call(this)),N.call(this)}})},scrollTo:function(t,o){if("undefined"!=typeof t&&null!=t){var n=f.call(this);return e(n).each(function(){var n=e(this);if(n.data(a)){var i=n.data(a),r=i.opt,l={trigger:"external",scrollInertia:r.scrollInertia,scrollEasing:"mcsEaseInOut",moveDragger:!1,timeout:60,callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},s=e.extend(!0,{},l,o),c=Y.call(this,t),d=s.scrollInertia>0&&s.scrollInertia<17?17:s.scrollInertia;c[0]=X.call(this,c[0],"y"),c[1]=X.call(this,c[1],"x"),s.moveDragger&&(c[0]*=i.scrollRatio.y,c[1]*=i.scrollRatio.x),s.dur=ne()?0:d,setTimeout(function(){null!==c[0]&&"undefined"!=typeof c[0]&&"x"!==r.axis&&i.overflowed[0]&&(s.dir="y",s.overwrite="all",G(n,c[0].toString(),s)),null!==c[1]&&"undefined"!=typeof c[1]&&"y"!==r.axis&&i.overflowed[1]&&(s.dir="x",s.overwrite="none",G(n,c[1].toString(),s))},s.timeout)}})}},stop:function(){var t=f.call(this);return e(t).each(function(){var t=e(this);t.data(a)&&Q(t)})},disable:function(t){var o=f.call(this);return e(o).each(function(){var o=e(this);if(o.data(a)){o.data(a);N.call(this,"remove"),k.call(this),t&&B.call(this),M.call(this,!0),o.addClass(d[3])}})},destroy:function(){var t=f.call(this);return e(t).each(function(){var n=e(this);if(n.data(a)){var i=n.data(a),r=i.opt,l=e("#mCSB_"+i.idx),s=e("#mCSB_"+i.idx+"_container"),c=e(".mCSB_"+i.idx+"_scrollbar");r.live&&m(r.liveSelector||e(t).selector),N.call(this,"remove"),k.call(this),B.call(this),n.removeData(a),$(this,"mcs"),c.remove(),s.find("img."+d[2]).removeClass(d[2]),l.replaceWith(s.contents()),n.removeClass(o+" _"+a+"_"+i.idx+" "+d[6]+" "+d[7]+" "+d[5]+" "+d[3]).addClass(d[4])}})}},f=function(){return"object"!=typeof e(this)||e(this).length<1?n:this},h=function(t){var o=["rounded","rounded-dark","rounded-dots","rounded-dots-dark"],a=["rounded-dots","rounded-dots-dark","3d","3d-dark","3d-thick","3d-thick-dark","inset","inset-dark","inset-2","inset-2-dark","inset-3","inset-3-dark"],n=["minimal","minimal-dark"],i=["minimal","minimal-dark"],r=["minimal","minimal-dark"];t.autoDraggerLength=e.inArray(t.theme,o)>-1?!1:t.autoDraggerLength,t.autoExpandScrollbar=e.inArray(t.theme,a)>-1?!1:t.autoExpandScrollbar,t.scrollButtons.enable=e.inArray(t.theme,n)>-1?!1:t.scrollButtons.enable,t.autoHideScrollbar=e.inArray(t.theme,i)>-1?!0:t.autoHideScrollbar,t.scrollbarPosition=e.inArray(t.theme,r)>-1?"outside":t.scrollbarPosition},m=function(e){l[e]&&(clearTimeout(l[e]),$(l,e))},p=function(e){return"yx"===e||"xy"===e||"auto"===e?"yx":"x"===e||"horizontal"===e?"x":"y"},g=function(e){return"stepped"===e||"pixels"===e||"step"===e||"click"===e?"stepped":"stepless"},v=function(){var t=e(this),n=t.data(a),i=n.opt,r=i.autoExpandScrollbar?" "+d[1]+"_expand":"",l=["<div id='mCSB_"+n.idx+"_scrollbar_vertical' class='mCSB_scrollTools mCSB_"+n.idx+"_scrollbar mCS-"+i.theme+" mCSB_scrollTools_vertical"+r+"'><div class='"+d[12]+"'><div id='mCSB_"+n.idx+"_dragger_vertical' class='mCSB_dragger' style='position:absolute;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>","<div id='mCSB_"+n.idx+"_scrollbar_horizontal' class='mCSB_scrollTools mCSB_"+n.idx+"_scrollbar mCS-"+i.theme+" mCSB_scrollTools_horizontal"+r+"'><div class='"+d[12]+"'><div id='mCSB_"+n.idx+"_dragger_horizontal' class='mCSB_dragger' style='position:absolute;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>"],s="yx"===i.axis?"mCSB_vertical_horizontal":"x"===i.axis?"mCSB_horizontal":"mCSB_vertical",c="yx"===i.axis?l[0]+l[1]:"x"===i.axis?l[1]:l[0],u="yx"===i.axis?"<div id='mCSB_"+n.idx+"_container_wrapper' class='mCSB_container_wrapper' />":"",f=i.autoHideScrollbar?" "+d[6]:"",h="x"!==i.axis&&"rtl"===n.langDir?" "+d[7]:"";i.setWidth&&t.css("width",i.setWidth),i.setHeight&&t.css("height",i.setHeight),i.setLeft="y"!==i.axis&&"rtl"===n.langDir?"989999px":i.setLeft,t.addClass(o+" _"+a+"_"+n.idx+f+h).wrapInner("<div id='mCSB_"+n.idx+"' class='mCustomScrollBox mCS-"+i.theme+" "+s+"'><div id='mCSB_"+n.idx+"_container' class='mCSB_container' style='position:relative; top:"+i.setTop+"; left:"+i.setLeft+";' dir='"+n.langDir+"' /></div>");var m=e("#mCSB_"+n.idx),p=e("#mCSB_"+n.idx+"_container");"y"===i.axis||i.advanced.autoExpandHorizontalScroll||p.css("width",x(p)),"outside"===i.scrollbarPosition?("static"===t.css("position")&&t.css("position","relative"),t.css("overflow","visible"),m.addClass("mCSB_outside").after(c)):(m.addClass("mCSB_inside").append(c),p.wrap(u)),w.call(this);var g=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")];g[0].css("min-height",g[0].height()),g[1].css("min-width",g[1].width())},x=function(t){var o=[t[0].scrollWidth,Math.max.apply(Math,t.children().map(function(){return e(this).outerWidth(!0)}).get())],a=t.parent().width();return o[0]>a?o[0]:o[1]>a?o[1]:"100%"},_=function(){var t=e(this),o=t.data(a),n=o.opt,i=e("#mCSB_"+o.idx+"_container");if(n.advanced.autoExpandHorizontalScroll&&"y"!==n.axis){i.css({width:"auto","min-width":0,"overflow-x":"scroll"});var r=Math.ceil(i[0].scrollWidth);3===n.advanced.autoExpandHorizontalScroll||2!==n.advanced.autoExpandHorizontalScroll&&r>i.parent().width()?i.css({width:r,"min-width":"100%","overflow-x":"inherit"}):i.css({"overflow-x":"inherit",position:"absolute"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({width:Math.ceil(i[0].getBoundingClientRect().right+.4)-Math.floor(i[0].getBoundingClientRect().left),"min-width":"100%",position:"relative"}).unwrap()}},w=function(){var t=e(this),o=t.data(a),n=o.opt,i=e(".mCSB_"+o.idx+"_scrollbar:first"),r=oe(n.scrollButtons.tabindex)?"tabindex='"+n.scrollButtons.tabindex+"'":"",l=["<a href='#' class='"+d[13]+"' "+r+" />","<a href='#' class='"+d[14]+"' "+r+" />","<a href='#' class='"+d[15]+"' "+r+" />","<a href='#' class='"+d[16]+"' "+r+" />"],s=["x"===n.axis?l[2]:l[0],"x"===n.axis?l[3]:l[1],l[2],l[3]];n.scrollButtons.enable&&i.prepend(s[0]).append(s[1]).next(".mCSB_scrollTools").prepend(s[2]).append(s[3])},S=function(){var t=e(this),o=t.data(a),n=e("#mCSB_"+o.idx),i=e("#mCSB_"+o.idx+"_container"),r=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],l=[n.height()/i.outerHeight(!1),n.width()/i.outerWidth(!1)],c=[parseInt(r[0].css("min-height")),Math.round(l[0]*r[0].parent().height()),parseInt(r[1].css("min-width")),Math.round(l[1]*r[1].parent().width())],d=s&&c[1]<c[0]?c[0]:c[1],u=s&&c[3]<c[2]?c[2]:c[3];r[0].css({height:d,"max-height":r[0].parent().height()-10}).find(".mCSB_dragger_bar").css({"line-height":c[0]+"px"}),r[1].css({width:u,"max-width":r[1].parent().width()-10})},b=function(){var t=e(this),o=t.data(a),n=e("#mCSB_"+o.idx),i=e("#mCSB_"+o.idx+"_container"),r=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],l=[i.outerHeight(!1)-n.height(),i.outerWidth(!1)-n.width()],s=[l[0]/(r[0].parent().height()-r[0].height()),l[1]/(r[1].parent().width()-r[1].width())];o.scrollRatio={y:s[0],x:s[1]}},C=function(e,t,o){var a=o?d[0]+"_expanded":"",n=e.closest(".mCSB_scrollTools");"active"===t?(e.toggleClass(d[0]+" "+a),n.toggleClass(d[1]),e[0]._draggable=e[0]._draggable?0:1):e[0]._draggable||("hide"===t?(e.removeClass(d[0]),n.removeClass(d[1])):(e.addClass(d[0]),n.addClass(d[1])))},y=function(){var t=e(this),o=t.data(a),n=e("#mCSB_"+o.idx),i=e("#mCSB_"+o.idx+"_container"),r=null==o.overflowed?i.height():i.outerHeight(!1),l=null==o.overflowed?i.width():i.outerWidth(!1),s=i[0].scrollHeight,c=i[0].scrollWidth;return s>r&&(r=s),c>l&&(l=c),[r>n.height(),l>n.width()]},B=function(){var t=e(this),o=t.data(a),n=o.opt,i=e("#mCSB_"+o.idx),r=e("#mCSB_"+o.idx+"_container"),l=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")];if(Q(t),("x"!==n.axis&&!o.overflowed[0]||"y"===n.axis&&o.overflowed[0])&&(l[0].add(r).css("top",0),G(t,"_resetY")),"y"!==n.axis&&!o.overflowed[1]||"x"===n.axis&&o.overflowed[1]){var s=dx=0;"rtl"===o.langDir&&(s=i.width()-r.outerWidth(!1),dx=Math.abs(s/o.scrollRatio.x)),r.css("left",s),l[1].css("left",dx),G(t,"_resetX")}},T=function(){function t(){r=setTimeout(function(){e.event.special.mousewheel?(clearTimeout(r),W.call(o[0])):t()},100)}var o=e(this),n=o.data(a),i=n.opt;if(!n.bindEvents){if(I.call(this),i.contentTouchScroll&&D.call(this),E.call(this),i.mouseWheel.enable){var r;t()}P.call(this),U.call(this),i.advanced.autoScrollOnFocus&&H.call(this),i.scrollButtons.enable&&F.call(this),i.keyboard.enable&&q.call(this),n.bindEvents=!0}},k=function(){var t=e(this),o=t.data(a),n=o.opt,i=a+"_"+o.idx,r=".mCSB_"+o.idx+"_scrollbar",l=e("#mCSB_"+o.idx+",#mCSB_"+o.idx+"_container,#mCSB_"+o.idx+"_container_wrapper,"+r+" ."+d[12]+",#mCSB_"+o.idx+"_dragger_vertical,#mCSB_"+o.idx+"_dragger_horizontal,"+r+">a"),s=e("#mCSB_"+o.idx+"_container");n.advanced.releaseDraggableSelectors&&l.add(e(n.advanced.releaseDraggableSelectors)),n.advanced.extraDraggableSelectors&&l.add(e(n.advanced.extraDraggableSelectors)),o.bindEvents&&(e(document).add(e(!A()||top.document)).unbind("."+i),l.each(function(){e(this).unbind("."+i)}),clearTimeout(t[0]._focusTimeout),$(t[0],"_focusTimeout"),clearTimeout(o.sequential.step),$(o.sequential,"step"),clearTimeout(s[0].onCompleteTimeout),$(s[0],"onCompleteTimeout"),o.bindEvents=!1)},M=function(t){var o=e(this),n=o.data(a),i=n.opt,r=e("#mCSB_"+n.idx+"_container_wrapper"),l=r.length?r:e("#mCSB_"+n.idx+"_container"),s=[e("#mCSB_"+n.idx+"_scrollbar_vertical"),e("#mCSB_"+n.idx+"_scrollbar_horizontal")],c=[s[0].find(".mCSB_dragger"),s[1].find(".mCSB_dragger")];"x"!==i.axis&&(n.overflowed[0]&&!t?(s[0].add(c[0]).add(s[0].children("a")).css("display","block"),l.removeClass(d[8]+" "+d[10])):(i.alwaysShowScrollbar?(2!==i.alwaysShowScrollbar&&c[0].css("display","none"),l.removeClass(d[10])):(s[0].css("display","none"),l.addClass(d[10])),l.addClass(d[8]))),"y"!==i.axis&&(n.overflowed[1]&&!t?(s[1].add(c[1]).add(s[1].children("a")).css("display","block"),l.removeClass(d[9]+" "+d[11])):(i.alwaysShowScrollbar?(2!==i.alwaysShowScrollbar&&c[1].css("display","none"),l.removeClass(d[11])):(s[1].css("display","none"),l.addClass(d[11])),l.addClass(d[9]))),n.overflowed[0]||n.overflowed[1]?o.removeClass(d[5]):o.addClass(d[5])},O=function(t){var o=t.type,a=t.target.ownerDocument!==document&&null!==frameElement?[e(frameElement).offset().top,e(frameElement).offset().left]:null,n=A()&&t.target.ownerDocument!==top.document&&null!==frameElement?[e(t.view.frameElement).offset().top,e(t.view.frameElement).offset().left]:[0,0];switch(o){case"pointerdown":case"MSPointerDown":case"pointermove":case"MSPointerMove":case"pointerup":case"MSPointerUp":return a?[t.originalEvent.pageY-a[0]+n[0],t.originalEvent.pageX-a[1]+n[1],!1]:[t.originalEvent.pageY,t.originalEvent.pageX,!1];case"touchstart":case"touchmove":case"touchend":var i=t.originalEvent.touches[0]||t.originalEvent.changedTouches[0],r=t.originalEvent.touches.length||t.originalEvent.changedTouches.length;return t.target.ownerDocument!==document?[i.screenY,i.screenX,r>1]:[i.pageY,i.pageX,r>1];default:return a?[t.pageY-a[0]+n[0],t.pageX-a[1]+n[1],!1]:[t.pageY,t.pageX,!1]}},I=function(){function t(e,t,a,n){if(h[0].idleTimer=d.scrollInertia<233?250:0,o.attr("id")===f[1])var i="x",s=(o[0].offsetLeft-t+n)*l.scrollRatio.x;else var i="y",s=(o[0].offsetTop-e+a)*l.scrollRatio.y;G(r,s.toString(),{dir:i,drag:!0})}var o,n,i,r=e(this),l=r.data(a),d=l.opt,u=a+"_"+l.idx,f=["mCSB_"+l.idx+"_dragger_vertical","mCSB_"+l.idx+"_dragger_horizontal"],h=e("#mCSB_"+l.idx+"_container"),m=e("#"+f[0]+",#"+f[1]),p=d.advanced.releaseDraggableSelectors?m.add(e(d.advanced.releaseDraggableSelectors)):m,g=d.advanced.extraDraggableSelectors?e(!A()||top.document).add(e(d.advanced.extraDraggableSelectors)):e(!A()||top.document);m.bind("contextmenu."+u,function(e){e.preventDefault()}).bind("mousedown."+u+" touchstart."+u+" pointerdown."+u+" MSPointerDown."+u,function(t){if(t.stopImmediatePropagation(),t.preventDefault(),ee(t)){c=!0,s&&(document.onselectstart=function(){return!1}),L.call(h,!1),Q(r),o=e(this);var a=o.offset(),l=O(t)[0]-a.top,u=O(t)[1]-a.left,f=o.height()+a.top,m=o.width()+a.left;f>l&&l>0&&m>u&&u>0&&(n=l,i=u),C(o,"active",d.autoExpandScrollbar)}}).bind("touchmove."+u,function(e){e.stopImmediatePropagation(),e.preventDefault();var a=o.offset(),r=O(e)[0]-a.top,l=O(e)[1]-a.left;t(n,i,r,l)}),e(document).add(g).bind("mousemove."+u+" pointermove."+u+" MSPointerMove."+u,function(e){if(o){var a=o.offset(),r=O(e)[0]-a.top,l=O(e)[1]-a.left;if(n===r&&i===l)return;t(n,i,r,l)}}).add(p).bind("mouseup."+u+" touchend."+u+" pointerup."+u+" MSPointerUp."+u,function(){o&&(C(o,"active",d.autoExpandScrollbar),o=null),c=!1,s&&(document.onselectstart=null),L.call(h,!0)})},D=function(){function o(e){if(!te(e)||c||O(e)[2])return void(t=0);t=1,b=0,C=0,d=1,y.removeClass("mCS_touch_action");var o=I.offset();u=O(e)[0]-o.top,f=O(e)[1]-o.left,z=[O(e)[0],O(e)[1]]}function n(e){if(te(e)&&!c&&!O(e)[2]&&(T.documentTouchScroll||e.preventDefault(),e.stopImmediatePropagation(),(!C||b)&&d)){g=K();var t=M.offset(),o=O(e)[0]-t.top,a=O(e)[1]-t.left,n="mcsLinearOut";if(E.push(o),W.push(a),z[2]=Math.abs(O(e)[0]-z[0]),z[3]=Math.abs(O(e)[1]-z[1]),B.overflowed[0])var i=D[0].parent().height()-D[0].height(),r=u-o>0&&o-u>-(i*B.scrollRatio.y)&&(2*z[3]<z[2]||"yx"===T.axis);if(B.overflowed[1])var l=D[1].parent().width()-D[1].width(),h=f-a>0&&a-f>-(l*B.scrollRatio.x)&&(2*z[2]<z[3]||"yx"===T.axis);r||h?(U||e.preventDefault(),b=1):(C=1,y.addClass("mCS_touch_action")),U&&e.preventDefault(),w="yx"===T.axis?[u-o,f-a]:"x"===T.axis?[null,f-a]:[u-o,null],I[0].idleTimer=250,B.overflowed[0]&&s(w[0],R,n,"y","all",!0),B.overflowed[1]&&s(w[1],R,n,"x",L,!0)}}function i(e){if(!te(e)||c||O(e)[2])return void(t=0);t=1,e.stopImmediatePropagation(),Q(y),p=K();var o=M.offset();h=O(e)[0]-o.top,m=O(e)[1]-o.left,E=[],W=[]}function r(e){if(te(e)&&!c&&!O(e)[2]){d=0,e.stopImmediatePropagation(),b=0,C=0,v=K();var t=M.offset(),o=O(e)[0]-t.top,a=O(e)[1]-t.left;if(!(v-g>30)){_=1e3/(v-p);var n="mcsEaseOut",i=2.5>_,r=i?[E[E.length-2],W[W.length-2]]:[0,0];x=i?[o-r[0],a-r[1]]:[o-h,a-m];var u=[Math.abs(x[0]),Math.abs(x[1])];_=i?[Math.abs(x[0]/4),Math.abs(x[1]/4)]:[_,_];var f=[Math.abs(I[0].offsetTop)-x[0]*l(u[0]/_[0],_[0]),Math.abs(I[0].offsetLeft)-x[1]*l(u[1]/_[1],_[1])];w="yx"===T.axis?[f[0],f[1]]:"x"===T.axis?[null,f[1]]:[f[0],null],S=[4*u[0]+T.scrollInertia,4*u[1]+T.scrollInertia];var y=parseInt(T.contentTouchScroll)||0;w[0]=u[0]>y?w[0]:0,w[1]=u[1]>y?w[1]:0,B.overflowed[0]&&s(w[0],S[0],n,"y",L,!1),B.overflowed[1]&&s(w[1],S[1],n,"x",L,!1)}}}function l(e,t){var o=[1.5*t,2*t,t/1.5,t/2];return e>90?t>4?o[0]:o[3]:e>60?t>3?o[3]:o[2]:e>30?t>8?o[1]:t>6?o[0]:t>4?t:o[2]:t>8?t:o[3]}function s(e,t,o,a,n,i){e&&G(y,e.toString(),{dur:t,scrollEasing:o,dir:a,overwrite:n,drag:i})}var d,u,f,h,m,p,g,v,x,_,w,S,b,C,y=e(this),B=y.data(a),T=B.opt,k=a+"_"+B.idx,M=e("#mCSB_"+B.idx),I=e("#mCSB_"+B.idx+"_container"),D=[e("#mCSB_"+B.idx+"_dragger_vertical"),e("#mCSB_"+B.idx+"_dragger_horizontal")],E=[],W=[],R=0,L="yx"===T.axis?"none":"all",z=[],P=I.find("iframe"),H=["touchstart."+k+" pointerdown."+k+" MSPointerDown."+k,"touchmove."+k+" pointermove."+k+" MSPointerMove."+k,"touchend."+k+" pointerup."+k+" MSPointerUp."+k],U=void 0!==document.body.style.touchAction&&""!==document.body.style.touchAction;I.bind(H[0],function(e){o(e)}).bind(H[1],function(e){n(e)}),M.bind(H[0],function(e){i(e)}).bind(H[2],function(e){r(e)}),P.length&&P.each(function(){e(this).bind("load",function(){A(this)&&e(this.contentDocument||this.contentWindow.document).bind(H[0],function(e){o(e),i(e)}).bind(H[1],function(e){n(e)}).bind(H[2],function(e){r(e)})})})},E=function(){function o(){return window.getSelection?window.getSelection().toString():document.selection&&"Control"!=document.selection.type?document.selection.createRange().text:0}function n(e,t,o){d.type=o&&i?"stepped":"stepless",d.scrollAmount=10,j(r,e,t,"mcsLinearOut",o?60:null)}var i,r=e(this),l=r.data(a),s=l.opt,d=l.sequential,u=a+"_"+l.idx,f=e("#mCSB_"+l.idx+"_container"),h=f.parent();f.bind("mousedown."+u,function(){t||i||(i=1,c=!0)}).add(document).bind("mousemove."+u,function(e){if(!t&&i&&o()){var a=f.offset(),r=O(e)[0]-a.top+f[0].offsetTop,c=O(e)[1]-a.left+f[0].offsetLeft;r>0&&r<h.height()&&c>0&&c<h.width()?d.step&&n("off",null,"stepped"):("x"!==s.axis&&l.overflowed[0]&&(0>r?n("on",38):r>h.height()&&n("on",40)),"y"!==s.axis&&l.overflowed[1]&&(0>c?n("on",37):c>h.width()&&n("on",39)))}}).bind("mouseup."+u+" dragend."+u,function(){t||(i&&(i=0,n("off",null)),c=!1)})},W=function(){function t(t,a){if(Q(o),!z(o,t.target)){var r="auto"!==i.mouseWheel.deltaFactor?parseInt(i.mouseWheel.deltaFactor):s&&t.deltaFactor<100?100:t.deltaFactor||100,d=i.scrollInertia;if("x"===i.axis||"x"===i.mouseWheel.axis)var u="x",f=[Math.round(r*n.scrollRatio.x),parseInt(i.mouseWheel.scrollAmount)],h="auto"!==i.mouseWheel.scrollAmount?f[1]:f[0]>=l.width()?.9*l.width():f[0],m=Math.abs(e("#mCSB_"+n.idx+"_container")[0].offsetLeft),p=c[1][0].offsetLeft,g=c[1].parent().width()-c[1].width(),v="y"===i.mouseWheel.axis?t.deltaY||a:t.deltaX;else var u="y",f=[Math.round(r*n.scrollRatio.y),parseInt(i.mouseWheel.scrollAmount)],h="auto"!==i.mouseWheel.scrollAmount?f[1]:f[0]>=l.height()?.9*l.height():f[0],m=Math.abs(e("#mCSB_"+n.idx+"_container")[0].offsetTop),p=c[0][0].offsetTop,g=c[0].parent().height()-c[0].height(),v=t.deltaY||a;"y"===u&&!n.overflowed[0]||"x"===u&&!n.overflowed[1]||((i.mouseWheel.invert||t.webkitDirectionInvertedFromDevice)&&(v=-v),i.mouseWheel.normalizeDelta&&(v=0>v?-1:1),(v>0&&0!==p||0>v&&p!==g||i.mouseWheel.preventDefault)&&(t.stopImmediatePropagation(),t.preventDefault()),t.deltaFactor<5&&!i.mouseWheel.normalizeDelta&&(h=t.deltaFactor,d=17),G(o,(m-v*h).toString(),{dir:u,dur:d}))}}if(e(this).data(a)){var o=e(this),n=o.data(a),i=n.opt,r=a+"_"+n.idx,l=e("#mCSB_"+n.idx),c=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")],d=e("#mCSB_"+n.idx+"_container").find("iframe");d.length&&d.each(function(){e(this).bind("load",function(){A(this)&&e(this.contentDocument||this.contentWindow.document).bind("mousewheel."+r,function(e,o){t(e,o)})})}),l.bind("mousewheel."+r,function(e,o){t(e,o)})}},R=new Object,A=function(t){var o=!1,a=!1,n=null;if(void 0===t?a="#empty":void 0!==e(t).attr("id")&&(a=e(t).attr("id")),a!==!1&&void 0!==R[a])return R[a];if(t){try{var i=t.contentDocument||t.contentWindow.document;n=i.body.innerHTML}catch(r){}o=null!==n}else{try{var i=top.document;n=i.body.innerHTML}catch(r){}o=null!==n}return a!==!1&&(R[a]=o),o},L=function(e){var t=this.find("iframe");if(t.length){var o=e?"auto":"none";t.css("pointer-events",o)}},z=function(t,o){var n=o.nodeName.toLowerCase(),i=t.data(a).opt.mouseWheel.disableOver,r=["select","textarea"];return e.inArray(n,i)>-1&&!(e.inArray(n,r)>-1&&!e(o).is(":focus"))},P=function(){var t,o=e(this),n=o.data(a),i=a+"_"+n.idx,r=e("#mCSB_"+n.idx+"_container"),l=r.parent(),s=e(".mCSB_"+n.idx+"_scrollbar ."+d[12]);s.bind("mousedown."+i+" touchstart."+i+" pointerdown."+i+" MSPointerDown."+i,function(o){c=!0,e(o.target).hasClass("mCSB_dragger")||(t=1)}).bind("touchend."+i+" pointerup."+i+" MSPointerUp."+i,function(){c=!1}).bind("click."+i,function(a){if(t&&(t=0,e(a.target).hasClass(d[12])||e(a.target).hasClass("mCSB_draggerRail"))){Q(o);var i=e(this),s=i.find(".mCSB_dragger");if(i.parent(".mCSB_scrollTools_horizontal").length>0){if(!n.overflowed[1])return;var c="x",u=a.pageX>s.offset().left?-1:1,f=Math.abs(r[0].offsetLeft)-u*(.9*l.width())}else{if(!n.overflowed[0])return;var c="y",u=a.pageY>s.offset().top?-1:1,f=Math.abs(r[0].offsetTop)-u*(.9*l.height())}G(o,f.toString(),{dir:c,scrollEasing:"mcsEaseInOut"})}})},H=function(){var t=e(this),o=t.data(a),n=o.opt,i=a+"_"+o.idx,r=e("#mCSB_"+o.idx+"_container"),l=r.parent();r.bind("focusin."+i,function(){var o=e(document.activeElement),a=r.find(".mCustomScrollBox").length,i=0;o.is(n.advanced.autoScrollOnFocus)&&(Q(t),clearTimeout(t[0]._focusTimeout),t[0]._focusTimer=a?(i+17)*a:0,t[0]._focusTimeout=setTimeout(function(){var e=[ae(o)[0],ae(o)[1]],a=[r[0].offsetTop,r[0].offsetLeft],s=[a[0]+e[0]>=0&&a[0]+e[0]<l.height()-o.outerHeight(!1),a[1]+e[1]>=0&&a[0]+e[1]<l.width()-o.outerWidth(!1)],c="yx"!==n.axis||s[0]||s[1]?"all":"none";"x"===n.axis||s[0]||G(t,e[0].toString(),{dir:"y",scrollEasing:"mcsEaseInOut",overwrite:c,dur:i}),"y"===n.axis||s[1]||G(t,e[1].toString(),{dir:"x",scrollEasing:"mcsEaseInOut",overwrite:c,dur:i})},t[0]._focusTimer))})},U=function(){var t=e(this),o=t.data(a),n=a+"_"+o.idx,i=e("#mCSB_"+o.idx+"_container").parent();i.bind("scroll."+n,function(){0===i.scrollTop()&&0===i.scrollLeft()||e(".mCSB_"+o.idx+"_scrollbar").css("visibility","hidden")})},F=function(){var t=e(this),o=t.data(a),n=o.opt,i=o.sequential,r=a+"_"+o.idx,l=".mCSB_"+o.idx+"_scrollbar",s=e(l+">a");s.bind("contextmenu."+r,function(e){e.preventDefault()}).bind("mousedown."+r+" touchstart."+r+" pointerdown."+r+" MSPointerDown."+r+" mouseup."+r+" touchend."+r+" pointerup."+r+" MSPointerUp."+r+" mouseout."+r+" pointerout."+r+" MSPointerOut."+r+" click."+r,function(a){function r(e,o){i.scrollAmount=n.scrollButtons.scrollAmount,j(t,e,o)}if(a.preventDefault(),ee(a)){var l=e(this).attr("class");switch(i.type=n.scrollButtons.scrollType,a.type){case"mousedown":case"touchstart":case"pointerdown":case"MSPointerDown":if("stepped"===i.type)return;c=!0,o.tweenRunning=!1,r("on",l);break;case"mouseup":case"touchend":case"pointerup":case"MSPointerUp":case"mouseout":case"pointerout":case"MSPointerOut":if("stepped"===i.type)return;c=!1,i.dir&&r("off",l);break;case"click":if("stepped"!==i.type||o.tweenRunning)return;r("on",l)}}})},q=function(){function t(t){function a(e,t){r.type=i.keyboard.scrollType,r.scrollAmount=i.keyboard.scrollAmount,"stepped"===r.type&&n.tweenRunning||j(o,e,t)}switch(t.type){case"blur":n.tweenRunning&&r.dir&&a("off",null);break;case"keydown":case"keyup":var l=t.keyCode?t.keyCode:t.which,s="on";if("x"!==i.axis&&(38===l||40===l)||"y"!==i.axis&&(37===l||39===l)){if((38===l||40===l)&&!n.overflowed[0]||(37===l||39===l)&&!n.overflowed[1])return;"keyup"===t.type&&(s="off"),e(document.activeElement).is(u)||(t.preventDefault(),t.stopImmediatePropagation(),a(s,l))}else if(33===l||34===l){if((n.overflowed[0]||n.overflowed[1])&&(t.preventDefault(),t.stopImmediatePropagation()),"keyup"===t.type){Q(o);var f=34===l?-1:1;if("x"===i.axis||"yx"===i.axis&&n.overflowed[1]&&!n.overflowed[0])var h="x",m=Math.abs(c[0].offsetLeft)-f*(.9*d.width());else var h="y",m=Math.abs(c[0].offsetTop)-f*(.9*d.height());G(o,m.toString(),{dir:h,scrollEasing:"mcsEaseInOut"})}}else if((35===l||36===l)&&!e(document.activeElement).is(u)&&((n.overflowed[0]||n.overflowed[1])&&(t.preventDefault(),t.stopImmediatePropagation()),"keyup"===t.type)){if("x"===i.axis||"yx"===i.axis&&n.overflowed[1]&&!n.overflowed[0])var h="x",m=35===l?Math.abs(d.width()-c.outerWidth(!1)):0;else var h="y",m=35===l?Math.abs(d.height()-c.outerHeight(!1)):0;G(o,m.toString(),{dir:h,scrollEasing:"mcsEaseInOut"})}}}var o=e(this),n=o.data(a),i=n.opt,r=n.sequential,l=a+"_"+n.idx,s=e("#mCSB_"+n.idx),c=e("#mCSB_"+n.idx+"_container"),d=c.parent(),u="input,textarea,select,datalist,keygen,[contenteditable='true']",f=c.find("iframe"),h=["blur."+l+" keydown."+l+" keyup."+l];f.length&&f.each(function(){e(this).bind("load",function(){A(this)&&e(this.contentDocument||this.contentWindow.document).bind(h[0],function(e){t(e)})})}),s.attr("tabindex","0").bind(h[0],function(e){t(e)})},j=function(t,o,n,i,r){function l(e){u.snapAmount&&(f.scrollAmount=u.snapAmount instanceof Array?"x"===f.dir[0]?u.snapAmount[1]:u.snapAmount[0]:u.snapAmount);var o="stepped"!==f.type,a=r?r:e?o?p/1.5:g:1e3/60,n=e?o?7.5:40:2.5,s=[Math.abs(h[0].offsetTop),Math.abs(h[0].offsetLeft)],d=[c.scrollRatio.y>10?10:c.scrollRatio.y,c.scrollRatio.x>10?10:c.scrollRatio.x],m="x"===f.dir[0]?s[1]+f.dir[1]*(d[1]*n):s[0]+f.dir[1]*(d[0]*n),v="x"===f.dir[0]?s[1]+f.dir[1]*parseInt(f.scrollAmount):s[0]+f.dir[1]*parseInt(f.scrollAmount),x="auto"!==f.scrollAmount?v:m,_=i?i:e?o?"mcsLinearOut":"mcsEaseInOut":"mcsLinear",w=!!e;return e&&17>a&&(x="x"===f.dir[0]?s[1]:s[0]),G(t,x.toString(),{dir:f.dir[0],scrollEasing:_,dur:a,onComplete:w}),e?void(f.dir=!1):(clearTimeout(f.step),void(f.step=setTimeout(function(){l()},a)))}function s(){clearTimeout(f.step),$(f,"step"),Q(t)}var c=t.data(a),u=c.opt,f=c.sequential,h=e("#mCSB_"+c.idx+"_container"),m="stepped"===f.type,p=u.scrollInertia<26?26:u.scrollInertia,g=u.scrollInertia<1?17:u.scrollInertia;switch(o){case"on":if(f.dir=[n===d[16]||n===d[15]||39===n||37===n?"x":"y",n===d[13]||n===d[15]||38===n||37===n?-1:1],Q(t),oe(n)&&"stepped"===f.type)return;l(m);break;case"off":s(),(m||c.tweenRunning&&f.dir)&&l(!0)}},Y=function(t){var o=e(this).data(a).opt,n=[];return"function"==typeof t&&(t=t()),t instanceof Array?n=t.length>1?[t[0],t[1]]:"x"===o.axis?[null,t[0]]:[t[0],null]:(n[0]=t.y?t.y:t.x||"x"===o.axis?null:t,n[1]=t.x?t.x:t.y||"y"===o.axis?null:t),"function"==typeof n[0]&&(n[0]=n[0]()),"function"==typeof n[1]&&(n[1]=n[1]()),n},X=function(t,o){if(null!=t&&"undefined"!=typeof t){var n=e(this),i=n.data(a),r=i.opt,l=e("#mCSB_"+i.idx+"_container"),s=l.parent(),c=typeof t;o||(o="x"===r.axis?"x":"y");var d="x"===o?l.outerWidth(!1)-s.width():l.outerHeight(!1)-s.height(),f="x"===o?l[0].offsetLeft:l[0].offsetTop,h="x"===o?"left":"top";switch(c){case"function":return t();case"object":var m=t.jquery?t:e(t);if(!m.length)return;return"x"===o?ae(m)[1]:ae(m)[0];case"string":case"number":if(oe(t))return Math.abs(t);if(-1!==t.indexOf("%"))return Math.abs(d*parseInt(t)/100);if(-1!==t.indexOf("-="))return Math.abs(f-parseInt(t.split("-=")[1]));if(-1!==t.indexOf("+=")){var p=f+parseInt(t.split("+=")[1]);return p>=0?0:Math.abs(p)}if(-1!==t.indexOf("px")&&oe(t.split("px")[0]))return Math.abs(t.split("px")[0]);if("top"===t||"left"===t)return 0;if("bottom"===t)return Math.abs(s.height()-l.outerHeight(!1));if("right"===t)return Math.abs(s.width()-l.outerWidth(!1));if("first"===t||"last"===t){var m=l.find(":"+t);return"x"===o?ae(m)[1]:ae(m)[0]}return e(t).length?"x"===o?ae(e(t))[1]:ae(e(t))[0]:(l.css(h,t),void u.update.call(null,n[0]))}}},N=function(t){function o(){return clearTimeout(f[0].autoUpdate),0===l.parents("html").length?void(l=null):void(f[0].autoUpdate=setTimeout(function(){return c.advanced.updateOnSelectorChange&&(s.poll.change.n=i(),s.poll.change.n!==s.poll.change.o)?(s.poll.change.o=s.poll.change.n,void r(3)):c.advanced.updateOnContentResize&&(s.poll.size.n=l[0].scrollHeight+l[0].scrollWidth+f[0].offsetHeight+l[0].offsetHeight+l[0].offsetWidth,s.poll.size.n!==s.poll.size.o)?(s.poll.size.o=s.poll.size.n,void r(1)):!c.advanced.updateOnImageLoad||"auto"===c.advanced.updateOnImageLoad&&"y"===c.axis||(s.poll.img.n=f.find("img").length,s.poll.img.n===s.poll.img.o)?void((c.advanced.updateOnSelectorChange||c.advanced.updateOnContentResize||c.advanced.updateOnImageLoad)&&o()):(s.poll.img.o=s.poll.img.n,void f.find("img").each(function(){n(this)}))},c.advanced.autoUpdateTimeout))}function n(t){function o(e,t){return function(){
return t.apply(e,arguments)}}function a(){this.onload=null,e(t).addClass(d[2]),r(2)}if(e(t).hasClass(d[2]))return void r();var n=new Image;n.onload=o(n,a),n.src=t.src}function i(){c.advanced.updateOnSelectorChange===!0&&(c.advanced.updateOnSelectorChange="*");var e=0,t=f.find(c.advanced.updateOnSelectorChange);return c.advanced.updateOnSelectorChange&&t.length>0&&t.each(function(){e+=this.offsetHeight+this.offsetWidth}),e}function r(e){clearTimeout(f[0].autoUpdate),u.update.call(null,l[0],e)}var l=e(this),s=l.data(a),c=s.opt,f=e("#mCSB_"+s.idx+"_container");return t?(clearTimeout(f[0].autoUpdate),void $(f[0],"autoUpdate")):void o()},V=function(e,t,o){return Math.round(e/t)*t-o},Q=function(t){var o=t.data(a),n=e("#mCSB_"+o.idx+"_container,#mCSB_"+o.idx+"_container_wrapper,#mCSB_"+o.idx+"_dragger_vertical,#mCSB_"+o.idx+"_dragger_horizontal");n.each(function(){Z.call(this)})},G=function(t,o,n){function i(e){return s&&c.callbacks[e]&&"function"==typeof c.callbacks[e]}function r(){return[c.callbacks.alwaysTriggerOffsets||w>=S[0]+y,c.callbacks.alwaysTriggerOffsets||-B>=w]}function l(){var e=[h[0].offsetTop,h[0].offsetLeft],o=[x[0].offsetTop,x[0].offsetLeft],a=[h.outerHeight(!1),h.outerWidth(!1)],i=[f.height(),f.width()];t[0].mcs={content:h,top:e[0],left:e[1],draggerTop:o[0],draggerLeft:o[1],topPct:Math.round(100*Math.abs(e[0])/(Math.abs(a[0])-i[0])),leftPct:Math.round(100*Math.abs(e[1])/(Math.abs(a[1])-i[1])),direction:n.dir}}var s=t.data(a),c=s.opt,d={trigger:"internal",dir:"y",scrollEasing:"mcsEaseOut",drag:!1,dur:c.scrollInertia,overwrite:"all",callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},n=e.extend(d,n),u=[n.dur,n.drag?0:n.dur],f=e("#mCSB_"+s.idx),h=e("#mCSB_"+s.idx+"_container"),m=h.parent(),p=c.callbacks.onTotalScrollOffset?Y.call(t,c.callbacks.onTotalScrollOffset):[0,0],g=c.callbacks.onTotalScrollBackOffset?Y.call(t,c.callbacks.onTotalScrollBackOffset):[0,0];if(s.trigger=n.trigger,0===m.scrollTop()&&0===m.scrollLeft()||(e(".mCSB_"+s.idx+"_scrollbar").css("visibility","visible"),m.scrollTop(0).scrollLeft(0)),"_resetY"!==o||s.contentReset.y||(i("onOverflowYNone")&&c.callbacks.onOverflowYNone.call(t[0]),s.contentReset.y=1),"_resetX"!==o||s.contentReset.x||(i("onOverflowXNone")&&c.callbacks.onOverflowXNone.call(t[0]),s.contentReset.x=1),"_resetY"!==o&&"_resetX"!==o){if(!s.contentReset.y&&t[0].mcs||!s.overflowed[0]||(i("onOverflowY")&&c.callbacks.onOverflowY.call(t[0]),s.contentReset.x=null),!s.contentReset.x&&t[0].mcs||!s.overflowed[1]||(i("onOverflowX")&&c.callbacks.onOverflowX.call(t[0]),s.contentReset.x=null),c.snapAmount){var v=c.snapAmount instanceof Array?"x"===n.dir?c.snapAmount[1]:c.snapAmount[0]:c.snapAmount;o=V(o,v,c.snapOffset)}switch(n.dir){case"x":var x=e("#mCSB_"+s.idx+"_dragger_horizontal"),_="left",w=h[0].offsetLeft,S=[f.width()-h.outerWidth(!1),x.parent().width()-x.width()],b=[o,0===o?0:o/s.scrollRatio.x],y=p[1],B=g[1],T=y>0?y/s.scrollRatio.x:0,k=B>0?B/s.scrollRatio.x:0;break;case"y":var x=e("#mCSB_"+s.idx+"_dragger_vertical"),_="top",w=h[0].offsetTop,S=[f.height()-h.outerHeight(!1),x.parent().height()-x.height()],b=[o,0===o?0:o/s.scrollRatio.y],y=p[0],B=g[0],T=y>0?y/s.scrollRatio.y:0,k=B>0?B/s.scrollRatio.y:0}b[1]<0||0===b[0]&&0===b[1]?b=[0,0]:b[1]>=S[1]?b=[S[0],S[1]]:b[0]=-b[0],t[0].mcs||(l(),i("onInit")&&c.callbacks.onInit.call(t[0])),clearTimeout(h[0].onCompleteTimeout),J(x[0],_,Math.round(b[1]),u[1],n.scrollEasing),!s.tweenRunning&&(0===w&&b[0]>=0||w===S[0]&&b[0]<=S[0])||J(h[0],_,Math.round(b[0]),u[0],n.scrollEasing,n.overwrite,{onStart:function(){n.callbacks&&n.onStart&&!s.tweenRunning&&(i("onScrollStart")&&(l(),c.callbacks.onScrollStart.call(t[0])),s.tweenRunning=!0,C(x),s.cbOffsets=r())},onUpdate:function(){n.callbacks&&n.onUpdate&&i("whileScrolling")&&(l(),c.callbacks.whileScrolling.call(t[0]))},onComplete:function(){if(n.callbacks&&n.onComplete){"yx"===c.axis&&clearTimeout(h[0].onCompleteTimeout);var e=h[0].idleTimer||0;h[0].onCompleteTimeout=setTimeout(function(){i("onScroll")&&(l(),c.callbacks.onScroll.call(t[0])),i("onTotalScroll")&&b[1]>=S[1]-T&&s.cbOffsets[0]&&(l(),c.callbacks.onTotalScroll.call(t[0])),i("onTotalScrollBack")&&b[1]<=k&&s.cbOffsets[1]&&(l(),c.callbacks.onTotalScrollBack.call(t[0])),s.tweenRunning=!1,h[0].idleTimer=0,C(x,"hide")},e)}}})}},J=function(e,t,o,a,n,i,r){function l(){S.stop||(x||m.call(),x=K()-v,s(),x>=S.time&&(S.time=x>S.time?x+f-(x-S.time):x+f-1,S.time<x+1&&(S.time=x+1)),S.time<a?S.id=h(l):g.call())}function s(){a>0?(S.currVal=u(S.time,_,b,a,n),w[t]=Math.round(S.currVal)+"px"):w[t]=o+"px",p.call()}function c(){f=1e3/60,S.time=x+f,h=window.requestAnimationFrame?window.requestAnimationFrame:function(e){return s(),setTimeout(e,.01)},S.id=h(l)}function d(){null!=S.id&&(window.requestAnimationFrame?window.cancelAnimationFrame(S.id):clearTimeout(S.id),S.id=null)}function u(e,t,o,a,n){switch(n){case"linear":case"mcsLinear":return o*e/a+t;case"mcsLinearOut":return e/=a,e--,o*Math.sqrt(1-e*e)+t;case"easeInOutSmooth":return e/=a/2,1>e?o/2*e*e+t:(e--,-o/2*(e*(e-2)-1)+t);case"easeInOutStrong":return e/=a/2,1>e?o/2*Math.pow(2,10*(e-1))+t:(e--,o/2*(-Math.pow(2,-10*e)+2)+t);case"easeInOut":case"mcsEaseInOut":return e/=a/2,1>e?o/2*e*e*e+t:(e-=2,o/2*(e*e*e+2)+t);case"easeOutSmooth":return e/=a,e--,-o*(e*e*e*e-1)+t;case"easeOutStrong":return o*(-Math.pow(2,-10*e/a)+1)+t;case"easeOut":case"mcsEaseOut":default:var i=(e/=a)*e,r=i*e;return t+o*(.499999999999997*r*i+-2.5*i*i+5.5*r+-6.5*i+4*e)}}e._mTween||(e._mTween={top:{},left:{}});var f,h,r=r||{},m=r.onStart||function(){},p=r.onUpdate||function(){},g=r.onComplete||function(){},v=K(),x=0,_=e.offsetTop,w=e.style,S=e._mTween[t];"left"===t&&(_=e.offsetLeft);var b=o-_;S.stop=0,"none"!==i&&d(),c()},K=function(){return window.performance&&window.performance.now?window.performance.now():window.performance&&window.performance.webkitNow?window.performance.webkitNow():Date.now?Date.now():(new Date).getTime()},Z=function(){var e=this;e._mTween||(e._mTween={top:{},left:{}});for(var t=["top","left"],o=0;o<t.length;o++){var a=t[o];e._mTween[a].id&&(window.requestAnimationFrame?window.cancelAnimationFrame(e._mTween[a].id):clearTimeout(e._mTween[a].id),e._mTween[a].id=null,e._mTween[a].stop=1)}},$=function(e,t){try{delete e[t]}catch(o){e[t]=null}},ee=function(e){return!(e.which&&1!==e.which)},te=function(e){var t=e.originalEvent.pointerType;return!(t&&"touch"!==t&&2!==t)},oe=function(e){return!isNaN(parseFloat(e))&&isFinite(e)},ae=function(e){var t=e.parents(".mCSB_container");return[e.offset().top-t.offset().top,e.offset().left-t.offset().left]},ne=function(){function e(){var e=["webkit","moz","ms","o"];if("hidden"in document)return"hidden";for(var t=0;t<e.length;t++)if(e[t]+"Hidden"in document)return e[t]+"Hidden";return null}var t=e();return t?document[t]:!1};e.fn[o]=function(t){return u[t]?u[t].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof t&&t?void e.error("Method "+t+" does not exist"):u.init.apply(this,arguments)},e[o]=function(t){return u[t]?u[t].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof t&&t?void e.error("Method "+t+" does not exist"):u.init.apply(this,arguments)},e[o].defaults=i,window[o]=!0,e(window).bind("load",function(){e(n)[o](),e.extend(e.expr[":"],{mcsInView:e.expr[":"].mcsInView||function(t){var o,a,n=e(t),i=n.parents(".mCSB_container");if(i.length)return o=i.parent(),a=[i[0].offsetTop,i[0].offsetLeft],a[0]+ae(n)[0]>=0&&a[0]+ae(n)[0]<o.height()-n.outerHeight(!1)&&a[1]+ae(n)[1]>=0&&a[1]+ae(n)[1]<o.width()-n.outerWidth(!1)},mcsInSight:e.expr[":"].mcsInSight||function(t,o,a){var n,i,r,l,s=e(t),c=s.parents(".mCSB_container"),d="exact"===a[3]?[[1,0],[1,0]]:[[.9,.1],[.6,.4]];if(c.length)return n=[s.outerHeight(!1),s.outerWidth(!1)],r=[c[0].offsetTop+ae(s)[0],c[0].offsetLeft+ae(s)[1]],i=[c.parent()[0].offsetHeight,c.parent()[0].offsetWidth],l=[n[0]<i[0]?d[0]:d[1],n[1]<i[1]?d[0]:d[1]],r[0]-i[0]*l[0][0]<0&&r[0]+n[0]-i[0]*l[0][1]>=0&&r[1]-i[1]*l[1][0]<0&&r[1]+n[1]-i[1]*l[1][1]>=0},mcsOverflow:e.expr[":"].mcsOverflow||function(t){var o=e(t).data(a);if(o)return o.overflowed[0]||o.overflowed[1]}})})})});
///#source 1 1 /Assets/scripts/hospitality-3.5.js
/*
 * ---------------------------------------- *
 * Name: 	AA Hospitality JavaScripts      *
 * Type: 	JavaScript                      *
 * Version: Not Versioned                   *
 * Author:	Aleksander Kisimov | Codehouse  *
 * ---------------------------------------- *
 */
window.aa || (window.aa = {}); //  aa namespace

window.aa.hospitality = {

    // functionality for filters & applied filters section
    globalBoolean: (new function () {
        this.searchButtonPressed = false;
    }()),
    searchFilters: function searchFilters() {
        var $appliedFilters = $(this),
            $filterGroupId = $appliedFilters.find('div[data-filter]'),
            $filterGroup = $appliedFilters.siblings('.filter-group'),
            $appliedFiltersCounter = $appliedFilters.find('.counter'),
            $clearFiltersButton = $appliedFilters.find('.clear-filters'),
            $noFiltersAppliedMessage = $appliedFilters.find('.no-filters');

        // show group heading if there are matched checkboxes
        $filterGroupId.each(function () {
            $appliedFilters.find('h5[data-filter="' + $(this).data('filter') + '"]').show();
        });

        if ($filterGroupId.length) {
            $appliedFilters.add($clearFiltersButton).show();
            $noFiltersAppliedMessage.hide();
        }

        // update counter of filters
        $appliedFiltersCounter.text($appliedFilters.find('.field').length);

        // clear filters
        $clearFiltersButton.on('click', function (e) {
            e.preventDefault();
            $appliedFilters.find('input:checked').trigger('click');
        });

        // clear corresponding property type filter
        $appliedFilters.find('input[data-id]').on('click', function () {
            $filterGroup.find('#' + $(this).data('id')).trigger('click');
        });

        window.aa.hospitality.globalBoolean.searchButtonPressed = false;

        // clear establishmentType hidden input if "type" filter is cleared
        $filterGroup.find('input.establishment-type').on('change', function () {
            if (!$(this).is(':checked') && !window.aa.hospitality.globalBoolean.searchButtonPressed) {
                $filterGroup.closest('.listing').find('#find-place').val('');
                $filterGroup.closest('.listing').find('.establishment-type').val('');
            }
        });
    },
    cropThumbnails: function ($image) {
        //BAU-AMD-222-starts//
        if ($(".cat-count").length > 1) {
            $("#cat-header").show();
        }
        else {
            $("#cat-header").hide();
        }
        //BAU-AMD-222-Ends//
        var $imageContainer = $image.closest('div'),
            image = new Image();

        image.src = $image.prop('tagName') === 'image' ? $image.attr('xlink:href') : $image.attr('src');

        image.onload = function () {
            if (image.naturalHeight > image.naturalWidth) {
                $imageContainer.addClass('portrait-orientation');
            }
        }
    }
};

(function ($) {

    var resizeTimer;
    //BAU-AMD-222-starts//
    $("#cat-header").hide();
    //BAU-AMD-222-ends//
    // determine the size of font based on establishment name length
    function establishmentNameRestriction($thisEstablishment) {

        var $establishmentName = $thisEstablishment.find('.est-name'),
            $establishmentNameString = $establishmentName.children('p').text();

        $establishmentName.removeClass('midlength-title short-title');

        if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && $establishmentNameString.length <= 46 && $establishmentNameString.length > 24) {
            $establishmentName.addClass('midlength-title');
        } else if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && $establishmentNameString.length <= 46 || window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && $establishmentNameString.length <= 24) {
            $establishmentName.addClass('short-title');
        }
    }

    // scroll between tweets
    function scrollTweets() {

        var $thisTwitterFeed = $(this),
            $tweet = $thisTwitterFeed.find('.tweet'),
            $tweetsContainer = $thisTwitterFeed.find('.tweets-container').children(),
            totalTweets = $tweetsContainer.length,
            tweetIndex = $tweet.index();

        // set the latest tweet to active
        $tweet.first().addClass('active');

        // display tweet based on active class
        function activeTweet() {
            $tweetsContainer.removeClass('active');
            $tweetsContainer.eq(tweetIndex).addClass('active');
        }

        // select next tweet
        $thisTwitterFeed.find('.tweet-next').on('click', function () {
            tweetIndex = tweetIndex + 1 > totalTweets - 1 ? 0 : tweetIndex + 1;
            activeTweet();
        });

        // select previous tweet
        $thisTwitterFeed.find('.tweet-prev').on('click', function () {
            tweetIndex = tweetIndex - 1 < 0 ? totalTweets - 1 : tweetIndex - 1;
            activeTweet();
        });
    }

    // truncate text & read more
    function truncationReadMore() {
        var $thisText = $(this),
            $readMore = $thisText.find('.read-more'),
            ellipses = '...',
            characterNr = window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT ? 420 : 690,
            $richText = $thisText.find('.rich-text').find('p'),
            shortText = window.aa.helpers.truncateText($richText.text(), characterNr),
            fullText = $thisText.find('.rich-text').find('p').text().trim();

        if ($readMore != undefined && $readMore.length > 0) {
            /*CD-4683 Fix */
            mbText = $thisText.find('.rich-text').hasClass('mem-ben');

            if (!shortText) {
                return;
            }
            if (mbText) {
                return;
            }

            $richText.text(shortText + ellipses);
            $readMore.removeClass('hidden');

            function readMore() {
                $readMore.addClass('hidden');
                $richText.text('');
                $richText.append(fullText);
                $richText.addClass('height');
            }

            $readMore.on('click', readMore);
        }
    }

    // review bar filled based on value
    function reviewBar() {
        var $thisReviewBar = $(this),
            $fullBar = $thisReviewBar.find('.full-bar'),
            reviewValue = $thisReviewBar.find('.review-value').text();

        $fullBar.css({ width: reviewValue * 10 + '%' });

        if (parseInt(reviewValue) < 5) {
            $fullBar.addClass('grey-rating');
        }

    }

    // hospitality show search result card
    function toggleSearchCard(listing) {

        var $thisListing = listing;

        function toggle(e) {
            var $thisCategory = $(this);
            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                e.stopImmediatePropagation();
                $thisCategory.siblings('.search-results').stop().slideToggle();
                $thisCategory.siblings('.search-results').toggleClass('active');
                $thisCategory.find('.arrow').toggleClass('flipped');
                $thisListing.find('.see-all.paginate').stop().toggle();
            }
        }

        $thisListing.on('click', '.category-title', toggle);
    }

    // fixed sidebar position when scrolling relative to parent height
    function fixedSidebar() {
        var $thisRowParent = $(this),
            $sidebarColumn = $(this).find('.col:last-child'),
            thresholdHeight = $thisRowParent.parent().prev().outerHeight();

        if ($thisRowParent.find('.sidebar-container').length === 0) {
            $sidebarColumn.wrap('<div class="sidebar-container"> </div>');
        }

        function stickyScrollbar() {


            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.TABLET_LANDSCAPE) {
                $sidebarColumn.removeClass('fixed');
            } else {
                var maxHeight = $thisRowParent.height() - $sidebarColumn.height() + thresholdHeight;
                //enable sticky sidebar when user scrolls past treshholdHeight
                if (window.aa.helpers.cache.cachedElements.$window.scrollTop() >= thresholdHeight) {
                    $sidebarColumn.addClass('fixed');
                } else {
                    $sidebarColumn.removeClass('fixed');
                }
                //disable sticky sidebar when maxHeight is reached
                if (window.aa.helpers.cache.cachedElements.$window.scrollTop() >= maxHeight) {
                    $sidebarColumn.addClass('bottom');
                } else {
                    $sidebarColumn.removeClass('bottom');
                }
            }
        }

        stickyScrollbar();

        window.aa.helpers.cache.cachedElements.$window.on('scroll', function () {
            //Start MEM-92
            if ($('#codeNotAvailableModal').length > 0) {
                return false;
            }
            //End MEM-92
            stickyScrollbar();
        });
    }

    function searchInputs() {
        var $thisContainer = $(this),
            $inputsParent = $thisContainer.closest('.inputs'),
            $input = $thisContainer.find('input[type="text"]'),
            $inputBorder = $thisContainer.find('.stylish-text span'),
            $findDestination = $inputsParent.find('#find-destination'),
            $findPlace = $inputsParent.find('#find-place'),
            $clearButton = $thisContainer.find('button.clear-input'),
            results = $thisContainer.find('input[type="hidden"]').val(),
            $establishmentTypeData = $thisContainer.find('.establishment-type'),
            $termData = $thisContainer.find('.data-term'),
            $listing = $thisContainer.closest('.listing'),
            $searchComponentSubmit = $inputsParent.siblings('.search-inputs input[type="submit"].search-component-submit'),
            $searchType = $listing.find('.is-search'),
            placeholderText = $input.attr('placeholder'),
            isSelected = false,
            isLocationAvailable = true,
            inputBlurred = false,
            isFirstSearch,
            serverRequest;

        // if mobile populate destination field on load, otherwise if query string is found
        if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
            if ($findDestination.val() === '') {
                populateLocation($findDestination);
            }
        } else if ($findDestination.val() === '' && window.location.search) {
            populateLocation($findDestination);
        }

        // find whether locations services are available on load and change suggested default result
        navigator.geolocation.getCurrentPosition(function () {
            // on success event handled elsewhere when the user selects a suggestion generated from autocomplete
            return;
        }, function () {
            // on failure event is needed on load to determine the destination suggestion coming from the markup
            $inputsParent.find('.find-destination-hidden').attr('data-label', $inputsParent.find('.location').data('label')).val($inputsParent.find('.location').data('label'));
            $inputsParent.find('.input.destination').addClass('location-unavailable');
            isLocationAvailable = false;
        });

        // find the correct data to populate data-to-send hidden input with
        function populateDataToSend(input, ui) {
            if (input.is('#find-place') && ui.item !== null) {
                if (typeof $('[data-input-id="' + ui.item.label + '"]').data('to-send') === 'undefined') {
                    $termData.val(ui.item.label);
                    $establishmentTypeData.val('');
                } else {
                    $establishmentTypeData.val($('[data-input-id="' + ui.item.label + '"]').data('to-send'));
                }
            } else {
                $termData.val(input.val());
                $establishmentTypeData.val('');
            }

        }

        // store response object according to type
        function buildArray(data, request, callback) {
            var termsData = [],
                label;

            for (var prop in data.Result) {
                // label is either the establishment name or location depending on response
                label = typeof data.Result[prop].EstablishmentName !== 'undefined' ? data.Result[prop].EstablishmentName : data.Result[prop].Description;
                termsData.push({ 'label': label, 'city': data.Result[prop].City, 'placeId': data.Result[prop].PlaceId, 'highlight': data.Result[prop].Highlight, 'url': data.Result[prop].Url });
            }

            // get results from array and filter
            results = $.ui.autocomplete.filter(termsData, request.term);
            if (typeof callback === 'function') {
                callback(results);
            }
        }

        // autocomplete
        $input.autocomplete({
            appendTo: $thisContainer,
            minLength: 0,
            create: function () {
                $(this).data('ui-autocomplete')._renderItem = function (ul, item) {

                    // custom markup
                    function buildListItem() {
                        var markup = [];

                        if ($input.val().length < 3) {
                            markup.push('<span class="icon">' + item.label + ' </span>');
                        } else {
                            markup.push('<span class="establishment-result">' + item.highlight + '</span>');

                            if (typeof item.city !== 'undefined') {
                                markup.push('<span class="location-result">' + item.city + ' </span>');
                            }
                        }
                        return markup.join('');
                    }
                    // wrap typed letters in list for styling
                    if (typeof item.url !== 'undefined') {
                        return $('<a href="' + item.url + '" data-value="' + item.label + '"></a>').data('item.autocomplete', item).html(buildListItem()).appendTo(ul);
                    } else {
                        return $('<li data-value="' + item.label + '"></li>').data('item.autocomplete', item).html(buildListItem()).appendTo(ul);
                    }

                };
            },
            source: function (request, response) {

                if (inputBlurred) {
                    return;
                }

                // reset the results value
                var results = [];

                // get results from a hidden input if input value is empty
                if (request.term.length < 3) {
                    isFirstSearch = true;

                    $thisContainer.find('input[type="hidden"].lookup').each(function () {
                        results.push($(this).val());
                    });

                    response(results);
                    return;
                }

                isFirstSearch = false;
                isSelected = false;

                // prevent calls from stacking due to constant search
                if (typeof serverRequest !== 'undefined') {
                    serverRequest.abort();
                }

                serverRequest = $.ajax({
                    method: $input.data('request-method'),
                    url: $input.data('autocomplete-url'),
                    dataType: 'json',
                    data: { searchText: request.term },
                    success: function (data) {
                        buildArray(data, request, response);
                        if ($input.val() !== '') {
                            $clearButton.show();
                        }
                    }
                });
            },
            select: function (e, ui) {
                isSelected = true;
                populateLocation($(this), ui);
                autoSearch($(this), ui);
            },
            change: function (e, ui) {
                if (!isSelected) {
                    populateLocation($(this), ui);
                }
                populateDataToSend($(this), ui);
            }
        });

        function autoSearch(input, ui) {
            populateDataToSend(input, ui);

            if (input.attr('id') === 'find-destination' && $findPlace.val() === '') {
                // clear call stack causing original input to be refocused
                setTimeout(function () {
                    $findPlace.focus();
                });
            } else if (input.attr('id') === 'find-place' && $findDestination.val() === '' || (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && $findDestination.hasClass('auto-populated'))) {
                // clear call stack causing original input to be refocused
                setTimeout(function () {
                    $findDestination.focus();
                });
                return;
            } else if ((window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) && ($findDestination.val() !== '' && $findPlace.val() !== '')) {
                setTimeout(function () {
                    $findDestination.add($findPlace).blur();
                });
            }

            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && ((input.attr('id') === 'find-destination' && $findPlace.val() !== '') || input.attr('id') === 'find-place' && $findDestination.val() !== '')) {
                $searchType.val('true');
                submit();
                $input.blur();
            }

            // remove auto-populated class if user started typing in find-desination input 
            if (aa.helpers.cache.cachedElements.$window.width() > aa.helpers.cache.constants.MOBILE_BREAKPOINT && input.attr('id') === 'find-destination') {
                $input.on('keypress', function () {
                    $(this).removeClass('auto-populated');
                });
            }

        }

        function populateLocation(input, ui) {
            // trigger geolocation in find destination input
            if (input.attr('id') === 'find-destination') {
                if (input.val() === '') {
                    findLocation();
                    return;
                }
                populateFields('', '', ui.item === null ? input.val() : ui.item.label, ui.item === null ? '' : ui.item.placeId);
            }
        }

        function populateFields(lat, long, location, placeId) {
            $inputsParent.find('.latitude').val(lat);
            $inputsParent.find('.longitude').val(long);
            $inputsParent.find('.location').val(location);
            $inputsParent.find('.place-id').val(placeId);
        }

        function findLocation() {
            function showPosition(position) {
                populateFields(position.coords.latitude, position.coords.longitude, '', '');
                $findDestination.val($inputsParent.find('.find-destination-hidden').data('label'));
            }

            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition, showError);
            } else {
                showError();
            }

            function showError(error) {
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                    case error.POSITION_UNAVAILABLE:
                    case error.TIMEOUT:
                    case error.UNKNOWN_ERROR:
                        populateFields('', '', 'London', 'ChIJdd4hrwug2EcRmSrV3Vo6llI');
                        $findDestination.val($inputsParent.find('.location').data('label'));
                        if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                            $findDestination.addClass('auto-populated');
                        }
                        break;
                }
            }
        }
        // submit
        function submit() {
            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && ($input.is('#find-destination') && $findPlace.val() === '')) {
                $findPlace.focus();
                return;
            }

            $inputsParent.find('.lookup-radius').val('');
            $searchType.val('true');

            if ($findDestination.val() === '') {
                populateLocation($findDestination);
            }

            // clear filters
            window.aa.hospitality.globalBoolean.searchButtonPressed = true;
            $listing.find('.filters-applied').find('input:checked').trigger('click');

            //clear callstack
            setTimeout(function () {
                $listing.trigger('getResults');
            });
        }

        // event fires twice, unbind previous iteration
        $inputsParent.siblings('.search-inputs input[type="submit"].search-establishments').off('click').on('click', function (e) {
            e.preventDefault();
            submit();
        });

        // hospitality search input component redirect & initial search parameters appended to query string
        $searchComponentSubmit.off('click').on('click', function (e) {
            var searchParameters = [];

            e.preventDefault();

            $inputsParent.find('.data-to-redirect').each(function () {
                var $thisInput = $(this);

                if ($thisInput.val() !== '') {
                    searchParameters.push((searchParameters.length ? '&' : '?') + $thisInput.attr('name') + '=' + $thisInput.val());
                }
            });

            if ($findDestination.val() === '') {
                populateLocation($findDestination);
            }

            window.location = $(this).data('url') + searchParameters.join('');

        });

        // prevent symbols from being entered into search inputs
        $('#find-place').add($('#find-destination')).on({
            keypress: function (e) {
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }
                return /^[a-zA-Z0-9-',. ]*$/.test($(this).val());
            },
            paste: function (e) {
                // allow backspace in firefox
                if (e.which === 8) {
                    return true;
                }
                return /^[a-zA-Z0-9-',. ]*$/.test(e.originalEvent.clipboardData.getData('text'));
            }
        });

        $clearButton.on('mousedown', function (e) {
            e.preventDefault();
            isSelected = true;
            $input.val('');
            $input.closest('.input').find('input[type="hidden"]').not('.lookup').val('');
            $clearButton.hide();
            $input.trigger('blur');
        });

        $input.on({
            focus: function () {
                if ($input.hasClass('auto-populated')) {
                    isSelected = true;
                    $input.val('');
                    $input.closest('.input').find('input[type="hidden"]').not('.lookup').val('');
                    $input.removeClass('auto-populated');
                }

                if (window.aa.helpers.cache.cachedElements.$window.width() < window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && $input.is('#find-place') && $findDestination.val() === '') {
                    populateLocation($findDestination);
                }

                inputBlurred = false;

                $inputBorder.addClass('active');
                $input.attr('placeholder', '');

                if ($input.val() !== '') {
                    $clearButton.show();
                }

                // only prepopulate and show autocomplete if on tablet or desktop and if the lookup input value isn't equal to the prepopulated input value
                if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && $(this).val() === $thisContainer.find('input[type="hidden"].find-destination-hidden.lookup').val()) {
                    return;
                }

                $(this).autocomplete('search', $(this).val());

            },
            blur: function () {
                $inputBorder.removeClass('active');
                $input.attr('placeholder', placeholderText);
                $clearButton.hide();
                inputBlurred = true;
            },
            keypress: function (e) {
                if (e.which === 13) {
                    if ($input.closest('.establishment-search-page').hasClass('search-field-component')) {
                        $input.trigger('blur'); // blur input to update hidden inputs with search parameters before redirecting to the search results page
                        $searchComponentSubmit.trigger('click');
                    }
                    e.preventDefault();
                    if ($input.is('#find-destination') && !isLocationAvailable && $input.val() === '') {
                        return;
                    }
                    $input.blur();
                    submit();
                }
            },
            keydown: function (e) {
                if ($input.hasClass('auto-populated') && (e.which === 8 || e.which === 46)) {
                    $input.removeClass('auto-populated');
                }
            }
        });
    }

    // filters functionality for mobile
    function searchFiltersMobile() {
        var $thisSortBy = $(this),
            $relativeWrapper = $thisSortBy.closest('.wrapper.results'),
            // caching window width to compare later on and make sure hideFilters does not get executed on window.resize
            windowWidth = window.aa.helpers.cache.cachedElements.$window.width(),
            $searchFilters = $thisSortBy.siblings('.search-filters').find('.refine-results');

        function hideFilters() {
            $searchFilters.fadeOut('fast', function () {
                $relativeWrapper.removeClass('filters-visible');
            });
        }

        $thisSortBy.on('click', '.sort-button', function (e) {
            e.preventDefault();
            $thisSortBy.find('label[for="hospitality-sort-by"]').trigger('click');
        });

        $searchFilters.on('change', 'input', function () {
            $(this).toggleClass('filter-pending');
        });

        $thisSortBy.on('click', '.filter-button', function (e) {
            e.preventDefault();
            $relativeWrapper.addClass('filters-visible');
            $searchFilters.fadeIn('fast');
        });

        $searchFilters.on('click', '.close-filters', function () {
            var $pendingInput = $searchFilters.find('input.filter-pending');

            if ($pendingInput.is(':checked')) {
                $pendingInput.prop('checked', false).trigger('change');
            } else {
                $pendingInput.trigger('click');
            }
            hideFilters();
        });

        $searchFilters.on('click', '.apply-filters', function () {
            $searchFilters.find('.filter-pending').removeClass('filter-pending');
            hideFilters();
        });

        window.aa.helpers.cache.cachedElements.$window.on('resize', function () {
            // change of window.height triggers window.resize // cached windowWidth variable helps discern whether height or width has changed - only executing the code on width change
            if (window.aa.helpers.cache.cachedElements.$window.width() !== windowWidth && window.aa.helpers.cache.cachedElements.$window.width() < window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                hideFilters();
                windowWidth = window.aa.helpers.cache.cachedElements.$window.width();
            }
        });
    }

    // link see all results buttons to category buttons
    function selectCategory(listing) {
        var $listing = listing,
            categoryId;

        $listing.on('click', 'button[data-id]', function () {
            categoryId = $(this).data('id');
            window.aa.helpers.cache.cachedElements.$body.add(window.aa.helpers.cache.cachedElements.$html).animate({ scrollTop: '0' });
            $listing.find('#categories input[data-see-all-id="' + categoryId + '"]').trigger('click');
        });
    }

    // view bottom of footer on tablet when booking widget is fixed to bottom of page, otherwise remove padding
    function bookingWidgetSize() {
        if (aa.helpers.cache.cachedElements.$window.width() <= aa.helpers.cache.constants.TABLET_LANDSCAPE) {
            aa.helpers.cache.cachedElements.$body.css({ paddingBottom: $(this).innerHeight() });
        } else {
            aa.helpers.cache.cachedElements.$body.css({ paddingBottom: 0 });
        }
    }

    // PP Jquery upgrade    window.aa.helpers.cache.cachedElements.$document.on({
    //        ready: function () {
    window.aa.helpers.cache.cachedElements.$document.ready(
        function () {
            //console.log('Jquery hospitality-js upgrade of document.on( ready');
            //BAU-AMD-222-starts//
            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                $("#refineResults").hide();
            }
            else {
                $("#refineResults").show();
            }
            //BAU-AMD-222-ends//
            $('.twitter-feed').each(scrollTweets);
            $('.detail-header').each(function () {
                var $detailHeader = $(this);

                establishmentNameRestriction($detailHeader);
                window.aa.hospitality.cropThumbnails($detailHeader.find('.header-thumbnail img'));
                window.aa.hospitality.cropThumbnails($detailHeader.find('svg image'));
            });
            $('.review-bar').each(reviewBar);
            $('.establishment-info').each(truncationReadMore);
            $('.input').each(searchInputs);
            $('.listing').each(function () {
                selectCategory($(this));
                toggleSearchCard($(this));
            });
            $('.sort-by-container').each(searchFiltersMobile);
            $('.booking-widgets').each(bookingWidgetSize);
            $('.related-results').find('.result').each(function () {
                window.aa.hospitality.cropThumbnails($(this).find('img'));
            });
            //}
        });
    window.aa.helpers.cache.cachedElements.$window.on({
        load: function () {
            $('.row-with-sidebar').each(fixedSidebar);
        },
        resize: function () {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function () {
                $('.detail-header').each(function () {
                    establishmentNameRestriction($(this));
                });
                $('.row-with-sidebar').each(fixedSidebar);
                $('.booking-widgets').each(bookingWidgetSize);
            }, 100);
        }
    });


})(jQ);
///#source 1 1 /Assets/scripts/hospitality-listing.js
/*
 * ---------------------------------------- *
 * Name: 	Listing JavaScripts             *
 * Type: 	JavaScript Module               *
 * Version: Not Versioned                   *
 * Author:	Catia Gomes | Codehouse Ltd     *
 * Requisites: >=jQuery 1.10.2              *
 *             serialise.js                 *
 * ---------------------------------------- *
 */

/*
 * javascripts for misc listing components using webapi with pagination
 */

window.aa || (window.aa = {}); //  aa namespace
window.aa.hospitalityListing || (window.aa.hospitalityListing = {});

// filter listing functionality
var listing = new function Listing() {
    // context
    $('.listing').each(function () {

        var $thisFilter = $(this),
            $resultsContainer = $thisFilter.find('.list-results'),
            $results = $resultsContainer.find('.result-cards'),
            $filters = $thisFilter.find('.refine-results'),
            $sortByResults = $thisFilter.find('.sort-by-container'),
            $categories = $thisFilter.find('#categories'),
            $loader = $resultsContainer.find('.loader'),
            $pagination = $resultsContainer.find('.pagination'),
            requestMethod = $thisFilter.data('request-method'),
            $errorMessages = $thisFilter.find('.error-messages'),
            $searchType = $thisFilter.find('.is-search'),
            categoriesTemplate,
            isPageReset,
            isFilterApplied,
            filtersTemplate,
            resultTilesTemplate,
            dataObj = {},
            sortByMarkup,
            serviceRequests,
            onLoad = false,
            allResults = false,
            currentPageNumber,
            loaderTimer,
            data = {
                settings: {
                    contextUrl: $thisFilter.data('url'),
                    noResultsMessage: $thisFilter.data('noresults-label'),
                    errorMessage: $thisFilter.data('error-message')
                },
                direction: {
                    next: function () {
                        currentPageNumber += 1;
                    },
                    prev: function () {
                        currentPageNumber -= 1;
                    }
                },
                serialiseToObj: function () {
                    dataObj = serialise.jQueryData($thisFilter, 'serialise-form');

                    // check if pagination exists
                    if (typeof currentPageNumber !== 'undefined') {
                        dataObj.Page = currentPageNumber;
                    }
                }
            },
            presentation = {
                buildMarkup: function (response) {
                    var filtersFinalMarkup,
                        categoriesFinalMarkup,
                        resultTilesFinalMarkup,
                        sortByFinalMarkup,
                        $sortBy;

                    presentation.loader.hide();
                    $errorMessages.hide();

                    // build markup using Mustache
                    resultTilesFinalMarkup = Mustache.render(resultTilesTemplate, response);
                    filtersFinalMarkup = Mustache.render(filtersTemplate, response);
                    categoriesFinalMarkup = Mustache.render(categoriesTemplate, response);
                    sortByFinalMarkup = Mustache.render(sortByMarkup, response);

                    // append markup
                    $results.html(resultTilesFinalMarkup).show();
                    $filters.html(filtersFinalMarkup);
                    $categories.html(categoriesFinalMarkup).show();
                    $sortByResults.html(sortByFinalMarkup).show();
                    
                    $sortBy = $thisFilter.find('.hospitality-sort-by');

                    // toggle direction button pagination
                    if (typeof response.Sections[0] !== 'undefined' && typeof response.Sections[0] !== "undefined") {
                        presentation.pagination(response.Sections[0].TotalPages, response.Sections[0].CurrentPage);
                    }

                    // no results
                    if (typeof response === 'undefined' || response.Sections.length < 1) {
                        $categories.hide();
                        $results.empty();
                        $errorMessages.text(data.settings.noResultsMessage).show();
                        return false;
                    }

                    if (allResults) {
                        $thisFilter.find('.search-results').show();
                        $thisFilter.find('.category-title .arrow').addClass('flipped');
                    }

                    $searchType.val('false');

                    if (!onLoad && $thisFilter.find('.search-result').length > 1) {
                        $sortBy.show();

                        if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                            $thisFilter.find('.refine-results').show();
                        } else {
                            $sortBy.find('select').removeAttr('disabled');
                        }
                    }

                    events.dynamic();
                    onLoad = false;
                    isFilterApplied = false;
                    allResults = false;

                    $thisFilter.find('.thumbnail img').each(function() {
                        window.aa.hospitality.cropThumbnails($(this));
                    });
                },
                loader: {
                    hide: function () {
                        clearTimeout(loaderTimer);
                        $loader.hide();
                    },
                    show: function () {
                        clearTimeout(loaderTimer);
                        loaderTimer = setTimeout(function () {
                            $loader.show();
                        }, 100);
                    }
                },
                pagination: function (totalPages, pageNumber) {
                    $pagination = $resultsContainer.find('.pagination');

                    if (pageNumber === 1) {
                        $pagination.find('[data-dir="prev"]').hide();
                    }

                    if (pageNumber === totalPages) {
                        $pagination.find('[data-dir="next"]').hide();
                    }

                    if (totalPages === 1) {
                        $pagination.hide();
                    } else {
                        $pagination.show();
                    }
                }
            },
            actions = {
                callService: function () {
                    var dataToSend,
                        url;
                  
                    presentation.loader.show();

                    // update data obj
                    data.serialiseToObj();

                    // if search button or auto search set category filter to ''
                    if ($searchType.val() === 'true') {
                        dataObj.CategoryFilters = '';
                    }

                    // set isMobileView to true if window size = mobile
                    dataObj.IsMobileView = window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT;

                    // prevent calls from stacking
                    if (typeof serviceRequests !== 'undefined') {
                        serviceRequests.abort();
                    }

                    // set page on first request
                    if (typeof dataObj.Page === 'undefined') {
                        dataObj.Page = 1;
                    }

                    if (isPageReset) {
                        dataObj.Page = 1;
                    }

                    isPageReset = false;

                    // define data and URL for POST
                    if (requestMethod === 'POST') {
                        dataToSend = JSON.stringify(dataObj);
                        url = data.settings.contextUrl;
                    } else {
                        dataToSend = dataObj;
                        url = data.settings.contextUrl;
                    }
    
                    serviceRequests = $.ajax({
                        method: requestMethod,
                        url: url,
                        contentType: 'application/json',
                        data: dataToSend,
                        success: function (response) {
                            presentation.buildMarkup(response);

                        },
                        error: function (xhr) {
                            if (xhr.status !== 0) {
                                presentation.loader.hide();
                                $results.empty();
                                $errorMessages.text(data.settings.errorMessage).show();
                            }
                        }
                    });
                }
            },
            events = {
                standard: function () {                    
                    
                    // submit
                    $thisFilter.on('getResults', function () {
                        isPageReset = true;
                        actions.callService();
                    });

                    // events for other form elements
                    $thisFilter.on('change', '.categories input', function () {
                        window.aa.hospitality.globalBoolean.searchButtonPressed = true;
                        $thisFilter.find('.filters-applied').find('input:checked').trigger('click');
                        $thisFilter.trigger('getResults');
                    });

                    // other elements
                    $thisFilter.on('change', '.search-sort-by select', function () {
                        actions.callService();
                    });

                    $thisFilter.on('change', '.search-sort-by select', function () {
                        $thisFilter.trigger('getResults');
                    });

                    $thisFilter.on('click', '.apply-filters', function () {
                        $thisFilter.trigger('getResults');
                    });

                    $thisFilter.on('change', '.refine-results input', function () {
                        var $fieldTypeInput = $(this).closest('.filter').find('input[type="hidden"]');

                        if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                            $fieldTypeInput.attr('data-serialise-form', 'CurrentFilterType');
                            isFilterApplied = true;
                            $thisFilter.trigger('getResults');
                        }
                    });

                    $thisFilter.on('click', '.all-results', function() {
                        allResults = true;
                    });
                },
                dynamic: function () {
                    $pagination = $resultsContainer.find('.pagination');

                    // pagination events
                    $pagination.on('click', 'button', function (e) {
                        var $btn = $(this);

                        if ($btn.hasClass('active')) {
                            return;
                        }

                        currentPageNumber = parseInt($pagination.find('.active').text());

                        if (typeof $btn.data('dir') !== 'undefined') {
                            data.direction[$btn.data('dir')]();
                        }

                        window.aa.helpers.cache.cachedElements.$body.add(window.aa.helpers.cache.cachedElements.$html).animate({ scrollTop: '0' });
                        data.settings.contextUrl = $thisFilter.data('url');
                        actions.callService();
                    });
                    
                    // truncate establishments names and locations
                    $thisFilter.find('a.name').each(function () {
                        var trucatedResult = window.aa.helpers.truncateText($(this).text(), 40);

                        if (!trucatedResult) {
                            return;
                        }
                        $(this).html(trucatedResult + '...' + '<span class="name icon"></span>');
                    });

                    if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                        $thisFilter.find('.location').each(function () {
                            var trucatedResult = window.aa.helpers.truncateText($(this).text(), 80);
                            if (!trucatedResult) {
                                return;
                            }
                            $(this).text(trucatedResult + '...');
                        });
                    }

                    $thisFilter.find('.filters-applied').each(window.aa.hospitality.searchFilters);
                    stylishForms.update();
                    $('.accordion').each(window.aa.helpers.accordions);

                    //add scrollbar for filters
                    $thisFilter.find('.scroll-component').each(function () {
                        var $thisScrollComponent = $(this);

                        if ($thisScrollComponent.find('.field').length > 5) {
                            $thisScrollComponent.addClass('scrollbar').mCustomScrollbar();
                        }
                    });
                },
                onLoad: function () {
                    onLoad = true;

                    // cache template markup
                    resultTilesTemplate = $results.html();
                    filtersTemplate = $filters.html();
                    categoriesTemplate = $categories.html();
                    sortByMarkup = $sortByResults.html();
                    // populate results
                    actions.callService();
                }
            };

        // initialise events
        events.onLoad();
        events.standard();
    });
}
///#source 1 1 /Assets/scripts/AutoNumeric.js
/**
* autoNumeric.js
* @author: Bob Knothe
* @author: Sokolov Yura
* @version: 1.9.26 - 2014-10-07 GMT 2:00 PM
*
* Created by Robert J. Knothe on 2010-10-25. Please report any bugs to https://github.com/BobKnothe/autoNumeric
* Created by Sokolov Yura on 2010-11-07
*
* Copyright (c) 2011 Robert J. Knothe http://www.decorplanit.com/plugin/
*
* The MIT License (http://www.opensource.org/licenses/mit-license.php)
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
(function ($) {
    "use strict";
    /*jslint browser: true*/
    /*global jQuery: false*/
    /* Cross browser routine for getting selected range/cursor position
     */
    function getElementSelection(that) {
        var position = {};
        if (that.selectionStart === undefined) {
            that.focus();
            var select = document.selection.createRange();
            position.length = select.text.length;
            select.moveStart('character', -that.value.length);
            position.end = select.text.length;
            position.start = position.end - position.length;
        } else {
            position.start = that.selectionStart;
            position.end = that.selectionEnd;
            position.length = position.end - position.start;
        }
        return position;
    }
    /**
     * Cross browser routine for setting selected range/cursor position
     */
    function setElementSelection(that, start, end) {
        if (that.selectionStart === undefined) {
            that.focus();
            var r = that.createTextRange();
            r.collapse(true);
            r.moveEnd('character', end);
            r.moveStart('character', start);
            r.select();
        } else {
            that.selectionStart = start;
            that.selectionEnd = end;
        }
    }
    /**
     * run callbacks in parameters if any
     * any parameter could be a callback:
     * - a function, which invoked with jQuery element, parameters and this parameter name and returns parameter value
     * - a name of function, attached to $(selector).autoNumeric.functionName(){} - which was called previously
     */
    function runCallbacks($this, settings) {
        /**
         * loops through the settings object (option array) to find the following
         * k = option name example k=aNum
         * val = option value example val=0123456789
         */
        $.each(settings, function (k, val) {
            if (typeof val === 'function') {
                settings[k] = val($this, settings, k);
            } else if (typeof $this.autoNumeric[val] === 'function') {
                /**
                 * calls the attached function from the html5 data example: data-a-sign="functionName"
                 */
                settings[k] = $this.autoNumeric[val]($this, settings, k);
            }
        });
    }
    function convertKeyToNumber(settings, key) {
        if (typeof (settings[key]) === 'string') {
            settings[key] *= 1;
        }
    }
    /**
     * Preparing user defined options for further usage
     * merge them with defaults appropriately
     */
    function autoCode($this, settings) {
        runCallbacks($this, settings);
        settings.oEvent = null;
        settings.tagList = ['b', 'caption', 'cite', 'code', 'dd', 'del', 'div', 'dfn', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ins', 'kdb', 'label', 'li', 'output', 'p', 'q', 's', 'sample', 'span', 'strong', 'td', 'th', 'u', 'var'];
        var vmax = settings.vMax.toString().split('.'),
            vmin = (!settings.vMin && settings.vMin !== 0) ? [] : settings.vMin.toString().split('.');
        convertKeyToNumber(settings, 'vMax');
        convertKeyToNumber(settings, 'vMin');
        convertKeyToNumber(settings, 'mDec'); /** set mDec if not defined by user */
        settings.mDec = (settings.mRound === 'CHF') ? '2' : settings.mDec;
        settings.allowLeading = true;
        settings.aNeg = settings.vMin < 0 ? '-' : '';
        vmax[0] = vmax[0].replace('-', '');
        vmin[0] = vmin[0].replace('-', '');
        settings.mInt = Math.max(vmax[0].length, vmin[0].length, 1);
        if (settings.mDec === null) {
            var vmaxLength = 0,
                vminLength = 0;
            if (vmax[1]) {
                vmaxLength = vmax[1].length;
            }
            if (vmin[1]) {
                vminLength = vmin[1].length;
            }
            settings.mDec = Math.max(vmaxLength, vminLength);
        } /** set alternative decimal separator key */
        if (settings.altDec === null && settings.mDec > 0) {
            if (settings.aDec === '.' && settings.aSep !== ',') {
                settings.altDec = ',';
            } else if (settings.aDec === ',' && settings.aSep !== '.') {
                settings.altDec = '.';
            }
        }
        /** cache regexps for autoStrip */
        var aNegReg = settings.aNeg ? '([-\\' + settings.aNeg + ']?)' : '(-?)';
        settings.aNegRegAutoStrip = aNegReg;
        settings.skipFirstAutoStrip = new RegExp(aNegReg + '[^-' + (settings.aNeg ? '\\' + settings.aNeg : '') + '\\' + settings.aDec + '\\d]' + '.*?(\\d|\\' + settings.aDec + '\\d)');
        settings.skipLastAutoStrip = new RegExp('(\\d\\' + settings.aDec + '?)[^\\' + settings.aDec + '\\d]\\D*$');
        var allowed = '-' + settings.aNum + '\\' + settings.aDec;
        settings.allowedAutoStrip = new RegExp('[^' + allowed + ']', 'gi');
        settings.numRegAutoStrip = new RegExp(aNegReg + '(?:\\' + settings.aDec + '?(\\d+\\' + settings.aDec + '\\d+)|(\\d*(?:\\' + settings.aDec + '\\d*)?))');
        return settings;
    }
    /**
     * strip all unwanted characters and leave only a number alert
     */
    function autoStrip(s, settings, strip_zero) {
        if (settings.aSign) { /** remove currency sign */
            while (s.indexOf(settings.aSign) > -1) {
                s = s.replace(settings.aSign, '');
            }
        }
        s = s.replace(settings.skipFirstAutoStrip, '$1$2'); /** first replace anything before digits */
        s = s.replace(settings.skipLastAutoStrip, '$1'); /** then replace anything after digits */
        s = s.replace(settings.allowedAutoStrip, ''); /** then remove any uninterested characters */
        if (settings.altDec) {
            s = s.replace(settings.altDec, settings.aDec);
        } /** get only number string */
        var m = s.match(settings.numRegAutoStrip);
        s = m ? [m[1], m[2], m[3]].join('') : '';
        if ((settings.lZero === 'allow' || settings.lZero === 'keep') && strip_zero !== 'strip') {
            var parts = [],
                nSign = '';
            parts = s.split(settings.aDec);
            if (parts[0].indexOf('-') !== -1) {
                nSign = '-';
                parts[0] = parts[0].replace('-', '');
            }
            if (parts[0].length > settings.mInt && parts[0].charAt(0) === '0') { /** strip leading zero if need */
                parts[0] = parts[0].slice(1);
            }
            s = nSign + parts.join(settings.aDec);
        }
        if ((strip_zero && settings.lZero === 'deny') || (strip_zero && settings.lZero === 'allow' && settings.allowLeading === false)) {
            var strip_reg = '^' + settings.aNegRegAutoStrip + '0*(\\d' + (strip_zero === 'leading' ? ')' : '|$)');
            strip_reg = new RegExp(strip_reg);
            s = s.replace(strip_reg, '$1$2');
        }
        return s;
    }
    /**
     * places or removes brackets on negative values
     */
    function negativeBracket(s, nBracket, oEvent) { /** oEvent = settings.oEvent */
        nBracket = nBracket.split(',');
        if (oEvent === 'set' || oEvent === 'focusout') {
            s = s.replace('-', '');
            s = nBracket[0] + s + nBracket[1];
        } else if ((oEvent === 'get' || oEvent === 'focusin' || oEvent === 'pageLoad') && s.charAt(0) === nBracket[0]) {
            s = s.replace(nBracket[0], '-');
            s = s.replace(nBracket[1], '');
        }
        return s;
    }
    /**
     * truncate decimal part of a number
     */
    function truncateDecimal(s, aDec, mDec) {
        if (aDec && mDec) {
            var parts = s.split(aDec);
            /** truncate decimal part to satisfying length
             * cause we would round it anyway */
            if (parts[1] && parts[1].length > mDec) {
                if (mDec > 0) {
                    parts[1] = parts[1].substring(0, mDec);
                    s = parts.join(aDec);
                } else {
                    s = parts[0];
                }
            }
        }
        return s;
    }
    /**
     * prepare number string to be converted to real number
     */
    function fixNumber(s, aDec, aNeg) {
        if (aDec && aDec !== '.') {
            s = s.replace(aDec, '.');
        }
        if (aNeg && aNeg !== '-') {
            s = s.replace(aNeg, '-');
        }
        if (!s.match(/\d/)) {
            s += '0';
        }
        return s;
    }
    /**
     * function to handle numbers less than 0 that are stored in Exponential notation ex: .0000001 stored as 1e-7
     */
    function checkValue(value, settings) {
        if (value) {
            var checkSmall = +value;
            if (checkSmall < 0.000001 && checkSmall > -1) {
                value = +value;
                if (value < 0.000001 && value > 0) {
                    value = (value + 10).toString();
                    value = value.substring(1);
                }
                if (value < 0 && value > -1) {
                    value = (value - 10).toString();
                    value = '-' + value.substring(2);
                }
                value = value.toString();
            } else {
                var parts = value.split('.');
                if (parts[1] !== undefined) {
                    if (+parts[1] === 0) {
                        value = parts[0];
                    } else {
                        parts[1] = parts[1].replace(/0*$/, '');
                        value = parts.join('.');
                    }
                }
            }
        }
        return (settings.lZero === 'keep') ? value : value.replace(/^0*(\d)/, '$1');
    }
    /**
     * prepare real number to be converted to our format
     */
    function presentNumber(s, aDec, aNeg) {
        if (aNeg && aNeg !== '-') {
            s = s.replace('-', aNeg);
        }
        if (aDec && aDec !== '.') {
            s = s.replace('.', aDec);
        }
        return s;
    }
    /**
     * checking that number satisfy format conditions
     * and lays between settings.vMin and settings.vMax
     * and the string length does not exceed the digits in settings.vMin and settings.vMax
     */
    function autoCheck(s, settings) {
        s = autoStrip(s, settings);
        s = truncateDecimal(s, settings.aDec, settings.mDec);
        s = fixNumber(s, settings.aDec, settings.aNeg);
        var value = +s;
        if (settings.oEvent === 'set' && (value < settings.vMin || value > settings.vMax)) {
            $.error("The value (" + value + ") from the 'set' method falls outside of the vMin / vMax range");
        }
        return value >= settings.vMin && value <= settings.vMax;
    }
    /**
     * private function to check for empty value
     */
    function checkEmpty(iv, settings, signOnEmpty) {
        if (iv === '' || iv === settings.aNeg) {
            if (settings.wEmpty === 'zero') {
                return iv + '0';
            }
            if (settings.wEmpty === 'sign' || signOnEmpty) {
                return iv + settings.aSign;
            }
            return iv;
        }
        return null;
    }
    /**
     * private function that formats our number
     */
    function autoGroup(iv, settings) {
        iv = autoStrip(iv, settings);
        var testNeg = iv.replace(',', '.'),
            empty = checkEmpty(iv, settings, true);
        if (empty !== null) {
            return empty;
        }
        var digitalGroup = '';
        if (settings.dGroup === 2) {
            digitalGroup = /(\d)((\d)(\d{2}?)+)$/;
        } else if (settings.dGroup === 4) {
            digitalGroup = /(\d)((\d{4}?)+)$/;
        } else {
            digitalGroup = /(\d)((\d{3}?)+)$/;
        } /** splits the string at the decimal string */
        var ivSplit = iv.split(settings.aDec);
        if (settings.altDec && ivSplit.length === 1) {
            ivSplit = iv.split(settings.altDec);
        } /** assigns the whole number to the a varibale (s) */
        var s = ivSplit[0];
        if (settings.aSep) {
            while (digitalGroup.test(s)) { /** re-inserts the thousand sepparator via a regualer expression */
                s = s.replace(digitalGroup, '$1' + settings.aSep + '$2');
            }
        }
        if (settings.mDec !== 0 && ivSplit.length > 1) {
            if (ivSplit[1].length > settings.mDec) {
                ivSplit[1] = ivSplit[1].substring(0, settings.mDec);
            } /** joins the whole number with the deciaml value */
            iv = s + settings.aDec + ivSplit[1];
        } else { /** if whole numbers only */
            iv = s;
        }
        if (settings.aSign) {
            var has_aNeg = iv.indexOf(settings.aNeg) !== -1;
            iv = iv.replace(settings.aNeg, '');
            iv = settings.pSign === 'p' ? settings.aSign + iv : iv + settings.aSign;
            if (has_aNeg) {
                iv = settings.aNeg + iv;
            }
        }
        if (settings.oEvent === 'set' && testNeg < 0 && settings.nBracket !== null) { /** removes the negative sign and places brackets */
            iv = negativeBracket(iv, settings.nBracket, settings.oEvent);
        }
        return iv;
    }
    /**
     * round number after setting by pasting or $().autoNumericSet()
     * private function for round the number
     * please note this handled as text - JavaScript math function can return inaccurate values
     * also this offers multiple rounding methods that are not easily accomplished in JavaScript
     */
    function autoRound(iv, settings) { /** value to string */
        iv = (iv === '') ? '0' : iv.toString();
        convertKeyToNumber(settings, 'mDec'); /** set mDec to number needed when mDec set by 'update method */
        if (settings.mRound === 'CHF') {
            iv = (Math.round(iv * 20) / 20).toString();
        }
        var ivRounded = '',
            i = 0,
            nSign = '',
            rDec = (typeof (settings.aPad) === 'boolean' || settings.aPad === null) ? (settings.aPad ? settings.mDec : 0) : +settings.aPad;
        var truncateZeros = function (ivRounded) { /** truncate not needed zeros */
            var regex = (rDec === 0) ? (/(\.(?:\d*[1-9])?)0*$/) : rDec === 1 ? (/(\.\d(?:\d*[1-9])?)0*$/) : new RegExp('(\\.\\d{' + rDec + '}(?:\\d*[1-9])?)0*$');
            ivRounded = ivRounded.replace(regex, '$1'); /** If there are no decimal places, we don't need a decimal point at the end */
            if (rDec === 0) {
                ivRounded = ivRounded.replace(/\.$/, '');
            }
            return ivRounded;
        };
        if (iv.charAt(0) === '-') { /** Checks if the iv (input Value)is a negative value */
            nSign = '-';
            iv = iv.replace('-', ''); /** removes the negative sign will be added back later if required */
        }
        if (!iv.match(/^\d/)) { /** append a zero if first character is not a digit (then it is likely to be a dot)*/
            iv = '0' + iv;
        }
        if (nSign === '-' && +iv === 0) { /** determines if the value is zero - if zero no negative sign */
            nSign = '';
        }
        if ((+iv > 0 && settings.lZero !== 'keep') || (iv.length > 0 && settings.lZero === 'allow')) { /** trims leading zero's if needed */
            iv = iv.replace(/^0*(\d)/, '$1');
        }
        var dPos = iv.lastIndexOf('.'), /** virtual decimal position */
            vdPos = (dPos === -1) ? iv.length - 1 : dPos, /** checks decimal places to determine if rounding is required */
            cDec = (iv.length - 1) - vdPos; /** check if no rounding is required */
        if (cDec <= settings.mDec) {
            ivRounded = iv; /** check if we need to pad with zeros */
            if (cDec < rDec) {
                if (dPos === -1) {
                    ivRounded += '.';
                }
                var zeros = '000000';
                while (cDec < rDec) {
                    zeros = zeros.substring(0, rDec - cDec);
                    ivRounded += zeros;
                    cDec += zeros.length;
                }
            } else if (cDec > rDec) {
                ivRounded = truncateZeros(ivRounded);
            } else if (cDec === 0 && rDec === 0) {
                ivRounded = ivRounded.replace(/\.$/, '');
            }
            if (settings.mRound !== 'CHF') {
                return (+ivRounded === 0) ? ivRounded : nSign + ivRounded;
            }
            if (settings.mRound === 'CHF') {
                dPos = ivRounded.lastIndexOf('.');
                iv = ivRounded;
            }

        } /** rounded length of the string after rounding */
        var rLength = dPos + settings.mDec,
            tRound = +iv.charAt(rLength + 1),
            ivArray = iv.substring(0, rLength + 1).split(''),
            odd = (iv.charAt(rLength) === '.') ? (iv.charAt(rLength - 1) % 2) : (iv.charAt(rLength) % 2),
            onePass = true;
        if (odd !== 1) {
            odd = (odd === 0 && (iv.substring(rLength + 2, iv.length) > 0)) ? 1 : 0;
        }
        if ((tRound > 4 && settings.mRound === 'S') || /** Round half up symmetric */
                (tRound > 4 && settings.mRound === 'A' && nSign === '') || /** Round half up asymmetric positive values */
                (tRound > 5 && settings.mRound === 'A' && nSign === '-') || /** Round half up asymmetric negative values */
                (tRound > 5 && settings.mRound === 's') || /** Round half down symmetric */
                (tRound > 5 && settings.mRound === 'a' && nSign === '') || /** Round half down asymmetric positive values */
                (tRound > 4 && settings.mRound === 'a' && nSign === '-') || /** Round half down asymmetric negative values */
                (tRound > 5 && settings.mRound === 'B') || /** Round half even "Banker's Rounding" */
                (tRound === 5 && settings.mRound === 'B' && odd === 1) || /** Round half even "Banker's Rounding" */
                (tRound > 0 && settings.mRound === 'C' && nSign === '') || /** Round to ceiling toward positive infinite */
                (tRound > 0 && settings.mRound === 'F' && nSign === '-') || /** Round to floor toward negative infinite */
                (tRound > 0 && settings.mRound === 'U') ||
                (settings.mRound === 'CHF')) { /** round up away from zero */
            for (i = (ivArray.length - 1); i >= 0; i -= 1) { /** Round up the last digit if required, and continue until no more 9's are found */
                if (ivArray[i] !== '.') {
                    if (settings.mRound === 'CHF' && ivArray[i] <= 2 && onePass) {
                        ivArray[i] = 0;
                        onePass = false;
                        break;
                    }
                    if (settings.mRound === 'CHF' && ivArray[i] <= 7 && onePass) {
                        ivArray[i] = 5;
                        onePass = false;
                        break;
                    }
                    if (settings.mRound === 'CHF' && onePass) {
                        ivArray[i] = 10;
                        onePass = false;
                    } else {
                        ivArray[i] = +ivArray[i] + 1;
                    }
                    if (ivArray[i] < 10) {
                        break;
                    }
                    if (i > 0) {
                        ivArray[i] = '0';
                    }
                }
            }
        }
        ivArray = ivArray.slice(0, rLength + 1); /** Reconstruct the string, converting any 10's to 0's */
        ivRounded = truncateZeros(ivArray.join('')); /** return rounded value */
        return (+ivRounded === 0) ? ivRounded : nSign + ivRounded;
    }
    /**
     * Holder object for field properties
     */
    function AutoNumericHolder(that, settings) {
        this.settings = settings;
        this.that = that;
        this.$that = $(that);
        this.formatted = false;
        this.settingsClone = autoCode(this.$that, this.settings);
        this.value = that.value;
    }
    AutoNumericHolder.prototype = {
        init: function (e) {
            this.value = this.that.value;
            this.settingsClone = autoCode(this.$that, this.settings);
            this.ctrlKey = e.ctrlKey;
            this.cmdKey = e.metaKey;
            this.shiftKey = e.shiftKey;
            this.selection = getElementSelection(this.that); /** keypress event overwrites meaningful value of e.keyCode */
            if (e.type === 'keydown' || e.type === 'keyup') {
                this.kdCode = e.keyCode;
            }
            this.which = e.which;
            this.processed = false;
            this.formatted = false;
        },
        setSelection: function (start, end, setReal) {
            start = Math.max(start, 0);
            end = Math.min(end, this.that.value.length);
            this.selection = {
                start: start,
                end: end,
                length: end - start
            };
            if (setReal === undefined || setReal) {
                setElementSelection(this.that, start, end);
            }
        },
        setPosition: function (pos, setReal) {
            this.setSelection(pos, pos, setReal);
        },
        getBeforeAfter: function () {
            var value = this.value,
                left = value.substring(0, this.selection.start),
                right = value.substring(this.selection.end, value.length);
            return [left, right];
        },
        getBeforeAfterStriped: function () {
            var parts = this.getBeforeAfter();
            parts[0] = autoStrip(parts[0], this.settingsClone);
            parts[1] = autoStrip(parts[1], this.settingsClone);
            return parts;
        },
        /**
         * strip parts from excess characters and leading zeroes
         */
        normalizeParts: function (left, right) {
            var settingsClone = this.settingsClone;
            right = autoStrip(right, settingsClone); /** if right is not empty and first character is not aDec, */
            /** we could strip all zeros, otherwise only leading */
            var strip = right.match(/^\d/) ? true : 'leading';
            left = autoStrip(left, settingsClone, strip); /** prevents multiple leading zeros from being entered */
            if ((left === '' || left === settingsClone.aNeg) && settingsClone.lZero === 'deny') {
                if (right > '') {
                    right = right.replace(/^0*(\d)/, '$1');
                }
            }
            var new_value = left + right; /** insert zero if has leading dot */
            if (settingsClone.aDec) {
                var m = new_value.match(new RegExp('^' + settingsClone.aNegRegAutoStrip + '\\' + settingsClone.aDec));
                if (m) {
                    left = left.replace(m[1], m[1] + '0');
                    new_value = left + right;
                }
            } /** insert zero if number is empty and io.wEmpty == 'zero' */
            if (settingsClone.wEmpty === 'zero' && (new_value === settingsClone.aNeg || new_value === '')) {
                left += '0';
            }
            return [left, right];
        },
        /**
         * set part of number to value keeping position of cursor
         */
        setValueParts: function (left, right) {
            var settingsClone = this.settingsClone,
                parts = this.normalizeParts(left, right),
                new_value = parts.join(''),
                position = parts[0].length;
            if (autoCheck(new_value, settingsClone)) {
                new_value = truncateDecimal(new_value, settingsClone.aDec, settingsClone.mDec);
                if (position > new_value.length) {
                    position = new_value.length;
                }
                this.value = new_value;
                this.setPosition(position, false);
                return true;
            }
            return false;
        },
        /**
         * helper function for expandSelectionOnSign
         * returns sign position of a formatted value
         */
        signPosition: function () {
            var settingsClone = this.settingsClone,
                aSign = settingsClone.aSign,
                that = this.that;
            if (aSign) {
                var aSignLen = aSign.length;
                if (settingsClone.pSign === 'p') {
                    var hasNeg = settingsClone.aNeg && that.value && that.value.charAt(0) === settingsClone.aNeg;
                    return hasNeg ? [1, aSignLen + 1] : [0, aSignLen];
                }
                var valueLen = that.value.length;
                return [valueLen - aSignLen, valueLen];
            }
            return [1000, -1];
        },
        /**
         * expands selection to cover whole sign
         * prevents partial deletion/copying/overwriting of a sign
         */
        expandSelectionOnSign: function (setReal) {
            var sign_position = this.signPosition(),
                selection = this.selection;
            if (selection.start < sign_position[1] && selection.end > sign_position[0]) { /** if selection catches something except sign and catches only space from sign */
                if ((selection.start < sign_position[0] || selection.end > sign_position[1]) && this.value.substring(Math.max(selection.start, sign_position[0]), Math.min(selection.end, sign_position[1])).match(/^\s*$/)) { /** then select without empty space */
                    if (selection.start < sign_position[0]) {
                        this.setSelection(selection.start, sign_position[0], setReal);
                    } else {
                        this.setSelection(sign_position[1], selection.end, setReal);
                    }
                } else { /** else select with whole sign */
                    this.setSelection(Math.min(selection.start, sign_position[0]), Math.max(selection.end, sign_position[1]), setReal);
                }
            }
        },
        /**
         * try to strip pasted value to digits
         */
        checkPaste: function () {
            if (this.valuePartsBeforePaste !== undefined) {
                var parts = this.getBeforeAfter(),
                    oldParts = this.valuePartsBeforePaste;
                delete this.valuePartsBeforePaste; /** try to strip pasted value first */
                parts[0] = parts[0].substr(0, oldParts[0].length) + autoStrip(parts[0].substr(oldParts[0].length), this.settingsClone);
                if (!this.setValueParts(parts[0], parts[1])) {
                    this.value = oldParts.join('');
                    this.setPosition(oldParts[0].length, false);
                }
            }
        },
        /**
         * process pasting, cursor moving and skipping of not interesting keys
         * if returns true, further processing is not performed
         */
        skipAllways: function (e) {
            var kdCode = this.kdCode,
                which = this.which,
                ctrlKey = this.ctrlKey,
                cmdKey = this.cmdKey,
                shiftKey = this.shiftKey; /** catch the ctrl up on ctrl-v */
            if (((ctrlKey || cmdKey) && e.type === 'keyup' && this.valuePartsBeforePaste !== undefined) || (shiftKey && kdCode === 45)) {
                this.checkPaste();
                return false;
            }
            /** codes are taken from http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx
             * skip Fx keys, windows keys, other special keys
             */
            if ((kdCode >= 112 && kdCode <= 123) || (kdCode >= 91 && kdCode <= 93) || (kdCode >= 9 && kdCode <= 31) || (kdCode < 8 && (which === 0 || which === kdCode)) || kdCode === 144 || kdCode === 145 || kdCode === 45) {
                return true;
            }
            if ((ctrlKey || cmdKey) && kdCode === 65) { /** if select all (a=65)*/
                return true;
            }
            if ((ctrlKey || cmdKey) && (kdCode === 67 || kdCode === 86 || kdCode === 88)) { /** if copy (c=67) paste (v=86) or cut (x=88) */
                if (e.type === 'keydown') {
                    this.expandSelectionOnSign();
                }
                if (kdCode === 86 || kdCode === 45) { /** try to prevent wrong paste */
                    if (e.type === 'keydown' || e.type === 'keypress') {
                        if (this.valuePartsBeforePaste === undefined) {
                            this.valuePartsBeforePaste = this.getBeforeAfter();
                        }
                    } else {
                        this.checkPaste();
                    }
                }
                return e.type === 'keydown' || e.type === 'keypress' || kdCode === 67;
            }
            if (ctrlKey || cmdKey) {
                return true;
            }
            if (kdCode === 37 || kdCode === 39) { /** jump over thousand separator */
                var aSep = this.settingsClone.aSep,
                    start = this.selection.start,
                    value = this.that.value;
                if (e.type === 'keydown' && aSep && !this.shiftKey) {
                    if (kdCode === 37 && value.charAt(start - 2) === aSep) {
                        this.setPosition(start - 1);
                    } else if (kdCode === 39 && value.charAt(start + 1) === aSep) {
                        this.setPosition(start + 1);
                    }
                }
                return true;
            }
            if (kdCode >= 34 && kdCode <= 40) {
                return true;
            }
            return false;
        },
        /**
         * process deletion of characters
         * returns true if processing performed
         */
        processAllways: function () {
            var parts; /** process backspace or delete */
            if (this.kdCode === 8 || this.kdCode === 46) {
                if (!this.selection.length) {
                    parts = this.getBeforeAfterStriped();
                    if (this.kdCode === 8) {
                        parts[0] = parts[0].substring(0, parts[0].length - 1);
                    } else {
                        parts[1] = parts[1].substring(1, parts[1].length);
                    }
                    this.setValueParts(parts[0], parts[1]);
                } else {
                    this.expandSelectionOnSign(false);
                    parts = this.getBeforeAfterStriped();
                    this.setValueParts(parts[0], parts[1]);
                }
                return true;
            }
            return false;
        },
        /**
         * process insertion of characters
         * returns true if processing performed
         */
        processKeypress: function () {
            var settingsClone = this.settingsClone,
                cCode = String.fromCharCode(this.which),
                parts = this.getBeforeAfterStriped(),
                left = parts[0],
                right = parts[1]; /** start rules when the decimal character key is pressed */
            /** always use numeric pad dot to insert decimal separator */
            if (cCode === settingsClone.aDec || (settingsClone.altDec && cCode === settingsClone.altDec) || ((cCode === '.' || cCode === ',') && this.kdCode === 110)) { /** do not allow decimal character if no decimal part allowed */
                if (!settingsClone.mDec || !settingsClone.aDec) {
                    return true;
                } /** do not allow decimal character before aNeg character */
                if (settingsClone.aNeg && right.indexOf(settingsClone.aNeg) > -1) {
                    return true;
                } /** do not allow decimal character if other decimal character present */
                if (left.indexOf(settingsClone.aDec) > -1) {
                    return true;
                }
                if (right.indexOf(settingsClone.aDec) > 0) {
                    return true;
                }
                if (right.indexOf(settingsClone.aDec) === 0) {
                    right = right.substr(1);
                }
                this.setValueParts(left + settingsClone.aDec, right);
                return true;
            }
            /**
             * start rule on negative sign & prevent minus if not allowed
             */
            if (cCode === '-' || cCode === '+') {
                if (!settingsClone.aNeg) {
                    return true;
                } /** caret is always after minus */
                if (left === '' && right.indexOf(settingsClone.aNeg) > -1) {
                    left = settingsClone.aNeg;
                    right = right.substring(1, right.length);
                } /** change sign of number, remove part if should */
                if (left.charAt(0) === settingsClone.aNeg) {
                    left = left.substring(1, left.length);
                } else {
                    left = (cCode === '-') ? settingsClone.aNeg + left : left;
                }
                this.setValueParts(left, right);
                return true;
            } /** digits */
            if (cCode >= '0' && cCode <= '9') { /** if try to insert digit before minus */
                if (settingsClone.aNeg && left === '' && right.indexOf(settingsClone.aNeg) > -1) {
                    left = settingsClone.aNeg;
                    right = right.substring(1, right.length);
                }
                if (settingsClone.vMax <= 0 && settingsClone.vMin < settingsClone.vMax && this.value.indexOf(settingsClone.aNeg) === -1 && cCode !== '0') {
                    left = settingsClone.aNeg + left;
                }
                this.setValueParts(left + cCode, right);
                return true;
            } /** prevent any other character */
            return true;
        },
        /**
         * formatting of just processed value with keeping of cursor position
         */
        formatQuick: function () {
            var settingsClone = this.settingsClone,
                parts = this.getBeforeAfterStriped(),
                leftLength = this.value;
            if ((settingsClone.aSep === '' || (settingsClone.aSep !== '' && leftLength.indexOf(settingsClone.aSep) === -1)) && (settingsClone.aSign === '' || (settingsClone.aSign !== '' && leftLength.indexOf(settingsClone.aSign) === -1))) {
                var subParts = [],
                    nSign = '';
                subParts = leftLength.split(settingsClone.aDec);
                if (subParts[0].indexOf('-') > -1) {
                    nSign = '-';
                    subParts[0] = subParts[0].replace('-', '');
                    parts[0] = parts[0].replace('-', '');
                }
                if (subParts[0].length > settingsClone.mInt && parts[0].charAt(0) === '0') { /** strip leading zero if need */
                    parts[0] = parts[0].slice(1);
                }
                parts[0] = nSign + parts[0];
            }
            var value = autoGroup(this.value, this.settingsClone),
                position = value.length;
            if (value) {
                /** prepare regexp which searches for cursor position from unformatted left part */
                var left_ar = parts[0].split(''),
                    i = 0;
                for (i; i < left_ar.length; i += 1) { /** thanks Peter Kovari */
                    if (!left_ar[i].match('\\d')) {
                        left_ar[i] = '\\' + left_ar[i];
                    }
                }
                var leftReg = new RegExp('^.*?' + left_ar.join('.*?'));
                /** search cursor position in formatted value */
                var newLeft = value.match(leftReg);
                if (newLeft) {
                    position = newLeft[0].length;
                    /** if we are just before sign which is in prefix position */
                    if (((position === 0 && value.charAt(0) !== settingsClone.aNeg) || (position === 1 && value.charAt(0) === settingsClone.aNeg)) && settingsClone.aSign && settingsClone.pSign === 'p') {
                        /** place caret after prefix sign */
                        position = this.settingsClone.aSign.length + (value.charAt(0) === '-' ? 1 : 0);
                    }
                } else if (settingsClone.aSign && settingsClone.pSign === 's') {
                    /** if we could not find a place for cursor and have a sign as a suffix */
                    /** place carret before suffix currency sign */
                    position -= settingsClone.aSign.length;
                }
            }
            this.that.value = value;
            this.setPosition(position);
            this.formatted = true;
        }
    };
    /** thanks to Anthony & Evan C */
    function autoGet(obj) {
        if (typeof obj === 'string') {
            obj = obj.replace(/\[/g, "\\[").replace(/\]/g, "\\]");
            obj = '#' + obj.replace(/(:|\.)/g, '\\$1');
            /** obj = '#' + obj.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1'); */
            /** possible modification to replace the above 2 lines */
        }
        return $(obj);
    }

    function getHolder($that, settings, update) {
        var data = $that.data('autoNumeric');
        if (!data) {
            data = {};
            $that.data('autoNumeric', data);
        }
        var holder = data.holder;
        if ((holder === undefined && settings) || update) {
            holder = new AutoNumericHolder($that.get(0), settings);
            data.holder = holder;
        }
        return holder;
    }
    var methods = {
        init: function (options) {
            return this.each(function () {
                var $this = $(this),
                    settings = $this.data('autoNumeric'), /** attempt to grab 'autoNumeric' settings, if they don't exist returns "undefined". */
                    tagData = $this.data(); /** attempt to grab HTML5 data, if they don't exist we'll get "undefined".*/
                if (typeof settings !== 'object') { /** If we couldn't grab settings, create them from defaults and passed options. */
                    var defaults = {
                        /** allowed numeric values
                         * please do not modify
                         */
                        aNum: '0123456789',
                        /** allowed thousand separator characters
                         * comma = ','
                         * period "full stop" = '.'
                         * apostrophe is escaped = '\''
                         * space = ' '
                         * none = ''
                         * NOTE: do not use numeric characters
                         */
                        aSep: ',',
                        /** digital grouping for the thousand separator used in Format
                         * dGroup: '2', results in 99,99,99,999 common in India for values less than 1 billion and greater than -1 billion
                         * dGroup: '3', results in 999,999,999 default
                         * dGroup: '4', results in 9999,9999,9999 used in some Asian countries
                         */
                        dGroup: '3',
                        /** allowed decimal separator characters
                         * period "full stop" = '.'
                         * comma = ','
                         */
                        aDec: '.',
                        /** allow to declare alternative decimal separator which is automatically replaced by aDec
                         * developed for countries the use a comma ',' as the decimal character
                         * and have keyboards\numeric pads that have a period 'full stop' as the decimal characters (Spain is an example)
                         */
                        altDec: null,
                        /** allowed currency symbol
                         * Must be in quotes aSign: '$', a space is allowed aSign: '$ '
                         */
                        aSign: '',
                        /** placement of currency sign
                         * for prefix pSign: 'p',
                         * for suffix pSign: 's',
                         */
                        pSign: 'p',
                        /** maximum possible value
                         * value must be enclosed in quotes and use the period for the decimal point
                         * value must be larger than vMin
                         */
                        vMax: '9999999999999.99',
                        /** minimum possible value
                         * value must be enclosed in quotes and use the period for the decimal point
                         * value must be smaller than vMax
                         */
                        vMin: '0.00',
                        /** max number of decimal places = used to override decimal places set by the vMin & vMax values
                         * value must be enclosed in quotes example mDec: '3',
                         * This can also set the value via a call back function mDec: 'css:#
                         */
                        mDec: null,
                        /** method used for rounding
                         * mRound: 'S', Round-Half-Up Symmetric (default)
                         * mRound: 'A', Round-Half-Up Asymmetric
                         * mRound: 's', Round-Half-Down Symmetric (lower case s)
                         * mRound: 'a', Round-Half-Down Asymmetric (lower case a)
                         * mRound: 'B', Round-Half-Even "Bankers Rounding"
                         * mRound: 'U', Round Up "Round-Away-From-Zero"
                         * mRound: 'D', Round Down "Round-Toward-Zero" - same as truncate
                         * mRound: 'C', Round to Ceiling "Toward Positive Infinity"
                         * mRound: 'F', Round to Floor "Toward Negative Infinity"
                         */
                        mRound: 'S',
                        /** controls decimal padding
                         * aPad: true - always Pad decimals with zeros
                         * aPad: false - does not pad with zeros.
                         * aPad: `some number` - pad decimals with zero to number different from mDec
                         * thanks to Jonas Johansson for the suggestion
                         */
                        aPad: true,
                        /** places brackets on negative value -$ 999.99 to (999.99)
                         * visible only when the field does NOT have focus the left and right symbols should be enclosed in quotes and seperated by a comma
                         * nBracket: null, nBracket: '(,)', nBracket: '[,]', nBracket: '<,>' or nBracket: '{,}'
                         */
                        nBracket: null,
                        /** Displayed on empty string
                         * wEmpty: 'empty', - input can be blank
                         * wEmpty: 'zero', - displays zero
                         * wEmpty: 'sign', - displays the currency sign
                         */
                        wEmpty: 'empty',
                        /** controls leading zero behavior
                         * lZero: 'allow', - allows leading zeros to be entered. Zeros will be truncated when entering additional digits. On focusout zeros will be deleted.
                         * lZero: 'deny', - allows only one leading zero on values less than one
                         * lZero: 'keep', - allows leading zeros to be entered. on fousout zeros will be retained.
                         */
                        lZero: 'allow',
                        /** determine if the default value will be formatted on page ready.
                         * true = automatically formats the default value on page ready
                         * false = will not format the default value
                         */
                        aForm: true,
                        /** future use */
                        onSomeEvent: function () {}
                    };
                    settings = $.extend({}, defaults, tagData, options); /** Merge defaults, tagData and options */
                    if (settings.aDec === settings.aSep) {
                        $.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand separator aSep: '" + settings.aSep + "' are the same character");
                        return this;
                    }
                    $this.data('autoNumeric', settings); /** Save our new settings */
                } else {
                    return this;
                }
                settings.runOnce = false;
                var holder = getHolder($this, settings);
                if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) === -1 && $this.prop('tagName').toLowerCase() !== 'input') {
                    $.error("The <" + $this.prop('tagName').toLowerCase() + "> is not supported by autoNumeric()");
                    return this;
                }
                if (settings.runOnce === false && settings.aForm) {/** routine to format default value on page load */
                    if ($this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])')) {
                        var setValue = true;
                        if ($this[0].value === '' && settings.wEmpty === 'empty') {
                            $this[0].value = '';
                            setValue = false;
                        }
                        if ($this[0].value === '' && settings.wEmpty === 'sign') {
                            $this[0].value = settings.aSign;
                            setValue = false;
                        }
                        if (setValue) {
                            $this.autoNumeric('set', $this.val());
                        }
                    }
                    if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) !== -1 && $this.text() !== '') {
                        $this.autoNumeric('set', $this.text());
                    }
                }
                settings.runOnce = true;
                if ($this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])')) { /**added hidden type */
                    $this.on('keydown.autoNumeric', function (e) {
                        holder = getHolder($this);
                        if (holder.settings.aDec === holder.settings.aSep) {
                            $.error("autoNumeric will not function properly when the decimal character aDec: '" + holder.settings.aDec + "' and thousand separator aSep: '" + holder.settings.aSep + "' are the same character");
                            return this;
                        }
                        if (holder.that.readOnly) {
                            holder.processed = true;
                            return true;
                        }
                        /** The below streamed code / comment allows the "enter" keydown to throw a change() event */
                        /** if (e.keyCode === 13 && holder.inVal !== $this.val()){
                            $this.change();
                            holder.inVal = $this.val();
                        }*/
                        holder.init(e);
                        holder.settings.oEvent = 'keydown';
                        if (holder.skipAllways(e)) {
                            holder.processed = true;
                            return true;
                        }
                        if (holder.processAllways()) {
                            holder.processed = true;
                            holder.formatQuick();
                            e.preventDefault();
                            return false;
                        }
                        holder.formatted = false;
                        return true;
                    });
                    $this.on('keypress.autoNumeric', function (e) {
                        var holder = getHolder($this),
                            processed = holder.processed;
                        holder.init(e);
                        holder.settings.oEvent = 'keypress';
                        if (holder.skipAllways(e)) {
                            return true;
                        }
                        if (processed) {
                            e.preventDefault();
                            return false;
                        }
                        if (holder.processAllways() || holder.processKeypress()) {
                            holder.formatQuick();
                            e.preventDefault();
                            return false;
                        }
                        holder.formatted = false;
                    });
                    $this.on('keyup.autoNumeric', function (e) {
                        var holder = getHolder($this);
                        holder.init(e);
                        holder.settings.oEvent = 'keyup';
                        var skip = holder.skipAllways(e);
                        holder.kdCode = 0;
                        delete holder.valuePartsBeforePaste;
                        if ($this[0].value === holder.settings.aSign) { /** added to properly place the caret when only the currency is present */
                            if (holder.settings.pSign === 's') {
                                setElementSelection(this, 0, 0);
                            } else {
                                setElementSelection(this, holder.settings.aSign.length, holder.settings.aSign.length);
                            }
                        }
                        if (skip) {
                            return true;
                        }
                        if (this.value === '') {
                            return true;
                        }
                        if (!holder.formatted) {
                            holder.formatQuick();
                        }
                    });
                    $this.on('focusin.autoNumeric', function () {
                        var holder = getHolder($this);
                        holder.settingsClone.oEvent = 'focusin';
                        if (holder.settingsClone.nBracket !== null) {
                            var checkVal = $this.val();
                            $this.val(negativeBracket(checkVal, holder.settingsClone.nBracket, holder.settingsClone.oEvent));
                        }
                        holder.inVal = $this.val();
                        var onempty = checkEmpty(holder.inVal, holder.settingsClone, true);
                        if (onempty !== null) {
                            $this.val(onempty);
                            if (holder.settings.pSign === 's') {
                                setElementSelection(this, 0, 0);
                            } else {
                                setElementSelection(this, holder.settings.aSign.length, holder.settings.aSign.length);
                            }
                        }
                    });
                    $this.on('focusout.autoNumeric', function () {
                        var holder = getHolder($this),
                            settingsClone = holder.settingsClone,
                            value = $this.val(),
                            origValue = value;
                        holder.settingsClone.oEvent = 'focusout';
                        var strip_zero = ''; /** added to control leading zero */
                        if (settingsClone.lZero === 'allow') { /** added to control leading zero */
                            settingsClone.allowLeading = false;
                            strip_zero = 'leading';
                        }
                        if (value !== '') {
                            value = autoStrip(value, settingsClone, strip_zero);
                            if (checkEmpty(value, settingsClone) === null && autoCheck(value, settingsClone, $this[0])) {
                                value = fixNumber(value, settingsClone.aDec, settingsClone.aNeg);
                                value = autoRound(value, settingsClone);
                                value = presentNumber(value, settingsClone.aDec, settingsClone.aNeg);
                            } else {
                                value = '';
                            }
                        }
                        var groupedValue = checkEmpty(value, settingsClone, false);
                        if (groupedValue === null) {
                            groupedValue = autoGroup(value, settingsClone);
                        }
                        if (groupedValue !== origValue) {
                            $this.val(groupedValue);
                        }
                        if (groupedValue !== holder.inVal) {
                            $this.change();
                            delete holder.inVal;
                        }
                        if (settingsClone.nBracket !== null && $this.autoNumeric('get') < 0) {
                            holder.settingsClone.oEvent = 'focusout';
                            $this.val(negativeBracket($this.val(), settingsClone.nBracket, settingsClone.oEvent));
                        }
                    });
                }
            });
        },
        /** method to remove settings and stop autoNumeric() */
        destroy: function () {
            return $(this).each(function () {
                var $this = $(this);
                $this.off('.autoNumeric');
                $this.removeData('autoNumeric');
            });
        },
        /** method to update settings - can call as many times */
        update: function (options) {
            return $(this).each(function () {
                var $this = autoGet($(this)),
                    settings = $this.data('autoNumeric');
                if (typeof settings !== 'object') {
                    $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'update' method");
                    return this;
                }
                var strip = $this.autoNumeric('get');
                settings = $.extend(settings, options);
                getHolder($this, settings, true);
                if (settings.aDec === settings.aSep) {
                    $.error("autoNumeric will not function properly when the decimal character aDec: '" + settings.aDec + "' and thousand separator aSep: '" + settings.aSep + "' are the same character");
                    return this;
                }
                $this.data('autoNumeric', settings);
                if ($this.val() !== '' || $this.text() !== '') {
                    return $this.autoNumeric('set', strip);
                }
                return;
            });
        },
        /** returns a formatted strings for "input:text" fields Uses jQuery's .val() method*/
        set: function (valueIn) {
            if (valueIn === null) {
                return;
            }
            return $(this).each(function () {
                var $this = autoGet($(this)),
                    settings = $this.data('autoNumeric'),
                    value = valueIn.toString(),
                    testValue = valueIn.toString();
                if (typeof settings !== 'object') {
                    $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'set' method");
                    return this;
                }
                /** routine to handle page re-load from back button */
                if (testValue !== $this.attr('value') && $this.prop('tagName').toLowerCase() === 'input' && settings.runOnce === false) {
                    value = (settings.nBracket !== null) ? negativeBracket($this.val(), settings.nBracket, 'pageLoad') : value;
                    value = autoStrip(value, settings);
                }
               /** allows locale decimal separator to be a comma */
                if ((testValue === $this.attr('value') || testValue === $this.text()) && settings.runOnce === false) {
                    value = value.replace(',', '.');
                }
                /** returns a empty string if the value being 'set' contains non-numeric characters and or more than decimal point (full stop) and will not be formatted */
                if (!$.isNumeric(+value)) {
                    return '';
                }
                value = checkValue(value, settings);
                settings.oEvent = 'set';
                value.toString();
                if (value !== '') {
                    value = autoRound(value, settings);
                }
                value = presentNumber(value, settings.aDec, settings.aNeg);
                if (!autoCheck(value, settings)) {
                    value = autoRound('', settings);
                }
                value = autoGroup(value, settings);
                if ($this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])')) { /**added hidden type */
                    return $this.val(value);
                }
                if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) !== -1) {
                    return $this.text(value);
                }
                $.error("The <" + $this.prop('tagName').toLowerCase() + "> is not supported by autoNumeric()");
                return false;
            });
        },
        /** method to get the unformatted value from a specific input field, returns a numeric value */
        get: function () {
            var $this = autoGet($(this)),
                settings = $this.data('autoNumeric');
            if (typeof settings !== 'object') {
                $.error("You must initialize autoNumeric('init', {options}) prior to calling the 'get' method");
                return this;
            }
            settings.oEvent = 'get';
            var getValue = '';
            /** determine the element type then use .eq(0) selector to grab the value of the first element in selector */
            if ($this.is('input[type=text], input[type=hidden], input[type=tel], input:not([type])')) { /**added hidden type */
                getValue = $this.eq(0).val();
            } else if ($.inArray($this.prop('tagName').toLowerCase(), settings.tagList) !== -1) {
                getValue = $this.eq(0).text();
            } else {
                $.error("The <" + $this.prop('tagName').toLowerCase() + "> is not supported by autoNumeric()");
                return false;
            }
            if ((getValue === '' && settings.wEmpty === 'empty') || (getValue === settings.aSign && (settings.wEmpty === 'sign' || settings.wEmpty === 'empty'))) {
                return '';
            }
            if (settings.nBracket !== null && getValue !== '') {
                getValue = negativeBracket(getValue, settings.nBracket, settings.oEvent);
            }
            if (settings.runOnce || settings.aForm === false) {
                getValue = autoStrip(getValue, settings);
            }
            getValue = fixNumber(getValue, settings.aDec, settings.aNeg);
            if (+getValue === 0 && settings.lZero !== 'keep') {
                getValue = '0';
            }
            if (settings.lZero === 'keep') {
                return getValue;
            }
            getValue = checkValue(getValue, settings);
            return getValue; /** returned Numeric String */
        },
        /** method to get the unformatted value from multiple fields */
        getString: function () {
            var isAutoNumeric = false,
                $this = autoGet($(this)),
                str = $this.serialize(),
                parts = str.split('&'),
                formIndex = $('form').index($this),
                i = 0;
            for (i; i < parts.length; i += 1) {
                var miniParts = parts[i].split('='),
                    $field = $('form:eq(' + formIndex + ') input[name="' + decodeURIComponent(miniParts[0]) + '"]'),
                    settings = $field.data('autoNumeric');
                if (typeof settings === 'object') {
                    if (miniParts[1] !== null) {
                        miniParts[1] = $field.autoNumeric('get');
                        parts[i] = miniParts.join('=');
                        isAutoNumeric = true;
                    }
                }
            }
            if (isAutoNumeric === true) {
                return parts.join('&');
            }
            return str;
        },
        /** method to get the unformatted value from multiple fields */
        getArray: function () {
            var isAutoNumeric = false,
                $this = autoGet($(this)),
                formFields = $this.serializeArray(),
                formIndex = $('form').index($this);
            /*jslint unparam: true*/
            $.each(formFields, function (i, field) {
                var $field = $('form:eq(' + formIndex + ') input[name="' + decodeURIComponent(field.name) + '"]'),
                    settings = $field.data('autoNumeric');
                if (typeof settings === 'object') {
                    if (field.value !== '') {
                        field.value = $field.autoNumeric('get').toString();
                    }
                    isAutoNumeric = true;
                }
            });
            /*jslint unparam: false*/
            if (isAutoNumeric === true) {
                return formFields;
            }
            return this;
        },
        /** returns the settings object for those who need to look under the hood */
        getSettings: function () {
            var $this = autoGet($(this));
            return $this.eq(0).data('autoNumeric');
        }
    };
    $.fn.autoNumeric = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        }
        $.error('Method "' + method + '" is not supported by autoNumeric()');
    };
}(jQuery));
///#source 1 1 /Assets/scripts/script-3.5.js

/* 
 * ---------------------------------------- *
 * Name: 	Primary JavaScripts             *
 * Type: 	JavaScript                      *
 * Version: Not Versioned                   *
 * Author:	Thomas Dale | Codehouse         *
 * Requisites: chg.Client                   *
 *             chg.Cookie                   *
 * ---------------------------------------- *
 */

(function ($) {

    var $header = $('#site-header, #sales-journey-header'),
        headerHeight = $header.outerHeight(),
        resizeTimer,
        timer;

    // constants
    var RESULTS_LENGTH = 15;

    // configure local & global paths
    boot.config.local = '/Assets/scripts/libs/codehouse-js/';
    boot.config.libs = '/Assets/scripts/libs/';
    boot.config.global = '/Assets/scripts/';

    // apply client script
    client.domApply();

    // requisites: searchPagination
    function stickyFooter() {
        if (!$('.no-results').length && window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
            window.aa.helpers.cache.cachedElements.$main.css({ paddingBottom: window.aa.helpers.cache.cachedElements.$footer.height() });
        } else if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
            window.aa.helpers.cache.cachedElements.$main.css({ paddingBottom: 0 });
        }
    }

    // product comparison tables
    function productComparison() {

        var $productTable = $(this).not('.filter-table'),
            $tableWrapper = $productTable.find('.wrapper'),
            $firstColumn = $productTable.find('.description'),
            $fixedColumn = $productTable.find('.fixed-column'),
            resizeColumn;

        function setWidthHeight() {
            $fixedColumn.height($productTable.find('.table').innerHeight());
            $fixedColumn.width($firstColumn.innerWidth());
        }

        function popularTagWidth() {

            var $tag = $productTable.find('.tag, .popular-bottom').not('.offer');

            $tag.css({ width: $tag.parent('.popular').innerWidth() + 4 });  // add 4 to accommodate for absolute positioned :before and :after (acting as borders)

        }

        function tableOverflowIndicator() {

            var $tableInnerShadow = $(this),
                $table = $tableWrapper.find('.table');

            $productTable.parent('.wrapper').addClass('comparison-table');
            $tableInnerShadow.css({ height: $table.innerHeight(), top: $table.css('margin-top'), right: $tableWrapper.css('margin-right') });

            // add scrolling class if scrollbar exists
            if ($tableWrapper.innerWidth() < $tableWrapper.get(0).scrollWidth) {
                $tableWrapper.addClass('scrolling');
            } else {
                $tableWrapper.removeClass('scrolling');
            }

            $tableWrapper.on('scroll', function () {

                var $thisTableWrapper = $(this),
                    scrollLeft = $thisTableWrapper.scrollLeft(),
                    maxScroll = $thisTableWrapper.get(0).scrollWidth - $thisTableWrapper.parent().width(),
                    $fixedColumnandDescription = $fixedColumn.add($fixedColumn.find('.description').children());

                if (scrollLeft > 0) {
                    $fixedColumnandDescription.addClass('active');
                } else {
                    $fixedColumnandDescription.removeClass('active');
                }

                // hide right hand shadow once last column is reached
                if (scrollLeft >= maxScroll) {
                    $tableInnerShadow.hide();
                } else {
                    $tableInnerShadow.show();
                }

            });

        }

        // get height of table cells and apply to new fixed column table cells
        function fixedColumnHeight() {

            var $fixedColumnContents = $fixedColumn.find('.description > div'),
                $servicesRecommendedProduct = $fixedColumn.find('.recommended-product-label, .tag'),
                heights = [];

            if ($servicesRecommendedProduct.length) {
                $servicesRecommendedProduct.closest('.description').addClass('popular');
            }

            // remove heights to be overwritten
            $fixedColumnContents.height(''); // remove heights from table cell

            $firstColumn.each(function () {
                heights.push($(this).outerHeight());
            });

            // set heights of each table cell
            $fixedColumnContents.each(function (i) {
                $(this).css('height', heights[i]);
            });

            $fixedColumn.css({ left: $tableWrapper.css('margin-left') });

            popularTagWidth();

        }

        function informationPanelSizing($informationPanel) {

            var $panelParent = $informationPanel.parent('div'),
                $informationPanelInner = $informationPanel.find('.information-inner'),
                $informationPanelTrigger = $informationPanel.siblings('.more-information'),
                headingWidth = 0;

            // calculate outerWidth of previous heading divs
            $panelParent.prevAll().each(function () {
                headingWidth += $(this).outerWidth();
            });

            $informationPanel.css({ left: -(headingWidth), width: $productTable.find('.information-table').innerWidth() });

            if (client.IE) {
                $informationPanel.css({ top: $panelParent.innerHeight() });
            }

            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.TABLET_LANDSCAPE) {

                $informationPanelInner.width(window.aa.helpers.cache.cachedElements.$window.width() - 30); // minus 30 to take padding into consideration

                // on scroll hide open panels and adjust text within to always be on left
                $productTable.find('.wrapper').on('scroll', function () {

                    var scrollLeft = $(this).scrollLeft(),
                        $tableInnerShadow = $productTable.find('.table-inner-shadow'),
                        $descriptionDiv = $fixedColumn.children('div');

                    if (scrollLeft > 0) {

                        if ($informationPanel.hasClass('open')) {
                            $informationPanelTrigger.trigger('click');
                        }

                        $informationPanelInner.css({ left: scrollLeft });
                        $tableInnerShadow.hide();

                        $fixedColumn.add($descriptionDiv).addClass('active');

                    } else {
                        $informationPanelInner.css({ left: 0 });
                        $tableInnerShadow.show();
                        $fixedColumn.add($descriptionDiv).removeClass('active');
                    }

                });
            }
        }

        // information panel within table
        function informationPanel($informationPanel) {
            var $panelParent = $informationPanel.parent('div'),
                $informationPanelTrigger = $informationPanel.siblings('.more-information');

            // hide/reveal panels based on classes
            $informationPanelTrigger.click(function (e) {

                var $panelParentSiblings = $panelParent.siblings('div');

                e.preventDefault();

                // hide other information panels if one is already open and reveal relevant panel
                if ($panelParentSiblings.length) {
                    $panelParentSiblings.children('.information').removeClass('open').stop().slideUp(300);
                }

                $informationPanel.toggleClass('open').stop().slideToggle(300, function () {

                    if ($informationPanel.hasClass('open')) {
                        $informationPanelTrigger.addClass('active');
                        $panelParentSiblings.children('.more-information').removeClass('active');
                    } else {
                        $informationPanelTrigger.removeClass('active');
                    }

                });

            });
        }

        $fixedColumn.each(function () {
            $firstColumn.clone().wrapInner('<div />').appendTo(this);
        });

        setWidthHeight();
        fixedColumnHeight();
        $productTable.find('.information').each(function () {
            informationPanelSizing($(this));
            informationPanel($(this));
        });
        $productTable.find('.table-inner-shadow').each(tableOverflowIndicator);

        // recalculate heights and widths
        window.aa.helpers.cache.cachedElements.$window.on('resize', function () {
            clearTimeout(resizeColumn);
            resizeColumn = setTimeout(function () {
                $productTable.find('.information').each(function () {
                    informationPanelSizing($(this));
                });
                setWidthHeight();
                fixedColumnHeight();
                $productTable.find('.table-inner-shadow').each(tableOverflowIndicator);

            }); // call on resize end
        });

    }

    // search results page 
    function searchResults() {

        var $searchArea = $(this),
            $resultsContainer = $searchArea.find('.results-container'),
            $searchBox = $searchArea.find('input[type="text"]'),
            $searchBtn = $searchArea.find('input[type="submit"]'),
            $minCharacters = $searchArea.find('input[type="hidden"]'),
            $searchSubmit = $searchArea.find('.button'),
            $searchBoxClosest = $searchBox.closest($searchArea),
            $closeBtn = $searchArea.find('.close');

        // remove value 'search' for tablet/mobile
        function removeSearchBtnValue() {
            if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.TABLET_BREAKPOINT || $searchBtn.parents('#search-takeover').length) {
                $searchBtn.val('');
            } else {
                $searchBtn.val('Search');
            }

            // if value exists enable search button
            if ($searchBox.val() !== '') {
                $searchBtn.attr('disabled', false).parent().removeClass('disabled');
            }
        }

        // focus keyword & select result && submit
        function focusKeyword() {
            var $focusedItem = $resultsContainer.find('.focus'),
                useResult = $focusedItem.length ? $focusedItem.data('result') : $searchBox.val();

            $searchBox.val(useResult);
            $searchBoxClosest.trigger('submit');

            // erase lazy load cookie for next result
            window.aa.helpers.cache.registerCookie.erase('SearchResultsPageOne');
        }

        // disable search button
        function disableButton() {
            $(this).stop().fadeOut(200);
            $searchBox.val('');
            $searchBtn.attr('disabled', true).parent().addClass('disabled');
        }

        $searchSubmit.on({
            keypress: function (e) {
                if (e.keyCode === 13 || e.which === 13) {
                    $searchBoxClosest.trigger('submit');
                }
            }
        });

        $searchBox.on({
            keyup: function () {
                $closeBtn.stop().fadeIn();
                $searchBtn.attr('disabled', false);
                $searchSubmit.removeClass('disabled');
            },
            blur: function () {
                if ($searchBox.val()) {
                    $closeBtn.show();
                    $searchBtn.attr('disabled', false);
                    $searchSubmit.removeClass('disabled');
                } else {
                    $searchBtn.attr('disabled', true);
                    $searchSubmit.addClass('disabled');
                    $closeBtn.fadeOut();
                }
            },
            keypress: function (event) {
                if (event.keyCode === 13) {
                    focusKeyword();
                }
            },
            paste: function (event) {
                // allow backspace in firefox
                if (event.which === 8) {
                    return true;
                }
                return /^[a-zA-Z0-9-',. ]*$/.test(event.originalEvent.clipboardData.getData('text'));
            }
        });

        $closeBtn.on({
            click: disableButton,
            keypress: function (e) {
                if (e.keyCode === 13 || e.which === 13) {
                    disableButton();
                }
            }
        });

        window.aa.helpers.cache.cachedElements.$window.on('resize', function () {
            removeSearchBtnValue();
        });

        removeSearchBtnValue();

        // call autocomplete if results container exists
        if ($resultsContainer.length) {
            // search input autocomplete
            window.aa.helpers.autoComplete({
                $input: $searchBox,
                $loadingElem: $searchBox,
                $resultsContainer: $resultsContainer,
                characterCount: $minCharacters.val(),
                url: '/cms/ajax/api/autocomplete/getautocompleteresults/{value}',
                onSuccess: function (data) {
                    var results = data.Results,
                        markup = '';

                    if (results === 'null' || !results.length) {
                        window.aa.helpers.hideResults($resultsContainer, $searchBox);
                    } else {
                        // build markup to insert
                        markup += '<ul><span class="separator"></span>';

                        for (var i = 0; i < results.length; i += 1) {
                            markup += '<li data-result="' + results[i].Suggestion + '">' + results[i].Suggestion.replace(data.SearchText, '<b>$&</b>') + '</li>';
                        }

                        markup += '</ul>';

                        // insert into results container
                        $resultsContainer[0].innerHTML = markup;

                        // bind events if necessary
                        $resultsContainer.find('li').on('click', function () {
                            $(this).addClass('focus');
                            focusKeyword();
                        });

                        // show container
                        window.aa.helpers.showResults($resultsContainer, $searchBox);

                    }
                },
                onEnter: function () {
                    if ($resultsContainer[0].innerHTML !== '') {
                        focusKeyword();
                    }
                }
            });
        }

    }
    $(".mid-grey-my-account-item").parent().addClass("mid-grey-my-account-item");
    // pagination for search results
    function searchPagination() {

        var $searchResultsListing = $('#search-results-listing'),
            $searchLoading = $searchResultsListing.find('#search-loading'),
            $results = $searchResultsListing.find('.result'),
            $pagination = $('#results-pagination'),
            $pagerBtns = $pagination.find('h5.button'),
            queryString = window.location.search,
            parameters = { q: '', pg: '1' },
            resultsLoadedOnce = false;

        if (queryString !== '') {
            var serialisedQuery = serialise.url(queryString);
            parameters.q = serialisedQuery.q;
            parameters.pg = serialisedQuery.pg || '1';
        }

        // hide loading gif if no results are found
        if ($results.length < RESULTS_LENGTH) {
            $searchLoading.addClass('hidden');
        }

        if (!$results.length) {
            window.aa.helpers.cache.cachedElements.$html.addClass('no-results');
        }

        // get next fifteen results
        function lazyLoadResults() {

            var $resultsListingWrapper = $searchResultsListing.children('.wrapper');

            parameters.pg = 2;

            $.ajax({
                url: 'cms/ajax/fragment/search/searchresultarticles',
                data: parameters,
                type: 'GET',
                dataType: 'text'
            }).done(function (response) {

                // lazy load only if 15 or more results
                if ($results.length >= RESULTS_LENGTH) {
                    resultsLoadedOnce = true;

                    $resultsListingWrapper.append(response); // append results to listing
                    $searchLoading.addClass('hidden'); // hide loading animation once results are loaded
                }

            }).fail(function () {
                resultsLoadedOnce = true;
                $resultsListingWrapper.find('#search-no-results').removeClass('hidden');
            });
        }

        // adjust height of search results page if no results
        function searchResultsHeight() {

            var $searchResultsPage = $searchResultsListing.parent('#search-results'),
                $alternativeSearchResults = $searchResultsPage.find('#alternative-results-option');

            if (!$searchResultsListing.find('.result').length && window.aa.helpers.cache.cachedElements.$body.height() < window.aa.helpers.cache.cachedElements.$window.height()) {
                $alternativeSearchResults.css({ height: $alternativeSearchResults.innerHeight() + window.aa.helpers.cache.cachedElements.$window.height() - window.aa.helpers.cache.cachedElements.$body.height() });
            }
        }

        // next or previous search result pages
        $pagerBtns.on('click', function () {
            var isLeft = $(this).hasClass('left');

            if (parameters.pg === '3') {
                isLeft ? parameters.pg = 1 : parameters.pg++;
            } else {
                isLeft ? parameters.pg-- : parameters.pg++;
            }

            window.aa.helpers.cache.registerCookie.write('SearchResultsPageOne', true);

            window.location.search = serialise.obj(parameters);
        });

        if (parameters.pg === '1') {
            window.aa.helpers.cache.cachedElements.$window.on('scroll', function () {
                if (window.aa.helpers.cache.cachedElements.$window.scrollTop() === window.aa.helpers.cache.cachedElements.$document.height() - window.aa.helpers.cache.cachedElements.$window.height()) {
                    if (resultsLoadedOnce === false && $results.length >= RESULTS_LENGTH) {
                        lazyLoadResults();
                    }
                }
            });

            if (window.aa.helpers.cache.registerCookie.check('SearchResultsPageOne')) {
                lazyLoadResults();
            }
        } else {
            $searchLoading.addClass('hidden');
        }

        searchResultsHeight();

        window.aa.helpers.cache.cachedElements.$window.on({
            resize: function () {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(function () {
                    searchResultsHeight();
                    if ($('#site-footer').length) {
                        stickyFooter();
                    } // resize #main bottom padding on search page
                }, 100); // call on resize end
            }
        });

    }

    // product comparison detail headers
    function productionDetailHeaders() {

        var $detailHeader = $(this).not('.journey-products'),
            $twoColumn = $detailHeader.closest('.two-column'),
            $detailHeaderH2 = $detailHeader.find('h2.alt'),
            $detailBeam = $detailHeader.find('.beam');

        if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.TABLET_BREAKPOINT) {
            $detailBeam.css('background-position', '' + ($detailHeaderH2.width() + 52) + 'px -70px');
        } else if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
            $detailBeam.css('background-position', '' + ($detailHeaderH2.width() + 35) / 10 + 'rem -3.8rem');
        }

        // add not-popular class if single product detail
        // does not have the popular tag
        if (!$detailHeader.find('.popular').length) {
            $detailHeader.addClass('not-popular');
        }

        // if both products do not have popular tag add class to column
        // to remove margin from both
        if ($twoColumn.find('.not-popular').length > 1) {
            $twoColumn.addClass('none-recommended');
        }
    }

    // fade text
    function textFadeIn() {

        if (!client.IE9 || window.aa.helpers.cache.cachedElements.isExperienceEditor) {
            return;
        }

        var $fadeIn = $(this),
            $one = $fadeIn.filter('.one'),
            $two = $fadeIn.filter('.two'),
            $three = $fadeIn.filter('.three'),
            $four = $fadeIn.filter('.four'),
            fadeTo = { opacity: '1' },
            delayTime = 300;

        $one.delay(1200).animate(fadeTo, delayTime);
        $two.delay(1400).animate(fadeTo, delayTime);
        $three.delay(1600).animate(fadeTo, delayTime);
        $four.delay(1800).animate(fadeTo, delayTime);
        $fadeIn.delay(delayTime).animate(fadeTo, delayTime);

    }

    // load YouTube API
    function initYouTubeAPI() {

        window.onYouTubePlayerAPIReady = function () {
            window.youTubePlayers = {};

            // cycle through and init players and overlays
            $('.youtube-video').each(function (i) {
                var $video = $(this),
                    $videoEmbed = $video.find('.video-container').children('div');

                // update id of each video iframe, in case same id exists
                $videoEmbed.prop('id', $videoEmbed.prop('id') + i);
                youTubeVideo($video);
            });
        }
    }

    // user interactions for the YouTube video overlay
    function youTubeVideo($el) {
        var $videoModule = $el,
            $videoContainer = $videoModule.find('.video-container'),
            videoId = $videoModule.data('videoid');

        function onPlayerReady() {
            $videoModule.find('.play-media').show().css("z-index", "1");
            $videoModule.find('.play-media').on("click", function () {
                window.youTubePlayers[videoId].playVideo();
            });
        }

        function onPlayerStateChange(event) {

            if (event.data === 0) {
                if (!client.Mobile && !$el.is('.hero-video')) {
                    $videoModule.removeClass('enlarged');
                }
            }
            else if (event.data == YT.PlayerState.PLAYING) {
                if (!client.Mobile && !$el.is('.hero-video')) {
                    $videoModule.addClass('enlarged');
                }
                $videoContainer.animate({ 'opacity': 1 }, 800);
                $videoModule.find('.play-media').hide();
            }
        }

        $('.play-media').on('click', function () {

        })

        window.youTubePlayers[videoId] = new YT.Player($videoContainer.children('div').prop('id'), {
            height: '390',
            width: '640',
            videoId: videoId,
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange,
                'onClick': onPlayerStateChange
            }
        });

        // init youtube lightbox
        if ($('#youtube-lightbox').length) {
            window.aa.helpers.youtubeLightbox();
        }
    }

    // init cinemagraph with hero banner
    function initCinemagraph() {

        var $cinemagraph = $(this),
            $cinemagraphContainer = window.aa.helpers.cache.cachedElements.$body.find('.cinemagraph-container'),
            $heroBanner = $cinemagraphContainer.find('.desktop-tablet-view, .mobile-view'),
            src = $cinemagraph.data('src');

        $heroBanner.addClass('visible');

        if (client.Mobile || client.OldIE || window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.TABLET_LANDSCAPE || !src.length) {
            $cinemagraph.empty().hide();

        } else if (src.length) {
            $heroBanner.removeClass('visible');
            $cinemagraph.html('<video autoplay loop><source src="' + src + '" type="video/mp4" /></video>').show();
        }
    }

    // call tealium view
    function fireTealiumPageView() {
        if (window.utag_cfg_ovrd && window.utag_cfg_ovrd.noview) {
            if (window.utag) {
                utag.view(window.utag_data);
            } else {
                window.utag_cfg_ovrd.noview = false;
            }
        }
    }

    // load in tealium for search page
    function loadTealium() {
        var $searchContainer = $('#search-results');

        if ($searchContainer.length) {
            var searchPage = $searchContainer.find('#results-currentPage').text().trim();

            if (searchPage === '1') {
                utag_data.search_keyword = $searchContainer.find('#alternative-results-option span').text();
                utag_data.search_results = $searchContainer.find('#results-count').text();
            }
        }

        fireTealiumPageView();
    }

    // iframeResizer
    function iframeResizer() {
        $(this).iFrameResize({
            heightCalculationMethod: client.IE ? 'max' : 'lowestElement'
        });
    }

    // set equal heights on related content modules
    function relatedContent() {

        var $moduleContent = $(this).find('.module-content'),
            heights = [];

        $moduleContent.css('height', '');

        function setHeights() {
            $moduleContent.each(function () {
                heights.push($(this).height());
            });

            $moduleContent.height(Math.max.apply(null, heights));
        }

        if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.TABLET_BREAKPOINT) {
            setHeights();
        } else if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && ($moduleContent.closest('.tweet-half-width').length || $moduleContent.parent('.multi-product').length || $moduleContent.closest('.related-results').length)) {
            setHeights();
        }
    }


    // bazaar voice initialisation
    function initBazaarVoice() {
        var $container = $('#BVRRContainer');

        function bVcallBack() {
            $BV.configure('global', { productId: $container.data('product-id') });

            $BV.ui('rr', 'show_reviews', {
                doShowContent: function () { }
            });

        }

        if (typeof window.$BV !== 'undefined') {
            bVcallBack();
        } else {
            $.ajax({
                url: $container.data('bv-url'),
                cache: true,
                dataType: 'script',
                success: function () {
                    $($BV.docReady);
                    bVcallBack();
                }
            });
        }
    }

    // emergency alert fixed bar
    function emergencyAlert() {

        var $emergencyAlert = $('#emergency-alert'),
            messageId = $emergencyAlert.data('message-id');

        // adjust bottom padding on body to show bottom of footer
        function bodyPadding() {

            var alertHeight = $emergencyAlert.outerHeight();

            window.aa.helpers.cache.cachedElements.$body.css({ paddingBottom: alertHeight });
        }

        function showAlert() {

            // delay padding to prevent white space at bottom of page
            setTimeout(function () {
                bodyPadding();
            }, 2400);

            $emergencyAlert.removeClass('slide-out-down').addClass('slide-in-up');

            // fallback animation for ie9
            if (client.IE9) {
                $emergencyAlert.delay(240).animate({ bottom: '0' }, 2400);
            }
        }

        function hideAlert() {
            window.aa.helpers.cache.cachedElements.$body.css({ paddingBottom: 0 });

            // delay removal of class for smooth transition
            setTimeout(function () {
                $emergencyAlert.removeClass('slide-in-up');
            }, 2400);

            $emergencyAlert.addClass('slide-out-down');

            // fallback animation for ie9
            if (client.IE9) {
                $emergencyAlert.animate({ bottom: '-100%' }, 2400);
            }
        }

        // no AppInstalled cookie, display banner 
        if (!window.aa.helpers.cache.registerCookie.check('EmergencyAlert')) {
            showAlert();
        } else {
            // check if app ID doesn't exist in the cookie's value
            if ($.inArray(messageId, window.aa.helpers.cache.registerCookie.check('EmergencyAlert').split(',')) === -1) {
                showAlert();
            }
        }

        if (!window.aa.helpers.cache.cachedElements.isExperienceEditor) {
            // click event
            $emergencyAlert.find('.close').on('click', function () {

                var cookieValue = window.aa.helpers.cache.registerCookie.check('EmergencyAlert');

                /* get the cookie value, if it's not null, 
                 * split it into an array, 
                 * otherwise set its value to an empty array */
                if (cookieValue) {
                    cookieValue = cookieValue.split(',');
                } else {
                    cookieValue = [];
                }

                // if non-existent value push it to array 
                if ($.inArray(messageId, cookieValue) === -1) {
                    cookieValue.push(messageId);
                }

                // write the cookie with new value(s)
                window.aa.helpers.cache.registerCookie.write('EmergencyAlert', cookieValue.join(','), 14);

                hideAlert();

            });
        }

        // for mobile devices reveal more text on click
        if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
            $emergencyAlert.find('h6').on('click', function () {
                $(this).toggleClass('active');
                bodyPadding();
            });
        }
        // adjust padding if height adjusts on resize
        window.aa.helpers.cache.cachedElements.$window.on('resize', function () {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function () {
                if ($emergencyAlert.hasClass('slide-in-up')) { // only adjust padding if emergency alert is visible
                    bodyPadding();
                }
            }, 100); // call on resize end
        });
    }

    // module image swap
    function swapImage() {
        var $module = $(this),
            mobileImage = $module.data('mobile');

        // replace background-image url with data attribute
        if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && typeof mobileImage !== 'undefined') {
            $module.css({ 'background-image': 'url("' + mobileImage + '")' });
        }
    }

    // apply min-height based on content within - covers several module types and layouts
    function moduleHeight() {

        var $moduleContainer = $(this),
            $moduleContainerTwoCol = $moduleContainer.parent('.col'),
            $moduleColumnContainer = $moduleContainer.closest('.two-column'),
            $moduleColumnSibling = $moduleContainerTwoCol.siblings('.col'),
            $videoModule = $moduleColumnSibling.find('.youtube-video'),
            newHeight;

        // set min height or reset
        function setMinHeight() {

            var innerHeight = $moduleContainer.find('.inner').innerHeight(),
                heightOrReset = innerHeight == null ? '' : innerHeight;

            $moduleContainer.css({ minHeight: heightOrReset });
            $moduleContainer.find('.text').css({ minHeight: heightOrReset });

        }

        // remove any initial inline min-heights
        $moduleContainer.css({ minHeight: '' });
        $moduleContainer.find('.text').css({ minHeight: '' });

        if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && !window.aa.helpers.cache.cachedElements.isExperienceEditor) {

            // if two col
            if ($moduleContainerTwoCol.length) {

                // get the tallest height from the inner section of each module in the column collection, include video module in collection for that exception
                newHeight = window.aa.helpers.getTallestHeightHelper($moduleColumnContainer.find('.inner').add($videoModule));

                $moduleContainer.css({ minHeight: newHeight }); // set min height to height of tallest in either column
                $moduleContainer.find('.text').css({ minHeight: $moduleColumnSibling.find('.text').innerHeight() });

            } else {
                setMinHeight();
            }
        } else if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && !window.aa.helpers.cache.cachedElements.isExperienceEditor) {
            setMinHeight();
        }
    }

    // apply class to row if it contains hero image component
    function heroImageRow() {
        $(this).closest('.row').addClass('hero-row');
    }

    // apply class to broken down now component if directly underneath hero image row
    function heroBrokenDown() {

        var $brokenDown = $(this),
            $brokenDownHero = $brokenDown.parents('.row');

        if ($brokenDownHero.prev('.row').find('.hero-image').length) {
            $brokenDownHero.addClass('hero-service');
        }

    }

    // member benefits hero
    function memberBenefitsHero() {

        var $hero = $(this),
            $image = $hero.find('img.responsive-image'),
            $textOverlay = $hero.find('.text-overlay');

        // calculate height based on contents on text overlay
        if ($image.length && $textOverlay.length) {
            $hero.css({ height: ($hero.find('.desktop-tablet-view').is(':visible') ? $image.get(0).naturalHeight : $hero.find('.mobile-view').find('img').get(0).naturalHeight + parseFloat($textOverlay.css('top')) + parseFloat($textOverlay.find('h2 + h2').find('span').css('margin-top')) + $textOverlay.find('.button').innerHeight()) });
        }
    }

    // apply class to wrapper if it contains contact content component
    function contactContent() {
        $(this).not('.filter').closest('.wrapper').addClass('contact-wrapper');
    }

    // apply class to wrapper if it contains rich text component
    function richTextWrapper() {

        var $richText = $(this),
            $richTextWrapper = $richText.closest('.wrapper');

        if (!$richText.closest('.two-column').length) {
            $richTextWrapper.addClass('rich-text-wrapper');
        }

        // remove rich text wrapper if accordion is within
        if ($('.rich-text-wrapper').find('.accordion').length) {
            $richTextWrapper.removeClass('rich-text-wrapper');
        }
        // remove rich text wrapper if schema is within
        if ($('.rich-text-wrapper').find('.SchemaText').length) {
            $richTextWrapper.removeClass('rich-text-wrapper');
            $('.SchemaText').hide();
        }

    }

    // hide/show more links if more than 9 in list
    function moreLinks() {

        var $links = $(this),
            $toggleBtns = $links.find('.more, .less'),
            $greaterThan9Links = $links.find('li:gt(8)');

        if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {

            $greaterThan9Links.hide();

            // show more button if there are more than 9 list items
            if ($links.find('li').length > 9) {
                $toggleBtns.not('.hidden').show();
            } else {
                $toggleBtns.hide();
            }

            $toggleBtns.on('click', function (e) {

                e.preventDefault();

                // toggle view of relevant button
                $toggleBtns.toggleClass('hidden');

                // toggle view of list items
                $greaterThan9Links.stop().fadeToggle(300);

            });
        }
    }

    // smooth scroll to content id on load
    function scrollToContent() {
        var sectionContentId = window.location.hash;
        try { //Start NW-2568
            //Start-NW-2548
            var $sectionContentId = $(sectionContentId.replace(/\//g, ""));
            //End-NW-2548
            var $accordion = $sectionContentId.closest('.accordion-item'),
                accordionHeight = $accordion.find('.accordion-header').outerHeight();

            function scrollToAccordionContentId() {
                window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).stop().animate({ scrollTop: $sectionContentId.offset().top - headerHeight / 2 - accordionHeight }, 750);
            }

            if (sectionContentId && $sectionContentId.length) {

                if ($accordion.length) {

                    if ($accordion.hasClass('active')) {
                        scrollToAccordionContentId();

                    } else {

                        $accordion.find('.accordion-header').trigger('click');

                        clearTimeout(timer);
                        timer = setTimeout(function () {
                            scrollToAccordionContentId();
                        },
                            250);
                    }

                } else {
                    window.aa.helpers.cache.cachedElements.$html.add(window.aa.helpers.cache.cachedElements.$body).stop().animate({ scrollTop: $sectionContentId.offset().top - headerHeight / 1.5 }, 750);
                }
            }
            //Start NW-2568
        }
        catch (err) {
            console.log(err.message);
        }
        //End NW-2568
    }

    // financial services product selector tabs
    function productSelector() {
        var $module = $(this),
            $tabs = $module.find('.product-tab'),
            $tabsCtaContainer = $module.find('.product-selector-tabs').find('.wrapper'),
            $tabsCta = $module.find('.product-tab-cta');

        function tabsClickEvents() {
            var $target = $(this);

            $tabs.add($tabsCta.find('.tab-arrow')).hide();
            $tabsCta.removeClass('current');

            $('#' + $target.data('tab-id')).fadeIn(150, function () {
                $target.addClass('current');
            });

            // set cta height based on tallest
            $tabsCtaContainer.each(toolkit.equalHeight);
        }

        function setActiveTab() {
            var $firstCtaTab = $tabsCta.eq(0),
                url = window.location.hash,
                $targetCtaTab,
                productName;

            if (url.length) {
                productName = url.split('#')[1];
                $targetCtaTab = $('[data-nav-id="' + productName + '"]');

                if ($targetCtaTab.length) {
                    $targetCtaTab.each(tabsClickEvents);
                } else {
                    $firstCtaTab.each(tabsClickEvents);
                }

                return;
            }

            $firstCtaTab.each(tabsClickEvents);
        }

        // set selection arrow type based on container background colour
        $tabs.each(function () {
            var $tab = $(this),
                $tabCol = $tab.find('.tab-col');

            if ($tab.hasClass('mid-grey-bg-color')) {
                $('[data-tab-id="' + $tab.attr('id') + '"]').addClass('grey-arrow');
            } else {
                $tab.addClass('white-bg-color');
                $('[data-tab-id="' + $tab.attr('id') + '"]').addClass('white-arrow');
            }

            if ($tabCol.length === 1) {
                $tabCol.addClass('single-item');
            }
        });

        // set inner shadow for tab content if cta tabs are visible
        if ($tabsCta.length) {
            $tabs.addClass('inner-shadow-light');

            switch ($tabsCta.length) {
                case 1:
                    $module.addClass('single-cta-grid');
                    break;
                case 2:
                    $module.addClass('two-cta-grid');
                    break;
                case 3:
                    $module.addClass('three-cta-grid');
                    break;
                case 4:
                    $module.addClass('four-cta-grid');
                    break;
            }

            // set active tab on load
            setActiveTab();
        }

        // show tab content if cta tabs are not visible
        if ($module.find('.product-selector-tabs').length === 0 || $module.find('.product-tab-cta').length === 0) {
            $tabs.addClass('tab-visible alternate-styles');

            // alternate content containers left/right
            if ($tabs.length > 1) {
                $tabs.each(function (index) {
                    var $target = $(this),
                        $imageSection = $target.find('.image-area'),
                        $descriptionArea = $target.find('.description-area');

                    $target.addClass('mid-grey-bg-color');

                    if (index % 2 === 0) {
                        $target.removeClass('mid-grey-bg-color').addClass('white-bg-color');

                        if ($imageSection.length && $descriptionArea.length) {
                            $imageSection.detach().insertBefore($descriptionArea);
                        }
                    }
                });
            }
        }

        // set cta height based on tallest
        $tabsCtaContainer.each(toolkit.equalHeight);

        toolkit.resizeTimer.push(function () {
            $tabsCtaContainer.each(toolkit.equalHeight);
        });

        $tabsCta.off('click', tabsClickEvents).on('click', tabsClickEvents);

        window.aa.helpers.cache.cachedElements.$window.on('orientationchange', function () {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function () {
                $tabsCta.css({ height: '' });
                $tabsCtaContainer.each(toolkit.equalHeight);
            }, 200);
        });
    }

    // findancial services loan product detail
    function loanProductDetail() {
        var $module = $(this),
            $aprDescription = $module.find('.apr-description'),
            $rate = $module.find('.rate');

        // show/hide separating pipes based on visible rate information elements in table header
        if (($aprDescription.length && $rate.length === 0) || $aprDescription.length === 0 && $rate.length) {
            $module.addClass('single-rate-separator');
        } else if ($aprDescription.length === 0 && $rate.length === 0) {
            $module.addClass('rate-separator-hidden');
        }

        // check features list items
        $module.find('.feature-list').each(function () {
            var $list = $(this),
                $listItems = $list.find('li');

            if ($listItems.length && $listItems.length < 3) {
                $list.addClass('two-col-group');
            } else if ($listItems.length === 0) {
                $list.closest('.feature-list-group').hide();
            }
        });
    }

    // PP Jquery upgrade
    //    window.aa.helpers.cache.cachedElements.$document.on({
    //        ready: function () {
    window.aa.helpers.cache.cachedElements.$document.ready(
        function () {

            window.aa.helpers.cache.cachedElements.$html.removeClass('no-js');

            var responsive = new Responsive(); // instantiate responsive class

       

            $('.accordion').each(window.aa.helpers.accordions);

            $('.search').each(searchResults);

            if ($('#results-pagination').length) {
                searchPagination();
            }

            if ($('#site-footer').length) {
                stickyFooter();
            }

            $('.equal-height').each(window.aa.helpers.panelHeight);

            $('.module.youtube-video, .related-product, .app-promo, .campaign-promo, .contact-content, .related-links, .two-column .exchange-tool, .est-related-links').each(moduleHeight);

            $('.fade-in').each(textFadeIn);

            $('.product-detail').each(productionDetailHeaders);

            if ($('.youtube-video').length) {
                boot.loadScript('https://www.youtube.com/iframe_api', 'cdn', function () {
                    initYouTubeAPI();
                });
            }

            // tealium universal tag data exists
            if (typeof window.utag_data !== 'undefined') {
                loadTealium();
            }

            if ($('#BVRRContainer').length) {
                initBazaarVoice();
            }

            if ($('.iframe-container').length) {
                boot.loadScript('iframeResizer.min.js', 'libs', function () {
                    $('.iframe').each(iframeResizer);
                });
            }

            if ($('#emergency-alert').length) {
                emergencyAlert();
            }

            if ($('#weather').length) {
                boot.loadScript('weather.js', 'global', function () { });
            }

            if ($('#site-wrapper').length) {
                scrollToContent();
            }

            // init cinemagraphs
            $('.cinemagraph').each(initCinemagraph);

            $('.module').each(swapImage);

            $('.hero-image').each(heroImageRow);

            $('.ch-hero-image').each(heroImageRow);

            $('.service').each(heroBrokenDown);

            $('.contact-content').each(contactContent);

            $('.rich-text').each(richTextWrapper);

            $('.module-accordion').each(window.aa.helpers.moduleAccordion);

            $('.related-links').each(moreLinks);

            $('.financial-services-product-selector').each(productSelector);

            $('.loan-product-detail').each(loanProductDetail);

            if ($('#sales-journey-header').length) {

                if (typeof window.aa.salesJourneyApp !== 'undefined') {
                    window.aa.salesJourneyApp.application.init();
                }

            }

            // calculator tools functionality
            if ($('.calculator-tool').length) {
                boot.loadScript('tools.js', 'global', function () { });
                if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    $('.calculator-tool').find('.calculation-result').removeClass('table');
                }
            }

            stylishForms.apply();
            //}
        });
    window.aa.helpers.cache.cachedElements.$window.on({
        resize: function () {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function () {
                $('.equal-height').each(window.aa.helpers.panelHeight);
                $('.related-content, .content-article, .multi-product-container, .twitter-container').each(relatedContent);
                $('.module.youtube-video, .related-product, .app-promo, .campaign-promo, .contact-content, .related-links, .two-column .exchange-tool, .est-related-links').each(moduleHeight);
                $('.module').each(swapImage);
                $('.product-detail').each(productionDetailHeaders);
                $('.hero-image.member-benefits').each(memberBenefitsHero);

                if ($('#site-footer').length) {
                    stickyFooter();
                }

                $('.cinemagraph').each(initCinemagraph);

                if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    $('.calculator-tool').find('.calculation-result').removeClass('table');
                } else {
                    $('.calculator-tool').find('.calculation-result').addClass('table');
                }

            }, 100); // call on resize end
        },
        load: function () {
            $('.module.youtube-video, .related-product, .app-promo, .campaign-promo, .contact-content, .related-links').each(moduleHeight); // call on load to account for images
            $('.product-comparison, .table-component').each(productComparison);
            $('#search-icon').on('click', function () {
                $('#search-takeover').find('input').first().focus();
            }); // call on load for mobile

            $('.hero-image.member-benefits').each(memberBenefitsHero);

            $('.related-content, .content-article, .multi-product-container, .twitter-container, .related-results').each(relatedContent);


        }
    });

    // PP Jquery upgrade
    //    window.aa.helpers.cache.cachedElements.$document.on({
    //        ready: function () {
    window.aa.helpers.cache.cachedElements.$document.ready(
        function () {


            $(document).find('.desktop-btn-view .filter-link,.filter-close-btn .close-link').on('click', function (e) {
                e.preventDefault();

                $('.offers-sidebar .offer-filter').slideToggle();/*CD-3143*/
            });



            $('#offersModal').on('show.bs.modal', function (e) {
                var rewardId = $(e.relatedTarget).data('reward-id');
                $(e.currentTarget).find('#offer-url').attr('src', rewardId);
            });


            //}
        });


    //$(window).on('load', function () {
    //    //include condition here
    //    $('#codeNotAvailableModal').modal('show');
    //});
    //$(document).ready(function () {
    //    $('#codeNotAvailableModal').on('hidden.bs.modal', function (e) {
    //      window.location = $('#codeNotAvailableModal').find('.modal-header').find('a').attr('href'); //MEM-1
    //        $(this).parents('.row-with-sidebar').css('z-index', '1');
    //    });
    //    $('#codeNotAvailableModal').on('shown.bs.modal', function (e) {
    //        $(this).parents('.row-with-sidebar').css('z-index', 'inherit');
    //        //END MEM-92
    //    });

    //});

    $(window).on('load', function () {
        //include condition here
        $('#codeNotAvailableModal').modal('show');
    });
    $(document).ready(function () {
        $('#codeNotAvailableModal').on('hidden.bs.modal', function (e) {
            window.location = $('#codeNotAvailableModal').find('.modal-header').find('a').attr('href');
            $(this).parents('.row-with-sidebar').css('z-index', '1');
            var url = "\/member-benefits/all";
            window.location = url;
        });
        $('#codeNotAvailableModal').on('shown.bs.modal', function (e) {
            $(this).parents('.row-with-sidebar').css('z-index', 'inherit');
        });
    });

    $('.report-breakdown').click(function () {
        //e.preventDefault();
        $(this).fadeOut(300);
        $('.modal-backdrop.fade.in').addClass('dark');
        $('#brokenDownModal').modal({
            backdrop: 'static',
            keyboard: false
        })
    });
    $('#brokenDownModal').on('shown.bs.modal', function (e) {


    });
    $('#brokenDownModal').on('hidden.bs.modal', function (e) {

        $('.report-breakdown').fadeIn(300);
    });

    //best bundle accordion
    var $bundletable = $('.best-bundle-table');
    var $headerClick = $bundletable.find('.best-bundle-content-item-head-title');
    $($headerClick).on('click', function (e) {
        e.preventDefault();

        $(this).parent().next('.best-bundle-content-item-description').slideToggle();
        $(this).parent().parent('.best-bundle-content-item').toggleClass('best-bundle-closed');
        if ($(this).parent().parent().siblings().find('.best-bundle-content-item-description').is(':visible')) {
            $(this).parent().parent().siblings().find('.best-bundle-content-item-description').slideUp().parent('.best-bundle-content-item').addClass('best-bundle-closed');;
            //$(this).parent().parent().addClass('best-bundle-closed');
        }
        else if ($(this).parent().parent().parent().parent().siblings().find('.best-bundle-content-item-description').is(':visible')) {
            $(this).parent().parent().parent().parent().siblings().find('.best-bundle-content-item-description').slideUp().parent('.best-bundle-content-item').addClass('best-bundle-closed');
            //$(this).siblings().addClass('best-bundle-closed');
        }


    });
    //cover table js
    function covetableHeight() {

        var $tableCol = $(this).find('.cover-level-table-col >.cover-level-table-content'),
            heights = [];

        $tableCol.css('height', '');

        function setHeights() {
            $tableCol.each(function () {
                heights.push($(this).height());
            });

            $tableCol.height(Math.max.apply(null, heights));
        }

        if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.TABLET_LANDSCAPE) {
            setHeights();
        }

        else if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.TABLET_LANDSCAPE && ($tableCol.closest('.cover-level-table-wrap').length)) {
            setHeights();

        }
    }
    //BAU-CD-1766
    window.aa.helpers.cache.cachedElements.$window.on({

        resize: function () {
            if ($(".cover-level-table").length) {
                $('.cover-level-table-wrap').each(covetableHeight);//summary boxes height
            }
        },
        load: function () {
            if ($(".cover-level-table").length) {
                $('.cover-level-table-wrap').each(covetableHeight);//summary boxes height
            }
        }
    });

    $('.tab-content:first').show();
    $('.product-type-tabs a').click(function (event) {

        event.preventDefault();
        $('.tab-content').hide();
        $(this).addClass('active');
        $(this).parent().siblings().find('a').removeClass('active');
        $('#' + $(this).attr('title')).show();

        if ($(".cover-level-table").length) {
            $('.cover-level-table-wrap').each(covetableHeight);//summary boxes height
        }


    });

    //CD-13970

    $(".flex-product-block").each(function () {
        if ($(this).find(".product-image").length) {
            //$(".flex-product-block").find(".product-image").hide();
            $(this).find('.product-brief').addClass('five-col-width');
        }
    });

    if ($(".flex-product-block").length) {
        if ($(".flex-product-block > .product-brief").find(".prod-cta-links:empty")) {
            $(".prod-cta-links").remove();
        }
    }


})(jQ);
///#source 1 1 /Assets/scripts/contact-us-3.5.js
/* 
 * ---------------------------------------- *
 * Name: 	Contact Us JavaScripts          *
 * Type: 	JavaScript                      *
 * Version: Not Versioned                   *
 * Author:	Mihai Boceanu | Codehouse       *
 * ---------------------------------------- *
 */

(function ($) {

    var subSectionHeight,
        resizeTimer,
        timer;

    // get active panel height
    function panelsHeight($optionsList, $selector) {

        subSectionHeight = $selector.height() + 10;

        $optionsList.css({ minHeight: subSectionHeight });
    }

    // set contact us options list height based on active panel height
    function contactUsPanelsHeight() {

        var $module = $(this),
            $optionsList = $module.find('.options-list'),
            $panels = $module.find('.panel.active'),
            $infoBlock = $module.find('.info-message-block'),
            $activeSubSection = $module.find('.sub-section.active');

        // show second level panels on larger screens
        if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
            $module.find('.sub-section').find('li').show();
            // hide info block on mobile
        } else {
            $infoBlock.hide();
        }

        // set container height based on highest active panel
        if ($activeSubSection.length && !$panels.hasClass('active')) {
            panelsHeight($optionsList, $activeSubSection);
            $infoBlock.hide();

        } else if ($activeSubSection.length && $panels.hasClass('active')) {

            if ($panels.height() > $activeSubSection.height() && window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                panelsHeight($optionsList, $panels);

            } else if ($panels.height() < $activeSubSection.height() && window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                panelsHeight($optionsList, $activeSubSection);

            }
        }
    }

    function setMinHeight() {

        var $module = $(this);

        $module.find('.inner-content').css({ minHeight: $module.find('.info-message-block .help-text').height() + 50 });
    }

    // init contact us events
    function contactUsEvents() {

        var $module = $(this),
            $optionsList = $module.find('.options-list'),
            $option = $module.find('.option'),
            $subOption = $module.find('.sub-option'),
            $subSections = $module.find('.sub-section'),
            $panels = $module.find('.panel'),
            $infoBlock = $module.find('.info-message-block'),
            $mobileSecondLevelHeader = $module.find('.second-level-title .mobile-list-label'),
            $mobileThirdLevelHeader = $module.find('.third-level-title .mobile-list-label'),
            $selectedPanel;

        function setColumnTitle() {

            var $columnTitle = $(this),
                columnTitlePlaceholderId = $columnTitle.data('placeholder'),
                columnTitleHtml = $columnTitle.html();

            if (columnTitleHtml) {
                $('.' + columnTitlePlaceholderId).html(columnTitleHtml);
            }
        }

        // set text for middle and right column title
        $('.third-level-right-title,.second-level-middle-title').each(setColumnTitle);

        // set module minimum height 
        $('.contact-us').each(setMinHeight);

        // focus on contact us component as soon as page loads
        $module.focus();

        // level one panels event handler
        $option.on('click', function () {

            var $target = $(this),
                $subSection = $target.closest('.content-section').find('.sub-section'),
                $subSectionButton = $subSections.find('button'),
                $primarySectionButton = $target.closest('.content-section').siblings().find('.option');

            $subSections.find('li').show();

            if ($subSection.hasClass('active')) {

                if (client.IE9 && window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    $subSections.css({ left: '28%' }).stop().animate({ left: '0' }, 350);
                }

                // accessibility
                $subSectionButton.prop('tabindex', '-1');
                $primarySectionButton.removeAttr('tabindex');

                $subSections.add($option).add($panels).add($subOption).removeClass('active');
                $optionsList.removeClass('sliding open sub-level-open').css({ minHeight: 0 });
                $infoBlock.show();
                // set module minimum height 
                $('.contact-us').each(setMinHeight);

            } else {

                if (client.IE9 && window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    $subSection.css({ left: 0 }).stop().animate({ left: '28%' }, 350);
                }

                $subSections.add($option).add($panels).add($subOption).removeClass('active');
                $subSection.add($target).addClass('active');

                $subSectionButton.removeAttr('tabindex');
                $primarySectionButton.prop('tabindex', '-1');

                subSectionHeight = $subSection.height();
                // store selected option
                $selectedPanel = $target;

                $optionsList.addClass('sliding open').css({ minHeight: subSectionHeight });
                $infoBlock.hide();

                clearTimeout(timer);

                timer = setTimeout(function () {
                    $optionsList.removeClass('sliding');
                }, 380);
            }
        });

        //level two panels event handler
        $subOption.on('click', function () {

            var $trigger = $(this),
                $targetPanel = $module.find('#' + $trigger.data('panel-id')),
                $activeSubSection = $module.find('.sub-section.active'),
                $subOptionSiblings = $trigger.closest('li').siblings().find('.sub-option'),
                panelSectionHeight = $activeSubSection.height();

            if ($targetPanel.hasClass('active')) {

                if (client.IE9 > window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    $panels.css({ left: '100%' }).stop().animate({ left: 0 }, 350);
                }

                // set tabindexes
                $subOptionSiblings.removeAttr('tabindex');
                $targetPanel.prop('tabindex', '-1');

                $panels.add($subOption).removeClass('active');
                $module.removeClass('panel-open');
                $optionsList.removeClass('sliding-second-level sub-level-open').css({ minHeight: panelSectionHeight });

            } else {

                if (client.IE9 && window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    $targetPanel.css({ left: 0 }).stop().animate({ left: '100%' }, 350);

                } else if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    $subSections.find('li').hide();
                    $targetPanel.parent().show();

                } else if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    $subSections.find('li').show();
                }

                // set tabindexes
                $panels.add($subOption).removeClass('active');
                $subOptionSiblings.prop('tabindex', '-1');

                $targetPanel.removeAttr('tabindex').add($trigger).addClass('active');
                $module.addClass('panel-open');
                $optionsList.addClass('sliding-second-level sub-level-open');

                panelSectionHeight = $targetPanel.height() + 10;
                subSectionHeight = $activeSubSection.height();

                if (panelSectionHeight > subSectionHeight || window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    $optionsList.css({ minHeight: panelSectionHeight });
                }

                else {
                    $optionsList.css('min-height', subSectionHeight);
                }

                clearTimeout(timer);

                timer = setTimeout(function () {
                    $optionsList.removeClass('sliding-second-level');
                }, 380);
            }

        });

        // return to first level selection panel
        $mobileSecondLevelHeader.on('click', function () {

            $subSections.add($option).add($panels).add($subOption).removeClass('active');
            $optionsList.removeClass('open sub-level-open').css({ minHeight: 0 });
        });

        // return to second level selection panel
        $mobileThirdLevelHeader.on('click', function () {
            $subSections.add($option).add($panels).add($subOption).removeClass('active');
            $optionsList.removeClass('open sub-level-open');
            $selectedPanel.trigger('click');
        });
    }

    function phoneCardOpeningHours() {

        var $thisCard = $(this),
            $currentStatus = $thisCard.find('.hours'),
            $openingTime = $thisCard.find('.time'),
            currentStatus = $currentStatus.data('current-status');

        // show/hide opening times if current time exceeded the time frame 
        if (currentStatus === 'Closed now' || currentStatus === 'Closed' || currentStatus === 'Closed today') {
            $openingTime.addClass('closed');

        } else {
            $openingTime.addClass('open');
        }

        $thisCard.find('.hours').on('click', function () {

            var $activePanel = $thisCard.closest('.panel.active'),
                $optionsList = $thisCard.closest('.options-list');

            $(this).fadeOut();
            $thisCard.find('.opening-hours').slideDown(function () {

                var panelSectionHeight = $activePanel.height();

                $optionsList.css({ minHeight: panelSectionHeight });
            });
        });
    }

    // PP Jquery upgrade
    //    window.aa.helpers.cache.cachedElements.$document.on({
    //        ready: function () {
    window.aa.helpers.cache.cachedElements.$document.ready(
        function () {

            $('.contact-us').each(contactUsEvents);

            $('.phone-card').each(phoneCardOpeningHours);
            //        }
        });
    window.aa.helpers.cache.cachedElements.$window.on({
        resize: function () {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function () {

                $('.contact-us').each(contactUsPanelsHeight);
                $('.contact-us').each(setMinHeight);

            }, 100); // call on resize end
        }
    });

})(jQ);
///#source 1 1 /Assets/scripts/eligibility-popup.js
function eligibilityCalculator() {
    //BAU-FS-448 Starts//

    var cid,
        defautSelectedValue,
        scCookieValue,
        scCookieFlag = false, // Query String Cookie Flag
        referrerCheck = false, // Referral Url Check Flag
        referrer,// Referal Url 
        loanProductDetailCode = $('#loanProductDetail').text(),
        hiddenLinkValue = $('#linkvalue').text(),
        selectedMembership;

    if (document.referrer != "") {
        referrer = document.referrer.match(/:\/\/(.[^/]+)/)[1];
        //Iterate over hidden fields for referral code
        $("div.searchenginereff label.search-engine-ref-token").each(function () {
            //  var searchTextId = this.id;
            var searchTextVal = $(this).data('value')
            var searchTextKey = $(this).data('key');
            if (referrer.toLowerCase() == searchTextKey.toLowerCase()) {
                referrerCheck = true; //Set Flag
                //sessionStorage.setItem("referrerName", searchTextVal);
                //referrer = sessionStorage.getItem("referrerName");
                return false;
            }

        });

    }
    //To get values from "TheAA_loanCalc" cookie
    function getCookie(name) {
        var value = "; " + document.cookie;
        var parts = value.split("; " + name + "=");
        if (parts.length == 2) return parts.pop().split(";").shift();
    }

    var intr = setInterval(function () {
        if (getCookie("TheAA_loanCalc") && getCookie("_ga")) {
            clearIntr();
        }
    }, 100);

    function clearIntr() {
        clearInterval(intr);
        //To get values from "TheAA_loanCalc" cookie
        var pairs = getCookie("TheAA_loanCalc");
        var array = pairs.split(",");
        $.each(array, function (i) {
            array[i];
            if (array[i].toString().toLowerCase().indexOf("productcode") >= 0) {
                defautSelectedValue = array[i].toString().toLowerCase().split(":").pop().replace(/\"/g, "");
            }
        });
        //defautSelectedValue = array[1].substr(array[1].indexOf(":") + 1);

        //To get values from "_GA" cookie
        var gaCookie = getCookie("_ga");

        var gaCookieArray = gaCookie.split(".");
        $.each(gaCookieArray, function (i) {
            gaCookieArray[i];
        });
        cid = gaCookieArray[2] + "." + gaCookieArray[3];

        //To get values from "sc" cookie//
        var scCookie = getCookie("f69fe449-ad88-491e-8b83-c53bb2b753c6");
        var decodeScCookie = unescape(scCookie);
        var arr = decodeScCookie.split(";");
        for (var i = 0; i < arr.length; i++) {
            var splitCookieVar = arr[i].split("=");
            var splitCookieVar = arr[i].split("=");
            if (splitCookieVar[0] == "sc") {
                scCookieValue = splitCookieVar[1];
                scCookieFlag = true; // Set flag
                break;
            }
        }
        setUrls();
    }

    //Calling setUrls function once the cookie is set
    function setUrls() {
        var url = window.location.href;

        // Memeber Flow 
        if (defautSelectedValue == loanProductDetailCode) {
            if (scCookieFlag) {
                $('.' + $('#productSelector').text()).attr('href', 'javascript:void(0);');
                $('.continueLink').attr('href', hiddenLinkValue + "?0&sourcecode=" + loanProductDetailCode + "&sc=" + scCookieValue + "&cid=" + cid);
            }

            else if (referrerCheck) {
                $('.' + $('#productSelector').text()).attr('href', 'javascript:void(0);');
                $('.continueLink').attr('href', hiddenLinkValue + "?0&sourcecode=" + loanProductDetailCode + "&sc=" + scCookieValue + "&cid=" + cid);
            }
            else {
                $('.' + $('#productSelector').text()).attr('href', 'javascript:void(0);');
                $('.continueLink').attr('href', hiddenLinkValue + "?0&sourcecode=" + loanProductDetailCode + "&cid=" + cid);
            }

        }

        //Non Member Flow 
        else {
            if (scCookieFlag) {
                $('.popup').attr('href', $('#eligibilityLink > a').attr('href') + "?0&sourcecode=" + defautSelectedValue + "&sc=" + scCookieValue + "&cid=" + cid);
                $('.continueLink').attr('href', hiddenLinkValue + "?0&sourcecode=" + loanProductDetailCode + "&sc=" + scCookieValue + "&cid=" + cid);
            }
            else if (referrerCheck) {
                $('.popup').attr('href', $('#eligibilityLink > a').attr('href') + "?0&sourcecode=" + defautSelectedValue + "&sc=" + scCookieValue + "&cid=" + cid);
                $('.continueLink').attr('href', hiddenLinkValue + "?0&sourcecode=" + loanProductDetailCode + "&sc=" + scCookieValue + "&cid=" + cid);
            }
            else {
                //FS-493-Starts//
                if (url.indexOf("80003") >= 0) {
                    $('.' + $('#productSelector').text()).attr('href', 'javascript:void(0);');
                    $('.continueLink').attr('href', hiddenLinkValue + "?0&sourcecode=" + loanProductDetailCode + "&cid=" + cid);
                }
                //FS-493-Ends//
                else {
                    $('.popup').attr('href', $('#eligibilityLink > a').attr('href') + "?0&sourcecode=" + defautSelectedValue + "&cid=" + cid);
                    $('.continueLink').attr('href', hiddenLinkValue + "?0&sourcecode=" + loanProductDetailCode + "&cid=" + cid);
                }
            }
        }
    }
    //BAU-FS-448 Ends//
    //Continue Link only Member and Membership Validation Popup
    $('.continueLink').click(function () {

        var memberShipRegex = /^((635601)\d{10})|((6356 01)\d{2}\s\d{4}\s\d{4})$/;
        var membershipValue = $('#memberShipCode').val();
        if (membershipValue != "") {
            $('#memberShipCode').removeClass('errorInput');
            var membershipValueTestResult = memberShipRegex.test(membershipValue);
            if (membershipValueTestResult == true) {
                if (scCookieFlag) {
                    $('.continueLink').attr('href', hiddenLinkValue + "?0&sourcecode=" + loanProductDetailCode + "&sc=" + scCookieValue + "&cid=" + cid);
                }
                else if (referrerCheck) {
                    $('.continueLink').attr('href', hiddenLinkValue + "?0&sourcecode=" + loanProductDetailCode + "&sc=" + scCookieValue + "&cid=" + cid);
                }
                else {
                    $('.continueLink').attr('href', hiddenLinkValue + "?0&sourcecode=" + loanProductDetailCode + "&cid=" + cid);
                }
            }
            else {
                $("#errorLabelInvalid").css("display", "block");
                $('#memberShipCode').addClass('errorInput');
                $("#errorLabelEmpty").css("display", "none");
                $('.continueLink').attr('href', 'javascript:void(0);');
                $(".invalidMembership").css("display", "block");

            }

        }
        else {
            $("#errorLabelInvalid").css("display", "none");
            $('#memberShipCode').addClass('errorInput');
            $("#errorLabelEmpty").css("display", "block");
            $(".invalidMembership").css("display", "block");
            $('.continueLink').attr('href', 'javascript:void(0);');
        }
    });


    //Calculator Yes/NO Cookie Set
    $("input:radio[name=membership]").click(function () {
        selectedMembership = $(this).val();

        if (selectedMembership == loanProductDetailCode) {
            $('.' + $('#productSelector').text()).attr('href', 'javascript:void(0);');
        }
        else {
            if (scCookieFlag) {
                $('.' + $('#productSelector').text()).attr('href', $('#eligibilityLink > a').attr('href') + "?0&sourcecode=" + selectedMembership + "&sc=" + scCookieValue + "&cid=" + cid);
            }
            else if (referrerCheck) {
                $('.' + $('#productSelector').text()).attr('href', $('#eligibilityLink > a').attr('href') + "?0&sourcecode=" + selectedMembership + "&sc=" + scCookieValue + "&cid=" + cid);
            }
            else {
                $('.' + $('#productSelector').text()).attr('href', $('#eligibilityLink > a').attr('href') + "?0&sourcecode=" + selectedMembership + "&cid=" + cid);
            }
        }
    });

    $("#memberShipCode").focusin(function () {
        $('#memberShipCode').removeClass('errorInput');
        $(".invalidMembership").css("display", "none");
    });

    $(".popup").click(function () {
        var popupyesorno = $('.' + $('#productSelector').text()).attr('href');
        if (popupyesorno == "javascript:void(0);") {

            $('#myModal').modal({ backdrop: true });


        }
        else {
            ('#myModal').modal('hide');

            e.preventDefault();
        }
    });

    $(".closeModal").click(function () {
        $('#myModal').modal('hide');

    });
}



///#source 1 1 /Assets/scripts/member-benefits-offers-jq-3.7.1.js
/*
 * ---------------------------------------- *
 * Name: 	Listing JavaScripts             *
 * Type: 	JavaScript Module               *
 * Version: Not Versioned                   *
 * Author:	Zensar    
 * Requisites: >=jQuery 1.10.2              *
 *             serialise.js                 *
 * ---------------------------------------- *
 */

/*
 * javascripts for misc listing components using webapi with pagination and sorting
 */

window.aa || (window.aa = {}); //  aa namespace
window.aa.memberBenefitsOffers || (window.aa.memberBenefitsOffers = {});


// filter listing functionality
$(document).ready(function () {

    var OfferListing = new function OfferListing() {

        //Height of boxes gobal function
        function categoryOffer() {

            var $boxContent = $(this).find('.offer-details-box'),
                heights = [];

            $boxContent.css('height', '');

            function setHeights() {
                $boxContent.each(function () {
                    heights.push($(this).height() + 20);
                });

                $boxContent.height(Math.max.apply(null, heights));
            }

            if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                setHeights();
            }
        }

        //format Membership Number
        function formatNumber(num) {
            if (num.length > 1) {
                return num.toString().replace(/(\d)(?=(\d{4})+(?!\d))/g, '$1 ')
            }
        }

        //for mobile view
        if (window.aa.helpers.cache.cachedElements.$window.width() < window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
            $('#site-footer').css('padding-bottom', $('.booking-widgets').height());//MEM-1
            //$(document).find(".mobile-filter-button button").attr("disabled", true);

        }
        //for tablet view
        else if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.TABLET_BREAKPOINT) {
            $('#site-footer').css('padding-bottom', $('.booking-widgets').height());//MEM-1
            $('.offer-filter').hide();//CD-3143
            //for social icons tablet 

            $('aside.social-media-icons').css('min-height', '170px');//MEM-99 social icons 

            //$(document).find(".mobile-filter-button button").attr("disabled", true);
        }
        else {
            $('#site-footer').css('padding-bottom', '0px');
        }


        $('.OffersArea').each(function () {

            var $thisFilter = $(this),
                $resultsOfferCategoryContainer = $thisFilter.find('.offers-sidebar'),
                $resultOfferTierContainer = $thisFilter.find('.offers-sidebar .tierBenefitsCategory'),
                $resultListOffersContainer = $thisFilter.find('.offers-with-sidebar'),
                $mobileResultsOfferCategoryContainer = $thisFilter.find('.mobileCategoryfilter'),
                $loader = $thisFilter.find('.loader'),
                categoriesTemplate,
                isPageReset,
                resultOfferCategoryTilesTemplate,
                resultOfferTierContainerTierTemplate,
                resultListOffersTilesTemplate,
                mobileResultOfferCategoryTilesTemplate,
                dataObj = {},
                serviceRequests,
                onLoad = false,
                allResults = false,
                currentPageNumber,
                loaderTimer,

                presentation = {
                    buildMarkup: function (response) {
                        var filtersFinalMarkup,
                            categoriesOfferFinalMarkup,
                            resultOfferTilesFinalMarkup,
                            sortOfferByFinalMarkup,
                            $sortBy;

                        // build markup using Mustache    
                        mobileResultOfferCategoryTilesFinalMarkup = Mustache.render(mobileResultOfferCategoryTilesTemplate, response);
                        mobileResultOfferTierContainerTierTemplate = Mustache.render(resultOfferTierContainerTierTemplate, response);
                        resultOfferCategoryTilesFinalMarkup = Mustache.render(resultOfferCategoryTilesTemplate, response);
                        //mobile append markup
                        if (allResults == false) {
                            $mobileResultsOfferCategoryContainer.html(mobileResultOfferCategoryTilesFinalMarkup);
                            $resultOfferTierContainer.html(mobileResultOfferTierContainerTierTemplate);
                            $resultsOfferCategoryContainer.html(resultOfferCategoryTilesFinalMarkup);
                        }


                        resultListOffersTilesFinalMarkup = Mustache.render(resultListOffersTilesTemplate, response);
                        $resultListOffersContainer.html(resultListOffersTilesFinalMarkup);

                        resizeHeightBoxes();

                        //for resizing Boxes 
                        function resizeHeightBoxes() {
                            /*CD-3001 start*/
                            var $OfferSpanItem = $(".offers-with-sidebar article.offer-box "),
                                $OfferSpanItemSiver = $(".offers-with-sidebar article.offer-box-silver"),
                                $OfferSpanItemGold = $(".offers-with-sidebar article.offer-box-gold");

                            for (var i = 0; i < $OfferSpanItem.length; i += 3) {

                                var $OfferRowdiv = $("<div/>", {
                                    class: 'offers-row spacer col-div mb-equalHeight'
                                });
                                $OfferSpanItem.slice(i, i + 3).wrapAll($OfferRowdiv);
                                $('.offer-image img').on('load', function () {
                                    $('.offers-row').each(categoryOffer);
                                });
                                //$('.offers-row').each(categoryOffer);
                            }

                            for (var i = 0; i < $OfferSpanItemSiver.length; i += 3) {

                                var $OfferRowdiv = $("<div/>", {
                                    class: 'offers-row spacer col-div mb-equalHeight'
                                });
                                $OfferSpanItemSiver.slice(i, i + 3).wrapAll($OfferRowdiv);
                                $('.offer-image img').on('load', function () {
                                    $('.offers-row').each(categoryOffer);
                                });
                            }

                            for (var i = 0; i < $OfferSpanItemGold.length; i += 3) {
                                var $OfferRowdiv = $("<div/>", {
                                    class: 'offers-row spacer col-div mb-equalHeight'
                                });
                                // $OfferSpanItemSiver.slice(i, i + 3).wrapAll($OfferRowdiv);
                                $OfferSpanItemGold.slice(i, i + 3).wrapAll($OfferRowdiv);
                                $('.offer-image img').on('load', function () {
                                    $('.offers-row').each(categoryOffer);
                                });
                            }


                        }
                        /*CD-3001 end*/

                        //Populate category names into array
                        function populateCategoryNames() {
                            categoryNames = [];
                            allResults = true;
                            i = 0;
                            $(".checkbox-row input:checkbox[name=categoryFilterSort]:checked").each(function () {
                                categoryNames[i] = { "categoryName": $(this).val() }
                                i++;
                            });

                            if (categoryNames.length > 0) {
                                actions.postDataService(categoryNames);
                            } else if (categoryNames.length == 0) {
                                actions.callService(categoryNames);
                            }
                        }

                        //clear all filter
                        if ($(".checkbox-row input:checkbox[name=categoryFilterSort]").is(':checked')) {
                            $(".clearAll-filters").css("display", "block");
                        } else {
                            $(".clearAll-filters").css("display", "none");
                        }

                        //on click of clear all filter link
                        $(".clearAll-filters").on('click', function (e) {
                            e.stopImmediatePropagation();
                            $(".checkbox-row  input:checkbox[name=categoryFilterSort]").prop("checked", false);
                            if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                                if (!$(".checkbox-row input:checkbox[name=categoryFilterSort]").is(':checked')) {
                                    $(".filter-btn .filterlinkForDesktop span").text(" ");
                                    populateCategoryNames();
                                }
                            } else if (window.aa.helpers.cache.cachedElements.$window.width() < window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                                $(".clearAll-filters").css("display", "none");
                                //$(document).find(".mobile-filter-button button").attr("disabled", true);
                                $(".filter-btn .filterlinkForMobile span").text(" ");
                            }
                        });

                        //On change of Category checkbox
                        $(".OfferCategoryCb").on('change', function (e) {
                            e.stopImmediatePropagation();
                            populateCategoryNames();
                            if ($('.checkbox-row input:checkbox[name=categoryFilterSort]').is(':checked')) {
                                $categoryIpadCount = $('.checkbox-row input:checkbox[name=categoryFilterSort]:checked').length;
                                $(".filter-btn .filterlinkForDesktop span").text("(" + $categoryIpadCount + ")");
                            } else {
                                $(".filter-btn .filterlinkForDesktop span").text(" ");
                            }
                        });

                        //for mobile on category change event
                        $(".mobileCategoryFilterCb").on('change', function () {

                            $(".clearAll-filters").css("display", "block");
                            if (!$(".mobileCategoryFilterCb input:checkbox[name=categoryFilterSort]").is(':checked')) {
                                $(".clearAll-filters").css("display", "none");
                                // $(document).find(".mobile-filter-button button").attr("disabled", true);
                                $(".filter-link span").text(" ");
                            } else {
                                $(".clearAll-filters").css("display", "block");
                                //$(document).find(".mobile-filter-button button").attr("disabled", false);

                            }
                        });

                        //for mobile modal pop up and category filter
                        $(".mobile-filter-button button").on('click', function (e) {
                            e.stopImmediatePropagation();
                            populateCategoryNames();
                            $('.mobileCategoryfilter').modal('hide');
                            $('.modal-backdrop').css('display', 'none');
                            if ($('.checkbox-row input:checkbox[name=categoryFilterSort]').is(':checked')) {
                                $categoryMobileCount = $('.checkbox-row input:checkbox[name=categoryFilterSort]:checked').length;
                                $(".filter-link span").text("(" + $categoryMobileCount + ")");
                            }
                        });

                        //ipad close toggle category filter
                        $(document).find(".filter-close-btn .close-link").on('click', function (e) {
                            e.stopImmediatePropagation();
                            $('.offers-sidebar .offer-filter').slideToggle();
                        });

                        //CD-2995
                        var tierArrow = document.querySelector('.tier-arrow');
                        if ($('.tier-arrow').length > 0) {
                            document.querySelector('.tier-arrow').addEventListener('click', function (e) {
                                e.stopImmediatePropagation();
                                $('.innerTierContainer').slideToggle();
                                $(this).toggleClass('active');
                            });
                        }



                        //iphone close modal toggle
                        $(document).find("#mobilefilter .modal-header .close").on('click', function (e) {
                            e.stopImmediatePropagation();
                            $('.mobileCategoryfilter').modal('hide');
                            $('.modal-backdrop').css('display', 'none');
                            if (!$(".mobileCategoryFilterCb input:checkbox[name=categoryFilterSort]").is(':checked')) {
                                actions.callService();
                            }

                        });
                        //MEM-126 start
                        var scrolltop = window.aa.helpers.cache.cachedElements.$window.scrollTop();


                        if ((scrolltop === 0 || scrolltop < 99)) {
                            $('#members-benefits-area #loader.mbLoader .loading').css('position', '');
                            $('#members-benefits-area #loader.mbLoader .loading').css('top', '158px');
                        }
                        else if (window.aa.helpers.cache.cachedElements.$window.scrollTop() > 100) {
                            $('#members-benefits-area #loader.mbLoader .loading').css('position', 'fixed');
                            $('#members-benefits-area #loader.mbLoader .loading').css('top', '60%');
                        }

                        //MEM-126 End
                    },
                    loader: {

                        hide: function () {
                            clearTimeout(loaderTimer);
                            $loader.hide();
                        },
                        show: function () {
                            clearTimeout(loaderTimer);
                            loaderTimer = setTimeout(function () {
                                $loader.show();
                            }, 100);
                        }
                    },
                    loginTierDisplay: function (response) {
                        var $loginBlock = $('.loginBlock'),
                            $benefitBlock = $('.benefitsBlock');

                        if (response.IsUserLoggedIn) {
                            //false
                            $loginBlock.hide();
                            $benefitBlock.show();
                            if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.TABLET_BREAKPOINT) {
                                if ($loginBlock.css('display') == 'none') {
                                    $(".offers-sidebar .benefitsBlock").remove().insertAfter($(".offers-sidebar .offer-filter"));//CD-3143
                                }
                            }
                        } else {
                            //true
                            $benefitBlock.hide();
                            $loginBlock.show();
                            if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.TABLET_BREAKPOINT) {

                                if ($benefitBlock.css('display') == 'none') {
                                    $(".offers-sidebar .loginBlock").remove().insertAfter($(".offers-sidebar .offer-filter"));//CD-3143
                                }
                            }
                        }
                    }
                },
                actions = {

                    //ajax call on initial load and if no category is selecteds
                    callService: function () {
                        if ($('.offer-section').length) {
                            $('article.offer-box').hide();
                            $('#loadermb').show();
                        } else {
                            presentation.loader.show();
                        }
                        $.ajax({
                            method: "POST",
                            data: {
                                Category: { "categoryName": " " }
                            },
                            url: "/api/sitecore/MemberBenefits/GetOffersListByCategory",
                            success: function (response) {
                                if (response.MembershipNumber != null) {
                                    response.MembershipNumber = formatNumber(response.MembershipNumber);
                                }
                                presentation.buildMarkup(response);
                                presentation.loginTierDisplay(response);
                                presentation.loader.hide();
                                $('#loadermb').hide();
                                $('article.offer-box').show();
                            },
                            error: function (xhr, ajaxCall) {
                                if (xhr.status !== 0) {
                                    presentation.loader.show();
                                    aa.salesJourneyApp.helpers.checkErrorsResponse(ajaxCall);
                                }
                            }

                        }).fail(function (ajaxCall) {
                            if (ajaxCall.statusText !== 'abort') {
                                aa.salesJourneyApp.helpers.checkErrorsResponse(ajaxCall);
                            }
                        });
                    },

                    //ajax call on change of category checkboxes
                    postDataService: function (dto) {
                        $('#loadermb').show();
                        $('article.offer-box').hide();
                        $.ajax({
                            method: "POST",
                            data: {
                                Category: dto
                            },
                            url: "/api/sitecore/MemberBenefits/GetOffersListByCategory",
                            crossDomain: true,
                            success: function (response) {
                                presentation.buildMarkup(response);
                                // presentation.loginTierDisplay(response);
                                presentation.loader.hide();
                                $('#loadermb').hide();
                                $('article.offer-box').show();

                            },
                            error: function (xhr, ajaxCall) {
                                if (xhr.status !== 0) {
                                    presentation.loader.show();
                                    // console.log("GetOffersListByCategory method error");
                                    aa.salesJourneyApp.helpers.checkErrorsResponse(ajaxCall);
                                }
                            }
                        }).fail(function (ajaxCall) {
                            if (ajaxCall.statusText !== 'abort') {
                                aa.salesJourneyApp.helpers.checkErrorsResponse(ajaxCall);
                            }
                        });
                    }
                },
                events = {
                    onLoad: function () {
                        onLoad = true;
                        // cache template markup
                        resultOfferCategoryTilesTemplate = $resultsOfferCategoryContainer.html();
                        resultOfferTierContainerTierTemplate = $resultOfferTierContainer.html();
                        resultListOffersTilesTemplate = $resultListOffersContainer.html();
                        mobileResultOfferCategoryTilesTemplate = $mobileResultsOfferCategoryContainer.html();
                        // presentation.loader.show();

                        // populate results
                        actions.callService();

                    },
                };

            //Load events on page load
            events.onLoad();
        });

        window.aa.helpers.cache.cachedElements.$window.on({

            //on screen resize  and load adjust height and div elements
            resize: function () {
                //for mobile view
                if (window.aa.helpers.cache.cachedElements.$window.width() < window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                    $('#site-footer').css('padding-bottom', $('.booking-widgets').height());//MEM-1
                    /*start MEM-99*/
                    if ($('.detail-header.top-margin-fix').length) {

                        //  $('.mobile-view-append').appendTo('.mobile-view-text-align');
                        $('.row-with-sidebar').addClass('mem-ben-margin');
                    }
                    /*end MEM-99*/

                }
                else if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.TABLET_LANDSCAPE) {
                    $('#site-footer').css('padding-bottom', $('.booking-widgets').height());//MEM-1
                    //  $('.mobile-view-append').appendTo('.prepend-div');//MEM-99
                }
                else {
                    $('#site-footer').css('padding-bottom', '0px');
                }

                if ($(".mb-equalHeight").length) {
                    $('.offers-row').each(categoryOffer);//offer boxes height
                }


            },
            load: function () {

                if ($(".mb-equalHeight").length) {
                    $('.offers-row').each(categoryOffer);//offer boxes height
                }

                /*start MEM-99*/
                if (window.aa.helpers.cache.cachedElements.$window.width() < window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {

                    if ($('.detail-header.top-margin-fix').length) {

                        //  $('.mobile-view-append').appendTo('.mobile-view-text-align');
                        $('.row-with-sidebar').addClass('mem-ben-margin');
                    }

                }
                /*end MEM-99*/


                //Modal open for Offer dynamic listing page.
                $(".mobile-btn-view .filter-link").on('click', function () {
                    $("#mobilefilter").modal('show');
                });
            },
            scroll: function () {
                /*MEM-126 start*/

                function stickyLoader() {
                    var total = $('.all-offers').outerHeight(),
                        scrolltop = window.aa.helpers.cache.cachedElements.$window.scrollTop(),
                        $spinningloader = $('#members-benefits-area #loadermb.mbLoader .loading');

                    if ($('.offers-sidebar').css('display') == 'none') {
                        scrolltop = window.aa.helpers.cache.cachedElements.$window.scrollTop() + 170;
                    } else {
                        scrolltop = window.aa.helpers.cache.cachedElements.$window.scrollTop()
                    }

                    if ((scrolltop === 0 || scrolltop < 99)) {
                        $spinningloader.css('position', '');
                        $spinningloader.css({ 'top': '158px', 'left': '50%' });
                    }
                    else if (scrolltop > 100) {
                        $spinningloader.css('position', 'fixed');
                        if (scrolltop > total) {
                            $spinningloader.css('top', '-999px');
                        } else if ((window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && window.aa.helpers.cache.cachedElements.$window.width() < window.aa.helpers.cache.constants.TABLET_LANDSCAPE)) {
                            $spinningloader.css({ 'top': '45%' });
                        } else if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
                            $spinningloader.css({ 'top': '80%', 'left': '40%' });
                        } else if (window.aa.helpers.cache.cachedElements.$window.width() >= window.aa.helpers.cache.constants.TABLET_LANDSCAPE) {
                            $spinningloader.css({ 'top': '60%', 'left': '64%' });
                        } else {
                            $spinningloader.css({ 'top': '60%', 'left': '64%' });
                        }

                    }

                }

                stickyLoader();
            }
            /*MEM-126 end*/
        });
    }
});
///#source 1 1 /Assets/scripts/libs/owl.carousel.js
/**
 * Owl Carousel v2.3.4
 * Copyright 2013-2018 David Deutsch
 * Licensed under: SEE LICENSE IN https://github.com/OwlCarousel2/OwlCarousel2/blob/master/LICENSE
 */
/**
 * Owl carousel
 * @version 2.3.4
 * @author Bartosz Wojciechowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 * @todo Lazy Load Icon
 * @todo prevent animationend bubling
 * @todo itemsScaleUp
 * @todo Test Zepto
 * @todo stagePadding calculate wrong active classes
 */
;(function($, window, document, undefined) {

	/**
	 * Creates a carousel.
	 * @class The Owl Carousel.
	 * @public
	 * @param {HTMLElement|jQuery} element - The element to create the carousel for.
	 * @param {Object} [options] - The options
	 */
	function Owl(element, options) {

		/**
		 * Current settings for the carousel.
		 * @public
		 */
		this.settings = null;

		/**
		 * Current options set by the caller including defaults.
		 * @public
		 */
		this.options = $.extend({}, Owl.Defaults, options);

		/**
		 * Plugin element.
		 * @public
		 */
		this.$element = $(element);

		/**
		 * Proxied event handlers.
		 * @protected
		 */
		this._handlers = {};

		/**
		 * References to the running plugins of this carousel.
		 * @protected
		 */
		this._plugins = {};

		/**
		 * Currently suppressed events to prevent them from being retriggered.
		 * @protected
		 */
		this._supress = {};

		/**
		 * Absolute current position.
		 * @protected
		 */
		this._current = null;

		/**
		 * Animation speed in milliseconds.
		 * @protected
		 */
		this._speed = null;

		/**
		 * Coordinates of all items in pixel.
		 * @todo The name of this member is missleading.
		 * @protected
		 */
		this._coordinates = [];

		/**
		 * Current breakpoint.
		 * @todo Real media queries would be nice.
		 * @protected
		 */
		this._breakpoint = null;

		/**
		 * Current width of the plugin element.
		 */
		this._width = null;

		/**
		 * All real items.
		 * @protected
		 */
		this._items = [];

		/**
		 * All cloned items.
		 * @protected
		 */
		this._clones = [];

		/**
		 * Merge values of all items.
		 * @todo Maybe this could be part of a plugin.
		 * @protected
		 */
		this._mergers = [];

		/**
		 * Widths of all items.
		 */
		this._widths = [];

		/**
		 * Invalidated parts within the update process.
		 * @protected
		 */
		this._invalidated = {};

		/**
		 * Ordered list of workers for the update process.
		 * @protected
		 */
		this._pipe = [];

		/**
		 * Current state information for the drag operation.
		 * @todo #261
		 * @protected
		 */
		this._drag = {
			time: null,
			target: null,
			pointer: null,
			stage: {
				start: null,
				current: null
			},
			direction: null
		};

		/**
		 * Current state information and their tags.
		 * @type {Object}
		 * @protected
		 */
		this._states = {
			current: {},
			tags: {
				'initializing': [ 'busy' ],
				'animating': [ 'busy' ],
				'dragging': [ 'interacting' ]
			}
		};

		$.each([ 'onResize', 'onThrottledResize' ], $.proxy(function(i, handler) {
			this._handlers[handler] = $.proxy(this[handler], this);
		}, this));

		$.each(Owl.Plugins, $.proxy(function(key, plugin) {
			this._plugins[key.charAt(0).toLowerCase() + key.slice(1)]
				= new plugin(this);
		}, this));

		$.each(Owl.Workers, $.proxy(function(priority, worker) {
			this._pipe.push({
				'filter': worker.filter,
				'run': $.proxy(worker.run, this)
			});
		}, this));

		this.setup();
		this.initialize();
	}

	/**
	 * Default options for the carousel.
	 * @public
	 */
	Owl.Defaults = {
		items: 3,
		loop: false,
		center: false,
		rewind: false,
		checkVisibility: true,

		mouseDrag: true,
		touchDrag: true,
		pullDrag: true,
		freeDrag: false,

		margin: 0,
		stagePadding: 0,

		merge: false,
		mergeFit: true,
		autoWidth: false,

		startPosition: 0,
		rtl: false,

		smartSpeed: 250,
		fluidSpeed: false,
		dragEndSpeed: false,

		responsive: {},
		responsiveRefreshRate: 200,
		responsiveBaseElement: window,

		fallbackEasing: 'swing',
		slideTransition: '',

		info: false,

		nestedItemSelector: false,
		itemElement: 'div',
		stageElement: 'div',

		refreshClass: 'owl-refresh',
		loadedClass: 'owl-loaded',
		loadingClass: 'owl-loading',
		rtlClass: 'owl-rtl',
		responsiveClass: 'owl-responsive',
		dragClass: 'owl-drag',
		itemClass: 'owl-item',
		stageClass: 'owl-stage',
		stageOuterClass: 'owl-stage-outer',
		grabClass: 'owl-grab'
	};

	/**
	 * Enumeration for width.
	 * @public
	 * @readonly
	 * @enum {String}
	 */
	Owl.Width = {
		Default: 'default',
		Inner: 'inner',
		Outer: 'outer'
	};

	/**
	 * Enumeration for types.
	 * @public
	 * @readonly
	 * @enum {String}
	 */
	Owl.Type = {
		Event: 'event',
		State: 'state'
	};

	/**
	 * Contains all registered plugins.
	 * @public
	 */
	Owl.Plugins = {};

	/**
	 * List of workers involved in the update process.
	 */
	Owl.Workers = [ {
		filter: [ 'width', 'settings' ],
		run: function() {
			this._width = this.$element.width();
		}
	}, {
		filter: [ 'width', 'items', 'settings' ],
		run: function(cache) {
			cache.current = this._items && this._items[this.relative(this._current)];
		}
	}, {
		filter: [ 'items', 'settings' ],
		run: function() {
			this.$stage.children('.cloned').remove();
		}
	}, {
		filter: [ 'width', 'items', 'settings' ],
		run: function(cache) {
			var margin = this.settings.margin || '',
				grid = !this.settings.autoWidth,
				rtl = this.settings.rtl,
				css = {
					'width': 'auto',
					'margin-left': rtl ? margin : '',
					'margin-right': rtl ? '' : margin
				};

			!grid && this.$stage.children().css(css);

			cache.css = css;
		}
	}, {
		filter: [ 'width', 'items', 'settings' ],
		run: function(cache) {
			var width = (this.width() / this.settings.items).toFixed(3) - this.settings.margin,
				merge = null,
				iterator = this._items.length,
				grid = !this.settings.autoWidth,
				widths = [];

			cache.items = {
				merge: false,
				width: width
			};

			while (iterator--) {
				merge = this._mergers[iterator];
				merge = this.settings.mergeFit && Math.min(merge, this.settings.items) || merge;

				cache.items.merge = merge > 1 || cache.items.merge;

				widths[iterator] = !grid ? this._items[iterator].width() : width * merge;
			}

			this._widths = widths;
		}
	}, {
		filter: [ 'items', 'settings' ],
		run: function() {
			var clones = [],
				items = this._items,
				settings = this.settings,
				// TODO: Should be computed from number of min width items in stage
				view = Math.max(settings.items * 2, 4),
				size = Math.ceil(items.length / 2) * 2,
				repeat = settings.loop && items.length ? settings.rewind ? view : Math.max(view, size) : 0,
				append = '',
				prepend = '';

			repeat /= 2;

			while (repeat > 0) {
				// Switch to only using appended clones
				clones.push(this.normalize(clones.length / 2, true));
				append = append + items[clones[clones.length - 1]][0].outerHTML;
				clones.push(this.normalize(items.length - 1 - (clones.length - 1) / 2, true));
				prepend = items[clones[clones.length - 1]][0].outerHTML + prepend;
				repeat -= 1;
			}

			this._clones = clones;

			$(append).addClass('cloned').appendTo(this.$stage);
			$(prepend).addClass('cloned').prependTo(this.$stage);
		}
	}, {
		filter: [ 'width', 'items', 'settings' ],
		run: function() {
			var rtl = this.settings.rtl ? 1 : -1,
				size = this._clones.length + this._items.length,
				iterator = -1,
				previous = 0,
				current = 0,
				coordinates = [];

			while (++iterator < size) {
				previous = coordinates[iterator - 1] || 0;
				current = this._widths[this.relative(iterator)] + this.settings.margin;
				coordinates.push(previous + current * rtl);
			}

			this._coordinates = coordinates;
		}
	}, {
		filter: [ 'width', 'items', 'settings' ],
		run: function() {
			var padding = this.settings.stagePadding,
				coordinates = this._coordinates,
				css = {
					'width': Math.ceil(Math.abs(coordinates[coordinates.length - 1])) + padding * 2,
					'padding-left': padding || '',
					'padding-right': padding || ''
				};

			this.$stage.css(css);
		}
	}, {
		filter: [ 'width', 'items', 'settings' ],
		run: function(cache) {
			var iterator = this._coordinates.length,
				grid = !this.settings.autoWidth,
				items = this.$stage.children();

			if (grid && cache.items.merge) {
				while (iterator--) {
					cache.css.width = this._widths[this.relative(iterator)];
					items.eq(iterator).css(cache.css);
				}
			} else if (grid) {
				cache.css.width = cache.items.width;
				items.css(cache.css);
			}
		}
	}, {
		filter: [ 'items' ],
		run: function() {
			this._coordinates.length < 1 && this.$stage.removeAttr('style');
		}
	}, {
		filter: [ 'width', 'items', 'settings' ],
		run: function(cache) {
			cache.current = cache.current ? this.$stage.children().index(cache.current) : 0;
			cache.current = Math.max(this.minimum(), Math.min(this.maximum(), cache.current));
			this.reset(cache.current);
		}
	}, {
		filter: [ 'position' ],
		run: function() {
			this.animate(this.coordinates(this._current));
		}
	}, {
		filter: [ 'width', 'position', 'items', 'settings' ],
		run: function() {
			var rtl = this.settings.rtl ? 1 : -1,
				padding = this.settings.stagePadding * 2,
				begin = this.coordinates(this.current()) + padding,
				end = begin + this.width() * rtl,
				inner, outer, matches = [], i, n;

			for (i = 0, n = this._coordinates.length; i < n; i++) {
				inner = this._coordinates[i - 1] || 0;
				outer = Math.abs(this._coordinates[i]) + padding * rtl;

				if ((this.op(inner, '<=', begin) && (this.op(inner, '>', end)))
					|| (this.op(outer, '<', begin) && this.op(outer, '>', end))) {
					matches.push(i);
				}
			}

			this.$stage.children('.active').removeClass('active');
			this.$stage.children(':eq(' + matches.join('), :eq(') + ')').addClass('active');

			this.$stage.children('.center').removeClass('center');
			if (this.settings.center) {
				this.$stage.children().eq(this.current()).addClass('center');
			}
		}
	} ];

	/**
	 * Create the stage DOM element
	 */
	Owl.prototype.initializeStage = function() {
		this.$stage = this.$element.find('.' + this.settings.stageClass);

		// if the stage is already in the DOM, grab it and skip stage initialization
		if (this.$stage.length) {
			return;
		}

		this.$element.addClass(this.options.loadingClass);

		// create stage
		this.$stage = $('<' + this.settings.stageElement + '>', {
			"class": this.settings.stageClass
		}).wrap( $( '<div/>', {
			"class": this.settings.stageOuterClass
		}));

		// append stage
		this.$element.append(this.$stage.parent());
	};

	/**
	 * Create item DOM elements
	 */
	Owl.prototype.initializeItems = function() {
		var $items = this.$element.find('.owl-item');

		// if the items are already in the DOM, grab them and skip item initialization
		if ($items.length) {
			this._items = $items.get().map(function(item) {
				return $(item);
			});

			this._mergers = this._items.map(function() {
				return 1;
			});

			this.refresh();

			return;
		}

		// append content
		this.replace(this.$element.children().not(this.$stage.parent()));

		// check visibility
		if (this.isVisible()) {
			// update view
			this.refresh();
		} else {
			// invalidate width
			this.invalidate('width');
		}

		this.$element
			.removeClass(this.options.loadingClass)
			.addClass(this.options.loadedClass);
	};

	/**
	 * Initializes the carousel.
	 * @protected
	 */
	Owl.prototype.initialize = function() {
		this.enter('initializing');
		this.trigger('initialize');

		this.$element.toggleClass(this.settings.rtlClass, this.settings.rtl);

		if (this.settings.autoWidth && !this.is('pre-loading')) {
			var imgs, nestedSelector, width;
			imgs = this.$element.find('img');
			nestedSelector = this.settings.nestedItemSelector ? '.' + this.settings.nestedItemSelector : undefined;
			width = this.$element.children(nestedSelector).width();

			if (imgs.length && width <= 0) {
				this.preloadAutoWidthImages(imgs);
			}
		}

		this.initializeStage();
		this.initializeItems();

		// register event handlers
		this.registerEventHandlers();

		this.leave('initializing');
		this.trigger('initialized');
	};

	/**
	 * @returns {Boolean} visibility of $element
	 *                    if you know the carousel will always be visible you can set `checkVisibility` to `false` to
	 *                    prevent the expensive browser layout forced reflow the $element.is(':visible') does
	 */
	Owl.prototype.isVisible = function() {
		return this.settings.checkVisibility
			? this.$element.is(':visible')
			: true;
	};

	/**
	 * Setups the current settings.
	 * @todo Remove responsive classes. Why should adaptive designs be brought into IE8?
	 * @todo Support for media queries by using `matchMedia` would be nice.
	 * @public
	 */
	Owl.prototype.setup = function() {
		var viewport = this.viewport(),
			overwrites = this.options.responsive,
			match = -1,
			settings = null;

		if (!overwrites) {
			settings = $.extend({}, this.options);
		} else {
			$.each(overwrites, function(breakpoint) {
				if (breakpoint <= viewport && breakpoint > match) {
					match = Number(breakpoint);
				}
			});

			settings = $.extend({}, this.options, overwrites[match]);
			if (typeof settings.stagePadding === 'function') {
				settings.stagePadding = settings.stagePadding();
			}
			delete settings.responsive;

			// responsive class
			if (settings.responsiveClass) {
				this.$element.attr('class',
					this.$element.attr('class').replace(new RegExp('(' + this.options.responsiveClass + '-)\\S+\\s', 'g'), '$1' + match)
				);
			}
		}

		this.trigger('change', { property: { name: 'settings', value: settings } });
		this._breakpoint = match;
		this.settings = settings;
		this.invalidate('settings');
		this.trigger('changed', { property: { name: 'settings', value: this.settings } });
	};

	/**
	 * Updates option logic if necessery.
	 * @protected
	 */
	Owl.prototype.optionsLogic = function() {
		if (this.settings.autoWidth) {
			this.settings.stagePadding = false;
			this.settings.merge = false;
		}
	};

	/**
	 * Prepares an item before add.
	 * @todo Rename event parameter `content` to `item`.
	 * @protected
	 * @returns {jQuery|HTMLElement} - The item container.
	 */
	Owl.prototype.prepare = function(item) {
		var event = this.trigger('prepare', { content: item });

		if (!event.data) {
			event.data = $('<' + this.settings.itemElement + '/>')
				.addClass(this.options.itemClass).append(item)
		}

		this.trigger('prepared', { content: event.data });

		return event.data;
	};

	/**
	 * Updates the view.
	 * @public
	 */
	Owl.prototype.update = function() {
		var i = 0,
			n = this._pipe.length,
			filter = $.proxy(function(p) { return this[p] }, this._invalidated),
			cache = {};

		while (i < n) {
			if (this._invalidated.all || $.grep(this._pipe[i].filter, filter).length > 0) {
				this._pipe[i].run(cache);
			}
			i++;
		}

		this._invalidated = {};

		!this.is('valid') && this.enter('valid');
	};

	/**
	 * Gets the width of the view.
	 * @public
	 * @param {Owl.Width} [dimension=Owl.Width.Default] - The dimension to return.
	 * @returns {Number} - The width of the view in pixel.
	 */
	Owl.prototype.width = function(dimension) {
		dimension = dimension || Owl.Width.Default;
		switch (dimension) {
			case Owl.Width.Inner:
			case Owl.Width.Outer:
				return this._width;
			default:
				return this._width - this.settings.stagePadding * 2 + this.settings.margin;
		}
	};

	/**
	 * Refreshes the carousel primarily for adaptive purposes.
	 * @public
	 */
	Owl.prototype.refresh = function() {
		this.enter('refreshing');
		this.trigger('refresh');

		this.setup();

		this.optionsLogic();

		this.$element.addClass(this.options.refreshClass);

		this.update();

		this.$element.removeClass(this.options.refreshClass);

		this.leave('refreshing');
		this.trigger('refreshed');
	};

	/**
	 * Checks window `resize` event.
	 * @protected
	 */
	Owl.prototype.onThrottledResize = function() {
		window.clearTimeout(this.resizeTimer);
		this.resizeTimer = window.setTimeout(this._handlers.onResize, this.settings.responsiveRefreshRate);
	};

	/**
	 * Checks window `resize` event.
	 * @protected
	 */
	Owl.prototype.onResize = function() {
		if (!this._items.length) {
			return false;
		}

		if (this._width === this.$element.width()) {
			return false;
		}

		if (!this.isVisible()) {
			return false;
		}

		this.enter('resizing');

		if (this.trigger('resize').isDefaultPrevented()) {
			this.leave('resizing');
			return false;
		}

		this.invalidate('width');

		this.refresh();

		this.leave('resizing');
		this.trigger('resized');
	};

	/**
	 * Registers event handlers.
	 * @todo Check `msPointerEnabled`
	 * @todo #261
	 * @protected
	 */
	Owl.prototype.registerEventHandlers = function() {
		if ($.support.transition) {
			this.$stage.on($.support.transition.end + '.owl.core', $.proxy(this.onTransitionEnd, this));
		}

		if (this.settings.responsive !== false) {
			this.on(window, 'resize', this._handlers.onThrottledResize);
		}

		if (this.settings.mouseDrag) {
			this.$element.addClass(this.options.dragClass);
			this.$stage.on('mousedown.owl.core', $.proxy(this.onDragStart, this));
			this.$stage.on('dragstart.owl.core selectstart.owl.core', function() { return false });
		}

		if (this.settings.touchDrag){
			this.$stage.on('touchstart.owl.core', $.proxy(this.onDragStart, this));
			this.$stage.on('touchcancel.owl.core', $.proxy(this.onDragEnd, this));
		}
	};

	/**
	 * Handles `touchstart` and `mousedown` events.
	 * @todo Horizontal swipe threshold as option
	 * @todo #261
	 * @protected
	 * @param {Event} event - The event arguments.
	 */
	Owl.prototype.onDragStart = function(event) {
		var stage = null;

		if (event.which === 3) {
			return;
		}

		if ($.support.transform) {
			stage = this.$stage.css('transform').replace(/.*\(|\)| /g, '').split(',');
			stage = {
				x: stage[stage.length === 16 ? 12 : 4],
				y: stage[stage.length === 16 ? 13 : 5]
			};
		} else {
			stage = this.$stage.position();
			stage = {
				x: this.settings.rtl ?
					stage.left + this.$stage.width() - this.width() + this.settings.margin :
					stage.left,
				y: stage.top
			};
		}

		if (this.is('animating')) {
			$.support.transform ? this.animate(stage.x) : this.$stage.stop()
			this.invalidate('position');
		}

		this.$element.toggleClass(this.options.grabClass, event.type === 'mousedown');

		this.speed(0);

		this._drag.time = new Date().getTime();
		this._drag.target = $(event.target);
		this._drag.stage.start = stage;
		this._drag.stage.current = stage;
		this._drag.pointer = this.pointer(event);

		$(document).on('mouseup.owl.core touchend.owl.core', $.proxy(this.onDragEnd, this));

		$(document).one('mousemove.owl.core touchmove.owl.core', $.proxy(function(event) {
			var delta = this.difference(this._drag.pointer, this.pointer(event));

			$(document).on('mousemove.owl.core touchmove.owl.core', $.proxy(this.onDragMove, this));

			if (Math.abs(delta.x) < Math.abs(delta.y) && this.is('valid')) {
				return;
			}

			event.preventDefault();

			this.enter('dragging');
			this.trigger('drag');
		}, this));
	};

	/**
	 * Handles the `touchmove` and `mousemove` events.
	 * @todo #261
	 * @protected
	 * @param {Event} event - The event arguments.
	 */
	Owl.prototype.onDragMove = function(event) {
		var minimum = null,
			maximum = null,
			pull = null,
			delta = this.difference(this._drag.pointer, this.pointer(event)),
			stage = this.difference(this._drag.stage.start, delta);

		if (!this.is('dragging')) {
			return;
		}

		event.preventDefault();

		if (this.settings.loop) {
			minimum = this.coordinates(this.minimum());
			maximum = this.coordinates(this.maximum() + 1) - minimum;
			stage.x = (((stage.x - minimum) % maximum + maximum) % maximum) + minimum;
		} else {
			minimum = this.settings.rtl ? this.coordinates(this.maximum()) : this.coordinates(this.minimum());
			maximum = this.settings.rtl ? this.coordinates(this.minimum()) : this.coordinates(this.maximum());
			pull = this.settings.pullDrag ? -1 * delta.x / 5 : 0;
			stage.x = Math.max(Math.min(stage.x, minimum + pull), maximum + pull);
		}

		this._drag.stage.current = stage;

		this.animate(stage.x);
	};

	/**
	 * Handles the `touchend` and `mouseup` events.
	 * @todo #261
	 * @todo Threshold for click event
	 * @protected
	 * @param {Event} event - The event arguments.
	 */
	Owl.prototype.onDragEnd = function(event) {
		var delta = this.difference(this._drag.pointer, this.pointer(event)),
			stage = this._drag.stage.current,
			direction = delta.x > 0 ^ this.settings.rtl ? 'left' : 'right';

		$(document).off('.owl.core');

		this.$element.removeClass(this.options.grabClass);

		if (delta.x !== 0 && this.is('dragging') || !this.is('valid')) {
			this.speed(this.settings.dragEndSpeed || this.settings.smartSpeed);
			this.current(this.closest(stage.x, delta.x !== 0 ? direction : this._drag.direction));
			this.invalidate('position');
			this.update();

			this._drag.direction = direction;

			if (Math.abs(delta.x) > 3 || new Date().getTime() - this._drag.time > 300) {
				this._drag.target.one('click.owl.core', function() { return false; });
			}
		}

		if (!this.is('dragging')) {
			return;
		}

		this.leave('dragging');
		this.trigger('dragged');
	};

	/**
	 * Gets absolute position of the closest item for a coordinate.
	 * @todo Setting `freeDrag` makes `closest` not reusable. See #165.
	 * @protected
	 * @param {Number} coordinate - The coordinate in pixel.
	 * @param {String} direction - The direction to check for the closest item. Ether `left` or `right`.
	 * @return {Number} - The absolute position of the closest item.
	 */
	Owl.prototype.closest = function(coordinate, direction) {
		var position = -1,
			pull = 30,
			width = this.width(),
			coordinates = this.coordinates();

		if (!this.settings.freeDrag) {
			// check closest item
			$.each(coordinates, $.proxy(function(index, value) {
				// on a left pull, check on current index
				if (direction === 'left' && coordinate > value - pull && coordinate < value + pull) {
					position = index;
				// on a right pull, check on previous index
				// to do so, subtract width from value and set position = index + 1
				} else if (direction === 'right' && coordinate > value - width - pull && coordinate < value - width + pull) {
					position = index + 1;
				} else if (this.op(coordinate, '<', value)
					&& this.op(coordinate, '>', coordinates[index + 1] !== undefined ? coordinates[index + 1] : value - width)) {
					position = direction === 'left' ? index + 1 : index;
				}
				return position === -1;
			}, this));
		}

		if (!this.settings.loop) {
			// non loop boundries
			if (this.op(coordinate, '>', coordinates[this.minimum()])) {
				position = coordinate = this.minimum();
			} else if (this.op(coordinate, '<', coordinates[this.maximum()])) {
				position = coordinate = this.maximum();
			}
		}

		return position;
	};

	/**
	 * Animates the stage.
	 * @todo #270
	 * @public
	 * @param {Number} coordinate - The coordinate in pixels.
	 */
	Owl.prototype.animate = function(coordinate) {
		var animate = this.speed() > 0;

		this.is('animating') && this.onTransitionEnd();

		if (animate) {
			this.enter('animating');
			this.trigger('translate');
		}

		if ($.support.transform3d && $.support.transition) {
			this.$stage.css({
				transform: 'translate3d(' + coordinate + 'px,0px,0px)',
				transition: (this.speed() / 1000) + 's' + (
					this.settings.slideTransition ? ' ' + this.settings.slideTransition : ''
				)
			});
		} else if (animate) {
			this.$stage.animate({
				left: coordinate + 'px'
			}, this.speed(), this.settings.fallbackEasing, $.proxy(this.onTransitionEnd, this));
		} else {
			this.$stage.css({
				left: coordinate + 'px'
			});
		}
	};

	/**
	 * Checks whether the carousel is in a specific state or not.
	 * @param {String} state - The state to check.
	 * @returns {Boolean} - The flag which indicates if the carousel is busy.
	 */
	Owl.prototype.is = function(state) {
		return this._states.current[state] && this._states.current[state] > 0;
	};

	/**
	 * Sets the absolute position of the current item.
	 * @public
	 * @param {Number} [position] - The new absolute position or nothing to leave it unchanged.
	 * @returns {Number} - The absolute position of the current item.
	 */
	Owl.prototype.current = function(position) {
		if (position === undefined) {
			return this._current;
		}

		if (this._items.length === 0) {
			return undefined;
		}

		position = this.normalize(position);

		if (this._current !== position) {
			var event = this.trigger('change', { property: { name: 'position', value: position } });

			if (event.data !== undefined) {
				position = this.normalize(event.data);
			}

			this._current = position;

			this.invalidate('position');

			this.trigger('changed', { property: { name: 'position', value: this._current } });
		}

		return this._current;
	};

	/**
	 * Invalidates the given part of the update routine.
	 * @param {String} [part] - The part to invalidate.
	 * @returns {Array.<String>} - The invalidated parts.
	 */
	Owl.prototype.invalidate = function(part) {
		if ($.type(part) === 'string') {
			this._invalidated[part] = true;
			this.is('valid') && this.leave('valid');
		}
		return $.map(this._invalidated, function(v, i) { return i });
	};

	/**
	 * Resets the absolute position of the current item.
	 * @public
	 * @param {Number} position - The absolute position of the new item.
	 */
	Owl.prototype.reset = function(position) {
		position = this.normalize(position);

		if (position === undefined) {
			return;
		}

		this._speed = 0;
		this._current = position;

		this.suppress([ 'translate', 'translated' ]);

		this.animate(this.coordinates(position));

		this.release([ 'translate', 'translated' ]);
	};

	/**
	 * Normalizes an absolute or a relative position of an item.
	 * @public
	 * @param {Number} position - The absolute or relative position to normalize.
	 * @param {Boolean} [relative=false] - Whether the given position is relative or not.
	 * @returns {Number} - The normalized position.
	 */
	Owl.prototype.normalize = function(position, relative) {
		var n = this._items.length,
			m = relative ? 0 : this._clones.length;

		if (!this.isNumeric(position) || n < 1) {
			position = undefined;
		} else if (position < 0 || position >= n + m) {
			position = ((position - m / 2) % n + n) % n + m / 2;
		}

		return position;
	};

	/**
	 * Converts an absolute position of an item into a relative one.
	 * @public
	 * @param {Number} position - The absolute position to convert.
	 * @returns {Number} - The converted position.
	 */
	Owl.prototype.relative = function(position) {
		position -= this._clones.length / 2;
		return this.normalize(position, true);
	};

	/**
	 * Gets the maximum position for the current item.
	 * @public
	 * @param {Boolean} [relative=false] - Whether to return an absolute position or a relative position.
	 * @returns {Number}
	 */
	Owl.prototype.maximum = function(relative) {
		var settings = this.settings,
			maximum = this._coordinates.length,
			iterator,
			reciprocalItemsWidth,
			elementWidth;

		if (settings.loop) {
			maximum = this._clones.length / 2 + this._items.length - 1;
		} else if (settings.autoWidth || settings.merge) {
			iterator = this._items.length;
			if (iterator) {
				reciprocalItemsWidth = this._items[--iterator].width();
				elementWidth = this.$element.width();
				while (iterator--) {
					reciprocalItemsWidth += this._items[iterator].width() + this.settings.margin;
					if (reciprocalItemsWidth > elementWidth) {
						break;
					}
				}
			}
			maximum = iterator + 1;
		} else if (settings.center) {
			maximum = this._items.length - 1;
		} else {
			maximum = this._items.length - settings.items;
		}

		if (relative) {
			maximum -= this._clones.length / 2;
		}

		return Math.max(maximum, 0);
	};

	/**
	 * Gets the minimum position for the current item.
	 * @public
	 * @param {Boolean} [relative=false] - Whether to return an absolute position or a relative position.
	 * @returns {Number}
	 */
	Owl.prototype.minimum = function(relative) {
		return relative ? 0 : this._clones.length / 2;
	};

	/**
	 * Gets an item at the specified relative position.
	 * @public
	 * @param {Number} [position] - The relative position of the item.
	 * @return {jQuery|Array.<jQuery>} - The item at the given position or all items if no position was given.
	 */
	Owl.prototype.items = function(position) {
		if (position === undefined) {
			return this._items.slice();
		}

		position = this.normalize(position, true);
		return this._items[position];
	};

	/**
	 * Gets an item at the specified relative position.
	 * @public
	 * @param {Number} [position] - The relative position of the item.
	 * @return {jQuery|Array.<jQuery>} - The item at the given position or all items if no position was given.
	 */
	Owl.prototype.mergers = function(position) {
		if (position === undefined) {
			return this._mergers.slice();
		}

		position = this.normalize(position, true);
		return this._mergers[position];
	};

	/**
	 * Gets the absolute positions of clones for an item.
	 * @public
	 * @param {Number} [position] - The relative position of the item.
	 * @returns {Array.<Number>} - The absolute positions of clones for the item or all if no position was given.
	 */
	Owl.prototype.clones = function(position) {
		var odd = this._clones.length / 2,
			even = odd + this._items.length,
			map = function(index) { return index % 2 === 0 ? even + index / 2 : odd - (index + 1) / 2 };

		if (position === undefined) {
			return $.map(this._clones, function(v, i) { return map(i) });
		}

		return $.map(this._clones, function(v, i) { return v === position ? map(i) : null });
	};

	/**
	 * Sets the current animation speed.
	 * @public
	 * @param {Number} [speed] - The animation speed in milliseconds or nothing to leave it unchanged.
	 * @returns {Number} - The current animation speed in milliseconds.
	 */
	Owl.prototype.speed = function(speed) {
		if (speed !== undefined) {
			this._speed = speed;
		}

		return this._speed;
	};

	/**
	 * Gets the coordinate of an item.
	 * @todo The name of this method is missleanding.
	 * @public
	 * @param {Number} position - The absolute position of the item within `minimum()` and `maximum()`.
	 * @returns {Number|Array.<Number>} - The coordinate of the item in pixel or all coordinates.
	 */
	Owl.prototype.coordinates = function(position) {
		var multiplier = 1,
			newPosition = position - 1,
			coordinate;

		if (position === undefined) {
			return $.map(this._coordinates, $.proxy(function(coordinate, index) {
				return this.coordinates(index);
			}, this));
		}

		if (this.settings.center) {
			if (this.settings.rtl) {
				multiplier = -1;
				newPosition = position + 1;
			}

			coordinate = this._coordinates[position];
			coordinate += (this.width() - coordinate + (this._coordinates[newPosition] || 0)) / 2 * multiplier;
		} else {
			coordinate = this._coordinates[newPosition] || 0;
		}

		coordinate = Math.ceil(coordinate);

		return coordinate;
	};

	/**
	 * Calculates the speed for a translation.
	 * @protected
	 * @param {Number} from - The absolute position of the start item.
	 * @param {Number} to - The absolute position of the target item.
	 * @param {Number} [factor=undefined] - The time factor in milliseconds.
	 * @returns {Number} - The time in milliseconds for the translation.
	 */
	Owl.prototype.duration = function(from, to, factor) {
		if (factor === 0) {
			return 0;
		}

		return Math.min(Math.max(Math.abs(to - from), 1), 6) * Math.abs((factor || this.settings.smartSpeed));
	};

	/**
	 * Slides to the specified item.
	 * @public
	 * @param {Number} position - The position of the item.
	 * @param {Number} [speed] - The time in milliseconds for the transition.
	 */
	Owl.prototype.to = function(position, speed) {
		var current = this.current(),
			revert = null,
			distance = position - this.relative(current),
			direction = (distance > 0) - (distance < 0),
			items = this._items.length,
			minimum = this.minimum(),
			maximum = this.maximum();

		if (this.settings.loop) {
			if (!this.settings.rewind && Math.abs(distance) > items / 2) {
				distance += direction * -1 * items;
			}

			position = current + distance;
			revert = ((position - minimum) % items + items) % items + minimum;

			if (revert !== position && revert - distance <= maximum && revert - distance > 0) {
				current = revert - distance;
				position = revert;
				this.reset(current);
			}
		} else if (this.settings.rewind) {
			maximum += 1;
			position = (position % maximum + maximum) % maximum;
		} else {
			position = Math.max(minimum, Math.min(maximum, position));
		}

		this.speed(this.duration(current, position, speed));
		this.current(position);

		if (this.isVisible()) {
			this.update();
		}
	};

	/**
	 * Slides to the next item.
	 * @public
	 * @param {Number} [speed] - The time in milliseconds for the transition.
	 */
	Owl.prototype.next = function(speed) {
		speed = speed || false;
		this.to(this.relative(this.current()) + 1, speed);
	};

	/**
	 * Slides to the previous item.
	 * @public
	 * @param {Number} [speed] - The time in milliseconds for the transition.
	 */
	Owl.prototype.prev = function(speed) {
		speed = speed || false;
		this.to(this.relative(this.current()) - 1, speed);
	};

	/**
	 * Handles the end of an animation.
	 * @protected
	 * @param {Event} event - The event arguments.
	 */
	Owl.prototype.onTransitionEnd = function(event) {

		// if css2 animation then event object is undefined
		if (event !== undefined) {
			event.stopPropagation();

			// Catch only owl-stage transitionEnd event
			if ((event.target || event.srcElement || event.originalTarget) !== this.$stage.get(0)) {
				return false;
			}
		}

		this.leave('animating');
		this.trigger('translated');
	};

	/**
	 * Gets viewport width.
	 * @protected
	 * @return {Number} - The width in pixel.
	 */
	Owl.prototype.viewport = function() {
		var width;
		if (this.options.responsiveBaseElement !== window) {
			width = $(this.options.responsiveBaseElement).width();
		} else if (window.innerWidth) {
			width = window.innerWidth;
		} else if (document.documentElement && document.documentElement.clientWidth) {
			width = document.documentElement.clientWidth;
		} else {
			console.warn('Can not detect viewport width.');
		}
		return width;
	};

	/**
	 * Replaces the current content.
	 * @public
	 * @param {HTMLElement|jQuery|String} content - The new content.
	 */
	Owl.prototype.replace = function(content) {
		this.$stage.empty();
		this._items = [];

		if (content) {
			content = (content instanceof jQuery) ? content : $(content);
		}

		if (this.settings.nestedItemSelector) {
			content = content.find('.' + this.settings.nestedItemSelector);
		}

		content.filter(function() {
			return this.nodeType === 1;
		}).each($.proxy(function(index, item) {
			item = this.prepare(item);
			this.$stage.append(item);
			this._items.push(item);
			this._mergers.push(item.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1 || 1);
		}, this));

		this.reset(this.isNumeric(this.settings.startPosition) ? this.settings.startPosition : 0);

		this.invalidate('items');
	};

	/**
	 * Adds an item.
	 * @todo Use `item` instead of `content` for the event arguments.
	 * @public
	 * @param {HTMLElement|jQuery|String} content - The item content to add.
	 * @param {Number} [position] - The relative position at which to insert the item otherwise the item will be added to the end.
	 */
	Owl.prototype.add = function(content, position) {
		var current = this.relative(this._current);

		position = position === undefined ? this._items.length : this.normalize(position, true);
		content = content instanceof jQuery ? content : $(content);

		this.trigger('add', { content: content, position: position });

		content = this.prepare(content);

		if (this._items.length === 0 || position === this._items.length) {
			this._items.length === 0 && this.$stage.append(content);
			this._items.length !== 0 && this._items[position - 1].after(content);
			this._items.push(content);
			this._mergers.push(content.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1 || 1);
		} else {
			this._items[position].before(content);
			this._items.splice(position, 0, content);
			this._mergers.splice(position, 0, content.find('[data-merge]').addBack('[data-merge]').attr('data-merge') * 1 || 1);
		}

		this._items[current] && this.reset(this._items[current].index());

		this.invalidate('items');

		this.trigger('added', { content: content, position: position });
	};

	/**
	 * Removes an item by its position.
	 * @todo Use `item` instead of `content` for the event arguments.
	 * @public
	 * @param {Number} position - The relative position of the item to remove.
	 */
	Owl.prototype.remove = function(position) {
		position = this.normalize(position, true);

		if (position === undefined) {
			return;
		}

		this.trigger('remove', { content: this._items[position], position: position });

		this._items[position].remove();
		this._items.splice(position, 1);
		this._mergers.splice(position, 1);

		this.invalidate('items');

		this.trigger('removed', { content: null, position: position });
	};

	/**
	 * Preloads images with auto width.
	 * @todo Replace by a more generic approach
	 * @protected
	 */
	Owl.prototype.preloadAutoWidthImages = function(images) {
		images.each($.proxy(function(i, element) {
			this.enter('pre-loading');
			element = $(element);
			$(new Image()).one('load', $.proxy(function(e) {
				element.attr('src', e.target.src);
				element.css('opacity', 1);
				this.leave('pre-loading');
				!this.is('pre-loading') && !this.is('initializing') && this.refresh();
			}, this)).attr('src', element.attr('src') || element.attr('data-src') || element.attr('data-src-retina'));
		}, this));
	};

	/**
	 * Destroys the carousel.
	 * @public
	 */
	Owl.prototype.destroy = function() {

		this.$element.off('.owl.core');
		this.$stage.off('.owl.core');
		$(document).off('.owl.core');

		if (this.settings.responsive !== false) {
			window.clearTimeout(this.resizeTimer);
			this.off(window, 'resize', this._handlers.onThrottledResize);
		}

		for (var i in this._plugins) {
			this._plugins[i].destroy();
		}

		this.$stage.children('.cloned').remove();

		this.$stage.unwrap();
		this.$stage.children().contents().unwrap();
		this.$stage.children().unwrap();
		this.$stage.remove();
		this.$element
			.removeClass(this.options.refreshClass)
			.removeClass(this.options.loadingClass)
			.removeClass(this.options.loadedClass)
			.removeClass(this.options.rtlClass)
			.removeClass(this.options.dragClass)
			.removeClass(this.options.grabClass)
			.attr('class', this.$element.attr('class').replace(new RegExp(this.options.responsiveClass + '-\\S+\\s', 'g'), ''))
			.removeData('owl.carousel');
	};

	/**
	 * Operators to calculate right-to-left and left-to-right.
	 * @protected
	 * @param {Number} [a] - The left side operand.
	 * @param {String} [o] - The operator.
	 * @param {Number} [b] - The right side operand.
	 */
	Owl.prototype.op = function(a, o, b) {
		var rtl = this.settings.rtl;
		switch (o) {
			case '<':
				return rtl ? a > b : a < b;
			case '>':
				return rtl ? a < b : a > b;
			case '>=':
				return rtl ? a <= b : a >= b;
			case '<=':
				return rtl ? a >= b : a <= b;
			default:
				break;
		}
	};

	/**
	 * Attaches to an internal event.
	 * @protected
	 * @param {HTMLElement} element - The event source.
	 * @param {String} event - The event name.
	 * @param {Function} listener - The event handler to attach.
	 * @param {Boolean} capture - Wether the event should be handled at the capturing phase or not.
	 */
	Owl.prototype.on = function(element, event, listener, capture) {
		if (element.addEventListener) {
			element.addEventListener(event, listener, capture);
		} else if (element.attachEvent) {
			element.attachEvent('on' + event, listener);
		}
	};

	/**
	 * Detaches from an internal event.
	 * @protected
	 * @param {HTMLElement} element - The event source.
	 * @param {String} event - The event name.
	 * @param {Function} listener - The attached event handler to detach.
	 * @param {Boolean} capture - Wether the attached event handler was registered as a capturing listener or not.
	 */
	Owl.prototype.off = function(element, event, listener, capture) {
		if (element.removeEventListener) {
			element.removeEventListener(event, listener, capture);
		} else if (element.detachEvent) {
			element.detachEvent('on' + event, listener);
		}
	};

	/**
	 * Triggers a public event.
	 * @todo Remove `status`, `relatedTarget` should be used instead.
	 * @protected
	 * @param {String} name - The event name.
	 * @param {*} [data=null] - The event data.
	 * @param {String} [namespace=carousel] - The event namespace.
	 * @param {String} [state] - The state which is associated with the event.
	 * @param {Boolean} [enter=false] - Indicates if the call enters the specified state or not.
	 * @returns {Event} - The event arguments.
	 */
	Owl.prototype.trigger = function(name, data, namespace, state, enter) {
		var status = {
			item: { count: this._items.length, index: this.current() }
		}, handler = $.camelCase(
			$.grep([ 'on', name, namespace ], function(v) { return v })
				.join('-').toLowerCase()
		), event = $.Event(
			[ name, 'owl', namespace || 'carousel' ].join('.').toLowerCase(),
			$.extend({ relatedTarget: this }, status, data)
		);

		if (!this._supress[name]) {
			$.each(this._plugins, function(name, plugin) {
				if (plugin.onTrigger) {
					plugin.onTrigger(event);
				}
			});

			this.register({ type: Owl.Type.Event, name: name });
			this.$element.trigger(event);

			if (this.settings && typeof this.settings[handler] === 'function') {
				this.settings[handler].call(this, event);
			}
		}

		return event;
	};

	/**
	 * Enters a state.
	 * @param name - The state name.
	 */
	Owl.prototype.enter = function(name) {
		$.each([ name ].concat(this._states.tags[name] || []), $.proxy(function(i, name) {
			if (this._states.current[name] === undefined) {
				this._states.current[name] = 0;
			}

			this._states.current[name]++;
		}, this));
	};

	/**
	 * Leaves a state.
	 * @param name - The state name.
	 */
	Owl.prototype.leave = function(name) {
		$.each([ name ].concat(this._states.tags[name] || []), $.proxy(function(i, name) {
			this._states.current[name]--;
		}, this));
	};

	/**
	 * Registers an event or state.
	 * @public
	 * @param {Object} object - The event or state to register.
	 */
	Owl.prototype.register = function(object) {
		if (object.type === Owl.Type.Event) {
			if (!$.event.special[object.name]) {
				$.event.special[object.name] = {};
			}

			if (!$.event.special[object.name].owl) {
				var _default = $.event.special[object.name]._default;
				$.event.special[object.name]._default = function(e) {
					if (_default && _default.apply && (!e.namespace || e.namespace.indexOf('owl') === -1)) {
						return _default.apply(this, arguments);
					}
					return e.namespace && e.namespace.indexOf('owl') > -1;
				};
				$.event.special[object.name].owl = true;
			}
		} else if (object.type === Owl.Type.State) {
			if (!this._states.tags[object.name]) {
				this._states.tags[object.name] = object.tags;
			} else {
				this._states.tags[object.name] = this._states.tags[object.name].concat(object.tags);
			}

			this._states.tags[object.name] = $.grep(this._states.tags[object.name], $.proxy(function(tag, i) {
				return $.inArray(tag, this._states.tags[object.name]) === i;
			}, this));
		}
	};

	/**
	 * Suppresses events.
	 * @protected
	 * @param {Array.<String>} events - The events to suppress.
	 */
	Owl.prototype.suppress = function(events) {
		$.each(events, $.proxy(function(index, event) {
			this._supress[event] = true;
		}, this));
	};

	/**
	 * Releases suppressed events.
	 * @protected
	 * @param {Array.<String>} events - The events to release.
	 */
	Owl.prototype.release = function(events) {
		$.each(events, $.proxy(function(index, event) {
			delete this._supress[event];
		}, this));
	};

	/**
	 * Gets unified pointer coordinates from event.
	 * @todo #261
	 * @protected
	 * @param {Event} - The `mousedown` or `touchstart` event.
	 * @returns {Object} - Contains `x` and `y` coordinates of current pointer position.
	 */
	Owl.prototype.pointer = function(event) {
		var result = { x: null, y: null };

		event = event.originalEvent || event || window.event;

		event = event.touches && event.touches.length ?
			event.touches[0] : event.changedTouches && event.changedTouches.length ?
				event.changedTouches[0] : event;

		if (event.pageX) {
			result.x = event.pageX;
			result.y = event.pageY;
		} else {
			result.x = event.clientX;
			result.y = event.clientY;
		}

		return result;
	};

	/**
	 * Determines if the input is a Number or something that can be coerced to a Number
	 * @protected
	 * @param {Number|String|Object|Array|Boolean|RegExp|Function|Symbol} - The input to be tested
	 * @returns {Boolean} - An indication if the input is a Number or can be coerced to a Number
	 */
	Owl.prototype.isNumeric = function(number) {
		return !isNaN(parseFloat(number));
	};

	/**
	 * Gets the difference of two vectors.
	 * @todo #261
	 * @protected
	 * @param {Object} - The first vector.
	 * @param {Object} - The second vector.
	 * @returns {Object} - The difference.
	 */
	Owl.prototype.difference = function(first, second) {
		return {
			x: first.x - second.x,
			y: first.y - second.y
		};
	};

	/**
	 * The jQuery Plugin for the Owl Carousel
	 * @todo Navigation plugin `next` and `prev`
	 * @public
	 */
	$.fn.owlCarousel = function(option) {
		var args = Array.prototype.slice.call(arguments, 1);

		return this.each(function() {
			var $this = $(this),
				data = $this.data('owl.carousel');

			if (!data) {
				data = new Owl(this, typeof option == 'object' && option);
				$this.data('owl.carousel', data);

				$.each([
					'next', 'prev', 'to', 'destroy', 'refresh', 'replace', 'add', 'remove'
				], function(i, event) {
					data.register({ type: Owl.Type.Event, name: event });
					data.$element.on(event + '.owl.carousel.core', $.proxy(function(e) {
						if (e.namespace && e.relatedTarget !== this) {
							this.suppress([ event ]);
							data[event].apply(this, [].slice.call(arguments, 1));
							this.release([ event ]);
						}
					}, data));
				});
			}

			if (typeof option == 'string' && option.charAt(0) !== '_') {
				data[option].apply(data, args);
			}
		});
	};

	/**
	 * The constructor for the jQuery Plugin
	 * @public
	 */
	$.fn.owlCarousel.Constructor = Owl;

})(window.Zepto || window.jQuery, window, document);

/**
 * AutoRefresh Plugin
 * @version 2.3.4
 * @author Artus Kolanowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
;(function($, window, document, undefined) {

	/**
	 * Creates the auto refresh plugin.
	 * @class The Auto Refresh Plugin
	 * @param {Owl} carousel - The Owl Carousel
	 */
	var AutoRefresh = function(carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
		this._core = carousel;

		/**
		 * Refresh interval.
		 * @protected
		 * @type {number}
		 */
		this._interval = null;

		/**
		 * Whether the element is currently visible or not.
		 * @protected
		 * @type {Boolean}
		 */
		this._visible = null;

		/**
		 * All event handlers.
		 * @protected
		 * @type {Object}
		 */
		this._handlers = {
			'initialized.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this._core.settings.autoRefresh) {
					this.watch();
				}
			}, this)
		};

		// set default options
		this._core.options = $.extend({}, AutoRefresh.Defaults, this._core.options);

		// register event handlers
		this._core.$element.on(this._handlers);
	};

	/**
	 * Default options.
	 * @public
	 */
	AutoRefresh.Defaults = {
		autoRefresh: true,
		autoRefreshInterval: 500
	};

	/**
	 * Watches the element.
	 */
	AutoRefresh.prototype.watch = function() {
		if (this._interval) {
			return;
		}

		this._visible = this._core.isVisible();
		this._interval = window.setInterval($.proxy(this.refresh, this), this._core.settings.autoRefreshInterval);
	};

	/**
	 * Refreshes the element.
	 */
	AutoRefresh.prototype.refresh = function() {
		if (this._core.isVisible() === this._visible) {
			return;
		}

		this._visible = !this._visible;

		this._core.$element.toggleClass('owl-hidden', !this._visible);

		this._visible && (this._core.invalidate('width') && this._core.refresh());
	};

	/**
	 * Destroys the plugin.
	 */
	AutoRefresh.prototype.destroy = function() {
		var handler, property;

		window.clearInterval(this._interval);

		for (handler in this._handlers) {
			this._core.$element.off(handler, this._handlers[handler]);
		}
		for (property in Object.getOwnPropertyNames(this)) {
			typeof this[property] != 'function' && (this[property] = null);
		}
	};

	$.fn.owlCarousel.Constructor.Plugins.AutoRefresh = AutoRefresh;

})(window.Zepto || window.jQuery, window, document);

/**
 * Lazy Plugin
 * @version 2.3.4
 * @author Bartosz Wojciechowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
;(function($, window, document, undefined) {

	/**
	 * Creates the lazy plugin.
	 * @class The Lazy Plugin
	 * @param {Owl} carousel - The Owl Carousel
	 */
	var Lazy = function(carousel) {

		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
		this._core = carousel;

		/**
		 * Already loaded items.
		 * @protected
		 * @type {Array.<jQuery>}
		 */
		this._loaded = [];

		/**
		 * Event handlers.
		 * @protected
		 * @type {Object}
		 */
		this._handlers = {
			'initialized.owl.carousel change.owl.carousel resized.owl.carousel': $.proxy(function(e) {
				if (!e.namespace) {
					return;
				}

				if (!this._core.settings || !this._core.settings.lazyLoad) {
					return;
				}

				if ((e.property && e.property.name == 'position') || e.type == 'initialized') {
					var settings = this._core.settings,
						n = (settings.center && Math.ceil(settings.items / 2) || settings.items),
						i = ((settings.center && n * -1) || 0),
						position = (e.property && e.property.value !== undefined ? e.property.value : this._core.current()) + i,
						clones = this._core.clones().length,
						load = $.proxy(function(i, v) { this.load(v) }, this);
					//TODO: Need documentation for this new option
					if (settings.lazyLoadEager > 0) {
						n += settings.lazyLoadEager;
						// If the carousel is looping also preload images that are to the "left"
						if (settings.loop) {
              position -= settings.lazyLoadEager;
              n++;
            }
					}

					while (i++ < n) {
						this.load(clones / 2 + this._core.relative(position));
						clones && $.each(this._core.clones(this._core.relative(position)), load);
						position++;
					}
				}
			}, this)
		};

		// set the default options
		this._core.options = $.extend({}, Lazy.Defaults, this._core.options);

		// register event handler
		this._core.$element.on(this._handlers);
	};

	/**
	 * Default options.
	 * @public
	 */
	Lazy.Defaults = {
		lazyLoad: false,
		lazyLoadEager: 0
	};

	/**
	 * Loads all resources of an item at the specified position.
	 * @param {Number} position - The absolute position of the item.
	 * @protected
	 */
	Lazy.prototype.load = function(position) {
		var $item = this._core.$stage.children().eq(position),
			$elements = $item && $item.find('.owl-lazy');

		if (!$elements || $.inArray($item.get(0), this._loaded) > -1) {
			return;
		}

		$elements.each($.proxy(function(index, element) {
			var $element = $(element), image,
                url = (window.devicePixelRatio > 1 && $element.attr('data-src-retina')) || $element.attr('data-src') || $element.attr('data-srcset');

			this._core.trigger('load', { element: $element, url: url }, 'lazy');

			if ($element.is('img')) {
				$element.one('load.owl.lazy', $.proxy(function() {
					$element.css('opacity', 1);
					this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
				}, this)).attr('src', url);
            } else if ($element.is('source')) {
                $element.one('load.owl.lazy', $.proxy(function() {
                    this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
                }, this)).attr('srcset', url);
			} else {
				image = new Image();
				image.onload = $.proxy(function() {
					$element.css({
						'background-image': 'url("' + url + '")',
						'opacity': '1'
					});
					this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
				}, this);
				image.src = url;
			}
		}, this));

		this._loaded.push($item.get(0));
	};

	/**
	 * Destroys the plugin.
	 * @public
	 */
	Lazy.prototype.destroy = function() {
		var handler, property;

		for (handler in this.handlers) {
			this._core.$element.off(handler, this.handlers[handler]);
		}
		for (property in Object.getOwnPropertyNames(this)) {
			typeof this[property] != 'function' && (this[property] = null);
		}
	};

	$.fn.owlCarousel.Constructor.Plugins.Lazy = Lazy;

})(window.Zepto || window.jQuery, window, document);

/**
 * AutoHeight Plugin
 * @version 2.3.4
 * @author Bartosz Wojciechowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
;(function($, window, document, undefined) {

	/**
	 * Creates the auto height plugin.
	 * @class The Auto Height Plugin
	 * @param {Owl} carousel - The Owl Carousel
	 */
	var AutoHeight = function(carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
		this._core = carousel;

		this._previousHeight = null;

		/**
		 * All event handlers.
		 * @protected
		 * @type {Object}
		 */
		this._handlers = {
			'initialized.owl.carousel refreshed.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this._core.settings.autoHeight) {
					this.update();
				}
			}, this),
			'changed.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this._core.settings.autoHeight && e.property.name === 'position'){
					this.update();
				}
			}, this),
			'loaded.owl.lazy': $.proxy(function(e) {
				if (e.namespace && this._core.settings.autoHeight
					&& e.element.closest('.' + this._core.settings.itemClass).index() === this._core.current()) {
					this.update();
				}
			}, this)
		};

		// set default options
		this._core.options = $.extend({}, AutoHeight.Defaults, this._core.options);

		// register event handlers
		this._core.$element.on(this._handlers);
		this._intervalId = null;
		var refThis = this;

		// These changes have been taken from a PR by gavrochelegnou proposed in #1575
		// and have been made compatible with the latest jQuery version
		$(window).on('load', function() {
			if (refThis._core.settings.autoHeight) {
				refThis.update();
			}
		});

		// Autoresize the height of the carousel when window is resized
		// When carousel has images, the height is dependent on the width
		// and should also change on resize
		$(window).resize(function() {
			if (refThis._core.settings.autoHeight) {
				if (refThis._intervalId != null) {
					clearTimeout(refThis._intervalId);
				}

				refThis._intervalId = setTimeout(function() {
					refThis.update();
				}, 250);
			}
		});

	};

	/**
	 * Default options.
	 * @public
	 */
	AutoHeight.Defaults = {
		autoHeight: false,
		autoHeightClass: 'owl-height'
	};

	/**
	 * Updates the view.
	 */
	AutoHeight.prototype.update = function() {
		var start = this._core._current,
			end = start + this._core.settings.items,
			lazyLoadEnabled = this._core.settings.lazyLoad,
			visible = this._core.$stage.children().toArray().slice(start, end),
			heights = [],
			maxheight = 0;

		$.each(visible, function(index, item) {
			heights.push($(item).height());
		});

		maxheight = Math.max.apply(null, heights);

		if (maxheight <= 1 && lazyLoadEnabled && this._previousHeight) {
			maxheight = this._previousHeight;
		}

		this._previousHeight = maxheight;

		this._core.$stage.parent()
			.height(maxheight)
			.addClass(this._core.settings.autoHeightClass);
	};

	AutoHeight.prototype.destroy = function() {
		var handler, property;

		for (handler in this._handlers) {
			this._core.$element.off(handler, this._handlers[handler]);
		}
		for (property in Object.getOwnPropertyNames(this)) {
			typeof this[property] !== 'function' && (this[property] = null);
		}
	};

	$.fn.owlCarousel.Constructor.Plugins.AutoHeight = AutoHeight;

})(window.Zepto || window.jQuery, window, document);

/**
 * Video Plugin
 * @version 2.3.4
 * @author Bartosz Wojciechowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
;(function($, window, document, undefined) {

	/**
	 * Creates the video plugin.
	 * @class The Video Plugin
	 * @param {Owl} carousel - The Owl Carousel
	 */
	var Video = function(carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
		this._core = carousel;

		/**
		 * Cache all video URLs.
		 * @protected
		 * @type {Object}
		 */
		this._videos = {};

		/**
		 * Current playing item.
		 * @protected
		 * @type {jQuery}
		 */
		this._playing = null;

		/**
		 * All event handlers.
		 * @todo The cloned content removale is too late
		 * @protected
		 * @type {Object}
		 */
		this._handlers = {
			'initialized.owl.carousel': $.proxy(function(e) {
				if (e.namespace) {
					this._core.register({ type: 'state', name: 'playing', tags: [ 'interacting' ] });
				}
			}, this),
			'resize.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this._core.settings.video && this.isInFullScreen()) {
					e.preventDefault();
				}
			}, this),
			'refreshed.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this._core.is('resizing')) {
					this._core.$stage.find('.cloned .owl-video-frame').remove();
				}
			}, this),
			'changed.owl.carousel': $.proxy(function(e) {
				if (e.namespace && e.property.name === 'position' && this._playing) {
					this.stop();
				}
			}, this),
			'prepared.owl.carousel': $.proxy(function(e) {
				if (!e.namespace) {
					return;
				}

				var $element = $(e.content).find('.owl-video');

				if ($element.length) {
					$element.css('display', 'none');
					this.fetch($element, $(e.content));
				}
			}, this)
		};

		// set default options
		this._core.options = $.extend({}, Video.Defaults, this._core.options);

		// register event handlers
		this._core.$element.on(this._handlers);

		this._core.$element.on('click.owl.video', '.owl-video-play-icon', $.proxy(function(e) {
			this.play(e);
		}, this));
	};

	/**
	 * Default options.
	 * @public
	 */
	Video.Defaults = {
		video: false,
		videoHeight: false,
		videoWidth: false
	};

	/**
	 * Gets the video ID and the type (YouTube/Vimeo/vzaar only).
	 * @protected
	 * @param {jQuery} target - The target containing the video data.
	 * @param {jQuery} item - The item containing the video.
	 */
	Video.prototype.fetch = function(target, item) {
			var type = (function() {
					if (target.attr('data-vimeo-id')) {
						return 'vimeo';
					} else if (target.attr('data-vzaar-id')) {
						return 'vzaar'
					} else {
						return 'youtube';
					}
				})(),
				id = target.attr('data-vimeo-id') || target.attr('data-youtube-id') || target.attr('data-vzaar-id'),
				width = target.attr('data-width') || this._core.settings.videoWidth,
				height = target.attr('data-height') || this._core.settings.videoHeight,
				url = target.attr('href');

		if (url) {

			/*
					Parses the id's out of the following urls (and probably more):
					https://www.youtube.com/watch?v=:id
					https://youtu.be/:id
					https://vimeo.com/:id
					https://vimeo.com/channels/:channel/:id
					https://vimeo.com/groups/:group/videos/:id
					https://app.vzaar.com/videos/:id

					Visual example: https://regexper.com/#(http%3A%7Chttps%3A%7C)%5C%2F%5C%2F(player.%7Cwww.%7Capp.)%3F(vimeo%5C.com%7Cyoutu(be%5C.com%7C%5C.be%7Cbe%5C.googleapis%5C.com)%7Cvzaar%5C.com)%5C%2F(video%5C%2F%7Cvideos%5C%2F%7Cembed%5C%2F%7Cchannels%5C%2F.%2B%5C%2F%7Cgroups%5C%2F.%2B%5C%2F%7Cwatch%5C%3Fv%3D%7Cv%5C%2F)%3F(%5BA-Za-z0-9._%25-%5D*)(%5C%26%5CS%2B)%3F
			*/

			id = url.match(/(http:|https:|)\/\/(player.|www.|app.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com|be\-nocookie\.com)|vzaar\.com)\/(video\/|videos\/|embed\/|channels\/.+\/|groups\/.+\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);

			if (id[3].indexOf('youtu') > -1) {
				type = 'youtube';
			} else if (id[3].indexOf('vimeo') > -1) {
				type = 'vimeo';
			} else if (id[3].indexOf('vzaar') > -1) {
				type = 'vzaar';
			} else {
				throw new Error('Video URL not supported.');
			}
			id = id[6];
		} else {
			throw new Error('Missing video URL.');
		}

		this._videos[url] = {
			type: type,
			id: id,
			width: width,
			height: height
		};

		item.attr('data-video', url);

		this.thumbnail(target, this._videos[url]);
	};

	/**
	 * Creates video thumbnail.
	 * @protected
	 * @param {jQuery} target - The target containing the video data.
	 * @param {Object} info - The video info object.
	 * @see `fetch`
	 */
	Video.prototype.thumbnail = function(target, video) {
		var tnLink,
			icon,
			path,
			dimensions = video.width && video.height ? 'width:' + video.width + 'px;height:' + video.height + 'px;' : '',
			customTn = target.find('img'),
			srcType = 'src',
			lazyClass = '',
			settings = this._core.settings,
			create = function(path) {
				icon = '<div class="owl-video-play-icon"></div>';

				if (settings.lazyLoad) {
					tnLink = $('<div/>',{
						"class": 'owl-video-tn ' + lazyClass,
						"srcType": path
					});
				} else {
					tnLink = $( '<div/>', {
						"class": "owl-video-tn",
						"style": 'opacity:1;background-image:url(' + path + ')'
					});
				}
				target.after(tnLink);
				target.after(icon);
			};

		// wrap video content into owl-video-wrapper div
		target.wrap( $( '<div/>', {
			"class": "owl-video-wrapper",
			"style": dimensions
		}));

		if (this._core.settings.lazyLoad) {
			srcType = 'data-src';
			lazyClass = 'owl-lazy';
		}

		// custom thumbnail
		if (customTn.length) {
			create(customTn.attr(srcType));
			customTn.remove();
			return false;
		}

		if (video.type === 'youtube') {
			path = "//img.youtube.com/vi/" + video.id + "/hqdefault.jpg";
			create(path);
		} else if (video.type === 'vimeo') {
			$.ajax({
				type: 'GET',
				url: '//vimeo.com/api/v2/video/' + video.id + '.json',
				jsonp: 'callback',
				dataType: 'jsonp',
				success: function(data) {
					path = data[0].thumbnail_large;
					create(path);
				}
			});
		} else if (video.type === 'vzaar') {
			$.ajax({
				type: 'GET',
				url: '//vzaar.com/api/videos/' + video.id + '.json',
				jsonp: 'callback',
				dataType: 'jsonp',
				success: function(data) {
					path = data.framegrab_url;
					create(path);
				}
			});
		}
	};

	/**
	 * Stops the current video.
	 * @public
	 */
	Video.prototype.stop = function() {
		this._core.trigger('stop', null, 'video');
		this._playing.find('.owl-video-frame').remove();
		this._playing.removeClass('owl-video-playing');
		this._playing = null;
		this._core.leave('playing');
		this._core.trigger('stopped', null, 'video');
	};

	/**
	 * Starts the current video.
	 * @public
	 * @param {Event} event - The event arguments.
	 */
	Video.prototype.play = function(event) {
		var target = $(event.target),
			item = target.closest('.' + this._core.settings.itemClass),
			video = this._videos[item.attr('data-video')],
			width = video.width || '100%',
			height = video.height || this._core.$stage.height(),
			html,
			iframe;

		if (this._playing) {
			return;
		}

		this._core.enter('playing');
		this._core.trigger('play', null, 'video');

		item = this._core.items(this._core.relative(item.index()));

		this._core.reset(item.index());

		html = $( '<iframe frameborder="0" allowfullscreen mozallowfullscreen webkitAllowFullScreen ></iframe>' );
		html.attr( 'height', height );
		html.attr( 'width', width );
		if (video.type === 'youtube') {
			html.attr( 'src', '//www.youtube.com/embed/' + video.id + '?autoplay=1&rel=0&v=' + video.id );
		} else if (video.type === 'vimeo') {
			html.attr( 'src', '//player.vimeo.com/video/' + video.id + '?autoplay=1' );
		} else if (video.type === 'vzaar') {
			html.attr( 'src', '//view.vzaar.com/' + video.id + '/player?autoplay=true' );
		}

		iframe = $(html).wrap( '<div class="owl-video-frame" />' ).insertAfter(item.find('.owl-video'));

		this._playing = item.addClass('owl-video-playing');
	};

	/**
	 * Checks whether an video is currently in full screen mode or not.
	 * @todo Bad style because looks like a readonly method but changes members.
	 * @protected
	 * @returns {Boolean}
	 */
	Video.prototype.isInFullScreen = function() {
		var element = document.fullscreenElement || document.mozFullScreenElement ||
				document.webkitFullscreenElement;

		return element && $(element).parent().hasClass('owl-video-frame');
	};

	/**
	 * Destroys the plugin.
	 */
	Video.prototype.destroy = function() {
		var handler, property;

		this._core.$element.off('click.owl.video');

		for (handler in this._handlers) {
			this._core.$element.off(handler, this._handlers[handler]);
		}
		for (property in Object.getOwnPropertyNames(this)) {
			typeof this[property] != 'function' && (this[property] = null);
		}
	};

	$.fn.owlCarousel.Constructor.Plugins.Video = Video;

})(window.Zepto || window.jQuery, window, document);

/**
 * Animate Plugin
 * @version 2.3.4
 * @author Bartosz Wojciechowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
;(function($, window, document, undefined) {

	/**
	 * Creates the animate plugin.
	 * @class The Navigation Plugin
	 * @param {Owl} scope - The Owl Carousel
	 */
	var Animate = function(scope) {
		this.core = scope;
		this.core.options = $.extend({}, Animate.Defaults, this.core.options);
		this.swapping = true;
		this.previous = undefined;
		this.next = undefined;

		this.handlers = {
			'change.owl.carousel': $.proxy(function(e) {
				if (e.namespace && e.property.name == 'position') {
					this.previous = this.core.current();
					this.next = e.property.value;
				}
			}, this),
			'drag.owl.carousel dragged.owl.carousel translated.owl.carousel': $.proxy(function(e) {
				if (e.namespace) {
					this.swapping = e.type == 'translated';
				}
			}, this),
			'translate.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this.swapping && (this.core.options.animateOut || this.core.options.animateIn)) {
					this.swap();
				}
			}, this)
		};

		this.core.$element.on(this.handlers);
	};

	/**
	 * Default options.
	 * @public
	 */
	Animate.Defaults = {
		animateOut: false,
		animateIn: false
	};

	/**
	 * Toggles the animation classes whenever an translations starts.
	 * @protected
	 * @returns {Boolean|undefined}
	 */
	Animate.prototype.swap = function() {

		if (this.core.settings.items !== 1) {
			return;
		}

		if (!$.support.animation || !$.support.transition) {
			return;
		}

		this.core.speed(0);

		var left,
			clear = $.proxy(this.clear, this),
			previous = this.core.$stage.children().eq(this.previous),
			next = this.core.$stage.children().eq(this.next),
			incoming = this.core.settings.animateIn,
			outgoing = this.core.settings.animateOut;

		if (this.core.current() === this.previous) {
			return;
		}

		if (outgoing) {
			left = this.core.coordinates(this.previous) - this.core.coordinates(this.next);
			previous.one($.support.animation.end, clear)
				.css( { 'left': left + 'px' } )
				.addClass('animated owl-animated-out')
				.addClass(outgoing);
		}

		if (incoming) {
			next.one($.support.animation.end, clear)
				.addClass('animated owl-animated-in')
				.addClass(incoming);
		}
	};

	Animate.prototype.clear = function(e) {
		$(e.target).css( { 'left': '' } )
			.removeClass('animated owl-animated-out owl-animated-in')
			.removeClass(this.core.settings.animateIn)
			.removeClass(this.core.settings.animateOut);
		this.core.onTransitionEnd();
	};

	/**
	 * Destroys the plugin.
	 * @public
	 */
	Animate.prototype.destroy = function() {
		var handler, property;

		for (handler in this.handlers) {
			this.core.$element.off(handler, this.handlers[handler]);
		}
		for (property in Object.getOwnPropertyNames(this)) {
			typeof this[property] != 'function' && (this[property] = null);
		}
	};

	$.fn.owlCarousel.Constructor.Plugins.Animate = Animate;

})(window.Zepto || window.jQuery, window, document);

/**
 * Autoplay Plugin
 * @version 2.3.4
 * @author Bartosz Wojciechowski
 * @author Artus Kolanowski
 * @author David Deutsch
 * @author Tom De Caluwé
 * @license The MIT License (MIT)
 */
;(function($, window, document, undefined) {

	/**
	 * Creates the autoplay plugin.
	 * @class The Autoplay Plugin
	 * @param {Owl} scope - The Owl Carousel
	 */
	var Autoplay = function(carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
		this._core = carousel;

		/**
		 * The autoplay timeout id.
		 * @type {Number}
		 */
		this._call = null;

		/**
		 * Depending on the state of the plugin, this variable contains either
		 * the start time of the timer or the current timer value if it's
		 * paused. Since we start in a paused state we initialize the timer
		 * value.
		 * @type {Number}
		 */
		this._time = 0;

		/**
		 * Stores the timeout currently used.
		 * @type {Number}
		 */
		this._timeout = 0;

		/**
		 * Indicates whenever the autoplay is paused.
		 * @type {Boolean}
		 */
		this._paused = true;

		/**
		 * All event handlers.
		 * @protected
		 * @type {Object}
		 */
		this._handlers = {
			'changed.owl.carousel': $.proxy(function(e) {
				if (e.namespace && e.property.name === 'settings') {
					if (this._core.settings.autoplay) {
						this.play();
					} else {
						this.stop();
					}
				} else if (e.namespace && e.property.name === 'position' && this._paused) {
					// Reset the timer. This code is triggered when the position
					// of the carousel was changed through user interaction.
					this._time = 0;
				}
			}, this),
			'initialized.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this._core.settings.autoplay) {
					this.play();
				}
			}, this),
			'play.owl.autoplay': $.proxy(function(e, t, s) {
				if (e.namespace) {
					this.play(t, s);
				}
			}, this),
			'stop.owl.autoplay': $.proxy(function(e) {
				if (e.namespace) {
					this.stop();
				}
			}, this),
			'mouseover.owl.autoplay': $.proxy(function() {
				if (this._core.settings.autoplayHoverPause && this._core.is('rotating')) {
					this.pause();
				}
			}, this),
			'mouseleave.owl.autoplay': $.proxy(function() {
				if (this._core.settings.autoplayHoverPause && this._core.is('rotating')) {
					this.play();
				}
			}, this),
			'touchstart.owl.core': $.proxy(function() {
				if (this._core.settings.autoplayHoverPause && this._core.is('rotating')) {
					this.pause();
				}
			}, this),
			'touchend.owl.core': $.proxy(function() {
				if (this._core.settings.autoplayHoverPause) {
					this.play();
				}
			}, this)
		};

		// register event handlers
		this._core.$element.on(this._handlers);

		// set default options
		this._core.options = $.extend({}, Autoplay.Defaults, this._core.options);
	};

	/**
	 * Default options.
	 * @public
	 */
	Autoplay.Defaults = {
		autoplay: false,
		autoplayTimeout: 5000,
		autoplayHoverPause: false,
		autoplaySpeed: false
	};

	/**
	 * Transition to the next slide and set a timeout for the next transition.
	 * @private
	 * @param {Number} [speed] - The animation speed for the animations.
	 */
	Autoplay.prototype._next = function(speed) {
		this._call = window.setTimeout(
			$.proxy(this._next, this, speed),
			this._timeout * (Math.round(this.read() / this._timeout) + 1) - this.read()
		);

		if (this._core.is('interacting') || document.hidden) {
			return;
		}
		this._core.next(speed || this._core.settings.autoplaySpeed);
	}

	/**
	 * Reads the current timer value when the timer is playing.
	 * @public
	 */
	Autoplay.prototype.read = function() {
		return new Date().getTime() - this._time;
	};

	/**
	 * Starts the autoplay.
	 * @public
	 * @param {Number} [timeout] - The interval before the next animation starts.
	 * @param {Number} [speed] - The animation speed for the animations.
	 */
	Autoplay.prototype.play = function(timeout, speed) {
		var elapsed;

		if (!this._core.is('rotating')) {
			this._core.enter('rotating');
		}

		timeout = timeout || this._core.settings.autoplayTimeout;

		// Calculate the elapsed time since the last transition. If the carousel
		// wasn't playing this calculation will yield zero.
		elapsed = Math.min(this._time % (this._timeout || timeout), timeout);

		if (this._paused) {
			// Start the clock.
			this._time = this.read();
			this._paused = false;
		} else {
			// Clear the active timeout to allow replacement.
			window.clearTimeout(this._call);
		}

		// Adjust the origin of the timer to match the new timeout value.
		this._time += this.read() % timeout - elapsed;

		this._timeout = timeout;
		this._call = window.setTimeout($.proxy(this._next, this, speed), timeout - elapsed);
	};

	/**
	 * Stops the autoplay.
	 * @public
	 */
	Autoplay.prototype.stop = function() {
		if (this._core.is('rotating')) {
			// Reset the clock.
			this._time = 0;
			this._paused = true;

			window.clearTimeout(this._call);
			this._core.leave('rotating');
		}
	};

	/**
	 * Pauses the autoplay.
	 * @public
	 */
	Autoplay.prototype.pause = function() {
		if (this._core.is('rotating') && !this._paused) {
			// Pause the clock.
			this._time = this.read();
			this._paused = true;

			window.clearTimeout(this._call);
		}
	};

	/**
	 * Destroys the plugin.
	 */
	Autoplay.prototype.destroy = function() {
		var handler, property;

		this.stop();

		for (handler in this._handlers) {
			this._core.$element.off(handler, this._handlers[handler]);
		}
		for (property in Object.getOwnPropertyNames(this)) {
			typeof this[property] != 'function' && (this[property] = null);
		}
	};

	$.fn.owlCarousel.Constructor.Plugins.autoplay = Autoplay;

})(window.Zepto || window.jQuery, window, document);

/**
 * Navigation Plugin
 * @version 2.3.4
 * @author Artus Kolanowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
;(function($, window, document, undefined) {
	'use strict';

	/**
	 * Creates the navigation plugin.
	 * @class The Navigation Plugin
	 * @param {Owl} carousel - The Owl Carousel.
	 */
	var Navigation = function(carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
		this._core = carousel;

		/**
		 * Indicates whether the plugin is initialized or not.
		 * @protected
		 * @type {Boolean}
		 */
		this._initialized = false;

		/**
		 * The current paging indexes.
		 * @protected
		 * @type {Array}
		 */
		this._pages = [];

		/**
		 * All DOM elements of the user interface.
		 * @protected
		 * @type {Object}
		 */
		this._controls = {};

		/**
		 * Markup for an indicator.
		 * @protected
		 * @type {Array.<String>}
		 */
		this._templates = [];

		/**
		 * The carousel element.
		 * @type {jQuery}
		 */
		this.$element = this._core.$element;

		/**
		 * Overridden methods of the carousel.
		 * @protected
		 * @type {Object}
		 */
		this._overrides = {
			next: this._core.next,
			prev: this._core.prev,
			to: this._core.to
		};

		/**
		 * All event handlers.
		 * @protected
		 * @type {Object}
		 */
		this._handlers = {
			'prepared.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this._core.settings.dotsData) {
					this._templates.push('<div class="' + this._core.settings.dotClass + '">' +
						$(e.content).find('[data-dot]').addBack('[data-dot]').attr('data-dot') + '</div>');
				}
			}, this),
			'added.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this._core.settings.dotsData) {
					this._templates.splice(e.position, 0, this._templates.pop());
				}
			}, this),
			'remove.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this._core.settings.dotsData) {
					this._templates.splice(e.position, 1);
				}
			}, this),
			'changed.owl.carousel': $.proxy(function(e) {
				if (e.namespace && e.property.name == 'position') {
					this.draw();
				}
			}, this),
			'initialized.owl.carousel': $.proxy(function(e) {
				if (e.namespace && !this._initialized) {
					this._core.trigger('initialize', null, 'navigation');
					this.initialize();
					this.update();
					this.draw();
					this._initialized = true;
					this._core.trigger('initialized', null, 'navigation');
				}
			}, this),
			'refreshed.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this._initialized) {
					this._core.trigger('refresh', null, 'navigation');
					this.update();
					this.draw();
					this._core.trigger('refreshed', null, 'navigation');
				}
			}, this)
		};

		// set default options
		this._core.options = $.extend({}, Navigation.Defaults, this._core.options);

		// register event handlers
		this.$element.on(this._handlers);
	};

	/**
	 * Default options.
	 * @public
	 * @todo Rename `slideBy` to `navBy`
	 */
	Navigation.Defaults = {
		nav: false,
		navText: [
			'<span aria-label="' + 'Previous' + '">&#x2039;</span>',
			'<span aria-label="' + 'Next' + '">&#x203a;</span>'
		],
		navSpeed: false,
		navElement: 'button type="button" role="presentation"',
		navContainer: false,
		navContainerClass: 'owl-nav',
		navClass: [
			'owl-prev',
			'owl-next'
		],
		slideBy: 1,
		dotClass: 'owl-dot',
		dotsClass: 'owl-dots',
		dots: true,
		dotsEach: false,
		dotsData: false,
		dotsSpeed: false,
		dotsContainer: false
	};

	/**
	 * Initializes the layout of the plugin and extends the carousel.
	 * @protected
	 */
	Navigation.prototype.initialize = function() {
		var override,
			settings = this._core.settings;

		// create DOM structure for relative navigation
		this._controls.$relative = (settings.navContainer ? $(settings.navContainer)
			: $('<div>').addClass(settings.navContainerClass).appendTo(this.$element)).addClass('disabled');

		this._controls.$previous = $('<' + settings.navElement + '>')
			.addClass(settings.navClass[0])
			.html(settings.navText[0])
			.prependTo(this._controls.$relative)
			.on('click', $.proxy(function(e) {
				this.prev(settings.navSpeed);
			}, this));
		this._controls.$next = $('<' + settings.navElement + '>')
			.addClass(settings.navClass[1])
			.html(settings.navText[1])
			.appendTo(this._controls.$relative)
			.on('click', $.proxy(function(e) {
				this.next(settings.navSpeed);
			}, this));

		// create DOM structure for absolute navigation
		if (!settings.dotsData) {
			this._templates = [ $('<button role="button">')
				.addClass(settings.dotClass)
				.append($('<span>'))
				.prop('outerHTML') ];
		}

		this._controls.$absolute = (settings.dotsContainer ? $(settings.dotsContainer)
			: $('<div>').addClass(settings.dotsClass).appendTo(this.$element)).addClass('disabled');

		this._controls.$absolute.on('click', 'button', $.proxy(function(e) {
			var index = $(e.target).parent().is(this._controls.$absolute)
				? $(e.target).index() : $(e.target).parent().index();

			e.preventDefault();

			this.to(index, settings.dotsSpeed);
		}, this));

		/*$el.on('focusin', function() {
			$(document).off(".carousel");

			$(document).on('keydown.carousel', function(e) {
				if(e.keyCode == 37) {
					$el.trigger('prev.owl')
				}
				if(e.keyCode == 39) {
					$el.trigger('next.owl')
				}
			});
		});*/

		// override public methods of the carousel
		for (override in this._overrides) {
			this._core[override] = $.proxy(this[override], this);
		}
	};

	/**
	 * Destroys the plugin.
	 * @protected
	 */
	Navigation.prototype.destroy = function() {
		var handler, control, property, override, settings;
		settings = this._core.settings;

		for (handler in this._handlers) {
			this.$element.off(handler, this._handlers[handler]);
		}
		for (control in this._controls) {
			if (control === '$relative' && settings.navContainer) {
				this._controls[control].html('');
			} else {
				this._controls[control].remove();
			}
		}
		for (override in this.overides) {
			this._core[override] = this._overrides[override];
		}
		for (property in Object.getOwnPropertyNames(this)) {
			typeof this[property] != 'function' && (this[property] = null);
		}
	};

	/**
	 * Updates the internal state.
	 * @protected
	 */
	Navigation.prototype.update = function() {
		var i, j, k,
			lower = this._core.clones().length / 2,
			upper = lower + this._core.items().length,
			maximum = this._core.maximum(true),
			settings = this._core.settings,
			size = settings.center || settings.autoWidth || settings.dotsData
				? 1 : settings.dotsEach || settings.items;

		if (settings.slideBy !== 'page') {
			settings.slideBy = Math.min(settings.slideBy, settings.items);
		}

		if (settings.dots || settings.slideBy == 'page') {
			this._pages = [];

			for (i = lower, j = 0, k = 0; i < upper; i++) {
				if (j >= size || j === 0) {
					this._pages.push({
						start: Math.min(maximum, i - lower),
						end: i - lower + size - 1
					});
					if (Math.min(maximum, i - lower) === maximum) {
						break;
					}
					j = 0, ++k;
				}
				j += this._core.mergers(this._core.relative(i));
			}
		}
	};

	/**
	 * Draws the user interface.
	 * @todo The option `dotsData` wont work.
	 * @protected
	 */
	Navigation.prototype.draw = function() {
		var difference,
			settings = this._core.settings,
			disabled = this._core.items().length <= settings.items,
			index = this._core.relative(this._core.current()),
			loop = settings.loop || settings.rewind;

		this._controls.$relative.toggleClass('disabled', !settings.nav || disabled);

		if (settings.nav) {
			this._controls.$previous.toggleClass('disabled', !loop && index <= this._core.minimum(true));
			this._controls.$next.toggleClass('disabled', !loop && index >= this._core.maximum(true));
		}

		this._controls.$absolute.toggleClass('disabled', !settings.dots || disabled);

		if (settings.dots) {
			difference = this._pages.length - this._controls.$absolute.children().length;

			if (settings.dotsData && difference !== 0) {
				this._controls.$absolute.html(this._templates.join(''));
			} else if (difference > 0) {
				this._controls.$absolute.append(new Array(difference + 1).join(this._templates[0]));
			} else if (difference < 0) {
				this._controls.$absolute.children().slice(difference).remove();
			}

			this._controls.$absolute.find('.active').removeClass('active');
			this._controls.$absolute.children().eq($.inArray(this.current(), this._pages)).addClass('active');
		}
	};

	/**
	 * Extends event data.
	 * @protected
	 * @param {Event} event - The event object which gets thrown.
	 */
	Navigation.prototype.onTrigger = function(event) {
		var settings = this._core.settings;

		event.page = {
			index: $.inArray(this.current(), this._pages),
			count: this._pages.length,
			size: settings && (settings.center || settings.autoWidth || settings.dotsData
				? 1 : settings.dotsEach || settings.items)
		};
	};

	/**
	 * Gets the current page position of the carousel.
	 * @protected
	 * @returns {Number}
	 */
	Navigation.prototype.current = function() {
		var current = this._core.relative(this._core.current());
		return $.grep(this._pages, $.proxy(function(page, index) {
			return page.start <= current && page.end >= current;
		}, this)).pop();
	};

	/**
	 * Gets the current succesor/predecessor position.
	 * @protected
	 * @returns {Number}
	 */
	Navigation.prototype.getPosition = function(successor) {
		var position, length,
			settings = this._core.settings;

		if (settings.slideBy == 'page') {
			position = $.inArray(this.current(), this._pages);
			length = this._pages.length;
			successor ? ++position : --position;
			position = this._pages[((position % length) + length) % length].start;
		} else {
			position = this._core.relative(this._core.current());
			length = this._core.items().length;
			successor ? position += settings.slideBy : position -= settings.slideBy;
		}

		return position;
	};

	/**
	 * Slides to the next item or page.
	 * @public
	 * @param {Number} [speed=false] - The time in milliseconds for the transition.
	 */
	Navigation.prototype.next = function(speed) {
		$.proxy(this._overrides.to, this._core)(this.getPosition(true), speed);
	};

	/**
	 * Slides to the previous item or page.
	 * @public
	 * @param {Number} [speed=false] - The time in milliseconds for the transition.
	 */
	Navigation.prototype.prev = function(speed) {
		$.proxy(this._overrides.to, this._core)(this.getPosition(false), speed);
	};

	/**
	 * Slides to the specified item or page.
	 * @public
	 * @param {Number} position - The position of the item or page.
	 * @param {Number} [speed] - The time in milliseconds for the transition.
	 * @param {Boolean} [standard=false] - Whether to use the standard behaviour or not.
	 */
	Navigation.prototype.to = function(position, speed, standard) {
		var length;

		if (!standard && this._pages.length) {
			length = this._pages.length;
			$.proxy(this._overrides.to, this._core)(this._pages[((position % length) + length) % length].start, speed);
		} else {
			$.proxy(this._overrides.to, this._core)(position, speed);
		}
	};

	$.fn.owlCarousel.Constructor.Plugins.Navigation = Navigation;

})(window.Zepto || window.jQuery, window, document);

/**
 * Hash Plugin
 * @version 2.3.4
 * @author Artus Kolanowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
;(function($, window, document, undefined) {
	'use strict';

	/**
	 * Creates the hash plugin.
	 * @class The Hash Plugin
	 * @param {Owl} carousel - The Owl Carousel
	 */
	var Hash = function(carousel) {
		/**
		 * Reference to the core.
		 * @protected
		 * @type {Owl}
		 */
		this._core = carousel;

		/**
		 * Hash index for the items.
		 * @protected
		 * @type {Object}
		 */
		this._hashes = {};

		/**
		 * The carousel element.
		 * @type {jQuery}
		 */
		this.$element = this._core.$element;

		/**
		 * All event handlers.
		 * @protected
		 * @type {Object}
		 */
		this._handlers = {
			'initialized.owl.carousel': $.proxy(function(e) {
				if (e.namespace && this._core.settings.startPosition === 'URLHash') {
					$(window).trigger('hashchange.owl.navigation');
				}
			}, this),
			'prepared.owl.carousel': $.proxy(function(e) {
				if (e.namespace) {
					var hash = $(e.content).find('[data-hash]').addBack('[data-hash]').attr('data-hash');

					if (!hash) {
						return;
					}

					this._hashes[hash] = e.content;
				}
			}, this),
			'changed.owl.carousel': $.proxy(function(e) {
				if (e.namespace && e.property.name === 'position') {
					var current = this._core.items(this._core.relative(this._core.current())),
						hash = $.map(this._hashes, function(item, hash) {
							return item === current ? hash : null;
						}).join();

					if (!hash || window.location.hash.slice(1) === hash) {
						return;
					}

					window.location.hash = hash;
				}
			}, this)
		};

		// set default options
		this._core.options = $.extend({}, Hash.Defaults, this._core.options);

		// register the event handlers
		this.$element.on(this._handlers);

		// register event listener for hash navigation
		$(window).on('hashchange.owl.navigation', $.proxy(function(e) {
			var hash = window.location.hash.substring(1),
				items = this._core.$stage.children(),
				position = this._hashes[hash] && items.index(this._hashes[hash]);

			if (position === undefined || position === this._core.current()) {
				return;
			}

			this._core.to(this._core.relative(position), false, true);
		}, this));
	};

	/**
	 * Default options.
	 * @public
	 */
	Hash.Defaults = {
		URLhashListener: false
	};

	/**
	 * Destroys the plugin.
	 * @public
	 */
	Hash.prototype.destroy = function() {
		var handler, property;

		$(window).off('hashchange.owl.navigation');

		for (handler in this._handlers) {
			this._core.$element.off(handler, this._handlers[handler]);
		}
		for (property in Object.getOwnPropertyNames(this)) {
			typeof this[property] != 'function' && (this[property] = null);
		}
	};

	$.fn.owlCarousel.Constructor.Plugins.Hash = Hash;

})(window.Zepto || window.jQuery, window, document);

/**
 * Support Plugin
 *
 * @version 2.3.4
 * @author Vivid Planet Software GmbH
 * @author Artus Kolanowski
 * @author David Deutsch
 * @license The MIT License (MIT)
 */
;(function($, window, document, undefined) {

	var style = $('<support>').get(0).style,
		prefixes = 'Webkit Moz O ms'.split(' '),
		events = {
			transition: {
				end: {
					WebkitTransition: 'webkitTransitionEnd',
					MozTransition: 'transitionend',
					OTransition: 'oTransitionEnd',
					transition: 'transitionend'
				}
			},
			animation: {
				end: {
					WebkitAnimation: 'webkitAnimationEnd',
					MozAnimation: 'animationend',
					OAnimation: 'oAnimationEnd',
					animation: 'animationend'
				}
			}
		},
		tests = {
			csstransforms: function() {
				return !!test('transform');
			},
			csstransforms3d: function() {
				return !!test('perspective');
			},
			csstransitions: function() {
				return !!test('transition');
			},
			cssanimations: function() {
				return !!test('animation');
			}
		};

	function test(property, prefixed) {
		var result = false,
			upper = property.charAt(0).toUpperCase() + property.slice(1);

		$.each((property + ' ' + prefixes.join(upper + ' ') + upper).split(' '), function(i, property) {
			if (style[property] !== undefined) {
				result = prefixed ? property : true;
				return false;
			}
		});

		return result;
	}

	function prefixed(property) {
		return test(property, true);
	}

	if (tests.csstransitions()) {
		/* jshint -W053 */
		$.support.transition = new String(prefixed('transition'))
		$.support.transition.end = events.transition.end[ $.support.transition ];
	}

	if (tests.cssanimations()) {
		/* jshint -W053 */
		$.support.animation = new String(prefixed('animation'))
		$.support.animation.end = events.animation.end[ $.support.animation ];
	}

	if (tests.csstransforms()) {
		/* jshint -W053 */
		$.support.transform = new String(prefixed('transform'));
		$.support.transform3d = tests.csstransforms3d();
	}

})(window.Zepto || window.jQuery, window, document);

///#source 1 1 /Assets/scripts/digital-breakdown.js
if (window.aa.helpers.cache.cachedElements.$window.width() >= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
   
$('.broken-down-modal-wrap ul li a[href^="tel:"]').parent('li').addClass('nolinkHover');

//close modal on outside click
$(document).mouseup(function(e) 
{
    var container = $(".broken-down-modal-wrap");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        $("#brokenDownModal").modal("hide");
    }
});
}

$(".broken-down-modal-wrap ul li a[href='']").addClass('nolink');
$(".broken-down-modal-wrap ul li a[href='']").parent('li').addClass('nolinkHover');


$('.report-breakdown').click(function () {
    //e.preventDefault();
   // $(this).fadeOut(100);
	//$('.report-breakdown-close').fadeIn(100);
	 
	$('#report-breakdown').fadeOut(150);
	$('#report-breakdown-close-section').fadeIn(150);
	if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT){
		//alert('mobile')
		$('#report-breakdown-close-section').hide();
		$('#report-breakdown').fadeOut(150);
		$('.report-breakdown-close').fadeIn(100);
		
	}
	
	
    $('body').addClass('modal-dark').css('padding-right', '0');
    $('.modal-backdrop.fade.in').addClass('dark');
    $('#brokenDownModal').modal({
      keyboard: false,
	backdrop: 'static'
    })
});
$(".report-btn-wrap button.close-btn").click(function(){
    $("#brokenDownModal").modal("hide");
  });
$('#brokenDownModal').on('shown.bs.modal', function (e) {

});
$('#brokenDownModal').on('hidden.bs.modal', function (e) {
    $('body').removeClass('modal-dark');
   // $('.report-breakdown').fadeIn(100);
	//$('.report-breakdown-close').fadeOut(100);
	$('#report-breakdown').fadeIn(150);
	$('#report-breakdown-close-section').fadeOut(150);
	if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.MOBILE_BREAKPOINT){
		//alert('mobile')
		$('#report-breakdown-close-section').hide();
		$('#report-breakdown').fadeIn(150);
		$('.report-breakdown-close').fadeIn(100);
		
	}

});
///#source 1 1 /Assets/scripts/contenthub.js
$(document).ready(function () {
	//alert('in');

	var mobileToggle = $('#contentHubHeader').find('.ch-mobile-toggle');
	var mobileMenu = $('#contentHubHeader').find('.ch-nav-bar');
	$(mobileToggle).on('click', function () {
		$(mobileMenu).toggle();
		$(this).toggleClass('active');
	});

	if ($('#contentHubHeader').length) {
		$('#site-wrapper').addClass('content-hub-pages');
	}
	//social sharing component
	if ($('.content-hub-pages .article-information').length && window.aa.helpers.cache.cachedElements.$window.width() < window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
		$(window).scroll(function () {
			if ($(window).scrollTop() + $(window).height() == $(document).height()) {
				//console.log('reached bottom with class');
				$('#site-footer').css('padding-bottom', '48px');
			}
		});
	}

	if ($('.content-hub-pages .article-information').length && window.aa.helpers.cache.cachedElements.$window.width() < window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
		$(window).resize(function () {
			if ($(window).scrollTop() + $(window).height() == $(document).height()) {
				$('#site-footer').css('padding-bottom', '48px');
			}
		});
	}


	$('.owl-carousel').owlCarousel({
		loop: true,
		margin: 0,
		nav: true,
		dots: false,
		responsiveClass: true,
		responsive: {
			0: {
				items: 1,

			},
			600: {
				items: 1,

			},
			1000: {
				items: 1,

				loop: false
			}
		}
	});

	function summeryArticles() {

		var $summarybox = $(this).find('.article-box'),
			heights = [];

		$summarybox.css('height', '');

		function setHeights() {
			$summarybox.each(function () {
				heights.push($(this).height());
			});

			$summarybox.height(Math.max.apply(null, heights));
		}

		if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT) {
			setHeights();
		}

		else if (window.aa.helpers.cache.cachedElements.$window.width() > window.aa.helpers.cache.constants.MOBILE_BREAKPOINT && ($boxContent.closest('.article-list-row').length)) {
			setHeights();

		}
	}
	window.aa.helpers.cache.cachedElements.$window.on({

		resize: function () {
			if ($(".article-equal-height").length) {
				$('.article-list-row').each(summeryArticles);//summary boxes height
			}
		},
		load: function () {
			if ($(".article-equal-height").length) {
				$('.article-list-row').each(summeryArticles);//summary boxes height
			}
		}
	});

	PaginationUtil = {
		gridNumber: 0,
		//goToTop: window.scrollTo(0, 0),
		getCurrentItem: function (id, num) {
			PaginationUtil.gridNumber = +num - 1;
			PaginationUtil.goToTop;
			$('.ch-pagination-item').removeClass('active');
			$('.paging-grid').hide();

			var selectedGrid = $("#" + id);
			if ($('.ch-pagination-item').length != 0) {
				$('.ch-pagination-item')[PaginationUtil.gridNumber].className += ' active';
			}
			selectedGrid.show();

			if (PaginationUtil.gridNumber == 0) $('#ch-prev-pagination-btn').addClass("inactive");
			else $('#ch-prev-pagination-btn').removeClass("inactive");//show/enable
			if ($('#'+ id).next().hasClass('paging-grid')) $('#ch-next-pagination-btn').removeClass("inactive");
			else $('#ch-next-pagination-btn').addClass("inactive");
            $(window).trigger('resize');
		},
		next: function () {
			// $('#ch-prev-pagination-btn').show();
			PaginationUtil.gridNumber += 2;
			var id = $('.related-articles > .paging-grid:eq(' + (PaginationUtil.gridNumber-1) + ')').attr('id');
			PaginationUtil.getCurrentItem(id, PaginationUtil.gridNumber);
		},
		prev: function () {
			var idnum = PaginationUtil.gridNumber-1;
			var id = $('.related-articles > .paging-grid:eq(' + idnum + ')').attr('id');
			PaginationUtil.getCurrentItem(id, PaginationUtil.gridNumber);
		},
		init: function () {
			// $('#ch-prev-pagination-btn').hide();
			// $('.related-articles > .paging-grid').first().show();
			var id = $('.related-articles > .paging-grid').first().attr('id');
			PaginationUtil.getCurrentItem(id, 1);
		},
		select: function (event) {
			//console.log($(this).html());
			PaginationUtil.getCurrentItem($(this).data('idnumber'), $(this).html());
		}
	}
	PaginationUtil.init();

	$("#ch-prev-pagination-btn").on('click', PaginationUtil.prev);
	$("#ch-next-pagination-btn").on('click', PaginationUtil.next);
	$(".ch-pagination-item").on('click', PaginationUtil.select);

});
///#source 1 1 /Assets/scripts/lazysizes.min.js
/*! lazysizes - v4.1.1 */
!function (a, b) { var c = b(a, a.document); a.lazySizes = c, "object" == typeof module && module.exports && (module.exports = c) }(window, function (a, b) { "use strict"; if (b.getElementsByClassName) { var c, d, 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("CustomEvent"); return e || (e = {}), e.instance = c, h.initCustomEvent(d, !f, !g, 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 = a === !0) && (g = 33), b || (b = !0, d = e - (f.now() - c), 0 > d && (d = 0), a || 9 > d ? i() : k(i, d)) } }, C = function (a) { var b, c, d = 99, e = function () { b = null, a() }, g = function () { var a = f.now() - c; d > a ? k(g, d - a) : (m || e)(e) }; return function () { c = f.now(), b || (b = k(g, d)) } }; !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]); a.lazySizesConfig = d, k(function () { d.init && F() }) }(); var D = function () { var g, l, m, o, p, y, D, F, G, H, I, J, K, L, M = /^img$/i, N = /^iframe$/i, O = "onscroll" in a && !/(gle|ing)bot/.test(navigator.userAgent), P = 0, Q = 0, R = 0, S = -1, T = function (a) { R-- , a && a.target && u(a.target, T), (!a || 0 > R || !a.target) && (R = 0) }, U = function (a, c) { var d, f = a, g = "hidden" == x(b.body, "visibility") || "hidden" != x(a.parentNode, "visibility") && "hidden" != x(a, "visibility"); for (F -= c, I += c, G -= c, H += c; g && (f = f.offsetParent) && f != b.body && f != e;)g = (x(f, "opacity") || 1) > 0, g && "visible" != x(f, "overflow") && (d = f.getBoundingClientRect(), g = H > d.left && G < d.right && I > d.top - 1 && F < d.bottom + 1); return g }, V = function () { var a, f, h, j, k, m, n, p, q, r = c.elements; if ((o = d.loadMode) && 8 > R && (a = r.length)) { f = 0, S++ , null == K && ("expand" in d || (d.expand = e.clientHeight > 500 && e.clientWidth > 500 ? 500 : 370), J = d.expand, K = J * d.expFactor), K > Q && 1 > R && S > 2 && o > 2 && !b.hidden ? (Q = K, S = 0) : Q = o > 1 && S > 1 && 6 > R ? J : P; for (; a > f; f++)if (r[f] && !r[f]._lazyRace) if (O) if ((p = r[f][i]("data-expand")) && (m = 1 * p) || (m = Q), q !== m && (y = innerWidth + m * L, D = innerHeight + m, n = -1 * m, q = m), h = r[f].getBoundingClientRect(), (I = h.bottom) >= n && (F = h.top) <= D && (H = h.right) >= n * L && (G = h.left) <= y && (I || H || G || F) && (d.loadHidden || "hidden" != x(r[f], "visibility")) && (l && 3 > R && !p && (3 > o || 4 > S) || U(r[f], m))) { if (ba(r[f]), k = !0, R > 9) break } else !k && l && !j && 4 > R && 4 > S && o > 2 && (g[0] || d.preloadAfterLoad) && (g[0] || !p && (I || H || G || F || "auto" != r[f][i](d.sizesAttr))) && (j = g[0] || r[f]); else ba(r[f]); j && !k && ba(j) } }, W = B(V), X = function (a) { s(a.target, d.loadedClass), t(a.target, d.loadingClass), u(a.target, Z), v(a.target, "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, o, p; (o = 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), o = { target: a }, p && (u(a, T, !0), clearTimeout(m), m = k(T, 2500), s(a, d.loadingClass), u(a, Z, !0)), l && q.call(j.getElementsByTagName("source"), _), h ? a.setAttribute("srcset", h) : g && !l && (N.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 () { (!p || a.complete && a.naturalWidth > 1) && (p ? T(o) : R-- , X(o)) }, !0) }), ba = function (a) { var b, c = M.test(a.nodeName), e = c && (a[i](d.sizesAttr) || a[i]("sizes")), f = "auto" == e; (!f && l || !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, R++ , aa(a, b, f, e, c)) }, ca = function () { if (!l) { if (f.now() - p < 999) return void k(ca, 999); var a = C(function () { d.loadMode = 3, W() }); l = !0, d.loadMode = 3, W(), j("scroll", function () { 3 == d.loadMode && (d.loadMode = 2), a() }, !0) } }; return { _: function () { p = f.now(), c.elements = b.getElementsByClassName(d.lazyClass), g = b.getElementsByClassName(d.lazyClass + " " + d.preloadClass), L = d.hFac, j("scroll", W, !0), j("resize", W, !0), 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", "webkitAnimationEnd"].forEach(function (a) { b[h](a, W, !0) }), /d$|^c/.test(b.readyState) ? ca() : (j("load", ca), b[h]("DOMContentLoaded", W), k(ca, 2e4)), c.elements.length ? (V(), z._lsFlush()) : W() }, checkElems: W, unveil: ba } }(), 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; g > f; 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 && d !== a._lazysizesWidth && c(a, f, e, d))) }, f = function () { var b, c = a.length; if (c) for (b = 0; c > b; 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 || (F.i = !0, E._(), D._()) }; return c = { cfg: d, autoSizer: E, loader: D, init: F, uP: w, aC: s, rC: t, hC: r, fire: v, gW: y, rAF: z } } });

///#source 1 1 /Assets/scripts/image-gallery-3.5.js

/* 
 * ---------------------------------------- *
 * Name:    Image Gallery JavaScripts       *
 * Type: 	JavaScript                      *
 * Version: Not Versioned                   *
 * Author:	Codehouse                       *
 * ---------------------------------------- *
 */

(function ($) {

    var lightboxTimer;

    // gallery functionality based on number of images
    function imageGallery() {

        var $thisLightboxGallery = $(this),
            $rowParent = $thisLightboxGallery.closest('.row-with-sidebar'),
            $imagesContainer = $thisLightboxGallery.find('.image-gallery'),
            $lightboxCarousel = $thisLightboxGallery.find('.lightbox-carousel'),
            $lightboxOverlay = $thisLightboxGallery.find('.lightbox-overlay'),
            imageCounter = $imagesContainer.find('.gallery-image').length,
            imageIndex = $lightboxCarousel.find('.active').index(),
            $totalImages = $thisLightboxGallery.find('.counter').find('span'),
            $presentedImageContainer = $thisLightboxGallery.find('.presented-image'),
            galleryActiveClassCounter = imageIndex,
            $scrollArea = $thisLightboxGallery.find('.scroll-bar'),
            $showListOfImages = $thisLightboxGallery.find('.show-list'),
            $showMoreText = $showListOfImages.find('.list'),
            $gallerySlide = $lightboxCarousel.find('.gallery-slide'),
            $filmStrip = $thisLightboxGallery.find('.film-strip'),
            $lightboxControls = $thisLightboxGallery.find('.lightbox-next, .lightbox-prev'),
            $activeGallerySlide,
            filmStripHidden = false,
            dir = {
                next: function () {
                    galleryActiveClassCounter = galleryActiveClassCounter + 1 > imageCounter - 1 ? 0 : galleryActiveClassCounter + 1;
                },
                prev: function () {
                    galleryActiveClassCounter = galleryActiveClassCounter - 1 < 0 ? imageCounter - 1 : galleryActiveClassCounter - 1;
                }
            };

        // toggle film strip
        function toggleCarousel() {
            $lightboxCarousel.toggleClass('hidden');
            $showListOfImages.toggleClass('flipped');
            $showMoreText.toggleClass('hide-text');
            $thisLightboxGallery.find('.lightbox-prev').add('.lightbox-next').toggleClass('hidden-arrows');
            filmStripHidden = !filmStripHidden;
        }

        // set the counter to appropriate index and change active class
        function activeClassLogic() {

            var $gallerySlideChildren = $gallerySlide.children();

            // update active class
            $gallerySlideChildren.removeClass('active');
            $gallerySlideChildren.eq(galleryActiveClassCounter).addClass('active');
            $activeGallerySlide = $gallerySlideChildren.filter('.active');

            // update scrollbar
            $scrollArea.stop().animate({ scrollLeft: Math.floor($activeGallerySlide.innerWidth() * $activeGallerySlide.index()) }, 150);

            // update total images in lightbox
            $totalImages.text($activeGallerySlide.index() + 1 + ' /' + imageCounter);

            // update the main presented image in lightbox
            updateMainImage();
        }

        function updateMainImage() {
            var $presentedImage = $presentedImageContainer.find('img');
            var $presentedImageText = $presentedImageContainer.find('p');
            if ($presentedImage.length > 0) {
                $presentedImage.removeClass('active-image').stop().fadeOut(100);
                $presentedImageText.removeClass('active-image').stop().fadeOut(100);
            }
            $presentedImageContainer.append($activeGallerySlide.find('img').clone().addClass('active-image').stop().fadeIn(100, function () {
                $presentedImage.not('.active-image').remove();
            }));
            $presentedImageContainer.append($activeGallerySlide.find('div.img-text').clone().addClass('active-image').stop().fadeIn(100, function () {
                $presentedImageText.not('.active-image').remove();
            }));

        }

        // close lightbox
        function closeLightbox() {
            $lightboxOverlay.fadeOut('fast');
            window.aa.helpers.cache.cachedElements.$body.off('scroll touchmove mousewheel', preventScrolling);
            window.aa.helpers.cache.cachedElements.$footer.removeClass('hide-footer');
            $('#site-wrapper').removeClass('background');
            $presentedImageContainer.empty();
            $rowParent.removeClass('lightbox-visible');

            if (filmStripHidden === true) {
                toggleCarousel();
            } else {
                clearTimeout(lightboxTimer);
            }
        }

        // used to prevent scrolling on body while lightbox is active
        function preventScrolling(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        // show/hide film strip
        if (window.aa.helpers.cache.cachedElements.$window.width() <= window.aa.helpers.cache.constants.TABLET_LANDSCAPE) {
            $showListOfImages.on('click', function () {
                if (filmStripHidden === false) {
                    clearTimeout(lightboxTimer);
                }
                toggleCarousel();
            });
        } else {
            $filmStrip.hover(function () {
                if (filmStripHidden === false) {
                    clearTimeout(lightboxTimer);
                } else {
                    toggleCarousel();
                }
            }, toggleCarousel);
        }

        if ($rowParent.length && aa.helpers.cache.cachedElements.$main.find('.detail-header').length) {
            $imagesContainer.addClass('establishment-gallery');
        }

        // lightbox trigger
        $thisLightboxGallery.find('.lightbox-trigger, .full-width').on('click', function (e) {
            var $image = $(this),
                $thumbnailImage = $gallerySlide.find('.gallery-image');

            e.preventDefault();

            $rowParent.addClass('lightbox-visible');

            if ($image.parent().hasClass('main-image') || $image.hasClass('full-width')) {
                galleryActiveClassCounter = $image.index();
            } else {
                galleryActiveClassCounter = $image.index() + 1;
            }

            $lightboxOverlay.show();
            window.aa.helpers.cache.cachedElements.$footer.addClass('hide-footer');
            window.aa.helpers.cache.cachedElements.$body.on('scroll touchmove mousewheel', preventScrolling);

            $('#site-wrapper').addClass('background');

            if (imageCounter === 1) {
                $filmStrip.add($lightboxControls).addClass('hidden');
            }

            $filmStrip.width($lightboxCarousel.width() + 150);

            // hide filmstrip arrows if gallery images are in viewport
            if ($thumbnailImage.length * $thumbnailImage.outerWidth() <= $scrollArea.width()) {
                $filmStrip.find('.lightbox-controls').children().addClass('hidden');
            }

            $gallerySlide.find('.see-more-images').remove();
            activeClassLogic();

            // hide film strip when lightbox is triggered
            clearTimeout(lightboxTimer);
            lightboxTimer = setTimeout(function () {
                if (filmStripHidden === false) {
                    toggleCarousel();
                }
            }, 2000);
        });

        $lightboxControls.not('.film-strip-control').on('click', function (e) {
            // update counter based on direction
            e.preventDefault();
            dir[$(this).data('dir')]();
            activeClassLogic();
        });

        // use filmstrip controls to navigate through thumbnail images
        $lightboxControls.filter('.film-strip-control').off('click').on('click', function (e) {
            var currentPosition = $scrollArea.scrollLeft(),
                filmStripCalculation = ($gallerySlide.find('.gallery-image').first().outerWidth() * 4); // times 4 images to scroll to

            e.preventDefault();

            // scroll 
            $scrollArea.stop().animate({ scrollLeft: $(this).data('dir') === 'prev' ? currentPosition - filmStripCalculation : currentPosition + filmStripCalculation }, 200);
        });

        $thisLightboxGallery.find('.overlay').add('.lightbox-close').on('click', function (e) {
            e.preventDefault();
            closeLightbox();
        });

        $thisLightboxGallery.on('click', '.lightbox-image', function (e) {
            e.preventDefault();
            if (galleryActiveClassCounter !== $(this).index() && filmStripHidden === false) {
                galleryActiveClassCounter = $(this).index();
                activeClassLogic();
                clearTimeout(lightboxTimer);
            }
        });

        // key and touch controlls
        window.aa.helpers.cache.cachedElements.$window.on('keydown', function (e) {
            var keyEvent = e.which || e.keyCode;
            switch (keyEvent) {
                case 37:
                    dir['prev']();
                    activeClassLogic();
                    break;
                case 27:
                    closeLightbox();
                    break;
                case 39:
                    dir['next']();
                    activeClassLogic();
                    break;
            }
        });

        // allow touch events on $presentedImageContainer
        $presentedImageContainer.touch({
            left: function () {
                dir['next']();
                activeClassLogic();
            }, right: function () {
                dir['prev']();
                activeClassLogic();
            }
        });
    }

    // PP Jquery upgrade
    //    window.aa.helpers.cache.cachedElements.$document.on({
    //        ready: function () {
    window.aa.helpers.cache.cachedElements.$document.ready(
        function () {
            //console.log('Jquery image-gallery upgrade of document.on( ready');
            $('.lightbox-gallery').each(imageGallery);
            //        }
        });
})(jQ);
