/* Minification failed. Returning unminified contents.
(1740,15-16): run-time error JS1010: Expected identifier: .
(1740,15-16): run-time error JS1195: Expected expression: .
(5265,11-12): run-time error JS1010: Expected identifier: .
(5265,11-12): run-time error JS1195: Expected expression: .
(5407,11-12): run-time error JS1010: Expected identifier: .
(5407,11-12): run-time error JS1195: Expected expression: .
(5520,11-12): run-time error JS1010: Expected identifier: .
(5520,11-12): run-time error JS1195: Expected expression: .
(5729,11-12): run-time error JS1010: Expected identifier: .
(5729,11-12): run-time error JS1195: Expected expression: .
(5786,11-12): run-time error JS1010: Expected identifier: .
(5786,11-12): run-time error JS1195: Expected expression: .
(6020,11-12): run-time error JS1010: Expected identifier: .
(6020,11-12): run-time error JS1195: Expected expression: .
(6119,11-12): run-time error JS1010: Expected identifier: .
(6119,11-12): run-time error JS1195: Expected expression: .
(6197,11-12): run-time error JS1010: Expected identifier: .
(6197,11-12): run-time error JS1195: Expected expression: .
(6406,11-12): run-time error JS1010: Expected identifier: .
(6406,11-12): run-time error JS1195: Expected expression: .
(7344,11-12): run-time error JS1010: Expected identifier: .
(7344,11-12): run-time error JS1195: Expected expression: .
(7647,11-12): run-time error JS1010: Expected identifier: .
(7647,11-12): run-time error JS1195: Expected expression: .
(7924,11-12): run-time error JS1010: Expected identifier: .
(7924,11-12): run-time error JS1195: Expected expression: .
(8322,11-12): run-time error JS1010: Expected identifier: .
(8322,11-12): run-time error JS1195: Expected expression: .
(8533,11-12): run-time error JS1010: Expected identifier: .
(8533,11-12): run-time error JS1195: Expected expression: .
(8721,11-12): run-time error JS1010: Expected identifier: .
(8721,11-12): run-time error JS1195: Expected expression: .
(8911,11-12): run-time error JS1010: Expected identifier: .
(8911,11-12): run-time error JS1195: Expected expression: .
(9073,11-12): run-time error JS1010: Expected identifier: .
(9073,11-12): run-time error JS1195: Expected expression: .
(9222,11-12): run-time error JS1010: Expected identifier: .
(9222,11-12): run-time error JS1195: Expected expression: .
(9255,11-12): run-time error JS1010: Expected identifier: .
(9255,11-12): run-time error JS1195: Expected expression: .
(9410,11-12): run-time error JS1010: Expected identifier: .
(9410,11-12): run-time error JS1195: Expected expression: .
(9788,11-12): run-time error JS1010: Expected identifier: .
(9788,11-12): run-time error JS1195: Expected expression: .
 */
/*! jQuery Validation Plugin - v1.19.0 - 11/28/2018
 * https://jqueryvalidation.org/
 * Copyright (c) 2018 Jörn Zaefferer; Licensed MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a){a.extend(a.fn,{validate:function(b){if(!this.length)return void(b&&b.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing."));var c=a.data(this[0],"validator");return c?c:(this.attr("novalidate","novalidate"),c=new a.validator(b,this[0]),a.data(this[0],"validator",c),c.settings.onsubmit&&(this.on("click.validate",":submit",function(b){c.submitButton=b.currentTarget,a(this).hasClass("cancel")&&(c.cancelSubmit=!0),void 0!==a(this).attr("formnovalidate")&&(c.cancelSubmit=!0)}),this.on("submit.validate",function(b){function d(){var d,e;return c.submitButton&&(c.settings.submitHandler||c.formSubmitted)&&(d=a("<input type='hidden'/>").attr("name",c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)),!(c.settings.submitHandler&&!c.settings.debug)||(e=c.settings.submitHandler.call(c,c.currentForm,b),d&&d.remove(),void 0!==e&&e)}return c.settings.debug&&b.preventDefault(),c.cancelSubmit?(c.cancelSubmit=!1,d()):c.form()?c.pendingRequest?(c.formSubmitted=!0,!1):d():(c.focusInvalid(),!1)})),c)},valid:function(){var b,c,d;return a(this[0]).is("form")?b=this.validate().form():(d=[],b=!0,c=a(this[0].form).validate(),this.each(function(){b=c.element(this)&&b,b||(d=d.concat(c.errorList))}),c.errorList=d),b},rules:function(b,c){var d,e,f,g,h,i,j=this[0],k="undefined"!=typeof this.attr("contenteditable")&&"false"!==this.attr("contenteditable");if(null!=j&&(!j.form&&k&&(j.form=this.closest("form")[0],j.name=this.attr("name")),null!=j.form)){if(b)switch(d=a.data(j.form,"validator").settings,e=d.rules,f=a.validator.staticRules(j),b){case"add":a.extend(f,a.validator.normalizeRule(c)),delete f.messages,e[j.name]=f,c.messages&&(d.messages[j.name]=a.extend(d.messages[j.name],c.messages));break;case"remove":return c?(i={},a.each(c.split(/\s/),function(a,b){i[b]=f[b],delete f[b]}),i):(delete e[j.name],f)}return g=a.validator.normalizeRules(a.extend({},a.validator.classRules(j),a.validator.attributeRules(j),a.validator.dataRules(j),a.validator.staticRules(j)),j),g.required&&(h=g.required,delete g.required,g=a.extend({required:h},g)),g.remote&&(h=g.remote,delete g.remote,g=a.extend(g,{remote:h})),g}}}),a.extend(a.expr.pseudos||a.expr[":"],{blank:function(b){return!a.trim(""+a(b).val())},filled:function(b){var c=a(b).val();return null!==c&&!!a.trim(""+c)},unchecked:function(b){return!a(b).prop("checked")}}),a.validator=function(b,c){this.settings=a.extend(!0,{},a.validator.defaults,b),this.currentForm=c,this.init()},a.validator.format=function(b,c){return 1===arguments.length?function(){var c=a.makeArray(arguments);return c.unshift(b),a.validator.format.apply(this,c)}:void 0===c?b:(arguments.length>2&&c.constructor!==Array&&(c=a.makeArray(arguments).slice(1)),c.constructor!==Array&&(c=[c]),a.each(c,function(a,c){b=b.replace(new RegExp("\\{"+a+"\\}","g"),function(){return c})}),b)},a.extend(a.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",pendingClass:"pending",validClass:"valid",errorElement:"label",focusCleanup:!1,focusInvalid:!0,errorContainer:a([]),errorLabelContainer:a([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(a){this.lastActive=a,this.settings.focusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass),this.hideThese(this.errorsFor(a)))},onfocusout:function(a){this.checkable(a)||!(a.name in this.submitted)&&this.optional(a)||this.element(a)},onkeyup:function(b,c){var d=[16,17,18,20,35,36,37,38,39,40,45,144,225];9===c.which&&""===this.elementValue(b)||a.inArray(c.keyCode,d)!==-1||(b.name in this.submitted||b.name in this.invalid)&&this.element(b)},onclick:function(a){a.name in this.submitted?this.element(a):a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).addClass(c).removeClass(d):a(b).addClass(c).removeClass(d)},unhighlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).removeClass(c).addClass(d):a(b).removeClass(c).addClass(d)}},setDefaults:function(b){a.extend(a.validator.defaults,b)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",equalTo:"Please enter the same value again.",maxlength:a.validator.format("Please enter no more than {0} characters."),minlength:a.validator.format("Please enter at least {0} characters."),rangelength:a.validator.format("Please enter a value between {0} and {1} characters long."),range:a.validator.format("Please enter a value between {0} and {1}."),max:a.validator.format("Please enter a value less than or equal to {0}."),min:a.validator.format("Please enter a value greater than or equal to {0}."),step:a.validator.format("Please enter a multiple of {0}.")},autoCreateRanges:!1,prototype:{init:function(){function b(b){var c="undefined"!=typeof a(this).attr("contenteditable")&&"false"!==a(this).attr("contenteditable");if(!this.form&&c&&(this.form=a(this).closest("form")[0],this.name=a(this).attr("name")),d===this.form){var e=a.data(this.form,"validator"),f="on"+b.type.replace(/^validate/,""),g=e.settings;g[f]&&!a(this).is(g.ignore)&&g[f].call(e,this,b)}}this.labelContainer=a(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||a(this.currentForm),this.containers=a(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var c,d=this.currentForm,e=this.groups={};a.each(this.settings.groups,function(b,c){"string"==typeof c&&(c=c.split(/\s/)),a.each(c,function(a,c){e[c]=b})}),c=this.settings.rules,a.each(c,function(b,d){c[b]=a.validator.normalizeRule(d)}),a(this.currentForm).on("focusin.validate focusout.validate keyup.validate",":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], [type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox'], [contenteditable], [type='button']",b).on("click.validate","select, option, [type='radio'], [type='checkbox']",b),this.settings.invalidHandler&&a(this.currentForm).on("invalid-form.validate",this.settings.invalidHandler)},form:function(){return this.checkForm(),a.extend(this.submitted,this.errorMap),this.invalid=a.extend({},this.errorMap),this.valid()||a(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(b){var c,d,e=this.clean(b),f=this.validationTargetFor(e),g=this,h=!0;return void 0===f?delete this.invalid[e.name]:(this.prepareElement(f),this.currentElements=a(f),d=this.groups[f.name],d&&a.each(this.groups,function(a,b){b===d&&a!==f.name&&(e=g.validationTargetFor(g.clean(g.findByName(a))),e&&e.name in g.invalid&&(g.currentElements.push(e),h=g.check(e)&&h))}),c=this.check(f)!==!1,h=h&&c,c?this.invalid[f.name]=!1:this.invalid[f.name]=!0,this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),a(b).attr("aria-invalid",!c)),h},showErrors:function(b){if(b){var c=this;a.extend(this.errorMap,b),this.errorList=a.map(this.errorMap,function(a,b){return{message:a,element:c.findByName(b)[0]}}),this.successList=a.grep(this.successList,function(a){return!(a.name in b)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){a.fn.resetForm&&a(this.currentForm).resetForm(),this.invalid={},this.submitted={},this.prepareForm(),this.hideErrors();var b=this.elements().removeData("previousValue").removeAttr("aria-invalid");this.resetElements(b)},resetElements:function(a){var b;if(this.settings.unhighlight)for(b=0;a[b];b++)this.settings.unhighlight.call(this,a[b],this.settings.errorClass,""),this.findByName(a[b].name).removeClass(this.settings.validClass);else a.removeClass(this.settings.errorClass).removeClass(this.settings.validClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(a){var b,c=0;for(b in a)void 0!==a[b]&&null!==a[b]&&a[b]!==!1&&c++;return c},hideErrors:function(){this.hideThese(this.toHide)},hideThese:function(a){a.not(this.containers).text(""),this.addWrapper(a).hide()},valid:function(){return 0===this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{a(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(b){}},findLastActive:function(){var b=this.lastActive;return b&&1===a.grep(this.errorList,function(a){return a.element.name===b.name}).length&&b},elements:function(){var b=this,c={};return a(this.currentForm).find("input, select, textarea, [contenteditable]").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function(){var d=this.name||a(this).attr("name"),e="undefined"!=typeof a(this).attr("contenteditable")&&"false"!==a(this).attr("contenteditable");return!d&&b.settings.debug&&window.console&&console.error("%o has no name assigned",this),e&&(this.form=a(this).closest("form")[0],this.name=d),this.form===b.currentForm&&(!(d in c||!b.objectLength(a(this).rules()))&&(c[d]=!0,!0))})},clean:function(b){return a(b)[0]},errors:function(){var b=this.settings.errorClass.split(" ").join(".");return a(this.settings.errorElement+"."+b,this.errorContext)},resetInternals:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=a([]),this.toHide=a([])},reset:function(){this.resetInternals(),this.currentElements=a([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset(),this.toHide=this.errorsFor(a)},elementValue:function(b){var c,d,e=a(b),f=b.type,g="undefined"!=typeof e.attr("contenteditable")&&"false"!==e.attr("contenteditable");return"radio"===f||"checkbox"===f?this.findByName(b.name).filter(":checked").val():"number"===f&&"undefined"!=typeof b.validity?b.validity.badInput?"NaN":e.val():(c=g?e.text():e.val(),"file"===f?"C:\\fakepath\\"===c.substr(0,12)?c.substr(12):(d=c.lastIndexOf("/"),d>=0?c.substr(d+1):(d=c.lastIndexOf("\\"),d>=0?c.substr(d+1):c)):"string"==typeof c?c.replace(/\r/g,""):c)},check:function(b){b=this.validationTargetFor(this.clean(b));var c,d,e,f,g=a(b).rules(),h=a.map(g,function(a,b){return b}).length,i=!1,j=this.elementValue(b);"function"==typeof g.normalizer?f=g.normalizer:"function"==typeof this.settings.normalizer&&(f=this.settings.normalizer),f&&(j=f.call(b,j),delete g.normalizer);for(d in g){e={method:d,parameters:g[d]};try{if(c=a.validator.methods[d].call(this,j,b,e.parameters),"dependency-mismatch"===c&&1===h){i=!0;continue}if(i=!1,"pending"===c)return void(this.toHide=this.toHide.not(this.errorsFor(b)));if(!c)return this.formatAndAdd(b,e),!1}catch(k){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+b.id+", check the '"+e.method+"' method.",k),k instanceof TypeError&&(k.message+=".  Exception occurred when checking element "+b.id+", check the '"+e.method+"' method."),k}}if(!i)return this.objectLength(g)&&this.successList.push(b),!0},customDataMessage:function(b,c){return a(b).data("msg"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase())||a(b).data("msg")},customMessage:function(a,b){var c=this.settings.messages[a];return c&&(c.constructor===String?c:c[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(void 0!==arguments[a])return arguments[a]},defaultMessage:function(b,c){"string"==typeof c&&(c={method:c});var d=this.findDefined(this.customMessage(b.name,c.method),this.customDataMessage(b,c.method),!this.settings.ignoreTitle&&b.title||void 0,a.validator.messages[c.method],"<strong>Warning: No message defined for "+b.name+"</strong>"),e=/\$?\{(\d+)\}/g;return"function"==typeof d?d=d.call(this,c.parameters,b):e.test(d)&&(d=a.validator.format(d.replace(e,"{$1}"),c.parameters)),d},formatAndAdd:function(a,b){var c=this.defaultMessage(a,b);this.errorList.push({message:c,element:a,method:b.method}),this.errorMap[a.name]=c,this.submitted[a.name]=c},addWrapper:function(a){return this.settings.wrapper&&(a=a.add(a.parent(this.settings.wrapper))),a},defaultShowErrors:function(){var a,b,c;for(a=0;this.errorList[a];a++)c=this.errorList[a],this.settings.highlight&&this.settings.highlight.call(this,c.element,this.settings.errorClass,this.settings.validClass),this.showLabel(c.element,c.message);if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight)for(a=0,b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return a(this.errorList).map(function(){return this.element})},showLabel:function(b,c){var d,e,f,g,h=this.errorsFor(b),i=this.idOrName(b),j=a(b).attr("aria-describedby");h.length?(h.removeClass(this.settings.validClass).addClass(this.settings.errorClass),h.html(c)):(h=a("<"+this.settings.errorElement+">").attr("id",i+"-error").addClass(this.settings.errorClass).html(c||""),d=h,this.settings.wrapper&&(d=h.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.length?this.labelContainer.append(d):this.settings.errorPlacement?this.settings.errorPlacement.call(this,d,a(b)):d.insertAfter(b),h.is("label")?h.attr("for",i):0===h.parents("label[for='"+this.escapeCssMeta(i)+"']").length&&(f=h.attr("id"),j?j.match(new RegExp("\\b"+this.escapeCssMeta(f)+"\\b"))||(j+=" "+f):j=f,a(b).attr("aria-describedby",j),e=this.groups[b.name],e&&(g=this,a.each(g.groups,function(b,c){c===e&&a("[name='"+g.escapeCssMeta(b)+"']",g.currentForm).attr("aria-describedby",h.attr("id"))})))),!c&&this.settings.success&&(h.text(""),"string"==typeof this.settings.success?h.addClass(this.settings.success):this.settings.success(h,b)),this.toShow=this.toShow.add(h)},errorsFor:function(b){var c=this.escapeCssMeta(this.idOrName(b)),d=a(b).attr("aria-describedby"),e="label[for='"+c+"'], label[for='"+c+"'] *";return d&&(e=e+", #"+this.escapeCssMeta(d).replace(/\s+/g,", #")),this.errors().filter(e)},escapeCssMeta:function(a){return a.replace(/([\\!"#$%&'()*+,.\/:;<=>?@\[\]^`{|}~])/g,"\\$1")},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},validationTargetFor:function(b){return this.checkable(b)&&(b=this.findByName(b.name)),a(b).not(this.settings.ignore)[0]},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(b){return a(this.currentForm).find("[name='"+this.escapeCssMeta(b)+"']")},getLength:function(b,c){switch(c.nodeName.toLowerCase()){case"select":return a("option:selected",c).length;case"input":if(this.checkable(c))return this.findByName(c.name).filter(":checked").length}return b.length},depend:function(a,b){return!this.dependTypes[typeof a]||this.dependTypes[typeof a](a,b)},dependTypes:{"boolean":function(a){return a},string:function(b,c){return!!a(b,c.form).length},"function":function(a,b){return a(b)}},optional:function(b){var c=this.elementValue(b);return!a.validator.methods.required.call(this,c,b)&&"dependency-mismatch"},startRequest:function(b){this.pending[b.name]||(this.pendingRequest++,a(b).addClass(this.settings.pendingClass),this.pending[b.name]=!0)},stopRequest:function(b,c){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[b.name],a(b).removeClass(this.settings.pendingClass),c&&0===this.pendingRequest&&this.formSubmitted&&this.form()?(a(this.currentForm).submit(),this.submitButton&&a("input:hidden[name='"+this.submitButton.name+"']",this.currentForm).remove(),this.formSubmitted=!1):!c&&0===this.pendingRequest&&this.formSubmitted&&(a(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(b,c){return c="string"==typeof c&&c||"remote",a.data(b,"previousValue")||a.data(b,"previousValue",{old:null,valid:!0,message:this.defaultMessage(b,{method:c})})},destroy:function(){this.resetForm(),a(this.currentForm).off(".validate").removeData("validator").find(".validate-equalTo-blur").off(".validate-equalTo").removeClass("validate-equalTo-blur").find(".validate-lessThan-blur").off(".validate-lessThan").removeClass("validate-lessThan-blur").find(".validate-lessThanEqual-blur").off(".validate-lessThanEqual").removeClass("validate-lessThanEqual-blur").find(".validate-greaterThanEqual-blur").off(".validate-greaterThanEqual").removeClass("validate-greaterThanEqual-blur").find(".validate-greaterThan-blur").off(".validate-greaterThan").removeClass("validate-greaterThan-blur")}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(b,c){b.constructor===String?this.classRuleSettings[b]=c:a.extend(this.classRuleSettings,b)},classRules:function(b){var c={},d=a(b).attr("class");return d&&a.each(d.split(" "),function(){this in a.validator.classRuleSettings&&a.extend(c,a.validator.classRuleSettings[this])}),c},normalizeAttributeRule:function(a,b,c,d){/min|max|step/.test(c)&&(null===b||/number|range|text/.test(b))&&(d=Number(d),isNaN(d)&&(d=void 0)),d||0===d?a[c]=d:b===c&&"range"!==b&&(a[c]=!0)},attributeRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)"required"===c?(d=b.getAttribute(c),""===d&&(d=!0),d=!!d):d=f.attr(c),this.normalizeAttributeRule(e,g,c,d);return e.maxlength&&/-1|2147483647|524288/.test(e.maxlength)&&delete e.maxlength,e},dataRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)d=f.data("rule"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase()),""===d&&(d=!0),this.normalizeAttributeRule(e,g,c,d);return e},staticRules:function(b){var c={},d=a.data(b.form,"validator");return d.settings.rules&&(c=a.validator.normalizeRule(d.settings.rules[b.name])||{}),c},normalizeRules:function(b,c){return a.each(b,function(d,e){if(e===!1)return void delete b[d];if(e.param||e.depends){var f=!0;switch(typeof e.depends){case"string":f=!!a(e.depends,c.form).length;break;case"function":f=e.depends.call(c,c)}f?b[d]=void 0===e.param||e.param:(a.data(c.form,"validator").resetElements(a(c)),delete b[d])}}),a.each(b,function(d,e){b[d]=a.isFunction(e)&&"normalizer"!==d?e(c):e}),a.each(["minlength","maxlength"],function(){b[this]&&(b[this]=Number(b[this]))}),a.each(["rangelength","range"],function(){var c;b[this]&&(a.isArray(b[this])?b[this]=[Number(b[this][0]),Number(b[this][1])]:"string"==typeof b[this]&&(c=b[this].replace(/[\[\]]/g,"").split(/[\s,]+/),b[this]=[Number(c[0]),Number(c[1])]))}),a.validator.autoCreateRanges&&(null!=b.min&&null!=b.max&&(b.range=[b.min,b.max],delete b.min,delete b.max),null!=b.minlength&&null!=b.maxlength&&(b.rangelength=[b.minlength,b.maxlength],delete b.minlength,delete b.maxlength)),b},normalizeRule:function(b){if("string"==typeof b){var c={};a.each(b.split(/\s/),function(){c[this]=!0}),b=c}return b},addMethod:function(b,c,d){a.validator.methods[b]=c,a.validator.messages[b]=void 0!==d?d:a.validator.messages[b],c.length<3&&a.validator.addClassRules(b,a.validator.normalizeRule(b))},methods:{required:function(b,c,d){if(!this.depend(d,c))return"dependency-mismatch";if("select"===c.nodeName.toLowerCase()){var e=a(c).val();return e&&e.length>0}return this.checkable(c)?this.getLength(b,c)>0:void 0!==b&&null!==b&&b.length>0},email:function(a,b){return this.optional(b)||/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(a)},url:function(a,b){return this.optional(b)||/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[\/?#]\S*)?$/i.test(a)},date:function(){var a=!1;return function(b,c){return a||(a=!0,this.settings.debug&&window.console&&console.warn("The `date` method is deprecated and will be removed in version '2.0.0'.\nPlease don't use it, since it relies on the Date constructor, which\nbehaves very differently across browsers and locales. Use `dateISO`\ninstead or one of the locale specific methods in `localizations/`\nand `additional-methods.js`.")),this.optional(c)||!/Invalid|NaN/.test(new Date(b).toString())}}(),dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(a)},number:function(a,b){return this.optional(b)||/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},minlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d},maxlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e<=d},rangelength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d[0]&&e<=d[1]},min:function(a,b,c){return this.optional(b)||a>=c},max:function(a,b,c){return this.optional(b)||a<=c},range:function(a,b,c){return this.optional(b)||a>=c[0]&&a<=c[1]},step:function(b,c,d){var e,f=a(c).attr("type"),g="Step attribute on input type "+f+" is not supported.",h=["text","number","range"],i=new RegExp("\\b"+f+"\\b"),j=f&&!i.test(h.join()),k=function(a){var b=(""+a).match(/(?:\.(\d+))?$/);return b&&b[1]?b[1].length:0},l=function(a){return Math.round(a*Math.pow(10,e))},m=!0;if(j)throw new Error(g);return e=k(d),(k(b)>e||l(b)%l(d)!==0)&&(m=!1),this.optional(c)||m},equalTo:function(b,c,d){var e=a(d);return this.settings.onfocusout&&e.not(".validate-equalTo-blur").length&&e.addClass("validate-equalTo-blur").on("blur.validate-equalTo",function(){a(c).valid()}),b===e.val()},remote:function(b,c,d,e){if(this.optional(c))return"dependency-mismatch";e="string"==typeof e&&e||"remote";var f,g,h,i=this.previousValue(c,e);return this.settings.messages[c.name]||(this.settings.messages[c.name]={}),i.originalMessage=i.originalMessage||this.settings.messages[c.name][e],this.settings.messages[c.name][e]=i.message,d="string"==typeof d&&{url:d}||d,h=a.param(a.extend({data:b},d.data)),i.old===h?i.valid:(i.old=h,f=this,this.startRequest(c),g={},g[c.name]=b,a.ajax(a.extend(!0,{mode:"abort",port:"validate"+c.name,dataType:"json",data:g,context:f.currentForm,success:function(a){var d,g,h,j=a===!0||"true"===a;f.settings.messages[c.name][e]=i.originalMessage,j?(h=f.formSubmitted,f.resetInternals(),f.toHide=f.errorsFor(c),f.formSubmitted=h,f.successList.push(c),f.invalid[c.name]=!1,f.showErrors()):(d={},g=a||f.defaultMessage(c,{method:e,parameters:b}),d[c.name]=i.message=g,f.invalid[c.name]=!0,f.showErrors(d)),i.valid=j,f.stopRequest(c,j)}},d)),"pending")}}});var b,c={};return a.ajaxPrefilter?a.ajaxPrefilter(function(a,b,d){var e=a.port;"abort"===a.mode&&(c[e]&&c[e].abort(),c[e]=d)}):(b=a.ajax,a.ajax=function(d){var e=("mode"in d?d:a.ajaxSettings).mode,f=("port"in d?d:a.ajaxSettings).port;return"abort"===e?(c[f]&&c[f].abort(),c[f]=b.apply(this,arguments),c[f]):b.apply(this,arguments)}),a});;
// Unobtrusive validation support library for jQuery and jQuery Validate
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// @version v3.2.11
!function(a){"function"==typeof define&&define.amd?define("jquery.validate.unobtrusive",["jquery-validation"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery-validation")):jQuery.validator.unobtrusive=a(jQuery)}(function(a){function e(a,e,n){a.rules[e]=n,a.message&&(a.messages[e]=a.message)}function n(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function t(a){return a.replace(/([!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function r(a){return a.substr(0,a.lastIndexOf(".")+1)}function i(a,e){return 0===a.indexOf("*.")&&(a=a.replace("*.",e)),a}function o(e,n){var r=a(this).find("[data-valmsg-for='"+t(n[0].name)+"']"),i=r.attr("data-valmsg-replace"),o=i?a.parseJSON(i)!==!1:null;r.removeClass("field-validation-valid").addClass("field-validation-error"),e.data("unobtrusiveContainer",r),o?(r.empty(),e.removeClass("input-validation-error").appendTo(r)):e.hide()}function d(e,n){var t=a(this).find("[data-valmsg-summary=true]"),r=t.find("ul");r&&r.length&&n.errorList.length&&(r.empty(),t.addClass("validation-summary-errors").removeClass("validation-summary-valid"),a.each(n.errorList,function(){a("<li />").html(this.message).appendTo(r)}))}function s(e){var n=e.data("unobtrusiveContainer");if(n){var t=n.attr("data-valmsg-replace"),r=t?a.parseJSON(t):null;n.addClass("field-validation-valid").removeClass("field-validation-error"),e.removeData("unobtrusiveContainer"),r&&n.empty()}}function l(e){var n=a(this),t="__jquery_unobtrusive_validation_form_reset";if(!n.data(t)){n.data(t,!0);try{n.data("validator").resetForm()}finally{n.removeData(t)}n.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors"),n.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}}function u(e){var n=a(e),t=n.data(v),r=a.proxy(l,e),i=f.unobtrusive.options||{},u=function(n,t){var r=i[n];r&&a.isFunction(r)&&r.apply(e,t)};return t||(t={options:{errorClass:i.errorClass||"input-validation-error",errorElement:i.errorElement||"span",errorPlacement:function(){o.apply(e,arguments),u("errorPlacement",arguments)},invalidHandler:function(){d.apply(e,arguments),u("invalidHandler",arguments)},messages:{},rules:{},success:function(){s.apply(e,arguments),u("success",arguments)}},attachValidation:function(){n.off("reset."+v,r).on("reset."+v,r).validate(this.options)},validate:function(){return n.validate(),n.valid()}},n.data(v,t)),t}var m,f=a.validator,v="unobtrusiveValidation";return f.unobtrusive={adapters:[],parseElement:function(e,n){var t,r,i,o=a(e),d=o.parents("form")[0];d&&(t=u(d),t.options.rules[e.name]=r={},t.options.messages[e.name]=i={},a.each(this.adapters,function(){var n="data-val-"+this.name,t=o.attr(n),s={};void 0!==t&&(n+="-",a.each(this.params,function(){s[this]=o.attr(n+this)}),this.adapt({element:e,form:d,message:t,params:s,rules:r,messages:i}))}),a.extend(r,{__dummy__:!0}),n||t.attachValidation())},parse:function(e){var n=a(e),t=n.parents().addBack().filter("form").add(n.find("form")).has("[data-val=true]");n.find("[data-val=true]").each(function(){f.unobtrusive.parseElement(this,!0)}),t.each(function(){var a=u(this);a&&a.attachValidation()})}},m=f.unobtrusive.adapters,m.add=function(a,e,n){return n||(n=e,e=[]),this.push({name:a,params:e,adapt:n}),this},m.addBool=function(a,n){return this.add(a,function(t){e(t,n||a,!0)})},m.addMinMax=function(a,n,t,r,i,o){return this.add(a,[i||"min",o||"max"],function(a){var i=a.params.min,o=a.params.max;i&&o?e(a,r,[i,o]):i?e(a,n,i):o&&e(a,t,o)})},m.addSingleVal=function(a,n,t){return this.add(a,[n||"val"],function(r){e(r,t||a,r.params[n])})},f.addMethod("__dummy__",function(a,e,n){return!0}),f.addMethod("regex",function(a,e,n){var t;return!!this.optional(e)||(t=new RegExp(n).exec(a),t&&0===t.index&&t[0].length===a.length)}),f.addMethod("nonalphamin",function(a,e,n){var t;return n&&(t=a.match(/\W/g),t=t&&t.length>=n),t}),f.methods.extension?(m.addSingleVal("accept","mimtype"),m.addSingleVal("extension","extension")):m.addSingleVal("extension","extension","accept"),m.addSingleVal("regex","pattern"),m.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url"),m.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range"),m.addMinMax("minlength","minlength").addMinMax("maxlength","minlength","maxlength"),m.add("equalto",["other"],function(n){var o=r(n.element.name),d=n.params.other,s=i(d,o),l=a(n.form).find(":input").filter("[name='"+t(s)+"']")[0];e(n,"equalTo",l)}),m.add("required",function(a){"INPUT"===a.element.tagName.toUpperCase()&&"CHECKBOX"===a.element.type.toUpperCase()||e(a,"required",!0)}),m.add("remote",["url","type","additionalfields"],function(o){var d={url:o.params.url,type:o.params.type||"GET",data:{}},s=r(o.element.name);a.each(n(o.params.additionalfields||o.element.name),function(e,n){var r=i(n,s);d.data[r]=function(){var e=a(o.form).find(":input").filter("[name='"+t(r)+"']");return e.is(":checkbox")?e.filter(":checked").val()||e.filter(":hidden").val()||"":e.is(":radio")?e.filter(":checked").val()||"":e.val()}}),e(o,"remote",d)}),m.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&e(a,"minlength",a.params.min),a.params.nonalphamin&&e(a,"nonalphamin",a.params.nonalphamin),a.params.regex&&e(a,"regex",a.params.regex)}),m.add("fileextensions",["extensions"],function(a){e(a,"extension",a.params.extensions)}),a(function(){f.unobtrusive.parse(document)}),f.unobtrusive});;
//! moment.js
//! version : 2.13.0
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):a.moment=b()}(this,function(){"use strict";function a(){return fd.apply(null,arguments)}function b(a){fd=a}function c(a){return a instanceof Array||"[object Array]"===Object.prototype.toString.call(a)}function d(a){return a instanceof Date||"[object Date]"===Object.prototype.toString.call(a)}function e(a,b){var c,d=[];for(c=0;c<a.length;++c)d.push(b(a[c],c));return d}function f(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function g(a,b){for(var c in b)f(b,c)&&(a[c]=b[c]);return f(b,"toString")&&(a.toString=b.toString),f(b,"valueOf")&&(a.valueOf=b.valueOf),a}function h(a,b,c,d){return Ja(a,b,c,d,!0).utc()}function i(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null}}function j(a){return null==a._pf&&(a._pf=i()),a._pf}function k(a){if(null==a._isValid){var b=j(a),c=gd.call(b.parsedDateParts,function(a){return null!=a});a._isValid=!isNaN(a._d.getTime())&&b.overflow<0&&!b.empty&&!b.invalidMonth&&!b.invalidWeekday&&!b.nullInput&&!b.invalidFormat&&!b.userInvalidated&&(!b.meridiem||b.meridiem&&c),a._strict&&(a._isValid=a._isValid&&0===b.charsLeftOver&&0===b.unusedTokens.length&&void 0===b.bigHour)}return a._isValid}function l(a){var b=h(NaN);return null!=a?g(j(b),a):j(b).userInvalidated=!0,b}function m(a){return void 0===a}function n(a,b){var c,d,e;if(m(b._isAMomentObject)||(a._isAMomentObject=b._isAMomentObject),m(b._i)||(a._i=b._i),m(b._f)||(a._f=b._f),m(b._l)||(a._l=b._l),m(b._strict)||(a._strict=b._strict),m(b._tzm)||(a._tzm=b._tzm),m(b._isUTC)||(a._isUTC=b._isUTC),m(b._offset)||(a._offset=b._offset),m(b._pf)||(a._pf=j(b)),m(b._locale)||(a._locale=b._locale),hd.length>0)for(c in hd)d=hd[c],e=b[d],m(e)||(a[d]=e);return a}function o(b){n(this,b),this._d=new Date(null!=b._d?b._d.getTime():NaN),id===!1&&(id=!0,a.updateOffset(this),id=!1)}function p(a){return a instanceof o||null!=a&&null!=a._isAMomentObject}function q(a){return 0>a?Math.ceil(a):Math.floor(a)}function r(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=q(b)),c}function s(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&r(a[d])!==r(b[d]))&&g++;return g+f}function t(b){a.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+b)}function u(b,c){var d=!0;return g(function(){return null!=a.deprecationHandler&&a.deprecationHandler(null,b),d&&(t(b+"\nArguments: "+Array.prototype.slice.call(arguments).join(", ")+"\n"+(new Error).stack),d=!1),c.apply(this,arguments)},c)}function v(b,c){null!=a.deprecationHandler&&a.deprecationHandler(b,c),jd[b]||(t(c),jd[b]=!0)}function w(a){return a instanceof Function||"[object Function]"===Object.prototype.toString.call(a)}function x(a){return"[object Object]"===Object.prototype.toString.call(a)}function y(a){var b,c;for(c in a)b=a[c],w(b)?this[c]=b:this["_"+c]=b;this._config=a,this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function z(a,b){var c,d=g({},a);for(c in b)f(b,c)&&(x(a[c])&&x(b[c])?(d[c]={},g(d[c],a[c]),g(d[c],b[c])):null!=b[c]?d[c]=b[c]:delete d[c]);return d}function A(a){null!=a&&this.set(a)}function B(a){return a?a.toLowerCase().replace("_","-"):a}function C(a){for(var b,c,d,e,f=0;f<a.length;){for(e=B(a[f]).split("-"),b=e.length,c=B(a[f+1]),c=c?c.split("-"):null;b>0;){if(d=D(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&s(e,c,!0)>=b-1)break;b--}f++}return null}function D(a){var b=null;if(!nd[a]&&"undefined"!=typeof module&&module&&module.exports)try{b=ld._abbr,require("./locale/"+a),E(b)}catch(c){}return nd[a]}function E(a,b){var c;return a&&(c=m(b)?H(a):F(a,b),c&&(ld=c)),ld._abbr}function F(a,b){return null!==b?(b.abbr=a,null!=nd[a]?(v("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale"),b=z(nd[a]._config,b)):null!=b.parentLocale&&(null!=nd[b.parentLocale]?b=z(nd[b.parentLocale]._config,b):v("parentLocaleUndefined","specified parentLocale is not defined yet")),nd[a]=new A(b),E(a),nd[a]):(delete nd[a],null)}function G(a,b){if(null!=b){var c;null!=nd[a]&&(b=z(nd[a]._config,b)),c=new A(b),c.parentLocale=nd[a],nd[a]=c,E(a)}else null!=nd[a]&&(null!=nd[a].parentLocale?nd[a]=nd[a].parentLocale:null!=nd[a]&&delete nd[a]);return nd[a]}function H(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return ld;if(!c(a)){if(b=D(a))return b;a=[a]}return C(a)}function I(){return kd(nd)}function J(a,b){var c=a.toLowerCase();od[c]=od[c+"s"]=od[b]=a}function K(a){return"string"==typeof a?od[a]||od[a.toLowerCase()]:void 0}function L(a){var b,c,d={};for(c in a)f(a,c)&&(b=K(c),b&&(d[b]=a[c]));return d}function M(b,c){return function(d){return null!=d?(O(this,b,d),a.updateOffset(this,c),this):N(this,b)}}function N(a,b){return a.isValid()?a._d["get"+(a._isUTC?"UTC":"")+b]():NaN}function O(a,b,c){a.isValid()&&a._d["set"+(a._isUTC?"UTC":"")+b](c)}function P(a,b){var c;if("object"==typeof a)for(c in a)this.set(c,a[c]);else if(a=K(a),w(this[a]))return this[a](b);return this}function Q(a,b,c){var d=""+Math.abs(a),e=b-d.length,f=a>=0;return(f?c?"+":"":"-")+Math.pow(10,Math.max(0,e)).toString().substr(1)+d}function R(a,b,c,d){var e=d;"string"==typeof d&&(e=function(){return this[d]()}),a&&(sd[a]=e),b&&(sd[b[0]]=function(){return Q(e.apply(this,arguments),b[1],b[2])}),c&&(sd[c]=function(){return this.localeData().ordinal(e.apply(this,arguments),a)})}function S(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function T(a){var b,c,d=a.match(pd);for(b=0,c=d.length;c>b;b++)sd[d[b]]?d[b]=sd[d[b]]:d[b]=S(d[b]);return function(b){var e,f="";for(e=0;c>e;e++)f+=d[e]instanceof Function?d[e].call(b,a):d[e];return f}}function U(a,b){return a.isValid()?(b=V(b,a.localeData()),rd[b]=rd[b]||T(b),rd[b](a)):a.localeData().invalidDate()}function V(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(qd.lastIndex=0;d>=0&&qd.test(a);)a=a.replace(qd,c),qd.lastIndex=0,d-=1;return a}function W(a,b,c){Kd[a]=w(b)?b:function(a,d){return a&&c?c:b}}function X(a,b){return f(Kd,a)?Kd[a](b._strict,b._locale):new RegExp(Y(a))}function Y(a){return Z(a.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e}))}function Z(a){return a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function $(a,b){var c,d=b;for("string"==typeof a&&(a=[a]),"number"==typeof b&&(d=function(a,c){c[b]=r(a)}),c=0;c<a.length;c++)Ld[a[c]]=d}function _(a,b){$(a,function(a,c,d,e){d._w=d._w||{},b(a,d._w,d,e)})}function aa(a,b,c){null!=b&&f(Ld,a)&&Ld[a](b,c._a,c,a)}function ba(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function ca(a,b){return c(this._months)?this._months[a.month()]:this._months[Vd.test(b)?"format":"standalone"][a.month()]}function da(a,b){return c(this._monthsShort)?this._monthsShort[a.month()]:this._monthsShort[Vd.test(b)?"format":"standalone"][a.month()]}function ea(a,b,c){var d,e,f,g=a.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],d=0;12>d;++d)f=h([2e3,d]),this._shortMonthsParse[d]=this.monthsShort(f,"").toLocaleLowerCase(),this._longMonthsParse[d]=this.months(f,"").toLocaleLowerCase();return c?"MMM"===b?(e=md.call(this._shortMonthsParse,g),-1!==e?e:null):(e=md.call(this._longMonthsParse,g),-1!==e?e:null):"MMM"===b?(e=md.call(this._shortMonthsParse,g),-1!==e?e:(e=md.call(this._longMonthsParse,g),-1!==e?e:null)):(e=md.call(this._longMonthsParse,g),-1!==e?e:(e=md.call(this._shortMonthsParse,g),-1!==e?e:null))}function fa(a,b,c){var d,e,f;if(this._monthsParseExact)return ea.call(this,a,b,c);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),d=0;12>d;d++){if(e=h([2e3,d]),c&&!this._longMonthsParse[d]&&(this._longMonthsParse[d]=new RegExp("^"+this.months(e,"").replace(".","")+"$","i"),this._shortMonthsParse[d]=new RegExp("^"+this.monthsShort(e,"").replace(".","")+"$","i")),c||this._monthsParse[d]||(f="^"+this.months(e,"")+"|^"+this.monthsShort(e,""),this._monthsParse[d]=new RegExp(f.replace(".",""),"i")),c&&"MMMM"===b&&this._longMonthsParse[d].test(a))return d;if(c&&"MMM"===b&&this._shortMonthsParse[d].test(a))return d;if(!c&&this._monthsParse[d].test(a))return d}}function ga(a,b){var c;if(!a.isValid())return a;if("string"==typeof b)if(/^\d+$/.test(b))b=r(b);else if(b=a.localeData().monthsParse(b),"number"!=typeof b)return a;return c=Math.min(a.date(),ba(a.year(),b)),a._d["set"+(a._isUTC?"UTC":"")+"Month"](b,c),a}function ha(b){return null!=b?(ga(this,b),a.updateOffset(this,!0),this):N(this,"Month")}function ia(){return ba(this.year(),this.month())}function ja(a){return this._monthsParseExact?(f(this,"_monthsRegex")||la.call(this),a?this._monthsShortStrictRegex:this._monthsShortRegex):this._monthsShortStrictRegex&&a?this._monthsShortStrictRegex:this._monthsShortRegex}function ka(a){return this._monthsParseExact?(f(this,"_monthsRegex")||la.call(this),a?this._monthsStrictRegex:this._monthsRegex):this._monthsStrictRegex&&a?this._monthsStrictRegex:this._monthsRegex}function la(){function a(a,b){return b.length-a.length}var b,c,d=[],e=[],f=[];for(b=0;12>b;b++)c=h([2e3,b]),d.push(this.monthsShort(c,"")),e.push(this.months(c,"")),f.push(this.months(c,"")),f.push(this.monthsShort(c,""));for(d.sort(a),e.sort(a),f.sort(a),b=0;12>b;b++)d[b]=Z(d[b]),e[b]=Z(e[b]),f[b]=Z(f[b]);this._monthsRegex=new RegExp("^("+f.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+e.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+d.join("|")+")","i")}function ma(a){var b,c=a._a;return c&&-2===j(a).overflow&&(b=c[Nd]<0||c[Nd]>11?Nd:c[Od]<1||c[Od]>ba(c[Md],c[Nd])?Od:c[Pd]<0||c[Pd]>24||24===c[Pd]&&(0!==c[Qd]||0!==c[Rd]||0!==c[Sd])?Pd:c[Qd]<0||c[Qd]>59?Qd:c[Rd]<0||c[Rd]>59?Rd:c[Sd]<0||c[Sd]>999?Sd:-1,j(a)._overflowDayOfYear&&(Md>b||b>Od)&&(b=Od),j(a)._overflowWeeks&&-1===b&&(b=Td),j(a)._overflowWeekday&&-1===b&&(b=Ud),j(a).overflow=b),a}function na(a){var b,c,d,e,f,g,h=a._i,i=$d.exec(h)||_d.exec(h);if(i){for(j(a).iso=!0,b=0,c=be.length;c>b;b++)if(be[b][1].exec(i[1])){e=be[b][0],d=be[b][2]!==!1;break}if(null==e)return void(a._isValid=!1);if(i[3]){for(b=0,c=ce.length;c>b;b++)if(ce[b][1].exec(i[3])){f=(i[2]||" ")+ce[b][0];break}if(null==f)return void(a._isValid=!1)}if(!d&&null!=f)return void(a._isValid=!1);if(i[4]){if(!ae.exec(i[4]))return void(a._isValid=!1);g="Z"}a._f=e+(f||"")+(g||""),Ca(a)}else a._isValid=!1}function oa(b){var c=de.exec(b._i);return null!==c?void(b._d=new Date(+c[1])):(na(b),void(b._isValid===!1&&(delete b._isValid,a.createFromInputFallback(b))))}function pa(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 100>a&&a>=0&&isFinite(h.getFullYear())&&h.setFullYear(a),h}function qa(a){var b=new Date(Date.UTC.apply(null,arguments));return 100>a&&a>=0&&isFinite(b.getUTCFullYear())&&b.setUTCFullYear(a),b}function ra(a){return sa(a)?366:365}function sa(a){return a%4===0&&a%100!==0||a%400===0}function ta(){return sa(this.year())}function ua(a,b,c){var d=7+b-c,e=(7+qa(a,0,d).getUTCDay()-b)%7;return-e+d-1}function va(a,b,c,d,e){var f,g,h=(7+c-d)%7,i=ua(a,d,e),j=1+7*(b-1)+h+i;return 0>=j?(f=a-1,g=ra(f)+j):j>ra(a)?(f=a+1,g=j-ra(a)):(f=a,g=j),{year:f,dayOfYear:g}}function wa(a,b,c){var d,e,f=ua(a.year(),b,c),g=Math.floor((a.dayOfYear()-f-1)/7)+1;return 1>g?(e=a.year()-1,d=g+xa(e,b,c)):g>xa(a.year(),b,c)?(d=g-xa(a.year(),b,c),e=a.year()+1):(e=a.year(),d=g),{week:d,year:e}}function xa(a,b,c){var d=ua(a,b,c),e=ua(a+1,b,c);return(ra(a)-d+e)/7}function ya(a,b,c){return null!=a?a:null!=b?b:c}function za(b){var c=new Date(a.now());return b._useUTC?[c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()]:[c.getFullYear(),c.getMonth(),c.getDate()]}function Aa(a){var b,c,d,e,f=[];if(!a._d){for(d=za(a),a._w&&null==a._a[Od]&&null==a._a[Nd]&&Ba(a),a._dayOfYear&&(e=ya(a._a[Md],d[Md]),a._dayOfYear>ra(e)&&(j(a)._overflowDayOfYear=!0),c=qa(e,0,a._dayOfYear),a._a[Nd]=c.getUTCMonth(),a._a[Od]=c.getUTCDate()),b=0;3>b&&null==a._a[b];++b)a._a[b]=f[b]=d[b];for(;7>b;b++)a._a[b]=f[b]=null==a._a[b]?2===b?1:0:a._a[b];24===a._a[Pd]&&0===a._a[Qd]&&0===a._a[Rd]&&0===a._a[Sd]&&(a._nextDay=!0,a._a[Pd]=0),a._d=(a._useUTC?qa:pa).apply(null,f),null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[Pd]=24)}}function Ba(a){var b,c,d,e,f,g,h,i;b=a._w,null!=b.GG||null!=b.W||null!=b.E?(f=1,g=4,c=ya(b.GG,a._a[Md],wa(Ka(),1,4).year),d=ya(b.W,1),e=ya(b.E,1),(1>e||e>7)&&(i=!0)):(f=a._locale._week.dow,g=a._locale._week.doy,c=ya(b.gg,a._a[Md],wa(Ka(),f,g).year),d=ya(b.w,1),null!=b.d?(e=b.d,(0>e||e>6)&&(i=!0)):null!=b.e?(e=b.e+f,(b.e<0||b.e>6)&&(i=!0)):e=f),1>d||d>xa(c,f,g)?j(a)._overflowWeeks=!0:null!=i?j(a)._overflowWeekday=!0:(h=va(c,d,e,f,g),a._a[Md]=h.year,a._dayOfYear=h.dayOfYear)}function Ca(b){if(b._f===a.ISO_8601)return void na(b);b._a=[],j(b).empty=!0;var c,d,e,f,g,h=""+b._i,i=h.length,k=0;for(e=V(b._f,b._locale).match(pd)||[],c=0;c<e.length;c++)f=e[c],d=(h.match(X(f,b))||[])[0],d&&(g=h.substr(0,h.indexOf(d)),g.length>0&&j(b).unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),k+=d.length),sd[f]?(d?j(b).empty=!1:j(b).unusedTokens.push(f),aa(f,d,b)):b._strict&&!d&&j(b).unusedTokens.push(f);j(b).charsLeftOver=i-k,h.length>0&&j(b).unusedInput.push(h),j(b).bigHour===!0&&b._a[Pd]<=12&&b._a[Pd]>0&&(j(b).bigHour=void 0),j(b).parsedDateParts=b._a.slice(0),j(b).meridiem=b._meridiem,b._a[Pd]=Da(b._locale,b._a[Pd],b._meridiem),Aa(b),ma(b)}function Da(a,b,c){var d;return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&12>b&&(b+=12),d||12!==b||(b=0),b):b}function Ea(a){var b,c,d,e,f;if(0===a._f.length)return j(a).invalidFormat=!0,void(a._d=new Date(NaN));for(e=0;e<a._f.length;e++)f=0,b=n({},a),null!=a._useUTC&&(b._useUTC=a._useUTC),b._f=a._f[e],Ca(b),k(b)&&(f+=j(b).charsLeftOver,f+=10*j(b).unusedTokens.length,j(b).score=f,(null==d||d>f)&&(d=f,c=b));g(a,c||b)}function Fa(a){if(!a._d){var b=L(a._i);a._a=e([b.year,b.month,b.day||b.date,b.hour,b.minute,b.second,b.millisecond],function(a){return a&&parseInt(a,10)}),Aa(a)}}function Ga(a){var b=new o(ma(Ha(a)));return b._nextDay&&(b.add(1,"d"),b._nextDay=void 0),b}function Ha(a){var b=a._i,e=a._f;return a._locale=a._locale||H(a._l),null===b||void 0===e&&""===b?l({nullInput:!0}):("string"==typeof b&&(a._i=b=a._locale.preparse(b)),p(b)?new o(ma(b)):(c(e)?Ea(a):e?Ca(a):d(b)?a._d=b:Ia(a),k(a)||(a._d=null),a))}function Ia(b){var f=b._i;void 0===f?b._d=new Date(a.now()):d(f)?b._d=new Date(f.valueOf()):"string"==typeof f?oa(b):c(f)?(b._a=e(f.slice(0),function(a){return parseInt(a,10)}),Aa(b)):"object"==typeof f?Fa(b):"number"==typeof f?b._d=new Date(f):a.createFromInputFallback(b)}function Ja(a,b,c,d,e){var f={};return"boolean"==typeof c&&(d=c,c=void 0),f._isAMomentObject=!0,f._useUTC=f._isUTC=e,f._l=c,f._i=a,f._f=b,f._strict=d,Ga(f)}function Ka(a,b,c,d){return Ja(a,b,c,d,!1)}function La(a,b){var d,e;if(1===b.length&&c(b[0])&&(b=b[0]),!b.length)return Ka();for(d=b[0],e=1;e<b.length;++e)(!b[e].isValid()||b[e][a](d))&&(d=b[e]);return d}function Ma(){var a=[].slice.call(arguments,0);return La("isBefore",a)}function Na(){var a=[].slice.call(arguments,0);return La("isAfter",a)}function Oa(a){var b=L(a),c=b.year||0,d=b.quarter||0,e=b.month||0,f=b.week||0,g=b.day||0,h=b.hour||0,i=b.minute||0,j=b.second||0,k=b.millisecond||0;this._milliseconds=+k+1e3*j+6e4*i+1e3*h*60*60,this._days=+g+7*f,this._months=+e+3*d+12*c,this._data={},this._locale=H(),this._bubble()}function Pa(a){return a instanceof Oa}function Qa(a,b){R(a,0,0,function(){var a=this.utcOffset(),c="+";return 0>a&&(a=-a,c="-"),c+Q(~~(a/60),2)+b+Q(~~a%60,2)})}function Ra(a,b){var c=(b||"").match(a)||[],d=c[c.length-1]||[],e=(d+"").match(ie)||["-",0,0],f=+(60*e[1])+r(e[2]);return"+"===e[0]?f:-f}function Sa(b,c){var e,f;return c._isUTC?(e=c.clone(),f=(p(b)||d(b)?b.valueOf():Ka(b).valueOf())-e.valueOf(),e._d.setTime(e._d.valueOf()+f),a.updateOffset(e,!1),e):Ka(b).local()}function Ta(a){return 15*-Math.round(a._d.getTimezoneOffset()/15)}function Ua(b,c){var d,e=this._offset||0;return this.isValid()?null!=b?("string"==typeof b?b=Ra(Hd,b):Math.abs(b)<16&&(b=60*b),!this._isUTC&&c&&(d=Ta(this)),this._offset=b,this._isUTC=!0,null!=d&&this.add(d,"m"),e!==b&&(!c||this._changeInProgress?jb(this,db(b-e,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,a.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?e:Ta(this):null!=b?this:NaN}function Va(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}function Wa(a){return this.utcOffset(0,a)}function Xa(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(Ta(this),"m")),this}function Ya(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(Ra(Gd,this._i)),this}function Za(a){return this.isValid()?(a=a?Ka(a).utcOffset():0,(this.utcOffset()-a)%60===0):!1}function $a(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function _a(){if(!m(this._isDSTShifted))return this._isDSTShifted;var a={};if(n(a,this),a=Ha(a),a._a){var b=a._isUTC?h(a._a):Ka(a._a);this._isDSTShifted=this.isValid()&&s(a._a,b.toArray())>0}else this._isDSTShifted=!1;return this._isDSTShifted}function ab(){return this.isValid()?!this._isUTC:!1}function bb(){return this.isValid()?this._isUTC:!1}function cb(){return this.isValid()?this._isUTC&&0===this._offset:!1}function db(a,b){var c,d,e,g=a,h=null;return Pa(a)?g={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(g={},b?g[b]=a:g.milliseconds=a):(h=je.exec(a))?(c="-"===h[1]?-1:1,g={y:0,d:r(h[Od])*c,h:r(h[Pd])*c,m:r(h[Qd])*c,s:r(h[Rd])*c,ms:r(h[Sd])*c}):(h=ke.exec(a))?(c="-"===h[1]?-1:1,g={y:eb(h[2],c),M:eb(h[3],c),w:eb(h[4],c),d:eb(h[5],c),h:eb(h[6],c),m:eb(h[7],c),s:eb(h[8],c)}):null==g?g={}:"object"==typeof g&&("from"in g||"to"in g)&&(e=gb(Ka(g.from),Ka(g.to)),g={},g.ms=e.milliseconds,g.M=e.months),d=new Oa(g),Pa(a)&&f(a,"_locale")&&(d._locale=a._locale),d}function eb(a,b){var c=a&&parseFloat(a.replace(",","."));return(isNaN(c)?0:c)*b}function fb(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function gb(a,b){var c;return a.isValid()&&b.isValid()?(b=Sa(b,a),a.isBefore(b)?c=fb(a,b):(c=fb(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c):{milliseconds:0,months:0}}function hb(a){return 0>a?-1*Math.round(-1*a):Math.round(a)}function ib(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||(v(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=db(c,d),jb(this,e,a),this}}function jb(b,c,d,e){var f=c._milliseconds,g=hb(c._days),h=hb(c._months);b.isValid()&&(e=null==e?!0:e,f&&b._d.setTime(b._d.valueOf()+f*d),g&&O(b,"Date",N(b,"Date")+g*d),h&&ga(b,N(b,"Month")+h*d),e&&a.updateOffset(b,g||h))}function kb(a,b){var c=a||Ka(),d=Sa(c,this).startOf("day"),e=this.diff(d,"days",!0),f=-6>e?"sameElse":-1>e?"lastWeek":0>e?"lastDay":1>e?"sameDay":2>e?"nextDay":7>e?"nextWeek":"sameElse",g=b&&(w(b[f])?b[f]():b[f]);return this.format(g||this.localeData().calendar(f,this,Ka(c)))}function lb(){return new o(this)}function mb(a,b){var c=p(a)?a:Ka(a);return this.isValid()&&c.isValid()?(b=K(m(b)?"millisecond":b),"millisecond"===b?this.valueOf()>c.valueOf():c.valueOf()<this.clone().startOf(b).valueOf()):!1}function nb(a,b){var c=p(a)?a:Ka(a);return this.isValid()&&c.isValid()?(b=K(m(b)?"millisecond":b),"millisecond"===b?this.valueOf()<c.valueOf():this.clone().endOf(b).valueOf()<c.valueOf()):!1}function ob(a,b,c,d){return d=d||"()",("("===d[0]?this.isAfter(a,c):!this.isBefore(a,c))&&(")"===d[1]?this.isBefore(b,c):!this.isAfter(b,c))}function pb(a,b){var c,d=p(a)?a:Ka(a);return this.isValid()&&d.isValid()?(b=K(b||"millisecond"),"millisecond"===b?this.valueOf()===d.valueOf():(c=d.valueOf(),this.clone().startOf(b).valueOf()<=c&&c<=this.clone().endOf(b).valueOf())):!1}function qb(a,b){return this.isSame(a,b)||this.isAfter(a,b)}function rb(a,b){return this.isSame(a,b)||this.isBefore(a,b)}function sb(a,b,c){var d,e,f,g;return this.isValid()?(d=Sa(a,this),d.isValid()?(e=6e4*(d.utcOffset()-this.utcOffset()),b=K(b),"year"===b||"month"===b||"quarter"===b?(g=tb(this,d),"quarter"===b?g/=3:"year"===b&&(g/=12)):(f=this-d,g="second"===b?f/1e3:"minute"===b?f/6e4:"hour"===b?f/36e5:"day"===b?(f-e)/864e5:"week"===b?(f-e)/6048e5:f),c?g:q(g)):NaN):NaN}function tb(a,b){var c,d,e=12*(b.year()-a.year())+(b.month()-a.month()),f=a.clone().add(e,"months");return 0>b-f?(c=a.clone().add(e-1,"months"),d=(b-f)/(f-c)):(c=a.clone().add(e+1,"months"),d=(b-f)/(c-f)),-(e+d)||0}function ub(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function vb(){var a=this.clone().utc();return 0<a.year()&&a.year()<=9999?w(Date.prototype.toISOString)?this.toDate().toISOString():U(a,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):U(a,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}function wb(b){b||(b=this.isUtc()?a.defaultFormatUtc:a.defaultFormat);var c=U(this,b);return this.localeData().postformat(c)}function xb(a,b){return this.isValid()&&(p(a)&&a.isValid()||Ka(a).isValid())?db({to:this,from:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function yb(a){return this.from(Ka(),a)}function zb(a,b){return this.isValid()&&(p(a)&&a.isValid()||Ka(a).isValid())?db({from:this,to:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function Ab(a){return this.to(Ka(),a)}function Bb(a){var b;return void 0===a?this._locale._abbr:(b=H(a),null!=b&&(this._locale=b),this)}function Cb(){return this._locale}function Db(a){switch(a=K(a)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===a&&this.weekday(0),"isoWeek"===a&&this.isoWeekday(1),"quarter"===a&&this.month(3*Math.floor(this.month()/3)),this}function Eb(a){return a=K(a),void 0===a||"millisecond"===a?this:("date"===a&&(a="day"),this.startOf(a).add(1,"isoWeek"===a?"week":a).subtract(1,"ms"))}function Fb(){return this._d.valueOf()-6e4*(this._offset||0)}function Gb(){return Math.floor(this.valueOf()/1e3)}function Hb(){return this._offset?new Date(this.valueOf()):this._d}function Ib(){var a=this;return[a.year(),a.month(),a.date(),a.hour(),a.minute(),a.second(),a.millisecond()]}function Jb(){var a=this;return{years:a.year(),months:a.month(),date:a.date(),hours:a.hours(),minutes:a.minutes(),seconds:a.seconds(),milliseconds:a.milliseconds()}}function Kb(){return this.isValid()?this.toISOString():null}function Lb(){return k(this)}function Mb(){return g({},j(this))}function Nb(){return j(this).overflow}function Ob(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}function Pb(a,b){R(0,[a,a.length],0,b)}function Qb(a){return Ub.call(this,a,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)}function Rb(a){return Ub.call(this,a,this.isoWeek(),this.isoWeekday(),1,4)}function Sb(){return xa(this.year(),1,4)}function Tb(){var a=this.localeData()._week;return xa(this.year(),a.dow,a.doy)}function Ub(a,b,c,d,e){var f;return null==a?wa(this,d,e).year:(f=xa(a,d,e),b>f&&(b=f),Vb.call(this,a,b,c,d,e))}function Vb(a,b,c,d,e){var f=va(a,b,c,d,e),g=qa(f.year,0,f.dayOfYear);return this.year(g.getUTCFullYear()),this.month(g.getUTCMonth()),this.date(g.getUTCDate()),this}function Wb(a){return null==a?Math.ceil((this.month()+1)/3):this.month(3*(a-1)+this.month()%3)}function Xb(a){return wa(a,this._week.dow,this._week.doy).week}function Yb(){return this._week.dow}function Zb(){return this._week.doy}function $b(a){var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")}function _b(a){var b=wa(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")}function ac(a,b){return"string"!=typeof a?a:isNaN(a)?(a=b.weekdaysParse(a),"number"==typeof a?a:null):parseInt(a,10)}function bc(a,b){return c(this._weekdays)?this._weekdays[a.day()]:this._weekdays[this._weekdays.isFormat.test(b)?"format":"standalone"][a.day()]}function cc(a){return this._weekdaysShort[a.day()]}function dc(a){return this._weekdaysMin[a.day()]}function ec(a,b,c){var d,e,f,g=a.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],d=0;7>d;++d)f=h([2e3,1]).day(d),this._minWeekdaysParse[d]=this.weekdaysMin(f,"").toLocaleLowerCase(),this._shortWeekdaysParse[d]=this.weekdaysShort(f,"").toLocaleLowerCase(),this._weekdaysParse[d]=this.weekdays(f,"").toLocaleLowerCase();return c?"dddd"===b?(e=md.call(this._weekdaysParse,g),-1!==e?e:null):"ddd"===b?(e=md.call(this._shortWeekdaysParse,g),-1!==e?e:null):(e=md.call(this._minWeekdaysParse,g),-1!==e?e:null):"dddd"===b?(e=md.call(this._weekdaysParse,g),-1!==e?e:(e=md.call(this._shortWeekdaysParse,g),-1!==e?e:(e=md.call(this._minWeekdaysParse,g),-1!==e?e:null))):"ddd"===b?(e=md.call(this._shortWeekdaysParse,g),-1!==e?e:(e=md.call(this._weekdaysParse,g),-1!==e?e:(e=md.call(this._minWeekdaysParse,g),-1!==e?e:null))):(e=md.call(this._minWeekdaysParse,g),-1!==e?e:(e=md.call(this._weekdaysParse,g),-1!==e?e:(e=md.call(this._shortWeekdaysParse,g),-1!==e?e:null)))}function fc(a,b,c){var d,e,f;if(this._weekdaysParseExact)return ec.call(this,a,b,c);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),d=0;7>d;d++){if(e=h([2e3,1]).day(d),c&&!this._fullWeekdaysParse[d]&&(this._fullWeekdaysParse[d]=new RegExp("^"+this.weekdays(e,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[d]=new RegExp("^"+this.weekdaysShort(e,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[d]=new RegExp("^"+this.weekdaysMin(e,"").replace(".",".?")+"$","i")),this._weekdaysParse[d]||(f="^"+this.weekdays(e,"")+"|^"+this.weekdaysShort(e,"")+"|^"+this.weekdaysMin(e,""),this._weekdaysParse[d]=new RegExp(f.replace(".",""),"i")),c&&"dddd"===b&&this._fullWeekdaysParse[d].test(a))return d;if(c&&"ddd"===b&&this._shortWeekdaysParse[d].test(a))return d;if(c&&"dd"===b&&this._minWeekdaysParse[d].test(a))return d;if(!c&&this._weekdaysParse[d].test(a))return d}}function gc(a){if(!this.isValid())return null!=a?this:NaN;var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=ac(a,this.localeData()),this.add(a-b,"d")):b}function hc(a){if(!this.isValid())return null!=a?this:NaN;var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")}function ic(a){return this.isValid()?null==a?this.day()||7:this.day(this.day()%7?a:a-7):null!=a?this:NaN}function jc(a){return this._weekdaysParseExact?(f(this,"_weekdaysRegex")||mc.call(this),a?this._weekdaysStrictRegex:this._weekdaysRegex):this._weekdaysStrictRegex&&a?this._weekdaysStrictRegex:this._weekdaysRegex}function kc(a){return this._weekdaysParseExact?(f(this,"_weekdaysRegex")||mc.call(this),a?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):this._weekdaysShortStrictRegex&&a?this._weekdaysShortStrictRegex:this._weekdaysShortRegex}function lc(a){return this._weekdaysParseExact?(f(this,"_weekdaysRegex")||mc.call(this),a?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):this._weekdaysMinStrictRegex&&a?this._weekdaysMinStrictRegex:this._weekdaysMinRegex}function mc(){function a(a,b){return b.length-a.length}var b,c,d,e,f,g=[],i=[],j=[],k=[];for(b=0;7>b;b++)c=h([2e3,1]).day(b),d=this.weekdaysMin(c,""),e=this.weekdaysShort(c,""),f=this.weekdays(c,""),g.push(d),i.push(e),j.push(f),k.push(d),k.push(e),k.push(f);for(g.sort(a),i.sort(a),j.sort(a),k.sort(a),b=0;7>b;b++)i[b]=Z(i[b]),j[b]=Z(j[b]),k[b]=Z(k[b]);this._weekdaysRegex=new RegExp("^("+k.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+j.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+i.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+g.join("|")+")","i")}function nc(a){var b=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")}function oc(){return this.hours()%12||12}function pc(){return this.hours()||24}function qc(a,b){R(a,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),b)})}function rc(a,b){return b._meridiemParse}function sc(a){return"p"===(a+"").toLowerCase().charAt(0)}function tc(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"}function uc(a,b){b[Sd]=r(1e3*("0."+a))}function vc(){return this._isUTC?"UTC":""}function wc(){return this._isUTC?"Coordinated Universal Time":""}function xc(a){return Ka(1e3*a)}function yc(){return Ka.apply(null,arguments).parseZone()}function zc(a,b,c){var d=this._calendar[a];return w(d)?d.call(b,c):d}function Ac(a){var b=this._longDateFormat[a],c=this._longDateFormat[a.toUpperCase()];return b||!c?b:(this._longDateFormat[a]=c.replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a])}function Bc(){return this._invalidDate}function Cc(a){return this._ordinal.replace("%d",a)}function Dc(a){return a}function Ec(a,b,c,d){var e=this._relativeTime[c];return w(e)?e(a,b,c,d):e.replace(/%d/i,a)}function Fc(a,b){var c=this._relativeTime[a>0?"future":"past"];return w(c)?c(b):c.replace(/%s/i,b)}function Gc(a,b,c,d){var e=H(),f=h().set(d,b);return e[c](f,a)}function Hc(a,b,c){if("number"==typeof a&&(b=a,a=void 0),a=a||"",null!=b)return Gc(a,b,c,"month");var d,e=[];for(d=0;12>d;d++)e[d]=Gc(a,d,c,"month");return e}function Ic(a,b,c,d){"boolean"==typeof a?("number"==typeof b&&(c=b,b=void 0),b=b||""):(b=a,c=b,a=!1,"number"==typeof b&&(c=b,b=void 0),b=b||"");var e=H(),f=a?e._week.dow:0;if(null!=c)return Gc(b,(c+f)%7,d,"day");var g,h=[];for(g=0;7>g;g++)h[g]=Gc(b,(g+f)%7,d,"day");return h}function Jc(a,b){return Hc(a,b,"months")}function Kc(a,b){return Hc(a,b,"monthsShort")}function Lc(a,b,c){return Ic(a,b,c,"weekdays")}function Mc(a,b,c){return Ic(a,b,c,"weekdaysShort")}function Nc(a,b,c){return Ic(a,b,c,"weekdaysMin")}function Oc(){var a=this._data;return this._milliseconds=Le(this._milliseconds),this._days=Le(this._days),this._months=Le(this._months),a.milliseconds=Le(a.milliseconds),a.seconds=Le(a.seconds),a.minutes=Le(a.minutes),a.hours=Le(a.hours),a.months=Le(a.months),a.years=Le(a.years),this}function Pc(a,b,c,d){var e=db(b,c);return a._milliseconds+=d*e._milliseconds,a._days+=d*e._days,a._months+=d*e._months,a._bubble()}function Qc(a,b){return Pc(this,a,b,1)}function Rc(a,b){return Pc(this,a,b,-1)}function Sc(a){return 0>a?Math.floor(a):Math.ceil(a)}function Tc(){var a,b,c,d,e,f=this._milliseconds,g=this._days,h=this._months,i=this._data;return f>=0&&g>=0&&h>=0||0>=f&&0>=g&&0>=h||(f+=864e5*Sc(Vc(h)+g),g=0,h=0),i.milliseconds=f%1e3,a=q(f/1e3),i.seconds=a%60,b=q(a/60),i.minutes=b%60,c=q(b/60),i.hours=c%24,g+=q(c/24),e=q(Uc(g)),h+=e,g-=Sc(Vc(e)),d=q(h/12),h%=12,i.days=g,i.months=h,i.years=d,this}function Uc(a){return 4800*a/146097}function Vc(a){return 146097*a/4800}function Wc(a){var b,c,d=this._milliseconds;if(a=K(a),"month"===a||"year"===a)return b=this._days+d/864e5,c=this._months+Uc(b),"month"===a?c:c/12;switch(b=this._days+Math.round(Vc(this._months)),a){case"week":return b/7+d/6048e5;case"day":return b+d/864e5;case"hour":return 24*b+d/36e5;case"minute":return 1440*b+d/6e4;case"second":return 86400*b+d/1e3;case"millisecond":return Math.floor(864e5*b)+d;default:throw new Error("Unknown unit "+a)}}function Xc(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*r(this._months/12)}function Yc(a){return function(){return this.as(a)}}function Zc(a){
return a=K(a),this[a+"s"]()}function $c(a){return function(){return this._data[a]}}function _c(){return q(this.days()/7)}function ad(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function bd(a,b,c){var d=db(a).abs(),e=_e(d.as("s")),f=_e(d.as("m")),g=_e(d.as("h")),h=_e(d.as("d")),i=_e(d.as("M")),j=_e(d.as("y")),k=e<af.s&&["s",e]||1>=f&&["m"]||f<af.m&&["mm",f]||1>=g&&["h"]||g<af.h&&["hh",g]||1>=h&&["d"]||h<af.d&&["dd",h]||1>=i&&["M"]||i<af.M&&["MM",i]||1>=j&&["y"]||["yy",j];return k[2]=b,k[3]=+a>0,k[4]=c,ad.apply(null,k)}function cd(a,b){return void 0===af[a]?!1:void 0===b?af[a]:(af[a]=b,!0)}function dd(a){var b=this.localeData(),c=bd(this,!a,b);return a&&(c=b.pastFuture(+this,c)),b.postformat(c)}function ed(){var a,b,c,d=bf(this._milliseconds)/1e3,e=bf(this._days),f=bf(this._months);a=q(d/60),b=q(a/60),d%=60,a%=60,c=q(f/12),f%=12;var g=c,h=f,i=e,j=b,k=a,l=d,m=this.asSeconds();return m?(0>m?"-":"")+"P"+(g?g+"Y":"")+(h?h+"M":"")+(i?i+"D":"")+(j||k||l?"T":"")+(j?j+"H":"")+(k?k+"M":"")+(l?l+"S":""):"P0D"}var fd,gd;gd=Array.prototype.some?Array.prototype.some:function(a){for(var b=Object(this),c=b.length>>>0,d=0;c>d;d++)if(d in b&&a.call(this,b[d],d,b))return!0;return!1};var hd=a.momentProperties=[],id=!1,jd={};a.suppressDeprecationWarnings=!1,a.deprecationHandler=null;var kd;kd=Object.keys?Object.keys:function(a){var b,c=[];for(b in a)f(a,b)&&c.push(b);return c};var ld,md,nd={},od={},pd=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,qd=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,rd={},sd={},td=/\d/,ud=/\d\d/,vd=/\d{3}/,wd=/\d{4}/,xd=/[+-]?\d{6}/,yd=/\d\d?/,zd=/\d\d\d\d?/,Ad=/\d\d\d\d\d\d?/,Bd=/\d{1,3}/,Cd=/\d{1,4}/,Dd=/[+-]?\d{1,6}/,Ed=/\d+/,Fd=/[+-]?\d+/,Gd=/Z|[+-]\d\d:?\d\d/gi,Hd=/Z|[+-]\d\d(?::?\d\d)?/gi,Id=/[+-]?\d+(\.\d{1,3})?/,Jd=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,Kd={},Ld={},Md=0,Nd=1,Od=2,Pd=3,Qd=4,Rd=5,Sd=6,Td=7,Ud=8;md=Array.prototype.indexOf?Array.prototype.indexOf:function(a){var b;for(b=0;b<this.length;++b)if(this[b]===a)return b;return-1},R("M",["MM",2],"Mo",function(){return this.month()+1}),R("MMM",0,0,function(a){return this.localeData().monthsShort(this,a)}),R("MMMM",0,0,function(a){return this.localeData().months(this,a)}),J("month","M"),W("M",yd),W("MM",yd,ud),W("MMM",function(a,b){return b.monthsShortRegex(a)}),W("MMMM",function(a,b){return b.monthsRegex(a)}),$(["M","MM"],function(a,b){b[Nd]=r(a)-1}),$(["MMM","MMMM"],function(a,b,c,d){var e=c._locale.monthsParse(a,d,c._strict);null!=e?b[Nd]=e:j(c).invalidMonth=a});var Vd=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/,Wd="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),Xd="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),Yd=Jd,Zd=Jd,$d=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/,_d=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/,ae=/Z|[+-]\d\d(?::?\d\d)?/,be=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],ce=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],de=/^\/?Date\((\-?\d+)/i;a.createFromInputFallback=u("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}),R("Y",0,0,function(){var a=this.year();return 9999>=a?""+a:"+"+a}),R(0,["YY",2],0,function(){return this.year()%100}),R(0,["YYYY",4],0,"year"),R(0,["YYYYY",5],0,"year"),R(0,["YYYYYY",6,!0],0,"year"),J("year","y"),W("Y",Fd),W("YY",yd,ud),W("YYYY",Cd,wd),W("YYYYY",Dd,xd),W("YYYYYY",Dd,xd),$(["YYYYY","YYYYYY"],Md),$("YYYY",function(b,c){c[Md]=2===b.length?a.parseTwoDigitYear(b):r(b)}),$("YY",function(b,c){c[Md]=a.parseTwoDigitYear(b)}),$("Y",function(a,b){b[Md]=parseInt(a,10)}),a.parseTwoDigitYear=function(a){return r(a)+(r(a)>68?1900:2e3)};var ee=M("FullYear",!0);a.ISO_8601=function(){};var fe=u("moment().min is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var a=Ka.apply(null,arguments);return this.isValid()&&a.isValid()?this>a?this:a:l()}),ge=u("moment().max is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var a=Ka.apply(null,arguments);return this.isValid()&&a.isValid()?a>this?this:a:l()}),he=function(){return Date.now?Date.now():+new Date};Qa("Z",":"),Qa("ZZ",""),W("Z",Hd),W("ZZ",Hd),$(["Z","ZZ"],function(a,b,c){c._useUTC=!0,c._tzm=Ra(Hd,a)});var ie=/([\+\-]|\d\d)/gi;a.updateOffset=function(){};var je=/^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?\d*)?$/,ke=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;db.fn=Oa.prototype;var le=ib(1,"add"),me=ib(-1,"subtract");a.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",a.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var ne=u("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(a){return void 0===a?this.localeData():this.locale(a)});R(0,["gg",2],0,function(){return this.weekYear()%100}),R(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Pb("gggg","weekYear"),Pb("ggggg","weekYear"),Pb("GGGG","isoWeekYear"),Pb("GGGGG","isoWeekYear"),J("weekYear","gg"),J("isoWeekYear","GG"),W("G",Fd),W("g",Fd),W("GG",yd,ud),W("gg",yd,ud),W("GGGG",Cd,wd),W("gggg",Cd,wd),W("GGGGG",Dd,xd),W("ggggg",Dd,xd),_(["gggg","ggggg","GGGG","GGGGG"],function(a,b,c,d){b[d.substr(0,2)]=r(a)}),_(["gg","GG"],function(b,c,d,e){c[e]=a.parseTwoDigitYear(b)}),R("Q",0,"Qo","quarter"),J("quarter","Q"),W("Q",td),$("Q",function(a,b){b[Nd]=3*(r(a)-1)}),R("w",["ww",2],"wo","week"),R("W",["WW",2],"Wo","isoWeek"),J("week","w"),J("isoWeek","W"),W("w",yd),W("ww",yd,ud),W("W",yd),W("WW",yd,ud),_(["w","ww","W","WW"],function(a,b,c,d){b[d.substr(0,1)]=r(a)});var oe={dow:0,doy:6};R("D",["DD",2],"Do","date"),J("date","D"),W("D",yd),W("DD",yd,ud),W("Do",function(a,b){return a?b._ordinalParse:b._ordinalParseLenient}),$(["D","DD"],Od),$("Do",function(a,b){b[Od]=r(a.match(yd)[0],10)});var pe=M("Date",!0);R("d",0,"do","day"),R("dd",0,0,function(a){return this.localeData().weekdaysMin(this,a)}),R("ddd",0,0,function(a){return this.localeData().weekdaysShort(this,a)}),R("dddd",0,0,function(a){return this.localeData().weekdays(this,a)}),R("e",0,0,"weekday"),R("E",0,0,"isoWeekday"),J("day","d"),J("weekday","e"),J("isoWeekday","E"),W("d",yd),W("e",yd),W("E",yd),W("dd",function(a,b){return b.weekdaysMinRegex(a)}),W("ddd",function(a,b){return b.weekdaysShortRegex(a)}),W("dddd",function(a,b){return b.weekdaysRegex(a)}),_(["dd","ddd","dddd"],function(a,b,c,d){var e=c._locale.weekdaysParse(a,d,c._strict);null!=e?b.d=e:j(c).invalidWeekday=a}),_(["d","e","E"],function(a,b,c,d){b[d]=r(a)});var qe="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),re="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),se="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),te=Jd,ue=Jd,ve=Jd;R("DDD",["DDDD",3],"DDDo","dayOfYear"),J("dayOfYear","DDD"),W("DDD",Bd),W("DDDD",vd),$(["DDD","DDDD"],function(a,b,c){c._dayOfYear=r(a)}),R("H",["HH",2],0,"hour"),R("h",["hh",2],0,oc),R("k",["kk",2],0,pc),R("hmm",0,0,function(){return""+oc.apply(this)+Q(this.minutes(),2)}),R("hmmss",0,0,function(){return""+oc.apply(this)+Q(this.minutes(),2)+Q(this.seconds(),2)}),R("Hmm",0,0,function(){return""+this.hours()+Q(this.minutes(),2)}),R("Hmmss",0,0,function(){return""+this.hours()+Q(this.minutes(),2)+Q(this.seconds(),2)}),qc("a",!0),qc("A",!1),J("hour","h"),W("a",rc),W("A",rc),W("H",yd),W("h",yd),W("HH",yd,ud),W("hh",yd,ud),W("hmm",zd),W("hmmss",Ad),W("Hmm",zd),W("Hmmss",Ad),$(["H","HH"],Pd),$(["a","A"],function(a,b,c){c._isPm=c._locale.isPM(a),c._meridiem=a}),$(["h","hh"],function(a,b,c){b[Pd]=r(a),j(c).bigHour=!0}),$("hmm",function(a,b,c){var d=a.length-2;b[Pd]=r(a.substr(0,d)),b[Qd]=r(a.substr(d)),j(c).bigHour=!0}),$("hmmss",function(a,b,c){var d=a.length-4,e=a.length-2;b[Pd]=r(a.substr(0,d)),b[Qd]=r(a.substr(d,2)),b[Rd]=r(a.substr(e)),j(c).bigHour=!0}),$("Hmm",function(a,b,c){var d=a.length-2;b[Pd]=r(a.substr(0,d)),b[Qd]=r(a.substr(d))}),$("Hmmss",function(a,b,c){var d=a.length-4,e=a.length-2;b[Pd]=r(a.substr(0,d)),b[Qd]=r(a.substr(d,2)),b[Rd]=r(a.substr(e))});var we=/[ap]\.?m?\.?/i,xe=M("Hours",!0);R("m",["mm",2],0,"minute"),J("minute","m"),W("m",yd),W("mm",yd,ud),$(["m","mm"],Qd);var ye=M("Minutes",!1);R("s",["ss",2],0,"second"),J("second","s"),W("s",yd),W("ss",yd,ud),$(["s","ss"],Rd);var ze=M("Seconds",!1);R("S",0,0,function(){return~~(this.millisecond()/100)}),R(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),R(0,["SSS",3],0,"millisecond"),R(0,["SSSS",4],0,function(){return 10*this.millisecond()}),R(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),R(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),R(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),R(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),R(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),J("millisecond","ms"),W("S",Bd,td),W("SS",Bd,ud),W("SSS",Bd,vd);var Ae;for(Ae="SSSS";Ae.length<=9;Ae+="S")W(Ae,Ed);for(Ae="S";Ae.length<=9;Ae+="S")$(Ae,uc);var Be=M("Milliseconds",!1);R("z",0,0,"zoneAbbr"),R("zz",0,0,"zoneName");var Ce=o.prototype;Ce.add=le,Ce.calendar=kb,Ce.clone=lb,Ce.diff=sb,Ce.endOf=Eb,Ce.format=wb,Ce.from=xb,Ce.fromNow=yb,Ce.to=zb,Ce.toNow=Ab,Ce.get=P,Ce.invalidAt=Nb,Ce.isAfter=mb,Ce.isBefore=nb,Ce.isBetween=ob,Ce.isSame=pb,Ce.isSameOrAfter=qb,Ce.isSameOrBefore=rb,Ce.isValid=Lb,Ce.lang=ne,Ce.locale=Bb,Ce.localeData=Cb,Ce.max=ge,Ce.min=fe,Ce.parsingFlags=Mb,Ce.set=P,Ce.startOf=Db,Ce.subtract=me,Ce.toArray=Ib,Ce.toObject=Jb,Ce.toDate=Hb,Ce.toISOString=vb,Ce.toJSON=Kb,Ce.toString=ub,Ce.unix=Gb,Ce.valueOf=Fb,Ce.creationData=Ob,Ce.year=ee,Ce.isLeapYear=ta,Ce.weekYear=Qb,Ce.isoWeekYear=Rb,Ce.quarter=Ce.quarters=Wb,Ce.month=ha,Ce.daysInMonth=ia,Ce.week=Ce.weeks=$b,Ce.isoWeek=Ce.isoWeeks=_b,Ce.weeksInYear=Tb,Ce.isoWeeksInYear=Sb,Ce.date=pe,Ce.day=Ce.days=gc,Ce.weekday=hc,Ce.isoWeekday=ic,Ce.dayOfYear=nc,Ce.hour=Ce.hours=xe,Ce.minute=Ce.minutes=ye,Ce.second=Ce.seconds=ze,Ce.millisecond=Ce.milliseconds=Be,Ce.utcOffset=Ua,Ce.utc=Wa,Ce.local=Xa,Ce.parseZone=Ya,Ce.hasAlignedHourOffset=Za,Ce.isDST=$a,Ce.isDSTShifted=_a,Ce.isLocal=ab,Ce.isUtcOffset=bb,Ce.isUtc=cb,Ce.isUTC=cb,Ce.zoneAbbr=vc,Ce.zoneName=wc,Ce.dates=u("dates accessor is deprecated. Use date instead.",pe),Ce.months=u("months accessor is deprecated. Use month instead",ha),Ce.years=u("years accessor is deprecated. Use year instead",ee),Ce.zone=u("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",Va);var De=Ce,Ee={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Fe={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},Ge="Invalid date",He="%d",Ie=/\d{1,2}/,Je={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Ke=A.prototype;Ke._calendar=Ee,Ke.calendar=zc,Ke._longDateFormat=Fe,Ke.longDateFormat=Ac,Ke._invalidDate=Ge,Ke.invalidDate=Bc,Ke._ordinal=He,Ke.ordinal=Cc,Ke._ordinalParse=Ie,Ke.preparse=Dc,Ke.postformat=Dc,Ke._relativeTime=Je,Ke.relativeTime=Ec,Ke.pastFuture=Fc,Ke.set=y,Ke.months=ca,Ke._months=Wd,Ke.monthsShort=da,Ke._monthsShort=Xd,Ke.monthsParse=fa,Ke._monthsRegex=Zd,Ke.monthsRegex=ka,Ke._monthsShortRegex=Yd,Ke.monthsShortRegex=ja,Ke.week=Xb,Ke._week=oe,Ke.firstDayOfYear=Zb,Ke.firstDayOfWeek=Yb,Ke.weekdays=bc,Ke._weekdays=qe,Ke.weekdaysMin=dc,Ke._weekdaysMin=se,Ke.weekdaysShort=cc,Ke._weekdaysShort=re,Ke.weekdaysParse=fc,Ke._weekdaysRegex=te,Ke.weekdaysRegex=jc,Ke._weekdaysShortRegex=ue,Ke.weekdaysShortRegex=kc,Ke._weekdaysMinRegex=ve,Ke.weekdaysMinRegex=lc,Ke.isPM=sc,Ke._meridiemParse=we,Ke.meridiem=tc,E("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===r(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),a.lang=u("moment.lang is deprecated. Use moment.locale instead.",E),a.langData=u("moment.langData is deprecated. Use moment.localeData instead.",H);var Le=Math.abs,Me=Yc("ms"),Ne=Yc("s"),Oe=Yc("m"),Pe=Yc("h"),Qe=Yc("d"),Re=Yc("w"),Se=Yc("M"),Te=Yc("y"),Ue=$c("milliseconds"),Ve=$c("seconds"),We=$c("minutes"),Xe=$c("hours"),Ye=$c("days"),Ze=$c("months"),$e=$c("years"),_e=Math.round,af={s:45,m:45,h:22,d:26,M:11},bf=Math.abs,cf=Oa.prototype;cf.abs=Oc,cf.add=Qc,cf.subtract=Rc,cf.as=Wc,cf.asMilliseconds=Me,cf.asSeconds=Ne,cf.asMinutes=Oe,cf.asHours=Pe,cf.asDays=Qe,cf.asWeeks=Re,cf.asMonths=Se,cf.asYears=Te,cf.valueOf=Xc,cf._bubble=Tc,cf.get=Zc,cf.milliseconds=Ue,cf.seconds=Ve,cf.minutes=We,cf.hours=Xe,cf.days=Ye,cf.weeks=_c,cf.months=Ze,cf.years=$e,cf.humanize=dd,cf.toISOString=ed,cf.toString=ed,cf.toJSON=ed,cf.locale=Bb,cf.localeData=Cb,cf.toIsoString=u("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",ed),cf.lang=ne,R("X",0,0,"unix"),R("x",0,0,"valueOf"),W("x",Fd),W("X",Id),$("X",function(a,b,c){c._d=new Date(1e3*parseFloat(a,10))}),$("x",function(a,b,c){c._d=new Date(r(a))}),a.version="2.13.0",b(Ka),a.fn=De,a.min=Ma,a.max=Na,a.now=he,a.utc=h,a.unix=xc,a.months=Jc,a.isDate=d,a.locale=E,a.invalid=l,a.duration=db,a.isMoment=p,a.weekdays=Lc,a.parseZone=yc,a.localeData=H,a.isDuration=Pa,a.monthsShort=Kc,a.weekdaysMin=Nc,a.defineLocale=F,a.updateLocale=G,a.locales=I,a.weekdaysShort=Mc,a.normalizeUnits=K,a.relativeTimeThreshold=cd,a.prototype=De;var df=a;return df});;
//! moment.js locale configuration
//! locale : great britain english (en-gb)
//! author : Chris Gedrim : https://github.com/chrisgedrim

;(function (global, factory) {
   typeof exports === 'object' && typeof module !== 'undefined'
       && typeof require === 'function' ? factory(require('../moment')) :
   typeof define === 'function' && define.amd ? define(['moment'], factory) :
   factory(global.moment)
}(this, function (moment) { 'use strict';


    var en_gb = moment.defineLocale('en-gb', {
        months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
        monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),
        weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
        weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),
        weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
        longDateFormat : {
            LT : 'HH:mm',
            LTS : 'HH:mm:ss',
            L : 'DD/MM/YYYY',
            LL : 'D MMMM YYYY',
            LLL : 'D MMMM YYYY HH:mm',
            LLLL : 'dddd, D MMMM YYYY HH:mm'
        },
        calendar : {
            sameDay : '[Today at] LT',
            nextDay : '[Tomorrow at] LT',
            nextWeek : 'dddd [at] LT',
            lastDay : '[Yesterday at] LT',
            lastWeek : '[Last] dddd [at] LT',
            sameElse : 'L'
        },
        relativeTime : {
            future : 'in %s',
            past : '%s ago',
            s : 'a few seconds',
            m : 'a minute',
            mm : '%d minutes',
            h : 'an hour',
            hh : '%d hours',
            d : 'a day',
            dd : '%d days',
            M : 'a month',
            MM : '%d months',
            y : 'a year',
            yy : '%d years'
        },
        ordinalParse: /\d{1,2}(st|nd|rd|th)/,
        ordinal : function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
            return number + output;
        },
        week : {
            dow : 1, // Monday is the first day of the week.
            doy : 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    return en_gb;

}));;
//! moment.js locale configuration
//! locale : swedish (sv)
//! author : Jens Alm : https://github.com/ulmus

;(function (global, factory) {
   typeof exports === 'object' && typeof module !== 'undefined'
       && typeof require === 'function' ? factory(require('../moment')) :
   typeof define === 'function' && define.amd ? define(['moment'], factory) :
   factory(global.moment)
}(this, function (moment) { 'use strict';


    var sv = moment.defineLocale('sv', {
        months : 'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split('_'),
        monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'),
        weekdays : 'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'),
        weekdaysShort : 'sön_mån_tis_ons_tor_fre_lör'.split('_'),
        weekdaysMin : 'sö_må_ti_on_to_fr_lö'.split('_'),
        longDateFormat : {
            LT : 'HH:mm',
            LTS : 'HH:mm:ss',
            L : 'YYYY-MM-DD',
            LL : 'D MMMM YYYY',
            LLL : 'D MMMM YYYY [kl.] HH:mm',
            LLLL : 'dddd D MMMM YYYY [kl.] HH:mm',
            lll : 'D MMM YYYY HH:mm',
            llll : 'ddd D MMM YYYY HH:mm'
        },
        calendar : {
            sameDay: '[Idag] LT',
            nextDay: '[Imorgon] LT',
            lastDay: '[Igår] LT',
            nextWeek: '[På] dddd LT',
            lastWeek: '[I] dddd[s] LT',
            sameElse: 'L'
        },
        relativeTime : {
            future : 'om %s',
            past : 'för %s sedan',
            s : 'några sekunder',
            m : 'en minut',
            mm : '%d minuter',
            h : 'en timme',
            hh : '%d timmar',
            d : 'en dag',
            dd : '%d dagar',
            M : 'en månad',
            MM : '%d månader',
            y : 'ett år',
            yy : '%d år'
        },
        ordinalParse: /\d{1,2}(e|a)/,
        ordinal : function (number) {
            var b = number % 10,
                output = (~~(number % 100 / 10) === 1) ? 'e' :
                (b === 1) ? 'a' :
                (b === 2) ? 'a' :
                (b === 3) ? 'e' : 'e';
            return number + output;
        },
        week : {
            dow : 1, // Monday is the first day of the week.
            doy : 4  // The week that contains Jan 4th is the first week of the year.
        }
    });

    return sv;

}));;
$(function () {
    var $calendarFilterShowAll = $("body").find(".js-filter-form").find("#ShowAll_Selected");
    $calendarFilterShowAll.prop("checked", "checked");

    $("body").on("click", ".js-toggle-genres", function (e) {
        e.preventDefault();
        var $self = $(this),
            id = $self.attr("data-genrelistid"),
            $target = $("body").find("[data-typefilterid=" + id + "]"),
            $container = $self.closest(".js-filter-group"),
            isOpen = $self.attr("aria-expanded") === "true",
            $checkbox = $container.find("input[type='checkbox']");
        $("body").find("[data-typefilterid]").not($target).hide();
        $target.slideToggle(300);
        $self.toggleAttr("aria-expanded");
        $self.toggleAttr("aria-pressed");
        $("body").find(".js-toggle-genres[aria-expanded='true']").not($self).attr("aria-expanded", false);
    });

    $(".js-calendar-filter").on("change", "input[type='checkbox']", function (e) {
        e.preventDefault();
        var $self = $(this),
            isSelectAll = $self.hasClass("js-select-all"),
            isglobalSelectAll = $self.hasClass("js-select-all") && $self.closest(".js-type-filters").length,
            $ul = $self.closest("ul"),
            isTypeFilter = $ul.hasClass("js-type-filters"),
            hasGenres = $(this).attr("data-hasgenres") === "True",
            $genreToggle = $self.siblings(".js-toggle-genres"),
            genrelistid = $self.data("genrelistid"),
            $genrelisttarget = $("body").find("[data-typefilterid=" + genrelistid + "]"),
            $form = $self.closest("form"),
            $localboxes = $ul.find("input[type='checkbox']"),
            $globalboxes = $form.find("input[type='checkbox']").not($localboxes),
            $selectAll = isSelectAll ? $self : $ul.find(".js-select-all"),
            hasChecked = $ul.find("input:checked:not(.js-select-all)").length > 0,
            targetVal = $form.attr("data-target"),
            $target = $("[data-target-value=" + targetVal + "]"),
            $calendarWrapper = $self.closest(".js-calendar-filter");
        var m = $.merge($globalboxes, $localboxes);
        $self.siblings("[name$='Selected']:first").attr("value", $self.is(":checked"));
        disableboxes(m);
        if (isglobalSelectAll) {
            $form.find("input[type='checkbox']")
                .not($self)
                .each(function () {
                    $(this).removeAttr("checked");
                    $(this).siblings("[name$='Selected']:first").attr("value", false);
                });
            $form.find(".js-genre-filters").each(function () {
                $(this).hide();
            });
            $form.find(".js-toggle-genres").attr("aria-expanded", false);
        }
        else if (isSelectAll) {
            var $local = $localboxes.not($self);
            $local.each(function () {
                $(this).removeAttr("checked");
                $(this).siblings("[name$='Selected']:first").attr("value", false);
            });
            $selectAll.prop("checked", "checked");
        } else {
            $selectAll.removeAttr("checked");
        }
        if (isSelectAll && isTypeFilter) {
            $calendarWrapper.find(".js-toggle-genres[aria-expanded='true']").trigger("click");
            var $selectAll = $calendarWrapper.find(".js-select-all").not($self);
            $selectAll.each(function () {
                $(this).removeAttr("checked");
                $(this).siblings("[name$='Selected']:first").attr("value", false);
            });
        }
        if (isTypeFilter) {
            if (hasGenres) {
                $genreToggle.attr("aria-expanded", $self.is(":checked"));
                if ($self.is(":checked")) {
                    $genrelisttarget.show();
                    $("body").find(".js-genre-filters.level-2").not($genrelisttarget).hide();
                    $("body").find(".js-toggle-genres").not($genreToggle).attr("aria-expanded", false);
                    $genrelisttarget.find(".js-select-all").prop("checked", "checked");
                } else {
                    $genrelisttarget.find("input[type='checkbox']").each(function () { $(this).removeAttr("checked"); $(this).siblings("[name$='Selected']:first").attr("value", false); });
                    $genrelisttarget.hide();
                }
            }
            else if (!$ul.find("[data-hasgenres='True']").is(":checked")) {
                $genrelisttarget.hide();
                $genrelisttarget.find("input[type='checkbox']:checked").each(function () {
                    $(this).removeAttr("checked");
                    $(this).siblings("[name$='Selected']:first").attr("value", false);
                });
            }
        }
        if (!isTypeFilter) {
            var typefilterid = $self.closest(".js-genre-filters").attr("data-typefilterid");
            var $parentbox = $calendarWrapper.find("[data-genrelistid=" + typefilterid + "]");
            $parentbox.prop("checked", "checked");
            $parentbox.siblings("[name$='Selected']:first").attr("value", true);

            var $selectAllTargets = isSelectAll ? $calendarWrapper.find(".js-select-all").not($self) : $calendarWrapper.find(".js-select-all");
            $selectAllTargets.each(function () { $(this).prop("checked", false); });
        }

        $target.html("<div class='text-center js-temp-load' aria-live='polite' aria-busy='true'><img alt='loading' src='/Static/icons/loader.svg'/></div>");

        var $selecteddate = $(".js-calendar-slide").find("li.js-selected-date");
        var firstOfMonth = $(".js-calendar-slide").find("li.firstOfMonth");
        var dateValue = $selecteddate.length ? $selecteddate.attr("data-fulldate") : firstOfMonth.length ? firstOfMonth.attr("data-fulldate") : "";

        var currentView = "normal";
        if ($(".jsChangeView.active").length === 1) {
            var currentView = $(".jsChangeView.active").data("currentview");
        }

        var data = $form.serialize();

        $.ajax({
            type: "POST",
            dataType: "html",
            url: $form.attr("action"),
            data: data + "&selectedDate=" + dateValue + "&lang=" + $("html").attr("lang") + "&viewType=" + currentView,
            success: function (response) {
                $target.hide().html(response).fadeIn("300", function () {
                    window.slimmage.checkResponsiveImages();
                    hideOtherDateIfBiggerThanMax($("body"));

                    $('.equalizeMe').matchHeight();

                    enableboxes($.merge($globalboxes, $localboxes));
                    if (!hasChecked) {
                        $selectAll.prop("checked", "checked");
                        $selectAll.siblings("[name$='Selected']:first").attr("value", true);
                        $selectAll.prop("disabled", "disabled");
                    } else if (!isSelectAll) {
                        $selectAll.removeAttr("checked disabled");
                        $selectAll.siblings("[name$='Selected']:first").attr("value", false);
                    }
                });
            }
        });
    });
});

function disableboxes($boxes) {
    $boxes.attr("disabled", "disabled");
}
function enableboxes($boxes) {
    $boxes.removeAttr("disabled");
}

function navigateToAnchor(href, $target) {
    $.get(href, function (response) {
        $target.hide().html(response).show();
    });
}
;
$(function () {
    //var d = dateHandler || {};
    var lang = $("html").attr("lang");
    moment().locale(lang).format('LLL');
    var $slide = $(".js-calendar-slide"),
        $updateTarget = $slide.find(".js-body"),
        $select = $slide.find(".js-select-month"),
        $slideResult = $(".js-slie-result"),
        amountToLoad = $(window).width() > 768 ? 10 : 7,
        initLoadAmount = 31,
        yesterday = moment().subtract(1, "days"),
        endOfMonth = moment().endOf('month');

    $("body").on("click", ".jsChangeView", function (e) {
        e.preventDefault();

        var currentView = $(this).data("currentview");

        if (currentView == "small") {
            $(".button-overview-view").removeClass("active");
            $(".button-detaild-view").addClass("active");

            $(".button-overview-view").attr("aria-selected", false);
            $(".button-detaild-view").attr("aria-selected", true);
        } else {
            $(".button-overview-view").addClass("active");
            $(".button-detaild-view").removeClass("active");

            $(".button-overview-view").attr("aria-selected", true);
            $(".button-detaild-view").attr("aria-selected", false);
        }

        if ($(".active.js-selected-date").length == 1) {
            if ($(".active.js-selected-date").parent().find(".noEvents").length == 0) {
                $(".active.js-selected-date").find("button").trigger("click");
            } else {
                $(".active.js-selected-date").removeClass("noEvents");
                $(".active.js-selected-date").find("button").trigger("click");
                $(".active.js-selected-date").addClass("noEvents");
            }
        } else {
            $(".js-select-month").trigger("change");
        }
    });

    $("body").on("click", ".jsPrint", function (e) {
        e.preventDefault();

        window.print();
    });
    

    $(".js-nav").on("click", "button", function (e) {
        e.preventDefault();

        var $self = $(this),
            $parent = $self.closest(".js-nav"),
            isAhead = $parent.hasClass("js-next"),
            loadFrom = moment($parent.attr("data-begin")),
            days = [];
        $slide.find("[data-fulldate]").each(function () { days.push($(this).attr("data-fulldate")) });
        var loaded = isAhead ? addDays(days, amountToLoad) : subtractDays(days, amountToLoad, initLoadAmount);
        var result = isAhead ? loadArrangements($self, loaded.start.clone().add(1, 'days'), loaded.end.subtract(1, 'days'), $updateTarget, true) : loadArrangements($self, loaded.start.clone().subtract(1, 'days'), loaded.end, $updateTarget, false);
        updateDateAttr($parent, loaded.end);
        updateDateAttr($slide.find(".js-nav").not($parent), loaded.start);
        //$updateTarget.hide("slide", { direction: (isAhead ? "left" : "right") }).html(loaded.days).show("slide", { direction: (isAhead ? "right" : "left") });
        $select.val('');
        $self.delay(isAhead ? 3000 : 6000)
            .queue(function (next) {
                $self.removeAttr("disabled");
                next();
            });
        var windowwidth = $(window).width();
        if (windowwidth < 900) {
            var vcount = 0;
            var $target = $(".js-calendar-slide").find(".js-body").find("li:first").find("span:not(.month):hidden:first");

            var $lis = $(".js-calendar-slide").find("[data-fulldate]:visible");
            if (!$lis.length) {
                $lis = $(".js-calendar-slide").find("[data-fulldate]").slice(0, 7);
            }
            $lis.each(function () {
                var $visibles = $(this).find("span").not(".month, .date, .dayname");
                $visibles.each(function () {
                    if (windowwidth > 500) {
                        var $li = $(this).closest("li");
                        if (isAhead) {
                            if (typeof $li.attr("style") !== "undefined") {
                                if ($li.attr("style").indexOf("list-item") > 0) {
                                    $(this).parent().attr("style", "padding-right:50%;");
                                } else {
                                    $(this).parent().removeAttr("style");
                                }
                            }
                        } else {
                            $(this).parent().attr("style", "padding-right:50%;");
                        }
                    }
                    if ($(this).html() === $target.html()) {
                        $(this).hide();
                    }
                });

                vcount += $visibles.length;
            });
            if (windowwidth > 500) {
                var $li = $target.closest("li");
                if (isAhead) {

                    if (typeof $li.attr("style") !== "undefined") {
                        if ($li.attr("style").indexOf("list-item") > 0) {
                            $target.parent().attr("style", "padding-right:50%;");
                        } else {
                            $target.parent().removeAttr("style");
                        }
                    }
                } else {
                    $target.parent().attr("style", "padding-right:50%;");
                }
            }
            $target.show();
        }
    });

    $("body").on("click", ".js-calendar-load-more", function (e) {
        e.preventDefault();
        var $self = $(this),
            take = parseInt($self.attr("data-take")),
            $container = $self.closest(".js-calendar-results"),
            $li = $self.closest("li"),
            amount = parseInt($li.prevAll("li").length),
            skip = amount,
            $calendarWrapper = $("body").find(".js-calendar-wrapper"),
            $filterParent = $self.closest(".js-filter-wrapper"),
            $filterContainer = $("body").find(".js-calendar-filter");
        var getpreviusli = $self.parent("li").prev("li");
    
        $self.attr("disabled", "disabled");
        var typefilters = [];
        var genres = [];

        var $typefillterul = $filterContainer.find(".js-type-filters:first");

        var $selectedTypeFilters = $typefillterul.find(":checked");
        $selectedTypeFilters.each(function () {
            var $curr = $(this),
                genrelistId = $curr.attr("data-genrelistid"),
                genres = [];
            if (typeof $curr.attr("data-genrelistid") !== 'undefined') {
                var $genrelist = $filterContainer.find("[data-typefilterid=" + genrelistId + "]");
                if ($genrelist.length) {
                    var $checkedboxes = $genrelist.find(":checked").not(".js-select-all");
                    $checkedboxes.each(function () {
                        var $hiddensibling = $(this).siblings("[name$='Id']");
                        genres.push(parseInt($hiddensibling.val()));
                    });
                }
            }
            var $hiddentypesibling = $curr.siblings("[name$='Id']");

            if ($hiddentypesibling.val() != 0 && !genres.length) {
                genres.push(1337);
            }
            typefilters.push({ Key: parseInt($hiddentypesibling.val()), Value: genres });
        });

        var $genreAndTypeBlock = $self.closest(".js-genre-and-type-block");

        if ($genreAndTypeBlock.length) {
            var type = $genreAndTypeBlock.attr("data-type"),
                genre = $genreAndTypeBlock.attr("data-genre");
            typeFilters = [];
            genres = [];
            genres.push(parseInt(genre));
            typefilters.push({ Key: parseInt(type), Value: genres });
        }

        var $selecteddate = $calendarWrapper.find("li.js-selected-date");
        var $lis = $(".js-calendar-results").find("li[data-fulldate]").not(".no-border");
        var lastDate = $lis.last().attr("data-fulltime");

        var currentView = "normal";
        if ($(".jsChangeView.active").length === 1) {
            var currentView = $(".jsChangeView.active").data("currentview");
        }

        if (currentView == "small") {
            $(".js-calendar-load-more").hide();
        }

        $("<div class='text-center js-temp-load' aria-live='polite' aria-busy='true'><img alt='loading' src='/Static/icons/loader.svg'/></div>").insertBefore($li);
        $.ajax({
            url: "/CalendarSlideBlock/LoadMore",
            dataType: "json",
            method: "POST",
            data: { date: lastDate, skip: skip, typefilters: typefilters, lang: $("html").attr("lang"), viewType: currentView },
            success: function (response) {
                var $markupResponse = $(response.Html),
                    $targetToReplace = $li.siblings(".js-temp-load:first");
                $markupResponse.hide();
                $targetToReplace.replaceWith($markupResponse);

                if (currentView == "normal") {
                    $markupResponse.fadeIn("300",
                        function() {
                            window.slimmage.checkResponsiveImages();
                            hideOtherDateIfBiggerThanMax($("body"));

                            $('.equalizeMe').matchHeight();
                            //var $firstLi = $markupResponse.children();
                            //$firstLi.find("button").focus();

                            //focus on first loaded item
                            getpreviusli.next("li").find(".js-arrangement-result-toggle").focus();
                            $self.removeAttr("disabled");
                            if (response.HideSelf) {
                                $self.hide();
                            }
                        });
                }
                else
                {
                    var seen = {};
                    $($(".js-calendar-results li.jsArrangementItem")).each(function() {
                        var dataId = $(this).data("id");
                        if (seen[dataId]) {
                            $(this).remove();
                        } else {
                            seen[dataId] = true;
                        }
                    });

                    $(".js-calendar-results").find("li").show();
                }

            }, error: function (xhr) {

            }
        });
    });

    $("body").on("click", ".js-calendar-load-more-serie-normal", function (e) {
        e.preventDefault();
        var $self = $(this),
            take = parseInt($self.attr("data-take")),
            $container = $self.closest(".js-calendar-results"),
            $li = $self.closest("li"),
            amount = parseInt($li.prevAll("li").length),
            skip = amount,
            $calendarWrapper = $("body").find(".js-calendar-wrapper"),
            getpreviusli = $self.parent("li").prev("li");
        contentguid = $(".js-calender-serie-wrapper").data("contentguid");

        $self.attr("disabled", "disabled");

        var $lis = $(".js-calendar-results").find("li[data-fulldate]").not(".no-border");

        var currentView = "normal";
        if ($(".jsChangeView.active").length === 1) {
            var currentView = $(".jsChangeView.active").data("currentview");
        }

        if (currentView === "small") {
            $(".js-calendar-load-more").hide();
        }

        $("<div class='text-center js-temp-load' aria-live='polite' aria-busy='true'><img alt='loading' src='/Static/icons/loader.svg'/></div>").insertBefore($li);
        $.ajax({
            url: "/CalendarSeriePage/LoadMoreNormal",
            dataType: "json",
            method: "POST",
            data: { guid: contentguid, skip: skip, lang: $("html").attr("lang") },
            success: function (response) {
                var $markupResponse = $(response.Html),
                    $targetToReplace = $li.siblings(".js-temp-load:first");
                $markupResponse.hide();
                $targetToReplace.replaceWith($markupResponse);

                if (currentView === "normal") {
                    $markupResponse.fadeIn("300",
                        function () {
                            window.slimmage.checkResponsiveImages();
                            hideOtherDateIfBiggerThanMax($("body"));

                            $('.equalizeMe').matchHeight();
                            var $firstLi = $markupResponse.children();
                            $firstLi.find("button").focus();
                            //focus on first loaded item
                            getpreviusli.next("li").find(".js-arrangement-result-toggle").focus();
                            //var $toggleButtons = $markupResponse.find(".jsToggleButton, .jsToggleSubButton");
                            //$toggleButtons.each(function () {
                            //    if (!$(this).attr("aria-expanded")) {
                            //        $(this).click();
                            //    }
                            //});
                            $self.removeAttr("disabled");
                            if (response.HideSelf) {
                                $self.hide();
                            }
                        });
                }
                else {
                    var seen = {};
                    $($(".js-calendar-results li.jsArrangementItem")).each(function () {
                        var dataId = $(this).data("id");
                        if (seen[dataId]) {
                            $(this).remove();
                        } else {
                            seen[dataId] = true;
                        }
                    });

                    $(".js-calendar-results").find("li").show();
                }

            }, error: function (xhr) {

            }
        });
    });

    $("body").on("click", ".js-calendar-load-more-serie-passed", function (e) {
        e.preventDefault();
        var $self = $(this),
            take = parseInt($self.attr("data-take")),
            $container = $self.closest(".js-calendar-results"),
            $li = $self.closest("li"),
            amount = parseInt($li.prevAll("li").length),
            skip = amount,
            $calendarWrapper = $("body").find(".js-calendar-wrapper"),
            getpreviusli = $self.parent("li").prev("li");
        contentguid = $(".js-calender-serie-wrapper").data("contentguid");

        $self.attr("disabled", "disabled");

        var $lis = $(".js-calendar-results").find("li[data-fulldate]").not(".no-border");

        var currentView = "normal";
        if ($(".jsChangeView.active").length === 1) {
            var currentView = $(".jsChangeView.active").data("currentview");
        }

        if (currentView === "small") {
            $(".js-calendar-load-more").hide();
        }

        $("<div class='text-center js-temp-load' aria-live='polite' aria-busy='true'><img alt='loading' src='/Static/icons/loader.svg'/></div>").insertBefore($li);
        $.ajax({
            url: "/CalendarSeriePage/LoadMorePassed",
            dataType: "json",
            method: "POST",
            data: { guid: contentguid, skip: skip, lang: $("html").attr("lang") },
            success: function (response) {
                var $markupResponse = $(response.Html),
                    $targetToReplace = $li.siblings(".js-temp-load:first");
                $markupResponse.hide();
                $targetToReplace.replaceWith($markupResponse);

                if (currentView === "normal") {
                    $markupResponse.fadeIn("300",
                        function () {
                            window.slimmage.checkResponsiveImages();
                            hideOtherDateIfBiggerThanMax($("body"));

                            $('.equalizeMe').matchHeight();
                            var $firstLi = $markupResponse.children();
                            $firstLi.find("button").focus();
                            //focus on first loaded item
                            getpreviusli.next("li").find(".js-arrangement-result-toggle").focus();
                            //var $toggleButtons = $markupResponse.find(".jsToggleButton, .jsToggleSubButton");
                            //$toggleButtons.each(function () {
                            //    if (!$(this).attr("aria-expanded")) {
                            //        $(this).click();
                            //    }
                            //});
                            $self.removeAttr("disabled");
                            if (response.HideSelf) {
                                $self.hide();
                            }
                        });
                }
                else {
                    var seen = {};
                    $($(".js-calendar-results li.jsArrangementItem")).each(function () {
                        var dataId = $(this).data("id");
                        if (seen[dataId]) {
                            $(this).remove();
                        } else {
                            seen[dataId] = true;
                        }
                    });

                    $(".js-calendar-results").find("li").show();
                }

            }, error: function (xhr) {

            }
        });
    });

    $(".js-body").on("click", "button:not(.js-month)", function (e) {
        e.preventDefault();
        var $self = $(this),
            $li = $self.closest("li"),
            hasDates = !$li.hasClass("noEvents"),
            $lisiblings = $li.siblings("li");

        if (!hasDates) {
            return false;
        }

        $slideResult.html("<div class='text-center js-temp-load' aria-live='polite' aria-busy='true'><img alt='loading' src='/Static/icons/loader.svg'/></div>");
        var date = $li.attr("data-fulldate"), $wrapper = $self.closest(".js-navigated-content");
        var typefilters = getFilterDictionary($wrapper);

        var currentView = "normal";
        if ($(".jsChangeView.active").length === 1) {
            var currentView = $(".jsChangeView.active").data("currentview");
        }

        console.log(typefilters);
        $li.addClass("active");
        $lisiblings.removeClass("active");
        $.ajax({
            url: '/CalendarSlideBlock/LoadDate',
            method: "POST",
            dataType: "html",
            data: { date: date, typefilters: typefilters, lang: $("html").attr("lang"), viewType: currentView },
            success: function (response) {
                $slideResult.hide().html(response).fadeIn("300", function () {
                    window.slimmage.checkResponsiveImages();
                    hideOtherDateIfBiggerThanMax($("body"));

                    $('.equalizeMe').matchHeight();
                    $lisiblings.find("button").attr("aria-pressed", "false");
                    
                    $self.attr("aria-pressed", "true");
                    $li.addClass("js-selected-date");
                    $lisiblings.removeClass("js-selected-date");
                    $select.val('');
                });
            }, error: function (xhr) {
                console.error(xhr.responseText);
            }
        });
    });

    $(".js-select-month").on("change", function (e) {
        e.preventDefault();
        e.stopImmediatePropagation();
        var $self = $(this);
        if ($self.val() !== "undefined" && $self.val() !== "") {
            ModifyDropdown($self, false, initLoadAmount, $slide);
        }
    }).on("keydown", function (e) {
    }).on("change", function (e) {
        e.preventDefault();
        var $self = $(this);
        ModifyDropdown($self, false, initLoadAmount, $slide);
    });

    ////ONLOAD
    runOnload($select, $slide, initLoadAmount, yesterday, endOfMonth, $updateTarget, amountToLoad);
});

function getFilterDictionary($filterContainer) {
    var typefilters = [];
    var genres = [];

    var $typefillterul = $filterContainer.find(".js-type-filters:first");

    var $selectedTypeFilters = $typefillterul.find(":checked");
    $selectedTypeFilters.each(function () {
        var $curr = $(this),
            genrelistId = $curr.attr("data-genrelistid"),
            genres = [];
        if (typeof $curr.attr("data-genrelistid") !== 'undefined') {
            var $genrelist = $filterContainer.find("[data-typefilterid=" + genrelistId + "]");
            if ($genrelist.length) {
                var $checkedboxes = $genrelist.find(":checked").not(".js-select-all");
                $checkedboxes.each(function () {
                    var $hiddensibling = $(this).siblings("[name$='Id']");
                    genres.push(parseInt($hiddensibling.val()));
                });
            }
        }

        var $hiddentypesibling = $curr.siblings("[name$='Id']");
        if ($hiddentypesibling.val() != 0 && !genres.length) {
            genres.push(1337);
        }
        typefilters.push({ Key: parseInt($hiddentypesibling.val()), Value: genres });
    });
    return typefilters;
}

function ModifyDropdown($self, iskeyDown, initLoadAmount, $slide) {
    var splittedVal = $self.val().split('|'),
        year = parseInt(splittedVal[0]),
        month = parseInt(splittedVal[1]);
    $wrapper = $self.closest(".js-navigated-content");

    var typefilters = getFilterDictionary($wrapper);

    var currentView = "normal";
    if ($(".jsChangeView.active").length === 1) {
        var currentView = $(".jsChangeView.active").data("currentview");
    }

    $slideResult = $(".js-calendar-results"),
        $slideResult.html("<div class='text-center js-temp-load' aria-live='polite' aria-busy='true'><img alt='loading' src='/Static/icons/loader.svg'/></div>");

    console.log(typefilters);
    $.ajax({
        url: '/CalendarSlideBlock/LoadArrangeMentsByMonth',
        method: "POST",
        dataType: "json",
        data: { year: year, month: month, amountToLoad: initLoadAmount, typefilters: typefilters, lang: $("html").attr("lang"), viewType: currentView },
        beforeSend: function () {
            $self.attr("disabled", "disabled");
        },
        success: function (response) {
            var parsedResponse = $(response);
            var renderedDates = $(response.RenderedDates);

            var $ul = $(".js-body").find("ul:first").empty();

            for (var i = 0; i < renderedDates.length - 1; i++) {
                $ul.append($(renderedDates[i]).hide().fadeIn("300"));
            }

            var first = renderedDates[0];
            var last = renderedDates[renderedDates.length - 1];
            var firstdate = $(first).attr("data-fulldate");
            var lastdate = $(last).attr("data-fulldate");


            updateDateAttr($slide.find(".js-next"), moment(lastdate).clone().add(1, 'days'));
            updateDateAttr($slide.find(".js-prev"), moment(firstdate).clone().subtract(1, 'days'));

            var $markupTarget = $("body").find(".js-calendar-results");
            $markupTarget.hide();
            $markupTarget.replaceWith(response.Html);

            var $newtarget = $("body").find(".js-calendar-results");
            window.slimmage.checkResponsiveImages();
            hideOtherDateIfBiggerThanMax($("body"));

            $('.equalizeMe').matchHeight();
            $newtarget.hide().fadeIn("300");

            $self.delay(400).queue(function (next) {
                $self.removeAttr("disabled").focus();
                next();
            });

        }, error: function (xhr) {
            //console.error(xhr.responseText);
        }
    });
}
function getFilters($container) {
    var $typeFilterUl = $container.find(".js-type-filters"),
        $genreFilterUl = $container.find(".js-genre-filters");
    var types = [];
    var genres = [];
    if ($typeFilterUl.length) {
        var $selected = $typeFilterUl.find("input[type='checkbox']:checked").not(".js-select-all");
        $selected.each(function () {
            var $sibling = $(this).siblings("input[type='hidden']");
            types.push(parseInt($sibling.val()));
        });
    }
    if ($genreFilterUl.length && $genreFilterUl.is(":visible")) {
        var $selected = $genreFilterUl.find("input[type='checkbox']:checked").not(".js-select-all");
        $selected.each(function () {
            var $sibling = $(this).siblings("input[type='hidden']");
            genres.push(parseInt($sibling.val()));
        });
    }
    var filters = {
        types: types,
        genres: genres
    };
    return filters;
}
function addDays(days, amountToLoad) {
    var e = moment(days[days.length - 1]).clone().add(amountToLoad, 'days'),
        loaded = {
            days: wrapDays(populateMarkupArr(reorderToFuture(days, amountToLoad))),
            end: e.clone().add(1, 'days'),
            start: e.clone().subtract(amountToLoad, 'days')
        };
    return loaded;
}

function subtractDays(days, amountToLoad, initLoadAmount) {
    var e = moment(days[0]).clone().subtract(amountToLoad, 'days');
    var loaded = {
        days: wrapDays(populateMarkupArr(reorderToPast(days, amountToLoad, initLoadAmount))),
        end: e.clone(),
        start: e.add(amountToLoad, 'days')
    };
    return loaded;
}

function reorderToFuture(days, amountToLoad) {
    days = $.map(days, function (item, index) {
        if (index < amountToLoad) return null; // Removes the first 10 elements;
        return item;
    });
    var last = moment(days[days.length - 1]);
    var newdays = getDatesBetween(last.clone().add(1, 'days'), last.add(amountToLoad, 'days'));
    return $.merge(days, newdays);
}

function reorderToPast(days, amountToLoad, initLoadAmount) {
    days = $.map(days, function (item, index) {
        if (index > (initLoadAmount - amountToLoad)) return null; // Removes the last 10 elements;
        return item;
    });
    var first = moment(days[0]);
    var newdays = getDatesBetweenPast(first.clone().subtract(1, 'days'), first.clone().subtract(amountToLoad, 'days'));
    return $.merge(newdays, days);
}

$(document).ajaxComplete(function () {
    console.log("finished");
});


function loadArrangements($trigger, start, end, $target, forward) {
    $.ajax({
        url: "/CalendarSlideBlock/LoadArrangements",
        cache: false,
        async: false,
        method: "POST",
        dataType: "json",
        data: { start: start.format("YYYY-MM-DD"), end: end.format("YYYY-MM-DD"), forward: forward, lang: $("html").attr("lang") },
        success: function (response) {
            if (response.length) {
                var $ul = $target.find("ul:first"),
                    existing = $ul.find("li");
                $(this).queue(function (nextqueue) {
                    if (forward) {
                        for (var j = 0; j < response.length; j++) {
                            $(existing[j]).remove();
                        }
                        for (var i = 0; i < response.length; i++) {
                            $ul.append($(response[i]).hide().delay(10 * i).queue(function (next) {
                                $(this).show("slide", { direction: "right" }, 140, function (next) { });
                                next();
                            }));
                            if (i === response.length - 1) {
                                nextqueue();
                            }
                        }
                    } else {
                        for (var j = existing.length; j > (existing.length - response.length) - 1; j--) {
                            $(existing[j]).remove();
                        }
                        for (var i = response.length; i >= 0; i--) {
                            $ul.prepend($(response[i]).hide().delay(10 * i).queue(function (next) {
                                $(this).show("slide", { direction: "left" }, 140, function (next) { });
                                next();
                            }));
                        }
                    }
                }).queue(function (next) {
                    $(this).removeAttr("disabled");
                    });

                window.slimmage.checkResponsiveImages();
                hideOtherDateIfBiggerThanMax($("body"));

                //animateSlide(forward, $ul, existing, response)
            }
            //$(this).delay(5000).queue(function (next) {
            //    $(".js-calendar-slide").find(".ui-effects-wrapper").remove();
            //});
        }
    });
}
function animateSlide(forward, $ul, existing, response) {
    var hackind = 0;
    if (forward) {
        for (var i = 0; i < response.length; i++) {
            $ul.append($(response[i]).hide());
        }
        var li = $ul.find("li");
        for (var j = 0; j < response.length; j++) {
            $(existing[j]).delay(j * 10).queue(function (next) {
                $(this).hide("slide", { direction: "left" }, 140, function () {
                    $(this).remove();
                    $(this).delay(i / 100).queue(function (next) {
                        for (var i = (existing.length + response.length); i >= existing.length; i--) {
                            $(li[i]).delay(i * 1).queue(function (next) {
                                $(this).show("slide", { direction: "right" }, 100, function () {
                                    $(li[i]).removeAttr("style");
                                });
                                next();
                            });
                        }
                        next();
                    });
                });
                next();
            });
        }
    } else {
        //workaround prepend hide and show with effect
        for (var i = response.length; i >= 0; i--) {
            $ul.prepend($(response[i]).hide());
        }
        var li = $ul.find("li");
        for (var j = existing.length; j > (existing.length - response.length) - 1; j--) {
            $(existing[j]).delay(j * 12).hide("slide", { direction: "right" }, 140, function () {
                $(this).remove();
                $(this).delay(i * 3000).queue(function (next) {
                    for (var i = 0; i < 10; i++) {
                        $(this).delay(i / 100).queue(function (next) {
                            $(li[i]).delay(i).queue(function (next) {
                                $(this).show("slide", { direction: "left" }, 100, function () {
                                    $(li[i]).removeAttr("style");
                                });
                                next();
                            });
                            next();
                        });
                        next();
                    }
                });
            });
        }
    }
    if (hackind === response.length) {
        return i;
    }
}

function runOnload($select, $slide, initLoadAmount, yesterday, endOfMonth, $updateTarget, amountToLoad) {

    ////hack
    //var $firstOption = $select.find("option:first"),
    //    $optiontext = $firstOption.text(),
    //    splitted = $optiontext.split(" ");
    //var newt = splitted[0] + " " + "m" + splitted[1].substr(1, splitted[1].length - 1);
    //console.log(newt);
    //$firstOption.html(newt);


    var currentMonth = moment().month(moment().month());
    var startAt = currentMonth.clone().subtract(2, 'months');
    var months = [];
    var showyear = false;
    //for (var i = 0; i < 12; i++) {
    //    var m = startAt.clone().add(i, 'months');
    //    showyear = (m.format("YYYY") !== currentMonth.format("YYYY") && parseInt(m.clone().month()) === 0);
    //    var month = {
    //        name: m.format("MMMM"),
    //        number: parseInt(m.format("M") - 1),
    //        year: m.format("YYYY"),
    //        current: (m.format("YYYY-M") === currentMonth.format("YYYY-M")),
    //        showyear: showyear
    //    };
    //    months.push(month);
    //}
    //for (var j = 0; j < months.length; j++) {
    //    $select.append("<option " + (months[j].current ? "selected='selected'" : "") + " value=" + months[j].year + "|" + months[j].number + ">" + months[j].name + (months[j].showyear ? " " + months[j].year : "") + "</option>");
    //}
    var startFrom = {
        dayName: yesterday.format("ddd"),
        date: yesterday.date(),
        monthNumb: yesterday.month(),
        monthNumbISO: (yesterday.month() + 1),
        dayOfWeek: yesterday.day(),
        year: yesterday.year(),
        fulldate: yesterday
    }
    var end = {
        dayName: endOfMonth.format("ddd"),
        date: endOfMonth.date(),
        monthNumb: endOfMonth.month(),
        monthNumbISO: (endOfMonth.month() + 1),
        dayOfWeek: endOfMonth.day(),
        year: endOfMonth.year(),
        fulldate: endOfMonth
    }

    var startMoment = moment([startFrom.year, startFrom.monthNumb, startFrom.date]),
        endMoment = moment([end.year, end.monthNumb, end.date]),
        diff = parseInt(endMoment.diff(startMoment, 'days')),
        remainingdays = initLoadAmount - diff,
        realend = endOfMonth.add(remainingdays, 'days');

    updateDateAttr($slide.find(".js-next"), startMoment.clone().add(initLoadAmount, 'days'));
    updateDateAttr($slide.find(".js-prev"), startMoment.clone());
    //updateHtml($updateTarget, startMoment, realend);
    $select.val('');
  var $selected = $(".js-selected-date");
  $selected.find("button").attr("aria-pressed", "true");
    $selected.attr("aria-current", "date");

    var $body = $slide.find(".js-body"),
        $firstvisibleli = $body.find("li:visible:first");
    console.log($firstvisibleli.find(".month").find("span").show());
    $firstvisibleli.find(".month").show();
}

function updateHtml($elem, s, e) {
    $elem.html("<ul>" +
        populateMarkupArr(getDatesBetween(s, e), e) + "</ul>");
}

function updateDateAttr($elem, s) {
    $elem.attr("data-begin", s.format("YYYY-M-DD"));
}
function wrapDays(markupArr) {
    return "<ul>" + markupArr + "</ul>";
}
function populateMarkupArr(dates, endDate) {
    var daysToLoad = [];
    for (var x = 0; x < dates.length; x++) {
        //console.log(s);
        daysToLoad.push(renderDate(convertMoment(moment(dates[x]), endDate), x));
    }
    return daysToLoad.join('');
}

function renderDate(date, index) {
    var classname = (date.isToday ? "today" : "");
    classname += " " + (date.isFirst ? "firstOfMonth" : "");

    return "<li data-fulldate=" + date.fulldate.format("YYYY-MM-DD") + " class=" + classname + "><span class='month' aria-hidden='true'><span style=" + (date.isFirst || index === 0 ? "" : 'display:none;') + ">" + date.fulldate.format("MMM") + "</span></span><button aria-controls='calendar-result-list'><span class='date'>" + date.date + "</span><span class='dayname'>" + date.dayName + "</span></button></li>";
}
function convertMoment(m, stopdate) {
    var month = moment().month(m.month());
    var today = moment().subtract(0, "days");
    return {
        dayName: m.format("ddd"),
        fulldate: m,
        date: m.date(),
        shortMonth: month.format("MMM"),
        fullMonth: month.format("MMMM"),
        dayOfWeek: m.day(),
        isFirst: m.date() === 1,
        isLast: (m.date() === stopdate),
        isToday: (m.date() === today.date() && m.month() == today.month())
    };
}
function getDatesBetween(startDate, stopDate) {
    var dateArray = [];
    var currentDate = moment(startDate);
    while (currentDate <= stopDate) {
        dateArray.push(moment(currentDate).format('YYYY-MM-DD'));
        currentDate = moment(currentDate).add(1, 'days');
    }
    return dateArray;
}

function getDatesBetweenPast(startDate, stopDate) {
    var dateArray = [];
    var currentDate = moment(startDate);
    while (currentDate >= stopDate) {
        dateArray.push(moment(currentDate).format('YYYY-MM-DD'));
        currentDate = moment(currentDate).subtract(1, 'days');
    }
    return dateArray.reverse();
}


function getDaysByMonth(monthToLoad, initLoadAmount) {
    var firstDate = monthToLoad.clone().date(0);
    return getDatesBetween(firstDate, firstDate.clone().add(initLoadAmount, 'days'));
};

$(document).ready(function () {
    $("body").on("keyup", "a, button, input, textarea, select", function (e) {
        var code = e.keyCode ? e.keyCode : e.which;
        var el = document.activeElement;

        if (code == '9') {
            el.classList.add('tabbed');
        }
    });

    $("body").on("click", 'input, textarea', function (e) {
        var el = document.activeElement;
        el.classList.add('tabbed');
    });


    $('body').on('blur', '.tabbed', function (e) {
        e.currentTarget.classList.remove('tabbed');
        if (e.currentTarget.classList.length === 0) {
            e.currentTarget.removeAttribute("class");
        }
    });
});
;
var K = K || {};

K.Cookies = {
    notexists: function(name) {
        var cookiee = Cookies.get(name);
        var cookieIsSet = typeof cookiee === 'undefined';

        return cookieIsSet;
    }
};
var time = 0;

var K = K || {};
$(function () {
    setupToggles();

    K.Play.Init();
    fadeOnLoad();

    attachEvents();
    $('.clickableArea').matchHeight();
    $('.jsMovieItem').matchHeight();

    if (K.Cookies.notexists("cookieinfocontainer")) {
        $("body").find(".js-cookie-info-container").show();
    }

    if (K.Cookies.notexists("importantnoticeinfocontaineronehour")) {
        $("body").find(".js-importantnotice-info-container").show();
    }

    $("body").on("click", ".jsButtonViewAll", function () {
        $(this).parent().find(".jsOtherDateList").find(".jsToggleContainer").show();
        $(this).parent().find(".jsFocusOnThis").focus();
        $(this).hide();
        $(this).parent().find(".jsButtonHideAll").show();
    });

    $("body").on("click", ".jsButtonHideAll", function () {
        $(this).parent().find(".jsOtherDateList").find(".jsToggleContainer").hide();
        $(this).hide();
        $(this).parent().find(".jsButtonViewAll").show().focus();

        var max = $(this).parent().find(".jsOtherDateList").data("maxotherdatesfromstart");
        var count = 0;

        $(this).parent().find(".jsOtherDateList").find(".jsToggleContainer").each(function () {
            count++;

            if (count <= max) {
                $(this).show();
            }
        });
    });

    $(".jsOtherDateList").each(function () {

        console.log($(this));
        if ($(this).data("toggleactive") == true) {
            var otherDateToggle = new funkanu.ariatoggle({
                container: "body",
                triggerSelector: "#" + $(this).attr("id") + " .jsToggleButtonOtherDate",
                target: function ($elem) {
                    return $elem.parents(".jsToggleContainer").find('.jsToggleTarget');
                },
                toggleAction: function ($target) {
                    $target.slideToggle("300", function () { });
                }
            });

            hideOtherDateIfBiggerThanMax($(this));
        }
    });

    $("#jsListenFormPageEmail").hide();

    $("body").on("click", "#SendType_Furb_Features_Pages_ListenForm_SendType_Email", function () {
        $("#jsListenFormPageEmail").show();
    });

    $("body").on("click", "#SendType_Furb_Features_Pages_ListenForm_SendType_Post", function () {
        $("#jsListenFormPageEmail").hide();
    });

    $('.carousel').flickity({
        "contain": true,
        "prevNextButtons": true,
        "pageDots": false,
        "cellAlign": "left",
        "groupCells": 1,
        on: {
            ready: function () {
                console.log('Flickity is ready');
            },
            change: function (index) {
                console.log('Slide changed to' + index);
            },
            staticClick: function (event, pointer, cellElement, cellIndex) {
                window.location = $(cellElement).data("link");
            }
        }
    });
});

function fadeOnLoad() {
    var $fadecontainer = $("body").find(".js-fade-values");
    if ($fadecontainer.length) {
        var fadetodelay = parseInt($fadecontainer.find(".js-fadeto").val()),
            fadeinitdelay = parseInt($fadecontainer.find(".js-fadeinit").val());
        if (!(fadetodelay === 0 && fadeinitdelay === 0)) {
            $('.main-content').delay(fadeinitdelay * 1000).queue(function (next) {
                $(this).animate({ "background-color": "rgba(0, 0, 0, 0.65)" }, fadetodelay * 1000);
                next();
            });
        }
    }
}

function hideOtherDateIfBiggerThanMax(elem) {
    elem.each(function () {
        var view = $(this).data("viewnaxotherdatesfromstart");

        if (view == true) {
            var max = $(this).data("maxotherdatesfromstart");

            if (max > 0) {
                if (max < $(this).find(".jsToggleContainer").length) {
                    var count = 0;
                    var focusSet = false;

                    $(this).find(".jsToggleContainer").each(function () {
                        count++;

                        if (count > max) {
                            if (focusSet == false) {
                                $(this).find("h3").addClass("jsFocusOnThis").attr("tabindex", "-1")
                                focusSet = true;
                            }

                            $(this).hide();
                        }
                    });

                    $(this).parent().find(".jsButtonViewAll").removeClass("hide");
                    $(this).parent().find(".jsButtonHideAll").removeClass("hide").hide();
                    $(this).parent().find(".jsButtonViewAll").text($(this).parent().find(".jsButtonViewAll").text().replace("{amount}", count));
                }
            }
        }
    });
}

function maximizepurchasebtnwidth() {
    var $buttons = $("body").find(".panel-buyButton");
    $buttons.each(function (i) {
        var $relDates = $(this).find(".release-date");

        var maxWidth = 0;
        if ($relDates.length > 1) {
            $relDates.each(function () {
                if ($(this).width() > maxWidth) {
                    maxWidth = $(this).width();
                }
            });
            $(this).delay(300).queue(function (next) {
                next();
            });
            maxWidth = maxWidth > 0 ? maxWidth : 265;
            console.log("maxwidth is:" + maxWidth);
            $relDates.each(function () {
                $(this).width(maxWidth);
            });
        }
    });
}


if (K.Cookies.notexists("cookieinfocontainer")) {
    $("body").on("click", ".js-close-cookie-info",
        function (e) {
            e.preventDefault();
            var $target = $(this).closest(".js-cookie-info-container");
            $target.slideUp(400,
                function () {
                    $(this).remove();
                });
            Cookies.set('cookieinfocontainer', 1, { expires: 5000 });
        });
}

if (K.Cookies.notexists("importantnoticeinfocontaineronehour")) {
    $("body").on("click", ".js-close-importantnotice-info",
        function (e) {
            e.preventDefault();
            var $target = $(this).closest(".js-importantnotice-info-container");
            $target.slideUp(400,
                function () {
                    $(this).remove();
                });
            var in60Minutes = 1 / 24;
            Cookies.set('importantnoticeinfocontaineronehour', 1, { expires: in60Minutes });
        });
}


(function (a) {
    a.fn.replaceTagName = function (f) {
        var g = [],
            h = this.length;
        while (h--) {
            var k = document.createElement(f),
                b = this[h],
                d = b.attributes;
            for (var c = d.length - 1; c >= 0; c--) {
                var j = d[c];
                k.setAttribute(j.name, j.value)
            }
            k.innerHTML = b.innerHTML;
            a(b).after(k).remove();
            g[h - 1] = k
        }
        return a(g)
    }
})(window.jQuery);

function setupToggles() {
    var headerFunctionLinksToggle = new funkanu.ariatoggle({
        container: ".functionLinksList",
        triggerSelector: ".functionLinksToggleButton",
        target: function ($elem) {
            return $('#' + $elem.attr('aria-controls'));
        },
        toggleAction: function ($target) {
            $target.slideToggle(700);
            $('.headerTogglableArea').not($target).hide();

            if ($target.is(':visible')) {
                $target.find('input').first().focus();
            }

            $target.siblings("div").each(function () {
                if (!$(this).is(":visible")) {
                    $(this).attr("aria-hidden", "true");
                }
            });
        },

        clickEvent: function ($currentTarget) {
            $('.functionLinksToggleButton').not($currentTarget).attr('aria-expanded', 'false');
            var $closestLi = $currentTarget.closest('li');
            $('.functionLinksList').find('li').not($closestLi).removeClass('active');
            $closestLi.toggleClass('active');

            if ($currentTarget.attr('aria-expanded') === "false") {
                $currentTarget.focus();
            }
        },
    });

    var openCalenderTimeout;
    var calenderToggle = new funkanu.ariatoggle({
        container: "body",
        triggerSelector: ".jsCalenderButton",
        target: function ($elem) {
            return $elem.parents(".jsCalenderContainer").find('.jsCalenderWrapper');
        },
        toggleAction: function ($target) {
            $target.slideToggle("300", function () { });

            openCalenderTimeout = setTimeout(function () {
                $target.slideToggle("300", function () { });

                $target.attr("aria-hidden", "true");
                $target.parent(".jsCalenderContainer").find('.jsCalenderButton').attr("aria-expanded", "false");
            }, 5 * 1000);
        },
        preventDefault: false
    });

    var mainToggle = new funkanu.ariatoggle({
        container: "body",
        triggerSelector: ".jsToggleButton",
        target: function ($elem) {
            return $elem.parents(".jsToggleContainer").find('.jsToggleTarget');
        },
        toggleAction: function ($target) {
            $target.slideToggle("300", function () { });
        }
    });

    var arrangementToggle = new funkanu.ariatoggle({
        container: "body",
        triggerSelector: ".js-arrangement-result-toggle",
        target: function ($elem) {
            return $elem.closest(".js-arrangement-result").find('[data-arrangement-id=' + $elem.attr("data-arrangement-target") + ']');
        },
        toggleAction: function ($target) {
            var $container = $target.closest(".js-arrangement-result");
            $container.find(".js-arrangement-display-initial").slideToggle(0, function () {
                $target.slideToggle(0, function () {
                });
                $("body").find("[data-hidden]").each(function () {
                    $(this).hide();
                });

                window.slimmage.checkResponsiveImages();
            });
        },
        clickEvent: function ($elem) {
            $container = $elem.closest(".js-arrangement-result"),
                $slideshow = $container.find(".js-slideshow-container"),
                otherDateList = $container.find(".jsOtherDateList")
            isToggleActiv = otherDateList.data("toggleactive"),

                console.log(isToggleActiv);

            if (isToggleActiv === false) {
                $container.find(".jsOtherDateList").data("toggleactive", true)

                var otherDateToggle = new funkanu.ariatoggle({
                    container: "body",
                    triggerSelector: "#" + otherDateList.attr("id") + " .jsToggleButtonOtherDate",
                    target: function ($elem) {
                        return $elem.parents(".jsToggleContainer").find('.jsToggleTarget');
                    },
                    toggleAction: function ($target) {
                        $target.slideToggle("0", function () { });
                    }
                });

                hideOtherDateIfBiggerThanMax(otherDateList);
            }

            var $h4elems = $container.find("*").filter(function () {
                return typeof ($(this).attr("class")) !== "undefined" && $(this).attr("class").match(/top-header|no-padding|discountHeader-text|hallHeader-text|concertInfoQuartHeader-text|otherDatesHeader-text|calenderResultOpenPerformanceHeader-text|calenderResultOpenPaticipateHeader-text/)
            });

            $h4elems.each(function () {
                //$(this).replaceTagName("h4");
            });
            var calenderResultOpenOtherDatesHeader = $container.find(".calenderResultOpenOtherDatesHeader-text");
            calenderResultOpenOtherDatesHeader.each(function (i) {
                //$(this).replaceTagName("h5");

            });
            var otherDatesAriaExpended = $container.find(".otherDatesAriaExpended-text");
            otherDatesAriaExpended.each(function (i) {
                //$(this).replaceTagName("h6");
            });

            if ($slideshow.length) {
                var $items = $slideshow.find(".js-slideshow-item");
                $items.each(function () {
                    if ($(this).attr("data-index") != 0) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }
        }
    });
}

function attachEvents() {
    $('body').on('click', '.jsHallImage', function () {

        $('.jsHallImage').colorbox({ rel: $(this).attr('rel'), alt: $(this).data("alt") });
        $("#cboxClose").focus();
    });
    $("body").on("click", ".js-restore-arrangement-display", function (e) {
        e.preventDefault();
        var $self = $(this),
            $container = $self.closest(".js-arrangement-result"),
            $currentConatiner = $self.closest("[data-arrangement-id]"),
            $target = $container.find(".js-arrangement-display-initial"),
            $li = $target.closest("li");
        $currentConatiner.slideToggle(0,
            function () {
                $target.slideToggle(0,
                    function () {
                        //$('html,body').animate({ scrollTop: $li.offset().top - 50 }, function () {
                        window.slimmage.checkResponsiveImages();
                        //});
                    });
            });
    });

    $("body").on("click", ".jsToggleSubButton", function (e) {
        e.preventDefault();
        var $self = $(this),
            $container = $self.closest(".jsToggleSubContainer"),
            $target = $container.find(".jsToggleSubTarget");
        $target.slideToggle("300", function () {
            $target.toggleAttr("aria-hidden");
            $self.toggleAttr("aria-expanded");

        });
    });

    $("body").on("change", ".js-mobile-nav-select", function (e) {
        e.preventDefault();
        var $self = $(this),
            selected = $self.find(":selected")
        href = selected.data("href");

        window.location = href;
    });

    $(".js-number-spec").on("focus", "input[type='number']", function (e) {
        if ($(this).val() == 0) {
            $(this).val("");
        }
    }).on("blur", "input[type='number']", function (e) {
        console.log("blur");
        if ($(this).val() === "") {
            $(this).val(0);
        }
    });

}

$(document).ready(function () {
    var clipboard = new ClipboardJS('.copy-link');

    $("body").on("click", ".copy-link", function () {
        var $correctElement = $(this).parents('.sharethislinks');
        $correctElement.addClass('copied');
        $correctElement.find('.copied-url-feedback-wrapper').addClass('active');

        clipboard.on('success', function (e) {

            console.log(e);

            $('.copied .copied-url-feedback-wrapper').attr('role', 'alert');
            $('.copied .copied-url-feedback-wrapper').attr('aria-live', 'assertive');
            $('.copied .copied-url-feedback-wrapper').attr('aria-hidden', 'false');

            // Hide message after 5 seconds
            setTimeout(function () {
                $correctElement.removeClass("copied");
                $correctElement.find('.copied-url-feedback-wrapper').removeClass('active');

            }, 5 * 1000);

        });

        clipboard.on('error', function (e) {
            console.log(e);
            $('.copied-url-feedback-wrapper').attr('aria-hidden', true);
        });
    });

    setTimeout(function () {
        $(".carousel[data-lazyload='True']").each(function () {
            FilterEngine.LazyLoad(this.id);
        });
    }, 1000);
});

let movieLandingPageNumber = 1;
var scrollBeforeLoad = 0;

$("body").on("click", ".jsMovieLandingLoadMore", function (e) {
    e.preventDefault();

    const contentGuid = $("#jsMovieListWrapper").data("contentguid");
    movieLandingPageNumber++;

    scrollBeforeLoad = $(document).scrollTop();

    $.ajax({
        url: "/MovieThemePage/LoadMore",
        dataType: "json",
        method: "POST",
        data: { contentGuid: contentGuid, pageNumber: movieLandingPageNumber, lang: $("html").attr("lang") },
        success: function (response) {
            var html = $(response.Html);
            var firstId = html.first().attr("id");

            setTimeout(function () {
                window.slimmage.checkResponsiveImages();

                html.find('.jsMovieItem').height(500);
                html.find('.clickableArea').height(420);
                html.appendTo($(".jsMovieListContent")).hide().fadeIn(500);
            },
                20);

            setTimeout(function () {
                window.slimmage.checkResponsiveImages();
                $('.clickableArea').matchHeight();
                $('.jsMovieItem').matchHeight();
                $('.jsMovieLandingLoadMore')[0].focus();
                $(document).scrollTop(scrollBeforeLoad);
            },
                150);

            if (response.MoreToLoad === false) {
                $(".jsMovieLandingLoadMore").hide(); 5300
            } else {
                const take = $(".jsMovieLandingLoadMore").data("take");
                const movieCount = $(".jsMovieLandingLoadMore").data("moviecount");
                const first = (movieLandingPageNumber * take) + 1;
                let last = ((movieLandingPageNumber + 1) * take);

                if (last > movieCount) {
                    last = movieCount;
                }

                $(".jsLoadMoreText").text(first + "–" + last);
            }
        },
        error: function (xhr) {

        }
    });
});;
/**
* jquery-match-height 0.7.2 by @liabru
* http://brm.io/jquery-match-height/
* License: MIT
*/

;(function(factory) { // eslint-disable-line no-extra-semi
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof module !== 'undefined' && module.exports) {
        // CommonJS
        module.exports = factory(require('jquery'));
    } else {
        // Global
        factory(jQuery);
    }
})(function($) {
    /*
    *  internal
    */

    var _previousResizeWidth = -1,
        _updateTimeout = -1;

    /*
    *  _parse
    *  value parse utility function
    */

    var _parse = function(value) {
        // parse value and convert NaN to 0
        return parseFloat(value) || 0;
    };

    /*
    *  _rows
    *  utility function returns array of jQuery selections representing each row
    *  (as displayed after float wrapping applied by browser)
    */

    var _rows = function(elements) {
        var tolerance = 1,
            $elements = $(elements),
            lastTop = null,
            rows = [];

        // group elements by their top position
        $elements.each(function(){
            var $that = $(this),
                top = $that.offset().top - _parse($that.css('margin-top')),
                lastRow = rows.length > 0 ? rows[rows.length - 1] : null;

            if (lastRow === null) {
                // first item on the row, so just push it
                rows.push($that);
            } else {
                // if the row top is the same, add to the row group
                if (Math.floor(Math.abs(lastTop - top)) <= tolerance) {
                    rows[rows.length - 1] = lastRow.add($that);
                } else {
                    // otherwise start a new row group
                    rows.push($that);
                }
            }

            // keep track of the last row top
            lastTop = top;
        });

        return rows;
    };

    /*
    *  _parseOptions
    *  handle plugin options
    */

    var _parseOptions = function(options) {
        var opts = {
            byRow: true,
            property: 'height',
            target: null,
            remove: false
        };

        if (typeof options === 'object') {
            return $.extend(opts, options);
        }

        if (typeof options === 'boolean') {
            opts.byRow = options;
        } else if (options === 'remove') {
            opts.remove = true;
        }

        return opts;
    };

    /*
    *  matchHeight
    *  plugin definition
    */

    var matchHeight = $.fn.matchHeight = function(options) {
        var opts = _parseOptions(options);

        // handle remove
        if (opts.remove) {
            var that = this;

            // remove fixed height from all selected elements
            this.css(opts.property, '');

            // remove selected elements from all groups
            $.each(matchHeight._groups, function(key, group) {
                group.elements = group.elements.not(that);
            });

            // TODO: cleanup empty groups

            return this;
        }

        if (this.length <= 1 && !opts.target) {
            return this;
        }

        // keep track of this group so we can re-apply later on load and resize events
        matchHeight._groups.push({
            elements: this,
            options: opts
        });

        // match each element's height to the tallest element in the selection
        matchHeight._apply(this, opts);

        return this;
    };

    /*
    *  plugin global options
    */

    matchHeight.version = '0.7.2';
    matchHeight._groups = [];
    matchHeight._throttle = 80;
    matchHeight._maintainScroll = false;
    matchHeight._beforeUpdate = null;
    matchHeight._afterUpdate = null;
    matchHeight._rows = _rows;
    matchHeight._parse = _parse;
    matchHeight._parseOptions = _parseOptions;

    /*
    *  matchHeight._apply
    *  apply matchHeight to given elements
    */

    matchHeight._apply = function(elements, options) {
        var opts = _parseOptions(options),
            $elements = $(elements),
            rows = [$elements];

        // take note of scroll position
        var scrollTop = $(window).scrollTop(),
            htmlHeight = $('html').outerHeight(true);

        // get hidden parents
        var $hiddenParents = $elements.parents().filter(':hidden');

        // cache the original inline style
        $hiddenParents.each(function() {
            var $that = $(this);
            $that.data('style-cache', $that.attr('style'));
        });

        // temporarily must force hidden parents visible
        $hiddenParents.css('display', 'block');

        // get rows if using byRow, otherwise assume one row
        if (opts.byRow && !opts.target) {

            // must first force an arbitrary equal height so floating elements break evenly
            $elements.each(function() {
                var $that = $(this),
                    display = $that.css('display');

                // temporarily force a usable display value
                if (display !== 'inline-block' && display !== 'flex' && display !== 'inline-flex') {
                    display = 'block';
                }

                // cache the original inline style
                $that.data('style-cache', $that.attr('style'));

                $that.css({
                    'display': display,
                    'padding-top': '0',
                    'padding-bottom': '0',
                    'margin-top': '0',
                    'margin-bottom': '0',
                    'border-top-width': '0',
                    'border-bottom-width': '0',
                    'height': '100px',
                    'overflow': 'hidden'
                });
            });

            // get the array of rows (based on element top position)
            rows = _rows($elements);

            // revert original inline styles
            $elements.each(function() {
                var $that = $(this);
                $that.attr('style', $that.data('style-cache') || '');
            });
        }

        $.each(rows, function(key, row) {
            var $row = $(row),
                targetHeight = 0;

            if (!opts.target) {
                // skip apply to rows with only one item
                if (opts.byRow && $row.length <= 1) {
                    $row.css(opts.property, '');
                    return;
                }

                // iterate the row and find the max height
                $row.each(function(){
                    var $that = $(this),
                        style = $that.attr('style'),
                        display = $that.css('display');

                    // temporarily force a usable display value
                    if (display !== 'inline-block' && display !== 'flex' && display !== 'inline-flex') {
                        display = 'block';
                    }

                    // ensure we get the correct actual height (and not a previously set height value)
                    var css = { 'display': display };
                    css[opts.property] = '';
                    $that.css(css);

                    // find the max height (including padding, but not margin)
                    if ($that.outerHeight(false) > targetHeight) {
                        targetHeight = $that.outerHeight(false);
                    }

                    // revert styles
                    if (style) {
                        $that.attr('style', style);
                    } else {
                        $that.css('display', '');
                    }
                });
            } else {
                // if target set, use the height of the target element
                targetHeight = opts.target.outerHeight(false);
            }

            // iterate the row and apply the height to all elements
            $row.each(function(){
                var $that = $(this),
                    verticalPadding = 0;

                // don't apply to a target
                if (opts.target && $that.is(opts.target)) {
                    return;
                }

                // handle padding and border correctly (required when not using border-box)
                if ($that.css('box-sizing') !== 'border-box') {
                    verticalPadding += _parse($that.css('border-top-width')) + _parse($that.css('border-bottom-width'));
                    verticalPadding += _parse($that.css('padding-top')) + _parse($that.css('padding-bottom'));
                }

                // set the height (accounting for padding and border)
                $that.css(opts.property, (targetHeight - verticalPadding) + 'px');
            });
        });

        // revert hidden parents
        $hiddenParents.each(function() {
            var $that = $(this);
            $that.attr('style', $that.data('style-cache') || null);
        });

        // restore scroll position if enabled
        if (matchHeight._maintainScroll) {
            $(window).scrollTop((scrollTop / htmlHeight) * $('html').outerHeight(true));
        }

        return this;
    };

    /*
    *  matchHeight._applyDataApi
    *  applies matchHeight to all elements with a data-match-height attribute
    */

    matchHeight._applyDataApi = function() {
        var groups = {};

        // generate groups by their groupId set by elements using data-match-height
        $('[data-match-height], [data-mh]').each(function() {
            var $this = $(this),
                groupId = $this.attr('data-mh') || $this.attr('data-match-height');

            if (groupId in groups) {
                groups[groupId] = groups[groupId].add($this);
            } else {
                groups[groupId] = $this;
            }
        });

        // apply matchHeight to each group
        $.each(groups, function() {
            this.matchHeight(true);
        });
    };

    /*
    *  matchHeight._update
    *  updates matchHeight on all current groups with their correct options
    */

    var _update = function(event) {
        if (matchHeight._beforeUpdate) {
            matchHeight._beforeUpdate(event, matchHeight._groups);
        }

        $.each(matchHeight._groups, function() {
            matchHeight._apply(this.elements, this.options);
        });

        if (matchHeight._afterUpdate) {
            matchHeight._afterUpdate(event, matchHeight._groups);
        }
    };

    matchHeight._update = function(throttle, event) {
        // prevent update if fired from a resize event
        // where the viewport width hasn't actually changed
        // fixes an event looping bug in IE8
        if (event && event.type === 'resize') {
            var windowWidth = $(window).width();
            if (windowWidth === _previousResizeWidth) {
                return;
            }
            _previousResizeWidth = windowWidth;
        }

        // throttle updates
        if (!throttle) {
            _update(event);
        } else if (_updateTimeout === -1) {
            _updateTimeout = setTimeout(function() {
                _update(event);
                _updateTimeout = -1;
            }, matchHeight._throttle);
        }
    };

    /*
    *  bind events
    */

    // apply on DOM ready event
    $(matchHeight._applyDataApi);

    // use on or bind where supported
    var on = $.fn.on ? 'on' : 'bind';

    // update heights on load and resize events
    $(window)[on]('load', function(event) {
        matchHeight._update(false, event);
    });

    // throttled update heights on resize events
    $(window)[on]('resize orientationchange', function(event) {
        matchHeight._update(true, event);
    });

});
;
$.validator.setDefaults({
    highlight: function (element) {
        $(element).closest('.form-field').addClass('errorOnThis');
    },
    unhighlight: function (element) {
        $(element).closest('.form-field').removeClass('errorOnThis');
    }
});;
var validationTimer = null;

$(function () {
    $('form').each(function () {
        $(this).unbind("invalid-form.validate"); // remove old handler
        $(this).bind("invalid-form.validate", function (event, validator) {
            var container = $(this).find("[data-valmsg-summary=true]"),
                errorAmount = $(this).find("[data-valmsg-summary-erroramount]"),
                list = container.find("ul"),
                errorList = validator.errorList;

            if (list && list.length && errorList.length) {
                list.empty();
                container.addClass("validation-summary-errors").removeClass("validation-summary-valid");

                $.each(errorList,
                    function () {
                        $("<li />").html($("#" + this.element.id).data("label")).appendTo(list);
                    });

                errorAmount.html(errorList.length);

                clearInterval(validationTimer);
                validationTimer = null;

                validationTimer = setInterval(setFocus, 10);
            }
        });

        //Hack to replace standard message from jQuery
        $.validator.messages.email = $(this).find("input[type='email']:first").data("val-regex");
    });
});

function setFocus() {
    clearInterval(validationTimer);

    if ($("form").find("[data-valmsg-summary=true]").find("h2").length > 0) {
        $("form").find("[data-valmsg-summary=true]").find("h2").attr("tabindex", "-1").focus();
    }

    if ($("form").find("[data-valmsg-summary=true]").find("h3").length > 0) {
        $("form").find("[data-valmsg-summary=true]").find("h3").attr("tabindex", "-1").focus();
    }

    if ($("form").find("[data-valmsg-summary=true]").find("h4").length > 0) {
        $("form").find("[data-valmsg-summary=true]").find("h4").attr("tabindex", "-1").focus();
    }


}

jQuery.validator.unobtrusive.adapters.add("mandatory", function (options) {
    if (options.element.tagName.toUpperCase() === "INPUT" && options.element.type.toUpperCase() === "CHECKBOX") {
        options.rules["required"] = true;

        if (options.message) {
            options.messages["required"] = options.message;
        }
    }
});;
$(document).ready(function () {
    $(".jsSearchResult").hide();

    var found = false;

    $("#jsChangeActiveType button").each(function () {
        if ($(this).data("count") > 0 && found === false) {
            $(this).addClass("active");
            $(".jsSearchResult[data-type='" + $(this).data("type") + "']").show();
            found = true;

            $("#jsChangeActiveType").data("currenttype", $(this).data("type"));
        }
    });

    window.slimmage.checkResponsiveImages();
    $('.clickableArea').matchHeight();

    $("#jsChangeActiveType").on("click", "button", function (e) {
        e.preventDefault();
        var currentType = $("#jsChangeActiveType").data("currenttype");
        var newType = $(this).data("type");

        if (newType !== currentType) {
            $(".jsSearchResult[data-type='" + newType + "']").show("slide", { direction: "right" }, 500);
            $(".jsSearchResult[data-type='" + currentType + "']").hide();

            $("button[data-type='" + newType + "']").addClass("active");
            $("button[data-type='" + currentType + "']").removeClass("active");

            $("#jsChangeActiveType").data("currenttype", newType);

            window.slimmage.checkResponsiveImages();
            $('.clickableArea').matchHeight();
        }
    });

    $(".jsSearchPage").on("click", ".jsNextPage", function (e) {
        var url = $(e.currentTarget).data("nextpageurl"),
            $self = $(this),
            type = $self.data("type");
        $.ajax({
            cache: false,
            url: url,
            success: function(data) {
                var $newSearchHitItems = $(data).find(".jsSearchResultlist").children();
                $(".jsSearchResult[data-type='" + type + "'] .jsSearchResultlist").append($newSearchHitItems);
                $newSearchHitItems.hide().slideDown();
                $newSearchHitItems.find("a").first().focus();

                if ($(data).find(".jsNextPage").data("nextpagenr") > 0) {
                    $(".jsSearchResult[data-type='" + type + "'] .jsNextPage").data("nextpageurl", $(data).find(".jsNextPage").data("nextpageurl"));
                } else {
                    $(".jsSearchResult[data-type='" + type + "'] .jsNextPage").hide();
                }

                window.slimmage.checkResponsiveImages();
                $('.clickableArea').matchHeight();
            }
        });
    });
});;
$(function () {
    $("body").find("[data-hidden]").each(function () {
        $(this).hide();
    });
});

$("body").on("click", ".js-slideshow-container button", function (e) {
    e.preventDefault();
    var $self = $(this),
        $container = $self.closest(".js-slideshow-container"),
        $items = $container.find(".js-slideshow-item"),
        itemAmount = $items.length,
        toNext = $self.attr("data-dir") === "right",
        index = 0,
        maxIndex = $items.last().attr("data-index");
    var $visibleItem;
    $(this).delay(100).queue(function (next) {
        console.log($items.filter(":visible").length);
        $items.each(function () {
            if ($(this).is(":visible")) {
                $visibleItem = $(this);
                index = parseInt($(this).attr("data-index"));
            }
        });
        var currIndex = typeof $visibleItem !== 'undefined' ? $visibleItem.attr("data-index") : 0;
        var $target;
        if (toNext) {
            if (currIndex === maxIndex) {
                $target = $items.first();
            } else {
                $target = $visibleItem.next();

            }
        } else {
            if (currIndex == 0) {
                $target = $items.last();
            } else {
                $target = $visibleItem.prev();
            }
        }
        disablebuttons($container);
        if (toNext) {
            $visibleItem.hide("slide", { direction: "left" }, 100, function () {
                $target.show("slide", { direction: "right" }, 100, function () {
                    enablebuttons($container);
                });
            });
        } else {
            $visibleItem.hide("slide", { direction: "right" }, 100, function () {
                $target.show("slide", { direction: "left" }, 100, function () {
                    enablebuttons($container);
                });
            });
        }
        //if ($target.attr("data-index") === maxIndex) {
        //} else if ($target.attr("data-index") == 0) {

        //}
        next();
    });


});

function disablebuttons($container) {
    $container.find("button").each(function () {
        $(this).attr("disabled", "disabled");
    })
}

function enablebuttons($container) {
    $container.find("button").each(function () {
        $(this).removeAttr("disabled");
    })
};
/*!
	Colorbox 1.6.4
	license: MIT
	http://www.jacklmoore.com/colorbox
*/
(function ($, document, window) {
    var
	// Default settings object.
	// See http://jacklmoore.com/colorbox for details.
	defaults = {
	    // data sources
	    html: false,
	    photo: false,
	    iframe: false,
	    inline: false,

	    // behavior and appearance
	    transition: "elastic",
	    speed: 300,
	    fadeOut: 300,
	    width: false,
	    initialWidth: "600",
	    innerWidth: false,
	    maxWidth: false,
	    height: false,
	    initialHeight: "450",
	    innerHeight: false,
	    maxHeight: false,
	    scalePhotos: true,
	    scrolling: true,
	    opacity: 0.9,
	    preloading: true,
	    className: false,
	    overlayClose: true,
	    escKey: true,
	    arrowKey: true,
	    top: false,
	    bottom: false,
	    left: false,
	    right: false,
	    fixed: false,
	    data: undefined,
	    closeButton: true,
	    fastIframe: true,
	    open: false,
	    reposition: true,
	    loop: true,
	    slideshow: false,
	    slideshowAuto: true,
	    slideshowSpeed: 2500,
	    slideshowStart: "start slideshow",
	    slideshowStop: "stop slideshow",
	    photoRegex: /\.(gif|png|jp(e|g|eg)|bmp|ico|webp|jxr|svg)((#|\?).*)?$/i,
	    alt: function() {
	        return this.alt;
	    },

	    // alternate image paths for high-res displays
	    retinaImage: false,
	    retinaUrl: false,
	    retinaSuffix: '@2x.$1',

	    // internationalization
	    current: "image {current} of {total}",
	    previous: "previous",
	    next: "next",
	    close: "close",
	    xhrError: "This content failed to load.",
	    imgError: "This image failed to load.",

	    // accessbility
	    returnFocus: true,
	    trapFocus: true,

	    // callbacks
	    onOpen: false,
	    onLoad: false,
	    onComplete: false,
	    onCleanup: false,
	    onClosed: false,

	    rel: function () {
	        return this.rel;
	    },
	    href: function () {
	        // using this.href would give the absolute url, when the href may have been inteded as a selector (e.g. '#container')
	        return $(this).attr('href');
	    },
	    title: function () {
	        return this.title;
	    },
	    createImg: function () {
	        var img = new Image();
	        var attrs = $(this).data('cbox-img-attrs');

	        if (typeof attrs === 'object') {
	            $.each(attrs, function (key, val) {
	                img[key] = val;
	            });
	        }
	        img["alt"] = settings.get('alt');
	        return img;
	    },
	    createIframe: function () {
	        var iframe = document.createElement('iframe');
	        var attrs = $(this).data('cbox-iframe-attrs');

	        if (typeof attrs === 'object') {
	            $.each(attrs, function (key, val) {
	                iframe[key] = val;
	            });
	        }

	        if ('frameBorder' in iframe) {
	            iframe.frameBorder = 0;
	        }
	        if ('allowTransparency' in iframe) {
	            iframe.allowTransparency = "true";
	        }
	        iframe.name = (new Date()).getTime(); // give the iframe a unique name to prevent caching
	        iframe.allowFullscreen = true;

	        return iframe;
	    }
	},

	// Abstracting the HTML and event identifiers for easy rebranding
	colorbox = 'colorbox',
	prefix = 'cbox',
	boxElement = prefix + 'Element',

	// Events
	event_open = prefix + '_open',
	event_load = prefix + '_load',
	event_complete = prefix + '_complete',
	event_cleanup = prefix + '_cleanup',
	event_closed = prefix + '_closed',
	event_purge = prefix + '_purge',

	// Cached jQuery Object Variables
	$overlay,
	$box,
	$wrap,
	$content,
	$topBorder,
	$leftBorder,
	$rightBorder,
	$bottomBorder,
	$related,
	$window,
	$loaded,
	$loadingBay,
	$loadingOverlay,
	$title,
	$current,
	$slideshow,
	$next,
	$prev,
	$close,
	$groupControls,
	$events = $('<a/>'), // $({}) would be preferred, but there is an issue with jQuery 1.4.2

	// Variables for cached values or use across multiple functions
	settings,
	interfaceHeight,
	interfaceWidth,
	loadedHeight,
	loadedWidth,
	index,
	photo,
	open,
	active,
	closing,
	loadingTimer,
	publicMethod,
	div = "div",
	requests = 0,
	previousCSS = {},
	init;

    // ****************
    // HELPER FUNCTIONS
    // ****************

    // Convenience function for creating new jQuery objects
    function $tag(tag, id, css) {
        var element = document.createElement(tag);

        if (id) {
            element.id = prefix + id;
        }

        if (css) {
            element.style.cssText = css;
        }

        return $(element);
    }

    // Get the window height using innerHeight when available to avoid an issue with iOS
    // http://bugs.jquery.com/ticket/6724
    function winheight() {
        return window.innerHeight ? window.innerHeight : $(window).height();
    }

    function Settings(element, options) {
        if (options !== Object(options)) {
            options = {};
        }

        this.cache = {};
        this.el = element;

        this.value = function (key) {
            var dataAttr;

            if (this.cache[key] === undefined) {
                dataAttr = $(this.el).attr('data-cbox-' + key);

                if (dataAttr !== undefined) {
                    this.cache[key] = dataAttr;
                } else if (options[key] !== undefined) {
                    this.cache[key] = options[key];
                } else if (defaults[key] !== undefined) {
                    this.cache[key] = defaults[key];
                }
            }

            return this.cache[key];
        };

        this.get = function (key) {
            var value = this.value(key);
            return $.isFunction(value) ? value.call(this.el, this) : value;
        };
    }

    // Determine the next and previous members in a group.
    function getIndex(increment) {
        var
		max = $related.length,
		newIndex = (index + increment) % max;

        return (newIndex < 0) ? max + newIndex : newIndex;
    }

    // Convert '%' and 'px' values to integers
    function setSize(size, dimension) {
        return Math.round((/%/.test(size) ? ((dimension === 'x' ? $window.width() : winheight()) / 100) : 1) * parseInt(size, 10));
    }

    // Checks an href to see if it is a photo.
    // There is a force photo option (photo: true) for hrefs that cannot be matched by the regex.
    function isImage(settings, url) {
        return settings.get('photo') || settings.get('photoRegex').test(url);
    }

    function retinaUrl(settings, url) {
        return settings.get('retinaUrl') && window.devicePixelRatio > 1 ? url.replace(settings.get('photoRegex'), settings.get('retinaSuffix')) : url;
    }

    function trapFocus(e) {
        if ('contains' in $box[0] && !$box[0].contains(e.target) && e.target !== $overlay[0]) {
            e.stopPropagation();
            $box.focus();
        }
    }

    function setClass(str) {
        if (setClass.str !== str) {
            $box.add($overlay).removeClass(setClass.str).addClass(str);
            setClass.str = str;
        }
    }

    function getRelated(rel) {
        index = 0;

        if (rel && rel !== false && rel !== 'nofollow') {
            $related = $('.' + boxElement).filter(function () {
                var options = $.data(this, colorbox);
                var settings = new Settings(this, options);
                return (settings.get('rel') === rel);
            });
            index = $related.index(settings.el);

            // Check direct calls to Colorbox.
            if (index === -1) {
                $related = $related.add(settings.el);
                index = $related.length - 1;
            }
        } else {
            $related = $(settings.el);
        }
    }

    function trigger(event) {
        // for external use
        $(document).trigger(event);
        // for internal use
        $events.triggerHandler(event);
    }

    var slideshow = (function () {
        var active,
			className = prefix + "Slideshow_",
			click = "click." + prefix,
			timeOut;

        function clear() {
            clearTimeout(timeOut);
        }

        function set() {
            if (settings.get('loop') || $related[index + 1]) {
                clear();
                timeOut = setTimeout(publicMethod.next, settings.get('slideshowSpeed'));
            }
        }

        function start() {
            $slideshow
				.html(settings.get('slideshowStop'))
				.unbind(click)
				.one(click, stop);

            $events
				.bind(event_complete, set)
				.bind(event_load, clear);

            $box.removeClass(className + "off").addClass(className + "on");
        }

        function stop() {
            clear();

            $events
				.unbind(event_complete, set)
				.unbind(event_load, clear);

            $slideshow
				.html(settings.get('slideshowStart'))
				.unbind(click)
				.one(click, function () {
				    publicMethod.next();
				    start();
				});

            $box.removeClass(className + "on").addClass(className + "off");
        }

        function reset() {
            active = false;
            $slideshow.hide();
            clear();
            $events
				.unbind(event_complete, set)
				.unbind(event_load, clear);
            $box.removeClass(className + "off " + className + "on");
        }

        return function () {
            if (active) {
                if (!settings.get('slideshow')) {
                    $events.unbind(event_cleanup, reset);
                    reset();
                }
            } else {
                if (settings.get('slideshow') && $related[1]) {
                    active = true;
                    $events.one(event_cleanup, reset);
                    if (settings.get('slideshowAuto')) {
                        start();
                    } else {
                        stop();
                    }
                    $slideshow.show();
                }
            }
        };

    }());


    function launch(element) {
        var options;

        if (!closing) {

            options = $(element).data(colorbox);

            settings = new Settings(element, options);

            getRelated(settings.get('rel'));

            if (!open) {
                open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys.

                setClass(settings.get('className'));

                // Show colorbox so the sizes can be calculated in older versions of jQuery
                $box.css({ visibility: 'hidden', display: 'block', opacity: '' });

                $loaded = $tag(div, 'LoadedContent', 'width:0; height:0; overflow:hidden; visibility:hidden');
                $content.css({ width: '', height: '' }).append($loaded);

                // Cache values needed for size calculations
                interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();
                interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width();
                loadedHeight = $loaded.outerHeight(true);
                loadedWidth = $loaded.outerWidth(true);

                // Opens inital empty Colorbox prior to content being loaded.
                var initialWidth = setSize(settings.get('initialWidth'), 'x');
                var initialHeight = setSize(settings.get('initialHeight'), 'y');
                var maxWidth = settings.get('maxWidth');
                var maxHeight = settings.get('maxHeight');

                settings.w = Math.max((maxWidth !== false ? Math.min(initialWidth, setSize(maxWidth, 'x')) : initialWidth) - loadedWidth - interfaceWidth, 0);
                settings.h = Math.max((maxHeight !== false ? Math.min(initialHeight, setSize(maxHeight, 'y')) : initialHeight) - loadedHeight - interfaceHeight, 0);

                $loaded.css({ width: '', height: settings.h });
                publicMethod.position();

                trigger(event_open);
                settings.get('onOpen');

                $groupControls.add($title).hide();

                $box.focus();

                if (settings.get('trapFocus')) {
                    // Confine focus to the modal
                    // Uses event capturing that is not supported in IE8-
                    if (document.addEventListener) {

                        document.addEventListener('focus', trapFocus, true);

                        $events.one(event_closed, function () {
                            document.removeEventListener('focus', trapFocus, true);
                        });
                    }
                }

                // Return focus on closing
                if (settings.get('returnFocus')) {
                    $events.one(event_closed, function () {
                        $(settings.el).focus();
                    });
                }
            }

            var opacity = parseFloat(settings.get('opacity'));
            $overlay.css({
                opacity: opacity === opacity ? opacity : '',
                cursor: settings.get('overlayClose') ? 'pointer' : '',
                visibility: 'visible'
            }).show();

            if (settings.get('closeButton')) {
                $close.html(settings.get('close')).appendTo($content);
            } else {
                $close.appendTo('<div/>'); // replace with .detach() when dropping jQuery < 1.4
            }

            load();
        }
    }

    // Colorbox's markup needs to be added to the DOM prior to being called
    // so that the browser will go ahead and load the CSS background images.
    function appendHTML() {
        if (!$box) {
            init = false;
            $window = $(window);
            $box = $tag(div).attr({
                id: colorbox,
                'class': $.support.opacity === false ? prefix + 'IE' : '', // class for optional IE8 & lower targeted CSS.
                role: 'dialog',
                tabindex: '-1'
            }).hide();
            $overlay = $tag(div, "Overlay").hide();
            $loadingOverlay = $([$tag(div, "LoadingOverlay")[0], $tag(div, "LoadingGraphic")[0]]);
            $wrap = $tag(div, "Wrapper");
            $content = $tag(div, "Content").append(
				$title = $tag(div, "Title"),
				$current = $tag(div, "Current"),
				$prev = $('<button type="button"/>').attr({ id: prefix + 'Previous' }),
				$next = $('<button type="button"/>').attr({ id: prefix + 'Next' }),
				$slideshow = $('<button type="button"/>').attr({ id: prefix + 'Slideshow' }),
				$loadingOverlay
			);

            $close = $('<button type="button"/>').attr({ id: prefix + 'Close' });

            $wrap.append( // The 3x3 Grid that makes up Colorbox
				$tag(div).append(
					$tag(div, "TopLeft"),
					$topBorder = $tag(div, "TopCenter"),
					$tag(div, "TopRight")
				),
				$tag(div, false, 'clear:left').append(
					$leftBorder = $tag(div, "MiddleLeft"),
					$content,
					$rightBorder = $tag(div, "MiddleRight")
				),
				$tag(div, false, 'clear:left').append(
					$tag(div, "BottomLeft"),
					$bottomBorder = $tag(div, "BottomCenter"),
					$tag(div, "BottomRight")
				)
			).find('div div').css({ 'float': 'left' });

            $loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none; max-width:none;');

            $groupControls = $next.add($prev).add($current).add($slideshow);
        }
        if (document.body && !$box.parent().length) {
            $(document.body).append($overlay, $box.append($wrap, $loadingBay));
        }
    }

    // Add Colorbox's event bindings
    function addBindings() {
        function clickHandler(e) {
            // ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt.
            // See: http://jacklmoore.com/notes/click-events/
            if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.ctrlKey)) {
                e.preventDefault();
                launch(this);
            }
        }

        if ($box) {
            if (!init) {
                init = true;

                // Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly.
                $next.click(function () {
                    publicMethod.next();
                });
                $prev.click(function () {
                    publicMethod.prev();
                });
                $close.click(function () {
                    publicMethod.close();
                });
                $overlay.click(function () {
                    if (settings.get('overlayClose')) {
                        publicMethod.close();
                    }
                });

                // Key Bindings
                $(document).bind('keydown.' + prefix, function (e) {
                    var key = e.keyCode;
                    if (open && settings.get('escKey') && key === 27) {
                        e.preventDefault();
                        publicMethod.close();
                    }
                    if (open && settings.get('arrowKey') && $related[1] && !e.altKey) {
                        if (key === 37) {
                            e.preventDefault();
                            $prev.click();
                        } else if (key === 39) {
                            e.preventDefault();
                            $next.click();
                        }
                    }
                });

                if ($.isFunction($.fn.on)) {
                    // For jQuery 1.7+
                    $(document).on('click.' + prefix, '.' + boxElement, clickHandler);
                } else {
                    // For jQuery 1.3.x -> 1.6.x
                    // This code is never reached in jQuery 1.9, so do not contact me about 'live' being removed.
                    // This is not here for jQuery 1.9, it's here for legacy users.
                    $('.' + boxElement).live('click.' + prefix, clickHandler);
                }
            }
            return true;
        }
        return false;
    }

    // Don't do anything if Colorbox already exists.
    if ($[colorbox]) {
        return;
    }

    // Append the HTML when the DOM loads
    $(appendHTML);


    // ****************
    // PUBLIC FUNCTIONS
    // Usage format: $.colorbox.close();
    // Usage from within an iframe: parent.jQuery.colorbox.close();
    // ****************

    publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
        var settings;
        var $obj = this;

        options = options || {};

        if ($.isFunction($obj)) { // assume a call to $.colorbox
            $obj = $('<a/>');
            options.open = true;
        }

        if (!$obj[0]) { // colorbox being applied to empty collection
            return $obj;
        }

        appendHTML();

        if (addBindings()) {

            if (callback) {
                options.onComplete = callback;
            }

            $obj.each(function () {
                var old = $.data(this, colorbox) || {};
                $.data(this, colorbox, $.extend(old, options));
            }).addClass(boxElement);

            settings = new Settings($obj[0], options);

            if (settings.get('open')) {
                launch($obj[0]);
            }
        }

        return $obj;
    };

    publicMethod.position = function (speed, loadedCallback) {
        var
		css,
		top = 0,
		left = 0,
		offset = $box.offset(),
		scrollTop,
		scrollLeft;

        $window.unbind('resize.' + prefix);

        // remove the modal so that it doesn't influence the document width/height
        $box.css({ top: -9e4, left: -9e4 });

        scrollTop = $window.scrollTop();
        scrollLeft = $window.scrollLeft();

        if (settings.get('fixed')) {
            offset.top -= scrollTop;
            offset.left -= scrollLeft;
            $box.css({ position: 'fixed' });
        } else {
            top = scrollTop;
            left = scrollLeft;
            $box.css({ position: 'absolute' });
        }

        // keeps the top and left positions within the browser's viewport.
        if (settings.get('right') !== false) {
            left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.get('right'), 'x'), 0);
        } else if (settings.get('left') !== false) {
            left += setSize(settings.get('left'), 'x');
        } else {
            left += Math.round(Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2);
        }

        if (settings.get('bottom') !== false) {
            top += Math.max(winheight() - settings.h - loadedHeight - interfaceHeight - setSize(settings.get('bottom'), 'y'), 0);
        } else if (settings.get('top') !== false) {
            top += setSize(settings.get('top'), 'y');
        } else {
            top += Math.round(Math.max(winheight() - settings.h - loadedHeight - interfaceHeight, 0) / 2);
        }

        $box.css({ top: offset.top, left: offset.left, visibility: 'visible' });

        // this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly,
        // but it has to be shrank down around the size of div#colorbox when it's done.  If not,
        // it can invoke an obscure IE bug when using iframes.
        $wrap[0].style.width = $wrap[0].style.height = "9999px";

        function modalDimensions() {
            $topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = (parseInt($box[0].style.width, 10) - interfaceWidth) + 'px';
            $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = (parseInt($box[0].style.height, 10) - interfaceHeight) + 'px';
        }

        css = { width: settings.w + loadedWidth + interfaceWidth, height: settings.h + loadedHeight + interfaceHeight, top: top, left: left };

        // setting the speed to 0 if the content hasn't changed size or position
        if (speed) {
            var tempSpeed = 0;
            $.each(css, function (i) {
                if (css[i] !== previousCSS[i]) {
                    tempSpeed = speed;
                    return;
                }
            });
            speed = tempSpeed;
        }

        previousCSS = css;

        if (!speed) {
            $box.css(css);
        }

        $box.dequeue().animate(css, {
            duration: speed || 0,
            complete: function () {
                modalDimensions();

                active = false;

                // shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation.
                $wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px";
                $wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px";

                if (settings.get('reposition')) {
                    setTimeout(function () {  // small delay before binding onresize due to an IE8 bug.
                        $window.bind('resize.' + prefix, publicMethod.position);
                    }, 1);
                }

                if ($.isFunction(loadedCallback)) {
                    loadedCallback();
                }
            },
            step: modalDimensions
        });
    };

    publicMethod.resize = function (options) {
        var scrolltop;

        if (open) {
            options = options || {};

            if (options.width) {
                settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth;
            }

            if (options.innerWidth) {
                settings.w = setSize(options.innerWidth, 'x');
            }

            $loaded.css({ width: settings.w });

            if (options.height) {
                settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight;
            }

            if (options.innerHeight) {
                settings.h = setSize(options.innerHeight, 'y');
            }

            if (!options.innerHeight && !options.height) {
                scrolltop = $loaded.scrollTop();
                $loaded.css({ height: "auto" });
                settings.h = $loaded.height();
            }

            $loaded.css({ height: settings.h });

            if (scrolltop) {
                $loaded.scrollTop(scrolltop);
            }

            publicMethod.position(settings.get('transition') === "none" ? 0 : settings.get('speed'));
        }
    };

    publicMethod.prep = function (object) {
        if (!open) {
            return;
        }

        var callback, speed = settings.get('transition') === "none" ? 0 : settings.get('speed');

        $loaded.remove();

        $loaded = $tag(div, 'LoadedContent').append(object);

        function getWidth() {
            settings.w = settings.w || $loaded.width();
            settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w;
            return settings.w;
        }
        function getHeight() {
            settings.h = settings.h || $loaded.height();
            settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h;
            return settings.h;
        }

        $loaded.hide()
		.appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations.
		.css({ width: getWidth(), overflow: settings.get('scrolling') ? 'auto' : 'hidden' })
		.css({ height: getHeight() })// sets the height independently from the width in case the new width influences the value of height.
		.prependTo($content);

        $loadingBay.hide();

        // floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width.

        $(photo).css({ 'float': 'none' });

        setClass(settings.get('className'));

        callback = function () {
            var total = $related.length,
				iframe,
				complete;

            if (!open) {
                return;
            }

            function removeFilter() { // Needed for IE8 in versions of jQuery prior to 1.7.2
                if ($.support.opacity === false) {
                    $box[0].style.removeAttribute('filter');
                }
            }

            complete = function () {
                clearTimeout(loadingTimer);
                $loadingOverlay.hide();
                trigger(event_complete);
                settings.get('onComplete');
            };


            $title.html(settings.get('title')).show();
            $loaded.show();

            if (total > 1) { // handle grouping
                if (typeof settings.get('current') === "string") {
                    $current.html(settings.get('current').replace('{current}', index + 1).replace('{total}', total)).show();
                }

                $next[(settings.get('loop') || index < total - 1) ? "show" : "hide"]().html(settings.get('next'));
                $prev[(settings.get('loop') || index) ? "show" : "hide"]().html(settings.get('previous'));

                slideshow();

                // Preloads images within a rel group
                if (settings.get('preloading')) {
                    $.each([getIndex(-1), getIndex(1)], function () {
                        var img,
							i = $related[this],
							settings = new Settings(i, $.data(i, colorbox)),
							src = settings.get('href');

                        if (src && isImage(settings, src)) {
                            src = retinaUrl(settings, src);
                            img = document.createElement('img');
                            img.src = src;
                        }
                    });
                }
            } else {
                $groupControls.hide();
            }

            if (settings.get('iframe')) {

                iframe = settings.get('createIframe');

                if (!settings.get('scrolling')) {
                    iframe.scrolling = "no";
                }

                $(iframe)
					.attr({
					    src: settings.get('href'),
					    'class': prefix + 'Iframe'
					})
					.one('load', complete)
					.appendTo($loaded);

                $events.one(event_purge, function () {
                    iframe.src = "//about:blank";
                });

                if (settings.get('fastIframe')) {
                    $(iframe).trigger('load');
                }
            } else {
                complete();
            }

            if (settings.get('transition') === 'fade') {
                $box.fadeTo(speed, 1, removeFilter);
            } else {
                removeFilter();
            }
        };

        if (settings.get('transition') === 'fade') {
            $box.fadeTo(speed, 0, function () {
                publicMethod.position(0, callback);
            });
        } else {
            publicMethod.position(speed, callback);
        }
    };

    function load() {
        var href, setResize, prep = publicMethod.prep, $inline, request = ++requests;

        active = true;

        photo = false;

        trigger(event_purge);
        trigger(event_load);
        settings.get('onLoad');

        settings.h = settings.get('height') ?
				setSize(settings.get('height'), 'y') - loadedHeight - interfaceHeight :
				settings.get('innerHeight') && setSize(settings.get('innerHeight'), 'y');

        settings.w = settings.get('width') ?
				setSize(settings.get('width'), 'x') - loadedWidth - interfaceWidth :
				settings.get('innerWidth') && setSize(settings.get('innerWidth'), 'x');

        // Sets the minimum dimensions for use in image scaling
        settings.mw = settings.w;
        settings.mh = settings.h;

        // Re-evaluate the minimum width and height based on maxWidth and maxHeight values.
        // If the width or height exceed the maxWidth or maxHeight, use the maximum values instead.
        if (settings.get('maxWidth')) {
            settings.mw = setSize(settings.get('maxWidth'), 'x') - loadedWidth - interfaceWidth;
            settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw;
        }
        if (settings.get('maxHeight')) {
            settings.mh = setSize(settings.get('maxHeight'), 'y') - loadedHeight - interfaceHeight;
            settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh;
        }

        href = settings.get('href');

        loadingTimer = setTimeout(function () {
            $loadingOverlay.show();
        }, 100);

        if (settings.get('inline')) {
            var $target = $(href).eq(0);
            // Inserts an empty placeholder where inline content is being pulled from.
            // An event is bound to put inline content back when Colorbox closes or loads new content.
            $inline = $('<div>').hide().insertBefore($target);

            $events.one(event_purge, function () {
                $inline.replaceWith($target);
            });

            prep($target);
        } else if (settings.get('iframe')) {
            // IFrame element won't be added to the DOM until it is ready to be displayed,
            // to avoid problems with DOM-ready JS that might be trying to run in that iframe.
            prep(" ");
        } else if (settings.get('html')) {
            prep(settings.get('html'));
        } else if (isImage(settings, href)) {

            href = retinaUrl(settings, href);

            photo = settings.get('createImg');

            $(photo)
			.addClass(prefix + 'Photo')
			.bind('error.' + prefix, function () {
			    prep($tag(div, 'Error').html(settings.get('imgError')));
			})
			.one('load', function () {
			    if (request !== requests) {
			        return;
			    }

			    // A small pause because some browsers will occasionally report a
			    // img.width and img.height of zero immediately after the img.onload fires
			    setTimeout(function () {
			        var percent;

			        if (settings.get('retinaImage') && window.devicePixelRatio > 1) {
			            photo.height = photo.height / window.devicePixelRatio;
			            photo.width = photo.width / window.devicePixelRatio;
			        }

			        if (settings.get('scalePhotos')) {
			            setResize = function () {
			                photo.height -= photo.height * percent;
			                photo.width -= photo.width * percent;
			            };
			            if (settings.mw && photo.width > settings.mw) {
			                percent = (photo.width - settings.mw) / photo.width;
			                setResize();
			            }
			            if (settings.mh && photo.height > settings.mh) {
			                percent = (photo.height - settings.mh) / photo.height;
			                setResize();
			            }
			        }

			        if (settings.h) {
			            photo.style.marginTop = Math.max(settings.mh - photo.height, 0) / 2 + 'px';
			        }

			        if ($related[1] && (settings.get('loop') || $related[index + 1])) {
			            photo.style.cursor = 'pointer';

			            $(photo).bind('click.' + prefix, function () {
			                publicMethod.next();
			            });
			        }

			        photo.style.width = photo.width + 'px';
			        photo.style.height = photo.height + 'px';
			        prep(photo);
			    }, 1);
			});

            photo.src = href;

        } else if (href) {
            $loadingBay.load(href, settings.get('data'), function (data, status) {
                if (request === requests) {
                    prep(status === 'error' ? $tag(div, 'Error').html(settings.get('xhrError')) : $(this).contents());
                }
            });
        }
    }

    // Navigates to the next page/image in a set.
    publicMethod.next = function () {
        if (!active && $related[1] && (settings.get('loop') || $related[index + 1])) {
            index = getIndex(1);
            launch($related[index]);
        }
    };

    publicMethod.prev = function () {
        if (!active && $related[1] && (settings.get('loop') || index)) {
            index = getIndex(-1);
            launch($related[index]);
        }
    };

    // Note: to use this within an iframe use the following format: parent.jQuery.colorbox.close();
    publicMethod.close = function () {
        if (open && !closing) {

            closing = true;
            open = false;
            trigger(event_cleanup);
            settings.get('onCleanup');
            $window.unbind('.' + prefix);
            $overlay.fadeTo(settings.get('fadeOut') || 0, 0);

            $box.stop().fadeTo(settings.get('fadeOut') || 0, 0, function () {
                $box.hide();
                $overlay.hide();
                trigger(event_purge);
                $loaded.remove();

                setTimeout(function () {
                    closing = false;
                    trigger(event_closed);
                    settings.get('onClosed');
                }, 1);
            });
        }
    };

    // Removes changes Colorbox made to the document, but does not remove the plugin.
    publicMethod.remove = function () {
        if (!$box) { return; }

        $box.stop();
        $[colorbox].close();
        $box.stop(false, true).remove();
        $overlay.remove();
        closing = false;
        $box = null;
        $('.' + boxElement)
			.removeData(colorbox)
			.removeClass(boxElement);

        $(document).unbind('click.' + prefix).unbind('keydown.' + prefix);
    };

    // A method for fetching the current element Colorbox is referencing.
    // returns a jQuery object.
    publicMethod.element = function () {
        return $(settings.el);
    };

    publicMethod.settings = defaults;

}(jQuery, document, window));
;
$(function () {
    var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
    if (window.location.pathname === "/play/" || window.location.pathname === "/play" || window.location.pathname === "/en/play/" || window.location.pathname === "/en/play") {
        var playlandingcookie = Cookies.get('playlandingcookie');
        var hasPlayCookie = typeof playlandingcookie !== 'undefined';
        if (!hasPlayCookie) {
            Cookies.set('playlandingcookie', 1, { expires: 3000 });
            if (!iOS) {
                //
            }
        } else {
            console.log("hasCookie");
        }
    } else {
        Cookies.remove('playlandingcookie');
    }

    $("body").on("click", ".js-play-sortorder button", function (e) {
        e.preventDefault();

        $(".js-play-sortorder button").toggleClass("active");
        
        e.preventDefault();
        FilterEngine.Search(null, true);
    });
});;
var K = K || {};
K.Play = {
    Init: function () {
        $("body").on("click", ".js-open-play-modal", function (e) {

            e.preventDefault();
            var $self = $(this);
            var trailerUrl = $self.data("trailer");
            $self.blur();

            K.Play.OpenModal(trailerUrl);
        });

        $("body").on("click", ".js-close-play-modal", function (e) {
            e.preventDefault();
            K.Play.CloseModal($(this));
        });

        $("body").on("click", ".js-play-load-more",
            function (e) {
                e.preventDefault();
                K.Play.LoadMore($(this));
            });
    },
    GetModalMarkup: function (content) {
        var lang = $("html").attr("lang");
        var closeText = lang == "en" ? "Close" : "Stäng";

        return $('<div id="myModal" class="modal" style="display:none;">' +
            '<div class="modal-content">' +
            '<button id="close" class="button-close js-close-play-modal">' + closeText + '</button>' +
            content +
            '</div></div>');
    },
    OpenModal: function (trailerUrl) {
        $.get(trailerUrl, function (response) {
            var $markup = K.Play.GetModalMarkup(response);
            $(this).delay(300).queue(function (next) {
                $("body").addClass("noscroll");
            });

            $("body").prepend($markup.fadeIn(1000, function () {
            }));
        });
    },
    CloseModal: function ($trigger) {
        $trigger.closest(".modal").detach();
        $("body").removeClass("noscroll");
    },
    LoadMore: function ($trigger) {
        var take = parseInt($trigger.attr("data-take")),
            $container = $("body"),
            skip = parseInt($container.find(".js-related-movie").length),
            $filterContainer = $("body").find(".js-movie-calendar-filter"),
            url = window.location.href;


        var typefilters = [];

        var $typefillterul = $filterContainer.find(".js-type-filters:first");

        var $selectedTypeFilters = $typefillterul.find(":checked");
        $selectedTypeFilters.each(function () {
            var $curr = $(this);
            var $hiddentypesibling = $curr.hasClass("js-select-all") ? $curr.siblings("[name$='Id']") : $curr.siblings("[name$='Value']");
            var value = parseInt($hiddentypesibling.val());
            if (value !== 0) {
                typefilters.push(parseInt($hiddentypesibling.val()));
            }
        });
        $("<div class='text-center js-temp-load' aria-live='polite' aria-busy='true'><img alt='loading' src='/Static/icons/loader.svg'/></div>").insertBefore($trigger);
        $.ajax({
            url: "/MovieLandingPage/LoadMore",
            dataType: "json",
            method: "POST",
            data: { skip: skip, categories: typefilters, lang: $("html").attr("lang") },
            success: function (response) {
                $trigger.removeAttr("disabled", true);
                if (response.HideSelf) {
                    $trigger.fadeOut(300);
                }
                var $markupResponse = $(response.Html),
                    $targetToReplace = $trigger.siblings(".js-temp-load:first");
                $markupResponse.hide();
                $targetToReplace.replaceWith($markupResponse);
                $markupResponse.fadeIn("300", function () {
                    window.slimmage.checkResponsiveImages();
                    var $firstLi = $markupResponse.children();

                    var $a = $($markupResponse.find(".js-related-movie").find("a")[0]);
                    $a.closest(".clickableArea").addClass('highlightTabbing');
                    $a.focus();


                    $markupResponse.on("keyup", "a", function (e) {
                        var code = e.keyCode ? e.keyCode : e.which;
                        var el = document.activeElement;
                        if (code == '9') {
                            $(this).closest(".clickableArea").addClass('highlightTabbing');
                        }
                    }).on("keydown", "a", function (e) {
                        var code = e.keyCode ? e.keyCode : e.which;
                        var el = document.activeElement;
                        if (code == '9') {
                            $(this).closest(".clickableArea").removeClass('highlightTabbing');
                        }
                    }).on("blur", "a", function (e) {
                        $(this).closest(".clickableArea").removeClass('highlightTabbing');
                    });
                });

            }, error: function (xhr) {

            }
        });

    }
}

;
var AutoComplete = AutoComplete || {};
var FilterEngine = {
    PendingRequest: null,
    Skip: parseInt($("body").find(".js-hs-result-li").length),
    Take: parseInt($(".js-historical-search").attr("data-take")),
    StartYear: $(".js-historical-search").attr("data-startyear") == "0" ? 1900 : parseInt($(".js-historical-search").attr("data-startyear")),
    ToggleFilter: function (e) {
        e.preventDefault();
        e.stopPropagation();
        var $self = $(this),
            id = $self.data("id"),
            isFree = $self.hasClass("free"),
            type = !isFree ? $self.attr("data-type").toLowerCase() : "categoryfilter",
            translatedType = !isFree ? $self.attr("data-ts-type") : "",
            html = $self.attr("data-markup"),
            shouldRemove = $self.hasClass("js-ac-remove"),
            $container = $self.closest(".js-historical-search"),
            $ghostinputcontainer = $container.find(".js-ac-ghost-container"),
            $textField = $ghostinputcontainer.find("input[type='text']"),
            $freeText = $container.find(".js-ac-freetext");
        if (shouldRemove) {
            if (type == "year") {
                var yearType = $self.closest("li").find("[data-year]").attr("data-type");
                if (yearType == "start") {
                    $("#StartYear").prop("type", "text");
                    $("#StartYear").val("");
                    $("#StartYear").prop("type", "number");
                } else {
                    $("#EndYear").prop("type", "text");
                    $("#EndYear").val("");
                    $("#EndYear").prop("type", "number");
                }
            }
            var $li = $(this).closest("li"),
                parentid = $li.attr("data-parentid"),
                isCategoryfilter = typeof (parentid) !== "undefined";
            if (isCategoryfilter) {
                FilterEngine.ResetFilterGroup($li.attr("data-id"), parentid);
            }
            $(this).closest("li").fadeOut(400).remove();
        } else {
            var text = $self.find(".autocomplete-hit-text").parent().data("markup"),
                firstSurrounded = text[0] === '"',
                lastSurrounded = text[text.length - 1] === '"';
            var closeTxt = $("html").attr("lang") === "en" ? "remove " : "ta bort ";
            var $clone = $self.find(".autocomplete-hit-text").clone();
            var childText = $clone.find("span:first").text();
            var $closeBtn = $("<div class='button-wrapper'><button data-type=" +
                type +
                " data-id=" +
                id +
                " class='js-ac-remove'><span>" + closeTxt + translatedType + " " + $clone.text() + "</span></button></div>");
            var $attached;

            $clone.children().remove();
            var t = $clone.text().replaceAll("\"", "");
            t += "¤" + childText;
            if (!isFree) {
                $attached = $("<li data-type=" +
                    type + " data-hack=\"" + t + "\"" +
                    " data-id=" +
                    id +
                    " class='js-autocomplete-filter " +
                    type +
                    "-filter'><div class='label-wrapper'><label>" +
                    translatedType +
                    "</label><span>" +
                    text.replaceAll("\"", "") +
                    "</span></div></li>");
                if ($ghostinputcontainer.find(".js-autocomplete-filter").length) {
                    $attached.insertAfter($ghostinputcontainer.find(".js-autocomplete-filter:last")).fadeIn(500);
                } else {
                    $ghostinputcontainer.find("ul:first").prepend($attached);
                    $attached.fadeIn(500);
                }
                $attached.append($closeBtn);
                var $bntn = $attached.find(".js-ac-remove");
                $bntn.get(0).addEventListener("click", FilterEngine.ToggleFilter, false);
            } else {
                //$attached = $("<li data-type=" + type + " class='js-autocomplete-filter free-text'><span>" + text.replaceAll("\"", "") + "</span></li>");
                var $last = $ghostinputcontainer.find(".js-autocomplete-filter").length ? $ghostinputcontainer.find(".js-autocomplete-filter:last") : $ghostinputcontainer.find("li:last");
                AutoComplete.AddChunks($last, text, type, true);
            }
        }
        $textField.val("").focus();
        $freeText.find("p").remove();
        FilterEngine.Search();
    },
    RemoveYearFilterFromParameter: function ($elem) {
        var $self = $elem;
        var yearType = $self.closest("li").find("[data-year]").attr("data-type");
        if (yearType == "start") {
            $("#StartYear").prop("type", "text");
            $("#StartYear").val(FilterEngine.StartYear);
            $("#StartYear").prop("type", "number");
        } else {
            $("#EndYear").prop("type", "text");
            $("#EndYear").val(new Date().getFullYear());
            $("#EndYear").prop("type", "number");
        }
        var $li = $(this).closest("li"),
            parentid = $li.attr("data-parentid"),
            isCategoryfilter = typeof (parentid) !== "undefined";
        if (isCategoryfilter) {
            FilterEngine.ResetFilterGroup($li.attr("data-id"), parentid);
        }
        $(this).closest("li").fadeOut(400).remove();
    },
    ResetFilterGroup: function (currentid, parentid) {
        var $filtergroup = $(".js-sub-filter-group[data-parentfilterid=" + parentid + "]");
        if (!$filtergroup.length) {
            return false;
        }
        var $inputs = $filtergroup.find("input[type='checkbox']"),
            isBoxGroup = true;
        if (!$inputs.length) {
            $inputs = $filtergroup.find("input[type='radio']");
            isBoxGroup = false;
        }
        $inputs.each(function () {
            if (isBoxGroup) {
                $(this).prop("checked", true);
                //if ($(this).prev().val() === currentid) {
                //    $(this).removeAttr("checked");
                //}
            } else {
                if ($(this).hasClass("js-select-all-hs")) {
                    $(this).prop("checked", true);
                } else {
                    $(this).removeAttr("checked");
                }
            }
        });

        if (isBoxGroup && !$filtergroup.find("input:checked").length) {
            $filtergroup.find(".js-select-all-hs").prop("checked", true);
        }
    },
    GetFilterDictionary: function ($filterContainer) {
        var filters = [];

        var $artists = $filterContainer.find(".artist-filter");
        var $composers = $filterContainer.find(".composer-filter");
        var $works = $filterContainer.find(".work-filter");
        var $productions = $filterContainer.find(".production-filter");
        var $categories = $filterContainer.find(".category-filter");

        var artists = [];
        $artists.each(function () {
            var artist = {
                Id: $(this).data("id"),
                Value: $(this).find("span:first").html()
            };
            artists.push(artist);
        });

        var composers = [];
        $composers.each(function () {
            var composer = {
                Id: $(this).data("id"),
                Value: $(this).find("span:first").html()
            };
            composers.push(composer);
        });

        var works = [];
        $works.each(function () {
            var work = {
                Id: $(this).data("id"),
                Value: typeof $(this).attr("data-hack") !== "undefined" ? $(this).attr("data-hack") : $(this).find("span:first").html()
            };
            works.push(work);
        });

        var productions = [];
        $productions.each(function () {
            var work = {
                Id: $(this).data("id"),
                Value: $(this).find("span:first").html()
            };
            productions.push(work);
        });

        var categories = [];
        $categories.each(function () {
            var work = {
                Id: $(this).data("id"),
                Value: $(this).find("span:first").html()
            };
            categories.push(work);
        });

        filters.push({ Key: "Artist", Value: artists.length ? artists : 0 });
        filters.push({ Key: "Composer", Value: composers.length ? composers : 0 });
        filters.push({ Key: "Work", Value: works.length ? works : 0 });
        filters.push({ Key: "Production", Value: productions.length ? productions : 0 });
        filters.push({ Key: "Category", Value: categories.length ? categories : 0 });

        return filters;
    },
    GetHistoricalSearchFilter: function ($container) {
        var historicalSearchFilter = {
            YearFilter: FilterEngine.GetYearFilter($container),
            Filters: FilterEngine.GetCategoryFilters($container)
        };
        return historicalSearchFilter;
    },
    GetYearFilter: function ($container) {
        var $startTag = $("body").find("#StartYear");
        var $endTag = $("body").find("#EndYear");
        var startValue = $startTag.val();
        var endValue = $endTag.val();
        var YearFilter = {
            StartYear: typeof (startValue) !== "undefined" && startValue !== "" ? startValue : "1753",
            EndYear: typeof (endValue) !== "undefined" && endValue != "" ? endValue : "9999"
        }
        return YearFilter;
    },
    GetCategoryFilters: function ($ghostContainer) {
        var $filters = $ghostContainer.find("[data-type='categoryfilter']").not(".free-text");
        var filters = [];
        var parentIds = [];
        var $boxContainer = $(".js-sub-filter-group[data-parentfilterid=" + 30 + "]"),
            $checked = $boxContainer.find("input[type='checkbox']").filter(function () { return $(this).is(":checked"); });


        var checkfilters = [];
        $checked.each(function () {
            var sFilter = {
                Id: $(this).prev().val(),
                HistoricalFilterType: 20
            };
            checkfilters.push(sFilter);
        });
        var filterT = {
            Id: 30,
            HistoricalFilterType: 20,
            HistoricalSubFilters: checkfilters,
            IsRadio: false
        };
        filters.push(filterT);

        if (!$filters.length) {
            return filters;
        }
        $filters.each(function () {
            var parentId = $(this).attr("data-parentid");

            if (parentIds.indexOf(parentId) < 0) {
                parentIds.push(parentId);
                if (parentId == 30) {
                    return true;
                } else {
                    var $subfilters = $ghostContainer.find("[data-parentid=" + parentId + "]");
                    var subfilters = [];
                    $subfilters.each(function () {
                        var filterType = $(this).data("historical-filter-type"),
                            id = $(this).attr("data-id");
                        var subfilter = {
                            Id: id,
                            HistoricalFilterType: filterType
                        };
                        subfilters.push(subfilter);
                    });
                    var filter = {
                        Id: parentId,
                        HistoricalFilterType: $(this).data("historical-filter-type"),
                        HistoricalSubFilters: subfilters,
                        IsRadio: $(this).attr("data-isradio")
                    };
                    filters.push(filter);
                }
            }
        });
        console.log(filters);
        return filters;
    },
    BuildModel: function ($ghostinputcontainer) {
        var order = "True";

        if ($("#jsautocomplete").data("type") === "historical") {
            var $sortBtn = $(".js-hs-datesort");
            order = $sortBtn.attr("data-order");
        }

        if ($("#jsautocomplete").data("type") === "play") {
            var $activSortBtn = $(".jsButtonSort.active");

            if ($activSortBtn.data("sort") === "latest") {
                order = "True";
            }

            if ($activSortBtn.data("sort") === "popular") {
                order = "False";
            }
        }

        var model = {};
        var filterDictionary = FilterEngine.GetFilterDictionary($ghostinputcontainer);
        if (FilterEngine.IsEmpty(filterDictionary)) {
            filterDictionary = null;
        }
        model.FilterDictionary = filterDictionary;

        var historicalSearchFilter = FilterEngine.GetHistoricalSearchFilter($ghostinputcontainer);

        var freeText = "";
        var $freetexts = $ghostinputcontainer.find(".free-text");
        $freetexts.each(function (i) {
            var divider = i === $freetexts.length - 1 ? "" : "|";
            freeText += $(this).find("span:first").html() + divider;
        });
        $ghostinputcontainer.find("input[type='text']").val("");

        var $hitTypeFilter = $ghostinputcontainer.find("[data-historical-filter-type='40']");
        var hitTypeFilterValue = $hitTypeFilter.length ? $hitTypeFilter.attr("data-hittype") : "";
        model.FreeText = freeText;
        model.SortAsc = order;
        model.AutoCompleteType = hitTypeFilterValue;
        model.YearFilter = historicalSearchFilter.YearFilter;
        model.Filters = historicalSearchFilter.Filters;
        model.DatabaseId = $(".js-historical-search").attr("data-sharedbid");
        return model;
    },
    Search: function (loadmore, updatesortorder) {
        var isloadmore = typeof (loadmore) !== "undefined" && loadmore !== null;
        var isSort = typeof (updatesortorder) !== "undefined" && updatesortorder !== null;
        var $resultContainer = $(".js-result-container"),
            $ghostinputcontainer = $(".js-ac-ghost-container");
        $ghostinputcontainer.siblings().remove();
        var model = FilterEngine.BuildModel($ghostinputcontainer);
        var lang = $("html").attr("lang");
        $(".js-traditional-trigger").addClass("button-loading");
        FilterEngine["PendingRequest"] = $.ajax({
            beforeSend: function () {
                if (FilterEngine["PendingRequest"] != null) {
                    FilterEngine["PendingRequest"].abort();
                }
                if (AutoComplete["PendingRequest"] != null) {
                    AutoComplete["PendingRequest"].abort();
                }
                $(".js-hs-load-more").hide();
                if (isloadmore) {
                    $(".js-result-count").clone().insertAfter($(".js-hs-load-more")).hide().fadeIn(200, function () {
                        //$(this).focus();
                    });
                }
                $(".js-result-count").each(function () {
                    $(this).addClass("loading");
                    $(this).html($(this).data("ts-load"));
                });
            },
            url: $("#jsautocomplete").data("filterurl"),
            method: "post",
            dataType: 'json',
            data: {
                historicalSearchFilter: model,
                skip: isloadmore ? FilterEngine.Skip : 0,
                take: FilterEngine.Take,
                updatesortorder: isSort,
                lang: lang
            },
            success: function (response) {

                $(".js-start-container").remove();

                var isCanceled = typeof (response.CancelMsg) !== "undefined";
                console.log("is canceled " + isCanceled);
                if (!isCanceled) {
                    if ($(".js-autocomplete").val() === "") {
                        $ghostinputcontainer.next().fadeOut(200);
                    }

                    if (isloadmore && $(".js-hs-load-more").next().hasClass("js-result-count")) {
                        $(".js-hs-load-more").next().remove();
                    }
                    if (response.HideLoadMore) {
                        $(".js-hs-load-more").hide();
                    } else {
                        $(".js-hs-load-more").html(response.UpdatedLoadMoreText);
                        $(".js-hs-load-more").show();
                    }
                    if (!isloadmore) {
                        $resultContainer.hide().html(response.Html).fadeIn(300,
                            function () {
                            });
                    } else {
                        $resultContainer.append(response.Html).slideDown(100,
                            function () {
                                var $li = $(".js-hs-result-li").eq(FilterEngine.Skip);
                                if ($li.length) {
                                    var $focused = $(':focus');
                                    if (!$focused.is("input[type='text']")) {
                                        $('html, body').animate({
                                            scrollTop: $li.offset().top
                                        },
                                            800,
                                            function () {
                                                $li.delay(400).queue(function (next) {
                                                    $li.removeAttr("style");
                                                    $li.find("h3:first").attr("tabindex", -1);
                                                    $li.find("h3:first").focus();
                                                    next();
                                                });
                                            });
                                    }
                                }
                            });
                    }
                    var resultCount = isloadmore ? response.LoadMoreHitText : $(".js-result-container").find(".js-result-count").text().replace(" ", "");

                    $(".js-result-count").each(function () {
                        $(this).hide().removeClass("loading");
                        $(this).html(resultCount.replace(/\b(\d+)\b/g, '<span>$1</span>')).fadeIn(100);
                    });

                    FilterEngine["Skip"] = $resultContainer.find(".js-hs-result-li").length;
                    FilterEngine["PendingRequest"] = null;
                    AutoComplete["YearTagPending"] = null;

                    FilterEngine.HandleClearBtn($ghostinputcontainer);
                    $(".js-traditional-trigger").removeClass("button-loading");
                    localStorage.removeItem("textor");
                    var hidesort = response.HideSort;
                    if (hidesort) {
                        $(".js-hs-datesort").hide();
                    }
                } else {
                    $(".js-traditional-trigger").removeClass("button-loading");
                    $(".js-result-count").each(function () {
                        $(this).hide().removeClass("loading");
                        $(this).html(response.CancelMsg).fadeIn(100);
                    });
                    $(".js-result-wrapper").html("");
                }

                $('.carousel').flickity({
                    contain: true,
                    prevNextButtons: true,
                    pageDots: false,
                    cellAlign: "left",
                    groupCells: 2
                });

                setTimeout(function () {
                    window.slimmage.checkResponsiveImages();
                    $('.clickableArea').matchHeight();
                    $('.jsMovieItem').matchHeight();
                }, 50);

                setTimeout(function () {
                    $(".carousel[data-lazyload='True']").each(function () {
                        FilterEngine.LazyLoad(this.id);
                    });
                }, 500);
            },
            error: function (xhr, e) {
                //console.error(xhr.responseText);
                console.error(e);
                FilterEngine["PendingRequest"] = null;

            }
        });
    },
    LazyLoad: function (contentGuid) {
        const lang = $("html").attr("lang");

        if ($(".js-ac-ghost-container").find(".js-autocomplete-filter").length === 0) {
            $.ajax({
                url: "/MovieLandingPage/LazyLoad",
                dataType: "json",
                method: "GET",
                data: { contentGuid: contentGuid, lang: lang },
                success: function (response) {
                    $('#' + contentGuid).flickity('append', $(response.Html));

                    setTimeout(function () {
                        window.slimmage.checkResponsiveImages();
                        $('.clickableArea').matchHeight();
                        $('.jsMovieItem').matchHeight();
                    },
                        50);
                },
                error: function (xhr) {
                    console.log(xhr);
                }
            });
        } else {
            const $ghostinputcontainer = $(".js-ac-ghost-container");
            $ghostinputcontainer.siblings().remove();
            const model = FilterEngine.BuildModel($ghostinputcontainer);

            $.ajax({
                url: "/MovieLandingPage/LazyLoadWithFilter",
                dataType: "json",
                method: "POST",
                data: { historicalSearchFilter: model, contentGuid: contentGuid, lang: lang },
                success: function (response) {
                    $('#' + contentGuid).flickity('append', $(response.Html));

                    setTimeout(function () {
                        window.slimmage.checkResponsiveImages();
                        $('.clickableArea').matchHeight();
                        $('.jsMovieItem').matchHeight();
                    },
                        50);
                },
                error: function (xhr) {
                    console.log(xhr);
                }
            });
        }
    },
    BackToIndex: function () {
        var url = FilterEngine.GetCookieLocation();
        $.ajax({
            type: "GET",
            url: url,
            data: {},
            dataType: "html",
            success: function (response) {
                $("body").html(response);
            }
        });
    },
    StoreCookieLocation: function () {
        var lang = $("html").attr("lang");
        Cookies.set('currentLocation_' + lang, window.location.href, { expires: 3000 });
    },
    GetCookieLocation: function () {
        var lang = $("html").attr("lang");
        return Cookies.get('currentLocation_' + lang);
    },
    IsEmpty: function (obj) {
        return Object.keys(obj).length === 0;
    },
    LoadMore: function () {
        FilterEngine.Search(true, null);
    },
    ClearAll: function (e) {
        e.preventDefault();
        var $self = $(this),
            $ul = $(".js-ac-ghost-container").find("ul:first");
        $self.attr("diabled", "disabled");
        $ul.find(".js-autocomplete-filter").each(function () {
            var $btn = $(this).find(".js-ac-remove");
            if ($(this).hasClass("js-ac-year-tag-from") || $(this).hasClass("js-ac-year-tag-to")) {
                FilterEngine.RemoveYearFilterFromParameter($btn);
            } else {
                AutoComplete.RemoveFilterTagFromParameter($btn, false);
            }
            $btn.closest("li").remove();
        });
        $(this).delay(200).queue(function (next) {
            FilterEngine.Search();
            next();
        });
    },
    HandleClearBtn: function ($ghostinputcontainer) {
        //var $ul = $ghostinputcontainer.find("ul:first");
        //var leng = $ul.find(".js-autocomplete-filter").length;
        //leng >= 2 ? $(".js-hs-clearance").find("button").removeAttr("disabled") : $(".js-hs-clearance").find("button").attr("disabled", "disabled");
    },
    StoreFilters: function (e) {
        e.preventDefault();
        var $self = $(this);

        if ($self.attr("href") !== "#" && $self.attr("href") !== undefined) {
            window.open($self.attr('href'));
        }

        var $ghostContainer = $(".js-ac-ghost-container");
        var model = FilterEngine.BuildModel($ghostContainer);
        $.ajax({
            url: "/SearchHistoricalPage/StoreFilter",
            method: "post",
            data: { historicalSearchFilter: model, hits: $(".historical-results-found").text().replace(/\s/g, "").match(/\d+/) },
            success: function (response) {
                $(".js-historical-search").attr("data-sharedbid", newGuid());

                if (response === 200 && $self.attr("href") === "#") {
                    var $old = $("<a class='js-mocked-share-this' target='_blank' href='#'><span class='hideText-for-small'>Spara filtrering!</span></a>");
                    var $new = $("<p>Ditt filter har sparats.</p>");
                    var $parent = $self.closest("li");
                    $self.fadeOut(300).remove();
                    $parent.append($new);
                    $new.fadeOut(5000,
                        function () {
                            $(this).remove();
                            $parent.append($old);
                        });
                }
            },
            error: function (xhr) {
                console.error(xhr.responseText);
            }
        });
    }
}
function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function newGuid() {
    // then to call it, plus stitch in '4' in the third group
    var guid = (S4() + S4() + "-" + S4() + "-4" + S4().substr(0, 3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
    return guid;
}

String.prototype.replaceAll = function (str1, str2, ignore) {
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof (str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);
};
var AutoComplete = {
    PendingRequest: null,
    YearTagPending: null,
    GhostContainer: $(".js-ac-ghost-container"),
    SweMode: $("html").attr("lang") === "sv",
    EventHandler: function (elem, event, func) {
        elem.addEventListener(event, func, false);
    },
    AdjustSize: function ($input) {
        if ($input.val().length > 20) {
            $input.attr("size", $input.val().length);
        }
    },
    Request: function (e) {
        var $input = $(this),
            val = $input.val(),
            keycode = e.keyCode || e.which,
            $ghostContainer = $input.closest(".js-ac-ghost-container"),
            $ul = $ghostContainer.find("ul:first"),
            $word = $(".searchWordsListing"),
            $free = $word.find(".free"),
            lang = $("html").attr("lang");
        if (val.length > 120 || (val.length < 1 && (keycode !== 8))) {
            AutoComplete["pendingRequest"] = null;
            $(".searchWordsListing").remove();
            return false;
        }
        var evt = e || window.event;
        var charCode = evt.which || evt.keyCode;
        var charStr = String.fromCharCode(charCode);
        var isNumberOrLetter = /[a-z0-9]/i.test(charStr);
        $(this).delay(10).queue(function (next) {
            if (!$free.length &&
                AutoComplete["PendingRequest"] == null &&
                val.trim() !== "" &&
                (isNumberOrLetter || charCode === 32 || charCode === 8)) {
                if (charCode === 8 && val.length <= 0) {
                    //
                } else {
                    if (val.indexOf(" ") > 0 && val.length - 1 > val.indexOf(" ")) {
                        $word.find("ul:first").prepend(
                            '<li class="autocompleteItem free"><button data-type="free" class="js-autocomplete-hit" data-markup="' +
                            val +
                            '"> <span class="autocomplete-hit-type">' +
                            '</span> <span class="autocomplete-hit-text">' +
                            (lang === "en" ? "Search as phrase: " : "Sök som fras: ") +
                            '"' +
                            val +
                            '"</span></button></li>');
                    }
                }
            }
            next();
        });

        if (e.which === 40 || e.which === 9 && !(e.shiftKey && e.which === 9)) {
            var $target = $ghostContainer.next().find(".js-autocomplete-hit:first");
            if ($target.length) {
                $ghostContainer.next().find(".js-autocomplete-hit.free").addClass("white");
                $target.focus();
                return false;
            } else {
                $(".js-traditional-trigger").focus();
                return false;
            }
        }
        AutoComplete.AdjustSize($input);
        var prvVal = localStorage.getItem("textor");
        console.log(prvVal);
        localStorage.setItem("textor", val.trim());
        var isenterorspace = keycode === 13 || keycode === 32;
        if (isenterorspace && $ghostContainer.find("#jsautocomplete").val().trim() === "") {
            return false;
        }
        if (keycode === 9) {
            return false;
        }
        var keyCodeResult = AutoComplete.HandleKeyCodes(keycode, $input, val, prvVal);
        if (keyCodeResult) {
            FilterEngine.Search();
            return false;
        }
        if (typeof keyCodeResult !== "undefined") {
            return false;
        }
        var filterDictionary = FilterEngine.GetFilterDictionary(AutoComplete.GhostContainer);
        if (FilterEngine.IsEmpty(filterDictionary)) {
            filterDictionary = null;
        }
        var $hitTypeFilter = $ghostContainer.find("[data-historical-filter-type='40']");
        var hitTypeFilterValue = $hitTypeFilter.length ? $hitTypeFilter.attr("data-hittype") : "";
        var $constructedFreeTexts = AutoComplete.GhostContainer.find(".js-autocomplete-filter.free-text");
        var stringList = [];
        $constructedFreeTexts.each(function () {
            stringList.push($(this).find("span:first").text());
        });
        AutoComplete["PendingRequest"] = $.ajax({
            beforeSend: function () {
                if (AutoComplete["PendingRequest"] != null) {
                    AutoComplete["PendingRequest"].abort();
                }
            },
            url: $("#jsautocomplete").data("autocompleteurl"),
            method: "post",
            dataType: "html",
            data: {
                searchQuery: $input.val().trim(),
                hitType: hitTypeFilterValue,
                lang: lang,
                filterDictionary: filterDictionary,
                freeFilters: stringList
            },
            success: function (response) {

                var $ghostContainer = $input.closest(".js-ac-ghost-container");
                $ghostContainer.next().remove();
                $(response).hide().insertAfter($ghostContainer).fadeIn(200,
                    function () {
                        var $ul = $(this).find("ul:first");
                        if (!$ul.find(".free").length) {
                            if (val.indexOf(" ") > 0 && val.length - 1 > val.indexOf(" ")) {
                                $ul.prepend(
                                    '<li class="autocompleteItem free"><button data-type="free" class="js-autocomplete-hit free" data-markup="' +
                                    val +
                                    '"> <span class="autocomplete-hit-type">' +
                                    '</span> <span class="autocomplete-hit-text">' +
                                    (lang === "en" ? "Search as phrase:" : "Sök som fras: ") +
                                    '"' +
                                    val +
                                    '"</span></button></li>');
                            }
                        }
                    });

                AutoComplete["PendingRequest"] = null;
            },
            error: function (xhr, e, s, d) {
                console.error(xhr.responseText);
                console.error(e);
                console.error(s);
                console.error(d);
                AutoComplete["PendingRequest"] = null;

            }
        });
    },
    HandleKeyCodes: function (keycode, $input, val, prvVal) {
        var $container = $input.closest(".js-historical-search"),
            $freetext = $container.find(".js-ac-freetext"),
            $mockedInput = $input.closest(".js-ac-ghost-container"),
            $filters = $mockedInput.find(".js-autocomplete-filter");
        var forbiddencodes = {
            shift: 16,
            alt: 18,
            pause: 19,
            caps: 20,
            escape: 27,
            pageup: 33,
            pagedown: 34,
            end: 35,
            home: 36,
            leftArrow: 37,
            upArrow: 38,
            rightArrow: 39,
            downArrow: 40,
            f1: 112,
            f2: 113,
            f3: 114,
            f4: 115,
            f5: 116,
            f6: 117,
            f7: 118,
            f8: 119,
            f9: 120,
            f10: 121,
            f11: 122,
            f12: 123,
            leftwindow: 91,
            rightwindow: 92,
            numpad0: 96,
            numpad1: 97,
            numpad2: 98,
            numpad3: 99,
            numpad4: 100,
            numpad5: 101,
            numpad6: 102,
            numpad7: 103,
            numpad8: 104,
            numpad9: 105,
            multiply: 106,
            add: 107,
            subtract: 109,
            decimalpoint: 110,
            divide: 111,
            numlock: 144,
            scrolllock: 145,
            semicolon: 186,
            equalsign: 187,
            comma: 188,
            dash: 189,
            period: 190,
            forwardslash: 191,
            graveaccent: 192,
            openbracket: 219,
            closebracket: 221,
            singlequote: 222,
            delete: 46,
            insert: 45,
            volumedown: 174,
            volumeup: 175,
            Mute: 173,
            multiplex: 179,
            backslash: 220,
            weirda: 226,
            apostrof: 219
        };
        var validKeyCode = true;
        for (var property in forbiddencodes) {
            if (forbiddencodes.hasOwnProperty(property)) {
                if (keycode == forbiddencodes[property]) {
                    validKeyCode = false;
                    break;
                }
            }
        }
        if (!validKeyCode) {
            return false;
        }
        var backspace = keycode === 8,
            enter = keycode === 13,
            blur = keycode === 0,
            tab = keycode === 9,
            ctrldown = keycode === 17 || keycode === 91, //ctrl || cmd
            $lastLi = $mockedInput.find(".free-text, .work-filter, .artist-filter, .composer-filter")
                .filter(function () { return $(this).is(":visible"); }).last();
        if (enter || blur || ctrldown) {
            if (val !== "") {
                $lastLi = $mockedInput.find("li").last();
                AutoComplete.AddChunks($lastLi, val, null, false);
                $freetext.html("");
                return true;
            }
        } else if (backspace) {
            var isFromYearTag = $lastLi.hasClass("js-ac-year-tag-from");
            var isToYearTag = $lastLi.hasClass("js-ac-year-tag-to");
            if (isFromYearTag) {
                $("#StartYear").prop("type", "text");
                $("#StartYear").val(FilterEngine.StartYear);
                $("#StartYear").prop("type", "number");
            } else if (isToYearTag) {
                $("#EndYear").prop("type", "text");
                $("#EndYear").val((new Date()).getFullYear());
                $("#EndYear").prop("type", "number");
            }
            var hasLi = AutoComplete.GhostContainer.find(".free-text, .work-filter, .artist-filter, .composer-filter")
                .length;
            if (val.length < 1 && (prvVal === null || prvVal.length < 1)) {
                $lastLi.remove();
                var parentid = $lastLi.attr("data-parentid"),
                    isCategoryfilter = typeof (parentid) !== "undefined";
                if (isCategoryfilter) {
                    FilterEngine.ResetFilterGroup($lastLi.attr("data-id"), parentid);
                }
                $freetext.html("").hide();

                return val.length >= 1 || hasLi;
            } else if (val.length < 1) {
                $(".searchWordsListing").remove();
                return false;
            }
        }
    },
    AddChunks: function ($lastLi, val, type, surroundWithQuotes) {
        var splitted = val.split(" ");
        type = (typeof type === "undefined" && type !== null ? "categoryfilter" : type);
        var closeTxt = AutoComplete.SweMode ? " ta bort " : " remove ";
        var grouped = [];
        for (var i = 0; i < splitted.length; i++) {
            var currentVal = splitted[i];
            if (currentVal === "") {
                continue;
            }
            if (currentVal.charAt(0) === '"' || grouped.length > 0 || surroundWithQuotes) {
                grouped.push(currentVal);
                if (i == splitted.length - 1 || currentVal.charAt(currentVal.length - 1) === '"'
                ) { //last or is last in group

                    var groupedval = grouped.join(' ');
                    grouped = [];
                    var $lastAttached =
                        $("<li data-type=" +
                            type +
                            " class='js-autocomplete-filter free-text'><span>" +
                            AutoComplete.HandleQuotes(groupedval) +
                            "</span></li>").hide().insertBefore($lastLi).fadeIn(500);
                    $lastAttached.append($("<div class='button-wrapper'><button class='js-ac-remove'><span>" +
                        closeTxt +
                        currentVal +
                        "</span></button></div>"));
                    $lastAttached.children().last().get(0)
                        .addEventListener("click", AutoComplete.RemoveFilterTag, false);
                    continue;
                }
                continue;
            }
            var $attached =
                $("<li data-type=" +
                    type +
                    " class='js-autocomplete-filter free-text'><span>" +
                    currentVal.replace('"', '') +
                    "</span></li>").hide().insertBefore($lastLi).fadeIn(500);
            $attached.append($("<div class='button-wrapper'><button class='js-ac-remove'><span>" +
                closeTxt +
                currentVal +
                "</span></button></div>"));
            $attached.children().last().get(0).addEventListener("click", AutoComplete.RemoveFilterTag, false);
        }
    },
    HandleQuotes: function (value) {
        var hasendingchar = value.charAt(value.length - 1) === '"';
        var hasLeadingChar = value.charAt(0) === '"';
        if (hasendingchar) {
            value = value.substring(1, value.length - 1);
        }
        if (hasLeadingChar && !hasendingchar) {
            value = value.substr(1, value.length - 1);
        }
        return value;
    },
    Debounce: function (func, delay) {
        var timer = null;
        return function () {
            var context = this, args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                func.apply(context, args);
            },
                delay);
        };
    },
    FireYearTag: function (e) {
        var isStart = $(this).attr("name") === "StartYear";
        if ($(this).val() === "" || $(this).val().length < 4) {
            var $msgs = $(this).closest(".js-year-filtercontainer").find(".customValidationMessage");
            $msgs.each(function () {
                var $prev = $(this).prev();
                if ($prev.is("br")) {
                    $prev.remove();
                }
                $(this).remove();
            });
            $(this).val(isStart ? FilterEngine.StartYear : (new Date()).getFullYear());
        }

        var oldValue = localStorage.getItem($(this).attr("id"));
        localStorage.setItem($(this).attr("id"), $(this).val());
        var isedge = window.navigator.userAgent.indexOf("Edge") > -1;
        $(this).delay(200).queue(function (next) {
            if (AutoComplete["YearTagPending"] !== null) {
                console.error("abort");
                return false;
            }
            console.log(($(this).val() === oldValue) + " same value");
            var s = (localStorage.getItem("shouldSearch") == null ||
                JSON.parse(localStorage.getItem("shouldSearch")) == true) &&
                $(this).val() != oldValue;
            if ((e.which === 13 || e.which === 9 || e.which === 0) || isedge) { //edge
                var valid = AutoComplete.ConstructYearTag($(this));
                console.log("is valid " + valid);
                console.log("search now? " + (s));
                if (valid && s) {
                    console.log("searcijfop");
                    FilterEngine.Search();
                } else {
                    console.log("nidd");
                }
            } else {
                console.log("NOPE!");
            }
            next();
            return true;
        });
    },
    HanldeIllegalCharacters: function (e) {
        var isNumber = (e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105),
            isArrow = e.which > 36 && e.which < 41,
            isBackTab = e.shiftKey && e.which === 9,
            isPaste = typeof e.which === "undefined";
        if (e.which === 9 || e.which === 8 || e.which === 0 || e.which === 16 || e.which === 13 || isBackTab) {
            e.preventDefault();
        } else if (!isNumber && !isArrow && !isPaste) {
            return false;
        }
        var $input = $(this),
            val = $input.val().replace('+', '');

        var selectedValue = isTextSelected($input.get(0));
        if (isNumber) {
            if (val.length >= 4 && selectedValue.length === 0) {
                $input.val(val.substring(0, 3));
            }
            return true;
        }

        if (e.which === 8) {
            if (selectedValue.length > 0) {
                $input.val(val.replace(selectedValue, ""));
            } else {
                $input.val(val.substring(0, val.length - 1));
            }
        }

        if (e.which === 9 || isBackTab || e.which === 13 || e.which === 0) {
            return AutoComplete.ValidateYear($input, e.which, isBackTab);
        }
        if (e.which === 69 || e.which > 184 && e.which < 195) {
            return false;
        }
    },
    ValidateYear: function ($yearField, keycode, isBackTab) {
        var $formfield = $yearField.closest(".form-field"),
            isBlur = keycode === 0 || keycode === 9 || keycode === 13 || isBackTab,
            val = $yearField.val(),
            id = $yearField.attr("id"),
            isStartYear = $yearField.attr("id").toLowerCase().indexOf('start') === 0,
            $container = $formfield.closest(".js-year-filtercontainer"),
            $secondYearField = $container.find(".js-year-filter").not($yearField),
            $existingTag = AutoComplete.GhostContainer.find(".js-ac-year-tag-" + (isStartYear ? "from" : "to")),
            $existingSiblingTag = AutoComplete.GhostContainer.find(".js-ac-year-tag-" + (isStartYear ? "to" : "from")),
            $small = $formfield.prev().find("small:first");
        var isValid = val.length === 4;
        if ($secondYearField.val() !== "" && isValid) {
            isValid = isStartYear
                ? parseInt(val) <= parseInt($secondYearField.val())
                : parseInt(val) >= parseInt($secondYearField.val());
        }
        //get last 
        var shouldSearch = true;
        if (!isValid && !(isBlur && val.length === 0)) {
            $formfield.addClass("errorOnThis");
            if (!$formfield.find(".customValidationMessage").length) {
                $formfield.find("label").append("<br><span class='customValidationMessage'>" +
                    $yearField.attr("data-error") +
                    "</span>");
            }
            $secondYearField.closest(".form-field").addClass("errorOnThis");
            if (!$secondYearField.closest(".form-field").find(".customValidationMessage").length) {
                $secondYearField.closest(".form-field").find("label").append(
                    "<br><span class='customValidationMessage'>" + $yearField.attr("data-error") + "</span>");
            }
            $yearField.focus();
            return false;
        }
        $formfield.removeClass("errorOnThis");
        $formfield.find("br, .customValidationMessage").remove();
        $secondYearField.closest(".form-field").find("br, .customValidationMessage").remove();
        if (isBlur) {
            if (val.length < 4) {
                $yearField.val(isStartYear ? FilterEngine.StartYear : (new Date()).getFullYear());
            }
            var retrievedObject = localStorage.getItem(id);
            var semivalid = retrievedObject === null ||
                (retrievedObject != null &&
                    retrievedObject.length === 4 &&
                    retrievedObject !== val &&
                    retrievedObject !== "");
            console.log(retrievedObject === null + " object is null");
            shouldSearch = semivalid;
            localStorage.setItem("shouldSearch", shouldSearch);
            if (keycode === 13 || keycode === 9 && !isBackTab) {
                isStartYear ? $(".js-year-filter").not($yearField).focus() : $(".js-filter-toggle").focus();
            } else if (isBackTab) {
                !isStartYear ? $(".js-year-filter").not($yearField).focus() : $(".js-traditional-trigger").focus();
            }
            return true;
        }
        if (!$small.length) {
            $small = $("<small>" + (AutoComplete.SweMode ? "(åååå)" : "(yyyy)") + "</small>");
        }
        return true;
    },
    ConstructYearTag: function ($input) {
        var val = $input.val(),
            firstOfKind = $input.attr("id").toLowerCase().indexOf('start') === 0,
            $ghostContainer = $(".js-ac-ghost-container"),
            $existingTag = $ghostContainer.find(".js-ac-year-tag-" + (firstOfKind ? "from" : "to")),
            $existingSiblingTag = $ghostContainer.find(".js-ac-year-tag-" + (firstOfKind ? "to" : "from")),
            hasFilters = $ghostContainer.find(".js-autocomplete-filter").length,
            $inputFilterSibling = $input.closest(".js-year-filtercontainer").find(".js-year-filter").not($input),
            $siblingformField = $inputFilterSibling.closest(".form-field"),
            $formfield = $input.closest(".form-field"),
            $small = $input.prev().find("small:first"),
            isSwedish = $("html").attr("lang") === "sv",
            closeTxt = AutoComplete.SweMode ? " ta bort " : " remove ";
        var toText = isSwedish ? "Till år" : "To year";
        var $closeBtn = $("<div class='button-wrapper'><button data-type='year' class='js-ac-remove'><span>" +
            closeTxt +
            toText +
            " " +
            val +
            "</span></button></div>");

        var fromText = isSwedish ? "Från år" : "From year";
        var $lblTag = $("<label>" + (firstOfKind ? fromText : toText) + "</label>");
        var $yearTag = $("<span data-year=" +
            val +
            " data-type=" +
            (firstOfKind ? "start" : "end") +
            " class='js-ac-year-subtag'>" +
            val +
            "</span>");

        $small = $("<small>" + (isSwedish ? "(åååå)" : "(yyyy)") + "</small>");
        var validValue = true;

        if ($inputFilterSibling.val() !== "" && validValue) {
            validValue =
                firstOfKind
                    ? parseInt(val) <= parseInt($inputFilterSibling.val())
                    : parseInt(val) >= parseInt($inputFilterSibling.val());
        }
        if (validValue) {
            $formfield.removeClass("errorOnThis");
            $siblingformField.removeClass("errorOnThis");
            if (!$existingTag.length) {
                $existingTag =
                    $("<li class='js-autocomplete-filter js-ac-year-tag-" + (firstOfKind ? "from" : "to") + "'></li>")
                        .hide();
                if (hasFilters) {
                    $existingTag.insertAfter($ghostContainer.find(".js-autocomplete-filter:last")).fadeIn(100,
                        function () {
                            $(this).prepend($yearTag);
                            $(this).prepend($lblTag);
                            $(this).append($closeBtn);
                            $(this).children().not('.button-wrapper').not(".label-wrapper")
                                .wrapAll("<div class='label-wrapper'></div>");
                            $(this).children().last().children().get(0)
                                .addEventListener("click", FilterEngine.ToggleFilter, false);
                        });
                } else {
                    $ghostContainer.find("ul:first").prepend($existingTag);
                    $existingTag.fadeIn(100,
                        function () {
                            $(this).prepend($yearTag);
                            $(this).prepend($lblTag);
                            $(this).append($closeBtn);
                            $(this).children().not('.button-wrapper').not(".label-wrapper")
                                .wrapAll("<div class='label-wrapper'></div>");
                            $(this).children().last().children().get(0)
                                .addEventListener("click", FilterEngine.ToggleFilter, false);
                            $small.insertBefore($lblTag.find("br"));

                        });
                }
            } else {
                //$existingTag.find("label:first").replaceWith($lblTag);
                $existingTag.find("[data-year]").replaceWith($yearTag);
                $existingTag.children().not('.button-wrapper').not(".label-wrapper")
                    .wrapAll("<div class='label-wrapper'></div>");
                //$existingTag.html($lblTag + $yearTag);
            }
            if ($inputFilterSibling.length) {
                var $span = $existingSiblingTag.find("span:first");
                $span.attr("data-year", $inputFilterSibling.val());
                $span.html($inputFilterSibling.val());
            }
            return true;
        }
    },
    HandleFilterTag: function (e) {
        e.preventDefault();
        var $input = $(this),
            iscreate = $input.is(":radio") ? $input.is(":checked") : !$input.is(":checked"),
            $subfiltergroup = $input.closest(".js-sub-filter-group"),
            $container = $(".js-ac-ghost-container"),
            parentFilterId = $input.closest(".js-sub-filter-group").data("parentfilterid"),
            isSelectAll = $input.hasClass("js-select-all-hs"),
            $selectAll = isSelectAll ? $input : $subfiltergroup.find(".js-select-all-hs:first"),
            value = $input.prev().val(),
            performSearch = !$input.attr("data-hitType");
        var type = $input.closest(".js-sub-filter-group").find("h3").html();
        var $removables = $container.find("[data-parentId='" + parentFilterId + "']");

        if ($input.is(":checkbox")) {
            $input.attr("value", iscreate);
            $input.next().attr("value", iscreate);
            $selectAll.attr("value", iscreate && isSelectAll);
            $selectAll.next().attr("value", iscreate && isSelectAll);
        }

        if (isSelectAll && $input.is(":checkbox")) {
            var $siblings = $subfiltergroup.find("input[type='checkbox']").not($input);
            $siblings.each(function () {
                $(this).removeAttr("checked");
                $(this).attr("value", false);
                $(this).next().attr("value", false);
            });
        }
        if ($input.is(":radio") && !isSelectAll) {
            $subfiltergroup.find("input[type='radio']").not($input).each(function () {
                $(this).prop("checked", false);
            });
        }
        if ($input.is(":radio") || (isSelectAll && $input.is(":checked"))) {
            $removables.remove();
        }
        if (!isSelectAll) {
            $selectAll.attr("checked", false);
        }
        if (!(isSelectAll && $input.is(":checked"))) {
            if (iscreate) {
                var $closeBtn =
                    $("<div class='button-wrapper'><button class='js-ac-remove'><span>Close</span></button></div>");
                var hitType = $input.data("hittype");
                var hasHitType = typeof (hitType) !== "undefined";
                var hasLi = $container.find(".js-autocomplete-filter").length;

                var $attached = $("<li data-type='categoryfilter' data-parentId=" +
                    parentFilterId +
                    (hasHitType ? " data-hittype=" + hitType : "") +
                    " data-historical-filter-type=" +
                    $input.data("historical-filter-type") +
                    "  data-id=" +
                    value +
                    " class='js-autocomplete-filter " +
                    "category-filter'><div class='label-wrapper'><label>" +
                    type +
                    "</label><span>" +
                    $input.data("text") +
                    "</span></div></li>");
                $attached.hide();
                $attached.append($closeBtn);

                if (hasLi) {
                    $attached.insertAfter($container.find(".js-autocomplete-filter:last")).fadeIn(500);
                } else {
                    $container.find("ul:first").prepend($attached);
                    $attached.fadeIn(500);
                }
                $attached.children().last().get(0).addEventListener("click", AutoComplete.RemoveFilterTag, false);
            } else {
                var $match = $container.find("[data-id=" + value + "]");
                $match.fadeOut(400).remove();
            }
        }

        //if (performSearch) {
        FilterEngine.Search();
        //}
    },
    CreateTagFromStoreFilter: function ($tag) {
        var $input = $tag,
            isRadio = $input.is(":radio"),
            $container = $(".js-ac-ghost-container"),
            parentFilterId = $input.closest(".js-sub-filter-group").data("parentfilterid"),
            value = $input.prev().val();
        var type = $input.closest(".js-sub-filter-group").find("h3").html();

        if (isRadio) {
            var $removables = $container.find("[data-parentId='" + parentFilterId + "']");
            $removables.remove();
        }


        var $closeBtn = $("<button class='js-ac-remove'><span>Close</span></button>");
        var $attached =
            $("<li data-type='categoryfilter' data-parentId=" +
                parentFilterId +
                " data-isradio=" +
                isRadio +
                " data-historical-filter-type=" +
                $input.data("historical-filter-type") +
                "  data-id=" +
                value +
                " class='js-autocomplete-filter " +
                "category-filter'><label>" +
                type +
                "</label><span>" +
                $input.data("text") +
                "</span></li>").hide().insertBefore($container.find("li:last")).fadeIn(500);
        $attached.append($closeBtn);
        $attached.children().last().get(0).addEventListener("click", AutoComplete.RemoveFilterTag, false);
    },
    RemoveFilterTag: function (e) {
        e.preventDefault();
        AutoComplete.RemoveFilterTagFromParameter($(this), true);
    },
    RemoveFilterTagFromParameter: function ($elem, removeparent) {
        var $li = $elem.closest("li"),
            parentid = $li.attr("data-parentid"),
            isCategoryfilter = typeof (parentid) !== "undefined",
            performSearch = !$li.attr("data-hittype");
        if (isCategoryfilter) {
            FilterEngine.ResetFilterGroup($li.attr("data-id"), parentid);
        }
        var $removeee = removeparent ? $elem.parent() : $elem.closest("li");
        $removeee.fadeOut(400).remove();
        if (removeparent) {
            $elem.delay(700).queue(function (next) {
                FilterEngine.Search();
                next();
            });
        }
    }
};

function isTextSelected(input) {
    var selected = document.getSelection().toString() === input.value;
    return document.getSelection().toString();
};
var FilterEngine = FilterEngine || {};
var AutoComplete = AutoComplete || {};
var funkanu = funkanu || {};

$(function () {
    if ($(".js-autocomplete").length) {
        localStorage.clear();
        setupEvents();
        FilterEngine.StoreCookieLocation();
        setupHistoricalToggles();
        visualizeStoredFilters();
    }

    if (getUrlVars()["q"] != null) {
        $("#jsautocomplete").val(decodeURI(getUrlVars()["q"]));
        $(".js-traditional-trigger").click();
    };


    if ($(".js-placeholder").length) {
        if ($(document).width() > 970) {
            $(".js-placeholder").attr("placeholder", $(".js-placeholder").data("placeholdernormal"));
        } else {
            $(".js-placeholder").attr("placeholder", $(".js-placeholder").data("placeholdershort"));
        }
    }
});

var setupHistoricalToggles = function () {
    var ariaToggle = new funkanu.ariatoggle({
        container: ".js-historical-search",
        triggerSelector: ".js-help-toggle",
        target: function ($elem) {
            return $('.js-search-help-text');
        },
        toggleAction: function ($target) {
            $target.slideToggle();
        },
        clickEvent: function ($currentTarget) {
            $(this).delay(100).queue(function (next) {
                var isExpanded = $currentTarget.text() === $currentTarget.data("ts-hide");
                $currentTarget.html($currentTarget.data("ts-" + (isExpanded ? "show" : "hide")));
                next();
            });
        }
    });

    var ariatoggle = new funkanu.ariatoggle({
        container: ".js-historical-search",
        triggerSelector: ".js-filter-toggle",
        target: function ($elem) {
            return $('.js-search-filters');
        },
        toggleAction: function ($target) {
            $target.slideToggle();
        }
    });

    $(".js-search-help-text").hide();
    $(".js-searchfilters").hide();
}

var setupEvents = function () {
    $(".js-autocomplete").on('keydown', AutoComplete.Debounce(AutoComplete.Request, 50)).on("focusout",
        function (e) {
            $(window).keyup(function (e) {
            });
            $(this).delay(500).queue(function (next) {
                var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
                var isAndroid = /(android)/i.test(navigator.userAgent);

                var $self = $(this);
                if ((iOS || isAndroid) && !$(".js-autocomplete-hit").is(":focus") && $self.val().length > 0) {
                    var $lastLi = AutoComplete.GhostContainer
                        .find(".free-text, .work-filter, .artist-filter, .composer-filter").filter(function () {
                            return $(this).is(":visible");
                        }).last();
                    $lastLi = $lastLi.length ? $lastLi : AutoComplete.GhostContainer.find("li:last");
                    AutoComplete.AddChunks($lastLi, $self.val());
                    FilterEngine.Search();
                }
                next();
                return false;
            });
        });

    $(".js-autocomplete").on("focus",
        function () {
            var $self = $(this);
            var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
            var isAndroid = /(android)/i.test(navigator.userAgent);
            var $target = !iOS && !isAndroid ? $self.closest(".historical-search-area") : $self.closest(".historical-search-area").find(".historical-search-large-label");

            //Remove scroll to text field when focus! 
            //    $('html, body').animate({
            //            scrollTop: $target.offset().top
            //        },
            //        500,
            //        function() {
            //        });
        });
    $("body").on("click", ".js-hs-clearance > button", FilterEngine.ClearAll);
    $("body").on("click", ".js-autocomplete-hit", FilterEngine.ToggleFilter);
    $("body").on("keydown",
        ".js-autocomplete-hit",
        function (e) {
            e.preventDefault();
            var $self = $(this);
            var isBackTab = e.which === 9 && e.shiftKey;
            if (e.which !== 13 && e.which !== 9 && e.which !== 38 && e.which !== 40 && !isBackTab) {
                return false;
            }
            if (e.which === 13) {
                $(this).trigger("click");
            }
            //var $self = $(this),
            var $li = $self.closest("li"),
                $target = (e.which === 40 || e.which === 9) && !isBackTab
                    ? $li.nextAll("li:first").find(".js-autocomplete-hit")
                    : $li.prevAll("li:first").find(".js-autocomplete-hit"),
                $viceTarget = $target.length
                    ? $target
                    : (e.which === 40 || e.which === 9) && !isBackTab
                        ? $(".js-traditional-trigger")
                        : $(".js-autocomplete");

            $viceTarget.focus();
            $(this).delay(200).queue(function (next) {
                var hasFocus = $('.js-autocomplete').is(':focus');

                //if ($viceTarget.closest(".searchWordsListing").length && !$viceTarget.hasClass("white")) {
                //    $(".js-autocomplete-hit.free").addClass("white");
                //}
                //else if (!$viceTarget.hasClass("js-traditional-trigger") && hasFocus) {
                //    $(".js-autocomplete-hit.free").removeClass("white").addClass("tabbed");
                //}
                next();
            });
            return true;
        });

    $(".js-year-filter").each(function () {
        localStorage.setItem($(this).attr("id"), $(this).val());
    });

    $(".js-year-filter").off('keydown').on("keydown", AutoComplete.HanldeIllegalCharacters);
    $(".js-year-filter").on("paste", function (e) { e.preventDefault(); });
    $(".js-year-filter").on("blur click", AutoComplete.FireYearTag);


    $("body").on("click", ".js-hs-load-more", FilterEngine.LoadMore);

    $("body").on("change", ".js-ext", AutoComplete.HandleFilterTag);
    $(".js-traditional-trigger").on("click",
        function (e) {
            e.preventDefault();
            var $autoComplete = $(".js-autocomplete"),
                val = $autoComplete.val().trim();
            val !== "" ? $autoComplete.trigger($.Event("keydown", { which: 13 })) : $autoComplete.focus();
        }).on("keydown",
            function (e) {
                var $slist = $(".searchWordsListing");
                if (e.shiftKey && e.which === 9 && $slist.length && $slist.find("li:not(.no-hits)").length < 1) {
                    $(".js-autocomplete").focus();
                    return false;
                }
            });
    $(".js-ac-ghost-container").on("click",
        function (e) {
            e.preventDefault();
            $(this).find(".js-autocomplete").focus();
        });
    $("body").on("change",
        ".js-select-all-hs",
        function (e) {
            e.preventDefault();
            var $container = $(this).closest(".js-sub-filter-group");
            $container.find("input[type='checkbox'], input[type='radio']").not($(this)).each(function () {
                $(this).prop("checked", false);
            });
        });

    $("body").on("click",
        ".js-hs-datesort",
        function (e) {
            e.preventDefault();
            FilterEngine.Search(null, true);
        });

    $("body").on("click", ".js-share-this-huh", FilterEngine.StoreFilters);
    $("body").on("click", ".js-mocked-share-this", FilterEngine.StoreFilters);
    $("body").on("click", ".copy-link", FilterEngine.StoreFilters);
};

var visualizeStoredFilters = function () {
    var $filterContainer = $(".js-search-filters");
    if (!$filterContainer.length) {
        return false;
    }
    var $selected = $filterContainer.find("input[type='radio'], input[type='checkbox']").filter(function () {
        return $(this).is(":checked") && !$(this).hasClass("js-select-all-hs");
    });
    if ($selected.length) {
        $selected.each(function () {
            if (!($(this).is(":checkbox") && $(this).siblings("input[type='checkbox']").is(":checked"))) {
                AutoComplete.CreateTagFromStoreFilter($(this));
            }
        });
    }

    var $storedFreeText = $(".js-stored-freetexts");
    var $ghostContainer = $(".js-ac-ghost-container");

    if ($storedFreeText.length) {
        $storedFreeText.find("span").each(function () {
            var $self = $(this),
                closeTxt = $("html").attr("lang") == "en" ? " remove " : " ta bort ";
            var $closeBtn = $("<div class='button-wrapper'><button class='js-ac-remove'><span>" +
                closeTxt +
                "</span></button></div>");
            var $attached =
                $("<li data-type='categoryfilter' class='js-autocomplete-filter free-text'><span>" +
                    $self.text() +
                    "</span></li>").hide().insertBefore($ghostContainer.find("li:last")).fadeIn(500);
            $attached.append($closeBtn);
            $attached.children().last().get(0).addEventListener("click", AutoComplete.RemoveFilterTag, false);
        });
    }
    var $yearFilters = $filterContainer.find(".js-year-filter").filter(function () { return $(this).val() !== "" });
    $yearFilters.each(function () {
        AutoComplete.ConstructYearTag($(this));
    });

    if (!$(".js-hs-result-li").length) {
        $(".js-hs-load-more").hide();
        $(".js-hs-datesort").hide();
    }

    var $storedfilterDictionary = $(".js-stored-filterdictionary");
    $storedfilterDictionary.find("li").each(function () {
        $(this).insertBefore($ghostContainer.find("li:last"));
        $(this).find(".js-ac-remove").get(0).addEventListener("click", FilterEngine.ToggleFilter, false);
    });
};

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    return vars;
};
var dataLayer = dataLayer || [];

var GA = {
    Send: function (category, action) {
        ga('send', {
            hitType: 'event',
            eventCategory: category,
            eventAction: action,
        });
    }
}

$(function () {
    //Calendar
    $("[aria-controls='calendar-result-list']").on("click",
        function (e) {
            dataLayer.push({
                "event": "GAevent",
                "eventCategory": "Calendar Event",
                "eventAction": "loaddate",
                "eventLabel": "Load Date"
            });
        });

    $("#calendar-button-previous").on("click",
        function (e) {
            dataLayer.push({
                "event": "GAevent",
                "eventCategory": "Calendar Event",
                "eventAction": "previousmonth",
                "eventLabel": "Previous Month"
            });
        });

    $("#calendar-button-next").on("click",
        function (e) {
            dataLayer.push({
                "event": "GAevent",
                "eventCategory": "Calendar Event",
                "eventAction": "nextmonth",
                "eventLabel": "Next Month"
            });
        });

    $("body").on("click",
        ".js-calendar-load-more",
        function (e) {
            dataLayer.push({
                "event": "GAevent",
                "eventCategory": "Calendar Event",
                "eventAction": "loadmore",
                "eventLabel": "Load More"
            });
        });


    $(".js-select-month").on("change",
        function (e) {
            dataLayer.push({
                "event": "GAevent",
                "eventCategory": "Calendar Event",
                "eventAction": "change month",
                "eventLabel": "´Change Month"
            });

        });


    $(".js-filter-form").on("change",
        "input[type='checkbox']",
        function (e) {
            dataLayer.push({
                "event": "GAevent",
                "eventCategory": "Calendar Event",
                "eventAction": "calendarfilter",
                "eventLabel": "Calendar Filter"
            });
        });


});;
/*!
 * Flickity PACKAGED v2.2.2
 * Touch, responsive, flickable carousels
 *
 * Licensed GPLv3 for open source use
 * or Flickity Commercial License for commercial use
 *
 * https://flickity.metafizzy.co
 * Copyright 2015-2021 Metafizzy
 */

/**
 * Bridget makes jQuery widgets
 * v2.0.1
 * MIT license
 */

/* jshint browser: true, strict: true, undef: true, unused: true */

( function( window, factory ) {
  // universal module definition
  /*jshint strict: false */ /* globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'jquery-bridget/jquery-bridget',[ 'jquery' ], function( jQuery ) {
      return factory( window, jQuery );
    });
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      window,
      require('jquery')
    );
  } else {
    // browser global
    window.jQueryBridget = factory(
      window,
      window.jQuery
    );
  }

}( window, function factory( window, jQuery ) {
'use strict';

// ----- utils ----- //

var arraySlice = Array.prototype.slice;

// helper function for logging errors
// $.error breaks jQuery chaining
var console = window.console;
var logError = typeof console == 'undefined' ? function() {} :
  function( message ) {
    console.error( message );
  };

// ----- jQueryBridget ----- //

function jQueryBridget( namespace, PluginClass, $ ) {
  $ = $ || jQuery || window.jQuery;
  if ( !$ ) {
    return;
  }

  // add option method -> $().plugin('option', {...})
  if ( !PluginClass.prototype.option ) {
    // option setter
    PluginClass.prototype.option = function( opts ) {
      // bail out if not an object
      if ( !$.isPlainObject( opts ) ){
        return;
      }
      this.options = $.extend( true, this.options, opts );
    };
  }

  // make jQuery plugin
  $.fn[ namespace ] = function( arg0 /*, arg1 */ ) {
    if ( typeof arg0 == 'string' ) {
      // method call $().plugin( 'methodName', { options } )
      // shift arguments by 1
      var args = arraySlice.call( arguments, 1 );
      return methodCall( this, arg0, args );
    }
    // just $().plugin({ options })
    plainCall( this, arg0 );
    return this;
  };

  // $().plugin('methodName')
  function methodCall( $elems, methodName, args ) {
    var returnValue;
    var pluginMethodStr = '$().' + namespace + '("' + methodName + '")';

    $elems.each( function( i, elem ) {
      // get instance
      var instance = $.data( elem, namespace );
      if ( !instance ) {
        logError( namespace + ' not initialized. Cannot call methods, i.e. ' +
          pluginMethodStr );
        return;
      }

      var method = instance[ methodName ];
      if ( !method || methodName.charAt(0) == '_' ) {
        logError( pluginMethodStr + ' is not a valid method' );
        return;
      }

      // apply method, get return value
      var value = method.apply( instance, args );
      // set return value if value is returned, use only first value
      returnValue = returnValue === undefined ? value : returnValue;
    });

    return returnValue !== undefined ? returnValue : $elems;
  }

  function plainCall( $elems, options ) {
    $elems.each( function( i, elem ) {
      var instance = $.data( elem, namespace );
      if ( instance ) {
        // set options & init
        instance.option( options );
        instance._init();
      } else {
        // initialize new instance
        instance = new PluginClass( elem, options );
        $.data( elem, namespace, instance );
      }
    });
  }

  updateJQuery( $ );

}

// ----- updateJQuery ----- //

// set $.bridget for v1 backwards compatibility
function updateJQuery( $ ) {
  if ( !$ || ( $ && $.bridget ) ) {
    return;
  }
  $.bridget = jQueryBridget;
}

updateJQuery( jQuery || window.jQuery );

// -----  ----- //

return jQueryBridget;

}));

/**
 * EvEmitter v1.1.0
 * Lil' event emitter
 * MIT License
 */

/* jshint unused: true, undef: true, strict: true */

( function( global, factory ) {
  // universal module definition
  /* jshint strict: false */ /* globals define, module, window */
  if ( typeof define == 'function' && define.amd ) {
    // AMD - RequireJS
    define( 'ev-emitter/ev-emitter',factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS - Browserify, Webpack
    module.exports = factory();
  } else {
    // Browser globals
    global.EvEmitter = factory();
  }

}( typeof window != 'undefined' ? window : this, function() {



function EvEmitter() {}

var proto = EvEmitter.prototype;

proto.on = function( eventName, listener ) {
  if ( !eventName || !listener ) {
    return;
  }
  // set events hash
  var events = this._events = this._events || {};
  // set listeners array
  var listeners = events[ eventName ] = events[ eventName ] || [];
  // only add once
  if ( listeners.indexOf( listener ) == -1 ) {
    listeners.push( listener );
  }

  return this;
};

proto.once = function( eventName, listener ) {
  if ( !eventName || !listener ) {
    return;
  }
  // add event
  this.on( eventName, listener );
  // set once flag
  // set onceEvents hash
  var onceEvents = this._onceEvents = this._onceEvents || {};
  // set onceListeners object
  var onceListeners = onceEvents[ eventName ] = onceEvents[ eventName ] || {};
  // set flag
  onceListeners[ listener ] = true;

  return this;
};

proto.off = function( eventName, listener ) {
  var listeners = this._events && this._events[ eventName ];
  if ( !listeners || !listeners.length ) {
    return;
  }
  var index = listeners.indexOf( listener );
  if ( index != -1 ) {
    listeners.splice( index, 1 );
  }

  return this;
};

proto.emitEvent = function( eventName, args ) {
  var listeners = this._events && this._events[ eventName ];
  if ( !listeners || !listeners.length ) {
    return;
  }
  // copy over to avoid interference if .off() in listener
  listeners = listeners.slice(0);
  args = args || [];
  // once stuff
  var onceListeners = this._onceEvents && this._onceEvents[ eventName ];

  for ( var i=0; i < listeners.length; i++ ) {
    var listener = listeners[i]
    var isOnce = onceListeners && onceListeners[ listener ];
    if ( isOnce ) {
      // remove listener
      // remove before trigger to prevent recursion
      this.off( eventName, listener );
      // unset once flag
      delete onceListeners[ listener ];
    }
    // trigger listener
    listener.apply( this, args );
  }

  return this;
};

proto.allOff = function() {
  delete this._events;
  delete this._onceEvents;
};

return EvEmitter;

}));

/*!
 * getSize v2.0.3
 * measure size of elements
 * MIT license
 */

/* jshint browser: true, strict: true, undef: true, unused: true */
/* globals console: false */

( function( window, factory ) {
  /* jshint strict: false */ /* globals define, module */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'get-size/get-size',factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory();
  } else {
    // browser global
    window.getSize = factory();
  }

})( window, function factory() {
'use strict';

// -------------------------- helpers -------------------------- //

// get a number from a string, not a percentage
function getStyleSize( value ) {
  var num = parseFloat( value );
  // not a percent like '100%', and a number
  var isValid = value.indexOf('%') == -1 && !isNaN( num );
  return isValid && num;
}

function noop() {}

var logError = typeof console == 'undefined' ? noop :
  function( message ) {
    console.error( message );
  };

// -------------------------- measurements -------------------------- //

var measurements = [
  'paddingLeft',
  'paddingRight',
  'paddingTop',
  'paddingBottom',
  'marginLeft',
  'marginRight',
  'marginTop',
  'marginBottom',
  'borderLeftWidth',
  'borderRightWidth',
  'borderTopWidth',
  'borderBottomWidth'
];

var measurementsLength = measurements.length;

function getZeroSize() {
  var size = {
    width: 0,
    height: 0,
    innerWidth: 0,
    innerHeight: 0,
    outerWidth: 0,
    outerHeight: 0
  };
  for ( var i=0; i < measurementsLength; i++ ) {
    var measurement = measurements[i];
    size[ measurement ] = 0;
  }
  return size;
}

// -------------------------- getStyle -------------------------- //

/**
 * getStyle, get style of element, check for Firefox bug
 * https://bugzilla.mozilla.org/show_bug.cgi?id=548397
 */
function getStyle( elem ) {
  var style = getComputedStyle( elem );
  if ( !style ) {
    logError( 'Style returned ' + style +
      '. Are you running this code in a hidden iframe on Firefox? ' +
      'See https://bit.ly/getsizebug1' );
  }
  return style;
}

// -------------------------- setup -------------------------- //

var isSetup = false;

var isBoxSizeOuter;

/**
 * setup
 * check isBoxSizerOuter
 * do on first getSize() rather than on page load for Firefox bug
 */
function setup() {
  // setup once
  if ( isSetup ) {
    return;
  }
  isSetup = true;

  // -------------------------- box sizing -------------------------- //

  /**
   * Chrome & Safari measure the outer-width on style.width on border-box elems
   * IE11 & Firefox<29 measures the inner-width
   */
  var div = document.createElement('div');
  div.style.width = '200px';
  div.style.padding = '1px 2px 3px 4px';
  div.style.borderStyle = 'solid';
  div.style.borderWidth = '1px 2px 3px 4px';
  div.style.boxSizing = 'border-box';

  var body = document.body || document.documentElement;
  body.appendChild( div );
  var style = getStyle( div );
  // round value for browser zoom. desandro/masonry#928
  isBoxSizeOuter = Math.round( getStyleSize( style.width ) ) == 200;
  getSize.isBoxSizeOuter = isBoxSizeOuter;

  body.removeChild( div );
}

// -------------------------- getSize -------------------------- //

function getSize( elem ) {
  setup();

  // use querySeletor if elem is string
  if ( typeof elem == 'string' ) {
    elem = document.querySelector( elem );
  }

  // do not proceed on non-objects
  if ( !elem || typeof elem != 'object' || !elem.nodeType ) {
    return;
  }

  var style = getStyle( elem );

  // if hidden, everything is 0
  if ( style.display == 'none' ) {
    return getZeroSize();
  }

  var size = {};
  size.width = elem.offsetWidth;
  size.height = elem.offsetHeight;

  var isBorderBox = size.isBorderBox = style.boxSizing == 'border-box';

  // get all measurements
  for ( var i=0; i < measurementsLength; i++ ) {
    var measurement = measurements[i];
    var value = style[ measurement ];
    var num = parseFloat( value );
    // any 'auto', 'medium' value will be 0
    size[ measurement ] = !isNaN( num ) ? num : 0;
  }

  var paddingWidth = size.paddingLeft + size.paddingRight;
  var paddingHeight = size.paddingTop + size.paddingBottom;
  var marginWidth = size.marginLeft + size.marginRight;
  var marginHeight = size.marginTop + size.marginBottom;
  var borderWidth = size.borderLeftWidth + size.borderRightWidth;
  var borderHeight = size.borderTopWidth + size.borderBottomWidth;

  var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter;

  // overwrite width and height if we can get it from style
  var styleWidth = getStyleSize( style.width );
  if ( styleWidth !== false ) {
    size.width = styleWidth +
      // add padding and border unless it's already including it
      ( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth );
  }

  var styleHeight = getStyleSize( style.height );
  if ( styleHeight !== false ) {
    size.height = styleHeight +
      // add padding and border unless it's already including it
      ( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight );
  }

  size.innerWidth = size.width - ( paddingWidth + borderWidth );
  size.innerHeight = size.height - ( paddingHeight + borderHeight );

  size.outerWidth = size.width + marginWidth;
  size.outerHeight = size.height + marginHeight;

  return size;
}

return getSize;

});

/**
 * matchesSelector v2.0.2
 * matchesSelector( element, '.selector' )
 * MIT license
 */

/*jshint browser: true, strict: true, undef: true, unused: true */

( function( window, factory ) {
  /*global define: false, module: false */
  'use strict';
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'desandro-matches-selector/matches-selector',factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory();
  } else {
    // browser global
    window.matchesSelector = factory();
  }

}( window, function factory() {
  'use strict';

  var matchesMethod = ( function() {
    var ElemProto = window.Element.prototype;
    // check for the standard method name first
    if ( ElemProto.matches ) {
      return 'matches';
    }
    // check un-prefixed
    if ( ElemProto.matchesSelector ) {
      return 'matchesSelector';
    }
    // check vendor prefixes
    var prefixes = [ 'webkit', 'moz', 'ms', 'o' ];

    for ( var i=0; i < prefixes.length; i++ ) {
      var prefix = prefixes[i];
      var method = prefix + 'MatchesSelector';
      if ( ElemProto[ method ] ) {
        return method;
      }
    }
  })();

  return function matchesSelector( elem, selector ) {
    return elem[ matchesMethod ]( selector );
  };

}));

/**
 * Fizzy UI utils v2.0.7
 * MIT license
 */

/*jshint browser: true, undef: true, unused: true, strict: true */

( function( window, factory ) {
  // universal module definition
  /*jshint strict: false */ /*globals define, module, require */

  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'fizzy-ui-utils/utils',[
      'desandro-matches-selector/matches-selector'
    ], function( matchesSelector ) {
      return factory( window, matchesSelector );
    });
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      window,
      require('desandro-matches-selector')
    );
  } else {
    // browser global
    window.fizzyUIUtils = factory(
      window,
      window.matchesSelector
    );
  }

}( window, function factory( window, matchesSelector ) {



var utils = {};

// ----- extend ----- //

// extends objects
utils.extend = function( a, b ) {
  for ( var prop in b ) {
    a[ prop ] = b[ prop ];
  }
  return a;
};

// ----- modulo ----- //

utils.modulo = function( num, div ) {
  return ( ( num % div ) + div ) % div;
};

// ----- makeArray ----- //

var arraySlice = Array.prototype.slice;

// turn element or nodeList into an array
utils.makeArray = function( obj ) {
  if ( Array.isArray( obj ) ) {
    // use object if already an array
    return obj;
  }
  // return empty array if undefined or null. #6
  if ( obj === null || obj === undefined ) {
    return [];
  }

  var isArrayLike = typeof obj == 'object' && typeof obj.length == 'number';
  if ( isArrayLike ) {
    // convert nodeList to array
    return arraySlice.call( obj );
  }

  // array of single index
  return [ obj ];
};

// ----- removeFrom ----- //

utils.removeFrom = function( ary, obj ) {
  var index = ary.indexOf( obj );
  if ( index != -1 ) {
    ary.splice( index, 1 );
  }
};

// ----- getParent ----- //

utils.getParent = function( elem, selector ) {
  while ( elem.parentNode && elem != document.body ) {
    elem = elem.parentNode;
    if ( matchesSelector( elem, selector ) ) {
      return elem;
    }
  }
};

// ----- getQueryElement ----- //

// use element as selector string
utils.getQueryElement = function( elem ) {
  if ( typeof elem == 'string' ) {
    return document.querySelector( elem );
  }
  return elem;
};

// ----- handleEvent ----- //

// enable .ontype to trigger from .addEventListener( elem, 'type' )
utils.handleEvent = function( event ) {
  var method = 'on' + event.type;
  if ( this[ method ] ) {
    this[ method ]( event );
  }
};

// ----- filterFindElements ----- //

utils.filterFindElements = function( elems, selector ) {
  // make array of elems
  elems = utils.makeArray( elems );
  var ffElems = [];

  elems.forEach( function( elem ) {
    // check that elem is an actual element
    if ( !( elem instanceof HTMLElement ) ) {
      return;
    }
    // add elem if no selector
    if ( !selector ) {
      ffElems.push( elem );
      return;
    }
    // filter & find items if we have a selector
    // filter
    if ( matchesSelector( elem, selector ) ) {
      ffElems.push( elem );
    }
    // find children
    var childElems = elem.querySelectorAll( selector );
    // concat childElems to filterFound array
    for ( var i=0; i < childElems.length; i++ ) {
      ffElems.push( childElems[i] );
    }
  });

  return ffElems;
};

// ----- debounceMethod ----- //

utils.debounceMethod = function( _class, methodName, threshold ) {
  threshold = threshold || 100;
  // original method
  var method = _class.prototype[ methodName ];
  var timeoutName = methodName + 'Timeout';

  _class.prototype[ methodName ] = function() {
    var timeout = this[ timeoutName ];
    clearTimeout( timeout );

    var args = arguments;
    var _this = this;
    this[ timeoutName ] = setTimeout( function() {
      method.apply( _this, args );
      delete _this[ timeoutName ];
    }, threshold );
  };
};

// ----- docReady ----- //

utils.docReady = function( callback ) {
  var readyState = document.readyState;
  if ( readyState == 'complete' || readyState == 'interactive' ) {
    // do async to allow for other scripts to run. metafizzy/flickity#441
    setTimeout( callback );
  } else {
    document.addEventListener( 'DOMContentLoaded', callback );
  }
};

// ----- htmlInit ----- //

// http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/
utils.toDashed = function( str ) {
  return str.replace( /(.)([A-Z])/g, function( match, $1, $2 ) {
    return $1 + '-' + $2;
  }).toLowerCase();
};

var console = window.console;
/**
 * allow user to initialize classes via [data-namespace] or .js-namespace class
 * htmlInit( Widget, 'widgetName' )
 * options are parsed from data-namespace-options
 */
utils.htmlInit = function( WidgetClass, namespace ) {
  utils.docReady( function() {
    var dashedNamespace = utils.toDashed( namespace );
    var dataAttr = 'data-' + dashedNamespace;
    var dataAttrElems = document.querySelectorAll( '[' + dataAttr + ']' );
    var jsDashElems = document.querySelectorAll( '.js-' + dashedNamespace );
    var elems = utils.makeArray( dataAttrElems )
      .concat( utils.makeArray( jsDashElems ) );
    var dataOptionsAttr = dataAttr + '-options';
    var jQuery = window.jQuery;

    elems.forEach( function( elem ) {
      var attr = elem.getAttribute( dataAttr ) ||
        elem.getAttribute( dataOptionsAttr );
      var options;
      try {
        options = attr && JSON.parse( attr );
      } catch ( error ) {
        // log error, do not initialize
        if ( console ) {
          console.error( 'Error parsing ' + dataAttr + ' on ' + elem.className +
          ': ' + error );
        }
        return;
      }
      // initialize
      var instance = new WidgetClass( elem, options );
      // make available via $().data('namespace')
      if ( jQuery ) {
        jQuery.data( elem, namespace, instance );
      }
    });

  });
};

// -----  ----- //

return utils;

}));

// Flickity.Cell
( function( window, factory ) {
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity/js/cell',[
      'get-size/get-size',
    ], function( getSize ) {
      return factory( window, getSize );
    } );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
        window,
        require('get-size')
    );
  } else {
    // browser global
    window.Flickity = window.Flickity || {};
    window.Flickity.Cell = factory(
        window,
        window.getSize
    );
  }

}( window, function factory( window, getSize ) {



function Cell( elem, parent ) {
  this.element = elem;
  this.parent = parent;

  this.create();
}

var proto = Cell.prototype;

proto.create = function() {
  this.element.style.position = 'absolute';
  this.element.setAttribute( 'aria-hidden', 'true' );
  this.x = 0;
  this.shift = 0;
};

proto.destroy = function() {
  // reset style
  this.unselect();
  this.element.style.position = '';
  var side = this.parent.originSide;
  this.element.style[ side ] = '';
  this.element.removeAttribute('aria-hidden');
};

proto.getSize = function() {
  this.size = getSize( this.element );
};

proto.setPosition = function( x ) {
  this.x = x;
  this.updateTarget();
  this.renderPosition( x );
};

// setDefaultTarget v1 method, backwards compatibility, remove in v3
proto.updateTarget = proto.setDefaultTarget = function() {
  var marginProperty = this.parent.originSide == 'left' ? 'marginLeft' : 'marginRight';
  this.target = this.x + this.size[ marginProperty ] +
    this.size.width * this.parent.cellAlign;
};

proto.renderPosition = function( x ) {
  // render position of cell with in slider
  var side = this.parent.originSide;
  this.element.style[ side ] = this.parent.getPositionValue( x );
};

proto.select = function() {
  this.element.classList.add('is-selected');
  this.element.removeAttribute('aria-hidden');
};

proto.unselect = function() {
  this.element.classList.remove('is-selected');
  this.element.setAttribute( 'aria-hidden', 'true' );
};

/**
 * @param {Integer} shift - 0, 1, or -1
 */
proto.wrapShift = function( shift ) {
  this.shift = shift;
  this.renderPosition( this.x + this.parent.slideableWidth * shift );
};

proto.remove = function() {
  this.element.parentNode.removeChild( this.element );
};

return Cell;

} ) );

// slide
( function( window, factory ) {
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity/js/slide',factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory();
  } else {
    // browser global
    window.Flickity = window.Flickity || {};
    window.Flickity.Slide = factory();
  }

}( window, function factory() {
'use strict';

function Slide( parent ) {
  this.parent = parent;
  this.isOriginLeft = parent.originSide == 'left';
  this.cells = [];
  this.outerWidth = 0;
  this.height = 0;
}

var proto = Slide.prototype;

proto.addCell = function( cell ) {
  this.cells.push( cell );
  this.outerWidth += cell.size.outerWidth;
  this.height = Math.max( cell.size.outerHeight, this.height );
  // first cell stuff
  if ( this.cells.length == 1 ) {
    this.x = cell.x; // x comes from first cell
    var beginMargin = this.isOriginLeft ? 'marginLeft' : 'marginRight';
    this.firstMargin = cell.size[ beginMargin ];
  }
};

proto.updateTarget = function() {
  var endMargin = this.isOriginLeft ? 'marginRight' : 'marginLeft';
  var lastCell = this.getLastCell();
  var lastMargin = lastCell ? lastCell.size[ endMargin ] : 0;
  var slideWidth = this.outerWidth - ( this.firstMargin + lastMargin );
  this.target = this.x + this.firstMargin + slideWidth * this.parent.cellAlign;
};

proto.getLastCell = function() {
  return this.cells[ this.cells.length - 1 ];
};

proto.select = function() {
  this.cells.forEach( function( cell ) {
    cell.select();
  } );
};

proto.unselect = function() {
  this.cells.forEach( function( cell ) {
    cell.unselect();
  } );
};

proto.getCellElements = function() {
  return this.cells.map( function( cell ) {
    return cell.element;
  } );
};

return Slide;

} ) );

// animate
( function( window, factory ) {
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity/js/animate',[
      'fizzy-ui-utils/utils',
    ], function( utils ) {
      return factory( window, utils );
    } );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
        window,
        require('fizzy-ui-utils')
    );
  } else {
    // browser global
    window.Flickity = window.Flickity || {};
    window.Flickity.animatePrototype = factory(
        window,
        window.fizzyUIUtils
    );
  }

}( window, function factory( window, utils ) {



// -------------------------- animate -------------------------- //

var proto = {};

proto.startAnimation = function() {
  if ( this.isAnimating ) {
    return;
  }

  this.isAnimating = true;
  this.restingFrames = 0;
  this.animate();
};

proto.animate = function() {
  this.applyDragForce();
  this.applySelectedAttraction();

  var previousX = this.x;

  this.integratePhysics();
  this.positionSlider();
  this.settle( previousX );
  // animate next frame
  if ( this.isAnimating ) {
    var _this = this;
    requestAnimationFrame( function animateFrame() {
      _this.animate();
    } );
  }
};

proto.positionSlider = function() {
  var x = this.x;
  // wrap position around
  if ( this.options.wrapAround && this.cells.length > 1 ) {
    x = utils.modulo( x, this.slideableWidth );
    x -= this.slideableWidth;
    this.shiftWrapCells( x );
  }

  this.setTranslateX( x, this.isAnimating );
  this.dispatchScrollEvent();
};

proto.setTranslateX = function( x, is3d ) {
  x += this.cursorPosition;
  // reverse if right-to-left and using transform
  x = this.options.rightToLeft ? -x : x;
  var translateX = this.getPositionValue( x );
  // use 3D transforms for hardware acceleration on iOS
  // but use 2D when settled, for better font-rendering
  this.slider.style.transform = is3d ?
    'translate3d(' + translateX + ',0,0)' : 'translateX(' + translateX + ')';
};

proto.dispatchScrollEvent = function() {
  var firstSlide = this.slides[0];
  if ( !firstSlide ) {
    return;
  }
  var positionX = -this.x - firstSlide.target;
  var progress = positionX / this.slidesWidth;
  this.dispatchEvent( 'scroll', null, [ progress, positionX ] );
};

proto.positionSliderAtSelected = function() {
  if ( !this.cells.length ) {
    return;
  }
  this.x = -this.selectedSlide.target;
  this.velocity = 0; // stop wobble
  this.positionSlider();
};

proto.getPositionValue = function( position ) {
  if ( this.options.percentPosition ) {
    // percent position, round to 2 digits, like 12.34%
    return ( Math.round( ( position / this.size.innerWidth ) * 10000 ) * 0.01 ) + '%';
  } else {
    // pixel positioning
    return Math.round( position ) + 'px';
  }
};

proto.settle = function( previousX ) {
  // keep track of frames where x hasn't moved
  var isResting = !this.isPointerDown &&
      Math.round( this.x * 100 ) == Math.round( previousX * 100 );
  if ( isResting ) {
    this.restingFrames++;
  }
  // stop animating if resting for 3 or more frames
  if ( this.restingFrames > 2 ) {
    this.isAnimating = false;
    delete this.isFreeScrolling;
    // render position with translateX when settled
    this.positionSlider();
    this.dispatchEvent( 'settle', null, [ this.selectedIndex ] );
  }
};

proto.shiftWrapCells = function( x ) {
  // shift before cells
  var beforeGap = this.cursorPosition + x;
  this._shiftCells( this.beforeShiftCells, beforeGap, -1 );
  // shift after cells
  var afterGap = this.size.innerWidth - ( x + this.slideableWidth + this.cursorPosition );
  this._shiftCells( this.afterShiftCells, afterGap, 1 );
};

proto._shiftCells = function( cells, gap, shift ) {
  for ( var i = 0; i < cells.length; i++ ) {
    var cell = cells[i];
    var cellShift = gap > 0 ? shift : 0;
    cell.wrapShift( cellShift );
    gap -= cell.size.outerWidth;
  }
};

proto._unshiftCells = function( cells ) {
  if ( !cells || !cells.length ) {
    return;
  }
  for ( var i = 0; i < cells.length; i++ ) {
    cells[i].wrapShift( 0 );
  }
};

// -------------------------- physics -------------------------- //

proto.integratePhysics = function() {
  this.x += this.velocity;
  this.velocity *= this.getFrictionFactor();
};

proto.applyForce = function( force ) {
  this.velocity += force;
};

proto.getFrictionFactor = function() {
  return 1 - this.options[ this.isFreeScrolling ? 'freeScrollFriction' : 'friction' ];
};

proto.getRestingPosition = function() {
  // my thanks to Steven Wittens, who simplified this math greatly
  return this.x + this.velocity / ( 1 - this.getFrictionFactor() );
};

proto.applyDragForce = function() {
  if ( !this.isDraggable || !this.isPointerDown ) {
    return;
  }
  // change the position to drag position by applying force
  var dragVelocity = this.dragX - this.x;
  var dragForce = dragVelocity - this.velocity;
  this.applyForce( dragForce );
};

proto.applySelectedAttraction = function() {
  // do not attract if pointer down or no slides
  var dragDown = this.isDraggable && this.isPointerDown;
  if ( dragDown || this.isFreeScrolling || !this.slides.length ) {
    return;
  }
  var distance = this.selectedSlide.target * -1 - this.x;
  var force = distance * this.options.selectedAttraction;
  this.applyForce( force );
};

return proto;

} ) );

// Flickity main
/* eslint-disable max-params */
( function( window, factory ) {
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity/js/flickity',[
      'ev-emitter/ev-emitter',
      'get-size/get-size',
      'fizzy-ui-utils/utils',
      './cell',
      './slide',
      './animate',
    ], function( EvEmitter, getSize, utils, Cell, Slide, animatePrototype ) {
      return factory( window, EvEmitter, getSize, utils, Cell, Slide, animatePrototype );
    } );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
        window,
        require('ev-emitter'),
        require('get-size'),
        require('fizzy-ui-utils'),
        require('./cell'),
        require('./slide'),
        require('./animate')
    );
  } else {
    // browser global
    var _Flickity = window.Flickity;

    window.Flickity = factory(
        window,
        window.EvEmitter,
        window.getSize,
        window.fizzyUIUtils,
        _Flickity.Cell,
        _Flickity.Slide,
        _Flickity.animatePrototype
    );
  }

}( window, function factory( window, EvEmitter, getSize,
    utils, Cell, Slide, animatePrototype ) {

/* eslint-enable max-params */


// vars
var jQuery = window.jQuery;
var getComputedStyle = window.getComputedStyle;
var console = window.console;

function moveElements( elems, toElem ) {
  elems = utils.makeArray( elems );
  while ( elems.length ) {
    toElem.appendChild( elems.shift() );
  }
}

// -------------------------- Flickity -------------------------- //

// globally unique identifiers
var GUID = 0;
// internal store of all Flickity intances
var instances = {};

function Flickity( element, options ) {
  var queryElement = utils.getQueryElement( element );
  if ( !queryElement ) {
    if ( console ) {
      console.error( 'Bad element for Flickity: ' + ( queryElement || element ) );
    }
    return;
  }
  this.element = queryElement;
  // do not initialize twice on same element
  if ( this.element.flickityGUID ) {
    var instance = instances[ this.element.flickityGUID ];
    if ( instance ) instance.option( options );
    return instance;
  }

  // add jQuery
  if ( jQuery ) {
    this.$element = jQuery( this.element );
  }
  // options
  this.options = utils.extend( {}, this.constructor.defaults );
  this.option( options );

  // kick things off
  this._create();
}

Flickity.defaults = {
  accessibility: true,
  // adaptiveHeight: false,
  cellAlign: 'center',
  // cellSelector: undefined,
  // contain: false,
  freeScrollFriction: 0.075, // friction when free-scrolling
  friction: 0.28, // friction when selecting
  namespaceJQueryEvents: true,
  // initialIndex: 0,
  percentPosition: true,
  resize: true,
  selectedAttraction: 0.025,
  setGallerySize: true,
  // watchCSS: false,
  // wrapAround: false
};

// hash of methods triggered on _create()
Flickity.createMethods = [];

var proto = Flickity.prototype;
// inherit EventEmitter
utils.extend( proto, EvEmitter.prototype );

proto._create = function() {
  // add id for Flickity.data
  var id = this.guid = ++GUID;
  this.element.flickityGUID = id; // expando
  instances[ id ] = this; // associate via id
  // initial properties
  this.selectedIndex = 0;
  // how many frames slider has been in same position
  this.restingFrames = 0;
  // initial physics properties
  this.x = 0;
  this.velocity = 0;
  this.originSide = this.options.rightToLeft ? 'right' : 'left';
  // create viewport & slider
  this.viewport = document.createElement('div');
  this.viewport.className = 'flickity-viewport';
  this._createSlider();

  if ( this.options.resize || this.options.watchCSS ) {
    window.addEventListener( 'resize', this );
  }

  // add listeners from on option
  for ( var eventName in this.options.on ) {
    var listener = this.options.on[ eventName ];
    this.on( eventName, listener );
  }

  Flickity.createMethods.forEach( function( method ) {
    this[ method ]();
  }, this );

  if ( this.options.watchCSS ) {
    this.watchCSS();
  } else {
    this.activate();
  }

};

/**
 * set options
 * @param {Object} opts - options to extend
 */
proto.option = function( opts ) {
  utils.extend( this.options, opts );
};

proto.activate = function() {
  if ( this.isActive ) {
    return;
  }
  this.isActive = true;
  this.element.classList.add('flickity-enabled');
  if ( this.options.rightToLeft ) {
    this.element.classList.add('flickity-rtl');
  }

  this.getSize();
  // move initial cell elements so they can be loaded as cells
  var cellElems = this._filterFindCellElements( this.element.children );
  moveElements( cellElems, this.slider );
  this.viewport.appendChild( this.slider );
  this.element.appendChild( this.viewport );
  // get cells from children
  this.reloadCells();

  if ( this.options.accessibility ) {
    // allow element to focusable
    this.element.tabIndex = 0;
    // listen for key presses
    this.element.addEventListener( 'keydown', this );
  }

  this.emitEvent('activate');
  this.selectInitialIndex();
  // flag for initial activation, for using initialIndex
  this.isInitActivated = true;
  // ready event. #493
  this.dispatchEvent('ready');
};

// slider positions the cells
proto._createSlider = function() {
  // slider element does all the positioning
  var slider = document.createElement('div');
  slider.className = 'flickity-slider';
  slider.style[ this.originSide ] = 0;
  this.slider = slider;
};

proto._filterFindCellElements = function( elems ) {
  return utils.filterFindElements( elems, this.options.cellSelector );
};

// goes through all children
proto.reloadCells = function() {
  // collection of item elements
  this.cells = this._makeCells( this.slider.children );
  this.positionCells();
  this._getWrapShiftCells();
  this.setGallerySize();
};

/**
 * turn elements into Flickity.Cells
 * @param {[Array, NodeList, HTMLElement]} elems - elements to make into cells
 * @returns {Array} items - collection of new Flickity Cells
 */
proto._makeCells = function( elems ) {
  var cellElems = this._filterFindCellElements( elems );

  // create new Flickity for collection
  var cells = cellElems.map( function( cellElem ) {
    return new Cell( cellElem, this );
  }, this );

  return cells;
};

proto.getLastCell = function() {
  return this.cells[ this.cells.length - 1 ];
};

proto.getLastSlide = function() {
  return this.slides[ this.slides.length - 1 ];
};

// positions all cells
proto.positionCells = function() {
  // size all cells
  this._sizeCells( this.cells );
  // position all cells
  this._positionCells( 0 );
};

/**
 * position certain cells
 * @param {Integer} index - which cell to start with
 */
proto._positionCells = function( index ) {
  index = index || 0;
  // also measure maxCellHeight
  // start 0 if positioning all cells
  this.maxCellHeight = index ? this.maxCellHeight || 0 : 0;
  var cellX = 0;
  // get cellX
  if ( index > 0 ) {
    var startCell = this.cells[ index - 1 ];
    cellX = startCell.x + startCell.size.outerWidth;
  }
  var len = this.cells.length;
  for ( var i = index; i < len; i++ ) {
    var cell = this.cells[i];
    cell.setPosition( cellX );
    cellX += cell.size.outerWidth;
    this.maxCellHeight = Math.max( cell.size.outerHeight, this.maxCellHeight );
  }
  // keep track of cellX for wrap-around
  this.slideableWidth = cellX;
  // slides
  this.updateSlides();
  // contain slides target
  this._containSlides();
  // update slidesWidth
  this.slidesWidth = len ? this.getLastSlide().target - this.slides[0].target : 0;
};

/**
 * cell.getSize() on multiple cells
 * @param {Array} cells - cells to size
 */
proto._sizeCells = function( cells ) {
  cells.forEach( function( cell ) {
    cell.getSize();
  } );
};

// --------------------------  -------------------------- //

proto.updateSlides = function() {
  this.slides = [];
  if ( !this.cells.length ) {
    return;
  }

  var slide = new Slide( this );
  this.slides.push( slide );
  var isOriginLeft = this.originSide == 'left';
  var nextMargin = isOriginLeft ? 'marginRight' : 'marginLeft';

  var canCellFit = this._getCanCellFit();

  this.cells.forEach( function( cell, i ) {
    // just add cell if first cell in slide
    if ( !slide.cells.length ) {
      slide.addCell( cell );
      return;
    }

    var slideWidth = ( slide.outerWidth - slide.firstMargin ) +
      ( cell.size.outerWidth - cell.size[ nextMargin ] );

    if ( canCellFit.call( this, i, slideWidth ) ) {
      slide.addCell( cell );
    } else {
      // doesn't fit, new slide
      slide.updateTarget();

      slide = new Slide( this );
      this.slides.push( slide );
      slide.addCell( cell );
    }
  }, this );
  // last slide
  slide.updateTarget();
  // update .selectedSlide
  this.updateSelectedSlide();
};

proto._getCanCellFit = function() {
  var groupCells = this.options.groupCells;
  if ( !groupCells ) {
    return function() {
      return false;
    };
  } else if ( typeof groupCells == 'number' ) {
    // group by number. 3 -> [0,1,2], [3,4,5], ...
    var number = parseInt( groupCells, 10 );
    return function( i ) {
      return ( i % number ) !== 0;
    };
  }
  // default, group by width of slide
  // parse '75%
  var percentMatch = typeof groupCells == 'string' &&
    groupCells.match( /^(\d+)%$/ );
  var percent = percentMatch ? parseInt( percentMatch[1], 10 ) / 100 : 1;
  return function( i, slideWidth ) {
    /* eslint-disable-next-line no-invalid-this */
    return slideWidth <= ( this.size.innerWidth + 1 ) * percent;
  };
};

// alias _init for jQuery plugin .flickity()
proto._init =
proto.reposition = function() {
  this.positionCells();
  this.positionSliderAtSelected();
};

proto.getSize = function() {
  this.size = getSize( this.element );
  this.setCellAlign();
  this.cursorPosition = this.size.innerWidth * this.cellAlign;
};

var cellAlignShorthands = {
  // cell align, then based on origin side
  center: {
    left: 0.5,
    right: 0.5,
  },
  left: {
    left: 0,
    right: 1,
  },
  right: {
    right: 0,
    left: 1,
  },
};

proto.setCellAlign = function() {
  var shorthand = cellAlignShorthands[ this.options.cellAlign ];
  this.cellAlign = shorthand ? shorthand[ this.originSide ] : this.options.cellAlign;
};

proto.setGallerySize = function() {
  if ( this.options.setGallerySize ) {
    var height = this.options.adaptiveHeight && this.selectedSlide ?
      this.selectedSlide.height : this.maxCellHeight;
    this.viewport.style.height = height + 'px';
  }
};

proto._getWrapShiftCells = function() {
  // only for wrap-around
  if ( !this.options.wrapAround ) {
    return;
  }
  // unshift previous cells
  this._unshiftCells( this.beforeShiftCells );
  this._unshiftCells( this.afterShiftCells );
  // get before cells
  // initial gap
  var gapX = this.cursorPosition;
  var cellIndex = this.cells.length - 1;
  this.beforeShiftCells = this._getGapCells( gapX, cellIndex, -1 );
  // get after cells
  // ending gap between last cell and end of gallery viewport
  gapX = this.size.innerWidth - this.cursorPosition;
  // start cloning at first cell, working forwards
  this.afterShiftCells = this._getGapCells( gapX, 0, 1 );
};

proto._getGapCells = function( gapX, cellIndex, increment ) {
  // keep adding cells until the cover the initial gap
  var cells = [];
  while ( gapX > 0 ) {
    var cell = this.cells[ cellIndex ];
    if ( !cell ) {
      break;
    }
    cells.push( cell );
    cellIndex += increment;
    gapX -= cell.size.outerWidth;
  }
  return cells;
};

// ----- contain ----- //

// contain cell targets so no excess sliding
proto._containSlides = function() {
  if ( !this.options.contain || this.options.wrapAround || !this.cells.length ) {
    return;
  }
  var isRightToLeft = this.options.rightToLeft;
  var beginMargin = isRightToLeft ? 'marginRight' : 'marginLeft';
  var endMargin = isRightToLeft ? 'marginLeft' : 'marginRight';
  var contentWidth = this.slideableWidth - this.getLastCell().size[ endMargin ];
  // content is less than gallery size
  var isContentSmaller = contentWidth < this.size.innerWidth;
  // bounds
  var beginBound = this.cursorPosition + this.cells[0].size[ beginMargin ];
  var endBound = contentWidth - this.size.innerWidth * ( 1 - this.cellAlign );
  // contain each cell target
  this.slides.forEach( function( slide ) {
    if ( isContentSmaller ) {
      // all cells fit inside gallery
      slide.target = contentWidth * this.cellAlign;
    } else {
      // contain to bounds
      slide.target = Math.max( slide.target, beginBound );
      slide.target = Math.min( slide.target, endBound );
    }
  }, this );
};

// -----  ----- //

/**
 * emits events via eventEmitter and jQuery events
 * @param {String} type - name of event
 * @param {Event} event - original event
 * @param {Array} args - extra arguments
 */
proto.dispatchEvent = function( type, event, args ) {
  var emitArgs = event ? [ event ].concat( args ) : args;
  this.emitEvent( type, emitArgs );

  if ( jQuery && this.$element ) {
    // default trigger with type if no event
    type += this.options.namespaceJQueryEvents ? '.flickity' : '';
    var $event = type;
    if ( event ) {
      // create jQuery event
      var jQEvent = new jQuery.Event( event );
      jQEvent.type = type;
      $event = jQEvent;
    }
    this.$element.trigger( $event, args );
  }
};

// -------------------------- select -------------------------- //

/**
 * @param {Integer} index - index of the slide
 * @param {Boolean} isWrap - will wrap-around to last/first if at the end
 * @param {Boolean} isInstant - will immediately set position at selected cell
 */
proto.select = function( index, isWrap, isInstant ) {
  if ( !this.isActive ) {
    return;
  }
  index = parseInt( index, 10 );
  this._wrapSelect( index );

  if ( this.options.wrapAround || isWrap ) {
    index = utils.modulo( index, this.slides.length );
  }
  // bail if invalid index
  if ( !this.slides[ index ] ) {
    return;
  }
  var prevIndex = this.selectedIndex;
  this.selectedIndex = index;
  this.updateSelectedSlide();
  if ( isInstant ) {
    this.positionSliderAtSelected();
  } else {
    this.startAnimation();
  }
  if ( this.options.adaptiveHeight ) {
    this.setGallerySize();
  }
  // events
  this.dispatchEvent( 'select', null, [ index ] );
  // change event if new index
  if ( index != prevIndex ) {
    this.dispatchEvent( 'change', null, [ index ] );
  }
  // old v1 event name, remove in v3
  this.dispatchEvent('cellSelect');
};

// wraps position for wrapAround, to move to closest slide. #113
proto._wrapSelect = function( index ) {
  var len = this.slides.length;
  var isWrapping = this.options.wrapAround && len > 1;
  if ( !isWrapping ) {
    return index;
  }
  var wrapIndex = utils.modulo( index, len );
  // go to shortest
  var delta = Math.abs( wrapIndex - this.selectedIndex );
  var backWrapDelta = Math.abs( ( wrapIndex + len ) - this.selectedIndex );
  var forewardWrapDelta = Math.abs( ( wrapIndex - len ) - this.selectedIndex );
  if ( !this.isDragSelect && backWrapDelta < delta ) {
    index += len;
  } else if ( !this.isDragSelect && forewardWrapDelta < delta ) {
    index -= len;
  }
  // wrap position so slider is within normal area
  if ( index < 0 ) {
    this.x -= this.slideableWidth;
  } else if ( index >= len ) {
    this.x += this.slideableWidth;
  }
};

proto.previous = function( isWrap, isInstant ) {
  this.select( this.selectedIndex - 1, isWrap, isInstant );
};

proto.next = function( isWrap, isInstant ) {
  this.select( this.selectedIndex + 1, isWrap, isInstant );
};

proto.updateSelectedSlide = function() {
  var slide = this.slides[ this.selectedIndex ];
  // selectedIndex could be outside of slides, if triggered before resize()
  if ( !slide ) {
    return;
  }
  // unselect previous selected slide
  this.unselectSelectedSlide();
  // update new selected slide
  this.selectedSlide = slide;
  slide.select();
  this.selectedCells = slide.cells;
  this.selectedElements = slide.getCellElements();
  // HACK: selectedCell & selectedElement is first cell in slide, backwards compatibility
  // Remove in v3?
  this.selectedCell = slide.cells[0];
  this.selectedElement = this.selectedElements[0];
};

proto.unselectSelectedSlide = function() {
  if ( this.selectedSlide ) {
    this.selectedSlide.unselect();
  }
};

proto.selectInitialIndex = function() {
  var initialIndex = this.options.initialIndex;
  // already activated, select previous selectedIndex
  if ( this.isInitActivated ) {
    this.select( this.selectedIndex, false, true );
    return;
  }
  // select with selector string
  if ( initialIndex && typeof initialIndex == 'string' ) {
    var cell = this.queryCell( initialIndex );
    if ( cell ) {
      this.selectCell( initialIndex, false, true );
      return;
    }
  }

  var index = 0;
  // select with number
  if ( initialIndex && this.slides[ initialIndex ] ) {
    index = initialIndex;
  }
  // select instantly
  this.select( index, false, true );
};

/**
 * select slide from number or cell element
 * @param {[Element, Number]} value - zero-based index or element to select
 * @param {Boolean} isWrap - enables wrapping around for extra index
 * @param {Boolean} isInstant - disables slide animation
 */
proto.selectCell = function( value, isWrap, isInstant ) {
  // get cell
  var cell = this.queryCell( value );
  if ( !cell ) {
    return;
  }

  var index = this.getCellSlideIndex( cell );
  this.select( index, isWrap, isInstant );
};

proto.getCellSlideIndex = function( cell ) {
  // get index of slides that has cell
  for ( var i = 0; i < this.slides.length; i++ ) {
    var slide = this.slides[i];
    var index = slide.cells.indexOf( cell );
    if ( index != -1 ) {
      return i;
    }
  }
};

// -------------------------- get cells -------------------------- //

/**
 * get Flickity.Cell, given an Element
 * @param {Element} elem - matching cell element
 * @returns {Flickity.Cell} cell - matching cell
 */
proto.getCell = function( elem ) {
  // loop through cells to get the one that matches
  for ( var i = 0; i < this.cells.length; i++ ) {
    var cell = this.cells[i];
    if ( cell.element == elem ) {
      return cell;
    }
  }
};

/**
 * get collection of Flickity.Cells, given Elements
 * @param {[Element, Array, NodeList]} elems - multiple elements
 * @returns {Array} cells - Flickity.Cells
 */
proto.getCells = function( elems ) {
  elems = utils.makeArray( elems );
  var cells = [];
  elems.forEach( function( elem ) {
    var cell = this.getCell( elem );
    if ( cell ) {
      cells.push( cell );
    }
  }, this );
  return cells;
};

/**
 * get cell elements
 * @returns {Array} cellElems
 */
proto.getCellElements = function() {
  return this.cells.map( function( cell ) {
    return cell.element;
  } );
};

/**
 * get parent cell from an element
 * @param {Element} elem - child element
 * @returns {Flickit.Cell} cell - parent cell
 */
proto.getParentCell = function( elem ) {
  // first check if elem is cell
  var cell = this.getCell( elem );
  if ( cell ) {
    return cell;
  }
  // try to get parent cell elem
  elem = utils.getParent( elem, '.flickity-slider > *' );
  return this.getCell( elem );
};

/**
 * get cells adjacent to a slide
 * @param {Integer} adjCount - number of adjacent slides
 * @param {Integer} index - index of slide to start
 * @returns {Array} cells - array of Flickity.Cells
 */
proto.getAdjacentCellElements = function( adjCount, index ) {
  if ( !adjCount ) {
    return this.selectedSlide.getCellElements();
  }
  index = index === undefined ? this.selectedIndex : index;

  var len = this.slides.length;
  if ( 1 + ( adjCount * 2 ) >= len ) {
    return this.getCellElements();
  }

  var cellElems = [];
  for ( var i = index - adjCount; i <= index + adjCount; i++ ) {
    var slideIndex = this.options.wrapAround ? utils.modulo( i, len ) : i;
    var slide = this.slides[ slideIndex ];
    if ( slide ) {
      cellElems = cellElems.concat( slide.getCellElements() );
    }
  }
  return cellElems;
};

/**
 * select slide from number or cell element
 * @param {[Element, String, Number]} selector - element, selector string, or index
 * @returns {Flickity.Cell} - matching cell
 */
proto.queryCell = function( selector ) {
  if ( typeof selector == 'number' ) {
    // use number as index
    return this.cells[ selector ];
  }
  if ( typeof selector == 'string' ) {
    // do not select invalid selectors from hash: #123, #/. #791
    if ( selector.match( /^[#.]?[\d/]/ ) ) {
      return;
    }
    // use string as selector, get element
    selector = this.element.querySelector( selector );
  }
  // get cell from element
  return this.getCell( selector );
};

// -------------------------- events -------------------------- //

proto.uiChange = function() {
  this.emitEvent('uiChange');
};

// keep focus on element when child UI elements are clicked
proto.childUIPointerDown = function( event ) {
  // HACK iOS does not allow touch events to bubble up?!
  if ( event.type != 'touchstart' ) {
    event.preventDefault();
  }
  this.focus();
};

// ----- resize ----- //

proto.onresize = function() {
  this.watchCSS();
  this.resize();
};

utils.debounceMethod( Flickity, 'onresize', 150 );

proto.resize = function() {
  if ( !this.isActive ) {
    return;
  }
  this.getSize();
  // wrap values
  if ( this.options.wrapAround ) {
    this.x = utils.modulo( this.x, this.slideableWidth );
  }
  this.positionCells();
  this._getWrapShiftCells();
  this.setGallerySize();
  this.emitEvent('resize');
  // update selected index for group slides, instant
  // TODO: position can be lost between groups of various numbers
  var selectedElement = this.selectedElements && this.selectedElements[0];
  this.selectCell( selectedElement, false, true );
};

// watches the :after property, activates/deactivates
proto.watchCSS = function() {
  var watchOption = this.options.watchCSS;
  if ( !watchOption ) {
    return;
  }

  var afterContent = getComputedStyle( this.element, ':after' ).content;
  // activate if :after { content: 'flickity' }
  if ( afterContent.indexOf('flickity') != -1 ) {
    this.activate();
  } else {
    this.deactivate();
  }
};

// ----- keydown ----- //

// go previous/next if left/right keys pressed
proto.onkeydown = function( event ) {
  // only work if element is in focus
  var isNotFocused = document.activeElement && document.activeElement != this.element;
  if ( !this.options.accessibility || isNotFocused ) {
    return;
  }

  var handler = Flickity.keyboardHandlers[ event.keyCode ];
  if ( handler ) {
    handler.call( this );
  }
};

Flickity.keyboardHandlers = {
  // left arrow
  37: function() {
    var leftMethod = this.options.rightToLeft ? 'next' : 'previous';
    this.uiChange();
    this[ leftMethod ]();
  },
  // right arrow
  39: function() {
    var rightMethod = this.options.rightToLeft ? 'previous' : 'next';
    this.uiChange();
    this[ rightMethod ]();
  },
};

// ----- focus ----- //

proto.focus = function() {
  // TODO remove scrollTo once focus options gets more support
  // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus ...
  //    #Browser_compatibility
  var prevScrollY = window.pageYOffset;
  this.element.focus({ preventScroll: true });
  // hack to fix scroll jump after focus, #76
  if ( window.pageYOffset != prevScrollY ) {
    window.scrollTo( window.pageXOffset, prevScrollY );
  }
};

// -------------------------- destroy -------------------------- //

// deactivate all Flickity functionality, but keep stuff available
proto.deactivate = function() {
  if ( !this.isActive ) {
    return;
  }
  this.element.classList.remove('flickity-enabled');
  this.element.classList.remove('flickity-rtl');
  this.unselectSelectedSlide();
  // destroy cells
  this.cells.forEach( function( cell ) {
    cell.destroy();
  } );
  this.element.removeChild( this.viewport );
  // move child elements back into element
  moveElements( this.slider.children, this.element );
  if ( this.options.accessibility ) {
    this.element.removeAttribute('tabIndex');
    this.element.removeEventListener( 'keydown', this );
  }
  // set flags
  this.isActive = false;
  this.emitEvent('deactivate');
};

proto.destroy = function() {
  this.deactivate();
  window.removeEventListener( 'resize', this );
  this.allOff();
  this.emitEvent('destroy');
  if ( jQuery && this.$element ) {
    jQuery.removeData( this.element, 'flickity' );
  }
  delete this.element.flickityGUID;
  delete instances[ this.guid ];
};

// -------------------------- prototype -------------------------- //

utils.extend( proto, animatePrototype );

// -------------------------- extras -------------------------- //

/**
 * get Flickity instance from element
 * @param {[Element, String]} elem - element or selector string
 * @returns {Flickity} - Flickity instance
 */
Flickity.data = function( elem ) {
  elem = utils.getQueryElement( elem );
  var id = elem && elem.flickityGUID;
  return id && instances[ id ];
};

utils.htmlInit( Flickity, 'flickity' );

if ( jQuery && jQuery.bridget ) {
  jQuery.bridget( 'flickity', Flickity );
}

// set internal jQuery, for Webpack + jQuery v3, #478
Flickity.setJQuery = function( jq ) {
  jQuery = jq;
};

Flickity.Cell = Cell;
Flickity.Slide = Slide;

return Flickity;

} ) );

/*!
 * Unipointer v2.3.0
 * base class for doing one thing with pointer event
 * MIT license
 */

/*jshint browser: true, undef: true, unused: true, strict: true */

( function( window, factory ) {
  // universal module definition
  /* jshint strict: false */ /*global define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'unipointer/unipointer',[
      'ev-emitter/ev-emitter'
    ], function( EvEmitter ) {
      return factory( window, EvEmitter );
    });
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      window,
      require('ev-emitter')
    );
  } else {
    // browser global
    window.Unipointer = factory(
      window,
      window.EvEmitter
    );
  }

}( window, function factory( window, EvEmitter ) {



function noop() {}

function Unipointer() {}

// inherit EvEmitter
var proto = Unipointer.prototype = Object.create( EvEmitter.prototype );

proto.bindStartEvent = function( elem ) {
  this._bindStartEvent( elem, true );
};

proto.unbindStartEvent = function( elem ) {
  this._bindStartEvent( elem, false );
};

/**
 * Add or remove start event
 * @param {Boolean} isAdd - remove if falsey
 */
proto._bindStartEvent = function( elem, isAdd ) {
  // munge isAdd, default to true
  isAdd = isAdd === undefined ? true : isAdd;
  var bindMethod = isAdd ? 'addEventListener' : 'removeEventListener';

  // default to mouse events
  var startEvent = 'mousedown';
  if ( window.PointerEvent ) {
    // Pointer Events
    startEvent = 'pointerdown';
  } else if ( 'ontouchstart' in window ) {
    // Touch Events. iOS Safari
    startEvent = 'touchstart';
  }
  elem[ bindMethod ]( startEvent, this );
};

// trigger handler methods for events
proto.handleEvent = function( event ) {
  var method = 'on' + event.type;
  if ( this[ method ] ) {
    this[ method ]( event );
  }
};

// returns the touch that we're keeping track of
proto.getTouch = function( touches ) {
  for ( var i=0; i < touches.length; i++ ) {
    var touch = touches[i];
    if ( touch.identifier == this.pointerIdentifier ) {
      return touch;
    }
  }
};

// ----- start event ----- //

proto.onmousedown = function( event ) {
  // dismiss clicks from right or middle buttons
  var button = event.button;
  if ( button && ( button !== 0 && button !== 1 ) ) {
    return;
  }
  this._pointerDown( event, event );
};

proto.ontouchstart = function( event ) {
  this._pointerDown( event, event.changedTouches[0] );
};

proto.onpointerdown = function( event ) {
  this._pointerDown( event, event );
};

/**
 * pointer start
 * @param {Event} event
 * @param {Event or Touch} pointer
 */
proto._pointerDown = function( event, pointer ) {
  // dismiss right click and other pointers
  // button = 0 is okay, 1-4 not
  if ( event.button || this.isPointerDown ) {
    return;
  }

  this.isPointerDown = true;
  // save pointer identifier to match up touch events
  this.pointerIdentifier = pointer.pointerId !== undefined ?
    // pointerId for pointer events, touch.indentifier for touch events
    pointer.pointerId : pointer.identifier;

  this.pointerDown( event, pointer );
};

proto.pointerDown = function( event, pointer ) {
  this._bindPostStartEvents( event );
  this.emitEvent( 'pointerDown', [ event, pointer ] );
};

// hash of events to be bound after start event
var postStartEvents = {
  mousedown: [ 'mousemove', 'mouseup' ],
  touchstart: [ 'touchmove', 'touchend', 'touchcancel' ],
  pointerdown: [ 'pointermove', 'pointerup', 'pointercancel' ],
};

proto._bindPostStartEvents = function( event ) {
  if ( !event ) {
    return;
  }
  // get proper events to match start event
  var events = postStartEvents[ event.type ];
  // bind events to node
  events.forEach( function( eventName ) {
    window.addEventListener( eventName, this );
  }, this );
  // save these arguments
  this._boundPointerEvents = events;
};

proto._unbindPostStartEvents = function() {
  // check for _boundEvents, in case dragEnd triggered twice (old IE8 bug)
  if ( !this._boundPointerEvents ) {
    return;
  }
  this._boundPointerEvents.forEach( function( eventName ) {
    window.removeEventListener( eventName, this );
  }, this );

  delete this._boundPointerEvents;
};

// ----- move event ----- //

proto.onmousemove = function( event ) {
  this._pointerMove( event, event );
};

proto.onpointermove = function( event ) {
  if ( event.pointerId == this.pointerIdentifier ) {
    this._pointerMove( event, event );
  }
};

proto.ontouchmove = function( event ) {
  var touch = this.getTouch( event.changedTouches );
  if ( touch ) {
    this._pointerMove( event, touch );
  }
};

/**
 * pointer move
 * @param {Event} event
 * @param {Event or Touch} pointer
 * @private
 */
proto._pointerMove = function( event, pointer ) {
  this.pointerMove( event, pointer );
};

// public
proto.pointerMove = function( event, pointer ) {
  this.emitEvent( 'pointerMove', [ event, pointer ] );
};

// ----- end event ----- //


proto.onmouseup = function( event ) {
  this._pointerUp( event, event );
};

proto.onpointerup = function( event ) {
  if ( event.pointerId == this.pointerIdentifier ) {
    this._pointerUp( event, event );
  }
};

proto.ontouchend = function( event ) {
  var touch = this.getTouch( event.changedTouches );
  if ( touch ) {
    this._pointerUp( event, touch );
  }
};

/**
 * pointer up
 * @param {Event} event
 * @param {Event or Touch} pointer
 * @private
 */
proto._pointerUp = function( event, pointer ) {
  this._pointerDone();
  this.pointerUp( event, pointer );
};

// public
proto.pointerUp = function( event, pointer ) {
  this.emitEvent( 'pointerUp', [ event, pointer ] );
};

// ----- pointer done ----- //

// triggered on pointer up & pointer cancel
proto._pointerDone = function() {
  this._pointerReset();
  this._unbindPostStartEvents();
  this.pointerDone();
};

proto._pointerReset = function() {
  // reset properties
  this.isPointerDown = false;
  delete this.pointerIdentifier;
};

proto.pointerDone = noop;

// ----- pointer cancel ----- //

proto.onpointercancel = function( event ) {
  if ( event.pointerId == this.pointerIdentifier ) {
    this._pointerCancel( event, event );
  }
};

proto.ontouchcancel = function( event ) {
  var touch = this.getTouch( event.changedTouches );
  if ( touch ) {
    this._pointerCancel( event, touch );
  }
};

/**
 * pointer cancel
 * @param {Event} event
 * @param {Event or Touch} pointer
 * @private
 */
proto._pointerCancel = function( event, pointer ) {
  this._pointerDone();
  this.pointerCancel( event, pointer );
};

// public
proto.pointerCancel = function( event, pointer ) {
  this.emitEvent( 'pointerCancel', [ event, pointer ] );
};

// -----  ----- //

// utility function for getting x/y coords from event
Unipointer.getPointerPoint = function( pointer ) {
  return {
    x: pointer.pageX,
    y: pointer.pageY
  };
};

// -----  ----- //

return Unipointer;

}));

/*!
 * Unidragger v2.3.1
 * Draggable base class
 * MIT license
 */

/*jshint browser: true, unused: true, undef: true, strict: true */

( function( window, factory ) {
  // universal module definition
  /*jshint strict: false */ /*globals define, module, require */

  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'unidragger/unidragger',[
      'unipointer/unipointer'
    ], function( Unipointer ) {
      return factory( window, Unipointer );
    });
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      window,
      require('unipointer')
    );
  } else {
    // browser global
    window.Unidragger = factory(
      window,
      window.Unipointer
    );
  }

}( window, function factory( window, Unipointer ) {



// -------------------------- Unidragger -------------------------- //

function Unidragger() {}

// inherit Unipointer & EvEmitter
var proto = Unidragger.prototype = Object.create( Unipointer.prototype );

// ----- bind start ----- //

proto.bindHandles = function() {
  this._bindHandles( true );
};

proto.unbindHandles = function() {
  this._bindHandles( false );
};

/**
 * Add or remove start event
 * @param {Boolean} isAdd
 */
proto._bindHandles = function( isAdd ) {
  // munge isAdd, default to true
  isAdd = isAdd === undefined ? true : isAdd;
  // bind each handle
  var bindMethod = isAdd ? 'addEventListener' : 'removeEventListener';
  var touchAction = isAdd ? this._touchActionValue : '';
  for ( var i=0; i < this.handles.length; i++ ) {
    var handle = this.handles[i];
    this._bindStartEvent( handle, isAdd );
    handle[ bindMethod ]( 'click', this );
    // touch-action: none to override browser touch gestures. metafizzy/flickity#540
    if ( window.PointerEvent ) {
      handle.style.touchAction = touchAction;
    }
  }
};

// prototype so it can be overwriteable by Flickity
proto._touchActionValue = 'none';

// ----- start event ----- //

/**
 * pointer start
 * @param {Event} event
 * @param {Event or Touch} pointer
 */
proto.pointerDown = function( event, pointer ) {
  var isOkay = this.okayPointerDown( event );
  if ( !isOkay ) {
    return;
  }
  // track start event position
  // Safari 9 overrides pageX and pageY. These values needs to be copied. flickity#842
  this.pointerDownPointer = {
    pageX: pointer.pageX,
    pageY: pointer.pageY,
  };

  event.preventDefault();
  this.pointerDownBlur();
  // bind move and end events
  this._bindPostStartEvents( event );
  this.emitEvent( 'pointerDown', [ event, pointer ] );
};

// nodes that have text fields
var cursorNodes = {
  TEXTAREA: true,
  INPUT: true,
  SELECT: true,
  OPTION: true,
};

// input types that do not have text fields
var clickTypes = {
  radio: true,
  checkbox: true,
  button: true,
  submit: true,
  image: true,
  file: true,
};

// dismiss inputs with text fields. flickity#403, flickity#404
proto.okayPointerDown = function( event ) {
  var isCursorNode = cursorNodes[ event.target.nodeName ];
  var isClickType = clickTypes[ event.target.type ];
  var isOkay = !isCursorNode || isClickType;
  if ( !isOkay ) {
    this._pointerReset();
  }
  return isOkay;
};

// kludge to blur previously focused input
proto.pointerDownBlur = function() {
  var focused = document.activeElement;
  // do not blur body for IE10, metafizzy/flickity#117
  var canBlur = focused && focused.blur && focused != document.body;
  if ( canBlur ) {
    focused.blur();
  }
};

// ----- move event ----- //

/**
 * drag move
 * @param {Event} event
 * @param {Event or Touch} pointer
 */
proto.pointerMove = function( event, pointer ) {
  var moveVector = this._dragPointerMove( event, pointer );
  this.emitEvent( 'pointerMove', [ event, pointer, moveVector ] );
  this._dragMove( event, pointer, moveVector );
};

// base pointer move logic
proto._dragPointerMove = function( event, pointer ) {
  var moveVector = {
    x: pointer.pageX - this.pointerDownPointer.pageX,
    y: pointer.pageY - this.pointerDownPointer.pageY
  };
  // start drag if pointer has moved far enough to start drag
  if ( !this.isDragging && this.hasDragStarted( moveVector ) ) {
    this._dragStart( event, pointer );
  }
  return moveVector;
};

// condition if pointer has moved far enough to start drag
proto.hasDragStarted = function( moveVector ) {
  return Math.abs( moveVector.x ) > 3 || Math.abs( moveVector.y ) > 3;
};

// ----- end event ----- //

/**
 * pointer up
 * @param {Event} event
 * @param {Event or Touch} pointer
 */
proto.pointerUp = function( event, pointer ) {
  this.emitEvent( 'pointerUp', [ event, pointer ] );
  this._dragPointerUp( event, pointer );
};

proto._dragPointerUp = function( event, pointer ) {
  if ( this.isDragging ) {
    this._dragEnd( event, pointer );
  } else {
    // pointer didn't move enough for drag to start
    this._staticClick( event, pointer );
  }
};

// -------------------------- drag -------------------------- //

// dragStart
proto._dragStart = function( event, pointer ) {
  this.isDragging = true;
  // prevent clicks
  this.isPreventingClicks = true;
  this.dragStart( event, pointer );
};

proto.dragStart = function( event, pointer ) {
  this.emitEvent( 'dragStart', [ event, pointer ] );
};

// dragMove
proto._dragMove = function( event, pointer, moveVector ) {
  // do not drag if not dragging yet
  if ( !this.isDragging ) {
    return;
  }

  this.dragMove( event, pointer, moveVector );
};

proto.dragMove = function( event, pointer, moveVector ) {
  event.preventDefault();
  this.emitEvent( 'dragMove', [ event, pointer, moveVector ] );
};

// dragEnd
proto._dragEnd = function( event, pointer ) {
  // set flags
  this.isDragging = false;
  // re-enable clicking async
  setTimeout( function() {
    delete this.isPreventingClicks;
  }.bind( this ) );

  this.dragEnd( event, pointer );
};

proto.dragEnd = function( event, pointer ) {
  this.emitEvent( 'dragEnd', [ event, pointer ] );
};

// ----- onclick ----- //

// handle all clicks and prevent clicks when dragging
proto.onclick = function( event ) {
  if ( this.isPreventingClicks ) {
    event.preventDefault();
  }
};

// ----- staticClick ----- //

// triggered after pointer down & up with no/tiny movement
proto._staticClick = function( event, pointer ) {
  // ignore emulated mouse up clicks
  if ( this.isIgnoringMouseUp && event.type == 'mouseup' ) {
    return;
  }

  this.staticClick( event, pointer );

  // set flag for emulated clicks 300ms after touchend
  if ( event.type != 'mouseup' ) {
    this.isIgnoringMouseUp = true;
    // reset flag after 300ms
    setTimeout( function() {
      delete this.isIgnoringMouseUp;
    }.bind( this ), 400 );
  }
};

proto.staticClick = function( event, pointer ) {
  this.emitEvent( 'staticClick', [ event, pointer ] );
};

// ----- utils ----- //

Unidragger.getPointerPoint = Unipointer.getPointerPoint;

// -----  ----- //

return Unidragger;

}));

// drag
( function( window, factory ) {
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity/js/drag',[
      './flickity',
      'unidragger/unidragger',
      'fizzy-ui-utils/utils',
    ], function( Flickity, Unidragger, utils ) {
      return factory( window, Flickity, Unidragger, utils );
    } );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
        window,
        require('./flickity'),
        require('unidragger'),
        require('fizzy-ui-utils')
    );
  } else {
    // browser global
    window.Flickity = factory(
        window,
        window.Flickity,
        window.Unidragger,
        window.fizzyUIUtils
    );
  }

}( window, function factory( window, Flickity, Unidragger, utils ) {



// ----- defaults ----- //

utils.extend( Flickity.defaults, {
  draggable: '>1',
  dragThreshold: 3,
} );

// ----- create ----- //

Flickity.createMethods.push('_createDrag');

// -------------------------- drag prototype -------------------------- //

var proto = Flickity.prototype;
utils.extend( proto, Unidragger.prototype );
proto._touchActionValue = 'pan-y';

// --------------------------  -------------------------- //

var isTouch = 'createTouch' in document;
var isTouchmoveScrollCanceled = false;

proto._createDrag = function() {
  this.on( 'activate', this.onActivateDrag );
  this.on( 'uiChange', this._uiChangeDrag );
  this.on( 'deactivate', this.onDeactivateDrag );
  this.on( 'cellChange', this.updateDraggable );
  // TODO updateDraggable on resize? if groupCells & slides change
  // HACK - add seemingly innocuous handler to fix iOS 10 scroll behavior
  // #457, RubaXa/Sortable#973
  if ( isTouch && !isTouchmoveScrollCanceled ) {
    window.addEventListener( 'touchmove', function() {} );
    isTouchmoveScrollCanceled = true;
  }
};

proto.onActivateDrag = function() {
  this.handles = [ this.viewport ];
  this.bindHandles();
  this.updateDraggable();
};

proto.onDeactivateDrag = function() {
  this.unbindHandles();
  this.element.classList.remove('is-draggable');
};

proto.updateDraggable = function() {
  // disable dragging if less than 2 slides. #278
  if ( this.options.draggable == '>1' ) {
    this.isDraggable = this.slides.length > 1;
  } else {
    this.isDraggable = this.options.draggable;
  }
  if ( this.isDraggable ) {
    this.element.classList.add('is-draggable');
  } else {
    this.element.classList.remove('is-draggable');
  }
};

// backwards compatibility
proto.bindDrag = function() {
  this.options.draggable = true;
  this.updateDraggable();
};

proto.unbindDrag = function() {
  this.options.draggable = false;
  this.updateDraggable();
};

proto._uiChangeDrag = function() {
  delete this.isFreeScrolling;
};

// -------------------------- pointer events -------------------------- //

proto.pointerDown = function( event, pointer ) {
  if ( !this.isDraggable ) {
    this._pointerDownDefault( event, pointer );
    return;
  }
  var isOkay = this.okayPointerDown( event );
  if ( !isOkay ) {
    return;
  }

  this._pointerDownPreventDefault( event );
  this.pointerDownFocus( event );
  // blur
  if ( document.activeElement != this.element ) {
    // do not blur if already focused
    this.pointerDownBlur();
  }

  // stop if it was moving
  this.dragX = this.x;
  this.viewport.classList.add('is-pointer-down');
  // track scrolling
  this.pointerDownScroll = getScrollPosition();
  window.addEventListener( 'scroll', this );

  this._pointerDownDefault( event, pointer );
};

// default pointerDown logic, used for staticClick
proto._pointerDownDefault = function( event, pointer ) {
  // track start event position
  // Safari 9 overrides pageX and pageY. These values needs to be copied. #779
  this.pointerDownPointer = {
    pageX: pointer.pageX,
    pageY: pointer.pageY,
  };
  // bind move and end events
  this._bindPostStartEvents( event );
  this.dispatchEvent( 'pointerDown', event, [ pointer ] );
};

var focusNodes = {
  INPUT: true,
  TEXTAREA: true,
  SELECT: true,
};

proto.pointerDownFocus = function( event ) {
  var isFocusNode = focusNodes[ event.target.nodeName ];
  if ( !isFocusNode ) {
    this.focus();
  }
};

proto._pointerDownPreventDefault = function( event ) {
  var isTouchStart = event.type == 'touchstart';
  var isTouchPointer = event.pointerType == 'touch';
  var isFocusNode = focusNodes[ event.target.nodeName ];
  if ( !isTouchStart && !isTouchPointer && !isFocusNode ) {
    event.preventDefault();
  }
};

// ----- move ----- //

proto.hasDragStarted = function( moveVector ) {
  return Math.abs( moveVector.x ) > this.options.dragThreshold;
};

// ----- up ----- //

proto.pointerUp = function( event, pointer ) {
  delete this.isTouchScrolling;
  this.viewport.classList.remove('is-pointer-down');
  this.dispatchEvent( 'pointerUp', event, [ pointer ] );
  this._dragPointerUp( event, pointer );
};

proto.pointerDone = function() {
  window.removeEventListener( 'scroll', this );
  delete this.pointerDownScroll;
};

// -------------------------- dragging -------------------------- //

proto.dragStart = function( event, pointer ) {
  if ( !this.isDraggable ) {
    return;
  }
  this.dragStartPosition = this.x;
  this.startAnimation();
  window.removeEventListener( 'scroll', this );
  this.dispatchEvent( 'dragStart', event, [ pointer ] );
};

proto.pointerMove = function( event, pointer ) {
  var moveVector = this._dragPointerMove( event, pointer );
  this.dispatchEvent( 'pointerMove', event, [ pointer, moveVector ] );
  this._dragMove( event, pointer, moveVector );
};

proto.dragMove = function( event, pointer, moveVector ) {
  if ( !this.isDraggable ) {
    return;
  }
  event.preventDefault();

  this.previousDragX = this.dragX;
  // reverse if right-to-left
  var direction = this.options.rightToLeft ? -1 : 1;
  if ( this.options.wrapAround ) {
    // wrap around move. #589
    moveVector.x %= this.slideableWidth;
  }
  var dragX = this.dragStartPosition + moveVector.x * direction;

  if ( !this.options.wrapAround && this.slides.length ) {
    // slow drag
    var originBound = Math.max( -this.slides[0].target, this.dragStartPosition );
    dragX = dragX > originBound ? ( dragX + originBound ) * 0.5 : dragX;
    var endBound = Math.min( -this.getLastSlide().target, this.dragStartPosition );
    dragX = dragX < endBound ? ( dragX + endBound ) * 0.5 : dragX;
  }

  this.dragX = dragX;

  this.dragMoveTime = new Date();
  this.dispatchEvent( 'dragMove', event, [ pointer, moveVector ] );
};

proto.dragEnd = function( event, pointer ) {
  if ( !this.isDraggable ) {
    return;
  }
  if ( this.options.freeScroll ) {
    this.isFreeScrolling = true;
  }
  // set selectedIndex based on where flick will end up
  var index = this.dragEndRestingSelect();

  if ( this.options.freeScroll && !this.options.wrapAround ) {
    // if free-scroll & not wrap around
    // do not free-scroll if going outside of bounding slides
    // so bounding slides can attract slider, and keep it in bounds
    var restingX = this.getRestingPosition();
    this.isFreeScrolling = -restingX > this.slides[0].target &&
      -restingX < this.getLastSlide().target;
  } else if ( !this.options.freeScroll && index == this.selectedIndex ) {
    // boost selection if selected index has not changed
    index += this.dragEndBoostSelect();
  }
  delete this.previousDragX;
  // apply selection
  // TODO refactor this, selecting here feels weird
  // HACK, set flag so dragging stays in correct direction
  this.isDragSelect = this.options.wrapAround;
  this.select( index );
  delete this.isDragSelect;
  this.dispatchEvent( 'dragEnd', event, [ pointer ] );
};

proto.dragEndRestingSelect = function() {
  var restingX = this.getRestingPosition();
  // how far away from selected slide
  var distance = Math.abs( this.getSlideDistance( -restingX, this.selectedIndex ) );
  // get closet resting going up and going down
  var positiveResting = this._getClosestResting( restingX, distance, 1 );
  var negativeResting = this._getClosestResting( restingX, distance, -1 );
  // use closer resting for wrap-around
  var index = positiveResting.distance < negativeResting.distance ?
    positiveResting.index : negativeResting.index;
  return index;
};

/**
 * given resting X and distance to selected cell
 * get the distance and index of the closest cell
 * @param {Number} restingX - estimated post-flick resting position
 * @param {Number} distance - distance to selected cell
 * @param {Integer} increment - +1 or -1, going up or down
 * @returns {Object} - { distance: {Number}, index: {Integer} }
 */
proto._getClosestResting = function( restingX, distance, increment ) {
  var index = this.selectedIndex;
  var minDistance = Infinity;
  var condition = this.options.contain && !this.options.wrapAround ?
    // if contain, keep going if distance is equal to minDistance
    function( dist, minDist ) {
      return dist <= minDist;
    } : function( dist, minDist ) {
      return dist < minDist;
    };
  while ( condition( distance, minDistance ) ) {
    // measure distance to next cell
    index += increment;
    minDistance = distance;
    distance = this.getSlideDistance( -restingX, index );
    if ( distance === null ) {
      break;
    }
    distance = Math.abs( distance );
  }
  return {
    distance: minDistance,
    // selected was previous index
    index: index - increment,
  };
};

/**
 * measure distance between x and a slide target
 * @param {Number} x - horizontal position
 * @param {Integer} index - slide index
 * @returns {Number} - slide distance
 */
proto.getSlideDistance = function( x, index ) {
  var len = this.slides.length;
  // wrap around if at least 2 slides
  var isWrapAround = this.options.wrapAround && len > 1;
  var slideIndex = isWrapAround ? utils.modulo( index, len ) : index;
  var slide = this.slides[ slideIndex ];
  if ( !slide ) {
    return null;
  }
  // add distance for wrap-around slides
  var wrap = isWrapAround ? this.slideableWidth * Math.floor( index/len ) : 0;
  return x - ( slide.target + wrap );
};

proto.dragEndBoostSelect = function() {
  // do not boost if no previousDragX or dragMoveTime
  if ( this.previousDragX === undefined || !this.dragMoveTime ||
    // or if drag was held for 100 ms
    new Date() - this.dragMoveTime > 100 ) {
    return 0;
  }

  var distance = this.getSlideDistance( -this.dragX, this.selectedIndex );
  var delta = this.previousDragX - this.dragX;
  if ( distance > 0 && delta > 0 ) {
    // boost to next if moving towards the right, and positive velocity
    return 1;
  } else if ( distance < 0 && delta < 0 ) {
    // boost to previous if moving towards the left, and negative velocity
    return -1;
  }
  return 0;
};

// ----- staticClick ----- //

proto.staticClick = function( event, pointer ) {
  // get clickedCell, if cell was clicked
  var clickedCell = this.getParentCell( event.target );
  var cellElem = clickedCell && clickedCell.element;
  var cellIndex = clickedCell && this.cells.indexOf( clickedCell );
  this.dispatchEvent( 'staticClick', event, [ pointer, cellElem, cellIndex ] );
};

// ----- scroll ----- //

proto.onscroll = function() {
  var scroll = getScrollPosition();
  var scrollMoveX = this.pointerDownScroll.x - scroll.x;
  var scrollMoveY = this.pointerDownScroll.y - scroll.y;
  // cancel click/tap if scroll is too much
  if ( Math.abs( scrollMoveX ) > 3 || Math.abs( scrollMoveY ) > 3 ) {
    this._pointerDone();
  }
};

// ----- utils ----- //

function getScrollPosition() {
  return {
    x: window.pageXOffset,
    y: window.pageYOffset,
  };
}

// -----  ----- //

return Flickity;

} ) );

// prev/next buttons
( function( window, factory ) {
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity/js/prev-next-button',[
      './flickity',
      'unipointer/unipointer',
      'fizzy-ui-utils/utils',
    ], function( Flickity, Unipointer, utils ) {
      return factory( window, Flickity, Unipointer, utils );
    } );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
        window,
        require('./flickity'),
        require('unipointer'),
        require('fizzy-ui-utils')
    );
  } else {
    // browser global
    factory(
        window,
        window.Flickity,
        window.Unipointer,
        window.fizzyUIUtils
    );
  }

}( window, function factory( window, Flickity, Unipointer, utils ) {
'use strict';

var svgURI = 'http://www.w3.org/2000/svg';

// -------------------------- PrevNextButton -------------------------- //

function PrevNextButton( direction, parent ) {
  this.direction = direction;
  this.parent = parent;
  this._create();
}

PrevNextButton.prototype = Object.create( Unipointer.prototype );

PrevNextButton.prototype._create = function() {
  // properties
  this.isEnabled = true;
  this.isPrevious = this.direction == -1;
  var leftDirection = this.parent.options.rightToLeft ? 1 : -1;
  this.isLeft = this.direction == leftDirection;

  var element = this.element = document.createElement('button');
  element.className = 'flickity-button flickity-prev-next-button';
  element.className += this.isPrevious ? ' previous' : ' next';
  // prevent button from submitting form http://stackoverflow.com/a/10836076/182183
  element.setAttribute( 'type', 'button' );
  // init as disabled
  this.disable();

  element.setAttribute( 'aria-label', this.isPrevious ? 'Previous' : 'Next' );

  // create arrow
  var svg = this.createSVG();
  element.appendChild( svg );
  // events
  this.parent.on( 'select', this.update.bind( this ) );
  this.on( 'pointerDown', this.parent.childUIPointerDown.bind( this.parent ) );
};

PrevNextButton.prototype.activate = function() {
  this.bindStartEvent( this.element );
  this.element.addEventListener( 'click', this );
  // add to DOM
  this.parent.element.appendChild( this.element );
};

PrevNextButton.prototype.deactivate = function() {
  // remove from DOM
  this.parent.element.removeChild( this.element );
  // click events
  this.unbindStartEvent( this.element );
  this.element.removeEventListener( 'click', this );
};

PrevNextButton.prototype.createSVG = function() {
  var svg = document.createElementNS( svgURI, 'svg' );
  svg.setAttribute( 'class', 'flickity-button-icon' );
  svg.setAttribute( 'viewBox', '0 0 100 100' );
  var path = document.createElementNS( svgURI, 'path' );
  var pathMovements = getArrowMovements( this.parent.options.arrowShape );
  path.setAttribute( 'd', pathMovements );
  path.setAttribute( 'class', 'arrow' );
  // rotate arrow
  if ( !this.isLeft ) {
    path.setAttribute( 'transform', 'translate(100, 100) rotate(180) ' );
  }
  svg.appendChild( path );
  return svg;
};

// get SVG path movmement
function getArrowMovements( shape ) {
  // use shape as movement if string
  if ( typeof shape == 'string' ) {
    return shape;
  }
  // create movement string
  return 'M ' + shape.x0 + ',50' +
    ' L ' + shape.x1 + ',' + ( shape.y1 + 50 ) +
    ' L ' + shape.x2 + ',' + ( shape.y2 + 50 ) +
    ' L ' + shape.x3 + ',50 ' +
    ' L ' + shape.x2 + ',' + ( 50 - shape.y2 ) +
    ' L ' + shape.x1 + ',' + ( 50 - shape.y1 ) +
    ' Z';
}

PrevNextButton.prototype.handleEvent = utils.handleEvent;

PrevNextButton.prototype.onclick = function() {
  if ( !this.isEnabled ) {
    return;
  }
  this.parent.uiChange();
  var method = this.isPrevious ? 'previous' : 'next';
  this.parent[ method ]();
};

// -----  ----- //

PrevNextButton.prototype.enable = function() {
  if ( this.isEnabled ) {
    return;
  }
  this.element.disabled = false;
  this.isEnabled = true;
};

PrevNextButton.prototype.disable = function() {
  if ( !this.isEnabled ) {
    return;
  }
  this.element.disabled = true;
  this.isEnabled = false;
};

PrevNextButton.prototype.update = function() {
  // index of first or last slide, if previous or next
  var slides = this.parent.slides;
  // enable is wrapAround and at least 2 slides
  if ( this.parent.options.wrapAround && slides.length > 1 ) {
    this.enable();
    return;
  }
  var lastIndex = slides.length ? slides.length - 1 : 0;
  var boundIndex = this.isPrevious ? 0 : lastIndex;
  var method = this.parent.selectedIndex == boundIndex ? 'disable' : 'enable';
  this[ method ]();
};

PrevNextButton.prototype.destroy = function() {
  this.deactivate();
  this.allOff();
};

// -------------------------- Flickity prototype -------------------------- //

utils.extend( Flickity.defaults, {
  prevNextButtons: true,
  arrowShape: {
    x0: 10,
    x1: 60, y1: 50,
    x2: 70, y2: 40,
    x3: 30,
  },
} );

Flickity.createMethods.push('_createPrevNextButtons');
var proto = Flickity.prototype;

proto._createPrevNextButtons = function() {
  if ( !this.options.prevNextButtons ) {
    return;
  }

  this.prevButton = new PrevNextButton( -1, this );
  this.nextButton = new PrevNextButton( 1, this );

  this.on( 'activate', this.activatePrevNextButtons );
};

proto.activatePrevNextButtons = function() {
  this.prevButton.activate();
  this.nextButton.activate();
  this.on( 'deactivate', this.deactivatePrevNextButtons );
};

proto.deactivatePrevNextButtons = function() {
  this.prevButton.deactivate();
  this.nextButton.deactivate();
  this.off( 'deactivate', this.deactivatePrevNextButtons );
};

// --------------------------  -------------------------- //

Flickity.PrevNextButton = PrevNextButton;

return Flickity;

} ) );

// page dots
( function( window, factory ) {
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity/js/page-dots',[
      './flickity',
      'unipointer/unipointer',
      'fizzy-ui-utils/utils',
    ], function( Flickity, Unipointer, utils ) {
      return factory( window, Flickity, Unipointer, utils );
    } );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
        window,
        require('./flickity'),
        require('unipointer'),
        require('fizzy-ui-utils')
    );
  } else {
    // browser global
    factory(
        window,
        window.Flickity,
        window.Unipointer,
        window.fizzyUIUtils
    );
  }

}( window, function factory( window, Flickity, Unipointer, utils ) {

// -------------------------- PageDots -------------------------- //



function PageDots( parent ) {
  this.parent = parent;
  this._create();
}

PageDots.prototype = Object.create( Unipointer.prototype );

PageDots.prototype._create = function() {
  // create holder element
  this.holder = document.createElement('ol');
  this.holder.className = 'flickity-page-dots';
  // create dots, array of elements
  this.dots = [];
  // events
  this.handleClick = this.onClick.bind( this );
  this.on( 'pointerDown', this.parent.childUIPointerDown.bind( this.parent ) );
};

PageDots.prototype.activate = function() {
  this.setDots();
  this.holder.addEventListener( 'click', this.handleClick );
  this.bindStartEvent( this.holder );
  // add to DOM
  this.parent.element.appendChild( this.holder );
};

PageDots.prototype.deactivate = function() {
  this.holder.removeEventListener( 'click', this.handleClick );
  this.unbindStartEvent( this.holder );
  // remove from DOM
  this.parent.element.removeChild( this.holder );
};

PageDots.prototype.setDots = function() {
  // get difference between number of slides and number of dots
  var delta = this.parent.slides.length - this.dots.length;
  if ( delta > 0 ) {
    this.addDots( delta );
  } else if ( delta < 0 ) {
    this.removeDots( -delta );
  }
};

PageDots.prototype.addDots = function( count ) {
  var fragment = document.createDocumentFragment();
  var newDots = [];
  var length = this.dots.length;
  var max = length + count;

  for ( var i = length; i < max; i++ ) {
    var dot = document.createElement('li');
    dot.className = 'dot';
    dot.setAttribute( 'aria-label', 'Page dot ' + ( i + 1 ) );
    fragment.appendChild( dot );
    newDots.push( dot );
  }

  this.holder.appendChild( fragment );
  this.dots = this.dots.concat( newDots );
};

PageDots.prototype.removeDots = function( count ) {
  // remove from this.dots collection
  var removeDots = this.dots.splice( this.dots.length - count, count );
  // remove from DOM
  removeDots.forEach( function( dot ) {
    this.holder.removeChild( dot );
  }, this );
};

PageDots.prototype.updateSelected = function() {
  // remove selected class on previous
  if ( this.selectedDot ) {
    this.selectedDot.className = 'dot';
    this.selectedDot.removeAttribute('aria-current');
  }
  // don't proceed if no dots
  if ( !this.dots.length ) {
    return;
  }
  this.selectedDot = this.dots[ this.parent.selectedIndex ];
  this.selectedDot.className = 'dot is-selected';
  this.selectedDot.setAttribute( 'aria-current', 'step' );
};

PageDots.prototype.onTap = // old method name, backwards-compatible
PageDots.prototype.onClick = function( event ) {
  var target = event.target;
  // only care about dot clicks
  if ( target.nodeName != 'LI' ) {
    return;
  }

  this.parent.uiChange();
  var index = this.dots.indexOf( target );
  this.parent.select( index );
};

PageDots.prototype.destroy = function() {
  this.deactivate();
  this.allOff();
};

Flickity.PageDots = PageDots;

// -------------------------- Flickity -------------------------- //

utils.extend( Flickity.defaults, {
  pageDots: true,
} );

Flickity.createMethods.push('_createPageDots');

var proto = Flickity.prototype;

proto._createPageDots = function() {
  if ( !this.options.pageDots ) {
    return;
  }
  this.pageDots = new PageDots( this );
  // events
  this.on( 'activate', this.activatePageDots );
  this.on( 'select', this.updateSelectedPageDots );
  this.on( 'cellChange', this.updatePageDots );
  this.on( 'resize', this.updatePageDots );
  this.on( 'deactivate', this.deactivatePageDots );
};

proto.activatePageDots = function() {
  this.pageDots.activate();
};

proto.updateSelectedPageDots = function() {
  this.pageDots.updateSelected();
};

proto.updatePageDots = function() {
  this.pageDots.setDots();
};

proto.deactivatePageDots = function() {
  this.pageDots.deactivate();
};

// -----  ----- //

Flickity.PageDots = PageDots;

return Flickity;

} ) );

// player & autoPlay
( function( window, factory ) {
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity/js/player',[
      'ev-emitter/ev-emitter',
      'fizzy-ui-utils/utils',
      './flickity',
    ], function( EvEmitter, utils, Flickity ) {
      return factory( EvEmitter, utils, Flickity );
    } );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
        require('ev-emitter'),
        require('fizzy-ui-utils'),
        require('./flickity')
    );
  } else {
    // browser global
    factory(
        window.EvEmitter,
        window.fizzyUIUtils,
        window.Flickity
    );
  }

}( window, function factory( EvEmitter, utils, Flickity ) {



// -------------------------- Player -------------------------- //

function Player( parent ) {
  this.parent = parent;
  this.state = 'stopped';
  // visibility change event handler
  this.onVisibilityChange = this.visibilityChange.bind( this );
  this.onVisibilityPlay = this.visibilityPlay.bind( this );
}

Player.prototype = Object.create( EvEmitter.prototype );

// start play
Player.prototype.play = function() {
  if ( this.state == 'playing' ) {
    return;
  }
  // do not play if page is hidden, start playing when page is visible
  var isPageHidden = document.hidden;
  if ( isPageHidden ) {
    document.addEventListener( 'visibilitychange', this.onVisibilityPlay );
    return;
  }

  this.state = 'playing';
  // listen to visibility change
  document.addEventListener( 'visibilitychange', this.onVisibilityChange );
  // start ticking
  this.tick();
};

Player.prototype.tick = function() {
  // do not tick if not playing
  if ( this.state != 'playing' ) {
    return;
  }

  var time = this.parent.options.autoPlay;
  // default to 3 seconds
  time = typeof time == 'number' ? time : 3000;
  var _this = this;
  // HACK: reset ticks if stopped and started within interval
  this.clear();
  this.timeout = setTimeout( function() {
    _this.parent.next( true );
    _this.tick();
  }, time );
};

Player.prototype.stop = function() {
  this.state = 'stopped';
  this.clear();
  // remove visibility change event
  document.removeEventListener( 'visibilitychange', this.onVisibilityChange );
};

Player.prototype.clear = function() {
  clearTimeout( this.timeout );
};

Player.prototype.pause = function() {
  if ( this.state == 'playing' ) {
    this.state = 'paused';
    this.clear();
  }
};

Player.prototype.unpause = function() {
  // re-start play if paused
  if ( this.state == 'paused' ) {
    this.play();
  }
};

// pause if page visibility is hidden, unpause if visible
Player.prototype.visibilityChange = function() {
  var isPageHidden = document.hidden;
  this[ isPageHidden ? 'pause' : 'unpause' ]();
};

Player.prototype.visibilityPlay = function() {
  this.play();
  document.removeEventListener( 'visibilitychange', this.onVisibilityPlay );
};

// -------------------------- Flickity -------------------------- //

utils.extend( Flickity.defaults, {
  pauseAutoPlayOnHover: true,
} );

Flickity.createMethods.push('_createPlayer');
var proto = Flickity.prototype;

proto._createPlayer = function() {
  this.player = new Player( this );

  this.on( 'activate', this.activatePlayer );
  this.on( 'uiChange', this.stopPlayer );
  this.on( 'pointerDown', this.stopPlayer );
  this.on( 'deactivate', this.deactivatePlayer );
};

proto.activatePlayer = function() {
  if ( !this.options.autoPlay ) {
    return;
  }
  this.player.play();
  this.element.addEventListener( 'mouseenter', this );
};

// Player API, don't hate the ... thanks I know where the door is

proto.playPlayer = function() {
  this.player.play();
};

proto.stopPlayer = function() {
  this.player.stop();
};

proto.pausePlayer = function() {
  this.player.pause();
};

proto.unpausePlayer = function() {
  this.player.unpause();
};

proto.deactivatePlayer = function() {
  this.player.stop();
  this.element.removeEventListener( 'mouseenter', this );
};

// ----- mouseenter/leave ----- //

// pause auto-play on hover
proto.onmouseenter = function() {
  if ( !this.options.pauseAutoPlayOnHover ) {
    return;
  }
  this.player.pause();
  this.element.addEventListener( 'mouseleave', this );
};

// resume auto-play on hover off
proto.onmouseleave = function() {
  this.player.unpause();
  this.element.removeEventListener( 'mouseleave', this );
};

// -----  ----- //

Flickity.Player = Player;

return Flickity;

} ) );

// add, remove cell
( function( window, factory ) {
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity/js/add-remove-cell',[
      './flickity',
      'fizzy-ui-utils/utils',
    ], function( Flickity, utils ) {
      return factory( window, Flickity, utils );
    } );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
        window,
        require('./flickity'),
        require('fizzy-ui-utils')
    );
  } else {
    // browser global
    factory(
        window,
        window.Flickity,
        window.fizzyUIUtils
    );
  }

}( window, function factory( window, Flickity, utils ) {



// append cells to a document fragment
function getCellsFragment( cells ) {
  var fragment = document.createDocumentFragment();
  cells.forEach( function( cell ) {
    fragment.appendChild( cell.element );
  } );
  return fragment;
}

// -------------------------- add/remove cell prototype -------------------------- //

var proto = Flickity.prototype;

/**
 * Insert, prepend, or append cells
 * @param {[Element, Array, NodeList]} elems - Elements to insert
 * @param {Integer} index - Zero-based number to insert
 */
proto.insert = function( elems, index ) {
  var cells = this._makeCells( elems );
  if ( !cells || !cells.length ) {
    return;
  }
  var len = this.cells.length;
  // default to append
  index = index === undefined ? len : index;
  // add cells with document fragment
  var fragment = getCellsFragment( cells );
  // append to slider
  var isAppend = index == len;
  if ( isAppend ) {
    this.slider.appendChild( fragment );
  } else {
    var insertCellElement = this.cells[ index ].element;
    this.slider.insertBefore( fragment, insertCellElement );
  }
  // add to this.cells
  if ( index === 0 ) {
    // prepend, add to start
    this.cells = cells.concat( this.cells );
  } else if ( isAppend ) {
    // append, add to end
    this.cells = this.cells.concat( cells );
  } else {
    // insert in this.cells
    var endCells = this.cells.splice( index, len - index );
    this.cells = this.cells.concat( cells ).concat( endCells );
  }

  this._sizeCells( cells );
  this.cellChange( index, true );
};

proto.append = function( elems ) {
  this.insert( elems, this.cells.length );
};

proto.prepend = function( elems ) {
  this.insert( elems, 0 );
};

/**
 * Remove cells
 * @param {[Element, Array, NodeList]} elems - ELements to remove
 */
proto.remove = function( elems ) {
  var cells = this.getCells( elems );
  if ( !cells || !cells.length ) {
    return;
  }

  var minCellIndex = this.cells.length - 1;
  // remove cells from collection & DOM
  cells.forEach( function( cell ) {
    cell.remove();
    var index = this.cells.indexOf( cell );
    minCellIndex = Math.min( index, minCellIndex );
    utils.removeFrom( this.cells, cell );
  }, this );

  this.cellChange( minCellIndex, true );
};

/**
 * logic to be run after a cell's size changes
 * @param {Element} elem - cell's element
 */
proto.cellSizeChange = function( elem ) {
  var cell = this.getCell( elem );
  if ( !cell ) {
    return;
  }
  cell.getSize();

  var index = this.cells.indexOf( cell );
  this.cellChange( index );
};

/**
 * logic any time a cell is changed: added, removed, or size changed
 * @param {Integer} changedCellIndex - index of the changed cell, optional
 * @param {Boolean} isPositioningSlider - Positions slider after selection
 */
proto.cellChange = function( changedCellIndex, isPositioningSlider ) {
  var prevSelectedElem = this.selectedElement;
  this._positionCells( changedCellIndex );
  this._getWrapShiftCells();
  this.setGallerySize();
  // update selectedIndex
  // try to maintain position & select previous selected element
  var cell = this.getCell( prevSelectedElem );
  if ( cell ) {
    this.selectedIndex = this.getCellSlideIndex( cell );
  }
  this.selectedIndex = Math.min( this.slides.length - 1, this.selectedIndex );

  this.emitEvent( 'cellChange', [ changedCellIndex ] );
  // position slider
  this.select( this.selectedIndex );
  // do not position slider after lazy load
  if ( isPositioningSlider ) {
    this.positionSliderAtSelected();
  }
};

// -----  ----- //

return Flickity;

} ) );

// lazyload
( function( window, factory ) {
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity/js/lazyload',[
      './flickity',
      'fizzy-ui-utils/utils',
    ], function( Flickity, utils ) {
      return factory( window, Flickity, utils );
    } );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
        window,
        require('./flickity'),
        require('fizzy-ui-utils')
    );
  } else {
    // browser global
    factory(
        window,
        window.Flickity,
        window.fizzyUIUtils
    );
  }

}( window, function factory( window, Flickity, utils ) {
'use strict';

Flickity.createMethods.push('_createLazyload');
var proto = Flickity.prototype;

proto._createLazyload = function() {
  this.on( 'select', this.lazyLoad );
};

proto.lazyLoad = function() {
  var lazyLoad = this.options.lazyLoad;
  if ( !lazyLoad ) {
    return;
  }
  // get adjacent cells, use lazyLoad option for adjacent count
  var adjCount = typeof lazyLoad == 'number' ? lazyLoad : 0;
  var cellElems = this.getAdjacentCellElements( adjCount );
  // get lazy images in those cells
  var lazyImages = [];
  cellElems.forEach( function( cellElem ) {
    var lazyCellImages = getCellLazyImages( cellElem );
    lazyImages = lazyImages.concat( lazyCellImages );
  } );
  // load lazy images
  lazyImages.forEach( function( img ) {
    new LazyLoader( img, this );
  }, this );
};

function getCellLazyImages( cellElem ) {
  // check if cell element is lazy image
  if ( cellElem.nodeName == 'IMG' ) {
    var lazyloadAttr = cellElem.getAttribute('data-flickity-lazyload');
    var srcAttr = cellElem.getAttribute('data-flickity-lazyload-src');
    var srcsetAttr = cellElem.getAttribute('data-flickity-lazyload-srcset');
    if ( lazyloadAttr || srcAttr || srcsetAttr ) {
      return [ cellElem ];
    }
  }
  // select lazy images in cell
  var lazySelector = 'img[data-flickity-lazyload], ' +
    'img[data-flickity-lazyload-src], img[data-flickity-lazyload-srcset]';
  var imgs = cellElem.querySelectorAll( lazySelector );
  return utils.makeArray( imgs );
}

// -------------------------- LazyLoader -------------------------- //

/**
 * class to handle loading images
 * @param {Image} img - Image element
 * @param {Flickity} flickity - Flickity instance
 */
function LazyLoader( img, flickity ) {
  this.img = img;
  this.flickity = flickity;
  this.load();
}

LazyLoader.prototype.handleEvent = utils.handleEvent;

LazyLoader.prototype.load = function() {
  this.img.addEventListener( 'load', this );
  this.img.addEventListener( 'error', this );
  // get src & srcset
  var src = this.img.getAttribute('data-flickity-lazyload') ||
    this.img.getAttribute('data-flickity-lazyload-src');
  var srcset = this.img.getAttribute('data-flickity-lazyload-srcset');
  // set src & serset
  this.img.src = src;
  if ( srcset ) {
    this.img.setAttribute( 'srcset', srcset );
  }
  // remove attr
  this.img.removeAttribute('data-flickity-lazyload');
  this.img.removeAttribute('data-flickity-lazyload-src');
  this.img.removeAttribute('data-flickity-lazyload-srcset');
};

LazyLoader.prototype.onload = function( event ) {
  this.complete( event, 'flickity-lazyloaded' );
};

LazyLoader.prototype.onerror = function( event ) {
  this.complete( event, 'flickity-lazyerror' );
};

LazyLoader.prototype.complete = function( event, className ) {
  // unbind events
  this.img.removeEventListener( 'load', this );
  this.img.removeEventListener( 'error', this );

  var cell = this.flickity.getParentCell( this.img );
  var cellElem = cell && cell.element;
  this.flickity.cellSizeChange( cellElem );

  this.img.classList.add( className );
  this.flickity.dispatchEvent( 'lazyLoad', event, cellElem );
};

// -----  ----- //

Flickity.LazyLoader = LazyLoader;

return Flickity;

} ) );

/*!
 * Flickity v2.2.2
 * Touch, responsive, flickable carousels
 *
 * Licensed GPLv3 for open source use
 * or Flickity Commercial License for commercial use
 *
 * https://flickity.metafizzy.co
 * Copyright 2015-2021 Metafizzy
 */

( function( window, factory ) {
  // universal module definition
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity/js/index',[
      './flickity',
      './drag',
      './prev-next-button',
      './page-dots',
      './player',
      './add-remove-cell',
      './lazyload',
    ], factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
        require('./flickity'),
        require('./drag'),
        require('./prev-next-button'),
        require('./page-dots'),
        require('./player'),
        require('./add-remove-cell'),
        require('./lazyload')
    );
  }

} )( window, function factory( Flickity ) {
  return Flickity;
} );

/*!
 * Flickity asNavFor v2.0.2
 * enable asNavFor for Flickity
 */

/*jshint browser: true, undef: true, unused: true, strict: true*/

( function( window, factory ) {
  // universal module definition
  /*jshint strict: false */ /*globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'flickity-as-nav-for/as-nav-for',[
      'flickity/js/index',
      'fizzy-ui-utils/utils'
    ], factory );
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      require('flickity'),
      require('fizzy-ui-utils')
    );
  } else {
    // browser global
    window.Flickity = factory(
      window.Flickity,
      window.fizzyUIUtils
    );
  }

}( window, function factory( Flickity, utils ) {



// -------------------------- asNavFor prototype -------------------------- //

// Flickity.defaults.asNavFor = null;

Flickity.createMethods.push('_createAsNavFor');

var proto = Flickity.prototype;

proto._createAsNavFor = function() {
  this.on( 'activate', this.activateAsNavFor );
  this.on( 'deactivate', this.deactivateAsNavFor );
  this.on( 'destroy', this.destroyAsNavFor );

  var asNavForOption = this.options.asNavFor;
  if ( !asNavForOption ) {
    return;
  }
  // HACK do async, give time for other flickity to be initalized
  var _this = this;
  setTimeout( function initNavCompanion() {
    _this.setNavCompanion( asNavForOption );
  });
};

proto.setNavCompanion = function( elem ) {
  elem = utils.getQueryElement( elem );
  var companion = Flickity.data( elem );
  // stop if no companion or companion is self
  if ( !companion || companion == this ) {
    return;
  }

  this.navCompanion = companion;
  // companion select
  var _this = this;
  this.onNavCompanionSelect = function() {
    _this.navCompanionSelect();
  };
  companion.on( 'select', this.onNavCompanionSelect );
  // click
  this.on( 'staticClick', this.onNavStaticClick );

  this.navCompanionSelect( true );
};

proto.navCompanionSelect = function( isInstant ) {
  // wait for companion & selectedCells first. #8
  var companionCells = this.navCompanion && this.navCompanion.selectedCells;
  if ( !companionCells ) {
    return;
  }
  // select slide that matches first cell of slide
  var selectedCell = companionCells[0];
  var firstIndex = this.navCompanion.cells.indexOf( selectedCell );
  var lastIndex = firstIndex + companionCells.length - 1;
  var selectIndex = Math.floor( lerp( firstIndex, lastIndex,
    this.navCompanion.cellAlign ) );
  this.selectCell( selectIndex, false, isInstant );
  // set nav selected class
  this.removeNavSelectedElements();
  // stop if companion has more cells than this one
  if ( selectIndex >= this.cells.length ) {
    return;
  }

  var selectedCells = this.cells.slice( firstIndex, lastIndex + 1 );
  this.navSelectedElements = selectedCells.map( function( cell ) {
    return cell.element;
  });
  this.changeNavSelectedClass('add');
};

function lerp( a, b, t ) {
  return ( b - a ) * t + a;
}

proto.changeNavSelectedClass = function( method ) {
  this.navSelectedElements.forEach( function( navElem ) {
    navElem.classList[ method ]('is-nav-selected');
  });
};

proto.activateAsNavFor = function() {
  this.navCompanionSelect( true );
};

proto.removeNavSelectedElements = function() {
  if ( !this.navSelectedElements ) {
    return;
  }
  this.changeNavSelectedClass('remove');
  delete this.navSelectedElements;
};

proto.onNavStaticClick = function( event, pointer, cellElement, cellIndex ) {
  if ( typeof cellIndex == 'number' ) {
    this.navCompanion.selectCell( cellIndex );
  }
};

proto.deactivateAsNavFor = function() {
  this.removeNavSelectedElements();
};

proto.destroyAsNavFor = function() {
  if ( !this.navCompanion ) {
    return;
  }
  this.navCompanion.off( 'select', this.onNavCompanionSelect );
  this.off( 'staticClick', this.onNavStaticClick );
  delete this.navCompanion;
};

// -----  ----- //

return Flickity;

}));

/*!
 * imagesLoaded v4.1.4
 * JavaScript is all like "You images are done yet or what?"
 * MIT License
 */

( function( window, factory ) { 'use strict';
  // universal module definition

  /*global define: false, module: false, require: false */

  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( 'imagesloaded/imagesloaded',[
      'ev-emitter/ev-emitter'
    ], function( EvEmitter ) {
      return factory( window, EvEmitter );
    });
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      window,
      require('ev-emitter')
    );
  } else {
    // browser global
    window.imagesLoaded = factory(
      window,
      window.EvEmitter
    );
  }

})( typeof window !== 'undefined' ? window : this,

// --------------------------  factory -------------------------- //

function factory( window, EvEmitter ) {



var $ = window.jQuery;
var console = window.console;

// -------------------------- helpers -------------------------- //

// extend objects
function extend( a, b ) {
  for ( var prop in b ) {
    a[ prop ] = b[ prop ];
  }
  return a;
}

var arraySlice = Array.prototype.slice;

// turn element or nodeList into an array
function makeArray( obj ) {
  if ( Array.isArray( obj ) ) {
    // use object if already an array
    return obj;
  }

  var isArrayLike = typeof obj == 'object' && typeof obj.length == 'number';
  if ( isArrayLike ) {
    // convert nodeList to array
    return arraySlice.call( obj );
  }

  // array of single index
  return [ obj ];
}

// -------------------------- imagesLoaded -------------------------- //

/**
 * @param {Array, Element, NodeList, String} elem
 * @param {Object or Function} options - if function, use as callback
 * @param {Function} onAlways - callback function
 */
function ImagesLoaded( elem, options, onAlways ) {
  // coerce ImagesLoaded() without new, to be new ImagesLoaded()
  if ( !( this instanceof ImagesLoaded ) ) {
    return new ImagesLoaded( elem, options, onAlways );
  }
  // use elem as selector string
  var queryElem = elem;
  if ( typeof elem == 'string' ) {
    queryElem = document.querySelectorAll( elem );
  }
  // bail if bad element
  if ( !queryElem ) {
    console.error( 'Bad element for imagesLoaded ' + ( queryElem || elem ) );
    return;
  }

  this.elements = makeArray( queryElem );
  this.options = extend( {}, this.options );
  // shift arguments if no options set
  if ( typeof options == 'function' ) {
    onAlways = options;
  } else {
    extend( this.options, options );
  }

  if ( onAlways ) {
    this.on( 'always', onAlways );
  }

  this.getImages();

  if ( $ ) {
    // add jQuery Deferred object
    this.jqDeferred = new $.Deferred();
  }

  // HACK check async to allow time to bind listeners
  setTimeout( this.check.bind( this ) );
}

ImagesLoaded.prototype = Object.create( EvEmitter.prototype );

ImagesLoaded.prototype.options = {};

ImagesLoaded.prototype.getImages = function() {
  this.images = [];

  // filter & find items if we have an item selector
  this.elements.forEach( this.addElementImages, this );
};

/**
 * @param {Node} element
 */
ImagesLoaded.prototype.addElementImages = function( elem ) {
  // filter siblings
  if ( elem.nodeName == 'IMG' ) {
    this.addImage( elem );
  }
  // get background image on element
  if ( this.options.background === true ) {
    this.addElementBackgroundImages( elem );
  }

  // find children
  // no non-element nodes, #143
  var nodeType = elem.nodeType;
  if ( !nodeType || !elementNodeTypes[ nodeType ] ) {
    return;
  }
  var childImgs = elem.querySelectorAll('img');
  // concat childElems to filterFound array
  for ( var i=0; i < childImgs.length; i++ ) {
    var img = childImgs[i];
    this.addImage( img );
  }

  // get child background images
  if ( typeof this.options.background == 'string' ) {
    var children = elem.querySelectorAll( this.options.background );
    for ( i=0; i < children.length; i++ ) {
      var child = children[i];
      this.addElementBackgroundImages( child );
    }
  }
};

var elementNodeTypes = {
  1: true,
  9: true,
  11: true
};

ImagesLoaded.prototype.addElementBackgroundImages = function( elem ) {
  var style = getComputedStyle( elem );
  if ( !style ) {
    // Firefox returns null if in a hidden iframe https://bugzil.la/548397
    return;
  }
  // get url inside url("...")
  var reURL = /url\((['"])?(.*?)\1\)/gi;
  var matches = reURL.exec( style.backgroundImage );
  while ( matches !== null ) {
    var url = matches && matches[2];
    if ( url ) {
      this.addBackground( url, elem );
    }
    matches = reURL.exec( style.backgroundImage );
  }
};

/**
 * @param {Image} img
 */
ImagesLoaded.prototype.addImage = function( img ) {
  var loadingImage = new LoadingImage( img );
  this.images.push( loadingImage );
};

ImagesLoaded.prototype.addBackground = function( url, elem ) {
  var background = new Background( url, elem );
  this.images.push( background );
};

ImagesLoaded.prototype.check = function() {
  var _this = this;
  this.progressedCount = 0;
  this.hasAnyBroken = false;
  // complete if no images
  if ( !this.images.length ) {
    this.complete();
    return;
  }

  function onProgress( image, elem, message ) {
    // HACK - Chrome triggers event before object properties have changed. #83
    setTimeout( function() {
      _this.progress( image, elem, message );
    });
  }

  this.images.forEach( function( loadingImage ) {
    loadingImage.once( 'progress', onProgress );
    loadingImage.check();
  });
};

ImagesLoaded.prototype.progress = function( image, elem, message ) {
  this.progressedCount++;
  this.hasAnyBroken = this.hasAnyBroken || !image.isLoaded;
  // progress event
  this.emitEvent( 'progress', [ this, image, elem ] );
  if ( this.jqDeferred && this.jqDeferred.notify ) {
    this.jqDeferred.notify( this, image );
  }
  // check if completed
  if ( this.progressedCount == this.images.length ) {
    this.complete();
  }

  if ( this.options.debug && console ) {
    console.log( 'progress: ' + message, image, elem );
  }
};

ImagesLoaded.prototype.complete = function() {
  var eventName = this.hasAnyBroken ? 'fail' : 'done';
  this.isComplete = true;
  this.emitEvent( eventName, [ this ] );
  this.emitEvent( 'always', [ this ] );
  if ( this.jqDeferred ) {
    var jqMethod = this.hasAnyBroken ? 'reject' : 'resolve';
    this.jqDeferred[ jqMethod ]( this );
  }
};

// --------------------------  -------------------------- //

function LoadingImage( img ) {
  this.img = img;
}

LoadingImage.prototype = Object.create( EvEmitter.prototype );

LoadingImage.prototype.check = function() {
  // If complete is true and browser supports natural sizes,
  // try to check for image status manually.
  var isComplete = this.getIsImageComplete();
  if ( isComplete ) {
    // report based on naturalWidth
    this.confirm( this.img.naturalWidth !== 0, 'naturalWidth' );
    return;
  }

  // If none of the checks above matched, simulate loading on detached element.
  this.proxyImage = new Image();
  this.proxyImage.addEventListener( 'load', this );
  this.proxyImage.addEventListener( 'error', this );
  // bind to image as well for Firefox. #191
  this.img.addEventListener( 'load', this );
  this.img.addEventListener( 'error', this );
  this.proxyImage.src = this.img.src;
};

LoadingImage.prototype.getIsImageComplete = function() {
  // check for non-zero, non-undefined naturalWidth
  // fixes Safari+InfiniteScroll+Masonry bug infinite-scroll#671
  return this.img.complete && this.img.naturalWidth;
};

LoadingImage.prototype.confirm = function( isLoaded, message ) {
  this.isLoaded = isLoaded;
  this.emitEvent( 'progress', [ this, this.img, message ] );
};

// ----- events ----- //

// trigger specified handler for event type
LoadingImage.prototype.handleEvent = function( event ) {
  var method = 'on' + event.type;
  if ( this[ method ] ) {
    this[ method ]( event );
  }
};

LoadingImage.prototype.onload = function() {
  this.confirm( true, 'onload' );
  this.unbindEvents();
};

LoadingImage.prototype.onerror = function() {
  this.confirm( false, 'onerror' );
  this.unbindEvents();
};

LoadingImage.prototype.unbindEvents = function() {
  this.proxyImage.removeEventListener( 'load', this );
  this.proxyImage.removeEventListener( 'error', this );
  this.img.removeEventListener( 'load', this );
  this.img.removeEventListener( 'error', this );
};

// -------------------------- Background -------------------------- //

function Background( url, element ) {
  this.url = url;
  this.element = element;
  this.img = new Image();
}

// inherit LoadingImage prototype
Background.prototype = Object.create( LoadingImage.prototype );

Background.prototype.check = function() {
  this.img.addEventListener( 'load', this );
  this.img.addEventListener( 'error', this );
  this.img.src = this.url;
  // check if image is already complete
  var isComplete = this.getIsImageComplete();
  if ( isComplete ) {
    this.confirm( this.img.naturalWidth !== 0, 'naturalWidth' );
    this.unbindEvents();
  }
};

Background.prototype.unbindEvents = function() {
  this.img.removeEventListener( 'load', this );
  this.img.removeEventListener( 'error', this );
};

Background.prototype.confirm = function( isLoaded, message ) {
  this.isLoaded = isLoaded;
  this.emitEvent( 'progress', [ this, this.element, message ] );
};

// -------------------------- jQuery -------------------------- //

ImagesLoaded.makeJQueryPlugin = function( jQuery ) {
  jQuery = jQuery || window.jQuery;
  if ( !jQuery ) {
    return;
  }
  // set local variable
  $ = jQuery;
  // $().imagesLoaded()
  $.fn.imagesLoaded = function( options, callback ) {
    var instance = new ImagesLoaded( this, options, callback );
    return instance.jqDeferred.promise( $(this) );
  };
};
// try making plugin
ImagesLoaded.makeJQueryPlugin();

// --------------------------  -------------------------- //

return ImagesLoaded;

});

/*!
 * Flickity imagesLoaded v2.0.0
 * enables imagesLoaded option for Flickity
 */

/*jshint browser: true, strict: true, undef: true, unused: true */

( function( window, factory ) {
  // universal module definition
  /*jshint strict: false */ /*globals define, module, require */
  if ( typeof define == 'function' && define.amd ) {
    // AMD
    define( [
      'flickity/js/index',
      'imagesloaded/imagesloaded'
    ], function( Flickity, imagesLoaded ) {
      return factory( window, Flickity, imagesLoaded );
    });
  } else if ( typeof module == 'object' && module.exports ) {
    // CommonJS
    module.exports = factory(
      window,
      require('flickity'),
      require('imagesloaded')
    );
  } else {
    // browser global
    window.Flickity = factory(
      window,
      window.Flickity,
      window.imagesLoaded
    );
  }

}( window, function factory( window, Flickity, imagesLoaded ) {
'use strict';

Flickity.createMethods.push('_createImagesLoaded');

var proto = Flickity.prototype;

proto._createImagesLoaded = function() {
  this.on( 'activate', this.imagesLoaded );
};

proto.imagesLoaded = function() {
  if ( !this.options.imagesLoaded ) {
    return;
  }
  var _this = this;
  function onImagesLoadedProgress( instance, image ) {
    var cell = _this.getParentCell( image.img );
    _this.cellSizeChange( cell && cell.element );
    if ( !_this.options.freeScroll ) {
      _this.positionSliderAtSelected();
    }
  }
  imagesLoaded( this.slider ).on( 'progress', onImagesLoadedProgress );
};

return Flickity;

}));

;
