/* Minification failed. Returning unminified contents.
(13878,793-796): run-time error JS1009: Expected '}': ...
(13878,793-796): run-time error JS1006: Expected ')': ...
(13878,782): run-time error JS1004: Expected ';'
(13878,798-799): run-time error JS1195: Expected expression: )
(13878,847-848): run-time error JS1006: Expected ')': t
(13878,847): run-time error JS1004: Expected ';'
(13878,8300-8303): run-time error JS1009: Expected '}': ...
(13878,8241): run-time error JS1004: Expected ';'
(13878,9057-9058): run-time error JS1006: Expected ')': ;
(13878,9057-9058): run-time error JS1006: Expected ')': ;
(13878,9057): run-time error JS1004: Expected ';'
(13878,9557-9560): run-time error JS1009: Expected '}': ...
(13878,9557-9560): run-time error JS1006: Expected ')': ...
(13878,9557): run-time error JS1004: Expected ';'
(13878,9578-9579): run-time error JS1010: Expected identifier: ,
(13878,9581-9582): run-time error JS1008: Expected '{': ;
(13878,10085-10088): run-time error JS1009: Expected '}': ...
(13878,10085-10088): run-time error JS1003: Expected ':': ...
(13878,10090-10091): run-time error JS1006: Expected ')': :
(13878,10090): run-time error JS1004: Expected ';'
(13878,10090-10091): run-time error JS1195: Expected expression: :
(13878,10244-10245): run-time error JS1010: Expected identifier: )
(13878,10261-10262): run-time error JS1008: Expected '{': ,
(13878,23452-23453): run-time error JS1002: Syntax error: }
(13878,23453-23454): run-time error JS1195: Expected expression: )
(13878,23456-23457): run-time error JS1002: Syntax error: }
(13878,23457-23458): run-time error JS1195: Expected expression: )
(13878,23458-23459): run-time error JS1195: Expected expression: )
(13878,4714-4823): run-time error JS1314: Implicit property name must be identifier: toHSVA(){const t=[s.h,s.s,s.v,s.a];return t.toString=i(t,(t=>`hsva(${t[0]}, ${t[1]}%, ${t[2]}%, ${s.a})`)),t}
(13878,4824-4939): run-time error JS1314: Implicit property name must be identifier: toHSLA(){const t=[...v(s.h,s.s,s.v),s.a];return t.toString=i(t,(t=>`hsla(${t[0]}, ${t[1]}%, ${t[2]}%, ${s.a})`)),t}
(13878,4940-5053): run-time error JS1314: Implicit property name must be identifier: toRGBA(){const t=[...f(s.h,s.s,s.v),s.a];return t.toString=i(t,(t=>`rgba(${t[0]}, ${t[1]}, ${t[2]}, ${s.a})`)),t}
(13878,5054-5343): run-time error JS1314: Implicit property name must be identifier: toCMYK(){const t=function(t,e,o){const n=f(t,e,o),i=n[0]/255,s=n[1]/255,r=n[2]/255,a=u(1-i,1-s,1-r);return[100*(1===a?0:(1-i-a)/(1-a)),100*(1===a?0:(1-s-a)/(1-a)),100*(1===a?0:(1-r-a)/(1-a)),100*a]}(s.h,s.s,s.v);return t.toString=i(t,(t=>`cmyk(${t[0]}%, ${t[1]}%, ${t[2]}%, ${t[3]}%)`)),t}
(13878,5344-5603): run-time error JS1314: Implicit property name must be identifier: toHEXA(){const t=function(t,e,o){return f(t,e,o).map((t=>m(t).toString(16).padStart(2,"0")))}(s.h,s.s,s.v),e=s.a>=1?"":Number((255*s.a).toFixed(0)).toString(16).toUpperCase().padStart(2,"0");return e&&t.push(e),t.toString=()=>`#${t.join("").toUpperCase()}`,t}
(13878,5768-6199): run-time error JS1314: Implicit property name must be identifier: _keyboard(t){const{options:o}=e,{type:n,key:i}=t;if(document.activeElement===o.wrapper){const{lock:o}=e.options,s="ArrowUp"===i,r="ArrowRight"===i,a="ArrowDown"===i,l="ArrowLeft"===i;if("keydown"===n&&(s||r||a||l)){let n=0,i=0;"v"===o?n=s||r?1:-1:"h"===o?n=s||r?-1:1:(i=s?-1:a?1:0,n=l?-1:r?1:0),e.update(C(e.cache.x+.01*n),C(e.cache.y+.01*i)),t.preventDefault()}else i.startsWith("Arrow")&&(e.options.onstop(),t.preventDefault())}}
(13878,6200-6369): run-time error JS1314: Implicit property name must be identifier: _tapstart(t){i(document,["mouseup","touchend","touchcancel"],e._tapstop),i(document,["mousemove","touchmove"],e._tapmove),t.cancelable&&t.preventDefault(),e._tapmove(t)}
(13878,6370-7048): run-time error JS1314: Implicit property name must be identifier: _tapmove(t){const{options:o,cache:n}=e,{lock:i,element:s,wrapper:r}=o,a=r.getBoundingClientRect();let l=0,c=0;if(t){const e=t&&t.touches&&t.touches[0];l=t?(e||t).clientX:0,c=t?(e||t).clientY:0,l<a.left?l=a.left:l>a.left+a.width&&(l=a.left+a.width),c<a.top?c=a.top:c>a.top+a.height&&(c=a.top+a.height),l-=a.left,c-=a.top}else n&&(l=n.x*a.width,c=n.y*a.height);"h"!==i&&(s.style.left=`calc(${l/a.width*100}% - ${s.offsetWidth/2}px)`),"v"!==i&&(s.style.top=`calc(${c/a.height*100}% - ${s.offsetHeight/2}px)`),e.cache={x:l/a.width,y:c/a.height};const p=C(l/a.width),u=C(c/a.height);switch(i){case"v":return o.onchange(p);case"h":return o.onchange(u);default:return o.onchange(p,u)}}
(13878,7049-7188): run-time error JS1314: Implicit property name must be identifier: _tapstop(){e.options.onstop(),s(document,["mouseup","touchend","touchcancel"],e._tapstop),s(document,["mousemove","touchmove"],e._tapmove)}
(13878,7189-7212): run-time error JS1314: Implicit property name must be identifier: trigger(){e._tapmove()}
(13878,7213-7378): run-time error JS1314: Implicit property name must be identifier: update(t=0,o=0){const{left:n,top:i,width:s,height:r}=e.options.wrapper.getBoundingClientRect();"h"===e.options.lock&&(o=t),e._tapmove({clientX:n+s*t,clientY:i+r*o})}
(13878,7379-7558): run-time error JS1314: Implicit property name must be identifier: destroy(){const{options:t,_tapstart:o,_keyboard:n}=e;s(document,["keydown","keyup"],n),s([t.wrapper,t.element],"mousedown",o),s([t.wrapper,t.element],"touchstart",o,{passive:!1})}
(13878,10100-10242): run-time error JS1314: Implicit property name must be identifier: update(t=n){const{reference:e,popper:o}=Object.assign(n,t);if(!o||!e)throw new Error("Popper- or reference-element missing.");return O(e,o,n)}
(13878,14929-15768): run-time error JS1314: Implicit property name must be identifier: onchange(o,n){if(!e.palette)return;const i=s(),{_root:r,options:a}=t,{lastColor:l,currentColor:c}=r.preview;t._recalc&&(i.s=100*o,i.v=100-100*n,i.v<0&&(i.v=0),t._updateOutput("slider"));const p=i.toRGBA().toString(0);this.element.style.background=p,this.wrapper.style.background=`\n                        linear-gradient(to top, rgba(0, 0, 0, ${i.a}), transparent),\n                        linear-gradient(to left, hsla(${i.h}, 100%, 50%, ${i.a}), rgba(255, 255, 255, ${i.a}))\n                    `,a.comparison?a.useAsButton||t._lastColor||l.style.setProperty("--pcr-color",p):(r.button.style.setProperty("--pcr-color",p),r.button.classList.remove("clear"));const u=i.toHEXA().toString();for(const{el:e,color:o}of t._swatchColors)e.classList[u===o.toHEXA().toString()?"add":"remove"]("pcr-active");c.style.setProperty("--pcr-color",p)}
(13878,15897-16053): run-time error JS1314: Implicit property name must be identifier: onchange(o){if(!e.hue||!e.palette)return;const n=s();t._recalc&&(n.h=360*o),this.element.style.backgroundColor=`hsl(${n.h}, 100%, 50%)`,r.palette.trigger()}
(13878,16194-16364): run-time error JS1314: Implicit property name must be identifier: onchange(o){if(!e.opacity||!e.palette)return;const n=s();t._recalc&&(n.a=Math.round(100*o)/100),this.element.style.background=`rgba(0, 0, 0, ${n.a})`,r.palette.trigger()}
(13878,16437-16553): run-time error JS1314: Implicit property name must be identifier: onchange(e){t._representation=e.target.getAttribute("data-type").toUpperCase(),t._recalc&&t._updateOutput("swatch")}
(13878,22508-23452): run-time error JS1018: 'return' statement outside of function: return E(L,"utils",o),E(L,"version","1.8.2"),E(L,"I18N_DEFAULTS",{"ui:dialog":"color picker dialog","btn:toggle":"toggle color picker dialog","btn:swatch":"color swatch","btn:last-color":"use previous color","btn:save":"Save","btn:cancel":"Cancel","btn:clear":"Clear","aria:btn:save":"save and close","aria:btn:cancel":"cancel and close","aria:btn:clear":"clear and close","aria:input":"color input field","aria:palette":"color selection area","aria:hue":"hue selection slider","aria:opacity":"selection slider"}),E(L,"DEFAULT_OPTIONS",{appClass:null,theme:"classic",useAsButton:!1,padding:8,disabled:!1,comparison:!0,closeOnScroll:!1,outputPrecision:0,lockOpacity:!1,autoReposition:!0,container:"body",components:{interaction:{}},i18n:{},swatches:null,inline:!1,sliders:null,default:"#42445a",defaultRepresentation:null,position:"bottom-middle",adjustableNumbers:!0,showAlways:!1,closeWithKey:"Escape"}),E(L,"create",(t=>new L(t))),e=e.default
 */
/* Modernizr 2.7.1 (Custom Build) | MIT & BSD
 * Build: http://modernizr.com/download/#-fontface-backgroundsize-borderimage-borderradius-boxshadow-flexbox-flexboxlegacy-hsla-multiplebgs-opacity-rgba-textshadow-cssanimations-csscolumns-generatedcontent-cssgradients-cssreflections-csstransforms-csstransforms3d-csstransitions-applicationcache-canvas-canvastext-draganddrop-hashchange-history-audio-video-indexeddb-input-inputtypes-localstorage-postmessage-sessionstorage-websockets-websqldatabase-webworkers-geolocation-inlinesvg-smil-svg-svgclippaths-touch-webgl-shiv-mq-cssclasses-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes-load
 */
;window.Modernizr=function(a,b,c){function D(a){j.cssText=a}function E(a,b){return D(n.join(a+";")+(b||""))}function F(a,b){return typeof a===b}function G(a,b){return!!~(""+a).indexOf(b)}function H(a,b){for(var d in a){var e=a[d];if(!G(e,"-")&&j[e]!==c)return b=="pfx"?e:!0}return!1}function I(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:F(f,"function")?f.bind(d||b):f}return!1}function J(a,b,c){var d=a.charAt(0).toUpperCase()+a.slice(1),e=(a+" "+p.join(d+" ")+d).split(" ");return F(b,"string")||F(b,"undefined")?H(e,b):(e=(a+" "+q.join(d+" ")+d).split(" "),I(e,b,c))}function K(){e.input=function(c){for(var d=0,e=c.length;d<e;d++)u[c[d]]=c[d]in k;return u.list&&(u.list=!!b.createElement("datalist")&&!!a.HTMLDataListElement),u}("autocomplete autofocus list placeholder max min multiple pattern required step".split(" ")),e.inputtypes=function(a){for(var d=0,e,f,h,i=a.length;d<i;d++)k.setAttribute("type",f=a[d]),e=k.type!=="text",e&&(k.value=l,k.style.cssText="position:absolute;visibility:hidden;",/^range$/.test(f)&&k.style.WebkitAppearance!==c?(g.appendChild(k),h=b.defaultView,e=h.getComputedStyle&&h.getComputedStyle(k,null).WebkitAppearance!=="textfield"&&k.offsetHeight!==0,g.removeChild(k)):/^(search|tel)$/.test(f)||(/^(url|email)$/.test(f)?e=k.checkValidity&&k.checkValidity()===!1:e=k.value!=l)),t[a[d]]=!!e;return t}("search tel url email datetime date month week time datetime-local number range color".split(" "))}var d="2.7.1",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k=b.createElement("input"),l=":)",m={}.toString,n=" -webkit- -moz- -o- -ms- ".split(" "),o="Webkit Moz O ms",p=o.split(" "),q=o.toLowerCase().split(" "),r={svg:"http://www.w3.org/2000/svg"},s={},t={},u={},v=[],w=v.slice,x,y=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["&#173;",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},z=function(b){var c=a.matchMedia||a.msMatchMedia;if(c)return c(b).matches;var d;return y("@media "+b+" { #"+h+" { position: absolute; } }",function(b){d=(a.getComputedStyle?getComputedStyle(b,null):b.currentStyle)["position"]=="absolute"}),d},A=function(){function d(d,e){e=e||b.createElement(a[d]||"div"),d="on"+d;var f=d in e;return f||(e.setAttribute||(e=b.createElement("div")),e.setAttribute&&e.removeAttribute&&(e.setAttribute(d,""),f=F(e[d],"function"),F(e[d],"undefined")||(e[d]=c),e.removeAttribute(d))),e=null,f}var a={select:"input",change:"input",submit:"form",reset:"form",error:"img",load:"img",abort:"img"};return d}(),B={}.hasOwnProperty,C;!F(B,"undefined")&&!F(B.call,"undefined")?C=function(a,b){return B.call(a,b)}:C=function(a,b){return b in a&&F(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=w.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(w.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(w.call(arguments)))};return e}),s.flexbox=function(){return J("flexWrap")},s.flexboxlegacy=function(){return J("boxDirection")},s.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},s.canvastext=function(){return!!e.canvas&&!!F(b.createElement("canvas").getContext("2d").fillText,"function")},s.webgl=function(){return!!a.WebGLRenderingContext},s.touch=function(){var c;return"ontouchstart"in a||a.DocumentTouch&&b instanceof DocumentTouch?c=!0:y(["@media (",n.join("touch-enabled),("),h,")","{#modernizr{top:9px;position:absolute}}"].join(""),function(a){c=a.offsetTop===9}),c},s.geolocation=function(){return"geolocation"in navigator},s.postmessage=function(){return!!a.postMessage},s.websqldatabase=function(){return!!a.openDatabase},s.indexedDB=function(){return!!J("indexedDB",a)},s.hashchange=function(){return A("hashchange",a)&&(b.documentMode===c||b.documentMode>7)},s.history=function(){return!!a.history&&!!history.pushState},s.draganddrop=function(){var a=b.createElement("div");return"draggable"in a||"ondragstart"in a&&"ondrop"in a},s.websockets=function(){return"WebSocket"in a||"MozWebSocket"in a},s.rgba=function(){return D("background-color:rgba(150,255,150,.5)"),G(j.backgroundColor,"rgba")},s.hsla=function(){return D("background-color:hsla(120,40%,100%,.5)"),G(j.backgroundColor,"rgba")||G(j.backgroundColor,"hsla")},s.multiplebgs=function(){return D("background:url(https://),url(https://),red url(https://)"),/(url\s*\(.*?){3}/.test(j.background)},s.backgroundsize=function(){return J("backgroundSize")},s.borderimage=function(){return J("borderImage")},s.borderradius=function(){return J("borderRadius")},s.boxshadow=function(){return J("boxShadow")},s.textshadow=function(){return b.createElement("div").style.textShadow===""},s.opacity=function(){return E("opacity:.55"),/^0.55$/.test(j.opacity)},s.cssanimations=function(){return J("animationName")},s.csscolumns=function(){return J("columnCount")},s.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return D((a+"-webkit- ".split(" ").join(b+a)+n.join(c+a)).slice(0,-a.length)),G(j.backgroundImage,"gradient")},s.cssreflections=function(){return J("boxReflect")},s.csstransforms=function(){return!!J("transform")},s.csstransforms3d=function(){var a=!!J("perspective");return a&&"webkitPerspective"in g.style&&y("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(b,c){a=b.offsetLeft===9&&b.offsetHeight===3}),a},s.csstransitions=function(){return J("transition")},s.fontface=function(){var a;return y('@font-face {font-family:"font";src:url("https://")}',function(c,d){var e=b.getElementById("smodernizr"),f=e.sheet||e.styleSheet,g=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"";a=/src/i.test(g)&&g.indexOf(d.split(" ")[0])===0}),a},s.generatedcontent=function(){var a;return y(["#",h,"{font:0/0 a}#",h,':after{content:"',l,'";visibility:hidden;font:3px/1 a}'].join(""),function(b){a=b.offsetHeight>=3}),a},s.video=function(){var a=b.createElement("video"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,""),c.h264=a.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,""),c.webm=a.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")}catch(d){}return c},s.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c},s.localstorage=function(){try{return localStorage.setItem(h,h),localStorage.removeItem(h),!0}catch(a){return!1}},s.sessionstorage=function(){try{return sessionStorage.setItem(h,h),sessionStorage.removeItem(h),!0}catch(a){return!1}},s.webworkers=function(){return!!a.Worker},s.applicationcache=function(){return!!a.applicationCache},s.svg=function(){return!!b.createElementNS&&!!b.createElementNS(r.svg,"svg").createSVGRect},s.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="<svg/>",(a.firstChild&&a.firstChild.namespaceURI)==r.svg},s.smil=function(){return!!b.createElementNS&&/SVGAnimate/.test(m.call(b.createElementNS(r.svg,"animate")))},s.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(m.call(b.createElementNS(r.svg,"clipPath")))};for(var L in s)C(s,L)&&(x=L.toLowerCase(),e[x]=s[L](),v.push((e[x]?"":"no-")+x));return e.input||K(),e.addTest=function(a,b){if(typeof a=="object")for(var d in a)C(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},D(""),i=k=null,function(a,b){function l(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function m(){var a=s.elements;return typeof a=="string"?a.split(" "):a}function n(a){var b=j[a[h]];return b||(b={},i++,a[h]=i,j[i]=b),b}function o(a,c,d){c||(c=b);if(k)return c.createElement(a);d||(d=n(c));var g;return d.cache[a]?g=d.cache[a].cloneNode():f.test(a)?g=(d.cache[a]=d.createElem(a)).cloneNode():g=d.createElem(a),g.canHaveChildren&&!e.test(a)&&!g.tagUrn?d.frag.appendChild(g):g}function p(a,c){a||(a=b);if(k)return a.createDocumentFragment();c=c||n(a);var d=c.frag.cloneNode(),e=0,f=m(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function q(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return s.shivMethods?o(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/[\w\-]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(s,b.frag)}function r(a){a||(a=b);var c=n(a);return s.shivCSS&&!g&&!c.hasCSS&&(c.hasCSS=!!l(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),k||q(a,c),a}var c="3.7.0",d=a.html5||{},e=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,f=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,g,h="_html5shiv",i=0,j={},k;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",g="hidden"in a,k=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){g=!0,k=!0}})();var s={elements:d.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",version:c,shivCSS:d.shivCSS!==!1,supportsUnknownElements:k,shivMethods:d.shivMethods!==!1,type:"default",shivDocument:r,createElement:o,createDocumentFragment:p};a.html5=s,r(b)}(this,b),e._version=d,e._prefixes=n,e._domPrefixes=q,e._cssomPrefixes=p,e.mq=z,e.hasEvent=A,e.testProp=function(a){return H([a])},e.testAllProps=J,e.testStyles=y,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+v.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};;
!function(n,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.device=e():n.device=e()}(window,function(){return function(n){var e={};function o(t){if(e[t])return e[t].exports;var i=e[t]={i:t,l:!1,exports:{}};return n[t].call(i.exports,i,i.exports,o),i.l=!0,i.exports}return o.m=n,o.c=e,o.d=function(n,e,t){o.o(n,e)||Object.defineProperty(n,e,{configurable:!1,enumerable:!0,get:t})},o.r=function(n){Object.defineProperty(n,"__esModule",{value:!0})},o.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return o.d(e,"a",e),e},o.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},o.p="",o(o.s=1)}([function(n,e,o){"use strict";o.r(e);var t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(n){return typeof n}:function(n){return n&&"function"==typeof Symbol&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},i=window.device,r={},a=[];window.device=r;var c=window.document.documentElement,d=window.navigator.userAgent.toLowerCase(),u=["googletv","viera","smarttv","internet.tv","netcast","nettv","appletv","boxee","kylo","roku","dlnadoc","roku","pov_tv","hbbtv","ce-html"];function l(n){return-1!==d.indexOf(n)}function s(n){return c.className.match(new RegExp(n,"i"))}function f(n){var e=null;s(n)||(e=c.className.replace(/^\s+|\s+$/g,""),c.className=e+" "+n)}function b(n){s(n)&&(c.className=c.className.replace(" "+n,""))}function p(){r.landscape()?(b("portrait"),f("landscape"),w("landscape")):(b("landscape"),f("portrait"),w("portrait")),h()}function w(n){for(var e in a)a[e](n)}r.macos=function(){return l("mac")},r.ios=function(){return r.iphone()||r.ipod()||r.ipad()},r.iphone=function(){return!r.windows()&&l("iphone")},r.ipod=function(){return l("ipod")},r.ipad=function(){return l("ipad")},r.android=function(){return!r.windows()&&l("android")},r.androidPhone=function(){return r.android()&&l("mobile")},r.androidTablet=function(){return r.android()&&!l("mobile")},r.blackberry=function(){return l("blackberry")||l("bb10")||l("rim")},r.blackberryPhone=function(){return r.blackberry()&&!l("tablet")},r.blackberryTablet=function(){return r.blackberry()&&l("tablet")},r.windows=function(){return l("windows")},r.windowsPhone=function(){return r.windows()&&l("phone")},r.windowsTablet=function(){return r.windows()&&l("touch")&&!r.windowsPhone()},r.fxos=function(){return(l("(mobile")||l("(tablet"))&&l(" rv:")},r.fxosPhone=function(){return r.fxos()&&l("mobile")},r.fxosTablet=function(){return r.fxos()&&l("tablet")},r.meego=function(){return l("meego")},r.cordova=function(){return window.cordova&&"file:"===location.protocol},r.nodeWebkit=function(){return"object"===t(window.process)},r.mobile=function(){return r.androidPhone()||r.iphone()||r.ipod()||r.windowsPhone()||r.blackberryPhone()||r.fxosPhone()||r.meego()},r.tablet=function(){return r.ipad()||r.androidTablet()||r.blackberryTablet()||r.windowsTablet()||r.fxosTablet()},r.desktop=function(){return!r.tablet()&&!r.mobile()},r.television=function(){for(var n=0;n<u.length;){if(l(u[n]))return!0;n++}return!1},r.portrait=function(){return screen.orientation&&Object.prototype.hasOwnProperty.call(window,"onorientationchange")?screen.orientation.type.includes("portrait"):window.innerHeight/window.innerWidth>1},r.landscape=function(){return screen.orientation&&Object.prototype.hasOwnProperty.call(window,"onorientationchange")?screen.orientation.type.includes("landscape"):window.innerHeight/window.innerWidth<1},r.noConflict=function(){return window.device=i,this},r.ios()?r.ipad()?f("ios ipad tablet"):r.iphone()?f("ios iphone mobile"):r.ipod()&&f("ios ipod mobile"):r.macos()?f("macos desktop"):r.android()?r.androidTablet()?f("android tablet"):f("android mobile"):r.blackberry()?r.blackberryTablet()?f("blackberry tablet"):f("blackberry mobile"):r.windows()?r.windowsTablet()?f("windows tablet"):r.windowsPhone()?f("windows mobile"):f("windows desktop"):r.fxos()?r.fxosTablet()?f("fxos tablet"):f("fxos mobile"):r.meego()?f("meego mobile"):r.nodeWebkit()?f("node-webkit"):r.television()?f("television"):r.desktop()&&f("desktop"),r.cordova()&&f("cordova"),r.onChangeOrientation=function(n){"function"==typeof n&&a.push(n)};var m="resize";function y(n){for(var e=0;e<n.length;e++)if(r[n[e]]())return n[e];return"unknown"}function h(){r.orientation=y(["portrait","landscape"])}Object.prototype.hasOwnProperty.call(window,"onorientationchange")&&(m="orientationchange"),window.addEventListener?window.addEventListener(m,p,!1):window.attachEvent?window.attachEvent(m,p):window[m]=p,p(),r.type=y(["mobile","tablet","desktop"]),r.os=y(["ios","iphone","ipad","ipod","android","blackberry","windows","fxos","meego","television"]),h(),e.default=r},function(n,e,o){n.exports=o(0)}]).default});;
/*!
  * Bowser - a browser detector
  * https://github.com/ded/bowser
  * MIT License | (c) Dustin Diaz 2014
  */
!function(e,t){typeof module!="undefined"&&module.exports?module.exports.browser=t():typeof define=="function"&&define.amd?define(t):this[e]=t()}("bowser",function(){function t(t){function n(e){var n=t.match(e);return n&&n.length>1&&n[1]||""}function r(e){var n=t.match(e);return n&&n.length>1&&n[2]||""}var i=n(/(ipod|iphone|ipad)/i).toLowerCase(),s=/like android/i.test(t),o=!s&&/android/i.test(t),u=n(/edge\/(\d+(\.\d+)?)/i),a=n(/version\/(\d+(\.\d+)?)/i),f=/tablet/i.test(t),l=!f&&/[^-]mobi/i.test(t),c;/opera|opr/i.test(t)?c={name:"Opera",opera:e,version:a||n(/(?:opera|opr)[\s\/](\d+(\.\d+)?)/i)}:/yabrowser/i.test(t)?c={name:"Yandex Browser",yandexbrowser:e,version:a||n(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i)}:/windows phone/i.test(t)?(c={name:"Windows Phone",windowsphone:e},u?(c.msedge=e,c.version=u):(c.msie=e,c.version=n(/iemobile\/(\d+(\.\d+)?)/i))):/msie|trident/i.test(t)?c={name:"Internet Explorer",msie:e,version:n(/(?:msie |rv:)(\d+(\.\d+)?)/i)}:/chrome.+? edge/i.test(t)?c={name:"Microsoft Edge",msedge:e,version:u}:/chrome|crios|crmo/i.test(t)?c={name:"Chrome",chrome:e,version:n(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i)}:i?(c={name:i=="iphone"?"iPhone":i=="ipad"?"iPad":"iPod"},a&&(c.version=a)):/sailfish/i.test(t)?c={name:"Sailfish",sailfish:e,version:n(/sailfish\s?browser\/(\d+(\.\d+)?)/i)}:/seamonkey\//i.test(t)?c={name:"SeaMonkey",seamonkey:e,version:n(/seamonkey\/(\d+(\.\d+)?)/i)}:/firefox|iceweasel/i.test(t)?(c={name:"Firefox",firefox:e,version:n(/(?:firefox|iceweasel)[ \/](\d+(\.\d+)?)/i)},/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(t)&&(c.firefoxos=e)):/silk/i.test(t)?c={name:"Amazon Silk",silk:e,version:n(/silk\/(\d+(\.\d+)?)/i)}:o?c={name:"Android",version:a}:/phantom/i.test(t)?c={name:"PhantomJS",phantom:e,version:n(/phantomjs\/(\d+(\.\d+)?)/i)}:/blackberry|\bbb\d+/i.test(t)||/rim\stablet/i.test(t)?c={name:"BlackBerry",blackberry:e,version:a||n(/blackberry[\d]+\/(\d+(\.\d+)?)/i)}:/(web|hpw)os/i.test(t)?(c={name:"WebOS",webos:e,version:a||n(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i)},/touchpad\//i.test(t)&&(c.touchpad=e)):/bada/i.test(t)?c={name:"Bada",bada:e,version:n(/dolfin\/(\d+(\.\d+)?)/i)}:/tizen/i.test(t)?c={name:"Tizen",tizen:e,version:n(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i)||a}:/safari/i.test(t)?c={name:"Safari",safari:e,version:a}:c={name:n(/^(.*)\/(.*) /),version:r(/^(.*)\/(.*) /)},!c.msedge&&/(apple)?webkit/i.test(t)?(c.name=c.name||"Webkit",c.webkit=e,!c.version&&a&&(c.version=a)):!c.opera&&/gecko\//i.test(t)&&(c.name=c.name||"Gecko",c.gecko=e,c.version=c.version||n(/gecko\/(\d+(\.\d+)?)/i)),!c.msedge&&(o||c.silk)?c.android=e:i&&(c[i]=e,c.ios=e);var h="";c.windowsphone?h=n(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i):i?(h=n(/os (\d+([_\s]\d+)*) like mac os x/i),h=h.replace(/[_\s]/g,".")):o?h=n(/android[ \/-](\d+(\.\d+)*)/i):c.webos?h=n(/(?:web|hpw)os\/(\d+(\.\d+)*)/i):c.blackberry?h=n(/rim\stablet\sos\s(\d+(\.\d+)*)/i):c.bada?h=n(/bada\/(\d+(\.\d+)*)/i):c.tizen&&(h=n(/tizen[\/\s](\d+(\.\d+)*)/i)),h&&(c.osversion=h);var p=h.split(".")[0];if(f||i=="ipad"||o&&(p==3||p==4&&!l)||c.silk)c.tablet=e;else if(l||i=="iphone"||i=="ipod"||o||c.blackberry||c.webos||c.bada)c.mobile=e;return c.msedge||c.msie&&c.version>=10||c.yandexbrowser&&c.version>=15||c.chrome&&c.version>=20||c.firefox&&c.version>=20||c.safari&&c.version>=6||c.opera&&c.version>=10||c.ios&&c.osversion&&c.osversion.split(".")[0]>=6||c.blackberry&&c.version>=10.1?c.a=e:c.msie&&c.version<10||c.chrome&&c.version<20||c.firefox&&c.version<20||c.safari&&c.version<6||c.opera&&c.version<10||c.ios&&c.osversion&&c.osversion.split(".")[0]<6?c.c=e:c.x=e,c}var e=!0,n=t(typeof navigator!="undefined"?navigator.userAgent:"");return n.test=function(e){for(var t=0;t<e.length;++t){var r=e[t];if(typeof r=="string"&&r in n)return!0}return!1},n._detect=t,n});
/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.1.3
 *
 * Requires: 1.2.2+
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'];
    var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
    var lowestDelta, lowestDeltaXY;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }

    $.event.special.mousewheel = {
        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
        },

        unmousewheel: function(fn) {
            return this.unbind("mousewheel", fn);
        }
    });


    function handler(event) {
        var orgEvent = event || window.event,
            args = [].slice.call(arguments, 1),
            delta = 0,
            deltaX = 0,
            deltaY = 0,
            absDelta = 0,
            absDeltaXY = 0,
            fn;
        event = $.event.fix(orgEvent);
        event.type = "mousewheel";

        // Old school scrollwheel delta
        if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; }
        if ( orgEvent.detail )     { delta = orgEvent.detail * -1; }

        // New school wheel delta (wheel event)
        if ( orgEvent.deltaY ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( orgEvent.deltaX ) {
            deltaX = orgEvent.deltaX;
            delta  = deltaX * -1;
        }

        // Webkit
        if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; }
        if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Look for lowest delta to normalize the delta values
        absDelta = Math.abs(delta);
        if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; }
        absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
        if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; }

        // Get a whole value for the deltas
        fn = delta > 0 ? 'floor' : 'ceil';
        delta  = Math[fn](delta / lowestDelta);
        deltaX = Math[fn](deltaX / lowestDeltaXY);
        deltaY = Math[fn](deltaY / lowestDeltaXY);

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

}));
;
/*! iScroll v5.2.0-snapshot ~ (c) 2008-2017 Matteo Spinelli ~ http://cubiq.org/license */
(function (window, document, Math) {
var rAF = window.requestAnimationFrame	||
	window.webkitRequestAnimationFrame	||
	window.mozRequestAnimationFrame		||
	window.oRequestAnimationFrame		||
	window.msRequestAnimationFrame		||
	function (callback) { window.setTimeout(callback, 1000 / 60); };

var utils = (function () {
	var me = {};

	var _elementStyle = document.createElement('div').style;
	var _vendor = (function () {
		var vendors = ['t', 'webkitT', 'MozT', 'msT', 'OT'],
			transform,
			i = 0,
			l = vendors.length;

		for ( ; i < l; i++ ) {
			transform = vendors[i] + 'ransform';
			if ( transform in _elementStyle ) return vendors[i].substr(0, vendors[i].length-1);
		}

		return false;
	})();

	function _prefixStyle (style) {
		if ( _vendor === false ) return false;
		if ( _vendor === '' ) return style;
		return _vendor + style.charAt(0).toUpperCase() + style.substr(1);
	}

	me.getTime = Date.now || function getTime () { return new Date().getTime(); };

	me.extend = function (target, obj) {
		for ( var i in obj ) {
			target[i] = obj[i];
		}
	};

	me.addEvent = function (el, type, fn, capture) {
		el.addEventListener(type, fn, !!capture);
	};

	me.removeEvent = function (el, type, fn, capture) {
		el.removeEventListener(type, fn, !!capture);
	};

	me.prefixPointerEvent = function (pointerEvent) {
		return window.MSPointerEvent ?
			'MSPointer' + pointerEvent.charAt(7).toUpperCase() + pointerEvent.substr(8):
			pointerEvent;
	};

	me.momentum = function (current, start, time, lowerMargin, wrapperSize, deceleration) {
		var distance = current - start,
			speed = Math.abs(distance) / time,
			destination,
			duration;

		deceleration = deceleration === undefined ? 0.0006 : deceleration;

		destination = current + ( speed * speed ) / ( 2 * deceleration ) * ( distance < 0 ? -1 : 1 );
		duration = speed / deceleration;

		if ( destination < lowerMargin ) {
			destination = wrapperSize ? lowerMargin - ( wrapperSize / 2.5 * ( speed / 8 ) ) : lowerMargin;
			distance = Math.abs(destination - current);
			duration = distance / speed;
		} else if ( destination > 0 ) {
			destination = wrapperSize ? wrapperSize / 2.5 * ( speed / 8 ) : 0;
			distance = Math.abs(current) + destination;
			duration = distance / speed;
		}

		return {
			destination: Math.round(destination),
			duration: duration
		};
	};

	var _transform = _prefixStyle('transform');

	me.extend(me, {
		hasTransform: _transform !== false,
		hasPerspective: _prefixStyle('perspective') in _elementStyle,
		hasTouch: 'ontouchstart' in window,
		hasPointer: !!(window.PointerEvent || window.MSPointerEvent), // IE10 is prefixed
		hasTransition: _prefixStyle('transition') in _elementStyle
	});

	/*
	This should find all Android browsers lower than build 535.19 (both stock browser and webview)
	- galaxy S2 is ok
    - 2.3.6 : `AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1`
    - 4.0.4 : `AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30`
   - galaxy S3 is badAndroid (stock brower, webview)
     `AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30`
   - galaxy S4 is badAndroid (stock brower, webview)
     `AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30`
   - galaxy S5 is OK
     `AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Mobile Safari/537.36 (Chrome/)`
   - galaxy S6 is OK
     `AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Mobile Safari/537.36 (Chrome/)`
  */
	me.isBadAndroid = (function() {
		var appVersion = window.navigator.appVersion;
		// Android browser is not a chrome browser.
		if (/Android/.test(appVersion) && !(/Chrome\/\d/.test(appVersion))) {
			var safariVersion = appVersion.match(/Safari\/(\d+.\d)/);
			if(safariVersion && typeof safariVersion === "object" && safariVersion.length >= 2) {
				return parseFloat(safariVersion[1]) < 535.19;
			} else {
				return true;
			}
		} else {
			return false;
		}
	})();

	me.extend(me.style = {}, {
		transform: _transform,
		transitionTimingFunction: _prefixStyle('transitionTimingFunction'),
		transitionDuration: _prefixStyle('transitionDuration'),
		transitionDelay: _prefixStyle('transitionDelay'),
		transformOrigin: _prefixStyle('transformOrigin'),
		touchAction: _prefixStyle('touchAction')
	});

	me.hasClass = function (e, c) {
		var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
		return re.test(e.className);
	};

	me.addClass = function (e, c) {
		if ( me.hasClass(e, c) ) {
			return;
		}

		var newclass = e.className.split(' ');
		newclass.push(c);
		e.className = newclass.join(' ');
	};

	me.removeClass = function (e, c) {
		if ( !me.hasClass(e, c) ) {
			return;
		}

		var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g');
		e.className = e.className.replace(re, ' ');
	};

	me.offset = function (el) {
		var left = -el.offsetLeft,
			top = -el.offsetTop;

		// jshint -W084
		while (el = el.offsetParent) {
			left -= el.offsetLeft;
			top -= el.offsetTop;
		}
		// jshint +W084

		return {
			left: left,
			top: top
		};
	};

	me.preventDefaultException = function (el, exceptions) {
		for ( var i in exceptions ) {
			if ( exceptions[i].test(el[i]) ) {
				return true;
			}
		}

		return false;
	};

	me.extend(me.eventType = {}, {
		touchstart: 1,
		touchmove: 1,
		touchend: 1,

		mousedown: 2,
		mousemove: 2,
		mouseup: 2,

		pointerdown: 3,
		pointermove: 3,
		pointerup: 3,

		MSPointerDown: 3,
		MSPointerMove: 3,
		MSPointerUp: 3
	});

	me.extend(me.ease = {}, {
		quadratic: {
			style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
			fn: function (k) {
				return k * ( 2 - k );
			}
		},
		circular: {
			style: 'cubic-bezier(0.1, 0.57, 0.1, 1)',	// Not properly "circular" but this looks better, it should be (0.075, 0.82, 0.165, 1)
			fn: function (k) {
				return Math.sqrt( 1 - ( --k * k ) );
			}
		},
		back: {
			style: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)',
			fn: function (k) {
				var b = 4;
				return ( k = k - 1 ) * k * ( ( b + 1 ) * k + b ) + 1;
			}
		},
		bounce: {
			style: '',
			fn: function (k) {
				if ( ( k /= 1 ) < ( 1 / 2.75 ) ) {
					return 7.5625 * k * k;
				} else if ( k < ( 2 / 2.75 ) ) {
					return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
				} else if ( k < ( 2.5 / 2.75 ) ) {
					return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
				} else {
					return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
				}
			}
		},
		elastic: {
			style: '',
			fn: function (k) {
				var f = 0.22,
					e = 0.4;

				if ( k === 0 ) { return 0; }
				if ( k == 1 ) { return 1; }

				return ( e * Math.pow( 2, - 10 * k ) * Math.sin( ( k - f / 4 ) * ( 2 * Math.PI ) / f ) + 1 );
			}
		}
	});

	me.tap = function (e, eventName) {
		var ev = document.createEvent('Event');
		ev.initEvent(eventName, true, true);
		ev.pageX = e.pageX;
		ev.pageY = e.pageY;
		e.target.dispatchEvent(ev);
	};

	me.click = function (e) {
		var target = e.target,
			ev;

		if ( !(/(SELECT|INPUT|TEXTAREA)/i).test(target.tagName) ) {
			// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent
			// initMouseEvent is deprecated.
			ev = document.createEvent(window.MouseEvent ? 'MouseEvents' : 'Event');
			ev.initEvent('click', true, true);
			ev.view = e.view || window;
			ev.detail = 1;
			ev.screenX = target.screenX || 0;
			ev.screenY = target.screenY || 0;
			ev.clientX = target.clientX || 0;
			ev.clientY = target.clientY || 0;
			ev.ctrlKey = !!e.ctrlKey;
			ev.altKey = !!e.altKey;
			ev.shiftKey = !!e.shiftKey;
			ev.metaKey = !!e.metaKey;
			ev.button = 0;
			ev.relatedTarget = null;
			ev._constructed = true;
			target.dispatchEvent(ev);
		}
	};

	me.getTouchAction = function(eventPassthrough, addPinch) {
		var touchAction = 'none';
		if ( eventPassthrough === 'vertical' ) {
			touchAction = 'pan-y';
		} else if (eventPassthrough === 'horizontal' ) {
			touchAction = 'pan-x';
		}
		if (addPinch && touchAction != 'none') {
			// add pinch-zoom support if the browser supports it, but if not (eg. Chrome <55) do nothing
			touchAction += ' pinch-zoom';
		}
		return touchAction;
	};

	me.getRect = function(el) {
		if (el instanceof SVGElement) {
			var rect = el.getBoundingClientRect();
			return {
				top : rect.top,
				left : rect.left,
				width : rect.width,
				height : rect.height
			};
		} else {
			return {
				top : el.offsetTop,
				left : el.offsetLeft,
				width : el.offsetWidth,
				height : el.offsetHeight
			};
		}
	};

	return me;
})();
function IScroll (el, options) {
	this.wrapper = typeof el == 'string' ? document.querySelector(el) : el;
	this.scroller = this.wrapper.children[0];
	this.scrollerStyle = this.scroller.style;		// cache style for better performance

	this.options = {

		resizeScrollbars: true,

		mouseWheelSpeed: 20,

		snapThreshold: 0.334,

// INSERT POINT: OPTIONS
		disablePointer : !utils.hasPointer,
		disableTouch : utils.hasPointer || !utils.hasTouch,
		disableMouse : utils.hasPointer || utils.hasTouch,
		startX: 0,
		startY: 0,
		scrollY: true,
		directionLockThreshold: 5,
		momentum: true,

		bounce: true,
		bounceTime: 600,
		bounceEasing: '',

		preventDefault: true,
		preventDefaultException: { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/ },

		HWCompositing: true,
		useTransition: true,
		useTransform: true,
		bindToWrapper: typeof window.onmousedown === "undefined"
	};

	for ( var i in options ) {
		this.options[i] = options[i];
	}

	// Normalize options
	this.translateZ = this.options.HWCompositing && utils.hasPerspective ? ' translateZ(0)' : '';

	this.options.useTransition = utils.hasTransition && this.options.useTransition;
	this.options.useTransform = utils.hasTransform && this.options.useTransform;

	this.options.eventPassthrough = this.options.eventPassthrough === true ? 'vertical' : this.options.eventPassthrough;
	this.options.preventDefault = !this.options.eventPassthrough && this.options.preventDefault;

	// If you want eventPassthrough I have to lock one of the axes
	this.options.scrollY = this.options.eventPassthrough == 'vertical' ? false : this.options.scrollY;
	this.options.scrollX = this.options.eventPassthrough == 'horizontal' ? false : this.options.scrollX;

	// With eventPassthrough we also need lockDirection mechanism
	this.options.freeScroll = this.options.freeScroll && !this.options.eventPassthrough;
	this.options.directionLockThreshold = this.options.eventPassthrough ? 0 : this.options.directionLockThreshold;

	this.options.bounceEasing = typeof this.options.bounceEasing == 'string' ? utils.ease[this.options.bounceEasing] || utils.ease.circular : this.options.bounceEasing;

	this.options.resizePolling = this.options.resizePolling === undefined ? 60 : this.options.resizePolling;

	if ( this.options.tap === true ) {
		this.options.tap = 'tap';
	}

	// https://github.com/cubiq/iscroll/issues/1029
	if (!this.options.useTransition && !this.options.useTransform) {
		if(!(/relative|absolute/i).test(this.scrollerStyle.position)) {
			this.scrollerStyle.position = "relative";
		}
	}

	if ( this.options.shrinkScrollbars == 'scale' ) {
		this.options.useTransition = false;
	}

	this.options.invertWheelDirection = this.options.invertWheelDirection ? -1 : 1;

// INSERT POINT: NORMALIZATION

	// Some defaults
	this.x = 0;
	this.y = 0;
	this.directionX = 0;
	this.directionY = 0;
	this._events = {};

// INSERT POINT: DEFAULTS

	this._init();
	this.refresh();

	this.scrollTo(this.options.startX, this.options.startY);
	this.enable();
}

IScroll.prototype = {
	version: '5.2.0-snapshot',

	_init: function () {
		this._initEvents();

		if ( this.options.scrollbars || this.options.indicators ) {
			this._initIndicators();
		}

		if ( this.options.mouseWheel ) {
			this._initWheel();
		}

		if ( this.options.snap ) {
			this._initSnap();
		}

		if ( this.options.keyBindings ) {
			this._initKeys();
		}

// INSERT POINT: _init

	},

	destroy: function () {
		this._initEvents(true);
		clearTimeout(this.resizeTimeout);
 		this.resizeTimeout = null;
		this._execEvent('destroy');
	},

	_transitionEnd: function (e) {
		if ( e.target != this.scroller || !this.isInTransition ) {
			return;
		}

		this._transitionTime();
		if ( !this.resetPosition(this.options.bounceTime) ) {
			this.isInTransition = false;
			this._execEvent('scrollEnd');
		}
	},

	_start: function (e) {
		// React to left mouse button only
		if ( utils.eventType[e.type] != 1 ) {
		  // for button property
		  // http://unixpapa.com/js/mouse.html
		  var button;
	    if (!e.which) {
	      /* IE case */
	      button = (e.button < 2) ? 0 :
	               ((e.button == 4) ? 1 : 2);
	    } else {
	      /* All others */
	      button = e.button;
	    }
			if ( button !== 0 ) {
				return;
			}
		}

		if ( !this.enabled || (this.initiated && utils.eventType[e.type] !== this.initiated) ) {
			return;
		}

		if ( this.options.preventDefault && !utils.isBadAndroid && !utils.preventDefaultException(e.target, this.options.preventDefaultException) ) {
			e.preventDefault();
		}

		var point = e.touches ? e.touches[0] : e,
			pos;

		this.initiated	= utils.eventType[e.type];
		this.moved		= false;
		this.distX		= 0;
		this.distY		= 0;
		this.directionX = 0;
		this.directionY = 0;
		this.directionLocked = 0;

		this.startTime = utils.getTime();

		if ( this.options.useTransition && this.isInTransition ) {
			this._transitionTime();
			this.isInTransition = false;
			pos = this.getComputedPosition();
			this._translate(Math.round(pos.x), Math.round(pos.y));
			this._execEvent('scrollEnd');
		} else if ( !this.options.useTransition && this.isAnimating ) {
			this.isAnimating = false;
			this._execEvent('scrollEnd');
		}

		this.startX    = this.x;
		this.startY    = this.y;
		this.absStartX = this.x;
		this.absStartY = this.y;
		this.pointX    = point.pageX;
		this.pointY    = point.pageY;

		this._execEvent('beforeScrollStart');
	},

	_move: function (e) {
		if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) {
			return;
		}

		if ( this.options.preventDefault ) {	// increases performance on Android? TODO: check!
			e.preventDefault();
		}

		var point		= e.touches ? e.touches[0] : e,
			deltaX		= point.pageX - this.pointX,
			deltaY		= point.pageY - this.pointY,
			timestamp	= utils.getTime(),
			newX, newY,
			absDistX, absDistY;

		this.pointX		= point.pageX;
		this.pointY		= point.pageY;

		this.distX		+= deltaX;
		this.distY		+= deltaY;
		absDistX		= Math.abs(this.distX);
		absDistY		= Math.abs(this.distY);

		// We need to move at least 10 pixels for the scrolling to initiate
		if ( timestamp - this.endTime > 300 && (absDistX < 10 && absDistY < 10) ) {
			return;
		}

		// If you are scrolling in one direction lock the other
		if ( !this.directionLocked && !this.options.freeScroll ) {
			if ( absDistX > absDistY + this.options.directionLockThreshold ) {
				this.directionLocked = 'h';		// lock horizontally
			} else if ( absDistY >= absDistX + this.options.directionLockThreshold ) {
				this.directionLocked = 'v';		// lock vertically
			} else {
				this.directionLocked = 'n';		// no lock
			}
		}

		if ( this.directionLocked == 'h' ) {
			if ( this.options.eventPassthrough == 'vertical' ) {
				e.preventDefault();
			} else if ( this.options.eventPassthrough == 'horizontal' ) {
				this.initiated = false;
				return;
			}

			deltaY = 0;
		} else if ( this.directionLocked == 'v' ) {
			if ( this.options.eventPassthrough == 'horizontal' ) {
				e.preventDefault();
			} else if ( this.options.eventPassthrough == 'vertical' ) {
				this.initiated = false;
				return;
			}

			deltaX = 0;
		}

		deltaX = this.hasHorizontalScroll ? deltaX : 0;
		deltaY = this.hasVerticalScroll ? deltaY : 0;

		newX = this.x + deltaX;
		newY = this.y + deltaY;

		// Slow down if outside of the boundaries
		if ( newX > 0 || newX < this.maxScrollX ) {
			newX = this.options.bounce ? this.x + deltaX / 3 : newX > 0 ? 0 : this.maxScrollX;
		}
		if ( newY > 0 || newY < this.maxScrollY ) {
			newY = this.options.bounce ? this.y + deltaY / 3 : newY > 0 ? 0 : this.maxScrollY;
		}

		this.directionX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
		this.directionY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;

		if ( !this.moved ) {
			this._execEvent('scrollStart');
		}

		this.moved = true;

		this._translate(newX, newY);

/* REPLACE START: _move */

		if ( timestamp - this.startTime > 300 ) {
			this.startTime = timestamp;
			this.startX = this.x;
			this.startY = this.y;
		}

/* REPLACE END: _move */

	},

	_end: function (e) {
		if ( !this.enabled || utils.eventType[e.type] !== this.initiated ) {
			return;
		}

		if ( this.options.preventDefault && !utils.preventDefaultException(e.target, this.options.preventDefaultException) ) {
			e.preventDefault();
		}

		var point = e.changedTouches ? e.changedTouches[0] : e,
			momentumX,
			momentumY,
			duration = utils.getTime() - this.startTime,
			newX = Math.round(this.x),
			newY = Math.round(this.y),
			distanceX = Math.abs(newX - this.startX),
			distanceY = Math.abs(newY - this.startY),
			time = 0,
			easing = '';

		this.isInTransition = 0;
		this.initiated = 0;
		this.endTime = utils.getTime();

		// reset if we are outside of the boundaries
		if ( this.resetPosition(this.options.bounceTime) ) {
			return;
		}

		this.scrollTo(newX, newY);	// ensures that the last position is rounded

		// we scrolled less than 10 pixels
		if ( !this.moved ) {
			if ( this.options.tap ) {
				utils.tap(e, this.options.tap);
			}

			if ( this.options.click ) {
				utils.click(e);
			}

			this._execEvent('scrollCancel');
			return;
		}

		if ( this._events.flick && duration < 200 && distanceX < 100 && distanceY < 100 ) {
			this._execEvent('flick');
			return;
		}

		// start momentum animation if needed
		if ( this.options.momentum && duration < 300 ) {
			momentumX = this.hasHorizontalScroll ? utils.momentum(this.x, this.startX, duration, this.maxScrollX, this.options.bounce ? this.wrapperWidth : 0, this.options.deceleration) : { destination: newX, duration: 0 };
			momentumY = this.hasVerticalScroll ? utils.momentum(this.y, this.startY, duration, this.maxScrollY, this.options.bounce ? this.wrapperHeight : 0, this.options.deceleration) : { destination: newY, duration: 0 };
			newX = momentumX.destination;
			newY = momentumY.destination;
			time = Math.max(momentumX.duration, momentumY.duration);
			this.isInTransition = 1;
		}


		if ( this.options.snap ) {
			var snap = this._nearestSnap(newX, newY);
			this.currentPage = snap;
			time = this.options.snapSpeed || Math.max(
					Math.max(
						Math.min(Math.abs(newX - snap.x), 1000),
						Math.min(Math.abs(newY - snap.y), 1000)
					), 300);
			newX = snap.x;
			newY = snap.y;

			this.directionX = 0;
			this.directionY = 0;
			easing = this.options.bounceEasing;
		}

// INSERT POINT: _end

		if ( newX != this.x || newY != this.y ) {
			// change easing function when scroller goes out of the boundaries
			if ( newX > 0 || newX < this.maxScrollX || newY > 0 || newY < this.maxScrollY ) {
				easing = utils.ease.quadratic;
			}

			this.scrollTo(newX, newY, time, easing);
			return;
		}

		this._execEvent('scrollEnd');
	},

	_resize: function () {
		var that = this;

		clearTimeout(this.resizeTimeout);

		this.resizeTimeout = setTimeout(function () {
			that.refresh();
		}, this.options.resizePolling);
	},

	resetPosition: function (time) {
		var x = this.x,
			y = this.y;

		time = time || 0;

		if ( !this.hasHorizontalScroll || this.x > 0 ) {
			x = 0;
		} else if ( this.x < this.maxScrollX ) {
			x = this.maxScrollX;
		}

		if ( !this.hasVerticalScroll || this.y > 0 ) {
			y = 0;
		} else if ( this.y < this.maxScrollY ) {
			y = this.maxScrollY;
		}

		if ( x == this.x && y == this.y ) {
			return false;
		}

		this.scrollTo(x, y, time, this.options.bounceEasing);

		return true;
	},

	disable: function () {
		this.enabled = false;
	},

	enable: function () {
		this.enabled = true;
	},

	refresh: function () {
		utils.getRect(this.wrapper);		// Force reflow

		this.wrapperWidth	= this.wrapper.clientWidth;
		this.wrapperHeight	= this.wrapper.clientHeight;

		var rect = utils.getRect(this.scroller);
/* REPLACE START: refresh */

		this.scrollerWidth	= rect.width;
		this.scrollerHeight	= rect.height;

		this.maxScrollX		= this.wrapperWidth - this.scrollerWidth;
		this.maxScrollY		= this.wrapperHeight - this.scrollerHeight;

/* REPLACE END: refresh */

		this.hasHorizontalScroll	= this.options.scrollX && this.maxScrollX < 0;
		this.hasVerticalScroll		= this.options.scrollY && this.maxScrollY < 0;
		
		if ( !this.hasHorizontalScroll ) {
			this.maxScrollX = 0;
			this.scrollerWidth = this.wrapperWidth;
		}

		if ( !this.hasVerticalScroll ) {
			this.maxScrollY = 0;
			this.scrollerHeight = this.wrapperHeight;
		}

		this.endTime = 0;
		this.directionX = 0;
		this.directionY = 0;
		
		if(utils.hasPointer && !this.options.disablePointer) {
			// The wrapper should have `touchAction` property for using pointerEvent.
			this.wrapper.style[utils.style.touchAction] = utils.getTouchAction(this.options.eventPassthrough, true);

			// case. not support 'pinch-zoom'
			// https://github.com/cubiq/iscroll/issues/1118#issuecomment-270057583
			if (!this.wrapper.style[utils.style.touchAction]) {
				this.wrapper.style[utils.style.touchAction] = utils.getTouchAction(this.options.eventPassthrough, false);
			}
		}
		this.wrapperOffset = utils.offset(this.wrapper);

		this._execEvent('refresh');

		this.resetPosition();

// INSERT POINT: _refresh

	},	

	on: function (type, fn) {
		if ( !this._events[type] ) {
			this._events[type] = [];
		}

		this._events[type].push(fn);
	},

	off: function (type, fn) {
		if ( !this._events[type] ) {
			return;
		}

		var index = this._events[type].indexOf(fn);

		if ( index > -1 ) {
			this._events[type].splice(index, 1);
		}
	},

	_execEvent: function (type) {
		if ( !this._events[type] ) {
			return;
		}

		var i = 0,
			l = this._events[type].length;

		if ( !l ) {
			return;
		}

		for ( ; i < l; i++ ) {
			this._events[type][i].apply(this, [].slice.call(arguments, 1));
		}
	},

	scrollBy: function (x, y, time, easing) {
		x = this.x + x;
		y = this.y + y;
		time = time || 0;

		this.scrollTo(x, y, time, easing);
	},

	scrollTo: function (x, y, time, easing) {
		easing = easing || utils.ease.circular;

		this.isInTransition = this.options.useTransition && time > 0;
		var transitionType = this.options.useTransition && easing.style;
		if ( !time || transitionType ) {
				if(transitionType) {
					this._transitionTimingFunction(easing.style);
					this._transitionTime(time);
				}
			this._translate(x, y);
		} else {
			this._animate(x, y, time, easing.fn);
		}
	},

	scrollToElement: function (el, time, offsetX, offsetY, easing) {
		el = el.nodeType ? el : this.scroller.querySelector(el);

		if ( !el ) {
			return;
		}

		var pos = utils.offset(el);

		pos.left -= this.wrapperOffset.left;
		pos.top  -= this.wrapperOffset.top;

		// if offsetX/Y are true we center the element to the screen
		var elRect = utils.getRect(el);
		var wrapperRect = utils.getRect(this.wrapper);
		if ( offsetX === true ) {
			offsetX = Math.round(elRect.width / 2 - wrapperRect.width / 2);
		}
		if ( offsetY === true ) {
			offsetY = Math.round(elRect.height / 2 - wrapperRect.height / 2);
		}

		pos.left -= offsetX || 0;
		pos.top  -= offsetY || 0;

		pos.left = pos.left > 0 ? 0 : pos.left < this.maxScrollX ? this.maxScrollX : pos.left;
		pos.top  = pos.top  > 0 ? 0 : pos.top  < this.maxScrollY ? this.maxScrollY : pos.top;

		time = time === undefined || time === null || time === 'auto' ? Math.max(Math.abs(this.x-pos.left), Math.abs(this.y-pos.top)) : time;

		this.scrollTo(pos.left, pos.top, time, easing);
	},

	_transitionTime: function (time) {
		if (!this.options.useTransition) {
			return;
		}
		time = time || 0;
		var durationProp = utils.style.transitionDuration;
		if(!durationProp) {
			return;
		}

		this.scrollerStyle[durationProp] = time + 'ms';

		if ( !time && utils.isBadAndroid ) {
			this.scrollerStyle[durationProp] = '0.0001ms';
			// remove 0.0001ms
			var self = this;
			rAF(function() {
				if(self.scrollerStyle[durationProp] === '0.0001ms') {
					self.scrollerStyle[durationProp] = '0s';
				}
			});
		}


		if ( this.indicators ) {
			for ( var i = this.indicators.length; i--; ) {
				this.indicators[i].transitionTime(time);
			}
		}


// INSERT POINT: _transitionTime

	},

	_transitionTimingFunction: function (easing) {
		this.scrollerStyle[utils.style.transitionTimingFunction] = easing;


		if ( this.indicators ) {
			for ( var i = this.indicators.length; i--; ) {
				this.indicators[i].transitionTimingFunction(easing);
			}
		}


// INSERT POINT: _transitionTimingFunction

	},

	_translate: function (x, y) {
		if ( this.options.useTransform ) {

/* REPLACE START: _translate */

			this.scrollerStyle[utils.style.transform] = 'translate(' + x + 'px,' + y + 'px)' + this.translateZ;

/* REPLACE END: _translate */

		} else {
			x = Math.round(x);
			y = Math.round(y);
			this.scrollerStyle.left = x + 'px';
			this.scrollerStyle.top = y + 'px';
		}

		this.x = x;
		this.y = y;


	if ( this.indicators ) {
		for ( var i = this.indicators.length; i--; ) {
			this.indicators[i].updatePosition();
		}
	}


// INSERT POINT: _translate

	},

	_initEvents: function (remove) {
		var eventType = remove ? utils.removeEvent : utils.addEvent,
			target = this.options.bindToWrapper ? this.wrapper : window;

		eventType(window, 'orientationchange', this);
		eventType(window, 'resize', this);

		if ( this.options.click ) {
			eventType(this.wrapper, 'click', this, true);
		}

		if ( !this.options.disableMouse ) {
			eventType(this.wrapper, 'mousedown', this);
			eventType(target, 'mousemove', this);
			eventType(target, 'mousecancel', this);
			eventType(target, 'mouseup', this);
		}

		if ( utils.hasPointer && !this.options.disablePointer ) {
			eventType(this.wrapper, utils.prefixPointerEvent('pointerdown'), this);
			eventType(target, utils.prefixPointerEvent('pointermove'), this);
			eventType(target, utils.prefixPointerEvent('pointercancel'), this);
			eventType(target, utils.prefixPointerEvent('pointerup'), this);
		}

		if ( utils.hasTouch && !this.options.disableTouch ) {
			eventType(this.wrapper, 'touchstart', this);
			eventType(target, 'touchmove', this);
			eventType(target, 'touchcancel', this);
			eventType(target, 'touchend', this);
		}

		eventType(this.scroller, 'transitionend', this);
		eventType(this.scroller, 'webkitTransitionEnd', this);
		eventType(this.scroller, 'oTransitionEnd', this);
		eventType(this.scroller, 'MSTransitionEnd', this);
	},

	getComputedPosition: function () {
		var matrix = window.getComputedStyle(this.scroller, null),
			x, y;

		if ( this.options.useTransform ) {
			matrix = matrix[utils.style.transform].split(')')[0].split(', ');
			x = +(matrix[12] || matrix[4]);
			y = +(matrix[13] || matrix[5]);
		} else {
			x = +matrix.left.replace(/[^-\d.]/g, '');
			y = +matrix.top.replace(/[^-\d.]/g, '');
		}

		return { x: x, y: y };
	},
	_initIndicators: function () {
		var interactive = this.options.interactiveScrollbars,
			customStyle = typeof this.options.scrollbars != 'string',
			indicators = [],
			indicator;

		var that = this;

		this.indicators = [];

		if ( this.options.scrollbars ) {
			// Vertical scrollbar
			if ( this.options.scrollY ) {
				indicator = {
					el: createDefaultScrollbar('v', interactive, this.options.scrollbars),
					interactive: interactive,
					defaultScrollbars: true,
					customStyle: customStyle,
					resize: this.options.resizeScrollbars,
					shrink: this.options.shrinkScrollbars,
					fade: this.options.fadeScrollbars,
					listenX: false
				};

				this.wrapper.appendChild(indicator.el);
				indicators.push(indicator);
			}

			// Horizontal scrollbar
			if ( this.options.scrollX ) {
				indicator = {
					el: createDefaultScrollbar('h', interactive, this.options.scrollbars),
					interactive: interactive,
					defaultScrollbars: true,
					customStyle: customStyle,
					resize: this.options.resizeScrollbars,
					shrink: this.options.shrinkScrollbars,
					fade: this.options.fadeScrollbars,
					listenY: false
				};

				this.wrapper.appendChild(indicator.el);
				indicators.push(indicator);
			}
		}

		if ( this.options.indicators ) {
			// TODO: check concat compatibility
			indicators = indicators.concat(this.options.indicators);
		}

		for ( var i = indicators.length; i--; ) {
			this.indicators.push( new Indicator(this, indicators[i]) );
		}

		// TODO: check if we can use array.map (wide compatibility and performance issues)
		function _indicatorsMap (fn) {
			if (that.indicators) {
				for ( var i = that.indicators.length; i--; ) {
					fn.call(that.indicators[i]);
				}
			}
		}

		if ( this.options.fadeScrollbars ) {
			this.on('scrollEnd', function () {
				_indicatorsMap(function () {
					this.fade();
				});
			});

			this.on('scrollCancel', function () {
				_indicatorsMap(function () {
					this.fade();
				});
			});

			this.on('scrollStart', function () {
				_indicatorsMap(function () {
					this.fade(1);
				});
			});

			this.on('beforeScrollStart', function () {
				_indicatorsMap(function () {
					this.fade(1, true);
				});
			});
		}


		this.on('refresh', function () {
			_indicatorsMap(function () {
				this.refresh();
			});
		});

		this.on('destroy', function () {
			_indicatorsMap(function () {
				this.destroy();
			});

			delete this.indicators;
		});
	},

	_initWheel: function () {
		utils.addEvent(this.wrapper, 'wheel', this);
		utils.addEvent(this.wrapper, 'mousewheel', this);
		utils.addEvent(this.wrapper, 'DOMMouseScroll', this);

		this.on('destroy', function () {
			clearTimeout(this.wheelTimeout);
			this.wheelTimeout = null;
			utils.removeEvent(this.wrapper, 'wheel', this);
			utils.removeEvent(this.wrapper, 'mousewheel', this);
			utils.removeEvent(this.wrapper, 'DOMMouseScroll', this);
		});
	},

	_wheel: function (e) {
		if ( !this.enabled ) {
			return;
		}

		e.preventDefault();

		var wheelDeltaX, wheelDeltaY,
			newX, newY,
			that = this;

		if ( this.wheelTimeout === undefined ) {
			that._execEvent('scrollStart');
		}

		// Execute the scrollEnd event after 400ms the wheel stopped scrolling
		clearTimeout(this.wheelTimeout);
		this.wheelTimeout = setTimeout(function () {
			if(!that.options.snap) {
				that._execEvent('scrollEnd');
			}
			that.wheelTimeout = undefined;
		}, 400);

		if ( 'deltaX' in e ) {
			if (e.deltaMode === 1) {
				wheelDeltaX = -e.deltaX * this.options.mouseWheelSpeed;
				wheelDeltaY = -e.deltaY * this.options.mouseWheelSpeed;
			} else {
				wheelDeltaX = -e.deltaX;
				wheelDeltaY = -e.deltaY;
			}
		} else if ( 'wheelDeltaX' in e ) {
			wheelDeltaX = e.wheelDeltaX / 120 * this.options.mouseWheelSpeed;
			wheelDeltaY = e.wheelDeltaY / 120 * this.options.mouseWheelSpeed;
		} else if ( 'wheelDelta' in e ) {
			wheelDeltaX = wheelDeltaY = e.wheelDelta / 120 * this.options.mouseWheelSpeed;
		} else if ( 'detail' in e ) {
			wheelDeltaX = wheelDeltaY = -e.detail / 3 * this.options.mouseWheelSpeed;
		} else {
			return;
		}

		wheelDeltaX *= this.options.invertWheelDirection;
		wheelDeltaY *= this.options.invertWheelDirection;

		if ( !this.hasVerticalScroll ) {
			wheelDeltaX = wheelDeltaY;
			wheelDeltaY = 0;
		}

		if ( this.options.snap ) {
			newX = this.currentPage.pageX;
			newY = this.currentPage.pageY;

			if ( wheelDeltaX > 0 ) {
				newX--;
			} else if ( wheelDeltaX < 0 ) {
				newX++;
			}

			if ( wheelDeltaY > 0 ) {
				newY--;
			} else if ( wheelDeltaY < 0 ) {
				newY++;
			}

			this.goToPage(newX, newY);

			return;
		}

		newX = this.x + Math.round(this.hasHorizontalScroll ? wheelDeltaX : 0);
		newY = this.y + Math.round(this.hasVerticalScroll ? wheelDeltaY : 0);

		this.directionX = wheelDeltaX > 0 ? -1 : wheelDeltaX < 0 ? 1 : 0;
		this.directionY = wheelDeltaY > 0 ? -1 : wheelDeltaY < 0 ? 1 : 0;

		if ( newX > 0 ) {
			newX = 0;
		} else if ( newX < this.maxScrollX ) {
			newX = this.maxScrollX;
		}

		if ( newY > 0 ) {
			newY = 0;
		} else if ( newY < this.maxScrollY ) {
			newY = this.maxScrollY;
		}

		this.scrollTo(newX, newY, 0);

// INSERT POINT: _wheel
	},

	_initSnap: function () {
		this.currentPage = {};

		if ( typeof this.options.snap == 'string' ) {
			this.options.snap = this.scroller.querySelectorAll(this.options.snap);
		}

		this.on('refresh', function () {
			var i = 0, l,
				m = 0, n,
				cx, cy,
				x = 0, y,
				stepX = this.options.snapStepX || this.wrapperWidth,
				stepY = this.options.snapStepY || this.wrapperHeight,
				el,
				rect;

			this.pages = [];

			if ( !this.wrapperWidth || !this.wrapperHeight || !this.scrollerWidth || !this.scrollerHeight ) {
				return;
			}

			if ( this.options.snap === true ) {
				cx = Math.round( stepX / 2 );
				cy = Math.round( stepY / 2 );

				while ( x > -this.scrollerWidth ) {
					this.pages[i] = [];
					l = 0;
					y = 0;

					while ( y > -this.scrollerHeight ) {
						this.pages[i][l] = {
							x: Math.max(x, this.maxScrollX),
							y: Math.max(y, this.maxScrollY),
							width: stepX,
							height: stepY,
							cx: x - cx,
							cy: y - cy
						};

						y -= stepY;
						l++;
					}

					x -= stepX;
					i++;
				}
			} else {
				el = this.options.snap;
				l = el.length;
				n = -1;

				for ( ; i < l; i++ ) {
					rect = utils.getRect(el[i]);
					if ( i === 0 || rect.left <= utils.getRect(el[i-1]).left ) {
						m = 0;
						n++;
					}

					if ( !this.pages[m] ) {
						this.pages[m] = [];
					}

					x = Math.max(-rect.left, this.maxScrollX);
					y = Math.max(-rect.top, this.maxScrollY);
					cx = x - Math.round(rect.width / 2);
					cy = y - Math.round(rect.height / 2);

					this.pages[m][n] = {
						x: x,
						y: y,
						width: rect.width,
						height: rect.height,
						cx: cx,
						cy: cy
					};

					if ( x > this.maxScrollX ) {
						m++;
					}
				}
			}

			this.goToPage(this.currentPage.pageX || 0, this.currentPage.pageY || 0, 0);

			// Update snap threshold if needed
			if ( this.options.snapThreshold % 1 === 0 ) {
				this.snapThresholdX = this.options.snapThreshold;
				this.snapThresholdY = this.options.snapThreshold;
			} else {
				this.snapThresholdX = Math.round(this.pages[this.currentPage.pageX][this.currentPage.pageY].width * this.options.snapThreshold);
				this.snapThresholdY = Math.round(this.pages[this.currentPage.pageX][this.currentPage.pageY].height * this.options.snapThreshold);
			}
		});

		this.on('flick', function () {
			var time = this.options.snapSpeed || Math.max(
					Math.max(
						Math.min(Math.abs(this.x - this.startX), 1000),
						Math.min(Math.abs(this.y - this.startY), 1000)
					), 300);

			this.goToPage(
				this.currentPage.pageX + this.directionX,
				this.currentPage.pageY + this.directionY,
				time
			);
		});
	},

	_nearestSnap: function (x, y) {
		if ( !this.pages.length ) {
			return { x: 0, y: 0, pageX: 0, pageY: 0 };
		}

		var i = 0,
			l = this.pages.length,
			m = 0;

		// Check if we exceeded the snap threshold
		if ( Math.abs(x - this.absStartX) < this.snapThresholdX &&
			Math.abs(y - this.absStartY) < this.snapThresholdY ) {
			return this.currentPage;
		}

		if ( x > 0 ) {
			x = 0;
		} else if ( x < this.maxScrollX ) {
			x = this.maxScrollX;
		}

		if ( y > 0 ) {
			y = 0;
		} else if ( y < this.maxScrollY ) {
			y = this.maxScrollY;
		}

		for ( ; i < l; i++ ) {
			if ( x >= this.pages[i][0].cx ) {
				x = this.pages[i][0].x;
				break;
			}
		}

		l = this.pages[i].length;

		for ( ; m < l; m++ ) {
			if ( y >= this.pages[0][m].cy ) {
				y = this.pages[0][m].y;
				break;
			}
		}

		if ( i == this.currentPage.pageX ) {
			i += this.directionX;

			if ( i < 0 ) {
				i = 0;
			} else if ( i >= this.pages.length ) {
				i = this.pages.length - 1;
			}

			x = this.pages[i][0].x;
		}

		if ( m == this.currentPage.pageY ) {
			m += this.directionY;

			if ( m < 0 ) {
				m = 0;
			} else if ( m >= this.pages[0].length ) {
				m = this.pages[0].length - 1;
			}

			y = this.pages[0][m].y;
		}

		return {
			x: x,
			y: y,
			pageX: i,
			pageY: m
		};
	},

	goToPage: function (x, y, time, easing) {
		easing = easing || this.options.bounceEasing;

		if ( x >= this.pages.length ) {
			x = this.pages.length - 1;
		} else if ( x < 0 ) {
			x = 0;
		}

		if ( y >= this.pages[x].length ) {
			y = this.pages[x].length - 1;
		} else if ( y < 0 ) {
			y = 0;
		}

		var posX = this.pages[x][y].x,
			posY = this.pages[x][y].y;

		time = time === undefined ? this.options.snapSpeed || Math.max(
			Math.max(
				Math.min(Math.abs(posX - this.x), 1000),
				Math.min(Math.abs(posY - this.y), 1000)
			), 300) : time;

		this.currentPage = {
			x: posX,
			y: posY,
			pageX: x,
			pageY: y
		};

		this.scrollTo(posX, posY, time, easing);
	},

	next: function (time, easing) {
		var x = this.currentPage.pageX,
			y = this.currentPage.pageY;

		x++;

		if ( x >= this.pages.length && this.hasVerticalScroll ) {
			x = 0;
			y++;
		}

		this.goToPage(x, y, time, easing);
	},

	prev: function (time, easing) {
		var x = this.currentPage.pageX,
			y = this.currentPage.pageY;

		x--;

		if ( x < 0 && this.hasVerticalScroll ) {
			x = 0;
			y--;
		}

		this.goToPage(x, y, time, easing);
	},

	_initKeys: function (e) {
		// default key bindings
		var keys = {
			pageUp: 33,
			pageDown: 34,
			end: 35,
			home: 36,
			left: 37,
			up: 38,
			right: 39,
			down: 40
		};
		var i;

		// if you give me characters I give you keycode
		if ( typeof this.options.keyBindings == 'object' ) {
			for ( i in this.options.keyBindings ) {
				if ( typeof this.options.keyBindings[i] == 'string' ) {
					this.options.keyBindings[i] = this.options.keyBindings[i].toUpperCase().charCodeAt(0);
				}
			}
		} else {
			this.options.keyBindings = {};
		}

		for ( i in keys ) {
			this.options.keyBindings[i] = this.options.keyBindings[i] || keys[i];
		}

		utils.addEvent(window, 'keydown', this);

		this.on('destroy', function () {
			utils.removeEvent(window, 'keydown', this);
		});
	},

	_key: function (e) {
		if ( !this.enabled ) {
			return;
		}

		var snap = this.options.snap,	// we are using this alot, better to cache it
			newX = snap ? this.currentPage.pageX : this.x,
			newY = snap ? this.currentPage.pageY : this.y,
			now = utils.getTime(),
			prevTime = this.keyTime || 0,
			acceleration = 0.250,
			pos;

		if ( this.options.useTransition && this.isInTransition ) {
			pos = this.getComputedPosition();

			this._translate(Math.round(pos.x), Math.round(pos.y));
			this.isInTransition = false;
		}

		this.keyAcceleration = now - prevTime < 200 ? Math.min(this.keyAcceleration + acceleration, 50) : 0;

		switch ( e.keyCode ) {
			case this.options.keyBindings.pageUp:
				if ( this.hasHorizontalScroll && !this.hasVerticalScroll ) {
					newX += snap ? 1 : this.wrapperWidth;
				} else {
					newY += snap ? 1 : this.wrapperHeight;
				}
				break;
			case this.options.keyBindings.pageDown:
				if ( this.hasHorizontalScroll && !this.hasVerticalScroll ) {
					newX -= snap ? 1 : this.wrapperWidth;
				} else {
					newY -= snap ? 1 : this.wrapperHeight;
				}
				break;
			case this.options.keyBindings.end:
				newX = snap ? this.pages.length-1 : this.maxScrollX;
				newY = snap ? this.pages[0].length-1 : this.maxScrollY;
				break;
			case this.options.keyBindings.home:
				newX = 0;
				newY = 0;
				break;
			case this.options.keyBindings.left:
				newX += snap ? -1 : 5 + this.keyAcceleration>>0;
				break;
			case this.options.keyBindings.up:
				newY += snap ? 1 : 5 + this.keyAcceleration>>0;
				break;
			case this.options.keyBindings.right:
				newX -= snap ? -1 : 5 + this.keyAcceleration>>0;
				break;
			case this.options.keyBindings.down:
				newY -= snap ? 1 : 5 + this.keyAcceleration>>0;
				break;
			default:
				return;
		}

		if ( snap ) {
			this.goToPage(newX, newY);
			return;
		}

		if ( newX > 0 ) {
			newX = 0;
			this.keyAcceleration = 0;
		} else if ( newX < this.maxScrollX ) {
			newX = this.maxScrollX;
			this.keyAcceleration = 0;
		}

		if ( newY > 0 ) {
			newY = 0;
			this.keyAcceleration = 0;
		} else if ( newY < this.maxScrollY ) {
			newY = this.maxScrollY;
			this.keyAcceleration = 0;
		}

		this.scrollTo(newX, newY, 0);

		this.keyTime = now;
	},

	_animate: function (destX, destY, duration, easingFn) {
		var that = this,
			startX = this.x,
			startY = this.y,
			startTime = utils.getTime(),
			destTime = startTime + duration;

		function step () {
			var now = utils.getTime(),
				newX, newY,
				easing;

			if ( now >= destTime ) {
				that.isAnimating = false;
				that._translate(destX, destY);

				if ( !that.resetPosition(that.options.bounceTime) ) {
					that._execEvent('scrollEnd');
				}

				return;
			}

			now = ( now - startTime ) / duration;
			easing = easingFn(now);
			newX = ( destX - startX ) * easing + startX;
			newY = ( destY - startY ) * easing + startY;
			that._translate(newX, newY);

			if ( that.isAnimating ) {
				rAF(step);
			}
		}

		this.isAnimating = true;
		step();
	},
	handleEvent: function (e) {
		switch ( e.type ) {
			case 'touchstart':
			case 'pointerdown':
			case 'MSPointerDown':
			case 'mousedown':
				this._start(e);
				break;
			case 'touchmove':
			case 'pointermove':
			case 'MSPointerMove':
			case 'mousemove':
				this._move(e);
				break;
			case 'touchend':
			case 'pointerup':
			case 'MSPointerUp':
			case 'mouseup':
			case 'touchcancel':
			case 'pointercancel':
			case 'MSPointerCancel':
			case 'mousecancel':
				this._end(e);
				break;
			case 'orientationchange':
			case 'resize':
				this._resize();
				break;
			case 'transitionend':
			case 'webkitTransitionEnd':
			case 'oTransitionEnd':
			case 'MSTransitionEnd':
				this._transitionEnd(e);
				break;
			case 'wheel':
			case 'DOMMouseScroll':
			case 'mousewheel':
				this._wheel(e);
				break;
			case 'keydown':
				this._key(e);
				break;
			case 'click':
				if (this.enabled && !e._constructed && $('.keyboard-user').length == 0) {
					e.preventDefault();
					e.stopPropagation();
				}
				break;
		}
	}
};
function createDefaultScrollbar (direction, interactive, type) {
	var scrollbar = document.createElement('div'),
		indicator = document.createElement('div');

	if ( type === true ) {
		scrollbar.style.cssText = 'position:absolute;z-index:9999';
		indicator.style.cssText = '-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);border-radius:3px';
	}

	indicator.className = 'iScrollIndicator';

	if ( direction == 'h' ) {
		if ( type === true ) {
			scrollbar.style.cssText += ';height:7px;left:2px;right:2px;bottom:0';
			indicator.style.height = '100%';
		}
		scrollbar.className = 'iScrollHorizontalScrollbar';
	} else {
		if ( type === true ) {
			scrollbar.style.cssText += ';width:7px;bottom:2px;top:2px;right:1px';
			indicator.style.width = '100%';
		}
		scrollbar.className = 'iScrollVerticalScrollbar';
	}

	scrollbar.style.cssText += ';overflow:hidden';

	if ( !interactive ) {
		scrollbar.style.pointerEvents = 'none';
	}

	scrollbar.appendChild(indicator);

	return scrollbar;
}

function Indicator (scroller, options) {
	this.wrapper = typeof options.el == 'string' ? document.querySelector(options.el) : options.el;
	this.wrapperStyle = this.wrapper.style;
	this.indicator = this.wrapper.children[0];
	this.indicatorStyle = this.indicator.style;
	this.scroller = scroller;

	this.options = {
		listenX: true,
		listenY: true,
		interactive: false,
		resize: true,
		defaultScrollbars: false,
		shrink: false,
		fade: false,
		speedRatioX: 0,
		speedRatioY: 0
	};

	for ( var i in options ) {
		this.options[i] = options[i];
	}

	this.sizeRatioX = 1;
	this.sizeRatioY = 1;
	this.maxPosX = 0;
	this.maxPosY = 0;

	if ( this.options.interactive ) {
		if ( !this.options.disableTouch ) {
			utils.addEvent(this.indicator, 'touchstart', this);
			utils.addEvent(window, 'touchend', this);
		}
		if ( !this.options.disablePointer ) {
			utils.addEvent(this.indicator, utils.prefixPointerEvent('pointerdown'), this);
			utils.addEvent(window, utils.prefixPointerEvent('pointerup'), this);
		}
		if ( !this.options.disableMouse ) {
			utils.addEvent(this.indicator, 'mousedown', this);
			utils.addEvent(window, 'mouseup', this);
		}
	}

	if ( this.options.fade ) {
		this.wrapperStyle[utils.style.transform] = this.scroller.translateZ;
		var durationProp = utils.style.transitionDuration;
		if(!durationProp) {
			return;
		}
		this.wrapperStyle[durationProp] = utils.isBadAndroid ? '0.0001ms' : '0ms';
		// remove 0.0001ms
		var self = this;
		if(utils.isBadAndroid) {
			rAF(function() {
				if(self.wrapperStyle[durationProp] === '0.0001ms') {
					self.wrapperStyle[durationProp] = '0s';
				}
			});
		}
		this.wrapperStyle.opacity = '0';
	}
}

Indicator.prototype = {
	handleEvent: function (e) {
		switch ( e.type ) {
			case 'touchstart':
			case 'pointerdown':
			case 'MSPointerDown':
			case 'mousedown':
				this._start(e);
				break;
			case 'touchmove':
			case 'pointermove':
			case 'MSPointerMove':
			case 'mousemove':
				this._move(e);
				break;
			case 'touchend':
			case 'pointerup':
			case 'MSPointerUp':
			case 'mouseup':
			case 'touchcancel':
			case 'pointercancel':
			case 'MSPointerCancel':
			case 'mousecancel':
				this._end(e);
				break;
		}
	},

	destroy: function () {
		if ( this.options.fadeScrollbars ) {
			clearTimeout(this.fadeTimeout);
			this.fadeTimeout = null;
		}
		if ( this.options.interactive ) {
			utils.removeEvent(this.indicator, 'touchstart', this);
			utils.removeEvent(this.indicator, utils.prefixPointerEvent('pointerdown'), this);
			utils.removeEvent(this.indicator, 'mousedown', this);

			utils.removeEvent(window, 'touchmove', this);
			utils.removeEvent(window, utils.prefixPointerEvent('pointermove'), this);
			utils.removeEvent(window, 'mousemove', this);

			utils.removeEvent(window, 'touchend', this);
			utils.removeEvent(window, utils.prefixPointerEvent('pointerup'), this);
			utils.removeEvent(window, 'mouseup', this);
		}

		if ( this.options.defaultScrollbars && this.wrapper.parentNode ) {
			this.wrapper.parentNode.removeChild(this.wrapper);
		}
	},

	_start: function (e) {
		var point = e.touches ? e.touches[0] : e;

		e.preventDefault();
		e.stopPropagation();

		this.transitionTime();

		this.initiated = true;
		this.moved = false;
		this.lastPointX	= point.pageX;
		this.lastPointY	= point.pageY;

		this.startTime	= utils.getTime();

		if ( !this.options.disableTouch ) {
			utils.addEvent(window, 'touchmove', this);
		}
		if ( !this.options.disablePointer ) {
			utils.addEvent(window, utils.prefixPointerEvent('pointermove'), this);
		}
		if ( !this.options.disableMouse ) {
			utils.addEvent(window, 'mousemove', this);
		}

		this.scroller._execEvent('beforeScrollStart');
	},

	_move: function (e) {
		var point = e.touches ? e.touches[0] : e,
			deltaX, deltaY,
			newX, newY,
			timestamp = utils.getTime();

		if ( !this.moved ) {
			this.scroller._execEvent('scrollStart');
		}

		this.moved = true;

		deltaX = point.pageX - this.lastPointX;
		this.lastPointX = point.pageX;

		deltaY = point.pageY - this.lastPointY;
		this.lastPointY = point.pageY;

		newX = this.x + deltaX;
		newY = this.y + deltaY;

		this._pos(newX, newY);

// INSERT POINT: indicator._move

		e.preventDefault();
		e.stopPropagation();
	},

	_end: function (e) {
		if ( !this.initiated ) {
			return;
		}

		this.initiated = false;

		e.preventDefault();
		e.stopPropagation();

		utils.removeEvent(window, 'touchmove', this);
		utils.removeEvent(window, utils.prefixPointerEvent('pointermove'), this);
		utils.removeEvent(window, 'mousemove', this);

		if ( this.scroller.options.snap ) {
			var snap = this.scroller._nearestSnap(this.scroller.x, this.scroller.y);

			var time = this.options.snapSpeed || Math.max(
					Math.max(
						Math.min(Math.abs(this.scroller.x - snap.x), 1000),
						Math.min(Math.abs(this.scroller.y - snap.y), 1000)
					), 300);

			if ( this.scroller.x != snap.x || this.scroller.y != snap.y ) {
				this.scroller.directionX = 0;
				this.scroller.directionY = 0;
				this.scroller.currentPage = snap;
				this.scroller.scrollTo(snap.x, snap.y, time, this.scroller.options.bounceEasing);
			}
		}

		if ( this.moved ) {
			this.scroller._execEvent('scrollEnd');
		}
	},

	transitionTime: function (time) {
		time = time || 0;
		var durationProp = utils.style.transitionDuration;
		if(!durationProp) {
			return;
		}

		this.indicatorStyle[durationProp] = time + 'ms';

		if ( !time && utils.isBadAndroid ) {
			this.indicatorStyle[durationProp] = '0.0001ms';
			// remove 0.0001ms
			var self = this;
			rAF(function() {
				if(self.indicatorStyle[durationProp] === '0.0001ms') {
					self.indicatorStyle[durationProp] = '0s';
				}
			});
		}
	},

	transitionTimingFunction: function (easing) {
		this.indicatorStyle[utils.style.transitionTimingFunction] = easing;
	},

	refresh: function () {
		this.transitionTime();

		if ( this.options.listenX && !this.options.listenY ) {
			this.indicatorStyle.display = this.scroller.hasHorizontalScroll ? 'block' : 'none';
		} else if ( this.options.listenY && !this.options.listenX ) {
			this.indicatorStyle.display = this.scroller.hasVerticalScroll ? 'block' : 'none';
		} else {
			this.indicatorStyle.display = this.scroller.hasHorizontalScroll || this.scroller.hasVerticalScroll ? 'block' : 'none';
		}

		if ( this.scroller.hasHorizontalScroll && this.scroller.hasVerticalScroll ) {
			utils.addClass(this.wrapper, 'iScrollBothScrollbars');
			utils.removeClass(this.wrapper, 'iScrollLoneScrollbar');

			if ( this.options.defaultScrollbars && this.options.customStyle ) {
				if ( this.options.listenX ) {
					this.wrapper.style.right = '8px';
				} else {
					this.wrapper.style.bottom = '8px';
				}
			}
		} else {
			utils.removeClass(this.wrapper, 'iScrollBothScrollbars');
			utils.addClass(this.wrapper, 'iScrollLoneScrollbar');

			if ( this.options.defaultScrollbars && this.options.customStyle ) {
				if ( this.options.listenX ) {
					this.wrapper.style.right = '2px';
				} else {
					this.wrapper.style.bottom = '2px';
				}
			}
		}

		utils.getRect(this.wrapper);	// force refresh

		if ( this.options.listenX ) {
			this.wrapperWidth = this.wrapper.clientWidth;
			if ( this.options.resize ) {
				this.indicatorWidth = Math.max(Math.round(this.wrapperWidth * this.wrapperWidth / (this.scroller.scrollerWidth || this.wrapperWidth || 1)), 8);
				this.indicatorStyle.width = this.indicatorWidth + 'px';
			} else {
				this.indicatorWidth = this.indicator.clientWidth;
			}

			this.maxPosX = this.wrapperWidth - this.indicatorWidth;

			if ( this.options.shrink == 'clip' ) {
				this.minBoundaryX = -this.indicatorWidth + 8;
				this.maxBoundaryX = this.wrapperWidth - 8;
			} else {
				this.minBoundaryX = 0;
				this.maxBoundaryX = this.maxPosX;
			}

			this.sizeRatioX = this.options.speedRatioX || (this.scroller.maxScrollX && (this.maxPosX / this.scroller.maxScrollX));
		}

		if ( this.options.listenY ) {
			this.wrapperHeight = this.wrapper.clientHeight;
			if ( this.options.resize ) {
				this.indicatorHeight = Math.max(Math.round(this.wrapperHeight * this.wrapperHeight / (this.scroller.scrollerHeight || this.wrapperHeight || 1)), 8);
				this.indicatorStyle.height = this.indicatorHeight + 'px';
			} else {
				this.indicatorHeight = this.indicator.clientHeight;
			}

			this.maxPosY = this.wrapperHeight - this.indicatorHeight;

			if ( this.options.shrink == 'clip' ) {
				this.minBoundaryY = -this.indicatorHeight + 8;
				this.maxBoundaryY = this.wrapperHeight - 8;
			} else {
				this.minBoundaryY = 0;
				this.maxBoundaryY = this.maxPosY;
			}

			this.maxPosY = this.wrapperHeight - this.indicatorHeight;
			this.sizeRatioY = this.options.speedRatioY || (this.scroller.maxScrollY && (this.maxPosY / this.scroller.maxScrollY));
		}

		this.updatePosition();
	},

	updatePosition: function () {
		var x = this.options.listenX && Math.round(this.sizeRatioX * this.scroller.x) || 0,
			y = this.options.listenY && Math.round(this.sizeRatioY * this.scroller.y) || 0;

		if ( !this.options.ignoreBoundaries ) {
			if ( x < this.minBoundaryX ) {
				if ( this.options.shrink == 'scale' ) {
					this.width = Math.max(this.indicatorWidth + x, 8);
					this.indicatorStyle.width = this.width + 'px';
				}
				x = this.minBoundaryX;
			} else if ( x > this.maxBoundaryX ) {
				if ( this.options.shrink == 'scale' ) {
					this.width = Math.max(this.indicatorWidth - (x - this.maxPosX), 8);
					this.indicatorStyle.width = this.width + 'px';
					x = this.maxPosX + this.indicatorWidth - this.width;
				} else {
					x = this.maxBoundaryX;
				}
			} else if ( this.options.shrink == 'scale' && this.width != this.indicatorWidth ) {
				this.width = this.indicatorWidth;
				this.indicatorStyle.width = this.width + 'px';
			}

			if ( y < this.minBoundaryY ) {
				if ( this.options.shrink == 'scale' ) {
					this.height = Math.max(this.indicatorHeight + y * 3, 8);
					this.indicatorStyle.height = this.height + 'px';
				}
				y = this.minBoundaryY;
			} else if ( y > this.maxBoundaryY ) {
				if ( this.options.shrink == 'scale' ) {
					this.height = Math.max(this.indicatorHeight - (y - this.maxPosY) * 3, 8);
					this.indicatorStyle.height = this.height + 'px';
					y = this.maxPosY + this.indicatorHeight - this.height;
				} else {
					y = this.maxBoundaryY;
				}
			} else if ( this.options.shrink == 'scale' && this.height != this.indicatorHeight ) {
				this.height = this.indicatorHeight;
				this.indicatorStyle.height = this.height + 'px';
			}
		}

		this.x = x;
		this.y = y;

		if ( this.scroller.options.useTransform ) {
			this.indicatorStyle[utils.style.transform] = 'translate(' + x + 'px,' + y + 'px)' + this.scroller.translateZ;
		} else {
			this.indicatorStyle.left = x + 'px';
			this.indicatorStyle.top = y + 'px';
		}
	},

	_pos: function (x, y) {
		if ( x < 0 ) {
			x = 0;
		} else if ( x > this.maxPosX ) {
			x = this.maxPosX;
		}

		if ( y < 0 ) {
			y = 0;
		} else if ( y > this.maxPosY ) {
			y = this.maxPosY;
		}

		x = this.options.listenX ? Math.round(x / this.sizeRatioX) : this.scroller.x;
		y = this.options.listenY ? Math.round(y / this.sizeRatioY) : this.scroller.y;

		this.scroller.scrollTo(x, y);
	},

	fade: function (val, hold) {
		if ( hold && !this.visible ) {
			return;
		}

		clearTimeout(this.fadeTimeout);
		this.fadeTimeout = null;

		var time = val ? 250 : 500,
			delay = val ? 0 : 300;

		val = val ? '1' : '0';

		this.wrapperStyle[utils.style.transitionDuration] = time + 'ms';

		this.fadeTimeout = setTimeout((function (val) {
			this.wrapperStyle.opacity = val;
			this.visible = +val;
		}).bind(this, val), delay);
	}
};

IScroll.utils = utils;

if ( typeof module != 'undefined' && module.exports ) {
	module.exports = IScroll;
} else if ( typeof define == 'function' && define.amd ) {
        define( function () { return IScroll; } );
} else {
	window.IScroll = IScroll;
}

})(window, document, Math);
;
;(function(){

	/**
	 * Require the module at `name`.
	 *
	 * @param {String} name
	 * @return {Object} exports
	 * @api public
	 */
	
	function require(name) {
	  var module = require.modules[name];
	  if (!module) throw new Error('failed to require "' + name + '"');
	
	  if (!('exports' in module) && typeof module.definition === 'function') {
		module.client = module.component = true;
		module.definition.call(this, module.exports = {}, module);
		delete module.definition;
	  }
	
	  return module.exports;
	}
	
	/**
	 * Meta info, accessible in the global scope unless you use AMD option.
	 */
	
	require.loader = 'component';
	
	/**
	 * Internal helper object, contains a sorting function for semantiv versioning
	 */
	require.helper = {};
	require.helper.semVerSort = function(a, b) {
	  var aArray = a.version.split('.');
	  var bArray = b.version.split('.');
	  for (var i=0; i<aArray.length; ++i) {
		var aInt = parseInt(aArray[i], 10);
		var bInt = parseInt(bArray[i], 10);
		if (aInt === bInt) {
		  var aLex = aArray[i].substr((""+aInt).length);
		  var bLex = bArray[i].substr((""+bInt).length);
		  if (aLex === '' && bLex !== '') return 1;
		  if (aLex !== '' && bLex === '') return -1;
		  if (aLex !== '' && bLex !== '') return aLex > bLex ? 1 : -1;
		  continue;
		} else if (aInt > bInt) {
		  return 1;
		} else {
		  return -1;
		}
	  }
	  return 0;
	}
	
	/**
	 * Find and require a module which name starts with the provided name.
	 * If multiple modules exists, the highest semver is used.
	 * This function can only be used for remote dependencies.
	
	 * @param {String} name - module name: `user~repo`
	 * @param {Boolean} returnPath - returns the canonical require path if true,
	 *                               otherwise it returns the epxorted module
	 */
	require.latest = function (name, returnPath) {
	  function showError(name) {
		throw new Error('failed to find latest module of "' + name + '"');
	  }
	  // only remotes with semvers, ignore local files conataining a '/'
	  var versionRegexp = /(.*)~(.*)@v?(\d+\.\d+\.\d+[^\/]*)$/;
	  var remoteRegexp = /(.*)~(.*)/;
	  if (!remoteRegexp.test(name)) showError(name);
	  var moduleNames = Object.keys(require.modules);
	  var semVerCandidates = [];
	  var otherCandidates = []; // for instance: name of the git branch
	  for (var i=0; i<moduleNames.length; i++) {
		var moduleName = moduleNames[i];
		if (new RegExp(name + '@').test(moduleName)) {
			var version = moduleName.substr(name.length+1);
			var semVerMatch = versionRegexp.exec(moduleName);
			if (semVerMatch != null) {
			  semVerCandidates.push({version: version, name: moduleName});
			} else {
			  otherCandidates.push({version: version, name: moduleName});
			}
		}
	  }
	  if (semVerCandidates.concat(otherCandidates).length === 0) {
		showError(name);
	  }
	  if (semVerCandidates.length > 0) {
		var module = semVerCandidates.sort(require.helper.semVerSort).pop().name;
		if (returnPath === true) {
		  return module;
		}
		return require(module);
	  }
	  // if the build contains more than one branch of the same module
	  // you should not use this funciton
	  var module = otherCandidates.sort(function(a, b) {return a.name > b.name})[0].name;
	  if (returnPath === true) {
		return module;
	  }
	  return require(module);
	}
	
	/**
	 * Registered modules.
	 */
	
	require.modules = {};
	
	/**
	 * Register module at `name` with callback `definition`.
	 *
	 * @param {String} name
	 * @param {Function} definition
	 * @api private
	 */
	
	require.register = function (name, definition) {
	  require.modules[name] = {
		definition: definition
	  };
	};
	
	/**
	 * Define a module's exports immediately with `exports`.
	 *
	 * @param {String} name
	 * @param {Generic} exports
	 * @api private
	 */
	
	require.define = function (name, exports) {
	  require.modules[name] = {
		exports: exports
	  };
	};
	require.register("abpetkov~transitionize@0.0.3", function (exports, module) {
	
	/**
	 * Transitionize 0.0.2
	 * https://github.com/abpetkov/transitionize
	 *
	 * Authored by Alexander Petkov
	 * https://github.com/abpetkov
	 *
	 * Copyright 2013, Alexander Petkov
	 * License: The MIT License (MIT)
	 * http://opensource.org/licenses/MIT
	 *
	 */
	
	/**
	 * Expose `Transitionize`.
	 */
	
	module.exports = Transitionize;
	
	/**
	 * Initialize new Transitionize.
	 *
	 * @param {Object} element
	 * @param {Object} props
	 * @api public
	 */
	
	function Transitionize(element, props) {
	  if (!(this instanceof Transitionize)) return new Transitionize(element, props);
	
	  this.element = element;
	  this.props = props || {};
	  this.init();
	}
	
	/**
	 * Detect if Safari.
	 *
	 * @returns {Boolean}
	 * @api private
	 */
	
	Transitionize.prototype.isSafari = function() {
	  return (/Safari/).test(navigator.userAgent) && (/Apple Computer/).test(navigator.vendor);
	};
	
	/**
	 * Loop though the object and push the keys and values in an array.
	 * Apply the CSS3 transition to the element and prefix with -webkit- for Safari.
	 *
	 * @api private
	 */
	
	Transitionize.prototype.init = function() {
	  var transitions = [];
	
	  for (var key in this.props) {
		transitions.push(key + ' ' + this.props[key]);
	  }
	
	  this.element.style.transition = transitions.join(', ');
	  if (this.isSafari()) this.element.style.webkitTransition = transitions.join(', ');
	};
	});
	
	require.register("ftlabs~fastclick@v0.6.11", function (exports, module) {
	/**
	 * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
	 *
	 * @version 0.6.11
	 * @codingstandard ftlabs-jsv2
	 * @copyright The Financial Times Limited [All Rights Reserved]
	 * @license MIT License (see LICENSE.txt)
	 */
	
	/*jslint browser:true, node:true*/
	/*global define, Event, Node*/
	
	
	/**
	 * Instantiate fast-clicking listeners on the specificed layer.
	 *
	 * @constructor
	 * @param {Element} layer The layer to listen on
	 */
	function FastClick(layer) {
		'use strict';
		var oldOnClick, self = this;
	
	
		/**
		 * Whether a click is currently being tracked.
		 *
		 * @type boolean
		 */
		this.trackingClick = false;
	
	
		/**
		 * Timestamp for when when click tracking started.
		 *
		 * @type number
		 */
		this.trackingClickStart = 0;
	
	
		/**
		 * The element being tracked for a click.
		 *
		 * @type EventTarget
		 */
		this.targetElement = null;
	
	
		/**
		 * X-coordinate of touch start event.
		 *
		 * @type number
		 */
		this.touchStartX = 0;
	
	
		/**
		 * Y-coordinate of touch start event.
		 *
		 * @type number
		 */
		this.touchStartY = 0;
	
	
		/**
		 * ID of the last touch, retrieved from Touch.identifier.
		 *
		 * @type number
		 */
		this.lastTouchIdentifier = 0;
	
	
		/**
		 * Touchmove boundary, beyond which a click will be cancelled.
		 *
		 * @type number
		 */
		this.touchBoundary = 10;
	
	
		/**
		 * The FastClick layer.
		 *
		 * @type Element
		 */
		this.layer = layer;
	
		if (!layer || !layer.nodeType) {
			throw new TypeError('Layer must be a document node');
		}
	
		/** @type function() */
		this.onClick = function() { return FastClick.prototype.onClick.apply(self, arguments); };
	
		/** @type function() */
		this.onMouse = function() { return FastClick.prototype.onMouse.apply(self, arguments); };
	
		/** @type function() */
		this.onTouchStart = function() { return FastClick.prototype.onTouchStart.apply(self, arguments); };
	
		/** @type function() */
		this.onTouchMove = function() { return FastClick.prototype.onTouchMove.apply(self, arguments); };
	
		/** @type function() */
		this.onTouchEnd = function() { return FastClick.prototype.onTouchEnd.apply(self, arguments); };
	
		/** @type function() */
		this.onTouchCancel = function() { return FastClick.prototype.onTouchCancel.apply(self, arguments); };
	
		if (FastClick.notNeeded(layer)) {
			return;
		}
	
		// Set up event handlers as required
		if (this.deviceIsAndroid) {
			layer.addEventListener('mouseover', this.onMouse, true);
			layer.addEventListener('mousedown', this.onMouse, true);
			layer.addEventListener('mouseup', this.onMouse, true);
		}
	
		layer.addEventListener('click', this.onClick, true);
		layer.addEventListener('touchstart', this.onTouchStart, false);
		layer.addEventListener('touchmove', this.onTouchMove, false);
		layer.addEventListener('touchend', this.onTouchEnd, false);
		layer.addEventListener('touchcancel', this.onTouchCancel, false);
	
		// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
		// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
		// layer when they are cancelled.
		if (!Event.prototype.stopImmediatePropagation) {
			layer.removeEventListener = function(type, callback, capture) {
				var rmv = Node.prototype.removeEventListener;
				if (type === 'click') {
					rmv.call(layer, type, callback.hijacked || callback, capture);
				} else {
					rmv.call(layer, type, callback, capture);
				}
			};
	
			layer.addEventListener = function(type, callback, capture) {
				var adv = Node.prototype.addEventListener;
				if (type === 'click') {
					adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
						if (!event.propagationStopped) {
							callback(event);
						}
					}), capture);
				} else {
					adv.call(layer, type, callback, capture);
				}
			};
		}
	
		// If a handler is already declared in the element's onclick attribute, it will be fired before
		// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
		// adding it as listener.
		if (typeof layer.onclick === 'function') {
	
			// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
			// - the old one won't work if passed to addEventListener directly.
			oldOnClick = layer.onclick;
			layer.addEventListener('click', function(event) {
				oldOnClick(event);
			}, false);
			layer.onclick = null;
		}
	}
	
	
	/**
	 * Android requires exceptions.
	 *
	 * @type boolean
	 */
	FastClick.prototype.deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0;
	
	
	/**
	 * iOS requires exceptions.
	 *
	 * @type boolean
	 */
	FastClick.prototype.deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
	
	
	/**
	 * iOS 4 requires an exception for select elements.
	 *
	 * @type boolean
	 */
	FastClick.prototype.deviceIsIOS4 = FastClick.prototype.deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
	
	
	/**
	 * iOS 6.0(+?) requires the target element to be manually derived
	 *
	 * @type boolean
	 */
	FastClick.prototype.deviceIsIOSWithBadTarget = FastClick.prototype.deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent);
	
	
	/**
	 * Determine whether a given element requires a native click.
	 *
	 * @param {EventTarget|Element} target Target DOM element
	 * @returns {boolean} Returns true if the element needs a native click
	 */
	FastClick.prototype.needsClick = function(target) {
		'use strict';
		switch (target.nodeName.toLowerCase()) {
	
		// Don't send a synthetic click to disabled inputs (issue #62)
		case 'button':
		case 'select':
		case 'textarea':
			if (target.disabled) {
				return true;
			}
	
			break;
		case 'input':
	
			// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
			if ((this.deviceIsIOS && target.type === 'file') || target.disabled) {
				return true;
			}
	
			break;
		case 'label':
		case 'video':
			return true;
		}
	
		return (/\bneedsclick\b/).test(target.className);
	};
	
	
	/**
	 * Determine whether a given element requires a call to focus to simulate click into element.
	 *
	 * @param {EventTarget|Element} target Target DOM element
	 * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
	 */
	FastClick.prototype.needsFocus = function(target) {
		'use strict';
		switch (target.nodeName.toLowerCase()) {
		case 'textarea':
			return true;
		case 'select':
			return !this.deviceIsAndroid;
		case 'input':
			switch (target.type) {
			case 'button':
			case 'checkbox':
			case 'file':
			case 'image':
			case 'radio':
			case 'submit':
				return false;
			}
	
			// No point in attempting to focus disabled inputs
			return !target.disabled && !target.readOnly;
		default:
			return (/\bneedsfocus\b/).test(target.className);
		}
	};
	
	
	/**
	 * Send a click event to the specified element.
	 *
	 * @param {EventTarget|Element} targetElement
	 * @param {Event} event
	 */
	FastClick.prototype.sendClick = function(targetElement, event) {
		'use strict';
		var clickEvent, touch;
	
		// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
		if (document.activeElement && document.activeElement !== targetElement) {
			document.activeElement.blur();
		}
	
		touch = event.changedTouches[0];
	
		// Synthesise a click event, with an extra attribute so it can be tracked
		clickEvent = document.createEvent('MouseEvents');
		clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
		clickEvent.forwardedTouchEvent = true;
		targetElement.dispatchEvent(clickEvent);
	};
	
	FastClick.prototype.determineEventType = function(targetElement) {
		'use strict';
	
		//Issue #159: Android Chrome Select Box does not open with a synthetic click event
		if (this.deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
			return 'mousedown';
		}
	
		return 'click';
	};
	
	
	/**
	 * @param {EventTarget|Element} targetElement
	 */
	FastClick.prototype.focus = function(targetElement) {
		'use strict';
		var length;
	
		// Issue #160: on iOS 7, some input elements (e.g. date datetime) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
		if (this.deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time') {
			length = targetElement.value.length;
			targetElement.setSelectionRange(length, length);
		} else {
			targetElement.focus();
		}
	};
	
	
	/**
	 * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
	 *
	 * @param {EventTarget|Element} targetElement
	 */
	FastClick.prototype.updateScrollParent = function(targetElement) {
		'use strict';
		var scrollParent, parentElement;
	
		scrollParent = targetElement.fastClickScrollParent;
	
		// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
		// target element was moved to another parent.
		if (!scrollParent || !scrollParent.contains(targetElement)) {
			parentElement = targetElement;
			do {
				if (parentElement.scrollHeight > parentElement.offsetHeight) {
					scrollParent = parentElement;
					targetElement.fastClickScrollParent = parentElement;
					break;
				}
	
				parentElement = parentElement.parentElement;
			} while (parentElement);
		}
	
		// Always update the scroll top tracker if possible.
		if (scrollParent) {
			scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
		}
	};
	
	
	/**
	 * @param {EventTarget} targetElement
	 * @returns {Element|EventTarget}
	 */
	FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
		'use strict';
	
		// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
		if (eventTarget.nodeType === Node.TEXT_NODE) {
			return eventTarget.parentNode;
		}
	
		return eventTarget;
	};
	
	
	/**
	 * On touch start, record the position and scroll offset.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchStart = function(event) {
		'use strict';
		var targetElement, touch, selection;
	
		// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
		if (event.targetTouches.length > 1) {
			return true;
		}
	
		targetElement = this.getTargetElementFromEventTarget(event.target);
		touch = event.targetTouches[0];
	
		if (this.deviceIsIOS) {
	
			// Only trusted events will deselect text on iOS (issue #49)
			selection = window.getSelection();
			if (selection.rangeCount && !selection.isCollapsed) {
				return true;
			}
	
			if (!this.deviceIsIOS4) {
	
				// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
				// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
				// with the same identifier as the touch event that previously triggered the click that triggered the alert.
				// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
				// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
				if (touch.identifier === this.lastTouchIdentifier) {
					event.preventDefault();
					return false;
				}
	
				this.lastTouchIdentifier = touch.identifier;
	
				// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
				// 1) the user does a fling scroll on the scrollable layer
				// 2) the user stops the fling scroll with another tap
				// then the event.target of the last 'touchend' event will be the element that was under the user's finger
				// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
				// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
				this.updateScrollParent(targetElement);
			}
		}
	
		this.trackingClick = true;
		this.trackingClickStart = event.timeStamp;
		this.targetElement = targetElement;
	
		this.touchStartX = touch.pageX;
		this.touchStartY = touch.pageY;
	
		// Prevent phantom clicks on fast double-tap (issue #36)
		if ((event.timeStamp - this.lastClickTime) < 200) {
			event.preventDefault();
		}
	
		return true;
	};
	
	
	/**
	 * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.touchHasMoved = function(event) {
		'use strict';
		var touch = event.changedTouches[0], boundary = this.touchBoundary;
	
		if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
			return true;
		}
	
		return false;
	};
	
	
	/**
	 * Update the last position.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchMove = function(event) {
		'use strict';
		if (!this.trackingClick) {
			return true;
		}
	
		// If the touch has moved, cancel the click tracking
		if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
			this.trackingClick = false;
			this.targetElement = null;
		}
	
		return true;
	};
	
	
	/**
	 * Attempt to find the labelled control for the given label element.
	 *
	 * @param {EventTarget|HTMLLabelElement} labelElement
	 * @returns {Element|null}
	 */
	FastClick.prototype.findControl = function(labelElement) {
		'use strict';
	
		// Fast path for newer browsers supporting the HTML5 control attribute
		if (labelElement.control !== undefined) {
			return labelElement.control;
		}
	
		// All browsers under test that support touch events also support the HTML5 htmlFor attribute
		if (labelElement.htmlFor) {
			return document.getElementById(labelElement.htmlFor);
		}
	
		// If no for attribute exists, attempt to retrieve the first labellable descendant element
		// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
		return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
	};
	
	
	/**
	 * On touch end, determine whether to send a click event at once.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onTouchEnd = function(event) {
		'use strict';
		var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
	
		if (!this.trackingClick) {
			return true;
		}
	
		// Prevent phantom clicks on fast double-tap (issue #36)
		if ((event.timeStamp - this.lastClickTime) < 200) {
			this.cancelNextClick = true;
			return true;
		}
	
		// Reset to prevent wrong click cancel on input (issue #156).
		this.cancelNextClick = false;
	
		this.lastClickTime = event.timeStamp;
	
		trackingClickStart = this.trackingClickStart;
		this.trackingClick = false;
		this.trackingClickStart = 0;
	
		// On some iOS devices, the targetElement supplied with the event is invalid if the layer
		// is performing a transition or scroll, and has to be re-detected manually. Note that
		// for this to function correctly, it must be called *after* the event target is checked!
		// See issue #57; also filed as rdar://13048589 .
		if (this.deviceIsIOSWithBadTarget) {
			touch = event.changedTouches[0];
	
			// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
			targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
			targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
		}
	
		targetTagName = targetElement.tagName.toLowerCase();
		if (targetTagName === 'label') {
			forElement = this.findControl(targetElement);
			if (forElement) {
				this.focus(targetElement);
				if (this.deviceIsAndroid) {
					return false;
				}
	
				targetElement = forElement;
			}
		} else if (this.needsFocus(targetElement)) {
	
			// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
			// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
			if ((event.timeStamp - trackingClickStart) > 100 || (this.deviceIsIOS && window.top !== window && targetTagName === 'input')) {
				this.targetElement = null;
				return false;
			}
	
			this.focus(targetElement);
	
			// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
			if (!this.deviceIsIOS4 || targetTagName !== 'select') {
				this.targetElement = null;
				event.preventDefault();
			}
	
			return false;
		}
	
		if (this.deviceIsIOS && !this.deviceIsIOS4) {
	
			// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
			// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
			scrollParent = targetElement.fastClickScrollParent;
			if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
				return true;
			}
		}
	
		// Prevent the actual click from going though - unless the target node is marked as requiring
		// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
		if (!this.needsClick(targetElement)) {
			event.preventDefault();
			this.sendClick(targetElement, event);
		}
	
		return false;
	};
	
	
	/**
	 * On touch cancel, stop tracking the click.
	 *
	 * @returns {void}
	 */
	FastClick.prototype.onTouchCancel = function() {
		'use strict';
		this.trackingClick = false;
		this.targetElement = null;
	};
	
	
	/**
	 * Determine mouse events which should be permitted.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onMouse = function(event) {
		'use strict';
	
		// If a target element was never set (because a touch event was never fired) allow the event
		if (!this.targetElement) {
			return true;
		}
	
		if (event.forwardedTouchEvent) {
			return true;
		}
	
		// Programmatically generated events targeting a specific element should be permitted
		if (!event.cancelable) {
			return true;
		}
	
		// Derive and check the target element to see whether the mouse event needs to be permitted;
		// unless explicitly enabled, prevent non-touch click events from triggering actions,
		// to prevent ghost/doubleclicks.
		if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
	
			// Prevent any user-added listeners declared on FastClick element from being fired.
			if (event.stopImmediatePropagation) {
				event.stopImmediatePropagation();
			} else {
	
				// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
				event.propagationStopped = true;
			}
	
			// Cancel the event
			event.stopPropagation();
			event.preventDefault();
	
			return false;
		}
	
		// If the mouse event is permitted, return true for the action to go through.
		return true;
	};
	
	
	/**
	 * On actual clicks, determine whether this is a touch-generated click, a click action occurring
	 * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
	 * an actual click which should be permitted.
	 *
	 * @param {Event} event
	 * @returns {boolean}
	 */
	FastClick.prototype.onClick = function(event) {
		'use strict';
		var permitted;
	
		// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
		if (this.trackingClick) {
			this.targetElement = null;
			this.trackingClick = false;
			return true;
		}
	
		// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
		if (event.target.type === 'submit' && event.detail === 0) {
			return true;
		}
	
		permitted = this.onMouse(event);
	
		// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
		if (!permitted) {
			this.targetElement = null;
		}
	
		// If clicks are permitted, return true for the action to go through.
		return permitted;
	};
	
	
	/**
	 * Remove all FastClick's event listeners.
	 *
	 * @returns {void}
	 */
	FastClick.prototype.destroy = function() {
		'use strict';
		var layer = this.layer;
	
		if (this.deviceIsAndroid) {
			layer.removeEventListener('mouseover', this.onMouse, true);
			layer.removeEventListener('mousedown', this.onMouse, true);
			layer.removeEventListener('mouseup', this.onMouse, true);
		}
	
		layer.removeEventListener('click', this.onClick, true);
		layer.removeEventListener('touchstart', this.onTouchStart, false);
		layer.removeEventListener('touchmove', this.onTouchMove, false);
		layer.removeEventListener('touchend', this.onTouchEnd, false);
		layer.removeEventListener('touchcancel', this.onTouchCancel, false);
	};
	
	
	/**
	 * Check whether FastClick is needed.
	 *
	 * @param {Element} layer The layer to listen on
	 */
	FastClick.notNeeded = function(layer) {
		'use strict';
		var metaViewport;
		var chromeVersion;
	
		// Devices that don't support touch don't need FastClick
		if (typeof window.ontouchstart === 'undefined') {
			return true;
		}
	
		// Chrome version - zero for other browsers
		chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
	
		if (chromeVersion) {
	
			if (FastClick.prototype.deviceIsAndroid) {
				metaViewport = document.querySelector('meta[name=viewport]');
	
				if (metaViewport) {
					// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
					if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
						return true;
					}
					// Chrome 32 and above with width=device-width or less don't need FastClick
					if (chromeVersion > 31 && window.innerWidth <= window.screen.width) {
						return true;
					}
				}
	
			// Chrome desktop doesn't need FastClick (issue #15)
			} else {
				return true;
			}
		}
	
		// IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
		if (layer.style.msTouchAction === 'none') {
			return true;
		}
	
		return false;
	};
	
	
	/**
	 * Factory method for creating a FastClick object
	 *
	 * @param {Element} layer The layer to listen on
	 */
	FastClick.attach = function(layer) {
		'use strict';
		return new FastClick(layer);
	};
	
	
	if (typeof define !== 'undefined' && define.amd) {
	
		// AMD. Register as an anonymous module.
		define(function() {
			'use strict';
			return FastClick;
		});
	} else if (typeof module !== 'undefined' && module.exports) {
		module.exports = FastClick.attach;
		module.exports.FastClick = FastClick;
	} else {
		window.FastClick = FastClick;
	}
	
	});
	
	require.register("component~indexof@0.0.3", function (exports, module) {
	module.exports = function(arr, obj){
	  if (arr.indexOf) return arr.indexOf(obj);
	  for (var i = 0; i < arr.length; ++i) {
		if (arr[i] === obj) return i;
	  }
	  return -1;
	};
	});
	
	require.register("component~classes@1.2.1", function (exports, module) {
	/**
	 * Module dependencies.
	 */
	
	var index = require('component~indexof@0.0.3');
	
	/**
	 * Whitespace regexp.
	 */
	
	var re = /\s+/;
	
	/**
	 * toString reference.
	 */
	
	var toString = Object.prototype.toString;
	
	/**
	 * Wrap `el` in a `ClassList`.
	 *
	 * @param {Element} el
	 * @return {ClassList}
	 * @api public
	 */
	
	module.exports = function(el){
	  return new ClassList(el);
	};
	
	/**
	 * Initialize a new ClassList for `el`.
	 *
	 * @param {Element} el
	 * @api private
	 */
	
	function ClassList(el) {
	  if (!el) throw new Error('A DOM element reference is required');
	  this.el = el;
	  this.list = el.classList;
	}
	
	/**
	 * Add class `name` if not already present.
	 *
	 * @param {String} name
	 * @return {ClassList}
	 * @api public
	 */
	
	ClassList.prototype.add = function(name){
	  // classList
	  if (this.list) {
		this.list.add(name);
		return this;
	  }
	
	  // fallback
	  var arr = this.array();
	  var i = index(arr, name);
	  if (!~i) arr.push(name);
	  this.el.className = arr.join(' ');
	  return this;
	};
	
	/**
	 * Remove class `name` when present, or
	 * pass a regular expression to remove
	 * any which match.
	 *
	 * @param {String|RegExp} name
	 * @return {ClassList}
	 * @api public
	 */
	
	ClassList.prototype.remove = function(name){
	  if ('[object RegExp]' == toString.call(name)) {
		return this.removeMatching(name);
	  }
	
	  // classList
	  if (this.list) {
		this.list.remove(name);
		return this;
	  }
	
	  // fallback
	  var arr = this.array();
	  var i = index(arr, name);
	  if (~i) arr.splice(i, 1);
	  this.el.className = arr.join(' ');
	  return this;
	};
	
	/**
	 * Remove all classes matching `re`.
	 *
	 * @param {RegExp} re
	 * @return {ClassList}
	 * @api private
	 */
	
	ClassList.prototype.removeMatching = function(re){
	  var arr = this.array();
	  for (var i = 0; i < arr.length; i++) {
		if (re.test(arr[i])) {
		  this.remove(arr[i]);
		}
	  }
	  return this;
	};
	
	/**
	 * Toggle class `name`, can force state via `force`.
	 *
	 * For browsers that support classList, but do not support `force` yet,
	 * the mistake will be detected and corrected.
	 *
	 * @param {String} name
	 * @param {Boolean} force
	 * @return {ClassList}
	 * @api public
	 */
	
	ClassList.prototype.toggle = function(name, force){
	  // classList
	  if (this.list) {
		if ("undefined" !== typeof force) {
		  if (force !== this.list.toggle(name, force)) {
			this.list.toggle(name); // toggle again to correct
		  }
		} else {
		  this.list.toggle(name);
		}
		return this;
	  }
	
	  // fallback
	  if ("undefined" !== typeof force) {
		if (!force) {
		  this.remove(name);
		} else {
		  this.add(name);
		}
	  } else {
		if (this.has(name)) {
		  this.remove(name);
		} else {
		  this.add(name);
		}
	  }
	
	  return this;
	};
	
	/**
	 * Return an array of classes.
	 *
	 * @return {Array}
	 * @api public
	 */
	
	ClassList.prototype.array = function(){
	  var str = this.el.className.replace(/^\s+|\s+$/g, '');
	  var arr = str.split(re);
	  if ('' === arr[0]) arr.shift();
	  return arr;
	};
	
	/**
	 * Check if class `name` is present.
	 *
	 * @param {String} name
	 * @return {ClassList}
	 * @api public
	 */
	
	ClassList.prototype.has =
	ClassList.prototype.contains = function(name){
	  return this.list
		? this.list.contains(name)
		: !! ~index(this.array(), name);
	};
	
	});
	
	require.register("component~event@0.1.4", function (exports, module) {
	var bind = window.addEventListener ? 'addEventListener' : 'attachEvent',
		unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent',
		prefix = bind !== 'addEventListener' ? 'on' : '';
	
	/**
	 * Bind `el` event `type` to `fn`.
	 *
	 * @param {Element} el
	 * @param {String} type
	 * @param {Function} fn
	 * @param {Boolean} capture
	 * @return {Function}
	 * @api public
	 */
	
	exports.bind = function(el, type, fn, capture){
	  el[bind](prefix + type, fn, capture || false);
	  return fn;
	};
	
	/**
	 * Unbind `el` event `type`'s callback `fn`.
	 *
	 * @param {Element} el
	 * @param {String} type
	 * @param {Function} fn
	 * @param {Boolean} capture
	 * @return {Function}
	 * @api public
	 */
	
	exports.unbind = function(el, type, fn, capture){
	  el[unbind](prefix + type, fn, capture || false);
	  return fn;
	};
	});
	
	require.register("component~query@0.0.3", function (exports, module) {
	function one(selector, el) {
	  return el.querySelector(selector);
	}
	
	exports = module.exports = function(selector, el){
	  el = el || document;
	  return one(selector, el);
	};
	
	exports.all = function(selector, el){
	  el = el || document;
	  return el.querySelectorAll(selector);
	};
	
	exports.engine = function(obj){
	  if (!obj.one) throw new Error('.one callback required');
	  if (!obj.all) throw new Error('.all callback required');
	  one = obj.one;
	  exports.all = obj.all;
	  return exports;
	};
	
	});
	
	require.register("component~matches-selector@0.1.5", function (exports, module) {
	/**
	 * Module dependencies.
	 */
	
	var query = require('component~query@0.0.3');
	
	/**
	 * Element prototype.
	 */
	
	var proto = Element.prototype;
	
	/**
	 * Vendor function.
	 */
	
	var vendor = proto.matches
	  || proto.webkitMatchesSelector
	  || proto.mozMatchesSelector
	  || proto.msMatchesSelector
	  || proto.oMatchesSelector;
	
	/**
	 * Expose `match()`.
	 */
	
	module.exports = match;
	
	/**
	 * Match `el` to `selector`.
	 *
	 * @param {Element} el
	 * @param {String} selector
	 * @return {Boolean}
	 * @api public
	 */
	
	function match(el, selector) {
	  if (!el || el.nodeType !== 1) return false;
	  if (vendor) return vendor.call(el, selector);
	  var nodes = query.all(selector, el.parentNode);
	  for (var i = 0; i < nodes.length; ++i) {
		if (nodes[i] == el) return true;
	  }
	  return false;
	}
	
	});
	
	require.register("component~closest@0.1.4", function (exports, module) {
	var matches = require('component~matches-selector@0.1.5')
	
	module.exports = function (element, selector, checkYoSelf, root) {
	  element = checkYoSelf ? {parentNode: element} : element
	
	  root = root || document
	
	  // Make sure `element !== document` and `element != null`
	  // otherwise we get an illegal invocation
	  while ((element = element.parentNode) && element !== document) {
		if (matches(element, selector))
		  return element
		// After `matches` on the edge case that
		// the selector matches the root
		// (when the root is not the document)
		if (element === root)
		  return
	  }
	}
	
	});
	
	require.register("component~delegate@0.2.3", function (exports, module) {
	/**
	 * Module dependencies.
	 */
	
	var closest = require('component~closest@0.1.4')
	  , event = require('component~event@0.1.4');
	
	/**
	 * Delegate event `type` to `selector`
	 * and invoke `fn(e)`. A callback function
	 * is returned which may be passed to `.unbind()`.
	 *
	 * @param {Element} el
	 * @param {String} selector
	 * @param {String} type
	 * @param {Function} fn
	 * @param {Boolean} capture
	 * @return {Function}
	 * @api public
	 */
	
	exports.bind = function(el, selector, type, fn, capture){
	  return event.bind(el, type, function(e){
		var target = e.target || e.srcElement;
		e.delegateTarget = closest(target, selector, true, el);
		if (e.delegateTarget) fn.call(el, e);
	  }, capture);
	};
	
	/**
	 * Unbind event `type`'s callback `fn`.
	 *
	 * @param {Element} el
	 * @param {String} type
	 * @param {Function} fn
	 * @param {Boolean} capture
	 * @api public
	 */
	
	exports.unbind = function(el, type, fn, capture){
	  event.unbind(el, type, fn, capture);
	};
	
	});
	
	require.register("component~events@1.0.9", function (exports, module) {
	
	/**
	 * Module dependencies.
	 */
	
	var events = require('component~event@0.1.4');
	var delegate = require('component~delegate@0.2.3');
	
	/**
	 * Expose `Events`.
	 */
	
	module.exports = Events;
	
	/**
	 * Initialize an `Events` with the given
	 * `el` object which events will be bound to,
	 * and the `obj` which will receive method calls.
	 *
	 * @param {Object} el
	 * @param {Object} obj
	 * @api public
	 */
	
	function Events(el, obj) {
	  if (!(this instanceof Events)) return new Events(el, obj);
	  if (!el) throw new Error('element required');
	  if (!obj) throw new Error('object required');
	  this.el = el;
	  this.obj = obj;
	  this._events = {};
	}
	
	/**
	 * Subscription helper.
	 */
	
	Events.prototype.sub = function(event, method, cb){
	  this._events[event] = this._events[event] || {};
	  this._events[event][method] = cb;
	};
	
	/**
	 * Bind to `event` with optional `method` name.
	 * When `method` is undefined it becomes `event`
	 * with the "on" prefix.
	 *
	 * Examples:
	 *
	 *  Direct event handling:
	 *
	 *    events.bind('click') // implies "onclick"
	 *    events.bind('click', 'remove')
	 *    events.bind('click', 'sort', 'asc')
	 *
	 *  Delegated event handling:
	 *
	 *    events.bind('click li > a')
	 *    events.bind('click li > a', 'remove')
	 *    events.bind('click a.sort-ascending', 'sort', 'asc')
	 *    events.bind('click a.sort-descending', 'sort', 'desc')
	 *
	 * @param {String} event
	 * @param {String|function} [method]
	 * @return {Function} callback
	 * @api public
	 */
	
	Events.prototype.bind = function(event, method){
	  var e = parse(event);
	  var el = this.el;
	  var obj = this.obj;
	  var name = e.name;
	  var method = method || 'on' + name;
	  var args = [].slice.call(arguments, 2);
	
	  // callback
	  function cb(){
		var a = [].slice.call(arguments).concat(args);
		obj[method].apply(obj, a);
	  }
	
	  // bind
	  if (e.selector) {
		cb = delegate.bind(el, e.selector, name, cb);
	  } else {
		events.bind(el, name, cb);
	  }
	
	  // subscription for unbinding
	  this.sub(name, method, cb);
	
	  return cb;
	};
	
	/**
	 * Unbind a single binding, all bindings for `event`,
	 * or all bindings within the manager.
	 *
	 * Examples:
	 *
	 *  Unbind direct handlers:
	 *
	 *     events.unbind('click', 'remove')
	 *     events.unbind('click')
	 *     events.unbind()
	 *
	 * Unbind delegate handlers:
	 *
	 *     events.unbind('click', 'remove')
	 *     events.unbind('click')
	 *     events.unbind()
	 *
	 * @param {String|Function} [event]
	 * @param {String|Function} [method]
	 * @api public
	 */
	
	Events.prototype.unbind = function(event, method){
	  if (0 == arguments.length) return this.unbindAll();
	  if (1 == arguments.length) return this.unbindAllOf(event);
	
	  // no bindings for this event
	  var bindings = this._events[event];
	  if (!bindings) return;
	
	  // no bindings for this method
	  var cb = bindings[method];
	  if (!cb) return;
	
	  events.unbind(this.el, event, cb);
	};
	
	/**
	 * Unbind all events.
	 *
	 * @api private
	 */
	
	Events.prototype.unbindAll = function(){
	  for (var event in this._events) {
		this.unbindAllOf(event);
	  }
	};
	
	/**
	 * Unbind all events for `event`.
	 *
	 * @param {String} event
	 * @api private
	 */
	
	Events.prototype.unbindAllOf = function(event){
	  var bindings = this._events[event];
	  if (!bindings) return;
	
	  for (var method in bindings) {
		this.unbind(event, method);
	  }
	};
	
	/**
	 * Parse `event`.
	 *
	 * @param {String} event
	 * @return {Object}
	 * @api private
	 */
	
	function parse(event) {
	  var parts = event.split(/ +/);
	  return {
		name: parts.shift(),
		selector: parts.join(' ')
	  }
	}
	
	});
	
	require.register("switchery", function (exports, module) {
	/**
	 * Switchery 0.8.1
	 * http://abpetkov.github.io/switchery/
	 *
	 * Authored by Alexander Petkov
	 * https://github.com/abpetkov
	 *
	 * Copyright 2013-2015, Alexander Petkov
	 * License: The MIT License (MIT)
	 * http://opensource.org/licenses/MIT
	 *
	 */
	
	/**
	 * External dependencies.
	 */
	
	var transitionize = require('abpetkov~transitionize@0.0.3')
	  , fastclick = require('ftlabs~fastclick@v0.6.11')
	  , classes = require('component~classes@1.2.1')
	  , events = require('component~events@1.0.9');
	
	/**
	 * Expose `Switchery`.
	 */
	
	module.exports = Switchery;
	
	/**
	 * Set Switchery default values.
	 *
	 * @api public
	 */
	
	var defaults = {
		color             : '#64bd63'
	  , secondaryColor    : '#dfdfdf'
	  , jackColor         : '#fff'
	  , jackSecondaryColor: null
	  , className         : 'switchery'
	  , disabled          : false
	  , disabledOpacity   : 0.5
	  , speed             : '0.4s'
	  , size              : 'default'
	};
	
	/**
	 * Create Switchery object.
	 *
	 * @param {Object} element
	 * @param {Object} options
	 * @api public
	 */
	
	function Switchery(element, options) {
	  if (!(this instanceof Switchery)) return new Switchery(element, options);
	
	  this.element = element;
	  this.options = options || {};
	
	  for (var i in defaults) {
		if (this.options[i] == null) {
		  this.options[i] = defaults[i];
		}
	  }
	
	  if (this.element != null && this.element.type == 'checkbox') this.init();
	  if (this.isDisabled() === true) this.disable();
	}
	
	/**
	 * Hide the target element.
	 *
	 * @api private
	 */
	
	Switchery.prototype.hide = function() {
	  this.element.style.display = 'none';
	};
	
	/**
	 * Show custom switch after the target element.
	 *
	 * @api private
	 */
	
	Switchery.prototype.show = function() {
	  var switcher = this.create();
	  this.insertAfter(this.element, switcher);
	};
	
	/**
	 * Create custom switch.
	 *
	 * @returns {Object} this.switcher
	 * @api private
	 */
	
	Switchery.prototype.create = function() {
	  var elementDocument = this.element.ownerDocument || document;
	  this.switcher = elementDocument.createElement('span');
	  this.jack = elementDocument.createElement('small');
	  this.switcher.appendChild(this.jack);
	  this.switcher.className = this.options.className;
	  this.events = events(this.switcher, this);
	
	  this.switcher.tabIndex = '0';
	  this.switcher.setAttribute('role', 'switch');
	  this.switcher.ariaChecked = 'false';
	  this.switcher.ariaLabel = this.options.ariaLabel;

	  return this.switcher;
	};
	
	/**
	 * Insert after element after another element.
	 *
	 * @param {Object} reference
	 * @param {Object} target
	 * @api private
	 */
	
	Switchery.prototype.insertAfter = function(reference, target) {
	  reference.parentNode.insertBefore(target, reference.nextSibling);
	};
	
	/**
	 * Set switch jack proper position.
	 *
	 * @param {Boolean} clicked - we need this in order to uncheck the input when the switch is clicked
	 * @api private
	 */
	
	Switchery.prototype.setPosition = function (clicked) {
	  var checked = this.isChecked()
		, switcher = this.switcher
		, jack = this.jack;
	
	  if (clicked && checked) checked = false;
	  else if (clicked && !checked) checked = true;
	
	  if (checked === true) {
		this.element.checked = true;
		this.switcher.ariaChecked = true;
	
		if (window.getComputedStyle) jack.style.left = parseInt(window.getComputedStyle(switcher).width) - parseInt(window.getComputedStyle(jack).width) + 'px';
		else jack.style.left = parseInt(switcher.currentStyle['width']) - parseInt(jack.currentStyle['width']) + 'px';
	
		if (this.options.color) this.colorize();
		this.setSpeed();
	  } else {
		jack.style.left = 0;
		this.element.checked = false;
		this.switcher.ariaChecked = false;
		this.switcher.style.boxShadow = 'inset 0 0 0 0 ' + this.options.secondaryColor;
		this.switcher.style.borderColor = this.options.secondaryColor;
		this.switcher.style.backgroundColor = (this.options.secondaryColor !== defaults.secondaryColor) ? this.options.secondaryColor : '#fff';
		this.jack.style.backgroundColor = (this.options.jackSecondaryColor !== this.options.jackColor) ? this.options.jackSecondaryColor : this.options.jackColor;
		this.setSpeed();
	  }
	};
	
	/**
	 * Set speed.
	 *
	 * @api private
	 */
	
	Switchery.prototype.setSpeed = function() {
	  var switcherProp = {}
		, jackProp = {
			'background-color': this.options.speed
		  , 'left': this.options.speed.replace(/[a-z]/, '') / 2 + 's'
		};
	
	  if (this.isChecked()) {
		switcherProp = {
			'border': this.options.speed
		  , 'box-shadow': this.options.speed
		  , 'background-color': this.options.speed.replace(/[a-z]/, '') * 3 + 's'
		};
	  } else {
		switcherProp = {
			'border': this.options.speed
		  , 'box-shadow': this.options.speed
		};
	  }
	
	  transitionize(this.switcher, switcherProp);
	  transitionize(this.jack, jackProp);
	};
	
	/**
	 * Set switch size.
	 *
	 * @api private
	 */
	
	Switchery.prototype.setSize = function() {
	  var small = 'switchery-small'
		, normal = 'switchery-default'
		, large = 'switchery-large';
	
	  switch (this.options.size) {
		case 'small':
		  classes(this.switcher).add(small)
		  break;
		case 'large':
		  classes(this.switcher).add(large)
		  break;
		default:
		  classes(this.switcher).add(normal)
		  break;
	  }
	};
	
	/**
	 * Set switch color.
	 *
	 * @api private
	 */
	
	Switchery.prototype.colorize = function() {
	  var switcherHeight = this.switcher.offsetHeight / 2;
	
	  this.switcher.style.backgroundColor = this.options.color;
	  this.switcher.style.borderColor = this.options.color;
	  this.switcher.style.boxShadow = 'inset 0 0 0 ' + switcherHeight + 'px ' + this.options.color;
	  this.jack.style.backgroundColor = this.options.jackColor;
	};
	
	/**
	 * Handle the onchange event.
	 *
	 * @param {Boolean} state
	 * @api private
	 */
	
	Switchery.prototype.handleOnchange = function(state) {
	  var elementDocument = this.element.ownerDocument || document;
	  if (elementDocument.dispatchEvent) {
		var event = elementDocument.createEvent('HTMLEvents');
		event.initEvent('change', true, true);
		this.element.dispatchEvent(event);
	  } else {
		this.element.fireEvent('onchange');
	  }
	};
	
	/**
	 * Handle the native input element state change.
	 * A `change` event must be fired in order to detect the change.
	 *
	 * @api private
	 */
	
	Switchery.prototype.handleChange = function() {
	  var self = this
		, el = this.element;
	
	  if (el.addEventListener) {
		el.addEventListener('change', function() {
		  self.setPosition();
		});
	  } else {
		el.attachEvent('onchange', function() {
		  self.setPosition();
		});
	  }
	};
	
	/**
	 * Handle the switch click event.
	 *
	 * @api private
	 */
	
	Switchery.prototype.handleClick = function() {
	  var switcher = this.switcher;
	
	  fastclick(switcher);
	  this.events.bind('click', 'bindClick');
	  this.events.bind('keyup', 'bindKeyUp');
	};
	
	/**
	 * Attach all methods that need to happen on switcher click.
	 *
	 * @api private
	 */
	
	Switchery.prototype.bindClick = function() {
	  var parent = this.element.parentNode.tagName.toLowerCase()
		, labelParent = (parent === 'label') ? false : true;
	
	  this.setPosition(labelParent);
	  this.handleOnchange(this.element.checked);
	};
	
	Switchery.prototype.keyPressCodes = [32, 13, 37, 39];
	Switchery.prototype.bindKeyUp = function(evt) {
		if (Switchery.prototype.keyPressCodes.indexOf(evt.keyCode) < 0)
			return;
		
		this.bindClick();
	}

	/**
	 * Mark an individual switch as already handled.
	 *
	 * @api private
	 */
	
	Switchery.prototype.markAsSwitched = function() {
	  this.element.setAttribute('data-switchery', true);
	};
	
	/**
	 * Check if an individual switch is already handled.
	 *
	 * @api private
	 */
	
	Switchery.prototype.markedAsSwitched = function() {
	  return this.element.getAttribute('data-switchery');
	};
	
	/**
	 * Initialize Switchery.
	 *
	 * @api private
	 */
	
	Switchery.prototype.init = function() {
	  this.hide();
	  this.show();
	  this.setSize();
	  this.setPosition();
	  this.markAsSwitched();
	  this.handleChange();
	  this.handleClick();
	};
	
	/**
	 * See if input is checked.
	 *
	 * @returns {Boolean}
	 * @api public
	 */
	
	Switchery.prototype.isChecked = function() {
	  return this.element.checked;
	};
	
	/**
	 * See if switcher should be disabled.
	 *
	 * @returns {Boolean}
	 * @api public
	 */
	
	Switchery.prototype.isDisabled = function() {
	  return this.options.disabled || this.element.disabled || this.element.readOnly;
	};
	
	/**
	 * Destroy all event handlers attached to the switch.
	 *
	 * @api public
	 */
	
	Switchery.prototype.destroy = function() {
	  this.events.unbind();
	};
	
	/**
	 * Enable disabled switch element.
	 *
	 * @api public
	 */
	
	Switchery.prototype.enable = function() {
	  if (!this.options.disabled) return;
	  if (this.options.disabled) this.options.disabled = false;
	  if (this.element.disabled) this.element.disabled = false;
	  if (this.element.readOnly) this.element.readOnly = false;
	  this.switcher.style.opacity = 1;
	  this.events.bind('click', 'bindClick');
	  this.events.bind('keyup', 'bindKeyUp');
	};
	
	/**
	 * Disable switch element.
	 *
	 * @api public
	 */
	
	Switchery.prototype.disable = function() {
	  if (this.options.disabled) return;
	  if (!this.options.disabled) this.options.disabled = true;
	  if (!this.element.disabled) this.element.disabled = true;
	  if (!this.element.readOnly) this.element.readOnly = true;
	  this.switcher.style.opacity = this.options.disabledOpacity;
	  this.destroy();
	};
	
	});
	
	if (typeof exports == "object") {
	  module.exports = require("switchery");
	} else if (typeof define == "function" && define.amd) {
	  define("Switchery", [], function(){ return require("switchery"); });
	} else {
	  (this || window)["Switchery"] = require("switchery");
	}
	})();
;
(function(){function e(t,s,n){var i=e.resolve(t);if(null==i){n=n||t,s=s||"root";var o=Error('Failed to require "'+n+'" from "'+s+'"');throw o.path=n,o.parent=s,o.require=!0,o}var r=e.modules[i];if(!r._resolving&&!r.exports){var a={};a.exports={},a.client=a.component=!0,r._resolving=!0,r.call(this,a.exports,e.relative(i),a),delete r._resolving,r.exports=a.exports}return r.exports}e.modules={},e.aliases={},e.resolve=function(t){"/"===t.charAt(0)&&(t=t.slice(1));for(var s=[t,t+".js",t+".json",t+"/index.js",t+"/index.json"],n=0;s.length>n;n++){var t=s[n];if(e.modules.hasOwnProperty(t))return t;if(e.aliases.hasOwnProperty(t))return e.aliases[t]}},e.normalize=function(e,t){var s=[];if("."!=t.charAt(0))return t;e=e.split("/"),t=t.split("/");for(var n=0;t.length>n;++n)".."==t[n]?e.pop():"."!=t[n]&&""!=t[n]&&s.push(t[n]);return e.concat(s).join("/")},e.register=function(t,s){e.modules[t]=s},e.alias=function(t,s){if(!e.modules.hasOwnProperty(t))throw Error('Failed to alias "'+t+'", it does not exist');e.aliases[s]=t},e.relative=function(t){function s(e,t){for(var s=e.length;s--;)if(e[s]===t)return s;return-1}function n(s){var i=n.resolve(s);return e(i,t,s)}var i=e.normalize(t,"..");return n.resolve=function(n){var o=n.charAt(0);if("/"==o)return n.slice(1);if("."==o)return e.normalize(i,n);var r=t.split("/"),a=s(r,"deps")+1;return a||(a=0),n=r.slice(0,a+1).join("/")+"/deps/"+n},n.exists=function(t){return e.modules.hasOwnProperty(n.resolve(t))},n},e.register("component-event/index.js",function(e){var t=window.addEventListener?"addEventListener":"attachEvent",s=window.removeEventListener?"removeEventListener":"detachEvent",n="addEventListener"!==t?"on":"";e.bind=function(e,s,i,o){return e[t](n+s,i,o||!1),i},e.unbind=function(e,t,i,o){return e[s](n+t,i,o||!1),i}}),e.register("component-query/index.js",function(e,t,s){function n(e,t){return t.querySelector(e)}e=s.exports=function(e,t){return t=t||document,n(e,t)},e.all=function(e,t){return t=t||document,t.querySelectorAll(e)},e.engine=function(t){if(!t.one)throw Error(".one callback required");if(!t.all)throw Error(".all callback required");return n=t.one,e.all=t.all,e}}),e.register("component-matches-selector/index.js",function(e,t,s){function n(e,t){if(r)return r.call(e,t);for(var s=i.all(t,e.parentNode),n=0;s.length>n;++n)if(s[n]==e)return!0;return!1}var i=t("query"),o=Element.prototype,r=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.msMatchesSelector||o.oMatchesSelector;s.exports=n}),e.register("discore-closest/index.js",function(e,t,s){var n=t("matches-selector");s.exports=function(e,t,s,i){for(e=s?{parentNode:e}:e,i=i||document;(e=e.parentNode)&&e!==document;){if(n(e,t))return e;if(e===i)return}}}),e.register("component-delegate/index.js",function(e,t){var s=t("closest"),n=t("event");e.bind=function(e,t,i,o,r){return n.bind(e,i,function(n){var i=n.target||n.srcElement;n.delegateTarget=s(i,t,!0,e),n.delegateTarget&&o.call(e,n)},r)},e.unbind=function(e,t,s,i){n.unbind(e,t,s,i)}}),e.register("component-events/index.js",function(e,t,s){function n(e,t){if(!(this instanceof n))return new n(e,t);if(!e)throw Error("element required");if(!t)throw Error("object required");this.el=e,this.obj=t,this._events={}}function i(e){var t=e.split(/ +/);return{name:t.shift(),selector:t.join(" ")}}var o=t("event"),r=t("delegate");s.exports=n,n.prototype.sub=function(e,t,s){this._events[e]=this._events[e]||{},this._events[e][t]=s},n.prototype.bind=function(e,t){function s(){var e=[].slice.call(arguments).concat(h);l[t].apply(l,e)}var n=i(e),a=this.el,l=this.obj,c=n.name,t=t||"on"+c,h=[].slice.call(arguments,2);return n.selector?s=r.bind(a,n.selector,c,s):o.bind(a,c,s),this.sub(c,t,s),s},n.prototype.unbind=function(e,t){if(0==arguments.length)return this.unbindAll();if(1==arguments.length)return this.unbindAllOf(e);var s=this._events[e];if(s){var n=s[t];n&&o.unbind(this.el,e,n)}},n.prototype.unbindAll=function(){for(var e in this._events)this.unbindAllOf(e)},n.prototype.unbindAllOf=function(e){var t=this._events[e];if(t)for(var s in t)this.unbind(e,s)}}),e.register("component-indexof/index.js",function(e,t,s){s.exports=function(e,t){if(e.indexOf)return e.indexOf(t);for(var s=0;e.length>s;++s)if(e[s]===t)return s;return-1}}),e.register("component-classes/index.js",function(e,t,s){function n(e){if(!e)throw Error("A DOM element reference is required");this.el=e,this.list=e.classList}var i=t("indexof"),o=/\s+/,r=Object.prototype.toString;s.exports=function(e){return new n(e)},n.prototype.add=function(e){if(this.list)return this.list.add(e),this;var t=this.array(),s=i(t,e);return~s||t.push(e),this.el.className=t.join(" "),this},n.prototype.remove=function(e){if("[object RegExp]"==r.call(e))return this.removeMatching(e);if(this.list)return this.list.remove(e),this;var t=this.array(),s=i(t,e);return~s&&t.splice(s,1),this.el.className=t.join(" "),this},n.prototype.removeMatching=function(e){for(var t=this.array(),s=0;t.length>s;s++)e.test(t[s])&&this.remove(t[s]);return this},n.prototype.toggle=function(e,t){return this.list?(t!==void 0?t!==this.list.toggle(e,t)&&this.list.toggle(e):this.list.toggle(e),this):(t!==void 0?t?this.add(e):this.remove(e):this.has(e)?this.remove(e):this.add(e),this)},n.prototype.array=function(){var e=this.el.className.replace(/^\s+|\s+$/g,""),t=e.split(o);return""===t[0]&&t.shift(),t},n.prototype.has=n.prototype.contains=function(e){return this.list?this.list.contains(e):!!~i(this.array(),e)}}),e.register("component-emitter/index.js",function(e,t,s){function n(e){return e?i(e):void 0}function i(e){for(var t in n.prototype)e[t]=n.prototype[t];return e}s.exports=n,n.prototype.on=n.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks[e]=this._callbacks[e]||[]).push(t),this},n.prototype.once=function(e,t){function s(){n.off(e,s),t.apply(this,arguments)}var n=this;return this._callbacks=this._callbacks||{},s.fn=t,this.on(e,s),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s=this._callbacks[e];if(!s)return this;if(1==arguments.length)return delete this._callbacks[e],this;for(var n,i=0;s.length>i;i++)if(n=s[i],n===t||n.fn===t){s.splice(i,1);break}return this},n.prototype.emit=function(e){this._callbacks=this._callbacks||{};var t=[].slice.call(arguments,1),s=this._callbacks[e];if(s){s=s.slice(0);for(var n=0,i=s.length;i>n;++n)s[n].apply(this,t)}return this},n.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks[e]||[]},n.prototype.hasListeners=function(e){return!!this.listeners(e).length}}),e.register("ui-component-mouse/index.js",function(e,t,s){function n(e,t){this.obj=t||{},this.el=e}var i=t("emitter"),o=t("event");s.exports=function(e,t){return new n(e,t)},i(n.prototype),n.prototype.bind=function(){function e(i){s.onmouseup&&s.onmouseup(i),o.unbind(document,"mousemove",t),o.unbind(document,"mouseup",e),n.emit("up",i)}function t(e){s.onmousemove&&s.onmousemove(e),n.emit("move",e)}var s=this.obj,n=this;return n.down=function(i){s.onmousedown&&s.onmousedown(i),o.bind(document,"mouseup",e),o.bind(document,"mousemove",t),n.emit("down",i)},o.bind(this.el,"mousedown",n.down),this},n.prototype.unbind=function(){o.unbind(this.el,"mousedown",this.down),this.down=null}}),e.register("abpetkov-percentage-calc/percentage-calc.js",function(e){e.isNumber=function(e){return"number"==typeof e?!0:!1},e.of=function(t,s){return e.isNumber(t)&&e.isNumber(s)?t/100*s:void 0},e.from=function(t,s){return e.isNumber(t)&&e.isNumber(s)?100*(t/s):void 0}}),e.register("abpetkov-closest-num/closest-num.js",function(e){e.find=function(e,t){var s=null,n=null,o=t[0];for(i=0;t.length>i;i++)s=Math.abs(e-o),n=Math.abs(e-t[i]),s>n&&(o=t[i]);return o}}),e.register("vesln-super/lib/super.js",function(e,t,s){function n(){var t=i.call(arguments);if(t.length)return"function"!=typeof t[0]?e.merge(t):(e.inherits.apply(null,t),void 0)}var i=Array.prototype.slice,e=s.exports=n;e.extend=function(t,s){var n=this,i=function(){return n.apply(this,arguments)};return e.merge([i,this]),e.inherits(i,this),t&&e.merge([i.prototype,t]),s&&e.merge([i,s]),i.extend=this.extend,i},e.inherits=function(e,t){e.super_=t,Object.create?e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}):(e.prototype=new t,e.prototype.constructor=e)},e.merge=function(e){for(var t=2===e.length?e.shift():{},s=null,n=0,i=e.length;i>n;n++){s=e[n];for(var o in s)s.hasOwnProperty(o)&&(t[o]=s[o])}return t}}),e.register("powerange/lib/powerange.js",function(e,t,s){var n=(t("./main"),t("./horizontal")),i=t("./vertical"),o={callback:function(){},decimal:!1,disable:!1,disableOpacity:.5,hideRange:!1,klass:"",min:0,max:100,start:null,step:null,vertical:!1};s.exports=function(e,t){t=t||{};for(var s in o)null==t[s]&&(t[s]=o[s]);return t.vertical?new i(e,t):new n(e,t)}}),e.register("powerange/lib/main.js",function(e,t,s){function n(e,t){return this instanceof n?(this.element=e,this.options=t||{},this.slider=this.create("span","range-bar"),null!==this.element&&"text"===this.element.type&&this.init(),void 0):new n(e,t)}var o=t("mouse"),r=t("events"),a=t("classes"),l=t("percentage-calc");s.exports=n,n.prototype.bindEvents=function(){this.handle=this.slider.querySelector(".range-handle"),this.touch=r(this.handle,this),this.touch.bind("touchstart","onmousedown"),this.touch.bind("touchmove","onmousemove"),this.touch.bind("touchend","onmouseup"),this.mouse=o(this.handle,this),this.mouse.bind()},n.prototype.hide=function(){this.element.style.display="none"},n.prototype.append=function(){var e=this.generate();this.insertAfter(this.element,e)},n.prototype.generate=function(){var e={handle:{type:"span",selector:"range-handle"},min:{type:"span",selector:"range-min"},max:{type:"span",selector:"range-max"},quantity:{type:"span",selector:"range-quantity"}};for(var t in e)if(e.hasOwnProperty(t)){var s=this.create(e[t].type,e[t].selector);this.slider.appendChild(s)}return this.slider},n.prototype.create=function(e,t){var s=document.createElement(e);return s.className=t,s},n.prototype.insertAfter=function(e,t){e.parentNode.insertBefore(t,e.nextSibling)},n.prototype.extraClass=function(e){this.options.klass&&a(this.slider).add(e)},n.prototype.setRange=function(e,t){"number"!=typeof e||"number"!=typeof t||this.options.hideRange||(this.slider.querySelector(".range-min").innerHTML=e,this.slider.querySelector(".range-max").innerHTML=t)},n.prototype.setValue=function(e,t){var s=l.from(parseFloat(e),t),n=l.of(s,this.options.max-this.options.min)+this.options.min,i=!1;n=this.options.decimal?Math.round(100*n)/100:Math.round(n),i=this.element.value!=n?!0:!1,this.element.value=n,this.options.callback(),i&&this.changeEvent()},n.prototype.step=function(e,t){var s=e-t,n=l.from(this.checkStep(this.options.step),this.options.max-this.options.min),o=l.of(n,s),r=[];for(i=0;s>=i;i+=o)r.push(i);return this.steps=r,this.steps},n.prototype.checkValues=function(e){this.options.min>e&&(this.options.start=this.options.min),e>this.options.max&&(this.options.start=this.options.max),this.options.min>=this.options.max&&(this.options.min=this.options.max)},n.prototype.checkStep=function(e){return 0>e&&(e=Math.abs(e)),this.options.step=e,this.options.step},n.prototype.disable=function(){(this.options.min==this.options.max||this.options.min>this.options.max||this.options.disable)&&(this.mouse.unbind(),this.touch.unbind(),this.slider.style.opacity=this.options.disableOpacity,a(this.handle).add("range-disabled"))},n.prototype.unselectable=function(e,t){a(this.slider).has("unselectable")||t!==!0?a(this.slider).remove("unselectable"):a(this.slider).add("unselectable")},n.prototype.changeEvent=function(){if("function"!=typeof Event&&document.fireEvent)this.element.fireEvent("onchange");else{var e=document.createEvent("HTMLEvents");e.initEvent("change",!1,!0),this.element.dispatchEvent(e)}},n.prototype.init=function(){this.hide(),this.append(),this.bindEvents(),this.extraClass(this.options.klass),this.checkValues(this.options.start),this.setRange(this.options.min,this.options.max),this.disable()}}),e.register("powerange/lib/horizontal.js",function(e,t,s){function n(){a.apply(this,arguments),this.options.step&&this.step(this.slider.offsetWidth,this.handle.offsetWidth),this.setStart(this.options.start)}var i=t("super"),o=t("closest-num"),r=t("percentage-calc"),a=t("./main");s.exports=n,i(n,a),n.prototype.setStart=function(e){var t=null===e?this.options.min:e,s=r.from(t-this.options.min,this.options.max-this.options.min)||0,n=r.of(s,this.slider.offsetWidth-this.handle.offsetWidth),i=this.options.step?o.find(n,this.steps):n;this.setPosition(i),this.setValue(this.handle.style.left,this.slider.offsetWidth-this.handle.offsetWidth)},n.prototype.setPosition=function(e){this.handle.style.left=e+"px",this.slider.querySelector(".range-quantity").style.width=e+"px"},n.prototype.onmousedown=function(e){e.touches&&(e=e.touches[0]),this.startX=e.clientX,this.handleOffsetX=this.handle.offsetLeft,this.restrictHandleX=this.slider.offsetWidth-this.handle.offsetWidth,this.unselectable(this.slider,!0)},n.prototype.onmousemove=function(e){e.preventDefault(),e.touches&&(e=e.touches[0]);var t=this.handleOffsetX+e.clientX-this.startX,s=this.steps?o.find(t,this.steps):t;0>=t?this.setPosition(0):t>=this.restrictHandleX?this.setPosition(this.restrictHandleX):this.setPosition(s),this.setValue(this.handle.style.left,this.slider.offsetWidth-this.handle.offsetWidth)},n.prototype.onmouseup=function(){this.unselectable(this.slider,!1)}}),e.register("powerange/lib/vertical.js",function(e,t,s){function n(){l.apply(this,arguments),o(this.slider).add("vertical"),this.options.step&&this.step(this.slider.offsetHeight,this.handle.offsetHeight),this.setStart(this.options.start)}var i=t("super"),o=t("classes"),r=t("closest-num"),a=t("percentage-calc"),l=t("./main");s.exports=n,i(n,l),n.prototype.setStart=function(e){var t=null===e?this.options.min:e,s=a.from(t-this.options.min,this.options.max-this.options.min)||0,n=a.of(s,this.slider.offsetHeight-this.handle.offsetHeight),i=this.options.step?r.find(n,this.steps):n;this.setPosition(i),this.setValue(this.handle.style.bottom,this.slider.offsetHeight-this.handle.offsetHeight)},n.prototype.setPosition=function(e){this.handle.style.bottom=e+"px",this.slider.querySelector(".range-quantity").style.height=e+"px"},n.prototype.onmousedown=function(e){e.touches&&(e=e.touches[0]),this.startY=e.clientY,this.handleOffsetY=this.slider.offsetHeight-this.handle.offsetHeight-this.handle.offsetTop,this.restrictHandleY=this.slider.offsetHeight-this.handle.offsetHeight,this.unselectable(this.slider,!0)},n.prototype.onmousemove=function(e){e.preventDefault(),e.touches&&(e=e.touches[0]);var t=this.handleOffsetY+this.startY-e.clientY,s=this.steps?r.find(t,this.steps):t;0>=t?this.setPosition(0):t>=this.restrictHandleY?this.setPosition(this.restrictHandleY):this.setPosition(s),this.setValue(this.handle.style.bottom,this.slider.offsetHeight-this.handle.offsetHeight)},n.prototype.onmouseup=function(){this.unselectable(this.slider,!1)}}),e.alias("component-events/index.js","powerange/deps/events/index.js"),e.alias("component-events/index.js","events/index.js"),e.alias("component-event/index.js","component-events/deps/event/index.js"),e.alias("component-delegate/index.js","component-events/deps/delegate/index.js"),e.alias("discore-closest/index.js","component-delegate/deps/closest/index.js"),e.alias("discore-closest/index.js","component-delegate/deps/closest/index.js"),e.alias("component-matches-selector/index.js","discore-closest/deps/matches-selector/index.js"),e.alias("component-query/index.js","component-matches-selector/deps/query/index.js"),e.alias("discore-closest/index.js","discore-closest/index.js"),e.alias("component-event/index.js","component-delegate/deps/event/index.js"),e.alias("component-classes/index.js","powerange/deps/classes/index.js"),e.alias("component-classes/index.js","classes/index.js"),e.alias("component-indexof/index.js","component-classes/deps/indexof/index.js"),e.alias("ui-component-mouse/index.js","powerange/deps/mouse/index.js"),e.alias("ui-component-mouse/index.js","mouse/index.js"),e.alias("component-emitter/index.js","ui-component-mouse/deps/emitter/index.js"),e.alias("component-event/index.js","ui-component-mouse/deps/event/index.js"),e.alias("abpetkov-percentage-calc/percentage-calc.js","powerange/deps/percentage-calc/percentage-calc.js"),e.alias("abpetkov-percentage-calc/percentage-calc.js","powerange/deps/percentage-calc/index.js"),e.alias("abpetkov-percentage-calc/percentage-calc.js","percentage-calc/index.js"),e.alias("abpetkov-percentage-calc/percentage-calc.js","abpetkov-percentage-calc/index.js"),e.alias("abpetkov-closest-num/closest-num.js","powerange/deps/closest-num/closest-num.js"),e.alias("abpetkov-closest-num/closest-num.js","powerange/deps/closest-num/index.js"),e.alias("abpetkov-closest-num/closest-num.js","closest-num/index.js"),e.alias("abpetkov-closest-num/closest-num.js","abpetkov-closest-num/index.js"),e.alias("vesln-super/lib/super.js","powerange/deps/super/lib/super.js"),e.alias("vesln-super/lib/super.js","powerange/deps/super/index.js"),e.alias("vesln-super/lib/super.js","super/index.js"),e.alias("vesln-super/lib/super.js","vesln-super/index.js"),e.alias("powerange/lib/powerange.js","powerange/index.js"),"object"==typeof exports?module.exports=e("powerange"):"function"==typeof define&&define.amd?define([],function(){return e("powerange")}):this.Powerange=e("powerange")})();;
(function($){var DEBUG=false;var version="1.1";$.fn.nailthumb=function(options){var opts=$.extend({},$.fn.nailthumb.defaults,options);return this.each(function(){var $this=$(this);var o=$.metadata?$.extend({},opts,$this.metadata()):opts;thumbize($this,o);});};function thumbize(element,options){var image=setImage(element,options);var container=setContainer(element,options);if(options.serverSideParams){$.fn.nailthumb.setServerSideParams(image,container,options);}debugObject("image",image);debugObject("container",container);if(options.onStart){options.onStart(container,options);}if(options.loadingClass){container.addClass(options.loadingClass);}if(options.preload||image.data("nailthumb.replaceto")){debug("wait on load");image.one("load",function(){debugObject("before check",image);if(!image.data("nailthumb.working")&&!image.data("nailthumb.replacing")){image.data("nailthumb.working",true);debugObject("inside check",image);doThumb(image,container,options);}});var src=image.attr("src");image.attr("src",null).attr("src",src);}else{debug("nail thumb directly");image.data("nailthumb.working",true);doThumb(image,container,options);}}function doThumb(image,container,options){resetImage(image,options);resetContainer(container,options);var imageDims=getImageDims(image,options);debugObject("image",image);debugObject("imageDims",imageDims);if(imageDims.width==0||imageDims.height==0){imageDims=getHiddenCloneDims(image);debugObject("imageCloneDims",imageDims);}var containerDims=getContainerDims(container,options);debugObject("container",container);debugObject("containerDims",containerDims);var prop=getProportion(containerDims,imageDims,options);debug("proportions",prop);resize(image,imageDims,container,containerDims,prop,options);}function setImage(element,options){var image=element.find("img").first();var finder=options.imageCustomFinder;if(!finder&&options.imageUrl){finder=imageUrlFinder;}else{if(!finder&&options.imageFromWrappingLink){finder=imageFromWrappingLinkFinder;}}if(finder){var img=finder(element,options);debugObject("finder",img);if(!img){img=[];}if(img.length>0){image=img;image.css("display","none");if(!image.data("nailthumb.replaceto")){image.data("nailthumb.replaceto",element);}image.data("nailthumb.originalImageDims",null);}}if(image.length==0){if(element.is("img")){image=element;}}return image;}function imageUrlFinder(element,options){var image=$("<img />").attr("src",options.imageUrl).css("display","none").data("nailthumb.replaceto",element);element.append(image);return image;}function imageFromWrappingLinkFinder(element,options){var image;var link=element.find("a").first();if(link.length==0&&element.is("a")){link=element;}if(link.attr("href")){image=$("<img />").attr("src",link.attr("href")).css("display","none").data("nailthumb.replaceto",link);if(link.attr("title")){image.attr("title",link.attr("title"));}link.append(image);}return image;}function resetImage(image,options){if(!options.nostyle){image.css({"position":"relative"});}if(!image.data("nailthumb.originalImageDims")){image.css({"width":"auto","height":"auto","top":0,"left":0}).removeAttr("width").removeAttr("height");}}function setContainer(element,options){var container=element;if(element.is("img")){if(options.ifImageAddContainer){var c=$("<div></div>");if(!element.parent().hasClass("nailthumb-container")){element.wrap(c)};}container=element.parent();}return container;}function resetContainer(container,options){if(options.containerClass){container.addClass(options.containerClass);}if(!options.nostyle){container.css({"overflow":"hidden","padding":"0px"});}if(options.replaceAnimation=="animate"){if(options.width||options.height){container.animate({"width":options.width,"height":options.height},options.animationTime,options.animation);}}else{if(options.width){container.width(options.width);}if(options.height){container.height(options.height);}}container.find("span."+options.titleClass).remove();}function resize(image,imageDims,container,containerDims,prop,options){var iw=imageDims.width*prop;var ih=imageDims.height*prop;var top=0,left=0,diff;var direction=getDirections(options.fitDirection);if(ih<containerDims.innerHeight){switch(direction.v){case"center":top=-(ih-containerDims.innerHeight)/2;break;case"bottom":top=-(ih-containerDims.innerHeight);diff="bottom";break;case"top":top=0;diff="top";break;default:break;}}else{if(ih>containerDims.innerHeight){switch(direction.v){case"center":top=-(ih-containerDims.innerHeight)/2;break;case"bottom":top=-(ih-containerDims.innerHeight);break;default:break;}}}if(iw<containerDims.innerWidth){switch(direction.h){case"center":left=-(iw-containerDims.innerWidth)/2;break;case"right":left=-(iw-containerDims.innerWidth);break;default:break;}}else{if(iw>containerDims.innerWidth){switch(direction.h){case"center":left=-(iw-containerDims.innerWidth)/2;break;case"right":left=-(iw-containerDims.innerWidth);break;default:break;}}}image.addClass(options.imageClass);if(image.data("nailthumb.replaceto")){replaceImage(image,imageDims,container,containerDims,ih,iw,left,top,diff,options);}else{showImage(image,imageDims,container,containerDims,ih,iw,left,top,diff,options);}}function replaceImage(image,imageDims,container,containerDims,ih,iw,left,top,diff,options){var element=image.data("nailthumb.replaceto");var replaceto=findReplaceTo(element,options);image.data("nailthumb.replacing",true);image.load(function(){image.data("nailthumb.replacing",null);});if(replaceto){replaceto.replaceWith(image);}else{element.append(image);}if(options.afterReplace){options.afterReplace(container,image,options);}showImage(image,imageDims,container,containerDims,ih,iw,left,top,diff,options);}function showImage(image,imageDims,container,containerDims,ih,iw,left,top,diff,options){if(options.replaceAnimation=="animate"){image.css("display","inline");container.animate({"width":containerDims.innerWidth,"height":containerDims.innerHeight},options.animationTime,options.animation);image.animate({"width":iw,"height":ih,"top":top,"left":left},options.animationTime,options.animation,function(){afterAppear(image,imageDims,container,containerDims,ih,iw,left,top,diff,options);});}else{container.css({"width":containerDims.innerWidth,"height":containerDims.innerHeight});if(options.replaceAnimation){image.css("display","none");}image.css({"width":iw,"height":ih,"top":top,"left":left});if(options.replaceAnimation=="fade"){image.fadeIn(options.animationTime,options.animation,function(){afterAppear(image,imageDims,container,containerDims,ih,iw,left,top,diff,options);});}else{if(options.replaceAnimation=="slide"){image.slideDown(options.animationTime,options.animation,function(){afterAppear(image,imageDims,container,containerDims,ih,iw,left,top,diff,options);});}else{if(options.replaceAnimation&&options.replaceAnimation instanceof Function){options.replaceAnimation(image,function(){afterAppear(image,imageDims,container,containerDims,ih,iw,left,top,diff,options);},options);if(!options.selfStartAfterAppear){afterAppear(image,imageDims,container,containerDims,ih,iw,left,top,diff,options);}}else{image.css("display","inline");afterAppear(image,imageDims,container,containerDims,ih,iw,left,top,diff,options);}}}}}function afterAppear(image,imageDims,container,containerDims,ih,iw,left,top,diff,options){if(options.afterAppear){options.afterAppear(container,image,options);}image.data("nailthumb.replaceto",null);decorate(image,imageDims,container,containerDims,ih,iw,left,top,diff,options);}function findReplaceTo(element,options){var rep=null;element.find("img").each(function(){if(!rep&&!$(this).data("nailthumb.replaceto")){rep=$(this);}});return rep;}function decorate(image,imageDims,container,containerDims,ih,iw,left,top,diff,options){if(options.title||(options.titleAttr&&image.attr(options.titleAttr))){var title=options.title?options.title:image.attr(options.titleAttr);if(title){var span=$('<span class="'+options.titleClass+'">'+title+"</span>");if(containerDims.innerHeight>ih){span.css("top",containerDims.innerHeight-ih);}else{span.css("top","0px");}container.append(span);
var tit=getHiddenDims(span);var im=getHiddenDims(image);debugObject("decorate containerDims",containerDims);debugObject("decorate imageDims",imageDims);debugObject("decorate imageDims",im);debugObject("decorate tit",tit);var outbound=containerDims.offsetTop+containerDims.innerHeight-tit.offsetTop;if(containerDims.height>containerDims.innerHeight){outbound+=(containerDims.height-containerDims.innerHeight)/2;}span.css("top","+="+outbound);if(iw<tit.width){span.css("width",iw);}if(left>0){span.css("left",left);}var delta=tit.height;if(containerDims.innerHeight>ih&&diff!="bottom"){delta+=(containerDims.innerHeight-ih)/((diff=="top")?1:2);}var clone=span.clone();clone.css("width","auto").css("display","none").css("position","absolute");container.append(clone);var cloneDims=getHiddenDims(clone);clone.remove();debugObject("decorate cloneDims",cloneDims);if(options.titleWhen=="hover"){container.unbind("mouseenter mouseleave").hover(function(){span.find("span."+options.titleScrollerClass).css("left",0);containerDims=getHiddenDims(container);tit=getHiddenDims(span);outbound=containerDims.offsetTop+containerDims.innerHeight-tit.offsetTop;if(containerDims.height>containerDims.innerHeight){outbound+=(containerDims.height-containerDims.innerHeight)/2;}debugObject("decorate hover tit",tit);debug("decorate hover outbound",tit);var doubleDelta=0;if(outbound<0){span.css("top","+="+outbound);doubleDelta=delta;}else{doubleDelta=delta-outbound;}if(options.animateTitle){resetScrollTitle(span,options);span.stop(true).animate({top:"-="+doubleDelta},options.titleAnimationTime,options.titleAnimation,function(){scrollTitle(span,cloneDims.width,containerDims.innerWidth,options);});}else{span.css({top:"-="+doubleDelta});scrollTitle(span,cloneDims.width,containerDims.innerWidth,options);}},function(){if(options.animateTitle){resetScrollTitle(span,options);span.animate({top:"+="+delta},options.titleAnimationTime,options.titleAnimation,function(){resetScrollTitle(span,options);});}else{resetScrollTitle(span,options);span.css({top:"+="+delta});}});}else{if(options.animateTitle){span.animate({top:"-="+delta},options.titleAnimationTime,options.titleAnimation,function(){scrollTitle(span,cloneDims.width,containerDims.innerWidth,options);});}else{span.css({top:"-="+delta});scrollTitle(span,cloneDims.width,containerDims.innerWidth,options);}}}}if(options.onFinish){options.onFinish(container,options);}if(options.loadingClass){container.removeClass(options.loadingClass);}image.data("nailthumb.working",null);}function resetScrollTitle(span,options){span.find("span."+options.titleScrollerClass).stop();}function scrollTitle(span,width,visibleWidth,options){if(width>visibleWidth&&options.titleScrolling){if(span.find("span."+options.titleScrollerClass).length==0){span.wrapInner('<span class="'+options.titleScrollerClass+'" />');span.find("span."+options.titleScrollerClass).width(width).css("position","relative").css("white-space","nowrap");}span.find("span."+options.titleScrollerClass).css("left",0);setTimeout(scrollFunction(span,width,visibleWidth,options),1000);}}function scrollFunction(span,width,visibleWidth,options){return function(){var indent=Number(span.find("span."+options.titleScrollerClass).css("left").replace(/[^-\d]/g,""));debug("indent",indent);debug("width",width);debug("visibleWidth",visibleWidth);debug("width <= -indent",(width<=-indent));var delta=width+indent;if(delta<=0){span.find("span."+options.titleScrollerClass).css("left",visibleWidth);delta=width+visibleWidth;}delta+=10;span.find("span."+options.titleScrollerClass).animate({"left":"-="+delta},width*1000/30,"linear",scrollFunction(span,width,visibleWidth,options));};}function getProportion(containerDims,imageDims,options){if(options.proportions!=null&&options.proportions>0){return options.proportions;}else{var prop=containerDims.innerWidth/imageDims.width;if(options.method&&options.method=="resize"){if(containerDims.innerHeight/imageDims.height<prop){prop=containerDims.innerHeight/imageDims.height;}}else{if(containerDims.innerHeight/imageDims.height>prop){prop=containerDims.innerHeight/imageDims.height;}}if(options.maxEnlargement&&options.maxEnlargement<prop){prop=options.maxEnlargement;}if(options.maxShrink&&options.maxShrink>prop){prop=options.maxShrink;}return prop;}}function getDirections(option){var dir={h:"center",v:"center"};if(option){var opts=option.split(" ");if(opts.length>0){dir=getDirection(opts[0],dir);}if(opts.length>1){dir=getDirection(opts[1],dir);}}return dir;}function getDirection(str,d){switch(str){case"top":d.v="top";break;case"bottom":d.v="bottom";break;case"left":d.h="left";break;case"right":d.h="right";break;default:break;}return d;}function getImageDims(image,options){var imageDims;if(!image.data("nailthumb.originalImageDims")){imageDims=getHiddenDims(image);image.data("nailthumb.originalImageDims",imageDims);if(!options.keepImageDimensions){image.one("load",function(){image.data("nailthumb.originalImageDims",null);});}}else{imageDims=image.data("nailthumb.originalImageDims");}return imageDims;}function getContainerDims(container,options){var containerDims=getHiddenDims(container);if(options.width){containerDims.innerWidth=options.width;}if(options.height){containerDims.innerHeight=options.height;}return containerDims;}function getDims(elem){var offset=$(elem).offset();return{offsetTop:offset.top,offsetLeft:offset.left,width:$(elem).outerWidth(),height:$(elem).outerHeight(),innerWidth:$(elem).innerWidth(),innerHeight:$(elem).innerHeight()};}function getHiddenDims(elems){var dims=null,i=0,offset,elem;while((elem=elems[i++])){var hiddenElems=$(elem).parents().andSelf().filter(":hidden");if(!hiddenElems.length){dims=getDims(elem);}else{var backupStyle=[];hiddenElems.each(function(){var style=$(this).attr("style");style=typeof style=="undefined"?"":style;backupStyle.push(style);$(this).attr("style",style+" display: block !important;");});hiddenElems.eq(0).css("left",-10000);dims=getDims(elem);hiddenElems.each(function(){$(this).attr("style",backupStyle.shift());});}}return dims;}function getHiddenCloneDims(elems){var dims=null,i=0,offset,elem;while((elem=elems[i++])){var hiddenElems=$(elem).parents().andSelf().filter(":hidden");if(!hiddenElems.length){dims=getDims(elem);}else{var backupStyle=[];hiddenElems.each(function(){var style=$(this).attr("style");style=typeof style=="undefined"?"":style;backupStyle.push(style);$(this).attr("style",style+" display: block !important;");});hiddenElems.eq(0).css("left",-10000);var clone=hiddenElems.eq(0).clone();$("body").append(clone);dims=getDims(clone);hiddenElems.each(function(){$(this).attr("style",backupStyle.shift());});clone.remove();}}return dims;}$.fn.nailthumb.evalServerSideParams=function(image,container,options){if(options.serverSideParams){var params={};if(!options.serverSideParams.noServerResize){var w=null,h=null;if(options.serverSideParams.width){w=options.serverSideParams.width;}else{if(options.width){w=options.width;}}if(options.serverSideParams.height){h=options.serverSideParams.height;}else{if(options.height){h=options.height;}}if(!(w&&h)){resetContainer(container,options);var containerDims=getContainerDims(container,options);w=containerDims.innerWidth;h=containerDims.innerHeight;}if(w&&h){params.w=w;params.h=h;if(options.serverSideParams.mode!="resize"){if(options.method=="crop"){params.mode="crop";}if(options.serverSideParams.mode){params.mode=options.serverSideParams.mode;}}}}$.each(options.serverSideParams,function(key,val){if(key!="width"&&key!="height"&&key!="mode"&&key!="noServerResize"&&val){params[key]=val;}});var pars="";$.each(params,function(key,val){pars+=";"+key+"="+val;});debug(pars,params);return pars;}else{return"";}};$.fn.nailthumb.setServerSideParams=function(image,container,options){if(options.serverSideParams){var url=image.attr("src");if(image.data("nailthumb.originalImageUrl")){url=image.data("nailthumb.originalImageUrl");}image.data("nailthumb.originalImageUrl",url);var pars=$.fn.nailthumb.evalServerSideParams(image,container,options);
url+=pars;image.attr("src",url);}};$.fn.nailthumb.toggleDebug=function(){DEBUG=!DEBUG;};$.fn.nailthumb.doThumb=function(image,container,options){doThumb(image,container,options);};$.fn.nailthumb.defaults={onStart:null,onFinish:null,loadingClass:"nailthumb-loading",imageUrl:null,imageFromWrappingLink:false,imageCustomFinder:null,imageClass:"nailthumb-image",afterReplace:null,afterAppear:null,replaceAnimation:"fade",selfStartAfterAppear:false,animationTime:1000,animation:"swing",keepImageDimensions:false,method:"crop",fitDirection:null,proportions:null,ifImageAddContainer:true,containerClass:"nailthumb-container",maxEnlargement:null,maxShrink:null,preload:true,nostyle:false,width:null,height:null,title:null,titleClass:"nailthumb-title",titleAttr:"title",titleWhen:"hover",titleScrolling:true,titleScrollerClass:"nailthumb-title-scroller",animateTitle:true,titleAnimationTime:500,titleAnimation:"swing",serverSideParams:null};function log(log,jQueryobj){try{debug(log,jQueryobj,true);}catch(ex){}}function debug(log,jQueryobj,force){try{if((DEBUG&&window.console&&window.console.log)||force){window.console.log(log+": "+jQueryobj);}}catch(ex){}}function debugObject(log,jQueryobj,force){try{if(!jQueryobj){jQueryobj=log;}debug(log,jQueryobj);if((DEBUG&&window.console&&window.console.log)||force){window.console.debug(jQueryobj);}}catch(ex){}}})(jQuery);;
$(document).ready(function ()
{
	if ($(".no-touch").length > 0 || $(".touch.desktop").length > 0)
	{
		settings.userDialog.instance = new UserInfoDialog();

		if (typeof Sys != "undefined" && typeof Sys.WebForms != "undefined")
		{
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function()
			{
				settings.userDialog.instance.init();
			});
		}
	}
});

var UserInfoDialog = function ()
{
	var theReturnObject =
	{
		mInfoDialog: null,
		mHideTimeOut: 0,
		mDialogVisible: false,
		mDataCache: {},
		mShowDelay: 300,
		mShowDelayTimeout: 0,

		init: function ()
		{
			if(this.mInfoDialog == null)
				this.createInfoDialog();

			this.setHandlers();
		},

		setHandlers: function ()
		{
			var theThis = this;

			$("*[data-user-id]").each(function ()
			{
				var theObject = $(this);

				if (theObject.parents('.widget-followed-users').length == 0)
				{
					// If already initialized return
					if(theObject.data("userDialogInitialized") == true)
						return;

					if ($(".webGuidelines").length > 0)
					{
						theObject.click(function ()
						{
							var focusTimeout;

							if (!theThis.mDialogVisible)
							{
								theThis.showDialog(theObject);

								theThis.mInfoDialog.off("focusout").focusout(function ()
								{
									clearTimeout(focusTimeout);

									focusTimeout = setTimeout(function ()
									{
										if ($(":focus").parents("#userInfoDialog").length == 0 || $(":focus")[0] == $("#userInfoDialog .tabCloser")[0])
										{
											theThis.hideInfoDialog();
											theObject.focus();
										}
									}, 40);
								});

								setTimeout(function ()
								{
									$("#userInfoDialog .userName a").focus();
								}, 500);
							}
							else
								theThis.hideInfoDialog();

							return false;
						});
					}
					else
					{
						theObject.hover(function ()
						{
							theThis.showDialog(theObject);
						},
						function ()
						{
							theThis.mDialogVisible = false;

							clearTimeout(theThis.mShowDelayTimeout);
							clearTimeout(theThis.mHideTimeOut);
							theThis.mHideTimeOut = setTimeout(function () { theThis.hideInfoDialog(); }, 100);
						});
					}

					theObject.data("userDialogInitialized", true);
				}
			});
		},

		showDialog: function (aObject)
		{
			var theThis = this;
			var theObject = aObject;

			theThis.mDialogVisible = true;

			clearTimeout(theThis.mHideTimeOut);

			if (parseInt(theObject.attr("data-user-id")) > 0)
			{
				// First try to get data from cache
				if (typeof theThis.mDataCache[theObject.attr("data-user-id")] != "undefined" && theThis.mDataCache[theObject.attr("data-user-id")] != null)
				{
					theThis.fillInfoDialog(theThis.mDataCache[theObject.attr("data-user-id")])
					theThis.showInfoDialog(theObject);
				}
				else
				{
					$.ajax(
					{
						url: "/api/user",
						data:
						{
							userID: theObject.attr("data-user-id"),
							sectionID: settings.section.ID,
							token: $("input[name='__RequestVerificationToken']").val()
						}
					})
					.done(function (aData)
					{
						if (aData != null) {

							theThis.mDataCache[theObject.attr("data-user-id")] = aData;

							if (!theThis.mDialogVisible)
								return;

							theThis.fillInfoDialog(aData);
							theThis.showInfoDialog(theObject);
						}
					})
					.error(function ()
					{
						$.fn.showError(settings.errors.generalErrorText + " ('" + theObject.attr("data-user-id") + "') (500.41)", "console");
					});
				}
			}
		},

		createInfoDialog: function ()
		{
			this.mInfoDialog = $('<div>');
			this.mInfoDialog.attr("id", "userInfoDialog");
			this.mInfoDialog.attr("role", "dialog");
			this.mInfoDialog.addClass("infoDialog");

			this.mInfoDialog.css({position: "absolute", zIndex: 1100, display: "none"});

			$("body").append(this.mInfoDialog);
		},

		fillInfoDialog: function (aData)
		{
			var theThis = this;
			var theInfoContainer = $('<div class="infoContainer"></div>');
			var theUserInfo = $('<ul class="userInfo"></ul>')
			var theUserLinks = $('<div class="userLinks"></div>');

			this.mInfoDialog.empty();

			this.mInfoDialog.attr("aria-label", "Profiel popup voor "+ aData.FirstName + " " + aData.LastName);

			if(aData.ProfileImage != "")
				this.mInfoDialog.append('<div class="userPhoto"><a href="' + aData.UserUrl + '"><img src="' + aData.ProfileImage + '?width=80&amp;height=80" alt="Bekijk profiel van ' + aData.FirstName + ' ' + aData.LastName + '" /></a></div>');

			theInfoContainer.append('<h2 class="userName"><a href="' + aData.UserUrl + '">' + aData.FirstName + ' ' + aData.MiddleName + ' ' + aData.LastName + ' ' + '</a></h2>');

			if(aData.Occupation != "" || aData.Location != "")
			{
				var theOccupationString = aData.Occupation;

				if(aData.Occupation != "" && aData.Location != "")
					theOccupationString += " " + settings.various.atText + " ";

				theOccupationString += aData.Location;

				theUserInfo.append('<li class="itemInformation">' +  theOccupationString + '</li>');
			}

			if(aData.Phone1 != "")
				theUserInfo.append('<li class="profileIcon phone icon-phone before">' +  aData.Phone1 + '</li>');
			if(aData.Phone2 != "")
				theUserInfo.append('<li class="profileIcon phone icon-phone before">' +  aData.Phone2 + '</li>');
			if(aData.Mobile != "")
				theUserInfo.append('<li class="profileIcon phone icon-mobile before">' +  aData.Mobile + '</li>');

			theInfoContainer.append(theUserInfo);
			this.mInfoDialog.append(theInfoContainer);
			this.mInfoDialog.append('<div class="clearBoth"></div>');

			if(settings.user.follow && settings.user.ID > 0)
				theUserLinks.append('<div class="followUserToolbar toolbar"><div class="button followuser transparent icon-bell before"><input type="button" value="' + settings.buttons.followText + '" title="' + settings.buttons.followText + '" /><input type="checkbox" class="hide" /></div></div>');

			if(aData.UserEmail != "")
				theUserLinks.append('<div class="button transparent icon-mail before"><a href="mailto:' + aData.UserEmail + '">E-mail<span class="screenReaderContent"> ' + aData.UserEmail + '</span></a></div>');

			if(aData.UserUrl != "" && aData.UserUrl.indexOf("mailto:") == -1)
				theUserLinks.append('<div class="button transparent icon-user before"><a href="' + aData.UserUrl + '">' + settings.buttons.profileText + '</a></div>');

			this.mInfoDialog.append(theUserLinks);

			$('.userLinks .followUserToolbar .button.followuser').initializeUserFollowButtons(aData.UserID, aData.FirstName);

			this.mInfoDialog.append('<div class="tabCloser" tabindex="0"></div>');

			this.mInfoDialog.mouseleave(function ()
			{
				clearTimeout(theThis.mShowDelayTimeout);
				clearTimeout(theThis.mHideTimeOut);
				theThis.mHideTimeOut = setTimeout(function () { theThis.hideInfoDialog(); }, 100);
			});
		},

		showInfoDialog: function (aObject, aSkipDelay)
		{
			var theThis = this;

			clearTimeout(this.mShowDelayTimeout);

			if(aSkipDelay != true)
			{
				this.mInfoDialog.css({display: "none"});
				this.mShowDelayTimeout = setTimeout(function () { theThis.showInfoDialog(aObject, true); }, this.mShowDelay);
				return;
			}

			var thePosition = aObject.offset();
			var theTargetTop = (thePosition.top + parseInt(aObject.css("paddingTop")) - this.mInfoDialog.outerHeight() - 8);
			var theArrowClass = "bottom";

			clearTimeout(this.mHideTimeOut);

			if(theTargetTop - $(window).scrollTop() < 0)
			{
				theTargetTop = (thePosition.top + aObject.outerHeight() - parseInt(aObject.css("paddingBottom")) + 8);
				theArrowClass = "top";
			}

			this.mInfoDialog.append('<div class="dialogArrow ' + theArrowClass + '"></div>');

			this.mInfoDialog.css({left: thePosition.left + parseInt(aObject.css("paddingLeft")), top: theTargetTop, display: "block"});
		},

		hideInfoDialog: function ()
		{
			if(!this.mInfoDialog.is(":hover"))
			{
				clearTimeout(this.mShowDelayTimeout);

				this.mDialogVisible = false;
				this.mInfoDialog.hide();
				this.mInfoDialog.empty();
			}
		}
	};

	theReturnObject.init();

	return theReturnObject;
}
;
// jquery.tweet.js - See http://tweet.seaofclouds.com/ or https://github.com/seaofclouds/tweet for more info
// Copyright (c) 2008-2012 Todd Matthews & Steve Purcell
(function (factory) {
  if (typeof define === 'function' && define.amd)
    define(['jquery'], factory); // AMD support for RequireJS etc.
  else
    factory(jQuery);
}(function ($) {
  $.fn.tweet = function(o){
    var s = $.extend({
      username: null,                           // [string or array] required unless using the 'query' option; one or more twitter screen names (use 'list' option for multiple names, where possible)
      list: null,                               // [string]   optional name of list belonging to username
      favorites: false,                         // [boolean]  display the user's favorites instead of his tweets
      query: null,                              // [string]   optional search query (see also: http://search.twitter.com/operators)
	  lang: "all",								// [string]	  set language of tweets
      avatar_size: null,                        // [integer]  height and width of avatar if displayed (48px max)
      count: 3,                                 // [integer]  how many tweets to display?
      fetch: null,                              // [integer]  how many tweets to fetch via the API (set this higher than 'count' if using the 'filter' option)
      page: 1,                                  // [integer]  which page of results to fetch (if count != fetch, you'll get unexpected results)
      retweets: true,                           // [boolean]  whether to fetch (official) retweets (not supported in all display modes)
      intro_text: null,                         // [string]   do you want text BEFORE your your tweets?
      outro_text: null,                         // [string]   do you want text AFTER your tweets?
      join_text:  null,                         // [string]   optional text in between date and tweet, try setting to "auto"
      auto_join_text_default: "zei ik",      	// [string]   auto text for non verb: "I said" bullocks
      auto_join_text_ed: "Ik",                 	// [string]   auto text for past tense: "I" surfed
      auto_join_text_ing: "Ik was",             // [string]   auto tense for present tense: "I was" surfing
      auto_join_text_reply: "reageerde ik op",  // [string]   auto tense for replies: "I replied to" @someone "with"
      auto_join_text_url: "keek ik naar", 		// [string]   auto tense for urls: "I was looking at" http:...
      loading_text: null,                       // [string]   optional loading text, displayed while tweets load
      refresh_interval: null,                   // [integer]  optional number of seconds after which to reload tweets
      twitter_url: "twitter.com",               // [string]   custom twitter url, if any (apigee, etc.)
      twitter_api_url: "/api/twitter",       	// [string]   custom twitter api url, if any (apigee, etc.)
      twitter_search_url: "search.twitter.com", // [string]   custom twitter search url, if any (apigee, etc.)
      template: "{avatar}{join}{text}<br>{time}",  // [string or function] template used to construct each tweet <li> - see code for available vars
      comparator: function(tweet1, tweet2) {    // [function] comparator used to sort tweets (see Array.sort)
        return tweet2.tweet_time - tweet1.tweet_time;
      },
      filter: function(tweet) {                 // [function] whether or not to include a particular tweet (be sure to also set 'fetch')
        return true;
      }
      // You can attach callbacks to the following events using jQuery's standard .bind() mechanism:
      //   "loaded" -- triggered when tweets have been fetched and rendered
    }, o);

    // See http://daringfireball.net/2010/07/improved_regex_for_matching_urls
    var url_regexp = /\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi;

    // Expand values inside simple string templates with {placeholders}
    function t(template, info) {
      if (typeof template === "string") {
        var result = template;
        for(var key in info) {
          var val = info[key];
          result = result.split('{'+key+'}').join(val === null ? '' : val);
        }
        return result;
      } else return template(info);
    }
    // Export the t function for use when passing a function as the 'template' option
    $.extend({tweet: {t: t}});

    function replacer (regex, replacement) {
      return function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(regex, replacement));
        });
        return $(returning);
      };
    }

    function escapeHTML(s) {
      return s.replace(/</g,"&lt;").replace(/>/g,"^&gt;");
    }

    $.fn.extend({
      linkUser: replacer(/(^|[\W])@(\w+)/gi, "$1<span class=\"at\">@</span><a href=\"http://"+s.twitter_url+"/$2\" target=\"_blank\" rel=\"noreferrer\">$2</a>"),
      // Support various latin1 (\u00**) and arabic (\u06**) alphanumeric chars
      linkHash: replacer(/(?:^| )[\#]+([\w\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0600-\u06ff]+)/gi,
                         ' <a href="https://twitter.com/search?q=%23$1&lang=all'+
                         ((s.username && s.username.length === 1 && !s.list) ? '&from='+s.username.join("%2BOR%2B") : '')+
                         '" class="tweet_hashtag" target=\"_blank\" rel=\"noreferrer\">#$1</a>'),
      makeHeart: replacer(/(&lt;)+[3]/gi, "<tt class='heart'>&#x2665;</tt>")
    });

    function linkURLs(text, entities) {
      return text.replace(url_regexp, function(match) {
        var url = (/^[a-z]+:/i).test(match) ? match : "http://"+match;
        var text = match;
        for(var i = 0; i < entities.length; ++i) {
          var entity = entities[i];
          if (entity.url === url && entity.expanded_url) {
            url = entity.expanded_url;
            text = entity.display_url;
            break;
          }
        }
        return "<a href=\""+escapeHTML(url)+"\" target=\"_blank\" rel=\"noreferrer\">"+escapeHTML(text)+"</a>";
      });
    }

    function parse_date(date_str) {
      // The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
      // cannot handle in IE. We therefore perform the following transformation:
      // "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
      return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
    }

    function extract_relative_time(date) {
      var toInt = function(val) { return parseInt(val, 10); };
      var relative_to = new Date();
      var delta = toInt((relative_to.getTime() - date) / 1000);
      if (delta < 1) delta = 0;
      return {
        days:    toInt(delta / 86400),
        hours:   toInt(delta / 3600),
        minutes: toInt(delta / 60),
        seconds: toInt(delta)
      };
    }

    function format_relative_time(time_ago) {
      if ( time_ago.days > 2 )     return time_ago.days + " " + settings.widgets.twitterDaysAgoText;
      if ( time_ago.hours > 24 )   return settings.widgets.twitterDayAgoText;
      if ( time_ago.hours > 2 )    return time_ago.hours + " " + settings.widgets.twitterHoursAgoText;
      if ( time_ago.minutes > 45 ) return settings.widgets.twitterHourAgoText;
      if ( time_ago.minutes > 2 )  return time_ago.minutes + " " + settings.widgets.twitterMinutesAgoText;
      if ( time_ago.seconds > 1 )  return time_ago.seconds + " " + settings.widgets.twitterSecondsAgoText;
      return 'Zojuist';
    }

    function build_auto_join_text(text) {
      if (text.match(/^(@([A-Za-z0-9-_]+)) .*/i)) {
        return s.auto_join_text_reply;
      } else if (text.match(url_regexp)) {
        return s.auto_join_text_url;
      } else if (text.match(/^((\w+ed)|just) .*/im)) {
        return s.auto_join_text_ed;
      } else if (text.match(/^(\w*ing) .*/i)) {
        return s.auto_join_text_ing;
      } else {
        return s.auto_join_text_default;
      }
    }

    function build_api_url() {
      var proto = ('https:' === document.location.protocol ? 'https:' : 'http:');
      var count = (s.fetch === null) ? s.count : s.fetch;
      var common_params = '&include_entities=1&callback=?';		
      if (s.list) {
        return s.twitter_api_url+"/1.1/"+s.username[0]+"/lists/"+s.list+"/statuses.json?page="+s.page+"&per_page="+count;
      } else if (s.favorites) {
        return s.twitter_api_url+"/favorites?screen_name="+s.username[0]+"&page="+s.page+"&count="+count;
      } else if (s.query === null && s.username.length === 1) {
        return s.twitter_api_url+'/timeline?screen_name='+s.username[0]+'&count='+count+(s.retweets ? '&include_rts=1' : '&include_rts=0');
      } else {
        var query = (s.query || 'from:'+s.username.join(' OR from:'));
        return s.twitter_api_url+'/search?q='+encodeURIComponent(query)+'&rpp='+count+'&lang='+s.lang+"&screen_name=";
      }
    }

    function extract_avatar_url(item, secure) {
      if (secure) {
        return ('user' in item) ?
          item.user.profile_image_url_https :
          extract_avatar_url(item, false).
            replace(/^http:\/\/[a-z0-9]{1,3}\.twimg\.com\//, "https://s3.amazonaws.com/twitter_production/");
      } else {
        return item.profile_image_url || item.user.profile_image_url;
      }
    }

    // Convert twitter API objects into data available for
    // constructing each tweet <li> using a template
    function extract_template_data(item){
      var o = {};
      o.item = item;
      o.source = item.source;
      o.screen_name = item.from_user || item.user.screen_name;
      // The actual user name is not returned by all Twitter APIs, so please do not
      // file an issue if it is empty:
      o.name = item.from_user_name || item.user.name;
      o.retweet = typeof(item.retweeted_status) != 'undefined';

      o.tweet_time = parse_date(item.created_at);
      o.join_text = s.join_text === "auto" ? build_auto_join_text(item.text) : s.join_text;
      o.tweet_id = item.id_str;
      o.twitter_base = "http://"+s.twitter_url+"/";
      o.user_url = o.twitter_base+o.screen_name;
      o.tweet_url = o.user_url+"/status/"+o.tweet_id;
      o.reply_url = o.twitter_base+"intent/tweet?in_reply_to="+o.tweet_id;
      o.retweet_url = o.twitter_base+"intent/retweet?tweet_id="+o.tweet_id;
      o.favorite_url = o.twitter_base+"intent/favorite?tweet_id="+o.tweet_id;
      o.retweeted_screen_name = o.retweet && item.retweeted_status.user.screen_name;
      o.tweet_relative_time = format_relative_time(extract_relative_time(o.tweet_time));
      o.entities = item.entities ? (item.entities.urls || []).concat(item.entities.media || []) : [];
      o.tweet_raw_text = o.retweet ? ('RT @'+o.retweeted_screen_name+' '+item.retweeted_status.text) : item.text; // avoid '...' in long retweets
      o.tweet_text = $([linkURLs(o.tweet_raw_text, o.entities)]).linkUser().linkHash()[0];
      o.retweeted_tweet_text = $([linkURLs(item.text, o.entities)]).linkUser().linkHash()[0];
      o.tweet_text_fancy = $([o.tweet_text]).makeHeart()[0];

      o.avatar_size = s.avatar_size;
      o.avatar_url = extract_avatar_url(o.retweet ? item.retweeted_status : item, (document.location.protocol === 'https:'));
      o.avatar_screen_name = o.retweet ? o.retweeted_screen_name : o.screen_name;
      o.avatar_profile_url = o.twitter_base+o.avatar_screen_name;

      // Default spans, and pre-formatted blocks for common layouts
      o.user = t('<a class="tweet_user" href="{user_url}" target=\"_blank\" rel=\"noreferrer\">{screen_name}</a>', o);
      o.join = s.join_text ? t('<span class="tweet_join">{join_text}</span>', o) : '';
      o.avatar = o.avatar_size ?
        t('<a class="tweet_avatar" href="{avatar_profile_url}" target=\"_blank\" rel=\"noreferrer\"><img src="{avatar_url}" height="{avatar_size}" width="{avatar_size}" alt="{avatar_screen_name}\'s avatar" title="{avatar_screen_name}\'s avatar" /></a>', o) : '';
      o.time = t('<span class="tweet_time"><a href="{tweet_url}" title="view tweet on twitter" target=\"_blank\" rel=\"noreferrer\">{tweet_relative_time}</a></span>', o);
      o.text = t('<span class="tweet_text">{tweet_text_fancy}</span>', o);
      o.retweeted_text = t('<span class="tweet_text">{retweeted_tweet_text}</span>', o);
      o.reply_action = t('<a class="tweet_action tweet_reply" href="{reply_url}" target=\"_blank\" rel=\"noreferrer\">reply</a>', o);
      o.retweet_action = t('<a class="tweet_action tweet_retweet" href="{retweet_url}" target=\"_blank\" rel=\"noreferrer\">retweet</a>', o);
      o.favorite_action = t('<a class="tweet_action tweet_favorite" href="{favorite_url}" target=\"_blank\" rel=\"noreferrer\">favorite</a>', o);
      return o;
    }

    function render_tweets(widget, tweets) {
      var list = $('<ul class="tweet_list">');
      list.append($.map(tweets, function(o) { return t(s.template, o); }).join('')).
        children('li:first').addClass('tweet_first').end().
        children('li:odd').addClass('tweet_even').end().
        children('li:even').addClass('tweet_odd');

      $(widget).empty().append(list);
      if (s.intro_text) list.before('<p class="tweet_intro">'+s.intro_text+'</p>');
      if (s.outro_text) list.after('<p class="tweet_outro">'+s.outro_text+'</p>');

      $(widget).trigger("loaded").trigger((tweets.length === 0 ? "empty" : "full"));
      if (s.refresh_interval) {
        window.setTimeout(function() { $(widget).trigger("tweet:load"); }, 1000 * s.refresh_interval);
      }
    }

    function load(widget) {
      var loading = $('<p class="loading">'+s.loading_text+'</p>');
      if (s.loading_text) $(widget).not(":has(.tweet_list)").empty().append(loading);
      
      $.getJSON(build_api_url() + "&token=" + $("input[name='__RequestVerificationToken']").val(), function(data){
		if(data == null)
			return;

        var tweets = $.map(data.statuses || data, extract_template_data);
        tweets = $.grep(tweets, s.filter).sort(s.comparator).slice(0, s.count);
        $(widget).trigger("tweet:retrieved", [tweets]);
      });
    }

    return this.each(function(i, widget){
      if(s.username && typeof(s.username) === "string"){
        s.username = [s.username];
      }

      $(widget).unbind("tweet:render").unbind("tweet:retrieved").unbind("tweet:load").
        bind({
          "tweet:load": function() { load(widget); },
          "tweet:retrieved": function(ev, tweets) {
            $(widget).trigger("tweet:render", [tweets]);
          },
          "tweet:render": function(ev, tweets) {
            render_tweets($(widget), tweets);
          }
        }).trigger("tweet:load");
    });
  };
}));
;
$(document).ready(function ()
{
	settings.liveSearch.instance = new LiveSearch($("#top .search input:text, #searchContainer .search input:text"), settings.liveSearch);
});

var LiveSearch = function(aObject, aSettings)
{
	var theReturnObject =
	{
		mSettings:
		{
			maxResults: 5,
			minimumSearchLength: 3 // Minimum number of characters to search for
		},

		mObject: null,
		mSearchTimeout: 0,
		mInfoContainer: null,
		mResultsContainer: null,
		mSearchCache: [],
		mLastSearchQuery: "",
		mKeyNames: {backspace: 8, del: 46, enter: 13, escape: 27, left: 37, up: 38, right: 39, down: 40},

		init: function (aObject, aSettings)
		{
			this.mObject = aObject;

			if(this.mObject.length == 0)
				return;

			if(typeof aSettings != "undefined" && aSettings != null)
				$.extend(this.mSettings, aSettings);

			this.mObject.attr("autocomplete", "off");

			this.createResultsContainer();
			this.initHandlers();
		},

		createResultsContainer: function ()
		{
			var theThis = this;

			this.mWrapperElement = $('<div class="lsResultsContainer dropDownMenu" aria-live="polite"></div>');
			this.mResultsContainer = $('<ul class="dropDown"></ul>');
			this.mWrapperElement.html(this.mResultsContainer);

			$(window).resize(function ()
			{
				theThis.positionWrapper();
			});

			$("body").append(this.mWrapperElement);
		},

		positionWrapper: function ()
		{
			var thePosition = this.mObject.offset();

			this.mWrapperElement.css(
			{
				top: thePosition.top + this.mObject.outerHeight() - 3 - $(document).scrollTop(),
				left: thePosition.left + 1
			});
		},

		initHandlers: function ()
		{
			var theThis = this;

			this.mObject.keyup(function (aEvent)
			{
				theThis.onKeyUp(aEvent);
			});

			this.mObject.keydown(function (aEvent)
			{
				theThis.onKeyDown(aEvent);
			});

			this.mObject.blur(function (aEvent)
			{
				theThis.onBlur(aEvent);
			});
		},

		onKeyDown: function (aEvent)
		{
			clearTimeout(this.mSearchTimeout);

			var theActiveResult = this.mResultsContainer.find("a.active");
			var theTargetResult;

			switch (aEvent.keyCode)
			{
				case this.mKeyNames.up:
					if(theActiveResult.length > 0)
					{
						theActiveResult.removeClass("active");
						theTargetResult = theActiveResult.parents("li:first").prev().find("a");
					}
					else
						this.mResultsContainer.find("a:last").last().addClass("active");

					aEvent.preventDefault();
					break;

				case this.mKeyNames.down:
					if(theActiveResult.length > 0)
					{
						theActiveResult.removeClass("active");

						theTargetResult = theActiveResult.parents("li:first").next().find("a");
					}
					else
						this.mResultsContainer.find("a:first").first().addClass("active");

					aEvent.preventDefault();
					break;

				case this.mKeyNames.enter:
					if(theActiveResult.length > 0)
					{
						theActiveResult[0].click();

						aEvent.preventDefault();
					}

					break;
			}

			if (theTargetResult && theTargetResult.length > 0) {
				var resultsContainer = theTargetResult.parents('.lsResultsContainer');

				theTargetResult.addClass("active");

				if (theTargetResult.offset().top + theTargetResult.outerHeight() > $(window).height()) {
					var targetScrollTop = theTargetResult.position().top + theTargetResult.outerHeight() - resultsContainer.height();

					resultsContainer.scrollTop(targetScrollTop);
				} else if (theTargetResult.offset().top < resultsContainer.offset().top) {
					var targetScrollTop = theTargetResult.position().top;

					resultsContainer.scrollTop(targetScrollTop);
				}
			}
		},

		onKeyUp: function (aEvent)
		{
			var theThis = this;
			var theSearchQuery = this.mObject.val();

			if($.trim(theSearchQuery).length >= this.mSettings.minimumSearchLength)
			{
				if(this.mLastSearchQuery != theSearchQuery)
				{
					clearTimeout(this.mSearchTimeout);

					this.mSearchTimeout = setTimeout(function () { theThis.search() }, 200);
					this.mLastSearchQuery = theSearchQuery;
				}
			}
			else
			{
				clearTimeout(this.mSearchTimeout);

				this.mLastSearchQuery = "";

				this.hide();
			}
		},

		search: function ()
		{
			var theThis = this;
			var theSearchQuery = theThis.mObject.val();

			var theCacheResult = this.mSearchCache.filter(function (aObject) { return aObject.query == theSearchQuery });

			if(theCacheResult.length > 0)
			{
				this.onDone(theCacheResult[0].data);

				return;
			}

			$.ajax({
				url: "/api/search/",
				cache: false,
				data:
				{
					query: 	theSearchQuery,
					token: 	$("input[name='__RequestVerificationToken']").val()
				}
			})
			.done(function (aData)
			{
				theThis.mSearchCache.push({query: theSearchQuery, data: aData});

				theThis.onDone(aData);
			})
			.fail(function (aData)
			{
				theThis.onFail(aData)
			});
		},

		show: function ()
		{
			this.mWrapperElement.show();
		},

		hide: function ()
		{
			this.mWrapperElement.hide();
		},

		onDone: function (aData)
		{
			this.mResultsContainer.empty();

			for(var i = 0; i < aData.length && i < this.mSettings.maxResults; i++)
			{
				var theContents = '<span class="title">' + aData[i].sectionTitle + '</span>';

				if($.trim(aData[i].contentPageTitle) != "")
					theContents += '<span class="subTitle">' + aData[i].contentPageTitle + '</span>';

				if (aData[i].contentPageType == '88') {
					if (aData[i].contentPageTheme > -1)
						this.mResultsContainer.append('<li><a href="/' + aData[i].sectionPath + '/default.aspx#question=' + aData[i].contentPageTheme + ',' + aData[i].contentPageID + '">' + theContents + '</a></li>');
					else
						this.mResultsContainer.append('<li><a href="/' + aData[i].sectionPath + '/default.aspx#question=' + aData[i].contentPageID + '">' + theContents + '</a></li>');
				}
				else
					this.mResultsContainer.append('<li><a href="/PageByID.aspx?sectionID=' + aData[i].sectionID + '&contentPageID=' + (aData[i].contentPageID == -1 ? '' : aData[i].contentPageID) + '">' + theContents + '</a></li>');
			}

			if(aData.length > 0)
				this.mResultsContainer.append('<li><a class="title icon-search before" href="/shortcuts/search_search.aspx?search=' + encodeURIComponent(this.mObject.val()) + '"> ' + settings.liveSearch.showAllResultsText + '</a></li>');
			else
				this.mResultsContainer.append('<li><a>' + settings.liveSearch.noResultsText + '</a></li>');

			this.mResultsContainer.css({width: this.mObject.outerWidth() - 2});
			this.positionWrapper();
			this.show();
		},

		onFail: function (aData)
		{
			$.fn.showError(settings.errors.generalErrorText + " ('" + aData + "') (500.44)", "console");
		},

		onBlur: function (aEvent)
		{
			theThis = this;

			setTimeout(function () { theThis.hide(); }, 200);
		}
	};

	theReturnObject.init(aObject, aSettings);
	return theReturnObject;
};
;
(function(a){var b=new Array;var c=new Array;a.fn.doAutosize=function(b){var c=a(this).data("minwidth"),d=a(this).data("maxwidth"),e="",f=a(this),g=a("#"+a(this).data("tester_id"));if(e===(e=f.val())){return}var h=e.replace(/&/g,"&").replace(/\s/g," ").replace(/</g,"<").replace(/>/g,">");g.html(h);var i=g.width(),j=i+b.comfortZone>=c?i+b.comfortZone:c,k=f.width(),l=j<k&&j>=c||j>c&&j<d;if(l){f.width(j)}};a.fn.resetAutosize=function(b){var c=a(this).data("minwidth")||b.minInputWidth||a(this).width(),d=a(this).data("maxwidth")||b.maxInputWidth||a(this).closest(".tagsinput").width()-b.inputPadding,e="",f=a(this),g=a("<tester/>").css({position:"absolute",top:-9999,left:-9999,width:"auto",fontSize:f.css("fontSize"),fontFamily:f.css("fontFamily"),fontWeight:f.css("fontWeight"),letterSpacing:f.css("letterSpacing"),whiteSpace:"nowrap"}),h=a(this).attr("id")+"_autosize_tester";if(!a("#"+h).length>0){g.attr("id",h);g.appendTo("body")}f.data("minwidth",c);f.data("maxwidth",d);f.data("tester_id",h);f.css("width",c)};a.fn.addTag=function(d,e){e=jQuery.extend({focus:false,callback:true},e);this.each(function(){var f=a(this).attr("id");var g=a(this).val().split(b[f]);if(g[0]==""){g=new Array}d=jQuery.trim(d);if(e.unique){var h=a(g).tagExist(d);if(h==true){a("#"+f+"_tag").addClass("not_valid")}}else{var h=false}if(d!=""&&h!=true){a("<span>").addClass("tag badgeCount").append(a("<span>").text(d).append("  "),a("<a>",{href:"#",title:"Removing tag",text:"x"}).click(function(){return a("#"+f).removeTag(escape(d))})).insertBefore("#"+f+"_addTag");g.push(d);a("#"+f+"_tag").val("");if(e.focus){a("#"+f+"_tag").focus()}else{a("#"+f+"_tag").blur()}a.fn.tagsInput.updateTagsField(this,g);if(e.callback&&c[f]&&c[f]["onAddTag"]){var i=c[f]["onAddTag"];i.call(this,d)}if(c[f]&&c[f]["onChange"]){var j=g.length;var i=c[f]["onChange"];i.call(this,a(this),g[j-1])}}});return false};a.fn.removeTag=function(d){d=unescape(d);this.each(function(){var e=a(this).attr("id");var f=a(this).val().split(b[e]);a("#"+e+"_tagsinput .tag").remove();str="";for(i=0;i<f.length;i++){if(f[i]!=d){str=str+b[e]+f[i]}}a.fn.tagsInput.importTags(this,str);if(c[e]&&c[e]["onRemoveTag"]){var g=c[e]["onRemoveTag"];g.call(this,d)}});return false};a.fn.tagExist=function(b){return jQuery.inArray(b,a(this))>=0};a.fn.importTags=function(b){id=a(this).attr("id");a("#"+id+"_tagsinput .tag").remove();a.fn.tagsInput.importTags(this,b)};a.fn.tagsInput=function(d){var e=jQuery.extend({interactive:true,defaultText:"add a tag",minChars:0,width:"300px",height:"100px",autocomplete:{selectFirst:false},hide:true,delimiter:",",unique:true,removeWithBackspace:true,placeholderColor:"#666666",autosize:true,comfortZone:20,inputPadding:6*2},d);this.each(function(){if(e.hide){a(this).hide()}var d=a(this).attr("id");if(!d||b[a(this).attr("id")]){d=a(this).attr("id","tags"+(new Date).getTime()).attr("id")}var f=jQuery.extend({pid:d,real_input:"#"+d,holder:"#"+d+"_tagsinput",input_wrapper:"#"+d+"_addTag",fake_input:"#"+d+"_tag"},e);b[d]=f.delimiter;if(e.onAddTag||e.onRemoveTag||e.onChange){c[d]=new Array;c[d]["onAddTag"]=e.onAddTag;c[d]["onRemoveTag"]=e.onRemoveTag;c[d]["onChange"]=e.onChange}var g='<div id="'+d+'_tagsinput" class="tagsinput"><div id="'+d+'_addTag">';if(e.interactive){g=g+'<input id="'+d+'_tag" value="" data-default="'+e.defaultText+'" title="Tag" />'}g=g+'</div><div class="tags_clear"></div></div>';a(g).insertAfter(this);a(f.holder).css("width",e.width);a(f.holder).css("height",e.height);if(a(f.real_input).val()!=""){a.fn.tagsInput.importTags(a(f.real_input),a(f.real_input).val())}if(e.interactive){a(f.fake_input).val(a(f.fake_input).attr("data-default"));a(f.fake_input).css("color",e.placeholderColor);a(f.fake_input).resetAutosize(e);a(f.holder).bind("click",f,function(b){a(b.data.fake_input).focus()});a(f.fake_input).bind("focus",f,function(b){if(a(b.data.fake_input).val()==a(b.data.fake_input).attr("data-default")){a(b.data.fake_input).val("")}a(b.data.fake_input).css("color","#000000")});if(e.autocomplete_url!=undefined){autocomplete_options={source:e.autocomplete_url};for(attrname in e.autocomplete){autocomplete_options[attrname]=e.autocomplete[attrname]}if(jQuery.Autocompleter!==undefined){a(f.fake_input).autocomplete(e.autocomplete_url,e.autocomplete);a(f.fake_input).bind("result",f,function(b,c,f){if(c){a("#"+d).addTag(c[0]+"",{focus:true,unique:e.unique})}})}else if(jQuery.ui.autocomplete!==undefined){a(f.fake_input).autocomplete(autocomplete_options);a(f.fake_input).bind("autocompleteselect",f,function(b,c){a(b.data.real_input).addTag(c.item.value,{focus:true,unique:e.unique});return false})}}else{a(f.fake_input).bind("blur",f,function(b){var c=a(this).attr("data-default");if(a(b.data.fake_input).val()!=""&&a(b.data.fake_input).val()!=c){if(b.data.minChars<=a(b.data.fake_input).val().length&&(!b.data.maxChars||b.data.maxChars>=a(b.data.fake_input).val().length))a(b.data.real_input).addTag(a(b.data.fake_input).val(),{focus:true,unique:e.unique})}else{a(b.data.fake_input).val(a(b.data.fake_input).attr("data-default"));a(b.data.fake_input).css("color",e.placeholderColor)}return false})}a(f.fake_input).bind("keypress",f,function(b){if(b.which==b.data.delimiter.charCodeAt(0)||b.which==13){b.preventDefault();if(b.data.minChars<=a(b.data.fake_input).val().length&&(!b.data.maxChars||b.data.maxChars>=a(b.data.fake_input).val().length))a(b.data.real_input).addTag(a(b.data.fake_input).val(),{focus:true,unique:e.unique});a(b.data.fake_input).resetAutosize(e);return false}else if(b.data.autosize){a(b.data.fake_input).doAutosize(e)}});f.removeWithBackspace&&a(f.fake_input).bind("keydown",function(b){if(b.keyCode==8&&a(this).val()==""){b.preventDefault();var c=a(this).closest(".tagsinput").find(".tag:last").text();var d=a(this).attr("id").replace(/_tag$/,"");c=c.replace(/[\s]+x$/,"");a("#"+d).removeTag(escape(c));a(this).trigger("focus")}});a(f.fake_input).blur();if(f.unique){a(f.fake_input).keydown(function(b){if(b.keyCode==8||String.fromCharCode(b.which).match(/\w+|[áéíóúÁÉÍÓÚñÑ,/]+/)){a(this).removeClass("not_valid")}})}}});return this};a.fn.tagsInput.updateTagsField=function(c,d){var e=a(c).attr("id");a(c).val(d.join(b[e]))};a.fn.tagsInput.importTags=function(d,e){a(d).val("");var f=a(d).attr("id");var g=e.split(b[f]);for(i=0;i<g.length;i++){a(d).addTag(g[i],{focus:false,callback:false})}if(c[f]&&c[f]["onChange"]){var h=c[f]["onChange"];h.call(d,d,g[i])}}})(jQuery);;
(function($)
{
	var MentionTextArea = function(aObject, aOptions)
	{
		var mThis = this,
			mObject = $(aObject),
			mMentionLocations = new Array(),
			mUsers = {},
			mMentionActive = false,
			keyNames = {backspace: 8, del: 46, enter: 13, escape: 27, left: 37, up: 38, right: 39, down: 40},
			mStartPosition = 0,
			mSearchString = "",
			mIsExtensionField = false,
			mFirstSetMentions = true,
			mInitialMentions = [];

		var mSettings = $.extend({
			maxResults: 15
		}, aOptions || {});

		var mMirrorStyles = [
			// Box Styles.
			'box-sizing', 'height', 'width', 'padding-bottom',
			'padding-left', 'padding-right', 'padding-top',
			// Font stuff.
			'font-family', 'font-size', 'font-style',
			'font-variant', 'font-weight',
			// Spacing etc.
			'word-spacing', 'letter-spacing', 'line-height',
			'text-decoration', 'text-indent', 'text-transform',
			// The direction.
			'direction'
		];

		var mContainer = $('<div class="mtaContainer"/>').css({position: 'relative', marginBottom: "-7px", clear: "both"}).insertAfter(mObject).append(mObject);

		var mMirror = $('<div/>').css({
			'left': -9999,
			'overflow': 'auto',
			'position': 'absolute',
			'top': 0,
			'white-space': 'pre-wrap',
			'word-wrap': 'break-word'
		}).insertAfter(mObject);

		var mMentionNameDummy = $('<div class="mtaMentionName"/>').css({
			position: "absolute",
			zIndex: 100
		});

		var mMentionList = $('<div class="mtaMentionList"/>').css({
			display: "none",
			position: "absolute",
			zIndex: 101
		}).appendTo(mContainer);

		// Public method - can be called from client code
		this.publicMethod = function()
		{
			$.fn.showError(settings.errors.publicMethodText + " (500.42)", "console");
		};

		var init = function ()
		{
			mIsExtensionField = mObject.parents('[id$=_pnlCustomFields]').length > 0;

			mObject.css({overflow: "hidden"});
			mObject.parents('.field:first').css('overflow', 'visible');

			if (mObject.hasClass('textbox'))
				mObject.css({ minHeight: 42 });

			mObject.keydown(function (aEvent)
			{
				switch(aEvent.keyCode)
				{
					case keyNames.backspace:
					case keyNames.ctrlKey && keyNames.backspace:
						for (var i = 0; i < mMentionLocations.length; i++)
						{
							var theValue = mObject.val();

							if (/\s$/.test(theValue))
							{
								// string contains space at last
								newValue = theValue.substr(0, theValue.length - 1);

								mObject.val(newValue);

								moveCaretTo(theValue.length - 1);

								aEvent.preventDefault();

								break;
							}

							if (getOriginalCaretPos() == (mMentionLocations[i].end))
							{
								theValue = theValue.slice(0, mMentionLocations[i].start) + theValue.slice(mMentionLocations[i].end);
								mObject.val(theValue);

								moveCaretTo(mMentionLocations[i].start);

								aEvent.preventDefault();
							}
						}

						break;
					case keyNames.del:
						for (var i = 0; i < mMentionLocations.length; i++)
						{
							if (getOriginalCaretPos() == (mMentionLocations[i].start))
							{
								var theValue = mObject.val();
								theValue = theValue.slice(0, mMentionLocations[i].start) + theValue.slice(mMentionLocations[i].end);
								mObject.val(theValue);

								moveCaretTo(mMentionLocations[i].start);

								aEvent.preventDefault();
							}
						}

						break;
					case keyNames.left:
						for (var i = 0; i < mMentionLocations.length; i++)
						{
							if (getOriginalCaretPos() == (mMentionLocations[i].end))
							{
								moveCaretTo(mMentionLocations[i].start);

								aEvent.preventDefault();
							}
						}
						break;
					case keyNames.right:
						for (var i = 0; i < mMentionLocations.length; i++)
						{
							if (getOriginalCaretPos() == (mMentionLocations[i].start))
							{
								moveCaretTo(mMentionLocations[i].end);

								aEvent.preventDefault();
							}
						}
						break;
					case keyNames.up:
						if (mMentionActive)
						{
							var theSelectedItem = mContainer.find(".mtaUserList li.selected");
							var thePrevItem = theSelectedItem.prev();

							if (thePrevItem.length > 0)
							{
								theSelectedItem.removeClass("selected");
								thePrevItem.addClass("selected");
							}

							aEvent.preventDefault();
						}

						break;
					case keyNames.down:
						if (mMentionActive)
						{
							var theSelectedItem = mContainer.find(".mtaUserList li.selected");
							var theNextItem = theSelectedItem.next();

							if (theNextItem.length > 0)
							{
								theSelectedItem.removeClass("selected");
								theNextItem.addClass("selected");
							}

							aEvent.preventDefault();
						}

						break;
					case keyNames.enter:
						if (mMentionActive)
						{
							var theSelectedItem = mContainer.find(".mtaUserList li.selected");

							if (theSelectedItem.length > 0)
							{
								addMentionText(theSelectedItem.data("userInfo"));
							}

							aEvent.preventDefault();
						}
						break;
					case keyNames.escape:
						if (mMentionActive)
						{
							stopMention();

							aEvent.preventDefault();
						}

						break;
				}

				update();
			});

			mObject.on('keyup paste cut mouseup', function (aEvent)
			{
				if (mObject.hasClass('textbox'))
					mObject.val(mObject.val().split('\r\n').join(' ').split('\n').join(' '));

				update();

				for (var i = 0; i < mMentionLocations.length; i++)
				{
					if (getOriginalCaretPos() > mMentionLocations[i].start && getOriginalCaretPos() < mMentionLocations[i].end)
						moveCaretTo(mMentionLocations[i].end);
				}

				var thePosition;

				if (!mMentionActive && aEvent.keyCode != keyNames.escape && (thePosition = checkMonkeyTail()) !== false)
					startMention(thePosition);

				if (mMentionActive)
				{
					if (updateSearchString())
						fillMentionList();
				}
			});

			mObject.on('keyup', function (aEvent)
			{
				recalculateHeight();
			});

			mObject.blur(function ()
			{
				setTimeout(function () { stopMention() }, 200);
			});

			mObject.scroll(function ()
			{
				update();
			});

			recalculateHeight();

			// Do update() twice, to prevent sizing issues on edit
			update();
			update();
		};

		var addMentionText = function (aUserInfo)
		{
			if (typeof aUserInfo != "undefined" && aUserInfo == null)
				return;

			var theText = mObject.val();
			var theMentionString = "@[" + aUserInfo.UserId + ":" + aUserInfo.FullName + "]";
			theMentionString = theMentionString.split(" ").join("+");
			theMentionString += ' ';

			theText = theText.splice(mStartPosition, getOriginalCaretPos() - mStartPosition, theMentionString);

			mObject.val(theText);

			stopMention();
			update();

			mObject.focus();
			moveCaretTo(mStartPosition + theMentionString.length);
		};

		var moveCaretTo = function (aPosition)
		{
			var theElement = mObject[0];

			if (theElement.setSelectionRange)
				theElement.setSelectionRange(aPosition, aPosition);
			else
			{
				var range = theElement.createTextRange();
				range.collapse(true);
				range.moveEnd('character', aPosition);
				range.moveStart('character', aPosition);
				range.select();
			}
		};

		var startMention = function (aPosition)
		{
			mMentionActive = true;
			mSearchString = "";

			mStartPosition = aPosition;

			getUsers();

			mMentionList.show();
			positionMentionList();
		};

		var positionMentionList = function ()
		{
			var theCoordinates = getCoordinates(mStartPosition);

			mMentionList.css({left: theCoordinates.left, top: theCoordinates.top + theCoordinates.height});
		};

		var stopMention = function ()
		{
			mMentionActive = false;

			mMentionList.hide();

			mSearchString = "";
		};

		var updateSearchString = function ()
		{
			if (mMentionActive)
			{
				var theText = mObject.val();

				if(theText.substr(mStartPosition, 1) != "@")
				{
					stopMention();

					return;
				}

				var theNewSearchString = theText.substr(mStartPosition + 1, getOriginalCaretPos() - (mStartPosition + 1));

				if(theNewSearchString != mSearchString)
				{
					mSearchString = theNewSearchString;

					return true;
				}
			}

			return false;
		};

		var getCoordinates = function (aPosition)
		{
			var theMirrorHtml = mMirror.html();
			theMirrorHtml = theMirrorHtml.splice(aPosition, 0, '<span id="mtaPositionTarget" style="position: absolute;">&nbsp;</span>');

			mMirror.html(theMirrorHtml);

			var thePositionTarget = mMirror.find("#mtaPositionTarget");
			var thePosition = thePositionTarget.position();
			thePosition.height = thePositionTarget.height();

			thePositionTarget.remove();

			return thePosition;
		};

		// Private method - can only be called from within this object
		var getOriginalCaretPos = function ()
		{
			var theElement = mObject[0];

			if (theElement.selectionStart)
				return theElement.selectionStart;
			else if (document.selection)
			{
				theElement.focus();

				var theRange = document.selection.createRange();

				if (theRange == null)
					return 0;

				var theTextRange = theElement.createTextRange(),
					theTextRangeCopy = theTextRange.duplicate();

				theTextRange.moveToBookmark(theTextRange.getBookmark());
				theTextRangeCopy.setEndPoint('EndToStart', theTextRange);

				return theTextRangeCopy.text.length;
			}
			return 0;
		};

		var checkMonkeyTail = function ()
		{
			update();

			var theText = mObject.val(),
				theCaretPos = getOriginalCaretPos(),
				thePrePos = theCaretPos - 1;

			if (thePrePos < 0)
				thePrePos = 0;

			if(theText.substr(thePrePos, 1) == "@" && (thePrePos == 0 || theText.substr(thePrePos - 1, 1).match(/(\s|\r|\n)/) != null))
				return thePrePos;

			return false;
		};

		var setMentions = function ()
		{
			var theText = mObject.val(),
				theHtml = $('<div>').text(theText).html(),
				theRegEx = new RegExp("\\@\\[([0-9]+?):(.+?)\\]", "gim"),
				theLastTaggedUsersElement = $('.lastTaggedUsers');

			mContainer.find(".mtaMentionName").remove();

			mMentionLocations = new Array();

			while ((theMatch = theRegEx.exec(theHtml)) != null)
			{
				var theIndexStart = theHtml.indexOf(theMatch[0]),
					theIndexEnd = theIndexStart + theMatch[0].length,
					theTopLeft = getCoordinates(theIndexStart),
					theBottomRight = getCoordinates(theIndexEnd);

				addMentionName(theMatch[2], theTopLeft, theBottomRight);

				if (mIsExtensionField && mFirstSetMentions) {
					var theLastTaggedUsers = theLastTaggedUsersElement.val();
					theLastTaggedUsers = theLastTaggedUsers.split(',' + theMatch[1]).join('');
					theLastTaggedUsers += ',' + theMatch[1];
					theLastTaggedUsersElement.val(theLastTaggedUsers);
				}

				mMentionLocations.push({start: theIndexStart, end: theIndexEnd});
			}

			mFirstSetMentions = false;
		};

		var addMentionName = function (aUserName, aCoordinatesTopLeft, aCoordinatesBottomRight)
		{
			if (aCoordinatesTopLeft.top < aCoordinatesBottomRight.top)
				aCoordinatesTopLeft.left = getCoordinates(0).left;

			var theWidth = aCoordinatesBottomRight.left - aCoordinatesTopLeft.left;

			var theTargetTop = aCoordinatesBottomRight.top + 2 - mObject.scrollTop();

			var theMentionName = mMentionNameDummy.clone().css({ left: aCoordinatesTopLeft.left, top: theTargetTop, width: theWidth + 2, height: aCoordinatesBottomRight.height});
			theMentionName.html(aUserName.split("+").join(" "));
			theMentionName.appendTo(mContainer);

			if (aCoordinatesBottomRight.top > mObject.height() || aCoordinatesBottomRight.top + theMentionName.height() < 0)
				theMentionName.hide()
			else
				theMentionName.show();
		};

		var update = function ()
		{
			mMirror.text(mObject.val());
			mMirror.scrollTop(mObject.scrollTop());

			setMentions();
			positionMentionList();
		};

		var recalculateHeight = function ()
		{
			mMirror.css({height: "auto", minHeight: 0});

			if (mObject.is("textarea") && mObject.parents(".addItemComment").length == 0)
				mObject.css({height: mMirror.height() + 30});
			else
			{
				/*tArea = document.getElementById(mObject[0].id);

				var mHeight = mObject.height();

				if (mHeight !== tArea.scrollHeight + 36)
				{
					mObject.css("height", "auto");
					mObject.css("height", (36 + tArea.scrollHeight) + "px");
				}*/
			}

			// Copy styles.
			var theStyles = {};
			for (var i = 0, theStyle; theStyle = mMirrorStyles[i]; i++)
			{
				theStyles[theStyle] = mObject.css(theStyle);
			}

			mMirror.css(theStyles);
		}

		var getUsers = function ()
		{
			mMentionList.html('<div class="loader" role="status"/>');

			$.ajax(
			{
				url: "/api/user/GetCommentersByPermissionsJson?sectionID=" + settings.section.ID + "&contentPageID=" + settings.section.itemID + "&token=" + $("input[name='__RequestVerificationToken']").val(),
				dataType: "json"
			})
			.done(function (aData)
			{
				mUsers = JSON.parse(aData);

				if (typeof mUsers.length == "undefined" || mUsers.length < 1)
				{
					stopMention();

					return;
				}

				fillMentionList();
			})
			.error(function ()
			{

			});
		};

		var fillMentionList = function ()
		{
			var theList = $('<ul class="mtaUserList"/>'),
				theSelectedSet = false,
				theNumberOfUsers = 0;

			if (typeof mUsers.length == "undefined" || mUsers.length < 1)
				return;

			for (var index in mUsers)
			{
				if (theNumberOfUsers >= mSettings.maxResults || mObject.val().indexOf("@[" + mUsers[index].UserId + ":") > -1)
					continue;

				if (mSearchString != "" &&
					mUsers[index].FullName.toLowerCase().indexOf(mSearchString.toLowerCase()) < 0)
					continue;

				var theListItem = $('<li/>');

				if (!theSelectedSet)
				{
					theListItem.addClass("selected");

					theSelectedSet = true;
				}

				var theListItemImageContainer = $('<div class="mtaImageContainer"/>');

				if (mUsers[index].ProfileImage && mUsers[index].ProfileImage != "")
					theListItemImageContainer.append('<img src="' + mUsers[index].ProfileImage + '?Width=30&amp;Height=30" alt="' + mUsers[index].FullName + '" />');
				else
					theListItemImageContainer.append('<div class="noAvatar icon-user before" />');

				theListItem.append(theListItemImageContainer);

				theListItem.append('<div class="mtaUser">' + mUsers[index].FullName + '</div>');
				theListItem.append('<div class="clearBoth"/>');
				theListItem.click(function ()
				{
					addMentionText($(this).data("userInfo"));
				});

				theListItem.data("userInfo", mUsers[index]);

				theList.append(theListItem);

				theNumberOfUsers++;
			}

			if (theNumberOfUsers == 0)
				stopMention();

			if (mMentionList.find("ul").length > 0)
			{
				if (mMentionList.find("ul").html() == theList.html())
					return;
			}

			mMentionList.html(theList);
		};

		init();
	};

	$.fn.mentionTextArea = function(aOptions)
	{
		return this.each(function()
		{
			var theObject = $(this);

			// Return early if this element already has a plugin instance
			if (theObject.data('mentionTextArea')) return;

			// pass options to plugin constructor
			var thePlugin = new MentionTextArea(this, aOptions);

			// Store plugin object in this element's data
			theObject.data('mentionTextArea', thePlugin);
		});
	};
})(jQuery);
;
/*
### jQuery Star Rating Plugin v4.11 - 2013-03-14 ###
 * Home: http://www.fyneworks.com/jquery/star-rating/
 * Code: http://code.google.com/p/jquery-star-rating-plugin/
 *
 * Licensed under http://en.wikipedia.org/wiki/MIT_License
###
*/

;if (window.jQuery) (function($)
{
	/*# AVOID COLLISIONS #*/
	// IE6 Background Image Fix
	if ((!$.support.opacity && !$.support.style))
		try
		{
			document.execCommand("BackgroundImageCache", false, true);
		}
		catch(e)
		{

		};
	// Thanks to http://www.visualjquery.com/rating/rating_redux.html

	// plugin initialization
	$.fn.rating = function(options)
	{
		if (this.length == 0)
			return this; // quick fail

		// Handle API methods
		if (typeof arguments[0] == 'string')
		{
			// Perform API methods on individual elements
			if (this.length > 1)
			{
				var args = arguments;
				return this.each(function()
				{
					$.fn.rating.apply($(this), args);
				});
			};

			// Invoke API method handler
			$.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);

			// Quick exit...
			return this;
		};

		// Initialize options for this call
		var options = $.extend(
			{},/* new object */
			$.fn.rating.options,/* default options */
			options || {} /* just-in-time options */
		);

		// Allow multiple controls with the same name by making each call unique
		$.fn.rating.calls++;

		// loop through each matched element
		this.not('.star-rating-applied').addClass('star-rating-applied').each(function()
		{
			// Load control parameters / find context / etc
			var control, input = $(this);
			var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g,'');
			var context = $(this.form || document.body);

			// FIX: http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=23
			var raters = context.data('rating');

			if (!raters || raters.call != $.fn.rating.calls)
				raters = { count:0, call:$.fn.rating.calls };

			var rater = raters[eid];

			// if rater is available, verify that the control still exists
			if (rater)
				control = rater.data('rating');

			if (rater && control)
				// add star to control if rater is available and the same control still exists
				control.count++;
			else
			{
				// create new control if first star or control element was removed/replaced

				// Initialize options for this rater
				control = $.extend(
					{}/* new object */,
					options || {} /* current call options */,
					($.metadata? input.metadata(): ($.meta?input.data():null)) || {}, /* metadata options */
					{ count:0, stars: [], inputs: [] }
				);

				// increment number of rating controls
				control.serial = raters.count++;

				// create rating element
				rater = $('<span class="star-rating-control"/>');

				var ratingScreenReaderValue = $('<span class="screenReaderContent screenReaderRating">' + settings.rating.noRatingYetText + '</span>');
				rater.append(ratingScreenReaderValue);

				input.before(rater);

				// Mark element for initialization (once all stars are ready)
				rater.addClass('rating-to-be-drawn');

				// Accept readOnly setting from 'disabled' property
				if (input.attr('disabled') || input.hasClass('disabled'))
					control.readOnly = true;

				// Accept required setting from class property (class='required')
				if (input.hasClass('required'))
					control.required = true;

				// Create 'cancel' button
				rater.append(
					control.cancel = $('<div class="rating-cancel"><a title="' + control.cancel + '">' + control.cancelValue + '</a></div>')
					.on('mouseover',function()
					{
						$(this).rating('drain');
						$(this).addClass('star-rating-hover');
						//$(this).rating('focus');
					})
					.on('mouseout',function()
					{
						$(this).rating('draw');
						$(this).removeClass('star-rating-hover');
						//$(this).rating('blur');
					})
					.on('click',function()
					{
						$(this).rating('select');
					})
					.data('rating', control)
				);
			}; // first element of group

			// insert rating star (thanks Jan Fanslau rev125 for blind support https://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=125)
			var star = $('<div class="star-rating rater-'+ control.serial +'"><a title="' + (this.title || this.value) + '">' + this.value + ' <span class="screenReaderContent">' + settings.rating.giveStarsText + '</span></a></div>');
			rater.append(star);

			// inherit attributes from input element
			if (this.id)
				star.attr('id', this.id + '_1');

			if (this.className)
				star.addClass(this.className);

			// Half-stars?
			if (control.half)
				control.split = 2;

			// Prepare division control
			if (typeof control.split == 'number' && control.split > 0)
			{
				var stw = ($.fn.width ? star.width() : 0) || control.starWidth;
				var spi = (control.count % control.split), spw = Math.floor(stw / control.split);
				star
				// restrict star's width and hide overflow (already in CSS)
				.width(spw)
				// move the star left by using a negative margin
				// this is work-around to IE's stupid box model (position:relative doesn't work)
				.find('a').css({ 'margin-left': '-'+ (spi * spw) +'px' })
			};

			// readOnly?
			if (control.readOnly)
				// Mark star as readOnly so user can customize display
				star.addClass('star-rating-readonly');
			else
			 // Enable hover css effects
				star.addClass('star-rating-live')
				 // Attach mouse events
				.on('mouseover',function()
				{
					if (control.readOnly) {
						star.removeClass('star-rating-live').addClass('star-rating-readonly');
						return;
					}
					$(this).rating('fill');
					$(this).rating('focus');
				})
				.on('mouseout',function()
				{
					if (control.readOnly) {
						star.removeClass('star-rating-live').addClass('star-rating-readonly');
						return;
					}
					$(this).rating('draw');
					$(this).rating('blur');
				})
				.on('click',function()
				{
					if (control.readOnly) {
						star.removeClass('star-rating-live').addClass('star-rating-readonly');
						return;
					}
					$(this).rating('select');

					// Rinse (13-04-15): trigger radio button click.
					input.click();
				});

			// set current selection
			if (this.checked)
				control.current = star;

			// set current select for links
			if (this.nodeName == "A")
			{
				if ($(this).hasClass('selected'))
					control.current = star;
			};

			// hide input element
			input.hide();

			// backward compatibility, form element to plugin
			input.on('change.rating', function(event)
			{
				if (event.selfTriggered)
					return false;

				$(this).rating('select');
			});

			// attach reference to star to input element and vice-versa
			star.data('rating.input', input.data('rating.star', star));

			// store control information in form (or body when form not available)
			control.stars[control.stars.length] = star[0];
			control.inputs[control.inputs.length] = input[0];
			control.rater = raters[eid] = rater;
			control.context = context;

			input.data('rating', control);
			rater.data('rating', control);
			star.data('rating', control);
			context.data('rating', raters);
			context.data('rating'+eid, rater); // required for ajax forms
		}); // each element

		// Initialize ratings (first draw)
		$('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn');

		return this; // don't break the chain...
	};

	/*--------------------------------------------------------*/

	/*
		### Core functionality and API ###
	*/
	$.extend($.fn.rating,
	{
		// Used to append a unique serial number to internal control ID
		// each time the plugin is invoked so same name controls can co-exist
		calls: 0,

		focus: function()
		{
			var control = this.data('rating');

			if (!control)
				return this;

			if (!control.focus)
				return this; // quick fail if not required

			// find data for event
			var input = $(this).data('rating.input') || $(this.tagName == 'INPUT' ? this : null);
			// focus handler, as requested by focusdigital.co.uk
			if (control.focus)
				control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.rating.focus
		blur: function()
		{
			var control = this.data('rating');
			if (!control)
				return this;

			if (!control.blur)
				return this; // quick fail if not required

			// find data for event
			var input = $(this).data('rating.input') || $(this.tagName=='INPUT' ? this : null);
			// blur handler, as requested by focusdigital.co.uk
			if (control.blur)
				control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.rating.blur
		fill: function()
		{ // fill to the current mouse position.
			var control = this.data('rating');

			if (!control)
				return this;

			// do not execute when control is in read-only mode
			if (control.readOnly)
				return;

				// Reset all stars and highlight them up to this element
			this.rating('drain');
			this.prevAll().addBack().filter('.rater-'+ control.serial).addClass('star-rating-hover');
		},// $.fn.rating.fill
		drain: function()
		{ // drain all the stars.
			var control = this.data('rating');

			if (!control)
				return this;

			// do not execute when control is in read-only mode
			if (control.readOnly)
				return;

			// Reset all stars
			control.rater.children().filter('.rater-'+ control.serial).removeClass('star-rating-on').removeClass('star-rating-hover');
		},// $.fn.rating.drain
		draw: function()
		{ // set value and stars to reflect current selection
			var control = this.data('rating');

			if (!control)
				return this;

			// Clear all stars
			this.rating('drain');
			// Set control value
			var current = $(control.current);//? control.current.data('rating.input') : null );
			var starson = current.length ? current.prevAll().addBack().filter('.rater-'+ control.serial) : null;
			var screenReaderRating = this.find('.screenReaderRating');

			current.attr('aria-current', 'true');

			if (starson)
			{
				starson.addClass('star-rating-on');

				switch(starson.length)
				{
					case 1:
						screenReaderRating.text(settings.rating.oneStarGivenText);
						break;
					case 2:
						screenReaderRating.text(settings.rating.twoStarsGivenText);
						break;
					case 3:
						screenReaderRating.text(settings.rating.threeStarsGivenText);
						break;
					case 4:
						screenReaderRating.text(settings.rating.fourStarsGivenText);
						break;
					case 5:
						screenReaderRating.text(settings.rating.fiveStarsGivenText);
						break;
				}
			}

			// Show/hide 'cancel' button
			control.cancel[control.readOnly || control.required ? 'hide' : 'show']();
			// Add/remove read-only classes to remove hand pointer
			this.siblings()[control.readOnly ? 'addClass' : 'removeClass']('star-rating-readonly');
		},// $.fn.rating.draw
		select: function(value, wantCallBack)
		{ // select a value
			var control = this.data('rating');

			if (!control)
				return this;

			// do not execute when control is in read-only mode
			if(control.readOnly)
				return;

				// clear selection
			control.current = null;
			// programmatically (based on user input)
			if (typeof value != 'undefined' || this.length > 1)
			{
				// select by index (0 based)
				if (typeof value == 'number')
					return $(control.stars[value]).rating('select',undefined,wantCallBack);

				// select by literal value (must be passed as a string
				if (typeof value == 'string')
				{
					//return
					$.each(control.stars, function()
					{
 						//console.log($(this).data('rating.input'), $(this).data('rating.input').val(), value, $(this).data('rating.input').val()==value?'BINGO!':'');
						if ($(this).data('rating.input').val() == value)
							$(this).rating('select',undefined,wantCallBack);
					});

					// don't break the chain
					return this;
				};
			}
			else
			{
				control.current = this[0].tagName=='INPUT' ? this.data('rating.star') : (this.is('.rater-'+ control.serial) ? this : null);
			};
			// Update rating control state
			this.data('rating', control);
			// Update display
			this.rating('draw');
			// find current input and its sibblings
			var current = $( control.current ? control.current.data('rating.input') : null );
			var lastipt = $( control.inputs ).filter(':checked');
			var deadipt = $( control.inputs ).not(current);
			// check and uncheck elements as required
			deadipt.prop('checked', false);//.removeAttr('checked');
			current.prop('checked', true);//.attr('checked','checked');
			// trigger change on current or last selected input
			$(current.length ? current : lastipt).trigger({ type:'change', selfTriggered:true });

			// click callback, as requested here: http://plugins.jquery.com/node/1655
			if ((wantCallBack || wantCallBack == undefined) && control.callback)
				control.callback.apply(current[0], [current.val(), $('a', control.current)[0]]);// callback event

			// don't break the chain
			return this;
		},// $.fn.rating.select
		readOnly: function(toggle, disable)
		{ // make the control read-only (still submits value)
			var control = this.data('rating');

			if (!control)
				return this;

			// setread-only status
			control.readOnly = toggle || toggle==undefined ? true : false;

			// enable/disable control value submission
			if (disable)
				$(control.inputs).attr("disabled", "disabled");
			else
				$(control.inputs).removeAttr("disabled");

			// Update rating control state
			this.data('rating', control);
			// Update display
			this.rating('draw');
		},// $.fn.rating.readOnly
		disable: function()
		{ // make read-only and never submit value
			this.rating('readOnly', true, true);
		},// $.fn.rating.disable
		enable: function()
		{ // make read/write and submit value
			this.rating('readOnly', false, false);
		}// $.fn.rating.select
	});

	/*--------------------------------------------------------*/

	/*
		### Default Settings ###
		eg.: You can override default control like this:
		$.fn.rating.options.cancel = 'Clear';
	*/
	$.fn.rating.options =
	{ //$.extend($.fn.rating, { options: {
		cancel: 'Cancel Rating',   // advisory title for the 'cancel' link
		cancelValue: '',           // value to submit when user click the 'cancel' link
		split: 0,                  // split the star into how many parts?
		// Width of star image in case the plugin can't work it out. This can happen if
		// the jQuery.dimensions plugin is not available OR the image is hidden at installation
		starWidth: 16//,

		//NB.: These don't need to be pre-defined (can be undefined/null) so let's save some code!
		//half:     false,         // just a shortcut to control.split = 2
		//required: false,         // disables the 'cancel' button so user can only select one of the specified values
		//readOnly: false,         // disable rating plugin interaction/ values cannot be.one('change',		//focus:    function(){},  // executed when stars are focused
		//blur:     function(){},  // executed when stars are focused
		//callback: function(){},  // executed when a star is clicked
	}; //} });
/*# AVOID COLLISIONS #*/
})(jQuery);
/*# AVOID COLLISIONS #*/

function setRating(sid, cpid, value, oldValue, aObject)
{
	var theObject = $(aObject),
		theRatingObject = theObject.parents(".rating"),
		avarageText = theRatingObject.find(".ratingsAverage.count"),
		totalRating = theRatingObject.find(".ratingsTotal"),
		removeButton = theRatingObject.find("input.remove"),
		screenReaderRating = theRatingObject.find('.screenReaderRating');

	// Talk to handler.
	$.getJSON("/api/participation/SetRating",
	{
		sectionId: 		sid,
		contentPageId:	cpid,
		ratingValue:	value,
		preventCache:	new Date().getTime(),
		token:   		$("input[name='__RequestVerificationToken']").val()
	},
	function(data)
	{
		if (data.status == "success")
		{
			if (data.message != "" && data.message != "-1")
			{
				avarageText.html(data.message);

				switch(value)
				{
					case 1:
						screenReaderRating.text(settings.rating.oneStarGivenText);
						break;
					case 2:
						screenReaderRating.text(settings.rating.twoStarsGivenText);
						break;
					case 3:
						screenReaderRating.text(settings.rating.threeStarsGivenText);
						break;
					case 4:
						screenReaderRating.text(settings.rating.fourStarsGivenText);
						break;
					case 5:
						screenReaderRating.text(settings.rating.fiveStarsGivenText);
						break;
				}

				if (oldValue == 0)
					$.fn.setTotalText(totalRating, parseInt(totalRating.find('.count').html()) + 1);

				if (!settings.rating.rateCanEditAndDelete) {
					theRatingObject.find('input[type=radio]').prop('disabled', true);
					theRatingObject.find('.star-rating-control').data('rating').readOnly = true;
					theRatingObject.find('input.star').rating();
				}

				removeButton.removeClass("hide");
			}
		}
	});
}

function removeRating(sid, cpid, aObject)
{
	var theObject = $(aObject),
		theRatingObject = theObject.parents(".rating"),
		avarageText = theRatingObject.find(".ratingsAverage.count"),
		totalRating = theRatingObject.find(".ratingsTotal"),
		screenReaderRating = theRatingObject.find('.screenReaderRating');

	theObject.parent().find(".star-rating-control").rating("select");
	theObject.addClass("hide");

	// Talk to handler.
	$.getJSON("/api/participation/RemoveRating",
	{
		sectionId:		sid,
		contentPageId: 	cpid,
		preventCache: 	new Date().getTime(),
		token:   		$("input[name='__RequestVerificationToken']").val()
	},
	function(data)
	{
		if (data.status == "success")
		{
			if (data.message != "" && data.message != "-1")
			{
				screenReaderRating.text(settings.rating.noRatingYetText);
				avarageText.html(data.message);

				$.fn.setTotalText(totalRating, parseInt(totalRating.find('.count').html()) - 1);
			}
		}
	});
}


$.fn.inititalizeRatings = function () {
	if ($('#eParticipation.add, #eParticipation.edit').length > 0)
		return;

	var visibleItems = [];
	var calls = [];

	$("#eParticipation [id*=_pnlRating]").addClass('hide');

	$('[id^=item_]').each(function () {
		var currentId = $(this).attr('id').split('_')[1];

		if (!isNaN(currentId))
			visibleItems.push(parseInt(currentId));
	});

	if (visibleItems.length === 0)
		return;

	while (visibleItems.length) {
		var currentBatch = visibleItems.splice(0, 50);
		calls.push($.fn.getTotalRatings(currentBatch));
		calls.push($.fn.getAverageRatings(currentBatch));
		calls.push($.fn.getUserRatings(currentBatch));
	}

	$.when.apply($, calls).done(function () {
		if (!settings.rating.rateCanEditAndDelete)
			$("#eParticipation [id*=_pnlRating] .btnRemove").remove();

		$.fn.setRatingHandlers();
		$("#eParticipation [id*=_pnlRating]").removeClass('hide');
		$("#eParticipation .rating input.star").rating();
	});
}

$.fn.setRatingHandlers = function () {
	$('[id^=item_]').each(function () {
		var currentItem = $(this);
		var currentId = currentItem.attr('id').split('_')[1];
		var currentRatingPanel = currentItem.find("[id*=_pnlRating]");
		currentRatingPanel.data("currentValue", currentRatingPanel.find("[type=radio]:checked").val() | 0);

		if (isNaN(currentId))
			return;

		currentRatingPanel.find("[type=radio]")
			.click(function () {
				setRating(settings.section.ID, currentId, $(this).val(), currentRatingPanel.data("currentValue"), this);
				currentRatingPanel.data("currentValue", $(this).val());
			});

		currentRatingPanel.find(".btnRemove").click(function () {
			removeRating(settings.section.ID, currentId, this);
			currentRatingPanel.data("currentValue", 0);
			return false;
		});
	});
}

$.fn.setTotalText = function (totalContainer, rating) {
	var countSpan = $('<span>');
	countSpan.addClass('count');
	countSpan.text(rating);

	var textSpan = $('<span>');
	textSpan.addClass('totalText');
	textSpan.text(' ' + (parseInt(rating) === 1 ? settings.rating.ratingText : settings.rating.ratingsText));

	totalContainer.html('');
	totalContainer.append(' (', countSpan, textSpan, ')');
}

$.fn.getTotalRatings = function (visibleItems) {
	return $.ajax({
		url: '/api/participation/GetTotalRatings',
		data: {
			sectionId: settings.section.ID,
			contentPageIds: visibleItems.join(','),
			token: $("input[name='__RequestVerificationToken']").val()
		}
	})
	.done(function (data) {
		if (!data || data.status != 'success' || !data.message)
			return;

		for (index in data.message) {
			var currentItem = data.message[index];
			var totalContainer = $('#item_' + currentItem.Rating_ContentPageID + ' .ratingsTotal');

			$.fn.setTotalText(totalContainer, currentItem.TotalRating);
		}
	});
}

$.fn.getAverageRatings = function (visibleItems) {
	return $.ajax({
		url: '/api/participation/GetAverageRatings',
		data: {
			sectionId: settings.section.ID,
			contentPageIds: visibleItems.join(','),
			token: $("input[name='__RequestVerificationToken']").val()
		}
	})
	.done(function (data) {
		if (!data || data.status != 'success' || !data.message)
			return;

		for (index in data.message) {
			var currentItem = data.message[index];
			$('#item_' + currentItem.contentPageId + ' .ratingsAverage').text((parseFloat(Math.round(currentItem.AverageRating)) / 10));
		}
	});
}

$.fn.getUserRatings = function (visibleItems) {
	return $.ajax({
		url: '/api/participation/GetUserRatings',
		data: {
			sectionId: settings.section.ID,
			contentPageIds: visibleItems.join(','),
			token: $("input[name='__RequestVerificationToken']").val()
		}
	})
	.done(function (data) {
		if (!data || data.status != 'success' || !data.message)
			return;

		for (index in data.message) {
			var currentItem = data.message[index];
			$('#item_' + currentItem.contentPageId + ' .starRating input[type=radio]').prop("checked", false);
			$('#item_' + currentItem.contentPageId + ' .starRating [value=' + (currentItem.yourRating / 10) + ']').prop("checked", true);

			if (settings.rating.rateCanEditAndDelete)
				$('#item_' + currentItem.contentPageId + ' .btnRemove').removeClass('hide');
			else
				$('#item_' + currentItem.contentPageId + ' .starRating input[type=radio]').prop('disabled', true);
		}
	});
};
$(document).ready(function()
{
	$(".customDropDown").customDropDown();

	if (typeof Sys != "undefined" && typeof Sys.WebForms != "undefined")
	{
		Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function()
		{
			$(".customDropDown").customDropDown();
		});
	}
});

$.fn.customDropDown = function()
{
	$(this).each(function()
	{
		var theReturnObject =
		{
			mObject: null,
			mAnimateObject: null,
			mButton: null,
			mItems: null,
			mValue: null,
			mPrefix: null,
			mInitialButtonValue: null,
			mMapsViewport: null,
			mMultiSelect: false,
			mAssociatedControl: null,
			mMouseControlled: false,
			mCollapseTimeout: 0,
			mValueOnOpen: null,
			initialized: false,
			onchange: null,
			onCloseAfterChange: null,

			getValue: function()
			{
				return this.mValue;
			},

			setValue: function(aValue)
			{
				var theThis = this;
				var theItemFound = false;

				if (aValue != null)
				{
					this.mItems.each(function()
					{
						if ($(this).attr("data-value") == aValue)
						{
							theThis.onItemClick($(this));

							theItemFound = true;
						}
					});
				}

				if (aValue == null || !theItemFound)
					this.resetValue();
			},

			init: function(aObject)
			{
				var theThis = this;

				this.mObject = aObject;
				this.mAnimateObject = this.mObject.find("ul").first();
				this.mItems = this.mAnimateObject.children("li");

				if (this.mItems.length == 0)
					return;

				this.mButton = this.mObject.find("button").first();
				this.mInitialButtonValue = this.mButton.html();

				this.mAnimateObject.css("opacity", 0);

				this.mButton.click(function() { theThis.mMouseControlled = true; theThis.onClick(); return false; });

				if (this.mObject.attr("data-onchange") != undefined)
				{
					this.onchange = "var theThis = this; \r\n" + this.mObject.attr("data-onchange").replace(/(\W+)(this\.value)(\W+)/gi, "$1theThis.mValue$3").replace(/(\W+)(this\.mapsViewport)(\W+)/gi, "$1theThis.mMapsViewport$3").replace(/(\W+)(this)(\W+)/gi, "$1theThis.mObject.get(0)$3");
				}

				if (typeof this.mObject.attr("data-prefix") != "undefined" && this.mObject.attr("data-prefix") != "" && this.mObject.attr("data-prefix") != null)
					this.mPrefix = this.mObject.attr("data-prefix");

				if (typeof this.mObject.attr("data-multi-select") != "undefined" && this.mObject.attr("data-multi-select").toLowerCase() == "true")
					this.mMultiSelect = true;

				if (typeof this.mObject.attr("data-associated-control") != "undefined" && this.mObject.attr("data-associated-control") != null && $.trim(this.mObject.attr("data-associated-control")) != "")
				{
					var theAssociatedControlID = $.trim(this.mObject.attr("data-associated-control"));

					if ($("[id$='" + theAssociatedControlID + "']").length > 0)
						this.mAssociatedControl = $("[id$='" + theAssociatedControlID + "']");
				}

				this.mItems.each(function()
				{
					theThis.initItem($(this))
				});
			},

			onClick: function()
			{
				var theThis = this;

				if (this.mObject.hasClass('active'))
				{
					this.mAnimateObject.stop(true, false);
					this.mAnimateObject.animate({opacity: 0}, 200, function()
					{
						$(this).css("display", "none");

						if (typeof theThis.onCloseAfterChange == "function" && theThis.mValueOnOpen != theThis.getValue())
							theThis.onCloseAfterChange();

						theThis.mMouseControlled = false;
					});

					this.mObject.removeClass('active').removeAttr('aria-expanded');
				}
				else
				{
					this.mValueOnOpen = this.getValue();
	
					this.mAnimateObject.stop(true, false);
	
					this.mAnimateObject.css("display", "block");
					this.mAnimateObject.animate({ opacity: 1 }, 200);
	
					this.mObject.addClass('active').attr('aria-expanded', 'true');
	
					$(document).on('click', function(event)
					{
						if (event.target !== theThis.mObject && !theThis.mObject.has(event.target).length && theThis.mObject.hasClass('active'))
							theThis.onClick();
					});

					$("body").keydown(function(e)
					{
						theThis.onKeyDown(e);
					});
				}
			},

			onKeyDown: function(e)
			{
				if (e.keyCode == 27 && this.mObject.hasClass('active'))
					this.onClick();
			},

			initItem: function(aObject)
			{
				var theThis = this;

				aObject.css("cursor", "pointer");

				if (this.mMultiSelect)
				{
					var theUniqueId = new Date().getTime().toString() + Math.round(Math.random() * 10000);

					aObject.html('<input type="checkbox" id="checkbox_' + theUniqueId + '"><label for="checkbox_' + theUniqueId + '">' + aObject.html() + '</label><div class="clear"></div>');

					if (this.mAssociatedControl != null && $.trim(this.mAssociatedControl.val()) != "")
					{
						var theAssociatedValues = this.mAssociatedControl.val().split(",");

						if (aObject.attr("data-value") != null && theAssociatedValues.indexOf($.trim(aObject.attr("data-value"))) > -1)
							aObject.find("input").prop("checked", true);

						this.loopSelectedValues();
					}
				}
				else
				{
					if (this.mAssociatedControl != null)
						this.setValue(this.mAssociatedControl.val());
				}

				if (typeof aObject.attr("data-selected") != "undefined")
					this.onItemClick(aObject);

				aObject.click(function(e)
				{
					if (!theThis.mMultiSelect)
						e.preventDefault();

					var theOldValue = theThis.mValue;

					theThis.onItemClick(aObject);

					if (theThis.onchange != null)
					{
						var myFunction = function()
						{
							eval(theThis.onchange);
						};

						myFunction.call(theThis);
					}

					if (theThis.mAssociatedControl != null)
						theThis.mAssociatedControl.val(theThis.getValue());
				});

				this.initialized = true;
			},

			onItemClick: function(aObject)
			{
				var theThis = this;
				var theButtonValue = ((this.mPrefix != null) ? this.mPrefix : "");

				theThis.mButton.html(this.mInitialButtonValue);

				if (this.mMultiSelect)
					this.loopSelectedValues();
				else
				{
					this.mValue = aObject.attr("data-value");
					this.mMapsViewport = (typeof aObject.attr("data-mapsViewport") == "undefined" || aObject.attr("data-mapsViewport") == "") ? null : aObject.attr("data-mapsViewport");

					this.mButton.html(theButtonValue + aObject.text());

					this.mItems.removeClass("selected");

					aObject.addClass("selected");

					this.onClick();
				}
			},

			loopSelectedValues: function()
			{
				var theThis = this;
				var theButtonValue = ((this.mPrefix != null) ? this.mPrefix : "");

				this.mValue = null;

				this.mItems.removeClass("selected");

				this.mItems.find("input[type='checkbox']:checked").parents(".customDropDown > ul > li").each(function()
				{
					var theCurrentSelectedItem = $(this);

					if (theThis.mValue != null)
					{
						theThis.mValue += ",";

						theThis.mButton.html(theButtonValue + theThis.mValue.split(",").length + " " + settings.various.itemsSelectedText);
					}
					else
					{
						theThis.mValue = "";

						theThis.mButton.html(theButtonValue + theCurrentSelectedItem.text());
					}

					if (typeof theCurrentSelectedItem.attr("data-value") != "undefined")
						theThis.mValue += theCurrentSelectedItem.attr("data-value");

					theCurrentSelectedItem.addClass("selected");
				});
			},

			resetValue: function()
			{
				this.mValue = null;
				this.mButton.html(this.mInitialButtonValue);

				this.mItems.removeClass("selected");
			}
		}

		if (typeof $(this).data("customDropDown") == 'undefined' || $(this).data("customDropDown") == null || !$(this).data("customDropDown").initialized)
		{
			theReturnObject.init($(this));
			$(this).data("customDropDown", theReturnObject);
		}
	});

	return $(this);
}
;
// Generated by CoffeeScript 1.10.0

/*
jQuery Growl
Copyright 2015 Kevin Sylvestre
1.3.2
 */

(function() {
  "use strict";
  var $, Animation, Growl,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  $ = jQuery;

  Animation = (function() {
    function Animation() {}

    Animation.transitions = {
      "webkitTransition": "webkitTransitionEnd",
      "mozTransition": "mozTransitionEnd",
      "oTransition": "oTransitionEnd",
      "transition": "transitionend"
    };

    Animation.transition = function($el) {
      var el, ref, result, type;
      el = $el[0];
      ref = this.transitions;
      for (type in ref) {
        result = ref[type];
        if (el.style[type] != null) {
          return result;
        }
      }
    };

    return Animation;

  })();

  Growl = (function() {
    Growl.settings = {
      namespace: 'growl',
      duration: 3200,
      close: "&#215;",
      location: "default",
      style: "default",
      size: "medium",
      delayOnHover: true
    };

    Growl.growl = function(settings) {
      if (settings == null) {
        settings = {};
      }
      this.initialize();
      return new Growl(settings);
    };

    Growl.initialize = function() {
      return $("body:not(:has(#growls))").append('<div id="growls" />');
    };

    function Growl(settings) {
      if (settings == null) {
        settings = {};
      }
      this.container = bind(this.container, this);
      this.content = bind(this.content, this);
      this.html = bind(this.html, this);
      this.$growl = bind(this.$growl, this);
      this.$growls = bind(this.$growls, this);
      this.animate = bind(this.animate, this);
      this.remove = bind(this.remove, this);
      this.dismiss = bind(this.dismiss, this);
      this.present = bind(this.present, this);
      this.waitAndDismiss = bind(this.waitAndDismiss, this);
      this.cycle = bind(this.cycle, this);
      this.close = bind(this.close, this);
      this.click = bind(this.click, this);
      this.mouseLeave = bind(this.mouseLeave, this);
      this.mouseEnter = bind(this.mouseEnter, this);
      this.unbind = bind(this.unbind, this);
      this.bind = bind(this.bind, this);
      this.render = bind(this.render, this);
      this.settings = $.extend({}, Growl.settings, settings);
      this.$growls().attr('class', this.settings.location);
      this.render();
    }

    Growl.prototype.render = function() {
      var $growl;
      $growl = this.$growl();
      this.$growls().append($growl);
      if (this.settings.fixed) {
        this.present();
      } else {
        this.cycle();
      }
    };

    Growl.prototype.bind = function($growl) {
      if ($growl == null) {
        $growl = this.$growl();
      }
      $growl.on("click", this.click);
      if (this.settings.delayOnHover) {
        $growl.on("mouseenter", this.mouseEnter);
        $growl.on("mouseleave", this.mouseLeave);
      }
      return $growl.on("contextmenu", this.close).find("." + this.settings.namespace + "-close").on("click", this.close);
    };

    Growl.prototype.unbind = function($growl) {
      if ($growl == null) {
        $growl = this.$growl();
      }
      $growl.off("click", this.click);
      if (this.settings.delayOnHover) {
        $growl.off("mouseenter", this.mouseEnter);
        $growl.off("mouseleave", this.mouseLeave);
      }
      return $growl.off("contextmenu", this.close).find("." + this.settings.namespace + "-close").off("click", this.close);
    };

    Growl.prototype.mouseEnter = function(event) {
      var $growl;
      $growl = this.$growl();
      return $growl.stop(true, true);
    };

    Growl.prototype.mouseLeave = function(event) {
      return this.waitAndDismiss();
    };

    Growl.prototype.click = function(event) {
      if (this.settings.url != null) {
        event.preventDefault();
        event.stopPropagation();
        return window.open(this.settings.url);
      }
    };

    Growl.prototype.close = function(event) {
      var $growl;
      event.preventDefault();
      event.stopPropagation();
      $growl = this.$growl();
      return $growl.stop().queue(this.dismiss).queue(this.remove);
    };

    Growl.prototype.cycle = function() {
      var $growl;
      $growl = this.$growl();
      return $growl.queue(this.present).queue(this.waitAndDismiss());
    };

    Growl.prototype.waitAndDismiss = function() {
      var $growl;
      $growl = this.$growl();
      return $growl.delay(this.settings.duration).queue(this.dismiss).queue(this.remove);
    };

    Growl.prototype.present = function(callback) {
      var $growl;
      $growl = this.$growl();
      this.bind($growl);
      return this.animate($growl, this.settings.namespace + "-incoming", 'out', callback);
    };

    Growl.prototype.dismiss = function(callback) {
      var $growl;
      $growl = this.$growl();
      this.unbind($growl);
      return this.animate($growl, this.settings.namespace + "-outgoing", 'in', callback);
    };

    Growl.prototype.remove = function(callback) {
      this.$growl().remove();
      return typeof callback === "function" ? callback() : void 0;
    };

    Growl.prototype.animate = function($element, name, direction, callback) {
      var transition;
      if (direction == null) {
        direction = 'in';
      }
      transition = Animation.transition($element);
      $element[direction === 'in' ? 'removeClass' : 'addClass'](name);
      $element.offset().position;
      $element[direction === 'in' ? 'addClass' : 'removeClass'](name);
      if (callback == null) {
        return;
      }
      if (transition != null) {
        $element.one(transition, callback);
      } else {
        callback();
      }
    };

    Growl.prototype.$growls = function() {
      return this.$_growls != null ? this.$_growls : this.$_growls = $('#growls');
    };

    Growl.prototype.$growl = function() {
      return this.$_growl != null ? this.$_growl : this.$_growl = $(this.html());
    };

    Growl.prototype.html = function() {
      return this.container(this.content());
    };

    Growl.prototype.content = function() {
      return "<div class='" + this.settings.namespace + "-close'>" + this.settings.close + "</div>\n<div class='" + this.settings.namespace + "-title'>" + this.settings.title + "</div>\n<div class='" + this.settings.namespace + "-message'>" + this.settings.message + "</div>";
    };

    Growl.prototype.container = function(content) {
      return "<div class='" + this.settings.namespace + " " + this.settings.namespace + "-" + this.settings.style + " " + this.settings.namespace + "-" + this.settings.size + "'>\n  " + content + "\n</div>";
    };

    return Growl;

  })();

  this.Growl = Growl;

  $.growl = function(options) {
    if (options == null) {
      options = {};
    }
    return Growl.growl(options);
  };

  $.growl.error = function(options) {
    var settings;
    if (options == null) {
      options = {};
    }
    settings = {
      title: "Error!",
      style: "error"
    };
    return $.growl($.extend(settings, options));
  };

  $.growl.notice = function(options) {
    var settings;
    if (options == null) {
      options = {};
    }
    settings = {
      title: "Notice!",
      style: "notice"
    };
    return $.growl($.extend(settings, options));
  };

  $.growl.warning = function(options) {
    var settings;
    if (options == null) {
      options = {};
    }
    settings = {
      title: "Warning!",
      style: "warning"
    };
    return $.growl($.extend(settings, options));
  };

}).call(this);
;
/*

TABGuard v1.0

jQuery UI Tabbing plugin.
http://spirytoos.blogspot.com.au/

Copyright (c) 2013 Tomasz Egiert

https://github.com/spirytoos/TABGuard/blob/master/LICENSE.md

Project site: http://tomaszegiert.seowebsolutions.com.au/tabguard/index.htm
Github site: https://github.com/spirytoos

 */
 
(function ($) {
	var defaults = {
		deactivate: false
	};

	var pluginName = 'tabGuard';

	$.fn[pluginName] = function (options) {
		var options = $.extend({}, defaults, options);
		var all = $(this);

		return this.each(function () {

			var $this = $(this);

			if (options.deactivate) {
				// Remove the events added by this plugin
				$this.off('.' + pluginName);
				return;
			}

			$this.on('keydown.' + pluginName, function (e) {

				// Make sure we're tabbing and hat our focused element is still focused
				if (e.keyCode === 9) {
					var tabbables = all.find(':tabbable'),
						first = tabbables.filter(':first'),
						last = tabbables.filter(':last'),
						focusedElement = $(e.target),

						isFirstInFocus = (first.get(0) === focusedElement.get(0)),
						isLastInFocus = (last.get(0) === focusedElement.get(0));

					// Check tab+shift
					var tabbingForward = !e.shiftKey;

					// Special case: radio buttons
					// input[type=radio] are always, according to jQuery ui, :tabbable.
					// If you've selected a radio input and press tab,
					// you will be tabbed to the next input and *not* to the next radio button
					//
					// Here we check if the active element is a radio and if the first/last is
					if (!isFirstInFocus && !isLastInFocus && focusedElement.is(':radio')) {
						var radioGroupName = focusedElement.attr('name');
						// If the focused element is a radio button
						if (tabbingForward) {
							if (last.is(':radio') && last.attr('name') === radioGroupName) {
								// the last one belongs to the same radio group as the focused one
								isLastInFocus = true;
							}
						} else {
							if (first.is(':radio') && first.attr('name') === radioGroupName) {
								// the first one belongs to the same radio group as the focused one
								isFirstInFocus = true;
							}
						}
					}

					if (tabbingForward) {
						if (isLastInFocus) {
							first.focus();
							e.preventDefault();
						}
					}
					else {
						if (isFirstInFocus) {
							last.focus();
							e.preventDefault();
						}
					}
				}
			});
		});
	};

})(jQuery);

(function(e,t){function i(t,i){var a,n,r,o=t.nodeName.toLowerCase();return"area"===o?(a=t.parentNode,n=a.name,t.href&&n&&"map"===a.nodeName.toLowerCase()?(r=e("img[usemap=#"+n+"]")[0],!!r&&s(r)):!1):(/input|select|textarea|button|object/.test(o)?!t.disabled:"a"===o?t.href||i:i)&&s(t)}function s(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var a=0,n=/^ui-id-\d+$/;e.ui=e.ui||{},e.extend(e.ui,{version:"1.10.3",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({focus:function(t){return function(i,s){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),s&&s.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;return t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(i){if(i!==t)return this.css("zIndex",i);if(this.length)for(var s,a,n=e(this[0]);n.length&&n[0]!==document;){if(s=n.css("position"),("absolute"===s||"relative"===s||"fixed"===s)&&(a=parseInt(n.css("zIndex"),10),!isNaN(a)&&0!==a))return a;n=n.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++a)})},removeUniqueId:function(){return this.each(function(){n.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,s){return!!e.data(t,s[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var s=e.attr(t,"tabindex"),a=isNaN(s);return(a||s>=0)&&i(t,!a)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(i,s){function a(t,i,s,a){return e.each(n,function(){i-=parseFloat(e.css(t,"padding"+this))||0,s&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),a&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var n="Width"===s?["Left","Right"]:["Top","Bottom"],r=s.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+s]=function(i){return i===t?o["inner"+s].call(this):this.each(function(){e(this).css(r,a(this,i)+"px")})},e.fn["outer"+s]=function(t,i){return"number"!=typeof t?o["outer"+s].call(this,t):this.each(function(){e(this).css(r,a(this,t,!0,i)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,i,s){var a,n=e.ui[t].prototype;for(a in s)n.plugins[a]=n.plugins[a]||[],n.plugins[a].push([i,s[a]])},call:function(e,t,i){var s,a=e.plugins[t];if(a&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(s=0;a.length>s;s++)e.options[a[s][0]]&&a[s][1].apply(e.element,i)}},hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",a=!1;return t[s]>0?!0:(t[s]=1,a=t[s]>0,t[s]=0,a)}})})(jQuery);;
/*!
 * Cropper v2.3.4
 * https://github.com/fengyuanchen/cropper
 *
 * Copyright (c) 2014-2016 Fengyuan Chen and contributors
 * Released under the MIT license
 *
 * Date: 2016-09-03T05:50:45.412Z
 */
!function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t("object"==typeof exports?require("jquery"):jQuery)}(function(t){"use strict";function i(t){return"number"==typeof t&&!isNaN(t)}function e(t){return"undefined"==typeof t}function s(t,e){var s=[];return i(e)&&s.push(e),s.slice.apply(t,s)}function a(t,i){var e=s(arguments,2);return function(){return t.apply(i,e.concat(s(arguments)))}}function o(t){var i=t.match(/^(https?:)\/\/([^\:\/\?#]+):?(\d*)/i);return i&&(i[1]!==C.protocol||i[2]!==C.hostname||i[3]!==C.port)}function h(t){var i="timestamp="+(new Date).getTime();return t+(t.indexOf("?")===-1?"?":"&")+i}function n(t){return t?' crossOrigin="'+t+'"':""}function r(t,i){var e;return t.naturalWidth&&!mt?i(t.naturalWidth,t.naturalHeight):(e=document.createElement("img"),e.onload=function(){i(this.width,this.height)},void(e.src=t.src))}function p(t){var e=[],s=t.rotate,a=t.scaleX,o=t.scaleY;return i(s)&&0!==s&&e.push("rotate("+s+"deg)"),i(a)&&1!==a&&e.push("scaleX("+a+")"),i(o)&&1!==o&&e.push("scaleY("+o+")"),e.length?e.join(" "):"none"}function l(t,i){var e,s,a=Ct(t.degree)%180,o=(a>90?180-a:a)*Math.PI/180,h=bt(o),n=Bt(o),r=t.width,p=t.height,l=t.aspectRatio;return i?(e=r/(n+h/l),s=e/l):(e=r*n+p*h,s=r*h+p*n),{width:e,height:s}}function c(e,s){var a,o,h,n=t("<canvas>")[0],r=n.getContext("2d"),p=0,c=0,d=s.naturalWidth,g=s.naturalHeight,u=s.rotate,f=s.scaleX,m=s.scaleY,v=i(f)&&i(m)&&(1!==f||1!==m),w=i(u)&&0!==u,x=w||v,C=d*Ct(f||1),b=g*Ct(m||1);return v&&(a=C/2,o=b/2),w&&(h=l({width:C,height:b,degree:u}),C=h.width,b=h.height,a=C/2,o=b/2),n.width=C,n.height=b,x&&(p=-d/2,c=-g/2,r.save(),r.translate(a,o)),w&&r.rotate(u*Math.PI/180),v&&r.scale(f,m),r.drawImage(e,$t(p),$t(c),$t(d),$t(g)),x&&r.restore(),n}function d(i){var e=i.length,s=0,a=0;return e&&(t.each(i,function(t,i){s+=i.pageX,a+=i.pageY}),s/=e,a/=e),{pageX:s,pageY:a}}function g(t,i,e){var s,a="";for(s=i,e+=i;s<e;s++)a+=Lt(t.getUint8(s));return a}function u(t){var i,e,s,a,o,h,n,r,p,l,c=new D(t),d=c.byteLength;if(255===c.getUint8(0)&&216===c.getUint8(1))for(p=2;p<d;){if(255===c.getUint8(p)&&225===c.getUint8(p+1)){n=p;break}p++}if(n&&(e=n+4,s=n+10,"Exif"===g(c,e,4)&&(h=c.getUint16(s),o=18761===h,(o||19789===h)&&42===c.getUint16(s+2,o)&&(a=c.getUint32(s+4,o),a>=8&&(r=s+a)))),r)for(d=c.getUint16(r,o),l=0;l<d;l++)if(p=r+12*l+2,274===c.getUint16(p,o)){p+=8,i=c.getUint16(p,o),mt&&c.setUint16(p,1,o);break}return i}function f(t){var i,e=t.replace(G,""),s=atob(e),a=s.length,o=new B(a),h=new y(o);for(i=0;i<a;i++)h[i]=s.charCodeAt(i);return o}function m(t){var i,e=new y(t),s=e.length,a="";for(i=0;i<s;i++)a+=Lt(e[i]);return"data:image/jpeg;base64,"+$(a)}function v(i,e){this.$element=t(i),this.options=t.extend({},v.DEFAULTS,t.isPlainObject(e)&&e),this.isLoaded=!1,this.isBuilt=!1,this.isCompleted=!1,this.isRotated=!1,this.isCropped=!1,this.isDisabled=!1,this.isReplaced=!1,this.isLimited=!1,this.wheeling=!1,this.isImg=!1,this.originalUrl="",this.canvas=null,this.cropBox=null,this.init()}var w=t(window),x=t(document),C=window.location,b=window.navigator,B=window.ArrayBuffer,y=window.Uint8Array,D=window.DataView,$=window.btoa,L="cropper",T="cropper-modal",X="cropper-hide",Y="cropper-hidden",k="cropper-invisible",M="cropper-move",W="cropper-crop",H="cropper-disabled",R="cropper-bg",z="mousedown touchstart pointerdown MSPointerDown",O="mousemove touchmove pointermove MSPointerMove",P="mouseup touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel",E="wheel mousewheel DOMMouseScroll",U="dblclick",I="load."+L,F="error."+L,j="resize."+L,A="build."+L,S="built."+L,N="cropstart."+L,_="cropmove."+L,q="cropend."+L,K="crop."+L,Z="zoom."+L,Q=/^(e|w|s|n|se|sw|ne|nw|all|crop|move|zoom)$/,V=/^data:/,G=/^data:([^;]+);base64,/,J=/^data:image\/jpeg.*;base64,/,tt="preview",it="action",et="e",st="w",at="s",ot="n",ht="se",nt="sw",rt="ne",pt="nw",lt="all",ct="crop",dt="move",gt="zoom",ut="none",ft=t.isFunction(t("<canvas>")[0].getContext),mt=b&&/(Macintosh|iPhone|iPod|iPad).*AppleWebKit/i.test(b.userAgent),vt=Number,wt=Math.min,xt=Math.max,Ct=Math.abs,bt=Math.sin,Bt=Math.cos,yt=Math.sqrt,Dt=Math.round,$t=Math.floor,Lt=String.fromCharCode;v.prototype={constructor:v,init:function(){var t,i=this.$element;if(i.is("img")){if(this.isImg=!0,this.originalUrl=t=i.attr("src"),!t)return;t=i.prop("src")}else i.is("canvas")&&ft&&(t=i[0].toDataURL());this.load(t)},trigger:function(i,e){var s=t.Event(i,e);return this.$element.trigger(s),s},load:function(i){var e,s,a=this.options,n=this.$element;if(i&&(n.one(A,a.build),!this.trigger(A).isDefaultPrevented())){if(this.url=i,this.image={},!a.checkOrientation||!B)return this.clone();if(e=t.proxy(this.read,this),V.test(i))return J.test(i)?e(f(i)):this.clone();s=new XMLHttpRequest,s.onerror=s.onabort=t.proxy(function(){this.clone()},this),s.onload=function(){e(this.response)},a.checkCrossOrigin&&o(i)&&n.prop("crossOrigin")&&(i=h(i)),s.open("get",i),s.responseType="arraybuffer",s.send()}},read:function(t){var i=this.options,e=u(t),s=this.image,a=0,o=1,h=1;if(e>1)switch(this.url=m(t),e){case 2:o=-1;break;case 3:a=-180;break;case 4:h=-1;break;case 5:a=90,h=-1;break;case 6:a=90;break;case 7:a=90,o=-1;break;case 8:a=-90}i.rotatable&&(s.rotate=a),i.scalable&&(s.scaleX=o,s.scaleY=h),this.clone()},clone:function(){var i,e,s=this.options,a=this.$element,r=this.url,p="";s.checkCrossOrigin&&o(r)&&(p=a.prop("crossOrigin"),p?i=r:(p="anonymous",i=h(r))),this.crossOrigin=p,this.crossOriginUrl=i,this.$clone=e=t("<img"+n(p)+' src="'+(i||r)+'">'),this.isImg?a[0].complete?this.start():a.one(I,t.proxy(this.start,this)):e.one(I,t.proxy(this.start,this)).one(F,t.proxy(this.stop,this)).addClass(X).insertAfter(a)},start:function(){var i=this.$element,e=this.$clone;this.isImg||(e.off(F,this.stop),i=e),r(i[0],t.proxy(function(i,e){t.extend(this.image,{naturalWidth:i,naturalHeight:e,aspectRatio:i/e}),this.isLoaded=!0,this.build()},this))},stop:function(){this.$clone.remove(),this.$clone=null},build:function(){var i,e,s,a=this.options,o=this.$element,h=this.$clone;this.isLoaded&&(this.isBuilt&&this.unbuild(),this.$container=o.parent(),this.$cropper=i=t(v.TEMPLATE),this.$canvas=i.find(".cropper-canvas").append(h),this.$dragBox=i.find(".cropper-drag-box"),this.$cropBox=e=i.find(".cropper-crop-box"),this.$viewBox=i.find(".cropper-view-box"),this.$face=s=e.find(".cropper-face"),o.addClass(Y).after(i),this.isImg||h.removeClass(X),this.initPreview(),this.bind(),a.aspectRatio=xt(0,a.aspectRatio)||NaN,a.viewMode=xt(0,wt(3,Dt(a.viewMode)))||0,a.autoCrop?(this.isCropped=!0,a.modal&&this.$dragBox.addClass(T)):e.addClass(Y),a.guides||e.find(".cropper-dashed").addClass(Y),a.center||e.find(".cropper-center").addClass(Y),a.cropBoxMovable&&s.addClass(M).data(it,lt),a.highlight||s.addClass(k),a.background&&i.addClass(R),a.cropBoxResizable||e.find(".cropper-line, .cropper-point").addClass(Y),this.setDragMode(a.dragMode),this.render(),this.isBuilt=!0,this.setData(a.data),o.one(S,a.built),this.completing=setTimeout(t.proxy(function(){this.trigger(S),this.trigger(K,this.getData()),this.isCompleted=!0},this),0))},unbuild:function(){this.isBuilt&&(this.isCompleted||clearTimeout(this.completing),this.isBuilt=!1,this.isCompleted=!1,this.initialImage=null,this.initialCanvas=null,this.initialCropBox=null,this.container=null,this.canvas=null,this.cropBox=null,this.unbind(),this.resetPreview(),this.$preview=null,this.$viewBox=null,this.$cropBox=null,this.$dragBox=null,this.$canvas=null,this.$container=null,this.$cropper.remove(),this.$cropper=null)},render:function(){this.initContainer(),this.initCanvas(),this.initCropBox(),this.renderCanvas(),this.isCropped&&this.renderCropBox()},initContainer:function(){var t=this.options,i=this.$element,e=this.$container,s=this.$cropper;s.addClass(Y),i.removeClass(Y),s.css(this.container={width:xt(e.width(),vt(t.minContainerWidth)||200),height:xt(e.height(),vt(t.minContainerHeight)||100)}),i.addClass(Y),s.removeClass(Y)},initCanvas:function(){var i,e=this.options.viewMode,s=this.container,a=s.width,o=s.height,h=this.image,n=h.naturalWidth,r=h.naturalHeight,p=90===Ct(h.rotate),l=p?r:n,c=p?n:r,d=l/c,g=a,u=o;o*d>a?3===e?g=o*d:u=a/d:3===e?u=a/d:g=o*d,i={naturalWidth:l,naturalHeight:c,aspectRatio:d,width:g,height:u},i.oldLeft=i.left=(a-g)/2,i.oldTop=i.top=(o-u)/2,this.canvas=i,this.isLimited=1===e||2===e,this.limitCanvas(!0,!0),this.initialImage=t.extend({},h),this.initialCanvas=t.extend({},i)},limitCanvas:function(t,i){var e,s,a,o,h=this.options,n=h.viewMode,r=this.container,p=r.width,l=r.height,c=this.canvas,d=c.aspectRatio,g=this.cropBox,u=this.isCropped&&g;t&&(e=vt(h.minCanvasWidth)||0,s=vt(h.minCanvasHeight)||0,n&&(n>1?(e=xt(e,p),s=xt(s,l),3===n&&(s*d>e?e=s*d:s=e/d)):e?e=xt(e,u?g.width:0):s?s=xt(s,u?g.height:0):u&&(e=g.width,s=g.height,s*d>e?e=s*d:s=e/d)),e&&s?s*d>e?s=e/d:e=s*d:e?s=e/d:s&&(e=s*d),c.minWidth=e,c.minHeight=s,c.maxWidth=1/0,c.maxHeight=1/0),i&&(n?(a=p-c.width,o=l-c.height,c.minLeft=wt(0,a),c.minTop=wt(0,o),c.maxLeft=xt(0,a),c.maxTop=xt(0,o),u&&this.isLimited&&(c.minLeft=wt(g.left,g.left+g.width-c.width),c.minTop=wt(g.top,g.top+g.height-c.height),c.maxLeft=g.left,c.maxTop=g.top,2===n&&(c.width>=p&&(c.minLeft=wt(0,a),c.maxLeft=xt(0,a)),c.height>=l&&(c.minTop=wt(0,o),c.maxTop=xt(0,o))))):(c.minLeft=-c.width,c.minTop=-c.height,c.maxLeft=p,c.maxTop=l))},renderCanvas:function(t){var i,e,s=this.canvas,a=this.image,o=a.rotate,h=a.naturalWidth,n=a.naturalHeight;this.isRotated&&(this.isRotated=!1,e=l({width:a.width,height:a.height,degree:o}),i=e.width/e.height,i!==s.aspectRatio&&(s.left-=(e.width-s.width)/2,s.top-=(e.height-s.height)/2,s.width=e.width,s.height=e.height,s.aspectRatio=i,s.naturalWidth=h,s.naturalHeight=n,o%180&&(e=l({width:h,height:n,degree:o}),s.naturalWidth=e.width,s.naturalHeight=e.height),this.limitCanvas(!0,!1))),(s.width>s.maxWidth||s.width<s.minWidth)&&(s.left=s.oldLeft),(s.height>s.maxHeight||s.height<s.minHeight)&&(s.top=s.oldTop),s.width=wt(xt(s.width,s.minWidth),s.maxWidth),s.height=wt(xt(s.height,s.minHeight),s.maxHeight),this.limitCanvas(!1,!0),s.oldLeft=s.left=wt(xt(s.left,s.minLeft),s.maxLeft),s.oldTop=s.top=wt(xt(s.top,s.minTop),s.maxTop),this.$canvas.css({width:s.width,height:s.height,left:s.left,top:s.top}),this.renderImage(),this.isCropped&&this.isLimited&&this.limitCropBox(!0,!0),t&&this.output()},renderImage:function(i){var e,s=this.canvas,a=this.image;a.rotate&&(e=l({width:s.width,height:s.height,degree:a.rotate,aspectRatio:a.aspectRatio},!0)),t.extend(a,e?{width:e.width,height:e.height,left:(s.width-e.width)/2,top:(s.height-e.height)/2}:{width:s.width,height:s.height,left:0,top:0}),this.$clone.css({width:a.width,height:a.height,marginLeft:a.left,marginTop:a.top,transform:p(a)}),i&&this.output()},initCropBox:function(){var i=this.options,e=this.canvas,s=i.aspectRatio,a=vt(i.autoCropArea)||.8,o={width:e.width,height:e.height};s&&(e.height*s>e.width?o.height=o.width/s:o.width=o.height*s),this.cropBox=o,this.limitCropBox(!0,!0),o.width=wt(xt(o.width,o.minWidth),o.maxWidth),o.height=wt(xt(o.height,o.minHeight),o.maxHeight),o.width=xt(o.minWidth,o.width*a),o.height=xt(o.minHeight,o.height*a),o.oldLeft=o.left=e.left+(e.width-o.width)/2,o.oldTop=o.top=e.top+(e.height-o.height)/2,this.initialCropBox=t.extend({},o)},limitCropBox:function(t,i){var e,s,a,o,h=this.options,n=h.aspectRatio,r=this.container,p=r.width,l=r.height,c=this.canvas,d=this.cropBox,g=this.isLimited;t&&(e=vt(h.minCropBoxWidth)||0,s=vt(h.minCropBoxHeight)||0,e=wt(e,p),s=wt(s,l),a=wt(p,g?c.width:p),o=wt(l,g?c.height:l),n&&(e&&s?s*n>e?s=e/n:e=s*n:e?s=e/n:s&&(e=s*n),o*n>a?o=a/n:a=o*n),d.minWidth=wt(e,a),d.minHeight=wt(s,o),d.maxWidth=a,d.maxHeight=o),i&&(g?(d.minLeft=xt(0,c.left),d.minTop=xt(0,c.top),d.maxLeft=wt(p,c.left+c.width)-d.width,d.maxTop=wt(l,c.top+c.height)-d.height):(d.minLeft=0,d.minTop=0,d.maxLeft=p-d.width,d.maxTop=l-d.height))},renderCropBox:function(){var t=this.options,i=this.container,e=i.width,s=i.height,a=this.cropBox;(a.width>a.maxWidth||a.width<a.minWidth)&&(a.left=a.oldLeft),(a.height>a.maxHeight||a.height<a.minHeight)&&(a.top=a.oldTop),a.width=wt(xt(a.width,a.minWidth),a.maxWidth),a.height=wt(xt(a.height,a.minHeight),a.maxHeight),this.limitCropBox(!1,!0),a.oldLeft=a.left=wt(xt(a.left,a.minLeft),a.maxLeft),a.oldTop=a.top=wt(xt(a.top,a.minTop),a.maxTop),t.movable&&t.cropBoxMovable&&this.$face.data(it,a.width===e&&a.height===s?dt:lt),this.$cropBox.css({width:a.width,height:a.height,left:a.left,top:a.top}),this.isCropped&&this.isLimited&&this.limitCanvas(!0,!0),this.isDisabled||this.output()},output:function(){this.preview(),this.isCompleted&&this.trigger(K,this.getData())},initPreview:function(){var i,e=n(this.crossOrigin),s=e?this.crossOriginUrl:this.url;this.$preview=t(this.options.preview),this.$clone2=i=t("<img"+e+' src="'+s+'">'),this.$viewBox.html(i),this.$preview.each(function(){var i=t(this);i.data(tt,{width:i.width(),height:i.height(),html:i.html()}),i.html("<img"+e+' src="'+s+'" style="display:block;width:100%;height:auto;min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;image-orientation:0deg!important;">')})},resetPreview:function(){this.$preview.each(function(){var i=t(this),e=i.data(tt);i.css({width:e.width,height:e.height}).html(e.html).removeData(tt)})},preview:function(){var i=this.image,e=this.canvas,s=this.cropBox,a=s.width,o=s.height,h=i.width,n=i.height,r=s.left-e.left-i.left,l=s.top-e.top-i.top;this.isCropped&&!this.isDisabled&&(this.$clone2.css({width:h,height:n,marginLeft:-r,marginTop:-l,transform:p(i)}),this.$preview.each(function(){var e=t(this),s=e.data(tt),c=s.width,d=s.height,g=c,u=d,f=1;a&&(f=c/a,u=o*f),o&&u>d&&(f=d/o,g=a*f,u=d),e.css({width:g,height:u}).find("img").css({width:h*f,height:n*f,marginLeft:-r*f,marginTop:-l*f,transform:p(i)})}))},bind:function(){var i=this.options,e=this.$element,s=this.$cropper;t.isFunction(i.cropstart)&&e.on(N,i.cropstart),t.isFunction(i.cropmove)&&e.on(_,i.cropmove),t.isFunction(i.cropend)&&e.on(q,i.cropend),t.isFunction(i.crop)&&e.on(K,i.crop),t.isFunction(i.zoom)&&e.on(Z,i.zoom),s.on(z,t.proxy(this.cropStart,this)),i.zoomable&&i.zoomOnWheel&&s.on(E,t.proxy(this.wheel,this)),i.toggleDragModeOnDblclick&&s.on(U,t.proxy(this.dblclick,this)),x.on(O,this._cropMove=a(this.cropMove,this)).on(P,this._cropEnd=a(this.cropEnd,this)),i.responsive&&w.on(j,this._resize=a(this.resize,this))},unbind:function(){var i=this.options,e=this.$element,s=this.$cropper;t.isFunction(i.cropstart)&&e.off(N,i.cropstart),t.isFunction(i.cropmove)&&e.off(_,i.cropmove),t.isFunction(i.cropend)&&e.off(q,i.cropend),t.isFunction(i.crop)&&e.off(K,i.crop),t.isFunction(i.zoom)&&e.off(Z,i.zoom),s.off(z,this.cropStart),i.zoomable&&i.zoomOnWheel&&s.off(E,this.wheel),i.toggleDragModeOnDblclick&&s.off(U,this.dblclick),x.off(O,this._cropMove).off(P,this._cropEnd),i.responsive&&w.off(j,this._resize)},resize:function(){var i,e,s,a=this.options.restore,o=this.$container,h=this.container;!this.isDisabled&&h&&(s=o.width()/h.width,1===s&&o.height()===h.height||(a&&(i=this.getCanvasData(),e=this.getCropBoxData()),this.render(),a&&(this.setCanvasData(t.each(i,function(t,e){i[t]=e*s})),this.setCropBoxData(t.each(e,function(t,i){e[t]=i*s})))))},dblclick:function(){this.isDisabled||(this.$dragBox.hasClass(W)?this.setDragMode(dt):this.setDragMode(ct))},wheel:function(i){var e=i.originalEvent||i,s=vt(this.options.wheelZoomRatio)||.1,a=1;this.isDisabled||(i.preventDefault(),this.wheeling||(this.wheeling=!0,setTimeout(t.proxy(function(){this.wheeling=!1},this),50),e.deltaY?a=e.deltaY>0?1:-1:e.wheelDelta?a=-e.wheelDelta/120:e.detail&&(a=e.detail>0?1:-1),this.zoom(-a*s,i)))},cropStart:function(i){var e,s,a=this.options,o=i.originalEvent,h=o&&o.touches,n=i;if(!this.isDisabled){if(h){if(e=h.length,e>1){if(!a.zoomable||!a.zoomOnTouch||2!==e)return;n=h[1],this.startX2=n.pageX,this.startY2=n.pageY,s=gt}n=h[0]}if(s=s||t(n.target).data(it),Q.test(s)){if(this.trigger(N,{originalEvent:o,action:s}).isDefaultPrevented())return;i.preventDefault(),this.action=s,this.cropping=!1,this.startX=n.pageX||o&&o.pageX,this.startY=n.pageY||o&&o.pageY,s===ct&&(this.cropping=!0,this.$dragBox.addClass(T))}}},cropMove:function(t){var i,e=this.options,s=t.originalEvent,a=s&&s.touches,o=t,h=this.action;if(!this.isDisabled){if(a){if(i=a.length,i>1){if(!e.zoomable||!e.zoomOnTouch||2!==i)return;o=a[1],this.endX2=o.pageX,this.endY2=o.pageY}o=a[0]}if(h){if(this.trigger(_,{originalEvent:s,action:h}).isDefaultPrevented())return;t.preventDefault(),this.endX=o.pageX||s&&s.pageX,this.endY=o.pageY||s&&s.pageY,this.change(o.shiftKey,h===gt?t:null)}}},cropEnd:function(t){var i=t.originalEvent,e=this.action;this.isDisabled||e&&(t.preventDefault(),this.cropping&&(this.cropping=!1,this.$dragBox.toggleClass(T,this.isCropped&&this.options.modal)),this.action="",this.trigger(q,{originalEvent:i,action:e}))},change:function(t,i){var e,s,a=this.options,o=a.aspectRatio,h=this.action,n=this.container,r=this.canvas,p=this.cropBox,l=p.width,c=p.height,d=p.left,g=p.top,u=d+l,f=g+c,m=0,v=0,w=n.width,x=n.height,C=!0;switch(!o&&t&&(o=l&&c?l/c:1),this.isLimited&&(m=p.minLeft,v=p.minTop,w=m+wt(n.width,r.width,r.left+r.width),x=v+wt(n.height,r.height,r.top+r.height)),s={x:this.endX-this.startX,y:this.endY-this.startY},o&&(s.X=s.y*o,s.Y=s.x/o),h){case lt:d+=s.x,g+=s.y;break;case et:if(s.x>=0&&(u>=w||o&&(g<=v||f>=x))){C=!1;break}l+=s.x,o&&(c=l/o,g-=s.Y/2),l<0&&(h=st,l=0);break;case ot:if(s.y<=0&&(g<=v||o&&(d<=m||u>=w))){C=!1;break}c-=s.y,g+=s.y,o&&(l=c*o,d+=s.X/2),c<0&&(h=at,c=0);break;case st:if(s.x<=0&&(d<=m||o&&(g<=v||f>=x))){C=!1;break}l-=s.x,d+=s.x,o&&(c=l/o,g+=s.Y/2),l<0&&(h=et,l=0);break;case at:if(s.y>=0&&(f>=x||o&&(d<=m||u>=w))){C=!1;break}c+=s.y,o&&(l=c*o,d-=s.X/2),c<0&&(h=ot,c=0);break;case rt:if(o){if(s.y<=0&&(g<=v||u>=w)){C=!1;break}c-=s.y,g+=s.y,l=c*o}else s.x>=0?u<w?l+=s.x:s.y<=0&&g<=v&&(C=!1):l+=s.x,s.y<=0?g>v&&(c-=s.y,g+=s.y):(c-=s.y,g+=s.y);l<0&&c<0?(h=nt,c=0,l=0):l<0?(h=pt,l=0):c<0&&(h=ht,c=0);break;case pt:if(o){if(s.y<=0&&(g<=v||d<=m)){C=!1;break}c-=s.y,g+=s.y,l=c*o,d+=s.X}else s.x<=0?d>m?(l-=s.x,d+=s.x):s.y<=0&&g<=v&&(C=!1):(l-=s.x,d+=s.x),s.y<=0?g>v&&(c-=s.y,g+=s.y):(c-=s.y,g+=s.y);l<0&&c<0?(h=ht,c=0,l=0):l<0?(h=rt,l=0):c<0&&(h=nt,c=0);break;case nt:if(o){if(s.x<=0&&(d<=m||f>=x)){C=!1;break}l-=s.x,d+=s.x,c=l/o}else s.x<=0?d>m?(l-=s.x,d+=s.x):s.y>=0&&f>=x&&(C=!1):(l-=s.x,d+=s.x),s.y>=0?f<x&&(c+=s.y):c+=s.y;l<0&&c<0?(h=rt,c=0,l=0):l<0?(h=ht,l=0):c<0&&(h=pt,c=0);break;case ht:if(o){if(s.x>=0&&(u>=w||f>=x)){C=!1;break}l+=s.x,c=l/o}else s.x>=0?u<w?l+=s.x:s.y>=0&&f>=x&&(C=!1):l+=s.x,s.y>=0?f<x&&(c+=s.y):c+=s.y;l<0&&c<0?(h=pt,c=0,l=0):l<0?(h=nt,l=0):c<0&&(h=rt,c=0);break;case dt:this.move(s.x,s.y),C=!1;break;case gt:this.zoom(function(t,i,e,s){var a=yt(t*t+i*i),o=yt(e*e+s*s);return(o-a)/a}(Ct(this.startX-this.startX2),Ct(this.startY-this.startY2),Ct(this.endX-this.endX2),Ct(this.endY-this.endY2)),i),this.startX2=this.endX2,this.startY2=this.endY2,C=!1;break;case ct:if(!s.x||!s.y){C=!1;break}e=this.$cropper.offset(),d=this.startX-e.left,g=this.startY-e.top,l=p.minWidth,c=p.minHeight,s.x>0?h=s.y>0?ht:rt:s.x<0&&(d-=l,h=s.y>0?nt:pt),s.y<0&&(g-=c),this.isCropped||(this.$cropBox.removeClass(Y),this.isCropped=!0,this.isLimited&&this.limitCropBox(!0,!0))}C&&(p.width=l,p.height=c,p.left=d,p.top=g,this.action=h,this.renderCropBox()),this.startX=this.endX,this.startY=this.endY},crop:function(){this.isBuilt&&!this.isDisabled&&(this.isCropped||(this.isCropped=!0,this.limitCropBox(!0,!0),this.options.modal&&this.$dragBox.addClass(T),this.$cropBox.removeClass(Y)),this.setCropBoxData(this.initialCropBox))},reset:function(){this.isBuilt&&!this.isDisabled&&(this.image=t.extend({},this.initialImage),this.canvas=t.extend({},this.initialCanvas),this.cropBox=t.extend({},this.initialCropBox),this.renderCanvas(),this.isCropped&&this.renderCropBox())},clear:function(){this.isCropped&&!this.isDisabled&&(t.extend(this.cropBox,{left:0,top:0,width:0,height:0}),this.isCropped=!1,this.renderCropBox(),this.limitCanvas(!0,!0),this.renderCanvas(),this.$dragBox.removeClass(T),this.$cropBox.addClass(Y))},replace:function(t,i){!this.isDisabled&&t&&(this.isImg&&this.$element.attr("src",t),i?(this.url=t,this.$clone.attr("src",t),this.isBuilt&&this.$preview.find("img").add(this.$clone2).attr("src",t)):(this.isImg&&(this.isReplaced=!0),this.options.data=null,this.load(t)))},enable:function(){this.isBuilt&&(this.isDisabled=!1,this.$cropper.removeClass(H))},disable:function(){this.isBuilt&&(this.isDisabled=!0,this.$cropper.addClass(H))},destroy:function(){var t=this.$element;this.isLoaded?(this.isImg&&this.isReplaced&&t.attr("src",this.originalUrl),this.unbuild(),t.removeClass(Y)):this.isImg?t.off(I,this.start):this.$clone&&this.$clone.remove(),t.removeData(L)},move:function(t,i){var s=this.canvas;this.moveTo(e(t)?t:s.left+vt(t),e(i)?i:s.top+vt(i))},moveTo:function(t,s){var a=this.canvas,o=!1;e(s)&&(s=t),t=vt(t),s=vt(s),this.isBuilt&&!this.isDisabled&&this.options.movable&&(i(t)&&(a.left=t,o=!0),i(s)&&(a.top=s,o=!0),o&&this.renderCanvas(!0))},zoom:function(t,i){var e=this.canvas;t=vt(t),t=t<0?1/(1-t):1+t,this.zoomTo(e.width*t/e.naturalWidth,i)},zoomTo:function(t,i){var e,s,a,o,h,n=this.options,r=this.canvas,p=r.width,l=r.height,c=r.naturalWidth,g=r.naturalHeight;if(t=vt(t),t>=0&&this.isBuilt&&!this.isDisabled&&n.zoomable){if(s=c*t,a=g*t,i&&(e=i.originalEvent),this.trigger(Z,{originalEvent:e,oldRatio:p/c,ratio:s/c}).isDefaultPrevented())return;e?(o=this.$cropper.offset(),h=e.touches?d(e.touches):{pageX:i.pageX||e.pageX||0,pageY:i.pageY||e.pageY||0},r.left-=(s-p)*((h.pageX-o.left-r.left)/p),r.top-=(a-l)*((h.pageY-o.top-r.top)/l)):(r.left-=(s-p)/2,r.top-=(a-l)/2),r.width=s,r.height=a,this.renderCanvas(!0)}},rotate:function(t){this.rotateTo((this.image.rotate||0)+vt(t))},rotateTo:function(t){t=vt(t),i(t)&&this.isBuilt&&!this.isDisabled&&this.options.rotatable&&(this.image.rotate=t%360,this.isRotated=!0,this.renderCanvas(!0))},scale:function(t,s){var a=this.image,o=!1;e(s)&&(s=t),t=vt(t),s=vt(s),this.isBuilt&&!this.isDisabled&&this.options.scalable&&(i(t)&&(a.scaleX=t,o=!0),i(s)&&(a.scaleY=s,o=!0),o&&this.renderImage(!0))},scaleX:function(t){var e=this.image.scaleY;this.scale(t,i(e)?e:1)},scaleY:function(t){var e=this.image.scaleX;this.scale(i(e)?e:1,t)},getData:function(i){var e,s,a=this.options,o=this.image,h=this.canvas,n=this.cropBox;return this.isBuilt&&this.isCropped?(s={x:n.left-h.left,y:n.top-h.top,width:n.width,height:n.height},e=o.width/o.naturalWidth,t.each(s,function(t,a){a/=e,s[t]=i?Dt(a):a})):s={x:0,y:0,width:0,height:0},a.rotatable&&(s.rotate=o.rotate||0),a.scalable&&(s.scaleX=o.scaleX||1,s.scaleY=o.scaleY||1),s},setData:function(e){var s,a,o,h=this.options,n=this.image,r=this.canvas,p={};t.isFunction(e)&&(e=e.call(this.element)),this.isBuilt&&!this.isDisabled&&t.isPlainObject(e)&&(h.rotatable&&i(e.rotate)&&e.rotate!==n.rotate&&(n.rotate=e.rotate,this.isRotated=s=!0),h.scalable&&(i(e.scaleX)&&e.scaleX!==n.scaleX&&(n.scaleX=e.scaleX,a=!0),i(e.scaleY)&&e.scaleY!==n.scaleY&&(n.scaleY=e.scaleY,a=!0)),s?this.renderCanvas():a&&this.renderImage(),o=n.width/n.naturalWidth,i(e.x)&&(p.left=e.x*o+r.left),i(e.y)&&(p.top=e.y*o+r.top),i(e.width)&&(p.width=e.width*o),i(e.height)&&(p.height=e.height*o),this.setCropBoxData(p))},getContainerData:function(){return this.isBuilt?this.container:{}},getImageData:function(){return this.isLoaded?this.image:{}},getCanvasData:function(){var i=this.canvas,e={};return this.isBuilt&&t.each(["left","top","width","height","naturalWidth","naturalHeight"],function(t,s){e[s]=i[s]}),e},setCanvasData:function(e){var s=this.canvas,a=s.aspectRatio;t.isFunction(e)&&(e=e.call(this.$element)),this.isBuilt&&!this.isDisabled&&t.isPlainObject(e)&&(i(e.left)&&(s.left=e.left),i(e.top)&&(s.top=e.top),i(e.width)?(s.width=e.width,s.height=e.width/a):i(e.height)&&(s.height=e.height,s.width=e.height*a),this.renderCanvas(!0))},getCropBoxData:function(){var t,i=this.cropBox;return this.isBuilt&&this.isCropped&&(t={left:i.left,top:i.top,width:i.width,height:i.height}),t||{}},setCropBoxData:function(e){var s,a,o=this.cropBox,h=this.options.aspectRatio;t.isFunction(e)&&(e=e.call(this.$element)),this.isBuilt&&this.isCropped&&!this.isDisabled&&t.isPlainObject(e)&&(i(e.left)&&(o.left=e.left),i(e.top)&&(o.top=e.top),i(e.width)&&(s=!0,o.width=e.width),i(e.height)&&(a=!0,o.height=e.height),h&&(s?o.height=o.width/h:a&&(o.width=o.height*h)),this.renderCropBox())},getCroppedCanvas:function(i){var e,s,a,o,h,n,r,p,l,d,g;if(this.isBuilt&&ft)return this.isCropped?(t.isPlainObject(i)||(i={}),g=this.getData(),e=g.width,s=g.height,p=e/s,t.isPlainObject(i)&&(h=i.width,n=i.height,h?(n=h/p,r=h/e):n&&(h=n*p,r=n/s)),a=$t(h||e),o=$t(n||s),l=t("<canvas>")[0],l.width=a,l.height=o,d=l.getContext("2d"),i.fillColor&&(d.fillStyle=i.fillColor,d.fillRect(0,0,a,o)),d.drawImage.apply(d,function(){var t,i,a,o,h,n,p=c(this.$clone[0],this.image),l=p.width,d=p.height,u=this.canvas,f=[p],m=g.x+u.naturalWidth*(Ct(g.scaleX||1)-1)/2,v=g.y+u.naturalHeight*(Ct(g.scaleY||1)-1)/2;return m<=-e||m>l?m=t=a=h=0:m<=0?(a=-m,m=0,t=h=wt(l,e+m)):m<=l&&(a=0,t=h=wt(e,l-m)),t<=0||v<=-s||v>d?v=i=o=n=0:v<=0?(o=-v,v=0,i=n=wt(d,s+v)):v<=d&&(o=0,i=n=wt(s,d-v)),f.push($t(m),$t(v),$t(t),$t(i)),r&&(a*=r,o*=r,h*=r,n*=r),h>0&&n>0&&f.push($t(a),$t(o),$t(h),$t(n)),f}.call(this)),l):c(this.$clone[0],this.image)},setAspectRatio:function(t){var i=this.options;this.isDisabled||e(t)||(i.aspectRatio=xt(0,t)||NaN,this.isBuilt&&(this.initCropBox(),this.isCropped&&this.renderCropBox()))},setDragMode:function(t){var i,e,s=this.options;this.isLoaded&&!this.isDisabled&&(i=t===ct,e=s.movable&&t===dt,t=i||e?t:ut,this.$dragBox.data(it,t).toggleClass(W,i).toggleClass(M,e),s.cropBoxMovable||this.$face.data(it,t).toggleClass(W,i).toggleClass(M,e))}},v.DEFAULTS={viewMode:0,dragMode:"crop",aspectRatio:NaN,data:null,preview:"",responsive:!0,restore:!0,checkCrossOrigin:!0,checkOrientation:!0,modal:!0,guides:!0,center:!0,highlight:!0,background:!0,autoCrop:!0,autoCropArea:.8,movable:!0,rotatable:!0,scalable:!0,zoomable:!0,zoomOnTouch:!0,zoomOnWheel:!0,wheelZoomRatio:.1,cropBoxMovable:!0,cropBoxResizable:!0,toggleDragModeOnDblclick:!0,minCanvasWidth:0,minCanvasHeight:0,minCropBoxWidth:0,minCropBoxHeight:0,minContainerWidth:200,minContainerHeight:100,build:null,built:null,cropstart:null,cropmove:null,cropend:null,crop:null,zoom:null},v.setDefaults=function(i){t.extend(v.DEFAULTS,i)},v.TEMPLATE='<div class="cropper-container"><div class="cropper-wrap-box"><div class="cropper-canvas"></div></div><div class="cropper-drag-box"></div><div class="cropper-crop-box"><span class="cropper-view-box"></span><span class="cropper-dashed dashed-h"></span><span class="cropper-dashed dashed-v"></span><span class="cropper-center"></span><span class="cropper-face"></span><span class="cropper-line line-e" data-action="e"></span><span class="cropper-line line-n" data-action="n"></span><span class="cropper-line line-w" data-action="w"></span><span class="cropper-line line-s" data-action="s"></span><span class="cropper-point point-e" data-action="e"></span><span class="cropper-point point-n" data-action="n"></span><span class="cropper-point point-w" data-action="w"></span><span class="cropper-point point-s" data-action="s"></span><span class="cropper-point point-ne" data-action="ne"></span><span class="cropper-point point-nw" data-action="nw"></span><span class="cropper-point point-sw" data-action="sw"></span><span class="cropper-point point-se" data-action="se"></span></div></div>',v.other=t.fn.cropper,t.fn.cropper=function(i){var a,o=s(arguments,1);return this.each(function(){var e,s,h=t(this),n=h.data(L);if(!n){if(/destroy/.test(i))return;e=t.extend({},h.data(),t.isPlainObject(i)&&i),h.data(L,n=new v(this,e))}"string"==typeof i&&t.isFunction(s=n[i])&&(a=s.apply(n,o))}),e(a)?this:a},t.fn.cropper.Constructor=v,t.fn.cropper.setDefaults=v.setDefaults,t.fn.cropper.noConflict=function(){return t.fn.cropper=v.other,this}});

$(document).ready(function()
{
	// Initialize.
	$(".no-touch .cropper").initializeImageCropper();

	if (typeof Sys != "undefined" && typeof Sys.WebForms != "undefined")
	{
		// After AJAX call.
		Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, e)
		{
			$(".no-touch .cropper").initializeImageCropper();
		});
	}
});

// Initialize image cropper.
$.fn.initializeImageCropper = function()
{
	$(this).each(function()
	{
		// Default values.
		var defaults = {
			zoomable: 			false,
			resizable:			true,
			guides:				true,
			viewMode:			2,
			autoCropArea:		1,
			minimumWidth:		100,
			minimumHeight:		100,
			optimalWidth: 		0,
			optimalHeight:		0,
			resizeFactor:		1,
			type:				"",
			buttonText:			settings.images.cropperButtonText,
			titleText:			settings.images.cropperTitleText,
			itemID:				settings.section.itemID
		};

		var options = $.extend(defaults, options);

		var originalImage = $(this);
		var dataContainer = originalImage;
		var originalImageURL = originalImage.prop("src").split("?")[0];
		var loader = $("<div class=\"loader update\" role=\"status\" />");
		var cropperButtons = $("<div class=\"cropperButtons\" />");
		var cropperButton = $("<div class=\"button openCropper transparent icon-resize-full before\" />");
		var rotateButton = $("<div class=\"button openRotate transparent icon-awesome-cw before\" />");
		var cropperLink = $("<a href=\"/\" />").html(options.buttonText).attr("title", options.titleText);
		var rotateLink = $("<a href=\"/\" />").html(settings.buttons.rotateText).attr("title", settings.images.rotateTitleText);
		var powerangeTrigger = false;

		if (dataContainer.data("cropper-type") == undefined)
		{
			// Try parent.
			dataContainer = originalImage.parents("div:first");
		}

		if (dataContainer.data("cropper-type") == undefined)
		{
			// Image type is mandatory.
			$.fn.showError(settings.errors.noCropperImageType + " (500.81)", "console");

			return false;
		}
		else
		{
			options.type = dataContainer.data("cropper-type");
		}

		if (dataContainer.data("cropper-width") != undefined)
		{
			options.optimalWidth = dataContainer.data("cropper-width");
		}

		if (dataContainer.data("cropper-height") != undefined)
		{
			options.optimalHeight = dataContainer.data("cropper-height");
		}

		if (dataContainer.data("cropper-button-text") != undefined)
		{
			cropperLink.html(dataContainer.data("cropper-button-text"));
		}

		if (dataContainer.data("cropper-content-page-id") != undefined) {
			options.itemID = parseInt(dataContainer.data("cropper-content-page-id"));
		}

		// Append loader.
		dataContainer.append(loader);

		cropperLink.unbind("click").click(function()
		{
			// Remove previously created overlay.
			$(".cropperOverlay").remove();

			// Create new overlay.
			var overlay = $("<div class=\"overlay cropperOverlay\" aria-modal=\"true\"><div class=\"overlayContent fullscreen\" /></div>");
			var overlayCloseButton = $("<a href=\"#\" class=\"button close info icon-cancel-circled iconOnly before pointer\"><span class=\"screenReaderContent\">" + settings.buttons.closeText + "</span></a>");
			var overlayTitle = $("<h1 class=\"overlayItemTitle\">" + options.titleText + "</h1>");
			var overlayHelp = $("<div class=\"overlayItemHeader\" />");
			var overlayContent = $("<div class=\"overlayItemContent invisible\" />");

			if (options.optimalWidth > 0 && options.optimalHeight > 0)
			{
				overlayHelp.append($("<p class=\"help\">" + settings.images.cropperHelpText + " " + options.optimalWidth + " x " + options.optimalHeight + " pixels.</p>"));
			}
			else if (options.optimalWidth > 0 && options.optimalHeight == 0)
			{
				overlayHelp.append("<p class=\"help\">" + settings.images.cropperHelpText + " " + options.optimalWidth + " pixels " + settings.images.widthText + ".</p>");
			}
			else if (options.optimalHeight > 0 && options.optimalWidth == 0)
			{
				overlayHelp.append("<p class=\"help\">" + settings.images.cropperHelpText + " " + options.optimalHeight + " pixels " + settings.images.heightText + ".</p>");
			}

			overlayHelp.append("<div class=\"loader show\" />");
			overlayContent.append("<p>" + "<img src=\"" + originalImageURL + "?preventCache=" + new Date().getTime().toString() + "\" class=\"imageToCrop\" />" + "</p>");

			// Create overlay.
			overlay.find(".overlayContent").append(overlayCloseButton).append(overlayTitle).append(overlayHelp).append(overlayContent);

			// Initialize dummy cropper (yeah suxx, I know...).
			var dummyCrapper = overlay.find(".imageToCrop").cropper(
			{
				built: function()
				{
					// Calculate relative cropbox width & height.
					var image = dummyCrapper.cropper("getImageData");

					options.resizeFactor = image.width / image.naturalWidth;

					// Destroy dummy meuk.
					dummyCrapper.cropper("destroy");

					// Initialize real image cropper.
					willTheRealImageCropperPleaseInitialize();
				}
			});

			function willTheRealImageCropperPleaseInitialize()
			{
				// Initialize image cropper.
				var cropper = overlay.find(".imageToCrop").cropper(
				{
					viewMode:			options.viewMode,
					zoomable:			options.zoomable,
					cropBoxResizable: 	options.resizable,
					autoCropArea:		options.autoCropArea,
					guides:				options.guides,
					minCropBoxWidth:	options.minimumWidth * options.resizeFactor,
					minCropBoxHeight:	options.minimumHeight * options.resizeFactor,
					crop: function(data)
					{
						if (!powerangeTrigger)
						{
							// Update sliders.
							if ($("#cropperImageWidth").val() != data.width)
							{
								if (settings.webGuidelines)
								{
									$("#cropperImageWidth").val(Math.round(data.width));
								}
								else
								{
									var widthSlider = $("#cropperImageWidth").parents(".field.powerange").data("powerange");
									widthSlider.setStart(data.width);
								}
							}

							if ($("#cropperImageHeight").val() != data.height)
							{
								if (settings.webGuidelines)
								{
									$("#cropperImageHeight").val(Math.round(data.width));
								}
								else
								{
									var heightSlider = $("#cropperImageHeight").parents(".field.powerange").data("powerange");
									heightSlider.setStart(data.height);
								}
							}
						}

						// Reset trigger.
						powerangeTrigger = false;

						//console.log("crop: [x: " + data.x + " y: " + data.y + " width: " + data.width + " height: " + data.height + " rotate: " + data.rotate + "]");
					},
					cropstart: function()
					{
						// Disable overlay "close on click".
						overlay.data("close-on-click", false);
					},
					cropend: function()
					{
						// Re-enable overlay "close on click".
						setTimeout(function()
						{
							overlay.data("close-on-click", true);
						}, 100);
					},
					built: function()
					{
						// Calculate relative cropbox width & height.
						var image = cropper.cropper("getImageData");

						// Image too small.
						if (image.naturalWidth < options.minimumWidth || image.naturalHeight < options.minimumHeight)
						{
							overlay.find(".overlayItemHeader").html(settings.warnings.imageTooSmallText);
							cropper.cropper("destroy");

							return false;
						}

						if (options.optimalWidth > 0 && options.optimalHeight > 0)
						{
							if (options.optimalWidth > image.naturalWidth)
							{
								// Set optimal width to current image width.
								options.optimalWidth = image.naturalWidth;
							}

							if (options.optimalHeight > image.naturalHeight)
							{
								// Set optimal height to current image height.
								options.optimalHeight = image.naturalHeight;
							}

							// Initial cropbox size.
							cropper.cropper("setCropBoxData", {width: (options.optimalWidth * options.resizeFactor), height: (options.optimalHeight * options.resizeFactor)});
						}

						// Width & height sliders in overlay.
						var widthSlider = $("<div class=\"field powerange center\" data-powerange-minimum=\"" + options.minimumWidth + "\" data-powerange-maximum=\"" + image.naturalWidth + "\" data-powerange-step=\"1\" data-powerange-text=\" pixels\" />");
						widthSlider.append("<label for=\"cropperImageWidth\">" + settings.images.widthSliderText + "</label><input type=\"text\" id=\"cropperImageWidth\" value=\"" + options.optimalWidth + "\" />");

						var heightSlider = $("<div class=\"field powerange center\" data-powerange-minimum=\"" + options.minimumHeight + "\" data-powerange-maximum=\"" + image.naturalHeight+ "\" data-powerange-step=\"1\" data-powerange-text=\" pixels\" />");
						heightSlider.append("<label for=\"cropperImageHeight\">" + settings.images.heightSliderText + "</label><input type=\"text\" id=\"cropperImageHeight\" value=\"" + options.optimalHeight + "\" />");

						overlay.find(".overlayItemContent").append(widthSlider).append(heightSlider);
						overlay.find(".field.powerange").initializePowerange();

						// Change crobox size on slider change.
						overlay.find("#cropperImageWidth, #cropperImageHeight").unbind("change").change(function()
						{
							powerangeTrigger = true;

							// Update cropbox size.
							cropper.cropper("setCropBoxData", {width: ($("#cropperImageWidth").val() * options.resizeFactor), height: ($("#cropperImageHeight").val() * options.resizeFactor)});
						});

						// Save button.
						var buttonSave = $("<div class=\"button save general icon-floppy before\"><input type=\"button\" value=\"" + settings.buttons.saveText + "\" /></div>");

						// Save button.
						buttonSave.find("input:button").unbind("click").click(function()
						{
							// Show loader.
							$(this).parents(".toolbarBottom").find(".button").hide();
							$(this).parents(".toolbarBottom").find(".loader").show();

							// Get data.
							var croppedImage = cropper.cropper("getData", true);

							//console.log("save: [x: " + croppedImage.x + " y: " + croppedImage.y + " width: " + croppedImage.width + " height: " + croppedImage.height + " rotate: " + croppedImage.rotate + "]");

							// Save image.
							$.ajax(
							{
								url: "/api/images/saveCroppedImage",
								data:
								{
									x:			croppedImage.x,
									y:			croppedImage.y,
									width:		croppedImage.width,
									height:		croppedImage.height,
									rotate:		croppedImage.rotate,
									url:		originalImageURL,
									sectionID:	settings.section.ID,
									itemID:		options.itemID,
									type:		options.type,
									token:   	$("input[name='__RequestVerificationToken']").val()
								}
							})
							.done(function(data)
							{
								var imageURL = originalImageURL;

								if (data.imagePath && data.imagePath != "")
									imageURL = data.imagePath;

								imageURL += imageURL.indexOf("?") > -1 ? "&" : "?";
								imageURL += "preventCache=" + new Date().getTime().toString();

								// Reload original image.
								originalImage.prop("src", imageURL);

								// Reset.
								cropper.cropper("destroy");
								originalImage.parent().find(".cropperButtons").remove();
								originalImage.initializeImageCropper();

								// Close overlay.
								overlayCloseButton.click();
							})
							.fail(function()
							{
								$.fn.showError(arguments + ". (500.80)", "console");
							});
						});

						overlay.find(".overlayItemContent").append("<div class=\"toolbar toolbarBottom\"><div class=\"loader\">" + settings.buttons.savingText + "</div></div>");
						overlay.find(".toolbarBottom").append(buttonSave);
						overlay.initializeToolbars();

						// All done! Show content.
						overlay.find(".loader").removeClass("show");
						overlay.find(".overlayItemContent").removeClass("invisible");
					}
				});
			};

			// Show overlay.
			$("body").append(overlay);
			$(".cropperOverlay").initializeOverlays();

			return false;
		});

		rotateLink.unbind("click").click(function()
		{
			// Hide buttons & show loader.
			cropperButtons.hide();
			loader.show();

			// Save image.
			$.ajax(
			{
				url: "/api/images/saveCroppedImage",
				data:
				{
					rotate:		90,
					url:		originalImageURL,
					sectionID:	settings.section.ID,
					itemID:		options.itemID,
					type:		options.type,
					token:   	$("input[name='__RequestVerificationToken']").val()
				}
			})
			.done(function(data)
			{
				var imageURL = originalImageURL;

				if (data.imagePath && data.imagePath != "")
					imageURL = data.imagePath;

				imageURL += imageURL.indexOf("?") > -1 ? "&" : "?";
				imageURL += "preventCache=" + new Date().getTime().toString();

				// Reload original image.
				originalImage.prop("src", imageURL);

				// Show buttons & hide loader.
				loader.hide();
				cropperButtons.show();
			})
			.fail(function()
			{
				$.fn.showError(arguments + ". (500.88)", "console");
			});

			return false;
		});

		// Place buttons on image.
		cropperButton.append(cropperLink);
		rotateButton.append(rotateLink);

		cropperButtons.append(cropperButton).append(rotateButton);
		cropperButtons.insertAfter(originalImage);
	});
};
;
/*!
 * jquery.sumoselect - v3.0.2
 * http://hemantnegi.github.io/jquery.sumoselect
 * 2014-04-08
 *
 * Copyright 2015 Hemant Negi
 * Email : hemant.frnz@gmail.com
 * Compressor http://refresh-sf.com/
 */

(function ($)
{
    'namespace sumo';
    $.fn.SumoSelect = function (options) {

        // This is the easiest way to have default options.
        var settings = $.extend({
            placeholder: 'Select Here',      // Dont change it here.
            csvDispCount: 3,                // display no. of items in multiselect. 0 to display all.
            captionFormat:'{0} Selected',   // format of caption text. you can set your locale.
            captionFormatAllSelected:'{0} all selected!', // format of caption text when all elements are selected. set null to use captionFormat. It will not work if there are disabled elements in select.
            floatWidth: 400,                // Screen width of device at which the list is rendered in floating popup fashion.
            forceCustomRendering: false,    // force the custom modal on all devices below floatWidth resolution.
            nativeOnDevice: ['Android', 'BlackBerry', 'iPhone', 'iPad', 'iPod', 'Opera Mini', 'IEMobile', 'Silk'], //
            outputAsCSV: false,              // true to POST data as csv ( false for Html control array ie. default select )
            csvSepChar: ',',                // separation char in csv mode
            okCancelInMulti: false,         // display ok cancel buttons in desktop mode multiselect also.
            triggerChangeCombined: true,    // im multi select mode wether to trigger change event on individual selection or combined selection.
            selectAll: false,               // to display select all button in multiselect mode.|| also select all will not be available on mobile devices.

            search: false,                  // to display input for filtering content. selectAlltext will be input text placeholder
            searchText: 'Search...',        // placeholder for search input
            noMatch: 'No matches for "{0}"',
            prefix: '',                     // some prefix usually the field name. eg. '<b>Hello</b>'
            locale: ['OK', 'Cancel'],       // all text that is used. don't change the index.
            up: false,                      // set true to open upside.
			moderatorCheck: false,
			publicCheck: false,
			authenticatedCheck: false,
            rolelessCheck: false,
			adminRole: "",
			moderatorRole: "",
			publicRole: "",
			autenticatedRole: "",
			adminWarning: "",
			moderatorWarning: "",
			publicWarning: "",
			authenticatedWarning: "",
            roleWarning: "",
            rolelessWarning: "",
            selectAllText: "",
            selectAllSearchText: "",
            sectionID: -1
        }, options);

        var ret = this.each(function () {
            var selObj = this; // the original select object.
            if (this.sumo || !$(this).is('select')) return; //already initialized

            this.sumo = {
                E: $(selObj),   //the jquery object of original select element.
                is_multi: $(selObj).attr('multiple'),  //if its a multiple select
                select: '',
                caption: '',
                placeholder: '',
                optDiv: '',
                CaptionCont: '',
                ul:'',
                is_floating: false,
                is_opened: false,
                //backdrop: '',
                mob:false, // if to open device default select
                Pstate: [],
				searchTimeout: 0,

                createElems: function () {
                    var O = this;
                    O.E.wrap('<div class="SumoSelect" tabindex="0">');
                    O.select = O.E.parent();
                    O.caption = $('<span>');
                    O.CaptionCont = $('<p class="CaptionCont"><label><i></i></label></p>').addClass('SelectBox').attr('style', O.E.attr('style')).prepend(O.caption);
                    O.select.append(O.CaptionCont);

                    // default turn off if no multiselect
                    if(!O.is_multi)settings.okCancelInMulti = false

                    if(O.E.attr('disabled'))
                        O.select.addClass('disabled').removeAttr('tabindex');

                    //if output as csv and is a multiselect.
                    if (settings.outputAsCSV && O.is_multi && O.E.attr('name')) {
                        //create a hidden field to store csv value.
                        O.select.append($('<input class="HEMANT123" type="hidden" />').attr('name', O.E.attr('name')).val(O.getSelStr()));

                        // so it can not post the original select.
                        O.E.removeAttr('name');
                    }

                    //break for mobile rendring.. if forceCustomRendering is false
                    if (O.isMobile() && !settings.forceCustomRendering) {
                        O.setNativeMobile();
                        return;
                    }

                    // if there is a name attr in select add a class to container div.
					if(O.E.attr('name')) O.select.addClass('sumo_'+O.E.attr('name'))

                    //hide original select
                    O.E.addClass('SumoUnder').attr('tabindex','-1');

                    //## Creating the list...
                    O.optDiv = $('<div class="optWrapper '+ (settings.up?'up':'') +'">');

                    //branch for floating list in low res devices.
                    O.floatingList();

                    //Creating the markup for the available options
                    O.ul = $('<ul class="options">');
                    O.optDiv.append(O.ul);

                    // Select all functionality
                    if(settings.selectAll) O.SelAll();

                    // search functionality
                    if(settings.search) O.Search();

                    O.ul.append(O.prepItems(O.E.children()));

                    //if multiple then add the class multiple and add OK / CANCEL button
                    if (O.is_multi) O.multiSelelect();

                    O.select.append(O.optDiv);
                    O.basicEvents();
                    O.selAllState();
                },

                prepItems: function(opts, d){
                    var lis = [], O=this;
                    $(opts).each(function (i, opt) {       // parsing options to li
                        opt = $(opt);
                        lis.push(opt.is('optgroup')?
                            $('<li class="group '+ (opt[0].disabled?'disabled':'') +'"><label>' + opt.attr('label') +'</label><ul></ul><li>')
                            .find('ul')
                            .append(O.prepItems(opt.children(), opt[0].disabled))
                            .end()
                            :
                            O.createLi(opt, d)
                            );
                    });
                    return lis;
                },

                //## Creates a LI element from a given option and binds events to it
                //## returns the jquery instance of li (not inserted in dom)
                createLi: function (opt, d) {
                    var O = this;

                    if(!opt.attr('value'))opt.attr('value',opt.val());
                    // todo: remove this data val
                    li = $('<li class="opt"><label>' + opt.text() + '</label></li>');//.data('val',opt.val());
                    li.data('opt', opt);    // store a direct reference to option.
                    opt.data('li', li);    // store a direct reference to list item.
                    if (O.is_multi) li.prepend('<span><i></i></span>');

                    if (opt[0].disabled || d || opt.attr('value') == options.sectionID)
                        li = li.addClass('disabled');

                    O.onOptClick(li);

                    if (opt[0].selected)
                        li.addClass('selected');

                    if (opt.attr('class'))
                        li.addClass(opt.attr('class'));

					// Extra checks.
					if (opt.text() == settings.adminRole)
					{
						li.addClass("adminRole");
					}

					if (opt.text() == settings.moderatorRole)
					{
						li.addClass("moderatorRole");
					}

					if (opt.text() == settings.autenticatedRole)
					{
					    li.addClass("authenticatedRole");
					}

                    if (opt.text() == settings.rolelessRole)
					{
					    li.addClass("rolelessRole");
					}

					if (opt.text() == settings.publicRole)
					{
						li.addClass("publicRole");
					}

                    return li;
                },

                //## Returns the selected items as string in a Multiselect.
                getSelStr: function () {
                    // get the pre selected items.
                    sopt = [];
                    this.E.find('option:selected').each(function () { sopt.push($(this).val()); });
                    return sopt.join(settings.csvSepChar);
                },

                //## THOSE OK/CANCEL BUTTONS ON MULTIPLE SELECT.
                multiSelelect: function () {
                    var O = this;
                    O.optDiv.addClass('multiple');
                    O.okbtn = $('<p class="btnOk">'+settings.locale[0]+'</p>').click(function () {

                        //if combined change event is set.
                        if (settings.triggerChangeCombined) {

                            //check for a change in the selection.
                            changed = false;
                            if (O.E.find('option:selected').length != O.Pstate.length) {
                                changed = true;
                            }
                            else {
                                O.E.find('option').each(function (i,e) {
                                    if(e.selected && O.Pstate.indexOf(i) < 0) changed = true;
                                });
                            }

                            if (changed) {
                                O.callChange();
                                O.setText();
                            }
                        }
                        O.hideOpts();
                    });
                    O.cancelBtn = $('<p class="btnCancel">'+settings.locale[1]+'</p>').click(function () {
                        O._cnbtn();
                        O.hideOpts();
                    });
                    O.optDiv.append($('<div class="MultiControls">').append(O.okbtn).append(O.cancelBtn));
                },

                _cnbtn:function(){
                    var O = this;
                    //remove all selections
                        O.E.find('option:selected').each(function () { this.selected = false; });
                        O.optDiv.find('li.selected').removeClass('selected')

                        //restore selections from saved state.
                        for(var i = 0; i < O.Pstate.length; i++) {
                            O.E.find('option')[O.Pstate[i]].selected = true;
                            O.ul.find('li.opt').eq(O.Pstate[i]).addClass('selected');
                        }
                    O.selAllState();
                },

                SelAll:function(){
                    var O = this;

                    if(!O.is_multi)return;
                    O.selAll = $('<p class="select-all"><span><i></i></span><label>' + settings.selectAllText + '</label></p>');
                    O.selAll.on('click',function(){
						//O.toggSelAll(!);
						O.selAll.toggleClass('selected');
						var targetItems;
						var selectAll = O.selAll.hasClass('selected');
						var excludeSelector = ".hidden, .disabled";

						if (selectAll)
						{
							if (settings.moderatorCheck)
							{
								// Exclude administrators & moderators role.
								excludeSelector += ", .adminRole, .moderatorRole";
							}

							if (settings.publicCheck)
							{
								excludeSelector += ", .publicRole";
							}

							if (settings.authenticatedCheck)
							{
								excludeSelector += ", .authenticatedRole";
							}

                            if (settings.rolelessCheck)
							{
								excludeSelector += ", .rolelessRole";
							}

							targetItems = O.optDiv.find("li.opt:not(.selected, " + excludeSelector + ")");
						}
						else
						{
							targetItems = O.optDiv.find("li.opt.selected:not(" + excludeSelector + ")");
						}

						targetItems.each(function(i)
						{
							var li = $(this);

							if (selectAll)
							{
								li.addClass("selected");
							}
							else
							{
								li.removeClass("selected");
							}

							li.data("opt")[0].selected = selectAll;
						});

						//branch for combined change event.
						if (!(O.is_multi && settings.triggerChangeCombined && (O.is_floating || settings.okCancelInMulti)))
						{
							O.setText();
							O.callChange();
						}
					});

                    O.optDiv.prepend(O.selAll);
                },

                // search module (can be removed if not required.)
                Search: function(){
                    var O = this,
                        cc = O.CaptionCont.addClass('search'),
                        P = $('<p class="no-match">');

                    O.ftxt = $('<input type="text" class="search-txt" value="" placeholder="' + settings.searchText + '">')
                        .on('click', function(e){
                            e.stopPropagation();
                        });
                    cc.append(O.ftxt);
                    O.optDiv.children('ul').after(P);

                    O.ftxt.on('keyup.sumo',function()
					{
						clearTimeout(O.searchTimeout);

						O.searchTimeout = setTimeout(function ()
						{
							var searchString = O.ftxt.val().toLowerCase();

                            // Change select all checkbox text (if needed).
                            if (searchString.length > 0)
                            {
                                O.select.find(".select-all label").html(settings.selectAllSearchText);
                            }
                            else
                            {
                                O.select.find(".select-all label").html(settings.selectAllText);
                            }

							var hid = O.optDiv.find('ul.options li.opt').addClass("hidden").filter(function(ix,e){
								e = $(e);
								if(e.text().toLowerCase().indexOf(searchString) > -1)
									return true;
							}).removeClass("hidden");

							setTimeout(function () { O.optDiv.find('ul.options').removeClass("hide"); }, 40);
							//P.html(settings.noMatch.replace(/\{0\}/g, O.ftxt.val())).toggle(!hid.length);

							O.selAllState();
						}, 500);
                    });
                },

                selAllState: function () {
                    var O = this;

                    if (settings.selectAll) {
						var sc = 0, vc = 0;
                        O.optDiv.find('li.opt').not('.hidden').each(function (ix, e) {
                            if ($(e).hasClass('selected') && !$(e).hasClass('disabled')) sc++;
                            if (!$(e).hasClass('disabled')) vc++;
                        });



                        //select all checkbox state change.
                        if (sc == 0) O.selAll.removeClass('selected')
                        else if (sc == vc && sc > 0) O.selAll.addClass('selected');
                        //else O.selAll.addClass('partial')//.removeClass('selected');
                    }
                },

                showOpts: function () {
                    var O = this;
                    if (O.E.attr('disabled')) return; // if select is disabled then retrun
                    O.is_opened = true;
                    O.select.addClass('open');

                    if(O.ftxt)O.ftxt.focus();
                    else O.select.focus();

                    // hide options on click outside.
                    $(document).on('click.sumo', function (e) {
                        if (!O.select.is(e.target)                  // if the target of the click isn't the container...
                            && O.select.has(e.target).length === 0){ // ... nor a descendant of the container
                            if(!O.is_opened)return;
                            O.hideOpts();
                            if (settings.okCancelInMulti)O._cnbtn();
                        }
                    });

                    if (O.is_floating) {
                        H = O.optDiv.children('ul').outerHeight() + 2;  // +2 is clear fix
                        if (O.is_multi) H = H + parseInt(O.optDiv.css('padding-bottom'));
                        O.optDiv.css('height', H);
                        $('body').addClass('sumoStopScroll');
                    }

                    O.setPstate();
                },

                //maintain state when ok/cancel buttons are available storing the indexes.
                setPstate: function(){
                    var O = this;
                    if (O.is_multi && (O.is_floating || settings.okCancelInMulti)){
                        O.Pstate = [];
                        // assuming that find returns elements in tree order
                        O.E.find('option').each(function (i, e){if(e.selected) O.Pstate.push(i);});
                    }
                },

                callChange:function(){
                    this.E.trigger('change').trigger('click');
                },

                hideOpts: function () {
                    if (!O)
                        var O = $(this)[0];

                    if(O.is_opened){
                        O.is_opened = false;
                        O.select.removeClass('open').find('ul li.sel').removeClass('sel');
                        $(document).off('click.sumo');
                        O.select.focus();
                        $('body').removeClass('sumoStopScroll');

                        // clear the search
                        if(settings.search){
                            O.ftxt.val('');
                            O.optDiv.find('ul.options li').removeClass('hidden');
                            O.optDiv.find('.no-match').toggle(false);
                        }
                    }
                },
                setOnOpen: function () {
                    var O = this,
                        selectableObjects = O.optDiv.find('li.opt:not(.hidden, .disabled)'),
                        target;

                    if (O.selAll)
                        selectableObjects = selectableObjects.add(O.selAll);

                    target = selectableObjects.eq(settings.search ? 0 : O.E[0].selectedIndex);

                    O.optDiv.find('li.sel').removeClass('sel');

                    if (O.selAll)
                        O.selAll.removeClass('sel');

                    target.addClass('sel');
                    O.showOpts();
                },
                nav: function (up) {
                    var O = this, c,
                        s = O.ul.find('li.opt:not(.disabled, .hidden)'),
                        sel = O.ul.find('li.opt.sel:not(.hidden, .disabled)');

                    if (O.selAll) {
                        s = s.add(O.selAll);

                        if (O.selAll.hasClass('sel'))
                            sel = sel.add(O.selAll);
                    }

                    idx = s.index(sel);

                    if (O.is_opened && sel.length) {

                        if (up && idx > 0)
                            c = s.eq(idx-1);
                        else if(!up && idx < s.length-1 && idx > -1)
                            c = s.eq(idx+1);
                        else return; // if no items before or after

                        sel.removeClass('sel');
                        sel = c.addClass('sel');

                        // setting sel item to visible view.
                        var ul = O.ul,
                            st = ul.scrollTop(),
                            t = sel.position().top + st;
                        if(t >= st + ul.height()-sel.outerHeight())
                            ul.scrollTop(t - ul.height() + sel.outerHeight());
                        if(t<st)
                            ul.scrollTop(t);

                    }
                    else
                        O.setOnOpen();
                },

                basicEvents: function () {
                    var O = this;
                    O.CaptionCont.click(function (evt) {
                        O.E.trigger('click');
                        if (O.is_opened) O.hideOpts(); else O.showOpts();
                        evt.stopPropagation();
                    });

                        O.select.on('keydown.sumo', function (e) {
                            switch (e.which) {
                                case 38: // up
                                    O.nav(true);
                                    break;

                                case 40: // down
                                    O.nav(false);
                                    break;

                                case 32: // space
                                    if(settings.search && O.ftxt.is(e.target))return;
                                case 13: // enter
                                    if (O.is_opened) {
                                        selectedObjects = O.optDiv.find('ul li.sel');

                                        if (O.selAll && O.selAll.hasClass('sel'))
                                            selectedObjects = selectedObjects.add(O.selAll);

                                        selectedObjects.trigger('click');
                                    } else
                                        O.setOnOpen();
                                    break;
				                case 9:	 //tab
                                case 27: // esc
                                    if (settings.okCancelInMulti)O._cnbtn();
                                    O.hideOpts();
                                    return;

                                default:
                                    return; // exit this handler for other keys
                            }
                            e.preventDefault(); // prevent the default action (scroll / move caret)
                        });

                    $(window).on('resize.sumo', function () {
                        O.floatingList();
                    });
                },

                onOptClick: function (li) {
                    var O = this;

                    li.click(function ()
					{
                        var li = $(this);
						var executeClick = true;

						txt = "";

						if (li.hasClass('disabled'))
						{
							return;
                        }

						if (!li.hasClass("selected"))
						{
							// Warnings.
							if (settings.moderatorCheck && li.hasClass("adminRole") && !li.confirm(settings.adminWarning))
							{
								executeClick = false;
							}

							if (settings.moderatorCheck && li.hasClass("moderatorRole") && !li.confirm(settings.moderatorWarning))
							{
								executeClick = false;
							}

							if (settings.publicCheck && li.hasClass("publicRole") && !li.confirm(settings.publicWarning.replace("{rightsType}", li.parents("fieldset").find("legend").html().toLowerCase())))
							{
								executeClick = false;
							}

							if (settings.authenticatedCheck && li.hasClass("authenticatedRole") && !li.confirm(settings.authenticatedWarning.replace("{rightsType}", li.parents("fieldset").find("legend").html().toLowerCase())))
							{
								executeClick = false;
							}

                            // Show warning when trying to give edit rights to a standard role on a users page.
                            if (li.parents("fieldset").hasClass("editRights") && $("#optionsTabContent .pageTypeID input").length > 0 && $("#optionsTabContent .pageTypeID input").val() == 28) {
                                if (!li.hasClass("adminRole") && !li.hasClass("moderatorRole") && !li.hasClass("publicRole") && !li.hasClass("authenticatedRole")) {
                                    if (!li.confirm(settings.roleWarning.replace("{rightsType}", li.parents("fieldset").find("legend").html().toLowerCase()).replace("{selectedRole}", li.find("label").text()))) {
                                        executeClick = false;
                                    }
                                }
                            }
						}

						if (executeClick)
						{
							if (O.is_multi)
							{
								li.toggleClass('selected');
								li.data('opt')[0].selected = li.hasClass('selected');
								O.selAllState();
							}
							else
							{
								li.parent().find('li.selected').removeClass('selected'); //if not multiselect then remove all selections from this list
								li.toggleClass('selected');
								li.data('opt')[0].selected = true;
							}

							//branch for combined change event.
							if (!(O.is_multi && settings.triggerChangeCombined && (O.is_floating || settings.okCancelInMulti))) {
								O.setText();
								O.callChange();
							}

							if (!O.is_multi) O.hideOpts(); //if its not a multiselect then hide on single select.
						}
                    });
                },

                setText: function () {
                    var O = this;
                    O.placeholder = "";
                    if (O.is_multi) {
                        sels = O.E.find(':selected').not(':disabled'); //selected options.

                        for (i = 0; i < sels.length; i++) {
                                if (i + 1 >= settings.csvDispCount && settings.csvDispCount) {
                                    if (sels.length == O.E.find('option').length && settings.captionFormatAllSelected) {
                                        O.placeholder = settings.captionFormatAllSelected.replace(/\{0\}/g, sels.length)+',';
                                    } else {
                                        O.placeholder = settings.captionFormat.replace(/\{0\}/g, sels.length)+',';
                                    }

                                    break;
                                }
                                else O.placeholder += $(sels[i]).text() + ", ";
                            }
                            O.placeholder = O.placeholder.replace(/,([^,]*)$/, '$1'); //remove unexpected "," from last.
                    }
                    else {
                        O.placeholder = O.E.find(':selected').not(':disabled').text();
                    }

                    is_placeholder = false;

                    if (!O.placeholder) {

                        is_placeholder = true;

                        O.placeholder = O.E.attr('placeholder');
                        if (!O.placeholder)                  //if placeholder is there then set it
                            O.placeholder = O.E.find('option:disabled:selected').text();
                    }

                    O.placeholder = O.placeholder ? (settings.prefix + ' ' + O.placeholder) : settings.placeholder

                    //set display text
                    O.caption.html(O.placeholder);
                    O.CaptionCont.attr('title', O.placeholder);

                    //set the hidden field if post as csv is true.
                    csvField = O.select.find('input.HEMANT123');
                    if (csvField.length) csvField.val(O.getSelStr());

                    //add class placeholder if its a placeholder text.
                    if (is_placeholder) O.caption.addClass('placeholder'); else O.caption.removeClass('placeholder');
                    return O.placeholder;
                },

                isMobile: function () {

                    // Adapted from http://www.detectmobilebrowsers.com
                    var ua = navigator.userAgent || navigator.vendor || window.opera;

                    // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
                    for (var i = 0; i < settings.nativeOnDevice.length; i++) if (ua.toString().toLowerCase().indexOf(settings.nativeOnDevice[i].toLowerCase()) > 0) return settings.nativeOnDevice[i];
                    return false;
                },

                setNativeMobile: function () {
                    var O = this;
                    O.E.addClass('SelectClass')//.css('height', O.select.outerHeight());
					O.mob = true;
                    O.E.change(function () {
                        O.setText();
                    });
                },

                floatingList: function () {
                    var O = this;
                    //called on init and also on resize.
                    //O.is_floating = true if window width is < specified float width
                    O.is_floating = $(window).width() <= settings.floatWidth;

                    //set class isFloating
                    O.optDiv.toggleClass('isFloating', O.is_floating);

                    //remove height if not floating
                    if (!O.is_floating) O.optDiv.css('height', '');

                    //toggle class according to okCancelInMulti flag only when it is not floating
                    O.optDiv.toggleClass('okCancelInMulti', settings.okCancelInMulti && !O.is_floating);
                },

                //HELPERS FOR OUTSIDERS
                // validates range of given item operations
                vRange: function (i) {
                    var O = this;
                    opts = O.E.find('option');
                    if (opts.length <= i || i < 0) throw "index out of bounds"
                    return O;
                },

                //toggles selection on c as boolean.
                toggSel: function (c, i) {
                    var O = this;
                    if (typeof(i) === "number"){
                        O.vRange(i);
                        opt = O.E.find('option')[i];
                    }
                    else{
                        opt = O.E.find('option[value="'+i+'"]')[0]||0;
                    }
                    if (!opt || opt.disabled)
                        return;

                    if(opt.selected != c){
                        opt.selected = c;
                        if(!O.mob) $(opt).data('li').toggleClass('selected',c);

                        O.callChange();
                        O.setPstate();
                        O.setText();
                        O.selAllState();
                    }
                },
                
                //toggles disabled on c as boolean.
                toggDis: function (c, i) {
                    var O = this.vRange(i);
                    O.E.find('option')[i].disabled = c;                              
                    
                    if (!O.mob) {
                        O.optDiv.find('ul.options li').eq(i).toggleClass('disabled', c);
                        
                        if (c) {
                            O.optDiv.find('ul.options li').eq(i).removeClass('selected');
                        }
                    }
                    
                    O.setText();
                },

                // toggle disable/enable on complete select control
                toggSumo: function(val) {
                    var O = this;
                    O.enabled = val;
                    O.select.toggleClass('disabled', val);

                    if (val) {
                        O.E.attr('disabled', 'disabled');
                        O.select.removeAttr('tabindex');
                    }
                    else{
                        O.E.removeAttr('disabled');
                        O.select.attr('tabindex','0');
                    }

                    return O;
                },

                //toggles alloption on c as boolean.
                toggSelAll: function (c) {
                    var O = this;
                    O.E.find('option').each(function (ix, el) {
                        if (O.E.find('option')[$(this).index()].disabled) return;
                        O.E.find('option')[$(this).index()].selected = c;
                        if (!O.mob)
							O.optDiv.find('ul.options li').eq($(this).index()).toggleClass('selected', c);
                        O.setText();
                    });
                    if(!O.mob && O.selAll)O.selAll.removeClass('partial').toggleClass('selected',c);
                    O.callChange();
                    O.setPstate();
                },

                /* outside accessibility options
                   which can be accessed from the element instance.
                */
                reload:function(){
                    var elm = this.unload();
                    return $(elm).SumoSelect(settings);
                },

                unload: function () {
                    var O = this;
                    O.select.before(O.E);
                    O.E.show();

                    if (settings.outputAsCSV && O.is_multi && O.select.find('input.HEMANT123').length) {
                        O.E.attr('name', O.select.find('input.HEMANT123').attr('name')); // restore the name;
                    }
                    O.select.remove();
                    delete selObj.sumo;
                    return selObj;
                },

                //## add a new option to select at a given index.
                add: function (val, txt, i) {
                    if (typeof val == "undefined") throw "No value to add"

                    var O = this;
                    opts=O.E.find('option')
                    if (typeof txt == "number") { i = txt; txt = val; }
                    if (typeof txt == "undefined") { txt = val; }

                    opt = $("<option></option>").val(val).html(txt);

                    if (opts.length < i) throw "index out of bounds"

                    if (typeof i == "undefined" || opts.length == i) { // add it to the last if given index is last no or no index provides.
                        O.E.append(opt);
                        if(!O.mob)O.ul.append(O.createLi(opt));
                    }
                    else {
                        opts.eq(i).before(opt);
                        if(!O.mob)O.ul.find('li.opt').eq(i).before(O.createLi(opt));
                    }

                    return selObj;
                },

                //## removes an item at a given index.
                remove: function (i) {
                    var O = this.vRange(i);
                    O.E.find('option').eq(i).remove();
                    if(!O.mob)O.optDiv.find('ul.options li').eq(i).remove();
                    O.setText();
                },

                //## Select an item at a given index.
                selectItem: function (i) { this.toggSel(true, i); },

                //## UnSelect an iten at a given index.
                unSelectItem: function (i) { this.toggSel(false, i); },

                //## Select all items  of the select.
                selectAll: function () { this.toggSelAll(true); },

                //## UnSelect all items of the select.
                unSelectAll: function () { this.toggSelAll(false); },

                //## Disable an iten at a given index.
                disableItem: function (i) { this.toggDis(true, i) },

                //## Removes disabled an iten at a given index.
                enableItem: function (i) { this.toggDis(false, i) },

                //## New simple methods as getter and setter are not working fine in ie8-
                //## variable to check state of control if enabled or disabled.
                enabled : true,
                //## Enables the control
                enable: function(){return this.toggSumo(false)},

                //## Disables the control
                disable: function(){return this.toggSumo(true)},


                init: function () {
                    var O = this;
                    O.createElems();
                    O.setText();
                    return O
                }

            };

            selObj.sumo.init();
        });

        return ret.length == 1 ? ret[0] : ret;
    };
}(jQuery));

$(document).ready(function()
{
    // Show loader (optional).
    $(".multiSelect").find(".loader").show();

    // Sneaky timeout to make document load (feel) faster.
    setTimeout(function()
    {
        $(".multiSelect").initializeMultiSelects();
    }, 500);

	if (typeof Sys != "undefined" && typeof Sys.WebForms != "undefined")
	{
		// After AJAX call.
		Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, e)
		{
			// Sneaky timeout to make document load (feel) faster.
            setTimeout(function()
            {
                $(".multiSelect").initializeMultiSelects();
            }, 500);
		});
	}
});

// Multi selects.
$.fn.initializeMultiSelects = function()
{
	var multiSelects = $(this);

    multiSelects.each(function()
	{
		// Default values.
		var defaults = {
			customRendering:		true,
			search: 				true,
			selectAll:				true,
			moderatorCheck:			false,
			publicCheck:			false,
            authenticatedCheck:		false,
            rolelessCheck:          false,
            sectionID:              settings.section.ID,
			selectText:				settings.multiSelects.selectText,
			selectAllText:			settings.multiSelects.selectAllText,
            selectAllSearchText:    settings.multiSelects.selectAllSearchText,
			selectedText:			settings.multiSelects.selectedText,
			searchText:				settings.multiSelects.searchText,
			noMatchText:			settings.multiSelects.noMatchText,
			selectedDisplayCount:	3
		};

		var options = $.extend(defaults, options);

		var multiSelect = $(this);
		var source = multiSelect.find(".source");
		var destination = multiSelect.find(".destination");
		var combinedSelect = $("<select />").attr("multiple", "multiple").addClass("combinedSelect hide");

		if (multiSelect.find(".combinedSelect").length == 0)
		{
			multiSelect.prepend(combinedSelect);

			combinedSelect.change(function()
			{
				// Badge count.
				if (multiSelect.parents(".tabs.vertical .tabContent").length > 0 && !multiSelect.hasClass("noBadgeCount"))
				{
					var destinationCount = multiSelects.parents(".tabs.vertical .tabContent").find(".multiSelect:not(.noBadgeCount) .combinedSelect option:selected").length;
					var selectedTab = $("#" + multiSelects.parents(".tabs.vertical .tabContent").attr("id").replace("Content", ""));

					if (destinationCount > 0)
					{
						selectedTab.find(".badge").html(destinationCount).removeClass("hide");
					}
					else
					{
						selectedTab.find(".badge").addClass("hide");
					}
				}

				// Optional: additional function(s).
				if (multiSelect.data("multiselect-after-click") != undefined)
				{
					// Execute.
					eval(multiSelect.data("multiselect-after-click"));
				}

				// Optional: linked multi selects.
				if (multiSelect.data("multiselect-linked") != undefined)
				{
					options.selectAll = false;
					var linkedMultiSelect = $(multiSelect.data("multiselect-linked")).find(".combinedSelect");
                    
					combinedSelect.find("option").not(".disabled").each(function()
					{                        
                        if ($.trim($(this).val()) == "")
						{
							return;
						}

						var optionIndex = linkedMultiSelect.find("option[value=" + $(this).val() + "]").index();
                        
						if (optionIndex > -1)
						{
							if ($(this).is(":selected"))
							{
								// Disable option.                               
                                linkedMultiSelect.data("sumoselect").sumo.disableItem(optionIndex);
							}
							else
							{
								// Re-enable option.                              
                                linkedMultiSelect.data("sumoselect").sumo.enableItem(optionIndex);                              
							}
						}
					});
				}
			});
		}

		// Mobile.
		if ($(".touch:not(.desktop)").length > 0)
		{
			options.search = false;
			options.selectAll = false;
			options.selectedDisplayCount = 1;
		}

		// Rename system roles.
		source.find("option").setSystemRoleNames();
		destination.find("option").setSystemRoleNames();

		// Sort.
		source.find("option").sort(sortSelect).appendTo(source);
		destination.find("option").prop("selected", true);
		destination.find("option").sort(sortSelect).appendTo(destination);

		$(source.find("option").get().reverse()).each(function()
		{
			if ($(this).html().indexOf("METT - ") > -1)
			{
				// Place SYSTEM roles first.
				$(this).prependTo(source);
			}
		});

		$(destination.find("option").get().reverse()).each(function()
		{
			if ($(this).html().indexOf("METT - ") > -1)
			{
				// Place SYSTEM roles first.
				$(this).prependTo(destination);
			}
		});

		// Append options to combined select.
		destination.find("option:not([value=''])").appendTo(combinedSelect);
		source.find("option:not([value=''])").appendTo(combinedSelect);

		if (multiSelect.data("multiselect-option-type") != undefined)
		{
			options.selectText += " " + multiSelect.data("multiselect-option-type") + "...";
		}

		if (multiSelect.data("multiselect-options-type") != undefined)
		{
			options.selectAllText += " " + multiSelect.data("multiselect-options-type");
            options.selectAllSearchText += " " + multiSelect.data("multiselect-options-type");
			options.selectedText += " " + multiSelect.data("multiselect-options-type");
		}
			// Checks (optional).
		if (multiSelect.data("multiselect-moderator-check") != undefined)
		{
			options.moderatorCheck = multiSelect.data("multiselect-moderator-check");
		}

		if (multiSelect.data("multiselect-public-check") != undefined)
		{
			options.publicCheck = multiSelect.data("multiselect-public-check");
		}

		if (multiSelect.data("multiselect-authenticated-check") != undefined)
		{
			options.authenticatedCheck = multiSelect.data("multiselect-authenticated-check");
		}

        if (multiSelect.data("multiselect-roleless-check") != undefined)
		{
			options.rolelessCheck = multiSelect.data("multiselect-roleless-check");
		}

		if (multiSelect.data("multiselect-linked") != undefined)
		{
			options.selectAll = false;
		}

		// Sumo select.
		var sumoSelect = combinedSelect.SumoSelect(
		{
			forceCustomRendering: 		options.customRendering,
			search:						options.search,
			selectAll: 					options.selectAll,
			placeholder:				options.selectText,
			searchText:					options.searchText,
			captionFormat:				"{0} " + options.selectedText,
			captionFormatAllSelected:	"{0} " + options.selectedText,
			noMatch:					options.noMatchText + " \"{0}\"",
			locale:						["OK", settings.buttons.cancelText],
			csvDispCount:				options.selectedDisplayCount,
			moderatorCheck:				options.moderatorCheck,
			publicCheck:				options.publicCheck,
			authenticatedCheck:			options.authenticatedCheck,
            rolelessCheck:              options.rolelessCheck,
			adminRole:					settings.roles.administrators,
			moderatorRole:				settings.roles.moderators,
			autenticatedRole:			settings.roles.authenticated,
			publicRole:					settings.roles.everyone,
            rolelessRole:               settings.roles.roleless,
			adminWarning:				settings.warnings.makeAdminText,
			moderatorWarning:			settings.warnings.makeModeratorText,
			authenticatedWarning:		settings.warnings.rightsAuthenticatedText,
			publicWarning:				settings.warnings.rightsPublicText,
            roleWarning:                settings.warnings.rightsRoleText,
            rolelessWarning:            settings.warnings.rightsRolelessText,
            selectAllText:              options.selectAllText,
            selectAllSearchText:        options.selectAllSearchText,
            sectionID:                  options.sectionID
		});

		// Store instance in data object.
        combinedSelect.data("sumoselect", sumoSelect);
        multiSelect.trigger("sumo:initialized");

        // Initialize.
        multiSelect.find(".loader").hide();
        
		setTimeout(function() {
		    combinedSelect.change().removeClass("hide");
            
            // Check if sections multiselect is allowed.
            if (settings.section.enableSectionsSelect || (settings.user.isAdmin || settings.user.isModerator)) {
                // Show sections multiselect when there are > 1 sections.
                if (multiSelect.parents(".sections").length > 0 && combinedSelect.find("option").length > 1) {
                    multiSelect.parents(".sections").removeClass("hide");
                }
            }
        }, 50);
	});

	function sortSelect(a, b)
	{
		return (a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase()) ? 1 : -1;
	};
};
;
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.moment=t()}(this,function(){"use strict";var H;function f(){return H.apply(null,arguments)}function a(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function F(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function c(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function L(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;for(var t in e)if(c(e,t))return;return 1}function o(e){return void 0===e}function u(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function V(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function G(e,t){for(var n=[],s=e.length,i=0;i<s;++i)n.push(t(e[i],i));return n}function E(e,t){for(var n in t)c(t,n)&&(e[n]=t[n]);return c(t,"toString")&&(e.toString=t.toString),c(t,"valueOf")&&(e.valueOf=t.valueOf),e}function l(e,t,n,s){return Pt(e,t,n,s,!0).utc()}function m(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function A(e){if(null==e._isValid){var t=m(e),n=j.call(t.parsedDateParts,function(e){return null!=e}),n=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidEra&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n);if(e._strict&&(n=n&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return n;e._isValid=n}return e._isValid}function I(e){var t=l(NaN);return null!=e?E(m(t),e):m(t).userInvalidated=!0,t}var j=Array.prototype.some||function(e){for(var t=Object(this),n=t.length>>>0,s=0;s<n;s++)if(s in t&&e.call(this,t[s],s,t))return!0;return!1},Z=f.momentProperties=[],z=!1;function $(e,t){var n,s,i,r=Z.length;if(o(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),o(t._i)||(e._i=t._i),o(t._f)||(e._f=t._f),o(t._l)||(e._l=t._l),o(t._strict)||(e._strict=t._strict),o(t._tzm)||(e._tzm=t._tzm),o(t._isUTC)||(e._isUTC=t._isUTC),o(t._offset)||(e._offset=t._offset),o(t._pf)||(e._pf=m(t)),o(t._locale)||(e._locale=t._locale),0<r)for(n=0;n<r;n++)o(i=t[s=Z[n]])||(e[s]=i);return e}function q(e){$(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===z&&(z=!0,f.updateOffset(this),z=!1)}function h(e){return e instanceof q||null!=e&&null!=e._isAMomentObject}function B(e){!1===f.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function e(r,a){var o=!0;return E(function(){if(null!=f.deprecationHandler&&f.deprecationHandler(null,r),o){for(var e,t,n=[],s=arguments.length,i=0;i<s;i++){if(e="","object"==typeof arguments[i]){for(t in e+="\n["+i+"] ",arguments[0])c(arguments[0],t)&&(e+=t+": "+arguments[0][t]+", ");e=e.slice(0,-2)}else e=arguments[i];n.push(e)}B(r+"\nArguments: "+Array.prototype.slice.call(n).join("")+"\n"+(new Error).stack),o=!1}return a.apply(this,arguments)},a)}var J={};function Q(e,t){null!=f.deprecationHandler&&f.deprecationHandler(e,t),J[e]||(B(t),J[e]=!0)}function d(e){return"undefined"!=typeof Function&&e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function X(e,t){var n,s=E({},e);for(n in t)c(t,n)&&(F(e[n])&&F(t[n])?(s[n]={},E(s[n],e[n]),E(s[n],t[n])):null!=t[n]?s[n]=t[n]:delete s[n]);for(n in e)c(e,n)&&!c(t,n)&&F(e[n])&&(s[n]=E({},s[n]));return s}function K(e){null!=e&&this.set(e)}f.suppressDeprecationWarnings=!1,f.deprecationHandler=null;var ee=Object.keys||function(e){var t,n=[];for(t in e)c(e,t)&&n.push(t);return n};function r(e,t,n){var s=""+Math.abs(e);return(0<=e?n?"+":"":"-")+Math.pow(10,Math.max(0,t-s.length)).toString().substr(1)+s}var te=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,ne=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,se={},ie={};function s(e,t,n,s){var i="string"==typeof s?function(){return this[s]()}:s;e&&(ie[e]=i),t&&(ie[t[0]]=function(){return r(i.apply(this,arguments),t[1],t[2])}),n&&(ie[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function re(e,t){return e.isValid()?(t=ae(t,e.localeData()),se[t]=se[t]||function(s){for(var e,i=s.match(te),t=0,r=i.length;t<r;t++)ie[i[t]]?i[t]=ie[i[t]]:i[t]=(e=i[t]).match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"");return function(e){for(var t="",n=0;n<r;n++)t+=d(i[n])?i[n].call(e,s):i[n];return t}}(t),se[t](e)):e.localeData().invalidDate()}function ae(e,t){var n=5;function s(e){return t.longDateFormat(e)||e}for(ne.lastIndex=0;0<=n&&ne.test(e);)e=e.replace(ne,s),ne.lastIndex=0,--n;return e}var oe={};function t(e,t){var n=e.toLowerCase();oe[n]=oe[n+"s"]=oe[t]=e}function _(e){return"string"==typeof e?oe[e]||oe[e.toLowerCase()]:void 0}function ue(e){var t,n,s={};for(n in e)c(e,n)&&(t=_(n))&&(s[t]=e[n]);return s}var le={};function n(e,t){le[e]=t}function he(e){return e%4==0&&e%100!=0||e%400==0}function y(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function g(e){var e=+e,t=0;return t=0!=e&&isFinite(e)?y(e):t}function de(t,n){return function(e){return null!=e?(fe(this,t,e),f.updateOffset(this,n),this):ce(this,t)}}function ce(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function fe(e,t,n){e.isValid()&&!isNaN(n)&&("FullYear"===t&&he(e.year())&&1===e.month()&&29===e.date()?(n=g(n),e._d["set"+(e._isUTC?"UTC":"")+t](n,e.month(),We(n,e.month()))):e._d["set"+(e._isUTC?"UTC":"")+t](n))}var i=/\d/,w=/\d\d/,me=/\d{3}/,_e=/\d{4}/,ye=/[+-]?\d{6}/,p=/\d\d?/,ge=/\d\d\d\d?/,we=/\d\d\d\d\d\d?/,pe=/\d{1,3}/,ke=/\d{1,4}/,ve=/[+-]?\d{1,6}/,Me=/\d+/,De=/[+-]?\d+/,Se=/Z|[+-]\d\d:?\d\d/gi,Ye=/Z|[+-]\d\d(?::?\d\d)?/gi,k=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;function v(e,n,s){be[e]=d(n)?n:function(e,t){return e&&s?s:n}}function Oe(e,t){return c(be,e)?be[e](t._strict,t._locale):new RegExp(M(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,s,i){return t||n||s||i})))}function M(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}var be={},xe={};function D(e,n){var t,s,i=n;for("string"==typeof e&&(e=[e]),u(n)&&(i=function(e,t){t[n]=g(e)}),s=e.length,t=0;t<s;t++)xe[e[t]]=i}function Te(e,i){D(e,function(e,t,n,s){n._w=n._w||{},i(e,n._w,n,s)})}var S,Y=0,O=1,b=2,x=3,T=4,N=5,Ne=6,Pe=7,Re=8;function We(e,t){if(isNaN(e)||isNaN(t))return NaN;var n=(t%(n=12)+n)%n;return e+=(t-n)/12,1==n?he(e)?29:28:31-n%7%2}S=Array.prototype.indexOf||function(e){for(var t=0;t<this.length;++t)if(this[t]===e)return t;return-1},s("M",["MM",2],"Mo",function(){return this.month()+1}),s("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),s("MMMM",0,0,function(e){return this.localeData().months(this,e)}),t("month","M"),n("month",8),v("M",p),v("MM",p,w),v("MMM",function(e,t){return t.monthsShortRegex(e)}),v("MMMM",function(e,t){return t.monthsRegex(e)}),D(["M","MM"],function(e,t){t[O]=g(e)-1}),D(["MMM","MMMM"],function(e,t,n,s){s=n._locale.monthsParse(e,s,n._strict);null!=s?t[O]=s:m(n).invalidMonth=e});var Ce="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),Ue="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),He=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Fe=k,Le=k;function Ve(e,t){var n;if(e.isValid()){if("string"==typeof t)if(/^\d+$/.test(t))t=g(t);else if(!u(t=e.localeData().monthsParse(t)))return;n=Math.min(e.date(),We(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n)}}function Ge(e){return null!=e?(Ve(this,e),f.updateOffset(this,!0),this):ce(this,"Month")}function Ee(){function e(e,t){return t.length-e.length}for(var t,n=[],s=[],i=[],r=0;r<12;r++)t=l([2e3,r]),n.push(this.monthsShort(t,"")),s.push(this.months(t,"")),i.push(this.months(t,"")),i.push(this.monthsShort(t,""));for(n.sort(e),s.sort(e),i.sort(e),r=0;r<12;r++)n[r]=M(n[r]),s[r]=M(s[r]);for(r=0;r<24;r++)i[r]=M(i[r]);this._monthsRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+n.join("|")+")","i")}function Ae(e){return he(e)?366:365}s("Y",0,0,function(){var e=this.year();return e<=9999?r(e,4):"+"+e}),s(0,["YY",2],0,function(){return this.year()%100}),s(0,["YYYY",4],0,"year"),s(0,["YYYYY",5],0,"year"),s(0,["YYYYYY",6,!0],0,"year"),t("year","y"),n("year",1),v("Y",De),v("YY",p,w),v("YYYY",ke,_e),v("YYYYY",ve,ye),v("YYYYYY",ve,ye),D(["YYYYY","YYYYYY"],Y),D("YYYY",function(e,t){t[Y]=2===e.length?f.parseTwoDigitYear(e):g(e)}),D("YY",function(e,t){t[Y]=f.parseTwoDigitYear(e)}),D("Y",function(e,t){t[Y]=parseInt(e,10)}),f.parseTwoDigitYear=function(e){return g(e)+(68<g(e)?1900:2e3)};var Ie=de("FullYear",!0);function je(e,t,n,s,i,r,a){var o;return e<100&&0<=e?(o=new Date(e+400,t,n,s,i,r,a),isFinite(o.getFullYear())&&o.setFullYear(e)):o=new Date(e,t,n,s,i,r,a),o}function Ze(e){var t;return e<100&&0<=e?((t=Array.prototype.slice.call(arguments))[0]=e+400,t=new Date(Date.UTC.apply(null,t)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function ze(e,t,n){n=7+t-n;return n-(7+Ze(e,0,n).getUTCDay()-t)%7-1}function $e(e,t,n,s,i){var r,t=1+7*(t-1)+(7+n-s)%7+ze(e,s,i),n=t<=0?Ae(r=e-1)+t:t>Ae(e)?(r=e+1,t-Ae(e)):(r=e,t);return{year:r,dayOfYear:n}}function qe(e,t,n){var s,i,r=ze(e.year(),t,n),r=Math.floor((e.dayOfYear()-r-1)/7)+1;return r<1?s=r+P(i=e.year()-1,t,n):r>P(e.year(),t,n)?(s=r-P(e.year(),t,n),i=e.year()+1):(i=e.year(),s=r),{week:s,year:i}}function P(e,t,n){var s=ze(e,t,n),t=ze(e+1,t,n);return(Ae(e)-s+t)/7}s("w",["ww",2],"wo","week"),s("W",["WW",2],"Wo","isoWeek"),t("week","w"),t("isoWeek","W"),n("week",5),n("isoWeek",5),v("w",p),v("ww",p,w),v("W",p),v("WW",p,w),Te(["w","ww","W","WW"],function(e,t,n,s){t[s.substr(0,1)]=g(e)});function Be(e,t){return e.slice(t,7).concat(e.slice(0,t))}s("d",0,"do","day"),s("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),s("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),s("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),s("e",0,0,"weekday"),s("E",0,0,"isoWeekday"),t("day","d"),t("weekday","e"),t("isoWeekday","E"),n("day",11),n("weekday",11),n("isoWeekday",11),v("d",p),v("e",p),v("E",p),v("dd",function(e,t){return t.weekdaysMinRegex(e)}),v("ddd",function(e,t){return t.weekdaysShortRegex(e)}),v("dddd",function(e,t){return t.weekdaysRegex(e)}),Te(["dd","ddd","dddd"],function(e,t,n,s){s=n._locale.weekdaysParse(e,s,n._strict);null!=s?t.d=s:m(n).invalidWeekday=e}),Te(["d","e","E"],function(e,t,n,s){t[s]=g(e)});var Je="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Qe="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Xe="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Ke=k,et=k,tt=k;function nt(){function e(e,t){return t.length-e.length}for(var t,n,s,i=[],r=[],a=[],o=[],u=0;u<7;u++)s=l([2e3,1]).day(u),t=M(this.weekdaysMin(s,"")),n=M(this.weekdaysShort(s,"")),s=M(this.weekdays(s,"")),i.push(t),r.push(n),a.push(s),o.push(t),o.push(n),o.push(s);i.sort(e),r.sort(e),a.sort(e),o.sort(e),this._weekdaysRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+r.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+i.join("|")+")","i")}function st(){return this.hours()%12||12}function it(e,t){s(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function rt(e,t){return t._meridiemParse}s("H",["HH",2],0,"hour"),s("h",["hh",2],0,st),s("k",["kk",2],0,function(){return this.hours()||24}),s("hmm",0,0,function(){return""+st.apply(this)+r(this.minutes(),2)}),s("hmmss",0,0,function(){return""+st.apply(this)+r(this.minutes(),2)+r(this.seconds(),2)}),s("Hmm",0,0,function(){return""+this.hours()+r(this.minutes(),2)}),s("Hmmss",0,0,function(){return""+this.hours()+r(this.minutes(),2)+r(this.seconds(),2)}),it("a",!0),it("A",!1),t("hour","h"),n("hour",13),v("a",rt),v("A",rt),v("H",p),v("h",p),v("k",p),v("HH",p,w),v("hh",p,w),v("kk",p,w),v("hmm",ge),v("hmmss",we),v("Hmm",ge),v("Hmmss",we),D(["H","HH"],x),D(["k","kk"],function(e,t,n){e=g(e);t[x]=24===e?0:e}),D(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),D(["h","hh"],function(e,t,n){t[x]=g(e),m(n).bigHour=!0}),D("hmm",function(e,t,n){var s=e.length-2;t[x]=g(e.substr(0,s)),t[T]=g(e.substr(s)),m(n).bigHour=!0}),D("hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[x]=g(e.substr(0,s)),t[T]=g(e.substr(s,2)),t[N]=g(e.substr(i)),m(n).bigHour=!0}),D("Hmm",function(e,t,n){var s=e.length-2;t[x]=g(e.substr(0,s)),t[T]=g(e.substr(s))}),D("Hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[x]=g(e.substr(0,s)),t[T]=g(e.substr(s,2)),t[N]=g(e.substr(i))});k=de("Hours",!0);var at,ot={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Ce,monthsShort:Ue,week:{dow:0,doy:6},weekdays:Je,weekdaysMin:Xe,weekdaysShort:Qe,meridiemParse:/[ap]\.?m?\.?/i},R={},ut={};function lt(e){return e&&e.toLowerCase().replace("_","-")}function ht(e){for(var t,n,s,i,r=0;r<e.length;){for(t=(i=lt(e[r]).split("-")).length,n=(n=lt(e[r+1]))?n.split("-"):null;0<t;){if(s=dt(i.slice(0,t).join("-")))return s;if(n&&n.length>=t&&function(e,t){for(var n=Math.min(e.length,t.length),s=0;s<n;s+=1)if(e[s]!==t[s])return s;return n}(i,n)>=t-1)break;t--}r++}return at}function dt(t){var e;if(void 0===R[t]&&"undefined"!=typeof module&&module&&module.exports&&null!=t.match("^[^/\\\\]*$"))try{e=at._abbr,require("./locale/"+t),ct(e)}catch(e){R[t]=null}return R[t]}function ct(e,t){return e&&((t=o(t)?mt(e):ft(e,t))?at=t:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),at._abbr}function ft(e,t){if(null===t)return delete R[e],null;var n,s=ot;if(t.abbr=e,null!=R[e])Q("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),s=R[e]._config;else if(null!=t.parentLocale)if(null!=R[t.parentLocale])s=R[t.parentLocale]._config;else{if(null==(n=dt(t.parentLocale)))return ut[t.parentLocale]||(ut[t.parentLocale]=[]),ut[t.parentLocale].push({name:e,config:t}),null;s=n._config}return R[e]=new K(X(s,t)),ut[e]&&ut[e].forEach(function(e){ft(e.name,e.config)}),ct(e),R[e]}function mt(e){var t;if(!(e=e&&e._locale&&e._locale._abbr?e._locale._abbr:e))return at;if(!a(e)){if(t=dt(e))return t;e=[e]}return ht(e)}function _t(e){var t=e._a;return t&&-2===m(e).overflow&&(t=t[O]<0||11<t[O]?O:t[b]<1||t[b]>We(t[Y],t[O])?b:t[x]<0||24<t[x]||24===t[x]&&(0!==t[T]||0!==t[N]||0!==t[Ne])?x:t[T]<0||59<t[T]?T:t[N]<0||59<t[N]?N:t[Ne]<0||999<t[Ne]?Ne:-1,m(e)._overflowDayOfYear&&(t<Y||b<t)&&(t=b),m(e)._overflowWeeks&&-1===t&&(t=Pe),m(e)._overflowWeekday&&-1===t&&(t=Re),m(e).overflow=t),e}var yt=/^\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)?)?$/,gt=/^\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)?)?$/,wt=/Z|[+-]\d\d(?::?\d\d)?/,pt=[["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}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],kt=[["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/]],vt=/^\/?Date\((-?\d+)/i,Mt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,Dt={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function St(e){var t,n,s,i,r,a,o=e._i,u=yt.exec(o)||gt.exec(o),o=pt.length,l=kt.length;if(u){for(m(e).iso=!0,t=0,n=o;t<n;t++)if(pt[t][1].exec(u[1])){i=pt[t][0],s=!1!==pt[t][2];break}if(null==i)e._isValid=!1;else{if(u[3]){for(t=0,n=l;t<n;t++)if(kt[t][1].exec(u[3])){r=(u[2]||" ")+kt[t][0];break}if(null==r)return void(e._isValid=!1)}if(s||null==r){if(u[4]){if(!wt.exec(u[4]))return void(e._isValid=!1);a="Z"}e._f=i+(r||"")+(a||""),Tt(e)}else e._isValid=!1}}else e._isValid=!1}function Yt(e,t,n,s,i,r){e=[function(e){e=parseInt(e,10);{if(e<=49)return 2e3+e;if(e<=999)return 1900+e}return e}(e),Ue.indexOf(t),parseInt(n,10),parseInt(s,10),parseInt(i,10)];return r&&e.push(parseInt(r,10)),e}function Ot(e){var t,n,s,i,r=Mt.exec(e._i.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,""));r?(t=Yt(r[4],r[3],r[2],r[5],r[6],r[7]),n=r[1],s=t,i=e,n&&Qe.indexOf(n)!==new Date(s[0],s[1],s[2]).getDay()?(m(i).weekdayMismatch=!0,i._isValid=!1):(e._a=t,e._tzm=(n=r[8],s=r[9],i=r[10],n?Dt[n]:s?0:60*(((n=parseInt(i,10))-(s=n%100))/100)+s),e._d=Ze.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),m(e).rfc2822=!0)):e._isValid=!1}function bt(e,t,n){return null!=e?e:null!=t?t:n}function xt(e){var t,n,s,i,r,a,o,u,l,h,d,c=[];if(!e._d){for(s=e,i=new Date(f.now()),n=s._useUTC?[i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate()]:[i.getFullYear(),i.getMonth(),i.getDate()],e._w&&null==e._a[b]&&null==e._a[O]&&(null!=(i=(s=e)._w).GG||null!=i.W||null!=i.E?(u=1,l=4,r=bt(i.GG,s._a[Y],qe(W(),1,4).year),a=bt(i.W,1),((o=bt(i.E,1))<1||7<o)&&(h=!0)):(u=s._locale._week.dow,l=s._locale._week.doy,d=qe(W(),u,l),r=bt(i.gg,s._a[Y],d.year),a=bt(i.w,d.week),null!=i.d?((o=i.d)<0||6<o)&&(h=!0):null!=i.e?(o=i.e+u,(i.e<0||6<i.e)&&(h=!0)):o=u),a<1||a>P(r,u,l)?m(s)._overflowWeeks=!0:null!=h?m(s)._overflowWeekday=!0:(d=$e(r,a,o,u,l),s._a[Y]=d.year,s._dayOfYear=d.dayOfYear)),null!=e._dayOfYear&&(i=bt(e._a[Y],n[Y]),(e._dayOfYear>Ae(i)||0===e._dayOfYear)&&(m(e)._overflowDayOfYear=!0),h=Ze(i,0,e._dayOfYear),e._a[O]=h.getUTCMonth(),e._a[b]=h.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=c[t]=n[t];for(;t<7;t++)e._a[t]=c[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[x]&&0===e._a[T]&&0===e._a[N]&&0===e._a[Ne]&&(e._nextDay=!0,e._a[x]=0),e._d=(e._useUTC?Ze:je).apply(null,c),r=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[x]=24),e._w&&void 0!==e._w.d&&e._w.d!==r&&(m(e).weekdayMismatch=!0)}}function Tt(e){if(e._f===f.ISO_8601)St(e);else if(e._f===f.RFC_2822)Ot(e);else{e._a=[],m(e).empty=!0;for(var t,n,s,i,r,a=""+e._i,o=a.length,u=0,l=ae(e._f,e._locale).match(te)||[],h=l.length,d=0;d<h;d++)n=l[d],(t=(a.match(Oe(n,e))||[])[0])&&(0<(s=a.substr(0,a.indexOf(t))).length&&m(e).unusedInput.push(s),a=a.slice(a.indexOf(t)+t.length),u+=t.length),ie[n]?(t?m(e).empty=!1:m(e).unusedTokens.push(n),s=n,r=e,null!=(i=t)&&c(xe,s)&&xe[s](i,r._a,r,s)):e._strict&&!t&&m(e).unusedTokens.push(n);m(e).charsLeftOver=o-u,0<a.length&&m(e).unusedInput.push(a),e._a[x]<=12&&!0===m(e).bigHour&&0<e._a[x]&&(m(e).bigHour=void 0),m(e).parsedDateParts=e._a.slice(0),m(e).meridiem=e._meridiem,e._a[x]=function(e,t,n){if(null==n)return t;return null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?((e=e.isPM(n))&&t<12&&(t+=12),t=e||12!==t?t:0):t}(e._locale,e._a[x],e._meridiem),null!==(o=m(e).era)&&(e._a[Y]=e._locale.erasConvertYear(o,e._a[Y])),xt(e),_t(e)}}function Nt(e){var t,n,s,i=e._i,r=e._f;if(e._locale=e._locale||mt(e._l),null===i||void 0===r&&""===i)return I({nullInput:!0});if("string"==typeof i&&(e._i=i=e._locale.preparse(i)),h(i))return new q(_t(i));if(V(i))e._d=i;else if(a(r))!function(e){var t,n,s,i,r,a,o=!1,u=e._f.length;if(0===u)return m(e).invalidFormat=!0,e._d=new Date(NaN);for(i=0;i<u;i++)r=0,a=!1,t=$({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],Tt(t),A(t)&&(a=!0),r=(r+=m(t).charsLeftOver)+10*m(t).unusedTokens.length,m(t).score=r,o?r<s&&(s=r,n=t):(null==s||r<s||a)&&(s=r,n=t,a&&(o=!0));E(e,n||t)}(e);else if(r)Tt(e);else if(o(r=(i=e)._i))i._d=new Date(f.now());else V(r)?i._d=new Date(r.valueOf()):"string"==typeof r?(n=i,null!==(t=vt.exec(n._i))?n._d=new Date(+t[1]):(St(n),!1===n._isValid&&(delete n._isValid,Ot(n),!1===n._isValid&&(delete n._isValid,n._strict?n._isValid=!1:f.createFromInputFallback(n))))):a(r)?(i._a=G(r.slice(0),function(e){return parseInt(e,10)}),xt(i)):F(r)?(t=i)._d||(s=void 0===(n=ue(t._i)).day?n.date:n.day,t._a=G([n.year,n.month,s,n.hour,n.minute,n.second,n.millisecond],function(e){return e&&parseInt(e,10)}),xt(t)):u(r)?i._d=new Date(r):f.createFromInputFallback(i);return A(e)||(e._d=null),e}function Pt(e,t,n,s,i){var r={};return!0!==t&&!1!==t||(s=t,t=void 0),!0!==n&&!1!==n||(s=n,n=void 0),(F(e)&&L(e)||a(e)&&0===e.length)&&(e=void 0),r._isAMomentObject=!0,r._useUTC=r._isUTC=i,r._l=n,r._i=e,r._f=t,r._strict=s,(i=new q(_t(Nt(i=r))))._nextDay&&(i.add(1,"d"),i._nextDay=void 0),i}function W(e,t,n,s){return Pt(e,t,n,s,!1)}f.createFromInputFallback=e("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),f.ISO_8601=function(){},f.RFC_2822=function(){};ge=e("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=W.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:I()}),we=e("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=W.apply(null,arguments);return this.isValid()&&e.isValid()?this<e?this:e:I()});function Rt(e,t){var n,s;if(!(t=1===t.length&&a(t[0])?t[0]:t).length)return W();for(n=t[0],s=1;s<t.length;++s)t[s].isValid()&&!t[s][e](n)||(n=t[s]);return n}var Wt=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Ct(e){var e=ue(e),t=e.year||0,n=e.quarter||0,s=e.month||0,i=e.week||e.isoWeek||0,r=e.day||0,a=e.hour||0,o=e.minute||0,u=e.second||0,l=e.millisecond||0;this._isValid=function(e){var t,n,s=!1,i=Wt.length;for(t in e)if(c(e,t)&&(-1===S.call(Wt,t)||null!=e[t]&&isNaN(e[t])))return!1;for(n=0;n<i;++n)if(e[Wt[n]]){if(s)return!1;parseFloat(e[Wt[n]])!==g(e[Wt[n]])&&(s=!0)}return!0}(e),this._milliseconds=+l+1e3*u+6e4*o+1e3*a*60*60,this._days=+r+7*i,this._months=+s+3*n+12*t,this._data={},this._locale=mt(),this._bubble()}function Ut(e){return e instanceof Ct}function Ht(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ft(e,n){s(e,0,0,function(){var e=this.utcOffset(),t="+";return e<0&&(e=-e,t="-"),t+r(~~(e/60),2)+n+r(~~e%60,2)})}Ft("Z",":"),Ft("ZZ",""),v("Z",Ye),v("ZZ",Ye),D(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=Vt(Ye,e)});var Lt=/([\+\-]|\d\d)/gi;function Vt(e,t){var t=(t||"").match(e);return null===t?null:0===(t=60*(e=((t[t.length-1]||[])+"").match(Lt)||["-",0,0])[1]+g(e[2]))?0:"+"===e[0]?t:-t}function Gt(e,t){var n;return t._isUTC?(t=t.clone(),n=(h(e)||V(e)?e:W(e)).valueOf()-t.valueOf(),t._d.setTime(t._d.valueOf()+n),f.updateOffset(t,!1),t):W(e).local()}function Et(e){return-Math.round(e._d.getTimezoneOffset())}function At(){return!!this.isValid()&&(this._isUTC&&0===this._offset)}f.updateOffset=function(){};var It=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,jt=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function C(e,t){var n,s=e,i=null;return Ut(e)?s={ms:e._milliseconds,d:e._days,M:e._months}:u(e)||!isNaN(+e)?(s={},t?s[t]=+e:s.milliseconds=+e):(i=It.exec(e))?(n="-"===i[1]?-1:1,s={y:0,d:g(i[b])*n,h:g(i[x])*n,m:g(i[T])*n,s:g(i[N])*n,ms:g(Ht(1e3*i[Ne]))*n}):(i=jt.exec(e))?(n="-"===i[1]?-1:1,s={y:Zt(i[2],n),M:Zt(i[3],n),w:Zt(i[4],n),d:Zt(i[5],n),h:Zt(i[6],n),m:Zt(i[7],n),s:Zt(i[8],n)}):null==s?s={}:"object"==typeof s&&("from"in s||"to"in s)&&(t=function(e,t){var n;if(!e.isValid()||!t.isValid())return{milliseconds:0,months:0};t=Gt(t,e),e.isBefore(t)?n=zt(e,t):((n=zt(t,e)).milliseconds=-n.milliseconds,n.months=-n.months);return n}(W(s.from),W(s.to)),(s={}).ms=t.milliseconds,s.M=t.months),i=new Ct(s),Ut(e)&&c(e,"_locale")&&(i._locale=e._locale),Ut(e)&&c(e,"_isValid")&&(i._isValid=e._isValid),i}function Zt(e,t){e=e&&parseFloat(e.replace(",","."));return(isNaN(e)?0:e)*t}function zt(e,t){var n={};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function $t(s,i){return function(e,t){var n;return null===t||isNaN(+t)||(Q(i,"moment()."+i+"(period, number) is deprecated. Please use moment()."+i+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),n=e,e=t,t=n),qt(this,C(e,t),s),this}}function qt(e,t,n,s){var i=t._milliseconds,r=Ht(t._days),t=Ht(t._months);e.isValid()&&(s=null==s||s,t&&Ve(e,ce(e,"Month")+t*n),r&&fe(e,"Date",ce(e,"Date")+r*n),i&&e._d.setTime(e._d.valueOf()+i*n),s&&f.updateOffset(e,r||t))}C.fn=Ct.prototype,C.invalid=function(){return C(NaN)};Ce=$t(1,"add"),Je=$t(-1,"subtract");function Bt(e){return"string"==typeof e||e instanceof String}function Jt(e){return h(e)||V(e)||Bt(e)||u(e)||function(t){var e=a(t),n=!1;e&&(n=0===t.filter(function(e){return!u(e)&&Bt(t)}).length);return e&&n}(e)||function(e){var t,n,s=F(e)&&!L(e),i=!1,r=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],a=r.length;for(t=0;t<a;t+=1)n=r[t],i=i||c(e,n);return s&&i}(e)||null==e}function Qt(e,t){if(e.date()<t.date())return-Qt(t,e);var n=12*(t.year()-e.year())+(t.month()-e.month()),s=e.clone().add(n,"months"),t=t-s<0?(t-s)/(s-e.clone().add(n-1,"months")):(t-s)/(e.clone().add(1+n,"months")-s);return-(n+t)||0}function Xt(e){return void 0===e?this._locale._abbr:(null!=(e=mt(e))&&(this._locale=e),this)}f.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",f.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";Xe=e("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});function Kt(){return this._locale}var en=126227808e5;function tn(e,t){return(e%t+t)%t}function nn(e,t,n){return e<100&&0<=e?new Date(e+400,t,n)-en:new Date(e,t,n).valueOf()}function sn(e,t,n){return e<100&&0<=e?Date.UTC(e+400,t,n)-en:Date.UTC(e,t,n)}function rn(e,t){return t.erasAbbrRegex(e)}function an(){for(var e=[],t=[],n=[],s=[],i=this.eras(),r=0,a=i.length;r<a;++r)t.push(M(i[r].name)),e.push(M(i[r].abbr)),n.push(M(i[r].narrow)),s.push(M(i[r].name)),s.push(M(i[r].abbr)),s.push(M(i[r].narrow));this._erasRegex=new RegExp("^("+s.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+t.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+e.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+n.join("|")+")","i")}function on(e,t){s(0,[e,e.length],0,t)}function un(e,t,n,s,i){var r;return null==e?qe(this,s,i).year:(r=P(e,s,i),function(e,t,n,s,i){e=$e(e,t,n,s,i),t=Ze(e.year,0,e.dayOfYear);return this.year(t.getUTCFullYear()),this.month(t.getUTCMonth()),this.date(t.getUTCDate()),this}.call(this,e,t=r<t?r:t,n,s,i))}s("N",0,0,"eraAbbr"),s("NN",0,0,"eraAbbr"),s("NNN",0,0,"eraAbbr"),s("NNNN",0,0,"eraName"),s("NNNNN",0,0,"eraNarrow"),s("y",["y",1],"yo","eraYear"),s("y",["yy",2],0,"eraYear"),s("y",["yyy",3],0,"eraYear"),s("y",["yyyy",4],0,"eraYear"),v("N",rn),v("NN",rn),v("NNN",rn),v("NNNN",function(e,t){return t.erasNameRegex(e)}),v("NNNNN",function(e,t){return t.erasNarrowRegex(e)}),D(["N","NN","NNN","NNNN","NNNNN"],function(e,t,n,s){s=n._locale.erasParse(e,s,n._strict);s?m(n).era=s:m(n).invalidEra=e}),v("y",Me),v("yy",Me),v("yyy",Me),v("yyyy",Me),v("yo",function(e,t){return t._eraYearOrdinalRegex||Me}),D(["y","yy","yyy","yyyy"],Y),D(["yo"],function(e,t,n,s){var i;n._locale._eraYearOrdinalRegex&&(i=e.match(n._locale._eraYearOrdinalRegex)),n._locale.eraYearOrdinalParse?t[Y]=n._locale.eraYearOrdinalParse(e,i):t[Y]=parseInt(e,10)}),s(0,["gg",2],0,function(){return this.weekYear()%100}),s(0,["GG",2],0,function(){return this.isoWeekYear()%100}),on("gggg","weekYear"),on("ggggg","weekYear"),on("GGGG","isoWeekYear"),on("GGGGG","isoWeekYear"),t("weekYear","gg"),t("isoWeekYear","GG"),n("weekYear",1),n("isoWeekYear",1),v("G",De),v("g",De),v("GG",p,w),v("gg",p,w),v("GGGG",ke,_e),v("gggg",ke,_e),v("GGGGG",ve,ye),v("ggggg",ve,ye),Te(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,s){t[s.substr(0,2)]=g(e)}),Te(["gg","GG"],function(e,t,n,s){t[s]=f.parseTwoDigitYear(e)}),s("Q",0,"Qo","quarter"),t("quarter","Q"),n("quarter",7),v("Q",i),D("Q",function(e,t){t[O]=3*(g(e)-1)}),s("D",["DD",2],"Do","date"),t("date","D"),n("date",9),v("D",p),v("DD",p,w),v("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),D(["D","DD"],b),D("Do",function(e,t){t[b]=g(e.match(p)[0])});ke=de("Date",!0);s("DDD",["DDDD",3],"DDDo","dayOfYear"),t("dayOfYear","DDD"),n("dayOfYear",4),v("DDD",pe),v("DDDD",me),D(["DDD","DDDD"],function(e,t,n){n._dayOfYear=g(e)}),s("m",["mm",2],0,"minute"),t("minute","m"),n("minute",14),v("m",p),v("mm",p,w),D(["m","mm"],T);var ln,_e=de("Minutes",!1),ve=(s("s",["ss",2],0,"second"),t("second","s"),n("second",15),v("s",p),v("ss",p,w),D(["s","ss"],N),de("Seconds",!1));for(s("S",0,0,function(){return~~(this.millisecond()/100)}),s(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),s(0,["SSS",3],0,"millisecond"),s(0,["SSSS",4],0,function(){return 10*this.millisecond()}),s(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),s(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),s(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),s(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),s(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),t("millisecond","ms"),n("millisecond",16),v("S",pe,i),v("SS",pe,w),v("SSS",pe,me),ln="SSSS";ln.length<=9;ln+="S")v(ln,Me);function hn(e,t){t[Ne]=g(1e3*("0."+e))}for(ln="S";ln.length<=9;ln+="S")D(ln,hn);ye=de("Milliseconds",!1),s("z",0,0,"zoneAbbr"),s("zz",0,0,"zoneName");i=q.prototype;function dn(e){return e}i.add=Ce,i.calendar=function(e,t){1===arguments.length&&(arguments[0]?Jt(arguments[0])?(e=arguments[0],t=void 0):function(e){for(var t=F(e)&&!L(e),n=!1,s=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"],i=0;i<s.length;i+=1)n=n||c(e,s[i]);return t&&n}(arguments[0])&&(t=arguments[0],e=void 0):t=e=void 0);var e=e||W(),n=Gt(e,this).startOf("day"),n=f.calendarFormat(this,n)||"sameElse",t=t&&(d(t[n])?t[n].call(this,e):t[n]);return this.format(t||this.localeData().calendar(n,this,W(e)))},i.clone=function(){return new q(this)},i.diff=function(e,t,n){var s,i,r;if(!this.isValid())return NaN;if(!(s=Gt(e,this)).isValid())return NaN;switch(i=6e4*(s.utcOffset()-this.utcOffset()),t=_(t)){case"year":r=Qt(this,s)/12;break;case"month":r=Qt(this,s);break;case"quarter":r=Qt(this,s)/3;break;case"second":r=(this-s)/1e3;break;case"minute":r=(this-s)/6e4;break;case"hour":r=(this-s)/36e5;break;case"day":r=(this-s-i)/864e5;break;case"week":r=(this-s-i)/6048e5;break;default:r=this-s}return n?r:y(r)},i.endOf=function(e){var t,n;if(void 0===(e=_(e))||"millisecond"===e||!this.isValid())return this;switch(n=this._isUTC?sn:nn,e){case"year":t=n(this.year()+1,0,1)-1;break;case"quarter":t=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=n(this.year(),this.month()+1,1)-1;break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=n(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=36e5-tn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5)-1;break;case"minute":t=this._d.valueOf(),t+=6e4-tn(t,6e4)-1;break;case"second":t=this._d.valueOf(),t+=1e3-tn(t,1e3)-1;break}return this._d.setTime(t),f.updateOffset(this,!0),this},i.format=function(e){return e=e||(this.isUtc()?f.defaultFormatUtc:f.defaultFormat),e=re(this,e),this.localeData().postformat(e)},i.from=function(e,t){return this.isValid()&&(h(e)&&e.isValid()||W(e).isValid())?C({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},i.fromNow=function(e){return this.from(W(),e)},i.to=function(e,t){return this.isValid()&&(h(e)&&e.isValid()||W(e).isValid())?C({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},i.toNow=function(e){return this.to(W(),e)},i.get=function(e){return d(this[e=_(e)])?this[e]():this},i.invalidAt=function(){return m(this).overflow},i.isAfter=function(e,t){return e=h(e)?e:W(e),!(!this.isValid()||!e.isValid())&&("millisecond"===(t=_(t)||"millisecond")?this.valueOf()>e.valueOf():e.valueOf()<this.clone().startOf(t).valueOf())},i.isBefore=function(e,t){return e=h(e)?e:W(e),!(!this.isValid()||!e.isValid())&&("millisecond"===(t=_(t)||"millisecond")?this.valueOf()<e.valueOf():this.clone().endOf(t).valueOf()<e.valueOf())},i.isBetween=function(e,t,n,s){return e=h(e)?e:W(e),t=h(t)?t:W(t),!!(this.isValid()&&e.isValid()&&t.isValid())&&(("("===(s=s||"()")[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===s[1]?this.isBefore(t,n):!this.isAfter(t,n)))},i.isSame=function(e,t){var e=h(e)?e:W(e);return!(!this.isValid()||!e.isValid())&&("millisecond"===(t=_(t)||"millisecond")?this.valueOf()===e.valueOf():(e=e.valueOf(),this.clone().startOf(t).valueOf()<=e&&e<=this.clone().endOf(t).valueOf()))},i.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},i.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},i.isValid=function(){return A(this)},i.lang=Xe,i.locale=Xt,i.localeData=Kt,i.max=we,i.min=ge,i.parsingFlags=function(){return E({},m(this))},i.set=function(e,t){if("object"==typeof e)for(var n=function(e){var t,n=[];for(t in e)c(e,t)&&n.push({unit:t,priority:le[t]});return n.sort(function(e,t){return e.priority-t.priority}),n}(e=ue(e)),s=n.length,i=0;i<s;i++)this[n[i].unit](e[n[i].unit]);else if(d(this[e=_(e)]))return this[e](t);return this},i.startOf=function(e){var t,n;if(void 0===(e=_(e))||"millisecond"===e||!this.isValid())return this;switch(n=this._isUTC?sn:nn,e){case"year":t=n(this.year(),0,1);break;case"quarter":t=n(this.year(),this.month()-this.month()%3,1);break;case"month":t=n(this.year(),this.month(),1);break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=n(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=tn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5);break;case"minute":t=this._d.valueOf(),t-=tn(t,6e4);break;case"second":t=this._d.valueOf(),t-=tn(t,1e3);break}return this._d.setTime(t),f.updateOffset(this,!0),this},i.subtract=Je,i.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},i.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},i.toDate=function(){return new Date(this.valueOf())},i.toISOString=function(e){if(!this.isValid())return null;var t=(e=!0!==e)?this.clone().utc():this;return t.year()<0||9999<t.year()?re(t,e?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):d(Date.prototype.toISOString)?e?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",re(t,"Z")):re(t,e?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},i.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e,t="moment",n="";return this.isLocal()||(t=0===this.utcOffset()?"moment.utc":"moment.parseZone",n="Z"),t="["+t+'("]',e=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",this.format(t+e+"-MM-DD[T]HH:mm:ss.SSS"+(n+'[")]'))},"undefined"!=typeof Symbol&&null!=Symbol.for&&(i[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),i.toJSON=function(){return this.isValid()?this.toISOString():null},i.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},i.unix=function(){return Math.floor(this.valueOf()/1e3)},i.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},i.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},i.eraName=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].name;if(t[n].until<=e&&e<=t[n].since)return t[n].name}return""},i.eraNarrow=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].narrow;if(t[n].until<=e&&e<=t[n].since)return t[n].narrow}return""},i.eraAbbr=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].abbr;if(t[n].until<=e&&e<=t[n].since)return t[n].abbr}return""},i.eraYear=function(){for(var e,t,n=this.localeData().eras(),s=0,i=n.length;s<i;++s)if(e=n[s].since<=n[s].until?1:-1,t=this.clone().startOf("day").valueOf(),n[s].since<=t&&t<=n[s].until||n[s].until<=t&&t<=n[s].since)return(this.year()-f(n[s].since).year())*e+n[s].offset;return this.year()},i.year=Ie,i.isLeapYear=function(){return he(this.year())},i.weekYear=function(e){return un.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)},i.isoWeekYear=function(e){return un.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},i.quarter=i.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},i.month=Ge,i.daysInMonth=function(){return We(this.year(),this.month())},i.week=i.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},i.isoWeek=i.isoWeeks=function(e){var t=qe(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},i.weeksInYear=function(){var e=this.localeData()._week;return P(this.year(),e.dow,e.doy)},i.weeksInWeekYear=function(){var e=this.localeData()._week;return P(this.weekYear(),e.dow,e.doy)},i.isoWeeksInYear=function(){return P(this.year(),1,4)},i.isoWeeksInISOWeekYear=function(){return P(this.isoWeekYear(),1,4)},i.date=ke,i.day=i.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t,n,s=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(t=e,n=this.localeData(),e="string"!=typeof t?t:isNaN(t)?"number"==typeof(t=n.weekdaysParse(t))?t:null:parseInt(t,10),this.add(e-s,"d")):s},i.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},i.isoWeekday=function(e){return this.isValid()?null!=e?(t=e,n=this.localeData(),n="string"==typeof t?n.weekdaysParse(t)%7||7:isNaN(t)?null:t,this.day(this.day()%7?n:n-7)):this.day()||7:null!=e?this:NaN;var t,n},i.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},i.hour=i.hours=k,i.minute=i.minutes=_e,i.second=i.seconds=ve,i.millisecond=i.milliseconds=ye,i.utcOffset=function(e,t,n){var s,i=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null==e)return this._isUTC?i:Et(this);if("string"==typeof e){if(null===(e=Vt(Ye,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(s=Et(this)),this._offset=e,this._isUTC=!0,null!=s&&this.add(s,"m"),i!==e&&(!t||this._changeInProgress?qt(this,C(e-i,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,f.updateOffset(this,!0),this._changeInProgress=null)),this},i.utc=function(e){return this.utcOffset(0,e)},i.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Et(this),"m")),this},i.parseZone=function(){var e;return null!=this._tzm?this.utcOffset(this._tzm,!1,!0):"string"==typeof this._i&&(null!=(e=Vt(Se,this._i))?this.utcOffset(e):this.utcOffset(0,!0)),this},i.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?W(e).utcOffset():0,(this.utcOffset()-e)%60==0)},i.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},i.isLocal=function(){return!!this.isValid()&&!this._isUTC},i.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},i.isUtc=At,i.isUTC=At,i.zoneAbbr=function(){return this._isUTC?"UTC":""},i.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},i.dates=e("dates accessor is deprecated. Use date instead.",ke),i.months=e("months accessor is deprecated. Use month instead",Ge),i.years=e("years accessor is deprecated. Use year instead",Ie),i.zone=e("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?(this.utcOffset(e="string"!=typeof e?-e:e,t),this):-this.utcOffset()}),i.isDSTShifted=e("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){if(!o(this._isDSTShifted))return this._isDSTShifted;var e,t={};return $(t,this),(t=Nt(t))._a?(e=(t._isUTC?l:W)(t._a),this._isDSTShifted=this.isValid()&&0<function(e,t,n){for(var s=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),r=0,a=0;a<s;a++)(n&&e[a]!==t[a]||!n&&g(e[a])!==g(t[a]))&&r++;return r+i}(t._a,e.toArray())):this._isDSTShifted=!1,this._isDSTShifted});w=K.prototype;function cn(e,t,n,s){var i=mt(),s=l().set(s,t);return i[n](s,e)}function fn(e,t,n){if(u(e)&&(t=e,e=void 0),e=e||"",null!=t)return cn(e,t,n,"month");for(var s=[],i=0;i<12;i++)s[i]=cn(e,i,n,"month");return s}function mn(e,t,n,s){t=("boolean"==typeof e?u(t)&&(n=t,t=void 0):(t=e,e=!1,u(n=t)&&(n=t,t=void 0)),t||"");var i,r=mt(),a=e?r._week.dow:0,o=[];if(null!=n)return cn(t,(n+a)%7,s,"day");for(i=0;i<7;i++)o[i]=cn(t,(i+a)%7,s,"day");return o}w.calendar=function(e,t,n){return d(e=this._calendar[e]||this._calendar.sameElse)?e.call(t,n):e},w.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.match(te).map(function(e){return"MMMM"===e||"MM"===e||"DD"===e||"dddd"===e?e.slice(1):e}).join(""),this._longDateFormat[e])},w.invalidDate=function(){return this._invalidDate},w.ordinal=function(e){return this._ordinal.replace("%d",e)},w.preparse=dn,w.postformat=dn,w.relativeTime=function(e,t,n,s){var i=this._relativeTime[n];return d(i)?i(e,t,n,s):i.replace(/%d/i,e)},w.pastFuture=function(e,t){return d(e=this._relativeTime[0<e?"future":"past"])?e(t):e.replace(/%s/i,t)},w.set=function(e){var t,n;for(n in e)c(e,n)&&(d(t=e[n])?this[n]=t:this["_"+n]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},w.eras=function(e,t){for(var n,s=this._eras||mt("en")._eras,i=0,r=s.length;i<r;++i){switch(typeof s[i].since){case"string":n=f(s[i].since).startOf("day"),s[i].since=n.valueOf();break}switch(typeof s[i].until){case"undefined":s[i].until=1/0;break;case"string":n=f(s[i].until).startOf("day").valueOf(),s[i].until=n.valueOf();break}}return s},w.erasParse=function(e,t,n){var s,i,r,a,o,u=this.eras();for(e=e.toUpperCase(),s=0,i=u.length;s<i;++s)if(r=u[s].name.toUpperCase(),a=u[s].abbr.toUpperCase(),o=u[s].narrow.toUpperCase(),n)switch(t){case"N":case"NN":case"NNN":if(a===e)return u[s];break;case"NNNN":if(r===e)return u[s];break;case"NNNNN":if(o===e)return u[s];break}else if(0<=[r,a,o].indexOf(e))return u[s]},w.erasConvertYear=function(e,t){var n=e.since<=e.until?1:-1;return void 0===t?f(e.since).year():f(e.since).year()+(t-e.offset)*n},w.erasAbbrRegex=function(e){return c(this,"_erasAbbrRegex")||an.call(this),e?this._erasAbbrRegex:this._erasRegex},w.erasNameRegex=function(e){return c(this,"_erasNameRegex")||an.call(this),e?this._erasNameRegex:this._erasRegex},w.erasNarrowRegex=function(e){return c(this,"_erasNarrowRegex")||an.call(this),e?this._erasNarrowRegex:this._erasRegex},w.months=function(e,t){return e?(a(this._months)?this._months:this._months[(this._months.isFormat||He).test(t)?"format":"standalone"])[e.month()]:a(this._months)?this._months:this._months.standalone},w.monthsShort=function(e,t){return e?(a(this._monthsShort)?this._monthsShort:this._monthsShort[He.test(t)?"format":"standalone"])[e.month()]:a(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},w.monthsParse=function(e,t,n){var s,i;if(this._monthsParseExact)return function(e,t,n){var s,i,r,e=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)r=l([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(r,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(r,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=S.call(this._shortMonthsParse,e))?i:null:-1!==(i=S.call(this._longMonthsParse,e))?i:null:"MMM"===t?-1!==(i=S.call(this._shortMonthsParse,e))||-1!==(i=S.call(this._longMonthsParse,e))?i:null:-1!==(i=S.call(this._longMonthsParse,e))||-1!==(i=S.call(this._shortMonthsParse,e))?i:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(i=l([2e3,s]),n&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[s]||(i="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[s]=new RegExp(i.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[s].test(e))return s;if(n&&"MMM"===t&&this._shortMonthsParse[s].test(e))return s;if(!n&&this._monthsParse[s].test(e))return s}},w.monthsRegex=function(e){return this._monthsParseExact?(c(this,"_monthsRegex")||Ee.call(this),e?this._monthsStrictRegex:this._monthsRegex):(c(this,"_monthsRegex")||(this._monthsRegex=Le),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},w.monthsShortRegex=function(e){return this._monthsParseExact?(c(this,"_monthsRegex")||Ee.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(c(this,"_monthsShortRegex")||(this._monthsShortRegex=Fe),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},w.week=function(e){return qe(e,this._week.dow,this._week.doy).week},w.firstDayOfYear=function(){return this._week.doy},w.firstDayOfWeek=function(){return this._week.dow},w.weekdays=function(e,t){return t=a(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(t)?"format":"standalone"],!0===e?Be(t,this._week.dow):e?t[e.day()]:t},w.weekdaysMin=function(e){return!0===e?Be(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin},w.weekdaysShort=function(e){return!0===e?Be(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort},w.weekdaysParse=function(e,t,n){var s,i;if(this._weekdaysParseExact)return function(e,t,n){var s,i,r,e=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)r=l([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(r,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(r,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(r,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=S.call(this._weekdaysParse,e))?i:null:"ddd"===t?-1!==(i=S.call(this._shortWeekdaysParse,e))?i:null:-1!==(i=S.call(this._minWeekdaysParse,e))?i:null:"dddd"===t?-1!==(i=S.call(this._weekdaysParse,e))||-1!==(i=S.call(this._shortWeekdaysParse,e))||-1!==(i=S.call(this._minWeekdaysParse,e))?i:null:"ddd"===t?-1!==(i=S.call(this._shortWeekdaysParse,e))||-1!==(i=S.call(this._weekdaysParse,e))||-1!==(i=S.call(this._minWeekdaysParse,e))?i:null:-1!==(i=S.call(this._minWeekdaysParse,e))||-1!==(i=S.call(this._weekdaysParse,e))||-1!==(i=S.call(this._shortWeekdaysParse,e))?i:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(i=l([2e3,1]).day(s),n&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(i,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(i,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(i,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[s]||(i="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[s]=new RegExp(i.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[s].test(e))return s;if(n&&"ddd"===t&&this._shortWeekdaysParse[s].test(e))return s;if(n&&"dd"===t&&this._minWeekdaysParse[s].test(e))return s;if(!n&&this._weekdaysParse[s].test(e))return s}},w.weekdaysRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||nt.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(c(this,"_weekdaysRegex")||(this._weekdaysRegex=Ke),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},w.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||nt.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(c(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=et),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},w.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||nt.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(c(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=tt),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},w.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},w.meridiem=function(e,t,n){return 11<e?n?"pm":"PM":n?"am":"AM"},ct("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===g(e%100/10)?"th":1==t?"st":2==t?"nd":3==t?"rd":"th")}}),f.lang=e("moment.lang is deprecated. Use moment.locale instead.",ct),f.langData=e("moment.langData is deprecated. Use moment.localeData instead.",mt);var _n=Math.abs;function yn(e,t,n,s){t=C(t,n);return e._milliseconds+=s*t._milliseconds,e._days+=s*t._days,e._months+=s*t._months,e._bubble()}function gn(e){return e<0?Math.floor(e):Math.ceil(e)}function wn(e){return 4800*e/146097}function pn(e){return 146097*e/4800}function kn(e){return function(){return this.as(e)}}pe=kn("ms"),me=kn("s"),Ce=kn("m"),we=kn("h"),ge=kn("d"),Je=kn("w"),k=kn("M"),_e=kn("Q"),ve=kn("y");function vn(e){return function(){return this.isValid()?this._data[e]:NaN}}var ye=vn("milliseconds"),ke=vn("seconds"),Ie=vn("minutes"),w=vn("hours"),Mn=vn("days"),Dn=vn("months"),Sn=vn("years");var Yn=Math.round,On={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function bn(e,t,n,s){var i=C(e).abs(),r=Yn(i.as("s")),a=Yn(i.as("m")),o=Yn(i.as("h")),u=Yn(i.as("d")),l=Yn(i.as("M")),h=Yn(i.as("w")),i=Yn(i.as("y")),r=(r<=n.ss?["s",r]:r<n.s&&["ss",r])||a<=1&&["m"]||a<n.m&&["mm",a]||o<=1&&["h"]||o<n.h&&["hh",o]||u<=1&&["d"]||u<n.d&&["dd",u];return(r=(r=null!=n.w?r||h<=1&&["w"]||h<n.w&&["ww",h]:r)||l<=1&&["M"]||l<n.M&&["MM",l]||i<=1&&["y"]||["yy",i])[2]=t,r[3]=0<+e,r[4]=s,function(e,t,n,s,i){return i.relativeTime(t||1,!!n,e,s)}.apply(null,r)}var xn=Math.abs;function Tn(e){return(0<e)-(e<0)||+e}function Nn(){if(!this.isValid())return this.localeData().invalidDate();var e,t,n,s,i,r,a,o=xn(this._milliseconds)/1e3,u=xn(this._days),l=xn(this._months),h=this.asSeconds();return h?(e=y(o/60),t=y(e/60),o%=60,e%=60,n=y(l/12),l%=12,s=o?o.toFixed(3).replace(/\.?0+$/,""):"",i=Tn(this._months)!==Tn(h)?"-":"",r=Tn(this._days)!==Tn(h)?"-":"",a=Tn(this._milliseconds)!==Tn(h)?"-":"",(h<0?"-":"")+"P"+(n?i+n+"Y":"")+(l?i+l+"M":"")+(u?r+u+"D":"")+(t||e||o?"T":"")+(t?a+t+"H":"")+(e?a+e+"M":"")+(o?a+s+"S":"")):"P0D"}var U=Ct.prototype;return U.isValid=function(){return this._isValid},U.abs=function(){var e=this._data;return this._milliseconds=_n(this._milliseconds),this._days=_n(this._days),this._months=_n(this._months),e.milliseconds=_n(e.milliseconds),e.seconds=_n(e.seconds),e.minutes=_n(e.minutes),e.hours=_n(e.hours),e.months=_n(e.months),e.years=_n(e.years),this},U.add=function(e,t){return yn(this,e,t,1)},U.subtract=function(e,t){return yn(this,e,t,-1)},U.as=function(e){if(!this.isValid())return NaN;var t,n,s=this._milliseconds;if("month"===(e=_(e))||"quarter"===e||"year"===e)switch(t=this._days+s/864e5,n=this._months+wn(t),e){case"month":return n;case"quarter":return n/3;case"year":return n/12}else switch(t=this._days+Math.round(pn(this._months)),e){case"week":return t/7+s/6048e5;case"day":return t+s/864e5;case"hour":return 24*t+s/36e5;case"minute":return 1440*t+s/6e4;case"second":return 86400*t+s/1e3;case"millisecond":return Math.floor(864e5*t)+s;default:throw new Error("Unknown unit "+e)}},U.asMilliseconds=pe,U.asSeconds=me,U.asMinutes=Ce,U.asHours=we,U.asDays=ge,U.asWeeks=Je,U.asMonths=k,U.asQuarters=_e,U.asYears=ve,U.valueOf=function(){return this.isValid()?this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*g(this._months/12):NaN},U._bubble=function(){var e=this._milliseconds,t=this._days,n=this._months,s=this._data;return 0<=e&&0<=t&&0<=n||e<=0&&t<=0&&n<=0||(e+=864e5*gn(pn(n)+t),n=t=0),s.milliseconds=e%1e3,e=y(e/1e3),s.seconds=e%60,e=y(e/60),s.minutes=e%60,e=y(e/60),s.hours=e%24,t+=y(e/24),n+=e=y(wn(t)),t-=gn(pn(e)),e=y(n/12),n%=12,s.days=t,s.months=n,s.years=e,this},U.clone=function(){return C(this)},U.get=function(e){return e=_(e),this.isValid()?this[e+"s"]():NaN},U.milliseconds=ye,U.seconds=ke,U.minutes=Ie,U.hours=w,U.days=Mn,U.weeks=function(){return y(this.days()/7)},U.months=Dn,U.years=Sn,U.humanize=function(e,t){if(!this.isValid())return this.localeData().invalidDate();var n=!1,s=On;return"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(n=e),"object"==typeof t&&(s=Object.assign({},On,t),null!=t.s&&null==t.ss&&(s.ss=t.s-1)),e=this.localeData(),t=bn(this,!n,s,e),n&&(t=e.pastFuture(+this,t)),e.postformat(t)},U.toISOString=Nn,U.toString=Nn,U.toJSON=Nn,U.locale=Xt,U.localeData=Kt,U.toIsoString=e("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Nn),U.lang=Xe,s("X",0,0,"unix"),s("x",0,0,"valueOf"),v("x",De),v("X",/[+-]?\d+(\.\d{1,3})?/),D("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e))}),D("x",function(e,t,n){n._d=new Date(g(e))}),f.version="2.29.4",H=W,f.fn=i,f.min=function(){return Rt("isBefore",[].slice.call(arguments,0))},f.max=function(){return Rt("isAfter",[].slice.call(arguments,0))},f.now=function(){return Date.now?Date.now():+new Date},f.utc=l,f.unix=function(e){return W(1e3*e)},f.months=function(e,t){return fn(e,t,"months")},f.isDate=V,f.locale=ct,f.invalid=I,f.duration=C,f.isMoment=h,f.weekdays=function(e,t,n){return mn(e,t,n,"weekdays")},f.parseZone=function(){return W.apply(null,arguments).parseZone()},f.localeData=mt,f.isDuration=Ut,f.monthsShort=function(e,t){return fn(e,t,"monthsShort")},f.weekdaysMin=function(e,t,n){return mn(e,t,n,"weekdaysMin")},f.defineLocale=ft,f.updateLocale=function(e,t){var n,s;return null!=t?(s=ot,null!=R[e]&&null!=R[e].parentLocale?R[e].set(X(R[e]._config,t)):(t=X(s=null!=(n=dt(e))?n._config:s,t),null==n&&(t.abbr=e),(s=new K(t)).parentLocale=R[e],R[e]=s),ct(e)):null!=R[e]&&(null!=R[e].parentLocale?(R[e]=R[e].parentLocale,e===ct()&&ct(e)):null!=R[e]&&delete R[e]),R[e]},f.locales=function(){return ee(R)},f.weekdaysShort=function(e,t,n){return mn(e,t,n,"weekdaysShort")},f.normalizeUnits=_,f.relativeTimeRounding=function(e){return void 0===e?Yn:"function"==typeof e&&(Yn=e,!0)},f.relativeTimeThreshold=function(e,t){return void 0!==On[e]&&(void 0===t?On[e]:(On[e]=t,"s"===e&&(On.ss=t-1),!0))},f.calendarFormat=function(e,t){return(e=e.diff(t,"days",!0))<-6?"sameElse":e<-1?"lastWeek":e<0?"lastDay":e<1?"sameDay":e<2?"nextDay":e<7?"nextWeek":"sameElse"},f.prototype=i,f.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},f});

if (settings) {    
    moment.locale(settings.language, {
        months: [
            settings.language == 'nl' ? settings.various.monthsLongJanuary.toLowerCase() : settings.various.monthsLongJanuary,
            settings.language == 'nl' ? settings.various.monthsLongFebruary.toLowerCase() : settings.various.monthsLongFebruary,
            settings.language == 'nl' ? settings.various.monthsLongMarch.toLowerCase() : settings.various.monthsLongMarch,
            settings.language == 'nl' ? settings.various.monthsLongApril.toLowerCase() : settings.various.monthsLongApril,
            settings.language == 'nl' ? settings.various.monthsLongMay.toLowerCase() : settings.various.monthsLongMay,
            settings.language == 'nl' ? settings.various.monthsLongJune.toLowerCase() : settings.various.monthsLongJune,
            settings.language == 'nl' ? settings.various.monthsLongJuly.toLowerCase() : settings.various.monthsLongJuly,
            settings.language == 'nl' ? settings.various.monthsLongAugust.toLowerCase() : settings.various.monthsLongAugust,
            settings.language == 'nl' ? settings.various.monthsLongSeptember.toLowerCase() : settings.various.monthsLongSeptember,
            settings.language == 'nl' ? settings.various.monthsLongOctober.toLowerCase() : settings.various.monthsLongOctober,
            settings.language == 'nl' ? settings.various.monthsLongNovember.toLowerCase() : settings.various.monthsLongNovember,
            settings.language == 'nl' ? settings.various.monthsLongDecember.toLowerCase() : settings.various.monthsLongDecember
        ],
        monthsShort: [
            settings.language == 'nl' ? settings.various.monthsShortJanuary.toLowerCase() : settings.various.monthsShortJanuary,
            settings.language == 'nl' ? settings.various.monthsShortFebruary.toLowerCase(): settings.various.monthsShortFebruary,
            settings.language == 'nl' ? settings.various.monthsShortMarch.toLowerCase(): settings.various.monthsShortMarch,
            settings.language == 'nl' ? settings.various.monthsShortApril.toLowerCase(): settings.various.monthsShortApril,
            settings.language == 'nl' ? settings.various.monthsShortMay.toLowerCase(): settings.various.monthsShortMay,
            settings.language == 'nl' ? settings.various.monthsShortJune.toLowerCase(): settings.various.monthsShortJune,
            settings.language == 'nl' ? settings.various.monthsShortJuly.toLowerCase(): settings.various.monthsShortJuly,
            settings.language == 'nl' ? settings.various.monthsShortAugust.toLowerCase(): settings.various.monthsShortAugust,
            settings.language == 'nl' ? settings.various.monthsShortSeptember.toLowerCase(): settings.various.monthsShortSeptember,
            settings.language == 'nl' ? settings.various.monthsShortOctober.toLowerCase(): settings.various.monthsShortOctober,
            settings.language == 'nl' ? settings.various.monthsShortNovember.toLowerCase(): settings.various.monthsShortNovember,
            settings.language == 'nl' ? settings.various.monthsShortDecember.toLowerCase(): settings.various.monthsShortDecember
        ],
        weekdays: [
            settings.various.daysLongSunday,
            settings.various.daysLongMonday,
            settings.various.daysLongTuesday,
            settings.various.daysLongWednesday,
            settings.various.daysLongThursday,
            settings.various.daysLongFriday,
            settings.various.daysLongSaturday
        ],
        weekdaysShort: [
            settings.various.daysShortSunday,
            settings.various.daysShortMonday,
            settings.various.daysShortTuesday,
            settings.various.daysShortWednesday,
            settings.various.daysShortThursday,
            settings.various.daysShortFriday,
            settings.various.daysShortSaturday
        ]
    });
};
$(document).ready(function()
{
	if ($('#users.item').length > 0)
		return;

	if ($('.filterable').length > 0)
	{
		$('.filterable').verticalFilter();

		$('.filterable').data('vertical-filter').initialized(function()
		{
			if ($('#content > .contentRow > .twelve.columns').length > 0)
				$('.filterOptions').addClass('topFilters');
		});
	}

	if (typeof Sys != 'undefined' && typeof Sys.WebForms != 'undefined')
	{
		Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function()
		{
			if ($('.filterable').length > 0)
			{
				$('.filterable').data('vertical-filter').initialized(function()
				{
					if ($('#content > .contentRow > .twelve.columns').length > 0)
						$('.filterOptions').addClass('topFilters');
				});
			}
		});
	}

	if ($('#eParticipation.item').length > 0)
		$('.filterOptions').hide();
});

$(window).resize(function()
{
	if ($('.filterOptions').length > 0)
	{
		if ($(window).width() < 768)
		{
			if ($('#right .filterOptions').length > 0)
				$('.sectionOptions').after($('.filterOptions').addClass('topFilters'));
		}
		else
		{
			if ($('#right .filterOptions').length == 0)
				$('#right .editorContent.rightEditor').append($('.filterOptions').removeClass('topFilters'));
		}
	}
});

$.fn.verticalFilter = function()
{
	$(this).each(function()
	{
		var fObject = null;

		var theReturnObject =
		{
			itemsPerPage: settings.section.itemsPerPage,
			fActiveFilters: [],
			changedContainer: null,
			previousFilter: '',
			changedContainerActive: false,
			isInitialized: false,
			initializedHandlers: [],
			filterOptions: null,
			filterOptionsHandlers: [],
			filterOptionMatches: null,
			filterOptionMatchesHandlers: [],

			init:function()
			{
				fObject = this;

				setTimeout(function()
				{
					fObject.initHandlers();
				}, 300);

				fObject.initHelperTooltips();
			},

			initHandlers:function()
			{
				if (typeof Sys !== 'undefined' && typeof Sys.WebForms !== 'undefined')
				{
					Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function()
					{
						fObject.hideChangedContainer();
					});
				}

				$('.resetFilters').unbind('click').bind('click', fObject.resetFilters);

				var checkedFilters = $('.filterOptions input[type="checkbox"]:checked');

				if (checkedFilters.length > 0)
				{
					$('.resetFilters').show();

					checkedFilters.each(function(i)
					{
						fObject.updateFilterData(checkedFilters[i]);
					});
				}
				else
				{
					$('.resetFilters').hide();

					setTimeout(function()
					{
						fObject.updateListClasses();
					}, 300);
				}

				$('.filterOptions .field input[type="checkbox"]').change(function()
				{
					fObject.updateFilterData($(this));
				});

				if (typeof Sys !== 'undefined' && typeof Sys.WebForms !== 'undefined')
				{
					Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, arguments) {
						if (!sender._postBackSettings || sender._postBackSettings.sourceElement === null)
							return;

						if (
							$(sender._postBackSettings.sourceElement).attr('id') === $('div[id$=_updateList]').attr('id') ||
							$(sender._postBackSettings.sourceElement).attr('id') === $('div[id$=_contentList]').attr('id')
						) {
							if (fObject.filterOptionMatchesHandlers.length > 0)
								fObject.getFilterOptionMatches();

							if (fObject.filterOptionsHandlers.length > 0)
								fObject.getFilterOptions();
						}
					});
				}

				fObject.isInitialized = true;

				fObject.updatePageLayout();
				fObject.updateLabels();
				fObject.initialized();
			},

			updateFilterData:function(filterItem)
			{
				if (!fObject.changedContainerActive)
					fObject.previousFilter = $('.txtFilterOptions').val() || '[]';

				var filter_cat = $(filterItem).parent().data('fieldid'),
					filter_id = $(filterItem).attr('id').split('_').pop(),
					filter_type = $(filterItem).parent().data('field-type'),
					filter_value = $(filterItem).val();

				if ($(filterItem).prop('checked') === true)
					fObject.addToActiveFiltersArray(filter_cat, filter_id, filter_type, filter_value);
				else
					fObject.removeFromActiveFiltersArray(filter_cat, filter_id);

				if (fObject.isInitialized)
					fObject.createChangedContainer();
			},

			updatePageLayout:function()
			{
				setTimeout(function()
				{
					$('.filterOptions input[type="checkbox"]').each(function()
					{
						$(this).initializeSwitchery();
					});
				}, 150);

				if (!($('.filterable .sectionContent ul.paging').length > 0))
					$('<ul class="paging"></ul>').insertAfter('.filterable .sectionContent ul');

				$('.resetFilters').wrap('<div class="filterOptionsHeader"><h2 class="filterTitle">Filters</h2></div>');

				var filterSaveBtn = $('.filterOptions .button.save.general');

				if (settings.widgets.allowed)
				{
					$('.filterOptions > div').css('margin-bottom', '25px');
					$('.filterOptions').append(filterSaveBtn);
				}
				else
					filterSaveBtn.remove();

				if ($('.filterOptions fieldset h2').length > 0)
				{
					$.each($('.filterOptions fieldset h2'), function()
					{
						var currentHeading = $(this);
						var currentFieldOptions = currentHeading.nextUntil('h2');
						var currentSubFieldSet = $('<div>');
						currentSubFieldSet.addClass('subfieldset open');

						var screenReaderContent = $('<span>');
						screenReaderContent.addClass('screenReaderContent');
						screenReaderContent.text(' ' + settings.filters.collapseCategory);

						var headingButton = $('<a>');
						headingButton.attr({
							href: '#',
							role: 'button',
							'aria-expanded': 'true'
						});

						currentHeading.wrapInner(headingButton);

						// Need to reassign headingButton after innerWrap
						headingButton = currentHeading.find('a');
						headingButton.append(screenReaderContent);

						currentSubFieldSet.append(currentFieldOptions);
						currentSubFieldSet.insertAfter(currentHeading);

						var collapsibleItem = $('<span class="collapse-item icon-up-open before"></span>');

						currentHeading.append(collapsibleItem);

						headingButton.on('click', function(e)
						{
							currentHeading.click();
							e.preventDefault();

							return false;
						});

						currentHeading.on('click', function()
						{
							currentSubFieldSet.toggleClass('open');

							if (currentSubFieldSet.hasClass('open'))
							{
								collapsibleItem.addClass('icon-up-open').removeClass('icon-down-open');
								headingButton.attr('aria-expanded', 'true');
								screenReaderContent.text(' ' + settings.filters.collapseCategory);
							}
							else
							{
								collapsibleItem.addClass('icon-down-open').removeClass('icon-up-open');
								headingButton.attr('aria-expanded', 'false');
								screenReaderContent.text(' ' + settings.filters.expandCategory);
							}
						});
					});
				}
			},

			addToActiveFiltersArray:function(cat, id, type, value)
			{
				var fExists = fObject.fActiveFilters.filter(function(option)
				{
					return option.catId === cat;
				});

				if (fExists.length === 0)
				{
					var filterObj =
					{
						catId: parseInt(cat),
						type: type,
						options: [{ id: parseInt(id), value: value }]
					};

					fObject.fActiveFilters.push(filterObj);
				}
				else
				{
					var pos = fObject.findInActiveFiltersArray(cat);

					fObject.fActiveFilters[pos].options.push({ id: parseInt(id), value: value });
				}

				fObject.updateHiddenFilterOptionField();
			},

			hideChangedContainer: function()
			{
				if (fObject.changedContainer)
					fObject.changedContainer.stop(true).animate({ top: -(fObject.changedContainer.outerHeight() + 20) }, 500);

				fObject.previousFilter = $('.txtFilterOptions').val() || '[]';
				fObject.changedContainerActive = false;
			},

			filterIsChanged:function()
			{
				var previousFilterObject = JSON.parse(fObject.previousFilter);
				var flatPreviousFilterOptions = [];
				var flatActiveFilterOptions = [];

				for (var i = 0; i < fObject.fActiveFilters.length; i++)
				{
					var currentCat = fObject.fActiveFilters[i];

					flatActiveFilterOptions = flatActiveFilterOptions.concat(currentCat.options);
				}

				for (var i = 0; i < previousFilterObject.length; i++)
				{
					var currentCat = previousFilterObject[i];

					flatPreviousFilterOptions = flatPreviousFilterOptions.concat(currentCat.options);
				}

				flatPreviousFilterOptions.sort();
				flatActiveFilterOptions.sort();

				return JSON.stringify(flatPreviousFilterOptions) != JSON.stringify(flatActiveFilterOptions);
			},

			createChangedContainer: function()
			{
				if (!fObject.filterIsChanged())
				{
					fObject.hideChangedContainer();

					return;
				}

				fObject.changedContainerActive = true;

				if (fObject.changedContainer != null)
				{
					fObject.changedContainer.stop(true).animate({ top: 0 }, 500);

					return;
				}

				fObject.changedContainer = $("<div class=\"message alert warning\"><div class=\"messageButtons\"></div></div>");

				var theSaveButton = $("<div class=\"button saveTree general icon-check before\"><input type=\"button\" value=\"" + settings.filters.applyFilters + "\" /></div>");

				fObject.changedContainer.find(".messageButtons").append(theSaveButton);

				theSaveButton.click(function()
				{
					fObject.applyFilters();
				});

				fObject.changedContainer.css({ visibility: 'hidden' });

				setTimeout(function()
				{
					fObject.changedContainer.css({ visibility: 'visible', display: "block", top: -(fObject.changedContainer.outerHeight() + 20) });

					fObject.changedContainer.stop(true).animate({ top: 0 }, 500);
				}, 40);

				$(".filterOptions fieldset").append(fObject.changedContainer);
			},

			removeFromActiveFiltersArray:function(cat, id)
			{
				var pos = fObject.findInActiveFiltersArray(cat);

				if (fObject.fActiveFilters[pos].options.length > 1)
				{
					fObject.fActiveFilters[pos].options = $.grep(fObject.fActiveFilters[pos].options, function(item)
					{
						return item.id !== parseInt(id);
					});
				}
				else
				{
					fObject.fActiveFilters = $.grep(fObject.fActiveFilters, function(item)
					{
						return item.catId !== parseInt(cat);
					});
				}

				fObject.updateHiddenFilterOptionField();
			},

			findInActiveFiltersArray:function(cat)
			{
				for (var i = 0; i < fObject.fActiveFilters.length; i++)
				{
					if (fObject.fActiveFilters[i].catId === cat)
						return i;
				}

				return null;
			},

			updateHiddenFilterOptionField: function ()
			{
				var activeFiltersJson = JSON.stringify(fObject.fActiveFilters);
				
				setTimeout(function()
				{
					$('.txtFilterOptions').val(activeFiltersJson);
				}, 50);
			},

			updateListContent:function()
			{
				__doPostBack($('div[id$=_updateList]').attr('id'), '');
			},

			updateListClasses:function()
			{
				var visibleChildren = $('.filterable .sectionContent ul.items .item:not(.concealed):not(.paginated)').length;

				if (visibleChildren < fObject.itemsPerPage)
					$('.filterable .sectionContent ul.items').addClass('flex-auto');
				else
					$('.filterable .sectionContent ul.items').removeClass('flex-auto');
			},

			updateLabels:function ()
			{
				var labelContainer = $('.labelContainer');
				labelContainer.empty();

				if (labelContainer.length == 0)
				{
					labelContainer = $('<div>');
					labelContainer.addClass('labelContainer');
					$('.filterOptions fieldset').append(labelContainer);
				}

				if (fObject.previousFilter)
				{
					var previousFilterObject = JSON.parse(fObject.previousFilter);

					$.each(previousFilterObject, function()
					{
						var currentCat = this;

						$.each(currentCat.options, function()
						{
							var currentOption = this;
							var currentLabel = $('<span>');
							currentLabel.addClass('filterLabel icon-cancel after');
							currentLabel.attr('role', 'button');
							currentLabel.text(currentOption.value);
							currentLabel.attr("label", settings.filters.filterText + ' ' + htmlEncode(currentOption.value) + ' ' + settings.various.deleteText);

							currentLabel.click(function()
							{
								fObject.updateHiddenFilterOptionField();

								$('input:checkbox[id$=_option_' + currentOption.id + ']:checked').click();

								currentLabel.remove();
							});

							labelContainer.append(currentLabel);
						});
					});
				}
			},

			applyFilters:function()
			{
				$.ajax(
					{
					url: "/api/sections/setCookie",
					data:
					{
						sectionID: settings.section.ID,
						value: $('.txtFilterOptions').val(),
						token: $("input[name='__RequestVerificationToken']").val()
					}
				})
				.done(function()
				{
					fObject.updateListContent();

					if (fObject.fActiveFilters.length > 0)
						$('.resetFilters').show();
					else
						$('.resetFilters').hide();
				});

				fObject.previousFilter = $('.txtFilterOptions').val();
				fObject.hideChangedContainer();
				fObject.updateLabels();
			},

			resetFilters:function()
			{
				if (fObject.fActiveFilters.length == 0)
					return false;

				fObject.hideChangedContainer();
				fObject.fActiveFilters = [];
				$('.txtFilterOptions').val('');
				console.log(fObject.previousFilter);

				$('.filterOptions input[type="checkbox"]').prop('checked', false).initializeSwitchery();

				fObject.updateHiddenFilterOptionField();

				$.ajax(
				{
					url: "/api/sections/setCookie",
					data:
					{
						sectionID: settings.section.ID,
						value: "[]",
						token: $("input[name='__RequestVerificationToken']").val()
					}
				})
				.done(function()
				{
					if (fObject.fActiveFilters.length > 0)
						$('.resetFilters').show();
					else
						$('.resetFilters').hide();

					fObject.updateListContent();
					fObject.updateLabels();
				});

				return false;
			},

			initHelperTooltips:function()
			{
				$('.filterOptions input[type="checkbox"]').each(function()
				{
					if ($(this).data('description'))
					{
						var desc = $(this).data('description');

						$(this).parent().append('<span class="filterTip"><span class="icon-awesome-info before"></span><span class="tip">' + desc + '</span></span>');
					}
				});
			},

			// Gets all filteroption values for all visible items
			getFilterOptions: function () {
				var itemIDs = [];

				$('[id^=item_]').each(function () {
					parseInt(itemIDs.push($(this).attr('id').split('_')[1]));
				});

				if (itemIDs.length === 0) {
					fObject.filterOptions = null;
					return;
				}

				$.ajax({
					url: '/api/contentpages/GetFilterOptionMatches',
					data: {
						contentPageIDs: itemIDs,
						filterOptions: '',
						token: $("input[name='__RequestVerificationToken']").val()
					}
				})
				.done(function (data) {
					if (data.status !== "success") {
						return;
					}

					fObject.filterOptions = JSON.parse(data.message);
					fObject.filterOptionsLoaded();
				});
			},

			// Gets all filteroption values for all visible items based on the filterOptions
			getFilterOptionMatches:function() {
				var itemIDs = [];

				$('[id^=item_]').each(function () {
					parseInt(itemIDs.push($(this).attr('id').split('_')[1]));
				});

				if (itemIDs.length === 0) {
					fObject.filterOptionMatches = null;
					return;
				}

				$.ajax({
					url: '/api/contentpages/GetFilterOptionMatches',
					data: {
						contentPageIDs: itemIDs,
						filterOptions: $('.txtFilterOptions').val(),
						token: $("input[name='__RequestVerificationToken']").val()
					}
				})
				.done(function (data) {
					if (data.status !== "success") {
						return;
					}

					fObject.filterOptionMatches = JSON.parse(data.message);
					fObject.filterOptionMatchesLoaded();
				});
			},

			filterOptionsLoaded: function (handler) {
				if (handler) {
					fObject.filterOptionsHandlers.push(handler);
					fObject.getFilterOptions();
				}
				else {
					for (var i in fObject.filterOptionsHandlers) {
						fObject.filterOptionsHandlers[i](fObject.filterOptions);
					}
				}
			},

			filterOptionMatchesLoaded: function (handler) {
				if (handler) {
					fObject.filterOptionMatchesHandlers.push(handler);
					fObject.getFilterOptionMatches();
				}
				else {
					for (var i in fObject.filterOptionMatchesHandlers) {
						fObject.filterOptionMatchesHandlers[i](fObject.filterOptionMatches);
					}
				}
			},

			initialized: function (handler)
			{
				if (handler)
				{
					fObject.initializedHandlers.push(handler);

					if (fObject.isInitialized)
						handler();
				}
				else
				{
					for (var i in fObject.initializedHandlers)
					{
						fObject.initializedHandlers[i]();
					}
				}
			}
		}

		theReturnObject.init($(this));

		$(this).data('vertical-filter', theReturnObject);
	});

	return $(this);
};
;
/*
colpick Color Picker
Copyright 2013 Jose Vargas. Licensed under GPL license. Based on Stefan Petre's Color Picker www.eyecon.ro, dual licensed under the MIT and GPL licenses

For usage and examples: colpick.com/plugin
 */

(function ($) {
	var colpick = function () {
		var
			tpl = '<div class="colpick"><div class="colpick_color"><div class="colpick_color_overlay1"><div class="colpick_color_overlay2"><div class="colpick_selector_outer"><div class="colpick_selector_inner"></div></div></div></div></div><div class="colpick_hue"><div class="colpick_hue_arrs"><div class="colpick_hue_larr"></div><div class="colpick_hue_rarr"></div></div></div><div class="colpick_new_color"></div><div class="colpick_current_color"></div><div class="colpick_hex_field"><div class="colpick_field_letter">#</div><input type="text" maxlength="6" size="6" /></div><div class="colpick_rgb_r colpick_field"><div class="colpick_field_letter">R</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_rgb_g colpick_field"><div class="colpick_field_letter">G</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_rgb_b colpick_field"><div class="colpick_field_letter">B</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_hsb_h colpick_field"><div class="colpick_field_letter">H</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_hsb_s colpick_field"><div class="colpick_field_letter">S</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_hsb_b colpick_field"><div class="colpick_field_letter">B</div><input type="text" maxlength="3" size="3" /><div class="colpick_field_arrs"><div class="colpick_field_uarr"></div><div class="colpick_field_darr"></div></div></div><div class="colpick_submit"></div></div>',
			defaults = {
				showEvent: 'click',
				onShow: function () {},
				onBeforeShow: function(){},
				onHide: function () {},
				onChange: function () {},
				onSubmit: function () {},
				colorScheme: 'light',
				color: '3289c7',
				livePreview: true,
				flat: false,
				layout: 'full',
				submit: 1,
				submitText: 'OK',
				height: 156,
                polyfill: false
			},
			//Fill the inputs of the plugin
			fillRGBFields = function  (hsb, cal) {
				var rgb = hsbToRgb(hsb);
				$(cal).data('colpick').fields
					.eq(1).val(rgb.r).end()
					.eq(2).val(rgb.g).end()
					.eq(3).val(rgb.b).end();
			},
			fillHSBFields = function  (hsb, cal) {
				$(cal).data('colpick').fields
					.eq(4).val(Math.round(hsb.h)).end()
					.eq(5).val(Math.round(hsb.s)).end()
					.eq(6).val(Math.round(hsb.b)).end();
			},
			fillHexFields = function (hsb, cal) {
				$(cal).data('colpick').fields.eq(0).val(hsbToHex(hsb));
			},
			//Set the round selector position
			setSelector = function (hsb, cal) {
				$(cal).data('colpick').selector.css('backgroundColor', '#' + hsbToHex({h: hsb.h, s: 100, b: 100}));
				$(cal).data('colpick').selectorIndic.css({
					left: parseInt($(cal).data('colpick').height * hsb.s/100, 10),
					top: parseInt($(cal).data('colpick').height * (100-hsb.b)/100, 10)
				});
			},
			//Set the hue selector position
			setHue = function (hsb, cal) {
				$(cal).data('colpick').hue.css('top', parseInt($(cal).data('colpick').height - $(cal).data('colpick').height * hsb.h/360, 10));
			},
			//Set current and new colors
			setCurrentColor = function (hsb, cal) {
				$(cal).data('colpick').currentColor.css('backgroundColor', '#' + hsbToHex(hsb));
			},
			setNewColor = function (hsb, cal) {
				$(cal).data('colpick').newColor.css('backgroundColor', '#' + hsbToHex(hsb));
			},
			//Called when the new color is changed
			change = function (ev) {
				var cal = $(this).parent().parent(), col;
				if (this.parentNode.className.indexOf('_hex') > 0) {
					cal.data('colpick').color = col = hexToHsb(fixHex(this.value));
					fillRGBFields(col, cal.get(0));
					fillHSBFields(col, cal.get(0));
				} else if (this.parentNode.className.indexOf('_hsb') > 0) {
					cal.data('colpick').color = col = fixHSB({
						h: parseInt(cal.data('colpick').fields.eq(4).val(), 10),
						s: parseInt(cal.data('colpick').fields.eq(5).val(), 10),
						b: parseInt(cal.data('colpick').fields.eq(6).val(), 10)
					});
					fillRGBFields(col, cal.get(0));
					fillHexFields(col, cal.get(0));
				} else {
					cal.data('colpick').color = col = rgbToHsb(fixRGB({
						r: parseInt(cal.data('colpick').fields.eq(1).val(), 10),
						g: parseInt(cal.data('colpick').fields.eq(2).val(), 10),
						b: parseInt(cal.data('colpick').fields.eq(3).val(), 10)
					}));
					fillHexFields(col, cal.get(0));
					fillHSBFields(col, cal.get(0));
				}
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
				cal.data('colpick').onChange.apply(cal.parent(), [col, hsbToHex(col), hsbToRgb(col), cal.data('colpick').el, 0]);
			},
			//Change style on blur and on focus of inputs
			blur = function (ev) {
				$(this).parent().removeClass('colpick_focus');
			},
			focus = function () {
				$(this).parent().parent().data('colpick').fields.parent().removeClass('colpick_focus');
				$(this).parent().addClass('colpick_focus');
			},
			//Increment/decrement arrows functions
			downIncrement = function (ev) {
				ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
				var field = $(this).parent().find('input').focus();
				var current = {
					el: $(this).parent().addClass('colpick_slider'),
					max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
					y: ev.pageY,
					field: field,
					val: parseInt(field.val(), 10),
					preview: $(this).parent().parent().data('colpick').livePreview
				};
				$(document).mouseup(current, upIncrement);
				$(document).mousemove(current, moveIncrement);
			},
			moveIncrement = function (ev) {
				ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val - ev.pageY + ev.data.y, 10))));
				if (ev.data.preview) {
					change.apply(ev.data.field.get(0), [true]);
				}
				return false;
			},
			upIncrement = function (ev) {
				change.apply(ev.data.field.get(0), [true]);
				ev.data.el.removeClass('colpick_slider').find('input').focus();
				$(document).off('mouseup', upIncrement);
				$(document).off('mousemove', moveIncrement);
				return false;
			},
			//Hue slider functions
			downHue = function (ev) {
				ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
				var current = {
					cal: $(this).parent(),
					y: $(this).offset().top
				};
				$(document).on('mouseup touchend',current,upHue);
				$(document).on('mousemove touchmove',current,moveHue);

				var pageY = ((ev.type == 'touchstart') ? ev.originalEvent.changedTouches[0].pageY : ev.pageY );
				change.apply(
					current.cal.data('colpick')
					.fields.eq(4).val(parseInt(360*(current.cal.data('colpick').height - (pageY - current.y))/current.cal.data('colpick').height, 10))
						.get(0),
					[current.cal.data('colpick').livePreview]
				);
				return false;
			},
			moveHue = function (ev) {
				var pageY = ((ev.type == 'touchmove') ? ev.originalEvent.changedTouches[0].pageY : ev.pageY );
				change.apply(
					ev.data.cal.data('colpick')
					.fields.eq(4).val(parseInt(360*(ev.data.cal.data('colpick').height - Math.max(0,Math.min(ev.data.cal.data('colpick').height,(pageY - ev.data.y))))/ev.data.cal.data('colpick').height, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upHue = function (ev) {
				fillRGBFields(ev.data.cal.data('colpick').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colpick').color, ev.data.cal.get(0));
				$(document).off('mouseup touchend',upHue);
				$(document).off('mousemove touchmove',moveHue);
				return false;
			},
			//Color selector functions
			downSelector = function (ev) {
				ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
				var current = {
					cal: $(this).parent(),
					pos: $(this).offset()
				};
				current.preview = current.cal.data('colpick').livePreview;

				$(document).on('mouseup touchend',current,upSelector);
				$(document).on('mousemove touchmove',current,moveSelector);

				var pageX,pageY;
				if(ev.type == 'touchstart') {
					pageX = ev.originalEvent.changedTouches[0].pageX;
					pageY = ev.originalEvent.changedTouches[0].pageY;
				} else {
					pageX = ev.pageX;
					pageY = ev.pageY;
				}

				change.apply(
					current.cal.data('colpick').fields
					.eq(6).val(parseInt(100*(current.cal.data('colpick').height - (pageY - current.pos.top))/current.cal.data('colpick').height, 10)).end()
					.eq(5).val(parseInt(100*(pageX - current.pos.left)/current.cal.data('colpick').height, 10))
					.get(0),
					[current.preview]
				);
				return false;
			},
			moveSelector = function (ev) {
				var pageX,pageY;
				if(ev.type == 'touchmove') {
					pageX = ev.originalEvent.changedTouches[0].pageX;
					pageY = ev.originalEvent.changedTouches[0].pageY;
				} else {
					pageX = ev.pageX;
					pageY = ev.pageY;
				}

				change.apply(
					ev.data.cal.data('colpick').fields
					.eq(6).val(parseInt(100*(ev.data.cal.data('colpick').height - Math.max(0,Math.min(ev.data.cal.data('colpick').height,(pageY - ev.data.pos.top))))/ev.data.cal.data('colpick').height, 10)).end()
					.eq(5).val(parseInt(100*(Math.max(0,Math.min(ev.data.cal.data('colpick').height,(pageX - ev.data.pos.left))))/ev.data.cal.data('colpick').height, 10))
					.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upSelector = function (ev) {
				fillRGBFields(ev.data.cal.data('colpick').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colpick').color, ev.data.cal.get(0));
				$(document).off('mouseup touchend',upSelector);
				$(document).off('mousemove touchmove',moveSelector);
				return false;
			},
			//Submit button
			clickSubmit = function (ev) {
				var cal = $(this).parent();
				var col = cal.data('colpick').color;
				cal.data('colpick').origColor = col;
				setCurrentColor(col, cal.get(0));
				cal.data('colpick').onSubmit(col, hsbToHex(col), hsbToRgb(col), cal.data('colpick').el);
			},
			//Show/hide the color picker
			show = function (ev) {
				if(ev) {
					// Prevent the trigger of any direct parent
					ev.stopPropagation();
				}
				var cal = $('#' + $(this).data('colpickId'));
                if (ev && !cal.data('colpick').polyfill) {
                    ev.preventDefault();
                }
				cal.data('colpick').onBeforeShow.apply(this, [cal.get(0)]);
				// Replaced offset with position to fix positioning of popup color picker
				//var pos = $(this).offset();
				var pos = $(this).position();
				var top = pos.top + this.offsetHeight;
				var left = pos.left;
				var viewPort = getViewport();
				var calW = cal.width();
				if (left + calW > viewPort.l + viewPort.w) {
					left -= calW;
				}

				cal.css({left: left + 'px', top: top + 'px'});
				if (cal.data('colpick').onShow.apply(this, [cal.get(0)]) != false) {
					cal.show();
				}
				//Hide when user clicks outside
				$('html').mousedown({cal:cal}, hide);
				cal.mousedown(function(ev){ev.stopPropagation();})
			},
			hide = function (ev) {
				if (ev.data.cal.data('colpick').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
					ev.data.cal.hide();
				}
				$('html').off('mousedown', hide);
			},
			getViewport = function () {
				var m = document.compatMode == 'CSS1Compat';
				return {
					l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
					w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth)
				};
			},
			//Fix the values if the user enters a negative or high value
			fixHSB = function (hsb) {
				return {
					h: Math.min(360, Math.max(0, hsb.h)),
					s: Math.min(100, Math.max(0, hsb.s)),
					b: Math.min(100, Math.max(0, hsb.b))
				};
			},
			fixRGB = function (rgb) {
				return {
					r: Math.min(255, Math.max(0, rgb.r)),
					g: Math.min(255, Math.max(0, rgb.g)),
					b: Math.min(255, Math.max(0, rgb.b))
				};
			},
			fixHex = function (hex) {
				var len = 6 - hex.length;
				if (len > 0) {
					var o = [];
					for (var i=0; i<len; i++) {
						o.push('0');
					}
					o.push(hex);
					hex = o.join('');
				}
				return hex;
			},
			getUniqueID = (function () {
				var cnt = 0;
				return function () {
					cnt += 1;
					return cnt;
				};
			})(),
			restoreOriginal = function () {
				var cal = $(this).parent();
				var col = cal.data('colpick').origColor;
				cal.data('colpick').color = col;
				fillRGBFields(col, cal.get(0));
				fillHexFields(col, cal.get(0));
				fillHSBFields(col, cal.get(0));
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
			};
		return {
			init: function (opt) {
				opt = $.extend({}, defaults, opt||{});
				//Set color
				if (typeof opt.color == 'string') {
					opt.color = hexToHsb(opt.color);
				} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
					opt.color = rgbToHsb(opt.color);
				} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
					opt.color = fixHSB(opt.color);
				} else {
					return this;
				}

				//For each selected DOM element
				return this.each(function () {
					//If the element does not have an ID
					if (!$(this).data('colpickId')) {
						var options = $.extend({}, opt);
						options.origColor = opt.color;

                        // Set polyfill
                        if (typeof opt.polyfill == 'function') {
                            options.polyfill = opt.polyfill(this);
                        }

                        //Input field operations
                        options.input = $(this).is('input');

                        //Polyfill fixes
                        if (options.polyfill && options.input && this.type === "color") {
                            return;
                        }

						//Generate and assign a random ID
						var id = 'colorpicker_' + getUniqueID();
						$(this).data('colpickId', id);
						//Set the tpl's ID and get the HTML
						var cal = $(tpl).attr('id', id);
						//Add class according to layout
						cal.addClass('colpick_'+options.layout+(options.submit?'':' colpick_'+options.layout+'_ns'));
						//Add class if the color scheme is not default
						if(options.colorScheme != 'light') {
							cal.addClass('colpick_'+options.colorScheme);
						}
						//Setup submit button
						cal.find('div.colpick_submit').html(options.submitText).click(clickSubmit);
						//Setup input fields
						options.fields = cal.find('input').change(change).blur(blur).focus(focus);
						cal.find('div.colpick_field_arrs').mousedown(downIncrement).end().find('div.colpick_current_color').click(restoreOriginal);
						//Setup hue selector
						options.selector = cal.find('div.colpick_color').on('mousedown touchstart',downSelector);
						options.selectorIndic = options.selector.find('div.colpick_selector_outer');
						//Store parts of the plugin
						options.el = this;
						options.hue = cal.find('div.colpick_hue_arrs');
						var huebar = options.hue.parent();
						//Paint the hue bar
						var UA = navigator.userAgent.toLowerCase();
						var isIE = navigator.appName === 'Microsoft Internet Explorer';
						var IEver = isIE ? parseFloat( UA.match( /msie ([0-9]{1,}[\.0-9]{0,})/ )[1] ) : 0;
						var ngIE = ( isIE && IEver < 10 );
						var stops = ['#ff0000','#ff0080','#ff00ff','#8000ff','#0000ff','#0080ff','#00ffff','#00ff80','#00ff00','#80ff00','#ffff00','#ff8000','#ff0000'];
						if(ngIE) {
							var i, div;
							for(i=0; i<=11; i++) {
								div = $('<div></div>').attr('style','height:8.333333%; filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='+stops[i]+', endColorstr='+stops[i+1]+'); -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='+stops[i]+', endColorstr='+stops[i+1]+')";');
								huebar.append(div);
							}
						} else {
							var stopList = stops.join(',');
							huebar.attr('style','background:-webkit-linear-gradient(top,'+stopList+'); background: -o-linear-gradient(top,'+stopList+'); background: -ms-linear-gradient(top,'+stopList+'); background:-moz-linear-gradient(top,'+stopList+'); -webkit-linear-gradient(top,'+stopList+'); background:linear-gradient(to bottom,'+stopList+'); ');
						}
						cal.find('div.colpick_hue').on('mousedown touchstart',downHue);
						options.newColor = cal.find('div.colpick_new_color');
						options.currentColor = cal.find('div.colpick_current_color');
						//Store options and fill with default color
						cal.data('colpick', options);
						fillRGBFields(options.color, cal.get(0));
						fillHSBFields(options.color, cal.get(0));
						fillHexFields(options.color, cal.get(0));
						setHue(options.color, cal.get(0));
						setSelector(options.color, cal.get(0));
						setCurrentColor(options.color, cal.get(0));
						setNewColor(options.color, cal.get(0));
						//Append to body if flat=false, else show in place
						if (options.flat) {
							cal.appendTo(this).show();
							cal.css({
								position: 'relative',
								display: 'block'
							});
						} else {
							cal.appendTo($(this).parent());
							$(this).on(options.showEvent, show);
							cal.css({
								position:'absolute'
							});
						}
					}
				});
			},
			//Shows the picker
			showPicker: function() {
				return this.each( function () {
					if ($(this).data('colpickId')) {
						show.apply(this);
					}
				});
			},
			//Hides the picker
			hidePicker: function() {
				return this.each( function () {
					if ($(this).data('colpickId')) {
						$('#' + $(this).data('colpickId')).hide();
					}
				});
			},
			//Sets a color as new and current (default)
			setColor: function(col, setCurrent) {
				if (col != undefined) {
					setCurrent = (typeof setCurrent === "undefined") ? 1 : setCurrent;
					if (typeof col == 'string') {
						col = hexToHsb(col);
					} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
						col = rgbToHsb(col);
					} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
						col = fixHSB(col);
					} else {
						return this;
					}
					return this.each(function(){
						if ($(this).data('colpickId')) {
							var cal = $('#' + $(this).data('colpickId'));
							cal.data('colpick').color = col;
							cal.data('colpick').origColor = col;
							fillRGBFields(col, cal.get(0));
							fillHSBFields(col, cal.get(0));
							fillHexFields(col, cal.get(0));
							setHue(col, cal.get(0));
							setSelector(col, cal.get(0));
							setNewColor(col, cal.get(0));
							cal.data('colpick').onChange.apply(cal.parent(), [col, hsbToHex(col), hsbToRgb(col), cal.data('colpick').el, 1]);
							if(setCurrent) {
								setCurrentColor(col, cal.get(0));
							}
						}
					});
				}
			},
			destroy: function(col, setCurrent) {
				$('#' + $(this).data('colpickId')).remove();
			}
		};
	}();
	//Color space convertions
	var hexToRgb = function (hex) {
		hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
		return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
	};
	var hexToHsb = function (hex) {
		return rgbToHsb(hexToRgb(hex));
	};
	var rgbToHsb = function (rgb) {
		var hsb = {h: 0, s: 0, b: 0};
		var min = Math.min(rgb.r, rgb.g, rgb.b);
		var max = Math.max(rgb.r, rgb.g, rgb.b);
		var delta = max - min;
		hsb.b = max;
		hsb.s = max != 0 ? 255 * delta / max : 0;
		if (hsb.s != 0) {
			if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta;
			else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta;
			else hsb.h = 4 + (rgb.r - rgb.g) / delta;
		} else hsb.h = -1;
		hsb.h *= 60;
		if (hsb.h < 0) hsb.h += 360;
		hsb.s *= 100/255;
		hsb.b *= 100/255;
		return hsb;
	};
	var hsbToRgb = function (hsb) {
		var rgb = {};
		var h = hsb.h;
		var s = hsb.s*255/100;
		var v = hsb.b*255/100;
		if(s == 0) {
			rgb.r = rgb.g = rgb.b = v;
		} else {
			var t1 = v;
			var t2 = (255-s)*v/255;
			var t3 = (t1-t2)*(h%60)/60;
			if(h==360) h = 0;
			if(h<60) {rgb.r=t1;	rgb.b=t2; rgb.g=t2+t3}
			else if(h<120) {rgb.g=t1; rgb.b=t2;	rgb.r=t1-t3}
			else if(h<180) {rgb.g=t1; rgb.r=t2;	rgb.b=t2+t3}
			else if(h<240) {rgb.b=t1; rgb.r=t2;	rgb.g=t1-t3}
			else if(h<300) {rgb.b=t1; rgb.g=t2;	rgb.r=t2+t3}
			else if(h<360) {rgb.r=t1; rgb.g=t2;	rgb.b=t1-t3}
			else {rgb.r=0; rgb.g=0;	rgb.b=0}
		}
		return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
	};
	var rgbToHex = function (rgb) {
		var hex = [
			rgb.r.toString(16),
			rgb.g.toString(16),
			rgb.b.toString(16)
		];
		$.each(hex, function (nr, val) {
			if (val.length == 1) {
				hex[nr] = '0' + val;
			}
		});
		return hex.join('');
	};
	var hsbToHex = function (hsb) {
		return rgbToHex(hsbToRgb(hsb));
	};
	$.fn.extend({
		colpick: colpick.init,
		colpickHide: colpick.hidePicker,
		colpickShow: colpick.showPicker,
		colpickSetColor: colpick.setColor,
		colpickDestroy: colpick.destroy
	});
	$.extend({
		colpick:{
			rgbToHex: rgbToHex,
			rgbToHsb: rgbToHsb,
			hsbToHex: hsbToHex,
			hsbToRgb: hsbToRgb,
			hexToHsb: hexToHsb,
			hexToRgb: hexToRgb
		}
	});
})(jQuery);
;
/*! powerbi-client v2.6.4 | (c) 2016 Microsoft Corporation MIT */
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports["powerbi-client"]=e():t["powerbi-client"]=e()}(this,function(){return function(r){var a={};function i(t){if(a[t])return a[t].exports;var e=a[t]={exports:{},id:t,loaded:!1};return r[t].call(e.exports,e,e.exports,i),e.loaded=!0,e.exports}return i.m=r,i.c=a,i.p="",i(0)}([function(t,e,r){var a=r(1);e.service=a;var i=r(15);e.factories=i;var o=r(4);e.models=o;var n=r(5);e.Report=n.Report;var l=r(11);e.Dashboard=l.Dashboard;var s=r(12);e.Tile=s.Tile;var d=r(2);e.Embed=d.Embed;var u=r(6);e.Page=u.Page;var p=r(13);e.Qna=p.Qna;var c=r(14);e.Visual=c.Visual;var f=r(7);e.VisualDescriptor=f.VisualDescriptor;var h=new a.Service(i.hpmFactory,i.wpmpFactory,i.routerFactory);window.powerbi=h},function(t,e,r){var l=r(2),s=r(5),i=r(10),a=r(11),o=r(12),d=r(6),u=r(13),p=r(14),c=r(3),n=function(){function n(t,e,r,a){var i=this;void 0===a&&(a={}),this.wpmp=e(a.wpmpName,a.logMessages),this.hpm=t(this.wpmp,null,a.version,a.type),this.router=r(this.wpmp),this.router.post("/reports/:uniqueId/events/:eventName",function(t,e){var r={type:"report",id:t.params.uniqueId,name:t.params.eventName,value:t.body};i.handleEvent(r)}),this.router.post("/reports/:uniqueId/pages/:pageName/events/:eventName",function(t,e){var r={type:"report",id:t.params.uniqueId,name:t.params.eventName,value:t.body};i.handleEvent(r)}),this.router.post("/reports/:uniqueId/pages/:pageName/visuals/:visualName/events/:eventName",function(t,e){var r={type:"report",id:t.params.uniqueId,name:t.params.eventName,value:t.body};i.handleEvent(r)}),this.router.post("/dashboards/:uniqueId/events/:eventName",function(t,e){var r={type:"dashboard",id:t.params.uniqueId,name:t.params.eventName,value:t.body};i.handleEvent(r)}),this.router.post("/tile/:uniqueId/events/:eventName",function(t,e){var r={type:"tile",id:t.params.uniqueId,name:t.params.eventName,value:t.body};i.handleEvent(r)}),this.router.post("/qna/:uniqueId/events/:eventName",function(t,e){var r={type:"qna",id:t.params.uniqueId,name:t.params.eventName,value:t.body};i.handleEvent(r)}),this.router.post("/ready/:uniqueId",function(t,e){var r={type:"report",id:t.params.uniqueId,name:"ready",value:t.body};i.handleEvent(r)}),this.embeds=[],this.config=c.assign({},n.defaultConfig,a),this.config.autoEmbedOnContentLoaded&&this.enableAutoEmbed()}return n.prototype.createReport=function(t,e){e.type="create";var r=t,a=new i.Create(this,r,e);return r.powerBiEmbed=a,this.addOrOverwriteEmbed(a,t),a},n.prototype.init=function(t,e){var r=this;return void 0===e&&(e=void 0),t=t&&t instanceof HTMLElement?t:document.body,Array.prototype.slice.call(t.querySelectorAll("["+l.Embed.embedUrlAttribute+"]")).map(function(t){return r.embed(t,e)})},n.prototype.embed=function(t,e){return void 0===e&&(e={}),this.embedInternal(t,e)},n.prototype.load=function(t,e){return void 0===e&&(e={}),this.embedInternal(t,e,!0)},n.prototype.embedInternal=function(t,e,r){void 0===e&&(e={});var a=t;return a.powerBiEmbed?this.embedExisting(a,e,r):this.embedNew(a,e,r)},n.prototype.embedNew=function(t,e,r){var a=e.type||t.getAttribute(l.Embed.typeAttribute);if(!a)throw new Error("Attempted to embed using config "+JSON.stringify(e)+" on element "+t.outerHTML+", but could not determine what type of component to embed. You must specify a type in the configuration or as an attribute such as '"+l.Embed.typeAttribute+'="'+s.Report.type.toLowerCase()+"\"'.");e.type=a;var i=c.find(function(t){return a===t.type.toLowerCase()},n.components);if(!i)throw new Error("Attempted to embed component of type: "+a+" but did not find any matching component.  Please verify the type you specified is intended.");var o=new i(this,t,e,r);return t.powerBiEmbed=o,this.addOrOverwriteEmbed(o,t),o},n.prototype.embedExisting=function(e,t,r){var a=c.find(function(t){return t.element===e},this.embeds);if(!a)throw new Error("Attempted to embed using config "+JSON.stringify(t)+" on element "+e.outerHTML+" which already has embedded comopnent associated, but could not find the existing comopnent in the list of active components. This could indicate the embeds list is out of sync with the DOM, or the component is referencing the incorrect HTML element.");if(t.type&&"qna"===t.type.toLowerCase())return this.embedNew(e,t);if("string"==typeof t.type&&t.type!==a.config.type){if("report"===t.type&&"create"===a.config.type){var i=new s.Report(this,e,t,!1,e.powerBiEmbed.iframe);return i.load(t),e.powerBiEmbed=i,this.addOrOverwriteEmbed(a,e),i}throw new Error("Embedding on an existing element with a different type than the previous embed object is not supported.  Attempted to embed using config "+JSON.stringify(t)+" on element "+e.outerHTML+", but the existing element contains an embed of type: "+this.config.type+" which does not match the new type: "+t.type)}return a.load(t,r),a},n.prototype.enableAutoEmbed=function(){var e=this;window.addEventListener("DOMContentLoaded",function(t){return e.init(document.body)},!1)},n.prototype.get=function(t){var e=t;if(!e.powerBiEmbed)throw new Error("You attempted to get an instance of powerbi component associated with element: "+t.outerHTML+" but there was no associated instance.");return e.powerBiEmbed},n.prototype.find=function(e){return c.find(function(t){return t.config.uniqueId===e},this.embeds)},n.prototype.addOrOverwriteEmbed=function(t,e){this.embeds=this.embeds.filter(function(t){return t.element.id!==e.id}),this.embeds.push(t)},n.prototype.reset=function(t){var e=t;if(e.powerBiEmbed){c.remove(function(t){return t===e.powerBiEmbed},this.embeds),delete e.powerBiEmbed;var r=t.querySelector("iframe");r&&(void 0!==r.remove?r.remove():r.parentElement.removeChild(r))}},n.prototype.handleTileEvents=function(t){"tile"===t.type&&this.handleEvent(t)},n.prototype.handleEvent=function(e){var t=c.find(function(t){return t.config.uniqueId===e.id},this.embeds);if(t){var r=e.value;if("pageChanged"===e.name){var a="newPage",i=r[a];if(!i)throw new Error("Page model not found at 'event.value."+a+"'.");r[a]=new d.Page(t,i.name,i.displayName,!0)}c.raiseCustomEvent(t.element,e.name,r)}},n.prototype.preload=function(t,e){var r=document.createElement("iframe");r.setAttribute("style","display:none;"),r.setAttribute("src",t.embedUrl),r.setAttribute("scrolling","no"),r.setAttribute("allowfullscreen","false");var a=e;return a||(a=document.getElementsByTagName("body")[0]),a.appendChild(r),r.onload=function(){c.raiseCustomEvent(r,"preloaded",{})},r},n.components=[o.Tile,s.Report,a.Dashboard,u.Qna,p.Visual],n.defaultConfig={autoEmbedOnContentLoaded:!1,onError:function(){for(var t=[],e=0;e<arguments.length;e++)t[e-0]=arguments[e];return console.log(t[0],t.slice(1))}},n.DefaultInitEmbedUrl="http://app.powerbi.com/reportEmbed",n}();e.Service=n},function(t,e,r){var n=r(3),a=r(4),i=function(){function o(t,e,r,a,i){this.allowedEvents=[],Array.prototype.push.apply(this.allowedEvents,o.allowedEvents),this.eventHandlers=[],this.service=t,this.element=e,this.iframe=a,this.embeType=r.type.toLowerCase(),this.populateConfig(r),"create"===this.embeType?this.setIframe(!1):this.setIframe(!0,i)}return o.prototype.createReport=function(t){var e=a.validateCreateReport(t);if(e)throw e;return this.service.hpm.post("/report/create",t,{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return t.body},function(t){throw t.body})},o.prototype.save=function(){return this.service.hpm.post("/report/save",null,{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return t.body}).catch(function(t){throw t.body})},o.prototype.saveAs=function(t){return this.service.hpm.post("/report/saveAs",t,{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return t.body}).catch(function(t){throw t.body})},o.prototype.load=function(e,t){var r=this,a=this.validate(e);if(a)throw a;var i=t&&"report"===e.type?this.phasedLoadPath:this.loadPath;return this.service.hpm.post(i,e,{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return n.assign(r.config,e),t.body},function(t){throw t.body})},o.prototype.off=function(t,e){var r=this,a={name:t,type:null,id:null,value:null};e?(n.remove(function(t){return t.test(a)&&t.handle===e},this.eventHandlers),this.element.removeEventListener(t,e)):this.eventHandlers.filter(function(t){return t.test(a)}).forEach(function(e){n.remove(function(t){return t===e},r.eventHandlers),r.element.removeEventListener(t,e.handle)})},o.prototype.on=function(e,t){if(-1===this.allowedEvents.indexOf(e))throw new Error("eventName is must be one of "+this.allowedEvents+". You passed: "+e);this.eventHandlers.push({test:function(t){return t.name===e},handle:t}),this.element.addEventListener(e,t)},o.prototype.reload=function(){return this.load(this.config)},o.prototype.setAccessToken=function(e){var r=this,t=this.config.type;return this.service.hpm.post("/"+t+"/token",e,{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return r.config.accessToken=e,r.element.setAttribute(o.accessTokenAttribute,e),r.service.accessToken=e,t.body}).catch(function(t){throw t.body})},o.prototype.getAccessToken=function(t){var e=this.config.accessToken||this.element.getAttribute(o.accessTokenAttribute)||t;if(!e)throw new Error("No access token was found for element. You must specify an access token directly on the element using attribute '"+o.accessTokenAttribute+"' or specify a global token at: powerbi.accessToken.");return e},o.prototype.populateConfig=function(t){this.config=t,this.config.uniqueId=this.getUniqueId(),this.config.embedUrl=this.getEmbedUrl(),this.config.accessToken=this.getAccessToken(this.service.accessToken),this.config.groupId=this.getGroupId(),this.addLocaleToEmbedUrl(t)},o.prototype.addLocaleToEmbedUrl=function(t){if(t.settings){var e=t.settings.localeSettings;e&&e.language&&(this.config.embedUrl=n.addParamToUrl(this.config.embedUrl,"language",e.language)),e&&e.formatLocale&&(this.config.embedUrl=n.addParamToUrl(this.config.embedUrl,"formatLocale",e.formatLocale))}},o.prototype.getEmbedUrl=function(){var t=this.config.embedUrl||this.element.getAttribute(o.embedUrlAttribute);if("string"!=typeof t||0===t.length)throw new Error("Embed Url is required, but it was not found. You must provide an embed url either as part of embed configuration or as attribute '"+o.embedUrlAttribute+"'.");return t},o.prototype.getUniqueId=function(){return this.config.uniqueId||this.element.getAttribute(o.nameAttribute)||n.createRandomString()},o.prototype.getGroupId=function(){return this.config.groupId||o.findGroupIdFromEmbedUrl(this.config.embedUrl)},o.prototype.fullscreen=function(){(this.iframe.requestFullscreen||this.iframe.msRequestFullscreen||this.iframe.mozRequestFullScreen||this.iframe.webkitRequestFullscreen).call(this.iframe)},o.prototype.exitFullscreen=function(){this.isFullscreen(this.iframe)&&(document.exitFullscreen||document.mozCancelFullScreen||document.webkitExitFullscreen||document.msExitFullscreen).call(document)},o.prototype.isFullscreen=function(e){return["fullscreenElement","webkitFullscreenElement","mozFullscreenScreenElement","msFullscreenElement"].some(function(t){return document[t]===e})},o.prototype.setIframe=function(t,e){var r=this;if(!this.iframe){var a=document.createElement("iframe"),i=this.config.uniqueId?n.addParamToUrl(this.config.embedUrl,"uid",this.config.uniqueId):this.config.embedUrl;a.setAttribute("style","width:100%;height:100%;"),a.setAttribute("src",i),a.setAttribute("scrolling","no"),a.setAttribute("allowfullscreen","true");for(var o=this.element;o.firstChild;)o.removeChild(o.firstChild);o.appendChild(a),this.iframe=o.firstChild}t?this.iframe.addEventListener("load",function(){return r.load(r.config,e)},!1):this.iframe.addEventListener("load",function(){return r.createReport(r.createConfig)},!1)},o.findGroupIdFromEmbedUrl=function(t){var e,r=t.match(/groupId="?([^&]+)"?/);return r&&(e=r[1]),e},o.allowedEvents=["loaded","saved","rendered","saveAsTriggered","error","dataSelected"],o.accessTokenAttribute="powerbi-access-token",o.embedUrlAttribute="powerbi-embed-url",o.nameAttribute="powerbi-name",o.typeAttribute="powerbi-type",o}();e.Embed=i},function(t,e){function a(r,t){if(!Array.isArray(t))throw new Error("You attempted to call find with second parameter that was not an array. You passed: "+t);var a;return t.some(function(t,e){if(r(t))return a=e,!0}),a}e.raiseCustomEvent=function(t,e,r){var a;"function"==typeof CustomEvent?a=new CustomEvent(e,{detail:r,bubbles:!0,cancelable:!0}):(a=document.createEvent("CustomEvent")).initCustomEvent(e,!0,!0,r),t.dispatchEvent(a)},e.findIndex=a,e.find=function(t,e){return e[a(t,e)]},e.remove=function(t,e){var r=a(t,e);e.splice(r,1)},e.assign=function(){for(var t=[],e=0;e<arguments.length;e++)t[e-0]=arguments[e];var r=t[0];if(null==r)throw new TypeError("Cannot convert undefined or null to object");for(var a=Object(r),i=1;i<arguments.length;i++){var o=arguments[i];if(null!=o)for(var n in o)o.hasOwnProperty(n)&&(a[n]=o[n])}return a},e.createRandomString=function(){return(Math.random()+1).toString(36).substring(7)},e.addParamToUrl=function(t,e,r){var a=0<t.indexOf("?")?"&":"?";return t+=a+e+"="+r}},function(t,e,r){var a;a=function(){return function(r){var a={};function i(t){if(a[t])return a[t].exports;var e=a[t]={exports:{},id:t,loaded:!1};return r[t].call(e.exports,e,e.exports,i),e.loaded=!0,e.exports}return i.m=r,i.c=a,i.p="",i(0)}([function(t,r,e){var a,i,o,n,l,s,d,u,p,c,f,h,v,y,m,V=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(r,"__esModule",{value:!0}),r.Validators=e(1).Validators,(i=r.TraceType||(r.TraceType={}))[i.Information=0]="Information",i[i.Verbose=1]="Verbose",i[i.Warning=2]="Warning",i[i.Error=3]="Error",i[i.ExpectedError=4]="ExpectedError",i[i.UnexpectedError=5]="UnexpectedError",i[i.Fatal=6]="Fatal",(o=r.PageSizeType||(r.PageSizeType={}))[o.Widescreen=0]="Widescreen",o[o.Standard=1]="Standard",o[o.Cortana=2]="Cortana",o[o.Letter=3]="Letter",o[o.Custom=4]="Custom",(n=r.DisplayOption||(r.DisplayOption={}))[n.FitToPage=0]="FitToPage",n[n.FitToWidth=1]="FitToWidth",n[n.ActualSize=2]="ActualSize",(l=r.BackgroundType||(r.BackgroundType={}))[l.Default=0]="Default",l[l.Transparent=1]="Transparent",(s=r.VisualContainerDisplayMode||(r.VisualContainerDisplayMode={}))[s.Visible=0]="Visible",s[s.Hidden=1]="Hidden",(d=r.LayoutType||(r.LayoutType={}))[d.Master=0]="Master",d[d.Custom=1]="Custom",d[d.MobilePortrait=2]="MobilePortrait",d[d.MobileLandscape=3]="MobileLandscape",(u=r.SectionVisibility||(r.SectionVisibility={}))[u.AlwaysVisible=0]="AlwaysVisible",u[u.HiddenInViewMode=1]="HiddenInViewMode",(p=r.Permissions||(r.Permissions={}))[p.Read=0]="Read",p[p.ReadWrite=1]="ReadWrite",p[p.Copy=2]="Copy",p[p.Create=4]="Create",p[p.All=7]="All",(c=r.ViewMode||(r.ViewMode={}))[c.View=0]="View",c[c.Edit=1]="Edit",(f=r.TokenType||(r.TokenType={}))[f.Aad=0]="Aad",f[f.Embed=1]="Embed",(v=h=r.FilterType||(r.FilterType={}))[v.Advanced=0]="Advanced",v[v.Basic=1]="Basic",v[v.Unknown=2]="Unknown",v[v.IncludeExclude=3]="IncludeExclude",v[v.RelativeDate=4]="RelativeDate",v[v.TopN=5]="TopN",(y=r.RelativeDateFilterTimeUnit||(r.RelativeDateFilterTimeUnit={}))[y.Days=0]="Days",y[y.Weeks=1]="Weeks",y[y.CalendarWeeks=2]="CalendarWeeks",y[y.Months=3]="Months",y[y.CalendarMonths=4]="CalendarMonths",y[y.Years=5]="Years",y[y.CalendarYears=6]="CalendarYears",(m=r.RelativeDateOperators||(r.RelativeDateOperators={}))[m.InLast=0]="InLast",m[m.InThis=1]="InThis",m[m.InNext=2]="InNext";var g=function(){function t(t,e){this.target=t,this.filterType=e}return t.prototype.toJSON=function(){return{$schema:this.schemaUrl,target:this.target,filterType:this.filterType}},t}(),w=function(i){function o(t,e,r){var a=i.call(this,t,h.Unknown)||this;return a.message=e,a.notSupportedTypeName=r,a.schemaUrl=o.schemaUrl,a}return V(o,i),o.prototype.toJSON=function(){var t=i.prototype.toJSON.call(this);return t.message=this.message,t.notSupportedTypeName=this.notSupportedTypeName,t},o.schemaUrl="http://powerbi.com/product/schema#notSupported",o}(r.Filter=g);r.NotSupportedFilter=w;var b=function(i){function o(t,e,r){var a=i.call(this,t,h.IncludeExclude)||this;return a.values=r,a.isExclude=e,a.schemaUrl=o.schemaUrl,a}return V(o,i),o.prototype.toJSON=function(){var t=i.prototype.toJSON.call(this);return t.isExclude=this.isExclude,t.values=this.values,t},o.schemaUrl="http://powerbi.com/product/schema#includeExclude",o}(g);r.IncludeExcludeFilter=b;var E=function(i){function o(t,e,r){var a=i.call(this,t,h.TopN)||this;return a.operator=e,a.itemCount=r,a.schemaUrl=o.schemaUrl,a}return V(o,i),o.prototype.toJSON=function(){var t=i.prototype.toJSON.call(this);return t.operator=this.operator,t.itemCount=this.itemCount,t},o.schemaUrl="http://powerbi.com/product/schema#topN",o}(g);r.TopNFilter=E;var O=function(n){function l(t,e,r,a,i){var o=n.call(this,t,h.RelativeDate)||this;return o.operator=e,o.timeUnitsCount=r,o.timeUnitType=a,o.includeToday=i,o.schemaUrl=l.schemaUrl,o}return V(l,n),l.prototype.toJSON=function(){var t=n.prototype.toJSON.call(this);return t.operator=this.operator,t.timeUnitsCount=this.timeUnitsCount,t.timeUnitType=this.timeUnitType,t.includeToday=this.includeToday,t},l.schemaUrl="http://powerbi.com/product/schema#relativeDate",l}(g);r.RelativeDateFilter=O;var _=function(o){function n(t,e){for(var r=[],a=2;a<arguments.length;a++)r[a-2]=arguments[a];var i=o.call(this,t,h.Basic)||this;if(i.operator=e,i.schemaUrl=n.schemaUrl,0===r.length&&"All"!==e)throw new Error('values must be a non-empty array unless your operator is "All".');return Array.isArray(r[0])?i.values=r[0]:i.values=r,i}return V(n,o),n.prototype.toJSON=function(){var t=o.prototype.toJSON.call(this);return t.operator=this.operator,t.values=this.values,t},n.schemaUrl="http://powerbi.com/product/schema#basic",n}(g),T=function(s){function t(t,e,r,a){var i=s.call(this,t,e,r)||this;i.keyValues=a;var o=(i.target=t).keys?t.keys.length:0;if(0<o&&!a)throw new Error("You shold pass the values to be filtered for each key. You passed: no values and "+o+" keys");if(0===o&&a&&0<a.length)throw new Error("You passed key values but your target object doesn't contain the keys to be filtered");for(var n=0;n<i.keyValues.length;n++)if(i.keyValues[n]){var l=i.keyValues[n].length;if(l!==o)throw new Error("Each tuple of key values should contain a value for each of the keys. You passed: "+l+" values and "+o+" keys")}return i}return V(t,s),t.prototype.toJSON=function(){var t=s.prototype.toJSON.call(this);return t.keyValues=this.keyValues,t},t}(r.BasicFilter=_);r.BasicFilterWithKeys=T;var P,S,k,A=function(n){function l(t,e){for(var r=[],a=2;a<arguments.length;a++)r[a-2]=arguments[a];var i,o=n.call(this,t,h.Advanced)||this;if(o.schemaUrl=l.schemaUrl,"string"!=typeof e||0===e.length)throw new Error("logicalOperator must be a valid operator, You passed: "+e);if(o.logicalOperator=e,0===(i=Array.isArray(r[0])?r[0]:r).length)throw new Error("conditions must be a non-empty array. You passed: "+r);if(2<i.length)throw new Error("AdvancedFilters may not have more than two conditions. You passed: "+r.length);if(1===i.length&&"And"!==e)throw new Error('Logical Operator must be "And" when there is only one condition provided');return o.conditions=i,o}return V(l,n),l.prototype.toJSON=function(){var t=n.prototype.toJSON.call(this);return t.logicalOperator=this.logicalOperator,t.conditions=this.conditions,t},l.schemaUrl="http://powerbi.com/product/schema#advanced",l}(g);function F(t){if(t.filterType)return t.filterType;var e=t,r=t;return"string"==typeof e.operator&&Array.isArray(e.values)?h.Basic:"string"==typeof r.logicalOperator&&Array.isArray(r.conditions)?h.Advanced:h.Unknown}function R(t){return void 0!==t.table&&void 0!==t.column}r.AdvancedFilter=A,r.isFilterKeyColumnsTarget=function(t){return R(t)&&!!t.keys},r.isBasicFilterWithKeys=function(t){return F(t)===h.Basic&&!!t.keyValues},r.getFilterType=F,r.isMeasure=function(t){return void 0!==t.table&&void 0!==t.measure},r.isColumn=R,r.isHierarchy=function(t){return void 0!==t.table&&void 0!==t.hierarchy&&void 0!==t.hierarchyLevel},(P=r.QnaMode||(r.QnaMode={}))[P.Interactive=0]="Interactive",P[P.ResultOnly=1]="ResultOnly",(S=r.ExportDataType||(r.ExportDataType={}))[S.Summarized=0]="Summarized",S[S.Underlying=1]="Underlying",(k=r.BookmarksPlayMode||(r.BookmarksPlayMode={}))[k.Off=0]="Off",k[k.Presentation=1]="Presentation",r.CommonErrorCodes={TokenExpired:"TokenExpired",NotFound:"PowerBIEntityNotFound",InvalidParameters:"Invalid parameters",LoadReportFailed:"LoadReportFailed",NotAuthorized:"PowerBINotAuthorizedException",FailedToLoadModel:"ExplorationContainer_FailedToLoadModel_DefaultDetails"};var x=function(){function t(t){this.$schema=t}return t.prototype.toJSON=function(){return{$schema:this.$schema}},t}(),q=function(r){function a(t){var e=r.call(this,a.schemaUrl)||this;return e.visualName=t,e}return V(a,r),a.prototype.toJSON=function(){var t=r.prototype.toJSON.call(this);return t.visualName=this.visualName,t},a.schemaUrl="http://powerbi.com/product/schema#visualSelector",a}(r.Selector=x);r.VisualSelector=q;var M=function(r){function t(t){var e=r.call(this,q.schemaUrl)||this;return e.visualType=t,e}return V(t,r),t.prototype.toJSON=function(){var t=r.prototype.toJSON.call(this);return t.visualType=this.visualType,t},t.schemaUrl="http://powerbi.com/product/schema#visualTypeSelector",t}(x);function C(t){var e=t.message;return e||(e=t.path+" is invalid. Not meeting "+t.keyword+" constraint"),{message:e}}r.VisualTypeSelector=M,r.validateVisualSelector=function(t){var e=r.Validators.visualSelectorValidator.validate(t);return e?e.map(C):void 0},r.validateSlicer=function(t){var e=r.Validators.slicerValidator.validate(t);return e?e.map(C):void 0},r.validateSlicerState=function(t){var e=r.Validators.slicerStateValidator.validate(t);return e?e.map(C):void 0},r.validatePlayBookmarkRequest=function(t){var e=r.Validators.playBookmarkRequestValidator.validate(t);return e?e.map(C):void 0},r.validateAddBookmarkRequest=function(t){var e=r.Validators.addBookmarkRequestValidator.validate(t);return e?e.map(C):void 0},r.validateApplyBookmarkByNameRequest=function(t){var e=r.Validators.applyBookmarkByNameRequestValidator.validate(t);return e?e.map(C):void 0},r.validateApplyBookmarkStateRequest=function(t){var e=r.Validators.applyBookmarkStateRequestValidator.validate(t);return e?e.map(C):void 0},r.validateSettings=function(t){var e=r.Validators.settingsValidator.validate(t);return e?e.map(C):void 0},r.validateCustomPageSize=function(t){var e=r.Validators.customPageSizeValidator.validate(t);return e?e.map(C):void 0},r.validateExtension=function(t){var e=r.Validators.extentionValidator.validate(t);return e?e.map(C):void 0},r.validateReportLoad=function(t){var e=r.Validators.reportLoadValidator.validate(t);return e?e.map(C):void 0},r.validateCreateReport=function(t){var e=r.Validators.reportCreateValidator.validate(t);return e?e.map(C):void 0},r.validateDashboardLoad=function(t){var e=r.Validators.dashboardLoadValidator.validate(t);return e?e.map(C):void 0},r.validateTileLoad=function(t){var e=r.Validators.tileLoadValidator.validate(t);return e?e.map(C):void 0},r.validatePage=function(t){var e=r.Validators.pageValidator.validate(t);return e?e.map(C):void 0},r.validateFilter=function(t){var e=r.Validators.filtersValidator.validate(t);return e?e.map(C):void 0},r.validateSaveAsParameters=function(t){var e=r.Validators.saveAsParametersValidator.validate(t);return e?e.map(C):void 0},r.validateLoadQnaConfiguration=function(t){var e=r.Validators.loadQnaValidator.validate(t);return e?e.map(C):void 0},r.validateQnaInterpretInputData=function(t){var e=r.Validators.qnaInterpretInputDataValidator.validate(t);return e?e.map(C):void 0},r.validateExportDataRequest=function(t){var e=r.Validators.exportDataRequestValidator.validate(t);return e?e.map(C):void 0},r.validateVisualHeader=function(t){var e=r.Validators.visualHeaderValidator.validate(t);return e?e.map(C):void 0},r.validateVisualSettings=function(t){var e=r.Validators.visualSettingsValidator.validate(t);return e?e.map(C):void 0}},function(t,e,r){Object.defineProperty(e,"__esModule",{value:!0});var a=r(2),i=r(3),o=r(5),n=r(6),l=r(7),s=r(8),d=r(9),u=r(10),p=r(11),c=r(12),f=r(13),h=r(14),v=r(15),y=r(16),m=r(17),V=r(18),g=r(19),w=r(20),b=r(20),E=r(21),O=r(22),_=r(22),T=r(22);e.Validators={advancedFilterTypeValidator:new a.EnumValidator([0]),advancedFilterValidator:new l.AdvancedFilterValidator,anyArrayValidator:new a.ArrayValidator([new d.AnyOfValidator([new a.StringValidator,new a.NumberValidator,new a.BooleanValidator])]),anyFilterValidator:new d.AnyOfValidator([new l.BasicFilterValidator,new l.AdvancedFilterValidator,new l.IncludeExcludeFilterValidator,new l.NotSupportedFilterValidator,new l.RelativeDateFilterValidator,new l.TopNFilterValidator]),anyValueValidator:new d.AnyOfValidator([new a.StringValidator,new a.NumberValidator,new a.BooleanValidator]),basicFilterTypeValidator:new a.EnumValidator([1]),basicFilterValidator:new l.BasicFilterValidator,playBookmarkRequestValidator:new n.PlayBookmarkRequestValidator,addBookmarkRequestValidator:new n.AddBookmarkRequestValidator,applyBookmarkByNameRequestValidator:new n.ApplyBookmarkByNameRequestValidator,applyBookmarkStateRequestValidator:new n.ApplyBookmarkStateRequestValidator,applyBookmarkValidator:new d.AnyOfValidator([new n.ApplyBookmarkByNameRequestValidator,new n.ApplyBookmarkStateRequestValidator]),backgroundValidator:new a.EnumValidator([0,1]),booleanArrayValidator:new a.BooleanArrayValidator,booleanValidator:new a.BooleanValidator,commandExtensionValidator:new i.CommandExtensionValidator,conditionItemValidator:new l.ConditionItemValidator,customLayoutValidator:new V.CustomLayoutValidator,customLayoutDisplayOptionValidator:new a.EnumValidator([0,1,2]),customPageSizeValidator:new h.CustomPageSizeValidator,dashboardLoadValidator:new c.DashboardLoadValidator,displayStateModeValidator:new a.EnumValidator([0,1]),displayStateValidator:new V.DisplayStateValidator,exportDataRequestValidator:new g.ExportDataRequestValidator,extensionPointsValidator:new i.ExtensionPointsValidator,extentionArrayValidator:new a.ArrayValidator([new i.ExtensionValidator]),extentionValidator:new i.ExtensionValidator,fieldRequiredValidator:new s.FieldRequiredValidator,filterColumnTargetValidator:new l.FilterColumnTargetValidator,filterConditionsValidator:new a.ArrayValidator([new l.ConditionItemValidator]),filterHierarchyTargetValidator:new l.FilterHierarchyTargetValidator,filterMeasureTargetValidator:new l.FilterMeasureTargetValidator,filterTargetValidator:new d.AnyOfValidator([new l.FilterColumnTargetValidator,new l.FilterHierarchyTargetValidator,new l.FilterMeasureTargetValidator]),filtersArrayValidator:new a.ArrayValidator([new d.AnyOfValidator([new l.BasicFilterValidator,new l.AdvancedFilterValidator,new l.RelativeDateFilterValidator])]),filtersValidator:new l.FilterValidator,includeExcludeFilterValidator:new l.IncludeExcludeFilterValidator,includeExludeFilterTypeValidator:new a.EnumValidator([3]),layoutTypeValidator:new a.EnumValidator([0,1,2,3]),loadQnaValidator:new v.LoadQnaValidator,menuExtensionValidator:new i.MenuExtensionValidator,notSupportedFilterTypeValidator:new a.EnumValidator([2]),notSupportedFilterValidator:new l.NotSupportedFilterValidator,numberArrayValidator:new a.NumberArrayValidator,numberValidator:new a.NumberValidator,pageLayoutValidator:new m.MapValidator([new a.StringValidator],[new V.VisualLayoutValidator]),pageSizeTypeValidator:new a.EnumValidator([0,1,2,3,4,5]),pageSizeValidator:new h.PageSizeValidator,pageValidator:new h.PageValidator,pageViewFieldValidator:new h.PageViewFieldValidator,pagesLayoutValidator:new m.MapValidator([new a.StringValidator],[new V.PageLayoutValidator]),permissionsValidator:new a.EnumValidator([0,1,2,4,7]),qnaInterpretInputDataValidator:new v.QnaInterpretInputDataValidator,qnaSettingValidator:new v.QnaSettingsValidator,relativeDateFilterOperatorValidator:new a.EnumValidator([0,1,2]),relativeDateFilterTimeUnitTypeValidator:new a.EnumValidator([0,1,2,3,4,5,6]),relativeDateFilterTypeValidator:new a.EnumValidator([4]),relativeDateFilterValidator:new l.RelativeDateFilterValidator,reportCreateValidator:new p.ReportCreateValidator,reportLoadValidator:new u.ReportLoadValidator,saveAsParametersValidator:new y.SaveAsParametersValidator,settingsValidator:new o.SettingsValidator,slicerValidator:new E.SlicerValidator,slicerStateValidator:new E.SlicerStateValidator,stringArrayValidator:new a.StringArrayValidator,stringValidator:new a.StringValidator,tileLoadValidator:new f.TileLoadValidator,tokenTypeValidator:new a.EnumValidator([0,1]),topNFilterTypeValidator:new a.EnumValidator([5]),topNFilterValidator:new l.TopNFilterValidator,viewModeValidator:new a.EnumValidator([0,1]),visualHeaderSettingsValidator:new O.VisualHeaderSettingsValidator,visualHeaderValidator:new _.VisualHeaderValidator,visualLayoutValidator:new V.VisualLayoutValidator,visualHeadersValidator:new a.ArrayValidator([new _.VisualHeaderValidator]),visualHeaderSelectorValidator:new d.AnyOfValidator([new w.VisualSelectorValidator,new b.VisualTypeSelectorValidator]),visualSelectorValidator:new w.VisualSelectorValidator,visualTypeSelectorValidator:new b.VisualTypeSelectorValidator,visualSettingsValidator:new T.VisualSettingsValidator}},function(t,e){var a,r=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(){}return t.prototype.validate=function(t,e,r){return null==t?null:"object"!=typeof t||Array.isArray(t)?[{message:void 0!==r?r+" must be an object":"input must be an object",path:e,keyword:"type"}]:null},t}();e.ObjectValidator=i;var o=function(){function t(t){this.itemValidators=t}return t.prototype.validate=function(t,e,r){if(null==t)return null;if(!Array.isArray(t))return[{message:r+" property is invalid",path:(e?e+".":"")+r,keyword:"type"}];for(var a=0;a<t.length;a++)for(var i=(e?e+".":"")+r+"."+a,o=0,n=this.itemValidators;o<n.length;o++){if(n[o].validate(t[a],i,r))return[{message:r+" property is invalid",path:(e?e+".":"")+r,keyword:"type"}]}return null},t}();e.ArrayValidator=o;var n=function(){function t(t){this.expectedType=t}return t.prototype.validate=function(t,e,r){return null==t?null:typeof t!==this.expectedType?[{message:r+" must be a "+this.expectedType,path:(e?e+".":"")+r,keyword:"type"}]:null},t}(),l=function(t){function e(){return t.call(this,"string")||this}return r(e,t),e}(e.TypeValidator=n);e.StringValidator=l;var s=function(t){function e(){return t.call(this,"boolean")||this}return r(e,t),e}(n);e.BooleanValidator=s;var d=function(t){function e(){return t.call(this,"number")||this}return r(e,t),e}(n);e.NumberValidator=d;var u=function(){function t(t){this.possibleValues=t}return t.prototype.validate=function(t,e,r){return null==t?null:this.possibleValues.indexOf(t)<0?[{message:r+" property is invalid",path:(e?e+".":"")+r,keyword:"invalid"}]:null},t}(),p=function(a){function t(t){var e=a.call(this,[t])||this;return e.schemaValue=t,e}return r(t,a),t.prototype.validate=function(t,e,r){return a.prototype.validate.call(this,t,e,r)},t}(e.ValueValidator=u);e.SchemaValidator=p;var c=function(i){function t(t){var e=i.call(this)||this;return e.possibleValues=t,e}return r(t,i),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=i.prototype.validate.call(this,t,e,r);return a||new u(this.possibleValues).validate(t,e,r)},t}(d);e.EnumValidator=c;var f=function(a){function t(){return a.call(this,[new l])||this}return r(t,a),t.prototype.validate=function(t,e,r){return a.prototype.validate.call(this,t,e,r)?[{message:r+" must be an array of strings",path:(e?e+".":"")+r,keyword:"type"}]:null},t}(o);e.StringArrayValidator=f;var h=function(a){function t(){return a.call(this,[new s])||this}return r(t,a),t.prototype.validate=function(t,e,r){return a.prototype.validate.call(this,t,e,r)?[{message:r+" must be an array of booleans",path:(e?e+".":"")+r,keyword:"type"}]:null},t}(o);e.BooleanArrayValidator=h;var v=function(a){function t(){return a.call(this,[new d])||this}return r(t,a),t.prototype.validate=function(t,e,r){return a.prototype.validate.call(this,t,e,r)?[{message:r+" must be an array of numbers",path:(e?e+".":"")+r,keyword:"type"}]:null},t}(o);e.NumberArrayValidator=v},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=r(2),s=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"title",validators:[n.Validators.stringValidator]},{field:"icon",validators:[n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.MenuExtensionValidator=s;var d=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"visualContextMenu",validators:[n.Validators.menuExtensionValidator]},{field:"visualOptionsMenu",validators:[n.Validators.menuExtensionValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.ExtensionPointsValidator=d;var u=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"name",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"extend",validators:[n.Validators.fieldRequiredValidator,n.Validators.extensionPointsValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator),p=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"title",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"icon",validators:[n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(e.ExtensionItemValidator=u);e.CommandExtensionValidator=p;var c=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"command",validators:[n.Validators.commandExtensionValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.ExtensionValidator=c},function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t){this.fieldValidatorsPairs=t}return t.prototype.validate=function(t,e,r){if(!this.fieldValidatorsPairs)return null;for(var a=e?e+"."+r:r,i=0,o=this.fieldValidatorsPairs;i<o.length;i++)for(var n=o[i],l=0,s=n.validators;l<s.length;l++){var d=s[l].validate(t[n.field],a,n.field);if(d)return d}return null},t}();e.MultipleFieldsValidator=r},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"filterPaneEnabled",validators:[n.Validators.booleanValidator]},{field:"navContentPaneEnabled",validators:[n.Validators.booleanValidator]},{field:"bookmarksPaneEnabled",validators:[n.Validators.booleanValidator]},{field:"useCustomSaveAsDialog",validators:[n.Validators.booleanValidator]},{field:"extensions",validators:[n.Validators.extentionArrayValidator]},{field:"layoutType",validators:[n.Validators.layoutTypeValidator]},{field:"customLayout",validators:[n.Validators.customLayoutValidator]},{field:"background",validators:[n.Validators.backgroundValidator]},{field:"visualSettings",validators:[n.Validators.visualSettingsValidator]},{field:"hideErrors",validators:[n.Validators.booleanValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(r(2).ObjectValidator);e.SettingsValidator=o},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),s=r(2),o=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"playMode",validators:[n.Validators.fieldRequiredValidator,new s.EnumValidator([0,1])]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(s.ObjectValidator);e.PlayBookmarkRequestValidator=o;var d=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"state",validators:[n.Validators.stringValidator]},{field:"displayName",validators:[n.Validators.stringValidator]},{field:"apply",validators:[n.Validators.booleanValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(s.ObjectValidator);e.AddBookmarkRequestValidator=d;var u=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"name",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(s.ObjectValidator);e.ApplyBookmarkByNameRequestValidator=u;var p=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"state",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(s.ObjectValidator);e.ApplyBookmarkStateRequestValidator=p},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=r(2),s=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"table",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"column",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.FilterColumnTargetValidator=s;var d=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"table",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"hierarchy",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"hierarchyLevel",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.FilterHierarchyTargetValidator=d;var u=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"table",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"measure",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.FilterMeasureTargetValidator=u;var p=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"target",validators:[n.Validators.fieldRequiredValidator,n.Validators.filterTargetValidator]},{field:"operator",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"values",validators:[n.Validators.fieldRequiredValidator,n.Validators.anyArrayValidator]},{field:"filterType",validators:[n.Validators.basicFilterTypeValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.BasicFilterValidator=p;var c=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"target",validators:[n.Validators.fieldRequiredValidator,n.Validators.filterTargetValidator]},{field:"logicalOperator",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"conditions",validators:[n.Validators.fieldRequiredValidator,n.Validators.filterConditionsValidator]},{field:"filterType",validators:[n.Validators.advancedFilterTypeValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.AdvancedFilterValidator=c;var f=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"target",validators:[n.Validators.fieldRequiredValidator,n.Validators.filterTargetValidator]},{field:"operator",validators:[n.Validators.fieldRequiredValidator,n.Validators.relativeDateFilterOperatorValidator]},{field:"timeUnitsCount",validators:[n.Validators.fieldRequiredValidator,n.Validators.numberValidator]},{field:"timeUnitType",validators:[n.Validators.fieldRequiredValidator,n.Validators.relativeDateFilterTimeUnitTypeValidator]},{field:"includeToday",validators:[n.Validators.fieldRequiredValidator,n.Validators.booleanValidator]},{field:"filterType",validators:[n.Validators.relativeDateFilterTypeValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.RelativeDateFilterValidator=f;var h=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"target",validators:[n.Validators.fieldRequiredValidator,n.Validators.filterTargetValidator]},{field:"operator",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"itemCount",validators:[n.Validators.fieldRequiredValidator,n.Validators.numberValidator]},{field:"filterType",validators:[n.Validators.topNFilterTypeValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.TopNFilterValidator=h;var v=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"target",validators:[n.Validators.filterTargetValidator]},{field:"message",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"notSupportedTypeName",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"filterType",validators:[n.Validators.notSupportedFilterTypeValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.NotSupportedFilterValidator=v;var y=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"target",validators:[n.Validators.fieldRequiredValidator,n.Validators.filterTargetValidator]},{field:"isExclude",validators:[n.Validators.fieldRequiredValidator,n.Validators.booleanValidator]},{field:"values",validators:[n.Validators.fieldRequiredValidator,n.Validators.anyArrayValidator]},{field:"filterType",validators:[n.Validators.includeExludeFilterTypeValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.IncludeExcludeFilterValidator=y;var m=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.validate=function(t,e,r){return null==t?null:n.Validators.anyFilterValidator.validate(t,e,r)},e}(o.ObjectValidator);e.FilterValidator=m;var V=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"value",validators:[n.Validators.fieldRequiredValidator,n.Validators.anyValueValidator]},{field:"operator",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.ConditionItemValidator=V},function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(){}return t.prototype.validate=function(t,e,r){return null==t?[{message:r+" is required",path:(e?e+".":"")+r,keyword:"required"}]:null},t}();e.FieldRequiredValidator=r},function(t,e){Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t){this.validators=t}return t.prototype.validate=function(t,e,r){if(null==t)return null;for(var a=!1,i=0,o=this.validators;i<o.length;i++){if(!o[i].validate(t,e,r)){a=!0;break}}return a?null:[{message:r+" property is invalid",path:(e?e+".":"")+r,keyword:"invalid"}]},t}();e.AnyOfValidator=r},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"accessToken",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"id",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"groupId",validators:[n.Validators.stringValidator]},{field:"settings",validators:[n.Validators.settingsValidator]},{field:"pageName",validators:[n.Validators.stringValidator]},{field:"filters",validators:[n.Validators.filtersArrayValidator]},{field:"permissions",validators:[n.Validators.permissionsValidator]},{field:"viewMode",validators:[n.Validators.viewModeValidator]},{field:"tokenType",validators:[n.Validators.tokenTypeValidator]},{field:"bookmark",validators:[n.Validators.applyBookmarkValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(r(2).ObjectValidator);e.ReportLoadValidator=o},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"accessToken",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"datasetId",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"groupId",validators:[n.Validators.stringValidator]},{field:"tokenType",validators:[n.Validators.tokenTypeValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(r(2).ObjectValidator);e.ReportCreateValidator=o},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"accessToken",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"id",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"groupId",validators:[n.Validators.stringValidator]},{field:"pageView",validators:[n.Validators.pageViewFieldValidator]},{field:"tokenType",validators:[n.Validators.tokenTypeValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(r(2).ObjectValidator);e.DashboardLoadValidator=o},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"accessToken",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"id",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"dashboardId",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"groupId",validators:[n.Validators.stringValidator]},{field:"pageView",validators:[n.Validators.stringValidator]},{field:"tokenType",validators:[n.Validators.tokenTypeValidator]},{field:"width",validators:[n.Validators.numberValidator]},{field:"height",validators:[n.Validators.numberValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(r(2).ObjectValidator);e.TileLoadValidator=o},function(t,e,r){var a,n=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var l=r(1),s=r(4),i=r(2),o=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return n(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"type",validators:[l.Validators.fieldRequiredValidator,l.Validators.pageSizeTypeValidator]}];return new s.MultipleFieldsValidator(i).validate(t,e,r)},t}(i.ObjectValidator),d=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return n(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"width",validators:[l.Validators.numberValidator]},{field:"height",validators:[l.Validators.numberValidator]}];return new s.MultipleFieldsValidator(i).validate(t,e,r)},t}(e.PageSizeValidator=o);e.CustomPageSizeValidator=d;var u=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return n(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"name",validators:[l.Validators.fieldRequiredValidator,l.Validators.stringValidator]}];return new s.MultipleFieldsValidator(i).validate(t,e,r)},t}(i.ObjectValidator);e.PageValidator=u;var p=function(i){function t(){return null!==i&&i.apply(this,arguments)||this}return n(t,i),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=i.prototype.validate.call(this,t,e,r);if(a)return a;return["actualSize","fitToWidth","oneColumn"].indexOf(t)<0?[{message:'pageView must be a string with one of the following values: "actualSize", "fitToWidth", "oneColumn"'}]:null},t}(i.StringValidator);e.PageViewFieldValidator=p},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=r(2),s=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"accessToken",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]},{field:"datasetIds",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringArrayValidator]},{field:"question",validators:[n.Validators.stringValidator]},{field:"viewMode",validators:[n.Validators.viewModeValidator]},{field:"settings",validators:[n.Validators.qnaSettingValidator]},{field:"tokenType",validators:[n.Validators.tokenTypeValidator]},{field:"groupId",validators:[n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.LoadQnaValidator=s;var d=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"filterPaneEnabled",validators:[n.Validators.booleanValidator]},{field:"hideErrors",validators:[n.Validators.booleanValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.QnaSettingsValidator=d;var u=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"datasetIds",validators:[n.Validators.stringArrayValidator]},{field:"question",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.QnaInterpretInputDataValidator=u},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"name",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(r(2).ObjectValidator);e.SaveAsParametersValidator=o},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var o=function(u){function t(t,e){var r=u.call(this)||this;return r.keyValidators=t,r.valueValidators=e,r}return i(t,u),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=u.prototype.validate.call(this,t,e,r);if(a)return a;for(var i in t)if(t.hasOwnProperty(i)){for(var o=(e?e+".":"")+r+"."+i,n=0,l=this.keyValidators;n<l.length;n++){if(a=l[n].validate(i,o,r))return a}for(var s=0,d=this.valueValidators;s<d.length;s++){if(a=d[s].validate(t[i],o,r))return a}}return null},t}(r(2).ObjectValidator);e.MapValidator=o},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=r(2),s=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"pageSize",validators:[n.Validators.pageSizeValidator]},{field:"displayOption",validators:[n.Validators.customLayoutDisplayOptionValidator]},{field:"pagesLayout",validators:[n.Validators.pagesLayoutValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.CustomLayoutValidator=s;var d=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"x",validators:[n.Validators.numberValidator]},{field:"y",validators:[n.Validators.numberValidator]},{field:"z",validators:[n.Validators.numberValidator]},{field:"width",validators:[n.Validators.numberValidator]},{field:"height",validators:[n.Validators.numberValidator]},{field:"displayState",validators:[n.Validators.displayStateValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.VisualLayoutValidator=d;var u=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"mode",validators:[n.Validators.displayStateModeValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.DisplayStateValidator=u;var p=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"visualsLayout",validators:[n.Validators.fieldRequiredValidator,n.Validators.pageLayoutValidator]},{field:"defaultLayout",validators:[n.Validators.visualLayoutValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.PageLayoutValidator=p},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(4),l=r(2),o=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"rows",validators:[new l.NumberValidator]},{field:"exportDataType",validators:[new l.EnumValidator([0,1])]}];return new n.MultipleFieldsValidator(i).validate(t,e,r)},t}(l.ObjectValidator);e.ExportDataRequestValidator=o},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=r(2),s=r(2),d=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"$schema",validators:[n.Validators.stringValidator,new s.SchemaValidator("http://powerbi.com/product/schema#visualSelector")]},{field:"visualName",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.VisualSelectorValidator=d;var u=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"$schema",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator,new s.SchemaValidator("http://powerbi.com/product/schema#visualTypeSelector")]},{field:"visualType",validators:[n.Validators.fieldRequiredValidator,n.Validators.stringValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.VisualTypeSelectorValidator=u},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=r(2),s=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"selector",validators:[n.Validators.fieldRequiredValidator,n.Validators.visualSelectorValidator]},{field:"state",validators:[n.Validators.fieldRequiredValidator,n.Validators.slicerStateValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.SlicerValidator=s;var d=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"filters",validators:[n.Validators.filtersArrayValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.SlicerStateValidator=d},function(t,e,r){var a,i=this&&this.__extends||(a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])},function(t,e){function r(){this.constructor=t}a(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)});Object.defineProperty(e,"__esModule",{value:!0});var n=r(1),l=r(4),o=r(2),s=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"visualHeaders",validators:[n.Validators.visualHeadersValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.VisualSettingsValidator=s;var d=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"visible",validators:[n.Validators.booleanValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.VisualHeaderSettingsValidator=d;var u=function(o){function t(){return null!==o&&o.apply(this,arguments)||this}return i(t,o),t.prototype.validate=function(t,e,r){if(null==t)return null;var a=o.prototype.validate.call(this,t,e,r);if(a)return a;var i=[{field:"settings",validators:[n.Validators.fieldRequiredValidator,n.Validators.visualHeaderSettingsValidator]},{field:"selector",validators:[n.Validators.visualHeaderSelectorValidator]}];return new l.MultipleFieldsValidator(i).validate(t,e,r)},t}(o.ObjectValidator);e.VisualHeaderValidator=u}])},t.exports=a()},function(t,e,r){var a=this&&this.__extends||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);function a(){this.constructor=t}t.prototype=null===e?Object.create(e):(a.prototype=e.prototype,new a)},i=r(2),o=r(4),c=r(3),n=r(6),l=r(8),f=r(9),s=function(u){function p(t,e,r,a,i){var o=r,n=o.settings&&o.settings.filterPaneEnabled||!("false"===e.getAttribute(p.filterPaneEnabledAttribute)),l=o.settings&&o.settings.navContentPaneEnabled||!("false"===e.getAttribute(p.navContentPaneEnabledAttribute)),s=c.assign({filterPaneEnabled:n,navContentPaneEnabled:l},o.settings),d=c.assign({settings:s},o);u.call(this,t,e,d,i,a),this.loadPath="/report/load",this.phasedLoadPath="/report/prepare",Array.prototype.push.apply(this.allowedEvents,p.allowedEvents),this.bookmarksManager=new f.BookmarksManager(t,o,this.iframe)}return a(p,u),p.findIdFromEmbedUrl=function(t){var e,r=t.match(/reportId="?([^&]+)"?/);return r&&(e=r[1]),e},p.prototype.render=function(t){return this.service.hpm.post("/report/render",t,{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return t.body}).catch(function(t){throw t.body})},p.prototype.getFilters=function(){return this.service.hpm.get("/report/filters",{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return t.body},function(t){throw t.body})},p.prototype.getId=function(){var t=this.config,e=t.id||this.element.getAttribute(p.reportIdAttribute)||p.findIdFromEmbedUrl(t.embedUrl);if("string"!=typeof e||0===e.length)throw new Error("Report id is required, but it was not found. You must provide an id either as part of embed configuration or as attribute '"+p.reportIdAttribute+"'.");return e},p.prototype.getPages=function(){var e=this;return this.service.hpm.get("/report/pages",{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return t.body.map(function(t){return new n.Page(e,t.name,t.displayName,t.isActive,t.visibility)})},function(t){throw t.body})},p.prototype.page=function(t,e,r,a){return new n.Page(this,t,e,r,a)},p.prototype.print=function(){return this.service.hpm.post("/report/print",null,{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return t.body}).catch(function(t){throw t.body})},p.prototype.removeFilters=function(){return this.setFilters([])},p.prototype.setPage=function(t){var e={name:t,displayName:null,isActive:!0};return this.service.hpm.put("/report/pages/active",e,{uid:this.config.uniqueId},this.iframe.contentWindow).catch(function(t){throw t.body})},p.prototype.setFilters=function(t){return this.service.hpm.put("/report/filters",t,{uid:this.config.uniqueId},this.iframe.contentWindow).catch(function(t){throw t.body})},p.prototype.updateSettings=function(t){return this.service.hpm.patch("/report/settings",t,{uid:this.config.uniqueId},this.iframe.contentWindow).catch(function(t){throw t.body})},p.prototype.validate=function(t){return o.validateReportLoad(t)},p.prototype.populateConfig=function(t){var e=t;!e.settings||e.settings.layoutType!==o.LayoutType.MobileLandscape&&e.settings.layoutType!==o.LayoutType.MobilePortrait||(e.embedUrl=c.addParamToUrl(e.embedUrl,"isMobile","true")),u.prototype.populateConfig.call(this,e);var r=c.assign({},l.Defaults.defaultSettings,e.settings);(e=c.assign({settings:r},e)).id=this.getId(),this.config=e},p.prototype.switchMode=function(t){var e="/report/switchMode/"+("string"==typeof t?t:this.viewModeToString(t));return this.service.hpm.post(e,null,{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return t.body}).catch(function(t){throw t.body})},p.prototype.refresh=function(){return this.service.hpm.post("/report/refresh",null,{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return t.body}).catch(function(t){throw t.body})},p.prototype.viewModeToString=function(t){var e;switch(t){case o.ViewMode.Edit:e="edit";break;case o.ViewMode.View:e="view"}return e},p.allowedEvents=["filtersApplied","pageChanged","commandTriggered","swipeStart","swipeEnd","bookmarkApplied"],p.reportIdAttribute="powerbi-report-id",p.filterPaneEnabledAttribute="powerbi-settings-filter-pane-enabled",p.navContentPaneEnabledAttribute="powerbi-settings-nav-content-pane-enabled",p.typeAttribute="powerbi-type",p.type="Report",p}(i.Embed);e.Report=s},function(t,e,r){var a=r(7),i=r(4),o=function(){function t(t,e,r,a,i){this.report=t,this.name=e,this.displayName=r,this.isActive=a,this.visibility=i}return t.prototype.getFilters=function(){return this.report.service.hpm.get("/report/pages/"+this.name+"/filters",{uid:this.report.config.uniqueId},this.report.iframe.contentWindow).then(function(t){return t.body},function(t){throw t.body})},t.prototype.removeFilters=function(){return this.setFilters([])},t.prototype.setActive=function(){var t={name:this.name,displayName:null,isActive:!0};return this.report.service.hpm.put("/report/pages/active",t,{uid:this.report.config.uniqueId},this.report.iframe.contentWindow).catch(function(t){throw t.body})},t.prototype.setFilters=function(t){return this.report.service.hpm.put("/report/pages/"+this.name+"/filters",t,{uid:this.report.config.uniqueId},this.report.iframe.contentWindow).catch(function(t){throw t.body})},t.prototype.getVisuals=function(){var e=this;return this.report.service.hpm.get("/report/pages/"+this.name+"/visuals",{uid:this.report.config.uniqueId},this.report.iframe.contentWindow).then(function(t){return t.body.map(function(t){return new a.VisualDescriptor(e,t.name,t.title,t.type,t.layout)})},function(t){throw t.body})},t.prototype.hasLayout=function(t){var e=i.LayoutType[t];return this.report.service.hpm.get("/report/pages/"+this.name+"/layoutTypes/"+e,{uid:this.report.config.uniqueId},this.report.iframe.contentWindow).then(function(t){return t.body},function(t){throw t.body})},t}();e.Page=o},function(t,e){var r=function(){function t(t,e,r,a,i){this.name=e,this.title=r,this.type=a,this.layout=i,this.page=t}return t.prototype.getFilters=function(){return this.page.report.service.hpm.get("/report/pages/"+this.page.name+"/visuals/"+this.name+"/filters",{uid:this.page.report.config.uniqueId},this.page.report.iframe.contentWindow).then(function(t){return t.body},function(t){throw t.body})},t.prototype.removeFilters=function(){return this.setFilters([])},t.prototype.setFilters=function(t){return this.page.report.service.hpm.put("/report/pages/"+this.page.name+"/visuals/"+this.name+"/filters",t,{uid:this.page.report.config.uniqueId},this.page.report.iframe.contentWindow).catch(function(t){throw t.body})},t.prototype.exportData=function(t,e){var r={rows:e,exportDataType:t};return this.page.report.service.hpm.post("/report/pages/"+this.page.name+"/visuals/"+this.name+"/exportData",r,{uid:this.page.report.config.uniqueId},this.page.report.iframe.contentWindow).then(function(t){return t.body},function(t){throw t.body})},t.prototype.setSlicerState=function(t){return this.page.report.service.hpm.put("/report/pages/"+this.page.name+"/visuals/"+this.name+"/slicer",t,{uid:this.page.report.config.uniqueId},this.page.report.iframe.contentWindow).catch(function(t){throw t.body})},t.prototype.getSlicerState=function(){return this.page.report.service.hpm.get("/report/pages/"+this.page.name+"/visuals/"+this.name+"/slicer",{uid:this.page.report.config.uniqueId},this.page.report.iframe.contentWindow).then(function(t){return t.body},function(t){throw t.body})},t}();e.VisualDescriptor=r},function(t,e){var r=function(){function t(){}return t.defaultSettings={filterPaneEnabled:!0},t.defaultQnaSettings={filterPaneEnabled:!1},t}();e.Defaults=r},function(t,e){var r=function(){function t(t,e,r){this.service=t,this.config=e,this.iframe=r}return t.prototype.getBookmarks=function(){return this.service.hpm.get("/report/bookmarks",{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return t.body},function(t){throw t.body})},t.prototype.apply=function(t){var e={name:t};return this.service.hpm.post("/report/bookmarks/applyByName",e,{uid:this.config.uniqueId},this.iframe.contentWindow).catch(function(t){throw t.body})},t.prototype.play=function(t){var e={playMode:t};return this.service.hpm.post("/report/bookmarks/play",e,{uid:this.config.uniqueId},this.iframe.contentWindow).catch(function(t){throw t.body})},t.prototype.capture=function(){return this.service.hpm.post("/report/bookmarks/capture",null,{uid:this.config.uniqueId},this.iframe.contentWindow).then(function(t){return t.body},function(t){throw t.body})},t.prototype.applyState=function(t){var e={state:t};return this.service.hpm.post("/report/bookmarks/applyState",e,{uid:this.config.uniqueId},this.iframe.contentWindow).catch(function(t){throw t.body})},t}();e.BookmarksManager=r},function(t,e,r){var a=this&&this.__extends||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);function a(){this.constructor=t}t.prototype=null===e?Object.create(e):(a.prototype=e.prototype,new a)},o=r(4),i=r(2),n=r(3),l=r(8),s=function(i){function e(t,e,r,a){i.call(this,t,e,r,void 0,a)}return a(e,i),e.prototype.getId=function(){var t=this.createConfig&&this.createConfig.datasetId?this.createConfig.datasetId:e.findIdFromEmbedUrl(this.config.embedUrl);if("string"!=typeof t||0===t.length)throw new Error("Dataset id is required, but it was not found. You must provide an id either as part of embed configuration.");return t},e.prototype.validate=function(t){return o.validateCreateReport(t)},e.prototype.populateConfig=function(t){i.prototype.populateConfig.call(this,t);var e=n.assign({},l.Defaults.defaultSettings,t.settings);this.config=n.assign({settings:e},t);var r=this.config;this.createConfig={datasetId:r.datasetId||this.getId(),accessToken:r.accessToken,tokenType:r.tokenType,settings:e,groupId:r.groupId}},e.findIdFromEmbedUrl=function(t){var e,r=t.match(/datasetId="?([^&]+)"?/);return r&&(e=r[1]),e},e}(i.Embed);e.Create=s},function(t,e,r){var a=this&&this.__extends||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);function a(){this.constructor=t}t.prototype=null===e?Object.create(e):(a.prototype=e.prototype,new a)},i=r(2),n=r(4),l=r(3),s=r(8),o=function(i){function o(t,e,r,a){i.call(this,t,e,r,void 0,a),this.loadPath="/dashboard/load",this.phasedLoadPath="/dashboard/prepare",Array.prototype.push.apply(this.allowedEvents,o.allowedEvents)}return a(o,i),o.findIdFromEmbedUrl=function(t){var e,r=t.match(/dashboardId="?([^&]+)"?/);return r&&(e=r[1]),e},o.prototype.getId=function(){var t=this.config,e=t.id||this.element.getAttribute(o.dashboardIdAttribute)||o.findIdFromEmbedUrl(t.embedUrl);if("string"!=typeof e||0===e.length)throw new Error("Dashboard id is required, but it was not found. You must provide an id either as part of embed configuration or as attribute '"+o.dashboardIdAttribute+"'.");return e},o.prototype.validate=function(t){var e=t,r=n.validateDashboardLoad(e);return r||this.ValidatePageView(e.pageView)},o.prototype.populateConfig=function(t){var e=t;i.prototype.populateConfig.call(this,e);var r=l.assign({},s.Defaults.defaultSettings,e.settings);(e=l.assign({settings:r},e)).id=this.getId(),this.config=e},o.prototype.ValidatePageView=function(t){if(t&&"fitToWidth"!==t&&"oneColumn"!==t&&"actualSize"!==t)return[{message:"pageView must be one of the followings: fitToWidth, oneColumn, actualSize"}]},o.allowedEvents=["tileClicked","error"],o.dashboardIdAttribute="powerbi-dashboard-id",o.typeAttribute="powerbi-type",o.type="Dashboard",o}(i.Embed);e.Dashboard=o},function(t,e,r){var a=this&&this.__extends||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);function a(){this.constructor=t}t.prototype=null===e?Object.create(e):(a.prototype=e.prototype,new a)},i=r(4),o=r(2),l=r(3),s=r(8),n=function(o){function n(t,e,r,a){var i=r;o.call(this,t,e,i,void 0,a),this.loadPath="/tile/load",Array.prototype.push.apply(this.allowedEvents,n.allowedEvents)}return a(n,o),n.prototype.getId=function(){var t=this.config.id||n.findIdFromEmbedUrl(this.config.embedUrl);if("string"!=typeof t||0===t.length)throw new Error("Tile id is required, but it was not found. You must provide an id either as part of embed configuration.");return t},n.prototype.validate=function(t){var e=t;return i.validateTileLoad(e)},n.prototype.populateConfig=function(t){var e=t;o.prototype.populateConfig.call(this,e);var r=l.assign({},s.Defaults.defaultSettings,e.settings);(e=l.assign({settings:r},e)).id=this.getId(),this.config=e},n.findIdFromEmbedUrl=function(t){var e,r=t.match(/tileId="?([^&]+)"?/);return r&&(e=r[1]),e},n.type="Tile",n.allowedEvents=["tileClicked","tileLoaded"],n}(o.Embed);e.Tile=n},function(t,e,r){var a=this&&this.__extends||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);function a(){this.constructor=t}t.prototype=null===e?Object.create(e):(a.prototype=e.prototype,new a)},n=r(4),i=function(i){function o(t,e,r,a){i.call(this,t,e,r,void 0,a),this.loadPath="/qna/load",this.phasedLoadPath="/qna/prepare",Array.prototype.push.apply(this.allowedEvents,o.allowedEvents)}return a(o,i),o.prototype.getId=function(){return null},o.prototype.setQuestion=function(t){var e={question:t};return this.service.hpm.post("/qna/interpret",e,{uid:this.config.uniqueId},this.iframe.contentWindow).catch(function(t){throw t.body})},o.prototype.validate=function(t){return n.validateLoadQnaConfiguration(t)},o.type="Qna",o.allowedEvents=["loaded","visualRendered"],o}(r(2).Embed);e.Qna=i},function(t,e,r){var a=this&&this.__extends||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);function a(){this.constructor=t}t.prototype=null===e?Object.create(e):(a.prototype=e.prototype,new a)},s=r(4),i=function(l){function e(t,e,r,a,i){l.call(this,t,e,r,a,i)}return a(e,l),e.prototype.load=function(t,e){var r=t;if("string"!=typeof r.pageName||0===r.pageName.length)throw new Error("Page name is required when embedding a visual.");if("string"!=typeof r.visualName||0===r.visualName.length)throw new Error("Visual name is required, but it was not found. You must provide a visual name as part of embed configuration.");var a=r.width?r.width:this.iframe.offsetWidth,i=r.height?r.height:this.iframe.offsetHeight,o={type:s.PageSizeType.Custom,width:a,height:i},n={};return n[r.pageName]={defaultLayout:{displayState:{mode:s.VisualContainerDisplayMode.Hidden}},visualsLayout:{}},n[r.pageName].visualsLayout[r.visualName]={displayState:{mode:s.VisualContainerDisplayMode.Visible},x:1,y:1,z:1,width:o.width,height:o.height},r.settings=r.settings||{},r.settings.filterPaneEnabled=!1,r.settings.navContentPaneEnabled=!1,r.settings.layoutType=s.LayoutType.Custom,r.settings.customLayout={displayOption:s.DisplayOption.FitToPage,pageSize:o,pagesLayout:n},l.prototype.load.call(this,r,e)},e.prototype.getPages=function(){throw e.GetPagesNotSupportedError},e.prototype.setPage=function(t){throw e.SetPageNotSupportedError},e.prototype.getFilters=function(){throw e.GetFiltersNotSupportedError},e.prototype.setFilters=function(t){throw e.SetFiltersNotSupportedError},e.type="visual",e.GetFiltersNotSupportedError="Getting visual level filters is not supported.",e.SetFiltersNotSupportedError="Setting visual level filters is not supported.",e.GetPagesNotSupportedError="Get pages is not supported while embedding a visual.",e.SetPageNotSupportedError="Set page is not supported while embedding a visual.",e}(r(5).Report);e.Visual=i},function(t,e,r){var i=r(16),a=r(17),o=r(18),n=r(19);e.hpmFactory=function(t,e,r,a){return void 0===r&&(r=i.default.version),void 0===a&&(a=i.default.type),new o.HttpPostMessage(t,{"x-sdk-type":a,"x-sdk-version":r},e)},e.wpmpFactory=function(t,e,r){return new a.WindowPostMessageProxy({processTrackingProperties:{addTrackingProperties:o.HttpPostMessage.addTrackingProperties,getTrackingProperties:o.HttpPostMessage.getTrackingProperties},isErrorMessage:o.HttpPostMessage.isErrorMessage,suppressWarnings:!0,name:t,logMessages:e,eventSourceOverrideWindow:r})},e.routerFactory=function(t){return new n.Router(t)}},function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.default={version:"2.6.4",type:"js"}},function(t,e,r){var a;a=function(){return function(r){var a={};function i(t){if(a[t])return a[t].exports;var e=a[t]={exports:{},id:t,loaded:!1};return r[t].call(e.exports,e,e.exports,i),e.loaded=!0,e.exports}return i.m=r,i.c=a,i.p="",i(0)}([function(t,e){"use strict";var r=function(){function i(t){var e=this;void 0===t&&(t={processTrackingProperties:{addTrackingProperties:i.defaultAddTrackingProperties,getTrackingProperties:i.defaultGetTrackingProperties},isErrorMessage:i.defaultIsErrorMessage,receiveWindow:window,name:i.createRandomString()}),this.pendingRequestPromises={},this.addTrackingProperties=t.processTrackingProperties&&t.processTrackingProperties.addTrackingProperties||i.defaultAddTrackingProperties,this.getTrackingProperties=t.processTrackingProperties&&t.processTrackingProperties.getTrackingProperties||i.defaultGetTrackingProperties,this.isErrorMessage=t.isErrorMessage||i.defaultIsErrorMessage,this.receiveWindow=t.receiveWindow||window,this.name=t.name||i.createRandomString(),this.logMessages=t.logMessages||!1,this.eventSourceOverrideWindow=t.eventSourceOverrideWindow,this.suppressWarnings=t.suppressWarnings||!1,this.logMessages&&console.log("new WindowPostMessageProxy created with name: "+this.name+" receiving on window: "+this.receiveWindow.document.title),this.handlers=[],this.windowMessageHandler=function(t){return e.onMessageReceived(t)},this.start()}return i.defaultAddTrackingProperties=function(t,e){return t[i.messagePropertyName]=e,t},i.defaultGetTrackingProperties=function(t){return t[i.messagePropertyName]},i.defaultIsErrorMessage=function(t){return!!t.error},i.createDeferred=function(){var r={resolve:null,reject:null,promise:null},t=new Promise(function(t,e){r.resolve=t,r.reject=e});return r.promise=t,r},i.createRandomString=function(){return(Math.random()+1).toString(36).substring(7)},i.prototype.addHandler=function(t){this.handlers.push(t)},i.prototype.removeHandler=function(t){var e=this.handlers.indexOf(t);if(-1===e)throw new Error("You attempted to remove a handler but no matching handler was found.");this.handlers.splice(e,1)},i.prototype.start=function(){this.receiveWindow.addEventListener("message",this.windowMessageHandler)},i.prototype.stop=function(){this.receiveWindow.removeEventListener("message",this.windowMessageHandler)},i.prototype.postMessage=function(t,e){var r={id:i.createRandomString()};this.addTrackingProperties(e,r),this.logMessages&&(console.log(this.name+" Posting message:"),console.log(JSON.stringify(e,null,"  "))),t.postMessage(e,"*");var a=i.createDeferred();return(this.pendingRequestPromises[r.id]=a).promise},i.prototype.sendResponse=function(t,e,r){this.addTrackingProperties(e,r),this.logMessages&&(console.log(this.name+" Sending response:"),console.log(JSON.stringify(e,null,"  "))),t.postMessage(e,"*")},i.prototype.onMessageReceived=function(t){var a=this;this.logMessages&&(console.log(this.name+" Received message:"),console.log("type: "+t.type),console.log(JSON.stringify(t.data,null,"  ")));var i=this.eventSourceOverrideWindow||t.source,o=t.data;if("object"==typeof o){var n,e;try{n=this.getTrackingProperties(o)}catch(t){this.suppressWarnings||console.warn("Proxy("+this.name+"): Error occurred when attempting to get tracking properties from incoming message:",JSON.stringify(o,null,"  "),"Error: ",t)}if(n&&(e=this.pendingRequestPromises[n.id]),e){var r=!0;try{r=this.isErrorMessage(o)}catch(t){console.warn("Proxy("+this.name+") Error occurred when trying to determine if message is consider an error response. Message: ",JSON.stringify(o,null,""),"Error: ",t)}r?e.reject(o):e.resolve(o),delete this.pendingRequestPromises[n.id]}else{this.handlers.some(function(t){var e=!1;try{e=t.test(o)}catch(t){a.suppressWarnings||console.warn("Proxy("+a.name+"): Error occurred when handler was testing incoming message:",JSON.stringify(o,null,"  "),"Error: ",t)}if(e){var r=void 0;try{r=Promise.resolve(t.handle(o))}catch(t){a.suppressWarnings||console.warn("Proxy("+a.name+"): Error occurred when handler was processing incoming message:",JSON.stringify(o,null,"  "),"Error: ",t),r=Promise.resolve()}return r.then(function(t){if(!t){var e="Handler for message: "+JSON.stringify(o,null,"  ")+" did not return a response message. The default response message will be returned instead.";a.suppressWarnings||console.warn("Proxy("+a.name+"): "+e),t={warning:e}}a.sendResponse(i,t,n)}),!0}})||this.suppressWarnings||console.warn("Proxy("+this.name+") did not handle message. Handlers: "+this.handlers.length+"  Message: "+JSON.stringify(o,null,"")+".")}}else this.suppressWarnings||console.warn("Proxy("+this.name+"): Received message that was not an object. Discarding message")},i.messagePropertyName="windowPostMessageProxy",i}();e.WindowPostMessageProxy=r}])},t.exports=a()},function(t,e,r){var a;a=function(){return function(r){var a={};function i(t){if(a[t])return a[t].exports;var e=a[t]={exports:{},id:t,loaded:!1};return r[t].call(e.exports,e,e.exports,i),e.loaded=!0,e.exports}return i.m=r,i.c=a,i.p="",i(0)}([function(t,e){"use strict";var r=function(){function t(t,e,r){void 0===e&&(e={}),this.defaultHeaders=e,this.defaultTargetWindow=r,this.windowPostMessageProxy=t}return t.addTrackingProperties=function(t,e){return t.headers=t.headers||{},e&&e.id&&(t.headers.id=e.id),t},t.getTrackingProperties=function(t){return{id:t.headers&&t.headers.id}},t.isErrorMessage=function(t){return"number"==typeof(t&&t.statusCode)&&!(200<=t.statusCode&&t.statusCode<300)},t.prototype.get=function(t,e,r){return void 0===e&&(e={}),void 0===r&&(r=this.defaultTargetWindow),this.send({method:"GET",url:t,headers:e},r)},t.prototype.post=function(t,e,r,a){return void 0===r&&(r={}),void 0===a&&(a=this.defaultTargetWindow),this.send({method:"POST",url:t,headers:r,body:e},a)},t.prototype.put=function(t,e,r,a){return void 0===r&&(r={}),void 0===a&&(a=this.defaultTargetWindow),this.send({method:"PUT",url:t,headers:r,body:e},a)},t.prototype.patch=function(t,e,r,a){return void 0===r&&(r={}),void 0===a&&(a=this.defaultTargetWindow),this.send({method:"PATCH",url:t,headers:r,body:e},a)},t.prototype.delete=function(t,e,r,a){return void 0===e&&(e=null),void 0===r&&(r={}),void 0===a&&(a=this.defaultTargetWindow),this.send({method:"DELETE",url:t,headers:r,body:e},a)},t.prototype.send=function(t,e){if(void 0===e&&(e=this.defaultTargetWindow),t.headers=this.assign({},this.defaultHeaders,t.headers),!e)throw new Error("target window is not provided.  You must either provide the target window explicitly as argument to request, or specify default target window when constructing instance of this class.");return this.windowPostMessageProxy.postMessage(e,t)},t.prototype.assign=function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(null==t)throw new TypeError("Cannot convert undefined or null to object");var a=Object(t);return e.forEach(function(t){if(null!=t)for(var e in t)Object.prototype.hasOwnProperty.call(t,e)&&(a[e]=t[e])}),a},t}();e.HttpPostMessage=r}])},t.exports=a()},function(t,e,r){var a;a=function(){return function(r){var a={};function i(t){if(a[t])return a[t].exports;var e=a[t]={exports:{},id:t,loaded:!1};return r[t].call(e.exports,e,e.exports,i),e.loaded=!0,e.exports}return i.m=r,i.c=a,i.p="",i(0)}([function(t,e,r){"use strict";var a=r(1),i=function(){function t(t){this.handlers=t,this.getRouteRecognizer=new a,this.patchRouteRecognizer=new a,this.postRouteRecognizer=new a,this.putRouteRecognizer=new a,this.deleteRouteRecognizer=new a}return t.prototype.get=function(t,e){return this.registerHandler(this.getRouteRecognizer,"GET",t,e),this},t.prototype.patch=function(t,e){return this.registerHandler(this.patchRouteRecognizer,"PATCH",t,e),this},t.prototype.post=function(t,e){return this.registerHandler(this.postRouteRecognizer,"POST",t,e),this},t.prototype.put=function(t,e){return this.registerHandler(this.putRouteRecognizer,"PUT",t,e),this},t.prototype.delete=function(t,e){return this.registerHandler(this.deleteRouteRecognizer,"DELETE",t,e),this},t.prototype.registerHandler=function(a,i,t,r){a.add([{path:t,handler:function(t){var e=new o;return Promise.resolve(r(t,e)).then(function(t){return e})}}]);var e={test:function(t){if(t.method!==i)return!1;var e=a.recognize(t.url);if(void 0===e)return!1;var r=e[0];return t.params=r.params,t.queryParams=e.queryParams,t.handler=r.handler,!0},handle:function(t){return t.handler(t)}};this.handlers.addHandler(e)},t}();e.Router=i;var o=function(){function t(){this.statusCode=200,this.headers={},this.body=null}return t.prototype.send=function(t,e){this.statusCode=t,this.body=e},t}();e.Response=o},function(t,V,g){var w;(function(o){(function(){"use strict";function n(t,e,r){this.path=t,this.matcher=e,this.delegate=r}function l(t){this.routes={},this.children={},this.target=t}function s(a,i,o){return function(t,e){var r=a+t;if(!e)return new n(a+t,i,o);e(s(r,i,o))}}function d(t,e,r){for(var a=0,i=0;i<t.length;i++)a+=t[i].path.length;var o={path:e=e.substr(a),handler:r};t.push(o)}n.prototype={to:function(t,e){var r=this.delegate;if(r&&r.willAddRoute&&(t=r.willAddRoute(this.matcher.target,t)),this.matcher.add(this.path,t),e){if(0===e.length)throw new Error("You must have an argument in the function passed to `to`");this.matcher.addChild(this.path,t,e,this.delegate)}return this}},l.prototype={add:function(t,e){this.routes[t]=e},addChild:function(t,e,r,a){var i=new l(e),o=s(t,this.children[t]=i,a);a&&a.contextEntered&&a.contextEntered(e,o),r(o)}};var t=new RegExp("(\\"+["/",".","*","+","?","|","(",")","[","]","{","}","\\"].join("|\\")+")","g");function u(t){this.string=t}function p(t){this.name=t}function c(t){this.name=t}function y(){}function m(t,e,r){"/"===t.charAt(0)&&(t=t.substr(1));var a=t.split("/"),i=new Array(a.length);r.val="";for(var o=0;o<a.length;o++){var n,l=a[o];(n=l.match(/^:([^\/]+)$/))?(i[o]=new p(n[1]),e.push(n[1]),r.val+="3"):(n=l.match(/^\*([^\/]+)$/))?(i[o]=new c(n[1]),r.val+="1",e.push(n[1])):""===l?(i[o]=new y,r.val+="2"):(i[o]=new u(l),r.val+="4")}return r.val=+r.val,i}function r(t){this.charSpec=t,this.nextStates=[],this.charSpecs={},this.regex=void 0,this.handlers=void 0,this.specificity=void 0}function f(t,e){for(var r=[],a=0,i=t.length;a<i;a++){var o=t[a];r=r.concat(o.match(e))}return r}u.prototype={eachChar:function(t){for(var e,r=this.string,a=0;a<r.length;a++)e=r.charAt(a),t=t.put({invalidChars:void 0,repeat:!1,validChars:e});return t},regex:function(){return this.string.replace(t,"\\$1")},generate:function(){return this.string}},p.prototype={eachChar:function(t){return t.put({invalidChars:"/",repeat:!0,validChars:void 0})},regex:function(){return"([^/]+)"},generate:function(t){return t[this.name]}},c.prototype={eachChar:function(t){return t.put({invalidChars:"",repeat:!0,validChars:void 0})},regex:function(){return"(.+)"},generate:function(t){return t[this.name]}},y.prototype={eachChar:function(t){return t},regex:function(){return""},generate:function(){return""}},r.prototype={get:function(t){if(this.charSpecs[t.validChars])return this.charSpecs[t.validChars];for(var e=this.nextStates,r=0;r<e.length;r++){var a=e[r],i=a.charSpec.validChars===t.validChars;if(i=i&&a.charSpec.invalidChars===t.invalidChars)return this.charSpecs[t.validChars]=a}},put:function(t){var e;return(e=this.get(t))||(e=new r(t),this.nextStates.push(e),t.repeat&&e.nextStates.push(e)),e},match:function(t){for(var e,r,a,i=this.nextStates,o=[],n=0;n<i.length;n++)void 0!==(a=(r=(e=i[n]).charSpec).validChars)?-1!==a.indexOf(t)&&o.push(e):void 0!==(a=r.invalidChars)&&-1===a.indexOf(t)&&o.push(e);return o}};var e=Object.create||function(t){function e(){}return e.prototype=t,new e};function h(t){this.queryParams=t||{}}function v(t){var e;t=t.replace(/\+/gm,"%20");try{e=decodeURIComponent(t)}catch(t){e=""}return e}h.prototype=e({splice:Array.prototype.splice,slice:Array.prototype.slice,push:Array.prototype.push,length:0,queryParams:null});var a=function(){this.rootState=new r,this.names={}};(a.prototype={add:function(t,e){for(var r,a=this.rootState,i="^",o={},n=new Array(t.length),l=[],s=!0,d=0;d<t.length;d++){var u=t[d],p=[],c=m(u.path,p,o);l=l.concat(c);for(var f=0;f<c.length;f++){var h=c[f];h instanceof y||(s=!1,a=a.put({invalidChars:void 0,repeat:!1,validChars:"/"}),i+="/",a=h.eachChar(a),i+=h.regex())}var v={handler:u.handler,names:p};n[d]=v}s&&(a=a.put({invalidChars:void 0,repeat:!1,validChars:"/"}),i+="/"),a.handlers=n,a.regex=new RegExp(i+"$"),a.specificity=o,(r=e&&e.as)&&(this.names[r]={segments:l,handlers:n})},handlersFor:function(t){var e=this.names[t];if(!e)throw new Error("There is no route named "+t);for(var r=new Array(e.handlers.length),a=0;a<e.handlers.length;a++)r[a]=e.handlers[a];return r},hasRoute:function(t){return!!this.names[t]},generate:function(t,e){var r=this.names[t],a="";if(!r)throw new Error("There is no route named "+t);for(var i=r.segments,o=0;o<i.length;o++){var n=i[o];n instanceof y||(a+="/",a+=n.generate(e))}return"/"!==a.charAt(0)&&(a="/"+a),e&&e.queryParams&&(a+=this.generateQueryString(e.queryParams,r.handlers)),a},generateQueryString:function(t,e){var r,a=[],i=[];for(var o in t)t.hasOwnProperty(o)&&i.push(o);i.sort();for(var n=0;n<i.length;n++){var l=t[o=i[n]];if(null!=l){var s=encodeURIComponent(o);if(r=l,"[object Array]"===Object.prototype.toString.call(r))for(var d=0;d<l.length;d++){var u=o+"[]="+encodeURIComponent(l[d]);a.push(u)}else s+="="+encodeURIComponent(l),a.push(s)}}return 0===a.length?"":"?"+a.join("&")},parseQueryString:function(t){for(var e=t.split("&"),r={},a=0;a<e.length;a++){var i,o=e[a].split("="),n=v(o[0]),l=n.length,s=!1;1===o.length?i="true":(2<l&&"[]"===n.slice(l-2)&&(s=!0,r[n=n.slice(0,l-2)]||(r[n]=[])),i=o[1]?v(o[1]):""),s?r[n].push(i):r[n]=i}return r},recognize:function(t){var e,r,a,i=[this.rootState],o={},n=!1;if(-1!==(a=t.indexOf("?"))){var l=t.substr(a+1,t.length);t=t.substr(0,a),o=this.parseQueryString(l)}for("/"!==(t=decodeURI(t)).charAt(0)&&(t="/"+t),1<(e=t.length)&&"/"===t.charAt(e-1)&&(t=t.substr(0,e-1),n=!0),r=0;r<t.length&&(i=f(i,t.charAt(r))).length;r++);var s=[];for(r=0;r<i.length;r++)i[r].handlers&&s.push(i[r]);i=s.sort(function(t,e){return e.specificity.val-t.specificity.val});var d=s[0];if(d&&d.handlers)return n&&"(.+)$"===d.regex.source.slice(-5)&&(t+="/"),function(t,e,r){var a=t.handlers,i=t.regex,o=e.match(i),n=1,l=new h(r);l.length=a.length;for(var s=0;s<a.length;s++){for(var d=a[s],u=d.names,p={},c=0;c<u.length;c++)p[u[c]]=o[n++];l[s]={handler:d.handler,params:p,isDynamic:!!u.length}}return l}(d,t,o)}}).map=function(t,e){var r=new l;t(s("",r,this.delegate)),function t(e,r,a,i){var o=r.routes;for(var n in o)if(o.hasOwnProperty(n)){var l=e.slice();d(l,n,o[n]),r.children[n]?t(l,r.children[n],a,i):a.call(i,l)}}([],r,function(t){e?e(this,t):this.add(t)},this)},a.VERSION="0.1.11";var i=a;g(3).amd?void 0===(w=function(){return i}.call(V,g,V,o))||(o.exports=w):void 0!==o&&o.exports?o.exports=i:void 0!==this&&(this.RouteRecognizer=i)}).call(this)}).call(V,g(2)(t))},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children=[],t.webpackPolyfill=1),t}},function(t,e){t.exports=function(){throw new Error("define cannot be used indirect")}}])},t.exports=a()}])});

$(document).ready(function()
{
	// Initialize.
	if ($(".powerBiReportContent").length > 0)
	{
		$(".powerBiReportContent select").getEmbedReportInfo();
	}

	if ($("#cms #optionsTabContent .powerBiOptions").length > 0)
	{
		$("#cms #optionsTabContent .powerBiGroups select").getPowerBiGroups();
	}

	if (typeof Sys !== "undefined" && typeof Sys.WebForms !== "undefined")
	{
		// After AJAX call.
		Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, e)
		{
			$("#cms #optionsTabContent .powerBiGroups select").getPowerBiGroups();
		});
	}
});

$.fn.getPowerBiGroups = function()
{
	var groupSelect = $(this);
	var selectedGroup = $(".powerBiSelectedGroup");
	var apiErrors = $(".powerBIError");

	if (groupSelect.length > 0)
	{
		// Reset & loader.
		groupSelect.find("option").remove();
		groupSelect.append($("<option />").text(settings.various.loadingText));

		$.ajax(
			{
				url: "/api/powerbi/getgroups",
				data:
				{
					token: $("input[name='__RequestVerificationToken']").val()
				}
			})
			.done(function (data) {
				if (data.status === 'error') {
					apiErrors.text(data.message);
					apiErrors.parent().removeClass("hide");
					return;
				}

				if (data.message === '[]') {
					groupSelect.find("option:first").text(settings.liveSearch.noResultsText);
					groupSelect.parent().removeClass("hide");
					return;
				}

				var parsedData = JSON.parse(data.message);

				parsedData.forEach(function (group) {
					var option = $("<option />");
					option.text(group.Key);
					option.val(group.Value);

					groupSelect.append(option);
				});

				if (groupSelect.find("option").length > 1) {
					groupSelect.unbind("change").change(function () {
						selectedGroup.val($(this).val());
						$(this).getPowerBiReports(false);
					});

					if (selectedGroup.val() !== "") {
						// Set selected group.
						groupSelect.val(selectedGroup.val());
						groupSelect.getPowerBiReports(true);
					}

					// Remove loader & show select.
					groupSelect.find("option:first").remove();
					groupSelect.parent().removeClass("hide");

					// Init. 
					groupSelect.change();
				}
			}).fail(function (data) {
				if (data.status === 'error') {
					apiErrors.text(data.message);
					apiErrors.parent().removeClass("hide");
					return;
				}
			});
	}
};

$.fn.getPowerBiReports = function(firstRun)
{
	var group = $(this);
	var reportSelect =  $(".field.powerBiReports select");
	var selectedReport = $(".powerBiSelectedReport");
	var apiErrors = $(".powerBIError");

	if (group.length > 0 && group.val() !== "")
	{
		// Reset & loader.
		reportSelect.find("option").remove();
		reportSelect.append($("<option />").text(settings.various.loadingText));

		$.ajax(
		{
			url: "/api/powerbi/getreports",
			data:
			{
				groupId: group.val(),
				token: $("input[name='__RequestVerificationToken']").val()
			}
		})
		.done(function(data)
		{
			if (data.status === 'error') {
				apiErrors.text(data.message);
				apiErrors.parent().removeClass("hide");
				return;
			}

			var parsedData = JSON.parse(data.message);

			parsedData.forEach(function(report)
			{
				var option = $("<option />");
				option.text(report.Key);
				option.val(report.Value);

				reportSelect.append(option);
			});

			if (reportSelect.find("option").length > 1)
			{
				reportSelect.unbind("change").change(function ()
				{
					selectedReport.val($(this).val());
				});

				if (selectedReport.val() !== "")
				{
					// Set selected report.
					reportSelect.val(selectedReport.val());
				}

				// Remove loader & show select.
				reportSelect.find("option:first").remove();
				reportSelect.parent().removeClass("hide");

				if (!firstRun)
				{
					selectedReport.val(reportSelect.find("option:first").val());
				}
			}
		});
	}
};

$.fn.getEmbedReportInfo = function ()
{
	$.ajax(
		{
			url: "/api/powerbi/getembedreportinfo",
			data:
			{
				sectionID: settings.section.ID,
				token: $("input[name='__RequestVerificationToken']").val()
			}
		})
		.done(function (data) {
			var parsedData = JSON.parse(data);

			// Models contains enums that can be used.
			var models = window["powerbi-client"].models;

			// Embed configuration used to describe the what and how to embed.
			// This object is used when calling powerbi.embed.
			// This also includes settings and options such as filters.
			// You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
			var config = {
				type: "report",
				tokenType: models.TokenType.Embed,
				accessToken: parsedData.EmbedToken,
				embedUrl: parsedData.EmbedUrl,
				id: parsedData.ReportId,
				permissions: models.Permissions.All,
				settings: {
					filterPaneEnabled: false,
					navContentPaneEnabled: true,
					background: models.BackgroundType.Transparent
				}
			};

			// Embed the report and display it within the div container.
			var report = powerbi.embed($('#embedContainer')[0], config);
		});
};;
/**
* @version: 3.0.3
* @author: Dan Grossman http://www.dangrossman.info/
* @copyright: Copyright (c) 2012-2018 Dan Grossman. All rights reserved.
* @license: Licensed under the MIT license. See http://www.opensource.org/licenses/mit-license.php
* @website: http://www.daterangepicker.com/
*/
// Following the UMD template https://github.com/umdjs/umd/blob/master/templates/returnExportsGlobal.js
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Make globaly available as well
        define(['moment', 'jquery'], function (moment, jquery) {
            if (!jquery.fn) jquery.fn = {}; // webpack server rendering
            if (typeof moment !== 'function' && moment.default) moment = moment.default
            return factory(moment, jquery);
        });
    } else if (typeof module === 'object' && module.exports) {
        // Node / Browserify
        //isomorphic issue
        var jQuery = (typeof window != 'undefined') ? window.jQuery : undefined;
        if (!jQuery) {
            jQuery = require('jquery');
            if (!jQuery.fn) jQuery.fn = {};
        }
        var moment = (typeof window != 'undefined' && typeof window.moment != 'undefined') ? window.moment : require('moment');
        module.exports = factory(moment, jQuery);
    } else {
        // Browser globals
        root.daterangepicker = factory(root.moment, root.jQuery);
    }
}(this, function(moment, $) {
    var DateRangePicker = function(element, options, cb) {

        //default settings for options
        this.parentEl = 'body';
        this.element = $(element);
        this.startDate = moment().startOf('day');
        this.endDate = moment().endOf('day');
        this.minDate = false;
        this.maxDate = false;
        this.maxSpan = false;
        this.autoApply = false;
        this.singleDatePicker = false;
        this.showDropdowns = false;
        this.minYear = moment().subtract(100, 'year').format('YYYY');
        this.maxYear = moment().add(100, 'year').format('YYYY');
        this.showWeekNumbers = false;
        this.showISOWeekNumbers = false;
        this.showCustomRangeLabel = true;
        this.timePicker = false;
        this.timePicker24Hour = false;
        this.timePickerIncrement = 1;
        this.timePickerSeconds = false;
        this.linkedCalendars = true;
        this.autoUpdateInput = true;
        this.alwaysShowCalendars = false;
        this.ranges = {};

        this.opens = 'right';
        if (this.element.hasClass('pull-right'))
            this.opens = 'left';

        this.drops = 'down';
        if (this.element.hasClass('dropup'))
            this.drops = 'up';

        this.buttonClasses = 'btn btn-sm';
        this.applyButtonClasses = 'btn-primary';
        this.cancelButtonClasses = 'btn-default';

        this.locale = {
            direction: 'ltr',
            format: moment.localeData().longDateFormat('L'),
            separator: ' - ',
            applyLabel: 'Apply',
            cancelLabel: 'Cancel',
            weekLabel: 'W',
            customRangeLabel: 'Custom Range',
            daysOfWeek: moment.weekdaysMin(),
            monthNames: moment.monthsShort(),
            firstDay: moment.localeData().firstDayOfWeek()
        };

        this.callback = function() { };

        //some state information
        this.isShowing = false;
        this.leftCalendar = {};
        this.rightCalendar = {};

        //custom options from user
        if (typeof options !== 'object' || options === null)
            options = {};

        //allow setting options with data attributes
        //data-api options will be overwritten with custom javascript options
        options = $.extend(this.element.data(), options);

        //html template for the picker UI
        if (typeof options.template !== 'string' && !(options.template instanceof $))
            options.template =
            '<div class="daterangepicker">' +
                '<div class="ranges"></div>' +
                '<div class="drp-calendar left">' +
                    '<div class="calendar-table"></div>' +
                    '<div class="calendar-time"></div>' +
                '</div>' +
                '<div class="drp-calendar right">' +
                    '<div class="calendar-table"></div>' +
                    '<div class="calendar-time"></div>' +
                '</div>' +
                '<div class="drp-buttons">' +
                    '<span class="drp-selected"></span>' +
                    '<button class="cancelBtn" type="button"></button>' +
                    '<button class="applyBtn" disabled="disabled" type="button"></button> ' +
                '</div>' +
            '</div>';

        this.parentEl = (options.parentEl && $(options.parentEl).length) ? $(options.parentEl) : $(this.parentEl);
        this.container = $(options.template).appendTo(this.parentEl);

        //
        // handle all the possible options overriding defaults
        //

        if (typeof options.locale === 'object') {

            if (typeof options.locale.direction === 'string')
                this.locale.direction = options.locale.direction;

            if (typeof options.locale.format === 'string')
                this.locale.format = options.locale.format;

            if (typeof options.locale.separator === 'string')
                this.locale.separator = options.locale.separator;

            if (typeof options.locale.daysOfWeek === 'object')
                this.locale.daysOfWeek = options.locale.daysOfWeek.slice();

            if (typeof options.locale.monthNames === 'object')
              this.locale.monthNames = options.locale.monthNames.slice();

            if (typeof options.locale.firstDay === 'number')
              this.locale.firstDay = options.locale.firstDay;

            if (typeof options.locale.applyLabel === 'string')
              this.locale.applyLabel = options.locale.applyLabel;

            if (typeof options.locale.cancelLabel === 'string')
              this.locale.cancelLabel = options.locale.cancelLabel;

            if (typeof options.locale.weekLabel === 'string')
              this.locale.weekLabel = options.locale.weekLabel;

            if (typeof options.locale.customRangeLabel === 'string'){
                //Support unicode chars in the custom range name.
                var elem = document.createElement('textarea');
                elem.innerHTML = options.locale.customRangeLabel;
                var rangeHtml = elem.value;
                this.locale.customRangeLabel = rangeHtml;
            }
        }
        this.container.addClass(this.locale.direction);

        if (typeof options.startDate === 'string')
            this.startDate = moment(options.startDate, this.locale.format);

        if (typeof options.endDate === 'string')
            this.endDate = moment(options.endDate, this.locale.format);

        if (typeof options.minDate === 'string')
            this.minDate = moment(options.minDate, this.locale.format);

        if (typeof options.maxDate === 'string')
            this.maxDate = moment(options.maxDate, this.locale.format);

        if (typeof options.startDate === 'object')
            this.startDate = moment(options.startDate);

        if (typeof options.endDate === 'object')
            this.endDate = moment(options.endDate);

        if (typeof options.minDate === 'object')
            this.minDate = moment(options.minDate);

        if (typeof options.maxDate === 'object')
            this.maxDate = moment(options.maxDate);

        // sanity check for bad options
        if (this.minDate && this.startDate.isBefore(this.minDate))
            this.startDate = this.minDate.clone();

        // sanity check for bad options
        if (this.maxDate && this.endDate.isAfter(this.maxDate))
            this.endDate = this.maxDate.clone();

        if (typeof options.applyButtonClasses === 'string')
            this.applyButtonClasses = options.applyButtonClasses;

        if (typeof options.applyClass === 'string') //backwards compat
            this.applyButtonClasses = options.applyClass;

        if (typeof options.cancelButtonClasses === 'string')
            this.cancelButtonClasses = options.cancelButtonClasses;

        if (typeof options.cancelClass === 'string') //backwards compat
            this.cancelButtonClasses = options.cancelClass;

        if (typeof options.maxSpan === 'object')
            this.maxSpan = options.maxSpan;

        if (typeof options.dateLimit === 'object') //backwards compat
            this.maxSpan = options.dateLimit;

        if (typeof options.opens === 'string')
            this.opens = options.opens;

        if (typeof options.drops === 'string')
            this.drops = options.drops;

        if (typeof options.showWeekNumbers === 'boolean')
            this.showWeekNumbers = options.showWeekNumbers;

        if (typeof options.showISOWeekNumbers === 'boolean')
            this.showISOWeekNumbers = options.showISOWeekNumbers;

        if (typeof options.buttonClasses === 'string')
            this.buttonClasses = options.buttonClasses;

        if (typeof options.buttonClasses === 'object')
            this.buttonClasses = options.buttonClasses.join(' ');

        if (typeof options.showDropdowns === 'boolean')
            this.showDropdowns = options.showDropdowns;

        if (typeof options.minYear === 'number')
            this.minYear = options.minYear;

        if (typeof options.maxYear === 'number')
            this.maxYear = options.maxYear;

        if (typeof options.showCustomRangeLabel === 'boolean')
            this.showCustomRangeLabel = options.showCustomRangeLabel;

        if (typeof options.singleDatePicker === 'boolean') {
            this.singleDatePicker = options.singleDatePicker;
            if (this.singleDatePicker)
                this.endDate = this.startDate.clone();
        }

        if (typeof options.timePicker === 'boolean')
            this.timePicker = options.timePicker;

        if (typeof options.timePickerSeconds === 'boolean')
            this.timePickerSeconds = options.timePickerSeconds;

        if (typeof options.timePickerIncrement === 'number')
            this.timePickerIncrement = options.timePickerIncrement;

        if (typeof options.timePicker24Hour === 'boolean')
            this.timePicker24Hour = options.timePicker24Hour;

        if (typeof options.autoApply === 'boolean')
            this.autoApply = options.autoApply;

        if (typeof options.autoUpdateInput === 'boolean')
            this.autoUpdateInput = options.autoUpdateInput;

        if (typeof options.linkedCalendars === 'boolean')
            this.linkedCalendars = options.linkedCalendars;

        if (typeof options.isInvalidDate === 'function')
            this.isInvalidDate = options.isInvalidDate;

        if (typeof options.isCustomDate === 'function')
            this.isCustomDate = options.isCustomDate;

        if (typeof options.alwaysShowCalendars === 'boolean')
            this.alwaysShowCalendars = options.alwaysShowCalendars;

        // update day names order to firstDay
        if (this.locale.firstDay != 0) {
            var iterator = this.locale.firstDay;
            while (iterator > 0) {
                this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift());
                iterator--;
            }
        }

        var start, end, range;

        //if no start/end dates set, check if an input element contains initial values
        if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') {
            if ($(this.element).is(':text')) {
                var val = $(this.element).val(),
                    split = val.split(this.locale.separator);

                start = end = null;

                if (split.length == 2) {
                    start = moment(split[0], this.locale.format);
                    end = moment(split[1], this.locale.format);
                } else if (this.singleDatePicker && val !== "") {
                    start = moment(val, this.locale.format);
                    end = moment(val, this.locale.format);
                }
                if (start !== null && end !== null) {
                    this.setStartDate(start);
                    this.setEndDate(end);
                }
            }
        }

        if (typeof options.ranges === 'object') {
            for (range in options.ranges) {

                if (typeof options.ranges[range][0] === 'string')
                    start = moment(options.ranges[range][0], this.locale.format);
                else
                    start = moment(options.ranges[range][0]);

                if (typeof options.ranges[range][1] === 'string')
                    end = moment(options.ranges[range][1], this.locale.format);
                else
                    end = moment(options.ranges[range][1]);

                // If the start or end date exceed those allowed by the minDate or maxSpan
                // options, shorten the range to the allowable period.
                if (this.minDate && start.isBefore(this.minDate))
                    start = this.minDate.clone();

                var maxDate = this.maxDate;
                if (this.maxSpan && maxDate && start.clone().add(this.maxSpan).isAfter(maxDate))
                    maxDate = start.clone().add(this.maxSpan);
                if (maxDate && end.isAfter(maxDate))
                    end = maxDate.clone();

                // If the end of the range is before the minimum or the start of the range is
                // after the maximum, don't display this range option at all.
                if ((this.minDate && end.isBefore(this.minDate, this.timepicker ? 'minute' : 'day'))
                  || (maxDate && start.isAfter(maxDate, this.timepicker ? 'minute' : 'day')))
                    continue;

                //Support unicode chars in the range names.
                var elem = document.createElement('textarea');
                elem.innerHTML = range;
                var rangeHtml = elem.value;

                this.ranges[rangeHtml] = [start, end];
            }

            var list = '<ul>';
            for (range in this.ranges) {
                list += '<li data-range-key="' + range + '">' + range + '</li>';
            }
            if (this.showCustomRangeLabel) {
                list += '<li data-range-key="' + this.locale.customRangeLabel + '">' + this.locale.customRangeLabel + '</li>';
            }
            list += '</ul>';
            this.container.find('.ranges').prepend(list);
        }

        if (typeof cb === 'function') {
            this.callback = cb;
        }

        if (!this.timePicker) {
            this.startDate = this.startDate.startOf('day');
            this.endDate = this.endDate.endOf('day');
            this.container.find('.calendar-time').hide();
        }

        //can't be used together for now
        if (this.timePicker && this.autoApply)
            this.autoApply = false;

        if (this.autoApply) {
            this.container.addClass('auto-apply');
        }

        if (typeof options.ranges === 'object')
            this.container.addClass('show-ranges');

        if (this.singleDatePicker) {
            this.container.addClass('single');
            this.container.find('.drp-calendar.left').addClass('single');
            this.container.find('.drp-calendar.left').show();
            this.container.find('.drp-calendar.right').hide();
            if (!this.timePicker) {
                this.container.addClass('auto-apply');
            }
        }

        if ((typeof options.ranges === 'undefined' && !this.singleDatePicker) || this.alwaysShowCalendars) {
            this.container.addClass('show-calendar');
        }

        this.container.addClass('opens' + this.opens);

        //apply CSS classes and labels to buttons
        this.container.find('.applyBtn, .cancelBtn').addClass(this.buttonClasses);
        if (this.applyButtonClasses.length)
            this.container.find('.applyBtn').addClass(this.applyButtonClasses);
        if (this.cancelButtonClasses.length)
            this.container.find('.cancelBtn').addClass(this.cancelButtonClasses);
        this.container.find('.applyBtn').html(this.locale.applyLabel);
        this.container.find('.cancelBtn').html(this.locale.cancelLabel);

        //
        // event listeners
        //

        this.container.find('.drp-calendar')
            .on('click.daterangepicker', '.prev', $.proxy(this.clickPrev, this))
            .on('click.daterangepicker', '.next', $.proxy(this.clickNext, this))
            .on('mousedown.daterangepicker', 'td.available', $.proxy(this.clickDate, this))
            .on('mouseenter.daterangepicker', 'td.available', $.proxy(this.hoverDate, this))
            .on('change.daterangepicker', 'select.yearselect', $.proxy(this.monthOrYearChanged, this))
            .on('change.daterangepicker', 'select.monthselect', $.proxy(this.monthOrYearChanged, this))
            .on('change.daterangepicker', 'select.hourselect,select.minuteselect,select.secondselect,select.ampmselect', $.proxy(this.timeChanged, this))

        this.container.find('.ranges')
            .on('click.daterangepicker', 'li', $.proxy(this.clickRange, this))

        this.container.find('.drp-buttons')
            .on('click.daterangepicker', 'button.applyBtn', $.proxy(this.clickApply, this))
            .on('click.daterangepicker', 'button.cancelBtn', $.proxy(this.clickCancel, this))

        if (this.element.is('input') || this.element.is('button')) {
            this.element.on({
                'click.daterangepicker': $.proxy(this.show, this),
                'focus.daterangepicker': $.proxy(this.show, this),
                'keyup.daterangepicker': $.proxy(this.elementChanged, this),
                'keydown.daterangepicker': $.proxy(this.keydown, this) //IE 11 compatibility
            });
        } else {
            this.element.on('click.daterangepicker', $.proxy(this.toggle, this));
            this.element.on('keydown.daterangepicker', $.proxy(this.toggle, this));
        }

        //
        // if attached to a text input, set the initial value
        //

        this.updateElement();

    };

    DateRangePicker.prototype = {

        constructor: DateRangePicker,

        setStartDate: function(startDate) {
            if (typeof startDate === 'string')
                this.startDate = moment(startDate, this.locale.format);

            if (typeof startDate === 'object')
                this.startDate = moment(startDate);

            if (!this.timePicker)
                this.startDate = this.startDate.startOf('day');

            if (this.timePicker && this.timePickerIncrement)
                this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);

            if (this.minDate && this.startDate.isBefore(this.minDate)) {
                this.startDate = this.minDate.clone();
                if (this.timePicker && this.timePickerIncrement)
                    this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
            }

            if (this.maxDate && this.startDate.isAfter(this.maxDate)) {
                this.startDate = this.maxDate.clone();
                if (this.timePicker && this.timePickerIncrement)
                    this.startDate.minute(Math.floor(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
            }

            if (!this.isShowing)
                this.updateElement();

            this.updateMonthsInView();
        },

        setEndDate: function(endDate) {
            if (typeof endDate === 'string')
                this.endDate = moment(endDate, this.locale.format);

            if (typeof endDate === 'object')
                this.endDate = moment(endDate);

            if (!this.timePicker)
                this.endDate = this.endDate.add(1,'d').startOf('day').subtract(1,'second');

            if (this.timePicker && this.timePickerIncrement)
                this.endDate.minute(Math.round(this.endDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);

            if (this.endDate.isBefore(this.startDate))
                this.endDate = this.startDate.clone();

            if (this.maxDate && this.endDate.isAfter(this.maxDate))
                this.endDate = this.maxDate.clone();

            if (this.maxSpan && this.startDate.clone().add(this.maxSpan).isBefore(this.endDate))
                this.endDate = this.startDate.clone().add(this.maxSpan);

            this.previousRightTime = this.endDate.clone();

            this.container.find('.drp-selected').html(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format));

            if (!this.isShowing)
                this.updateElement();

            this.updateMonthsInView();
        },

        isInvalidDate: function() {
            return false;
        },

        isCustomDate: function() {
            return false;
        },

        updateView: function() {
            if (this.timePicker) {
                this.renderTimePicker('left');
                this.renderTimePicker('right');
                if (!this.endDate) {
                    this.container.find('.right .calendar-time select').attr('disabled', 'disabled').addClass('disabled');
                } else {
                    this.container.find('.right .calendar-time select').removeAttr('disabled').removeClass('disabled');
                }
            }
            if (this.endDate)
                this.container.find('.drp-selected').html(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format));
            this.updateMonthsInView();
            this.updateCalendars();
            this.updateFormInputs();
        },

        updateMonthsInView: function() {
            if (this.endDate) {

                //if both dates are visible already, do nothing
                if (!this.singleDatePicker && this.leftCalendar.month && this.rightCalendar.month &&
                    (this.startDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.startDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM'))
                    &&
                    (this.endDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.endDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM'))
                    ) {
                    return;
                }

                this.leftCalendar.month = this.startDate.clone().date(2);
                if (!this.linkedCalendars && (this.endDate.month() != this.startDate.month() || this.endDate.year() != this.startDate.year())) {
                    this.rightCalendar.month = this.endDate.clone().date(2);
                } else {
                    this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month');
                }

            } else {
                if (this.leftCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM') && this.rightCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM')) {
                    this.leftCalendar.month = this.startDate.clone().date(2);
                    this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month');
                }
            }
            if (this.maxDate && this.linkedCalendars && !this.singleDatePicker && this.rightCalendar.month > this.maxDate) {
              this.rightCalendar.month = this.maxDate.clone().date(2);
              this.leftCalendar.month = this.maxDate.clone().date(2).subtract(1, 'month');
            }
        },

        updateCalendars: function() {

            if (this.timePicker) {
                var hour, minute, second;
                if (this.endDate) {
                    hour = parseInt(this.container.find('.left .hourselect').val(), 10);
                    minute = parseInt(this.container.find('.left .minuteselect').val(), 10);
                    second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0;
                    if (!this.timePicker24Hour) {
                        var ampm = this.container.find('.left .ampmselect').val();
                        if (ampm === 'PM' && hour < 12)
                            hour += 12;
                        if (ampm === 'AM' && hour === 12)
                            hour = 0;
                    }
                } else {
                    hour = parseInt(this.container.find('.right .hourselect').val(), 10);
                    minute = parseInt(this.container.find('.right .minuteselect').val(), 10);
                    second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0;
                    if (!this.timePicker24Hour) {
                        var ampm = this.container.find('.right .ampmselect').val();
                        if (ampm === 'PM' && hour < 12)
                            hour += 12;
                        if (ampm === 'AM' && hour === 12)
                            hour = 0;
                    }
                }
                this.leftCalendar.month.hour(hour).minute(minute).second(second);
                this.rightCalendar.month.hour(hour).minute(minute).second(second);
            }

            this.renderCalendar('left');
            this.renderCalendar('right');

            //highlight any predefined range matching the current start and end dates
            this.container.find('.ranges li').removeClass('active');
            if (this.endDate == null) return;

            this.calculateChosenLabel();
        },

        renderCalendar: function(side) {

            //
            // Build the matrix of dates that will populate the calendar
            //

            var calendar = side == 'left' ? this.leftCalendar : this.rightCalendar;
            var month = calendar.month.month();
            var year = calendar.month.year();
            var hour = calendar.month.hour();
            var minute = calendar.month.minute();
            var second = calendar.month.second();
            var daysInMonth = moment([year, month]).daysInMonth();
            var firstDay = moment([year, month, 1]);
            var lastDay = moment([year, month, daysInMonth]);
            var lastMonth = moment(firstDay).subtract(1, 'month').month();
            var lastYear = moment(firstDay).subtract(1, 'month').year();
            var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth();
            var dayOfWeek = firstDay.day();

            //initialize a 6 rows x 7 columns array for the calendar
            var calendar = [];
            calendar.firstDay = firstDay;
            calendar.lastDay = lastDay;

            for (var i = 0; i < 6; i++) {
                calendar[i] = [];
            }

            //populate the calendar with date objects
            var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1;
            if (startDay > daysInLastMonth)
                startDay -= 7;

            if (dayOfWeek == this.locale.firstDay)
                startDay = daysInLastMonth - 6;

            var curDate = moment([lastYear, lastMonth, startDay, 12, minute, second]);

            var col, row;
            for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add(24, 'hour')) {
                if (i > 0 && col % 7 === 0) {
                    col = 0;
                    row++;
                }
                calendar[row][col] = curDate.clone().hour(hour).minute(minute).second(second);
                curDate.hour(12);

                if (this.minDate && calendar[row][col].format('YYYY-MM-DD') == this.minDate.format('YYYY-MM-DD') && calendar[row][col].isBefore(this.minDate) && side == 'left') {
                    calendar[row][col] = this.minDate.clone();
                }

                if (this.maxDate && calendar[row][col].format('YYYY-MM-DD') == this.maxDate.format('YYYY-MM-DD') && calendar[row][col].isAfter(this.maxDate) && side == 'right') {
                    calendar[row][col] = this.maxDate.clone();
                }

            }

            //make the calendar object available to hoverDate/clickDate
            if (side == 'left') {
                this.leftCalendar.calendar = calendar;
            } else {
                this.rightCalendar.calendar = calendar;
            }

            //
            // Display the calendar
            //

            var minDate = side == 'left' ? this.minDate : this.startDate;
            var maxDate = this.maxDate;
            var selected = side == 'left' ? this.startDate : this.endDate;
            var arrow = this.locale.direction == 'ltr' ? {left: 'chevron-left', right: 'chevron-right'} : {left: 'chevron-right', right: 'chevron-left'};

            var html = '<table class="table-condensed">';
            html += '<thead>';
            html += '<tr>';

            // add empty cell for week number
            if (this.showWeekNumbers || this.showISOWeekNumbers)
                html += '<th></th>';

            if ((!minDate || minDate.isBefore(calendar.firstDay)) && (!this.linkedCalendars || side == 'left')) {
                html += '<th class="prev available"><span></span></th>';
            } else {
                html += '<th></th>';
            }

            var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY");

            if (this.showDropdowns) {
                var currentMonth = calendar[1][1].month();
                var currentYear = calendar[1][1].year();
                var maxYear = (maxDate && maxDate.year()) || (this.maxYear);
                var minYear = (minDate && minDate.year()) || (this.minYear);
                var inMinYear = currentYear == minYear;
                var inMaxYear = currentYear == maxYear;

                var monthHtml = '<select class="monthselect">';
                for (var m = 0; m < 12; m++) {
                    if ((!inMinYear || m >= minDate.month()) && (!inMaxYear || m <= maxDate.month())) {
                        monthHtml += "<option value='" + m + "'" +
                            (m === currentMonth ? " selected='selected'" : "") +
                            ">" + this.locale.monthNames[m] + "</option>";
                    } else {
                        monthHtml += "<option value='" + m + "'" +
                            (m === currentMonth ? " selected='selected'" : "") +
                            " disabled='disabled'>" + this.locale.monthNames[m] + "</option>";
                    }
                }
                monthHtml += "</select>";

                var yearHtml = '<select class="yearselect">';
                for (var y = minYear; y <= maxYear; y++) {
                    yearHtml += '<option value="' + y + '"' +
                        (y === currentYear ? ' selected="selected"' : '') +
                        '>' + y + '</option>';
                }
                yearHtml += '</select>';

                dateHtml = monthHtml + yearHtml;
            }

            html += '<th colspan="5" class="month">' + dateHtml + '</th>';
            if ((!maxDate || maxDate.isAfter(calendar.lastDay)) && (!this.linkedCalendars || side == 'right' || this.singleDatePicker)) {
                html += '<th class="next available"><span></span></th>';
            } else {
                html += '<th></th>';
            }

            html += '</tr>';
            html += '<tr>';

            // add week number label
            if (this.showWeekNumbers || this.showISOWeekNumbers)
                html += '<th class="week">' + this.locale.weekLabel + '</th>';

            $.each(this.locale.daysOfWeek, function(index, dayOfWeek) {
                html += '<th>' + dayOfWeek + '</th>';
            });

            html += '</tr>';
            html += '</thead>';
            html += '<tbody>';

            //adjust maxDate to reflect the maxSpan setting in order to
            //grey out end dates beyond the maxSpan
            if (this.endDate == null && this.maxSpan) {
                var maxLimit = this.startDate.clone().add(this.maxSpan).endOf('day');
                if (!maxDate || maxLimit.isBefore(maxDate)) {
                    maxDate = maxLimit;
                }
            }

            for (var row = 0; row < 6; row++) {
                html += '<tr>';

                // add week number
                if (this.showWeekNumbers)
                    html += '<td class="week">' + calendar[row][0].week() + '</td>';
                else if (this.showISOWeekNumbers)
                    html += '<td class="week">' + calendar[row][0].isoWeek() + '</td>';

                for (var col = 0; col < 7; col++) {

                    var classes = [];

                    //highlight today's date
                    if (calendar[row][col].isSame(new Date(), "day"))
                        classes.push('today');

                    //highlight weekends
                    if (calendar[row][col].isoWeekday() > 5)
                        classes.push('weekend');

                    //grey out the dates in other months displayed at beginning and end of this calendar
                    if (calendar[row][col].month() != calendar[1][1].month())
                        classes.push('off');

                    //don't allow selection of dates before the minimum date
                    if (this.minDate && calendar[row][col].isBefore(this.minDate, 'day'))
                        classes.push('off', 'disabled');

                    //don't allow selection of dates after the maximum date
                    if (maxDate && calendar[row][col].isAfter(maxDate, 'day'))
                        classes.push('off', 'disabled');

                    //don't allow selection of date if a custom function decides it's invalid
                    if (this.isInvalidDate(calendar[row][col]))
                        classes.push('off', 'disabled');

                    //highlight the currently selected start date
                    if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD'))
                        classes.push('active', 'start-date');

                    //highlight the currently selected end date
                    if (this.endDate != null && calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD'))
                        classes.push('active', 'end-date');

                    //highlight dates in-between the selected dates
                    if (this.endDate != null && calendar[row][col] > this.startDate && calendar[row][col] < this.endDate)
                        classes.push('in-range');

                    //apply custom classes for this date
                    var isCustom = this.isCustomDate(calendar[row][col]);
                    if (isCustom !== false) {
                        if (typeof isCustom === 'string')
                            classes.push(isCustom);
                        else
                            Array.prototype.push.apply(classes, isCustom);
                    }

                    var cname = '', disabled = false;
                    for (var i = 0; i < classes.length; i++) {
                        cname += classes[i] + ' ';
                        if (classes[i] == 'disabled')
                            disabled = true;
                    }
                    if (!disabled)
                        cname += 'available';

                    html += '<td class="' + cname.replace(/^\s+|\s+$/g, '') + '" data-title="' + 'r' + row + 'c' + col + '">' + calendar[row][col].date() + '</td>';

                }
                html += '</tr>';
            }

            html += '</tbody>';
            html += '</table>';

            this.container.find('.drp-calendar.' + side + ' .calendar-table').html(html);

        },

        renderTimePicker: function(side) {

            // Don't bother updating the time picker if it's currently disabled
            // because an end date hasn't been clicked yet
            if (side == 'right' && !this.endDate) return;

            var html, selected, minDate, maxDate = this.maxDate;

            if (this.maxSpan && (!this.maxDate || this.startDate.clone().add(this.maxSpan).isAfter(this.maxDate)))
                maxDate = this.startDate.clone().add(this.maxSpan);

            if (side == 'left') {
                selected = this.startDate.clone();
                minDate = this.minDate;
            } else if (side == 'right') {
                selected = this.endDate.clone();
                minDate = this.startDate;

                //Preserve the time already selected
                var timeSelector = this.container.find('.drp-calendar.right .calendar-time');
                if (timeSelector.html() != '') {

                    selected.hour(selected.hour() || timeSelector.find('.hourselect option:selected').val());
                    selected.minute(selected.minute() || timeSelector.find('.minuteselect option:selected').val());
                    selected.second(selected.second() || timeSelector.find('.secondselect option:selected').val());

                    if (!this.timePicker24Hour) {
                        var ampm = timeSelector.find('.ampmselect option:selected').val();
                        if (ampm === 'PM' && selected.hour() < 12)
                            selected.hour(selected.hour() + 12);
                        if (ampm === 'AM' && selected.hour() === 12)
                            selected.hour(0);
                    }

                }

                if (selected.isBefore(this.startDate))
                    selected = this.startDate.clone();

                if (maxDate && selected.isAfter(maxDate))
                    selected = maxDate.clone();

            }

            //
            // hours
            //

            html = '<select class="hourselect">';

            var start = this.timePicker24Hour ? 0 : 1;
            var end = this.timePicker24Hour ? 23 : 12;

            for (var i = start; i <= end; i++) {
                var i_in_24 = i;
                if (!this.timePicker24Hour)
                    i_in_24 = selected.hour() >= 12 ? (i == 12 ? 12 : i + 12) : (i == 12 ? 0 : i);

                var time = selected.clone().hour(i_in_24);
                var disabled = false;
                if (minDate && time.minute(59).isBefore(minDate))
                    disabled = true;
                if (maxDate && time.minute(0).isAfter(maxDate))
                    disabled = true;

                if (i_in_24 == selected.hour() && !disabled) {
                    html += '<option value="' + i + '" selected="selected">' + i + '</option>';
                } else if (disabled) {
                    html += '<option value="' + i + '" disabled="disabled" class="disabled">' + i + '</option>';
                } else {
                    html += '<option value="' + i + '">' + i + '</option>';
                }
            }

            html += '</select> ';

            //
            // minutes
            //

            html += ': <select class="minuteselect">';

            for (var i = 0; i < 60; i += this.timePickerIncrement) {
                var padded = i < 10 ? '0' + i : i;
                var time = selected.clone().minute(i);

                var disabled = false;
                if (minDate && time.second(59).isBefore(minDate))
                    disabled = true;
                if (maxDate && time.second(0).isAfter(maxDate))
                    disabled = true;

                if (selected.minute() == i && !disabled) {
                    html += '<option value="' + i + '" selected="selected">' + padded + '</option>';
                } else if (disabled) {
                    html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>';
                } else {
                    html += '<option value="' + i + '">' + padded + '</option>';
                }
            }

            html += '</select> ';

            //
            // seconds
            //

            if (this.timePickerSeconds) {
                html += ': <select class="secondselect">';

                for (var i = 0; i < 60; i++) {
                    var padded = i < 10 ? '0' + i : i;
                    var time = selected.clone().second(i);

                    var disabled = false;
                    if (minDate && time.isBefore(minDate))
                        disabled = true;
                    if (maxDate && time.isAfter(maxDate))
                        disabled = true;

                    if (selected.second() == i && !disabled) {
                        html += '<option value="' + i + '" selected="selected">' + padded + '</option>';
                    } else if (disabled) {
                        html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>';
                    } else {
                        html += '<option value="' + i + '">' + padded + '</option>';
                    }
                }

                html += '</select> ';
            }

            //
            // AM/PM
            //

            if (!this.timePicker24Hour) {
                html += '<select class="ampmselect">';

                var am_html = '';
                var pm_html = '';

                if (minDate && selected.clone().hour(12).minute(0).second(0).isBefore(minDate))
                    am_html = ' disabled="disabled" class="disabled"';

                if (maxDate && selected.clone().hour(0).minute(0).second(0).isAfter(maxDate))
                    pm_html = ' disabled="disabled" class="disabled"';

                if (selected.hour() >= 12) {
                    html += '<option value="AM"' + am_html + '>AM</option><option value="PM" selected="selected"' + pm_html + '>PM</option>';
                } else {
                    html += '<option value="AM" selected="selected"' + am_html + '>AM</option><option value="PM"' + pm_html + '>PM</option>';
                }

                html += '</select>';
            }

            this.container.find('.drp-calendar.' + side + ' .calendar-time').html(html);

        },

        updateFormInputs: function() {

            if (this.singleDatePicker || (this.endDate && (this.startDate.isBefore(this.endDate) || this.startDate.isSame(this.endDate)))) {
                this.container.find('button.applyBtn').removeAttr('disabled');
            } else {
                this.container.find('button.applyBtn').attr('disabled', 'disabled');
            }

        },

        move: function() {
            var parentOffset = { top: 0, left: 0 },
                containerTop;
            var parentRightEdge = $(window).width();
            if (!this.parentEl.is('body')) {
                parentOffset = {
                    top: this.parentEl.offset().top - this.parentEl.scrollTop(),
                    left: this.parentEl.offset().left - this.parentEl.scrollLeft()
                };
                parentRightEdge = this.parentEl[0].clientWidth + this.parentEl.offset().left;
            }

            if (this.drops == 'up')
                containerTop = this.element.offset().top - this.container.outerHeight() - parentOffset.top;
            else
                containerTop = this.element.offset().top + this.element.outerHeight() - parentOffset.top;
            this.container[this.drops == 'up' ? 'addClass' : 'removeClass']('drop-up');

            if (this.opens == 'left') {
                this.container.css({
                    top: containerTop,
                    right: parentRightEdge - this.element.offset().left - this.element.outerWidth(),
                    left: 'auto'
                });
                if (this.container.offset().left < 0) {
                    this.container.css({
                        right: 'auto',
                        left: 9
                    });
                }
            } else if (this.opens == 'center') {
                this.container.css({
                    top: containerTop,
                    left: this.element.offset().left - parentOffset.left + this.element.outerWidth() / 2
                            - this.container.outerWidth() / 2,
                    right: 'auto'
                });
                if (this.container.offset().left < 0) {
                    this.container.css({
                        right: 'auto',
                        left: 9
                    });
                }
            } else {
                this.container.css({
                    top: containerTop,
                    left: this.element.offset().left - parentOffset.left,
                    right: 'auto'
                });
                if (this.container.offset().left + this.container.outerWidth() > $(window).width()) {
                    this.container.css({
                        left: 'auto',
                        right: 0
                    });
                }
            }
        },

        show: function(e) {
            if (this.isShowing) return;

            // Create a click proxy that is private to this instance of datepicker, for unbinding
            this._outsideClickProxy = $.proxy(function(e) { this.outsideClick(e); }, this);

            // Bind global datepicker mousedown for hiding and
            $(document)
              .on('mousedown.daterangepicker', this._outsideClickProxy)
              // also support mobile devices
              .on('touchend.daterangepicker', this._outsideClickProxy)
              // also explicitly play nice with Bootstrap dropdowns, which stopPropagation when clicking them
              .on('click.daterangepicker', '[data-toggle=dropdown]', this._outsideClickProxy)
              // and also close when focus changes to outside the picker (eg. tabbing between controls)
              .on('focusin.daterangepicker', this._outsideClickProxy);

            // Reposition the picker if the window is resized while it's open
            $(window).on('resize.daterangepicker', $.proxy(function(e) { this.move(e); }, this));

            this.oldStartDate = this.startDate.clone();
            this.oldEndDate = this.endDate.clone();
            this.previousRightTime = this.endDate.clone();

            this.updateView();
            this.container.show();
            this.move();
            this.element.trigger('show.daterangepicker', this);
            this.isShowing = true;
        },

        hide: function(e) {
            if (!this.isShowing) return;

            //incomplete date selection, revert to last values
            if (!this.endDate) {
                this.startDate = this.oldStartDate.clone();
                this.endDate = this.oldEndDate.clone();
            }

            //if a new date range was selected, invoke the user callback function
            if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
                this.callback(this.startDate.clone(), this.endDate.clone(), this.chosenLabel);

            //if picker is attached to a text input, update it
            this.updateElement();

            $(document).off('.daterangepicker');
            $(window).off('.daterangepicker');
            this.container.hide();
            this.element.trigger('hide.daterangepicker', this);
            this.isShowing = false;
        },

        toggle: function(e) {
            if (this.isShowing) {
                this.hide();
            } else {
                this.show();
            }
        },

        outsideClick: function(e) {
            var target = $(e.target);
            // if the page is clicked anywhere except within the daterangerpicker/button
            // itself then call this.hide()
            if (
                // ie modal dialog fix
                e.type == "focusin" ||
                target.closest(this.element).length ||
                target.closest(this.container).length ||
                target.closest('.calendar-table').length
                ) return;
            this.hide();
            this.element.trigger('outsideClick.daterangepicker', this);
        },

        showCalendars: function() {
            this.container.addClass('show-calendar');
            this.move();
            this.element.trigger('showCalendar.daterangepicker', this);
        },

        hideCalendars: function() {
            this.container.removeClass('show-calendar');
            this.element.trigger('hideCalendar.daterangepicker', this);
        },

        clickRange: function(e) {
            var label = e.target.getAttribute('data-range-key');
            this.chosenLabel = label;
            if (label == this.locale.customRangeLabel) {
                this.showCalendars();
            } else {
                var dates = this.ranges[label];
                this.startDate = dates[0];
                this.endDate = dates[1];

                if (!this.timePicker) {
                    this.startDate.startOf('day');
                    this.endDate.endOf('day');
                }

                if (!this.alwaysShowCalendars)
                    this.hideCalendars();
                this.clickApply();
            }
        },

        clickPrev: function(e) {
            var cal = $(e.target).parents('.drp-calendar');
            if (cal.hasClass('left')) {
                this.leftCalendar.month.subtract(1, 'month');
                if (this.linkedCalendars)
                    this.rightCalendar.month.subtract(1, 'month');
            } else {
                this.rightCalendar.month.subtract(1, 'month');
            }
            this.updateCalendars();
        },

        clickNext: function(e) {
            var cal = $(e.target).parents('.drp-calendar');
            if (cal.hasClass('left')) {
                this.leftCalendar.month.add(1, 'month');
            } else {
                this.rightCalendar.month.add(1, 'month');
                if (this.linkedCalendars)
                    this.leftCalendar.month.add(1, 'month');
            }
            this.updateCalendars();
        },

        hoverDate: function(e) {

            //ignore dates that can't be selected
            if (!$(e.target).hasClass('available')) return;

            var title = $(e.target).attr('data-title');
            var row = title.substr(1, 1);
            var col = title.substr(3, 1);
            var cal = $(e.target).parents('.drp-calendar');
            var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col];

            //highlight the dates between the start date and the date being hovered as a potential end date
            var leftCalendar = this.leftCalendar;
            var rightCalendar = this.rightCalendar;
            var startDate = this.startDate;
            if (!this.endDate) {
                this.container.find('.drp-calendar tbody td').each(function(index, el) {

                    //skip week numbers, only look at dates
                    if ($(el).hasClass('week')) return;

                    var title = $(el).attr('data-title');
                    var row = title.substr(1, 1);
                    var col = title.substr(3, 1);
                    var cal = $(el).parents('.drp-calendar');
                    var dt = cal.hasClass('left') ? leftCalendar.calendar[row][col] : rightCalendar.calendar[row][col];

                    if ((dt.isAfter(startDate) && dt.isBefore(date)) || dt.isSame(date, 'day')) {
                        $(el).addClass('in-range');
                    } else {
                        $(el).removeClass('in-range');
                    }

                });
            }

        },

        clickDate: function(e) {

            if (!$(e.target).hasClass('available')) return;

            var title = $(e.target).attr('data-title');
            var row = title.substr(1, 1);
            var col = title.substr(3, 1);
            var cal = $(e.target).parents('.drp-calendar');
            var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col];

            //
            // this function needs to do a few things:
            // * alternate between selecting a start and end date for the range,
            // * if the time picker is enabled, apply the hour/minute/second from the select boxes to the clicked date
            // * if autoapply is enabled, and an end date was chosen, apply the selection
            // * if single date picker mode, and time picker isn't enabled, apply the selection immediately
            // * if one of the inputs above the calendars was focused, cancel that manual input
            //

            if (this.endDate || date.isBefore(this.startDate, 'day')) { //picking start
                if (this.timePicker) {
                    var hour = parseInt(this.container.find('.left .hourselect').val(), 10);
                    if (!this.timePicker24Hour) {
                        var ampm = this.container.find('.left .ampmselect').val();
                        if (ampm === 'PM' && hour < 12)
                            hour += 12;
                        if (ampm === 'AM' && hour === 12)
                            hour = 0;
                    }
                    var minute = parseInt(this.container.find('.left .minuteselect').val(), 10);
                    var second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0;
                    date = date.clone().hour(hour).minute(minute).second(second);
                }
                this.endDate = null;
                this.setStartDate(date.clone());
            } else if (!this.endDate && date.isBefore(this.startDate)) {
                //special case: clicking the same date for start/end,
                //but the time of the end date is before the start date
                this.setEndDate(this.startDate.clone());
            } else { // picking end
                if (this.timePicker) {
                    var hour = parseInt(this.container.find('.right .hourselect').val(), 10);
                    if (!this.timePicker24Hour) {
                        var ampm = this.container.find('.right .ampmselect').val();
                        if (ampm === 'PM' && hour < 12)
                            hour += 12;
                        if (ampm === 'AM' && hour === 12)
                            hour = 0;
                    }
                    var minute = parseInt(this.container.find('.right .minuteselect').val(), 10);
                    var second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0;
                    date = date.clone().hour(hour).minute(minute).second(second);
                }
                this.setEndDate(date.clone());
                if (this.autoApply) {
                  this.calculateChosenLabel();
                  this.clickApply();
                }
            }

            if (this.singleDatePicker) {
                this.setEndDate(this.startDate);
                if (!this.timePicker)
                    this.clickApply();
            }

            this.updateView();

            //This is to cancel the blur event handler if the mouse was in one of the inputs
            e.stopPropagation();

        },

        calculateChosenLabel: function () {
            var customRange = true;
            var i = 0;
            for (var range in this.ranges) {
              if (this.timePicker) {
                    var format = this.timePickerSeconds ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM-DD HH:mm";
                    //ignore times when comparing dates if time picker seconds is not enabled
                    if (this.startDate.format(format) == this.ranges[range][0].format(format) && this.endDate.format(format) == this.ranges[range][1].format(format)) {
                        customRange = false;
                        this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').attr('data-range-key');
                        break;
                    }
                } else {
                    //ignore times when comparing dates if time picker is not enabled
                    if (this.startDate.format('YYYY-MM-DD') == this.ranges[range][0].format('YYYY-MM-DD') && this.endDate.format('YYYY-MM-DD') == this.ranges[range][1].format('YYYY-MM-DD')) {
                        customRange = false;
                        this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').attr('data-range-key');
                        break;
                    }
                }
                i++;
            }
            if (customRange) {
                if (this.showCustomRangeLabel) {
                    this.chosenLabel = this.container.find('.ranges li:last').addClass('active').attr('data-range-key');
                } else {
                    this.chosenLabel = null;
                }
                this.showCalendars();
            }
        },

        clickApply: function(e) {
            this.hide();
            this.element.trigger('apply.daterangepicker', this);
        },

        clickCancel: function(e) {
            this.startDate = this.oldStartDate;
            this.endDate = this.oldEndDate;
            this.hide();
            this.element.trigger('cancel.daterangepicker', this);
        },

        monthOrYearChanged: function(e) {
            var isLeft = $(e.target).closest('.drp-calendar').hasClass('left'),
                leftOrRight = isLeft ? 'left' : 'right',
                cal = this.container.find('.drp-calendar.'+leftOrRight);

            // Month must be Number for new moment versions
            var month = parseInt(cal.find('.monthselect').val(), 10);
            var year = cal.find('.yearselect').val();

            if (!isLeft) {
                if (year < this.startDate.year() || (year == this.startDate.year() && month < this.startDate.month())) {
                    month = this.startDate.month();
                    year = this.startDate.year();
                }
            }

            if (this.minDate) {
                if (year < this.minDate.year() || (year == this.minDate.year() && month < this.minDate.month())) {
                    month = this.minDate.month();
                    year = this.minDate.year();
                }
            }

            if (this.maxDate) {
                if (year > this.maxDate.year() || (year == this.maxDate.year() && month > this.maxDate.month())) {
                    month = this.maxDate.month();
                    year = this.maxDate.year();
                }
            }

            if (isLeft) {
                this.leftCalendar.month.month(month).year(year);
                if (this.linkedCalendars)
                    this.rightCalendar.month = this.leftCalendar.month.clone().add(1, 'month');
            } else {
                this.rightCalendar.month.month(month).year(year);
                if (this.linkedCalendars)
                    this.leftCalendar.month = this.rightCalendar.month.clone().subtract(1, 'month');
            }
            this.updateCalendars();
        },

        timeChanged: function(e) {

            var cal = $(e.target).closest('.drp-calendar'),
                isLeft = cal.hasClass('left');

            var hour = parseInt(cal.find('.hourselect').val(), 10);
            var minute = parseInt(cal.find('.minuteselect').val(), 10);
            var second = this.timePickerSeconds ? parseInt(cal.find('.secondselect').val(), 10) : 0;

            if (!this.timePicker24Hour) {
                var ampm = cal.find('.ampmselect').val();
                if (ampm === 'PM' && hour < 12)
                    hour += 12;
                if (ampm === 'AM' && hour === 12)
                    hour = 0;
            }

            if (isLeft) {
                var start = this.startDate.clone();
                start.hour(hour);
                start.minute(minute);
                start.second(second);
                this.setStartDate(start);
                if (this.singleDatePicker) {
                    this.endDate = this.startDate.clone();
                } else if (this.endDate && this.endDate.format('YYYY-MM-DD') == start.format('YYYY-MM-DD') && this.endDate.isBefore(start)) {
                    this.setEndDate(start.clone());
                }
            } else if (this.endDate) {
                var end = this.endDate.clone();
                end.hour(hour);
                end.minute(minute);
                end.second(second);
                this.setEndDate(end);
            }

            //update the calendars so all clickable dates reflect the new time component
            this.updateCalendars();

            //update the form inputs above the calendars with the new time
            this.updateFormInputs();

            //re-render the time pickers because changing one selection can affect what's enabled in another
            this.renderTimePicker('left');
            this.renderTimePicker('right');

        },

        elementChanged: function() {
            if (!this.element.is('input')) return;
            if (!this.element.val().length) return;

            var dateString = this.element.val().split(this.locale.separator),
                start = null,
                end = null;

            if (dateString.length === 2) {
                start = moment(dateString[0], this.locale.format);
                end = moment(dateString[1], this.locale.format);
            }

            if (this.singleDatePicker || start === null || end === null) {
                start = moment(this.element.val(), this.locale.format);
                end = start;
            }

            if (!start.isValid() || !end.isValid()) return;

            this.setStartDate(start);
            this.setEndDate(end);
            this.updateView();
        },

        keydown: function(e) {
            //hide on tab or enter
            if ((e.keyCode === 9) || (e.keyCode === 13)) {
                this.hide();
            }

            //hide on esc and prevent propagation
            if (e.keyCode === 27) {
                e.preventDefault();
                e.stopPropagation();

                this.hide();
            }
        },

        updateElement: function() {
            if (this.element.is('input') && this.autoUpdateInput) {
                var newValue = this.startDate.format(this.locale.format);
                if (!this.singleDatePicker) {
                    newValue += this.locale.separator + this.endDate.format(this.locale.format);
                }
                if (newValue !== this.element.val()) {
                    this.element.val(newValue).trigger('change');
                }
            }
        },

        remove: function() {
            this.container.remove();
            this.element.off('.daterangepicker');
            this.element.removeData();
        }

    };

    $.fn.daterangepicker = function(options, callback) {
        var implementOptions = $.extend(true, {}, $.fn.daterangepicker.defaultOptions, options);
        this.each(function() {
            var el = $(this);
            if (el.data('daterangepicker'))
                el.data('daterangepicker').remove();
            el.data('daterangepicker', new DateRangePicker(el, implementOptions, callback));
        });
        return this;
    };

    return DateRangePicker;

}));
;
$(window).load(function()
{
	if ($('#events.section').length > 0 || $('#events.item:not(.edit)').length > 0)
	{
		$(this).recurringEvents();

		if (typeof Sys != 'undefined' && typeof Sys.WebForms != 'undefined')
		{
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function()
			{
				$(this).recurringEvents();
			});
		}
	}

	if ($('#events.item.edit').length > 0)
	{
		$(this).recurringEventsAddEdit();

		if (typeof Sys != 'undefined' && typeof Sys.WebForms != 'undefined')
		{
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function()
			{
				$(this).recurringEventsAddEdit();
			});
		}
	}
});

$.fn.recurringEvents = function()
{
	var rObject = null;

	var theReturnObject =
	{
		eventID: settings.section.itemID,
		eventIDs: [],
		currentUrl: settings.section.url,
		recurrenceID: getUrlParameter('recurrenceID'),

		init:function()
		{
			rObject = this;

			if ($('#events.item').length > 0)
				rObject.eventIDs.push(rObject.eventID);

			if ($('#events.section').length > 0)
			{
				$.each($('#events.section .eventItem'), function()
				{
					rObject.eventIDs.push($(this).data('event-id'));
				});
			}

			if (!$.isEmptyObject(rObject.eventIDs))
			{
				$.ajax(
				{
					url: "/api/recurrence/hasrecurrence",
					data:
					{
						eventIDs: rObject.eventIDs,
						token: $('input[name="__RequestVerificationToken"]').val()
					}
				}).done(function(data)
				{
					var results = JSON.parse(data);

					if ($('#events.item').length > 0)
					{
						if (results[0]["Item2"] == true)
							$('h1.itemTitle').addClass('icon-awesome-arrows-cw before');
					}

					if ($('#events.section').length > 0)
					{
						$.each(results, function()
						{
							if ($(this)[0]["Item2"] === true)
								$('#events.section').find('[data-event-id=' + $(this)[0]["Item1"] + ']').addClass('recurring-event');
						});
					}
				});
			}
		}
	}

	theReturnObject.init($(this));

	$(this).data('recurrence-data', theReturnObject);

	return $(this);
}

$.fn.recurringEventsAddEdit = function()
{
	var rObject = null;

	var theReturnObject =
	{
		eventID: settings.section.itemID,
		currentUrl: settings.section.url,
		hasRecurrence: $('.hasRecurrence').text(),
		recurrenceID: getUrlParameter('recurrenceID'),
		recurrenceTypeVal: null,
		recurrenceDurationVal: null,
		dateRangeStart: null,
		dateRangeEnd: null,
		durationDate: null,
		dateRangeLocale: {},
		recurrenceFreeRanges: [],
		dateRanges: [],

		init:function()
		{
			rObject = this;

			rObject.initializeInterface();
			rObject.initializeListeners();
		},

		initializeInterface:function()
		{
			if (rObject.hasRecurrence == 1)
			{
				if (rObject.recurrenceID == undefined)
				{
					$('.eventRecurrenceText').text(settings.events.recurringEventText);
					$('#linkBtnOpenRecurrenceOverlay a').text(settings.events.changeRecurrenceText);
					$('.msgDeleteRecurrence').remove();
					$('#linkBtnDeleteRecurrence a').text(settings.events.removeRecurrencesText);
				}
				else if (rObject.recurrenceID > 0)
				{
					var mainEventUrl = rObject.stripUrlParam('recurrenceID');
					$('.eventRecurrenceText').html('Dit is een herhaling van een andere afspraak. <a href="' + mainEventUrl + '">Klik hier</a> om naar de hoofdafspraak te gaan.');
					$('.eventRecurrenceText').html(settings.events.eventIsRecurrenceText.replace("{0}", mainEventUrl));
					$('#linkBtnOpenRecurrenceOverlay').remove();
					$('.msgDeleteAllRecurrences').remove();
					$('#linkBtnDeleteRecurrence a').text(settings.events.removeRecurrenceText);

					// Update add/edit layout
					$('label[for$="PublishDate_dropDay"]').parent().addClass('hide');
					$('label[for$="txtEventTitle"]').parent().addClass('hide');
					$('label[for="eventColorDropdown"]').parent().addClass('hide');
					$('label[for$="txtEventBriefDescription"]').parent().parent().addClass('hide');
					$('.tabs .tab').addClass('hide').removeClass('active');
					$('.tabs #locationTab').removeClass('hide').addClass('active');
					$('.tabs .tabContent.active').removeClass('active');
					$('.tabs #locationTabContent').addClass('active');
					$('div[id$="pnlSections"]').addClass('hide');

					var legends = $('legend');
					$.each(legends, function()
					{
						if ($.trim($(this).text()) == 'Beschrijving')
							$(this).addClass('hide');
					});
				}

				$('.eventRecurrenceText').removeClass('hide');
				$('#linkBtnDeleteRecurrence').removeClass('hide');
			}

			rObject.dateRangeStart = moment();
			rObject.dateRangeEnd = moment();
			rObject.dateRangeLocale = {
				'format': 'DD-MM-YYYY',
				'separator': ' - ',
				'applyLabel': settings.statistics.applyText,
				'cancelLabel': settings.statistics.cancelText,
				'fromLabel': settings.statistics.fromText,
				'toLabel': settings.statistics.toText,
				'customRangeLabel': settings.statistics.customRangeText,
				'weekLabel': 'W',
				'daysOfWeek': [
					settings.various.daysShortSunday,
					settings.various.daysShortMonday,
					settings.various.daysShortTuesday,
					settings.various.daysShortWednesday,
					settings.various.daysShortThursday,
					settings.various.daysShortFriday,
					settings.various.daysShortSaturday
				],
				'monthNames': [
					settings.various.monthsLongJanuary,
					settings.various.monthsLongFebruary,
					settings.various.monthsLongMarch,
					settings.various.monthsLongApril,
					settings.various.monthsLongMay,
					settings.various.monthsLongJune,
					settings.various.monthsLongJuly,
					settings.various.monthsLongAugust,
					settings.various.monthsLongSeptember,
					settings.various.monthsLongOctober,
					settings.various.monthsLongNovember,
					settings.various.monthsLongDecember
				],
				'firstDay': 1
			};

			rObject.recurrenceTypeVal = $('.field.recurrenceType select').val();
			rObject.updateRecurrenceTypeLayout();

			$('.field.recurrenceType select').change(function()
			{
				rObject.recurrenceTypeVal = $(this).val();

				rObject.updateRecurrenceTypeLayout();

				rObject.recurrenceDurationVal = $('.field.durationButtonGroup input[type=radio]:checked').val();
				rObject.updateRecurrenceDurationLayout();
			});

			if ($('.field.durationButtonGroup input[type=radio]:checked').val() == undefined)
				$('.field.durationButtonGroup input[type=radio][value="always"]').prop('checked', true);

			rObject.recurrenceDurationVal = $('.field.durationButtonGroup input[type=radio]:checked').val();
			rObject.updateRecurrenceDurationLayout();

			$('.field.durationButtonGroup input[type=radio]').change(function()
			{
				rObject.recurrenceDurationVal = $('.field.durationButtonGroup input[type=radio]:checked').val();
				rObject.updateRecurrenceDurationLayout();
			});

			if ($('.field.recurrenceMonthDayWeekday input[type=radio]:checked').val() == undefined)
				$('.field.recurrenceMonthDayWeekday input[type=radio][value="the"]').prop('checked', true);

			$('.recurrenceFreeRangePicker').initializeDateSelect();

			if (!settings.webGuidelines)
			{
				var endDate;

				if ($('.lblRecurrenceDuration').text() != '')
					endDate = moment.unix($('.lblRecurrenceDuration').text()).format('DD-MM-YYYY');
				else
					endDate = moment().format('DD-MM-YYYY');

				$('.recurrenceDurationPicker input').val(moment().format('DD-MM-YYYY'));
				$('.recurrenceDurationPicker input').daterangepicker(
				{
					'startDate': moment(endDate, 'DD-MM-YYYY'),
					'endDate': rObject.dateRangeEnd,
					'singleDatePicker': true,
					'locale': rObject.dateRangeLocale,
					'autoApply': true
				}, function(start, end, label)
				{
					$('.recurrenceDurationPicker input').val(start.format('DD-MM-YYYY'));
				});

				$('.recurrenceFreeRangePicker input').val(moment().format('DD-MM-YYYY'));
				$('.recurrenceFreeRangePicker input').daterangepicker(
				{
					'startDate': rObject.dateRangeStart,
					'endDate': rObject.dateRangeEnd,
					'singleDatePicker': true,
					'locale': rObject.dateRangeLocale,
					'autoApply': true
				}, function(start, end, label)
				{
					rObject.dateRangeStart = start;
					rObject.dateRangeEnd = end;

					$('.recurrenceFreeRangePicker input').val(start.format('DD-MM-YYYY'));
				});
			}

			if (rObject.recurrenceTypeVal == 3) // Free selection
			{
				$.ajax(
				{
					url: "/api/recurrence/getrecurrenceselection",
					data:
					{
						eventID: rObject.eventID,
						token: $('input[name="__RequestVerificationToken"]').val()
					}
				}).success(function(data)
				{
					var results = JSON.parse(data);

					if (results.length > 0)
					{
						$('.rangeList .rangeListLabel').removeClass('hide');
						$('.rangeList .emptyRangeListLabel').addClass('hide');
					}

					$.each(results, function()
					{
						var dateObj = moment.unix($(this)[0]["Item2"]).format('DD-MM-YYYY');

						rObject.recurrenceFreeRanges.push($(this)[0]["Item2"]);
						rObject.addFreeSelectionItem(dateObj);
					});
				});
			}
		},

		initializeListeners:function()
		{
			$('#linkBtnOpenRecurrenceOverlay a').unbind('click').on('click', function()
			{				
				$('.recurrenceOverlay').removeClass('hide');
				$('.recurrenceOverlay').initializeOverlays();
			});

			$('#linkBtnDeleteRecurrence a').unbind('click').on('click', function()
			{				
				$('.deleteRecurrenceModal').removeClass('hide');
				$('.deleteRecurrenceModal').initializeOverlays();				
			});

			$('#btnCancelDeleteRecurrence').unbind('click').on('click', function()
			{
				$('.deleteRecurrenceModal').addClass('hide');
				$('body').removeClass('overlayOpen');
				$.fn.restoreLastFocus();
			});

			$('.recurrenceFreeRanges .button.add a').unbind('click').on('click', function(event)
			{
				event.preventDefault();

				var day = String($('.recurrenceFreeRanges select.day').val()),
					month = String($('.recurrenceFreeRanges select.month').val()),
					year = String($('.recurrenceFreeRanges select.year').val()),
					dateString = day + '/' + month + '/' + year,
					dateObj = moment(dateString, 'D/M/YYYY');

				if (moment(dateString, 'D/M/YYYY').isDST())
					dateObj = moment(dateString, 'D/M/YYYY').add(1, 'hours');

				rObject.dateRangeStart = dateObj;
				rObject.prepareAddFreeSelectionItem();
			});

			$('.recurrenceFreeRangePicker input.dateTimeOutput').on('apply.daterangepicker', function(event, picker)
			{
				event.preventDefault();

				rObject.prepareAddFreeSelectionItem();
			});

			$('#btnSaveRecurrence').unbind('click').on('click', function(event)
			{
				event.preventDefault();

				rObject.saveRecurrenceData();
			});

			$('#btnDeleteRecurrence').unbind('click').on('click', function(event)
			{
				event.preventDefault();

				rObject.deleteRecurrenceData();
			});
		},

		updateRecurrenceTypeLayout:function()
		{
			if (rObject.recurrenceTypeVal == 0) // Daily
			{
				$('.recurrenceOverlay .recurrenceDuration').removeClass('hide');
				$('.recurrenceOverlay .field.dateTimeSelect, .recurrenceOverlay .field.recurrenceWeekday, .recurrenceOverlay .field.recurrenceWeekday span, .recurrenceOverlay input[name=recurrenceDayDate], .recurrenceOverlay .field.recurrenceDay, .recurrenceOverlay .field.recurrenceWeekdayDeviated, .recurrenceOverlay .field.recurrenceFreeRanges, .field.recurrenceMonthDayWeekday').addClass('hide');
				$('.field.recurrenceWeekdayDeviated').parent().parent().addClass('hide');
			}
			else if (rObject.recurrenceTypeVal == 1) // Weekly
			{
				$('.recurrenceOverlay .recurrenceDuration, .recurrenceOverlay .field.recurrenceWeekday, .recurrenceOverlay .field.recurrenceWeekday span').removeClass('hide');
				$('.field.recurrenceWeekdayDeviated').parent().parent().removeClass('hide');
				$('.recurrenceOverlay .field.dateTimeSelect, .recurrenceOverlay input[name=recurrenceDayDate], .recurrenceOverlay .field.recurrenceDay, .recurrenceOverlay .field.recurrenceWeekdayDeviated, .recurrenceOverlay .field.recurrenceFreeRanges, .field.recurrenceMonthDayWeekday').addClass('hide');
			}
			else if (rObject.recurrenceTypeVal == 2) // Monthly
			{
				$('.recurrenceOverlay .recurrenceDuration, .recurrenceOverlay .field.recurrenceWeekday, .recurrenceOverlay input[name=recurrenceDayDate], .recurrenceOverlay .field.recurrenceDay, .recurrenceOverlay .field.recurrenceWeekdayDeviated, .field.recurrenceMonthDayWeekday').removeClass('hide');
				$('.field.recurrenceWeekdayDeviated').parent().parent().removeClass('hide');
				$('.recurrenceOverlay .field.dateTimeSelect, .recurrenceOverlay .field.recurrenceWeekday span, .recurrenceOverlay .field.recurrenceFreeRanges').addClass('hide');
			}
			else if (rObject.recurrenceTypeVal == 3) // Free selection
			{
				$('.recurrenceOverlay .field.recurrenceFreeRanges').removeClass('hide');
				$('.recurrenceOverlay .recurrenceDuration, .recurrenceOverlay .field.dateTimeSelect, .recurrenceOverlay .field.recurrenceWeekday, .recurrenceOverlay .field.recurrenceWeekday span, .recurrenceOverlay input[name=recurrenceDayDate], .recurrenceOverlay .field.recurrenceDay, .recurrenceOverlay .field.recurrenceWeekdayDeviated, .field.recurrenceMonthDayWeekday').addClass('hide');
				$('.field.recurrenceWeekdayDeviated').parent().parent().addClass('hide');
			}
		},

		updateRecurrenceDurationLayout:function()
		{
			if (rObject.recurrenceDurationVal == 'always')
				$('.recurrenceOverlay .field.recurrenceDurationPicker').addClass('hide');
			else if (rObject.recurrenceDurationVal == 'ends on')
				$('.recurrenceOverlay .field.recurrenceDurationPicker').removeClass('hide');
		},

		prepareAddFreeSelectionItem:function(dateObj)
		{
			var newDateString = rObject.dateRangeStart.format('DD-MM-YYYY'),
				newDateUnix = moment(newDateString, 'DD-MM-YYYY').add(moment().utcOffset(), 'm').unix(),
				mainEventStartDateString = $('.field.startDate input').val(),
				mainEventStartDateUnix = moment(mainEventStartDateString, 'D MMMM YYYY').add(moment().utcOffset(), 'm').unix();


			if ($.inArray(newDateUnix, rObject.recurrenceFreeRanges) == -1 && newDateUnix !== mainEventStartDateUnix)
			{
				rObject.recurrenceFreeRanges.push(newDateUnix);
				rObject.addFreeSelectionItem(moment(newDateString, 'DD-MM-YYYY').add(moment().utcOffset(), 'm').format('DD-MM-YYYY'));
			}

			if (rObject.recurrenceFreeRanges.length > 0)
			{
				$('.rangeList .rangeListLabel').removeClass('hide');
				$('.rangeList .emptyRangeListLabel').addClass('hide');
			}
		},

		addFreeSelectionItem:function(dateObj)
		{
			var listItem = $('<div class="item"><span class="date">' + dateObj + '</span><div class="button delete trash transparent icon-trash iconOnly before"><a title="' + settings.events.removeDateText + '" data-continue-text="Remove date" data-continue-class="general icon-trash" role="button"><span>Remove date</span></a></div></div>');

			$(listItem).find('.button.delete a').on('click', function(event)
			{
				event.preventDefault();

				var dateObj = $(this).parent().parent().find('.date').text(),
					dateIndex = rObject.recurrenceFreeRanges.indexOf(moment(dateObj, 'DD/MM/YYYY').add(moment().utcOffset(), 'm').unix());

				if (dateIndex >= 0)
				{
					rObject.recurrenceFreeRanges.splice(dateIndex, 1);

					$(this).parent().parent().remove();

					if (rObject.recurrenceFreeRanges.length == 0)
					{
						$('.rangeList .rangeListLabel').addClass('hide');
						$('.rangeList .emptyRangeListLabel').removeClass('hide');
					}
				}
			});

			$('.rangeList').append(listItem);
		},

		saveRecurrenceData:function()
		{
			var recurrenceType = $('.field.recurrenceType select').val(),
				year = '',
				month = '',
				week = '',
				day = '',
				weekDay = '';

			// 0: Daily / 1: Weekly / 2: Monthly
			if (recurrenceType == 0 || recurrenceType == 1 || recurrenceType == 2)
			{
				if (recurrenceType == 0)
					day = '1';
				if (recurrenceType == 1)
				{
					week = '1';
					weekDay = $('.field.recurrenceWeekday select').val();
				}
				if (recurrenceType == 2)
				{
					month = '1';

					if ($('input:radio[name$="rblRecurrenceMonthDayWeekday"]:checked').val() == 'the')
					{
						week = $('.field.recurrenceWeekdayDeviated select').val();
						weekDay = $('.field.recurrenceWeekday select').val();
					}
					else
						day = $('.field.recurrenceDay select').val();
				}

				var end = '';

				if ($('.recurrenceDuration input:radio[name$="rblRecurrenceDuration"]:checked').val() == 'always')
					end = moment().add(1, 'Y').unix();
				else
				{
					if (!settings.webGuidelines)
						end = moment($('.recurrenceDurationPicker input').val(), "DD/MM/YYYY").add(moment().utcOffset(), 'm').unix();
					else
					{
						var endDate = $('.recurrenceDurationPicker select:eq(0)').val() + '/' + $('.recurrenceDurationPicker select:eq(1)').val() + '/' + $('.recurrenceDurationPicker select:eq(2)').val();
						end = moment(endDate, "DD/MM/YYYY").add(moment().utcOffset(), 'm').unix();
					}
				}

				$.ajax(
				{
					url: "/api/recurrence/postpattern",
					data:
					{
						eventID: rObject.eventID,
						end: end,
						year: year,
						month: month,
						week: week,
						day: day,
						weekDay: weekDay,
						token: $('input[name="__RequestVerificationToken"]').val()
					}
				}).success(function(data)
				{
					$('.recurrenceOverlay .button.save').addClass('hide');

					location.reload();
				});
			}
			// 3: Free selection
			else if (recurrenceType == 3)
			{
				$.ajax(
				{
					url: "/api/recurrence/postrecurrenceselection",
					data:
					{
						eventID: rObject.eventID,
						recurringItems: rObject.recurrenceFreeRanges,
						token: $('input[name="__RequestVerificationToken"]').val()
					}
				})
				.done(function(data)
				{
					$('.recurrenceOverlay .button.save').addClass('hide');

					location.reload();
				});
			}
		},

		deleteRecurrenceData:function()
		{
			if (rObject.hasRecurrence == 1 && rObject.recurrenceID == undefined)
			{
				$.ajax(
				{
					url: "/api/recurrence/deleteallrecurrence",
					data:
					{
						eventID: rObject.eventID,
						token: $('input[name="__RequestVerificationToken"]').val()
					}
				})
				.success(function(data)
				{
					$('.deleteRecurrenceModal .loader').css('display', 'inline-block');
					$('.deleteRecurrenceModal .button.delete').addClass('hide');

					var newUrl = rObject.stripUrlParam('recurrenceID');

					window.location.href = newUrl;
				});
			}
			else if (rObject.hasRecurrence == 1 && rObject.recurrenceID > 0)
			{
				$.ajax(
				{
					url: "/api/recurrence/deleterecurrence",
					data:
					{
						eventID: rObject.eventID,
						recurrenceID: rObject.recurrenceID,
						token: $('input[name="__RequestVerificationToken"]').val()
					}
				})
				.success(function(data)
				{
					$('.deleteRecurrenceModal .loader').css('display', 'inline-block');
					$('.deleteRecurrenceModal .button.delete').addClass('hide');

					var lastSlash = rObject.currentUrl.lastIndexOf('/'),
						newUrl = rObject.currentUrl.substr(0, lastSlash);

					window.location.href = newUrl;
				});
			}
		},

		stripUrlParam:function(paramName)
		{
			var urlParams = rObject.currentUrl.split('?');

			if (urlParams.length >= 2)
			{
				var prefix = encodeURIComponent(paramName) + '=',
					parts = urlParams[1].split(/[&;]/g);

				for (var i = parts.length; i-- > 0;)
				{
					if (parts[i].lastIndexOf(prefix, 0) !== -1)
						parts.splice(i, 1);
				}

				return urlParams[0] + '?' + parts.join('&');
			}
			else
				return rObject.currentUrl;
		}
	}

	theReturnObject.init($(this));

	$(this).data('recurrence-data', theReturnObject);

	return $(this);
};
;
$(document).ready(function()
{
	$.fn.a11yToolbar({readSpeakerID: settings.readSpeaker.ID});
});

$.fn.a11yToolbar = function(options)
{
	if (!settings.a11y.showToolbar || $(".a11yToolbar").length > 0) {
		return;
	}
	
	if (settings.section.isAdd || settings.section.isEdit || settings.section.isDelete || settings.section.isCMS || $.cookie == undefined) {
		return;
	}
	
	var defaults =
	{
		contrast: true,
		fontSize: true,
		enableContrast: false,
		enableFontSize: false,
		readSpeakerID: 0,
		readSpeakerLanguage: "nl_nl"
	};

	var options = $.extend(defaults, options);

	if ($.cookie(settings.a11y.cookieID))
	{
		// Get settings from cookie.
		$.cookie.json = true
		var a11ySettings = $.cookie(settings.a11y.cookieID);

		options.enableContrast = a11ySettings.contrast;
		options.enableFontSize = a11ySettings.fontSize;
	}

	// Cookie expire date (1 year from now).
	var expiryDate = new Date();
	expiryDate.setTime(expiryDate.getTime() + 3600 * 1000 * 24 * 365);

	var toolbar = $("<div />");
	toolbar.addClass("a11yToolbar");

	var contrastButtonContainer = $("<div />");
	contrastButtonContainer.addClass("contrastButton a11yButton");

	var contrastButton = $("<button />");
	contrastButton.prop("type", "button").attr("aria-label", settings.a11y.increaseContrastText).html("<span>" + settings.a11y.contrastText + "</span>");

	var fontSizeButtonContainer = $("<div />");
	fontSizeButtonContainer.addClass("fontSizeButton a11yButton");

	var fontSizeButton = $("<button />");
	fontSizeButton.prop("type", "button").attr("aria-label", settings.a11y.increaseFontSizeText).html("<span>" + settings.a11y.increaseFontSizeText + "</span>");

	var readSpeakerButtonContainer = $("<div />");
	readSpeakerButtonContainer.addClass("readSpeakerButton a11yButton");

	var readSpeakerButton = $("<button />");
	readSpeakerButton.prop("type", "button").attr("aria-label", settings.a11y.longReadSpeakerText).attr("rel", "nofollow").attr("title", settings.a11y.longReadSpeakerText).html("<span>" + settings.a11y.shortReadSpeakerText + "</span>");

	var readSpeakerPluginContainer = $("<div />");
	readSpeakerPluginContainer.addClass("readOptions hide");

	var readSpeakerPluginButton = $("<div />");
	readSpeakerPluginButton.prop("id", "readspeaker_button1").addClass("rs_skip rsbtn rs_preserve");

	var readSpeakerPluginPlayButton = $("<a />");
	readSpeakerPluginPlayButton.prop("rel", "nofollow").prop("accesskey", "L").prop("title", settings.a11y.fullReadSpeakerText).addClass("rsbtn_play");
	readSpeakerPluginPlayButton.prop("href", "//app-eu.readspeaker.com/cgi-bin/rsent?customerid=" + options.readSpeakerID + "&lang=" + options.readSpeakerLanguage + "&readclass=sectionContent,sectionHeader,itemTitle,itemContent,comments&url=" + encodeURIComponent(globals.url));

	var readSpeakerPluginPlayLeftButton = $("<span />");
	readSpeakerPluginPlayLeftButton.addClass("rsbtn_left rsimg rspart");

	var readSpeakerPluginPlayLeftButtonText = $("<span />");
	readSpeakerPluginPlayLeftButtonText.addClass("rsbtn_text").html("<span>" + settings.a11y.shortReadSpeakerText + "</span>");

	var readSpeakerPluginPlayRightButton = $("<span />");
	readSpeakerPluginPlayRightButton.addClass("rsbtn_right rsimg rsplay rspart");

	var readSpeakerPluginClearDiv = $("<div />");
	readSpeakerPluginClearDiv.addClass("clear");

	contrastButton.unbind("click").click(function()
	{
		$("body").toggleClass("a11y-contrast");

		if ($("body").hasClass("a11y-contrast"))
		{
			// Decrease contrast.
			$(this).prop("aria-label", settings.a11y.decreaseContrastText);
		}
		else
		{
			// Increase contrast.
			$(this).prop("aria-label", settings.a11y.increaseContrastText);
		}

		// Store ay11 settings in cookie.
		$.cookie.json = true;
		$.cookie(settings.a11y.cookieID, { contrast: $("body").hasClass("a11y-contrast"), fontSize: $("body").hasClass("a11y-fontSize")}, { expires: expiryDate, path: "/" });
	});

	fontSizeButton.unbind("click").click(function() {
		$("body").toggleClass("a11y-fontSize");

		if ($("body").hasClass("a11y-fontSize"))
		{
			// Increase font size.
			$("html, p, h1, h2, h3, h4, h5, h6, legend, .intro, .button a, .editorButton a, #shortcuts a, #mainMenu a, .box, .rsABlock, #path a, #footer a.shortcut").changeFontSize(4);
			$(this).prop("aria-label", settings.a11y.decreaseFontSizeText);
			$(this).find("span").text(settings.a11y.decreaseFontSizeText);
		}
		else
		{
			// Decrase font size.
			$("html, p, h1, h2, h3, h4, h5, h6, legend, .intro, .button a, .editorButton a, #shortcuts a, #mainMenu a, .box, .rsABlock, #path a, #footer a.shortcut").css({fontSize: "", height: ""});

			// Reset main menu height.
			$("#mainMenu").initializeMainMenu();
			$.fn.initializeSpacers();

			$(this).prop("aria-label", settings.a11y.increaseFontSizeText);
			$(this).find("span").text(settings.a11y.increaseFontSizeText);
		}

		// Store ay11 settings in cookie.
		$.cookie.json = true;
		$.cookie(settings.a11y.cookieID, { contrast: $("body").hasClass("a11y-contrast"), fontSize: $("body").hasClass("a11y-fontSize")}, { expires: expiryDate, path: "/" });
	});

	readSpeakerButton.unbind("click").click(function()
	{
		// Show ReadSpeaker plugin.
		readSpeakerPluginContainer.toggleClass("hide");
	});

	if (options.contrast)
	{
		// Contrast toolbar button.
		contrastButtonContainer.append(contrastButton);
		toolbar.append(contrastButtonContainer);
	}

	if (options.fontSize)
	{
		// Font size toolbar button.
		fontSizeButtonContainer.append(fontSizeButton);
		toolbar.append(fontSizeButtonContainer);
	}

	if (options.readSpeakerID != 0)
	{
		var rsScript = $('<script></script>');
		rsScript.prop('id', 'rs_req_Init').prop('src', 'https://cdn-eu.readspeaker.com/script/' + options.readSpeakerID + '/webReader/webReader.js?pids=wr');
		$('body').append(rsScript);

		// Readspeaker plugin.
		readSpeakerPluginPlayLeftButton.append(readSpeakerPluginPlayLeftButtonText);
		readSpeakerPluginPlayButton.append(readSpeakerPluginPlayLeftButton).append(readSpeakerPluginPlayRightButton);
		readSpeakerPluginButton.append(readSpeakerPluginPlayButton);
		readSpeakerPluginContainer.append(readSpeakerPluginButton).append(readSpeakerPluginClearDiv);

		// Readspeaker toolbar button.
		readSpeakerButtonContainer.append(readSpeakerButton);
		toolbar.append(readSpeakerButtonContainer).append(readSpeakerPluginContainer);
	}

	if ($('.touch').length > 0)
		toolbar.insertBefore($('#mobileMenu'));
	else
		toolbar.insertAfter($("#scrollTop"));

	// Init.
	if (options.enableContrast)
		contrastButton.click();

	if (options.enableFontSize)
		fontSizeButton.click();
};
;
$(document).ready(function () {
	var bbwCollection = $('.bluebillywig[data-video-url]');
	var bbwHostName = '';

	if (bbwCollection.length == 0)
		return;

	for (var i = 0; i < bbwCollection.length; i++) {
		var currentVideoUrl = $(bbwCollection[i]).data('video-url');

		if (currentVideoUrl.indexOf('.bbvms.com') > -1) {
			bbwHostName = new URL(currentVideoUrl).hostname;
			break;
		}

		return;
	}

	$.getScript('https://' + bbwHostName + '/launchpad/', function () {
		$('.bluebillywig[data-video-url]').each(function () {
			var currentPlaceholder = $(this);

			if (currentPlaceholder.data('video-url')) {
				var videoUrl = currentPlaceholder.data('video-url');

				if (videoUrl.indexOf('.bbvms.com') == -1)
					return;

				videoUrl = videoUrl.split('.js').join('.json');

				new bluebillywig.Player(videoUrl, {
					target: currentPlaceholder[0],
					autoPlay: "false"
				});
			}
		});
	});
});;
/*
 * jQuery.fontselect - A font selector for system fonts, local fonts and Google Web Fonts
 *
 * Made by Arjan Haverkamp, https://www.webgear.nl
 * Based on original by Tom Moor, http://tommoor.com
 * Copyright (c) 2011 Tom Moor, 2019-2020 Arjan Haverkamp
 * MIT Licensed
 * @version 1.0 - 2020-02-26
 * @url https://github.com/av01d/fontselect-jquery-plugin
 */

(function ($) {
    var fontsLoaded = {};

    $.fn.fontselect = function (options) {
        var __bind = function (fn, me) {
            return function () {
                return fn.apply(me, arguments);
            };
        };

        var settings = {
            styleTarget: $("head"),
            style: "font-select",
            placeholder: "Select a font",
            placeholderSearch: "Search...",
            searchable: true,
            lookahead: 2,
            googleApi: "https://fonts.googleapis.com/css?family=",
            localFontsUrl: "/fonts/",
            systemFonts: "Arial|Helvetica+Neue|Courier+New|Times+New+Roman|Comic+Sans+MS|Verdana|Impact".split("|"),

            googleFonts: [
                "ABeeZee:400,italic",
                "Abel:400",
                "Abhaya+Libre:400,500,600,700,800",
                "Abril+Fatface:400",
                "Aclonica:400",
                "Acme:400",
                "Actor:400",
                "Adamina:400",
                "Advent+Pro:100,200,300,400,500,600,700",
                "Aguafina+Script:400",
                "Akronim:400",
                "Aladin:400",
                "Alata:400",
                "Alatsi:400",
                "Aldrich:400",
                "Alef:400,700",
                "Alegreya:400,italic,500,500italic,700,700italic,800,800italic,900,900italic",
                "Alegreya+SC:400,italic,500,500italic,700,700italic,800,800italic,900,900italic",
                "Alegreya+Sans:100,100italic,300,300italic,400,italic,500,500italic,700,700italic,800,800italic,900,900italic",
                "Alegreya+Sans+SC:100,100italic,300,300italic,400,italic,500,500italic,700,700italic,800,800italic,900,900italic",
                "Aleo:300,300italic,400,italic,700,700italic",
                "Alex+Brush:400",
                "Alfa+Slab+One:400",
                "Alice:400",
                "Alike:400",
                "Alike+Angular:400",
                "Allan:400,700",
                "Allerta:400",
                "Allerta+Stencil:400",
                "Allura:400",
                "Almarai:300,400,700,800",
                "Almendra:400,italic,700,700italic",
                "Almendra+Display:400",
                "Almendra+SC:400",
                "Amarante:400",
                "Amaranth:400,italic,700,700italic",
                "Amatic+SC:400,700",
                "Amethysta:400",
                "Amiko:400,600,700",
                "Amiri:400,italic,700,700italic",
                "Amita:400,700",
                "Anaheim:400",
                "Andada:400",
                "Andika:400",
                "Angkor:400",
                "Annie+Use+Your+Telescope:400",
                "Anonymous+Pro:400,italic,700,700italic",
                "Antic:400",
                "Antic+Didone:400",
                "Antic+Slab:400",
                "Anton:400",
                "Arapey:400,italic",
                "Arbutus:400",
                "Arbutus+Slab:400",
                "Architects+Daughter:400",
                "Archivo:400,italic,500,500italic,600,600italic,700,700italic",
                "Archivo+Black:400",
                "Archivo+Narrow:400,italic,500,500italic,600,600italic,700,700italic",
                "Aref+Ruqaa:400,700",
                "Arima+Madurai:100,200,300,400,500,700,800,900",
                "Arimo:400,italic,700,700italic",
                "Arizonia:400",
                "Armata:400",
                "Arsenal:400,italic,700,700italic",
                "Artifika:400",
                "Arvo:400,italic,700,700italic",
                "Arya:400,700",
                "Asap:400,italic,500,500italic,600,600italic,700,700italic",
                "Asap+Condensed:400,italic,500,500italic,600,600italic,700,700italic",
                "Asar:400",
                "Asset:400",
                "Assistant:200,300,400,600,700,800",
                "Astloch:400,700",
                "Asul:400,700",
                "Athiti:200,300,400,500,600,700",
                "Atma:300,400,500,600,700",
                "Atomic+Age:400",
                "Aubrey:400",
                "Audiowide:400",
                "Autour+One:400",
                "Average:400",
                "Average+Sans:400",
                "Averia+Gruesa+Libre:400",
                "Averia+Libre:300,300italic,400,italic,700,700italic",
                "Averia+Sans+Libre:300,300italic,400,italic,700,700italic",
                "Averia+Serif+Libre:300,300italic,400,italic,700,700italic",
                "B612:400,italic,700,700italic",
                "B612+Mono:400,italic,700,700italic",
                "Bad+Script:400",
                "Bahiana:400",
                "Bahianita:400",
                "Bai+Jamjuree:200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Baloo:400",
                "Baloo+Bhai:400",
                "Baloo+Bhaijaan:400",
                "Baloo+Bhaina:400",
                "Baloo+Chettan:400",
                "Baloo+Da:400",
                "Baloo+Paaji:400",
                "Baloo+Tamma:400",
                "Baloo+Tammudu:400",
                "Baloo+Tammudu+2:400,500,600,700,800",
                "Baloo+Thambi:400",
                "Balthazar:400",
                "Bangers:400",
                "Barlow:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Barlow+Condensed:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Barlow+Semi+Condensed:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Barriecito:400",
                "Barrio:400",
                "Basic:400",
                "Baskervville:400,italic",
                "Battambang:400,700",
                "Baumans:400",
                "Bayon:400",
                "Be+Vietnam:100,100italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic",
                "Bebas+Neue:400",
                "Belgrano:400",
                "Bellefair:400",
                "Belleza:400",
                "BenchNine:300,400,700",
                "Bentham:400",
                "Berkshire+Swash:400",
                "Besley:400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Beth+Ellen:400",
                "Bevan:400",
                "Big+Shoulders+Display:100,300,400,500,600,700,800,900",
                "Big+Shoulders+Text:100,300,400,500,600,700,800,900",
                "Bigelow+Rules:400",
                "Bigshot+One:400",
                "Bilbo:400",
                "Bilbo+Swash+Caps:400",
                "BioRhyme:200,300,400,700,800",
                "BioRhyme+Expanded:200,300,400,700,800",
                "Biryani:200,300,400,600,700,800,900",
                "Bitter:400,italic,700",
                "Black+And+White+Picture:400",
                "Black+Han+Sans:400",
                "Black+Ops+One:400",
                "Blinker:100,200,300,400,600,700,800,900",
                "Bokor:400",
                "Bonbon:400",
                "Boogaloo:400",
                "Bowlby+One:400",
                "Bowlby+One+SC:400",
                "Brawler:400",
                "Bree+Serif:400",
                "Bubblegum+Sans:400",
                "Bubbler+One:400",
                "Buda:300",
                "Buenard:400,700",
                "Bungee:400",
                "Bungee+Hairline:400",
                "Bungee+Inline:400",
                "Bungee+Outline:400",
                "Bungee+Shade:400",
                "Butcherman:400",
                "Butterfly+Kids:400",
                "Cabin:400,italic,500,500italic,600,600italic,700,700italic",
                "Cabin+Condensed:400,500,600,700",
                "Cabin+Sketch:400,700",
                "Caesar+Dressing:400",
                "Cagliostro:400",
                "Cairo:200,300,400,600,700,900",
                "Calistoga:400",
                "Calligraffitti:400",
                "Cambay:400,italic,700,700italic",
                "Cambo:400",
                "Candal:400",
                "Cantarell:400,italic,700,700italic",
                "Cantata+One:400",
                "Cantora+One:400",
                "Capriola:400",
                "Cardo:400,italic,700",
                "Carme:400",
                "Carrois+Gothic:400",
                "Carrois+Gothic+SC:400",
                "Carter+One:400",
                "Catamaran:100,200,300,400,500,600,700,800,900",
                "Caudex:400,italic,700,700italic",
                "Caveat:400,700",
                "Caveat+Brush:400",
                "Cedarville+Cursive:400",
                "Ceviche+One:400",
                "Chakra+Petch:300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Changa:200,300,400,500,600,700,800",
                "Changa+One:400,italic",
                "Chango:400",
                "Charm:400,700",
                "Charmonman:400,700",
                "Chathura:100,300,400,700,800",
                "Chau+Philomene+One:400,italic",
                "Chela+One:400",
                "Chelsea+Market:400",
                "Chenla:400",
                "Cherry+Cream+Soda:400",
                "Cherry+Swash:400,700",
                "Chewy:400",
                "Chicle:400",
                "Chilanka:400",
                "Chivo:300,300italic,400,italic,700,700italic,900,900italic",
                "Chonburi:400",
                "Cinzel:400,700,900",
                "Cinzel+Decorative:400,700,900",
                "Clicker+Script:400",
                "Coda:400,800",
                "Coda+Caption:800",
                "Codystar:300,400",
                "Coiny:400",
                "Combo:400",
                "Comfortaa:300,400,500,600,700",
                "Coming+Soon:400",
                "Concert+One:400",
                "Condiment:400",
                "Content:400,700",
                "Contrail+One:400",
                "Convergence:400",
                "Cookie:400",
                "Copse:400",
                "Corben:400,700",
                "Cormorant:300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Cormorant+Garamond:300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Cormorant+Infant:300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Cormorant+SC:300,400,500,600,700",
                "Cormorant+Unicase:300,400,500,600,700",
                "Cormorant+Upright:300,400,500,600,700",
                "Courgette:400",
                "Courier+Prime:400,italic,700,700italic",
                "Cousine:400,italic,700,700italic",
                "Coustard:400,900",
                "Covered+By+Your+Grace:400",
                "Crafty+Girls:400",
                "Creepster:400",
                "Crete+Round:400,italic",
                "Crimson+Pro:200,300,400,500,600,700,800,900,200italic,300italic,italic,500italic,600italic,700italic,800italic,900italic",
                "Crimson+Text:400,italic,600,600italic,700,700italic",
                "Croissant+One:400",
                "Crushed:400",
                "Cuprum:400,italic,700,700italic",
                "Cute+Font:400",
                "Cutive:400",
                "Cutive+Mono:400",
                "DM+Sans:400,italic,500,500italic,700,700italic",
                "DM+Serif+Display:400,italic",
                "DM+Serif+Text:400,italic",
                "Damion:400",
                "Dancing+Script:400,500,600,700",
                "Dangrek:400",
                "Darker+Grotesque:300,400,500,600,700,800,900",
                "David+Libre:400,500,700",
                "Dawning+of+a+New+Day:400",
                "Days+One:400",
                "Dekko:400",
                "Delius:400",
                "Delius+Swash+Caps:400",
                "Delius+Unicase:400,700",
                "Della+Respira:400",
                "Denk+One:400",
                "Devonshire:400",
                "Dhurjati:400",
                "Didact+Gothic:400",
                "Diplomata:400",
                "Diplomata+SC:400",
                "Do+Hyeon:400",
                "Dokdo:400",
                "Domine:400,700",
                "Donegal+One:400",
                "Doppio+One:400",
                "Dorsa:400",
                "Dosis:200,300,400,500,600,700,800",
                "Dr+Sugiyama:400",
                "Duru+Sans:400",
                "Dynalight:400",
                "EB+Garamond:400,500,600,700,800,italic,500italic,600italic,700italic,800italic",
                "Eagle+Lake:400",
                "East+Sea+Dokdo:400",
                "Eater:400",
                "Economica:400,italic,700,700italic",
                "Eczar:400,500,600,700,800",
                "El+Messiri:400,500,600,700",
                "Electrolize:400",
                "Elsie:400,900",
                "Elsie+Swash+Caps:400,900",
                "Emblema+One:400",
                "Emilys+Candy:400",
                "Encode+Sans:100,200,300,400,500,600,700,800,900",
                "Encode+Sans+Condensed:100,200,300,400,500,600,700,800,900",
                "Encode+Sans+Expanded:100,200,300,400,500,600,700,800,900",
                "Encode+Sans+Semi+Condensed:100,200,300,400,500,600,700,800,900",
                "Encode+Sans+Semi+Expanded:100,200,300,400,500,600,700,800,900",
                "Engagement:400",
                "Englebert:400",
                "Enriqueta:400,500,600,700",
                "Erica+One:400",
                "Esteban:400",
                "Euphoria+Script:400",
                "Ewert:400",
                "Exo:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Exo+2:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Expletus+Sans:400,italic,500,500italic,600,600italic,700,700italic",
                "Fahkwang:200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Fanwood+Text:400,italic",
                "Farro:300,400,500,700",
                "Farsan:400",
                "Fascinate:400",
                "Fascinate+Inline:400",
                "Faster+One:400",
                "Fasthand:400",
                "Fauna+One:400",
                "Faustina:400,500,600,700,italic,500italic,600italic,700italic",
                "Federant:400",
                "Federo:400",
                "Felipa:400",
                "Fenix:400",
                "Figtree:100,100italic,300,300italic,400,400italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Finger+Paint:400",
                "Fira+Code:300,400,500,600,700",
                "Fira+Mono:400,500,700",
                "Fira+Sans:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Fira+Sans+Condensed:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Fira+Sans+Extra+Condensed:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Fjalla+One:400",
                "Fjord+One:400",
                "Flamenco:300,400",
                "Flavors:400",
                "Fondamento:400,italic",
                "Fontdiner+Swanky:400",
                "Forum:400",
                "Francois+One:400",
                "Frank+Ruhl+Libre:300,400,500,700,900",
                "Freckle+Face:400",
                "Fredericka+the+Great:400",
                "Fredoka+One:400",
                "Freehand:400",
                "Fresca:400",
                "Frijole:400",
                "Fruktur:400",
                "Fugaz+One:400",
                "GFS+Didot:400",
                "GFS+Neohellenic:400,italic,700,700italic",
                "Gabriela:400",
                "Gaegu:300,400,700",
                "Gafata:400",
                "Galada:400",
                "Galdeano:400",
                "Galindo:400",
                "Gamja+Flower:400",
                "Gayathri:100,400,700",
                "Gelasio:400,italic,500,500italic,600,600italic,700,700italic",
                "Gentium+Basic:400,italic,700,700italic",
                "Gentium+Book+Basic:400,italic,700,700italic",
                "Geo:400,italic",
                "Geostar:400",
                "Geostar+Fill:400",
                "Germania+One:400",
                "Gidugu:400",
                "Gilda+Display:400",
                "Girassol:400",
                "Give+You+Glory:400",
                "Glass+Antiqua:400",
                "Glegoo:400,700",
                "Gloria+Hallelujah:400",
                "Goblin+One:400",
                "Gochi+Hand:400",
                "Gorditas:400,700",
                "Gothic+A1:100,200,300,400,500,600,700,800,900",
                "Goudy+Bookletter+1911:400",
                "Graduate:400",
                "Grand+Hotel:400",
                "Gravitas+One:400",
                "Great+Vibes:400",
                "Grenze:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Griffy:400",
                "Gruppo:400",
                "Gudea:400,italic,700",
                "Gugi:400",
                "Gupter:400,500,700",
                "Gurajada:400",
                "Habibi:400",
                "Halant:300,400,500,600,700",
                "Hammersmith+One:400",
                "Hanalei:400",
                "Hanalei+Fill:400",
                "Handlee:400",
                "Hanuman:400,700",
                "Happy+Monkey:400",
                "Harmattan:400",
                "Headland+One:400",
                "Heebo:100,300,400,500,700,800,900",
                "Henny+Penny:400",
                "Hepta+Slab:100,200,300,400,500,600,700,800,900",
                "Herr+Von+Muellerhoff:400",
                "Hi+Melody:400",
                "Hind:300,400,500,600,700",
                "Hind+Guntur:300,400,500,600,700",
                "Hind+Madurai:300,400,500,600,700",
                "Hind+Siliguri:300,400,500,600,700",
                "Hind+Vadodara:300,400,500,600,700",
                "Holtwood+One+SC:400",
                "Homemade+Apple:400",
                "Homenaje:400",
                "IBM+Plex+Mono:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "IBM+Plex+Sans:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "IBM+Plex+Sans+Condensed:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "IBM+Plex+Serif:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "IM+Fell+DW+Pica:400,italic",
                "IM+Fell+DW+Pica+SC:400",
                "IM+Fell+Double+Pica:400,italic",
                "IM+Fell+Double+Pica+SC:400",
                "IM+Fell+English:400,italic",
                "IM+Fell+English+SC:400",
                "IM+Fell+French+Canon:400,italic",
                "IM+Fell+French+Canon+SC:400",
                "IM+Fell+Great+Primer:400,italic",
                "IM+Fell+Great+Primer+SC:400",
                "Ibarra+Real+Nova:400,italic,600,600italic,700,700italic",
                "Iceberg:400",
                "Iceland:400",
                "Imprima:400",
                "Inconsolata:400,700",
                "Inder:400",
                "Indie+Flower:400",
                "Inika:400,700",
                "Inknut+Antiqua:300,400,500,600,700,800,900",
                "Inria+Serif:300,300italic,400,italic,700,700italic",
                "Inter:100,200,300,400,500,600,700",
                "Irish+Grover:400",
                "Istok+Web:400,italic,700,700italic",
                "Italiana:400",
                "Italianno:400",
                "Itim:400",
                "Jacques+Francois:400",
                "Jacques+Francois+Shadow:400",
                "Jaldi:400,700",
                "Jim+Nightshade:400",
                "Jockey+One:400",
                "Jolly+Lodger:400",
                "Jomhuria:400",
                "Jomolhari:400",
                "Josefin+Sans:100,100italic,300,300italic,400,italic,600,600italic,700,700italic",
                "Josefin+Slab:100,100italic,300,300italic,400,italic,600,600italic,700,700italic",
                "Jost:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Joti+One:400",
                "Jua:400",
                "Judson:400,italic,700",
                "Julee:400",
                "Julius+Sans+One:400",
                "Junge:400",
                "Jura:300,400,500,600,700",
                "Just+Another+Hand:400",
                "Just+Me+Again+Down+Here:400",
                "K2D:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic",
                "Kadwa:400,700",
                "Kalam:300,400,700",
                "Kameron:400,700",
                "Kanit:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Kantumruy:300,400,700",
                "Karla:400,italic,700,700italic",
                "Karma:300,400,500,600,700",
                "Katibeh:400",
                "Kaushan+Script:400",
                "Kavivanar:400",
                "Kavoon:400",
                "Kdam+Thmor:400",
                "Keania+One:400",
                "Kelly+Slab:400",
                "Kenia:400",
                "Khand:300,400,500,600,700",
                "Khmer:400",
                "Khula:300,400,600,700,800",
                "Kirang+Haerang:400",
                "Kite+One:400",
                "Knewave:400",
                "KoHo:200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Kodchasan:200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Kosugi:400",
                "Kosugi+Maru:400",
                "Kotta+One:400",
                "Koulen:400",
                "Kranky:400",
                "Kreon:300,400,500,600,700",
                "Kristi:400",
                "Krona+One:400",
                "Krub:200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Kulim+Park:200,200italic,300,300italic,400,italic,600,600italic,700,700italic",
                "Kumar+One:400",
                "Kumar+One+Outline:400",
                "Kurale:400",
                "La+Belle+Aurore:400",
                "Lacquer:400",
                "Laila:300,400,500,600,700",
                "Lakki+Reddy:400",
                "Lalezar:400",
                "Lancelot:400",
                "Lateef:400",
                "Lato:100,100italic,300,300italic,400,italic,700,700italic,900,900italic",
                "League+Script:400",
                "Leckerli+One:400",
                "Ledger:400",
                "Lekton:400,italic,700",
                "Lemon:400",
                "Lemonada:300,400,500,600,700",
                "Lexend+Deca:400",
                "Lexend+Exa:400",
                "Lexend+Giga:400",
                "Lexend+Mega:400",
                "Lexend+Peta:400",
                "Lexend+Tera:400",
                "Lexend+Zetta:400",
                "Libre+Barcode+128:400",
                "Libre+Barcode+128+Text:400",
                "Libre+Barcode+39:400",
                "Libre+Barcode+39+Extended:400",
                "Libre+Barcode+39+Extended+Text:400",
                "Libre+Barcode+39+Text:400",
                "Libre+Baskerville:400,italic,700",
                "Libre+Caslon+Display:400",
                "Libre+Caslon+Text:400,italic,700",
                "Libre+Franklin:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Life+Savers:400,700,800",
                "Lilita+One:400",
                "Lily+Script+One:400",
                "Limelight:400",
                "Linden+Hill:400,italic",
                "Literata:400,500,600,700,italic,500italic,600italic,700italic",
                "Liu+Jian+Mao+Cao:400",
                "Livvic:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,900,900italic",
                "Lobster:400",
                "Lobster+Two:400,italic,700,700italic",
                "Londrina+Outline:400",
                "Londrina+Shadow:400",
                "Londrina+Sketch:400",
                "Londrina+Solid:100,300,400,900",
                "Long+Cang:400",
                "Lora:400,italic,700,700italic",
                "Love+Ya+Like+A+Sister:400",
                "Loved+by+the+King:400",
                "Lovers+Quarrel:400",
                "Luckiest+Guy:400",
                "Lusitana:400,700",
                "Lustria:400",
                "M+PLUS+1p:100,300,400,500,700,800,900",
                "M+PLUS+Rounded+1c:100,300,400,500,700,800,900",
                "Ma+Shan+Zheng:400",
                "Macondo:400",
                "Macondo+Swash+Caps:400",
                "Mada:200,300,400,500,600,700,900",
                "Magra:400,700",
                "Maiden+Orange:400",
                "Maitree:200,300,400,500,600,700",
                "Major+Mono+Display:400",
                "Mako:400",
                "Mali:200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Mallanna:400",
                "Mandali:400",
                "Manjari:100,400,700",
                "Manrope:200,300,400,500,600,700,800",
                "Mansalva:400",
                "Manuale:400,500,600,700,italic,500italic,600italic,700italic",
                "Marcellus:400",
                "Marcellus+SC:400",
                "Marck+Script:400",
                "Margarine:400",
                "Markazi+Text:400,500,600,700",
                "Marko+One:400",
                "Marmelad:400",
                "Martel:200,300,400,600,700,800,900",
                "Martel+Sans:200,300,400,600,700,800,900",
                "Marvel:400,italic,700,700italic",
                "Mate:400,italic",
                "Mate+SC:400",
                "Maven+Pro:400,500,600,700,800,900",
                "McLaren:400",
                "Meddon:400",
                "MedievalSharp:400",
                "Medula+One:400",
                "Meera+Inimai:400",
                "Megrim:400",
                "Meie+Script:400",
                "Merienda:400,700",
                "Merienda+One:400",
                "Merriweather:300,300italic,400,italic,700,700italic,900,900italic",
                "Merriweather+Sans:300,300italic,400,italic,700,700italic,800,800italic",
                "Metal:400",
                "Metal+Mania:400",
                "Metamorphous:400",
                "Metrophobic:400",
                "Michroma:400",
                "Milonga:400",
                "Miltonian:400",
                "Miltonian+Tattoo:400",
                "Mina:400,700",
                "Miniver:400",
                "Miriam+Libre:400,700",
                "Mirza:400,500,600,700",
                "Miss+Fajardose:400",
                "Mitr:200,300,400,500,600,700",
                "Modak:400",
                "Modern+Antiqua:400",
                "Mogra:400",
                "Molengo:400",
                "Molle:italic",
                "Monda:400,700",
                "Monofett:400",
                "Monoton:400",
                "Monsieur+La+Doulaise:400",
                "Montaga:400",
                "Montez:400",
                "Montserrat:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Montserrat+Alternates:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Montserrat+Subrayada:400,700",
                "Moul:400",
                "Moulpali:400",
                "Mountains+of+Christmas:400,700",
                "Mouse+Memoirs:400",
                "Mr+Bedfort:400",
                "Mr+Dafoe:400",
                "Mr+De+Haviland:400",
                "Mrs+Saint+Delafield:400",
                "Mrs+Sheppards:400",
                "Mukta:200,300,400,500,600,700,800",
                "Mukta+Mahee:200,300,400,500,600,700,800",
                "Mukta+Malar:200,300,400,500,600,700,800",
                "Mukta+Vaani:200,300,400,500,600,700,800",
                "Muli:200,300,400,500,600,700,800,900,200italic,300italic,italic,500italic,600italic,700italic,800italic,900italic",
                "Mystery+Quest:400",
                "NTR:400",
                "Nanum+Brush+Script:400",
                "Nanum+Gothic:400,700,800",
                "Nanum+Gothic+Coding:400,700",
                "Nanum+Myeongjo:400,700,800",
                "Nanum+Pen+Script:400",
                "Neucha:400",
                "Neuton:200,300,400,italic,700,800",
                "New+Rocker:400",
                "News+Cycle:400,700",
                "Niconne:400",
                "Niramit:200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Nixie+One:400",
                "Nobile:400,italic,500,500italic,700,700italic",
                "Nokora:400,700",
                "Norican:400",
                "Nosifer:400",
                "Notable:400",
                "Nothing+You+Could+Do:400",
                "Noticia+Text:400,italic,700,700italic",
                "Noto+Sans:400,italic,700,700italic",
                "Noto+Sans+HK:100,300,400,500,700,900",
                "Noto+Sans+JP:100,300,400,500,700,900",
                "Noto+Sans+KR:100,300,400,500,700,900",
                "Noto+Sans+SC:100,300,400,500,700,900",
                "Noto+Sans+TC:100,300,400,500,700,900",
                "Noto+Serif:400,italic,700,700italic",
                "Noto+Serif+JP:200,300,400,500,600,700,900",
                "Noto+Serif+KR:200,300,400,500,600,700,900",
                "Noto+Serif+SC:200,300,400,500,600,700,900",
                "Noto+Serif+TC:200,300,400,500,600,700,900",
                "Nova+Cut:400",
                "Nova+Flat:400",
                "Nova+Mono:400",
                "Nova+Oval:400",
                "Nova+Round:400",
                "Nova+Script:400",
                "Nova+Slim:400",
                "Nova+Square:400",
                "Numans:400",
                "Nunito:200,200italic,300,300italic,400,italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Nunito+Sans:200,200italic,300,300italic,400,italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Odibee+Sans:400",
                "Odor+Mean+Chey:400",
                "Offside:400",
                "Old+Standard+TT:400,italic,700",
                "Oldenburg:400",
                "Oleo+Script:400,700",
                "Oleo+Script+Swash+Caps:400,700",
                "Open+Sans:300,300italic,400,italic,600,600italic,700,700italic,800,800italic",
                "Open+Sans+Condensed:300,300italic,700",
                "Oranienbaum:400",
                "Orbitron:400,500,600,700,800,900",
                "Oregano:400,italic",
                "Orienta:400",
                "Original+Surfer:400",
                "Oswald:200,300,400,500,600,700",
                "Over+the+Rainbow:400",
                "Overlock:400,italic,700,700italic,900,900italic",
                "Overlock+SC:400",
                "Overpass:100,100italic,200,200italic,300,300italic,400,italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Overpass+Mono:300,400,600,700",
                "Ovo:400",
                "Oxygen:300,400,700",
                "Oxygen+Mono:400",
                "PT+Mono:400",
                "PT+Sans:400,italic,700,700italic",
                "PT+Sans+Caption:400,700",
                "PT+Sans+Narrow:400,700",
                "PT+Serif:400,italic,700,700italic",
                "PT+Serif+Caption:400,italic",
                "Pacifico:400",
                "Padauk:400,700",
                "Palanquin:100,200,300,400,500,600,700",
                "Palanquin+Dark:400,500,600,700",
                "Pangolin:400",
                "Paprika:400",
                "Parisienne:400",
                "Passero+One:400",
                "Passion+One:400,700,900",
                "Pathway+Gothic+One:400",
                "Patrick+Hand:400",
                "Patrick+Hand+SC:400",
                "Pattaya:400",
                "Patua+One:400",
                "Pavanam:400",
                "Paytone+One:400",
                "Peddana:400",
                "Peralta:400",
                "Permanent+Marker:400",
                "Petit+Formal+Script:400",
                "Petrona:400",
                "Philosopher:400,italic,700,700italic",
                "Piedra:400",
                "Pinyon+Script:400",
                "Pirata+One:400",
                "Plaster:400",
                "Play:400,700",
                "Playball:400",
                "Playfair+Display:400,500,600,700,800,900,italic,500italic,600italic,700italic,800italic,900italic",
                "Playfair+Display+SC:400,italic,700,700italic,900,900italic",
                "Podkova:400,500,600,700,800",
                "Poiret+One:400",
                "Poller+One:400",
                "Poly:400,italic",
                "Pompiere:400",
                "Pontano+Sans:400",
                "Poor+Story:400",
                "Poppins:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Port+Lligat+Sans:400",
                "Port+Lligat+Slab:400",
                "Pragati+Narrow:400,700",
                "Prata:400",
                "Preahvihear:400",
                "Press+Start+2P:400",
                "Pridi:200,300,400,500,600,700",
                "Princess+Sofia:400",
                "Prociono:400",
                "Prompt:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Prosto+One:400",
                "Proza+Libre:400,italic,500,500italic,600,600italic,700,700italic,800,800italic",
                "Public+Sans:100,200,300,400,500,600,700,800,900,100italic,200italic,300italic,italic,500italic,600italic,700italic,800italic,900italic",
                "Puritan:400,italic,700,700italic",
                "Purple+Purse:400",
                "Quando:400",
                "Quantico:400,italic,700,700italic",
                "Quattrocento:400,700",
                "Quattrocento+Sans:400,italic,700,700italic",
                "Questrial:400",
                "Quicksand:300,400,500,600,700",
                "Quintessential:400",
                "Qwigley:400",
                "Racing+Sans+One:400",
                "Radley:400,italic",
                "Rajdhani:300,400,500,600,700",
                "Rakkas:400",
                "Raleway:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Raleway+Dots:400",
                "Ramabhadra:400",
                "Ramaraja:400",
                "Rambla:400,italic,700,700italic",
                "Rammetto+One:400",
                "Ranchers:400",
                "Rancho:400",
                "Ranga:400,700",
                "Rasa:300,400,500,600,700",
                "Rationale:400",
                "Ravi+Prakash:400",
                "Red+Hat+Display:400,italic,500,500italic,700,700italic,900,900italic",
                "Red+Hat+Text:400,italic,500,500italic,700,700italic",
                "Redressed:400",
                "Reem+Kufi:400",
                "Reenie+Beanie:400",
                "Revalia:400",
                "Rhodium+Libre:400",
                "Ribeye:400",
                "Ribeye+Marrow:400",
                "Righteous:400",
                "Risque:400",
                "Roboto:100,100italic,300,300italic,400,italic,500,500italic,700,700italic,900,900italic",
                "Roboto+Condensed:300,300italic,400,italic,700,700italic",
                "Roboto+Mono:100,100italic,300,300italic,400,italic,500,500italic,700,700italic",
                "Roboto+Slab:100,200,300,400,500,600,700,800,900",
                "Rochester:400",
                "Rock+Salt:400",
                "Rokkitt:100,200,300,400,500,600,700,800,900",
                "Romanesco:400",
                "Ropa+Sans:400,italic",
                "Rosario:300,400,500,600,700,300italic,italic,500italic,600italic,700italic",
                "Rosarivo:400,italic",
                "Rouge+Script:400",
                "Rozha+One:400",
                "Rubik:300,300italic,400,italic,500,500italic,700,700italic,900,900italic",
                "Rubik+Mono+One:400",
                "Ruda:400,700,900",
                "Rufina:400,700",
                "Ruge+Boogie:400",
                "Ruluko:400",
                "Rum+Raisin:400",
                "Ruslan+Display:400",
                "Russo+One:400",
                "Ruthie:400",
                "Rye:400",
                "Sacramento:400",
                "Sahitya:400,700",
                "Sail:400",
                "Saira:100,200,300,400,500,600,700,800,900",
                "Saira+Condensed:100,200,300,400,500,600,700,800,900",
                "Saira+Extra+Condensed:100,200,300,400,500,600,700,800,900",
                "Saira+Semi+Condensed:100,200,300,400,500,600,700,800,900",
                "Saira+Stencil+One:400",
                "Salsa:400",
                "Sanchez:400,italic",
                "Sancreek:400",
                "Sansita:400,italic,700,700italic,800,800italic,900,900italic",
                "Sarabun:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic",
                "Sarala:400,700",
                "Sarina:400",
                "Sarpanch:400,500,600,700,800,900",
                "Satisfy:400",
                "Sawarabi+Gothic:400",
                "Sawarabi+Mincho:400",
                "Scada:400,italic,700,700italic",
                "Scheherazade:400,700",
                "Schoolbell:400",
                "Scope+One:400",
                "Seaweed+Script:400",
                "Secular+One:400",
                "Sedgwick+Ave:400",
                "Sedgwick+Ave+Display:400",
                "Sen:400,500,600,700,800",
                "Sevillana:400",
                "Seymour+One:400",
                "Shadows+Into+Light:400",
                "Shadows+Into+Light+Two:400",
                "Shanti:400",
                "Share:400,italic,700,700italic",
                "Share+Tech:400",
                "Share+Tech+Mono:400",
                "Shojumaru:400",
                "Short+Stack:400",
                "Shrikhand:400",
                "Siemreap:400",
                "Sigmar+One:400",
                "Signika:300,400,600,700",
                "Signika+Negative:300,400,600,700",
                "Simonetta:400,italic,900,900italic",
                "Single+Day:400",
                "Sintony:400,700",
                "Sirin+Stencil:400",
                "Six+Caps:400",
                "Skranji:400,700",
                "Slabo+13px:400",
                "Slabo+27px:400",
                "Slackey:400",
                "Smokum:400",
                "Smythe:400",
                "Sniglet:400,800",
                "Snippet:400",
                "Snowburst+One:400",
                "Sofadi+One:400",
                "Sofia:400",
                "Solway:300,400,500,700,800",
                "Song+Myung:400",
                "Sonsie+One:400",
                "Sorts+Mill+Goudy:400,italic",
                "Source+Code+Pro:200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,900,900italic",
                "Source+Sans+Pro:200,200italic,300,300italic,400,italic,600,600italic,700,700italic,900,900italic",
                "Source+Serif+Pro:400,600,700",
                "Space+Mono:400,italic,700,700italic",
                "Special+Elite:400",
                "Spectral:200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic",
                "Spectral+SC:200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic",
                "Spicy+Rice:400",
                "Spinnaker:400",
                "Spirax:400",
                "Squada+One:400",
                "Sree+Krushnadevaraya:400",
                "Sriracha:400",
                "Srisakdi:400,700",
                "Staatliches:400",
                "Stalemate:400",
                "Stalinist+One:400",
                "Stardos+Stencil:400,700",
                "Stint+Ultra+Condensed:400",
                "Stint+Ultra+Expanded:400",
                "Stoke:300,400",
                "Strait:400",
                "Stylish:400",
                "Sue+Ellen+Francisco:400",
                "Suez+One:400",
                "Sulphur+Point:300,400,700",
                "Sumana:400,700",
                "Sunflower:300,500,700",
                "Sunshiney:400",
                "Supermercado+One:400",
                "Sura:400,700",
                "Suranna:400",
                "Suravaram:400",
                "Suwannaphum:400",
                "Swanky+and+Moo+Moo:400",
                "Syncopate:400,700",
                "Tajawal:200,300,400,500,700,800,900",
                "Tangerine:400,700",
                "Taprom:400",
                "Tauri:400",
                "Taviraj:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Teko:300,400,500,600,700",
                "Telex:400",
                "Tenali+Ramakrishna:400",
                "Tenor+Sans:400",
                "Text+Me+One:400",
                "Thasadith:400,italic,700,700italic",
                "The+Girl+Next+Door:400",
                "Tienne:400,700,900",
                "Tillana:400,500,600,700,800",
                "Timmana:400",
                "Tinos:400,italic,700,700italic",
                "Titan+One:400",
                "Titillium+Web:200,200italic,300,300italic,400,italic,600,600italic,700,700italic,900",
                "Tomorrow:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Trade+Winds:400",
                "Trirong:100,100italic,200,200italic,300,300italic,400,italic,500,500italic,600,600italic,700,700italic,800,800italic,900,900italic",
                "Trocchi:400",
                "Trochut:400,italic,700",
                "Trykker:400",
                "Tulpen+One:400",
                "Turret+Road:200,300,400,500,700,800",
                "Ubuntu:300,300italic,400,italic,500,500italic,700,700italic",
                "Ubuntu+Condensed:400",
                "Ubuntu+Mono:400,italic,700,700italic",
                "Ultra:400",
                "Uncial+Antiqua:400",
                "Underdog:400",
                "Unica+One:400",
                "UnifrakturCook:700",
                "UnifrakturMaguntia:400",
                "Unkempt:400,700",
                "Unlock:400",
                "Unna:400,italic,700,700italic",
                "VT323:400",
                "Vampiro+One:400",
                "Varela:400",
                "Varela+Round:400",
                "Vast+Shadow:400",
                "Vesper+Libre:400,500,700,900",
                "Vibes:400",
                "Vibur:400",
                "Vidaloka:400",
                "Viga:400",
                "Voces:400",
                "Volkhov:400,italic,700,700italic",
                "Vollkorn:400,italic,600,600italic,700,700italic,900,900italic",
                "Vollkorn+SC:400,600,700,900",
                "Voltaire:400",
                "Waiting+for+the+Sunrise:400",
                "Wallpoet:400",
                "Walter+Turncoat:400",
                "Warnes:400",
                "Wellfleet:400",
                "Wendy+One:400",
                "Wire+One:400",
                "Work+Sans:100,200,300,400,500,600,700,800,900",
                "Yanone+Kaffeesatz:200,300,400,500,600,700",
                "Yantramanav:100,300,400,500,700,900",
                "Yatra+One:400",
                "Yellowtail:400",
                "Yeon+Sung:400",
                "Yeseva+One:400",
                "Yesteryear:400",
                "Yrsa:300,400,500,600,700",
                "ZCOOL+KuaiLe:400",
                "ZCOOL+QingKe+HuangYou:400",
                "ZCOOL+XiaoWei:400",
                "Zeyada:400",
                "Zhi+Mang+Xing:400",
                "Zilla+Slab:300,300italic,400,italic,500,500italic,600,600italic,700,700italic",
                "Zilla+Slab+Highlight:400,700",
            ],
        };

        var Fontselect = (function () {
            function Fontselect(original, o) {
                if (!o.systemFonts) {
                    o.systemFonts = [];
                }
                if (!o.localFonts) {
                    o.localFonts = [];
                }
                if (!o.googleFonts) {
                    o.googleFonts = [];
                }

                var googleFonts = [];
                for (var i = 0; i < o.googleFonts.length; i++) {
                    var item = o.googleFonts[i].split(":"); // Unna:regular,italic,700,700italic
                    var fontName = item[0],
                        fontVariants = item[1] ? item[1].split(",") : [];
                    for (var v = 0; v < fontVariants.length; v++) {
                        googleFonts.push(fontName + ":" + fontVariants[v]);
                    }
                }
                o.googleFonts = googleFonts;

                this.options = o;
                this.$original = $(original);
                this.setupHtml();
                this.getVisibleFonts();
                this.bindEvents();
                this.query = "";
                this.keyActive = false;
                this.searchBoxHeight = 0;

                var font = this.$original.val();
                if (font) {
                    this.updateSelected();
                    this.addFontLink(font);
                }
            }

            Fontselect.prototype = {
                keyDown: function (e) {
                    function stop(e) {
                        e.preventDefault();
                        e.stopPropagation();
                    }

                    this.keyActive = true;
                    if (e.keyCode == 27) {
                        // Escape
                        stop(e);
                        this.toggleDropdown("hide");
                        return;
                    }
                    if (e.keyCode == 38) {
                        // Cursor up
                        stop(e);
                        var $li = $("li.active", this.$results),
                            $pli = $li.prev("li");
                        if ($pli.length > 0) {
                            $li.removeClass("active");
                            this.$results.scrollTop($pli.addClass("active")[0].offsetTop - this.searchBoxHeight);
                        }
                        return;
                    }
                    if (e.keyCode == 40) {
                        // Cursor down
                        stop(e);
                        var $li = $("li.active", this.$results),
                            $nli = $li.next("li");
                        if ($nli.length > 0) {
                            $li.removeClass("active");
                            this.$results.scrollTop($nli.addClass("active")[0].offsetTop - this.searchBoxHeight);
                        }
                        return;
                    }
                    if (e.keyCode == 13) {
                        // Enter
                        stop(e);
                        $("li.active", this.$results).trigger("click");
                        return;
                    }
                    this.query += String.fromCharCode(e.keyCode).toLowerCase();
                    var $found = $("li[data-query^='" + this.query + "']").first();
                    if ($found.length > 0) {
                        $("li.active", this.$results).removeClass("active");
                        this.$results.scrollTop($found.addClass("active")[0].offsetTop);
                    }
                },

                keyUp: function (e) {
                    this.keyActive = false;
                },

                bindEvents: function () {
                    var self = this;

                    $("li", this.$results)
                        .click(__bind(this.selectFont, this))
                        .mouseover(__bind(this.activateFont, this));

                    this.$select.click(
                        __bind(function () {
                            self.toggleDropdown("show");
                        }, this)
                    );

                    // Call like so: $("input[name='ffSelect']").trigger('setFont', [fontFamily, fontWeight]);
                    this.$original.on("setFont", function (e, fontFamily, fontWeight) {
                        //self.setFont(fontFamily, fontWeight);
                    });

                    this.$original.on("change", function () {
                        self.updateSelected();
                        self.addFontLink($("li.active", self.$results).data("value"));
                    });

                    if (this.options.searchable) {
                        this.$input.on("keyup", function () {
                            var q = this.value.toLowerCase();
                            // Hide options that don't match query:
                            $("li", self.$results).each(function () {
                                if ($(this).text().toLowerCase().indexOf(q) == -1) {
                                    $(this).hide();
                                } else {
                                    $(this).show();
                                }
                            });
                        });
                    }

                    $(document).on("click", function (e) {
                        if ($(e.target).closest("." + self.options.style).length === 0) {
                            self.toggleDropdown("hide");
                        }
                    });
                },

                toggleDropdown: function (hideShow) {
                    if (hideShow === "hide") {
                        // Make inactive
                        this.$element.off("keydown keyup");
                        this.query = "";
                        this.keyActive = false;
                        this.$element.removeClass("font-select-active");
                        this.$drop.hide();
                        clearInterval(this.visibleInterval);
                    } else {
                        // Make active
                        this.$element.on("keydown", __bind(this.keyDown, this));
                        this.$element.on("keyup", __bind(this.keyUp, this));
                        this.$element.addClass("font-select-active");
                        this.$drop.show();

                        this.visibleInterval = setInterval(__bind(this.getVisibleFonts, this), 500);
                        this.searchBoxHeight = this.$search.outerHeight();
                        this.moveToSelected();

                        /*
						if (this.options.searchable) {
							// Focus search box
							$this.$input.focus();
						}
						*/
                    }
                },

                selectFont: function () {
                    var font = $("li.active", this.$results).data("value");
                    this.$original.val(font).change();
                    this.updateSelected();
                    this.toggleDropdown("hide"); // Hide dropdown
                },

                moveToSelected: function () {
                    var font = this.$original.val().replace(/ /g, "+");
                    var $li = font
                        ? $("li[data-value='" + font + "']", this.$results)
                        : ($li = $("li", this.$results).first());
                    this.$results.scrollTop($li.addClass("active")[0].offsetTop - this.searchBoxHeight);
                },

                activateFont: function (e) {
                    if (this.keyActive) {
                        return;
                    }
                    $("li.active", this.$results).removeClass("active");
                    $(e.target).addClass("active");
                },

                updateSelected: function () {
                    var font = this.$original.val();
                    $("span", this.$element).text(this.toReadable(font)).css(this.toStyle(font));
                },

                setFont: function (fontFamily, fontWeight) {
                    fontWeight = fontWeight || 400;

                    var fontSpec = fontFamily.replace(/ /g, "+") + ":" + fontWeight;

                    var $li = $("li[data-value='" + fontSpec + "']", this.$results);
                    if ($li.length == 0) {
                        fontSpec = fontFamily.replace(/ /g, "+");
                    }
                    $li = $("li[data-value='" + fontSpec + "']", this.$results);
                    $("li.active", this.$results).removeClass("active");
                    $li.addClass("active");

                    this.$original.val(fontSpec);
                    this.updateSelected();
                    this.addFontLink($li.data("value"));
                },

                setupHtml: function () {
                    this.$original.hide();
                    this.$element = $("<div>", { class: this.options.style });
                    this.$select = $('<span tabindex="0">' + this.options.placeholder + "</span>");
                    this.$search = $("<div>", { class: "fs-search" });
                    this.$input = $("<input>", { type: "text" });
                    if (this.options.placeholderSearch) {
                        this.$input.attr("placeholder", this.options.placeholderSearch);
                    }
                    this.$search.append(this.$input);
                    this.$drop = $("<div>", { class: "fs-drop" });
                    this.$results = $("<ul>", { class: "fs-results" });
                    this.$original.after(this.$element.append(this.$select, this.$drop));
                    this.options.searchable && this.$drop.append(this.$search);
                    this.$drop.append(this.$results.append(this.fontsAsHtml())).hide();
                },

                fontsAsHtml: function () {
                    var i,
                        r,
                        s,
                        style,
                        h = "";
                    var systemFonts = this.options.systemFonts;
                    var localFonts = this.options.localFonts;
                    var googleFonts = this.options.googleFonts;

                    for (i = 0; i < systemFonts.length; i++) {
                        r = this.toReadable(systemFonts[i]);
                        s = this.toStyle(systemFonts[i]);
                        style = "font-family:" + s["font-family"];
                        if ((localFonts.length > 0 || googleFonts.length > 0) && i == systemFonts.length - 1) {
                            style += ";border-bottom:1px solid #444"; // Separator after last system font
                        }
                        h +=
                            '<li data-value="' +
                            systemFonts[i] +
                            '" data-query="' +
                            systemFonts[i].toLowerCase() +
                            '" style="' +
                            style +
                            '">' +
                            r +
                            "</li>";
                    }

                    for (i = 0; i < localFonts.length; i++) {
                        r = this.toReadable(localFonts[i]);
                        s = this.toStyle(localFonts[i]);
                        style = "font-family:" + s["font-family"];
                        if (googleFonts.length > 0 && i == localFonts.length - 1) {
                            style += ";border-bottom:1px solid #444"; // Separator after last local font
                        }
                        h +=
                            '<li data-value="' +
                            localFonts[i] +
                            '" data-query="' +
                            localFonts[i].toLowerCase() +
                            '" style="' +
                            style +
                            '">' +
                            r +
                            "</li>";
                    }

                    for (i = 0; i < googleFonts.length; i++) {
                        r = this.toReadable(googleFonts[i]);
                        s = this.toStyle(googleFonts[i]);
                        style =
                            "font-family:" +
                            s["font-family"] +
                            ";font-weight:" +
                            s["font-weight"] +
                            ";font-style:" +
                            s["font-style"];
                        h +=
                            '<li data-value="' +
                            googleFonts[i] +
                            '" data-query="' +
                            googleFonts[i].toLowerCase() +
                            '" style="' +
                            style +
                            '">' +
                            r +
                            "</li>";
                    }

                    return h;
                },

                toReadable: function (font) {
                    return font.replace(/[\+|:]/g, " ").replace(/(\d+)italic/, "$1 italic");
                },

                toStyle: function (font) {
                    var t = font.split(":"),
                        italic = false;
                    if (t[1] && /italic/.test(t[1])) {
                        italic = true;
                        t[1] = t[1].replace("italic", "");
                    }

                    return {
                        "font-family": "'" + this.toReadable(t[0]) + "'",
                        "font-weight": t[1] || 400,
                        "font-style": italic ? "italic" : "normal",
                    };
                },

                getVisibleFonts: function () {
                    if (this.$results.is(":hidden")) {
                        return;
                    }

                    var fs = this;
                    var top = this.$results.scrollTop();
                    var bottom = top + this.$results.height();

                    if (this.options.lookahead) {
                        var li = $("li", this.$results).first().height();
                        bottom += li * this.options.lookahead;
                    }

                    $("li:visible", this.$results).each(function () {
                        var ft = $(this).position().top + top;
                        var fb = ft + $(this).height();

                        if (fb >= top && ft <= bottom) {
                            fs.addFontLink($(this).data("value"));
                        }
                    });
                },

                addFontLink: function (font) {
                    if (fontsLoaded[font]) {
                        return;
                    }
                    fontsLoaded[font] = true;

                    if (this.options.googleFonts.indexOf(font) > -1) {
                        $(this.options.styleTarget).after(
                            '<link jq-fontselect href="' +
                                this.options.googleApi +
                                font +
                                '" rel="stylesheet" type="text/css">'
                        );
                    } else if (this.options.localFonts.indexOf(font) > -1) {
                        font = this.toReadable(font);
                        $(this.options.styleTarget).append(
                            "<style jq-fontselect> @font-face { font-family:'" +
                                font +
                                "'; font-style:normal; font-weight:400; src:local('" +
                                font +
                                "'), url('" +
                                this.options.localFontsUrl +
                                font +
                                ".woff') format('woff'); } </style>"
                        );
                    }
                    // System fonts need not be loaded!
                },

                getLoadedFonts: function () {
                    return fontsLoaded;
                },
            }; // End prototype

            return Fontselect;
        })();

        if (options === undefined || typeof options === "object") {
            this.each(function () {
                var plugin = new Fontselect(this, $.extend({}, settings, options));

                $(this).data("_fontselect", plugin);

                return plugin;
            });

            return $(this);
        } else if (typeof options === "string" && ["setFont", "getLoadedFonts"].indexOf(options) >= 0) {
            var returns = undefined;

            this.each(function () {
                var instance = $(this).data("_fontselect");

                if (instance && typeof instance[options] === "function") {
                    returns = instance[options].apply(instance, Array.prototype.slice.call(arguments, 1));
                }
            });

            return returns !== undefined ? returns : $(this);
        }
    };
})(jQuery);
;
/*! Pickr 1.8.2 MIT | https://github.com/Simonwep/pickr */
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Pickr=e():t.Pickr=e()}(self,(function(){return(()=>{"use strict";var t={d:(e,o)=>{for(var n in o)t.o(o,n)&&!t.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:o[n]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.d(e,{default:()=>L});var o={};function n(t,e,o,n,i={}){e instanceof HTMLCollection||e instanceof NodeList?e=Array.from(e):Array.isArray(e)||(e=[e]),Array.isArray(o)||(o=[o]);for(const s of e)for(const e of o)s[t](e,n,{capture:!1,...i});return Array.prototype.slice.call(arguments,1)}t.r(o),t.d(o,{adjustableInputNumbers:()=>p,createElementFromString:()=>r,createFromTemplate:()=>a,eventPath:()=>l,off:()=>s,on:()=>i,resolveElement:()=>c});const i=n.bind(null,"addEventListener"),s=n.bind(null,"removeEventListener");function r(t){const e=document.createElement("div");return e.innerHTML=t.trim(),e.firstElementChild}function a(t){const e=(t,e)=>{const o=t.getAttribute(e);return t.removeAttribute(e),o},o=(t,n={})=>{const i=e(t,":obj"),s=e(t,":ref"),r=i?n[i]={}:n;s&&(n[s]=t);for(const n of Array.from(t.children)){const t=e(n,":arr"),i=o(n,t?{}:r);t&&(r[t]||(r[t]=[])).push(Object.keys(i).length?i:n)}return n};return o(r(t))}function l(t){let e=t.path||t.composedPath&&t.composedPath();if(e)return e;let o=t.target.parentElement;for(e=[t.target,o];o=o.parentElement;)e.push(o);return e.push(document,window),e}function c(t){return t instanceof Element?t:"string"==typeof t?t.split(/>>/g).reduce(((t,e,o,n)=>(t=t.querySelector(e),o<n.length-1?t.shadowRoot:t)),document):null}function p(t,e=(t=>t)){function o(o){const n=[.001,.01,.1][Number(o.shiftKey||2*o.ctrlKey)]*(o.deltaY<0?1:-1);let i=0,s=t.selectionStart;t.value=t.value.replace(/[\d.]+/g,((t,o)=>o<=s&&o+t.length>=s?(s=o,e(Number(t),n,i)):(i++,t))),t.focus(),t.setSelectionRange(s,s),o.preventDefault(),t.dispatchEvent(new Event("input"))}i(t,"focus",(()=>i(window,"wheel",o,{passive:!1}))),i(t,"blur",(()=>s(window,"wheel",o)))}const{min:u,max:h,floor:d,round:m}=Math;function f(t,e,o){e/=100,o/=100;const n=d(t=t/360*6),i=t-n,s=o*(1-e),r=o*(1-i*e),a=o*(1-(1-i)*e),l=n%6;return[255*[o,r,s,s,a,o][l],255*[a,o,o,r,s,s][l],255*[s,s,a,o,o,r][l]]}function v(t,e,o){const n=(2-(e/=100))*(o/=100)/2;return 0!==n&&(e=1===n?0:n<.5?e*o/(2*n):e*o/(2-2*n)),[t,100*e,100*n]}function b(t,e,o){const n=u(t/=255,e/=255,o/=255),i=h(t,e,o),s=i-n;let r,a;if(0===s)r=a=0;else{a=s/i;const n=((i-t)/6+s/2)/s,l=((i-e)/6+s/2)/s,c=((i-o)/6+s/2)/s;t===i?r=c-l:e===i?r=1/3+n-c:o===i&&(r=2/3+l-n),r<0?r+=1:r>1&&(r-=1)}return[360*r,100*a,100*i]}function y(t,e,o,n){e/=100,o/=100;return[...b(255*(1-u(1,(t/=100)*(1-(n/=100))+n)),255*(1-u(1,e*(1-n)+n)),255*(1-u(1,o*(1-n)+n)))]}function g(t,e,o){e/=100;const n=2*(e*=(o/=100)<.5?o:1-o)/(o+e)*100,i=100*(o+e);return[t,isNaN(n)?0:n,i]}function _(t){return b(...t.match(/.{2}/g).map((t=>parseInt(t,16))))}function w(t){t=t.match(/^[a-zA-Z]+$/)?function(t){if("black"===t.toLowerCase())return"#000";const e=document.createElement("canvas").getContext("2d");return e.fillStyle=t,"#000"===e.fillStyle?null:e.fillStyle}(t):t;const e={cmyk:/^cmyk[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)/i,rgba:/^((rgba)|rgb)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hsla:/^((hsla)|hsl)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hsva:/^((hsva)|hsv)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hexa:/^#?(([\dA-Fa-f]{3,4})|([\dA-Fa-f]{6})|([\dA-Fa-f]{8}))$/i},o=t=>t.map((t=>/^(|\d+)\.\d+|\d+$/.test(t)?Number(t):void 0));let n;t:for(const i in e){if(!(n=e[i].exec(t)))continue;const s=t=>!!n[2]==("number"==typeof t);switch(i){case"cmyk":{const[,t,e,s,r]=o(n);if(t>100||e>100||s>100||r>100)break t;return{values:y(t,e,s,r),type:i}}case"rgba":{const[,,,t,e,r,a]=o(n);if(t>255||e>255||r>255||a<0||a>1||!s(a))break t;return{values:[...b(t,e,r),a],a,type:i}}case"hexa":{let[,t]=n;4!==t.length&&3!==t.length||(t=t.split("").map((t=>t+t)).join(""));const e=t.substring(0,6);let o=t.substring(6);return o=o?parseInt(o,16)/255:void 0,{values:[..._(e),o],a:o,type:i}}case"hsla":{const[,,,t,e,r,a]=o(n);if(t>360||e>100||r>100||a<0||a>1||!s(a))break t;return{values:[...g(t,e,r),a],a,type:i}}case"hsva":{const[,,,t,e,r,a]=o(n);if(t>360||e>100||r>100||a<0||a>1||!s(a))break t;return{values:[t,e,r,a],a,type:i}}}}return{values:null,type:null}}function A(t=0,e=0,o=0,n=1){const i=(t,e)=>(o=-1)=>e(~o?t.map((t=>Number(t.toFixed(o)))):t),s={h:t,s:e,v:o,a:n,toHSVA(){const t=[s.h,s.s,s.v,s.a];return t.toString=i(t,(t=>`hsva(${t[0]}, ${t[1]}%, ${t[2]}%, ${s.a})`)),t},toHSLA(){const t=[...v(s.h,s.s,s.v),s.a];return t.toString=i(t,(t=>`hsla(${t[0]}, ${t[1]}%, ${t[2]}%, ${s.a})`)),t},toRGBA(){const t=[...f(s.h,s.s,s.v),s.a];return t.toString=i(t,(t=>`rgba(${t[0]}, ${t[1]}, ${t[2]}, ${s.a})`)),t},toCMYK(){const t=function(t,e,o){const n=f(t,e,o),i=n[0]/255,s=n[1]/255,r=n[2]/255,a=u(1-i,1-s,1-r);return[100*(1===a?0:(1-i-a)/(1-a)),100*(1===a?0:(1-s-a)/(1-a)),100*(1===a?0:(1-r-a)/(1-a)),100*a]}(s.h,s.s,s.v);return t.toString=i(t,(t=>`cmyk(${t[0]}%, ${t[1]}%, ${t[2]}%, ${t[3]}%)`)),t},toHEXA(){const t=function(t,e,o){return f(t,e,o).map((t=>m(t).toString(16).padStart(2,"0")))}(s.h,s.s,s.v),e=s.a>=1?"":Number((255*s.a).toFixed(0)).toString(16).toUpperCase().padStart(2,"0");return e&&t.push(e),t.toString=()=>`#${t.join("").toUpperCase()}`,t},clone:()=>A(s.h,s.s,s.v,s.a)};return s}const C=t=>Math.max(Math.min(t,1),0);function $(t){const e={options:Object.assign({lock:null,onchange:()=>0,onstop:()=>0},t),_keyboard(t){const{options:o}=e,{type:n,key:i}=t;if(document.activeElement===o.wrapper){const{lock:o}=e.options,s="ArrowUp"===i,r="ArrowRight"===i,a="ArrowDown"===i,l="ArrowLeft"===i;if("keydown"===n&&(s||r||a||l)){let n=0,i=0;"v"===o?n=s||r?1:-1:"h"===o?n=s||r?-1:1:(i=s?-1:a?1:0,n=l?-1:r?1:0),e.update(C(e.cache.x+.01*n),C(e.cache.y+.01*i)),t.preventDefault()}else i.startsWith("Arrow")&&(e.options.onstop(),t.preventDefault())}},_tapstart(t){i(document,["mouseup","touchend","touchcancel"],e._tapstop),i(document,["mousemove","touchmove"],e._tapmove),t.cancelable&&t.preventDefault(),e._tapmove(t)},_tapmove(t){const{options:o,cache:n}=e,{lock:i,element:s,wrapper:r}=o,a=r.getBoundingClientRect();let l=0,c=0;if(t){const e=t&&t.touches&&t.touches[0];l=t?(e||t).clientX:0,c=t?(e||t).clientY:0,l<a.left?l=a.left:l>a.left+a.width&&(l=a.left+a.width),c<a.top?c=a.top:c>a.top+a.height&&(c=a.top+a.height),l-=a.left,c-=a.top}else n&&(l=n.x*a.width,c=n.y*a.height);"h"!==i&&(s.style.left=`calc(${l/a.width*100}% - ${s.offsetWidth/2}px)`),"v"!==i&&(s.style.top=`calc(${c/a.height*100}% - ${s.offsetHeight/2}px)`),e.cache={x:l/a.width,y:c/a.height};const p=C(l/a.width),u=C(c/a.height);switch(i){case"v":return o.onchange(p);case"h":return o.onchange(u);default:return o.onchange(p,u)}},_tapstop(){e.options.onstop(),s(document,["mouseup","touchend","touchcancel"],e._tapstop),s(document,["mousemove","touchmove"],e._tapmove)},trigger(){e._tapmove()},update(t=0,o=0){const{left:n,top:i,width:s,height:r}=e.options.wrapper.getBoundingClientRect();"h"===e.options.lock&&(o=t),e._tapmove({clientX:n+s*t,clientY:i+r*o})},destroy(){const{options:t,_tapstart:o,_keyboard:n}=e;s(document,["keydown","keyup"],n),s([t.wrapper,t.element],"mousedown",o),s([t.wrapper,t.element],"touchstart",o,{passive:!1})}},{options:o,_tapstart:n,_keyboard:r}=e;return i([o.wrapper,o.element],"mousedown",n),i([o.wrapper,o.element],"touchstart",n,{passive:!1}),i(document,["keydown","keyup"],r),e}function k(t={}){t=Object.assign({onchange:()=>0,className:"",elements:[]},t);const e=i(t.elements,"click",(e=>{t.elements.forEach((o=>o.classList[e.target===o?"add":"remove"](t.className))),t.onchange(e),e.stopPropagation()}));return{destroy:()=>s(...e)}}const S={variantFlipOrder:{start:"sme",middle:"mse",end:"ems"},positionFlipOrder:{top:"tbrl",right:"rltb",bottom:"btrl",left:"lrbt"},position:"bottom",margin:8},O=(t,e,o)=>{const{container:n,margin:i,position:s,variantFlipOrder:r,positionFlipOrder:a}={container:document.documentElement.getBoundingClientRect(),...S,...o},{left:l,top:c}=e.style;e.style.left="0",e.style.top="0";const p=t.getBoundingClientRect(),u=e.getBoundingClientRect(),h={t:p.top-u.height-i,b:p.bottom+i,r:p.right+i,l:p.left-u.width-i},d={vs:p.left,vm:p.left+p.width/2+-u.width/2,ve:p.left+p.width-u.width,hs:p.top,hm:p.bottom-p.height/2-u.height/2,he:p.bottom-u.height},[m,f="middle"]=s.split("-"),v=a[m],b=r[f],{top:y,left:g,bottom:_,right:w}=n;for(const t of v){const o="t"===t||"b"===t,n=h[t],[i,s]=o?["top","left"]:["left","top"],[r,a]=o?[u.height,u.width]:[u.width,u.height],[l,c]=o?[_,w]:[w,_],[p,m]=o?[y,g]:[g,y];if(!(n<p||n+r>l))for(const r of b){const l=d[(o?"v":"h")+r];if(!(l<m||l+a>c))return e.style[s]=l-u[s]+"px",e.style[i]=n-u[i]+"px",t+r}}return e.style.left=l,e.style.top=c,null};function E(t,e,o){return e in t?Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0,writable:!0}):t[e]=o,t}class L{constructor(t){E(this,"_initializingActive",!0),E(this,"_recalc",!0),E(this,"_nanopop",null),E(this,"_root",null),E(this,"_color",A()),E(this,"_lastColor",A()),E(this,"_swatchColors",[]),E(this,"_setupAnimationFrame",null),E(this,"_eventListener",{init:[],save:[],hide:[],show:[],clear:[],change:[],changestop:[],cancel:[],swatchselect:[]}),this.options=t=Object.assign({...L.DEFAULT_OPTIONS},t);const{swatches:e,components:o,theme:n,sliders:i,lockOpacity:s,padding:r}=t;["nano","monolith"].includes(n)&&!i&&(t.sliders="h"),o.interaction||(o.interaction={});const{preview:a,opacity:l,hue:c,palette:p}=o;o.opacity=!s&&l,o.palette=p||a||l||c,this._preBuild(),this._buildComponents(),this._bindEvents(),this._finalBuild(),e&&e.length&&e.forEach((t=>this.addSwatch(t)));const{button:u,app:h}=this._root;this._nanopop=((t,e,o)=>{const n="object"!=typeof t||t instanceof HTMLElement?{reference:t,popper:e,...o}:t;return{update(t=n){const{reference:e,popper:o}=Object.assign(n,t);if(!o||!e)throw new Error("Popper- or reference-element missing.");return O(e,o,n)}}})(u,h,{margin:r}),u.setAttribute("role","button"),u.setAttribute("aria-label",this._t("btn:toggle"));const d=this;this._setupAnimationFrame=requestAnimationFrame((function e(){if(!h.offsetWidth)return requestAnimationFrame(e);d.setColor(t.default),d._rePositioningPicker(),t.defaultRepresentation&&(d._representation=t.defaultRepresentation,d.setColorRepresentation(d._representation)),t.showAlways&&d.show(),d._initializingActive=!1,d._emit("init")}))}_preBuild(){const{options:t}=this;for(const e of["el","container"])t[e]=c(t[e]);this._root=(t=>{const{components:e,useAsButton:o,inline:n,appClass:i,theme:s,lockOpacity:r}=t.options,l=t=>t?"":'style="display:none" hidden',c=e=>t._t(e),p=a(`\n      <div :ref="root" class="pickr">\n\n        ${o?"":'<button type="button" :ref="button" class="pcr-button"></button>'}\n\n        <div :ref="app" class="pcr-app ${i||""}" data-theme="${s}" ${n?'style="position: unset"':""} aria-label="${c("ui:dialog")}" role="window">\n          <div class="pcr-selection" ${l(e.palette)}>\n            <div :obj="preview" class="pcr-color-preview" ${l(e.preview)}>\n              <button type="button" :ref="lastColor" class="pcr-last-color" aria-label="${c("btn:last-color")}"></button>\n              <div :ref="currentColor" class="pcr-current-color"></div>\n            </div>\n\n            <div :obj="palette" class="pcr-color-palette">\n              <div :ref="picker" class="pcr-picker"></div>\n              <div :ref="palette" class="pcr-palette" tabindex="0" aria-label="${c("aria:palette")}" role="listbox"></div>\n            </div>\n\n            <div :obj="hue" class="pcr-color-chooser" ${l(e.hue)}>\n              <div :ref="picker" class="pcr-picker"></div>\n              <div :ref="slider" class="pcr-hue pcr-slider" tabindex="0" aria-label="${c("aria:hue")}" role="slider"></div>\n            </div>\n\n            <div :obj="opacity" class="pcr-color-opacity" ${l(e.opacity)}>\n              <div :ref="picker" class="pcr-picker"></div>\n              <div :ref="slider" class="pcr-opacity pcr-slider" tabindex="0" aria-label="${c("aria:opacity")}" role="slider"></div>\n            </div>\n          </div>\n\n          <div class="pcr-swatches ${e.palette?"":"pcr-last"}" :ref="swatches"></div>\n\n          <div :obj="interaction" class="pcr-interaction" ${l(Object.keys(e.interaction).length)}>\n            <input :ref="result" class="pcr-result" type="text" spellcheck="false" ${l(e.interaction.input)} aria-label="${c("aria:input")}">\n\n            <input :arr="options" class="pcr-type" data-type="HEXA" value="${r?"HEX":"HEXA"}" type="button" ${l(e.interaction.hex)}>\n            <input :arr="options" class="pcr-type" data-type="RGBA" value="${r?"RGB":"RGBA"}" type="button" ${l(e.interaction.rgba)}>\n            <input :arr="options" class="pcr-type" data-type="HSLA" value="${r?"HSL":"HSLA"}" type="button" ${l(e.interaction.hsla)}>\n            <input :arr="options" class="pcr-type" data-type="HSVA" value="${r?"HSV":"HSVA"}" type="button" ${l(e.interaction.hsva)}>\n            <input :arr="options" class="pcr-type" data-type="CMYK" value="CMYK" type="button" ${l(e.interaction.cmyk)}>\n\n            <input :ref="save" class="pcr-save" value="${c("btn:save")}" type="button" ${l(e.interaction.save)} aria-label="${c("aria:btn:save")}">\n            <input :ref="cancel" class="pcr-cancel" value="${c("btn:cancel")}" type="button" ${l(e.interaction.cancel)} aria-label="${c("aria:btn:cancel")}">\n            <input :ref="clear" class="pcr-clear" value="${c("btn:clear")}" type="button" ${l(e.interaction.clear)} aria-label="${c("aria:btn:clear")}">\n          </div>\n        </div>\n      </div>\n    `),u=p.interaction;return u.options.find((t=>!t.hidden&&!t.classList.add("active"))),u.type=()=>u.options.find((t=>t.classList.contains("active"))),p})(this),t.useAsButton&&(this._root.button=t.el),t.container.appendChild(this._root.root)}_finalBuild(){const t=this.options,e=this._root;if(t.container.removeChild(e.root),t.inline){const o=t.el.parentElement;t.el.nextSibling?o.insertBefore(e.app,t.el.nextSibling):o.appendChild(e.app)}else t.container.appendChild(e.app);t.useAsButton?t.inline&&t.el.remove():t.el.parentNode.replaceChild(e.root,t.el),t.disabled&&this.disable(),t.comparison||(e.button.style.transition="none",t.useAsButton||(e.preview.lastColor.style.transition="none")),this.hide()}_buildComponents(){const t=this,e=this.options.components,o=(t.options.sliders||"v").repeat(2),[n,i]=o.match(/^[vh]+$/g)?o:[],s=()=>this._color||(this._color=this._lastColor.clone()),r={palette:$({element:t._root.palette.picker,wrapper:t._root.palette.palette,onstop:()=>t._emit("changestop","slider",t),onchange(o,n){if(!e.palette)return;const i=s(),{_root:r,options:a}=t,{lastColor:l,currentColor:c}=r.preview;t._recalc&&(i.s=100*o,i.v=100-100*n,i.v<0&&(i.v=0),t._updateOutput("slider"));const p=i.toRGBA().toString(0);this.element.style.background=p,this.wrapper.style.background=`\n                        linear-gradient(to top, rgba(0, 0, 0, ${i.a}), transparent),\n                        linear-gradient(to left, hsla(${i.h}, 100%, 50%, ${i.a}), rgba(255, 255, 255, ${i.a}))\n                    `,a.comparison?a.useAsButton||t._lastColor||l.style.setProperty("--pcr-color",p):(r.button.style.setProperty("--pcr-color",p),r.button.classList.remove("clear"));const u=i.toHEXA().toString();for(const{el:e,color:o}of t._swatchColors)e.classList[u===o.toHEXA().toString()?"add":"remove"]("pcr-active");c.style.setProperty("--pcr-color",p)}}),hue:$({lock:"v"===i?"h":"v",element:t._root.hue.picker,wrapper:t._root.hue.slider,onstop:()=>t._emit("changestop","slider",t),onchange(o){if(!e.hue||!e.palette)return;const n=s();t._recalc&&(n.h=360*o),this.element.style.backgroundColor=`hsl(${n.h}, 100%, 50%)`,r.palette.trigger()}}),opacity:$({lock:"v"===n?"h":"v",element:t._root.opacity.picker,wrapper:t._root.opacity.slider,onstop:()=>t._emit("changestop","slider",t),onchange(o){if(!e.opacity||!e.palette)return;const n=s();t._recalc&&(n.a=Math.round(100*o)/100),this.element.style.background=`rgba(0, 0, 0, ${n.a})`,r.palette.trigger()}}),selectable:k({elements:t._root.interaction.options,className:"active",onchange(e){t._representation=e.target.getAttribute("data-type").toUpperCase(),t._recalc&&t._updateOutput("swatch")}})};this._components=r}_bindEvents(){const{_root:t,options:e}=this,o=[i(t.interaction.clear,"click",(()=>this._clearColor())),i([t.interaction.cancel,t.preview.lastColor],"click",(()=>{this.setHSVA(...(this._lastColor||this._color).toHSVA(),!0),this._emit("cancel")})),i(t.interaction.save,"click",(()=>{!this.applyColor()&&!e.showAlways&&this.hide()})),i(t.interaction.result,["keyup","input"],(t=>{this.setColor(t.target.value,!0)&&!this._initializingActive&&(this._emit("change",this._color,"input",this),this._emit("changestop","input",this)),t.stopImmediatePropagation()})),i(t.interaction.result,["focus","blur"],(t=>{this._recalc="blur"===t.type,this._recalc&&this._updateOutput(null)})),i([t.palette.palette,t.palette.picker,t.hue.slider,t.hue.picker,t.opacity.slider,t.opacity.picker],["mousedown","touchstart"],(()=>this._recalc=!0),{passive:!0})];if(!e.showAlways){const n=e.closeWithKey;o.push(i(t.button,"click",(()=>this.isOpen()?this.hide():this.show())),i(document,"keyup",(t=>this.isOpen()&&(t.key===n||t.code===n)&&this.hide())),i(document,["touchstart","mousedown"],(e=>{this.isOpen()&&!l(e).some((e=>e===t.app||e===t.button))&&this.hide()}),{capture:!0}))}if(e.adjustableNumbers){const e={rgba:[255,255,255,1],hsva:[360,100,100,1],hsla:[360,100,100,1],cmyk:[100,100,100,100]};p(t.interaction.result,((t,o,n)=>{const i=e[this.getColorRepresentation().toLowerCase()];if(i){const e=i[n],s=t+(e>=100?1e3*o:o);return s<=0?0:Number((s<e?s:e).toPrecision(3))}return t}))}if(e.autoReposition&&!e.inline){let t=null;const n=this;o.push(i(window,["scroll","resize"],(()=>{n.isOpen()&&(e.closeOnScroll&&n.hide(),null===t?(t=setTimeout((()=>t=null),100),requestAnimationFrame((function e(){n._rePositioningPicker(),null!==t&&requestAnimationFrame(e)}))):(clearTimeout(t),t=setTimeout((()=>t=null),100)))}),{capture:!0}))}this._eventBindings=o}_rePositioningPicker(){const{options:t}=this;if(!t.inline){if(!this._nanopop.update({container:document.body.getBoundingClientRect(),position:t.position})){const t=this._root.app,e=t.getBoundingClientRect();t.style.top=(window.innerHeight-e.height)/2+"px",t.style.left=(window.innerWidth-e.width)/2+"px"}}}_updateOutput(t){const{_root:e,_color:o,options:n}=this;if(e.interaction.type()){const t=`to${e.interaction.type().getAttribute("data-type")}`;e.interaction.result.value="function"==typeof o[t]?o[t]().toString(n.outputPrecision):""}!this._initializingActive&&this._recalc&&this._emit("change",o,t,this)}_clearColor(t=!1){const{_root:e,options:o}=this;o.useAsButton||e.button.style.setProperty("--pcr-color","rgba(0, 0, 0, 0.15)"),e.button.classList.add("clear"),o.showAlways||this.hide(),this._lastColor=null,this._initializingActive||t||(this._emit("save",null),this._emit("clear"))}_parseLocalColor(t){const{values:e,type:o,a:n}=w(t),{lockOpacity:i}=this.options,s=void 0!==n&&1!==n;return e&&3===e.length&&(e[3]=void 0),{values:!e||i&&s?null:e,type:o}}_t(t){return this.options.i18n[t]||L.I18N_DEFAULTS[t]}_emit(t,...e){this._eventListener[t].forEach((t=>t(...e,this)))}on(t,e){return this._eventListener[t].push(e),this}off(t,e){const o=this._eventListener[t]||[],n=o.indexOf(e);return~n&&o.splice(n,1),this}addSwatch(t){const{values:e}=this._parseLocalColor(t);if(e){const{_swatchColors:t,_root:o}=this,n=A(...e),s=r(`<button type="button" style="--pcr-color: ${n.toRGBA().toString(0)}" aria-label="${this._t("btn:swatch")}"/>`);return o.swatches.appendChild(s),t.push({el:s,color:n}),this._eventBindings.push(i(s,"click",(()=>{this.setHSVA(...n.toHSVA(),!0),this._emit("swatchselect",n),this._emit("change",n,"swatch",this)}))),!0}return!1}removeSwatch(t){const e=this._swatchColors[t];if(e){const{el:o}=e;return this._root.swatches.removeChild(o),this._swatchColors.splice(t,1),!0}return!1}applyColor(t=!1){const{preview:e,button:o}=this._root,n=this._color.toRGBA().toString(0);return e.lastColor.style.setProperty("--pcr-color",n),this.options.useAsButton||o.style.setProperty("--pcr-color",n),o.classList.remove("clear"),this._lastColor=this._color.clone(),this._initializingActive||t||this._emit("save",this._color),this}destroy(){cancelAnimationFrame(this._setupAnimationFrame),this._eventBindings.forEach((t=>s(...t))),Object.keys(this._components).forEach((t=>this._components[t].destroy()))}destroyAndRemove(){this.destroy();const{root:t,app:e}=this._root;t.parentElement&&t.parentElement.removeChild(t),e.parentElement.removeChild(e),Object.keys(this).forEach((t=>this[t]=null))}hide(){return!!this.isOpen()&&(this._root.app.classList.remove("visible"),this._emit("hide"),!0)}show(){return!this.options.disabled&&!this.isOpen()&&(this._root.app.classList.add("visible"),this._rePositioningPicker(),this._emit("show",this._color),this)}isOpen(){return this._root.app.classList.contains("visible")}setHSVA(t=360,e=0,o=0,n=1,i=!1){const s=this._recalc;if(this._recalc=!1,t<0||t>360||e<0||e>100||o<0||o>100||n<0||n>1)return!1;this._color=A(t,e,o,n);const{hue:r,opacity:a,palette:l}=this._components;return r.update(t/360),a.update(n),l.update(e/100,1-o/100),i||this.applyColor(),s&&this._updateOutput(),this._recalc=s,!0}setColor(t,e=!1){if(null===t)return this._clearColor(e),!0;const{values:o,type:n}=this._parseLocalColor(t);if(o){const t=n.toUpperCase(),{options:i}=this._root.interaction,s=i.find((e=>e.getAttribute("data-type")===t));if(s&&!s.hidden)for(const t of i)t.classList[t===s?"add":"remove"]("active");return!!this.setHSVA(...o,e)&&this.setColorRepresentation(t)}return!1}setColorRepresentation(t){return t=t.toUpperCase(),!!this._root.interaction.options.find((e=>e.getAttribute("data-type").startsWith(t)&&!e.click()))}getColorRepresentation(){return this._representation}getColor(){return this._color}getSelectedColor(){return this._lastColor}getRoot(){return this._root}disable(){return this.hide(),this.options.disabled=!0,this._root.button.classList.add("disabled"),this}enable(){return this.options.disabled=!1,this._root.button.classList.remove("disabled"),this}}return E(L,"utils",o),E(L,"version","1.8.2"),E(L,"I18N_DEFAULTS",{"ui:dialog":"color picker dialog","btn:toggle":"toggle color picker dialog","btn:swatch":"color swatch","btn:last-color":"use previous color","btn:save":"Save","btn:cancel":"Cancel","btn:clear":"Clear","aria:btn:save":"save and close","aria:btn:cancel":"cancel and close","aria:btn:clear":"clear and close","aria:input":"color input field","aria:palette":"color selection area","aria:hue":"hue selection slider","aria:opacity":"selection slider"}),E(L,"DEFAULT_OPTIONS",{appClass:null,theme:"classic",useAsButton:!1,padding:8,disabled:!1,comparison:!0,closeOnScroll:!1,outputPrecision:0,lockOpacity:!1,autoReposition:!0,container:"body",components:{interaction:{}},i18n:{},swatches:null,inline:!1,sliders:null,default:"#42445a",defaultRepresentation:null,position:"bottom-middle",adjustableNumbers:!0,showAlways:!1,closeWithKey:"Escape"}),E(L,"create",(t=>new L(t))),e=e.default})()}));
//# sourceMappingURL=pickr.js.map;
$(document).ready(function () {
    if ($(".typeform").length > 0) {
        $(".typeform[data-tf-widget]").attr("data-tf-auto-resize", true);
        $(".typeform").attr({
            "data-tf-hide-header": true,
            "data-tf-hide-footer": true,
        });

        if (settings.user.ID > 0) {
            $(".typeform.typeformContainer, .typeformLink").attr(
                "data-tf-hidden",
                "full_name=" + settings.user.fullName + ",email=" + settings.user.email
            );
        }

        var script = $("<script>");
        script.attr("src", "//embed.typeform.com/next/embed.js");

        $("head").append(script);
    }
});
;
