/**
 * bxSlider v4.2.12
 * Copyright 2013-2015 Steven Wanderski
 * Written while drinking Belgian ales and listening to jazz
 * Licensed under MIT (http://opensource.org/licenses/MIT)
 */
!function(t){var e={mode:"horizontal",slideSelector:"",infiniteLoop:!0,hideControlOnEnd:!1,speed:500,easing:null,slideMargin:0,startSlide:0,randomStart:!1,captions:!1,ticker:!1,tickerHover:!1,adaptiveHeight:!1,adaptiveHeightSpeed:500,video:!1,useCSS:!0,preloadImages:"visible",responsive:!0,slideZIndex:50,wrapperClass:"bx-wrapper",touchEnabled:!0,swipeThreshold:50,oneToOneTouch:!0,preventDefaultSwipeX:!0,preventDefaultSwipeY:!1,ariaLive:!0,ariaHidden:!0,keyboardEnabled:!1,pager:!0,pagerType:"full",pagerShortSeparator:" / ",pagerSelector:null,buildPager:null,pagerCustom:null,controls:!0,nextText:"Next",prevText:"Prev",nextSelector:null,prevSelector:null,autoControls:!1,startText:"Start",stopText:"Stop",autoControlsCombine:!1,autoControlsSelector:null,auto:!1,pause:4e3,autoStart:!0,autoDirection:"next",stopAutoOnClick:!1,autoHover:!1,autoDelay:0,autoSlideForOnePage:!1,minSlides:1,maxSlides:1,moveSlides:0,slideWidth:0,shrinkItems:!1,onSliderLoad:function(){return!0},onSlideBefore:function(){return!0},onSlideAfter:function(){return!0},onSlideNext:function(){return!0},onSlidePrev:function(){return!0},onSliderResize:function(){return!0}};t.fn.bxSlider=function(n){if(0===this.length)return this;if(this.length>1)return this.each(function(){t(this).bxSlider(n)}),this;var s={},o=this,r=t(window).width(),a=t(window).height();if(!t(o).data("bxSlider")){var l=function(){t(o).data("bxSlider")||(s.settings=t.extend({},e,n),s.settings.slideWidth=parseInt(s.settings.slideWidth),s.children=o.children(s.settings.slideSelector),s.children.length<s.settings.minSlides&&(s.settings.minSlides=s.children.length),s.children.length<s.settings.maxSlides&&(s.settings.maxSlides=s.children.length),s.settings.randomStart&&(s.settings.startSlide=Math.floor(Math.random()*s.children.length)),s.active={index:s.settings.startSlide},s.carousel=s.settings.minSlides>1||s.settings.maxSlides>1,s.carousel&&(s.settings.preloadImages="all"),s.minThreshold=s.settings.minSlides*s.settings.slideWidth+(s.settings.minSlides-1)*s.settings.slideMargin,s.maxThreshold=s.settings.maxSlides*s.settings.slideWidth+(s.settings.maxSlides-1)*s.settings.slideMargin,s.working=!1,s.controls={},s.interval=null,s.animProp="vertical"===s.settings.mode?"top":"left",s.usingCSS=s.settings.useCSS&&"fade"!==s.settings.mode&&function(){for(var t=document.createElement("div"),e=["WebkitPerspective","MozPerspective","OPerspective","msPerspective"],i=0;i<e.length;i++)if(void 0!==t.style[e[i]])return s.cssPrefix=e[i].replace("Perspective","").toLowerCase(),s.animProp="-"+s.cssPrefix+"-transform",!0;return!1}(),"vertical"===s.settings.mode&&(s.settings.maxSlides=s.settings.minSlides),o.data("origStyle",o.attr("style")),o.children(s.settings.slideSelector).each(function(){t(this).data("origStyle",t(this).attr("style"))}),d())},d=function(){var e=s.children.eq(s.settings.startSlide);o.wrap('<div class="'+s.settings.wrapperClass+'"><div class="bx-viewport"></div></div>'),s.viewport=o.parent(),s.settings.ariaLive&&!s.settings.ticker&&s.viewport.attr("aria-live","polite"),s.loader=t('<div class="bx-loading" />'),s.viewport.prepend(s.loader),o.css({width:"horizontal"===s.settings.mode?1e3*s.children.length+215+"%":"auto",position:"relative"}),s.usingCSS&&s.settings.easing?o.css("-"+s.cssPrefix+"-transition-timing-function",s.settings.easing):s.settings.easing||(s.settings.easing="swing"),s.viewport.css({width:"100%",overflow:"hidden",position:"relative"}),s.viewport.parent().css({maxWidth:u()}),s.children.css({float:"horizontal"===s.settings.mode?"left":"none",listStyle:"none",position:"relative"}),s.children.css("width",h()),"horizontal"===s.settings.mode&&s.settings.slideMargin>0&&s.children.css("marginRight",s.settings.slideMargin),"vertical"===s.settings.mode&&s.settings.slideMargin>0&&s.children.css("marginBottom",s.settings.slideMargin),"fade"===s.settings.mode&&(s.children.css({position:"absolute",zIndex:0,display:"none"}),s.children.eq(s.settings.startSlide).css({zIndex:s.settings.slideZIndex,display:"block"})),s.controls.el=t('<div class="bx-controls" />'),s.settings.captions&&P(),s.active.last=s.settings.startSlide===f()-1,s.settings.video&&o.fitVids(),("all"===s.settings.preloadImages||s.settings.ticker)&&(e=s.children),s.settings.ticker?s.settings.pager=!1:(s.settings.controls&&C(),s.settings.auto&&s.settings.autoControls&&T(),s.settings.pager&&w(),(s.settings.controls||s.settings.autoControls||s.settings.pager)&&s.viewport.after(s.controls.el)),c(e,g)},c=function(e,i){var n=e.find('img:not([src=""]), iframe').length,s=0;return 0===n?void i():void e.find('img:not([src=""]), iframe').each(function(){t(this).one("load error",function(){++s===n&&i()}).each(function(){this.complete&&t(this).trigger("load")})})},g=function(){if(s.settings.infiniteLoop&&"fade"!==s.settings.mode&&!s.settings.ticker){var e="vertical"===s.settings.mode?s.settings.minSlides:s.settings.maxSlides,i=s.children.slice(0,e).clone(!0).addClass("bx-clone"),n=s.children.slice(-e).clone(!0).addClass("bx-clone");s.settings.ariaHidden&&(i.attr("aria-hidden",!0),n.attr("aria-hidden",!0)),o.append(i).prepend(n)}s.loader.remove(),m(),"vertical"===s.settings.mode&&(s.settings.adaptiveHeight=!0),s.viewport.height(p()),o.redrawSlider(),s.settings.onSliderLoad.call(o,s.active.index),s.initialized=!0,s.settings.responsive&&t(window).bind("resize",Z),s.settings.auto&&s.settings.autoStart&&(f()>1||s.settings.autoSlideForOnePage)&&H(),s.settings.ticker&&W(),s.settings.pager&&I(s.settings.startSlide),s.settings.controls&&D(),s.settings.touchEnabled&&!s.settings.ticker&&N(),s.settings.keyboardEnabled&&!s.settings.ticker&&t(document).keydown(F)},p=function(){var e=0,n=t();if("vertical"===s.settings.mode||s.settings.adaptiveHeight)if(s.carousel){var o=1===s.settings.moveSlides?s.active.index:s.active.index*x();for(n=s.children.eq(o),i=1;i<=s.settings.maxSlides-1;i++)n=o+i>=s.children.length?n.add(s.children.eq(i-1)):n.add(s.children.eq(o+i))}else n=s.children.eq(s.active.index);else n=s.children;return"vertical"===s.settings.mode?(n.each(function(i){e+=t(this).outerHeight()}),s.settings.slideMargin>0&&(e+=s.settings.slideMargin*(s.settings.minSlides-1))):e=Math.max.apply(Math,n.map(function(){return t(this).outerHeight(!1)}).get()),"border-box"===s.viewport.css("box-sizing")?e+=parseFloat(s.viewport.css("padding-top"))+parseFloat(s.viewport.css("padding-bottom"))+parseFloat(s.viewport.css("border-top-width"))+parseFloat(s.viewport.css("border-bottom-width")):"padding-box"===s.viewport.css("box-sizing")&&(e+=parseFloat(s.viewport.css("padding-top"))+parseFloat(s.viewport.css("padding-bottom"))),e},u=function(){var t="100%";return s.settings.slideWidth>0&&(t="horizontal"===s.settings.mode?s.settings.maxSlides*s.settings.slideWidth+(s.settings.maxSlides-1)*s.settings.slideMargin:s.settings.slideWidth),t},h=function(){var t=s.settings.slideWidth,e=s.viewport.width();if(0===s.settings.slideWidth||s.settings.slideWidth>e&&!s.carousel||"vertical"===s.settings.mode)t=e;else if(s.settings.maxSlides>1&&"horizontal"===s.settings.mode){if(e>s.maxThreshold)return t;e<s.minThreshold?t=(e-s.settings.slideMargin*(s.settings.minSlides-1))/s.settings.minSlides:s.settings.shrinkItems&&(t=Math.floor((e+s.settings.slideMargin)/Math.ceil((e+s.settings.slideMargin)/(t+s.settings.slideMargin))-s.settings.slideMargin))}return t},v=function(){var t=1,e=null;return"horizontal"===s.settings.mode&&s.settings.slideWidth>0?s.viewport.width()<s.minThreshold?t=s.settings.minSlides:s.viewport.width()>s.maxThreshold?t=s.settings.maxSlides:(e=s.children.first().width()+s.settings.slideMargin,t=Math.floor((s.viewport.width()+s.settings.slideMargin)/e)):"vertical"===s.settings.mode&&(t=s.settings.minSlides),t},f=function(){var t=0,e=0,i=0;if(s.settings.moveSlides>0)if(s.settings.infiniteLoop)t=Math.ceil(s.children.length/x());else for(;e<s.children.length;)++t,e=i+v(),i+=s.settings.moveSlides<=v()?s.settings.moveSlides:v();else t=Math.ceil(s.children.length/v());return t},x=function(){return s.settings.moveSlides>0&&s.settings.moveSlides<=v()?s.settings.moveSlides:v()},m=function(){var t,e,i;s.children.length>s.settings.maxSlides&&s.active.last&&!s.settings.infiniteLoop?"horizontal"===s.settings.mode?(e=s.children.last(),t=e.position(),S(-(t.left-(s.viewport.width()-e.outerWidth())),"reset",0)):"vertical"===s.settings.mode&&(i=s.children.length-s.settings.minSlides,t=s.children.eq(i).position(),S(-t.top,"reset",0)):(t=s.children.eq(s.active.index*x()).position(),s.active.index===f()-1&&(s.active.last=!0),void 0!==t&&("horizontal"===s.settings.mode?S(-t.left,"reset",0):"vertical"===s.settings.mode&&S(-t.top,"reset",0)))},S=function(e,i,n,r){var a,l;s.usingCSS?(l="vertical"===s.settings.mode?"translate3d(0, "+e+"px, 0)":"translate3d("+e+"px, 0, 0)",o.css("-"+s.cssPrefix+"-transition-duration",n/1e3+"s"),"slide"===i?(o.css(s.animProp,l),0!==n?o.bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",function(e){t(e.target).is(o)&&(o.unbind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd"),q())}):q()):"reset"===i?o.css(s.animProp,l):"ticker"===i&&(o.css("-"+s.cssPrefix+"-transition-timing-function","linear"),o.css(s.animProp,l),0!==n?o.bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",function(e){t(e.target).is(o)&&(o.unbind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd"),S(r.resetValue,"reset",0),L())}):(S(r.resetValue,"reset",0),L()))):(a={},a[s.animProp]=e,"slide"===i?o.animate(a,n,s.settings.easing,function(){q()}):"reset"===i?o.css(s.animProp,e):"ticker"===i&&o.animate(a,n,"linear",function(){S(r.resetValue,"reset",0),L()}))},b=function(){for(var e="",i="",n=f(),o=0;o<n;o++)i="",s.settings.buildPager&&t.isFunction(s.settings.buildPager)||s.settings.pagerCustom?(i=s.settings.buildPager(o),s.pagerEl.addClass("bx-custom-pager")):(i=o+1,s.pagerEl.addClass("bx-default-pager")),e+='<div class="bx-pager-item"><a href="" data-slide-index="'+o+'" class="bx-pager-link">'+i+"</a></div>";s.pagerEl.html(e)},w=function(){s.settings.pagerCustom?s.pagerEl=t(s.settings.pagerCustom):(s.pagerEl=t('<div class="bx-pager" />'),s.settings.pagerSelector?t(s.settings.pagerSelector).html(s.pagerEl):s.controls.el.addClass("bx-has-pager").append(s.pagerEl),b()),s.pagerEl.on("click touchend","a",z)},C=function(){s.controls.next=t('<a class="bx-next" href="">'+s.settings.nextText+"</a>"),s.controls.prev=t('<a class="bx-prev" href="">'+s.settings.prevText+"</a>"),s.controls.next.bind("click touchend",E),s.controls.prev.bind("click touchend",k),s.settings.nextSelector&&t(s.settings.nextSelector).append(s.controls.next),s.settings.prevSelector&&t(s.settings.prevSelector).append(s.controls.prev),s.settings.nextSelector||s.settings.prevSelector||(s.controls.directionEl=t('<div class="bx-controls-direction" />'),s.controls.directionEl.append(s.controls.prev).append(s.controls.next),s.controls.el.addClass("bx-has-controls-direction").append(s.controls.directionEl))},T=function(){s.controls.start=t('<div class="bx-controls-auto-item"><a class="bx-start" href="">'+s.settings.startText+"</a></div>"),s.controls.stop=t('<div class="bx-controls-auto-item"><a class="bx-stop" href="">'+s.settings.stopText+"</a></div>"),s.controls.autoEl=t('<div class="bx-controls-auto" />'),s.controls.autoEl.on("click",".bx-start",M),s.controls.autoEl.on("click",".bx-stop",y),s.settings.autoControlsCombine?s.controls.autoEl.append(s.controls.start):s.controls.autoEl.append(s.controls.start).append(s.controls.stop),s.settings.autoControlsSelector?t(s.settings.autoControlsSelector).html(s.controls.autoEl):s.controls.el.addClass("bx-has-controls-auto").append(s.controls.autoEl),A(s.settings.autoStart?"stop":"start")},P=function(){s.children.each(function(e){var i=t(this).find("img:first").attr("title");void 0!==i&&(""+i).length&&t(this).append('<div class="bx-caption"><span>'+i+"</span></div>")})},E=function(t){t.preventDefault(),s.controls.el.hasClass("disabled")||(s.settings.auto&&s.settings.stopAutoOnClick&&o.stopAuto(),o.goToNextSlide())},k=function(t){t.preventDefault(),s.controls.el.hasClass("disabled")||(s.settings.auto&&s.settings.stopAutoOnClick&&o.stopAuto(),o.goToPrevSlide())},M=function(t){o.startAuto(),t.preventDefault()},y=function(t){o.stopAuto(),t.preventDefault()},z=function(e){var i,n;e.preventDefault(),s.controls.el.hasClass("disabled")||(s.settings.auto&&s.settings.stopAutoOnClick&&o.stopAuto(),i=t(e.currentTarget),void 0!==i.attr("data-slide-index")&&(n=parseInt(i.attr("data-slide-index")),n!==s.active.index&&o.goToSlide(n)))},I=function(e){var i=s.children.length;return"short"===s.settings.pagerType?(s.settings.maxSlides>1&&(i=Math.ceil(s.children.length/s.settings.maxSlides)),void s.pagerEl.html(e+1+s.settings.pagerShortSeparator+i)):(s.pagerEl.find("a").removeClass("active"),void s.pagerEl.each(function(i,n){t(n).find("a").eq(e).addClass("active")}))},q=function(){if(s.settings.infiniteLoop){var t="";0===s.active.index?t=s.children.eq(0).position():s.active.index===f()-1&&s.carousel?t=s.children.eq((f()-1)*x()).position():s.active.index===s.children.length-1&&(t=s.children.eq(s.children.length-1).position()),t&&("horizontal"===s.settings.mode?S(-t.left,"reset",0):"vertical"===s.settings.mode&&S(-t.top,"reset",0))}s.working=!1,s.settings.onSlideAfter.call(o,s.children.eq(s.active.index),s.oldIndex,s.active.index)},A=function(t){s.settings.autoControlsCombine?s.controls.autoEl.html(s.controls[t]):(s.controls.autoEl.find("a").removeClass("active"),s.controls.autoEl.find("a:not(.bx-"+t+")").addClass("active"))},D=function(){1===f()?(s.controls.prev.addClass("disabled"),s.controls.next.addClass("disabled")):!s.settings.infiniteLoop&&s.settings.hideControlOnEnd&&(0===s.active.index?(s.controls.prev.addClass("disabled"),s.controls.next.removeClass("disabled")):s.active.index===f()-1?(s.controls.next.addClass("disabled"),s.controls.prev.removeClass("disabled")):(s.controls.prev.removeClass("disabled"),s.controls.next.removeClass("disabled")))},H=function(){if(s.settings.autoDelay>0){setTimeout(o.startAuto,s.settings.autoDelay)}else o.startAuto(),t(window).focus(function(){o.startAuto()}).blur(function(){o.stopAuto()});s.settings.autoHover&&o.hover(function(){s.interval&&(o.stopAuto(!0),s.autoPaused=!0)},function(){s.autoPaused&&(o.startAuto(!0),s.autoPaused=null)})},W=function(){var e,i,n,r,a,l,d,c,g=0;"next"===s.settings.autoDirection?o.append(s.children.clone().addClass("bx-clone")):(o.prepend(s.children.clone().addClass("bx-clone")),e=s.children.first().position(),g="horizontal"===s.settings.mode?-e.left:-e.top),S(g,"reset",0),s.settings.pager=!1,s.settings.controls=!1,s.settings.autoControls=!1,s.settings.tickerHover&&(s.usingCSS?(r="horizontal"===s.settings.mode?4:5,s.viewport.hover(function(){i=o.css("-"+s.cssPrefix+"-transform"),n=parseFloat(i.split(",")[r]),S(n,"reset",0)},function(){c=0,s.children.each(function(e){c+="horizontal"===s.settings.mode?t(this).outerWidth(!0):t(this).outerHeight(!0)}),a=s.settings.speed/c,l="horizontal"===s.settings.mode?"left":"top",d=a*(c-Math.abs(parseInt(n))),L(d)})):s.viewport.hover(function(){o.stop()},function(){c=0,s.children.each(function(e){c+="horizontal"===s.settings.mode?t(this).outerWidth(!0):t(this).outerHeight(!0)}),a=s.settings.speed/c,l="horizontal"===s.settings.mode?"left":"top",d=a*(c-Math.abs(parseInt(o.css(l)))),L(d)})),L()},L=function(t){var e,i,n,r=t?t:s.settings.speed,a={left:0,top:0},l={left:0,top:0};"next"===s.settings.autoDirection?a=o.find(".bx-clone").first().position():l=s.children.first().position(),e="horizontal"===s.settings.mode?-a.left:-a.top,i="horizontal"===s.settings.mode?-l.left:-l.top,n={resetValue:i},S(e,"ticker",r,n)},O=function(e){var i=t(window),n={top:i.scrollTop(),left:i.scrollLeft()},s=e.offset();return n.right=n.left+i.width(),n.bottom=n.top+i.height(),s.right=s.left+e.outerWidth(),s.bottom=s.top+e.outerHeight(),!(n.right<s.left||n.left>s.right||n.bottom<s.top||n.top>s.bottom)},F=function(t){var e=document.activeElement.tagName.toLowerCase(),i="input|textarea",n=new RegExp(e,["i"]),s=n.exec(i);if(null==s&&O(o)){if(39===t.keyCode)return E(t),!1;if(37===t.keyCode)return k(t),!1}},N=function(){s.touch={start:{x:0,y:0},end:{x:0,y:0}},s.viewport.bind("touchstart MSPointerDown pointerdown",X),s.viewport.on("click",".bxslider a",function(t){s.viewport.hasClass("click-disabled")&&(t.preventDefault(),s.viewport.removeClass("click-disabled"))})},X=function(t){if(s.controls.el.addClass("disabled"),s.working)t.preventDefault(),s.controls.el.removeClass("disabled");else{s.touch.originalPos=o.position();var e=t.originalEvent,i="undefined"!=typeof e.changedTouches?e.changedTouches:[e];s.touch.start.x=i[0].pageX,s.touch.start.y=i[0].pageY,s.viewport.get(0).setPointerCapture&&(s.pointerId=e.pointerId,s.viewport.get(0).setPointerCapture(s.pointerId)),s.viewport.bind("touchmove MSPointerMove pointermove",V),s.viewport.bind("touchend MSPointerUp pointerup",R),s.viewport.bind("MSPointerCancel pointercancel",Y)}},Y=function(t){S(s.touch.originalPos.left,"reset",0),s.controls.el.removeClass("disabled"),s.viewport.unbind("MSPointerCancel pointercancel",Y),s.viewport.unbind("touchmove MSPointerMove pointermove",V),s.viewport.unbind("touchend MSPointerUp pointerup",R),s.viewport.get(0).releasePointerCapture&&s.viewport.get(0).releasePointerCapture(s.pointerId)},V=function(t){var e=t.originalEvent,i="undefined"!=typeof e.changedTouches?e.changedTouches:[e],n=Math.abs(i[0].pageX-s.touch.start.x),o=Math.abs(i[0].pageY-s.touch.start.y),r=0,a=0;3*n>o&&s.settings.preventDefaultSwipeX?t.preventDefault():3*o>n&&s.settings.preventDefaultSwipeY&&t.preventDefault(),"fade"!==s.settings.mode&&s.settings.oneToOneTouch&&("horizontal"===s.settings.mode?(a=i[0].pageX-s.touch.start.x,r=s.touch.originalPos.left+a):(a=i[0].pageY-s.touch.start.y,r=s.touch.originalPos.top+a),S(r,"reset",0))},R=function(t){s.viewport.unbind("touchmove MSPointerMove pointermove",V),s.controls.el.removeClass("disabled");var e=t.originalEvent,i="undefined"!=typeof e.changedTouches?e.changedTouches:[e],n=0,r=0;s.touch.end.x=i[0].pageX,s.touch.end.y=i[0].pageY,"fade"===s.settings.mode?(r=Math.abs(s.touch.start.x-s.touch.end.x),r>=s.settings.swipeThreshold&&(s.touch.start.x>s.touch.end.x?o.goToNextSlide():o.goToPrevSlide(),o.stopAuto())):("horizontal"===s.settings.mode?(r=s.touch.end.x-s.touch.start.x,n=s.touch.originalPos.left):(r=s.touch.end.y-s.touch.start.y,n=s.touch.originalPos.top),!s.settings.infiniteLoop&&(0===s.active.index&&r>0||s.active.last&&r<0)?S(n,"reset",200):Math.abs(r)>=s.settings.swipeThreshold?(r<0?o.goToNextSlide():o.goToPrevSlide(),o.stopAuto()):S(n,"reset",200)),s.viewport.unbind("touchend MSPointerUp pointerup",R),s.viewport.get(0).releasePointerCapture&&s.viewport.get(0).releasePointerCapture(s.pointerId)},Z=function(e){if(s.initialized)if(s.working)window.setTimeout(Z,10);else{var i=t(window).width(),n=t(window).height();r===i&&a===n||(r=i,a=n,o.redrawSlider(),s.settings.onSliderResize.call(o,s.active.index))}},B=function(t){var e=v();s.settings.ariaHidden&&!s.settings.ticker&&(s.children.attr("aria-hidden","true"),s.children.slice(t,t+e).attr("aria-hidden","false"))},U=function(t){return t<0?s.settings.infiniteLoop?f()-1:s.active.index:t>=f()?s.settings.infiniteLoop?0:s.active.index:t};return o.goToSlide=function(e,i){var n,r,a,l,d=!0,c=0,g={left:0,top:0},u=null;if(s.oldIndex=s.active.index,s.active.index=U(e),!s.working&&s.active.index!==s.oldIndex){if(s.working=!0,d=s.settings.onSlideBefore.call(o,s.children.eq(s.active.index),s.oldIndex,s.active.index),"undefined"!=typeof d&&!d)return s.active.index=s.oldIndex,void(s.working=!1);"next"===i?s.settings.onSlideNext.call(o,s.children.eq(s.active.index),s.oldIndex,s.active.index)||(d=!1):"prev"===i&&(s.settings.onSlidePrev.call(o,s.children.eq(s.active.index),s.oldIndex,s.active.index)||(d=!1)),s.active.last=s.active.index>=f()-1,(s.settings.pager||s.settings.pagerCustom)&&I(s.active.index),s.settings.controls&&D(),"fade"===s.settings.mode?(s.settings.adaptiveHeight&&s.viewport.height()!==p()&&s.viewport.animate({height:p()},s.settings.adaptiveHeightSpeed),s.children.filter(":visible").fadeOut(s.settings.speed).css({zIndex:0}),s.children.eq(s.active.index).css("zIndex",s.settings.slideZIndex+1).fadeIn(s.settings.speed,function(){t(this).css("zIndex",s.settings.slideZIndex),q()})):(s.settings.adaptiveHeight&&s.viewport.height()!==p()&&s.viewport.animate({height:p()},s.settings.adaptiveHeightSpeed),!s.settings.infiniteLoop&&s.carousel&&s.active.last?"horizontal"===s.settings.mode?(u=s.children.eq(s.children.length-1),g=u.position(),c=s.viewport.width()-u.outerWidth()):(n=s.children.length-s.settings.minSlides,g=s.children.eq(n).position()):s.carousel&&s.active.last&&"prev"===i?(r=1===s.settings.moveSlides?s.settings.maxSlides-x():(f()-1)*x()-(s.children.length-s.settings.maxSlides),u=o.children(".bx-clone").eq(r),g=u.position()):"next"===i&&0===s.active.index?(g=o.find("> .bx-clone").eq(s.settings.maxSlides).position(),s.active.last=!1):e>=0&&(l=e*parseInt(x()),g=s.children.eq(l).position()),"undefined"!=typeof g?(a="horizontal"===s.settings.mode?-(g.left-c):-g.top,S(a,"slide",s.settings.speed)):s.working=!1),s.settings.ariaHidden&&B(s.active.index*x())}},o.goToNextSlide=function(){if(s.settings.infiniteLoop||!s.active.last){var t=parseInt(s.active.index)+1;o.goToSlide(t,"next")}},o.goToPrevSlide=function(){if(s.settings.infiniteLoop||0!==s.active.index){var t=parseInt(s.active.index)-1;o.goToSlide(t,"prev")}},o.startAuto=function(t){s.interval||(s.interval=setInterval(function(){"next"===s.settings.autoDirection?o.goToNextSlide():o.goToPrevSlide()},s.settings.pause),s.settings.autoControls&&t!==!0&&A("stop"))},o.stopAuto=function(t){s.interval&&(clearInterval(s.interval),s.interval=null,s.settings.autoControls&&t!==!0&&A("start"))},o.getCurrentSlide=function(){return s.active.index},o.getCurrentSlideElement=function(){return s.children.eq(s.active.index)},o.getSlideElement=function(t){return s.children.eq(t)},o.getSlideCount=function(){return s.children.length},o.isWorking=function(){return s.working},o.redrawSlider=function(){s.children.add(o.find(".bx-clone")).outerWidth(h()),s.viewport.css("height",p()),s.settings.ticker||m(),s.active.last&&(s.active.index=f()-1),s.active.index>=f()&&(s.active.last=!0),s.settings.pager&&!s.settings.pagerCustom&&(b(),I(s.active.index)),s.settings.ariaHidden&&B(s.active.index*x())},o.destroySlider=function(){s.initialized&&(s.initialized=!1,t(".bx-clone",this).remove(),s.children.each(function(){void 0!==t(this).data("origStyle")?t(this).attr("style",t(this).data("origStyle")):t(this).removeAttr("style")}),void 0!==t(this).data("origStyle")?this.attr("style",t(this).data("origStyle")):t(this).removeAttr("style"),t(this).unwrap().unwrap(),s.controls.el&&s.controls.el.remove(),s.controls.next&&s.controls.next.remove(),s.controls.prev&&s.controls.prev.remove(),s.pagerEl&&s.settings.controls&&!s.settings.pagerCustom&&s.pagerEl.remove(),t(".bx-caption",this).remove(),s.controls.autoEl&&s.controls.autoEl.remove(),clearInterval(s.interval),s.settings.responsive&&t(window).unbind("resize",Z),s.settings.keyboardEnabled&&t(document).unbind("keydown",F),t(this).removeData("bxSlider"))},o.reloadSlider=function(e){void 0!==e&&(n=e),o.destroySlider(),l(),t(o).data("bxSlider",this)},l(),t(o).data("bxSlider",this),this}}}(jQuery);
/*!
 * hoverIntent v1.10.2 // 2020.04.28 // jQuery v1.7.0+
 */

;(function(factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        module.exports = factory(require('jquery'));
    } else if (jQuery && !jQuery.fn.hoverIntent) {
        factory(jQuery);
    }
})(function($) {
    'use strict';

    // default configuration values
    var _cfg = {
        interval: 100,
        sensitivity: 6,
        timeout: 0
    };

    // counter used to generate an ID for each instance
    var INSTANCE_COUNT = 0;

    // current X and Y position of mouse, updated during mousemove tracking (shared across instances)
    var cX, cY;

    // saves the current pointer position coordinates based on the given mousemove event
    var track = function(ev) {
        cX = ev.pageX;
        cY = ev.pageY;
    };

    // compares current and previous mouse positions
    var compare = function(ev,$el,s,cfg) {
        // compare mouse positions to see if pointer has slowed enough to trigger `over` function
        if ( Math.sqrt( (s.pX-cX)*(s.pX-cX) + (s.pY-cY)*(s.pY-cY) ) < cfg.sensitivity ) {
            $el.off(s.event,track);
            delete s.timeoutId;
            // set hoverIntent state as active for this element (permits `out` handler to trigger)
            s.isActive = true;
            // overwrite old mouseenter event coordinates with most recent pointer position
            ev.pageX = cX; ev.pageY = cY;
            // clear coordinate data from state object
            delete s.pX; delete s.pY;
            return cfg.over.apply($el[0],[ev]);
        } else {
            // set previous coordinates for next comparison
            s.pX = cX; s.pY = cY;
            // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
            s.timeoutId = setTimeout( function(){compare(ev, $el, s, cfg);} , cfg.interval );
        }
    };

    // triggers given `out` function at configured `timeout` after a mouseleave and clears state
    var delay = function(ev,$el,s,out) {
        var data = $el.data('hoverIntent');
        if (data) {
            delete data[s.id];
        }
        return out.apply($el[0],[ev]);
    };

    // checks if `value` is a function
    var isFunction = function(value) {
        return typeof value === 'function';
    };

    $.fn.hoverIntent = function(handlerIn,handlerOut,selector) {
        // instance ID, used as a key to store and retrieve state information on an element
        var instanceId = INSTANCE_COUNT++;

        // extend the default configuration and parse parameters
        var cfg = $.extend({}, _cfg);
        if ( $.isPlainObject(handlerIn) ) {
            cfg = $.extend(cfg, handlerIn);
            if ( !isFunction(cfg.out) ) {
                cfg.out = cfg.over;
            }
        } else if ( isFunction(handlerOut) ) {
            cfg = $.extend(cfg, { over: handlerIn, out: handlerOut, selector: selector } );
        } else {
            cfg = $.extend(cfg, { over: handlerIn, out: handlerIn, selector: handlerOut } );
        }

        // A private function for handling mouse 'hovering'
        var handleHover = function(e) {
            // cloned event to pass to handlers (copy required for event object to be passed in IE)
            var ev = $.extend({},e);

            // the current target of the mouse event, wrapped in a jQuery object
            var $el = $(this);

            // read hoverIntent data from element (or initialize if not present)
            var hoverIntentData = $el.data('hoverIntent');
            if (!hoverIntentData) { $el.data('hoverIntent', (hoverIntentData = {})); }

            // read per-instance state from element (or initialize if not present)
            var state = hoverIntentData[instanceId];
            if (!state) { hoverIntentData[instanceId] = state = { id: instanceId }; }

            // state properties:
            // id = instance ID, used to clean up data
            // timeoutId = timeout ID, reused for tracking mouse position and delaying "out" handler
            // isActive = plugin state, true after `over` is called just until `out` is called
            // pX, pY = previously-measured pointer coordinates, updated at each polling interval
            // event = string representing the namespaced event used for mouse tracking

            // clear any existing timeout
            if (state.timeoutId) { state.timeoutId = clearTimeout(state.timeoutId); }

            // namespaced event used to register and unregister mousemove tracking
            var mousemove = state.event = 'mousemove.hoverIntent.hoverIntent'+instanceId;

            // handle the event, based on its type
            if (e.type === 'mouseenter') {
                // do nothing if already active
                if (state.isActive) { return; }
                // set "previous" X and Y position based on initial entry point
                state.pX = ev.pageX; state.pY = ev.pageY;
                // update "current" X and Y position based on mousemove
                $el.off(mousemove,track).on(mousemove,track);
                // start polling interval (self-calling timeout) to compare mouse coordinates over time
                state.timeoutId = setTimeout( function(){compare(ev,$el,state,cfg);} , cfg.interval );
            } else { // "mouseleave"
                // do nothing if not already active
                if (!state.isActive) { return; }
                // unbind expensive mousemove event
                $el.off(mousemove,track);
                // if hoverIntent state is true, then call the mouseOut function after the specified delay
                state.timeoutId = setTimeout( function(){delay(ev,$el,state,cfg.out);} , cfg.timeout );
            }
        };

        // listen for mouseenter and mouseleave
        return this.on({'mouseenter.hoverIntent':handleHover,'mouseleave.hoverIntent':handleHover}, cfg.selector);
    };
});


function deviceModeDark() {
    document.body.className = "device-mode-dark";
    $('#lightSwitch').val(1);
    $('header #switch').prop('checked', true);
    $('#logo .light').hide();
    $('#logo .dark').show();
    $('#motif.light').hide();
    $('#motif.dark').show();
}

function deviceModeLight() {
    document.body.className = "device-mode-light"; 
    $('#lightSwitch').val(0);
    $('header #switch').prop('checked', false);
    $('#logo .light').show();
    $('#logo .dark').hide();
    $('#motif.dark').hide();
    $('#motif.light').show();
}

// Hacky way to implement old jQuery v1.7+ style 'toggle' between two functions
(function($) {
    $.fn.clickToggle = function(func1, func2) {
        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };
}(jQuery));

// Cookie List Function
(function ($) {
    $.fn.extend({
        cookieList: function (cookieName) {
            var cookie = $.cookie(cookieName);

            var items = cookie ? cookie.replace("([","").replace("])","").split(",") : [];

            return {
                add: function (val) {
                    var index = items.indexOf(val);

                    // Note: Add only unique values.
                    if (index == -1) {
                        items.push(val.toString());
                        $.cookie(cookieName, items.join(','), { expires: 365, path: '/' });
                    }
                },
                remove: function (val) {
                    var index = items.indexOf(val);

                    if (index != -1) {
                        items.splice(index, 1);
                        $.cookie(cookieName, items.join(','), { expires: 365, path: '/' });
                     }
                },
                indexOf: function (val) {
                    return items.indexOf(val);
                },
                clear: function () {
                    items = null;
                    $.cookie(cookieName, null, { expires: 365, path: '/' });
                },
                items: function () {
                    return items;
                },
                length: function () {
                    return items.length;
                },
                join: function (separator) {
                    return items.join(separator);
                }
            };
        }
    });
})(jQuery);

var cookieList = $.fn.cookieList("device-notification-dismiss");

// Only Show Non-Dismissed Notifications
var dismissedNotifications = cookieList.items();
// console.log(cookieList.items());

$('blockquote.notice').each(function() {
    var tid = $(this).attr('id').toString();

    if (!cookieList.items().includes(tid)) {
        $(this).show();
    }
});

$('blockquote i.fa-times').click(function() {
   var id = $(this).parent().parent().attr('id');
   cookieList.add(id);
   $(this).parent().parent().hide();
});

// var selectedVal = jQuery.cookie("device-mode");

// Random Sort Elements by Parent
jQuery.fn.shuffle = function () {
    var j;
    for (var i = 0; i < this.length; i++) {
        j = Math.floor(Math.random() * this.length);
        $(this[i]).before($(this[j]));
    }
    return this;
};

 if (!!window.performance && window.performance.navigation.type === 2) {
    $('#lazySpaceDestroyer').parent().html('Page Generated from Browser Cache');
 } else {
    var lazySpaceDestroyer = $('#lazySpaceDestroyer').text().replace(' ','');
    $('#lazySpaceDestroyer').text(lazySpaceDestroyer);
 }

$(document).ready(function() {
    var selectedVal = jQuery.cookie("device-mode");

    if (selectedVal) {
        if (selectedVal == 1) {
            deviceModeDark();
        } else {
            deviceModeLight(); // Swap to Dark to Force Dark
        }
    } else {
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            deviceModeDark();
        } else {
            document.body.className = "device-mode-light";
            deviceModeLight(); // Swap to Dark to Force Dark
        }
    }
    /* $('#lightSwitch').on('change', function() {
        if (this.value == '1') {
            deviceModeDark();
        } else {
            deviceModeLight();
        }

        var selection = jQuery(this).val();
        jQuery.cookie("device-mode", selection, {expires: 365, path: '/'})
    }); */

    $('header #switch').change(function() {
        if ($(this).is(':checked')) {
            deviceModeDark();
            var selection = 1;
        } else {
            deviceModeLight();
            var selection = 0;
        }

        jQuery.cookie("device-mode", selection, {
            expires: 365,
            path: '/'
        })
    });

    $('header nav > ul > li').click(function() {
        var href = $(this).children('a').attr('href');
        $(location).attr('href', href);
    });

    var windowWidth = $(window).width();
    var cutLoad = 0;

    if (windowWidth < 1440) {
        $("header nav > ul").cutList({
            moreBtnTitle: '<i class="menuFill fas fa-bars"></i>',
            resizeDelay: 0
        });

        cutLoad = 1;
    } else {
        $(window).on("orientationchange resize", function() {
            var windowWidth = $(window).width();

            if (windowWidth < 1440 && cutLoad == 0) {
                $("header nav > ul").cutList({
                    moreBtnTitle: '<i class="menuFill fas fa-bars"></i>',
                    resizeDelay: 0
                });

                cutLoad = 1;
            } 
        });
    }

    $('header nav figure#menu').clickToggle(function() {   
        $('header nav ul > li').css('display','inline-block');
    }, function() {
        $('header nav ul > li:not(.active)').css('display','none');
    });

    $('.pdfStrain').click(function() {
        var href = $(this).attr('href');
        $(location).attr('href', href);
    });

    $('.pseudoLink').click(function() {
        var href = $(this).attr('href');
        $(location).attr('href', href);
    });

    function sortNav(selector) {
        $(selector).children("a").sort(function(a, b) {
            var upA = $(a).attr('title').toUpperCase();
            var upB = $(b).attr('title').toUpperCase();
            return (upA < upB) ? -1 : (upA > upB) ? 1 : 0;
        }).appendTo(selector);
    }

    /* $('header nav > ul > li:nth-child(1) > ul ul').remove('ul'); */
    $('header nav > ul > li:nth-child(2) > ul ul').remove('ul');
    $('header nav > ul > li:nth-child(3) > ul ul').remove('ul');
    /* $('header nav > ul > li:nth-child(1) > ul li').removeClass('parent'); */
    $('header nav > ul > li:nth-child(2) > ul li').removeClass('parent');
    $('header nav > ul > li:nth-child(3) > ul li').removeClass('parent');

    sortNav('header nav > ul > li:nth-child(2) > ul'); // Clinics 
    sortNav('header nav > ul > li:nth-child(3) > ul'); // Pharmacies
    sortNav('header nav > ul > li:nth-child(4) > ul'); // Producers

    // Strains, Discontinued
    $('header nav > ul > li:nth-child(5) > ul').each(function() {
        var parent = $(this);
        if ($('a.discontinued', this).length > 0) {
//
        }
    }); 

     $('form#table-controls select.access').on('change', function() {
        var scheme = $("option:selected", this).text();

        if (scheme == 'T21') {
            $('tr.flower.GAP:not(.T21)').each(function() {
                $('.priceGramGAP',this).hide();  
                $('.priceBreakdownGAP',this).hide();   
                $('.priceGram',this).show(); 
                $('.priceBreakdown',this).show();  
                $('td',this).css('background','');
            });
            $('tr.flower.T21').each(function() {
                $('.priceBreakdownT21',this).show();
                $('.priceBreakdown',this).hide();    
                $('.priceGramT21',this).show();
                $('.priceGram',this).hide(); 
                $('.priceGramGAP',this).hide();  
                $('.priceBreakdownGAP',this).hide();   
                $('tr.flower td').css('background','');

                if ($('body').hasClass('device-mode-dark')) {
                    $('tr.flower.T21 td').css('background', '#2E2C00');
                } else {
                    $('tr.flower.T21 td').css('background', '#fffddc');
                }      
            });
        } else if (scheme == 'GAP') {
            $('tr.flower.T21:not(.GAP)').each(function() {
                $('.priceGramT21',this).hide();  
                $('.priceBreakdownT21',this).hide();   
                $('.priceGram',this).show(); 
                $('.priceBreakdown',this).show();  
                $('td',this).css('background','');
            });
            $('tr.flower.GAP').each(function() {
                $('.priceBreakdownGAP',this).show();
                $('.priceBreakdown',this).hide();    
                $('.priceGramGAP',this).show();
                $('.priceGram',this).hide(); 
                $('.priceGramT21',this).hide();  
                $('.priceBreakdownT21',this).hide();     
                $('tr.flower td').css('background','');

                if ($('body').hasClass('device-mode-dark')) {
                    $('tr.flower.GAP td').css('background', '#2E2C00');
                } else {
                    $('tr.flower.GAP td').css('background', '#fffddc');
                }      
            });
        } else {
            $('tr.flower').each(function() {
                $('.priceBreakdownGAP',this).hide();
                $('.priceGramGAP',this).hide();
                $('.priceGramT21',this).hide();  
                $('.priceBreakdownT21',this).hide();      
                $('.priceBreakdown',this).show();    
                $('.priceGram',this).show();  
                $('tr.flower td').css('background','');
            });
        }
    });

    $('figure#context').hover(function() {
        $('#contextChanger').toggle();
    });

const dateToday = new Date();
const dateYesterday = new Date(dateToday);
dateYesterday.setDate(dateYesterday.getDate() - 1);
const dateWeek = new Date(dateToday);
dateWeek.setDate(dateWeek.getDate() - 7);

function dateOrdinal(d) {
    return d+(31==d||21==d||1==d?"st":22==d||2==d?"nd":23==d||3==d?"rd":"th")
};

$('time.ago').each(function() { 
    if ($(this).attr('datetime').length > 0) {
        var datetime = $(this).attr('datetime');
        var dateTarget = new Date(datetime);

        if (dateToday.toDateString() === dateTarget.toDateString()) {
            if (dateTarget.getHours() > 12) {
                var dateHour = (dateTarget.getHours() - 12) + 'pm';
            } else if (dateTarget.getHours() == 12) {
                var dateHour = '12pm';
            } else if (dateTarget.getHours() == 0) {
                var dateHour = '12am';
            } else {
                var dateHour = dateTarget.getHours() + 'am';  
            }
            $(this).text(dateHour + ' Today'); 
        } else if (dateYesterday.toDateString() === dateTarget.toDateString()) {
            $(this).text('Yesterday'); 
        } else if (dateWeek < dateTarget) {
            var dateString = dateTarget.toLocaleDateString('default', { weekday: 'long' });
            $(this).text(dateString);
        } else {
            var dateDay = dateOrdinal(dateTarget.getDate());
            var dateMonth = dateTarget.toLocaleString('default', { month: 'short' });
            $(this).text(dateDay + ' ' + dateMonth); 
        }
    }
});

$(".target-tab").click(function(e) {
    e.preventDefault();
    var url = $(this).attr('href');
    var hash = url.substring(url.indexOf('#'));
    $('.tab-container > section').hide();
    $('.tab-container section' + hash).show();
    $('.tabs > a').removeClass('active');
    $('.tabs > a[href*="' + hash + '"]').addClass('active');
});

var $slider;

function buildSliderConfiguration() {
    var windowWidth = $(window).width();
    var numberOfVisibleSlides;
    var isScrolling;

    /*if (windowWidth < 500) {
        numberOfVisibleSlides = 1;
    } else*/ if (windowWidth < 680) {
        numberOfVisibleSlides = 2;
    } else if (windowWidth < 900) {
        numberOfVisibleSlides = 3;
    } else if (windowWidth < 1100) {
        numberOfVisibleSlides = 4;
    } else if (windowWidth < 1260) {
        numberOfVisibleSlides = 5;
    } else {
        numberOfVisibleSlides = 6;
    }

    if (windowWidth > 1260) {
        isScrolling = false;
    } else {
        isScrolling = true;
    }

    return {
        auto: isScrolling,
        infiniteLoop: true,
        speed: 100,
        pause: 7000,
        pager: false,
        responsive: true,
        useCSS: false,
        controls: false,
        slideWidth: 5000,
        minSlides: numberOfVisibleSlides,
        maxSlides: numberOfVisibleSlides
    };
}

function configureSlider() {
    var config = buildSliderConfiguration();

    if ($slider && $slider.reloadSlider) {
        $slider.reloadSlider(config);
    } else {
        $slider = $('aside.charter ul').bxSlider(config);
    }
}

// Configure the slider every time its size changes.
$(window).on("orientationchange resize", configureSlider);
// Configure the slider once on page load.
configureSlider();

    $('main.carousel section').bxSlider({
        useCSS: false,
        auto: true,
        pause: 7000,
        speed: 330,
        infiniteLoop: true,
        controls: false,
        pager: false,
        moveSlides: 8,
        slideWidth: 170,
        minSlides: 2,
        maxSlides: 8
    }); 



    $("p a[href^='http']:not(.noicon), .latest td a[href^='http']:not(.noicon), main ul a[href^='http']:not(.noicon), article p a[href^='http'], article li a[href^='http'], blockquote p a[href^='http']:not(.noicon)").each(function() {
        var href = $(this).attr('href');

        if (href.indexOf('medbud.wiki') == -1) {
            $(this).css({
                background: "url(https://www.google.com/s2/favicons?domain=" + this.hostname + ") left center no-repeat",
                "padding-left": "20px"
            });
        }
    });

    $('tr:not(.discontinued) .flower-thumb').mouseover(function() {
        $(this).parent().next('.flower-full').show();
    });
    $('.flower-full').mouseout(function() {
        $(this).hide();
    });
    $('.flower-thumb').mouseout(function() {
        $(this).parent().next('.flower-full').hide();
    });

$('td.terps .data-sort div:nth-child(n+4) dt').hide();
$('td.terps .data-sort div:nth-child(n+4) dd').hide();

$('td.terps .data-sort').each(function() {
    if ($('div:nth-child(n+4) dt', this).length > 0) {
        $(this).append('<span class="quiet" style="float:right;margin-top:-1rem;">...</span>');
    }
});  

    // $("aside.terpenes .pie").click(function() {
    //     $(this).next('dl').show();
    // });

    $("aside.terpenes .pie, td.terps").clickToggle(function() {
       $('td.terps .data-sort div:nth-child(n+4) dt').css('display','inline');
       $('td.terps .data-sort div:nth-child(n+4) dt i').css('display','inline');
       $('td.terps .data-sort div:nth-child(n+4) dd').css('display','inline');
       $('td.terps .data-sort div:nth-child(n+4) .quiet').css('display','inline');
    }, function() {
       $('td.terps .data-sort div:nth-child(n+4) dt').hide();
       $('td.terps .data-sort div:nth-child(n+4) dt i').hide();
       $('td.terps .data-sort div:nth-child(n+4) dd').hide();
       $('td.terps .data-sort div:nth-child(n+4) .quiet').hide();
    });

    // $("aside.terpenes .pie").mouseover(function() {
    //     $(this).next('dl').show();
    // });

    $("aside.terpenes").mouseleave(function() {
        $(this).children('dl').hide();
    });

    $("button#filterToggle").click(function(e) {
        e.preventDefault();
        $('#table-filters').slideToggle();
    });

    $('.overlay').overlay();
});

// Search
//$("form#search").submit(function () { 
//      $("#js-search").load("//medbud.wiki/api/search/", $("form#search").serialize()).show();
//      return false;
//});

$("form#search input").keyup(function() {
    $("form#search input[type='reset']").show();
    if (this.value.length > 2) {
        $("form#search input[type='reset']").hide();
        $("svg.spinner").show();
        $("#js-search").load("https://" + window.location.hostname + "/api/search/", $("form#search").serialize(), function() {
            $("#searchField").addClass('resultsOpen');
            $("svg.spinner").hide();
            $("form#search input[type='reset']").show()
        }).show();
    } else if (this.value.length > 0) {
        $("form#search input[type='reset']").show();
        $("#js-search").hide();
        $("svg.spinner").hide();
        $("#searchField").removeClass('resultsOpen');
    } else if (this.value.length == 0) {
        $("form#search input[type='reset']").hide();
        $("#js-search").hide();
        $("svg.spinner").hide();
        $("#searchField").removeClass('resultsOpen');
    } else {
        $("#js-search").hide();
        $("svg.spinner").hide();
        $("#searchField").removeClass('resultsOpen');
    }
});

$("form#search input[type='reset']").click(function() {
    $("#js-search").slideUp(520, function() {
        $("#searchField").removeClass('resultsOpen');
    });
    $("svg.spinner").hide();
    $(this).hide();
});

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

$('.calcStrain').click(function() {
    $(this).toggleClass('selected');
    $('i', this).toggleClass('fa-file-medical').toggleClass('fa-file-contract');

    if (typeof(Storage) !== "undefined") {
        if ($(this).hasClass('selected')) {
            //var grams = prompt('Enter Quantity in Grams (Numbers Only)');
            var grams = 0;
            const data = grams;
            //alert('Added: ' + JSON.stringify(data));
            localStorage.setItem($(this).data('id'), JSON.stringify(data));
            calculatePrescription();
        } else {
            localStorage.removeItem($(this).data('id'));
            calculatePrescription();
        }
    }
});

$('tr.flower').each(function() {
    if (localStorage.getItem($(this).data('id'))) {
        $('tr.flower[data-id="' + $(this).data('id') + '"] td:last-child button').toggleClass('selected');
        $('tr.flower[data-id="' + $(this).data('id') + '"] td:last-child i').toggleClass('fa-file-medical').toggleClass('fa-file-contract');
    }    
});

var scriptCount = 0;
var scriptTotal = 0;
var scriptList = '';

function calculatePrescription() {
    if (localStorage.getItem('prescriptionP21')) {
        var P21 = localStorage.getItem('prescriptionP21');
    }

        scriptCount = 0;
        scriptTotal = 0;
        scriptList = '';
        total = 0;

        for (var key in localStorage) {
            if (isNumeric(key) == 1) {
                let pid = key;
                var value = localStorage.getItem(key);
                let target = value;

                //var data = JSON.parse(localStorage[key]);

                $.get("//medbud.wiki/api/prescription/?id=" + key + "&qty=" + value, function(data) {
                  //alert(data);
                  updatePrescriptionStats(data, value);

                  $('.prescriptionQuantity').change(function() {
                      var key = $(this).data('id');
                      var qty = $(this).find('option:selected').text().replace('g','');
                      var price = parseFloat($(this).find('option:selected').attr('value')).toFixed(2);
                      localStorage.setItem(key, qty);

                      if ($(this).parent().parent().hasClass('P21') && P21 == 1) {
                         if (qty < 10.1) {
                              $(this).parent().parent().find('span.total').text((parseFloat(qty) * parseFloat(6.5)).toFixed(2));
                         } else if (qty < 20.1) {
                              $(this).parent().parent().find('span.total').text((parseFloat(qty) * parseFloat(6)).toFixed(2));
                         } else {
                              $(this).parent().parent().find('span.total').text((parseFloat(qty) * parseFloat(5)).toFixed(2));
                         }
                      } else {
                          $(this).parent().parent().find('span.total').text(price);
                      }

                      updatePrescriptionTotals();
                  });
                }).complete(function() {
                    setTimeout(function() { 
                        var price = parseFloat($('.prescriptionQuantity[data-id=' + pid + ']').find('option:selected').attr('value')).toFixed(2);

                     if ($('.prescriptionQuantity[data-id=' + pid + ']').parent().parent().hasClass('P21') && P21 == 1) {
                         if (target < 10.1) {
                             $('.prescriptionQuantity[data-id=' + pid + ']').parent().parent().find('span.total').text((parseFloat(target) * parseFloat(6.5)).toFixed(2));
                         } else if (target < 20.1) {
                             $('.prescriptionQuantity[data-id=' + pid + ']').parent().parent().find('span.total').text((parseFloat(target) * parseFloat(6)).toFixed(2));
                         } else {
                             $('.prescriptionQuantity[data-id=' + pid + ']').parent().parent().find('span.total').text((parseFloat(target) * parseFloat(5)).toFixed(2));
                         }
                     } else {
                         $('.prescriptionQuantity[data-id=' + pid + ']').parent().parent().find('span.total').text(price);
                     }

                     updatePrescriptionTotals();
                    }, 500);
                });
            }
        }
}

function updatePrescriptionTotals() {
    total = 0;

    $('.prescriptionQuantity').each(function() {
        var price = parseFloat($(this).find('option:selected').attr('value')).toFixed(2);
        total = parseFloat(total) + parseFloat(price);
    });

    $('#prescriptionTotalItems span').text(total.toFixed(2));

    grandTotal = total;

    if ($('dt.prescriptionSignup').is(':visible')) {
        price = $('#priceSignup').text().replace('£','');
        grandTotal = parseFloat(grandTotal) + parseFloat(price);
    }
    if ($('dt.prescriptionConsult').is(':visible')) {
        price = $('#priceConsult').text().replace('£','');
        grandTotal = parseFloat(grandTotal) + parseFloat(price);
    }
    if ($('dt.prescriptionRepeat').is(':visible')) {
        price = $('#priceRepeat').text().replace('£','');
        grandTotal = parseFloat(grandTotal) + parseFloat(price);
    }

    grandTotal = parseFloat(grandTotal).toFixed(2);
    $('#prescriptionTotalGrand span').text(grandTotal);
    //alert(grandTotal);
}

function updatePrescriptionStats(scriptListAdd, qty) {
    scriptList += scriptListAdd;
    scriptTotal += qty;

    scriptCount++;

    if (scriptCount > 2) {
        $('#calculatorResults blockquote.warning').show();
    } else {
        $('#calculatorResults blockquote.warning').hide();
    }

    $('#calculator span').text(scriptCount + ' Prescription Items (In Development)');
    $('#calculatorResults table').html(scriptList);
}

calculatePrescription();

$('#calculator').hoverIntent(function() {
    $('#calculatorResults').show();
    $('.closeCalculator').show();
});

$('.closeCalculator').click(function() {
    $('#calculatorResults').slideUp(220, function() {
        $('.closeCalculator').hide();
    });
});

$('main').hover(function() {
    $('#calculatorResults').slideUp(220, function() {
        $('.closeCalculator').hide();
    });
});
function hideRow(el) {
    var id = $(el).parent().data('id');
    $(el).parent().hide();
    $("tr[data-id=" + id + "] .calcStrain").toggleClass('selected');
    localStorage.removeItem(id);
    calculatePrescription();
}

$('#prescriptionWipe').click(function() {
   localStorage.clear();
   calculatePrescription();
});

if (localStorage.getItem('prescriptionClinic')) {
    var idSelect = localStorage.getItem('prescriptionClinic');
    $('#prescriptionClinic option[id=' + idSelect + ']').attr('selected', 'selected');

    var image = $('#prescriptionClinic').find('option:selected').data('image');
    $('#prescriptionClinicLogo').attr('src',image);

    var priceSignup = $('#prescriptionClinic').find('option:selected').data('priceSignup');

    if (priceSignup > 0) {
        priceSignup = '£' + priceSignup;
    } else {
        priceSignup = 'Unknown';
    }

    $('#priceSignup').text(priceSignup);

    var priceConsult = $('#prescriptionClinic').find('option:selected').data('priceConsult');

    if (priceConsult > 0) {
        priceConsult = '£' + priceConsult;
    } else {
        priceConsult = 'Unknown';
    }

    $('#priceConsult').text(priceConsult);

    var priceRepeat = $('#prescriptionClinic').find('option:selected').data('priceRepeat');

    if (priceRepeat > 0) {
        priceRepeat = '£' + priceRepeat;
    } else {
        priceRepeat = '£0.00';
    }

    $('#priceRepeat').text(priceRepeat);
}

$('#prescriptionClinic').change(function() {
    var id = $(this).find('option:selected').attr('id');
    localStorage.setItem('prescriptionClinic', id);

    var image = $(this).find('option:selected').data('image');
    //alert(id + ' - development code');
    $('#prescriptionClinicLogo').attr('src',image);

    var priceSignup = $(this).find('option:selected').data('priceSignup');

    if (priceSignup > 0) {
        priceSignup = '£' + priceSignup;
    } else {
        priceSignup = 'Unknown';
    }

    $('#priceSignup').text(priceSignup);

    var priceConsult = $(this).find('option:selected').data('priceConsult');

    if (priceConsult > 0) {
        priceConsult = '£' + priceConsult;
    } else {
        priceConsult = 'Unknown';
    }

    $('#priceConsult').text(priceConsult);

    var priceRepeat = $(this).find('option:selected').data('priceRepeat');

    if (priceRepeat > 0) {
        priceRepeat = '£' + priceRepeat;
    } else {
        priceRepeat = '£0.00';
    }

    $('#priceRepeat').text(priceRepeat);
    updatePrescriptionTotals();
});

if (localStorage.getItem('prescriptionType')) {
    var idSelect = localStorage.getItem('prescriptionType');
    $('#prescriptionType option[value=' + idSelect + ']').attr('selected', 'selected');

    if (idSelect == 1) {
        $('.prescriptionSignup').show();
        $('.prescriptionConsult').hide();
        $('.prescriptionRepeat').hide();
    } else if (idSelect == 2) {
        $('.prescriptionSignup').hide();
        $('.prescriptionConsult').show();
        $('.prescriptionRepeat').hide();
    } else if (idSelect == 3) {
        $('.prescriptionSignup').hide();
        $('.prescriptionConsult').hide();
        $('.prescriptionRepeat').show();
    }
}

$('#prescriptionType').change(function() {
    var idSelect = $(this).find('option:selected').attr('value');
    localStorage.setItem('prescriptionType', idSelect);

    if (idSelect == 0) {
        $('.prescriptionSignup').hide();
        $('.prescriptionConsult').hide();
        $('.prescriptionRepeat').hide();
    } else if (idSelect == 1) {
        $('.prescriptionSignup').show();
        $('.prescriptionConsult').hide();
        $('.prescriptionRepeat').hide();
    } else if (idSelect == 2) {
        $('.prescriptionSignup').hide();
        $('.prescriptionConsult').show();
        $('.prescriptionRepeat').hide();
    } else if (idSelect == 3) {
        $('.prescriptionSignup').hide();
        $('.prescriptionConsult').hide();
        $('.prescriptionRepeat').show();
    }
    updatePrescriptionTotals();
});

if (localStorage.getItem('prescriptionP21')) {
    let P21 = localStorage.getItem('prescriptionP21');
    $('#prescriptionP21 option[value=' + P21 + ']').attr('selected', 'selected');
}

$('#prescriptionP21').change(function() {
    P21 = $(this).find('option:selected').attr('value');
    localStorage.setItem('prescriptionP21', P21);
    calculatePrescription();
    setTimeout(function() { updatePrescriptionTotals(); }, 300);
});

$('.toggleMore').clickToggle(function() {
    $(this).parent().siblings('.more').show();
    $(this).html('&#x21b1; Hide More');
}, function() {
    $(this).parent().siblings('.more').hide();
    $(this).html('&#x21b3; Show More');
},);

$('.quoteClose').click(function() {
    $(this).parent().parent('blockquote').hide();
});

$('.toggleUK').click(function() {
    if ($('.toggleUK').is(':checked')) {
        $("#countryEN").prop("checked", true);
        $("#countrySC").prop("checked", true);
        $("#countryWA").prop("checked", true);
        $("#countryNI").prop("checked", true);
        $("table tr.en").show();
        $("table tr.en + tr + tr.notes").show();
        $("table tr.sc").show();
        $("table tr.sc + tr + tr.notes").show();
        $("table tr.wa").show();
        $("table tr.wa + tr + tr.notes").show();
        $("table tr.ni").show();
        $("table tr.ni + tr + tr.notes").show();
    } else {
        $("#countryEN").prop("checked", false);
        $("#countrySC").prop("checked", false);
        $("#countryWA").prop("checked", false);
        $("#countryNI").prop("checked", false);
        $("table tr.en").hide();
        $("table tr.en + tr + tr.notes").hide();
        $("table tr.sc").hide();
        $("table tr.sc + tr + tr.notes").hide();
        $("table tr.wa").hide();
        $("table tr.wa + tr + tr.notes").hide();
        $("table tr.ni").hide();
        $("table tr.ni + tr + tr.notes").hide();
    }
});

$('.toggleCI').click(function() {
    if ($('.toggleCI').is(':checked')) {
        $("#countryGG").prop("checked", true);
        $("#countryJE").prop("checked", true); 
        $("table tr.je").show();
        $("table tr.je + tr + tr.notes").show();
        $("table tr.gg").show();
        $("table tr.gg + tr + tr.notes").show();
    } else {
        $("#countryGG").prop("checked", false);
        $("#countryJE").prop("checked", false); 
        $("table tr.je").hide();
        $("table tr.je + tr + tr.notes").hide();
        $("table tr.gg").hide();
        $("table tr.gg + tr + tr.notes").hide();
    }
});

$('.filterP21').click(function() {
    if ($('.filterP21').is(':checked')) {
        $("table tbody tr").hide();
        $("table tbody tr.P21").show();
        $("table tbody tr.P21 + tr + tr.notes").show();
        $(".toggleUK").prop("disabled", true).css('opacity', 0.6);
        $(".toggleCI").prop("disabled", true).css('opacity', 0.6);
        $(".countryEN").prop("disabled", true).css('opacity', 0.6);
        $(".countrySC").prop("disabled", true).css('opacity', 0.6);
        $(".countryWA").prop("disabled", true).css('opacity', 0.6);
        $(".countryNI").prop("disabled", true).css('opacity', 0.6);
        $(".countryGG").prop("disabled", true).css('opacity', 0.6);
        $(".countryJE").prop("disabled", true).css('opacity', 0.6);
        $(".countryIM").prop("disabled", true).css('opacity', 0.6);

    } else {
        $("table tbody tr").show();
        $("table tbody tr.P21 + tr + tr.notes").hide();   
        $(".toggleUK").prop("disabled", false).css('opacity', 1);
        $(".toggleCI").prop("disabled", false).css('opacity', 1);
        $(".countryEN").prop("disabled", false).css('opacity', 1);
        $(".countrySC").prop("disabled", false).css('opacity', 1);
        $(".countryWA").prop("disabled", false).css('opacity', 1);
        $(".countryNI").prop("disabled", false).css('opacity', 1);
        $(".countryGG").prop("disabled", false).css('opacity', 1);
        $(".countryJE").prop("disabled", false).css('opacity', 1);
        $(".countryIM").prop("disabled", false).css('opacity', 1);
    }
});

$('.countryEN').click(function() {
    if ($('.countryEN').is(':checked')) {
        $("table tr.en").show();
        $("table tr.en + tr + tr.notes").show();   
    } else {
        $("table tr.en").each(function() {
            $(this).hide();
       });

        $("table tr.en + tr + tr.notes").hide();  
    }
});

$('.countrySC').click(function() {
    if ($('.countrySC').is(':checked')) {
        $("table tr.sc").show();
        $("table tr.sc + tr + tr.notes").show();   
    } else {
        $("table tr.sc").hide();
        $("table tr.sc + tr + tr.notes").hide();  
    }
});

$('.countryWA').click(function() {
    if ($('.countryWA').is(':checked')) {
        $("table tr.wa").show();
        $("table tr.wa + tr + tr.notes").show();   
    } else {
        $("table tr.wa").hide();
        $("table tr.wa + tr + tr.notes").hide();  
    }
});

$('.countryNI').click(function() {
    if ($('.countryNI').is(':checked')) {
        $("table tr.ni").show();
        $("table tr.ni + tr + tr.notes").show();   
    } else {
        $("table tr.ni").hide();
        $("table tr.ni + tr + tr.notes").hide();  
    }
});

$('.countryJE').click(function() {
    if ($('.countryJE').is(':checked')) {
        $("table tr.je").show();
        $("table tr.je + tr + tr.notes").show();   
    } else {
        $("table tr.je").hide();
        $("table tr.je + tr + tr.notes").hide();  
    }
});

$('.countryGG').click(function() {
    if ($('.countryGG').is(':checked')) {
        $("table tr.gg").show();
        $("table tr.gg + tr + tr.notes").show();   
    } else {
        $("table tr.gg").hide();
        $("table tr.gg + tr + tr.notes").hide();  
    }
});

$('.countryIM').click(function() {
    if ($('.countryIM').is(':checked')) {
        $("table tr.im").show();
        $("table tr.im + tr + tr.notes").show();   
    } else {
        $("table tr.im").hide();
        $("table tr.im + tr + tr.notes").hide();  
    }
});

        jQuery(document).ready(function($) {
            $('dl.site-stats dd span').counterUp({
                delay: 10,
                time: 170
            });
        });
$('.review-stars').hover(function() {
    $(this).addClass('gold');
}, function() {
    $(this).removeClass('gold');
});
$('.review-stars:not(".rated") > i:nth-of-type(1)').hover(function() {
   $(this).removeClass().addClass('fas fa-star-half-alt');
});
$('.review-stars:not(".rated") > i:nth-of-type(1) i').hover(function() {
   $(this).parent().removeClass().addClass('fas fa-star');
});
$('.review-stars:not(".rated") > i:nth-of-type(2)').hover(function() {
   $(this).removeClass().addClass('fas fa-star-half-alt');
   $(this).prev().removeClass().addClass('fas fa-star');
});
$('.review-stars:not(".rated") > i:nth-of-type(2) i').hover(function() {
   $(this).parent().removeClass().addClass('fas fa-star');
   $(this).parent().prev().removeClass().addClass('fas fa-star');
});
$('.review-stars:not(".rated") > i:nth-of-type(3)').hover(function() {
   $(this).removeClass().addClass('fas fa-star-half-alt');
   $(this).prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star');
});
$('.review-stars:not(".rated") > i:nth-of-type(3) i').hover(function() {
   $(this).parent().removeClass().addClass('fas fa-star');
   $(this).parent().prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star');
});
$('.review-stars:not(".rated") > i:nth-of-type(4)').hover(function() {
   $(this).removeClass().addClass('fas fa-star-half-alt');
   $(this).prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star');
});
$('.review-stars:not(".rated") > i:nth-of-type(4) i').hover(function() {
   $(this).parent().removeClass().addClass('fas fa-star');
   $(this).parent().prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star');
});
$('.review-stars:not(".rated") > i:nth-of-type(5)').hover(function() {
   $(this).removeClass().addClass('fas fa-star-half-alt');
   $(this).prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star');
});
$('.review-stars:not(".rated") > i:nth-of-type(5) i').hover(function() {
   $(this).parent().removeClass().addClass('fas fa-star');
   $(this).parent().prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star').prev().removeClass().addClass('fas fa-star');
});
$('.review-stars:not(".rated")').mouseout(function() {
    $('> i', this).removeClass().addClass('far fa-star');
});
 
$('.review-stars > i').click(function() {
    if (!$(this).parent('i').length > 0) {
        var id = 'r' + $(this).parent().data('id');
        var rating = $(this).data('rating');

        if (typeof(Storage) !== "undefined") {
            const data = rating;
            alert('Rated ' + JSON.stringify(data) + ' on your device.' );
            localStorage.setItem(id, JSON.stringify(data));
            updateRating('r' + $(this).parent().data('id'),$(this).data('rating'));
        }
    }
});

$('.review-stars > i > i').click(function(e) {
    e.stopPropagation();
    var id = 'r' + $(this).parent().parent().data('id');
    var rating = $(this).data('rating');

    if (typeof(Storage) !== "undefined") {
        const data = rating;
        alert('Rated ' + JSON.stringify(data) + ' on your device.' );
        localStorage.setItem(id, JSON.stringify(data));
        updateRating('r' + $(this).parent().parent().data('id'),$(this).data('rating'));
    }
});

$('.review-stars').each(function() {
    if (localStorage.getItem('r' + $(this).data('id'))) {
        updateRating('r' + $(this).data('id'),localStorage.getItem('r' + $(this).data('id')));
    }    
});

function updateRating(id, rating) {  
    if (rating == 0) {
        pHtml = '<i class="far fa-star" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="far fa-star" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="far fa-star" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="far fa-star" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="far fa-star" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    } else if (rating == 0.5) {
        pHtml = '<i class="fas fa-star-half-alt" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="far fa-star" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="far fa-star" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="far fa-star" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="far fa-star" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    } else if (rating == 1) {
        pHtml = '<i class="fas fa-star" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="far fa-star" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="far fa-star" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="far fa-star" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="far fa-star" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    } else if (rating == 1.5) {
        pHtml = '<i class="fas fa-star" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="fas fa-star-half-alt" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="far fa-star" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="far fa-star" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="far fa-star" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    } else if (rating == 2) {
        pHtml = '<i class="fas fa-star" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="fas fa-star" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="far fa-star" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="far fa-star" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="far fa-star" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    } else if (rating == 2.5) {
        pHtml = '<i class="fas fa-star" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="fas fa-star" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="fas fa-star-half-alt" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="far fa-star" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="far fa-star" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    } else if (rating == 3) {
        pHtml = '<i class="fas fa-star" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="fas fa-star" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="fas fa-star" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="far fa-star" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="far fa-star" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    } else if (rating == 3.5) {
        pHtml = '<i class="fas fa-star" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="fas fa-star" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="fas fa-star" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="fas fa-star-half-alt" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="far fa-star" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    } else if (rating == 4) {
        pHtml = '<i class="fas fa-star" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="fas fa-star" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="fas fa-star" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="fas fa-star" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="far fa-star" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    } else if (rating == 4.5) {
        pHtml = '<i class="fas fa-star" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="fas fa-star" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="fas fa-star" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="fas fa-star" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="fas fa-star-half-alt" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    } else if (rating == 5) {
        pHtml = '<i class="fas fa-star" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="fas fa-star" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="fas fa-star" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="fas fa-star" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="fas fa-star" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    }

    if (pHtml) {
        // alert('.review-stars[data-id="' + id.replace('r','') + '"]');
        if ($('.review-stars[data-id="' + id.replace('r','') + '"]').hasClass('large')) {
             pHtml += '<span style="font-size:1rem;line-height:1rem"> - Your Saved Rating</span>';
        }
        $('.review-stars[data-id="' + id.replace('r','') + '"]').addClass('gold').addClass('rated').html(pHtml).next('i.fa-times').show();
    }
}

function clearRating(id) {
    localStorage.removeItem('r' + id);
    alert('Rating removed, please refresh page to rate again.');
    pHtml = '<i class="far fa-star" title="Rate 0.5/5" data-rating="0.5"><i title="Rate 1/5" data-rating="1"></i></i><i class="far fa-star" title="Rate 1.5/5" data-rating="1.5"><i title="Rate 2/5" data-rating="2"></i></i><i class="far fa-star" title="Rate 2.5/5" data-rating="2.5"><i title="Rate 3/5" data-rating="3"></i></i><i class="far fa-star" title="Rate 3.5/5" data-rating="3.5"><i title="Rate 4/5" data-rating="4"></i></i><i class="far fa-star" title="Rate 4.5/5" data-rating="4.5"><i title="Rate 5/5" data-rating="5"></i></i>';
    $('.review-stars[data-id="' + id + '"]').removeClass('gold').removeClass('rated').html(pHtml).next('i.fa-times').hide();
}

/*!
 * Lightbox v2.11.2
 * by Lokesh Dhakar
 *
 * More info:
 * http://lokeshdhakar.com/projects/lightbox2/
 *
 * Copyright Lokesh Dhakar
 * Released under the MIT license
 * https://github.com/lokesh/lightbox2/blob/master/LICENSE
 *
 * @preserve
 */

// Uses Node, AMD or browser globals to create a module.
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory(require('jquery'));
    } else {
        // Browser globals (root is window)
        root.lightbox = factory(root.jQuery);
    }
}(this, function ($) {

  function Lightbox(options) {
    this.album = [];
    this.currentImageIndex = void 0;
    this.init();

    // options
    this.options = $.extend({}, this.constructor.defaults);
    this.option(options);
  }

  // Descriptions of all options available on the demo site:
  // http://lokeshdhakar.com/projects/lightbox2/index.html#options
  Lightbox.defaults = {
    albumLabel: 'Image %1 of %2',
    alwaysShowNavOnTouchDevices: false,
    fadeDuration: 600,
    fitImagesInViewport: true,
    imageFadeDuration: 600,
    // maxWidth: 800,
    // maxHeight: 600,
    positionFromTop: 50,
    resizeDuration: 700,
    showImageNumberLabel: true,
    wrapAround: false,
    disableScrolling: false,
    /*
    Sanitize Title
    If the caption data is trusted, for example you are hardcoding it in, then leave this to false.
    This will free you to add html tags, such as links, in the caption.

    If the caption data is user submitted or from some other untrusted source, then set this to true
    to prevent xss and other injection attacks.
     */
    sanitizeTitle: false
  };

  Lightbox.prototype.option = function(options) {
    $.extend(this.options, options);
  };

  Lightbox.prototype.imageCountLabel = function(currentImageNum, totalImages) {
    return this.options.albumLabel.replace(/%1/g, currentImageNum).replace(/%2/g, totalImages);
  };

  Lightbox.prototype.init = function() {
    var self = this;
    // Both enable and build methods require the body tag to be in the DOM.
    $(document).ready(function() {
      self.enable();
      self.build();
    });
  };

  // Loop through anchors and areamaps looking for either data-lightbox attributes or rel attributes
  // that contain 'lightbox'. When these are clicked, start lightbox.
  Lightbox.prototype.enable = function() {
    var self = this;
    $('body').on('click', 'a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]', function(event) {
      self.start($(event.currentTarget));
      return false;
    });
  };

  // Build html for the lightbox and the overlay.
  // Attach event handlers to the new DOM elements. click click click
  Lightbox.prototype.build = function() {
    if ($('#lightbox').length > 0) {
        return;
    }

    var self = this;

    // The two root notes generated, #lightboxOverlay and #lightbox are given
    // tabindex attrs so they are focusable. We attach our keyboard event
    // listeners to these two elements, and not the document. Clicking anywhere
    // while Lightbox is opened will keep the focus on or inside one of these
    // two elements.
    //
    // We do this so we can prevent propogation of the Esc keypress when
    // Lightbox is open. This prevents it from intefering with other components
    // on the page below.
    //
    // Github issue: https://github.com/lokesh/lightbox2/issues/663
    $('<div id="lightboxOverlay" tabindex="-1" class="lightboxOverlay"></div><div id="lightbox" tabindex="-1" class="lightbox"><div class="lb-outerContainer"><div class="lb-container"><img class="lb-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" alt=""/><div class="lb-nav"><a class="lb-prev" aria-label="Previous image"></a><a class="lb-next" aria-label="Next image"></a></div><div class="lb-loader"><a class="lb-cancel"></a></div></div></div><div class="lb-dataContainer"><div class="lb-data"><div class="lb-details"><span class="lb-caption"></span><span class="lb-number"></span></div><div class="lb-closeContainer"><a class="lb-close"></a></div></div></div></div>').appendTo($('body'));

    // Cache jQuery objects
    this.$lightbox       = $('#lightbox');
    this.$overlay        = $('#lightboxOverlay');
    this.$outerContainer = this.$lightbox.find('.lb-outerContainer');
    this.$container      = this.$lightbox.find('.lb-container');
    this.$image          = this.$lightbox.find('.lb-image');
    this.$nav            = this.$lightbox.find('.lb-nav');

    // Store css values for future lookup
    this.containerPadding = {
      top: parseInt(this.$container.css('padding-top'), 10),
      right: parseInt(this.$container.css('padding-right'), 10),
      bottom: parseInt(this.$container.css('padding-bottom'), 10),
      left: parseInt(this.$container.css('padding-left'), 10)
    };

    this.imageBorderWidth = {
      top: parseInt(this.$image.css('border-top-width'), 10),
      right: parseInt(this.$image.css('border-right-width'), 10),
      bottom: parseInt(this.$image.css('border-bottom-width'), 10),
      left: parseInt(this.$image.css('border-left-width'), 10)
    };

    // Attach event handlers to the newly minted DOM elements
    this.$overlay.hide().on('click', function() {
      self.end();
      return false;
    });

    this.$lightbox.hide().on('click', function(event) {
      if ($(event.target).attr('id') === 'lightbox') {
        self.end();
      }
    });

    this.$outerContainer.on('click', function(event) {
      if ($(event.target).attr('id') === 'lightbox') {
        self.end();
      }
      return false;
    });

    this.$lightbox.find('.lb-prev').on('click', function() {
      if (self.currentImageIndex === 0) {
        self.changeImage(self.album.length - 1);
      } else {
        self.changeImage(self.currentImageIndex - 1);
      }
      return false;
    });

    this.$lightbox.find('.lb-next').on('click', function() {
      if (self.currentImageIndex === self.album.length - 1) {
        self.changeImage(0);
      } else {
        self.changeImage(self.currentImageIndex + 1);
      }
      return false;
    });

    /*
      Show context menu for image on right-click

      There is a div containing the navigation that spans the entire image and lives above of it. If
      you right-click, you are right clicking this div and not the image. This prevents users from
      saving the image or using other context menu actions with the image.

      To fix this, when we detect the right mouse button is pressed down, but not yet clicked, we
      set pointer-events to none on the nav div. This is so that the upcoming right-click event on
      the next mouseup will bubble down to the image. Once the right-click/contextmenu event occurs
      we set the pointer events back to auto for the nav div so it can capture hover and left-click
      events as usual.
     */
    this.$nav.on('mousedown', function(event) {
      if (event.which === 3) {
        self.$nav.css('pointer-events', 'none');

        self.$lightbox.one('contextmenu', function() {
          setTimeout(function() {
              this.$nav.css('pointer-events', 'auto');
          }.bind(self), 0);
        });
      }
    });


    this.$lightbox.find('.lb-loader, .lb-close').on('click', function() {
      self.end();
      return false;
    });
  };

  // Show overlay and lightbox. If the image is part of a set, add siblings to album array.
  Lightbox.prototype.start = function($link) {
    var self    = this;
    var $window = $(window);

    $window.on('resize', $.proxy(this.sizeOverlay, this));

    this.sizeOverlay();

    this.album = [];
    var imageNumber = 0;

    function addToAlbum($link) {
      self.album.push({
        alt: $link.attr('data-alt'),
        link: $link.attr('href'),
        title: $link.attr('data-title') || $link.attr('title')
      });
    }

    // Support both data-lightbox attribute and rel attribute implementations
    var dataLightboxValue = $link.attr('data-lightbox');
    var $links;

    if (dataLightboxValue) {
      $links = $($link.prop('tagName') + '[data-lightbox="' + dataLightboxValue + '"]');
      for (var i = 0; i < $links.length; i = ++i) {
        addToAlbum($($links[i]));
        if ($links[i] === $link[0]) {
          imageNumber = i;
        }
      }
    } else {
      if ($link.attr('rel') === 'lightbox') {
        // If image is not part of a set
        addToAlbum($link);
      } else {
        // If image is part of a set
        $links = $($link.prop('tagName') + '[rel="' + $link.attr('rel') + '"]');
        for (var j = 0; j < $links.length; j = ++j) {
          addToAlbum($($links[j]));
          if ($links[j] === $link[0]) {
            imageNumber = j;
          }
        }
      }
    }

    // Position Lightbox
    var top  = $window.scrollTop() + this.options.positionFromTop;
    var left = $window.scrollLeft();
    this.$lightbox.css({
      top: top + 'px',
      left: left + 'px'
    }).fadeIn(this.options.fadeDuration);

    // Disable scrolling of the page while open
    if (this.options.disableScrolling) {
      $('body').addClass('lb-disable-scrolling');
    }

    this.changeImage(imageNumber);
  };

  // Hide most UI elements in preparation for the animated resizing of the lightbox.
  Lightbox.prototype.changeImage = function(imageNumber) {
    var self = this;
    var filename = this.album[imageNumber].link;
    var filetype = filename.split('.').slice(-1)[0];
    var $image = this.$lightbox.find('.lb-image');

    // Disable keyboard nav during transitions
    this.disableKeyboardNav();

    // Show loading state
    this.$overlay.fadeIn(this.options.fadeDuration);
    $('.lb-loader').fadeIn('slow');
    this.$lightbox.find('.lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption').hide();
    this.$outerContainer.addClass('animating');

    // When image to show is preloaded, we send the width and height to sizeContainer()
    var preloader = new Image();
    preloader.onload = function() {
      var $preloader;
      var imageHeight;
      var imageWidth;
      var maxImageHeight;
      var maxImageWidth;
      var windowHeight;
      var windowWidth;

      $image.attr({
        'alt': self.album[imageNumber].alt,
        'src': filename
      });

      $preloader = $(preloader);

      $image.width(preloader.width);
      $image.height(preloader.height);
      windowWidth = $(window).width();
      windowHeight = $(window).height();

      // Calculate the max image dimensions for the current viewport.
      // Take into account the border around the image and an additional 10px gutter on each side.
      maxImageWidth  = windowWidth - self.containerPadding.left - self.containerPadding.right - self.imageBorderWidth.left - self.imageBorderWidth.right - 20;
      maxImageHeight = windowHeight - self.containerPadding.top - self.containerPadding.bottom - self.imageBorderWidth.top - self.imageBorderWidth.bottom - self.options.positionFromTop - 70;

      /*
      Since many SVGs have small intrinsic dimensions, but they support scaling
      up without quality loss because of their vector format, max out their
      size.
      */
      if (filetype === 'svg') {
        $image.width(maxImageWidth);
        $image.height(maxImageHeight);
      }

      // Fit image inside the viewport.
      if (self.options.fitImagesInViewport) {

        // Check if image size is larger then maxWidth|maxHeight in settings
        if (self.options.maxWidth && self.options.maxWidth < maxImageWidth) {
          maxImageWidth = self.options.maxWidth;
        }
        if (self.options.maxHeight && self.options.maxHeight < maxImageHeight) {
          maxImageHeight = self.options.maxHeight;
        }

      } else {
        maxImageWidth = self.options.maxWidth || preloader.width || maxImageWidth;
        maxImageHeight = self.options.maxHeight || preloader.height || maxImageHeight;
      }

      // Is the current image's width or height is greater than the maxImageWidth or maxImageHeight
      // option than we need to size down while maintaining the aspect ratio.
      if ((preloader.width > maxImageWidth) || (preloader.height > maxImageHeight)) {
        if ((preloader.width / maxImageWidth) > (preloader.height / maxImageHeight)) {
          imageWidth  = maxImageWidth;
          imageHeight = parseInt(preloader.height / (preloader.width / imageWidth), 10);
          $image.width(imageWidth);
          $image.height(imageHeight);
        } else {
          imageHeight = maxImageHeight;
          imageWidth = parseInt(preloader.width / (preloader.height / imageHeight), 10);
          $image.width(imageWidth);
          $image.height(imageHeight);
        }
      }
      self.sizeContainer($image.width(), $image.height());
    };

    // Preload image before showing
    preloader.src = this.album[imageNumber].link;
    this.currentImageIndex = imageNumber;
  };

  // Stretch overlay to fit the viewport
  Lightbox.prototype.sizeOverlay = function() {
    var self = this;
    /*
    We use a setTimeout 0 to pause JS execution and let the rendering catch-up.
    Why do this? If the `disableScrolling` option is set to true, a class is added to the body
    tag that disables scrolling and hides the scrollbar. We want to make sure the scrollbar is
    hidden before we measure the document width, as the presence of the scrollbar will affect the
    number.
    */
    setTimeout(function() {
      self.$overlay
        .width($(document).width())
        .height($(document).height());

    }, 0);
  };

  // Animate the size of the lightbox to fit the image we are showing
  // This method also shows the the image.
  Lightbox.prototype.sizeContainer = function(imageWidth, imageHeight) {
    var self = this;

    var oldWidth  = this.$outerContainer.outerWidth();
    var oldHeight = this.$outerContainer.outerHeight();
    var newWidth  = imageWidth + this.containerPadding.left + this.containerPadding.right + this.imageBorderWidth.left + this.imageBorderWidth.right;
    var newHeight = imageHeight + this.containerPadding.top + this.containerPadding.bottom + this.imageBorderWidth.top + this.imageBorderWidth.bottom;

    function postResize() {
      self.$lightbox.find('.lb-dataContainer').width(newWidth);
      self.$lightbox.find('.lb-prevLink').height(newHeight);
      self.$lightbox.find('.lb-nextLink').height(newHeight);

      // Set focus on one of the two root nodes so keyboard events are captured.
      self.$overlay.focus();

      self.showImage();
    }

    if (oldWidth !== newWidth || oldHeight !== newHeight) {
      this.$outerContainer.animate({
        width: newWidth,
        height: newHeight
      }, this.options.resizeDuration, 'swing', function() {
        postResize();
      });
    } else {
      postResize();
    }
  };

  // Display the image and its details and begin preload neighboring images.
  Lightbox.prototype.showImage = function() {
    this.$lightbox.find('.lb-loader').stop(true).hide();
    this.$lightbox.find('.lb-image').fadeIn(this.options.imageFadeDuration);

    this.updateNav();
    this.updateDetails();
    this.preloadNeighboringImages();
    this.enableKeyboardNav();
  };

  // Display previous and next navigation if appropriate.
  Lightbox.prototype.updateNav = function() {
    // Check to see if the browser supports touch events. If so, we take the conservative approach
    // and assume that mouse hover events are not supported and always show prev/next navigation
    // arrows in image sets.
    var alwaysShowNav = false;
    try {
      document.createEvent('TouchEvent');
      alwaysShowNav = (this.options.alwaysShowNavOnTouchDevices) ? true : false;
    } catch (e) {}

    this.$lightbox.find('.lb-nav').show();

    if (this.album.length > 1) {
      if (this.options.wrapAround) {
        if (alwaysShowNav) {
          this.$lightbox.find('.lb-prev, .lb-next').css('opacity', '1');
        }
        this.$lightbox.find('.lb-prev, .lb-next').show();
      } else {
        if (this.currentImageIndex > 0) {
          this.$lightbox.find('.lb-prev').show();
          if (alwaysShowNav) {
            this.$lightbox.find('.lb-prev').css('opacity', '1');
          }
        }
        if (this.currentImageIndex < this.album.length - 1) {
          this.$lightbox.find('.lb-next').show();
          if (alwaysShowNav) {
            this.$lightbox.find('.lb-next').css('opacity', '1');
          }
        }
      }
    }
  };

  // Display caption, image number, and closing button.
  Lightbox.prototype.updateDetails = function() {
    var self = this;

    // Enable anchor clicks in the injected caption html.
    // Thanks Nate Wright for the fix. @https://github.com/NateWr
    if (typeof this.album[this.currentImageIndex].title !== 'undefined' &&
      this.album[this.currentImageIndex].title !== '') {
      var $caption = this.$lightbox.find('.lb-caption');
      if (this.options.sanitizeTitle) {
        $caption.text(this.album[this.currentImageIndex].title);
      } else {
        $caption.html(this.album[this.currentImageIndex].title);
      }
      $caption.fadeIn('fast');
    }

    if (this.album.length > 1 && this.options.showImageNumberLabel) {
      var labelText = this.imageCountLabel(this.currentImageIndex + 1, this.album.length);
      this.$lightbox.find('.lb-number').text(labelText).fadeIn('fast');
    } else {
      this.$lightbox.find('.lb-number').hide();
    }

    this.$outerContainer.removeClass('animating');

    this.$lightbox.find('.lb-dataContainer').fadeIn(this.options.resizeDuration, function() {
      return self.sizeOverlay();
    });
  };

  // Preload previous and next images in set.
  Lightbox.prototype.preloadNeighboringImages = function() {
    if (this.album.length > this.currentImageIndex + 1) {
      var preloadNext = new Image();
      preloadNext.src = this.album[this.currentImageIndex + 1].link;
    }
    if (this.currentImageIndex > 0) {
      var preloadPrev = new Image();
      preloadPrev.src = this.album[this.currentImageIndex - 1].link;
    }
  };

  Lightbox.prototype.enableKeyboardNav = function() {
    this.$lightbox.on('keyup.keyboard', $.proxy(this.keyboardAction, this));
    this.$overlay.on('keyup.keyboard', $.proxy(this.keyboardAction, this));
  };

  Lightbox.prototype.disableKeyboardNav = function() {
    this.$lightbox.off('.keyboard');
    this.$overlay.off('.keyboard');
  };

  Lightbox.prototype.keyboardAction = function(event) {
    var KEYCODE_ESC        = 27;
    var KEYCODE_LEFTARROW  = 37;
    var KEYCODE_RIGHTARROW = 39;

    var keycode = event.keyCode;
    if (keycode === KEYCODE_ESC) {
      // Prevent bubbling so as to not affect other components on the page.
      event.stopPropagation();
      this.end();
    } else if (keycode === KEYCODE_LEFTARROW) {
      if (this.currentImageIndex !== 0) {
        this.changeImage(this.currentImageIndex - 1);
      } else if (this.options.wrapAround && this.album.length > 1) {
        this.changeImage(this.album.length - 1);
      }
    } else if (keycode === KEYCODE_RIGHTARROW) {
      if (this.currentImageIndex !== this.album.length - 1) {
        this.changeImage(this.currentImageIndex + 1);
      } else if (this.options.wrapAround && this.album.length > 1) {
        this.changeImage(0);
      }
    }
  };

  // Closing time. :-(
  Lightbox.prototype.end = function() {
    this.disableKeyboardNav();
    $(window).off('resize', this.sizeOverlay);
    this.$lightbox.fadeOut(this.options.fadeDuration);
    this.$overlay.fadeOut(this.options.fadeDuration);

    if (this.options.disableScrolling) {
      $('body').removeClass('lb-disable-scrolling');
    }
  };

  return new Lightbox();
}));

/* 
 * overlay.js v1.1.0
 * Copyright 2014 Joah Gerstenberg (www.joahg.com)
 */
!function(a){a.fn.overlay=function(){overlay=a(".overlay"),overlay.ready(function(){overlay.on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",function(){a(this).hasClass("shown")||a(this).css("visibility","hidden")}),overlay.on("show",function(){return a(this).css("visibility","visible"),a(this).addClass("shown"),!0}),overlay.on("hide",function(){return a(this).removeClass("shown"),!0}),overlay.on("click",function(b){return b.target.className===a(this).attr("class")?a(this).trigger("hide"):!1}),a('a[data-overlay-trigger=""]').on("click",function(){overlay.trigger("show")}),a('a[data-overlay-trigger]:not([data-overlay-trigger=""])').on("click",function(){console.log(a(".overlay#"+a(this).attr("data-overlay-trigger"))),a(".overlay#"+a(this).attr("data-overlay-trigger")).trigger("show")})})}}(jQuery);
/*! lazysizes - v5.3.2 */

!function(e){var t=function(u,D,f){"use strict";var k,H;if(function(){var e;var t={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",errorClass:"lazyerror",autosizesClass:"lazyautosizes",fastLoadedClass:"ls-is-cached",iframeLoadMode:0,srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:true,expFactor:1.5,hFac:.8,loadMode:2,loadHidden:true,ricTimeout:0,throttleDelay:125};H=u.lazySizesConfig||u.lazysizesConfig||{};for(e in t){if(!(e in H)){H[e]=t[e]}}}(),!D||!D.getElementsByClassName){return{init:function(){},cfg:H,noSupport:true}}var O=D.documentElement,i=u.HTMLPictureElement,P="addEventListener",$="getAttribute",q=u[P].bind(u),I=u.setTimeout,U=u.requestAnimationFrame||I,o=u.requestIdleCallback,j=/^picture$/i,r=["load","error","lazyincluded","_lazyloaded"],a={},G=Array.prototype.forEach,J=function(e,t){if(!a[t]){a[t]=new RegExp("(\\s|^)"+t+"(\\s|$)")}return a[t].test(e[$]("class")||"")&&a[t]},K=function(e,t){if(!J(e,t)){e.setAttribute("class",(e[$]("class")||"").trim()+" "+t)}},Q=function(e,t){var a;if(a=J(e,t)){e.setAttribute("class",(e[$]("class")||"").replace(a," "))}},V=function(t,a,e){var i=e?P:"removeEventListener";if(e){V(t,a)}r.forEach(function(e){t[i](e,a)})},X=function(e,t,a,i,r){var n=D.createEvent("Event");if(!a){a={}}a.instance=k;n.initEvent(t,!i,!r);n.detail=a;e.dispatchEvent(n);return n},Y=function(e,t){var a;if(!i&&(a=u.picturefill||H.pf)){if(t&&t.src&&!e[$]("srcset")){e.setAttribute("srcset",t.src)}a({reevaluate:true,elements:[e]})}else if(t&&t.src){e.src=t.src}},Z=function(e,t){return(getComputedStyle(e,null)||{})[t]},s=function(e,t,a){a=a||e.offsetWidth;while(a<H.minSize&&t&&!e._lazysizesWidth){a=t.offsetWidth;t=t.parentNode}return a},ee=function(){var a,i;var t=[];var r=[];var n=t;var s=function(){var e=n;n=t.length?r:t;a=true;i=false;while(e.length){e.shift()()}a=false};var e=function(e,t){if(a&&!t){e.apply(this,arguments)}else{n.push(e);if(!i){i=true;(D.hidden?I:U)(s)}}};e._lsFlush=s;return e}(),te=function(a,e){return e?function(){ee(a)}:function(){var e=this;var t=arguments;ee(function(){a.apply(e,t)})}},ae=function(e){var a;var i=0;var r=H.throttleDelay;var n=H.ricTimeout;var t=function(){a=false;i=f.now();e()};var s=o&&n>49?function(){o(t,{timeout:n});if(n!==H.ricTimeout){n=H.ricTimeout}}:te(function(){I(t)},true);return function(e){var t;if(e=e===true){n=33}if(a){return}a=true;t=r-(f.now()-i);if(t<0){t=0}if(e||t<9){s()}else{I(s,t)}}},ie=function(e){var t,a;var i=99;var r=function(){t=null;e()};var n=function(){var e=f.now()-a;if(e<i){I(n,i-e)}else{(o||r)(r)}};return function(){a=f.now();if(!t){t=I(n,i)}}},e=function(){var v,m,c,h,e;var y,z,g,p,C,b,A;var n=/^img$/i;var d=/^iframe$/i;var E="onscroll"in u&&!/(gle|ing)bot/.test(navigator.userAgent);var _=0;var w=0;var M=0;var N=-1;var L=function(e){M--;if(!e||M<0||!e.target){M=0}};var x=function(e){if(A==null){A=Z(D.body,"visibility")=="hidden"}return A||!(Z(e.parentNode,"visibility")=="hidden"&&Z(e,"visibility")=="hidden")};var W=function(e,t){var a;var i=e;var r=x(e);g-=t;b+=t;p-=t;C+=t;while(r&&(i=i.offsetParent)&&i!=D.body&&i!=O){r=(Z(i,"opacity")||1)>0;if(r&&Z(i,"overflow")!="visible"){a=i.getBoundingClientRect();r=C>a.left&&p<a.right&&b>a.top-1&&g<a.bottom+1}}return r};var t=function(){var e,t,a,i,r,n,s,o,l,u,f,c;var d=k.elements;if((h=H.loadMode)&&M<8&&(e=d.length)){t=0;N++;for(;t<e;t++){if(!d[t]||d[t]._lazyRace){continue}if(!E||k.prematureUnveil&&k.prematureUnveil(d[t])){R(d[t]);continue}if(!(o=d[t][$]("data-expand"))||!(n=o*1)){n=w}if(!u){u=!H.expand||H.expand<1?O.clientHeight>500&&O.clientWidth>500?500:370:H.expand;k._defEx=u;f=u*H.expFactor;c=H.hFac;A=null;if(w<f&&M<1&&N>2&&h>2&&!D.hidden){w=f;N=0}else if(h>1&&N>1&&M<6){w=u}else{w=_}}if(l!==n){y=innerWidth+n*c;z=innerHeight+n;s=n*-1;l=n}a=d[t].getBoundingClientRect();if((b=a.bottom)>=s&&(g=a.top)<=z&&(C=a.right)>=s*c&&(p=a.left)<=y&&(b||C||p||g)&&(H.loadHidden||x(d[t]))&&(m&&M<3&&!o&&(h<3||N<4)||W(d[t],n))){R(d[t]);r=true;if(M>9){break}}else if(!r&&m&&!i&&M<4&&N<4&&h>2&&(v[0]||H.preloadAfterLoad)&&(v[0]||!o&&(b||C||p||g||d[t][$](H.sizesAttr)!="auto"))){i=v[0]||d[t]}}if(i&&!r){R(i)}}};var a=ae(t);var S=function(e){var t=e.target;if(t._lazyCache){delete t._lazyCache;return}L(e);K(t,H.loadedClass);Q(t,H.loadingClass);V(t,B);X(t,"lazyloaded")};var i=te(S);var B=function(e){i({target:e.target})};var T=function(e,t){var a=e.getAttribute("data-load-mode")||H.iframeLoadMode;if(a==0){e.contentWindow.location.replace(t)}else if(a==1){e.src=t}};var F=function(e){var t;var a=e[$](H.srcsetAttr);if(t=H.customMedia[e[$]("data-media")||e[$]("media")]){e.setAttribute("media",t)}if(a){e.setAttribute("srcset",a)}};var s=te(function(t,e,a,i,r){var n,s,o,l,u,f;if(!(u=X(t,"lazybeforeunveil",e)).defaultPrevented){if(i){if(a){K(t,H.autosizesClass)}else{t.setAttribute("sizes",i)}}s=t[$](H.srcsetAttr);n=t[$](H.srcAttr);if(r){o=t.parentNode;l=o&&j.test(o.nodeName||"")}f=e.firesLoad||"src"in t&&(s||n||l);u={target:t};K(t,H.loadingClass);if(f){clearTimeout(c);c=I(L,2500);V(t,B,true)}if(l){G.call(o.getElementsByTagName("source"),F)}if(s){t.setAttribute("srcset",s)}else if(n&&!l){if(d.test(t.nodeName)){T(t,n)}else{t.src=n}}if(r&&(s||l)){Y(t,{src:n})}}if(t._lazyRace){delete t._lazyRace}Q(t,H.lazyClass);ee(function(){var e=t.complete&&t.naturalWidth>1;if(!f||e){if(e){K(t,H.fastLoadedClass)}S(u);t._lazyCache=true;I(function(){if("_lazyCache"in t){delete t._lazyCache}},9)}if(t.loading=="lazy"){M--}},true)});var R=function(e){if(e._lazyRace){return}var t;var a=n.test(e.nodeName);var i=a&&(e[$](H.sizesAttr)||e[$]("sizes"));var r=i=="auto";if((r||!m)&&a&&(e[$]("src")||e.srcset)&&!e.complete&&!J(e,H.errorClass)&&J(e,H.lazyClass)){return}t=X(e,"lazyunveilread").detail;if(r){re.updateElem(e,true,e.offsetWidth)}e._lazyRace=true;M++;s(e,t,r,i,a)};var r=ie(function(){H.loadMode=3;a()});var o=function(){if(H.loadMode==3){H.loadMode=2}r()};var l=function(){if(m){return}if(f.now()-e<999){I(l,999);return}m=true;H.loadMode=3;a();q("scroll",o,true)};return{_:function(){e=f.now();k.elements=D.getElementsByClassName(H.lazyClass);v=D.getElementsByClassName(H.lazyClass+" "+H.preloadClass);q("scroll",a,true);q("resize",a,true);q("pageshow",function(e){if(e.persisted){var t=D.querySelectorAll("."+H.loadingClass);if(t.length&&t.forEach){U(function(){t.forEach(function(e){if(e.complete){R(e)}})})}}});if(u.MutationObserver){new MutationObserver(a).observe(O,{childList:true,subtree:true,attributes:true})}else{O[P]("DOMNodeInserted",a,true);O[P]("DOMAttrModified",a,true);setInterval(a,999)}q("hashchange",a,true);["focus","mouseover","click","load","transitionend","animationend"].forEach(function(e){D[P](e,a,true)});if(/d$|^c/.test(D.readyState)){l()}else{q("load",l);D[P]("DOMContentLoaded",a);I(l,2e4)}if(k.elements.length){t();ee._lsFlush()}else{a()}},checkElems:a,unveil:R,_aLSL:o}}(),re=function(){var a;var n=te(function(e,t,a,i){var r,n,s;e._lazysizesWidth=i;i+="px";e.setAttribute("sizes",i);if(j.test(t.nodeName||"")){r=t.getElementsByTagName("source");for(n=0,s=r.length;n<s;n++){r[n].setAttribute("sizes",i)}}if(!a.detail.dataAttr){Y(e,a.detail)}});var i=function(e,t,a){var i;var r=e.parentNode;if(r){a=s(e,r,a);i=X(e,"lazybeforesizes",{width:a,dataAttr:!!t});if(!i.defaultPrevented){a=i.detail.width;if(a&&a!==e._lazysizesWidth){n(e,r,i,a)}}}};var e=function(){var e;var t=a.length;if(t){e=0;for(;e<t;e++){i(a[e])}}};var t=ie(e);return{_:function(){a=D.getElementsByClassName(H.autosizesClass);q("resize",t)},checkElems:t,updateElem:i}}(),t=function(){if(!t.i&&D.getElementsByClassName){t.i=true;re._();e._()}};return I(function(){H.init&&t()}),k={cfg:H,autoSizer:re,loader:e,init:t,uP:Y,aC:K,rC:Q,hC:J,fire:X,gW:s,rAF:ee}}(e,e.document,Date);e.lazySizes=t,"object"==typeof module&&module.exports&&(module.exports=t)}("undefined"!=typeof window?window:{});
/*!
 * Elevator.js
 *
*/

var Elevator = function(options) {
    "use strict";

    // Elements
    var body = null;

    // Scroll vars
    var animation = null;
    var duration = null; // ms
    var customDuration = false;
    var startTime = null;
    var startPosition = null;
    var endPosition = 0;
    var targetElement = null;
    var verticalPadding = null;
    var elevating = false;

    var startCallback;
    var mainAudio;
    var endAudio;
    var endCallback;

    var that = this;

    /**
     * Utils
     */

    // Thanks Mr Penner - http://robertpenner.com/easing/
    function easeInOutQuad(t, b, c, d) {
        t /= d / 2;
        if (t < 1) return c / 2 * t * t + b;
        t--;
        return -c / 2 * (t * (t - 2) - 1) + b;
    }

    function extendParameters(options, defaults) {
        for (var option in defaults) {
            var t =
                options[option] === undefined && typeof option !== "function";
            if (t) {
                options[option] = defaults[option];
            }
        }
        return options;
    }

    function getVerticalOffset(element) {
        var verticalOffset = 0;
        while (element) {
            verticalOffset += element.offsetTop || 0;
            element = element.offsetParent;
        }

        if (verticalPadding) {
            verticalOffset = verticalOffset - verticalPadding;
        }

        return verticalOffset;
    }

    /**
     * Main
     */

    // Time is passed through requestAnimationFrame, what a world!
    function animateLoop(time) {
        if (!startTime) {
            startTime = time;
        }

        var timeSoFar = time - startTime;
        var easedPosition = easeInOutQuad(
            timeSoFar,
            startPosition,
            endPosition - startPosition,
            duration
        );

        window.scrollTo(0, easedPosition);

        if (timeSoFar < duration) {
            animation = requestAnimationFrame(animateLoop);
        } else {
            animationFinished();
        }
    }

    // ELEVATE!

    this.elevate = function() {
        if (elevating) {
            return;
        }

        elevating = true;
        startPosition = document.documentElement.scrollTop || body.scrollTop;
        updateEndPosition();

        // No custom duration set, so we travel at pixels per millisecond. (0.75px per ms)
        if (!customDuration) {
            duration = Math.abs(endPosition - startPosition) * 1.5;
        }

        requestAnimationFrame(animateLoop);

        // Start music!
        if (mainAudio) {
            mainAudio.play();
        }

        if (startCallback) {
            startCallback();
        }
    };

    function browserMeetsRequirements() {
        return (
            window.requestAnimationFrame &&
            window.Audio &&
            window.addEventListener
        );
    }

    function resetPositions() {
        startTime = null;
        startPosition = null;
        elevating = false;
    }

    function updateEndPosition() {
        if (targetElement) {
            endPosition = getVerticalOffset(targetElement);
        }
    }

    function animationFinished() {
        resetPositions();

        // Stop music!
        if (mainAudio) {
            mainAudio.pause();
            mainAudio.currentTime = 0;
        }

        if (endAudio) {
            endAudio.play();
        }

        if (endCallback) {
            endCallback();
        }
    }

    function onWindowBlur() {
        // If animating, go straight to the top. And play no more music.
        if (elevating) {
            cancelAnimationFrame(animation);
            resetPositions();

            if (mainAudio) {
                mainAudio.pause();
                mainAudio.currentTime = 0;
            }

            updateEndPosition();
            window.scrollTo(0, endPosition);
        }
    }

    function bindElevateToElement(element) {
        if (element.addEventListener) {
            element.addEventListener("click", that.elevate, false);
        } else {
            // Older browsers
            element.attachEvent("onclick", function() {
                updateEndPosition();
                document.documentElement.scrollTop = endPosition;
                document.body.scrollTop = endPosition;
                window.scroll(0, endPosition);
            });
        }
    }

    function init(_options) {
		// Take the stairs instead
		if (!browserMeetsRequirements()) {
			return;
		}

        // Bind to element click event.
        body = document.body;

        var defaults = {
            duration: undefined,
            mainAudio: false,
            endAudio: false,
            preloadAudio: true,
            loopAudio: true,
            startCallback: null,
            endCallback: null
        };

        _options = extendParameters(_options, defaults);

        if (_options.element) {
            bindElevateToElement(_options.element);
        }

        if (_options.duration) {
            customDuration = true;
            duration = _options.duration;
        }

        if (_options.targetElement) {
            targetElement = _options.targetElement;
        }

        if (_options.verticalPadding) {
            verticalPadding = _options.verticalPadding;
        }

        window.addEventListener("blur", onWindowBlur, false);

        if (_options.mainAudio) {
            mainAudio = new Audio(_options.mainAudio);
            mainAudio.setAttribute("preload", _options.preloadAudio);
            mainAudio.setAttribute("loop", _options.loopAudio);
        }

        if (_options.endAudio) {
            endAudio = new Audio(_options.endAudio);
            endAudio.setAttribute("preload", "true");
        }

        if (_options.endCallback) {
            endCallback = _options.endCallback;
        }

        if (_options.startCallback) {
            startCallback = _options.startCallback;
        }
    }

    init(options);
};

if (typeof module !== "undefined" && module.exports) {
    module.exports = Elevator;
}

/* https://www.jqueryscript.net/menu/truncate-long-list.html */

(function($) {
  $.fn.cutList = function() {
    var defaults = {
      moreBtnTitle: 'More Items',
      showMoreOnHover: true,
      alwaysVisibleElem: undefined,
      resizeDelay: 50
    }
    
    var options = extend(defaults, arguments[0]);
    
    function extend(defaults, options ) {
      var extended = {};
      var prop;
      
      for (prop in defaults) {
        if (Object.prototype.hasOwnProperty.call(defaults, prop)) {
          extended[prop] = defaults[prop];
        }
      }
      for (prop in options) {
        if (Object.prototype.hasOwnProperty.call(options, prop)) {
          extended[prop] = options[prop];
        }
      }
  
      return extended;
    };
        
    return this.each(function() {
      var $this = $(this),
          $clone = $(this).clone(),
          limit,
          position,
          areaWidth,
          listWidth,
          alwaysVisibleIndex,
          resizeTimeout;

      setup($this);

      function resizeHandle () {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(function(){reset($this)}, options.resizeDelay);
      }

      function setup(obj) {
        if (!obj.find(".menuEllipsis__dropdown").length) {
          obj.append('<div style="display:none" class="menuEllipsis__elem menuEllipsis__dropdown"></div>')
            .find(".menuEllipsis__dropdown")
            .append('<div class="menuEllipsis__drop"></div>')
            .find(".menuEllipsis__drop")
            .append('<div class="menuEllipsis__drop-toggle">' + options.moreBtnTitle + '</div>')
            .append('<div class="menuEllipsis__more"><div class="menuEllipsis__more-content"></div></div>');
        }
  
        obj.addClass("menuEllipsis").children().each(function(index) {
          $(this).attr("data-index", index).addClass("menuEllipsis__elem");
        });
  
        limit = obj.find(".menuEllipsis__elem").length;
        index = limit - 1;
        
        alwaysVisibleIndex = obj.find(options.alwaysVisibleElem + ':first').index();
        
        create(obj);
        
        if (options.showMoreOnHover) {
          obj.find(".menuEllipsis__drop").hoverIntent(
          function(){
            $(this).parents(".menuEllipsis__dropdown").addClass("is-show");
            showMore($(this).parents(".menuEllipsis__dropdown").find(".menuEllipsis__more"));
          },
          function(){
            $(this).parents(".menuEllipsis__dropdown").removeClass("is-show").find(".menuEllipsis__more").hide().removeClass("is-top is-left");
          });
        }
        else {
          obj.find(".menuEllipsis__drop-toggle").on("click", function(){
            if ($(this).parents(".menuEllipsis__dropdown").is(".is-show")){
              $(this).parents(".menuEllipsis__dropdown").removeClass("is-show").find(".menuEllipsis__more").hide().removeClass("is-top is-left");
            }
            else {
              $(this).parents(".menuEllipsis__dropdown").addClass("is-show");
              showMore($(this).parents(".menuEllipsis__dropdown").find(".menuEllipsis__more"));
            }
          });
          
          $(document).on("click", function(event) {
            if ($(event.target).closest(".menuEllipsis__dropdown").length)
              return;
            
            $(".menuEllipsis__dropdown.is-show").removeClass("is-show").find(".menuEllipsis__more").hide().removeClass("is-top is-left");
          });
        }

        $(window).on('resize', resizeHandle);
      }
      
      function reset(obj) {
        position = limit;
  
        $.when(backToStartingPlace(obj)).done(function() {
          create(obj);
        });
      }
      
      function backToStartingPlace(obj) {
        var more_elems = obj.find(".menuEllipsis__more .menuEllipsis__elem");
        
        more_elems.each(function() {
          var elem_index = $(this).data("index");
          
          if (elem_index == 0)
            $(this).prependTo(obj);
          else
            $(this).insertAfter( obj.find('.menuEllipsis__elem[data-index="' + (elem_index - 1) + '"]'));
        });
      }

      function create(obj) {
        areaWidth = obj.innerWidth();
        listWidth = obj.find(".menuEllipsis__dropdown").outerWidth(true);
        
        var find_elems = '.menuEllipsis__elem:not(".menuEllipsis__dropdown")';
        
        if (alwaysVisibleIndex != -1) {
          listWidth += obj.find(options.alwaysVisibleElem + ':first').outerWidth(true);
          find_elems = '.menuEllipsis__elem:not(".menuEllipsis__dropdown,' + options.alwaysVisibleElem + ':first")';
        }
      
        obj.find(find_elems).each(function(index) {
          listWidth += $(this).outerWidth(true);

          if (listWidth >= areaWidth) {
            if (alwaysVisibleIndex != -1) {
              if (index > alwaysVisibleIndex)
                position = index + 1;
              else
                position = index;
            }
            else
              position = index;
                        
            move(obj, position);
            obj.addClass("with-more-items").find(".menuEllipsis__dropdown").show();
                        
            return false;
          } 
          else {
            obj.removeClass("with-more-items").find(".menuEllipsis__dropdown").hide();
          }
        });
      }

      function move(obj, position) {
        var find_elems = '.menuEllipsis__elem:not(".menuEllipsis__dropdown")';
        
        if (alwaysVisibleIndex != -1)
          find_elems = '.menuEllipsis__elem:not(".menuEllipsis__dropdown,' + options.alwaysVisibleElem + ':first")';
        
        for (x = position; x <= limit; x++) {
          obj.find(find_elems + '[data-index="' + x + '"]').appendTo(obj.find(".menuEllipsis__more-content"));
        }
        
        if (alwaysVisibleIndex != -1) {
          if (obj.find(".menuEllipsis__elem:first").is(options.alwaysVisibleElem)) {
            areaWidth = obj.innerWidth();
            listWidth = obj.find(".menuEllipsis__dropdown").outerWidth(true) + obj.find(options.alwaysVisibleElem + ':first').outerWidth(true);
            
            if (listWidth >= (areaWidth - 5)) { // Ax-ax-ax
              obj.find('.menuEllipsis__elem:not(".menuEllipsis__dropdown")[data-index="' + obj.find(options.alwaysVisibleElem + ':first').data("index") + '"]').appendTo(obj.find(".menuEllipsis__more-content"));
            } 
          }
        }
      }
      
      function showMore(moreBlock){
        var document_height = $(document).outerHeight(true);
          
        moreBlock.css("visibility", "hidden").show();   
            
        if ((moreBlock.offset().top + moreBlock.innerHeight()) > document_height)
          moreBlock.addClass("is-top");

        if (moreBlock.offset().left < 0)
          moreBlock.addClass("is-left");
        
        moreBlock.css("visibility", "visible");
      }

      $.fn.cutList.setup = function() {
        setup($this)
      }

      $.fn.cutList.destroy = function() {
        $this.html($clone.html())
        $(window).off('resize', resizeHandle);
      }
      
    });
  };
})($);

// Generated by CoffeeScript 1.6.2
/*
jQuery Waypoints - v2.0.3
Copyright (c) 2011-2013 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/jquery-waypoints/blob/master/licenses.txt
*/
(function(){var t=[].indexOf||function(t){for(var e=0,n=this.length;e<n;e++){if(e in this&&this[e]===t)return e}return-1},e=[].slice;(function(t,e){if(typeof define==="function"&&define.amd){return define("waypoints",["jquery"],function(n){return e(n,t)})}else{return e(t.jQuery,t)}})(this,function(n,r){var i,o,l,s,f,u,a,c,h,d,p,y,v,w,g,m;i=n(r);c=t.call(r,"ontouchstart")>=0;s={horizontal:{},vertical:{}};f=1;a={};u="waypoints-context-id";p="resize.waypoints";y="scroll.waypoints";v=1;w="waypoints-waypoint-ids";g="waypoint";m="waypoints";o=function(){function t(t){var e=this;this.$element=t;this.element=t[0];this.didResize=false;this.didScroll=false;this.id="context"+f++;this.oldScroll={x:t.scrollLeft(),y:t.scrollTop()};this.waypoints={horizontal:{},vertical:{}};t.data(u,this.id);a[this.id]=this;t.bind(y,function(){var t;if(!(e.didScroll||c)){e.didScroll=true;t=function(){e.doScroll();return e.didScroll=false};return r.setTimeout(t,n[m].settings.scrollThrottle)}});t.bind(p,function(){var t;if(!e.didResize){e.didResize=true;t=function(){n[m]("refresh");return e.didResize=false};return r.setTimeout(t,n[m].settings.resizeThrottle)}})}t.prototype.doScroll=function(){var t,e=this;t={horizontal:{newScroll:this.$element.scrollLeft(),oldScroll:this.oldScroll.x,forward:"right",backward:"left"},vertical:{newScroll:this.$element.scrollTop(),oldScroll:this.oldScroll.y,forward:"down",backward:"up"}};if(c&&(!t.vertical.oldScroll||!t.vertical.newScroll)){n[m]("refresh")}n.each(t,function(t,r){var i,o,l;l=[];o=r.newScroll>r.oldScroll;i=o?r.forward:r.backward;n.each(e.waypoints[t],function(t,e){var n,i;if(r.oldScroll<(n=e.offset)&&n<=r.newScroll){return l.push(e)}else if(r.newScroll<(i=e.offset)&&i<=r.oldScroll){return l.push(e)}});l.sort(function(t,e){return t.offset-e.offset});if(!o){l.reverse()}return n.each(l,function(t,e){if(e.options.continuous||t===l.length-1){return e.trigger([i])}})});return this.oldScroll={x:t.horizontal.newScroll,y:t.vertical.newScroll}};t.prototype.refresh=function(){var t,e,r,i=this;r=n.isWindow(this.element);e=this.$element.offset();this.doScroll();t={horizontal:{contextOffset:r?0:e.left,contextScroll:r?0:this.oldScroll.x,contextDimension:this.$element.width(),oldScroll:this.oldScroll.x,forward:"right",backward:"left",offsetProp:"left"},vertical:{contextOffset:r?0:e.top,contextScroll:r?0:this.oldScroll.y,contextDimension:r?n[m]("viewportHeight"):this.$element.height(),oldScroll:this.oldScroll.y,forward:"down",backward:"up",offsetProp:"top"}};return n.each(t,function(t,e){return n.each(i.waypoints[t],function(t,r){var i,o,l,s,f;i=r.options.offset;l=r.offset;o=n.isWindow(r.element)?0:r.$element.offset()[e.offsetProp];if(n.isFunction(i)){i=i.apply(r.element)}else if(typeof i==="string"){i=parseFloat(i);if(r.options.offset.indexOf("%")>-1){i=Math.ceil(e.contextDimension*i/100)}}r.offset=o-e.contextOffset+e.contextScroll-i;if(r.options.onlyOnScroll&&l!=null||!r.enabled){return}if(l!==null&&l<(s=e.oldScroll)&&s<=r.offset){return r.trigger([e.backward])}else if(l!==null&&l>(f=e.oldScroll)&&f>=r.offset){return r.trigger([e.forward])}else if(l===null&&e.oldScroll>=r.offset){return r.trigger([e.forward])}})})};t.prototype.checkEmpty=function(){if(n.isEmptyObject(this.waypoints.horizontal)&&n.isEmptyObject(this.waypoints.vertical)){this.$element.unbind([p,y].join(" "));return delete a[this.id]}};return t}();l=function(){function t(t,e,r){var i,o;r=n.extend({},n.fn[g].defaults,r);if(r.offset==="bottom-in-view"){r.offset=function(){var t;t=n[m]("viewportHeight");if(!n.isWindow(e.element)){t=e.$element.height()}return t-n(this).outerHeight()}}this.$element=t;this.element=t[0];this.axis=r.horizontal?"horizontal":"vertical";this.callback=r.handler;this.context=e;this.enabled=r.enabled;this.id="waypoints"+v++;this.offset=null;this.options=r;e.waypoints[this.axis][this.id]=this;s[this.axis][this.id]=this;i=(o=t.data(w))!=null?o:[];i.push(this.id);t.data(w,i)}t.prototype.trigger=function(t){if(!this.enabled){return}if(this.callback!=null){this.callback.apply(this.element,t)}if(this.options.triggerOnce){return this.destroy()}};t.prototype.disable=function(){return this.enabled=false};t.prototype.enable=function(){this.context.refresh();return this.enabled=true};t.prototype.destroy=function(){delete s[this.axis][this.id];delete this.context.waypoints[this.axis][this.id];return this.context.checkEmpty()};t.getWaypointsByElement=function(t){var e,r;r=n(t).data(w);if(!r){return[]}e=n.extend({},s.horizontal,s.vertical);return n.map(r,function(t){return e[t]})};return t}();d={init:function(t,e){var r;if(e==null){e={}}if((r=e.handler)==null){e.handler=t}this.each(function(){var t,r,i,s;t=n(this);i=(s=e.context)!=null?s:n.fn[g].defaults.context;if(!n.isWindow(i)){i=t.closest(i)}i=n(i);r=a[i.data(u)];if(!r){r=new o(i)}return new l(t,r,e)});n[m]("refresh");return this},disable:function(){return d._invoke(this,"disable")},enable:function(){return d._invoke(this,"enable")},destroy:function(){return d._invoke(this,"destroy")},prev:function(t,e){return d._traverse.call(this,t,e,function(t,e,n){if(e>0){return t.push(n[e-1])}})},next:function(t,e){return d._traverse.call(this,t,e,function(t,e,n){if(e<n.length-1){return t.push(n[e+1])}})},_traverse:function(t,e,i){var o,l;if(t==null){t="vertical"}if(e==null){e=r}l=h.aggregate(e);o=[];this.each(function(){var e;e=n.inArray(this,l[t]);return i(o,e,l[t])});return this.pushStack(o)},_invoke:function(t,e){t.each(function(){var t;t=l.getWaypointsByElement(this);return n.each(t,function(t,n){n[e]();return true})});return this}};n.fn[g]=function(){var t,r;r=arguments[0],t=2<=arguments.length?e.call(arguments,1):[];if(d[r]){return d[r].apply(this,t)}else if(n.isFunction(r)){return d.init.apply(this,arguments)}else if(n.isPlainObject(r)){return d.init.apply(this,[null,r])}else if(!r){return n.error("jQuery Waypoints needs a callback function or handler option.")}else{return n.error("The "+r+" method does not exist in jQuery Waypoints.")}};n.fn[g].defaults={context:r,continuous:true,enabled:true,horizontal:false,offset:0,triggerOnce:false};h={refresh:function(){return n.each(a,function(t,e){return e.refresh()})},viewportHeight:function(){var t;return(t=r.innerHeight)!=null?t:i.height()},aggregate:function(t){var e,r,i;e=s;if(t){e=(i=a[n(t).data(u)])!=null?i.waypoints:void 0}if(!e){return[]}r={horizontal:[],vertical:[]};n.each(r,function(t,i){n.each(e[t],function(t,e){return i.push(e)});i.sort(function(t,e){return t.offset-e.offset});r[t]=n.map(i,function(t){return t.element});return r[t]=n.unique(r[t])});return r},above:function(t){if(t==null){t=r}return h._filter(t,"vertical",function(t,e){return e.offset<=t.oldScroll.y})},below:function(t){if(t==null){t=r}return h._filter(t,"vertical",function(t,e){return e.offset>t.oldScroll.y})},left:function(t){if(t==null){t=r}return h._filter(t,"horizontal",function(t,e){return e.offset<=t.oldScroll.x})},right:function(t){if(t==null){t=r}return h._filter(t,"horizontal",function(t,e){return e.offset>t.oldScroll.x})},enable:function(){return h._invoke("enable")},disable:function(){return h._invoke("disable")},destroy:function(){return h._invoke("destroy")},extendFn:function(t,e){return d[t]=e},_invoke:function(t){var e;e=n.extend({},s.vertical,s.horizontal);return n.each(e,function(e,n){n[t]();return true})},_filter:function(t,e,r){var i,o;i=a[n(t).data(u)];if(!i){return[]}o=[];n.each(i.waypoints[e],function(t,e){if(r(i,e)){return o.push(e)}});o.sort(function(t,e){return t.offset-e.offset});return n.map(o,function(t){return t.element})}};n[m]=function(){var t,n;n=arguments[0],t=2<=arguments.length?e.call(arguments,1):[];if(h[n]){return h[n].apply(null,t)}else{return h.aggregate.call(null,n)}};n[m].settings={resizeThrottle:100,scrollThrottle:30};return i.load(function(){return n[m]("refresh")})})}).call(this);
/*!
* jquery.counterup.js 1.0
* Copyright 2013, Benjamin Intal http://gambit.ph @bfintal
*/(function(e){"use strict";e.fn.counterUp=function(t){var n=e.extend({time:400,delay:10},t);return this.each(function(){var t=e(this),r=n,i=function(){var e=[],n=r.time/r.delay,i=t.text(),s=/[0-9]+,[0-9]+/.test(i);i=i.replace(/,/g,"");var o=/^[0-9]+$/.test(i),u=/^[0-9]+\.[0-9]+$/.test(i),a=u?(i.split(".")[1]||[]).length:0;for(var f=n;f>=1;f--){var l=parseInt(i/n*f);u&&(l=parseFloat(i/n*f).toFixed(a));if(s)while(/(\d+)(\d{3})/.test(l.toString()))l=l.toString().replace(/(\d+)(\d{3})/,"$1,$2");e.unshift(l)}t.data("counterup-nums",e);t.text("0");var c=function(){t.text(t.data("counterup-nums").shift());if(t.data("counterup-nums").length)setTimeout(t.data("counterup-func"),r.delay);else{delete t.data("counterup-nums");t.data("counterup-nums",null);t.data("counterup-func",null)}};t.data("counterup-func",c);setTimeout(t.data("counterup-func"),r.delay)};t.waypoint(i,{offset:"100%",triggerOnce:!0})})}})(jQuery);